Hfzune commited on
Commit
834a7eb
·
verified ·
1 Parent(s): 762bbd1

Upload app (4).py

Browse files
Files changed (1) hide show
  1. app (4).py +697 -0
app (4).py ADDED
@@ -0,0 +1,697 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ============================================================
2
+ # app.py — Telegram Mobile→Aadhaar→ASURPAPA Lookup Bot
3
+ # Deployed on Hugging Face ZeroGPU Space
4
+ #
5
+ # Flow:
6
+ # 1. User sends 10-digit mobile to Telegram bot
7
+ # 2. Bot searches parquet (Inddata → Inddatainonefile → 850MindData)
8
+ # for aadhaar linked to that mobile
9
+ # 3. Calls 4 ASURPAPA APIs (num-to-info + 3 aadhaar APIs) in parallel
10
+ # 4. Formats a nice HTML reply to the user
11
+ # 5. Forwards the FULL raw JSON payload as a .json file to your backup channel
12
+ #
13
+ # Every HF-specific hack from your problem log is preserved.
14
+ # ============================================================
15
+
16
+ # ============================================================
17
+ # STEP 0: MONKEY-PATCH HfFolder BEFORE ANY GRADIO/HF IMPORT
18
+ # (This must be the very first executable code — no other import
19
+ # may come before it, or Gradio's oauth.py will crash on import.)
20
+ # ============================================================
21
+ import huggingface_hub
22
+ if not hasattr(huggingface_hub, "HfFolder"):
23
+ class _HfFolder:
24
+ @staticmethod
25
+ def get_token():
26
+ fn = getattr(huggingface_hub, "get_token", None)
27
+ return fn() if fn else None
28
+ @staticmethod
29
+ def save_token(token):
30
+ fn = getattr(huggingface_hub, "login", None)
31
+ if fn: fn(token)
32
+ @staticmethod
33
+ def delete_token():
34
+ fn = getattr(huggingface_hub, "logout", None)
35
+ if fn: fn()
36
+ huggingface_hub.HfFolder = _HfFolder
37
+
38
+ # ============================================================
39
+ # STEP 1: ALL REMAINING IMPORTS
40
+ # ============================================================
41
+ import os
42
+ import json
43
+ import time
44
+ import html as _html
45
+ import asyncio
46
+ import hashlib
47
+ import threading
48
+ import traceback
49
+ from datetime import datetime, timezone
50
+ from typing import Optional, Dict, Any, List
51
+
52
+ import duckdb
53
+ import httpx
54
+
55
+ try:
56
+ import spaces
57
+ _HAS_SPACES = True
58
+ except ImportError:
59
+ _HAS_SPACES = False
60
+ class spaces: # local-dev fallback so app.py runs outside ZeroGPU
61
+ @staticmethod
62
+ def GPU(*_a, **_kw):
63
+ def deco(f): return f
64
+ return deco
65
+
66
+ import gradio as gr
67
+ from fastapi import Request
68
+ from fastapi.responses import JSONResponse
69
+ from starlette.routing import Route as StarletteRoute
70
+ from huggingface_hub import hf_hub_url
71
+
72
+ # ============================================================
73
+ # STEP 2: CONFIG (read from HF Secrets / env)
74
+ # ============================================================
75
+ BOT_TOKEN = os.environ.get("BOT_TOKEN", "")
76
+ BACKUP_CHANNEL_ID = os.environ.get("BACKUP_CHANNEL_ID", "")
77
+ ASUR_KEY = os.environ.get("ASUR_KEY", "@ASUR_ABOUT")
78
+ WEBHOOK_SECRET = os.environ.get("WEBHOOK_SECRET", "change_me_please")
79
+ SPACE_HOST = os.environ.get("SPACE_HOST", "") # auto-set by HF
80
+ OWNER_IDS = {int(x) for x in os.environ.get("OWNER_IDS", "").split(",") if x.strip().isdigit()}
81
+
82
+ # Telegram webhook header secret — must match ^[A-Za-z0-9_-]{1,256}$
83
+ SECRET_TOKEN = hashlib.sha256(WEBHOOK_SECRET.encode()).hexdigest()[:32]
84
+
85
+ # Dataset sources
86
+ DATASET_INDATA = "tfqdeadlo/Inddata"
87
+ DATASET_SINGLE_URL = "https://huggingface.co/datasets/tfqdeadlo/Inddatainonefile/resolve/main/users_data.parquet"
88
+ DATASET_850_REPO = "tfqdeadlo/850MindData"
89
+ DATASET_850_PARTS = ["072", "000", "222", "850", "851"] # hardcoded known partitions
90
+
91
+ # ASURPAPA endpoints
92
+ ASUR_API = {
93
+ "num_to_info": "https://num-to-info.asurpapa.workers.dev/api",
94
+ "aadhaar_to_info": "https://aadhaar.asurpapa.workers.dev/api",
95
+ "aadhaar_family": "https://aadhaar-family.asurpapa.workers.dev/api",
96
+ "aadhaar_ration": "https://ration-card.asurpapa.workers.dev/api", # NOTE: param is `aadhar`
97
+ }
98
+
99
+ # Tunables
100
+ QUERY_TIMEOUT = 90 # seconds — DuckDB hard-cancel timeout
101
+ CACHE_TTL = 86400 # 24h — cache full result per mobile
102
+ RATE_LIMIT_SEC = 10 # seconds between queries per Telegram user
103
+ HTTP_TIMEOUT = 30 # seconds — ASURPAPA request timeout
104
+ BOT_VERSION = "1.0"
105
+
106
+ # ============================================================
107
+ # STEP 3: GLOBAL STATE
108
+ # ============================================================
109
+ con = duckdb.connect()
110
+ _db_lock = threading.Lock()
111
+ _cache = {} # mobile -> (ts, user_text)
112
+ _cache_lock = threading.Lock()
113
+ _rate = {} # user_id -> last_ts
114
+ _rate_lock = threading.Lock()
115
+ _bg_tasks = set() # keep refs to background tasks
116
+
117
+
118
+ # ============================================================
119
+ # STEP 4: SMALL HELPERS
120
+ # ============================================================
121
+ def esc(x: Any) -> str:
122
+ """HTML-escape any value; None -> empty string."""
123
+ if x is None:
124
+ return ""
125
+ return _html.escape(str(x), quote=False)
126
+
127
+
128
+ async def tg_send(chat_id: Any, text: str, **kw) -> Dict[str, Any]:
129
+ """Send a Telegram message. HTML parse_mode by default."""
130
+ kw.setdefault("parse_mode", "HTML")
131
+ kw.setdefault("disable_web_page_preview", True)
132
+ payload = {"chat_id": chat_id, "text": text}
133
+ payload.update(kw)
134
+ try:
135
+ async with httpx.AsyncClient(timeout=HTTP_TIMEOUT) as cli:
136
+ r = await cli.post(f"https://api.telegram.org/bot{BOT_TOKEN}/sendMessage", json=payload)
137
+ return r.json()
138
+ except Exception as e:
139
+ print(f"[tg_send] {e}")
140
+ return {"ok": False, "error": str(e)}
141
+
142
+
143
+ async def tg_edit(chat_id: Any, message_id: int, text: str, **kw) -> Dict[str, Any]:
144
+ """Edit an existing Telegram message."""
145
+ kw.setdefault("parse_mode", "HTML")
146
+ kw.setdefault("disable_web_page_preview", True)
147
+ payload = {"chat_id": chat_id, "message_id": message_id, "text": text}
148
+ payload.update(kw)
149
+ try:
150
+ async with httpx.AsyncClient(timeout=HTTP_TIMEOUT) as cli:
151
+ r = await cli.post(f"https://api.telegram.org/bot{BOT_TOKEN}/editMessageText", json=payload)
152
+ return r.json()
153
+ except Exception as e:
154
+ print(f"[tg_edit] {e}")
155
+ return {"ok": False, "error": str(e)}
156
+
157
+
158
+ async def tg_send_doc(chat_id: Any, filename: str, content: str, caption: str = "") -> Dict[str, Any]:
159
+ """Send a document (used for backup JSON — avoids 4096-char limit)."""
160
+ try:
161
+ async with httpx.AsyncClient(timeout=60) as cli:
162
+ files = {"document": (filename, content.encode("utf-8"), "application/json")}
163
+ data = {"chat_id": str(chat_id), "caption": caption[:1024]}
164
+ r = await cli.post(f"https://api.telegram.org/bot{BOT_TOKEN}/sendDocument",
165
+ data=data, files=files)
166
+ return r.json()
167
+ except Exception as e:
168
+ print(f"[tg_send_doc] {e}")
169
+ return {"ok": False, "error": str(e)}
170
+
171
+
172
+ # ============================================================
173
+ # STEP 5: DUCKDB INIT + MOBILE → AADHAAR SEARCH
174
+ # ============================================================
175
+ def _init_duckdb():
176
+ try:
177
+ con.execute("INSTALL httpfs;")
178
+ con.execute("LOAD httpfs;")
179
+ print("[duckdb] httpfs ready")
180
+ except Exception as e:
181
+ print(f"[duckdb init] {e}")
182
+
183
+
184
+ def _warm_cache():
185
+ """Prime HF CDN + DuckDB row-group cache for the `mobile` column."""
186
+ try:
187
+ t0 = time.time()
188
+ q = (f"SELECT mobile FROM read_parquet("
189
+ f"'hf://datasets/{DATASET_INDATA}/0*/*.parquet', union_by_name=True) LIMIT 1")
190
+ with _db_lock:
191
+ con.execute(q).fetchall()
192
+ print(f"[warm] primed in {time.time() - t0:.1f}s")
193
+ except Exception as e:
194
+ print(f"[warm] failed: {e}")
195
+
196
+
197
+ # Column names that might carry an Aadhaar number in the parquet
198
+ _AADHAAR_COL_CANDIDATES = (
199
+ "aadharNumber", "aadhaarNumber", "aadhaar_number",
200
+ "aadhar_number", "aadhaar", "aadhar", "uid",
201
+ )
202
+
203
+
204
+ def _extract_aadhaar_from_row(row: Dict[str, Any]) -> Optional[str]:
205
+ """Best-effort extraction; returns digits-only string or None."""
206
+ if not row:
207
+ return None
208
+ for col in _AADHAAR_COL_CANDIDATES:
209
+ v = row.get(col)
210
+ if v is None:
211
+ continue
212
+ s = str(v).strip()
213
+ if not s or s.lower() in ("null", "none", "na", "n/a"):
214
+ continue
215
+ digits = "".join(c for c in s if c.isdigit())
216
+ if len(digits) >= 10:
217
+ return digits
218
+ # last-resort fallback: the `id` column (null in some rows but populated in others)
219
+ v = row.get("id")
220
+ if v is not None:
221
+ digits = "".join(c for c in str(v) if c.isdigit())
222
+ if len(digits) >= 10:
223
+ return digits
224
+ return None
225
+
226
+
227
+ def find_aadhaar_by_mobile(mobile: str) -> Dict[str, Any]:
228
+ """
229
+ Blocking. Run via asyncio.to_thread().
230
+ Returns: { aadhaar | None, source | None, raw_row | None, error? }
231
+ """
232
+ # ---- Attempt 1: Inddata prefix partition ----
233
+ prefix = mobile[:3]
234
+ try:
235
+ q = (f"SELECT * FROM read_parquet("
236
+ f"'hf://datasets/{DATASET_INDATA}/{prefix}/*.parquet', union_by_name=True) "
237
+ f"WHERE mobile = '{mobile}' LIMIT 1")
238
+ with _db_lock:
239
+ rows = con.execute(q).fetchall()
240
+ cols = [d[0] for d in con.description] if rows else []
241
+ if rows:
242
+ row = dict(zip(cols, rows[0]))
243
+ return {
244
+ "aadhaar": _extract_aadhaar_from_row(row),
245
+ "source": f"Inddata/{prefix}",
246
+ "raw_row": row,
247
+ }
248
+ except Exception as e:
249
+ print(f"[find_aadhaar:Inddata] {e}")
250
+
251
+ # ---- Attempt 2: single-file Inddata ----
252
+ try:
253
+ q = (f"SELECT * FROM read_parquet('{DATASET_SINGLE_URL}') "
254
+ f"WHERE mobile = '{mobile}' LIMIT 1")
255
+ with _db_lock:
256
+ rows = con.execute(q).fetchall()
257
+ cols = [d[0] for d in con.description] if rows else []
258
+ if rows:
259
+ row = dict(zip(cols, rows[0]))
260
+ return {
261
+ "aadhaar": _extract_aadhaar_from_row(row),
262
+ "source": "Inddatainonefile",
263
+ "raw_row": row,
264
+ }
265
+ except Exception as e:
266
+ print(f"[find_aadhaar:Inddatainonefile] {e}")
267
+
268
+ # ---- Attempt 3: 850MindData known partitions ----
269
+ for p in DATASET_850_PARTS:
270
+ try:
271
+ fname = f"data/Hi-Tek_Part_{p}.parquet"
272
+ url = hf_hub_url(repo_id=DATASET_850_REPO, filename=fname, repo_type="dataset")
273
+ q = (f"SELECT * FROM read_parquet('{url}') "
274
+ f"WHERE CAST(mobile AS VARCHAR) = '{mobile}' LIMIT 1")
275
+ with _db_lock:
276
+ rows = con.execute(q).fetchall()
277
+ cols = [d[0] for d in con.description] if rows else []
278
+ if rows:
279
+ row = dict(zip(cols, rows[0]))
280
+ return {
281
+ "aadhaar": _extract_aadhaar_from_row(row),
282
+ "source": f"850MindData/{p}",
283
+ "raw_row": row,
284
+ }
285
+ except Exception as e:
286
+ print(f"[find_aadhaar:850MindData/{p}] {e}")
287
+ continue
288
+
289
+ return {"aadhaar": None, "source": None, "raw_row": None, "error": "not_found"}
290
+
291
+
292
+ # ============================================================
293
+ # STEP 6: ASURPAPA API FETCHER (parallel)
294
+ # ============================================================
295
+ async def fetch_asurpapa_all(mobile: str, aadhaar: Optional[str]) -> Dict[str, Any]:
296
+ results: Dict[str, Any] = {}
297
+
298
+ async with httpx.AsyncClient(timeout=HTTP_TIMEOUT) as cli:
299
+ # ---- 1. num-to-info (always runs) ----
300
+ try:
301
+ r = await cli.get(
302
+ ASUR_API["num_to_info"],
303
+ params={"key": ASUR_KEY, "number": mobile},
304
+ )
305
+ results["num_to_info"] = r.json()
306
+ except Exception as e:
307
+ results["num_to_info"] = {"error": str(e)}
308
+
309
+ # ---- 2-4. aadhaar APIs (only if aadhaar was resolved) ----
310
+ if not aadhaar:
311
+ for k in ("aadhaar_to_info", "aadhaar_family", "aadhaar_ration"):
312
+ results[k] = {"error": "skipped: no aadhaar resolved from mobile"}
313
+ return results
314
+
315
+ async def _call(name: str, url: str, param_name: str):
316
+ try:
317
+ r = await cli.get(url, params={"key": ASUR_KEY, param_name: aadhaar})
318
+ return name, r.json()
319
+ except Exception as e:
320
+ return name, {"error": str(e)}
321
+
322
+ gathered = await asyncio.gather(
323
+ _call("aadhaar_to_info", ASUR_API["aadhaar_to_info"], "aadhaar"),
324
+ _call("aadhaar_family", ASUR_API["aadhaar_family"], "aadhaar"),
325
+ _call("aadhaar_ration", ASUR_API["aadhaar_ration"], "aadhar"), # NOTE spelling
326
+ return_exceptions=False,
327
+ )
328
+ for name, res in gathered:
329
+ results[name] = res
330
+
331
+ return results
332
+
333
+
334
+ # ============================================================
335
+ # STEP 7: FORMATTERS
336
+ # ============================================================
337
+ def format_user_message(mobile: str,
338
+ aadhaar_res: Dict[str, Any],
339
+ api_results: Dict[str, Any]) -> str:
340
+ """Build the user-facing HTML message (parse_mode=HTML)."""
341
+ lines: List[str] = []
342
+ lines.append(f"🔎 <b>Lookup complete</b> for <code>{esc(mobile)}</code>")
343
+ lines.append("")
344
+
345
+ # --- Aadhaar resolution status ---
346
+ aad = aadhaar_res.get("aadhaar")
347
+ if aad:
348
+ masked = "XXXX-XXXX-" + aad[-4:]
349
+ lines.append(f"🪪 <b>Aadhaar:</b> <code>{masked}</code> "
350
+ f"<i>(via {esc(aadhaar_res.get('source'))})</i>")
351
+ else:
352
+ lines.append("🪪 <b>Aadhaar:</b> <i>not found in datasets — "
353
+ "aadhaar APIs skipped</i>")
354
+ lines.append("")
355
+
356
+ # --- Mobile Info (num-to-info) ---
357
+ nti = api_results.get("num_to_info", {}) or {}
358
+ if nti.get("status") == "success" and isinstance(nti.get("data"), dict):
359
+ d = nti["data"]
360
+ lines.append("📱 <b>Mobile Info</b>")
361
+ if d.get("name"): lines.append(f"👤 <b>Name:</b> {esc(d['name'])}")
362
+ if d.get("fname"): lines.append(f"👨 <b>Father:</b> {esc(d['fname'])}")
363
+ if d.get("circle"): lines.append(f"🌐 <b>Circle:</b> {esc(d['circle'])}")
364
+ if d.get("email"): lines.append(f"📧 <b>Email:</b> {esc(d['email'])}")
365
+ if d.get("alt"): lines.append(f"📞 <b>Alt:</b> {esc(d['alt'])}")
366
+ if d.get("address"):lines.append(f"🏠 <b>Address:</b> {esc(d['address'])}")
367
+ lines.append("")
368
+ elif nti.get("error"):
369
+ lines.append(f"📱 <b>Mobile Info:</b> ⚠️ {esc(nti['error'])}")
370
+ lines.append("")
371
+
372
+ # --- Aadhaar linked records (aadhaar_to_info) ---
373
+ ati = api_results.get("aadhaar_to_info", {}) or {}
374
+ if ati.get("status") == "success":
375
+ recs = ati.get("data") or []
376
+ cnt = len(recs)
377
+ lines.append(f"🪪 <b>Aadhaar Linked Records:</b> {cnt}")
378
+ for rec in recs[:3]:
379
+ lines.append(f" • {esc(rec.get('name'))} — "
380
+ f"📞 {esc(rec.get('phoneNumber'))}")
381
+ if cnt > 3:
382
+ lines.append(f" <i>… and {cnt - 3} more (see attached JSON)</i>")
383
+ lines.append("")
384
+
385
+ # --- Family ---
386
+ fam = api_results.get("aadhaar_family", {}) or {}
387
+ if fam.get("status") is True:
388
+ members = fam.get("members") or []
389
+ lines.append(f"👨‍👩‍👧 <b>Family ({len(members)} members)</b>")
390
+ for m in members[:10]:
391
+ lines.append(f" • {esc(m.get('name'))} ({esc(m.get('relation'))})")
392
+ if len(members) > 10:
393
+ lines.append(f" <i>… and {len(members) - 10} more (see attached JSON)</i>")
394
+ lines.append("")
395
+
396
+ # --- Ration ---
397
+ rat = api_results.get("aadhaar_ration", {}) or {}
398
+ if rat.get("status") is True:
399
+ lines.append("🍚 <b>Ration Card</b>")
400
+ if rat.get("head_family"): lines.append(f"👤 Head: {esc(rat['head_family'])}")
401
+ if rat.get("ration_number"): lines.append(f"🔢 Number: <code>{esc(rat['ration_number'])}</code>")
402
+ if rat.get("scheme"): lines.append(f"📋 Scheme: {esc(rat['scheme'])}")
403
+ if rat.get("address"): lines.append(f"🏠 Address: {esc(rat['address'])}")
404
+ if rat.get("district"): lines.append(f"📍 {esc(rat['district'])}, {esc(rat.get('state'))}")
405
+ if rat.get("fps_id"): lines.append(f"🆔 FPS: <code>{esc(rat['fps_id'])}</code>")
406
+ lines.append("")
407
+
408
+ lines.append("📎 <i>Full JSON forwarded to backup channel.</i>")
409
+
410
+ text = "\n".join(lines)
411
+ if len(text) > 4000:
412
+ text = text[:3985] + "\n<i>… (truncated)</i>"
413
+ return text
414
+
415
+
416
+ def build_backup_payload(user_id: int, username: Optional[str], mobile: str,
417
+ aadhaar_res: Dict[str, Any],
418
+ api_results: Dict[str, Any]) -> Dict[str, Any]:
419
+ found = bool(aadhaar_res.get("aadhaar"))
420
+ nti_ok = (api_results.get("num_to_info") or {}).get("status") == "success"
421
+ if not found and not nti_ok:
422
+ status = "not_found"
423
+ elif not found:
424
+ status = "partial"
425
+ else:
426
+ status = "success"
427
+
428
+ return {
429
+ "meta": {
430
+ "timestamp_utc": datetime.now(timezone.utc).isoformat(),
431
+ "telegram_user_id": user_id,
432
+ "telegram_username": f"@{username}" if username else None,
433
+ "bot_version": BOT_VERSION,
434
+ },
435
+ "input": {"mobile": mobile},
436
+ "aadhaar_resolution": {
437
+ "found": found,
438
+ "aadhaar": aadhaar_res.get("aadhaar"),
439
+ "source_dataset": aadhaar_res.get("source"),
440
+ "raw_row": aadhaar_res.get("raw_row"),
441
+ },
442
+ "asurpapa_responses": api_results,
443
+ "status": status,
444
+ }
445
+
446
+
447
+ # ============================================================
448
+ # STEP 8: BACKUP FORWARDER
449
+ # ============================================================
450
+ async def forward_to_backup(user_id: int, username: Optional[str], mobile: str,
451
+ aadhaar_res: Dict[str, Any],
452
+ api_results: Dict[str, Any]) -> None:
453
+ if not BACKUP_CHANNEL_ID:
454
+ print("[backup] BACKUP_CHANNEL_ID not set — skipping")
455
+ return
456
+
457
+ payload = build_backup_payload(user_id, username, mobile, aadhaar_res, api_results)
458
+
459
+ header = (
460
+ f"📥 <b>New lookup</b>\n"
461
+ f"👤 User: <code>{user_id}</code>"
462
+ f"{' (@' + esc(username) + ')' if username else ''}\n"
463
+ f"📱 Mobile: <code>{esc(mobile)}</code>\n"
464
+ f"🪪 Aadhaar: "
465
+ f"{'<code>' + esc(aadhaar_res.get('aadhaar')) + '</code>' if aadhaar_res.get('aadhaar') else 'not found'}\n"
466
+ f"📊 Status: <b>{esc(payload['status'])}</b>"
467
+ )
468
+ await tg_send(BACKUP_CHANNEL_ID, header)
469
+
470
+ json_str = json.dumps(payload, indent=2, ensure_ascii=False, default=str)
471
+ filename = f"lookup_{mobile}_{int(time.time())}.json"
472
+ await tg_send_doc(BACKUP_CHANNEL_ID, filename, json_str,
473
+ caption=f"Mobile {mobile} — full JSON")
474
+
475
+
476
+ # ============================================================
477
+ # STEP 9: UPDATE PROCESSOR (main bot logic)
478
+ # ============================================================
479
+ async def process_update(update: Dict[str, Any]) -> None:
480
+ msg = update.get("message") or {}
481
+ user = msg.get("from") or {}
482
+ chat = msg.get("chat") or {}
483
+ uid = user.get("id")
484
+ uname = user.get("username")
485
+ cid = chat.get("id")
486
+ text = (msg.get("text") or "").strip()
487
+
488
+ if not uid or not cid or not text:
489
+ return
490
+
491
+ # ---- Authorization ----
492
+ if OWNER_IDS and uid not in OWNER_IDS:
493
+ await tg_send(cid, "⛔ <b>Not authorized.</b>\n\nSend /id to get your Telegram user ID.")
494
+ return
495
+
496
+ # ---- Commands ----
497
+ if text.startswith("/start"):
498
+ await tg_send(cid,
499
+ "👋 <b>Welcome!</b>\n\n"
500
+ "Send a <b>10-digit Indian mobile number</b> to look up info.\n\n"
501
+ f"Your Telegram ID: <code>{uid}</code>")
502
+ return
503
+ if text.startswith("/help"):
504
+ await tg_send(cid,
505
+ "Send a 10-digit mobile number (e.g. <code>9876543210</code>).\n\n"
506
+ "/id — get your Telegram user ID\n"
507
+ "/help — this help")
508
+ return
509
+ if text.startswith("/id"):
510
+ await tg_send(cid, f"Your Telegram ID: <code>{uid}</code>")
511
+ return
512
+
513
+ # ---- Validate 10-digit mobile ----
514
+ digits = "".join(c for c in text if c.isdigit())
515
+ if len(digits) != 10:
516
+ await tg_send(cid, "❌ <b>Invalid input.</b>\n\nPlease send a <b>10-digit mobile number</b>.")
517
+ return
518
+
519
+ # ---- Rate limit ----
520
+ now = time.time()
521
+ with _rate_lock:
522
+ last = _rate.get(uid, 0.0)
523
+ if now - last < RATE_LIMIT_SEC:
524
+ wait = int(RATE_LIMIT_SEC - (now - last))
525
+ await tg_send(cid, f"⏳ Please wait {wait}s before the next query.")
526
+ return
527
+ _rate[uid] = now
528
+
529
+ # ---- Cache ----
530
+ with _cache_lock:
531
+ cached = _cache.get(digits)
532
+ if cached and now - cached[0] < CACHE_TTL:
533
+ await tg_send(cid, cached[1])
534
+ return
535
+
536
+ # ---- Send "Searching…" ----
537
+ status = await tg_send(cid, f"🔍 <b>Searching…</b> for <code>{digits}</code>")
538
+ status_id = (status or {}).get("result", {}).get("message_id")
539
+
540
+ try:
541
+ # 1. Resolve aadhaar (blocking call → thread)
542
+ aadhaar_res = await asyncio.to_thread(find_aadhaar_by_mobile, digits)
543
+
544
+ # 2. Fetch all ASURPAPA APIs
545
+ api_results = await fetch_asurpapa_all(digits, aadhaar_res.get("aadhaar"))
546
+
547
+ # 3. Format user message
548
+ user_text = format_user_message(digits, aadhaar_res, api_results)
549
+
550
+ # 4. Send / edit
551
+ if status_id:
552
+ await tg_edit(cid, status_id, user_text)
553
+ else:
554
+ await tg_send(cid, user_text)
555
+
556
+ # 5. Cache
557
+ with _cache_lock:
558
+ _cache[digits] = (time.time(), user_text)
559
+
560
+ # 6. Backup channel
561
+ await forward_to_backup(uid, uname, digits, aadhaar_res, api_results)
562
+
563
+ except Exception as e:
564
+ print(f"[process_update] {e}\n{traceback.format_exc()}")
565
+ err = f"⚠️ <b>Error:</b> <code>{esc(str(e))[:200]}</code>"
566
+ if status_id:
567
+ await tg_edit(cid, status_id, err)
568
+ else:
569
+ await tg_send(cid, err)
570
+
571
+
572
+ # ============================================================
573
+ # STEP 10: FASTAPI ROUTE HANDLERS
574
+ # ============================================================
575
+ async def webhook_handler(request: Request):
576
+ # Path secret
577
+ if request.path_params.get("secret") != WEBHOOK_SECRET:
578
+ return JSONResponse({"ok": False, "reason": "bad_path_secret"}, status_code=403)
579
+ # Telegram secret header
580
+ if request.headers.get("x-telegram-bot-api-secret-token") != SECRET_TOKEN:
581
+ return JSONResponse({"ok": False, "reason": "bad_header"}, status_code=403)
582
+
583
+ try:
584
+ data = await request.json()
585
+ except Exception:
586
+ return JSONResponse({"ok": True}) # swallow malformed to prevent retries
587
+
588
+ # Fire-and-forget — return 200 immediately so Telegram doesn't retry
589
+ try:
590
+ task = asyncio.create_task(process_update(data))
591
+ _bg_tasks.add(task)
592
+ task.add_done_callback(_bg_tasks.discard)
593
+ except RuntimeError:
594
+ # No running loop — extreme edge case
595
+ threading.Thread(
596
+ target=lambda: asyncio.run(process_update(data)),
597
+ daemon=True,
598
+ ).start()
599
+
600
+ return JSONResponse({"ok": True})
601
+
602
+
603
+ async def health_handler(request: Request):
604
+ return JSONResponse({
605
+ "status": "ok",
606
+ "time": time.time(),
607
+ "version": BOT_VERSION,
608
+ })
609
+
610
+
611
+ # ============================================================
612
+ # STEP 11: GRADIO UI (hidden GPU init button for ZeroGPU scanner)
613
+ # ============================================================
614
+ def _build_gradio() -> gr.Blocks:
615
+ with gr.Blocks(title="Telegram Lookup Bot") as demo:
616
+ gr.Markdown("# 🤖 Telegram PII Lookup Bot")
617
+ gr.Markdown(
618
+ "This Space runs a **Telegram bot**. Open Telegram and send a "
619
+ "**10-digit mobile number** to the bot.\n\n"
620
+ "- `/health` — health check\n"
621
+ "- `/webhook/<secret>` — Telegram webhook"
622
+ )
623
+
624
+ if _HAS_SPACES:
625
+ @spaces.GPU(duration=10)
626
+ def _zerogpu_register():
627
+ return "gpu-ready"
628
+
629
+ _btn = gr.Button("init-gpu", visible=False)
630
+ _btn.click(fn=_zerogpu_register, inputs=None, outputs=None)
631
+
632
+ return demo
633
+
634
+
635
+ # ============================================================
636
+ # STEP 12: WEBHOOK REGISTRATION (background thread)
637
+ # ============================================================
638
+ def _set_webhook():
639
+ if not BOT_TOKEN:
640
+ print("[webhook] BOT_TOKEN missing — skipped")
641
+ return
642
+ if not SPACE_HOST:
643
+ print("[webhook] SPACE_HOST missing — skipped")
644
+ return
645
+
646
+ url = f"https://{SPACE_HOST}/webhook/{WEBHOOK_SECRET}"
647
+ try:
648
+ with httpx.Client(timeout=30) as cli:
649
+ r = cli.post(
650
+ f"https://api.telegram.org/bot{BOT_TOKEN}/setWebhook",
651
+ json={
652
+ "url": url,
653
+ "secret_token": SECRET_TOKEN,
654
+ "allowed_updates": ["message"],
655
+ "drop_pending_updates": True,
656
+ },
657
+ )
658
+ res = r.json()
659
+ print(f"[webhook] set -> {res}")
660
+ except Exception as e:
661
+ print(f"[webhook] error: {e}")
662
+
663
+
664
+ # ============================================================
665
+ # STEP 13: BOOT
666
+ # ============================================================
667
+ print("[boot] initialising DuckDB…")
668
+ _init_duckdb()
669
+
670
+ print("[boot] building Gradio app…")
671
+ demo = _build_gradio()
672
+
673
+ print("[boot] launching Gradio (ssr_mode=False, prevent_thread_lock=True)…")
674
+ demo.launch(
675
+ server_name="0.0.0.0",
676
+ server_port=7860,
677
+ share=False,
678
+ ssr_mode=False, # disables Node SSR proxy so /webhook is reachable
679
+ prevent_thread_lock=True, # returns live app immediately
680
+ )
681
+
682
+ print("[boot] injecting /webhook and /health routes at index 0…")
683
+ live_app = demo.app # NOT demo.server.app
684
+ live_app.router.routes.insert(
685
+ 0, StarletteRoute("/webhook/{secret}", webhook_handler, methods=["POST"])
686
+ )
687
+ live_app.router.routes.insert(
688
+ 0, StarletteRoute("/health", health_handler, methods=["GET"])
689
+ )
690
+ live_app.build_middleware_stack()
691
+
692
+ print("[boot] starting background tasks…")
693
+ threading.Thread(target=_warm_cache, daemon=True, name="warm").start()
694
+ threading.Thread(target=_set_webhook, daemon=True, name="setwh").start()
695
+
696
+ print("[boot] ready — blocking main thread")
697
+ demo.block_thread()