import json
import numpy as np
from datetime import datetime
from jsonschema import validate, ValidationError
from sklearn.ensemble import IsolationForest
# ==========================================
# CUSTOM EXCEPTIONS
# ==========================================
class ValidationPipelineError(Exception):
"""Base class for pipeline errors."""
pass
class StructuralError(ValidationPipelineError):
pass
class PolicyError(ValidationPipelineError):
pass
class AnomalyError(ValidationPipelineError):
pass
# ==========================================
# LAYER 1: STRUCTURAL VALIDATION (JSON SCHEMA)
# ==========================================
class SchemaValidator:
def __init__(self):
# Define the expected shape of the data
self.schema = {
"type": "object",
"properties": {
"transaction_id": {"type": "string"},
"amount": {"type": "number"},
"currency": {"type": "string"},
"timestamp": {"type": "string", "format": "date-time"},
"user_id": {"type": "string"},
"geo_lat": {"type": "number"},
"geo_long": {"type": "number"}
},
"required": ["transaction_id", "amount", "user_id"]
}
def validate(self, data):
try:
validate(instance=data, schema=self.schema)
return True
except ValidationError as e:
raise StructuralError(f"Schema violation: {e.message}")
# ==========================================
# LAYER 2: DOMAIN POLICIES (BUSINESS LOGIC)
# ==========================================
class PolicyValidator:
def __init__(self):
self.allowed_currencies = ["USD", "EUR", "GBP"]
def validate(self, data):
# Policy 1: Currency Check
if data.get("currency") not in self.allowed_currencies:
raise PolicyError(f"Currency {data.get('currency')} is not supported.")
# Policy 2: Timestamp Sanity (Not in future)
ts_str = data.get("timestamp")
if ts_str:
ts = datetime.fromisoformat(ts_str.replace("Z", "+00:00"))
if ts > datetime.now(ts.tzinfo):
raise PolicyError("Transaction timestamp cannot be in the future.")
# Policy 3: Hard Amount Cap (Compliance limit)
if data.get("amount", 0) > 50000:
raise PolicyError("Amount exceeds single transaction limit.")
return True
# ==========================================
# LAYER 3: ML ANOMALY DETECTOR
# ==========================================
class AnomalyDetector:
def __init__(self):
# Initialize Isolation Forest
# contamination=0.05 expects roughly 5% of data to be outliers
self.model = IsolationForest(contamination=0.05, random_state=42)
self.is_trained = False
def feature_engineering(self, data):
"""
Convert JSON dict into a numerical vector for the model.
"""
# Simple features: Amount, Hour of day, Location cluster
amount = data.get("amount", 0)
time_feat = 0.0
if "timestamp" in data:
ts = datetime.fromisoformat(data["timestamp"].replace("Z", "+00:00"))
time_feat = float(ts.hour)
# Naive location feature (distance from 0,0)
lat = data.get("geo_lat", 0)
long = data.get("geo_long", 0)
loc_feat = np.sqrt(lat**2 + long**2)
return np.array([[amount, time_feat, loc_feat]])
def train(self, historical_data_list):
"""
Train the model on 'normal' historical data.
"""
X = np.array([self.feature_engineering(d)[0] for d in historical_data_list])
self.model.fit(X)
self.is_trained = True
print(f"Model trained on {len(X)} samples.")
def validate(self, data):
if not self.is_trained:
print("Warning: Anomaly Detector skipping (untrained).")
return True
vector = self.feature_engineering(data)
# Predict returns 1 for inlier, -1 for outlier
prediction = self.model.predict(vector)
if prediction[0] == -1:
# Retrieve anomaly score for context
score = self.model.decision_function(vector)
raise AnomalyError(f"ML Anomaly detected. Score: {score[0]:.4f}")
return True
# ==========================================
# PIPELINE ORCHESTRATOR
# ==========================================
class DataValidationPipeline:
def __init__(self):
self.schema_validator = SchemaValidator()
self.policy_validator = PolicyValidator()
self.anomaly_detector = AnomalyDetector()
def train_anomaly_model(self, training_data):
"""Pre-train the ML model with normal data."""
self.anomaly_detector.train(training_data)
def process(self, json_data):
print(f"\nProcessing ID: {json_data.get('transaction_id')}...")
# Step 1: Schema
try:
self.schema_validator.validate(json_data)
print(" [✓] Schema Valid")
except StructuralError as e:
print(f" [✗] Schema Failed: {e}")
return False # Critical fail, stop here
# Step 2: Policies
try:
self.policy_validator.validate(json_data)
print(" [✓] Policies Valid")
except PolicyError as e:
print(f" [✗] Policy Failed: {e}")
return False # Critical fail, stop here
# Step 3: Anomalies (Soft fail or Warning depending on use case)
try:
self.anomaly_detector.validate(json_data)
print(" [✓] Anomaly Check Passed")
except AnomalyError as e:
# In a real pipeline, you might log this to a manual review queue
# rather than rejecting outright.
print(f" [!] Anomaly Warning: {e}")
# return False # Uncomment to strictly block anomalies
return True
# ==========================================
# EXECUTION EXAMPLE
# ==========================================
if __name__ == "__main__":
pipeline = DataValidationPipeline()
# 1. Simulate training the ML model with 'normal' data
# Amounts ~100, Time ~noon, Location near 0
mock_training_data = [
{"amount": 100 + np.random.normal(0, 10), "timestamp": "2023-10-10T12:00:00Z", "geo_lat": 1, "geo_long": 1}
for _ in range(100)
]
pipeline.train_anomaly_model(mock_training_data)
# 2. Test Case A: Valid Data
good_data = {
"transaction_id": "txn_123",
"amount": 120.00,
"currency": "USD",
"user_id": "user_1",
"timestamp": "2023-10-10T12:05:00Z",
"geo_lat": 1.1,
"geo_long": 1.1
}
pipeline.process(good_data)
# 3. Test Case B: Policy Violation (Amount too high)
policy_violation_data = {
"transaction_id": "txn_124",
"amount": 60000.00, # Violates hard limit
"currency": "USD",
"user_id": "user_1",
"timestamp": "2023-10-10T12:05:00Z"
}
pipeline.process(policy_violation_data)
# 4. Test Case C: ML Anomaly (Amount weird, but passes rules)
ml_outlier_data = {
"transaction_id": "txn_125",
"amount": 5.00, # Passes policy (< 50k)
"currency": "USD", # Passes policy
"user_id": "user_1",
"timestamp": "2023-10-10T03:00:00Z", # Weird time
"geo_lat": 50.0, # Weird location
"geo_long": 50.0
}
pipeline.process(ml_outlier_data)