Hfzune commited on
Commit
afcb32d
Β·
verified Β·
1 Parent(s): 01745b2

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +767 -0
app.py ADDED
@@ -0,0 +1,767 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ─────────────────────────────────────────────────────────────
2
+ # 0. HfFolder shim (must be first executable code)
3
+ # ─────────────────────────────────────────────────────────────
4
+ import huggingface_hub
5
+ if not hasattr(huggingface_hub, "HfFolder"):
6
+ class _HfFolder:
7
+ @staticmethod
8
+ def get_token(): return huggingface_hub.get_token()
9
+ @staticmethod
10
+ def save_token(token): huggingface_hub.login(token)
11
+ @staticmethod
12
+ def delete_token(): huggingface_hub.logout()
13
+ huggingface_hub.HfFolder = _HfFolder
14
+
15
+ # ─────────────────────────────────────────────────────────────
16
+ # 1. Imports
17
+ # ─────────────────────────────────────────────────────────────
18
+ import os
19
+ import re
20
+ import time
21
+ import html
22
+ import asyncio
23
+ import logging
24
+ import threading
25
+ from typing import Optional
26
+
27
+ import httpx
28
+ from fastapi import Request
29
+ from fastapi.responses import JSONResponse
30
+ from starlette.routing import Route as StarletteRoute
31
+ import gradio as gr
32
+ import spaces
33
+
34
+ # ─────────────────────────────────────────────────────────────
35
+ # 2. Config
36
+ # ─────────────────────────────────────────────────────────────
37
+ BOT_TOKEN = os.environ["BOT_TOKEN"]
38
+ WEBHOOK_SECRET = os.environ.get("WEBHOOK_SECRET", "1221")
39
+ SPACE_URL = os.environ["SPACE_URL"].rstrip("/")
40
+ TELEGRAM_PROXY = os.environ.get("TELEGRAM_PROXY", "").rstrip("/")
41
+
42
+ ADMIN_IDS = [int(x) for x in os.environ.get("ADMIN_IDS", "").split(",") if x.strip().isdigit()]
43
+ AUTH_ENABLED = len(ADMIN_IDS) > 0
44
+
45
+ TG_API = (TELEGRAM_PROXY + "/bot" + BOT_TOKEN) if TELEGRAM_PROXY \
46
+ else f"https://api.telegram.org/bot{BOT_TOKEN}"
47
+
48
+ RATE_LIMIT_SEC = 5
49
+ PAGE_SIZE = 4
50
+ QUERY_TIMEOUT = 90
51
+ HTTP_TIMEOUT = httpx.Timeout(60.0, connect=15.0)
52
+ CACHE_TTL = 300
53
+ ADMIN_STATE_TTL = 180
54
+ TELEGRAM_MAX_MSG = 4000
55
+
56
+ logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
57
+ log = logging.getLogger("bot")
58
+
59
+ # ─────────────────────────────────────────────────────────────
60
+ # 3. HTTP clients (one AsyncClient per running event loop)
61
+ # ─────────────────────────────────────────────────────────────
62
+ _api_clients: dict[int, httpx.AsyncClient] = {}
63
+ _clients_lock = threading.Lock()
64
+
65
+
66
+ async def _get_api_client() -> httpx.AsyncClient:
67
+ loop = asyncio.get_running_loop()
68
+ key = id(loop)
69
+ client = _api_clients.get(key)
70
+ if client is None or client.is_closed:
71
+ client = httpx.AsyncClient(timeout=HTTP_TIMEOUT, follow_redirects=True)
72
+ with _clients_lock:
73
+ _api_clients[key] = client
74
+ return client
75
+
76
+
77
+ # ─────────────────────────────────────────────────────────────
78
+ # 4. Result cache (5-min TTL)
79
+ # ─────────────────────────────────────────────────────────────
80
+ _cache: dict[str, tuple[float, list]] = {}
81
+ _cache_lock = threading.Lock()
82
+
83
+
84
+ def _cache_get(number: str) -> Optional[list]:
85
+ with _cache_lock:
86
+ entry = _cache.get(number)
87
+ if entry is None:
88
+ return None
89
+ ts, data = entry
90
+ if time.time() - ts > CACHE_TTL:
91
+ _cache.pop(number, None)
92
+ return None
93
+ return data
94
+
95
+
96
+ def _cache_set(number: str, data: list):
97
+ with _cache_lock:
98
+ _cache[number] = (time.time(), data)
99
+ if len(_cache) > 500:
100
+ now = time.time()
101
+ for k in list(_cache.keys()):
102
+ if now - _cache[k][0] > CACHE_TTL:
103
+ _cache.pop(k, None)
104
+
105
+
106
+ # ─────────────────────────────────────────────────────────────
107
+ # 5. External data sources (only the two working ones)
108
+ # ─────────────────────────────────────────────────────────────
109
+ def _clean(v):
110
+ if v is None:
111
+ return None
112
+ s = str(v).strip()
113
+ if s in ("", "null", "N/A", "None", "-"):
114
+ return None
115
+ return s
116
+
117
+
118
+ async def _q_cr850(client, number):
119
+ """850CR Fast β€” GET /search/{number}"""
120
+ url = f"https://sauravsingh2111-850crfastsearch.hf.space/search/{number}"
121
+ try:
122
+ r = await client.get(url, timeout=40.0)
123
+ if r.status_code != 200:
124
+ log.info("cr850 β†’ %s", r.status_code)
125
+ return []
126
+ data = r.json()
127
+ if not data.get("success") or not data.get("results"):
128
+ return []
129
+ out = []
130
+ for item in data["results"]:
131
+ addr = item.get("address") or {}
132
+ full = None
133
+ if isinstance(addr, dict):
134
+ full = addr.get("full_address")
135
+ if full:
136
+ full = full.lstrip(", ").strip()
137
+ out.append({
138
+ "source": "850CR Fast",
139
+ "fields": {
140
+ "Name": _clean(item.get("name")),
141
+ "Father": _clean(item.get("father_name")),
142
+ "Address": _clean(full),
143
+ "Alternate": _clean(item.get("alternate_number")),
144
+ "Circle": _clean(item.get("circle")),
145
+ "Operator": _clean(item.get("operator")),
146
+ "State": _clean(item.get("state")),
147
+ "Email": _clean(item.get("email")),
148
+ },
149
+ })
150
+ return out
151
+ except Exception as e:
152
+ log.warning("cr850 failed: %s", e)
153
+ return []
154
+
155
+
156
+ async def _q_inddata(client, number):
157
+ """IndData 1.4B β€” GET /search?mobile={number}"""
158
+ url = "https://tfqdeadlo-inddataapi.hf.space/search"
159
+ try:
160
+ r = await client.get(url, params={"mobile": number}, timeout=30.0)
161
+ if r.status_code != 200:
162
+ log.info("inddata β†’ %s", r.status_code)
163
+ return []
164
+ data = r.json()
165
+ rows = data.get("data") if isinstance(data, dict) else None
166
+ if not isinstance(rows, list):
167
+ return []
168
+ out = []
169
+ for item in rows:
170
+ out.append({
171
+ "source": "IndData 1.4B",
172
+ "fields": {
173
+ "Mobile": _clean(item.get("mobile")),
174
+ "Name": _clean(item.get("name")),
175
+ "Father": _clean(item.get("fname")),
176
+ "Address": _clean(item.get("address")),
177
+ "Email": _clean(item.get("email")),
178
+ "ID": _clean(item.get("id")),
179
+ },
180
+ })
181
+ return out
182
+ except Exception as e:
183
+ log.warning("inddata failed: %s", e)
184
+ return []
185
+
186
+
187
+ # ─────────────────────────────────────────────────────────────
188
+ # 5b. Per-API safety wrapper
189
+ # ─────────────────────────────────────────────────────────────
190
+ async def _safe(fn, client, number, timeout: float, label: str) -> list[dict]:
191
+ t0 = time.time()
192
+ try:
193
+ res = await asyncio.wait_for(fn(client, number), timeout=timeout)
194
+ log.info("%s β†’ %d records in %.2fs", label, len(res), time.time() - t0)
195
+ return res
196
+ except asyncio.TimeoutError:
197
+ log.warning("%s β†’ TIMEOUT after %.1fs", label, timeout)
198
+ return []
199
+ except Exception as e:
200
+ log.warning("%s β†’ ERROR after %.2fs: %s", label, time.time() - t0, e)
201
+ return []
202
+
203
+
204
+ # ─────────────────────────────────────────────────────────────
205
+ # 5c. De-duplication
206
+ # ─────────────────────────────────────────────────────────────
207
+ def _norm(s) -> str:
208
+ if not s:
209
+ return ""
210
+ return re.sub(r"\s+", " ", str(s).strip().lower())
211
+
212
+
213
+ def _dedup_key(rec: dict):
214
+ f = rec.get("fields", {})
215
+ name = _norm(f.get("Name"))
216
+ father = _norm(f.get("Father"))
217
+ addr = _norm(f.get("Address"))
218
+ addr_n = re.sub(r"[^a-z0-9]+", " ", addr).strip()
219
+
220
+ if name and addr_n:
221
+ return ("na", name, addr_n)
222
+ if name and father:
223
+ return ("nf", name, father)
224
+ if addr_n:
225
+ return ("a", addr_n)
226
+ return None
227
+
228
+
229
+ def _dedup(records: list[dict]) -> list[dict]:
230
+ seen: dict = {}
231
+ result: list[dict] = []
232
+ for rec in records:
233
+ key = _dedup_key(rec)
234
+ if key is None:
235
+ result.append(rec)
236
+ continue
237
+ idx = seen.get(key)
238
+ if idx is None:
239
+ seen[key] = len(result)
240
+ result.append(rec)
241
+ else:
242
+ existing = result[idx]
243
+ if len(rec.get("fields", {})) > len(existing.get("fields", {})):
244
+ result[idx] = rec
245
+ return result
246
+
247
+
248
+ # ─────────────────────────────────────────────────────────────
249
+ # 5d. Search (cached)
250
+ # ─────────────────────────────────────────────────────────────
251
+ async def search_phone(number: str) -> list[dict]:
252
+ cached = _cache_get(number)
253
+ if cached is not None:
254
+ log.info("Cache HIT for %s (%d records)", number, len(cached))
255
+ return cached
256
+
257
+ client = await _get_api_client()
258
+ t0 = time.time()
259
+
260
+ chunks = await asyncio.gather(
261
+ _safe(_q_cr850, client, number, 40, "850CR"),
262
+ _safe(_q_inddata, client, number, 30, "IndData"),
263
+ )
264
+
265
+ merged: list[dict] = []
266
+ for chunk in chunks:
267
+ merged.extend(chunk)
268
+
269
+ before = len(merged)
270
+ deduped = _dedup(merged)
271
+ log.info("Search %s: %d raw β†’ %d unique in %.2fs",
272
+ number, before, len(deduped), time.time() - t0)
273
+
274
+ _cache_set(number, deduped)
275
+ return deduped
276
+
277
+
278
+ # ─────────────────────────────────────────────────────────────
279
+ # 6. Telegram API helpers
280
+ # ─────────────────────────────────────────────────────────────
281
+ async def tg(method: str, **payload):
282
+ client = await _get_api_client()
283
+ url = f"{TG_API}/{method}"
284
+ r = await client.post(url, json=payload)
285
+ if r.status_code >= 400:
286
+ log.warning("Telegram %s failed: %s %s", method, r.status_code, r.text[:200])
287
+ try:
288
+ return r.json()
289
+ except Exception:
290
+ return {}
291
+
292
+
293
+ async def send(chat_id: int, text: str, **kw):
294
+ kw.setdefault("parse_mode", "HTML")
295
+ kw.setdefault("disable_web_page_preview", True)
296
+ try:
297
+ if len(text) <= TELEGRAM_MAX_MSG:
298
+ return await tg("sendMessage", chat_id=chat_id, text=text, **kw)
299
+ chunks = _split_message(text, TELEGRAM_MAX_MSG)
300
+ result = None
301
+ for i, chunk in enumerate(chunks):
302
+ kw_chunk = dict(kw)
303
+ if i < len(chunks) - 1:
304
+ kw_chunk.pop("reply_markup", None)
305
+ result = await tg("sendMessage", chat_id=chat_id, text=chunk, **kw_chunk)
306
+ return result
307
+ except Exception:
308
+ log.exception("send failed")
309
+ return {}
310
+
311
+
312
+ async def edit(chat_id: int, message_id: int, text: str, **kw):
313
+ kw.setdefault("parse_mode", "HTML")
314
+ kw.setdefault("disable_web_page_preview", True)
315
+ if len(text) > TELEGRAM_MAX_MSG:
316
+ try:
317
+ await tg("deleteMessage", chat_id=chat_id, message_id=message_id)
318
+ except Exception:
319
+ pass
320
+ return await send(chat_id, text, **kw)
321
+ try:
322
+ return await tg("editMessageText", chat_id=chat_id, message_id=message_id, text=text, **kw)
323
+ except Exception:
324
+ log.exception("edit failed")
325
+ return {}
326
+
327
+
328
+ async def answer_callback(callback_id: str, **kw):
329
+ try:
330
+ return await tg("answerCallbackQuery", callback_query_id=callback_id, **kw)
331
+ except Exception:
332
+ log.exception("answer_callback failed")
333
+ return {}
334
+
335
+
336
+ def _split_message(text: str, limit: int) -> list[str]:
337
+ parts = text.split("\n\n")
338
+ chunks: list[str] = []
339
+ cur = ""
340
+ for p in parts:
341
+ candidate = (cur + "\n\n" + p) if cur else p
342
+ if len(candidate) <= limit:
343
+ cur = candidate
344
+ else:
345
+ if cur:
346
+ chunks.append(cur)
347
+ while len(p) > limit:
348
+ chunks.append(p[:limit])
349
+ p = p[limit:]
350
+ cur = p
351
+ if cur:
352
+ chunks.append(cur)
353
+ return chunks
354
+
355
+
356
+ # ─────────────────────────────────────────────────────────────
357
+ # 7. Formatting
358
+ # ─────────────────────────────────────────────────────────────
359
+ def _esc(v) -> str:
360
+ if v is None:
361
+ return ""
362
+ return html.escape(str(v))
363
+
364
+
365
+ def render_record(rec: dict) -> str:
366
+ src = _esc(rec.get("source", "Unknown"))
367
+ fields = rec.get("fields", {})
368
+ lines = [f"πŸ—‚ <b>{src}</b>"]
369
+ for k, v in fields.items():
370
+ if v is None or v == "":
371
+ continue
372
+ val = str(v)
373
+ if len(val) > 300:
374
+ val = val[:297] + "..."
375
+ lines.append(f"β€’ <b>{_esc(k)}:</b> {_esc(val)}")
376
+ if len(lines) == 1:
377
+ lines.append("β€’ <i>no data</i>")
378
+ return "\n".join(lines)
379
+
380
+
381
+ def render_page(number: str, records: list[dict], page: int) -> str:
382
+ total = len(records)
383
+ start = page * PAGE_SIZE
384
+ chunk = records[start:start + PAGE_SIZE]
385
+ if not chunk:
386
+ return "No more results."
387
+ pages = (total - 1) // PAGE_SIZE + 1
388
+ header = (
389
+ f"πŸ”Ž <b>Results for</b> <code>{_esc(number)}</code> β€” "
390
+ f"page {page + 1}/{pages} ({total} record{'s' if total != 1 else ''})\n\n"
391
+ )
392
+ body = "\n\n━━━━━━━━━━━━━━━━━━\n\n".join(render_record(r) for r in chunk)
393
+ return header + body
394
+
395
+
396
+ def pagination_kb(number: str, page: int, total: int):
397
+ nav = []
398
+ if page > 0:
399
+ nav.append({"text": "β—€ Prev", "callback_data": f"pg|{number}|{page - 1}"})
400
+ if (page + 1) * PAGE_SIZE < total:
401
+ nav.append({"text": "Next β–Ά", "callback_data": f"pg|{number}|{page + 1}"})
402
+ return {"inline_keyboard": [nav]} if nav else None
403
+
404
+
405
+ # ─────────────────────────────────────────────────────────────
406
+ # 8. Per-user state
407
+ # ─────────────────────────────────────────────────────────────
408
+ _last_search: dict[int, float] = {}
409
+ _search_lock = threading.Lock()
410
+
411
+ _admin_states: dict[int, tuple[str, float]] = {}
412
+ _authorized_users: set[int] = set()
413
+ _custom_apis: list[str] = []
414
+ _admin_lock = threading.Lock()
415
+
416
+
417
+ def _admin_state_get(user_id: int) -> Optional[str]:
418
+ with _admin_lock:
419
+ entry = _admin_states.get(user_id)
420
+ if entry is None:
421
+ return None
422
+ state, set_at = entry
423
+ if time.time() - set_at > ADMIN_STATE_TTL:
424
+ _admin_states.pop(user_id, None)
425
+ return None
426
+ return state
427
+
428
+
429
+ def _admin_state_set(user_id: int, state: str):
430
+ with _admin_lock:
431
+ _admin_states[user_id] = (state, time.time())
432
+
433
+
434
+ def _admin_state_clear(user_id: int):
435
+ with _admin_lock:
436
+ _admin_states.pop(user_id, None)
437
+
438
+
439
+ # ─────────────────────────────────────────────────────────────
440
+ # 9. Admin helpers
441
+ # ─────────────────────────────────────────────────────────────
442
+ def _is_admin(user_id: int) -> bool:
443
+ return user_id in ADMIN_IDS
444
+
445
+
446
+ def _is_authorized(user_id: int) -> bool:
447
+ if not AUTH_ENABLED:
448
+ return True
449
+ with _admin_lock:
450
+ return user_id in _authorized_users or _is_admin(user_id)
451
+
452
+
453
+ def _admin_menu_kb():
454
+ return {
455
+ "inline_keyboard": [
456
+ [{"text": "βž• Add User", "callback_data": "admin|add_user"}],
457
+ [{"text": "βž– Remove User", "callback_data": "admin|remove_user"}],
458
+ [{"text": "πŸ“‹ List Users", "callback_data": "admin|list_users"}],
459
+ [{"text": "πŸ”Œ Add API", "callback_data": "admin|add_api"}],
460
+ [{"text": "πŸ—‘ Clear APIs", "callback_data": "admin|clear_apis"}],
461
+ [{"text": "πŸ“‹ List APIs", "callback_data": "admin|list_apis"}],
462
+ ]
463
+ }
464
+
465
+
466
+ # ─────────────────────────────────────────────────────────────
467
+ # 10. Message handlers
468
+ # ─────────────────────────────────────────────────────────────
469
+ async def handle_message(update: dict):
470
+ msg = update.get("message") or update.get("edited_message")
471
+ if not msg:
472
+ return
473
+
474
+ chat_id = msg["chat"]["id"]
475
+ sender = msg.get("from") or {}
476
+ user_id = sender.get("id")
477
+ if user_id is None:
478
+ return
479
+
480
+ if "text" not in msg:
481
+ await send(chat_id, "❗ Please send a <b>text message</b> with a 10‑digit number.")
482
+ return
483
+
484
+ text = (msg.get("text") or "").strip()
485
+ log.info("MSG from %s: %r", user_id, text[:100])
486
+
487
+ state = _admin_state_get(user_id)
488
+ if state and _is_admin(user_id):
489
+ if state == "await_user_id":
490
+ if text.isdigit():
491
+ with _admin_lock:
492
+ _authorized_users.add(int(text))
493
+ _admin_state_clear(user_id)
494
+ await send(chat_id, f"βœ… User <code>{text}</code> authorized.")
495
+ else:
496
+ await send(chat_id, "❗ Send a numeric Telegram user ID (or /cancel).")
497
+ return
498
+ if state == "await_api_url":
499
+ if text.startswith("http"):
500
+ with _admin_lock:
501
+ _custom_apis.append(text.rstrip("/"))
502
+ _admin_state_clear(user_id)
503
+ await send(chat_id, f"βœ… API added: <code>{_esc(text)}</code>")
504
+ else:
505
+ await send(chat_id, "❗ Send a valid http(s) URL (or /cancel).")
506
+ return
507
+
508
+ if text.startswith("/"):
509
+ cmd = text.split()[0].lower()
510
+
511
+ if cmd == "/start":
512
+ await send(
513
+ chat_id,
514
+ "πŸ‘‹ <b>Welcome!</b>\n\n"
515
+ "Send me a <b>10‑digit mobile number</b> and I'll search across multiple databases.\n\n"
516
+ "Commands:\n"
517
+ "/start β€” this message\n"
518
+ "/status β€” bot health\n"
519
+ "/myid β€” show your Telegram user ID\n"
520
+ "/cancel β€” cancel current input",
521
+ )
522
+ return
523
+
524
+ if cmd == "/myid":
525
+ await send(chat_id, f"πŸ†” Your Telegram user ID: <code>{user_id}</code>")
526
+ return
527
+
528
+ if cmd == "/cancel":
529
+ _admin_state_clear(user_id)
530
+ await send(chat_id, "βœ… Cancelled.")
531
+ return
532
+
533
+ if cmd == "/status":
534
+ with _cache_lock:
535
+ cache_size = len(_cache)
536
+ await send(
537
+ chat_id,
538
+ "βœ… <b>Bot alive</b>\n"
539
+ f"πŸ—‚ Sources: 2 (dedup ON)\n"
540
+ f"πŸ’Ύ Cache entries: {cache_size}\n"
541
+ f"⏱ Rate limit: {RATE_LIMIT_SEC}s\n"
542
+ f"πŸ“„ Page size: {PAGE_SIZE}",
543
+ )
544
+ return
545
+
546
+ if cmd == "/nemesis":
547
+ if not _is_admin(user_id):
548
+ await send(chat_id, "β›” Unauthorized.")
549
+ return
550
+ await send(chat_id, "πŸ›‘ <b>Admin Panel</b>\nChoose an action:", reply_markup=_admin_menu_kb())
551
+ return
552
+
553
+ return
554
+
555
+ if not _is_authorized(user_id):
556
+ await send(chat_id, "β›” You are not authorized to use this bot.")
557
+ return
558
+
559
+ if not (text.isdigit() and len(text) == 10):
560
+ await send(chat_id, "❗ Please send a <b>10‑digit mobile number</b> only.")
561
+ return
562
+
563
+ now = time.time()
564
+ with _search_lock:
565
+ last = _last_search.get(user_id, 0)
566
+ if now - last < RATE_LIMIT_SEC:
567
+ wait = int(RATE_LIMIT_SEC - (now - last)) + 1
568
+ await send(chat_id, f"⏳ Please wait <b>{wait}s</b> before searching again.")
569
+ return
570
+ _last_search[user_id] = now
571
+ if len(_last_search) > 1000:
572
+ cutoff = now - 3600
573
+ for k in list(_last_search.keys()):
574
+ if _last_search[k] < cutoff:
575
+ _last_search.pop(k, None)
576
+
577
+ await send(chat_id, f"πŸ” <b>Searching</b> <code>{_esc(text)}</code> across 2 databases …")
578
+
579
+ try:
580
+ records = await asyncio.wait_for(search_phone(text), timeout=QUERY_TIMEOUT)
581
+ except asyncio.TimeoutError:
582
+ await send(chat_id, "⏰ Search timed out. Try again in a moment.")
583
+ return
584
+ except Exception:
585
+ log.exception("search_phone unexpected error")
586
+ await send(chat_id, "⚠️ Unexpected error during search.")
587
+ return
588
+
589
+ if not records:
590
+ await send(chat_id, f"❌ No records found for <code>{_esc(text)}</code>.")
591
+ return
592
+
593
+ kb = pagination_kb(text, 0, len(records))
594
+ await send(chat_id, render_page(text, records, 0), reply_markup=kb)
595
+
596
+
597
+ async def handle_callback(update: dict):
598
+ cb = update.get("callback_query")
599
+ if not cb:
600
+ return
601
+ data = cb.get("data") or ""
602
+ chat_id = cb["message"]["chat"]["id"]
603
+ user_id = (cb.get("from") or {}).get("id")
604
+ message_id = cb["message"]["message_id"]
605
+
606
+ await answer_callback(cb["id"])
607
+
608
+ if user_id is None:
609
+ return
610
+
611
+ if data.startswith("admin|"):
612
+ if not _is_admin(user_id):
613
+ await edit(chat_id, message_id, "β›” Unauthorized.")
614
+ return
615
+ action = data.split("|", 1)[1]
616
+
617
+ if action == "add_user":
618
+ _admin_state_set(user_id, "await_user_id")
619
+ await edit(chat_id, message_id, "Send the Telegram user ID to authorize (or /cancel):")
620
+ return
621
+
622
+ if action == "remove_user":
623
+ with _admin_lock:
624
+ users = sorted(_authorized_users)
625
+ if not users:
626
+ await edit(chat_id, message_id, "No authorized users.", reply_markup=_admin_menu_kb())
627
+ else:
628
+ txt = "Authorized users:\n" + "\n".join(f"<code>{u}</code>" for u in users)
629
+ await edit(chat_id, message_id, txt, reply_markup=_admin_menu_kb())
630
+ return
631
+
632
+ if action == "list_users":
633
+ with _admin_lock:
634
+ users = sorted(_authorized_users)
635
+ txt = "Authorized users:\n" + ("\n".join(f"<code>{u}</code>" for u in users) if users else "β€”")
636
+ await edit(chat_id, message_id, txt, reply_markup=_admin_menu_kb())
637
+ return
638
+
639
+ if action == "add_api":
640
+ _admin_state_set(user_id, "await_api_url")
641
+ await edit(chat_id, message_id, "Send the API base URL to add (or /cancel):")
642
+ return
643
+
644
+ if action == "clear_apis":
645
+ with _admin_lock:
646
+ _custom_apis.clear()
647
+ await edit(chat_id, message_id, "βœ… All custom APIs cleared.", reply_markup=_admin_menu_kb())
648
+ return
649
+
650
+ if action == "list_apis":
651
+ with _admin_lock:
652
+ apis = list(_custom_apis)
653
+ txt = "Custom APIs:\n" + ("\n".join(f"<code>{_esc(a)}</code>" for a in apis) if apis else "β€”")
654
+ await edit(chat_id, message_id, txt, reply_markup=_admin_menu_kb())
655
+ return
656
+
657
+ return
658
+
659
+ if not data.startswith("pg|"):
660
+ return
661
+
662
+ try:
663
+ _, number, page_s = data.split("|", 2)
664
+ page = int(page_s)
665
+ except Exception:
666
+ return
667
+
668
+ try:
669
+ records = await asyncio.wait_for(search_phone(number), timeout=QUERY_TIMEOUT)
670
+ except Exception:
671
+ log.exception("callback search failed")
672
+ await edit(chat_id, message_id, "⚠️ Could not load that page. Try again.")
673
+ return
674
+
675
+ if not records:
676
+ await edit(chat_id, message_id, "❌ No records found.")
677
+ return
678
+
679
+ kb = pagination_kb(number, page, len(records))
680
+ await edit(chat_id, message_id, render_page(number, records, page), reply_markup=kb)
681
+
682
+
683
+ # ─────────────────────────────────────────────────────────────
684
+ # 11. FastAPI routes
685
+ # ─────────────────────────────────────────────────────────────
686
+ async def webhook_handler(request: Request):
687
+ if request.headers.get("x-telegram-bot-api-secret-token") != WEBHOOK_SECRET:
688
+ log.warning("Bad webhook secret β€” ignoring")
689
+ return JSONResponse({"ok": True})
690
+
691
+ try:
692
+ update = await request.json()
693
+ except Exception:
694
+ return JSONResponse({"ok": True})
695
+
696
+ try:
697
+ if "message" in update or "edited_message" in update:
698
+ await handle_message(update)
699
+ elif "callback_query" in update:
700
+ await handle_callback(update)
701
+ except Exception:
702
+ log.exception("Handler error")
703
+
704
+ return JSONResponse({"ok": True})
705
+
706
+
707
+ async def health_handler(request: Request):
708
+ with _cache_lock:
709
+ cache_size = len(_cache)
710
+ return JSONResponse({
711
+ "status": "ok",
712
+ "time": time.time(),
713
+ "cache_entries": cache_size,
714
+ })
715
+
716
+
717
+ # ─────────────────────────────────────────────────────────────
718
+ # 12. Gradio UI (ZeroGPU registration)
719
+ # ─────────────────────────────────────────────────────────────
720
+ @spaces.GPU(duration=10)
721
+ def _zerogpu_register():
722
+ return "gpu-ready"
723
+
724
+
725
+ with gr.Blocks(title="Phone Lookup Bot") as demo:
726
+ gr.Markdown("## Phone Lookup Bot\nTelegram webhook endpoint is live.")
727
+ _btn = gr.Button("init-gpu", visible=False)
728
+ _btn.click(fn=_zerogpu_register, inputs=None, outputs=None)
729
+
730
+
731
+ # ─────────────────────────────────────────────────────────────
732
+ # 13. Launch + inject routes
733
+ # ─────────────────────────────────────────────────────────────
734
+ demo.launch(
735
+ server_name="0.0.0.0",
736
+ server_port=7860,
737
+ share=False,
738
+ ssr_mode=False,
739
+ prevent_thread_lock=True,
740
+ )
741
+
742
+ live_app = demo.app
743
+ live_app.router.routes.insert(0, StarletteRoute("/webhook", webhook_handler, methods=["POST"]))
744
+ live_app.router.routes.insert(0, StarletteRoute("/health", health_handler, methods=["GET"]))
745
+ live_app.build_middleware_stack()
746
+
747
+
748
+ # ─────────────────────────────────────────────────────────────
749
+ # 14. setWebhook (sync β€” own thread)
750
+ # ─────────────────────────────────────────────────────────────
751
+ def _set_webhook_sync():
752
+ time.sleep(3)
753
+ try:
754
+ with httpx.Client(timeout=15.0) as c:
755
+ r = c.post(f"{TG_API}/setWebhook", json={
756
+ "url": f"{SPACE_URL}/webhook",
757
+ "secret_token": WEBHOOK_SECRET,
758
+ "allowed_updates": ["message", "edited_message", "callback_query"],
759
+ })
760
+ log.info("setWebhook β†’ %s", r.text)
761
+ except Exception:
762
+ log.exception("setWebhook failed")
763
+
764
+
765
+ threading.Thread(target=_set_webhook_sync, daemon=True).start()
766
+
767
+ demo.block_thread()