Spaces:
Sleeping
Sleeping
Commit ·
48337b7
1
Parent(s): 4ac80cb
feat(phase-34): add api/routes/forensics.py with 5 endpoints
Browse filesGET /forensics/circular-ownership -- detect shell company ownership rings
GET /forensics/ghost-companies -- companies with contracts but no activity
GET /forensics/shadow-directors -- directors of 10+ companies / shared addresses
GET /forensics/benfords/{entity_id} -- Benford Law analysis on asset declarations
GET /forensics/shadow-draft -- policy text similarity to lobbying documents
All 5 endpoints use pre-built detection engines in ai/ that were fully
implemented but imported by zero routes. Each returns gracefully if
the underlying data (affidavits, company filings) is not yet ingested.
- api/routes/forensics.py +205 -0
api/routes/forensics.py
ADDED
|
@@ -0,0 +1,205 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
BharatGraph - Phase 34: Forensic Intelligence API
|
| 3 |
+
GET /forensics/circular-ownership -- detect shell company ownership rings
|
| 4 |
+
GET /forensics/ghost-companies -- companies with contracts but no activity
|
| 5 |
+
GET /forensics/shadow-directors -- directors of 10+ companies / shared addresses
|
| 6 |
+
GET /forensics/benfords/{entity_id} -- Benford Law analysis on asset declarations
|
| 7 |
+
GET /forensics/shadow-draft -- policy text similarity to lobbying documents
|
| 8 |
+
|
| 9 |
+
Pure ASCII. All detectors built in ai/ -- this file just exposes them.
|
| 10 |
+
"""
|
| 11 |
+
import os, sys
|
| 12 |
+
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
|
| 13 |
+
|
| 14 |
+
from datetime import datetime
|
| 15 |
+
from fastapi import APIRouter, Depends, Query
|
| 16 |
+
from loguru import logger
|
| 17 |
+
|
| 18 |
+
from api.dependencies import get_db
|
| 19 |
+
|
| 20 |
+
router = APIRouter(prefix="/forensics", tags=["Forensics"])
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
@router.get("/circular-ownership")
|
| 24 |
+
def circular_ownership(
|
| 25 |
+
max_cycle_length: int = Query(6, ge=3, le=10),
|
| 26 |
+
driver=Depends(get_db),
|
| 27 |
+
):
|
| 28 |
+
"""
|
| 29 |
+
Detect shell company ownership cycles in the full graph.
|
| 30 |
+
A cycle A -> B -> C -> A indicates potential circular ownership
|
| 31 |
+
used to obscure beneficial ownership.
|
| 32 |
+
"""
|
| 33 |
+
logger.info("[Forensics] circular ownership scan")
|
| 34 |
+
try:
|
| 35 |
+
from ai.circular_ownership import CircularOwnershipDetector
|
| 36 |
+
det = CircularOwnershipDetector(driver=driver)
|
| 37 |
+
cycles = det.detect_cycles()
|
| 38 |
+
filtered = [c for c in cycles if len(c.get("cycle", [])) <= max_cycle_length]
|
| 39 |
+
return {
|
| 40 |
+
"total_cycles_detected": len(cycles),
|
| 41 |
+
"shown": len(filtered),
|
| 42 |
+
"max_cycle_length": max_cycle_length,
|
| 43 |
+
"cycles": filtered,
|
| 44 |
+
"analyzed_at": datetime.now().isoformat(),
|
| 45 |
+
"note": (
|
| 46 |
+
"Circular ownership often indicates shell company structures "
|
| 47 |
+
" used to obscure beneficial ownership or inflate valuations."
|
| 48 |
+
),
|
| 49 |
+
}
|
| 50 |
+
except Exception as e:
|
| 51 |
+
logger.error(f"[Forensics] circular ownership error: {type(e).__name__}")
|
| 52 |
+
return {"status": "error", "detail": str(type(e).__name__),
|
| 53 |
+
"analyzed_at": datetime.now().isoformat()}
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
@router.get("/ghost-companies")
|
| 57 |
+
def ghost_companies(
|
| 58 |
+
min_score: int = Query(70, ge=0, le=100),
|
| 59 |
+
limit: int = Query(50, ge=1, le=200),
|
| 60 |
+
driver=Depends(get_db),
|
| 61 |
+
):
|
| 62 |
+
"""
|
| 63 |
+
Score every company in the graph for ghost company indicators:
|
| 64 |
+
- No declared employees
|
| 65 |
+
- Minimal registered capital
|
| 66 |
+
- High government contract volume
|
| 67 |
+
- No web presence or filings
|
| 68 |
+
|
| 69 |
+
Returns companies with ghost_score >= min_score (default 70).
|
| 70 |
+
"""
|
| 71 |
+
logger.info(f"[Forensics] ghost company scan min_score={min_score}")
|
| 72 |
+
try:
|
| 73 |
+
from ai.ghost_company import GhostCompanyDetector
|
| 74 |
+
det = GhostCompanyDetector(driver=driver)
|
| 75 |
+
results = det.run_detection()
|
| 76 |
+
flagged = [r for r in results if r.get("ghost_score", 0) >= min_score]
|
| 77 |
+
flagged.sort(key=lambda x: x.get("ghost_score", 0), reverse=True)
|
| 78 |
+
return {
|
| 79 |
+
"total_scanned": len(results),
|
| 80 |
+
"flagged_count": len(flagged),
|
| 81 |
+
"min_score": min_score,
|
| 82 |
+
"companies": flagged[:limit],
|
| 83 |
+
"analyzed_at": datetime.now().isoformat(),
|
| 84 |
+
}
|
| 85 |
+
except Exception as e:
|
| 86 |
+
logger.error(f"[Forensics] ghost companies error: {type(e).__name__}")
|
| 87 |
+
return {"status": "error", "detail": str(type(e).__name__),
|
| 88 |
+
"analyzed_at": datetime.now().isoformat()}
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
@router.get("/shadow-directors")
|
| 92 |
+
def shadow_directors(
|
| 93 |
+
min_company_count: int = Query(10, ge=3, le=100),
|
| 94 |
+
driver=Depends(get_db),
|
| 95 |
+
):
|
| 96 |
+
"""
|
| 97 |
+
Detect shadow director patterns:
|
| 98 |
+
1. Individuals who are director of 10+ companies
|
| 99 |
+
2. Multiple companies sharing the same registered address
|
| 100 |
+
(indicates a registration agent acting as nominee director)
|
| 101 |
+
"""
|
| 102 |
+
logger.info("[Forensics] shadow director scan")
|
| 103 |
+
try:
|
| 104 |
+
from ai.shadow_director import ShadowDirectorDetector
|
| 105 |
+
det = ShadowDirectorDetector(driver=driver)
|
| 106 |
+
result = det.run_full_detection()
|
| 107 |
+
high_count = [
|
| 108 |
+
r for r in result.get("high_directorship_count", [])
|
| 109 |
+
if r.get("company_count", 0) >= min_company_count
|
| 110 |
+
]
|
| 111 |
+
return {
|
| 112 |
+
"address_reuse_clusters": result.get("address_reuse", []),
|
| 113 |
+
"high_directorship_entities": high_count,
|
| 114 |
+
"min_company_count": min_company_count,
|
| 115 |
+
"analyzed_at": datetime.now().isoformat(),
|
| 116 |
+
}
|
| 117 |
+
except Exception as e:
|
| 118 |
+
logger.error(f"[Forensics] shadow directors error: {type(e).__name__}")
|
| 119 |
+
return {"status": "error", "detail": str(type(e).__name__),
|
| 120 |
+
"analyzed_at": datetime.now().isoformat()}
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
@router.get("/benfords/{entity_id}")
|
| 124 |
+
def benfords_analysis(entity_id: str, driver=Depends(get_db)):
|
| 125 |
+
"""
|
| 126 |
+
Run Benford Law analysis on all affidavit asset values declared
|
| 127 |
+
by this entity. Significant deviation (chi2 > 15.5) suggests
|
| 128 |
+
fabricated or heavily rounded financial figures.
|
| 129 |
+
"""
|
| 130 |
+
logger.info(f"[Forensics] Benford analysis entity={entity_id[:8]}")
|
| 131 |
+
try:
|
| 132 |
+
from ai.benfords_analyzer import BenfordsAnalyzer
|
| 133 |
+
ba = BenfordsAnalyzer()
|
| 134 |
+
with driver.session() as s:
|
| 135 |
+
rows = s.run(
|
| 136 |
+
"MATCH (n {id:})-[:FILED_AFFIDAVIT]->(a:Affidavit)"
|
| 137 |
+
" RETURN a.total_assets_crore AS total,"
|
| 138 |
+
" a.movable_assets_crore AS movable,"
|
| 139 |
+
" a.liabilities_crore AS liabilities,"
|
| 140 |
+
" a.year AS year",
|
| 141 |
+
id=entity_id
|
| 142 |
+
).data()
|
| 143 |
+
if not rows:
|
| 144 |
+
return {
|
| 145 |
+
"entity_id": entity_id,
|
| 146 |
+
"status": "no_data",
|
| 147 |
+
"note": "No affidavit records found for this entity",
|
| 148 |
+
}
|
| 149 |
+
values = []
|
| 150 |
+
for r in rows:
|
| 151 |
+
for k in ("total", "movable", "liabilities"):
|
| 152 |
+
if r.get(k): values.append(float(r[k]))
|
| 153 |
+
if len(values) < 5:
|
| 154 |
+
return {
|
| 155 |
+
"entity_id": entity_id,
|
| 156 |
+
"status": "insufficient_data",
|
| 157 |
+
"value_count": len(values),
|
| 158 |
+
"note": "Fewer than 5 numeric values -- Benford analysis unreliable",
|
| 159 |
+
}
|
| 160 |
+
result = ba.analyze(values)
|
| 161 |
+
result["entity_id"] = entity_id
|
| 162 |
+
result["value_count"] = len(values)
|
| 163 |
+
result["analyzed_at"] = datetime.now().isoformat()
|
| 164 |
+
return result
|
| 165 |
+
except Exception as e:
|
| 166 |
+
logger.error(f"[Forensics] Benford error entity={entity_id[:8]}: {type(e).__name__}")
|
| 167 |
+
return {"status": "error", "detail": str(type(e).__name__)}
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
@router.get("/shadow-draft")
|
| 171 |
+
def shadow_draft_check(
|
| 172 |
+
submission_id: str = Query(..., description="Node ID of submitted policy/bill text"),
|
| 173 |
+
bill_id: str = Query(..., description="Node ID of reference bill text"),
|
| 174 |
+
driver=Depends(get_db),
|
| 175 |
+
):
|
| 176 |
+
"""
|
| 177 |
+
Compare two policy/bill texts for shadow drafting (text copied from
|
| 178 |
+
lobbying documents or industry submissions into government bills).
|
| 179 |
+
Returns similarity score and matched sections.
|
| 180 |
+
"""
|
| 181 |
+
logger.info(f"[Forensics] shadow draft check {submission_id[:8]} vs {bill_id[:8]}")
|
| 182 |
+
try:
|
| 183 |
+
from ai.shadow_draft_detector import ShadowDraftDetector
|
| 184 |
+
det = ShadowDraftDetector()
|
| 185 |
+
with driver.session() as s:
|
| 186 |
+
sub = s.run(
|
| 187 |
+
"MATCH (n {id:}) RETURN coalesce(n.text,n.content,n.summary) AS t",
|
| 188 |
+
id=submission_id
|
| 189 |
+
).single()
|
| 190 |
+
bill = s.run(
|
| 191 |
+
"MATCH (n {id:}) RETURN coalesce(n.text,n.content,n.summary) AS t",
|
| 192 |
+
id=bill_id
|
| 193 |
+
).single()
|
| 194 |
+
if not sub or not bill:
|
| 195 |
+
return {"status": "node_not_found",
|
| 196 |
+
"found_submission": sub is not None,
|
| 197 |
+
"found_bill": bill is not None}
|
| 198 |
+
result = det.compare(sub["t"] or "", bill["t"] or "")
|
| 199 |
+
result["submission_id"] = submission_id
|
| 200 |
+
result["bill_id"] = bill_id
|
| 201 |
+
result["analyzed_at"] = datetime.now().isoformat()
|
| 202 |
+
return result
|
| 203 |
+
except Exception as e:
|
| 204 |
+
logger.error(f"[Forensics] shadow draft error: {type(e).__name__}")
|
| 205 |
+
return {"status": "error", "detail": str(type(e).__name__)}
|