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 
 
 
 
 
1
+ # ══════════════════════════════════════════════════════════════════
2
+ # CRITICAL SHIM β€” MUST BE THE FIRST EXECUTABLE CODE IN THIS FILE
3
+ # ══════════════════════════════════════════════════════════════════
4
+ import huggingface_hub
5
+
6
+ if not hasattr(huggingface_hub, "HfFolder"):
7
+ class _HfFolder:
8
+ @staticmethod
9
+ def get_token():
10
+ try: return huggingface_hub.get_token()
11
+ except Exception: return None
12
+ @staticmethod
13
+ def save_token(token):
14
+ try: huggingface_hub.login(token)
15
+ except Exception: pass
16
+ @staticmethod
17
+ def delete_token():
18
+ try: huggingface_hub.logout()
19
+ except Exception: pass
20
+ huggingface_hub.HfFolder = _HfFolder
21
+
22
+ # ── Now safe to import everything else ────────────────────────────
23
+ import os
24
+ import asyncio
25
+ import html
26
+ import time
27
+ import uuid
28
+ import threading
29
+ from typing import Optional
30
+
31
+ import duckdb
32
+ import httpx
33
+ import gradio as gr
34
+ from fastapi import Request, HTTPException
35
+
36
+ # ─────────────────────────────────────────────
37
+ # CONFIG
38
+ # ─────────────────────────────────────────────
39
+ BOT_TOKEN = os.environ.get("BOT_TOKEN", "").strip()
40
+ HF_TOKEN = os.environ.get("HF_TOKEN", "").strip()
41
+ WEBHOOK_SECRET = os.environ.get("WEBHOOK_SECRET", "1221").strip()
42
+ SPACE_URL = os.environ.get("SPACE_URL", "").strip().rstrip("/")
43
+ TELEGRAM_PROXY = os.environ.get("TELEGRAM_PROXY", "").strip().rstrip("/")
44
+
45
+ if TELEGRAM_PROXY:
46
+ TELEGRAM_API = f"{TELEGRAM_PROXY}/bot{BOT_TOKEN}"
47
+ print(f"πŸ”€ Using Telegram proxy: {TELEGRAM_PROXY}", flush=True)
48
+ else:
49
+ TELEGRAM_API = f"https://api.telegram.org/bot{BOT_TOKEN}"
50
+
51
+ # Startup sanity check
52
+ print(f"πŸ”‘ BOT_TOKEN set: {bool(BOT_TOKEN)}", flush=True)
53
+ print(f"πŸ”‘ SPACE_URL: {SPACE_URL or '(missing!)'}", flush=True)
54
+ print(f"πŸ”‘ WEBHOOK_SECRET set: {bool(WEBHOOK_SECRET)}", flush=True)
55
+
56
+ DATASET = "Kzr0xx/Icmr-and-hitek"
57
+ PARQUET_URLS = [
58
+ f"https://huggingface.co/datasets/{DATASET}/resolve/main/part1.parquet",
59
+ f"https://huggingface.co/datasets/{DATASET}/resolve/main/part2a.parquet",
60
+ f"https://huggingface.co/datasets/{DATASET}/resolve/main/part2b_new.parquet",
61
+ ]
62
+
63
+ PAGE_SIZE = 4
64
+ FETCH_LIMIT = 40
65
+ QUERY_TIMEOUT = 300
66
+ USER_COOLDOWN = 8
67
+ CACHE_TTL = 3600
68
+
69
+ ALLOWED_FIELDS = {
70
+ "name", "fathersName", "phoneNumber", "aadharNumber", "otherNumber",
71
+ "address", "district", "pincode", "state", "town", "source",
72
+ }
73
+ NUMERIC_FIELDS = {"phoneNumber", "aadharNumber", "otherNumber"}
74
+
75
+ TRUNC = {
76
+ "name": 80, "fathersName": 80, "address": 200,
77
+ "phoneNumber": 40, "aadharNumber": 40, "otherNumber": 40,
78
+ "district": 40, "pincode": 15, "state": 40, "town": 40, "source": 30,
79
+ }
80
+
81
+ # ─────────────────────────────────────────────
82
+ # DUCKDB
83
+ # ─────────────────────────────────────────────
84
+ _con = None
85
+ _con_lock = threading.Lock()
86
+ _con_ready = threading.Event()
87
+
88
+ def get_con() -> duckdb.DuckDBPyConnection:
89
+ global _con
90
+ with _con_lock:
91
+ if _con is not None:
92
+ return _con
93
+ print("πŸ”§ Initializing DuckDB...", flush=True)
94
+ c = duckdb.connect(":memory:")
95
+ c.execute("INSTALL httpfs; LOAD httpfs;")
96
+ if HF_TOKEN:
97
+ c.execute(f"CREATE SECRET hf (TYPE HUGGINGFACE, TOKEN '{HF_TOKEN}');")
98
+ c.execute("SET enable_object_cache=true;")
99
+ c.execute("SET preserve_insertion_order=false;")
100
+ c.execute("SET threads=4;")
101
+ c.execute("SET memory_limit='10GB';")
102
+ urls = ", ".join(f"'{u}'" for u in PARQUET_URLS)
103
+ try:
104
+ c.execute(f"SELECT COUNT(*) FROM read_parquet([{urls}], union_by_name=true) WHERE 1=0")
105
+ print("βœ… DuckDB ready", flush=True)
106
+ except Exception as e:
107
+ print(f"⚠️ Warm-up warning: {e}", flush=True)
108
+ _con = c
109
+ _con_ready.set()
110
+ return _con
111
+
112
+ def run_search(field: str, value: str, limit: int) -> list[dict]:
113
+ if field not in ALLOWED_FIELDS:
114
+ raise ValueError(f"Field not allowed: {field}")
115
+ con = get_con()
116
+ urls = ", ".join(f"'{u}'" for u in PARQUET_URLS)
117
+ if field in NUMERIC_FIELDS:
118
+ where, param = f"CAST({field} AS VARCHAR) = ?", value
119
+ else:
120
+ where, param = f"{field} ILIKE ?", f"%{value}%"
121
+ sql = f"""
122
+ SELECT name, fathersName, phoneNumber, aadharNumber, otherNumber,
123
+ address, district, pincode, state, town, source
124
+ FROM read_parquet([{urls}], union_by_name=true)
125
+ WHERE {where}
126
+ LIMIT {int(limit)}
127
+ """
128
+ cur = con.execute(sql, [param])
129
+ cols = [d[0] for d in cur.description]
130
+ return [dict(zip(cols, r)) for r in cur.fetchall()]
131
+
132
+ # ─────────────────────────────────────────────
133
+ # INPUT DETECTION & FORMATTING
134
+ # ─────────────────────────────────────────────
135
+ def detect_field(text: str) -> tuple[str, str]:
136
+ t = text.strip()
137
+ if t.isdigit() and len(t) == 10:
138
+ return "phoneNumber", t
139
+ if t.isdigit() and len(t) == 12:
140
+ return "aadharNumber", t
141
+ if t.isdigit() and len(t) >= 6:
142
+ return "phoneNumber", t
143
+ has_alpha = any(c.isalpha() for c in t)
144
+ has_digit = any(c.isdigit() for c in t)
145
+ if has_alpha and has_digit and len(t) >= 15:
146
+ return "address", t
147
+ if len(t) >= 40:
148
+ return "address", t
149
+ return "name", t
150
+
151
+ def _tv(v, n: int) -> str:
152
+ if v is None:
153
+ return ""
154
+ s = str(v).strip()
155
+ if s.lower() in ("", "null", "none", "nan"):
156
+ return ""
157
+ return s if len(s) <= n else s[: n - 1] + "…"
158
+
159
+ def format_result(idx: int, row: dict) -> str:
160
+ lines = [f"<b>── #{idx} ──</b>"]
161
+ order = ["name", "fathersName", "phoneNumber", "aadharNumber", "otherNumber",
162
+ "address", "district", "pincode", "state", "town", "source"]
163
+ for k in order:
164
+ v = _tv(row.get(k), TRUNC.get(k, 60))
165
+ if v:
166
+ lines.append(f"<b>{k}:</b> <code>{html.escape(v)}</code>")
167
+ return "\n".join(lines)
168
+
169
+ def render_page(results, page, total_pages, query, elapsed):
170
+ start = page * PAGE_SIZE
171
+ chunk = results[start:start + PAGE_SIZE]
172
+ head = (
173
+ f"πŸ” <b>Query:</b> <code>{html.escape(query)}</code>\n"
174
+ f"πŸ“„ <b>Page {page+1}/{total_pages}</b> Β· "
175
+ f"{len(results)} result(s) · ⏱️ {elapsed:.1f}s\n"
176
+ )
177
+ body = "\n\n".join(format_result(start + i + 1, r) for i, r in enumerate(chunk))
178
+ return f"{head}\n{body}"
179
+
180
+ def page_keyboard(search_id, page, total_pages):
181
+ nav = []
182
+ if page > 0:
183
+ nav.append({"text": "β—€ Prev", "callback_data": f"p:{search_id}:{page-1}"})
184
+ nav.append({"text": f"{page+1} / {total_pages}", "callback_data": "noop"})
185
+ if page < total_pages - 1:
186
+ nav.append({"text": "Next β–Ά", "callback_data": f"p:{search_id}:{page+1}"})
187
+ return {"inline_keyboard": [nav]}
188
+
189
+ # ─────────────────────────────────────────────
190
+ # TELEGRAM API
191
+ # ─────────────────────────────────────────────
192
+ async def tg(method: str, payload: dict, timeout: float = 30) -> dict:
193
+ try:
194
+ async with httpx.AsyncClient(timeout=timeout) as client:
195
+ r = await client.post(f"{TELEGRAM_API}/{method}", json=payload)
196
+ return r.json()
197
+ except Exception as e:
198
+ print(f"❌ tg({method}) error: {e!r}", flush=True)
199
+ return {"ok": False, "error": str(e)}
200
+
201
+ async def send(chat_id, text, **kw):
202
+ res = await tg("sendMessage", {"chat_id": chat_id, "text": text, **kw})
203
+ if res.get("ok"):
204
+ return res["result"]["message_id"]
205
+ print(f"⚠️ sendMessage failed: {res}", flush=True)
206
+ return None
207
+
208
+ async def edit(chat_id, message_id, text, **kw):
209
+ res = await tg("editMessageText",
210
+ {"chat_id": chat_id, "message_id": message_id, "text": text, **kw})
211
+ if not res.get("ok") and "message is not modified" not in str(res):
212
+ print(f"⚠️ editMessageText failed: {res}", flush=True)
213
+
214
+ # ─────────────────────────────────────────────
215
+ # STATE
216
+ # ─────────────────────────────────────────────
217
+ SEARCH_CACHE: dict[str, dict] = {}
218
+ USER_LAST: dict[int, float] = {}
219
+
220
+ def cache_gc():
221
+ while True:
222
+ time.sleep(300)
223
+ now = time.time()
224
+ dead = [k for k, v in SEARCH_CACHE.items() if now - v["ts"] > CACHE_TTL]
225
+ for k in dead:
226
+ SEARCH_CACHE.pop(k, None)
227
+
228
+ # ─────────────────────────────────────────────
229
+ # HANDLERS
230
+ # ─────────────────────────────────────────────
231
+ WELCOME = (
232
+ "πŸ‘‹ <b>Phone Lookup Bot</b>\n\n"
233
+ "Send me any of:\n"
234
+ "β€’ 10-digit phone number\n"
235
+ "β€’ 12-digit Aadhaar number\n"
236
+ "β€’ A person's name\n"
237
+ "β€’ An address\n\n"
238
+ "I'll search the database and return matches with pagination."
239
+ )
240
+
241
+ async def handle_message(msg: dict):
242
+ chat_id = msg["chat"]["id"]
243
+ text = (msg.get("text") or "").strip()
244
+ print(f"πŸ’¬ Message from {chat_id}: {text[:50]!r}", flush=True)
245
+ if not text:
246
+ return
247
+ if text in ("/start", "/help"):
248
+ await send(chat_id, WELCOME)
249
+ return
250
+ now = time.time()
251
+ if now - USER_LAST.get(chat_id, 0) < USER_COOLDOWN:
252
+ wait = USER_COOLDOWN - (now - USER_LAST.get(chat_id, 0))
253
+ await send(chat_id, f"⏳ Slow down β€” wait {wait:.0f}s before next search.")
254
+ return
255
+ USER_LAST[chat_id] = now
256
+ field, value = detect_field(text)
257
+ print(f"πŸ” Detected field={field} value={value[:50]!r}", flush=True)
258
+ if len(value) < 3:
259
+ await send(chat_id, "❌ Query too short (min 3 chars).")
260
+ return
261
+ placeholder = await send(
262
+ chat_id,
263
+ f"πŸ” <b>Searching…</b>\nField: <code>{field}</code>\n"
264
+ f"Value: <code>{html.escape(value[:100])}</code>\n\n"
265
+ f"<i>Cold-cache queries can take 30–120s.</i>",
266
+ )
267
+ if placeholder is None:
268
+ return
269
+ loop = asyncio.get_running_loop()
270
+ t0 = time.time()
271
+ try:
272
+ results = await asyncio.wait_for(
273
+ loop.run_in_executor(None, run_search, field, value, FETCH_LIMIT),
274
+ timeout=QUERY_TIMEOUT,
275
+ )
276
+ except asyncio.TimeoutError:
277
+ await edit(chat_id, placeholder, "⏱️ Search timed out.")
278
+ return
279
+ except Exception as e:
280
+ print(f"❌ search error: {e!r}", flush=True)
281
+ await edit(chat_id, placeholder,
282
+ f"❌ Error: <code>{html.escape(str(e)[:200])}</code>")
283
+ return
284
+ elapsed = time.time() - t0
285
+ print(f"βœ… Search returned {len(results)} rows in {elapsed:.1f}s", flush=True)
286
+ if not results:
287
+ await edit(chat_id, placeholder,
288
+ f"❌ <b>No results</b>\nField: <code>{field}</code>\n"
289
+ f"Value: <code>{html.escape(value[:100])}</code>\n⏱️ {elapsed:.1f}s")
290
+ return
291
+ search_id = uuid.uuid4().hex[:10]
292
+ total_pages = (len(results) + PAGE_SIZE - 1) // PAGE_SIZE
293
+ SEARCH_CACHE[search_id] = {
294
+ "ts": time.time(), "results": results,
295
+ "query": value, "elapsed": elapsed,
296
+ }
297
+ await edit(
298
+ chat_id, placeholder,
299
+ render_page(results, 0, total_pages, value, elapsed),
300
+ parse_mode="HTML",
301
+ reply_markup=page_keyboard(search_id, 0, total_pages),
302
+ )
303
+
304
+ async def handle_callback(cb: dict):
305
+ data = cb.get("data", "")
306
+ cb_id = cb["id"]
307
+ msg = cb.get("message") or {}
308
+ chat_id = msg.get("chat", {}).get("id")
309
+ message_id = msg.get("message_id")
310
+ print(f"πŸ”˜ Callback: {data!r} from {chat_id}", flush=True)
311
+ if not chat_id or not message_id:
312
+ await tg("answerCallbackQuery", {"callback_query_id": cb_id})
313
+ return
314
+ if data == "noop" or not data.startswith("p:"):
315
+ await tg("answerCallbackQuery", {"callback_query_id": cb_id})
316
+ return
317
+ try:
318
+ _, search_id, page_str = data.split(":")
319
+ page = int(page_str)
320
+ except Exception:
321
+ await tg("answerCallbackQuery", {"callback_query_id": cb_id})
322
+ return
323
+ entry = SEARCH_CACHE.get(search_id)
324
+ if not entry:
325
+ await tg("answerCallbackQuery", {
326
+ "callback_query_id": cb_id,
327
+ "text": "Session expired β€” search again.",
328
+ "show_alert": True,
329
+ })
330
+ return
331
+ results = entry["results"]
332
+ total_pages = (len(results) + PAGE_SIZE - 1) // PAGE_SIZE
333
+ page = max(0, min(page, total_pages - 1))
334
+ await edit(
335
+ chat_id, message_id,
336
+ render_page(results, page, total_pages, entry["query"], entry["elapsed"]),
337
+ parse_mode="HTML",
338
+ reply_markup=page_keyboard(search_id, page, total_pages),
339
+ )
340
+ await tg("answerCallbackQuery", {"callback_query_id": cb_id})
341
+
342
+ # ─────────────────────────────────────────────
343
+ # WEBHOOK REGISTRATION
344
+ # ─────────────────────────────────────────────
345
+ async def set_webhook():
346
+ if not SPACE_URL:
347
+ print("⚠️ SPACE_URL not set β€” skipping setWebhook", flush=True)
348
+ return
349
+ url = f"{SPACE_URL}/webhook"
350
+ payload = {
351
+ "url": url,
352
+ "secret_token": WEBHOOK_SECRET,
353
+ "drop_pending_updates": True,
354
+ "allowed_updates": ["message", "callback_query"],
355
+ }
356
+ for attempt in range(1, 4):
357
+ try:
358
+ async with httpx.AsyncClient(timeout=30) as client:
359
+ r = await client.post(f"{TELEGRAM_API}/setWebhook", json=payload)
360
+ data = r.json()
361
+ print(f"πŸ”— setWebhook β†’ {data}", flush=True)
362
+ if data.get("ok"):
363
+ return
364
+ except Exception as e:
365
+ print(f"⚠️ setWebhook attempt {attempt}: {e}", flush=True)
366
+ await asyncio.sleep(3)
367
+
368
+ # ─────────────────────────────────────────────
369
+ # GRADIO UI + ZEROGPU REGISTRATION
370
+ # ─────────────────────────────────────────────
371
+ with gr.Blocks(title="Phone Lookup Bot") as demo:
372
+ gr.Markdown("# πŸ“ž Phone Lookup Bot")
373
+ gr.Markdown(
374
+ "This Space hosts a Telegram bot that searches the "
375
+ "`Kzr0xx/Icmr-and-hitek` dataset (104 GB, streamed live).\n\n"
376
+ "**Open Telegram and message the bot to search.**"
377
+ )
378
+ gr.Markdown("### Status")
379
+ status_box = gr.JSON(label="Health")
380
+ demo.load(
381
+ fn=lambda: {
382
+ "status": "ok",
383
+ "duckdb_ready": _con_ready.is_set(),
384
+ "cached_searches": len(SEARCH_CACHE),
385
+ },
386
+ outputs=status_box,
387
+ )
388
+
389
+ # ZeroGPU registration
390
+ try:
391
+ import spaces
392
+
393
+ @spaces.GPU(duration=10)
394
+ def _zerogpu_register():
395
+ return "gpu-ready"
396
+
397
+ _zerogpu_btn = gr.Button("init-gpu", visible=False)
398
+ _zerogpu_btn.click(fn=_zerogpu_register, inputs=None, outputs=None)
399
+ print("βœ… @spaces.GPU function registered", flush=True)
400
+ except Exception as e:
401
+ print(f"⚠️ Could not register @spaces.GPU: {e}", flush=True)
402
+
403
+ # ─────────────────────────────────────────────
404
+ # CUSTOM ROUTES ON GRADIO'S FASTAPI APP
405
+ # ─────────────────────────────────────────────
406
+ app = demo.app
407
+
408
+
409
+ @app.get("/health")
410
+ async def health():
411
+ return {
412
+ "status": "ok",
413
+ "duckdb_ready": _con_ready.is_set(),
414
+ "cached_searches": len(SEARCH_CACHE),
415
+ "telegram_proxy": bool(TELEGRAM_PROXY),
416
+ "bot_token_set": bool(BOT_TOKEN),
417
+ }
418
+
419
+
420
+ @app.post("/webhook")
421
+ async def webhook(request: Request):
422
+ print(f"πŸ“© /webhook hit from {request.client}", flush=True)
423
+
424
+ if WEBHOOK_SECRET:
425
+ got = request.headers.get("x-telegram-bot-api-secret-token", "")
426
+ if got != WEBHOOK_SECRET:
427
+ print(f"❌ Bad secret: got={got!r} expected={WEBHOOK_SECRET!r}", flush=True)
428
+ raise HTTPException(status_code=403, detail="forbidden")
429
+
430
+ try:
431
+ update = await request.json()
432
+ except Exception as e:
433
+ print(f"⚠️ JSON parse error: {e}", flush=True)
434
+ return {"ok": True}
435
+
436
+ kind = next((k for k in ("message", "callback_query", "edited_message") if k in update), None)
437
+ print(f"πŸ“¨ Update type: {kind}", flush=True)
438
+
439
+ if "message" in update:
440
+ asyncio.create_task(handle_message(update["message"]))
441
+ elif "callback_query" in update:
442
+ asyncio.create_task(handle_callback(update["callback_query"]))
443
+ return {"ok": True}
444
+
445
+ # ─────────────────────────────────────────────
446
+ # BACKGROUND THREADS + LAUNCH
447
+ # ─────────────────────────────────────────────
448
+ threading.Thread(target=cache_gc, daemon=True).start()
449
+ threading.Thread(target=get_con, daemon=True).start()
450
+
451
+ def _register_webhook_later():
452
+ loop = asyncio.new_event_loop()
453
+ asyncio.set_event_loop(loop)
454
+ loop.run_until_complete(set_webhook())
455
+
456
+ threading.Thread(target=_register_webhook_later, daemon=True).start()
457
+
458
+ # πŸ”₯ CRITICAL: ssr_mode=False disables the Node SSR proxy.
459
+ # Without this, external POSTs to /webhook hit the Node proxy on
460
+ # port 7860 and never reach Python's FastAPI routes.
461
+ demo.launch(
462
+ server_name="0.0.0.0",
463
+ server_port=7860,
464
+ share=False,
465
+ ssr_mode=False,
466
+ )