riskapp / app.py
Raz Tsook
Fix history tracking - update entries with final job results and better UI display
40d66cb
Raw History Blame Contribute Delete
29 kB
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 = """
<!DOCTYPE html>
<html>
<head>
<title>Risk API Server</title>
<meta charset="utf-8">
<style>
body {
font-family: Arial, sans-serif;
max-width: 1200px;
margin: 0 auto;
padding: 20px;
background-color: #f5f5f5;
}
.container {
background: white;
padding: 30px;
border-radius: 10px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
margin-bottom: 20px;
}
h1 {
color: #333;
text-align: center;
margin-bottom: 10px;
}
h2 {
color: #555;
border-bottom: 2px solid #007bff;
padding-bottom: 10px;
}
.subtitle {
text-align: center;
color: #666;
margin-bottom: 30px;
}
textarea {
width: 100%;
height: 200px;
padding: 15px;
border: 2px solid #ddd;
border-radius: 5px;
font-family: monospace;
font-size: 14px;
box-sizing: border-box;
}
button {
background: #007bff;
color: white;
border: none;
padding: 12px 24px;
border-radius: 5px;
cursor: pointer;
font-size: 16px;
margin: 10px 5px;
}
button:hover {
background: #0056b3;
}
button:disabled {
background: #6c757d;
cursor: not-allowed;
}
.response {
margin-top: 20px;
padding: 15px;
border: 2px solid #28a745;
border-radius: 5px;
background: #f8fff9;
white-space: pre-wrap;
font-family: monospace;
max-height: 300px;
overflow-y: auto;
}
.error {
border-color: #dc3545;
background: #fff8f8;
}
.example {
background: #f8f9fa;
padding: 15px;
border-radius: 5px;
margin: 10px 0;
border-left: 4px solid #007bff;
}
.row {
display: flex;
gap: 20px;
margin-bottom: 20px;
}
.col {
flex: 1;
}
.tabs {
display: flex;
margin-bottom: 20px;
}
.tab {
padding: 10px 20px;
background: #e9ecef;
border: none;
cursor: pointer;
margin-right: 5px;
border-radius: 5px 5px 0 0;
}
.tab.active {
background: #007bff;
color: white;
}
.tab-content {
display: none;
}
.tab-content.active {
display: block;
}
</style>
</head>
<body>
<div class="container">
<h1>πŸš€ Risk API Server</h1>
<p class="subtitle">Async-Lite Risk Analysis API with Legacy JSON Endpoint</p>
<div class="tabs">
<button class="tab active" onclick="showTab('risk')">Risk Analysis API</button>
<button class="tab" onclick="showTab('legacy')">Legacy JSON API</button>
<button class="tab" onclick="showTab('history')">API History</button>
</div>
<!-- Risk Analysis API Tab -->
<div id="risk" class="tab-content active">
<h2>Risk Analysis API</h2>
<div class="row">
<div class="col">
<label for="riskInput"><strong>Risk Analysis JSON Input:</strong></label>
<textarea id="riskInput" placeholder='Enter risk analysis JSON...'>{
"company": {
"name": "Example Corp",
"id": "12345",
"sector": "technology"
},
"related": {
"deals": [
{"id": 1, "amount": 75000, "status": "active"}
],
"invoices": [
{"id": 1, "total": 5000, "paid": true},
{"id": 2, "total": 3000, "paid": false}
]
},
"meta": {
"org": "demo-org",
"v": 1,
}
}</textarea>
</div>
<div class="col">
<label><strong>Actions:</strong></label><br>
<button onclick="startRiskAnalysis()">Start Risk Analysis</button>
<button onclick="pollRiskStatus()" id="pollRiskBtn" disabled>Poll Status</button>
<button onclick="clearRiskResults()">Clear</button>
<div id="riskResponse" style="display: none;"></div>
</div>
</div>
</div>
<!-- Legacy JSON API Tab -->
<div id="legacy" class="tab-content">
<h2>Legacy JSON API</h2>
<div class="row">
<div class="col">
<label for="legacyInput"><strong>Any JSON Input:</strong></label>
<textarea id="legacyInput" placeholder='Enter any JSON...'>{
"name": "John",
"age": 30,
"city": "Tel Aviv",
"message": "Hello from legacy API"
}</textarea>
</div>
<div class="col">
<label><strong>Actions:</strong></label><br>
<button onclick="sendLegacyRequest()">Send to Legacy API</button>
<button onclick="clearLegacyResults()">Clear</button>
<div id="legacyResponse" style="display: none;"></div>
</div>
</div>
</div>
<!-- API History Tab -->
<div id="history" class="tab-content">
<h2>πŸ“Š API History</h2>
<div class="row">
<div class="col" style="width: 100%;">
<label><strong>Recent API Calls:</strong></label><br>
<button onclick="loadHistory()" style="margin-bottom: 15px;">πŸ”„ Refresh History</button>
<button onclick="clearHistory()" style="margin-bottom: 15px; margin-left: 10px;">πŸ—‘οΈ Clear History</button>
<div id="historyContainer" style="max-height: 400px; overflow-y: auto; border: 1px solid #ddd; padding: 15px; background: #f9f9f9;">
<p>Click "Refresh History" to load recent API calls...</p>
</div>
</div>
</div>
</div>
<div class="example">
<strong>API Endpoints:</strong><br>
<code>POST /api/risk</code> - Start risk analysis (πŸ” Requires API Key)<br>
<code>GET /api/risk/:job</code> - Poll job status (πŸ” Requires API Key)<br>
<code>POST /api/process</code> - Legacy JSON processor<br>
<code>GET /health</code> - Health check<br>
<code>GET /debug/jobs</code> - List all risk jobs
</div>
<div class="example">
<strong>πŸ” Authentication:</strong><br>
Add header: <code>Authorization: Bearer riskapp-demo-key-2024</code><br>
<br>
<strong>Example cURL:</strong><br>
<code style="font-size: 12px;">
curl -X POST "https://raztsook-riskapp.hf.space/api/risk" \<br>
&nbsp;&nbsp;&nbsp;&nbsp;-H "Content-Type: application/json" \<br>
&nbsp;&nbsp;&nbsp;&nbsp;-H "Authorization: Bearer riskapp-demo-key-2024" \<br>
&nbsp;&nbsp;&nbsp;&nbsp;-d '{"company":{"sector":"technology"},"meta":{"org":"test","v":1}}'
</code>
</div>
</div>
<script>
let currentRiskJobId = null;
function showTab(tabName) {
// Hide all tabs
document.querySelectorAll('.tab-content').forEach(tab => {
tab.classList.remove('active');
});
document.querySelectorAll('.tab').forEach(tab => {
tab.classList.remove('active');
});
// Show selected tab
document.getElementById(tabName).classList.add('active');
event.target.classList.add('active');
}
// Risk Analysis Functions
async function startRiskAnalysis() {
const jsonInput = document.getElementById('riskInput');
const responseDiv = document.getElementById('riskResponse');
const pollBtn = document.getElementById('pollRiskBtn');
try {
const jsonData = JSON.parse(jsonInput.value);
const response = await fetch('/api/risk', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer riskapp-demo-key-2024'
},
body: JSON.stringify(jsonData)
});
const result = await response.json();
responseDiv.className = 'response';
responseDiv.style.display = 'block';
responseDiv.textContent = JSON.stringify(result, null, 2);
if (result.job) {
currentRiskJobId = result.job;
pollBtn.disabled = false;
}
} catch (error) {
responseDiv.className = 'response error';
responseDiv.style.display = 'block';
responseDiv.textContent = 'Error: ' + error.message;
}
}
async function pollRiskStatus() {
if (!currentRiskJobId) return;
const responseDiv = document.getElementById('riskResponse');
try {
const response = await fetch(`/api/risk/${currentRiskJobId}`);
const result = await response.json();
responseDiv.className = 'response';
responseDiv.style.display = 'block';
responseDiv.textContent = JSON.stringify(result, null, 2);
} catch (error) {
responseDiv.className = 'response error';
responseDiv.style.display = 'block';
responseDiv.textContent = 'Error: ' + error.message;
}
}
function clearRiskResults() {
document.getElementById('riskResponse').style.display = 'none';
document.getElementById('pollRiskBtn').disabled = true;
currentRiskJobId = null;
}
// Legacy API Functions
async function sendLegacyRequest() {
const jsonInput = document.getElementById('legacyInput');
const responseDiv = document.getElementById('legacyResponse');
try {
const jsonData = JSON.parse(jsonInput.value);
const response = await fetch('/api/process', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(jsonData)
});
const result = await response.json();
responseDiv.className = 'response';
responseDiv.style.display = 'block';
responseDiv.textContent = JSON.stringify(result, null, 2);
} catch (error) {
responseDiv.className = 'response error';
responseDiv.style.display = 'block';
responseDiv.textContent = 'Error: ' + error.message;
}
}
function clearLegacyResults() {
document.getElementById('legacyResponse').style.display = 'none';
}
// History Functions
async function loadHistory() {
const container = document.getElementById('historyContainer');
container.innerHTML = '<p>Loading history...</p>';
try {
const response = await fetch('/api/history');
const data = await response.json();
if (data.history && data.history.length > 0) {
let historyHtml = `<h4>Total API Calls: ${data.total_calls}</h4>`;
historyHtml += '<div style="margin-top: 15px;">';
data.history.reverse().forEach((call, index) => {
const startTime = new Date(call.timestamp).toLocaleString();
const finalTime = call.final_timestamp ? new Date(call.final_timestamp).toLocaleString() : null;
const statusColor = call.status_code === 200 || call.status_code === 202 ? '#28a745' : '#dc3545';
const responseStatus = call.response?.status || 'unknown';
const statusIcon = responseStatus === 'ok' ? 'βœ…' : responseStatus === 'pending' ? '⏳' : responseStatus === 'error' ? '❌' : '❓';
historyHtml += `
<div style="border: 1px solid #ddd; margin-bottom: 10px; padding: 10px; background: white; border-radius: 5px;">
<div style="display: flex; justify-content: space-between; margin-bottom: 5px;">
<strong>${call.method} ${call.endpoint} ${statusIcon}</strong>
<span style="color: ${statusColor}; font-weight: bold;">${call.status_code}</span>
</div>
<small style="color: #666;">πŸš€ Started: ${startTime}</small>
${finalTime ? `<br><small style="color: #666;">βœ… Completed: ${finalTime}</small>` : ''}
${call.job_id ? `<br><small style="color: #999;">πŸ†” Job: ${call.job_id}</small>` : ''}
${call.payload ? `<br><small><strong>Request:</strong> ${JSON.stringify(call.payload).substring(0, 100)}...</small>` : ''}
${call.response ? `<br><small><strong>Response:</strong> ${JSON.stringify(call.response).substring(0, 100)}...</small>` : ''}
</div>
`;
});
historyHtml += '</div>';
container.innerHTML = historyHtml;
} else {
container.innerHTML = '<p>No API calls recorded yet.</p>';
}
} catch (error) {
container.innerHTML = '<p style="color: red;">Error loading history: ' + error.message + '</p>';
}
}
async function clearHistory() {
if (confirm('Are you sure you want to clear the API history? This cannot be undone.')) {
// Note: This would require a DELETE endpoint to actually clear server-side history
document.getElementById('historyContainer').innerHTML = '<p>History cleared! (Note: Server-side history remains until server restart)</p>';
}
}
</script>
</body>
</html>
"""
return html_content
if __name__ == "__main__":
# For local development
uvicorn.run(app, host="0.0.0.0", port=7860)