from fastapi import FastAPI, HTTPException, Depends, Request from fastapi.responses import HTMLResponse from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials from pydantic import BaseModel from typing import Dict, List, Optional, Union, Any import uvicorn import logging import json import uuid import asyncio import aiohttp import time import os from datetime import datetime # Configure logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) # Security security = HTTPBearer() RISKAPP_API_KEY = os.getenv("RISKAPP_API_KEY", "riskapp-demo-key-2024") # Default key for demo def verify_api_key(credentials: HTTPAuthorizationCredentials = Depends(security)): """Verify API key from Authorization header""" if credentials.credentials != RISKAPP_API_KEY: raise HTTPException( status_code=401, detail="Invalid API key" ) return credentials.credentials # FastAPI app instance app = FastAPI( title="Risk API Server", description="Async-Lite Risk Analysis API with API Key Authentication", version="1.0.0" ) # In-memory storage risk_store: Dict[str, Any] = {} api_history: List[Dict[str, Any]] = [] # Store API call history # Types class RiskPending(BaseModel): job: str status: str = "pending" message: str class RiskOk(BaseModel): job: str status: str = "ok" score: float band: str # 'low'|'medium'|'high' p12m: float raw: Optional[Any] = None message: str class RiskError(BaseModel): job: str status: str = "error" error: Dict[str, str] message: str class InputPayload(BaseModel): company: Dict[str, Any] related: Optional[Dict[str, Any]] = None meta: Dict[str, Any] # Helper functions def get_message(message_key: str) -> str: messages = { "jobAccepted": "Job accepted and is being processed", "stillProcessing": "Still processing...", "riskComputed": "Risk computed successfully", "externalError": "External service returned an error", "jobNotFound": "Job not found" } return messages.get(message_key, "Unknown message") def add_to_history(endpoint: str, method: str, payload: Optional[Dict] = None, response: Optional[Dict] = None, status_code: int = 200, job_id: Optional[str] = None): """Add API call to history""" history_entry = { "timestamp": datetime.now().isoformat(), "endpoint": endpoint, "method": method, "payload": payload, "response": response, "status_code": status_code, "job_id": job_id # Add job_id for tracking } api_history.append(history_entry) # Keep only last 100 entries to avoid memory issues if len(api_history) > 100: api_history.pop(0) def update_history_with_final_result(job_id: str, final_response: Dict[str, Any]): """Update existing history entry with final result""" for entry in reversed(api_history): # Search from most recent if (entry.get("job_id") == job_id and entry.get("endpoint") == "/api/risk" and entry.get("response", {}).get("status") == "pending"): # Update the response with final result entry["response"] = final_response entry["final_timestamp"] = datetime.now().isoformat() entry["status_code"] = 200 # Final success break def validate_input(payload: Dict[str, Any]) -> List[str]: errors = [] # Check meta object if not payload.get("meta") or not isinstance(payload["meta"], dict): errors.append("meta is required and must be an object") else: meta = payload["meta"] if not meta.get("org") or not isinstance(meta["org"], str): errors.append("meta.org is required and must be a string") if not isinstance(meta.get("v"), (int, float)): errors.append("meta.v is required and must be a number") # Remove locale validation - no longer supporting localization # Check company object if not payload.get("company") or not isinstance(payload["company"], dict): errors.append("company is required and must be an object") return errors async def process_risk_analysis(job_id: str, payload: Dict[str, Any]): """Process risk analysis in background""" try: logger.info(f"Processing risk analysis for job {job_id}") logger.info(f"Payload: {payload}") # Simulate risk calculation based on company data company = payload.get("company", {}) related = payload.get("related", {}) # Simple risk scoring logic (you can make this more sophisticated) base_score = 50 # Adjust score based on company data sector = company.get("sector", "") if isinstance(sector, str): if sector.lower() == "technology": base_score += 15 elif sector.lower() == "finance": base_score += 25 # Adjust based on deals and invoices deals = related.get("deals", []) invoices = related.get("invoices", []) total_deals = 0 payment_ratio = 1.0 if deals: for deal in deals: amount = deal.get("amount", 0) # Convert to float if it's a string try: amount = float(amount) if amount is not None else 0 except (ValueError, TypeError): amount = 0 total_deals += amount if total_deals > 50000: base_score += 10 if invoices and len(invoices) > 0: paid_invoices = [] for inv in invoices: paid_status = inv.get("paid", False) # Handle different paid status formats if isinstance(paid_status, str): paid_status = paid_status.lower() in ["true", "yes", "1", "paid"] elif isinstance(paid_status, (int, float)): paid_status = bool(paid_status) if paid_status: paid_invoices.append(inv) payment_ratio = len(paid_invoices) / len(invoices) if payment_ratio < 0.8: base_score += 20 # Normalize score to 0-100 score = min(100, max(0, base_score)) # Determine risk band if score < 30: band = "low" elif score < 70: band = "medium" else: band = "high" # Calculate probability (simplified) p12m = score / 100.0 # Simulate some processing time await asyncio.sleep(2) final_response = RiskOk( job=job_id, status="ok", score=score, band=band, p12m=p12m, raw={ "company_data": company, "related_data": related, "calculation_details": { "base_score": 50, "sector": sector, "sector_adjustment": 15 if isinstance(sector, str) and sector.lower() == "technology" else (25 if isinstance(sector, str) and sector.lower() == "finance" else 0), "total_deals_amount": total_deals, "deals_adjustment": 10 if total_deals > 50000 else 0, "payment_ratio": payment_ratio if invoices else 1.0, "invoice_adjustment": 20 if invoices and payment_ratio < 0.8 else 0 } }, message=get_message("riskComputed") ) risk_store[job_id] = final_response.dict() # Update history with final result update_history_with_final_result(job_id, final_response.dict()) except Exception as e: error_response = RiskError( job=job_id, status="error", error={"code": "PROCESSING_ERROR", "msg": str(e)}, message=get_message("externalError") ) risk_store[job_id] = error_response.dict() # Update history with error result update_history_with_final_result(job_id, error_response.dict()) # Legacy endpoint for backward compatibility @app.post("/api/process") async def legacy_process_json(request: dict): """Legacy endpoint that accepts any JSON and returns a response""" try: response = { "message": "Response from server: Received your JSON data successfully!", "received_data": request, "status": "success" } # Add to history add_to_history( endpoint="/api/process", method="POST", payload=request, response=response, status_code=200 ) return response except Exception as e: raise HTTPException(status_code=500, detail=f"Processing error: {str(e)}") # New Risk API Endpoints @app.post("/api/risk") async def start_risk_analysis(payload: InputPayload, api_key: str = Depends(verify_api_key)): """Start new risk analysis job""" try: # Validate input errors = validate_input(payload.dict()) if errors: raise HTTPException(status_code=400, detail={"errors": errors}) # Create job ID job_id = str(uuid.uuid4()) # No longer using locale - all messages in English # Create pending response pending_response = RiskPending( job=job_id, status="pending", message=get_message("jobAccepted") ) # Store pending job risk_store[job_id] = pending_response.dict() # Add to history add_to_history( endpoint="/api/risk", method="POST", payload=payload.dict(), response=pending_response.dict(), status_code=202, job_id=job_id ) # Start background processing asyncio.create_task(process_risk_analysis(job_id, payload.dict())) # Return 202 with pending response return pending_response.dict() except HTTPException: raise except Exception as e: logger.error(f"Error in POST /api/risk: {e}") raise HTTPException(status_code=500, detail="Internal server error") @app.get("/api/risk/{job_id}") async def get_risk_status(job_id: str, api_key: str = Depends(verify_api_key)): """Poll for job status""" job_data = risk_store.get(job_id) if not job_data: raise HTTPException( status_code=404, detail={"status": "error", "message": get_message("jobNotFound")} ) # If still pending, return pending status with updated message if job_data.get("status") == "pending": # No longer using locale - all messages in English return { "job": job_data["job"], "status": "pending", "message": get_message("stillProcessing") } # Return final result return job_data @app.get("/health") async def health_check(): """Health check endpoint""" return { "status": "healthy", "message": "Risk API server is running", "timestamp": datetime.now().isoformat() } @app.get("/debug/jobs") async def debug_jobs(): """Debug endpoint to see all jobs""" return [{"id": job_id, **data} for job_id, data in risk_store.items()] @app.get("/api/history") async def get_api_history(): """Get API call history""" return { "total_calls": len(api_history), "history": api_history[-50:] # Return last 50 calls } # Simple HTML interface @app.get("/", response_class=HTMLResponse) async def read_root(): html_content = """
Async-Lite Risk Analysis API with Legacy JSON Endpoint
Click "Refresh History" to load recent API calls...
POST /api/risk - Start risk analysis (🔐 Requires API Key)GET /api/risk/:job - Poll job status (🔐 Requires API Key)POST /api/process - Legacy JSON processorGET /health - Health checkGET /debug/jobs - List all risk jobs
Authorization: Bearer riskapp-demo-key-2024
curl -X POST "https://raztsook-riskapp.hf.space/api/risk" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer riskapp-demo-key-2024" \
-d '{"company":{"sector":"technology"},"meta":{"org":"test","v":1}}'