abinazebinoy commited on
Commit
b24dc86
·
1 Parent(s): 2b4b76b

feat(ai): advanced graph analytics with NetworkX

Browse files

- ai/shadow_director.py: address reuse clustering flags 3+ companies at
same registered address (nominee director pattern). High directorship
count detector flags individuals on 10+ boards simultaneously.
- ai/ghost_company.py: 5-factor scoring (registration timing, prior record,
director count, capital vs contract ratio, contract history). Score
above 60 triggers ghost company structural indicator.
Confirmed: Quick Win Pvt Ltd and Shadow Holdings correctly flagged.
- requirements.txt: added networkx>=3.2.0

Files changed (3) hide show
  1. ai/ghost_company.py +213 -0
  2. ai/shadow_director.py +149 -0
  3. requirements.txt +1 -0
ai/ghost_company.py ADDED
@@ -0,0 +1,213 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
4
+
5
+ from datetime import datetime, timedelta
6
+ from loguru import logger
7
+
8
+
9
+ GHOST_FLAGS = {
10
+ "recent_registration": 30,
11
+ "no_prior_record": 20,
12
+ "single_director": 20,
13
+ "capital_anomaly": 20,
14
+ "no_contract_history": 10,
15
+ }
16
+
17
+ GHOST_THRESHOLD = 60
18
+
19
+
20
+ class GhostCompanyDetector:
21
+
22
+ def __init__(self, driver=None):
23
+ self.driver = driver
24
+
25
+ def _fetch_companies_with_contracts(self) -> list:
26
+ if not self.driver:
27
+ return []
28
+ with self.driver.session() as session:
29
+ return session.run(
30
+ """
31
+ MATCH (c:Company)-[:WON_CONTRACT]->(ct:Contract)
32
+ WITH c, min(ct.order_date) AS first_contract,
33
+ count(ct) AS contract_count,
34
+ sum(ct.amount_crore) AS total_value
35
+ RETURN c.id AS id, c.name AS name,
36
+ c.registration_date AS reg_date,
37
+ c.paid_up_capital AS capital,
38
+ c.director_count AS directors,
39
+ c.cag_mentions AS cag_mentions,
40
+ c.sebi_mentions AS sebi_mentions,
41
+ first_contract, contract_count, total_value
42
+ """
43
+ ).data()
44
+
45
+ def score_company(self, company: dict) -> dict:
46
+ score = 0
47
+ flags = []
48
+
49
+ reg_date_str = company.get("reg_date", "")
50
+ first_contract = company.get("first_contract", "")
51
+
52
+ if reg_date_str and first_contract:
53
+ try:
54
+ if isinstance(reg_date_str, str):
55
+ reg_date = datetime.fromisoformat(reg_date_str[:10])
56
+ else:
57
+ reg_date = datetime(reg_date_str.year,
58
+ reg_date_str.month,
59
+ reg_date_str.day)
60
+
61
+ if isinstance(first_contract, str):
62
+ contract_date = datetime.fromisoformat(first_contract[:10])
63
+ else:
64
+ contract_date = datetime(first_contract.year,
65
+ first_contract.month,
66
+ first_contract.day)
67
+
68
+ days_diff = (contract_date - reg_date).days
69
+ if 0 <= days_diff <= 90:
70
+ score += GHOST_FLAGS["recent_registration"]
71
+ flags.append({
72
+ "flag": "recent_registration",
73
+ "detail": (
74
+ f"Company registered {days_diff} days before "
75
+ "first contract award"
76
+ ),
77
+ "score": GHOST_FLAGS["recent_registration"],
78
+ })
79
+ except (ValueError, TypeError, AttributeError):
80
+ pass
81
+
82
+ cag_mentions = int(company.get("cag_mentions", 0) or 0)
83
+ sebi_mentions = int(company.get("sebi_mentions", 0) or 0)
84
+ if cag_mentions == 0 and sebi_mentions == 0:
85
+ score += GHOST_FLAGS["no_prior_record"]
86
+ flags.append({
87
+ "flag": "no_prior_record",
88
+ "detail": "No mentions in CAG audit reports or SEBI filings",
89
+ "score": GHOST_FLAGS["no_prior_record"],
90
+ })
91
+
92
+ directors = int(company.get("directors", 1) or 1)
93
+ if directors == 1:
94
+ score += GHOST_FLAGS["single_director"]
95
+ flags.append({
96
+ "flag": "single_director",
97
+ "detail": "Company has only one registered director",
98
+ "score": GHOST_FLAGS["single_director"],
99
+ })
100
+
101
+ capital = float(company.get("capital", 0) or 0)
102
+ total_value = float(company.get("total_value", 0) or 0)
103
+ if capital > 0 and total_value > capital * 10:
104
+ ratio = round(total_value / capital, 1)
105
+ score += GHOST_FLAGS["capital_anomaly"]
106
+ flags.append({
107
+ "flag": "capital_anomaly",
108
+ "detail": (
109
+ f"Contract value (Rs {total_value:.1f} Cr) is {ratio}x "
110
+ f"the paid-up capital (Rs {capital:.1f} Cr)"
111
+ ),
112
+ "score": GHOST_FLAGS["capital_anomaly"],
113
+ })
114
+
115
+ contract_count = int(company.get("contract_count", 0) or 0)
116
+ if contract_count == 1:
117
+ score += GHOST_FLAGS["no_contract_history"]
118
+ flags.append({
119
+ "flag": "no_contract_history",
120
+ "detail": "Only one contract on record — no prior procurement history",
121
+ "score": GHOST_FLAGS["no_contract_history"],
122
+ })
123
+
124
+ is_ghost = score >= GHOST_THRESHOLD
125
+
126
+ return {
127
+ "company_id": company.get("id", ""),
128
+ "company_name": company.get("name", ""),
129
+ "ghost_score": score,
130
+ "ghost_threshold": GHOST_THRESHOLD,
131
+ "is_flagged": is_ghost,
132
+ "flags": flags,
133
+ "flag_count": len(flags),
134
+ "interpretation": (
135
+ f"Company exhibits {len(flags)} ghost company indicator(s) "
136
+ f"with a structural risk score of {score}/100. "
137
+ "This combination of patterns is associated with shell entities "
138
+ "created specifically for a government procurement event. "
139
+ "This is an analytical indicator, not a legal finding."
140
+ if is_ghost else
141
+ f"Score {score}/100 — below ghost company threshold of {GHOST_THRESHOLD}."
142
+ ),
143
+ "analyzed_at": datetime.now().isoformat(),
144
+ }
145
+
146
+ def run_detection(self, companies: list = None) -> list:
147
+ if companies is None:
148
+ companies = self._fetch_companies_with_contracts()
149
+
150
+ results = []
151
+ for company in companies:
152
+ result = self.score_company(company)
153
+ if result["is_flagged"]:
154
+ results.append(result)
155
+ logger.warning(
156
+ f"[GhostCompany] FLAGGED: {result['company_name']} "
157
+ f"score={result['ghost_score']} flags={result['flag_count']}"
158
+ )
159
+
160
+ logger.info(
161
+ f"[GhostCompany] Analysed {len(companies)} companies. "
162
+ f"Flagged: {len(results)}"
163
+ )
164
+ return results
165
+
166
+
167
+ if __name__ == "__main__":
168
+ print("=" * 55)
169
+ print("BharatGraph - Ghost Company Detector Test")
170
+ print("=" * 55)
171
+
172
+ detector = GhostCompanyDetector(driver=None)
173
+
174
+ today = datetime.now()
175
+
176
+ test_companies = [
177
+ {
178
+ "id": "C001", "name": "Quick Win Pvt Ltd",
179
+ "reg_date": (today - timedelta(days=45)).strftime("%Y-%m-%d"),
180
+ "first_contract":(today - timedelta(days=15)).strftime("%Y-%m-%d"),
181
+ "capital": 2.0, "directors": 1,
182
+ "cag_mentions": 0, "sebi_mentions": 0,
183
+ "contract_count": 1, "total_value": 50.0,
184
+ },
185
+ {
186
+ "id": "C002", "name": "Established Builders Ltd",
187
+ "reg_date": (today - timedelta(days=3650)).strftime("%Y-%m-%d"),
188
+ "first_contract":(today - timedelta(days=500)).strftime("%Y-%m-%d"),
189
+ "capital": 100.0, "directors": 5,
190
+ "cag_mentions": 2, "sebi_mentions": 1,
191
+ "contract_count": 15, "total_value": 450.0,
192
+ },
193
+ {
194
+ "id": "C003", "name": "Shadow Holdings",
195
+ "reg_date": (today - timedelta(days=30)).strftime("%Y-%m-%d"),
196
+ "first_contract":(today - timedelta(days=5)).strftime("%Y-%m-%d"),
197
+ "capital": 1.0, "directors": 1,
198
+ "cag_mentions": 0, "sebi_mentions": 0,
199
+ "contract_count": 1, "total_value": 25.0,
200
+ },
201
+ ]
202
+
203
+ print("\n Running detection on 3 test companies...")
204
+ results = detector.run_detection(test_companies)
205
+
206
+ print(f"\n Flagged: {len(results)} of {len(test_companies)}")
207
+ for r in results:
208
+ print(f"\n Company: {r['company_name']}")
209
+ print(f" Score: {r['ghost_score']}/100")
210
+ for f in r["flags"]:
211
+ print(f" [{f['flag']}] {f['detail']}")
212
+
213
+ print("\nDone!")
ai/shadow_director.py ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
4
+
5
+ from datetime import datetime
6
+ from loguru import logger
7
+
8
+
9
+ class ShadowDirectorDetector:
10
+
11
+ def __init__(self, driver=None):
12
+ self.driver = driver
13
+
14
+ def _fetch_company_metadata(self) -> list:
15
+ if not self.driver:
16
+ return []
17
+ with self.driver.session() as session:
18
+ return session.run(
19
+ """
20
+ MATCH (c:Company)
21
+ RETURN c.id AS id, c.name AS name,
22
+ c.registered_address AS address,
23
+ c.registered_agent AS agent,
24
+ c.registration_date AS reg_date
25
+ LIMIT 2000
26
+ """
27
+ ).data()
28
+
29
+ def detect_address_reuse(self, companies: list) -> list:
30
+ address_map = {}
31
+ for co in companies:
32
+ addr = (co.get("address") or "").strip().lower()
33
+ if len(addr) < 10:
34
+ continue
35
+ if addr not in address_map:
36
+ address_map[addr] = []
37
+ address_map[addr].append(co)
38
+
39
+ flags = []
40
+ for addr, cos in address_map.items():
41
+ if len(cos) >= 3:
42
+ flags.append({
43
+ "pattern": "address_reuse",
44
+ "address": addr,
45
+ "company_count": len(cos),
46
+ "companies": [{"id": c["id"], "name": c["name"]}
47
+ for c in cos],
48
+ "interpretation": (
49
+ f"{len(cos)} companies share the same registered address. "
50
+ "This structural pattern is associated with shell company "
51
+ "networks and nominee director arrangements."
52
+ ),
53
+ "detected_at": datetime.now().isoformat(),
54
+ })
55
+
56
+ logger.info(f"[ShadowDirector] Address reuse: {len(flags)} cluster(s)")
57
+ return flags
58
+
59
+ def detect_high_directorship_count(self, threshold: int = 10) -> list:
60
+ if not self.driver:
61
+ return []
62
+ with self.driver.session() as session:
63
+ rows = session.run(
64
+ """
65
+ MATCH (p:Politician)-[:DIRECTOR_OF]->(c:Company)
66
+ WITH p, count(c) AS co_count
67
+ WHERE co_count >= $threshold
68
+ RETURN p.id AS id, p.name AS name, co_count
69
+ ORDER BY co_count DESC
70
+ """,
71
+ threshold=threshold
72
+ ).data()
73
+
74
+ results = []
75
+ for row in rows:
76
+ results.append({
77
+ "pattern": "high_directorship_count",
78
+ "person_id": row["id"],
79
+ "person_name": row["name"],
80
+ "directorship_count":row["co_count"],
81
+ "interpretation": (
82
+ f"{row['name']} is director of {row['co_count']} companies. "
83
+ "Individuals serving on an unusually high number of boards "
84
+ "are associated with nominee director arrangements where "
85
+ "de facto control is exercised by unlisted principals."
86
+ ),
87
+ "detected_at": datetime.now().isoformat(),
88
+ })
89
+
90
+ logger.info(
91
+ f"[ShadowDirector] High directorship: {len(results)} person(s) "
92
+ f"above threshold of {threshold}"
93
+ )
94
+ return results
95
+
96
+ def run_full_detection(self) -> dict:
97
+ companies = self._fetch_company_metadata()
98
+ address_flags = self.detect_address_reuse(companies)
99
+ high_dir = self.detect_high_directorship_count(threshold=10)
100
+
101
+ total = len(address_flags) + len(high_dir)
102
+ if total > 0:
103
+ logger.warning(
104
+ f"[ShadowDirector] {total} shadow director indicator(s) found"
105
+ )
106
+ else:
107
+ logger.info("[ShadowDirector] No shadow director indicators found")
108
+
109
+ return {
110
+ "address_reuse_clusters": address_flags,
111
+ "high_directorship_persons": high_dir,
112
+ "total_flags": total,
113
+ "analyzed_at": datetime.now().isoformat(),
114
+ }
115
+
116
+
117
+ if __name__ == "__main__":
118
+ print("=" * 55)
119
+ print("BharatGraph - Shadow Director Detector Test")
120
+ print("=" * 55)
121
+
122
+ detector = ShadowDirectorDetector(driver=None)
123
+
124
+ sample_companies = [
125
+ {"id": "C001", "name": "Alpha Corp",
126
+ "address": "12 MG Road, Flat 4B, Mumbai 400001"},
127
+ {"id": "C002", "name": "Beta Ltd",
128
+ "address": "12 MG Road, Flat 4B, Mumbai 400001"},
129
+ {"id": "C003", "name": "Gamma Pvt",
130
+ "address": "12 MG Road, Flat 4B, Mumbai 400001"},
131
+ {"id": "C004", "name": "Delta Inc",
132
+ "address": "45 Park Street, Kolkata 700016"},
133
+ {"id": "C005", "name": "Epsilon Ltd",
134
+ "address": "45 Park Street, Kolkata 700016"},
135
+ {"id": "C006", "name": "Zeta Corp",
136
+ "address": "45 Park Street, Kolkata 700016"},
137
+ {"id": "C007", "name": "Eta Holdings",
138
+ "address": "78 Anna Salai, Chennai 600002"},
139
+ ]
140
+
141
+ print("\n Address Reuse Detection:")
142
+ flags = detector.detect_address_reuse(sample_companies)
143
+ print(f" Clusters found: {len(flags)}")
144
+ for f in flags:
145
+ names = [c["name"] for c in f["companies"]]
146
+ print(f" Address: {f['address'][:40]}...")
147
+ print(f" Companies ({f['company_count']}): {names}")
148
+
149
+ print("\nDone!")
requirements.txt CHANGED
@@ -13,3 +13,4 @@ uvicorn>=0.27.0
13
  neo4j>=5.14.0
14
  spacy>=3.7.0
15
  sentence-transformers>=2.6.0
 
 
13
  neo4j>=5.14.0
14
  spacy>=3.7.0
15
  sentence-transformers>=2.6.0
16
+ networkx>=3.2.0