|
1 | | -""" |
2 | | -FinShield - Dashboard API |
| 1 | +"""Finsight - Dashboard API.""" |
3 | 2 |
|
4 | | -Extraction quality metrics and analytics. |
5 | | -""" |
| 3 | +from datetime import datetime, timedelta |
| 4 | +import math |
| 5 | +from typing import Any, Dict, List, Tuple |
6 | 6 |
|
7 | | -from fastapi import APIRouter |
8 | | -from typing import Dict, Any |
9 | | -import logging |
| 7 | +from fastapi import APIRouter, Depends |
| 8 | +from sqlmodel import Session, select |
10 | 9 |
|
11 | | -from app.services.learning_loop import get_correction_store |
| 10 | +from app.db.models import Anomaly, Correction, Document, Entity |
| 11 | +from app.db.session import get_session |
| 12 | +from app.services.learning import cluster_corrections |
12 | 13 |
|
13 | | -logger = logging.getLogger(__name__) |
14 | | - |
15 | | -router = APIRouter() |
| 14 | +router = APIRouter(prefix="/dashboard") |
16 | 15 |
|
17 | 16 |
|
18 | 17 | @router.get("/metrics") |
19 | | -async def get_dashboard_metrics() -> Dict[str, Any]: |
20 | | - """ |
21 | | - Get extraction quality dashboard metrics. |
22 | | - |
23 | | - Returns: |
24 | | - Metrics including accuracy, error rate, processing time, etc. |
25 | | - """ |
26 | | - store = get_correction_store() |
27 | | - |
28 | | - # Calculate metrics |
29 | | - total_corrections = len(store.corrections) |
30 | | - error_rate = store.get_error_rate() |
31 | | - error_clusters = store.get_error_clusters() |
32 | | - |
33 | | - # Mock additional metrics (replace with real data in production) |
| 18 | +async def get_dashboard_metrics(session: Session = Depends(get_session)) -> Dict[str, Any]: |
| 19 | + docs = session.exec(select(Document)).all() |
| 20 | + corrections = session.exec(select(Correction)).all() |
| 21 | + entities = session.exec(select(Entity)).all() |
| 22 | + all_anomalies = session.exec(select(Anomaly)).all() |
| 23 | + |
| 24 | + total_docs = len(docs) |
| 25 | + total_corrections = len(corrections) |
| 26 | + error_rate = (total_corrections / total_docs) if total_docs else 0.0 |
| 27 | + |
| 28 | + # Processing time stats |
| 29 | + processing_times = [d.processing_time_ms for d in docs if d.processing_time_ms is not None] |
| 30 | + avg_processing_time = round(sum(processing_times) / len(processing_times), 1) if processing_times else None |
| 31 | + max_processing_time = max(processing_times) if processing_times else None |
| 32 | + |
| 33 | + # Anomaly aggregation |
| 34 | + anomaly_by_type: Dict[str, int] = {} |
| 35 | + anomaly_by_severity: Dict[str, int] = {"critical": 0, "warning": 0, "info": 0} |
| 36 | + for a in all_anomalies: |
| 37 | + anomaly_by_type[a.anomaly_type] = anomaly_by_type.get(a.anomaly_type, 0) + 1 |
| 38 | + anomaly_by_severity[a.severity] = anomaly_by_severity.get(a.severity, 0) + 1 |
| 39 | + |
| 40 | + accuracy_by_type: Dict[str, Dict[str, float | int]] = {} |
| 41 | + for doc in docs: |
| 42 | + stats = accuracy_by_type.setdefault( |
| 43 | + doc.doc_type or "unknown", {"accuracy": 0.0, "count": 0, "passes": 0} |
| 44 | + ) |
| 45 | + stats["count"] = int(stats["count"]) + 1 |
| 46 | + if not doc.validation_errors: |
| 47 | + stats["passes"] = int(stats["passes"]) + 1 |
| 48 | + |
| 49 | + for doc_type, stats in accuracy_by_type.items(): |
| 50 | + count = int(stats["count"]) or 1 |
| 51 | + passes = int(stats.get("passes", 0)) |
| 52 | + stats["accuracy"] = passes / count |
| 53 | + stats.pop("passes", None) |
| 54 | + |
| 55 | + error_clusters = cluster_corrections(session).get("clusters", {}) |
| 56 | + |
| 57 | + week_ago = datetime.utcnow() - timedelta(days=7) |
| 58 | + docs_last_7 = [doc for doc in docs if doc.created_at >= week_ago] |
| 59 | + corrections_last_7 = [corr for corr in corrections if corr.created_at >= week_ago] |
| 60 | + error_rate_7 = (len(corrections_last_7) / len(docs_last_7)) if docs_last_7 else 0.0 |
| 61 | + |
| 62 | + avg_quality = None |
| 63 | + quality_scores = [doc.image_quality for doc in docs if doc.image_quality is not None] |
| 64 | + if quality_scores: |
| 65 | + avg_quality = sum(quality_scores) / len(quality_scores) |
| 66 | + |
| 67 | + benford_series = _build_benford_series(docs) |
| 68 | + flow_data = _build_money_flow(docs) |
| 69 | + |
| 70 | + # Status distribution |
| 71 | + status_dist: Dict[str, int] = {} |
| 72 | + for doc in docs: |
| 73 | + status_dist[doc.status] = status_dist.get(doc.status, 0) + 1 |
| 74 | + |
34 | 75 | metrics = { |
35 | 76 | "overview": { |
36 | | - "total_documents_processed": 0, # Track in production |
| 77 | + "total_documents_processed": total_docs, |
37 | 78 | "total_corrections": total_corrections, |
38 | 79 | "error_rate": error_rate, |
39 | | - "avg_processing_time": 0.0 # Track in production |
| 80 | + "avg_processing_time_ms": avg_processing_time, |
| 81 | + "max_processing_time_ms": max_processing_time, |
| 82 | + "avg_quality_score": avg_quality, |
| 83 | + }, |
| 84 | + "anomaly_overview": { |
| 85 | + "total_anomalies": len(all_anomalies), |
| 86 | + "by_type": anomaly_by_type, |
| 87 | + "by_severity": anomaly_by_severity, |
| 88 | + "density": round(len(all_anomalies) / total_docs, 2) if total_docs else 0, |
40 | 89 | }, |
41 | | - "accuracy_by_type": { |
42 | | - "invoice": {"accuracy": 0.95, "count": 0}, |
43 | | - "bank_statement": {"accuracy": 0.92, "count": 0}, |
44 | | - "payslip": {"accuracy": 0.88, "count": 0} |
| 90 | + "knowledge_graph": { |
| 91 | + "entities": len(entities), |
| 92 | + "documents": total_docs, |
45 | 93 | }, |
| 94 | + "accuracy_by_type": accuracy_by_type, |
46 | 95 | "error_clusters": error_clusters, |
| 96 | + "quality_distribution": { |
| 97 | + "low": len([q for q in quality_scores if q < 0.4]), |
| 98 | + "medium": len([q for q in quality_scores if 0.4 <= q < 0.75]), |
| 99 | + "high": len([q for q in quality_scores if q >= 0.75]), |
| 100 | + }, |
| 101 | + "status_distribution": status_dist, |
| 102 | + "benford": benford_series, |
| 103 | + "money_flow": flow_data, |
47 | 104 | "trends": { |
48 | 105 | "last_7_days": { |
49 | | - "documents": 0, |
50 | | - "corrections": total_corrections, |
51 | | - "error_rate": error_rate |
| 106 | + "documents": len(docs_last_7), |
| 107 | + "corrections": len(corrections_last_7), |
| 108 | + "error_rate": error_rate_7, |
52 | 109 | } |
53 | 110 | }, |
54 | 111 | "top_error_fields": [ |
55 | 112 | {"field": field, "count": data["count"]} |
56 | 113 | for field, data in sorted( |
57 | 114 | error_clusters.items(), |
58 | 115 | key=lambda x: x[1]["count"], |
59 | | - reverse=True |
| 116 | + reverse=True, |
60 | 117 | )[:5] |
61 | | - ] |
| 118 | + ], |
62 | 119 | } |
63 | | - |
| 120 | + |
64 | 121 | return metrics |
65 | 122 |
|
66 | 123 |
|
67 | | -@router.get("/health") |
68 | | -async def dashboard_health() -> Dict[str, str]: |
69 | | - """Dashboard health check.""" |
70 | | - return {"status": "healthy", "service": "dashboard"} |
| 124 | +def _iter_transaction_amounts(docs: List[Document]) -> List[Tuple[float, str]]: |
| 125 | + amounts: List[Tuple[float, str]] = [] |
| 126 | + for doc in docs: |
| 127 | + extracted = doc.extracted_fields or {} |
| 128 | + transactions = extracted.get("transactions") or [] |
| 129 | + if not isinstance(transactions, list): |
| 130 | + continue |
| 131 | + for tx in transactions: |
| 132 | + if not isinstance(tx, dict): |
| 133 | + continue |
| 134 | + amount = tx.get("amount") |
| 135 | + if amount is None: |
| 136 | + continue |
| 137 | + try: |
| 138 | + value = float(amount) |
| 139 | + except (TypeError, ValueError): |
| 140 | + continue |
| 141 | + description = str(tx.get("description") or "") |
| 142 | + amounts.append((value, description)) |
| 143 | + return amounts |
| 144 | + |
| 145 | + |
| 146 | +def _build_benford_series(docs: List[Document]) -> List[Dict[str, float]]: |
| 147 | + counts = [0] * 9 |
| 148 | + amounts = _iter_transaction_amounts(docs) |
| 149 | + for value, _ in amounts: |
| 150 | + value = abs(value) |
| 151 | + if value < 1: |
| 152 | + continue |
| 153 | + first_digit = int(str(int(value))[0]) |
| 154 | + if 1 <= first_digit <= 9: |
| 155 | + counts[first_digit - 1] += 1 |
| 156 | + total = sum(counts) or 1 |
| 157 | + series: List[Dict[str, float]] = [] |
| 158 | + for idx, count in enumerate(counts): |
| 159 | + digit = idx + 1 |
| 160 | + expected = round(math.log10(1 + 1 / digit), 4) |
| 161 | + observed = round(count / total, 4) |
| 162 | + series.append({"digit": digit, "observed": observed, "expected": expected}) |
| 163 | + return series |
| 164 | + |
| 165 | + |
| 166 | +def _build_money_flow(docs: List[Document]) -> Dict[str, Any]: |
| 167 | + categories = [ |
| 168 | + "Income", |
| 169 | + "Expense", |
| 170 | + "Transfers", |
| 171 | + "Fees", |
| 172 | + "Card", |
| 173 | + "ATM", |
| 174 | + "Payments", |
| 175 | + "Interest", |
| 176 | + "Other", |
| 177 | + "Suspicious", |
| 178 | + ] |
| 179 | + nodes = [{"name": name} for name in categories] |
| 180 | + amounts = _iter_transaction_amounts(docs) |
| 181 | + abs_values = sorted(abs(value) for value, _ in amounts if abs(value) > 0) |
| 182 | + threshold = abs_values[int(len(abs_values) * 0.95)] if abs_values else 0.0 |
| 183 | + |
| 184 | + def classify(desc: str, amount: float) -> str: |
| 185 | + lower = desc.lower() |
| 186 | + if not desc or abs(amount) >= threshold: |
| 187 | + return "Suspicious" |
| 188 | + if "fee" in lower or "charge" in lower: |
| 189 | + return "Fees" |
| 190 | + if "card" in lower or "pos" in lower: |
| 191 | + return "Card" |
| 192 | + if "atm" in lower or "cash" in lower: |
| 193 | + return "ATM" |
| 194 | + if "transfer" in lower or "neft" in lower or "imps" in lower: |
| 195 | + return "Transfers" |
| 196 | + if "interest" in lower: |
| 197 | + return "Interest" |
| 198 | + if "payment" in lower or "bill" in lower or "upi" in lower: |
| 199 | + return "Payments" |
| 200 | + if amount >= 0: |
| 201 | + return "Income" |
| 202 | + return "Other" |
| 203 | + |
| 204 | + totals: Dict[str, float] = {} |
| 205 | + for amount, desc in amounts: |
| 206 | + source_name = "Income" if amount >= 0 else "Expense" |
| 207 | + target_name = classify(desc, amount) |
| 208 | + key = f"{source_name}->{target_name}" |
| 209 | + totals[key] = (totals.get(key, 0.0) + abs(amount)) |
| 210 | + |
| 211 | + def idx(name: str) -> int: |
| 212 | + return categories.index(name) |
| 213 | + |
| 214 | + links = [] |
| 215 | + for key, value in totals.items(): |
| 216 | + source_name, target_name = key.split("->") |
| 217 | + if value <= 0: |
| 218 | + continue |
| 219 | + links.append( |
| 220 | + { |
| 221 | + "source": idx(source_name), |
| 222 | + "target": idx(target_name), |
| 223 | + "value": round(value, 2), |
| 224 | + } |
| 225 | + ) |
| 226 | + |
| 227 | + return {"nodes": nodes, "links": links, "suspicious_threshold": threshold} |
0 commit comments