Spaces:
Build error
Build error
Commit ·
9c33ffa
1
Parent(s): 2a9acf6
fix: complete pipeline - pull correct scraper versions into branch
Browse files- processing/pipeline.py: working, 23 records, saves to data/processed/
- processing/cleaner.py + entity_resolver.py: restored from main
- scrapers/pib_scraper.py: pulled HTML version from main (was old RSS)
- scrapers/gem_scraper.py: pulled fixed version from main (was old hardcoded key)
- scrapers/base_scraper.py: pulled load_dotenv version from main
- .gitignore: *.pyc added
- .gitignore +1 -0
- processing/cleaner.py +206 -0
- processing/entity_resolver.py +301 -0
- processing/pipeline.py +215 -0
- scrapers/base_scraper.py +5 -1
- scrapers/gem_scraper.py +93 -128
- scrapers/pib_scraper.py +124 -111
.gitignore
CHANGED
|
@@ -1,6 +1,7 @@
|
|
| 1 |
# Python
|
| 2 |
__pycache__/
|
| 3 |
*.py[cod]
|
|
|
|
| 4 |
*.egg-info/
|
| 5 |
dist/
|
| 6 |
build/
|
|
|
|
| 1 |
# Python
|
| 2 |
__pycache__/
|
| 3 |
*.py[cod]
|
| 4 |
+
*.pyc
|
| 5 |
*.egg-info/
|
| 6 |
dist/
|
| 7 |
build/
|
processing/cleaner.py
ADDED
|
@@ -0,0 +1,206 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
BharatGraph - Data Cleaner
|
| 3 |
+
Normalizes messy Indian names, titles, and text fields
|
| 4 |
+
scraped from government datasets.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import re
|
| 8 |
+
import unicodedata
|
| 9 |
+
from loguru import logger
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
INDIAN_TITLES = [
|
| 13 |
+
"shri", "smt", "smt.", "shri.", "dr", "dr.", "prof", "prof.",
|
| 14 |
+
"mr", "mr.", "mrs", "mrs.", "ms", "ms.", "adv", "adv.",
|
| 15 |
+
"hon", "hon.", "honble", "hon'ble", "er", "er.",
|
| 16 |
+
"col", "col.", "gen", "brig", "maj", "capt",
|
| 17 |
+
"justice", "judge", "chief justice",
|
| 18 |
+
]
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class NameCleaner:
|
| 22 |
+
"""
|
| 23 |
+
Cleans and normalizes Indian personal names and company names.
|
| 24 |
+
Used before entity resolution to ensure consistent matching.
|
| 25 |
+
"""
|
| 26 |
+
|
| 27 |
+
def clean_person_name(self, name: str) -> str:
|
| 28 |
+
"""
|
| 29 |
+
Normalize a person name.
|
| 30 |
+
'SHRI RAHUL KUMAR' -> 'Rahul Kumar'
|
| 31 |
+
'Dr. A.P.J. Abdul Kalam' -> 'A.P.J. Abdul Kalam'
|
| 32 |
+
"""
|
| 33 |
+
if not name or not isinstance(name, str):
|
| 34 |
+
return ""
|
| 35 |
+
name = unicodedata.normalize("NFKC", name).strip()
|
| 36 |
+
name = re.sub(r"\(.*?\)", "", name).strip()
|
| 37 |
+
name = re.sub(r"[^\w\s.\-']", " ", name)
|
| 38 |
+
name = name.title()
|
| 39 |
+
for title in INDIAN_TITLES:
|
| 40 |
+
for pat in [rf"^{re.escape(title)}\s+", rf"^{re.escape(title)}\.\s*"]:
|
| 41 |
+
name = re.sub(pat, "", name, flags=re.IGNORECASE).strip()
|
| 42 |
+
return re.sub(r"\s+", " ", name).strip()
|
| 43 |
+
|
| 44 |
+
def clean_company_name(self, name: str) -> str:
|
| 45 |
+
"""
|
| 46 |
+
Normalize a company name.
|
| 47 |
+
'M/S. DELHI ROADS LTD' -> 'Delhi Roads Ltd'
|
| 48 |
+
'M/S SAMPLE INFRASTRUCTURE PRIVATE LIMITED' -> 'Sample Infrastructure Pvt Ltd'
|
| 49 |
+
'ABC CONSTRUCTIONS PVT. LTD.' -> 'Abc Constructions Pvt Ltd'
|
| 50 |
+
"""
|
| 51 |
+
if not name or not isinstance(name, str):
|
| 52 |
+
return ""
|
| 53 |
+
name = unicodedata.normalize("NFKC", name).strip()
|
| 54 |
+
name = re.sub(r"\s+", " ", name)
|
| 55 |
+
# Strip M/s prefix before title case
|
| 56 |
+
name = re.sub(r"^m\s*/\s*s\.?\s*", "", name, flags=re.IGNORECASE).strip()
|
| 57 |
+
name = name.title()
|
| 58 |
+
# Normalize end suffixes
|
| 59 |
+
end_map = [
|
| 60 |
+
(r"private limited$", "Pvt Ltd"),
|
| 61 |
+
(r"pvt\.\s*ltd\.$", "Pvt Ltd"),
|
| 62 |
+
(r"pvt\.\s*ltd$", "Pvt Ltd"),
|
| 63 |
+
(r"pvt\s+ltd$", "Pvt Ltd"),
|
| 64 |
+
(r"p\s*ltd$", "Pvt Ltd"),
|
| 65 |
+
(r"l\.l\.p\.?$", "LLP"),
|
| 66 |
+
(r"llp$", "LLP"),
|
| 67 |
+
(r"limited$", "Ltd"),
|
| 68 |
+
(r"ltd\.$", "Ltd"),
|
| 69 |
+
]
|
| 70 |
+
for pattern, replacement in end_map:
|
| 71 |
+
name, n = re.subn(pattern, replacement, name, flags=re.IGNORECASE)
|
| 72 |
+
if n:
|
| 73 |
+
break
|
| 74 |
+
return re.sub(r"\s+", " ", name).strip()
|
| 75 |
+
|
| 76 |
+
def clean_amount(self, amount_str: str) -> float:
|
| 77 |
+
"""
|
| 78 |
+
Parse Indian currency strings to float in crore.
|
| 79 |
+
'150 Cr' -> 150.0, '500 lakh' -> 5.0,
|
| 80 |
+
'1500000' -> 1.5 (raw rupees), '₹75cr' -> 75.0
|
| 81 |
+
"""
|
| 82 |
+
if not amount_str:
|
| 83 |
+
return 0.0
|
| 84 |
+
s = str(amount_str).strip()
|
| 85 |
+
# Plain number -> treat as raw rupees
|
| 86 |
+
try:
|
| 87 |
+
return round(float(s.replace(",", "")) / 1e7, 4)
|
| 88 |
+
except ValueError:
|
| 89 |
+
pass
|
| 90 |
+
# Remove currency symbols and commas
|
| 91 |
+
s = re.sub(r"[₹,\s]", "", s)
|
| 92 |
+
s = re.sub(r"^rs\.?", "", s, flags=re.IGNORECASE)
|
| 93 |
+
# Detect suffix
|
| 94 |
+
if re.search(r"crore|cr", s, re.IGNORECASE):
|
| 95 |
+
s = re.sub(r"crore|cr", "", s, flags=re.IGNORECASE)
|
| 96 |
+
multiplier = 1.0
|
| 97 |
+
elif re.search(r"lakh|lac", s, re.IGNORECASE):
|
| 98 |
+
s = re.sub(r"lakh|lac", "", s, flags=re.IGNORECASE)
|
| 99 |
+
multiplier = 0.01
|
| 100 |
+
else:
|
| 101 |
+
multiplier = 1 / 1e7
|
| 102 |
+
try:
|
| 103 |
+
return round(float(s.strip()) * multiplier, 4)
|
| 104 |
+
except ValueError:
|
| 105 |
+
return 0.0
|
| 106 |
+
|
| 107 |
+
def clean_state_name(self, state: str) -> str:
|
| 108 |
+
"""Normalize Indian state names. 'TN' -> 'Tamil Nadu'"""
|
| 109 |
+
if not state:
|
| 110 |
+
return ""
|
| 111 |
+
STATE_MAP = {
|
| 112 |
+
"tn": "Tamil Nadu", "tamilnadu": "Tamil Nadu",
|
| 113 |
+
"mh": "Maharashtra", "maharashtra": "Maharashtra",
|
| 114 |
+
"dl": "Delhi", "delhi": "Delhi",
|
| 115 |
+
"ka": "Karnataka", "karnataka": "Karnataka",
|
| 116 |
+
"up": "Uttar Pradesh", "uttarpradesh": "Uttar Pradesh",
|
| 117 |
+
"wb": "West Bengal", "westbengal": "West Bengal",
|
| 118 |
+
"rj": "Rajasthan", "rajasthan": "Rajasthan",
|
| 119 |
+
"mp": "Madhya Pradesh", "madhyapradesh": "Madhya Pradesh",
|
| 120 |
+
"gj": "Gujarat", "gujarat": "Gujarat",
|
| 121 |
+
"ap": "Andhra Pradesh", "andhrapradesh": "Andhra Pradesh",
|
| 122 |
+
"ts": "Telangana", "telangana": "Telangana",
|
| 123 |
+
"kl": "Kerala", "kerala": "Kerala",
|
| 124 |
+
"pb": "Punjab", "punjab": "Punjab",
|
| 125 |
+
"hr": "Haryana", "haryana": "Haryana",
|
| 126 |
+
"br": "Bihar", "bihar": "Bihar",
|
| 127 |
+
"or": "Odisha", "odisha": "Odisha",
|
| 128 |
+
"as": "Assam", "assam": "Assam",
|
| 129 |
+
"jh": "Jharkhand", "jharkhand": "Jharkhand",
|
| 130 |
+
"hp": "Himachal Pradesh", "himachalpradesh": "Himachal Pradesh",
|
| 131 |
+
"uk": "Uttarakhand", "uttarakhand": "Uttarakhand",
|
| 132 |
+
"ct": "Chhattisgarh", "chhattisgarh": "Chhattisgarh",
|
| 133 |
+
"ga": "Goa", "goa": "Goa",
|
| 134 |
+
"mn": "Manipur", "manipur": "Manipur",
|
| 135 |
+
"ml": "Meghalaya", "meghalaya": "Meghalaya",
|
| 136 |
+
"mz": "Mizoram", "mizoram": "Mizoram",
|
| 137 |
+
"nl": "Nagaland", "nagaland": "Nagaland",
|
| 138 |
+
"tr": "Tripura", "tripura": "Tripura",
|
| 139 |
+
"sk": "Sikkim", "sikkim": "Sikkim",
|
| 140 |
+
"ar": "Arunachal Pradesh",
|
| 141 |
+
}
|
| 142 |
+
key = re.sub(r"\s+", "", state.lower().strip())
|
| 143 |
+
return STATE_MAP.get(key, state.title())
|
| 144 |
+
|
| 145 |
+
def clean_record(self, record: dict, record_type: str = "person") -> dict:
|
| 146 |
+
"""Clean all fields in a scraped record dict."""
|
| 147 |
+
cleaned = dict(record)
|
| 148 |
+
if record_type == "person":
|
| 149 |
+
if "name" in cleaned:
|
| 150 |
+
cleaned["name_raw"] = cleaned["name"]
|
| 151 |
+
cleaned["name"] = self.clean_person_name(cleaned["name"])
|
| 152 |
+
if "party" in cleaned:
|
| 153 |
+
cleaned["party"] = cleaned["party"].strip().title()
|
| 154 |
+
if "state" in cleaned:
|
| 155 |
+
cleaned["state"] = self.clean_state_name(cleaned["state"])
|
| 156 |
+
elif record_type == "company":
|
| 157 |
+
if "name" in cleaned:
|
| 158 |
+
cleaned["name_raw"] = cleaned["name"]
|
| 159 |
+
cleaned["name"] = self.clean_company_name(cleaned["name"])
|
| 160 |
+
if "state" in cleaned:
|
| 161 |
+
cleaned["state"] = self.clean_state_name(cleaned["state"])
|
| 162 |
+
elif record_type == "contract":
|
| 163 |
+
if "seller_name" in cleaned:
|
| 164 |
+
cleaned["seller_name_raw"] = cleaned["seller_name"]
|
| 165 |
+
cleaned["seller_name"] = self.clean_company_name(cleaned["seller_name"])
|
| 166 |
+
if "buyer_org" in cleaned:
|
| 167 |
+
cleaned["buyer_org"] = cleaned["buyer_org"].strip().title()
|
| 168 |
+
if "state" in cleaned:
|
| 169 |
+
cleaned["state"] = self.clean_state_name(cleaned["state"])
|
| 170 |
+
if "amount_inr" in cleaned:
|
| 171 |
+
cleaned["amount_crore"] = self.clean_amount(
|
| 172 |
+
str(cleaned.get("amount_crore", cleaned.get("amount_inr", 0)))
|
| 173 |
+
)
|
| 174 |
+
cleaned["_cleaned"] = True
|
| 175 |
+
return cleaned
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
if __name__ == "__main__":
|
| 179 |
+
print("=" * 55)
|
| 180 |
+
print("BharatGraph - Name Cleaner Test")
|
| 181 |
+
print("=" * 55)
|
| 182 |
+
c = NameCleaner()
|
| 183 |
+
|
| 184 |
+
print("\n[1] Person names:")
|
| 185 |
+
for n in ["SHRI RAHUL KUMAR","smt. priya devi","Dr. A.P.J. Abdul Kalam",
|
| 186 |
+
"Hon. Justice Ranjan Gogoi","MR. NARENDRA MODI"," adv. sunita sharma "]:
|
| 187 |
+
print(f" '{n}' -> '{c.clean_person_name(n)}'")
|
| 188 |
+
|
| 189 |
+
print("\n[2] Company names:")
|
| 190 |
+
for n in ["M/S SAMPLE INFRASTRUCTURE PRIVATE LIMITED",
|
| 191 |
+
"ABC CONSTRUCTIONS PVT. LTD.","xyz trading co. llp","M/S. DELHI ROADS LTD"]:
|
| 192 |
+
print(f" '{n}' -> '{c.clean_company_name(n)}'")
|
| 193 |
+
|
| 194 |
+
print("\n[3] Amounts (to crore):")
|
| 195 |
+
for a in ["150 Cr","500 lakh","1500000","Rs. 2,50,00,000","₹75cr"]:
|
| 196 |
+
print(f" '{a}' -> {c.clean_amount(a)} Cr")
|
| 197 |
+
|
| 198 |
+
print("\n[4] States:")
|
| 199 |
+
for s in ["TN","tamilnadu","MH","dl","UP","wb"]:
|
| 200 |
+
print(f" '{s}' -> '{c.clean_state_name(s)}'")
|
| 201 |
+
|
| 202 |
+
print("\n[5] Full record:")
|
| 203 |
+
r = {"name":"SHRI RAMESH KUMAR","party":"sample party","state":"TN","criminal_cases":"3"}
|
| 204 |
+
print(f" In: {r}")
|
| 205 |
+
print(f" Out: {c.clean_record(r,'person')}")
|
| 206 |
+
print("\nDone!")
|
processing/entity_resolver.py
ADDED
|
@@ -0,0 +1,301 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
BharatGraph - Entity Resolver
|
| 3 |
+
Matches the SAME person or company appearing under different names
|
| 4 |
+
across scrapers.
|
| 5 |
+
|
| 6 |
+
The core problem in Indian data:
|
| 7 |
+
MyNeta says: "Rahul Kumar"
|
| 8 |
+
MCA says: "RAHUL KUMAR"
|
| 9 |
+
GeM says: "R. Kumar"
|
| 10 |
+
PIB says: "Shri Rahul Kumar"
|
| 11 |
+
|
| 12 |
+
Are they the same person? This module figures that out.
|
| 13 |
+
|
| 14 |
+
Method: fuzzy string matching (no ML needed for Phase 2).
|
| 15 |
+
Phase 4 (AI) will upgrade this with graph embeddings.
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
import re
|
| 19 |
+
import json
|
| 20 |
+
import os
|
| 21 |
+
from datetime import datetime
|
| 22 |
+
from loguru import logger
|
| 23 |
+
from processing.cleaner import NameCleaner
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class EntityResolver:
|
| 27 |
+
"""
|
| 28 |
+
Resolves duplicate entities across scraped datasets.
|
| 29 |
+
|
| 30 |
+
Approach:
|
| 31 |
+
1. Clean all names first (using NameCleaner)
|
| 32 |
+
2. Build a token set for each name
|
| 33 |
+
3. Compare token overlap ratios
|
| 34 |
+
4. Score >= threshold -> same entity -> merge into canonical record
|
| 35 |
+
|
| 36 |
+
Example:
|
| 37 |
+
"Rahul Kumar" -> tokens: {"rahul", "kumar"}
|
| 38 |
+
"R. Kumar" -> tokens: {"r", "kumar"}
|
| 39 |
+
overlap = 1/2 = 0.5 -> probably same (threshold 0.6 = no match)
|
| 40 |
+
|
| 41 |
+
"Rahul Kumar" -> tokens: {"rahul", "kumar"}
|
| 42 |
+
"Kumar Rahul" -> tokens: {"kumar", "rahul"}
|
| 43 |
+
overlap = 2/2 = 1.0 -> definite match
|
| 44 |
+
"""
|
| 45 |
+
|
| 46 |
+
def __init__(self, threshold: float = 0.7):
|
| 47 |
+
"""
|
| 48 |
+
threshold: minimum token overlap ratio to consider a match.
|
| 49 |
+
0.7 means 70% of tokens must match.
|
| 50 |
+
Higher = stricter (fewer false positives).
|
| 51 |
+
Lower = looser (catches more variations but more false positives).
|
| 52 |
+
"""
|
| 53 |
+
self.threshold = threshold
|
| 54 |
+
self.cleaner = NameCleaner()
|
| 55 |
+
logger.info(f"[Resolver] Initialized with threshold={threshold}")
|
| 56 |
+
|
| 57 |
+
def _tokenize(self, name: str) -> set:
|
| 58 |
+
"""
|
| 59 |
+
Convert a name to a set of lowercase tokens.
|
| 60 |
+
Strips single-char initials that can vary (R. vs Rahul).
|
| 61 |
+
"""
|
| 62 |
+
if not name:
|
| 63 |
+
return set()
|
| 64 |
+
# Lowercase, remove punctuation except spaces
|
| 65 |
+
name = name.lower()
|
| 66 |
+
name = re.sub(r"[^\w\s]", " ", name)
|
| 67 |
+
tokens = set(name.split())
|
| 68 |
+
# Remove very short tokens (initials like "r", "k")
|
| 69 |
+
# but keep them if the name is mostly initials
|
| 70 |
+
long_tokens = {t for t in tokens if len(t) > 1}
|
| 71 |
+
return long_tokens if long_tokens else tokens
|
| 72 |
+
|
| 73 |
+
def similarity_score(self, name1: str, name2: str) -> float:
|
| 74 |
+
"""
|
| 75 |
+
Calculate similarity between two names.
|
| 76 |
+
Returns float between 0.0 (no match) and 1.0 (exact match).
|
| 77 |
+
|
| 78 |
+
Uses Jaccard similarity on token sets:
|
| 79 |
+
score = |intersection| / |union|
|
| 80 |
+
"""
|
| 81 |
+
t1 = self._tokenize(name1)
|
| 82 |
+
t2 = self._tokenize(name2)
|
| 83 |
+
|
| 84 |
+
if not t1 or not t2:
|
| 85 |
+
return 0.0
|
| 86 |
+
|
| 87 |
+
intersection = t1 & t2
|
| 88 |
+
union = t1 | t2
|
| 89 |
+
|
| 90 |
+
return len(intersection) / len(union)
|
| 91 |
+
|
| 92 |
+
def is_same_entity(self, name1: str, name2: str) -> bool:
|
| 93 |
+
"""
|
| 94 |
+
Returns True if two names likely refer to the same person/company.
|
| 95 |
+
"""
|
| 96 |
+
# First try exact match (after cleaning)
|
| 97 |
+
c1 = self.cleaner.clean_person_name(name1)
|
| 98 |
+
c2 = self.cleaner.clean_person_name(name2)
|
| 99 |
+
if c1.lower() == c2.lower():
|
| 100 |
+
return True
|
| 101 |
+
|
| 102 |
+
# Then try fuzzy match
|
| 103 |
+
score = self.similarity_score(c1, c2)
|
| 104 |
+
return score >= self.threshold
|
| 105 |
+
|
| 106 |
+
def find_matches(self, name: str, candidates: list,
|
| 107 |
+
name_field: str = "name") -> list:
|
| 108 |
+
"""
|
| 109 |
+
Find all records in candidates that match the given name.
|
| 110 |
+
|
| 111 |
+
Args:
|
| 112 |
+
name: the name to search for
|
| 113 |
+
candidates: list of dicts with a name field
|
| 114 |
+
name_field: which dict key contains the name
|
| 115 |
+
|
| 116 |
+
Returns:
|
| 117 |
+
list of (record, score) tuples, sorted by score desc
|
| 118 |
+
"""
|
| 119 |
+
name_clean = self.cleaner.clean_person_name(name)
|
| 120 |
+
matches = []
|
| 121 |
+
|
| 122 |
+
for record in candidates:
|
| 123 |
+
candidate_name = record.get(name_field, "")
|
| 124 |
+
candidate_clean = self.cleaner.clean_person_name(candidate_name)
|
| 125 |
+
|
| 126 |
+
score = self.similarity_score(name_clean, candidate_clean)
|
| 127 |
+
if score >= self.threshold:
|
| 128 |
+
matches.append((record, score))
|
| 129 |
+
|
| 130 |
+
# Sort by score descending
|
| 131 |
+
matches.sort(key=lambda x: x[1], reverse=True)
|
| 132 |
+
return matches
|
| 133 |
+
|
| 134 |
+
def resolve_dataset(self, records: list,
|
| 135 |
+
name_field: str = "name") -> list:
|
| 136 |
+
"""
|
| 137 |
+
Takes a list of records and groups duplicates together.
|
| 138 |
+
Returns list of canonical records, each with a 'duplicates' key.
|
| 139 |
+
|
| 140 |
+
This is the main method for deduplication within one dataset.
|
| 141 |
+
"""
|
| 142 |
+
if not records:
|
| 143 |
+
return []
|
| 144 |
+
|
| 145 |
+
resolved = []
|
| 146 |
+
used_indices = set()
|
| 147 |
+
|
| 148 |
+
for i, record in enumerate(records):
|
| 149 |
+
if i in used_indices:
|
| 150 |
+
continue
|
| 151 |
+
|
| 152 |
+
canonical = dict(record)
|
| 153 |
+
canonical["duplicates"] = []
|
| 154 |
+
canonical["_resolved"] = True
|
| 155 |
+
canonical["_resolve_ids"] = [i]
|
| 156 |
+
|
| 157 |
+
name_i = record.get(name_field, "")
|
| 158 |
+
|
| 159 |
+
# Find duplicates
|
| 160 |
+
for j, other in enumerate(records):
|
| 161 |
+
if j <= i or j in used_indices:
|
| 162 |
+
continue
|
| 163 |
+
name_j = other.get(name_field, "")
|
| 164 |
+
score = self.similarity_score(
|
| 165 |
+
self.cleaner.clean_person_name(name_i),
|
| 166 |
+
self.cleaner.clean_person_name(name_j)
|
| 167 |
+
)
|
| 168 |
+
if score >= self.threshold:
|
| 169 |
+
canonical["duplicates"].append({
|
| 170 |
+
"record": other,
|
| 171 |
+
"score": round(score, 3),
|
| 172 |
+
})
|
| 173 |
+
canonical["_resolve_ids"].append(j)
|
| 174 |
+
used_indices.add(j)
|
| 175 |
+
|
| 176 |
+
used_indices.add(i)
|
| 177 |
+
resolved.append(canonical)
|
| 178 |
+
|
| 179 |
+
logger.info(
|
| 180 |
+
f"[Resolver] {len(records)} records -> "
|
| 181 |
+
f"{len(resolved)} unique entities "
|
| 182 |
+
f"({len(records) - len(resolved)} duplicates merged)"
|
| 183 |
+
)
|
| 184 |
+
return resolved
|
| 185 |
+
|
| 186 |
+
def cross_dataset_match(self,
|
| 187 |
+
dataset_a: list, dataset_b: list,
|
| 188 |
+
name_field_a: str = "name",
|
| 189 |
+
name_field_b: str = "name") -> list:
|
| 190 |
+
"""
|
| 191 |
+
Find matching entities ACROSS two different datasets.
|
| 192 |
+
e.g. match politicians (MyNeta) against company directors (MCA)
|
| 193 |
+
|
| 194 |
+
Returns list of match dicts:
|
| 195 |
+
{
|
| 196 |
+
"record_a": {...},
|
| 197 |
+
"record_b": {...},
|
| 198 |
+
"score": 0.85,
|
| 199 |
+
"match_type": "cross_dataset"
|
| 200 |
+
}
|
| 201 |
+
|
| 202 |
+
This is the KEY function for finding politician-company links.
|
| 203 |
+
"""
|
| 204 |
+
matches = []
|
| 205 |
+
|
| 206 |
+
for rec_a in dataset_a:
|
| 207 |
+
name_a = self.cleaner.clean_person_name(
|
| 208 |
+
rec_a.get(name_field_a, "")
|
| 209 |
+
)
|
| 210 |
+
if not name_a:
|
| 211 |
+
continue
|
| 212 |
+
|
| 213 |
+
for rec_b in dataset_b:
|
| 214 |
+
name_b = self.cleaner.clean_person_name(
|
| 215 |
+
rec_b.get(name_field_b, "")
|
| 216 |
+
)
|
| 217 |
+
if not name_b:
|
| 218 |
+
continue
|
| 219 |
+
|
| 220 |
+
score = self.similarity_score(name_a, name_b)
|
| 221 |
+
if score >= self.threshold:
|
| 222 |
+
matches.append({
|
| 223 |
+
"record_a": rec_a,
|
| 224 |
+
"record_b": rec_b,
|
| 225 |
+
"name_a": name_a,
|
| 226 |
+
"name_b": name_b,
|
| 227 |
+
"score": round(score, 3),
|
| 228 |
+
"match_type": "cross_dataset",
|
| 229 |
+
"matched_at": datetime.now().isoformat(),
|
| 230 |
+
})
|
| 231 |
+
|
| 232 |
+
logger.info(
|
| 233 |
+
f"[Resolver] Cross-dataset: {len(dataset_a)} x {len(dataset_b)} "
|
| 234 |
+
f"-> {len(matches)} matches found"
|
| 235 |
+
)
|
| 236 |
+
return matches
|
| 237 |
+
|
| 238 |
+
def save_matches(self, matches: list, filepath: str):
|
| 239 |
+
"""Save match results to JSON."""
|
| 240 |
+
os.makedirs(os.path.dirname(filepath), exist_ok=True)
|
| 241 |
+
with open(filepath, "w", encoding="utf-8") as f:
|
| 242 |
+
json.dump(matches, f, indent=2, ensure_ascii=False)
|
| 243 |
+
logger.success(f"[Resolver] Saved {len(matches)} matches to {filepath}")
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
# ── Run directly to test ─────────────────────────────────
|
| 247 |
+
if __name__ == "__main__":
|
| 248 |
+
print("=" * 55)
|
| 249 |
+
print("BharatGraph - Entity Resolver Test")
|
| 250 |
+
print("=" * 55)
|
| 251 |
+
|
| 252 |
+
resolver = EntityResolver(threshold=0.6)
|
| 253 |
+
|
| 254 |
+
print("\n[1] Similarity scores:")
|
| 255 |
+
pairs = [
|
| 256 |
+
("Rahul Kumar", "RAHUL KUMAR"),
|
| 257 |
+
("Rahul Kumar", "Kumar Rahul"),
|
| 258 |
+
("R. Kumar", "Rahul Kumar"),
|
| 259 |
+
("Priya Sharma", "Priya Devi"),
|
| 260 |
+
("Sample Infra Ltd", "SAMPLE INFRASTRUCTURE PVT LTD"),
|
| 261 |
+
("John Smith", "Jane Smith"),
|
| 262 |
+
("Narendra Modi", "N. Modi"),
|
| 263 |
+
]
|
| 264 |
+
for a, b in pairs:
|
| 265 |
+
score = resolver.similarity_score(a, b)
|
| 266 |
+
match = "✅ MATCH" if score >= 0.6 else "❌ no match"
|
| 267 |
+
print(f" {match} ({score:.2f}) '{a}' vs '{b}'")
|
| 268 |
+
|
| 269 |
+
print("\n[2] Deduplication within dataset:")
|
| 270 |
+
politicians = [
|
| 271 |
+
{"name": "RAHUL KUMAR", "party": "Party A", "state": "TN"},
|
| 272 |
+
{"name": "Rahul Kumar", "party": "Party A", "state": "Tamil Nadu"},
|
| 273 |
+
{"name": "Priya Sharma", "party": "Party B", "state": "MH"},
|
| 274 |
+
{"name": "PRIYA SHARMA", "party": "Party B", "state": "Maharashtra"},
|
| 275 |
+
{"name": "Suresh Patel", "party": "Party C", "state": "GJ"},
|
| 276 |
+
]
|
| 277 |
+
resolved = resolver.resolve_dataset(politicians, name_field="name")
|
| 278 |
+
print(f" Input: {len(politicians)} records")
|
| 279 |
+
print(f" Output: {len(resolved)} unique entities")
|
| 280 |
+
for r in resolved:
|
| 281 |
+
dupes = len(r["duplicates"])
|
| 282 |
+
print(f" -> '{r['name']}'" + (f" (merged {dupes} duplicate)" if dupes else ""))
|
| 283 |
+
|
| 284 |
+
print("\n[3] Cross-dataset matching (politicians vs company directors):")
|
| 285 |
+
directors = [
|
| 286 |
+
{"director_name": "Rahul Kumar", "company": "Sample Infra Pvt Ltd"},
|
| 287 |
+
{"director_name": "Priya Sharma", "company": "ABC Trading Ltd"},
|
| 288 |
+
{"director_name": "Amit Shah", "company": "XYZ Holdings Ltd"},
|
| 289 |
+
]
|
| 290 |
+
matches = resolver.cross_dataset_match(
|
| 291 |
+
politicians, directors,
|
| 292 |
+
name_field_a="name",
|
| 293 |
+
name_field_b="director_name"
|
| 294 |
+
)
|
| 295 |
+
print(f" Found {len(matches)} cross-dataset matches:")
|
| 296 |
+
for m in matches:
|
| 297 |
+
print(f" -> '{m['name_a']}' (politician) matches '{m['name_b']}' (director) "
|
| 298 |
+
f"score={m['score']}")
|
| 299 |
+
print(f" Company: {m['record_b']['company']}")
|
| 300 |
+
|
| 301 |
+
print("\nDone!")
|
processing/pipeline.py
ADDED
|
@@ -0,0 +1,215 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
BharatGraph - Data Pipeline
|
| 3 |
+
Orchestrates all scrapers -> clean -> resolve -> save.
|
| 4 |
+
|
| 5 |
+
Usage:
|
| 6 |
+
python -m processing.pipeline
|
| 7 |
+
python -m processing.pipeline --scrapers datagov,cag,gem
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
import sys
|
| 11 |
+
import os
|
| 12 |
+
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
| 13 |
+
|
| 14 |
+
import json
|
| 15 |
+
import argparse
|
| 16 |
+
from datetime import datetime
|
| 17 |
+
from loguru import logger
|
| 18 |
+
from .cleaner import NameCleaner
|
| 19 |
+
from .entity_resolver import EntityResolver
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class BharatGraphPipeline:
|
| 23 |
+
"""Full data pipeline: scrape -> clean -> resolve -> save."""
|
| 24 |
+
|
| 25 |
+
def __init__(self):
|
| 26 |
+
self.cleaner = NameCleaner()
|
| 27 |
+
self.resolver = EntityResolver(threshold=0.65)
|
| 28 |
+
self.timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 29 |
+
os.makedirs("data/processed", exist_ok=True)
|
| 30 |
+
os.makedirs("data/samples", exist_ok=True)
|
| 31 |
+
logger.info("[Pipeline] Initialized")
|
| 32 |
+
|
| 33 |
+
def run_datagov(self) -> list:
|
| 34 |
+
logger.info("[Pipeline] Running DataGov scraper...")
|
| 35 |
+
try:
|
| 36 |
+
from scrapers.datagov_scraper import DataGovScraper
|
| 37 |
+
data = DataGovScraper().fetch_all_datasets(save=False)
|
| 38 |
+
records = []
|
| 39 |
+
for ds_name, ds in data.items():
|
| 40 |
+
for r in ds.get("records", []):
|
| 41 |
+
r["_source"] = "datagov"
|
| 42 |
+
r["_dataset"] = ds_name
|
| 43 |
+
records.append(r)
|
| 44 |
+
logger.success(f"[Pipeline] DataGov: {len(records)} records")
|
| 45 |
+
return records
|
| 46 |
+
except Exception as e:
|
| 47 |
+
logger.error(f"[Pipeline] DataGov failed: {e}")
|
| 48 |
+
return []
|
| 49 |
+
|
| 50 |
+
def run_cag(self) -> list:
|
| 51 |
+
logger.info("[Pipeline] Running CAG scraper...")
|
| 52 |
+
try:
|
| 53 |
+
from scrapers.cag_scraper import CAGScraper
|
| 54 |
+
reports = CAGScraper().fetch_report_list(limit=20)
|
| 55 |
+
for r in reports:
|
| 56 |
+
r["_source"] = "cag"
|
| 57 |
+
logger.success(f"[Pipeline] CAG: {len(reports)} reports")
|
| 58 |
+
return reports
|
| 59 |
+
except Exception as e:
|
| 60 |
+
logger.error(f"[Pipeline] CAG failed: {e}")
|
| 61 |
+
return []
|
| 62 |
+
|
| 63 |
+
def run_gem(self) -> list:
|
| 64 |
+
logger.info("[Pipeline] Running GeM scraper...")
|
| 65 |
+
try:
|
| 66 |
+
from scrapers.gem_scraper import GeMScraper
|
| 67 |
+
contracts = GeMScraper().fetch_contracts_by_ministry(limit=20)
|
| 68 |
+
cleaned = []
|
| 69 |
+
for c in contracts:
|
| 70 |
+
c["_source"] = "gem"
|
| 71 |
+
cleaned.append(self.cleaner.clean_record(c, "contract"))
|
| 72 |
+
logger.success(f"[Pipeline] GeM: {len(cleaned)} contracts")
|
| 73 |
+
return cleaned
|
| 74 |
+
except Exception as e:
|
| 75 |
+
logger.error(f"[Pipeline] GeM failed: {e}")
|
| 76 |
+
return []
|
| 77 |
+
|
| 78 |
+
def run_myneta(self) -> list:
|
| 79 |
+
logger.info("[Pipeline] Running MyNeta scraper...")
|
| 80 |
+
try:
|
| 81 |
+
from scrapers.myneta_scraper import MyNetaScraper
|
| 82 |
+
candidates = MyNetaScraper().fetch_sample_data(save=False)
|
| 83 |
+
cleaned = []
|
| 84 |
+
for c in candidates:
|
| 85 |
+
c["_source"] = "myneta"
|
| 86 |
+
cleaned.append(self.cleaner.clean_record(c, "person"))
|
| 87 |
+
logger.success(f"[Pipeline] MyNeta: {len(cleaned)} candidates")
|
| 88 |
+
return cleaned
|
| 89 |
+
except Exception as e:
|
| 90 |
+
logger.error(f"[Pipeline] MyNeta failed: {e}")
|
| 91 |
+
return []
|
| 92 |
+
|
| 93 |
+
def run_mca(self) -> list:
|
| 94 |
+
logger.info("[Pipeline] Running MCA scraper...")
|
| 95 |
+
try:
|
| 96 |
+
from scrapers.mca_scraper import MCAScraper
|
| 97 |
+
result = MCAScraper().fetch_and_save_sample(save=False)
|
| 98 |
+
companies = []
|
| 99 |
+
for state, recs in result.items():
|
| 100 |
+
for r in recs:
|
| 101 |
+
r["_source"] = "mca"
|
| 102 |
+
companies.append(self.cleaner.clean_record(r, "company"))
|
| 103 |
+
logger.success(f"[Pipeline] MCA: {len(companies)} companies")
|
| 104 |
+
return companies
|
| 105 |
+
except Exception as e:
|
| 106 |
+
logger.error(f"[Pipeline] MCA failed: {e}")
|
| 107 |
+
return []
|
| 108 |
+
|
| 109 |
+
def run_pib(self) -> list:
|
| 110 |
+
logger.info("[Pipeline] Running PIB scraper...")
|
| 111 |
+
try:
|
| 112 |
+
from scrapers.pib_scraper import PIBScraper
|
| 113 |
+
articles = PIBScraper().fetch_all_feeds(save=False)
|
| 114 |
+
for a in articles:
|
| 115 |
+
a["_source"] = "pib"
|
| 116 |
+
logger.success(f"[Pipeline] PIB: {len(articles)} articles")
|
| 117 |
+
return articles
|
| 118 |
+
except Exception as e:
|
| 119 |
+
logger.error(f"[Pipeline] PIB failed: {e}")
|
| 120 |
+
return []
|
| 121 |
+
|
| 122 |
+
def find_politician_company_links(self,
|
| 123 |
+
politicians: list,
|
| 124 |
+
companies: list) -> list:
|
| 125 |
+
"""Core analysis: find politicians who appear as company directors."""
|
| 126 |
+
logger.info("[Pipeline] Finding politician-company links...")
|
| 127 |
+
matches = self.resolver.cross_dataset_match(
|
| 128 |
+
politicians, companies,
|
| 129 |
+
name_field_a="name", name_field_b="name"
|
| 130 |
+
)
|
| 131 |
+
if matches:
|
| 132 |
+
logger.warning(f"[Pipeline] {len(matches)} politician-company links found!")
|
| 133 |
+
return matches
|
| 134 |
+
|
| 135 |
+
def save(self, data: dict) -> str:
|
| 136 |
+
filepath = f"data/processed/pipeline_{self.timestamp}.json"
|
| 137 |
+
with open(filepath, "w", encoding="utf-8") as f:
|
| 138 |
+
json.dump(data, f, indent=2, ensure_ascii=False)
|
| 139 |
+
logger.success(f"[Pipeline] Saved to {filepath}")
|
| 140 |
+
return filepath
|
| 141 |
+
|
| 142 |
+
def run(self, scrapers: list = None) -> dict:
|
| 143 |
+
"""Run full pipeline. scrapers=None runs all."""
|
| 144 |
+
all_scrapers = ["datagov", "cag", "gem", "myneta", "mca", "pib"]
|
| 145 |
+
to_run = scrapers if scrapers else all_scrapers
|
| 146 |
+
logger.info(f"[Pipeline] Starting: {to_run}")
|
| 147 |
+
start = datetime.now()
|
| 148 |
+
|
| 149 |
+
runner_map = {
|
| 150 |
+
"datagov": self.run_datagov,
|
| 151 |
+
"cag": self.run_cag,
|
| 152 |
+
"gem": self.run_gem,
|
| 153 |
+
"myneta": self.run_myneta,
|
| 154 |
+
"mca": self.run_mca,
|
| 155 |
+
"pib": self.run_pib,
|
| 156 |
+
}
|
| 157 |
+
|
| 158 |
+
raw = {name: runner_map[name]() for name in to_run if name in runner_map}
|
| 159 |
+
|
| 160 |
+
politicians = raw.get("myneta", [])
|
| 161 |
+
companies = raw.get("mca", [])
|
| 162 |
+
links = []
|
| 163 |
+
if politicians and companies:
|
| 164 |
+
politicians = self.resolver.resolve_dataset(politicians, "name")
|
| 165 |
+
companies = self.resolver.resolve_dataset(companies, "name")
|
| 166 |
+
links = self.find_politician_company_links(politicians, companies)
|
| 167 |
+
|
| 168 |
+
duration = (datetime.now() - start).seconds
|
| 169 |
+
summary = {
|
| 170 |
+
"scrapers_run": to_run,
|
| 171 |
+
"duration_seconds": duration,
|
| 172 |
+
"total_raw_records": sum(len(v) for v in raw.values()),
|
| 173 |
+
"politicians_found": len(raw.get("myneta", [])),
|
| 174 |
+
"companies_found": len(raw.get("mca", [])),
|
| 175 |
+
"contracts_found": len(raw.get("gem", [])),
|
| 176 |
+
"cag_reports_found": len(raw.get("cag", [])),
|
| 177 |
+
"pib_articles_found": len(raw.get("pib", [])),
|
| 178 |
+
"politician_co_links": len(links),
|
| 179 |
+
}
|
| 180 |
+
logger.info(f"[Pipeline] Done in {duration}s")
|
| 181 |
+
|
| 182 |
+
results = {"raw": raw, "links": links,
|
| 183 |
+
"summary": summary, "run_at": start.isoformat()}
|
| 184 |
+
results["saved_to"] = self.save(results)
|
| 185 |
+
return results
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
if __name__ == "__main__":
|
| 189 |
+
parser = argparse.ArgumentParser(description="BharatGraph Pipeline")
|
| 190 |
+
parser.add_argument("--scrapers", type=str, default=None,
|
| 191 |
+
help="e.g. datagov,cag,gem,myneta,mca,pib")
|
| 192 |
+
args = parser.parse_args()
|
| 193 |
+
scrapers = args.scrapers.split(",") if args.scrapers else None
|
| 194 |
+
|
| 195 |
+
print("=" * 55)
|
| 196 |
+
print("BharatGraph - Data Pipeline")
|
| 197 |
+
print("=" * 55)
|
| 198 |
+
|
| 199 |
+
results = BharatGraphPipeline().run(scrapers=scrapers)
|
| 200 |
+
s = results["summary"]
|
| 201 |
+
|
| 202 |
+
print(f"\n{'='*55}")
|
| 203 |
+
print("PIPELINE SUMMARY")
|
| 204 |
+
print(f"{'='*55}")
|
| 205 |
+
print(f" Scrapers run: {s['scrapers_run']}")
|
| 206 |
+
print(f" Duration: {s['duration_seconds']}s")
|
| 207 |
+
print(f" Total records: {s['total_raw_records']}")
|
| 208 |
+
print(f" Politicians: {s['politicians_found']}")
|
| 209 |
+
print(f" Companies: {s['companies_found']}")
|
| 210 |
+
print(f" GeM contracts: {s['contracts_found']}")
|
| 211 |
+
print(f" CAG reports: {s['cag_reports_found']}")
|
| 212 |
+
print(f" PIB articles: {s['pib_articles_found']}")
|
| 213 |
+
print(f" Politician-co: {s['politician_co_links']}")
|
| 214 |
+
print(f" Saved to: {results.get('saved_to')}")
|
| 215 |
+
print(f"{'='*55}")
|
scrapers/base_scraper.py
CHANGED
|
@@ -3,9 +3,13 @@ BharatGraph - Base Scraper
|
|
| 3 |
All scrapers inherit from this class.
|
| 4 |
"""
|
| 5 |
import time
|
|
|
|
| 6 |
import requests
|
| 7 |
from loguru import logger
|
| 8 |
-
import
|
|
|
|
|
|
|
|
|
|
| 9 |
|
| 10 |
class BaseScraper:
|
| 11 |
def __init__(self, name, delay=2.0):
|
|
|
|
| 3 |
All scrapers inherit from this class.
|
| 4 |
"""
|
| 5 |
import time
|
| 6 |
+
import os
|
| 7 |
import requests
|
| 8 |
from loguru import logger
|
| 9 |
+
from dotenv import load_dotenv
|
| 10 |
+
|
| 11 |
+
# Load .env file automatically for ALL scrapers that inherit this class
|
| 12 |
+
load_dotenv()
|
| 13 |
|
| 14 |
class BaseScraper:
|
| 15 |
def __init__(self, name, delay=2.0):
|
scrapers/gem_scraper.py
CHANGED
|
@@ -3,18 +3,14 @@ BharatGraph - GeM (Government e-Marketplace) Scraper
|
|
| 3 |
Fetches government contract and procurement data.
|
| 4 |
Source: gem.gov.in + data.gov.in GeM datasets (public)
|
| 5 |
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
If a politician's relative's company wins contracts here,
|
| 9 |
-
that's exactly the pattern BharatGraph needs to flag.
|
| 10 |
-
|
| 11 |
-
Pattern we're looking for:
|
| 12 |
-
Politician → (relative/director) → Company → GeM Contract Won
|
| 13 |
"""
|
| 14 |
|
|
|
|
| 15 |
import json
|
| 16 |
-
import re
|
| 17 |
from datetime import datetime
|
|
|
|
| 18 |
from scrapers.base_scraper import BaseScraper
|
| 19 |
from loguru import logger
|
| 20 |
|
|
@@ -22,53 +18,41 @@ from loguru import logger
|
|
| 22 |
class GeMScraper(BaseScraper):
|
| 23 |
"""
|
| 24 |
Scrapes procurement contract data from Government e-Marketplace (GeM).
|
| 25 |
-
|
| 26 |
GeM is India's official online procurement portal.
|
| 27 |
All government purchases through GeM are public record.
|
| 28 |
-
|
| 29 |
-
Data includes:
|
| 30 |
-
- Contract/order details
|
| 31 |
-
- Buyer (government department)
|
| 32 |
-
- Seller (company that won)
|
| 33 |
-
- Contract value in INR
|
| 34 |
-
- Product/service category
|
| 35 |
-
- Order date
|
| 36 |
-
|
| 37 |
-
This is critical for finding:
|
| 38 |
-
- Repeated contract winners
|
| 39 |
-
- Companies linked to politicians winning contracts
|
| 40 |
-
- Unusual concentration of contracts
|
| 41 |
"""
|
| 42 |
|
| 43 |
-
|
| 44 |
-
|
| 45 |
|
| 46 |
-
# GeM data on data.gov.in
|
| 47 |
-
DATAGOV_BASE = "https://api.data.gov.in/resource/"
|
| 48 |
-
DATAGOV_APIKEY = "579b464db66ec23d9960025070515804"
|
| 49 |
-
|
| 50 |
-
# GeM dataset resource IDs on data.gov.in
|
| 51 |
GEM_DATASETS = {
|
| 52 |
"gem_orders": "0a4b1e09-c3e0-4f0a-8f06-4f62a6d08e4e",
|
| 53 |
}
|
| 54 |
|
| 55 |
def __init__(self):
|
| 56 |
super().__init__(name="gem", delay=2.0)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 57 |
|
| 58 |
def fetch_gem_stats(self) -> dict:
|
| 59 |
"""
|
| 60 |
-
Fetch public GeM platform statistics.
|
| 61 |
-
Returns total orders, GMV, sellers, buyers count.
|
| 62 |
"""
|
| 63 |
logger.info("[GeM] Fetching platform statistics...")
|
| 64 |
-
data = self.get_json(self.GEM_STATS_URL)
|
| 65 |
|
| 66 |
-
|
| 67 |
-
|
|
|
|
| 68 |
return {
|
| 69 |
-
"source":
|
| 70 |
"scraped_at": datetime.now().isoformat(),
|
| 71 |
-
"
|
|
|
|
|
|
|
| 72 |
}
|
| 73 |
|
| 74 |
logger.warning("[GeM] Could not fetch stats, using sample")
|
|
@@ -78,15 +62,12 @@ class GeMScraper(BaseScraper):
|
|
| 78 |
limit: int = 50) -> list:
|
| 79 |
"""
|
| 80 |
Fetch procurement contracts, optionally filtered by ministry.
|
| 81 |
-
Uses data.gov.in GeM dataset.
|
| 82 |
"""
|
| 83 |
-
import os
|
| 84 |
-
api_key = os.getenv("DATAGOV_API_KEY", self.DATAGOV_APIKEY)
|
| 85 |
logger.info(f"[GeM] Fetching contracts for ministry: {ministry}")
|
| 86 |
|
| 87 |
url = f"{self.DATAGOV_BASE}{self.GEM_DATASETS['gem_orders']}"
|
| 88 |
params = {
|
| 89 |
-
"api-key": api_key,
|
| 90 |
"format": "json",
|
| 91 |
"limit": limit,
|
| 92 |
}
|
|
@@ -104,26 +85,21 @@ class GeMScraper(BaseScraper):
|
|
| 104 |
return self._get_sample_contracts()
|
| 105 |
|
| 106 |
def _normalize_contracts(self, records: list) -> list:
|
| 107 |
-
"""Normalize GeM contract records."""
|
| 108 |
contracts = []
|
| 109 |
for rec in records:
|
| 110 |
contract = {
|
| 111 |
-
"order_id":
|
| 112 |
-
"buyer_org":
|
| 113 |
-
|
| 114 |
-
"
|
| 115 |
-
|
| 116 |
-
"
|
| 117 |
-
"
|
| 118 |
-
|
| 119 |
-
"
|
| 120 |
-
|
| 121 |
-
"
|
| 122 |
-
rec.get("date", "")),
|
| 123 |
-
"state": rec.get("buyer_state", ""),
|
| 124 |
-
"source": "GeM / data.gov.in",
|
| 125 |
-
"scraped_at": datetime.now().isoformat(),
|
| 126 |
-
"entity_type": "contract",
|
| 127 |
}
|
| 128 |
if contract["seller_name"] or contract["order_id"]:
|
| 129 |
contracts.append(contract)
|
|
@@ -132,78 +108,72 @@ class GeMScraper(BaseScraper):
|
|
| 132 |
def _get_sample_stats(self) -> dict:
|
| 133 |
"""Sample GeM statistics for testing."""
|
| 134 |
return {
|
| 135 |
-
"source":
|
| 136 |
"scraped_at": datetime.now().isoformat(),
|
| 137 |
"stats": {
|
| 138 |
-
"total_orders":
|
| 139 |
"total_gmv_crore": 285000,
|
| 140 |
-
"total_sellers":
|
| 141 |
-
"total_buyers":
|
| 142 |
"note": "SAMPLE DATA - real stats at gem.gov.in/statistics",
|
| 143 |
},
|
| 144 |
}
|
| 145 |
|
| 146 |
def _get_sample_contracts(self) -> list:
|
| 147 |
-
"""
|
| 148 |
-
Sample contract structures for graph testing.
|
| 149 |
-
Shows the type of data we'll eventually link to politicians.
|
| 150 |
-
"""
|
| 151 |
return [
|
| 152 |
{
|
| 153 |
-
"order_id":
|
| 154 |
-
"buyer_org":
|
| 155 |
-
"seller_name":
|
| 156 |
-
"seller_gstin":"33AABCS1234A1Z5",
|
| 157 |
-
"product":
|
| 158 |
-
"amount_inr":
|
| 159 |
"amount_crore": 1.5,
|
| 160 |
-
"order_date":
|
| 161 |
-
"state":
|
| 162 |
-
"source":
|
| 163 |
-
"scraped_at":
|
| 164 |
-
"entity_type":
|
| 165 |
-
"note":
|
| 166 |
},
|
| 167 |
{
|
| 168 |
-
"order_id":
|
| 169 |
-
"buyer_org":
|
| 170 |
-
"seller_name":
|
| 171 |
-
"seller_gstin":"27AABCM5678B1Z3",
|
| 172 |
-
"product":
|
| 173 |
-
"amount_inr":
|
| 174 |
"amount_crore": 5.0,
|
| 175 |
-
"order_date":
|
| 176 |
-
"state":
|
| 177 |
-
"source":
|
| 178 |
-
"scraped_at":
|
| 179 |
-
"entity_type":
|
| 180 |
-
"note":
|
| 181 |
},
|
| 182 |
{
|
| 183 |
-
"order_id":
|
| 184 |
-
"buyer_org":
|
| 185 |
-
"seller_name":
|
| 186 |
-
"seller_gstin":"33AABCS1234A1Z5",
|
| 187 |
-
"product":
|
| 188 |
-
"amount_inr":
|
| 189 |
"amount_crore": 8.0,
|
| 190 |
-
"order_date":
|
| 191 |
-
"state":
|
| 192 |
-
"source":
|
| 193 |
-
"scraped_at":
|
| 194 |
-
"entity_type":
|
| 195 |
-
"note":
|
| 196 |
},
|
| 197 |
]
|
| 198 |
|
| 199 |
def find_repeated_winners(self, contracts: list) -> dict:
|
| 200 |
"""
|
| 201 |
Find companies that won multiple contracts.
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
Returns dict of {seller_name: [list of contracts]}
|
| 205 |
"""
|
| 206 |
-
from collections import defaultdict
|
| 207 |
winners = defaultdict(list)
|
| 208 |
|
| 209 |
for c in contracts:
|
|
@@ -211,23 +181,20 @@ class GeMScraper(BaseScraper):
|
|
| 211 |
if seller:
|
| 212 |
winners[seller].append(c)
|
| 213 |
|
| 214 |
-
# Only return sellers with 2+ contracts
|
| 215 |
repeated = {k: v for k, v in winners.items() if len(v) >= 2}
|
| 216 |
|
| 217 |
logger.info(f"[GeM] Repeated contract winners: {len(repeated)}")
|
| 218 |
-
for seller,
|
| 219 |
-
total = sum(float(c.get("amount_crore", 0) or 0)
|
| 220 |
-
for c in contracts_list)
|
| 221 |
logger.info(
|
| 222 |
-
f"
|
| 223 |
-
f"
|
| 224 |
)
|
| 225 |
return repeated
|
| 226 |
|
| 227 |
def fetch_and_save(self, save: bool = True) -> dict:
|
| 228 |
"""Fetch contracts + stats and save to disk."""
|
| 229 |
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 230 |
-
|
| 231 |
stats = self.fetch_gem_stats()
|
| 232 |
contracts = self.fetch_contracts_by_ministry(limit=30)
|
| 233 |
repeated = self.find_repeated_winners(contracts)
|
|
@@ -235,10 +202,8 @@ class GeMScraper(BaseScraper):
|
|
| 235 |
result = {
|
| 236 |
"stats": stats,
|
| 237 |
"contracts": contracts,
|
| 238 |
-
"repeated_winners":
|
| 239 |
-
|
| 240 |
-
},
|
| 241 |
-
"scraped_at": datetime.now().isoformat(),
|
| 242 |
}
|
| 243 |
|
| 244 |
if save:
|
|
@@ -249,7 +214,7 @@ class GeMScraper(BaseScraper):
|
|
| 249 |
return result
|
| 250 |
|
| 251 |
|
| 252 |
-
# ── Run directly to test ─────────────────────────────────────────────────────
|
| 253 |
if __name__ == "__main__":
|
| 254 |
print("=" * 60)
|
| 255 |
print("BharatGraph - GeM Contracts Scraper Test")
|
|
@@ -261,7 +226,7 @@ if __name__ == "__main__":
|
|
| 261 |
stats = scraper.fetch_gem_stats()
|
| 262 |
s = stats.get("stats", {})
|
| 263 |
print(f" Total orders: {s.get('total_orders', 'N/A'):,}")
|
| 264 |
-
print(f" Total GMV:
|
| 265 |
print(f" Total sellers: {s.get('total_sellers', 'N/A'):,}")
|
| 266 |
|
| 267 |
print("\n[2] Fetching contracts...")
|
|
@@ -271,21 +236,21 @@ if __name__ == "__main__":
|
|
| 271 |
if contracts:
|
| 272 |
c = contracts[0]
|
| 273 |
print(f"\n Example contract:")
|
| 274 |
-
print(f" Order ID:
|
| 275 |
-
print(f" Buyer:
|
| 276 |
-
print(f" Seller:
|
| 277 |
-
print(f" Amount:
|
| 278 |
-
print(f" Date:
|
| 279 |
|
| 280 |
-
print("\n[3] Finding repeated contract winners
|
| 281 |
repeated = scraper.find_repeated_winners(contracts)
|
| 282 |
if repeated:
|
| 283 |
-
print(f"
|
| 284 |
else:
|
| 285 |
-
print(" No repeated winners
|
| 286 |
|
| 287 |
print("\n[4] Saving full data...")
|
| 288 |
result = scraper.fetch_and_save(save=True)
|
| 289 |
-
print(f" Contracts saved:
|
| 290 |
print(f" Repeated winners: {len(result['repeated_winners'])}")
|
| 291 |
-
print("\nDone!
|
|
|
|
| 3 |
Fetches government contract and procurement data.
|
| 4 |
Source: gem.gov.in + data.gov.in GeM datasets (public)
|
| 5 |
|
| 6 |
+
Pattern we are looking for:
|
| 7 |
+
Politician -> (relative/director) -> Company -> GeM Contract Won
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
"""
|
| 9 |
|
| 10 |
+
import os
|
| 11 |
import json
|
|
|
|
| 12 |
from datetime import datetime
|
| 13 |
+
from collections import defaultdict
|
| 14 |
from scrapers.base_scraper import BaseScraper
|
| 15 |
from loguru import logger
|
| 16 |
|
|
|
|
| 18 |
class GeMScraper(BaseScraper):
|
| 19 |
"""
|
| 20 |
Scrapes procurement contract data from Government e-Marketplace (GeM).
|
|
|
|
| 21 |
GeM is India's official online procurement portal.
|
| 22 |
All government purchases through GeM are public record.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
"""
|
| 24 |
|
| 25 |
+
GEM_STATS_URL = "https://gem.gov.in/statistics"
|
| 26 |
+
DATAGOV_BASE = "https://api.data.gov.in/resource/"
|
| 27 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
GEM_DATASETS = {
|
| 29 |
"gem_orders": "0a4b1e09-c3e0-4f0a-8f06-4f62a6d08e4e",
|
| 30 |
}
|
| 31 |
|
| 32 |
def __init__(self):
|
| 33 |
super().__init__(name="gem", delay=2.0)
|
| 34 |
+
self.api_key = os.getenv("DATAGOV_API_KEY", "")
|
| 35 |
+
if not self.api_key:
|
| 36 |
+
logger.warning(
|
| 37 |
+
"[GeM] No API key! Add DATAGOV_API_KEY to .env "
|
| 38 |
+
"Register free at: https://data.gov.in/user/register"
|
| 39 |
+
)
|
| 40 |
|
| 41 |
def fetch_gem_stats(self) -> dict:
|
| 42 |
"""
|
| 43 |
+
Fetch public GeM platform statistics from gem.gov.in/statistics.
|
|
|
|
| 44 |
"""
|
| 45 |
logger.info("[GeM] Fetching platform statistics...")
|
|
|
|
| 46 |
|
| 47 |
+
html = self.get_html(self.GEM_STATS_URL)
|
| 48 |
+
if html and len(html) > 500:
|
| 49 |
+
logger.success("[GeM] Fetched GeM statistics page")
|
| 50 |
return {
|
| 51 |
+
"source": "gem.gov.in/statistics",
|
| 52 |
"scraped_at": datetime.now().isoformat(),
|
| 53 |
+
"url": self.GEM_STATS_URL,
|
| 54 |
+
"note": "HTML fetched - using sample stats structure",
|
| 55 |
+
"stats": self._get_sample_stats()["stats"],
|
| 56 |
}
|
| 57 |
|
| 58 |
logger.warning("[GeM] Could not fetch stats, using sample")
|
|
|
|
| 62 |
limit: int = 50) -> list:
|
| 63 |
"""
|
| 64 |
Fetch procurement contracts, optionally filtered by ministry.
|
|
|
|
| 65 |
"""
|
|
|
|
|
|
|
| 66 |
logger.info(f"[GeM] Fetching contracts for ministry: {ministry}")
|
| 67 |
|
| 68 |
url = f"{self.DATAGOV_BASE}{self.GEM_DATASETS['gem_orders']}"
|
| 69 |
params = {
|
| 70 |
+
"api-key": self.api_key,
|
| 71 |
"format": "json",
|
| 72 |
"limit": limit,
|
| 73 |
}
|
|
|
|
| 85 |
return self._get_sample_contracts()
|
| 86 |
|
| 87 |
def _normalize_contracts(self, records: list) -> list:
|
| 88 |
+
"""Normalize GeM contract records into standard format."""
|
| 89 |
contracts = []
|
| 90 |
for rec in records:
|
| 91 |
contract = {
|
| 92 |
+
"order_id": rec.get("order_id", rec.get("id", "")),
|
| 93 |
+
"buyer_org": rec.get("buyer_organisation", rec.get("ministry", "")),
|
| 94 |
+
"seller_name": rec.get("seller_name", rec.get("company_name", "")),
|
| 95 |
+
"seller_gstin": rec.get("gstin", ""),
|
| 96 |
+
"product": rec.get("product_name", rec.get("category", "")),
|
| 97 |
+
"amount_inr": rec.get("order_value", rec.get("amount", 0)),
|
| 98 |
+
"order_date": rec.get("order_date", rec.get("date", "")),
|
| 99 |
+
"state": rec.get("buyer_state", ""),
|
| 100 |
+
"source": "GeM / data.gov.in",
|
| 101 |
+
"scraped_at": datetime.now().isoformat(),
|
| 102 |
+
"entity_type": "contract",
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 103 |
}
|
| 104 |
if contract["seller_name"] or contract["order_id"]:
|
| 105 |
contracts.append(contract)
|
|
|
|
| 108 |
def _get_sample_stats(self) -> dict:
|
| 109 |
"""Sample GeM statistics for testing."""
|
| 110 |
return {
|
| 111 |
+
"source": "GeM Sample Data",
|
| 112 |
"scraped_at": datetime.now().isoformat(),
|
| 113 |
"stats": {
|
| 114 |
+
"total_orders": 6200000,
|
| 115 |
"total_gmv_crore": 285000,
|
| 116 |
+
"total_sellers": 680000,
|
| 117 |
+
"total_buyers": 75000,
|
| 118 |
"note": "SAMPLE DATA - real stats at gem.gov.in/statistics",
|
| 119 |
},
|
| 120 |
}
|
| 121 |
|
| 122 |
def _get_sample_contracts(self) -> list:
|
| 123 |
+
"""Sample contract structures for graph testing."""
|
|
|
|
|
|
|
|
|
|
| 124 |
return [
|
| 125 |
{
|
| 126 |
+
"order_id": "GEM/2024/B/12345",
|
| 127 |
+
"buyer_org": "Ministry of Rural Development",
|
| 128 |
+
"seller_name": "SAMPLE INFRASTRUCTURE PVT LTD",
|
| 129 |
+
"seller_gstin": "33AABCS1234A1Z5",
|
| 130 |
+
"product": "Construction Services",
|
| 131 |
+
"amount_inr": 15000000,
|
| 132 |
"amount_crore": 1.5,
|
| 133 |
+
"order_date": "2024-03-15",
|
| 134 |
+
"state": "Tamil Nadu",
|
| 135 |
+
"source": "GeM (sample)",
|
| 136 |
+
"scraped_at": datetime.now().isoformat(),
|
| 137 |
+
"entity_type": "contract",
|
| 138 |
+
"note": "SAMPLE - replace with real GeM fetch",
|
| 139 |
},
|
| 140 |
{
|
| 141 |
+
"order_id": "GEM/2024/B/67890",
|
| 142 |
+
"buyer_org": "Ministry of Health",
|
| 143 |
+
"seller_name": "SAMPLE MEDICAL SUPPLIES LTD",
|
| 144 |
+
"seller_gstin": "27AABCM5678B1Z3",
|
| 145 |
+
"product": "Medical Equipment",
|
| 146 |
+
"amount_inr": 50000000,
|
| 147 |
"amount_crore": 5.0,
|
| 148 |
+
"order_date": "2024-06-10",
|
| 149 |
+
"state": "Maharashtra",
|
| 150 |
+
"source": "GeM (sample)",
|
| 151 |
+
"scraped_at": datetime.now().isoformat(),
|
| 152 |
+
"entity_type": "contract",
|
| 153 |
+
"note": "SAMPLE - replace with real GeM fetch",
|
| 154 |
},
|
| 155 |
{
|
| 156 |
+
"order_id": "GEM/2024/B/11111",
|
| 157 |
+
"buyer_org": "Ministry of Rural Development",
|
| 158 |
+
"seller_name": "SAMPLE INFRASTRUCTURE PVT LTD",
|
| 159 |
+
"seller_gstin": "33AABCS1234A1Z5",
|
| 160 |
+
"product": "Road Construction",
|
| 161 |
+
"amount_inr": 80000000,
|
| 162 |
"amount_crore": 8.0,
|
| 163 |
+
"order_date": "2024-09-20",
|
| 164 |
+
"state": "Tamil Nadu",
|
| 165 |
+
"source": "GeM (sample)",
|
| 166 |
+
"scraped_at": datetime.now().isoformat(),
|
| 167 |
+
"entity_type": "contract",
|
| 168 |
+
"note": "SAMPLE - same company 2nd contract (pattern!)",
|
| 169 |
},
|
| 170 |
]
|
| 171 |
|
| 172 |
def find_repeated_winners(self, contracts: list) -> dict:
|
| 173 |
"""
|
| 174 |
Find companies that won multiple contracts.
|
| 175 |
+
KEY risk indicator - contract concentration.
|
|
|
|
|
|
|
| 176 |
"""
|
|
|
|
| 177 |
winners = defaultdict(list)
|
| 178 |
|
| 179 |
for c in contracts:
|
|
|
|
| 181 |
if seller:
|
| 182 |
winners[seller].append(c)
|
| 183 |
|
|
|
|
| 184 |
repeated = {k: v for k, v in winners.items() if len(v) >= 2}
|
| 185 |
|
| 186 |
logger.info(f"[GeM] Repeated contract winners: {len(repeated)}")
|
| 187 |
+
for seller, clist in repeated.items():
|
| 188 |
+
total = sum(float(c.get("amount_crore", 0) or 0) for c in clist)
|
|
|
|
| 189 |
logger.info(
|
| 190 |
+
f" -> {seller}: {len(clist)} contracts, "
|
| 191 |
+
f"Rs {total:.2f} Cr total"
|
| 192 |
)
|
| 193 |
return repeated
|
| 194 |
|
| 195 |
def fetch_and_save(self, save: bool = True) -> dict:
|
| 196 |
"""Fetch contracts + stats and save to disk."""
|
| 197 |
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
|
|
|
| 198 |
stats = self.fetch_gem_stats()
|
| 199 |
contracts = self.fetch_contracts_by_ministry(limit=30)
|
| 200 |
repeated = self.find_repeated_winners(contracts)
|
|
|
|
| 202 |
result = {
|
| 203 |
"stats": stats,
|
| 204 |
"contracts": contracts,
|
| 205 |
+
"repeated_winners": repeated,
|
| 206 |
+
"scraped_at": datetime.now().isoformat(),
|
|
|
|
|
|
|
| 207 |
}
|
| 208 |
|
| 209 |
if save:
|
|
|
|
| 214 |
return result
|
| 215 |
|
| 216 |
|
| 217 |
+
# ── Run directly to test ─────────────────────────────────────────────────────
|
| 218 |
if __name__ == "__main__":
|
| 219 |
print("=" * 60)
|
| 220 |
print("BharatGraph - GeM Contracts Scraper Test")
|
|
|
|
| 226 |
stats = scraper.fetch_gem_stats()
|
| 227 |
s = stats.get("stats", {})
|
| 228 |
print(f" Total orders: {s.get('total_orders', 'N/A'):,}")
|
| 229 |
+
print(f" Total GMV: Rs {s.get('total_gmv_crore', 'N/A'):,} Cr")
|
| 230 |
print(f" Total sellers: {s.get('total_sellers', 'N/A'):,}")
|
| 231 |
|
| 232 |
print("\n[2] Fetching contracts...")
|
|
|
|
| 236 |
if contracts:
|
| 237 |
c = contracts[0]
|
| 238 |
print(f"\n Example contract:")
|
| 239 |
+
print(f" Order ID: {c.get('order_id')}")
|
| 240 |
+
print(f" Buyer: {c.get('buyer_org')}")
|
| 241 |
+
print(f" Seller: {c.get('seller_name')}")
|
| 242 |
+
print(f" Amount: Rs {c.get('amount_crore')} Cr")
|
| 243 |
+
print(f" Date: {c.get('order_date')}")
|
| 244 |
|
| 245 |
+
print("\n[3] Finding repeated contract winners...")
|
| 246 |
repeated = scraper.find_repeated_winners(contracts)
|
| 247 |
if repeated:
|
| 248 |
+
print(f" WARNING: {len(repeated)} companies won multiple contracts!")
|
| 249 |
else:
|
| 250 |
+
print(" No repeated winners in sample")
|
| 251 |
|
| 252 |
print("\n[4] Saving full data...")
|
| 253 |
result = scraper.fetch_and_save(save=True)
|
| 254 |
+
print(f" Contracts saved: {len(result['contracts'])}")
|
| 255 |
print(f" Repeated winners: {len(result['repeated_winners'])}")
|
| 256 |
+
print("\nDone!")
|
scrapers/pib_scraper.py
CHANGED
|
@@ -1,156 +1,169 @@
|
|
| 1 |
"""
|
| 2 |
BharatGraph - PIB (Press Information Bureau) Scraper
|
| 3 |
-
Fetches official government press releases
|
| 4 |
-
Source: pib.gov.in
|
| 5 |
-
|
|
|
|
|
|
|
| 6 |
"""
|
| 7 |
|
| 8 |
-
import feedparser
|
| 9 |
-
import json
|
| 10 |
import os
|
| 11 |
from datetime import datetime
|
|
|
|
| 12 |
from scrapers.base_scraper import BaseScraper
|
| 13 |
from loguru import logger
|
| 14 |
|
| 15 |
|
| 16 |
class PIBScraper(BaseScraper):
|
| 17 |
"""
|
| 18 |
-
Scrapes
|
| 19 |
-
|
| 20 |
-
for disseminating information to print and electronic media.
|
| 21 |
-
|
| 22 |
-
Data includes:
|
| 23 |
-
- Cabinet decisions
|
| 24 |
-
- Ministry press releases
|
| 25 |
-
- Policy announcements
|
| 26 |
-
- Scheme launches
|
| 27 |
"""
|
| 28 |
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
"all_ministries": "https://pib.gov.in/RssMain.aspx?ModId=6&Lang=1&Regid=3",
|
| 32 |
-
"pib_main": "https://pib.gov.in/Rss.aspx",
|
| 33 |
-
"pib_english": "https://pib.gov.in/newsite/erelease.aspx",
|
| 34 |
-
}
|
| 35 |
|
| 36 |
-
# Keywords that could indicate schemes, contracts, or money flows
|
| 37 |
ALERT_KEYWORDS = [
|
| 38 |
"scheme", "crore", "lakh", "contract", "tender", "allocation",
|
| 39 |
"fund", "grant", "subsidy", "project", "award", "procurement",
|
| 40 |
-
"budget", "expenditure", "beneficiary", "disburse",
|
|
|
|
| 41 |
]
|
| 42 |
|
| 43 |
def __init__(self):
|
| 44 |
super().__init__(name="pib", delay=2.0)
|
| 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 |
def _find_keywords(self, text: str) -> list:
|
| 81 |
-
"""
|
| 82 |
-
|
| 83 |
-
Helps flag articles about money, schemes, contracts.
|
| 84 |
-
"""
|
| 85 |
-
text_lower = text.lower()
|
| 86 |
-
found = [kw for kw in self.ALERT_KEYWORDS if kw in text_lower]
|
| 87 |
-
return found
|
| 88 |
|
| 89 |
def fetch_all_feeds(self, save: bool = True) -> list:
|
| 90 |
-
"""
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
seen_links = set()
|
| 95 |
-
|
| 96 |
-
for feed_name in self.RSS_FEEDS:
|
| 97 |
-
articles = self.fetch_feed(feed_name)
|
| 98 |
-
for article in articles:
|
| 99 |
-
if article["link"] not in seen_links:
|
| 100 |
-
all_articles.append(article)
|
| 101 |
-
seen_links.add(article["link"])
|
| 102 |
-
|
| 103 |
-
# Sort by date (newest first)
|
| 104 |
-
all_articles.sort(key=lambda x: x.get("published", ""), reverse=True)
|
| 105 |
-
|
| 106 |
-
if save and all_articles:
|
| 107 |
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 108 |
-
filepath
|
| 109 |
-
self.save_json(
|
| 110 |
-
logger.success(f"[PIB] Saved {len(
|
| 111 |
|
| 112 |
-
return
|
| 113 |
|
| 114 |
def get_high_alert_articles(self, articles: list = None) -> list:
|
| 115 |
-
"""
|
| 116 |
-
Filter articles that contain 3+ alert keywords.
|
| 117 |
-
These are most likely about money flows or schemes.
|
| 118 |
-
"""
|
| 119 |
if articles is None:
|
| 120 |
articles = self.fetch_all_feeds(save=False)
|
|
|
|
|
|
|
|
|
|
| 121 |
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 125 |
]
|
| 126 |
|
| 127 |
-
logger.info(f"[PIB] High-alert articles: {len(high_alert)}/{len(articles)}")
|
| 128 |
-
return high_alert
|
| 129 |
|
| 130 |
-
|
| 131 |
-
# ── Run directly to test ──────────────────────────────────────────────────────
|
| 132 |
if __name__ == "__main__":
|
| 133 |
print("=" * 60)
|
| 134 |
-
print("BharatGraph - PIB Scraper Test")
|
| 135 |
print("=" * 60)
|
| 136 |
|
| 137 |
scraper = PIBScraper()
|
| 138 |
|
| 139 |
-
print("\n[1] Fetching
|
| 140 |
articles = scraper.fetch_all_feeds(save=True)
|
| 141 |
-
print(f"
|
| 142 |
|
| 143 |
if articles:
|
| 144 |
-
print(f"\n
|
| 145 |
-
print(f"
|
| 146 |
-
print(f"
|
| 147 |
-
|
| 148 |
-
print("\n[2]
|
| 149 |
-
|
| 150 |
-
print(f"
|
| 151 |
-
|
| 152 |
-
if high_alert:
|
| 153 |
-
print(f"\n Example high-alert: {high_alert[0]['title'][:70]}")
|
| 154 |
-
print(f" Keywords: {high_alert[0]['alert_keywords']}")
|
| 155 |
-
|
| 156 |
-
print("\nDone! Check data/samples/ folder.")
|
|
|
|
| 1 |
"""
|
| 2 |
BharatGraph - PIB (Press Information Bureau) Scraper
|
| 3 |
+
Fetches official government press releases.
|
| 4 |
+
Source: pib.gov.in
|
| 5 |
+
|
| 6 |
+
NOTE: PIB RSS feeds return empty XML - server blocks feedparser.
|
| 7 |
+
Solution: Scrape pib.gov.in/allRel.aspx HTML directly instead.
|
| 8 |
"""
|
| 9 |
|
|
|
|
|
|
|
| 10 |
import os
|
| 11 |
from datetime import datetime
|
| 12 |
+
from bs4 import BeautifulSoup
|
| 13 |
from scrapers.base_scraper import BaseScraper
|
| 14 |
from loguru import logger
|
| 15 |
|
| 16 |
|
| 17 |
class PIBScraper(BaseScraper):
|
| 18 |
"""
|
| 19 |
+
Scrapes press releases from PIB using direct HTML scraping.
|
| 20 |
+
RSS/feedparser abandoned - PIB server returns empty XML.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
"""
|
| 22 |
|
| 23 |
+
PIB_RELEASES_URL = "https://pib.gov.in/allRel.aspx"
|
| 24 |
+
PIB_BASE_URL = "https://pib.gov.in"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
|
|
|
|
| 26 |
ALERT_KEYWORDS = [
|
| 27 |
"scheme", "crore", "lakh", "contract", "tender", "allocation",
|
| 28 |
"fund", "grant", "subsidy", "project", "award", "procurement",
|
| 29 |
+
"budget", "expenditure", "beneficiary", "disburse", "inaugurate",
|
| 30 |
+
"launch", "approve", "sanction", "release",
|
| 31 |
]
|
| 32 |
|
| 33 |
def __init__(self):
|
| 34 |
super().__init__(name="pib", delay=2.0)
|
| 35 |
+
self.session.headers.update({
|
| 36 |
+
"User-Agent": (
|
| 37 |
+
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
|
| 38 |
+
"AppleWebKit/537.36 (KHTML, like Gecko) "
|
| 39 |
+
"Chrome/120.0.0.0 Safari/537.36"
|
| 40 |
+
),
|
| 41 |
+
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
|
| 42 |
+
"Accept-Language": "en-US,en;q=0.5",
|
| 43 |
+
})
|
| 44 |
+
|
| 45 |
+
def fetch_releases(self, limit: int = 30) -> list:
|
| 46 |
+
"""Fetch press releases by scraping pib.gov.in/allRel.aspx"""
|
| 47 |
+
logger.info(f"[PIB] Fetching from: {self.PIB_RELEASES_URL}")
|
| 48 |
+
html = self.get_html(self.PIB_RELEASES_URL)
|
| 49 |
+
|
| 50 |
+
if not html:
|
| 51 |
+
logger.error("[PIB] Could not fetch page")
|
| 52 |
+
return self._get_sample_articles()
|
| 53 |
+
|
| 54 |
+
articles = self._parse_releases_page(html, limit)
|
| 55 |
+
|
| 56 |
+
if not articles:
|
| 57 |
+
logger.warning("[PIB] No articles parsed - using sample data")
|
| 58 |
+
return self._get_sample_articles()
|
| 59 |
+
|
| 60 |
+
return articles
|
| 61 |
+
|
| 62 |
+
def _parse_releases_page(self, html: str, limit: int) -> list:
|
| 63 |
+
"""Parse press release links from PIB HTML page."""
|
| 64 |
+
soup = BeautifulSoup(html, "lxml")
|
| 65 |
+
articles = []
|
| 66 |
+
|
| 67 |
+
for link in soup.find_all("a", href=True):
|
| 68 |
+
href = link.get("href", "")
|
| 69 |
+
title = link.get_text(strip=True)
|
| 70 |
+
|
| 71 |
+
if not title or len(title) < 15:
|
| 72 |
+
continue
|
| 73 |
+
if not any(kw in href.lower() for kw in
|
| 74 |
+
["prid=", "pressrelease", "pressrelaseid", "newsite"]):
|
| 75 |
+
continue
|
| 76 |
+
|
| 77 |
+
if href.startswith("http"):
|
| 78 |
+
full_url = href
|
| 79 |
+
elif href.startswith("/"):
|
| 80 |
+
full_url = self.PIB_BASE_URL + href
|
| 81 |
+
else:
|
| 82 |
+
full_url = self.PIB_BASE_URL + "/" + href
|
| 83 |
+
|
| 84 |
+
articles.append({
|
| 85 |
+
"title": title,
|
| 86 |
+
"link": full_url,
|
| 87 |
+
"published": "",
|
| 88 |
+
"source": "PIB",
|
| 89 |
+
"scraped_at": datetime.now().isoformat(),
|
| 90 |
+
"entity_type": "press_release",
|
| 91 |
+
"alert_keywords": self._find_keywords(title),
|
| 92 |
+
})
|
| 93 |
+
|
| 94 |
+
if len(articles) >= limit:
|
| 95 |
+
break
|
| 96 |
+
|
| 97 |
+
logger.info(f"[PIB] Parsed {len(articles)} press releases")
|
| 98 |
+
return articles
|
| 99 |
|
| 100 |
def _find_keywords(self, text: str) -> list:
|
| 101 |
+
"""Find alert keywords in article title."""
|
| 102 |
+
return [kw for kw in self.ALERT_KEYWORDS if kw in text.lower()]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 103 |
|
| 104 |
def fetch_all_feeds(self, save: bool = True) -> list:
|
| 105 |
+
"""Main pipeline method - fetch all press releases."""
|
| 106 |
+
articles = self.fetch_releases(limit=50)
|
| 107 |
+
|
| 108 |
+
if save and articles:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 109 |
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 110 |
+
filepath = f"data/samples/pib_articles_{timestamp}.json"
|
| 111 |
+
self.save_json(articles, filepath)
|
| 112 |
+
logger.success(f"[PIB] Saved {len(articles)} articles to {filepath}")
|
| 113 |
|
| 114 |
+
return articles
|
| 115 |
|
| 116 |
def get_high_alert_articles(self, articles: list = None) -> list:
|
| 117 |
+
"""Filter articles with 2+ alert keywords."""
|
|
|
|
|
|
|
|
|
|
| 118 |
if articles is None:
|
| 119 |
articles = self.fetch_all_feeds(save=False)
|
| 120 |
+
high_alert = [a for a in articles if len(a.get("alert_keywords", [])) >= 2]
|
| 121 |
+
logger.info(f"[PIB] High-alert: {len(high_alert)}/{len(articles)}")
|
| 122 |
+
return high_alert
|
| 123 |
|
| 124 |
+
def _get_sample_articles(self) -> list:
|
| 125 |
+
"""Fallback sample data when site is unreachable."""
|
| 126 |
+
return [
|
| 127 |
+
{
|
| 128 |
+
"title": "PM launches rural infrastructure fund allocation scheme",
|
| 129 |
+
"link": "https://pib.gov.in/PressReleasePage.aspx?PRID=1000001",
|
| 130 |
+
"published": datetime.now().isoformat(),
|
| 131 |
+
"source": "PIB (sample)",
|
| 132 |
+
"scraped_at": datetime.now().isoformat(),
|
| 133 |
+
"entity_type": "press_release",
|
| 134 |
+
"alert_keywords": ["scheme", "fund", "allocation"],
|
| 135 |
+
"note": "SAMPLE - real PIB fetch failed",
|
| 136 |
+
},
|
| 137 |
+
{
|
| 138 |
+
"title": "Cabinet approves procurement worth 500 crore for medical equipment",
|
| 139 |
+
"link": "https://pib.gov.in/PressReleasePage.aspx?PRID=1000002",
|
| 140 |
+
"published": datetime.now().isoformat(),
|
| 141 |
+
"source": "PIB (sample)",
|
| 142 |
+
"scraped_at": datetime.now().isoformat(),
|
| 143 |
+
"entity_type": "press_release",
|
| 144 |
+
"alert_keywords": ["procurement", "crore", "approve"],
|
| 145 |
+
"note": "SAMPLE - real PIB fetch failed",
|
| 146 |
+
},
|
| 147 |
]
|
| 148 |
|
|
|
|
|
|
|
| 149 |
|
|
|
|
|
|
|
| 150 |
if __name__ == "__main__":
|
| 151 |
print("=" * 60)
|
| 152 |
+
print("BharatGraph - PIB Scraper Test (HTML mode)")
|
| 153 |
print("=" * 60)
|
| 154 |
|
| 155 |
scraper = PIBScraper()
|
| 156 |
|
| 157 |
+
print("\n[1] Fetching PIB press releases...")
|
| 158 |
articles = scraper.fetch_all_feeds(save=True)
|
| 159 |
+
print(f" Total: {len(articles)}")
|
| 160 |
|
| 161 |
if articles:
|
| 162 |
+
print(f"\n Example:")
|
| 163 |
+
print(f" Title: {articles[0]['title'][:70]}")
|
| 164 |
+
print(f" Keywords: {articles[0]['alert_keywords']}")
|
| 165 |
+
|
| 166 |
+
print("\n[2] High-alert articles (2+ keywords)...")
|
| 167 |
+
high = scraper.get_high_alert_articles(articles)
|
| 168 |
+
print(f" High-alert: {len(high)}")
|
| 169 |
+
print("\nDone!")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|