Hfzune commited on
Commit
fd26440
·
verified ·
1 Parent(s): df189d8

Update config.py

Browse files
Files changed (1) hide show
  1. config.py +295 -352
config.py CHANGED
@@ -1,162 +1,209 @@
1
- # ═══════════════════════════════════════════════════════════════════════════
2
- # config.py — File 1 of 4
3
- # ─────────────────────────────────────────────────────────────────────────
4
- # MUST be imported FIRST by every other module (before gradio).
5
- # Contains: HfFolder shim, imports, env config, constants, in-memory state,
6
- # pure helpers (no network, no asyncio, no FastAPI).
7
- # ═══════════════════════════════════════════════════════════════════════════
8
-
9
- # ── STEP 0: HfFolder shim — MUST be the first executable code ─────────────
10
- import huggingface_hub
11
-
12
- if not hasattr(huggingface_hub, "HfFolder"):
13
- class _HfFolder:
14
- @staticmethod
15
- def get_token():
16
- try: return huggingface_hub.get_token()
17
- except Exception: return None
18
- @staticmethod
19
- def save_token(token):
20
- try: huggingface_hub.login(token)
21
- except Exception: pass
22
- @staticmethod
23
- def delete_token():
24
- try: huggingface_hub.logout()
25
- except Exception: pass
26
- huggingface_hub.HfFolder = _HfFolder
27
-
28
- # ── Standard library ─────────────────────────────────────────────────────
29
  import os
30
- import io
31
- import csv
32
- import json
33
  import re
34
- import time
35
- import uuid
36
- import hmac
37
- import base64
38
  import hashlib
39
- import asyncio
40
- import threading
41
- import logging
42
- from datetime import datetime, timezone, timedelta
43
- from collections import deque, Counter
44
- from typing import Optional
45
-
46
- log = logging.getLogger("bot")
47
- logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
48
-
49
-
50
- # ═══════════════════════════════════════════════════════════════════════════
51
- # ENVIRONMENT (with aliases — first non-empty wins)
52
- # ═══════════════════════════════════════════════════════════════════════════
53
- def _env(*names, default=""):
54
- """Return first non-empty env var among `names`, else `default`."""
55
- for n in names:
56
- v = os.environ.get(n, "").strip()
57
- if v:
58
- return v
59
- return default
60
-
61
-
62
- TELEGRAM_TOKEN = _env("TELEGRAM_TOKEN", "BOT_TOKEN")
63
- API_KEY = _env("API_KEY", default="@ASUR_ABOUT")
64
- SPACE_HOST = _env("SPACE_HOST")
65
- WEBHOOK_BASE_URL = (
66
- _env("WEBHOOK_BASE_URL", "SPACE_URL")
67
- or (f"https://{SPACE_HOST}" if SPACE_HOST else "")
68
- )
69
- TELEGRAM_PROXY = _env("TELEGRAM_PROXY").rstrip("/")
70
- WEBHOOK_SECRET = _env("WEBHOOK_SECRET")
71
- HF_TOKEN = _env("HF_TOKEN")
72
-
73
- ADMIN_SECRET = _env("ADMIN_SECRET", "ADMIN_TOKEN") or ("change-me-" + os.urandom(8).hex())
74
- VIEWER_SECRET = _env("VIEWER_SECRET")
75
- LOG_CHAT_ID = _env("LOG_CHAT_ID")
76
-
77
- # ── Tuning knobs ─────────────────────────────────────────────────────────
78
- MAX_INMEM_LOG = int(_env("MAX_INMEM_LOG", default="5000"))
79
- LOG_FILE_PATH = _env("LOG_FILE_PATH", default="/tmp/bot_logs.jsonl")
80
- LOG_ROTATE_MB = int(_env("LOG_ROTATE_MB", default="40"))
81
- LOG_KEEP_ROTATED = int(_env("LOG_KEEP_ROTATED", default="3"))
82
- LOG_RETENTION_DAYS = int(_env("LOG_RETENTION_DAYS", default="30"))
83
- PANEL_ALLOWED_IPS = [x.strip() for x in _env("PANEL_ALLOWED_IPS").split(",") if x.strip()]
84
- PANEL_SESSION_TTL_MIN = int(_env("PANEL_SESSION_TTL_MIN", default="60"))
85
- ADMIN_SESSION_TTL_MIN = int(_env("ADMIN_SESSION_TTL_MIN", default="60"))
86
- ADMIN_MAX_FAILS = int(_env("ADMIN_MAX_FAILS", default="3"))
87
-
88
- USER_COOLDOWN = int(_env("USER_COOLDOWN", default="5"))
89
- DOSSIER_COOLDOWN = int(_env("DOSSIER_COOLDOWN", default="30"))
90
- QUERY_TIMEOUT = int(_env("QUERY_TIMEOUT", default="90"))
91
- PAGE_SIZE = int(_env("PAGE_SIZE", default="4"))
92
- FETCH_LIMIT = int(_env("FETCH_LIMIT", default="40"))
93
- BATCH_MAX = int(_env("BATCH_MAX", default="5"))
94
- BATCH_TIMEOUT = int(_env("BATCH_TIMEOUT", default="60"))
95
- HISTORY_LEN = int(_env("HISTORY_LEN", default="10"))
96
- LIVE_WINDOW = int(_env("LIVE_WINDOW", default="300"))
97
- CACHE_TTL = int(_env("CACHE_TTL", default="300"))
98
- BROADCAST_DELAY = 0.05 # seconds between broadcast messages
99
-
100
- VERSION = "2.0.0"
101
-
102
- # ── Derived ──────────────────────────────────────────────────────────────
103
- PANEL_TOKEN = ADMIN_SECRET
104
- SESSION_KEY = hashlib.sha256((ADMIN_SECRET + os.urandom(8).hex()).encode()).hexdigest()
105
- STARTED_AT = datetime.now(timezone.utc)
106
-
107
- TG_API = f"https://api.telegram.org/bot{TELEGRAM_TOKEN}"
108
- TG_API_PROXY = f"{TELEGRAM_PROXY}/bot{TELEGRAM_TOKEN}" if TELEGRAM_PROXY else TG_API
109
-
110
-
111
- # ═══════════════════════════════════════════════════════════════════════════
112
- # CONSTANTS
113
- # ═══════════════════════════════════════════════════════════════════════════
114
- PHONE_REGEX = re.compile(r"^\d{10}$")
115
- AADHAAR_REGEX = re.compile(r"^\d{12}$")
116
 
