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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ══════════════════════════════════════════════════════════════════
2
+ # app.py — Entry point (v2.0.1 — defensive boot)
3
+ #
4
+ # Fixes vs v2.0.0:
5
+ # • _verify_bot_module() — fails fast with clear message if bot.py
6
+ # is truncated or any required attribute is missing
7
+ # • _safe_start() — one failing daemon thread no longer kills boot
8
+ # • All thread starts guarded
9
+ # • Route injection also guarded per-route
10
+ # • Boot never aborts silently — logs exactly what's missing
11
+ #
12
+ # Responsibility:
13
+ # • HfFolder monkey-patch (MUST be line 1, before any gradio import)
14
+ # • Imports gradio + sub-modules (config → engine → bot → admin_panel)
15
+ # • Gradio UI (health JSON + hidden ZeroGPU registration button)
16
+ # • demo.launch(ssr_mode=False, prevent_thread_lock=True)
17
+ # • Route injection at index 0:
18
+ # POST /webhook ← Telegram webhook
19
+ # GET /health ← liveness probe
20
+ # /admin/* ← web panel (only if ADMIN_TOKEN set)
21
+ # • Startup threads (all wrapped):
22
+ # get_con, warm_phone_cache, get_asur_con, warm_asur_cache
23
+ # cache_gc, set_webhook, api_health_poller
24
+ # • demo.block_thread() ← keeps process alive
25
+ # ══════════════════════════════════════════════════════════════════
26
+
27
+ # ══════════════════════════════════════════════════════════════════
28
+ # STEP 0: MONKEY-PATCH HfFolder BEFORE ANY GRADIO/HF IMPORT
29
+ # ══════════════════════════════════════════════════════════════════
30
+ import huggingface_hub
31
+
32
+ if not hasattr(huggingface_hub, "HfFolder"):
33
+ class _HfFolder:
34
+ @staticmethod
35
+ def get_token():
36
+ try:
37
+ return huggingface_hub.get_token()
38
+ except Exception:
39
+ return None
40
+
41
+ @staticmethod
42
+ def save_token(token):
43
+ try:
44
+ huggingface_hub.login(token)
45
+ except Exception:
46
+ pass
47
+
48
+ @staticmethod
49
+ def delete_token():
50
+ try:
51
+ huggingface_hub.logout()
52
+ except Exception:
53
+ pass
54
+
55
+ huggingface_hub.HfFolder = _HfFolder
56
+
57
+ # ══════════════════════════════════════════════════════════════════
58
+ # STEP 1: STANDARD LIB
59
+ # ══════════════════════════════════════════════════════════════════
60
+ import asyncio
61
+ import logging
62
+ import threading
63
+ import time
64
+ import traceback
65
+
66
+ # ══════════════════════════════════════════════════════════════════
67
+ # STEP 2: THIRD-PARTY
68
+ # ══════════════════════════════════════════════════════════════════
69
+ import gradio as gr
70
+ from fastapi import Request
71
+ from fastapi.responses import JSONResponse
72
+ from starlette.routing import Route as StarletteRoute
73
+
74
+ # ZeroGPU optional — HF Spaces provide it, local dev doesn't
75
+ try:
76
+ import spaces
77
+ _HAS_SPACES = True
78
+ except ImportError:
79
+ _HAS_SPACES = False
80
+ class spaces:
81
+ @staticmethod
82
+ def GPU(*_a, **_kw):
83
+ def deco(f):
84
+ return f
85
+ return deco
86
+
87
+ # ══════════════════════════════════════════════════════════════════
88
+ # STEP 3: PROJECT MODULES (order matters)
89
+ # ══════════════════════════════════════════════════════════════════
90
+ import config
91
+ import engine
92
+ import bot
93
+ import admin_panel
94
+
95
+ # ══════════════════════════════════════════════════════════════════
96
+ # STEP 4: LOGGING
97
+ # ══════════════════════════════════════════════════════════════════
98
+ logging.basicConfig(
99
+ level=logging.INFO,
100
+ format="%(asctime)s %(levelname)-7s [%(name)s] %(message)s",
101
+ datefmt="%H:%M:%S",
102
+ )
103
+ log = logging.getLogger("app")
104
+
105
+ # ══════════════════════════════════════════════════════════════════
106
+ # STEP 5: ROUTE HANDLERS (webhook + health)
107
+ # ══════════════════════════════════════════════════════════════════
108
+ async def webhook_handler(request: Request):
109
+ """Telegram webhook. Returns 200 immediately; dispatches work in tasks."""
110
+ # ── Header secret check ──
111
+ if config.SECRET_TOKEN:
112
+ got = request.headers.get("x-telegram-bot-api-secret-token", "")
113
+ if got != config.SECRET_TOKEN:
114
+ log.warning(f"[webhook] bad secret header: {got[:8]}…")
115
+ return JSONResponse({"ok": False, "reason": "bad_header"}, status_code=403)
116
+
117
+ try:
118
+ update = await request.json()
119
+ except Exception:
120
+ return JSONResponse({"ok": True})
121
+
122
+ # ── Dedup by update_id ──
123
+ update_id = update.get("update_id")
124
+ if bot.is_duplicate_update(update_id):
125
+ log.debug(f"[webhook] duplicate update_id={update_id}")
126
+ return JSONResponse({"ok": True})
127
+
128
+ # ── Dispatch ──
129
+ try:
130
+ if "message" in update:
131
+ asyncio.create_task(bot.handle_message(update["message"]))
132
+ elif "callback_query" in update:
133
+ asyncio.create_task(bot.handle_callback(update["callback_query"]))
134
+ except RuntimeError:
135
+ threading.Thread(
136
+ target=lambda: asyncio.run(_dispatch_sync(update)),
137
+ daemon=True,
138
+ ).start()
139
+
140
+ return JSONResponse({"ok": True})
141
+
142
+
143
+ async def _dispatch_sync(update: dict):
144
+ """Fallback if create_task fails."""
145
+ try:
146
+ if "message" in update:
147
+ await bot.handle_message(update["message"])
148
+ elif "callback_query" in update:
149
+ await bot.handle_callback(update["callback_query"])
150
+ except Exception as e:
151
+ log.error(f"[webhook] dispatch: {e!r}\n{traceback.format_exc()}")
152
+
153
+
154
+ async def health_handler(request: Request):
155
+ """Liveness probe — cheap, no API calls."""
156
+ return JSONResponse({
157
+ "status": "ok",
158
+ "version": config.VERSION,
159
+ "time": time.time(),
160
+ "duckdb_ready": engine.con_ready.is_set(),
161
+ "warmed": engine.warmed.is_set(),
162
+ "files": len(config.ALL_PARQUET_URLS),
163
+ "hiteck_files": len(config.PARQUET_URLS),
164
+ "flipkart_files": len(config.FLIPKART_URLS),
165
+ "cached_searches": len(bot.SEARCH_CACHE),
166
+ "unique_users": len(bot.UNIQUE_USERS),
167
+ "live_users": bot._get_stats()["live_users"],
168
+ "maintenance": bot.MAINTENANCE_MODE,
169
+ "force_join": bool(config.FORCE_JOIN_CHANNEL),
170
+ "backup_enabled": bot.BACKUP_ENABLED,
171
+ "admin_panel": bool(config.ADMIN_TOKEN),
172
+ "apis": {
173
+ "cr850": config.API_850CR,
174
+ "inddata": config.API_INDDATA,
175
+ "asur": list(config.ASUR_API.values()),
176
+ },
177
+ "stats": bot.STATS,
178
+ })
179
+
180
+
181
+ # ══════════════════════════════════════════════════════════════════
182
+ # STEP 6: GRADIO UI
183
+ # ══════════════════════════════════════════════════════════════════
184
+ def _build_gradio() -> gr.Blocks:
185
+ with gr.Blocks(title=f"{config.BOT_NAME} v{config.VERSION}") as demo:
186
+ gr.Markdown(f"# 🤖 {config.BOT_NAME} v{config.VERSION}")
187
+ gr.Markdown(
188
+ "This Space runs a **Telegram bot**.\n\n"
189
+ "**Endpoints**\n"
190
+ "- `GET /health` — liveness\n"
191
+ "- `POST /webhook` — Telegram webhook\n"
192
+ + ("- `GET /admin` — web admin panel\n" if config.ADMIN_TOKEN else "")
193
+ )
194
+
195
+ status_box = gr.JSON(label="Health")
196
+ refresh_btn = gr.Button("🔄 Refresh health", variant="secondary")
197
+
198
+ def _health_snapshot():
199
+ try:
200
+ s = bot._get_stats()
201
+ return {
202
+ "status": "ok",
203
+ "version": config.VERSION,
204
+ "duckdb_ready": engine.con_ready.is_set(),
205
+ "warmed": engine.warmed.is_set(),
206
+ "files": len(config.ALL_PARQUET_URLS),
207
+ "cached_searches": len(bot.SEARCH_CACHE),
208
+ "unique_users": s["unique_users"],
209
+ "live_users": s["live_users"],
210
+ "backup_enabled": bot.BACKUP_ENABLED,
211
+ "maintenance": s["maintenance"],
212
+ }
213
+ except Exception as e:
214
+ return {"error": str(e)}
215
+
216
+ refresh_btn.click(fn=_health_snapshot, inputs=None, outputs=status_box)
217
+ demo.load(fn=_health_snapshot, inputs=None, outputs=status_box)
218
+
219
+ # Hidden ZeroGPU registration button
220
+ if _HAS_SPACES:
221
+ try:
222
+ @spaces.GPU(duration=10)
223
+ def _zerogpu_register():
224
+ return "gpu-ready"
225
+
226
+ _zgpu_btn = gr.Button("init-gpu", visible=False)
227
+ _zgpu_btn.click(fn=_zerogpu_register, inputs=None, outputs=None)
228
+ log.info("✅ ZeroGPU registered")
229
+ except Exception as e:
230
+ log.warning(f"⚠️ ZeroGPU registration failed: {e!r}")
231
+
232
+ return demo
233
+
234
+
235
+ # ══════════════════════════════════════════════════════════════════
236
+ # STEP 7: WEBHOOK REGISTRATION (background thread, async impl)
237
+ # ══════════════════════════════════════════════════════════════════
238
+ async def _set_webhook_async_impl():
239
+ if not config.BOT_TOKEN:
240
+ log.warning("[setwebhook] BOT_TOKEN missing — skipped")
241
+ return
242
+ space_url = config.SPACE_URL or (f"https://{config.SPACE_HOST}" if config.SPACE_HOST else "")
243
+ if not space_url:
244
+ log.warning("[setwebhook] SPACE_URL/SPACE_HOST missing — skipped")
245
+ return
246
+
247
+ url = f"{space_url.rstrip('/')}/webhook"
248
+ payload = {
249
+ "url": url,
250
+ "secret_token": config.SECRET_TOKEN,
251
+ "allowed_updates": ["message", "callback_query"],
252
+ "drop_pending_updates": True,
253
+ }
254
+ import httpx
255
+ for attempt in range(1, 4):
256
+ try:
257
+ async with httpx.AsyncClient(timeout=30) as cli:
258
+ r = await cli.post(f"{config.TELEGRAM_API}/setWebhook", json=payload)
259
+ data = r.json()
260
+ log.info(f"[setwebhook] attempt {attempt}: {data}")
261
+ if data.get("ok"):
262
+ return
263
+ except Exception as e:
264
+ log.warning(f"[setwebhook] attempt {attempt}: {e!r}")
265
+ await asyncio.sleep(3)
266
+ log.error("[setwebhook] gave up after 3 attempts")
267
+
268
+
269
+ def _set_webhook_async():
270
+ try:
271
+ loop = asyncio.new_event_loop()
272
+ asyncio.set_event_loop(loop)
273
+ loop.run_until_complete(_set_webhook_async_impl())
274
+ except Exception as e:
275
+ log.warning(f"[setwebhook] fatal: {e!r}")
276
+
277
+
278
+ # ══════════════════════════════════════════════════════════════════
279
+ # STEP 8: API HEALTH POLLER
280
+ # ══════════════════════════════════════════════════════════════════
281
+ def _api_health_poller():
282
+ try:
283
+ loop = asyncio.new_event_loop()
284
+ asyncio.set_event_loop(loop)
285
+
286
+ async def _loop_forever():
287
+ await asyncio.sleep(30) # initial delay
288
+ while True:
289
+ try:
290
+ await engine.check_api_health()
291
+ log.debug("[health-poller] tick ok")
292
+ except Exception as e:
293
+ log.warning(f"[health-poller] {e!r}")
294
+ await asyncio.sleep(config.API_HEALTH_INTERVAL)
295
+
296
+ loop.run_until_complete(_loop_forever())
297
+ except Exception as e:
298
+ log.warning(f"[health-poller] fatal: {e!r}")
299
+
300
+
301
+ # ══════════════════════════════════════════════════════════════════
302
+ # STEP 9: BOOT — defensive
303
+ # ══════════════════════════════════════════════════════════════════
304
+
305
+ # Every attribute app.py (and admin_panel.py, indirectly) needs from bot.
306
+ # If any is missing → module is truncated and boot must abort with a clear message.
307
+ _BOT_REQUIRED_ATTRS = [
308
+ # handlers
309
+ "handle_message", "handle_callback", "is_duplicate_update",
310
+ # threads
311
+ "cache_gc",
312
+ # stats / state (read by health_handler + admin_panel)
313
+ "_get_stats", "_get_live_users",
314
+ "SEARCH_CACHE", "UNIQUE_USERS", "ACTIVE_USERS", "STATS",
315
+ "ACTIVITY_LOG", "BANNED_USERS", "BAN_REASONS",
316
+ "MAINTENANCE_MODE", "BACKUP_ENABLED",
317
+ # mutators (used by admin_panel)
318
+ "_ban_user", "_unban_user",
319
+ "_set_maintenance", "_get_maintenance",
320
+ "_revoke_admin", "_is_admin_session",
321
+ # internal locks referenced by admin_panel
322
+ "_activity_lock", "_state_lock",
323
+ ]
324
+
325
+
326
+ def _verify_bot_module() -> bool:
327
+ """Return True if bot.py exports everything app.py + admin_panel need."""
328
+ missing = [n for n in _BOT_REQUIRED_ATTRS if not hasattr(bot, n)]
329
+ if missing:
330
+ log.error("╔══════════════════════════════════════════════════════════╗")
331
+ log.error("║ ❌ bot module is INCOMPLETE — missing attributes: ║")
332
+ log.error("╚══════════════════════════════════════════════════════════╝")
333
+ for m in missing:
334
+ log.error(f" • bot.{m}")
335
+ log.error("")
336
+ log.error(" Likely cause: bot.py was truncated during save.")
337
+ log.error(" Expected: ~950 lines, ending with:")
338
+ log.error(' if __name__ == "__main__":')
339
+ log.error(" ...")
340
+ log.error("")
341
+ log.error(" Fix: re-save bot.py in full, then restart the Space.")
342
+ return False
343
+ log.info(f"✅ bot module OK ({len(_BOT_REQUIRED_ATTRS)} attributes present)")
344
+ return True
345
+
346
+
347
+ def _safe_start(name: str, target, *args):
348
+ """Start a daemon thread — never raise."""
349
+ if target is None:
350
+ log.error(f"⚠️ thread '{name}': target is None — NOT started")
351
+ return
352
+ if not callable(target):
353
+ log.error(f"⚠️ thread '{name}': target is not callable — NOT started")
354
+ return
355
+ try:
356
+ threading.Thread(target=target, args=args, daemon=True, name=name).start()
357
+ log.info(f"✅ thread started: {name}")
358
+ except Exception as e:
359
+ log.error(f"❌ thread '{name}' failed: {e!r}")
360
+
361
+
362
+ def _safe_inject(live_app, route, description: str):
363
+ """Insert a route at index 0 — never raise."""
364
+ try:
365
+ live_app.router.routes.insert(0, route)
366
+ return True
367
+ except Exception as e:
368
+ log.error(f"❌ route inject failed ({description}): {e!r}")
369
+ return False
370
+
371
+
372
+ def _boot():
373
+ # ── 9.0 Verify bot module FIRST ──
374
+ if not _verify_bot_module():
375
+ log.critical("❌ Aborting boot — fix bot.py and restart the Space.")
376
+ time.sleep(5)
377
+ raise RuntimeError("bot module incomplete — see log for missing attributes")
378
+
379
+ # ── 9.1 Sanity + config dump ──
380
+ print()
381
+ print(config.summary())
382
+ warnings = config._sanity_check()
383
+ if warnings:
384
+ print("\n⚠️ Config warnings:")
385
+ for w in warnings:
386
+ print(f" • {w}")
387
+ print()
388
+
389
+ # ── 9.2 Build Gradio ──
390
+ log.info("[boot] building Gradio app…")
391
+ demo = _build_gradio()
392
+
393
+ # ── 9.3 Launch Gradio ──
394
+ log.info("[boot] launching Gradio (ssr_mode=False, prevent_thread_lock=True)…")
395
+ demo.launch(
396
+ server_name="0.0.0.0",
397
+ server_port=7860,
398
+ share=False,
399
+ ssr_mode=False,
400
+ prevent_thread_lock=True,
401
+ show_error=True,
402
+ )
403
+
404
+ # ── 9.4 Inject routes ──
405
+ log.info("[boot] injecting /webhook, /health, /admin/* at index 0…")
406
+ live_app = demo.app
407
+
408
+ _safe_inject(
409
+ live_app,
410
+ StarletteRoute("/webhook", webhook_handler, methods=["POST"]),
411
+ "POST /webhook",
412
+ )
413
+ _safe_inject(
414
+ live_app,
415
+ StarletteRoute("/health", health_handler, methods=["GET"]),
416
+ "GET /health",
417
+ )
418
+
419
+ # ── 9.5 Admin panel ──
420
+ admin_route_count = 0
421
+ try:
422
+ admin_routes = admin_panel.get_admin_routes()
423
+ for route in admin_routes:
424
+ if _safe_inject(live_app, route, getattr(route, "path", "?")):
425
+ admin_route_count += 1
426
+ if admin_route_count:
427
+ log.info(f"✅ injected {admin_route_count} admin routes at /admin/*")
428
+ else:
429
+ log.info("ℹ️ admin routes not injected (ADMIN_TOKEN unset)")
430
+ except Exception as e:
431
+ log.warning(f"⚠️ admin_panel injection failed: {e!r}\n{traceback.format_exc()}")
432
+
433
+ # ── 9.6 Rebuild middleware ──
434
+ try:
435
+ live_app.build_middleware_stack()
436
+ log.info("✅ middleware stack rebuilt")
437
+ except Exception as e:
438
+ log.warning(f"⚠️ middleware stack rebuild: {e!r}")
439
+
440
+ # ── 9.7 Log routes ──
441
+ log.info("📋 First 10 routes:")
442
+ for route in live_app.router.routes[:10]:
443
+ path = getattr(route, "path", "?")
444
+ methods = getattr(route, "methods", None)
445
+ ms = f"{sorted(methods)}" if methods else "?"
446
+ log.info(f" {ms:30s} {path}")
447
+
448
+ # ── 9.8 Warm-up threads (engine) ──
449
+ log.info("[boot] starting warm-up threads…")
450
+ _safe_start("con", getattr(engine, "get_con", None))
451
+ _safe_start("warm", getattr(engine, "warm_phone_cache", None))
452
+ _safe_start("asur-con", getattr(engine, "get_asur_con", None))
453
+ _safe_start("asur-warm", getattr(engine, "warm_asur_cache", None))
454
+
455
+ # ── 9.9 Background daemons ──
456
+ log.info("[boot] starting background daemons…")
457
+ _safe_start("gc", bot.cache_gc)
458
+ _safe_start("setwh", _set_webhook_async)
459
+ _safe_start("health", _api_health_poller)
460
+
461
+ # ── 9.10 Ready ──
462
+ log.info("[boot] ✅ ready — blocking main thread")
463
+ print()
464
+ print("═" * 60)
465
+ print(f" {config.BOT_NAME} v{config.VERSION} — ONLINE")
466
+ print(f" Webhook : {config.SPACE_URL or config.SPACE_HOST or '(local)'}/webhook")
467
+ print(f" Health : /health")
468
+ print(f" Admin : {'/admin' if config.ADMIN_TOKEN else '(disabled — ADMIN_TOKEN unset)'}")
469
+ print("═" * 60)
470
+ print()
471
+
472
+ return demo
473
+
474
+
475
+ # ══════════════════════════════════════════════════════════════════
476
+ # STEP 10: MAIN
477
+ # ══════════════════════════════════════════════════════════════════
478
+ if __name__ == "__main__":
479
+ try:
480
+ demo = _boot()
481
+ demo.block_thread()
482
+ except KeyboardInterrupt:
483
+ log.info("shutting down…")
484
+ except Exception as e:
485
+ log.critical(f"❌ boot failed: {e!r}\n{traceback.format_exc()}")
486
+ raise