File size: 9,283 Bytes
0a977be | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 | import gradio as gr
import hashlib
import time
import json
from datetime import datetime
from collections import defaultdict
import os
# ============================================================================
# GCC INSURANCE INTELLIGENCE LAB - UNIFIED API GATEWAY
# ============================================================================
# Version: 1.0.0
# Features: Authentication, Rate Limiting, Pricing Tiers, Usage Tracking
# ============================================================================
# Pricing Tiers Configuration
PRICING_TIERS = {
"starter": {
"name": "Starter",
"price": 500,
"requests_per_month": 1000,
"rate_limit_per_minute": 10,
"features": ["claims_processing", "basic_fraud_detection"],
"support": "email"
},
"professional": {
"name": "Professional",
"price": 2000,
"requests_per_month": 10000,
"rate_limit_per_minute": 50,
"features": ["claims_processing", "fraud_detection", "underwriting", "document_rag"],
"support": "priority"
},
"enterprise": {
"name": "Enterprise",
"price": 5000,
"requests_per_month": 100000,
"rate_limit_per_minute": 200,
"features": ["all"],
"support": "dedicated"
}
}
# Demo API Keys (In production, use secure database)
API_KEYS = {
"demo-starter-key": {"tier": "starter", "org": "Demo Starter Org"},
"demo-pro-key": {"tier": "professional", "org": "Demo Professional Org"},
"demo-enterprise-key": {"tier": "enterprise", "org": "Demo Enterprise Org"}
}
# Usage tracking
usage_tracker = defaultdict(lambda: {"requests": 0, "last_reset": time.time()})
rate_limiter = defaultdict(list)
def validate_api_key(api_key):
"""Validate API key and return tier info"""
if api_key in API_KEYS:
return True, API_KEYS[api_key]
return False, None
def check_rate_limit(api_key):
"""Check if request is within rate limits"""
if api_key not in API_KEYS:
return False, "Invalid API key"
tier = API_KEYS[api_key]["tier"]
limit = PRICING_TIERS[tier]["rate_limit_per_minute"]
current_time = time.time()
minute_ago = current_time - 60
# Clean old requests
rate_limiter[api_key] = [t for t in rate_limiter[api_key] if t > minute_ago]
if len(rate_limiter[api_key]) >= limit:
return False, f"Rate limit exceeded ({limit}/min for {tier} tier)"
rate_limiter[api_key].append(current_time)
return True, "OK"
def process_claims(api_key, claim_data):
"""Process insurance claim using AI"""
valid, info = validate_api_key(api_key)
if not valid:
return {"error": "Invalid API key", "status": 401}
allowed, msg = check_rate_limit(api_key)
if not allowed:
return {"error": msg, "status": 429}
# Simulate AI processing
result = {
"status": "success",
"claim_id": f"CLM-{hashlib.md5(claim_data.encode()).hexdigest()[:8].upper()}",
"processing_time": "0.45s",
"ai_assessment": {
"validity_score": 0.92,
"recommended_action": "APPROVE",
"confidence": 0.88,
"flags": []
},
"tier": info["tier"],
"organization": info["org"]
}
return result
def detect_fraud(api_key, transaction_data):
"""Detect potential fraud in transaction"""
valid, info = validate_api_key(api_key)
if not valid:
return {"error": "Invalid API key", "status": 401}
tier = info["tier"]
if tier == "starter":
features = ["basic_fraud_detection"]
else:
features = ["advanced_fraud_detection", "pattern_analysis", "network_analysis"]
allowed, msg = check_rate_limit(api_key)
if not allowed:
return {"error": msg, "status": 429}
result = {
"status": "success",
"transaction_id": f"TXN-{hashlib.md5(transaction_data.encode()).hexdigest()[:8].upper()}",
"fraud_score": 0.15,
"risk_level": "LOW",
"features_used": features,
"recommendation": "PROCEED",
"tier": tier
}
return result
def assess_underwriting(api_key, policy_data):
"""AI-powered underwriting risk assessment"""
valid, info = validate_api_key(api_key)
if not valid:
return {"error": "Invalid API key", "status": 401}
tier = info["tier"]
if tier == "starter":
return {"error": "Underwriting not available in Starter tier. Upgrade to Professional.", "status": 403}
allowed, msg = check_rate_limit(api_key)
if not allowed:
return {"error": msg, "status": 429}
result = {
"status": "success",
"policy_id": f"POL-{hashlib.md5(policy_data.encode()).hexdigest()[:8].upper()}",
"risk_score": 0.35,
"risk_category": "MODERATE",
"premium_adjustment": "+5%",
"factors": ["age", "location", "claims_history"],
"tier": tier
}
return result
def get_usage_stats(api_key):
"""Get API usage statistics"""
valid, info = validate_api_key(api_key)
if not valid:
return {"error": "Invalid API key", "status": 401}
tier = info["tier"]
tier_info = PRICING_TIERS[tier]
return {
"organization": info["org"],
"tier": tier,
"price": f"${tier_info['price']}/month",
"requests_used": usage_tracker[api_key]["requests"],
"requests_limit": tier_info["requests_per_month"],
"rate_limit": f"{tier_info['rate_limit_per_minute']}/min",
"features": tier_info["features"],
"support_level": tier_info["support"]
}
# Gradio Interface
with gr.Blocks(title="GCC Insurance Intelligence API Gateway", theme=gr.themes.Soft()) as demo:
gr.Markdown("""
# π’ GCC Insurance Intelligence Lab - API Gateway
### Unified AI-Powered Insurance Platform
**Available Endpoints:**
- `/claims` - Process insurance claims with AI
- `/fraud` - Detect fraudulent transactions
- `/underwriting` - Risk assessment for policies
- `/usage` - Check your API usage stats
**Demo API Keys:**
- `demo-starter-key` - Starter tier ($500/mo)
- `demo-pro-key` - Professional tier ($2,000/mo)
- `demo-enterprise-key` - Enterprise tier ($5,000/mo)
""")
with gr.Tab("π Authentication"):
api_key_input = gr.Textbox(label="API Key", placeholder="Enter your API key...")
auth_btn = gr.Button("Validate Key", variant="primary")
auth_output = gr.JSON(label="Authentication Result")
auth_btn.click(fn=lambda k: get_usage_stats(k), inputs=api_key_input, outputs=auth_output)
with gr.Tab("π Claims Processing"):
gr.Markdown("### Process Insurance Claims with AI")
claims_key = gr.Textbox(label="API Key")
claims_data = gr.Textbox(label="Claim Data (JSON)", lines=5,
value='{"policy_number": "POL-12345", "claim_type": "auto", "amount": 5000, "description": "Vehicle damage from accident"}')
claims_btn = gr.Button("Process Claim", variant="primary")
claims_output = gr.JSON(label="Processing Result")
claims_btn.click(fn=process_claims, inputs=[claims_key, claims_data], outputs=claims_output)
with gr.Tab("π Fraud Detection"):
gr.Markdown("### AI-Powered Fraud Detection")
fraud_key = gr.Textbox(label="API Key")
fraud_data = gr.Textbox(label="Transaction Data (JSON)", lines=5,
value='{"transaction_id": "TXN-001", "amount": 15000, "merchant": "Auto Repair Shop", "location": "Dubai"}')
fraud_btn = gr.Button("Analyze Transaction", variant="primary")
fraud_output = gr.JSON(label="Fraud Analysis Result")
fraud_btn.click(fn=detect_fraud, inputs=[fraud_key, fraud_data], outputs=fraud_output)
with gr.Tab("π Underwriting"):
gr.Markdown("### Risk Assessment for Underwriting")
gr.Markdown("*Requires Professional or Enterprise tier*")
uw_key = gr.Textbox(label="API Key")
uw_data = gr.Textbox(label="Policy Data (JSON)", lines=5,
value='{"applicant_age": 35, "policy_type": "comprehensive", "vehicle_value": 50000, "location": "Riyadh"}')
uw_btn = gr.Button("Assess Risk", variant="primary")
uw_output = gr.JSON(label="Underwriting Result")
uw_btn.click(fn=assess_underwriting, inputs=[uw_key, uw_data], outputs=uw_output)
with gr.Tab("π° Pricing Tiers"):
gr.Markdown("""
### Pricing Plans
| Tier | Price | Requests/Month | Rate Limit | Features |
|------|-------|----------------|------------|----------|
| **Starter** | $500/mo | 1,000 | 10/min | Claims, Basic Fraud |
| **Professional** | $2,000/mo | 10,000 | 50/min | + Underwriting, Document RAG |
| **Enterprise** | $5,000/mo | 100,000 | 200/min | All Features + Dedicated Support |
Contact sales@gcc-insurance-lab.ai for custom enterprise pricing.
""")
gr.Markdown("""
---
**GCC Insurance Intelligence Lab** | [Documentation](https://huggingface.co/gcc-insurance-intelligence-lab) | [Contact](mailto:sales@gcc-insurance-lab.ai)
""")
demo.launch() |