Download app.py from Mrx400/worker: direct link, hf CLI and curl.
- Browser
- Download file 10.9 kB
-
https://huggingface.co/spaces/Mrx400/worker/resolve/main/app.py
- Command line
-
hf download hf://spaces/Mrx400/worker/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Mrx400/worker/resolve/main/app.py
10.9 kB
| import traceback | |
| import os | |
| import re | |
| import queue | |
| import threading | |
| from functools import lru_cache | |
| import duckdb | |
| import fastapi | |
| import gradio as gr | |
| import spaces | |
| from slowapi import Limiter, _rate_limit_exceeded_handler | |
| from slowapi.util import get_remote_address | |
| from slowapi.errors import RateLimitExceeded | |
| limiter = Limiter(key_func=get_remote_address) | |
| HF_TOKEN = os.getenv("HF_TOKEN") | |
| # ββ DATABASE (remote streamed parquet, zero local storage) ββββββββββββββββ | |
| DB_PATH = "workerdb" # in-memory DB shared by the connection pool | |
| QUERY_TIMEOUT = 70 # seconds | |
| POOL_SIZE = int(os.getenv("POOL_SIZE", "4")) # parallel queries per Space instance | |
| DB_THREADS = int(os.getenv("DB_THREADS", "2")) | |
| # UPDATED: pointing to your private bucket instead of a public dataset | |
| DATAS = { | |
| "tc_fast": "hf://datasets/wannabeyour/truecallerdata/combined_selected_columns.parquet", | |
| "tc_full": "hf://datasets/wannabeyour/truecallerdata/combined_truecaller_data.parquet", | |
| "icmr_phone": "hf://buckets/Mrx400/icrm-hitek-full-db-mixed-bucket/idx_phone.*.parquet", | |
| "icmr_aadhar": "hf://buckets/Mrx400/icrm-hitek-full-db-mixed-bucket/idx_aadhar.*.parquet", | |
| } | |
| _pool: queue.Queue = queue.Queue() | |
| _boot_lock = threading.Lock() | |
| _built = False # one-time bootstrap (prevents concurrent CREATE VIEW conflicts) | |
| def _bootstrap(): | |
| global _built | |
| with _boot_lock: | |
| if _built or _pool.qsize() >= POOL_SIZE: | |
| return | |
| print("Mounting remote dataset views...") | |
| con = duckdb.connect(DB_PATH, config={"threads": DB_THREADS}) | |
| con.execute("INSTALL httpfs; LOAD httpfs;") | |
| con.execute(f"CREATE SECRET hf_auth (TYPE HUGGINGFACE, TOKEN '{HF_TOKEN}');") | |
| for name, path in DATAS.items(): | |
| con.execute(f"CREATE OR REPLACE VIEW {name} AS SELECT * FROM read_parquet('{path}')") | |
| seeds = [con] | |
| for _ in range(POOL_SIZE - 1): | |
| seeds.append(duckdb.connect(DB_PATH, config={"threads": DB_THREADS})) | |
| for c in seeds: | |
| _pool.put(c) | |
| _built = True | |
| def acquire(timeout: float = 600.0): | |
| if _pool.empty(): | |
| _bootstrap() | |
| return _pool.get(timeout=timeout) | |
| def release(con): | |
| if _pool.qsize() < POOL_SIZE * 2: | |
| _pool.put(con) | |
| _bootstrap() | |
| def run_sql(sql: str) -> list: | |
| con = acquire() | |
| t = threading.Timer(QUERY_TIMEOUT, lambda: con.interrupt()) | |
| t.daemon = True | |
| t.start() | |
| try: | |
| cur = con.execute(sql) | |
| cols = [d[0] for d in (cur.description or [])] | |
| rows = cur.fetchall() | |
| return [dict(zip(cols, r)) for r in rows] | |
| except duckdb.Error as e: | |
| if "interrupt" in str(e).lower(): | |
| raise TimeoutError(f"query took > {QUERY_TIMEOUT}s") | |
| raise | |
| finally: | |
| t.cancel() | |
| release(con) | |
| def _clean(v): | |
| return v.replace("\x00", "").strip() if isinstance(v, str) else v | |
| # ββ IN-MEMORY QUERY CACHE ββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def cached_query(sql: str) -> tuple: | |
| recs = tuple({_k: _clean(_v) for _k, _v in r.items()} for r in run_sql(sql)) | |
| return recs | |
| def clean_digits(s: str, n: int = 10) -> str: | |
| return re.sub(r'\D', '', s)[-n:] | |
| # ββ FASTAPI MONKEY-PATCH βββββββββββββββββββββββββββββββββββββββββββββββββ | |
| _original_init = fastapi.FastAPI.__init__ | |
| def _custom_init(self, *args, **kwargs): | |
| _original_init(self, *args, **kwargs) | |
| self.state.limiter = limiter | |
| self.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler) | |
| def health(): | |
| return {"status": "online", "cache_size": cached_query.cache_info().currsize} | |
| # --- Truecaller Endpoint (curated fast set first, full dump only if needed) --- | |
| def search_tc(request: fastapi.Request, mobile: str = ""): | |
| clean = clean_digits(mobile, 10) | |
| if len(clean) < 10: | |
| return {"status": "error", "message": "Invalid input: 10-digit mobile number required"} | |
| nums = f"('{clean}', '91{clean}')" | |
| try: | |
| records = list(cached_query(f"SELECT DISTINCT Number, Name, Gender, Address, Email FROM tc_fast WHERE Number IN {nums} LIMIT 15")) | |
| if not records: | |
| big = cached_query(f"SELECT Number, Name, Email FROM tc_full WHERE Number IN {nums} LIMIT 15") | |
| records = list(big) or records | |
| if not records: | |
| return {"status": "not_found", "message": f"No records found for target: {clean}", "count": 0, "data": []} | |
| return {"status": "success", "count": len(records), "data": records} | |
| except TimeoutError: | |
| traceback.print_exc() | |
| return {"status": "error", "message": f"Query timed out after {QUERY_TIMEOUT}s"} | |
| except Exception: | |
| traceback.print_exc() | |
| return {"status": "error", "message": "Internal query execution failed"} | |
| # --- ICMR Phone Endpoint --- | |
| def search_icmr_phone(request: fastapi.Request, mobile: str = ""): | |
| clean = clean_digits(mobile, 10) | |
| if len(clean) < 10: | |
| return {"status": "error", "message": "Invalid input: 10-digit mobile number required"} | |
| sql = f"SELECT DISTINCT * FROM icmr_phone WHERE phoneNumber = '{clean}' LIMIT 15" | |
| try: | |
| records = list(cached_query(sql)) | |
| if not records: | |
| return {"status": "not_found", "message": f"No records found for target: {clean}", "count": 0, "data": []} | |
| return {"status": "success", "count": len(records), "data": records} | |
| except TimeoutError: | |
| traceback.print_exc() | |
| return {"status": "error", "message": f"Query timed out after {QUERY_TIMEOUT}s"} | |
| except Exception: | |
| traceback.print_exc() | |
| return {"status": "error", "message": "Internal query execution failed"} | |
| # --- ICMR Aadhaar Endpoint --- | |
| def search_icmr_aadhar(request: fastapi.Request, aadhar: str = ""): | |
| clean = clean_digits(aadhar, 12) | |
| if len(clean) < 12: | |
| return {"status": "error", "message": "Invalid input: 12-digit number required"} | |
| sql = f"SELECT DISTINCT * FROM icmr_aadhar WHERE aadharNumber = '{clean}' LIMIT 15" | |
| try: | |
| records = list(cached_query(sql)) | |
| if not records: | |
| return {"status": "not_found", "message": "No matching records found", "count": 0, "data": []} | |
| return {"status": "success", "count": len(records), "data": records} | |
| except TimeoutError: | |
| traceback.print_exc() | |
| return {"status": "error", "message": f"Query timed out after {QUERY_TIMEOUT}s"} | |
| except Exception: | |
| traceback.print_exc() | |
| return {"status": "error", "message": "Internal query execution failed"} | |
| # --- Combined Endpoint (one shot across sources) --- | |
| def lookup_all(request: fastapi.Request, mobile: str = ""): | |
| clean = clean_digits(mobile, 10) | |
| if len(clean) < 10: | |
| return {"status": "error", "message": "Invalid input: 10-digit mobile number required"} | |
| nums = f"('{clean}', '91{clean}')" | |
| try: | |
| tc = list(cached_query(f"SELECT DISTINCT Number, Name, Gender, Address, Email FROM tc_fast WHERE Number IN {nums} LIMIT 15")) | |
| icmr = list(cached_query(f"SELECT DISTINCT * FROM icmr_phone WHERE phoneNumber = '{clean}' LIMIT 15")) | |
| return { | |
| "status": "success", | |
| "target": clean, | |
| "truecaller_count": len(tc), | |
| "icmr_phone_count": len(icmr), | |
| "truecaller": tc, | |
| "icmr_phone": icmr, | |
| } | |
| except TimeoutError: | |
| traceback.print_exc() | |
| return {"status": "error", "message": f"Query timed out after {QUERY_TIMEOUT}s"} | |
| except Exception: | |
| traceback.print_exc() | |
| return {"status": "error", "message": "Internal query execution failed"} | |
| fastapi.FastAPI.__init__ = _custom_init | |
| # ββ ZERO-GPU DECOY & UI βββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def gr_lookup(mobile: str): | |
| clean = clean_digits(mobile or "", 10) | |
| if len(clean) < 10: | |
| return {"status": "error", "message": "Invalid input: 10-digit mobile number required"} | |
| nums = f"('{clean}', '91{clean}')" | |
| try: | |
| tc = list(cached_query(f"SELECT DISTINCT Number, Name, Gender, Address, Email FROM tc_fast WHERE Number IN {nums} LIMIT 15")) | |
| icmr = list(cached_query(f"SELECT DISTINCT * FROM icmr_phone WHERE phoneNumber = '{clean}' LIMIT 15")) | |
| return { | |
| "target": clean, | |
| "truecaller_count": len(tc), | |
| "icmr_phone_count": len(icmr), | |
| "truecaller": tc, | |
| "icmr_phone": icmr, | |
| } | |
| except Exception: | |
| return {"status": "error", "message": "Internal query execution failed"} | |
| custom_theme = gr.themes.Monochrome( | |
| font=[gr.themes.GoogleFont("JetBrains Mono"), "ui-monospace", "monospace"], | |
| primary_hue="slate", | |
| neutral_hue="slate", | |
| ) | |
| with gr.Blocks(theme=custom_theme, title="Worker Node Hub") as app: | |
| gr.Markdown( | |
| """ | |
| # Worker Node Central Hub | |
| **Status:** `ONLINE` | **Architecture:** `Remote Streaming + LRU Cache + Query Pool` | |
| """ | |
| ) | |
| with gr.Row(): | |
| with gr.Column(): | |
| num = gr.Textbox(label="Mobile number (10 digits)", placeholder="9876543210") | |
| btn = gr.Button("Lookup") | |
| out = gr.JSON(label="Result", value=None) | |
| btn.click(fn=gr_lookup, inputs=[num], outputs=[out]) | |
| num.submit(fn=gr_lookup, inputs=[num], outputs=[out]) | |
| with gr.Column(): | |
| gr.Markdown("### REST Endpoints") | |
| gr.Markdown( | |
| """ | |
| - `GET /api/truecaller?mobile={10_digits}` | |
| - `GET /api/icmr/phone?mobile={10_digits}` | |
| - `GET /api/icmr/aadhar?aadhar={12_digits}` | |
| - `GET /api/lookup?mobile={10_digits}` (combined) | |
| - `GET /health` | |
| Rate limit: 30 req/min/IP Β· Query timeout: 70s | |
| """ | |
| ) | |
| # Zero-GPU decoy (satisfies HF Zero GPU hardware claim) | |
| def fake_gpu(): | |
| pass | |
| app.launch(ssr_mode=False) |