""" Auto-Owners AI Claims API Full pipeline: CV detection → cost estimation → LLM explanation + STP decision """ from fastapi import FastAPI, File, Form, UploadFile, HTTPException from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import HTMLResponse from pathlib import Path import json import shutil import time from PIL import Image as PILImage from cv_detector import CVDetector from cost_estimator import CostEstimator from audit_logger import log_claim, AUDIT_LOG_PATH try: from fraud_detector import check_duplicate, check_metadata _fraud_detection_available = True print("✓ Fraud detector ready") except Exception as e: print(f"⚠ Fraud detection unavailable: {e}") _fraud_detection_available = False app = FastAPI(title="Auto-Owners AI Claims API") app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) print("\nLoading CV models...") cv_detector = CVDetector() print("✓ CV models ready") print("Loading cost estimator...") cost_estimator = CostEstimator() print("✓ Cost estimator ready") # LLM client is optional — gracefully degrades if GEMINI_API_KEY is missing try: from llm_client import LLMClient llm_client = LLMClient() print("✓ LLM client ready") _llm_available = True except Exception as e: print( f"⚠ LLM client unavailable ({e}) — STP decisions will use rule-based fallback" ) llm_client = None _llm_available = False print("Models ready.\n") def _rule_based_stp(cost_output: dict, detections: list) -> dict: """Fallback STP logic when Gemini is unavailable.""" total_cost = sum(cost_output["total_cost_range"]) / 2 confidences = [d.get("confidence", 0.5) for d in detections] confidence = max(confidences) if confidences else 0.5 severities = [d.get("severity", "minor") for d in detections] cost_ok = total_cost < 1500 confidence_ok = confidence > 0.60 stp_eligible = cost_ok and confidence_ok if stp_eligible: reasoning = ( f"Claim eligible for auto-approval: cost ${total_cost:.0f} under $1,500, " f"{confidence:.0%} confidence." ) else: reasons = [] if not cost_ok: reasons.append(f"cost ${total_cost:.0f} exceeds $1,500") if not confidence_ok: reasons.append(f"{confidence:.0%} confidence below 60%") reasoning = f"Manual review required: {', '.join(reasons)}." requires_review = not stp_eligible or confidence < 0.40 parts_list = ", ".join({d["part"] for d in detections}) explanation = ( f"Our AI detected damage to the following area(s): {parts_list}. " f"The estimated repair cost is ${cost_output['total_cost_range'][0]}–" f"${cost_output['total_cost_range'][1]}." ) return { "damaged_parts": cost_output["damaged_parts"], "total_cost_range": cost_output["total_cost_range"], "explanation": explanation, "confidence_score": round(confidence, 2), "stp_eligible": stp_eligible, "stp_reasoning": reasoning, "requires_adjuster_review": requires_review, "override_allowed": True, "model_version": "1.0.0", } @app.post("/detect") async def detect( image: UploadFile = File(...), state: str = Form(default=""), session_id: str = Form(default=""), ): """ Upload a vehicle photo. Returns detected parts, damage types, cost estimate, and STP decision as JSON. """ if not image.filename: raise HTTPException(status_code=400, detail="No image provided") temp_path = Path(f"temp/temp_{image.filename}") temp_path.parent.mkdir(exist_ok=True) try: with open(temp_path, "wb") as f: shutil.copyfileobj(image.file, f) t0 = time.perf_counter() # ── 1. CV detection ─────────────────────────────────────────────────── t_cv = time.perf_counter() detections, fraud_flags = cv_detector.detect(str(temp_path)) cv_ms = round((time.perf_counter() - t_cv) * 1000, 1) print( f"[TIMING] cv_total: {cv_ms}ms detections={len(detections)}", flush=True, ) inference_ms = cv_ms # ── 1b. Additional fraud signals (metadata + duplicate) ─────────────── print(f"[FRAUD] available={_fraud_detection_available}", flush=True) if _fraud_detection_available: try: pil_image = PILImage.open(temp_path) dup_flag = check_duplicate(pil_image) if dup_flag: fraud_flags.append(dup_flag) meta_flags = check_metadata(str(temp_path)) fraud_flags.extend(meta_flags) print(f"[FRAUD] flags={fraud_flags}", flush=True) except Exception as e: print(f"[FRAUD] error: {e}", flush=True) # ── 2. Cost estimation ──────────────────────────────────────────────── t_cost = time.perf_counter() cost_output = cost_estimator.estimate(detections, state=state) cost_ms = round((time.perf_counter() - t_cost) * 1000, 1) print(f"[TIMING] cost_estimator:{cost_ms}ms", flush=True) # ── 3. LLM explanation + STP decision ───────────────────────────────── vehicle_info = {"year": 2021, "make": "Vehicle", "model": ""} cv_output_for_llm = {"damaged_parts": detections} t_llm = time.perf_counter() if _llm_available: try: llm_output = llm_client.process_claim( cv_output_for_llm, cost_output, vehicle_info ) except Exception as e: print(f"LLM error: {e} — using rule-based fallback") llm_output = _rule_based_stp(cost_output, detections) else: llm_output = _rule_based_stp(cost_output, detections) llm_ms = round((time.perf_counter() - t_llm) * 1000, 1) print( f"[TIMING] stp_decision: {llm_ms}ms stp={llm_output.get('stp_eligible')}", flush=True, ) print( f"[TIMING] request_total: {round((time.perf_counter() - t0) * 1000, 1)}ms", flush=True, ) # ── 4. Audit trail ──────────────────────────────────────────────────── try: claim_id = log_claim( cv_output_for_llm, cost_output, llm_output, session_id=session_id ) except Exception as e: print(f"Audit log warning: {e}") claim_id = None return { "detections": detections, "cost": cost_output, "explanation": llm_output.get("explanation", ""), "confidence_score": llm_output.get("confidence_score"), "stp_eligible": llm_output.get("stp_eligible"), "stp_reasoning": llm_output.get("stp_reasoning"), "requires_adjuster_review": llm_output.get("requires_adjuster_review"), "override_allowed": True, "model_version": "1.0.0", "fraud_flags": fraud_flags, "inference_ms": inference_ms, "claim_id": claim_id, "state": state.upper() if state else "", # Kept for backwards compatibility with ResultsDisplay "summary": { "total_damaged_parts": len(detections), "parts": list({d["part"] for d in detections}), "damage_types": list({d["damage_type"] for d in detections}), }, } except Exception as e: raise HTTPException(status_code=500, detail=str(e)) finally: if temp_path.exists(): temp_path.unlink() @app.get("/estimate") def estimate_cost(part: str, damage_type: str, severity: str, state: str = ""): """Return accurate cost estimate for a single part using backend labor rates.""" result = cost_estimator.estimate( [{"part": part, "damage_type": damage_type, "severity": severity}], state=state, ) if result["damaged_parts"]: p = result["damaged_parts"][0] return { "cost_range": p["cost_range"], "action": p["action"], "labor_rate": p["labor_rate"], } return {"cost_range": [0, 0], "action": "repair", "labor_rate": 0} @app.get("/claims") def get_claims(session_id: str = "", limit: int = 50): """Return claims for this session from the audit log. Audit log is append-only.""" if not AUDIT_LOG_PATH.exists(): return {"claims": []} lines = AUDIT_LOG_PATH.read_text().strip().splitlines() records = [] for line in reversed(lines): try: r = json.loads(line) if not session_id or r.get("session_id") == session_id: records.append(r) if len(records) >= limit: break except Exception: pass return {"claims": records} @app.get("/health") def health(): return { "status": "healthy", "models": "Mask R-CNN (parts) + YOLOv8m (damage) + GradientBoosting (cost)", "llm": "gemini-2.5-flash" if _llm_available else "unavailable", } @app.get("/", response_class=HTMLResponse) def home(): return """ CV Damage Detection

CV Damage Detection

Mask R-CNN parts + YOLOv8m damage + GradientBoosting cost + Gemini STP

""" if __name__ == "__main__": import uvicorn uvicorn.run(app, host="0.0.0.0", port=8000)