File size: 26,785 Bytes
834a7eb | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 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 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 | # ============================================================
# 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"🔎 <b>Lookup complete</b> for <code>{esc(mobile)}</code>")
lines.append("")
# --- Aadhaar resolution status ---
aad = aadhaar_res.get("aadhaar")
if aad:
masked = "XXXX-XXXX-" + aad[-4:]
lines.append(f"🪪 <b>Aadhaar:</b> <code>{masked}</code> "
f"<i>(via {esc(aadhaar_res.get('source'))})</i>")
else:
lines.append("🪪 <b>Aadhaar:</b> <i>not found in datasets — "
"aadhaar APIs skipped</i>")
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("📱 <b>Mobile Info</b>")
if d.get("name"): lines.append(f"👤 <b>Name:</b> {esc(d['name'])}")
if d.get("fname"): lines.append(f"👨 <b>Father:</b> {esc(d['fname'])}")
if d.get("circle"): lines.append(f"🌐 <b>Circle:</b> {esc(d['circle'])}")
if d.get("email"): lines.append(f"📧 <b>Email:</b> {esc(d['email'])}")
if d.get("alt"): lines.append(f"📞 <b>Alt:</b> {esc(d['alt'])}")
if d.get("address"):lines.append(f"🏠 <b>Address:</b> {esc(d['address'])}")
lines.append("")
elif nti.get("error"):
lines.append(f"📱 <b>Mobile Info:</b> ⚠️ {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"🪪 <b>Aadhaar Linked Records:</b> {cnt}")
for rec in recs[:3]:
lines.append(f" • {esc(rec.get('name'))} — "
f"📞 {esc(rec.get('phoneNumber'))}")
if cnt > 3:
lines.append(f" <i>… and {cnt - 3} more (see attached JSON)</i>")
lines.append("")
# --- Family ---
fam = api_results.get("aadhaar_family", {}) or {}
if fam.get("status") is True:
members = fam.get("members") or []
lines.append(f"👨👩👧 <b>Family ({len(members)} members)</b>")
for m in members[:10]:
lines.append(f" • {esc(m.get('name'))} ({esc(m.get('relation'))})")
if len(members) > 10:
lines.append(f" <i>… and {len(members) - 10} more (see attached JSON)</i>")
lines.append("")
# --- Ration ---
rat = api_results.get("aadhaar_ration", {}) or {}
if rat.get("status") is True:
lines.append("🍚 <b>Ration Card</b>")
if rat.get("head_family"): lines.append(f"👤 Head: {esc(rat['head_family'])}")
if rat.get("ration_number"): lines.append(f"🔢 Number: <code>{esc(rat['ration_number'])}</code>")
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: <code>{esc(rat['fps_id'])}</code>")
lines.append("")
lines.append("📎 <i>Full JSON forwarded to backup channel.</i>")
text = "\n".join(lines)
if len(text) > 4000:
text = text[:3985] + "\n<i>… (truncated)</i>"
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"📥 <b>New lookup</b>\n"
f"👤 User: <code>{user_id}</code>"
f"{' (@' + esc(username) + ')' if username else ''}\n"
f"📱 Mobile: <code>{esc(mobile)}</code>\n"
f"🪪 Aadhaar: "
f"{'<code>' + esc(aadhaar_res.get('aadhaar')) + '</code>' if aadhaar_res.get('aadhaar') else 'not found'}\n"
f"📊 Status: <b>{esc(payload['status'])}</b>"
)
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, "⛔ <b>Not authorized.</b>\n\nSend /id to get your Telegram user ID.")
return
# ---- Commands ----
if text.startswith("/start"):
await tg_send(cid,
"👋 <b>Welcome!</b>\n\n"
"Send a <b>10-digit Indian mobile number</b> to look up info.\n\n"
f"Your Telegram ID: <code>{uid}</code>")
return
if text.startswith("/help"):
await tg_send(cid,
"Send a 10-digit mobile number (e.g. <code>9876543210</code>).\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: <code>{uid}</code>")
return
# ---- Validate 10-digit mobile ----
digits = "".join(c for c in text if c.isdigit())
if len(digits) != 10:
await tg_send(cid, "❌ <b>Invalid input.</b>\n\nPlease send a <b>10-digit mobile number</b>.")
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"🔍 <b>Searching…</b> for <code>{digits}</code>")
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"⚠️ <b>Error:</b> <code>{esc(str(e))[:200]}</code>"
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/<secret>` — 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() |