117
- TRUNC = {
118
- "name": 80, "fathersName": 80, "address": 200,
119
- "phoneNumber": 40, "aadharNumber": 40, "otherNumber": 40,
120
- "district": 40, "pincode": 15, "state": 40, "town": 40, "source": 30,
121
- }
 
 
 
 
 
 
 
 
 
 
122
 
123
- # 4 asurpapa HTTP APIs (menu + /360 sources)
124
- APIS = {
125
- "mobile": {
126
- "url": "https://num-to-info.asurpapa.workers.dev/api",
127
- "param": "number",
128
- "pattern": PHONE_REGEX,
129
- "hint": "Send a 10-digit Indian mobile number.",
130
- },
131
- "aadhaar_info": {
132
- "url": "https://aadhaar.asurpapa.workers.dev/api",
133
- "param": "aadhaar",
134
- "pattern": AADHAAR_REGEX,
135
- "hint": "Send a 12-digit Aadhaar number.",
136
- },
137
- "aadhaar_family": {
138
- "url": "https://aadhaar-family.asurpapa.workers.dev/api",
139
- "param": "aadhaar",
140
- "pattern": AADHAAR_REGEX,
141
- "hint": "Send a 12-digit Aadhaar number.",
142
- },
143
- "aadhaar_ration": {
144
- "url": "https://ration-card.asurpapa.workers.dev/api",
145
- "param": "aadhar", # single-a — upstream typo, must match
146
- "pattern": AADHAAR_REGEX,
147
- "hint": "Send a 12-digit Aadhaar number.",
148
- },
149
  }
150
 
151
- # DuckDB dataset (HiTeck) + 2 HTTP fallbacks (used when DuckDB not warmed)
152
- PARQUET_URLS = [
153
- f"https://huggingface.co/datasets/Hfzune/HiTeckgroop/resolve/main/idx_phone.{i}.parquet"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
154
  for i in range(7)
155
  ]
156
- API_850CR = "https://sauravsingh2111-850crfastsearch.hf.space/search"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
157
  API_INDDATA = "https://tfqdeadlo-inddataapi.hf.space/search"
158
 
