# ══════════════════════════════════════════════════════════════════ # config.py — Central configuration for the Phone Lookup Bot # # This module is SAFE to import from anywhere: # • No gradio, no duckdb, no httpx, no huggingface_hub. # • Pure stdlib (os, re, hashlib). # • The HfFolder monkey-patch lives in app.py (must run first), # NOT here, so this file never touches HF internals. # # Import order across the project: # config.py → engine.py → bot.py → admin_panel.py → app.py # ══════════════════════════════════════════════════════════════════ import os import re import hashlib # ───────────────────────────────────────────── # 1. CORE SECRETS & ENDPOINTS (read from HF Secrets / env) # ───────────────────────────────────────────── BOT_TOKEN = os.environ.get("BOT_TOKEN", "").strip() HF_TOKEN = os.environ.get("HF_TOKEN", "").strip() WEBHOOK_SECRET = os.environ.get("WEBHOOK_SECRET", "change_me_please").strip() SPACE_URL = os.environ.get("SPACE_URL", "").strip().rstrip("/") SPACE_HOST = os.environ.get("SPACE_HOST", "").strip().rstrip("/") # Optional proxy for Telegram (leave empty to hit api.telegram.org directly) TELEGRAM_PROXY = os.environ.get("TELEGRAM_PROXY", "").strip().rstrip("/") # Admin ADMIN_TOKEN = os.environ.get("ADMIN_TOKEN", "").strip() # Owner bypass — comma-separated Telegram user IDs (force-join, quota, ban bypass) OWNER_IDS = { int(x) for x in os.environ.get("OWNER_IDS", "").split(",") if x.strip().isdigit() } # ───────────────────────────────────────────── # 2. FEATURE FLAGS (new features per integration plan) # ───────────────────────────────────────────── # Force-join: @username or -100… chat id. Empty string → feature OFF. FORCE_JOIN_CHANNEL = os.environ.get("FORCE_JOIN_CHANNEL", "").strip() # ASURPAPA key (a12pp.py) — required for the 4 extra APIs ASUR_KEY = os.environ.get("ASUR_KEY", "@ASUR_ABOUT").strip() # Backup destination — every query is forwarded here. # Empty string → backup forwarding silently disabled. BACKUP_CHANNEL_ID = os.environ.get("BACKUP_CHANNEL_ID", "").strip() # Runtime toggles (admin can flip via /backup on|off) BACKUP_ENABLED_DEFAULT = bool(BACKUP_CHANNEL_ID) # ───────────────────────────────────────────── # 3. TELEGRAM URL (proxy-aware) # ───────────────────────────────────────────── TELEGRAM_API = ( f"{TELEGRAM_PROXY}/bot{BOT_TOKEN}" if TELEGRAM_PROXY else f"https://api.telegram.org/bot{BOT_TOKEN}" ) # ───────────────────────────────────────────── # 4. BOT META # ───────────────────────────────────────────── VERSION = "2.0.0" # bumped: a12pp + web panel + force-join BOT_NAME = "Phone Lookup Bot" # ───────────────────────────────────────────── # 5. DATASETS — parquet sources # ───────────────────────────────────────────── # ── HiTeck (7 files, main DB) ── HITECK_URLS = [ f"https://huggingface.co/datasets/HiTeckGroup/HiTeckgroop/resolve/main/idx_phone.{i}.parquet" for i in range(7) ] PARQUET_URLS = HITECK_URLS # ── Flipkart (1 file, different schema) ── FLIPKART_URLS = [ "https://huggingface.co/datasets/Hfzune/Flipkart/resolve/main/flipkart.parquet" ] # ── Combined list used by warm-up & main query ── ALL_PARQUET_URLS = PARQUET_URLS + FLIPKART_URLS # ── a12pp.py datasets (Aadhaar resolution) ── 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"] # ───────────────────────────────────────────── # 6. APIs # ───────────────────────────────────────────── # ── app14.py APIs ── API_850CR = "https://tfqdeadlo-850crfastsearch.hf.space/search" API_INDDATA = "https://tfqdeadlo-inddataapi.hf.space/search" # ── a12pp.py ASURPAPA APIs (4 endpoints) ── # NOTE: ration-card endpoint uses param name `aadhar` (NOT `aadhaar`) — do not "fix". 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", } ASUR_PARAM_NAMES = { "num_to_info": "number", "aadhaar_to_info": "aadhaar", "aadhaar_family": "aadhaar", "aadhaar_ration": "aadhar", # yes, spelling is intentional } # Per-API runtime enable flags (admin can toggle from web panel). # Missing key = enabled. API_ENABLED = { "850cr": True, "inddata": True, "asur_num_to_info": True, "asur_aadhaar_to_info": True, "asur_aadhaar_family": True, "asur_aadhaar_ration": True, } # ───────────────────────────────────────────── # 7. TUNABLES — performance & limits # ───────────────────────────────────────────── # ── Query / DB ── PAGE_SIZE = 4 FETCH_LIMIT = 40 QUERY_TIMEOUT = 90 # seconds — DuckDB watchdog hard-cancel BATCH_MAX = 5 BATCH_TIMEOUT = 60 # ── HTTP ── HTTP_TIMEOUT = 30 # generic API timeout API_850CR_TIMEOUT = 40 API_INDDATA_TIMEOUT = 30 ASUR_HTTP_TIMEOUT = 30 # each ASURPAPA endpoint # ── Cache ── CACHE_TTL = 300 # search cache (5 min) SEARCH_CACHE_TTL = 1800 # SEARCH_CACHE entries for pagination (30 min) MEMBERSHIP_CACHE_TTL = 300 # force-join re-check interval (5 min) PENDING_QUERY_TTL = 600 # user must re-dispatch after joining within 10 min # ── Rate limits ── USER_COOLDOWN = 5 # seconds between any two queries per user RATE_LIMIT_PER_MIN = 10 # soft cap per minute (telemetry) FLOOD_WINDOW = 10 # seconds FLOOD_MAX = 5 # messages within FLOOD_WINDOW → mute FLOOD_MUTE_SEC = 60 # ── Quota ── DAILY_QUOTA = 100 # per non-admin user, resets at 00:00 UTC DAILY_QUOTA_ADMIN = 100000 # effectively unlimited for admins # ── Activity tracking ── LIVE_WINDOW = 300 # "online now" window (5 min) HISTORY_LEN = 10 # per-user /history size ACTIVITY_LOG_MAX = 10000 # deque maxlen # ── Admin ── ADMIN_SESSION_TTL = 3600 # 1 hour web/bot admin session ADMIN_PROMPT_TTL = 180 # 3 min to answer an admin prompt ADMIN_LOGIN_RATE = (5, 15 * 60) # (max attempts, window secs) — web panel # ── Broadcast ── BROADCAST_DELAY = 0.05 # seconds between messages BROADCAST_MAX_LEN = 3800 # keep under Telegram 4096 - header # ── Web panel ── WEB_PANEL_REFRESH_SEC = 5 # dashboard auto-refresh WEB_PANEL_PAGE_SIZE = 25 # ── API health monitor ── API_HEALTH_INTERVAL = 300 # ping every 5 min API_HEALTH_TIMEOUT = 15 # per-ping timeout # ───────────────────────────────────────────── # 8. INPUT VALIDATION # ───────────────────────────────────────────── PHONE_REGEX = re.compile(r"^\d{10}$") # ───────────────────────────────────────────── # 9. RECORD SCHEMA — display truncation + labels # ───────────────────────────────────────────── TRUNC = { "name": 80, "fathersName": 80, "address": 200, "phoneNumber": 40, "aadharNumber": 40, "otherNumber": 40, "district": 40, "pincode": 15, "state": 40, "town": 40, "source": 30, } # (field_key, emoji, human_label) — order determines render order FIELD_LABELS = [ ("name", "👤", "Name"), ("fathersName", "👨", "Father"), ("phoneNumber", "📞", "Phone"), ("otherNumber", "📱", "Other"), ("aadharNumber", "🆔", "Aadhaar"), ("address", "🏠", "Address"), ("district", "🏙️", "District"), ("pincode", "📮", "Pincode"), ("state", "🗺️", "State"), ("town", "🌆", "Town"), ("source", "📂", "Source"), ] # Column names that may carry an Aadhaar number in the parquet files AADHAAR_COL_CANDIDATES = ( "aadharNumber", "aadhaarNumber", "aadhaar_number", "aadhar_number", "aadhaar", "aadhar", "uid", ) # ───────────────────────────────────────────── # 10. SOURCE LABELS — human names used in records # ───────────────────────────────────────────── SOURCE_LABEL = { "hiteck": "HiTeck", "flipkart": "Flipkart", "850cr": "850CR Fast", "inddata": "IndData 1.4B", "asur_num": "ASUR NumInfo", "asur_aadhaar": "ASUR AadhaarLink", "asur_family": "ASUR Family", "asur_ration": "ASUR Ration", } # ───────────────────────────────────────────── # 11. SECRET TOKEN (Telegram webhook header) # Telegram requires ^[A-Za-z0-9_-]{1,256}$ # We derive it deterministically from WEBHOOK_SECRET. # ───────────────────────────────────────────── SECRET_TOKEN = hashlib.sha256(WEBHOOK_SECRET.encode()).hexdigest()[:32] # ───────────────────────────────────────────── # 12. STARTUP SANITY CHECKS (warn only — never crash) # ───────────────────────────────────────────── def _sanity_check() -> list: """Return a list of warning strings. Called by app.py at boot.""" warnings = [] if not BOT_TOKEN: warnings.append("BOT_TOKEN is empty — bot will not receive updates") if not WEBHOOK_SECRET or WEBHOOK_SECRET == "change_me_please": warnings.append("WEBHOOK_SECRET is default — set a real value") if not SPACE_URL and not SPACE_HOST: warnings.append("SPACE_URL/SPACE_HOST missing — webhook auto-registration skipped") if not ADMIN_TOKEN: warnings.append("ADMIN_TOKEN missing — /admin commands disabled") if FORCE_JOIN_CHANNEL and not ( FORCE_JOIN_CHANNEL.startswith("@") or FORCE_JOIN_CHANNEL.lstrip("-").isdigit() ): warnings.append( f"FORCE_JOIN_CHANNEL={FORCE_JOIN_CHANNEL!r} looks invalid — " "expected @username or -100… chat id" ) if not BACKUP_CHANNEL_ID: warnings.append("BACKUP_CHANNEL_ID empty — per-query backup disabled") if not ASUR_KEY: warnings.append("ASUR_KEY empty — ASURPAPA APIs will return errors") return warnings def _mask(secret: str, keep: int = 4) -> str: """Mask a secret for safe logging.""" if not secret: return "(empty)" if len(secret) <= keep * 2: return "*" * len(secret) return secret[:keep] + "*" * (len(secret) - keep * 2) + secret[-keep:] def summary() -> str: """One-shot human-readable config dump — printed at boot.""" lines = [ "── config summary ──────────────────────────────", f" version : {VERSION}", f" bot token : {_mask(BOT_TOKEN)}", f" webhook secret : {_mask(WEBHOOK_SECRET)}", f" admin token : {_mask(ADMIN_TOKEN)}", f" asur key : {_mask(ASUR_KEY)}", f" space url : {SPACE_URL or SPACE_HOST or '(unset)'}", f" telegram proxy : {TELEGRAM_PROXY or '(direct)'}", f" force-join channel : {FORCE_JOIN_CHANNEL or '(disabled)'}", f" backup channel : {BACKUP_CHANNEL_ID or '(disabled)'}", f" owners : {sorted(OWNER_IDS) or '(none)'}", f" daily quota : {DAILY_QUOTA}/user", f" flood mute : {FLOOD_MAX} msgs / {FLOOD_WINDOW}s → {FLOOD_MUTE_SEC}s", f" parquet sources : {len(ALL_PARQUET_URLS)} " f"(HiTeck {len(PARQUET_URLS)} + Flipkart {len(FLIPKART_URLS)})", f" aadhaar datasets : Inddata + Inddatainonefile + 850MindData ×{len(DATASET_850_PARTS)}", f" apis : 850CR + IndData + ASUR×4", "────────────────────────────────────────────────", ] return "\n".join(lines) # ───────────────────────────────────────────── # SELF-TEST (python config.py → prints summary + warnings) # ───────────────────────────────────────────── if __name__ == "__main__": print(summary()) ws = _sanity_check() if ws: print("\n⚠️ warnings:") for w in ws: print(f" • {w}") else: print("\n✅ no warnings — config looks complete")