File size: 29,017 Bytes
af02316 7ec55dc af02316 9ed4edc e283a4f 9ed4edc 14e9c7a e283a4f af02316 e283a4f 9ed4edc af02316 9ed4edc e283a4f af02316 9ed4edc e283a4f 0c2a2d6 9ed4edc e283a4f 23aeb1a 9ed4edc e283a4f 4054db6 e283a4f 4054db6 e283a4f 9ed4edc 4054db6 e283a4f 40d66cb 0c2a2d6 40d66cb 0c2a2d6 40d66cb e283a4f 4054db6 7c211b9 e283a4f 7c211b9 e283a4f 9ed4edc e283a4f 9ed4edc 1e247f2 e283a4f 762bdf1 17258c0 e283a4f 762bdf1 7c211b9 e283a4f 762bdf1 e283a4f 9ed4edc 762bdf1 e283a4f 762bdf1 1e247f2 762bdf1 e283a4f 4054db6 71d96e2 e283a4f 40d66cb 4054db6 e283a4f 4054db6 e283a4f 40d66cb e283a4f 0c2a2d6 e283a4f 0c2a2d6 9ed4edc e283a4f af02316 e283a4f 4054db6 e283a4f 4054db6 e283a4f 0c2a2d6 40d66cb 0c2a2d6 e283a4f af02316 e283a4f 4054db6 e283a4f 4054db6 e283a4f 4054db6 e283a4f 9ed4edc e283a4f 9ed4edc 0c2a2d6 e283a4f 7ec55dc e283a4f 7ec55dc e283a4f 7ec55dc e283a4f 7ec55dc e283a4f 7ec55dc e283a4f 7ec55dc e283a4f 7ec55dc e283a4f 7ec55dc e283a4f 7ec55dc e283a4f 7ec55dc e283a4f 7ec55dc e283a4f 0c2a2d6 7ec55dc e283a4f 7ec55dc e283a4f 7ec55dc 0c2a2d6 7ec55dc e283a4f af02316 e283a4f 7ec55dc af02316 7ec55dc 9ed4edc 7ec55dc e283a4f af02316 e283a4f 7ec55dc e283a4f 0c2a2d6 40d66cb 0c2a2d6 40d66cb 0c2a2d6 40d66cb 0c2a2d6 40d66cb 0c2a2d6 7ec55dc 9ed4edc 7ec55dc | 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 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 | 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>
-H "Content-Type: application/json" \<br>
-H "Authorization: Bearer riskapp-demo-key-2024" \<br>
-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) |