159
- # Field labels used by all formatters (bot + panel + /360)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
160
  FIELD_LABELS = [
161
  ("name", "👤", "Name"),
162
  ("fathersName", "👨", "Father"),
@@ -171,208 +218,104 @@ FIELD_LABELS = [
171
  ("source", "📂", "Source"),
172
  ]
173
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
174
 
175
- # ═══════════════════════════════════════════════════════════════════════════
176
- # IN-MEMORY STATE
177
- # ═══════════════════════════════════════════════════════════════════════════
178
-
179
- # ── Users & panel/admin sessions ──
180
- USERS = {} # user_id -> user record (for panel Users tab)
181
- USER_STATE = {} # user_id -> {"awaiting": api_key} (menu selection)
182
- ADMIN_SESSIONS = {} # user_id -> expiry_ts
183
- ADMIN_FAILS = {} # user_id -> [ts, ...] (failed /admin attempts)
184
- ADMIN_AWAITING = set() # user_ids waiting to type admin secret
185
- LOG_DEQUE = deque(maxlen=MAX_INMEM_LOG)
186
- ADMIN_AUDIT = deque(maxlen=1000)
187
-
188
- # ── Activity tracking (app2.py) ──
189
- ACTIVITY_LOG = deque(maxlen=10000)
190
- ACTIVE_USERS = {} # user_id -> last_active_ts
191
- UNIQUE_USERS = {} # user_id -> {username, first_name, last_name, count, first_seen, last_seen}
192
- PHONE_COUNTS = Counter()
193
- PEAK_CONCURRENT = 0
194
-
195
- # ── Moderation & maintenance ──
196
- BANNED_USERS: set = set()
197
- BAN_REASONS: dict = {}
198
- USER_HISTORY: dict = {} # user_id -> deque of {phone, ts, count, elapsed, source}
199
- MAINTENANCE_MODE = False
200
- MAINTENANCE_REASON = ""
201
-
202
- # ── Caches ──
203
- SEARCH_CACHE = {} # search_id -> {ts, results, query, elapsed, source_note, mode}
204
- USER_LAST = {} # user_id -> last search ts (for USER_COOLDOWN)
205
- DOSSIER_LAST = {} # user_id -> last /360 ts (for DOSSIER_COOLDOWN)
206
- STATS = {"queries": 0, "timeouts": 0, "errors": 0, "dossiers": 0,
207
- "started": time.time()}
208
-
209
- # ── Thread locks (shared across modules) ──
210
- _activity_lock = threading.Lock()
211
- _admin_lock = threading.Lock()
212
- _state_lock = threading.Lock()
213
-
214
-
215
- # ═══════════════════════════════════════════════════════════════════════════
216
- # PURE HELPERS (no I/O, no await)
217
- # ═══════════════════════════════════════════════════════════════════════════
218
- def now_iso() -> str:
219
- """UTC ISO timestamp."""
220
- return datetime.now(timezone.utc).isoformat(timespec="seconds")
221
-
222
-
223
- def record_id(ts_iso: str, uid: int, query: str) -> str:
224
- """Deterministic 16-char ID for a log record."""
225
- return hashlib.sha1(f"{ts_iso}|{uid}|{query}".encode()).hexdigest()[:16]
226
-
227
-
228
- def escape_html(s) -> str:
229
- """Escape a value for safe embedding in Telegram HTML / panel HTML."""
230
- if s is None:
231
- return ""
232
- s = str(s)
233
- return (s.replace("&", "&")
234
- .replace("<", "&lt;")
235
- .replace(">", "&gt;")
236
- .replace('"', "&quot;"))
237
-
238
-
239
- def chunk_text(text: str, limit: int = 3800) -> list:
240
- """Split text into chunks ≤ limit, breaking on newlines when possible."""
241
- if len(text) <= limit:
242
- return [text]
243
- chunks, buf = [], ""
244
- for line in text.split("\n"):
245
- if len(buf) + len(line) + 1 > limit and buf:
246
- chunks.append(buf)
247
- buf = line
248
- else:
249
- buf = (buf + "\n" + line) if buf else line
250
- if buf:
251
- chunks.append(buf)
252
- return chunks or [text[:limit]]
253
-
254
-
255
- def fmt_ts(ts) -> str:
256
- """Format a timestamp (float or ISO string) as HH:MM:SS."""
257
- if isinstance(ts, str):
258
- try:
259
- return datetime.fromisoformat(ts).strftime("%H:%M:%S")
260
- except Exception:
261
- return ts[:19]
262
- try:
263
- return time.strftime("%H:%M:%S", time.localtime(ts))
264
- except Exception:
265
- return str(ts)
266
-
267
-
268
- def short_user(user_id: int, user: Optional[dict] = None) -> str:
269
- """Short display name for a user."""
270
- info = UNIQUE_USERS.get(user_id) or {}
271
- username = (user or {}).get("username") or info.get("username")
272
- first = (user or {}).get("first_name") or info.get("first_name")
273
- if username:
274
- return f"@{username} ({user_id})"
275
- if first:
276
- return f"{first} ({user_id})"
277
- return f"({user_id})"
278
-
279
-
280
- def touch_user(uid: int, from_obj: dict) -> dict:
281
- """Create/update the USERS record for panel Users tab."""
282
- u = USERS.setdefault(uid, {
283
- "user_id": uid,
284
- "username": from_obj.get("username") or "",
285
- "first_name": from_obj.get("first_name") or "",
286
- "first_seen": now_iso(),
287
- "last_seen": now_iso(),
288
- "total_searches": 0,
289
- "last_query_type": "",
290
- "blocked": False,
291
- })
292
- u["last_seen"] = now_iso()
293
- if from_obj.get("username"):
294
- u["username"] = from_obj["username"]
295
- if from_obj.get("first_name"):
296
- u["first_name"] = from_obj["first_name"]
297
- return u
298
-
299
-
300
- # ── Panel session cookie ─────────────────────────────────────────────────
301
- def make_session_cookie() -> str:
302
- exp = int(time.time()) + PANEL_SESSION_TTL_MIN * 60
303
- sig = hmac.new(
304
- SESSION_KEY.encode(), f"panel:{exp}".encode(), hashlib.sha256
305
- ).hexdigest()[:24]
306
- return f"{exp}.{sig}"
307
-
308
-
309
- def check_session_cookie(val: str) -> bool:
310
- try:
311
- exp_s, sig = val.split(".")
312
- exp = int(exp_s)
313
- if exp < time.time():
314
- return False
315
- expected = hmac.new(
316
- SESSION_KEY.encode(), f"panel:{exp}".encode(), hashlib.sha256
317
- ).hexdigest()[:24]
318
- return hmac.compare_digest(sig, expected)
319
- except Exception:
320
- return False
321
-
322
-
323
- # ── Search log filtering (used by /api/searches) ─────────────────────────
324
- def filter_searches(q_type: str, q_status: str, q_user: str,
325
- q_from: str, q_to: str) -> list:
326
- """Return LOG_DEQUE entries matching the given filters."""
327
- out = []
328
- for r in LOG_DEQUE:
329
- if q_type and r.get("type") != q_type:
330
- continue
331
- if q_status and r.get("status") != q_status:
332
- continue
333
- if q_user:
334
- try:
335
- if int(r.get("user_id")) != int(q_user):
336
- continue
337
- except Exception:
338
- continue
339
- if q_from or q_to:
340
- try:
341
- ts = datetime.fromisoformat(r["ts_utc"])
342
- except Exception:
343
- continue
344
- if q_from:
345
- try:
346
- f = datetime.strptime(q_from, "%Y-%m-%d").replace(tzinfo=timezone.utc)
347
- if ts < f:
348
- continue
349
- except Exception:
350
- pass
351
- if q_to:
352
- try:
353
- t = (datetime.strptime(q_to, "%Y-%m-%d").replace(tzinfo=timezone.utc)
354
- + timedelta(days=1))
355
- if ts >= t:
356
- continue
357
- except Exception:
358
- pass
359
- out.append(r)
360
- return out
361
-
362
-
363
- # ═══════════════════════════════════════════════════════════════════════════
364
- # SANITY CHECK (fails fast on import if required config is missing)
365
- # ═══════════════════════════════════════════════════════════════════════════
366
- if not TELEGRAM_TOKEN:
367
- log.warning("TELEGRAM_TOKEN is empty — bot will not send or receive messages")
368
- if not WEBHOOK_BASE_URL:
369
- log.warning("WEBHOOK_BASE_URL/SPACE_URL is empty — setWebhook will be skipped")
370
-
371
- log.info(
372
- f"config loaded: VERSION={VERSION} "
373
- f"TOKEN={'ok' if TELEGRAM_TOKEN else 'MISSING'} "
374
- f"WEBHOOK={'set' if WEBHOOK_BASE_URL else 'MISSING'} "
375
- f"LOG_CHAT_ID={bool(LOG_CHAT_ID)} "
376
- f"ADMIN_SECRET={bool(ADMIN_SECRET)} "
377
- f"VIEWER_SECRET={bool(VIEWER_SECRET)}"
378
- )
 
1
+ # ══════════════════════════════════════════════════════════════════
2
+ # config.py — Central configuration for the Phone Lookup Bot
3
+ #
4
+ # This module is SAFE to import from anywhere:
5
+ # • No gradio, no duckdb, no httpx, no huggingface_hub.
6
+ # • Pure stdlib (os, re, hashlib).
7
+ # • The HfFolder monkey-patch lives in app.py (must run first),
8
+ # NOT here, so this file never touches HF internals.
9
+ #
10
+ # Import order across the project:
11
+ # config.py → engine.py → bot.py → admin_panel.py → app.py
12
+ # ══════════════════════════════════════════════════════════════════
13
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
  import os
 
 
 
15
  import re
 
 
 
 
16
  import hashlib
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
 
18
+ # ─────────────────────────────────────────────
19
+ # 1. CORE SECRETS & ENDPOINTS (read from HF Secrets / env)
20
+ # ─────────────────────────────────────────────
21
+ BOT_TOKEN = os.environ.get("BOT_TOKEN", "").strip()
22
+ HF_TOKEN = os.environ.get("HF_TOKEN", "").strip()
23
+ WEBHOOK_SECRET = os.environ.get("WEBHOOK_SECRET", "change_me_please").strip()
24
+
25
+ SPACE_URL = os.environ.get("SPACE_URL", "").strip().rstrip("/")
26
+ SPACE_HOST = os.environ.get("SPACE_HOST", "").strip().rstrip("/")
27
+
28
+ # Optional proxy for Telegram (leave empty to hit api.telegram.org directly)
29
+ TELEGRAM_PROXY = os.environ.get("TELEGRAM_PROXY", "").strip().rstrip("/")
30
+
31
+ # Admin
32
+ ADMIN_TOKEN = os.environ.get("ADMIN_TOKEN", "").strip()
33
 
34
+ # Owner bypass — comma-separated Telegram user IDs (force-join, quota, ban bypass)
35
+ OWNER_IDS = {
36
+ int(x) for x in os.environ.get("OWNER_IDS", "").split(",") if x.strip().isdigit()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
  }
38
 
39
+ # ─────────────────────────────────────────────
40
+ # 2. FEATURE FLAGS (new features per integration plan)
41
+ # ─────────────────────────────────────────────
42
+ # Force-join: @username or -100… chat id. Empty string → feature OFF.
43
+ FORCE_JOIN_CHANNEL = os.environ.get("FORCE_JOIN_CHANNEL", "").strip()
44
+
45
+ # ASURPAPA key (a12pp.py) — required for the 4 extra APIs
46
+ ASUR_KEY = os.environ.get("ASUR_KEY", "@ASUR_ABOUT").strip()
47
+
48
+ # Backup destination — every query is forwarded here.
49
+ # Empty string → backup forwarding silently disabled.
50
+ BACKUP_CHANNEL_ID = os.environ.get("BACKUP_CHANNEL_ID", "").strip()
51
+
52
+ # Runtime toggles (admin can flip via /backup on|off)
53
+ BACKUP_ENABLED_DEFAULT = bool(BACKUP_CHANNEL_ID)
54
+
55
+ # ─────────────────────────────────────────────
56
+ # 3. TELEGRAM URL (proxy-aware)
57
+ # ─────────────────────────────────────────────
58
+ TELEGRAM_API = (
59
+ f"{TELEGRAM_PROXY}/bot{BOT_TOKEN}"
60
+ if TELEGRAM_PROXY
61
+ else f"https://api.telegram.org/bot{BOT_TOKEN}"
62
+ )
63
+
64
+ # ─────────────────────────────────────────────
65
+ # 4. BOT META
66
+ # ─────────────────────────────────────────────
67
+ VERSION = "2.0.0" # bumped: a12pp + web panel + force-join
68
+ BOT_NAME = "Phone Lookup Bot"
69
+
70
+ # ─────────────────────────────────────────────
71
+ # 5. DATASETS — parquet sources
72
+ # ─────────────────────────────────────────────
73
+ # ── HiTeck (7 files, main DB) ──
74
+ HITECK_URLS = [
75
+ f"https://huggingface.co/datasets/HiTeckGroup/HiTeckgroop/resolve/main/idx_phone.{i}.parquet"
76
  for i in range(7)
77
  ]
78
+ PARQUET_URLS = HITECK_URLS
79
+
80
+ # ── Flipkart (1 file, different schema) ──
81
+ FLIPKART_URLS = [
82
+ "https://huggingface.co/datasets/Hfzune/Flipkart/resolve/main/flipkart.parquet"
83
+ ]
84
+
85
+ # ── Combined list used by warm-up & main query ──
86
+ ALL_PARQUET_URLS = PARQUET_URLS + FLIPKART_URLS
87
+
88
+ # ── a12pp.py datasets (Aadhaar resolution) ──
89
+ DATASET_INDATA = "tfqdeadlo/Inddata"
90
+ DATASET_SINGLE_URL = (
91
+ "https://huggingface.co/datasets/tfqdeadlo/Inddatainonefile/resolve/main/users_data.parquet"
92
+ )
93
+ DATASET_850_REPO = "tfqdeadlo/850MindData"
94
+ DATASET_850_PARTS = ["072", "000", "222", "850", "851"]
95
+
96
+ # ─────────────────────────────────────────────
97
+ # 6. APIs
98
+ # ─────────────────────────────────────────────
99
+ # ── app14.py APIs ──
100
+ API_850CR = "https://tfqdeadlo-850crfastsearch.hf.space/search"
101
  API_INDDATA = "https://tfqdeadlo-inddataapi.hf.space/search"
102
 
103
+ # ── a12pp.py ASURPAPA APIs (4 endpoints) ──
104
+ # NOTE: ration-card endpoint uses param name `aadhar` (NOT `aadhaar`) — do not "fix".
105
+ ASUR_API = {
106
+ "num_to_info": "https://num-to-info.asurpapa.workers.dev/api",
107
+ "aadhaar_to_info": "https://aadhaar.asurpapa.workers.dev/api",
108
+ "aadhaar_family": "https://aadhaar-family.asurpapa.workers.dev/api",
109
+ "aadhaar_ration": "https://ration-card.asurpapa.workers.dev/api",
110
+ }
111
+ ASUR_PARAM_NAMES = {
112
+ "num_to_info": "number",
113
+ "aadhaar_to_info": "aadhaar",
114
+ "aadhaar_family": "aadhaar",
115
+ "aadhaar_ration": "aadhar", # yes, spelling is intentional
116
+ }
117
+
118
+ # Per-API runtime enable flags (admin can toggle from web panel).
119
+ # Missing key = enabled.
120
+ API_ENABLED = {
121
+ "850cr": True,
122
+ "inddata": True,
123
+ "asur_num_to_info": True,
124
+ "asur_aadhaar_to_info": True,
125
+ "asur_aadhaar_family": True,
126
+ "asur_aadhaar_ration": True,
127
+ }
128
+
129
+ # ─────────────────────────────────────────────
130
+ # 7. TUNABLES — performance & limits
131
+ # ─────────────────────────────────────────────
132
+ # ── Query / DB ──
133
+ PAGE_SIZE = 4
134
+ FETCH_LIMIT = 40
135
+ QUERY_TIMEOUT = 90 # seconds — DuckDB watchdog hard-cancel
136
+ BATCH_MAX = 5
137
+ BATCH_TIMEOUT = 60
138
+
139
+ # ── HTTP ──
140
+ HTTP_TIMEOUT = 30 # generic API timeout
141
+ API_850CR_TIMEOUT = 40
142
+ API_INDDATA_TIMEOUT = 30
143
+ ASUR_HTTP_TIMEOUT = 30 # each ASURPAPA endpoint
144
+
145
+ # ── Cache ──
146
+ CACHE_TTL = 300 # search cache (5 min)
147
+ SEARCH_CACHE_TTL = 1800 # SEARCH_CACHE entries for pagination (30 min)
148
+ MEMBERSHIP_CACHE_TTL = 300 # force-join re-check interval (5 min)
149
+ PENDING_QUERY_TTL = 600 # user must re-dispatch after joining within 10 min
150
+
151
+ # ── Rate limits ──
152
+ USER_COOLDOWN = 5 # seconds between any two queries per user
153
+ RATE_LIMIT_PER_MIN = 10 # soft cap per minute (telemetry)
154
+ FLOOD_WINDOW = 10 # seconds
155
+ FLOOD_MAX = 5 # messages within FLOOD_WINDOW → mute
156
+ FLOOD_MUTE_SEC = 60
157
+
158
+ # ── Quota ──
159
+ DAILY_QUOTA = 100 # per non-admin user, resets at 00:00 UTC
160
+ DAILY_QUOTA_ADMIN = 100000 # effectively unlimited for admins
161
+
162
+ # ── Activity tracking ──
163
+ LIVE_WINDOW = 300 # "online now" window (5 min)
164
+ HISTORY_LEN = 10 # per-user /history size
165
+ ACTIVITY_LOG_MAX = 10000 # deque maxlen
166
+
167
+ # ── Admin ──
168
+ ADMIN_SESSION_TTL = 3600 # 1 hour web/bot admin session
169
+ ADMIN_PROMPT_TTL = 180 # 3 min to answer an admin prompt
170
+ ADMIN_LOGIN_RATE = (5, 15 * 60) # (max attempts, window secs) — web panel
171
+
172
+ # ── Broadcast ──
173
+ BROADCAST_DELAY = 0.05 # seconds between messages
174
+ BROADCAST_MAX_LEN = 3800 # keep under Telegram 4096 - header
175
+
176
+ # ── Web panel ──
177
+ WEB_PANEL_REFRESH_SEC = 5 # dashboard auto-refresh
178
+ WEB_PANEL_PAGE_SIZE = 25
179
+
180
+ # ── API health monitor ──
181
+ API_HEALTH_INTERVAL = 300 # ping every 5 min
182
+ API_HEALTH_TIMEOUT = 15 # per-ping timeout
183
+
184
+ # ─────────────────────────────────────────────
185
+ # 8. INPUT VALIDATION
186
+ # ─────────────────────────────────────────────
187
+ PHONE_REGEX = re.compile(r"^\d{10}$")
188
+
189
+ # ─────────────────────────────────────────────
190
+ # 9. RECORD SCHEMA — display truncation + labels
191
+ # ─────────────────────────────────────────────
192
+ TRUNC = {
193
+ "name": 80,
194
+ "fathersName": 80,
195
+ "address": 200,
196
+ "phoneNumber": 40,
197
+ "aadharNumber": 40,
198
+ "otherNumber": 40,
199
+ "district": 40,
200
+ "pincode": 15,
201
+ "state": 40,
202
+ "town": 40,
203
+ "source": 30,
204
+ }
205
+
206
+ # (field_key, emoji, human_label) — order determines render order
207
  FIELD_LABELS = [
208
  ("name", "👤", "Name"),
209
  ("fathersName", "👨", "Father"),
 
218
  ("source", "📂", "Source"),
219
  ]
220
 
221
+ # Column names that may carry an Aadhaar number in the parquet files
222
+ AADHAAR_COL_CANDIDATES = (
223
+ "aadharNumber", "aadhaarNumber", "aadhaar_number",
224
+ "aadhar_number", "aadhaar", "aadhar", "uid",
225
+ )
226
+
227
+ # ─────────────────────────────────────────────
228
+ # 10. SOURCE LABELS — human names used in records
229
+ # ─────────────────────────────────────────────
230
+ SOURCE_LABEL = {
231
+ "hiteck": "HiTeck",
232
+ "flipkart": "Flipkart",
233
+ "850cr": "850CR Fast",
234
+ "inddata": "IndData 1.4B",
235
+ "asur_num": "ASUR NumInfo",
236
+ "asur_aadhaar": "ASUR AadhaarLink",
237
+ "asur_family": "ASUR Family",
238
+ "asur_ration": "ASUR Ration",
239
+ }
240
 
241
+ # ─────────────────────────────────────────────
242
+ # 11. SECRET TOKEN (Telegram webhook header)
243
+ # Telegram requires ^[A-Za-z0-9_-]{1,256}$
244
+ # We derive it deterministically from WEBHOOK_SECRET.
245
+ # ─────────────────────────────────────────────
246
+ SECRET_TOKEN = hashlib.sha256(WEBHOOK_SECRET.encode()).hexdigest()[:32]
247
+
248
+ # ─────────────────────────────────────────────
249
+ # 12. STARTUP SANITY CHECKS (warn only — never crash)
250
+ # ─────────────────────────────────────────────
251
+ def _sanity_check() -> list:
252
+ """Return a list of warning strings. Called by app.py at boot."""
253
+ warnings = []
254
+ if not BOT_TOKEN:
255
+ warnings.append("BOT_TOKEN is empty — bot will not receive updates")
256
+ if not WEBHOOK_SECRET or WEBHOOK_SECRET == "change_me_please":
257
+ warnings.append("WEBHOOK_SECRET is default — set a real value")
258
+ if not SPACE_URL and not SPACE_HOST:
259
+ warnings.append("SPACE_URL/SPACE_HOST missing — webhook auto-registration skipped")
260
+ if not ADMIN_TOKEN:
261
+ warnings.append("ADMIN_TOKEN missing — /admin commands disabled")
262
+ if FORCE_JOIN_CHANNEL and not (
263
+ FORCE_JOIN_CHANNEL.startswith("@") or FORCE_JOIN_CHANNEL.lstrip("-").isdigit()
264
+ ):
265
+ warnings.append(
266
+ f"FORCE_JOIN_CHANNEL={FORCE_JOIN_CHANNEL!r} looks invalid — "
267
+ "expected @username or -100… chat id"
268
+ )
269
+ if not BACKUP_CHANNEL_ID:
270
+ warnings.append("BACKUP_CHANNEL_ID empty — per-query backup disabled")
271
+ if not ASUR_KEY:
272
+ warnings.append("ASUR_KEY empty — ASURPAPA APIs will return errors")
273
+ return warnings
274
+
275
+
276
+ def _mask(secret: str, keep: int = 4) -> str:
277
+ """Mask a secret for safe logging."""
278
+ if not secret:
279
+ return "(empty)"
280
+ if len(secret) <= keep * 2:
281
+ return "*" * len(secret)
282
+ return secret[:keep] + "*" * (len(secret) - keep * 2) + secret[-keep:]
283
+
284
+
285
+ def summary() -> str:
286
+ """One-shot human-readable config dump — printed at boot."""
287
+ lines = [
288
+ "── config summary ──────────────────────────────",
289
+ f" version : {VERSION}",
290
+ f" bot token : {_mask(BOT_TOKEN)}",
291
+ f" webhook secret : {_mask(WEBHOOK_SECRET)}",
292
+ f" admin token : {_mask(ADMIN_TOKEN)}",
293
+ f" asur key : {_mask(ASUR_KEY)}",
294
+ f" space url : {SPACE_URL or SPACE_HOST or '(unset)'}",
295
+ f" telegram proxy : {TELEGRAM_PROXY or '(direct)'}",
296
+ f" force-join channel : {FORCE_JOIN_CHANNEL or '(disabled)'}",
297
+ f" backup channel : {BACKUP_CHANNEL_ID or '(disabled)'}",
298
+ f" owners : {sorted(OWNER_IDS) or '(none)'}",
299
+ f" daily quota : {DAILY_QUOTA}/user",
300
+ f" flood mute : {FLOOD_MAX} msgs / {FLOOD_WINDOW}s → {FLOOD_MUTE_SEC}s",
301
+ f" parquet sources : {len(ALL_PARQUET_URLS)} "
302
+ f"(HiTeck {len(PARQUET_URLS)} + Flipkart {len(FLIPKART_URLS)})",
303
+ f" aadhaar datasets : Inddata + Inddatainonefile + 850MindData ×{len(DATASET_850_PARTS)}",
304
+ f" apis : 850CR + IndData + ASUR×4",
305
+ "────────────────────────────────────────────────",
306
+ ]
307
+ return "\n".join(lines)
308
+
309
+
310
+ # ─────────────────────────────────────────────
311
+ # SELF-TEST (python config.py → prints summary + warnings)
312
+ # ─────────────────────────────────────────────
313
+ if __name__ == "__main__":
314
+ print(summary())
315
+ ws = _sanity_check()
316
+ if ws:
317
+ print("\n⚠️ warnings:")
318
+ for w in ws:
319
+ print(f" • {w}")
320
+ else:
321
+ print("\n✅ no warnings — config looks complete")