# ============================================================ # app.py — Telegram Mobile→Aadhaar→ASURPAPA Lookup Bot # Deployed on Hugging Face ZeroGPU Space # # Flow: # 1. User sends 10-digit mobile to Telegram bot # 2. Bot searches parquet (Inddata → Inddatainonefile → 850MindData) # for aadhaar linked to that mobile # 3. Calls 4 ASURPAPA APIs (num-to-info + 3 aadhaar APIs) in parallel # 4. Formats a nice HTML reply to the user # 5. Forwards the FULL raw JSON payload as a .json file to your backup channel # # Every HF-specific hack from your problem log is preserved. # ============================================================ # ============================================================ # STEP 0: MONKEY-PATCH HfFolder BEFORE ANY GRADIO/HF IMPORT # (This must be the very first executable code — no other import # may come before it, or Gradio's oauth.py will crash on import.) # ============================================================ import huggingface_hub if not hasattr(huggingface_hub, "HfFolder"): class _HfFolder: @staticmethod def get_token(): fn = getattr(huggingface_hub, "get_token", None) return fn() if fn else None @staticmethod def save_token(token): fn = getattr(huggingface_hub, "login", None) if fn: fn(token) @staticmethod def delete_token(): fn = getattr(huggingface_hub, "logout", None) if fn: fn() huggingface_hub.HfFolder = _HfFolder # ============================================================ # STEP 1: ALL REMAINING IMPORTS # ============================================================ import os import json import time import html as _html import asyncio import hashlib import threading import traceback from datetime import datetime, timezone from typing import Optional, Dict, Any, List import duckdb import httpx try: import spaces _HAS_SPACES = True except ImportError: _HAS_SPACES = False class spaces: # local-dev fallback so app.py runs outside ZeroGPU @staticmethod def GPU(*_a, **_kw): def deco(f): return f return deco import gradio as gr from fastapi import Request from fastapi.responses import JSONResponse from starlette.routing import Route as StarletteRoute from huggingface_hub import hf_hub_url # ============================================================ # STEP 2: CONFIG (read from HF Secrets / env) # ============================================================ BOT_TOKEN = os.environ.get("BOT_TOKEN", "") BACKUP_CHANNEL_ID = os.environ.get("BACKUP_CHANNEL_ID", "") ASUR_KEY = os.environ.get("ASUR_KEY", "@ASUR_ABOUT") WEBHOOK_SECRET = os.environ.get("WEBHOOK_SECRET", "change_me_please") SPACE_HOST = os.environ.get("SPACE_HOST", "") # auto-set by HF OWNER_IDS = {int(x) for x in os.environ.get("OWNER_IDS", "").split(",") if x.strip().isdigit()} # Telegram webhook header secret — must match ^[A-Za-z0-9_-]{1,256}$ SECRET_TOKEN = hashlib.sha256(WEBHOOK_SECRET.encode()).hexdigest()[:32] # Dataset sources DATASET_INDATA = "tfqdeadlo/Inddata" DATASET_SINGLE_URL = "https://huggingface.co/datasets/tfqdeadlo/Inddatainonefile/resolve/main/users_data.parquet" DATASET_850_REPO = "tfqdeadlo/850MindData" DATASET_850_PARTS = ["072", "000", "222", "850", "851"] # hardcoded known partitions # ASURPAPA endpoints ASUR_API = { "num_to_info": "https://num-to-info.asurpapa.workers.dev/api", "aadhaar_to_info": "https://aadhaar.asurpapa.workers.dev/api", "aadhaar_family": "https://aadhaar-family.asurpapa.workers.dev/api", "aadhaar_ration": "https://ration-card.asurpapa.workers.dev/api", # NOTE: param is `aadhar` } # Tunables QUERY_TIMEOUT = 90 # seconds — DuckDB hard-cancel timeout CACHE_TTL = 86400 # 24h — cache full result per mobile RATE_LIMIT_SEC = 10 # seconds between queries per Telegram user HTTP_TIMEOUT = 30 # seconds — ASURPAPA request timeout BOT_VERSION = "1.0" # ============================================================ # STEP 3: GLOBAL STATE # ============================================================ con = duckdb.connect() _db_lock = threading.Lock() _cache = {} # mobile -> (ts, user_text) _cache_lock = threading.Lock() _rate = {} # user_id -> last_ts _rate_lock = threading.Lock() _bg_tasks = set() # keep refs to background tasks # ============================================================ # STEP 4: SMALL HELPERS # ============================================================ def esc(x: Any) -> str: """HTML-escape any value; None -> empty string.""" if x is None: return "" return _html.escape(str(x), quote=False) async def tg_send(chat_id: Any, text: str, **kw) -> Dict[str, Any]: """Send a Telegram message. HTML parse_mode by default.""" kw.setdefault("parse_mode", "HTML") kw.setdefault("disable_web_page_preview", True) payload = {"chat_id": chat_id, "text": text} payload.update(kw) try: async with httpx.AsyncClient(timeout=HTTP_TIMEOUT) as cli: r = await cli.post(f"https://api.telegram.org/bot{BOT_TOKEN}/sendMessage", json=payload) return r.json() except Exception as e: print(f"[tg_send] {e}") return {"ok": False, "error": str(e)} async def tg_edit(chat_id: Any, message_id: int, text: str, **kw) -> Dict[str, Any]: """Edit an existing Telegram message.""" kw.setdefault("parse_mode", "HTML") kw.setdefault("disable_web_page_preview", True) payload = {"chat_id": chat_id, "message_id": message_id, "text": text} payload.update(kw) try: async with httpx.AsyncClient(timeout=HTTP_TIMEOUT) as cli: r = await cli.post(f"https://api.telegram.org/bot{BOT_TOKEN}/editMessageText", json=payload) return r.json() except Exception as e: print(f"[tg_edit] {e}") return {"ok": False, "error": str(e)} async def tg_send_doc(chat_id: Any, filename: str, content: str, caption: str = "") -> Dict[str, Any]: """Send a document (used for backup JSON — avoids 4096-char limit).""" try: async with httpx.AsyncClient(timeout=60) as cli: files = {"document": (filename, content.encode("utf-8"), "application/json")} data = {"chat_id": str(chat_id), "caption": caption[:1024]} r = await cli.post(f"https://api.telegram.org/bot{BOT_TOKEN}/sendDocument", data=data, files=files) return r.json() except Exception as e: print(f"[tg_send_doc] {e}") return {"ok": False, "error": str(e)} # ============================================================ # STEP 5: DUCKDB INIT + MOBILE → AADHAAR SEARCH # ============================================================ def _init_duckdb(): try: con.execute("INSTALL httpfs;") con.execute("LOAD httpfs;") print("[duckdb] httpfs ready") except Exception as e: print(f"[duckdb init] {e}") def _warm_cache(): """Prime HF CDN + DuckDB row-group cache for the `mobile` column.""" try: t0 = time.time() q = (f"SELECT mobile FROM read_parquet(" f"'hf://datasets/{DATASET_INDATA}/0*/*.parquet', union_by_name=True) LIMIT 1") with _db_lock: con.execute(q).fetchall() print(f"[warm] primed in {time.time() - t0:.1f}s") except Exception as e: print(f"[warm] failed: {e}") # Column names that might carry an Aadhaar number in the parquet _AADHAAR_COL_CANDIDATES = ( "aadharNumber", "aadhaarNumber", "aadhaar_number", "aadhar_number", "aadhaar", "aadhar", "uid", ) def _extract_aadhaar_from_row(row: Dict[str, Any]) -> Optional[str]: """Best-effort extraction; returns digits-only string or None.""" if not row: return None for col in _AADHAAR_COL_CANDIDATES: v = row.get(col) if v is None: continue s = str(v).strip() if not s or s.lower() in ("null", "none", "na", "n/a"): continue digits = "".join(c for c in s if c.isdigit()) if len(digits) >= 10: return digits # last-resort fallback: the `id` column (null in some rows but populated in others) v = row.get("id") if v is not None: digits = "".join(c for c in str(v) if c.isdigit()) if len(digits) >= 10: return digits return None def find_aadhaar_by_mobile(mobile: str) -> Dict[str, Any]: """ Blocking. Run via asyncio.to_thread(). Returns: { aadhaar | None, source | None, raw_row | None, error? } """ # ---- Attempt 1: Inddata prefix partition ---- prefix = mobile[:3] try: q = (f"SELECT * FROM read_parquet(" f"'hf://datasets/{DATASET_INDATA}/{prefix}/*.parquet', union_by_name=True) " f"WHERE mobile = '{mobile}' LIMIT 1") with _db_lock: rows = con.execute(q).fetchall() cols = [d[0] for d in con.description] if rows else [] if rows: row = dict(zip(cols, rows[0])) return { "aadhaar": _extract_aadhaar_from_row(row), "source": f"Inddata/{prefix}", "raw_row": row, } except Exception as e: print(f"[find_aadhaar:Inddata] {e}") # ---- Attempt 2: single-file Inddata ---- try: q = (f"SELECT * FROM read_parquet('{DATASET_SINGLE_URL}') " f"WHERE mobile = '{mobile}' LIMIT 1") with _db_lock: rows = con.execute(q).fetchall() cols = [d[0] for d in con.description] if rows else [] if rows: row = dict(zip(cols, rows[0])) return { "aadhaar": _extract_aadhaar_from_row(row), "source": "Inddatainonefile", "raw_row": row, } except Exception as e: print(f"[find_aadhaar:Inddatainonefile] {e}") # ---- Attempt 3: 850MindData known partitions ---- for p in DATASET_850_PARTS: try: fname = f"data/Hi-Tek_Part_{p}.parquet" url = hf_hub_url(repo_id=DATASET_850_REPO, filename=fname, repo_type="dataset") q = (f"SELECT * FROM read_parquet('{url}') " f"WHERE CAST(mobile AS VARCHAR) = '{mobile}' LIMIT 1") with _db_lock: rows = con.execute(q).fetchall() cols = [d[0] for d in con.description] if rows else [] if rows: row = dict(zip(cols, rows[0])) return { "aadhaar": _extract_aadhaar_from_row(row), "source": f"850MindData/{p}", "raw_row": row, } except Exception as e: print(f"[find_aadhaar:850MindData/{p}] {e}") continue return {"aadhaar": None, "source": None, "raw_row": None, "error": "not_found"} # ============================================================ # STEP 6: ASURPAPA API FETCHER (parallel) # ============================================================ async def fetch_asurpapa_all(mobile: str, aadhaar: Optional[str]) -> Dict[str, Any]: results: Dict[str, Any] = {} async with httpx.AsyncClient(timeout=HTTP_TIMEOUT) as cli: # ---- 1. num-to-info (always runs) ---- try: r = await cli.get( ASUR_API["num_to_info"], params={"key": ASUR_KEY, "number": mobile}, ) results["num_to_info"] = r.json() except Exception as e: results["num_to_info"] = {"error": str(e)} # ---- 2-4. aadhaar APIs (only if aadhaar was resolved) ---- if not aadhaar: for k in ("aadhaar_to_info", "aadhaar_family", "aadhaar_ration"): results[k] = {"error": "skipped: no aadhaar resolved from mobile"} return results async def _call(name: str, url: str, param_name: str): try: r = await cli.get(url, params={"key": ASUR_KEY, param_name: aadhaar}) return name, r.json() except Exception as e: return name, {"error": str(e)} gathered = await asyncio.gather( _call("aadhaar_to_info", ASUR_API["aadhaar_to_info"], "aadhaar"), _call("aadhaar_family", ASUR_API["aadhaar_family"], "aadhaar"), _call("aadhaar_ration", ASUR_API["aadhaar_ration"], "aadhar"), # NOTE spelling return_exceptions=False, ) for name, res in gathered: results[name] = res return results # ============================================================ # STEP 7: FORMATTERS # ============================================================ def format_user_message(mobile: str, aadhaar_res: Dict[str, Any], api_results: Dict[str, Any]) -> str: """Build the user-facing HTML message (parse_mode=HTML).""" lines: List[str] = [] lines.append(f"🔎 Lookup complete for {esc(mobile)}") lines.append("") # --- Aadhaar resolution status --- aad = aadhaar_res.get("aadhaar") if aad: masked = "XXXX-XXXX-" + aad[-4:] lines.append(f"🪪 Aadhaar: {masked} " f"(via {esc(aadhaar_res.get('source'))})") else: lines.append("🪪 Aadhaar: not found in datasets — " "aadhaar APIs skipped") lines.append("") # --- Mobile Info (num-to-info) --- nti = api_results.get("num_to_info", {}) or {} if nti.get("status") == "success" and isinstance(nti.get("data"), dict): d = nti["data"] lines.append("📱 Mobile Info") if d.get("name"): lines.append(f"👤 Name: {esc(d['name'])}") if d.get("fname"): lines.append(f"👨 Father: {esc(d['fname'])}") if d.get("circle"): lines.append(f"🌐 Circle: {esc(d['circle'])}") if d.get("email"): lines.append(f"📧 Email: {esc(d['email'])}") if d.get("alt"): lines.append(f"📞 Alt: {esc(d['alt'])}") if d.get("address"):lines.append(f"🏠 Address: {esc(d['address'])}") lines.append("") elif nti.get("error"): lines.append(f"📱 Mobile Info: ⚠️ {esc(nti['error'])}") lines.append("") # --- Aadhaar linked records (aadhaar_to_info) --- ati = api_results.get("aadhaar_to_info", {}) or {} if ati.get("status") == "success": recs = ati.get("data") or [] cnt = len(recs) lines.append(f"🪪 Aadhaar Linked Records: {cnt}") for rec in recs[:3]: lines.append(f" • {esc(rec.get('name'))} — " f"📞 {esc(rec.get('phoneNumber'))}") if cnt > 3: lines.append(f" … and {cnt - 3} more (see attached JSON)") lines.append("") # --- Family --- fam = api_results.get("aadhaar_family", {}) or {} if fam.get("status") is True: members = fam.get("members") or [] lines.append(f"👨‍👩‍👧 Family ({len(members)} members)") for m in members[:10]: lines.append(f" • {esc(m.get('name'))} ({esc(m.get('relation'))})") if len(members) > 10: lines.append(f" … and {len(members) - 10} more (see attached JSON)") lines.append("") # --- Ration --- rat = api_results.get("aadhaar_ration", {}) or {} if rat.get("status") is True: lines.append("🍚 Ration Card") if rat.get("head_family"): lines.append(f"👤 Head: {esc(rat['head_family'])}") if rat.get("ration_number"): lines.append(f"🔢 Number: {esc(rat['ration_number'])}") if rat.get("scheme"): lines.append(f"📋 Scheme: {esc(rat['scheme'])}") if rat.get("address"): lines.append(f"🏠 Address: {esc(rat['address'])}") if rat.get("district"): lines.append(f"📍 {esc(rat['district'])}, {esc(rat.get('state'))}") if rat.get("fps_id"): lines.append(f"🆔 FPS: {esc(rat['fps_id'])}") lines.append("") lines.append("📎 Full JSON forwarded to backup channel.") text = "\n".join(lines) if len(text) > 4000: text = text[:3985] + "\n… (truncated)" return text def build_backup_payload(user_id: int, username: Optional[str], mobile: str, aadhaar_res: Dict[str, Any], api_results: Dict[str, Any]) -> Dict[str, Any]: found = bool(aadhaar_res.get("aadhaar")) nti_ok = (api_results.get("num_to_info") or {}).get("status") == "success" if not found and not nti_ok: status = "not_found" elif not found: status = "partial" else: status = "success" return { "meta": { "timestamp_utc": datetime.now(timezone.utc).isoformat(), "telegram_user_id": user_id, "telegram_username": f"@{username}" if username else None, "bot_version": BOT_VERSION, }, "input": {"mobile": mobile}, "aadhaar_resolution": { "found": found, "aadhaar": aadhaar_res.get("aadhaar"), "source_dataset": aadhaar_res.get("source"), "raw_row": aadhaar_res.get("raw_row"), }, "asurpapa_responses": api_results, "status": status, } # ============================================================ # STEP 8: BACKUP FORWARDER # ============================================================ async def forward_to_backup(user_id: int, username: Optional[str], mobile: str, aadhaar_res: Dict[str, Any], api_results: Dict[str, Any]) -> None: if not BACKUP_CHANNEL_ID: print("[backup] BACKUP_CHANNEL_ID not set — skipping") return payload = build_backup_payload(user_id, username, mobile, aadhaar_res, api_results) header = ( f"📥 New lookup\n" f"👤 User: {user_id}" f"{' (@' + esc(username) + ')' if username else ''}\n" f"📱 Mobile: {esc(mobile)}\n" f"🪪 Aadhaar: " f"{'' + esc(aadhaar_res.get('aadhaar')) + '' if aadhaar_res.get('aadhaar') else 'not found'}\n" f"📊 Status: {esc(payload['status'])}" ) await tg_send(BACKUP_CHANNEL_ID, header) json_str = json.dumps(payload, indent=2, ensure_ascii=False, default=str) filename = f"lookup_{mobile}_{int(time.time())}.json" await tg_send_doc(BACKUP_CHANNEL_ID, filename, json_str, caption=f"Mobile {mobile} — full JSON") # ============================================================ # STEP 9: UPDATE PROCESSOR (main bot logic) # ============================================================ async def process_update(update: Dict[str, Any]) -> None: msg = update.get("message") or {} user = msg.get("from") or {} chat = msg.get("chat") or {} uid = user.get("id") uname = user.get("username") cid = chat.get("id") text = (msg.get("text") or "").strip() if not uid or not cid or not text: return # ---- Authorization ---- if OWNER_IDS and uid not in OWNER_IDS: await tg_send(cid, "⛔ Not authorized.\n\nSend /id to get your Telegram user ID.") return # ---- Commands ---- if text.startswith("/start"): await tg_send(cid, "👋 Welcome!\n\n" "Send a 10-digit Indian mobile number to look up info.\n\n" f"Your Telegram ID: {uid}") return if text.startswith("/help"): await tg_send(cid, "Send a 10-digit mobile number (e.g. 9876543210).\n\n" "/id — get your Telegram user ID\n" "/help — this help") return if text.startswith("/id"): await tg_send(cid, f"Your Telegram ID: {uid}") return # ---- Validate 10-digit mobile ---- digits = "".join(c for c in text if c.isdigit()) if len(digits) != 10: await tg_send(cid, "❌ Invalid input.\n\nPlease send a 10-digit mobile number.") return # ---- Rate limit ---- now = time.time() with _rate_lock: last = _rate.get(uid, 0.0) if now - last < RATE_LIMIT_SEC: wait = int(RATE_LIMIT_SEC - (now - last)) await tg_send(cid, f"⏳ Please wait {wait}s before the next query.") return _rate[uid] = now # ---- Cache ---- with _cache_lock: cached = _cache.get(digits) if cached and now - cached[0] < CACHE_TTL: await tg_send(cid, cached[1]) return # ---- Send "Searching…" ---- status = await tg_send(cid, f"🔍 Searching… for {digits}") status_id = (status or {}).get("result", {}).get("message_id") try: # 1. Resolve aadhaar (blocking call → thread) aadhaar_res = await asyncio.to_thread(find_aadhaar_by_mobile, digits) # 2. Fetch all ASURPAPA APIs api_results = await fetch_asurpapa_all(digits, aadhaar_res.get("aadhaar")) # 3. Format user message user_text = format_user_message(digits, aadhaar_res, api_results) # 4. Send / edit if status_id: await tg_edit(cid, status_id, user_text) else: await tg_send(cid, user_text) # 5. Cache with _cache_lock: _cache[digits] = (time.time(), user_text) # 6. Backup channel await forward_to_backup(uid, uname, digits, aadhaar_res, api_results) except Exception as e: print(f"[process_update] {e}\n{traceback.format_exc()}") err = f"⚠️ Error: {esc(str(e))[:200]}" if status_id: await tg_edit(cid, status_id, err) else: await tg_send(cid, err) # ============================================================ # STEP 10: FASTAPI ROUTE HANDLERS # ============================================================ async def webhook_handler(request: Request): # Path secret if request.path_params.get("secret") != WEBHOOK_SECRET: return JSONResponse({"ok": False, "reason": "bad_path_secret"}, status_code=403) # Telegram secret header if request.headers.get("x-telegram-bot-api-secret-token") != SECRET_TOKEN: return JSONResponse({"ok": False, "reason": "bad_header"}, status_code=403) try: data = await request.json() except Exception: return JSONResponse({"ok": True}) # swallow malformed to prevent retries # Fire-and-forget — return 200 immediately so Telegram doesn't retry try: task = asyncio.create_task(process_update(data)) _bg_tasks.add(task) task.add_done_callback(_bg_tasks.discard) except RuntimeError: # No running loop — extreme edge case threading.Thread( target=lambda: asyncio.run(process_update(data)), daemon=True, ).start() return JSONResponse({"ok": True}) async def health_handler(request: Request): return JSONResponse({ "status": "ok", "time": time.time(), "version": BOT_VERSION, }) # ============================================================ # STEP 11: GRADIO UI (hidden GPU init button for ZeroGPU scanner) # ============================================================ def _build_gradio() -> gr.Blocks: with gr.Blocks(title="Telegram Lookup Bot") as demo: gr.Markdown("# 🤖 Telegram PII Lookup Bot") gr.Markdown( "This Space runs a **Telegram bot**. Open Telegram and send a " "**10-digit mobile number** to the bot.\n\n" "- `/health` — health check\n" "- `/webhook/` — Telegram webhook" ) if _HAS_SPACES: @spaces.GPU(duration=10) def _zerogpu_register(): return "gpu-ready" _btn = gr.Button("init-gpu", visible=False) _btn.click(fn=_zerogpu_register, inputs=None, outputs=None) return demo # ============================================================ # STEP 12: WEBHOOK REGISTRATION (background thread) # ============================================================ def _set_webhook(): if not BOT_TOKEN: print("[webhook] BOT_TOKEN missing — skipped") return if not SPACE_HOST: print("[webhook] SPACE_HOST missing — skipped") return url = f"https://{SPACE_HOST}/webhook/{WEBHOOK_SECRET}" try: with httpx.Client(timeout=30) as cli: r = cli.post( f"https://api.telegram.org/bot{BOT_TOKEN}/setWebhook", json={ "url": url, "secret_token": SECRET_TOKEN, "allowed_updates": ["message"], "drop_pending_updates": True, }, ) res = r.json() print(f"[webhook] set -> {res}") except Exception as e: print(f"[webhook] error: {e}") # ============================================================ # STEP 13: BOOT # ============================================================ print("[boot] initialising DuckDB…") _init_duckdb() print("[boot] building Gradio app…") demo = _build_gradio() print("[boot] launching Gradio (ssr_mode=False, prevent_thread_lock=True)…") demo.launch( server_name="0.0.0.0", server_port=7860, share=False, ssr_mode=False, # disables Node SSR proxy so /webhook is reachable prevent_thread_lock=True, # returns live app immediately ) print("[boot] injecting /webhook and /health routes at index 0…") live_app = demo.app # NOT demo.server.app live_app.router.routes.insert( 0, StarletteRoute("/webhook/{secret}", webhook_handler, methods=["POST"]) ) live_app.router.routes.insert( 0, StarletteRoute("/health", health_handler, methods=["GET"]) ) live_app.build_middleware_stack() print("[boot] starting background tasks…") threading.Thread(target=_warm_cache, daemon=True, name="warm").start() threading.Thread(target=_set_webhook, daemon=True, name="setwh").start() print("[boot] ready — blocking main thread") demo.block_thread()