File size: 40,712 Bytes
36c73b5 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 | # ══════════════════════════════════════════════════════════════════
# engine.py — Data & API layer
#
# Owns:
# • DuckDB main connection (HiTeck ×7 + Flipkart ×1)
# • DuckDB ASUR connection (Inddata + Inddatainonefile + 850MindData)
# • Fast APIs (850CR + IndData)
# • ASURPAPA APIs ×4 (num_to_info + 3 aadhaar endpoints)
# • Aadhaar resolution (mobile → aadhaar)
# • Filtering (drops empty / errored API responses)
# • Deduplication (name + address / name + father)
# • Formatting primitives (render_page, format_result, extras block)
#
# NEVER imports bot.py or app.py — this is a leaf module.
# ══════════════════════════════════════════════════════════════════
import asyncio
import html
import logging
import re
import threading
import time
import urllib.parse
from typing import Optional, Any, List
import duckdb
import httpx
from config import (
# Datasets
PARQUET_URLS, FLIPKART_URLS, ALL_PARQUET_URLS,
DATASET_INDATA, DATASET_SINGLE_URL, DATASET_850_REPO, DATASET_850_PARTS,
# APIs
API_850CR, API_INDDATA, ASUR_API, ASUR_PARAM_NAMES, ASUR_KEY, HF_TOKEN,
API_ENABLED,
# Tunables
FETCH_LIMIT, QUERY_TIMEOUT, PAGE_SIZE,
API_850CR_TIMEOUT, API_INDDATA_TIMEOUT, ASUR_HTTP_TIMEOUT,
API_HEALTH_TIMEOUT,
# Schema
TRUNC, FIELD_LABELS, AADHAAR_COL_CANDIDATES, SOURCE_LABEL, PHONE_REGEX,
)
log = logging.getLogger("engine")
# ─────────────────────────────────────────────
# SMALL HELPERS
# ─────────────────────────────────────────────
def esc(x: Any) -> str:
"""HTML-escape a value; None → empty string."""
if x is None:
return ""
return html.escape(str(x), quote=False)
def _tv(v, n: int) -> str:
"""Truncate a value for display."""
if v is None:
return ""
s = str(v).strip()
if s.lower() in ("", "null", "none", "nan", "n/a", "na"):
return ""
return s if len(s) <= n else s[: n - 1] + "…"
# ══════════════════════════════════════════════════════════════════
# 1. MAIN DUCKDB (HiTeck ×7 + Flipkart ×1)
# ══════════════════════════════════════════════════════════════════
_con: Optional[duckdb.DuckDBPyConnection] = None
_con_lock = threading.Lock()
_query_lock = threading.Lock()
con_ready = threading.Event()
warmed = threading.Event()
_warm_thread_started = False
def get_con() -> duckdb.DuckDBPyConnection:
"""Lazily create + return the main DuckDB connection."""
global _con
with _con_lock:
if _con is not None:
return _con
log.info("🔧 Initializing main DuckDB...")
c = duckdb.connect(":memory:")
c.execute("INSTALL httpfs; LOAD httpfs;")
if HF_TOKEN:
try:
c.execute(f"CREATE SECRET hf (TYPE HUGGINGFACE, TOKEN '{HF_TOKEN}');")
except Exception as e:
log.warning(f"[main-con] HF secret failed: {e!r}")
c.execute("SET enable_object_cache=true;")
c.execute("SET preserve_insertion_order=false;")
c.execute("SET threads=6;")
c.execute("SET memory_limit='12GB';")
# Probe schema (warn-only)
urls = ", ".join(f"'{u}'" for u in ALL_PARQUET_URLS)
try:
c.execute(f"SELECT COUNT(*) FROM read_parquet([{urls}], union_by_name=true) WHERE 1=0")
log.info("✅ Main DuckDB ready")
except Exception as e:
log.warning(f"⚠️ Metadata probe warning: {e!r}")
_con = c
con_ready.set()
return _con
def _flipkart_clean(rec: dict) -> dict:
"""URL-decode percent-encoded Flipkart text fields."""
for k in ("name", "address", "district", "state", "town"):
v = rec.get(k)
if isinstance(v, str) and "%" in v:
try:
rec[k] = urllib.parse.unquote(v)
except Exception:
pass
return rec
def run_search_safe(phone: str,
limit: int = FETCH_LIMIT,
timeout_secs: int = QUERY_TIMEOUT) -> list:
"""
Blocking. Query HiTeck + Flipkart under a watchdog.
Returns a list of records with app14-compatible schema.
"""
con = get_con()
with _query_lock:
stop = threading.Event()
def watchdog():
if not stop.wait(timeout_secs):
log.warning(f"⏱️ DB timeout {timeout_secs}s — interrupting")
try:
con.interrupt()
except Exception as e:
log.warning(f"⚠️ interrupt() failed: {e!r}")
wd = threading.Thread(target=watchdog, daemon=True)
wd.start()
results: list = []
try:
# ── HiTeck ──
try:
urls = ", ".join(f"'{u}'" for u in PARQUET_URLS)
sql = f"""
SELECT name, fathersName, phoneNumber, aadharNumber, otherNumber,
address, district, pincode, state, town, source
FROM read_parquet([{urls}], union_by_name=true)
WHERE CAST(phoneNumber AS VARCHAR) = ?
LIMIT {int(limit)}
"""
cur = con.execute(sql, [phone])
cols = [d[0] for d in cur.description]
for r in cur.fetchall():
rec = dict(zip(cols, r))
# fill empty source with default
if not rec.get("source"):
rec["source"] = SOURCE_LABEL["hiteck"]
results.append(rec)
except duckdb.InterruptException:
raise TimeoutError(f"Search timed out after {timeout_secs}s")
except Exception as e:
log.warning(f"⚠️ HiTeck query failed for {phone}: {e!r}")
# ── Flipkart ──
try:
fk_urls = ", ".join(f"'{u}'" for u in FLIPKART_URLS)
fk_sql = f"""
SELECT
CustomerName AS name,
NULL AS fathersName,
CustomerPhone AS phoneNumber,
NULL AS aadharNumber,
NULL AS otherNumber,
CustomerAddress AS address,
CustomerCity AS district,
CustomerPincode AS pincode,
CustomerState AS state,
CustomerCity AS town,
'{SOURCE_LABEL["flipkart"]}' AS source
FROM read_parquet([{fk_urls}], union_by_name=true)
WHERE RIGHT(
REPLACE(REPLACE(REPLACE(
CAST(CustomerPhone AS VARCHAR),
' ', ''), '-', ''), '+', ''),
10
) = ?
LIMIT {int(limit)}
"""
cur = con.execute(fk_sql, [phone])
cols = [d[0] for d in cur.description]
for r in cur.fetchall():
results.append(_flipkart_clean(dict(zip(cols, r))))
except duckdb.InterruptException:
raise TimeoutError(f"Search timed out after {timeout_secs}s")
except Exception as e:
log.warning(f"⚠️ Flipkart query failed for {phone}: {e!r}")
return results
finally:
stop.set()
def warm_phone_cache() -> None:
"""Prime HF CDN + row-group cache for HiTeck + Flipkart."""
global _warm_thread_started
if warmed.is_set():
return
_warm_thread_started = True
log.info(f"🔥 Warm-up starting ({len(ALL_PARQUET_URLS)} files)...")
t0 = time.time()
loaded = skipped = 0
try:
con = get_con()
for url in ALL_PARQUET_URLS:
name = url.rsplit("/", 1)[-1]
try:
con.execute(f"SELECT * FROM read_parquet('{url}') LIMIT 1").fetchall()
loaded += 1
log.info(f" ✅ warmed: {name}")
except Exception as e:
skipped += 1
log.warning(f" ⏭️ skipped {name}: {str(e)[:120]}")
warmed.set()
log.info(f"✅ Warm-up done in {time.time()-t0:.1f}s "
f"({loaded} loaded, {skipped} skipped)")
except Exception as e:
log.error(f"⚠️ Warm-up fatal: {e!r}")
_warm_thread_started = False
# ══════════════════════════════════════════════════════════════════
# 2. ASUR DUCKDB (Inddata + single-file + 850MindData)
# Separate connection: main con.interrupt() must not kill these.
# ══════════════════════════════════════════════════════════════════
_asur_con: Optional[duckdb.DuckDBPyConnection] = None
_asur_con_lock = threading.Lock()
_asur_query_lock = threading.Lock()
def get_asur_con() -> duckdb.DuckDBPyConnection:
global _asur_con
with _asur_con_lock:
if _asur_con is not None:
return _asur_con
log.info("🔧 Initializing ASUR DuckDB...")
c = duckdb.connect(":memory:")
c.execute("INSTALL httpfs; LOAD httpfs;")
if HF_TOKEN:
try:
c.execute(f"CREATE SECRET hf (TYPE HUGGINGFACE, TOKEN '{HF_TOKEN}');")
except Exception as e:
log.warning(f"[asur-con] secret failed: {e!r}")
c.execute("SET enable_object_cache=true;")
c.execute("SET preserve_insertion_order=false;")
c.execute("SET threads=2;")
c.execute("SET memory_limit='4GB';")
_asur_con = c
log.info("✅ ASUR DuckDB ready")
return _asur_con
def _extract_aadhaar_from_row(row: dict) -> Optional[str]:
"""Best-effort extraction of aadhaar from a parquet row."""
if not row:
return None
for col in AADHAAR_COL_CANDIDATES:
v = row.get(col)
if v is None:
continue
s = str(v).strip()
if not s or s.lower() in ("null", "none", "na", "n/a"):
continue
digits = "".join(c for c in s if c.isdigit())
if len(digits) >= 10:
return digits
v = row.get("id")
if v is not None:
digits = "".join(c for c in str(v) if c.isdigit())
if len(digits) >= 10:
return digits
return None
def find_aadhaar_by_mobile(mobile: str, timeout: int = QUERY_TIMEOUT) -> dict:
"""
Blocking. Resolve aadhaar from mobile using 3 fallback datasets.
Returns: {aadhaar, source, raw_row, error?}.
"""
con = get_asur_con()
with _asur_query_lock:
stop = threading.Event()
def watchdog():
if not stop.wait(timeout):
log.warning(f"⏱️ ASUR DB timeout {timeout}s — interrupting")
try:
con.interrupt()
except Exception:
pass
threading.Thread(target=watchdog, daemon=True).start()
try:
# ── Attempt 1: Inddata/{prefix} ──
prefix = mobile[:3]
try:
q = (f"SELECT * FROM read_parquet("
f"'hf://datasets/{DATASET_INDATA}/{prefix}/*.parquet', union_by_name=true) "
f"WHERE mobile = '{mobile}' LIMIT 1")
rows = con.execute(q).fetchall()
cols = [d[0] for d in con.description] if rows else []
if rows:
row = dict(zip(cols, rows[0]))
return {
"aadhaar": _extract_aadhaar_from_row(row),
"source": f"Inddata/{prefix}",
"raw_row": row,
}
except duckdb.InterruptException:
raise TimeoutError("aadhaar lookup timeout")
except Exception as e:
log.debug(f"[find_aadhaar:Inddata] {e!r}")
# ── Attempt 2: single-file Inddata ──
try:
q = (f"SELECT * FROM read_parquet('{DATASET_SINGLE_URL}') "
f"WHERE mobile = '{mobile}' LIMIT 1")
rows = con.execute(q).fetchall()
cols = [d[0] for d in con.description] if rows else []
if rows:
row = dict(zip(cols, rows[0]))
return {
"aadhaar": _extract_aadhaar_from_row(row),
"source": "Inddatainonefile",
"raw_row": row,
}
except duckdb.InterruptException:
raise TimeoutError("aadhaar lookup timeout")
except Exception as e:
log.debug(f"[find_aadhaar:single] {e!r}")
# ── Attempt 3: 850MindData partitions ──
for p in DATASET_850_PARTS:
try:
url = (f"https://huggingface.co/datasets/{DATASET_850_REPO}"
f"/resolve/main/data/Hi-Tek_Part_{p}.parquet")
q = (f"SELECT * FROM read_parquet('{url}') "
f"WHERE CAST(mobile AS VARCHAR) = '{mobile}' LIMIT 1")
rows = con.execute(q).fetchall()
cols = [d[0] for d in con.description] if rows else []
if rows:
row = dict(zip(cols, rows[0]))
return {
"aadhaar": _extract_aadhaar_from_row(row),
"source": f"850MindData/{p}",
"raw_row": row,
}
except duckdb.InterruptException:
raise TimeoutError("aadhaar lookup timeout")
except Exception as e:
log.debug(f"[find_aadhaar:850/{p}] {e!r}")
continue
return {"aadhaar": None, "source": None, "raw_row": None, "error": "not_found"}
finally:
stop.set()
# ══════════════════════════════════════════════════════════════════
# 3. RESPONSE VALIDATION (hide dead-API rule)
# ══════════════════════════════════════════════════════════════════
def _is_valid_api_response(name: str, resp) -> bool:
"""Strict: True only if the response carries usable content."""
if not isinstance(resp, dict):
return False
if resp.get("error"):
return False
if not API_ENABLED.get(name, True):
return False
if name == "850cr":
return resp.get("success") is True and isinstance(resp.get("results"), list) and len(resp["results"]) > 0
if name == "inddata":
return resp.get("status") == "success" and isinstance(resp.get("data"), dict)
if name == "num_to_info":
return resp.get("status") == "success" and isinstance(resp.get("data"), dict)
if name == "aadhaar_to_info":
return (resp.get("status") == "success"
and isinstance(resp.get("data"), list)
and len(resp["data"]) > 0)
if name == "aadhaar_family":
return (resp.get("status") is True
and isinstance(resp.get("members"), list)
and len(resp["members"]) > 0)
if name == "aadhaar_ration":
return resp.get("status") is True and any(
resp.get(k) for k in ("head_family", "ration_number", "scheme", "address", "fps_id")
)
return False
def _record_has_content(rec: dict) -> bool:
"""A record is kept only if at least one displayable field is non-empty."""
if not isinstance(rec, dict):
return False
for key in ("name", "fathersName", "phoneNumber", "otherNumber",
"aadharNumber", "address", "district", "pincode", "state", "town"):
v = rec.get(key)
if v is None:
continue
s = str(v).strip()
if s and s.lower() not in ("null", "none", "nan", "n/a", "na"):
return True
return False
def _drop_empty_records(records: list) -> list:
return [r for r in records if _record_has_content(r)]
# ══════════════════════════════════════════════════════════════════
# 4. FAST APIs — 850CR + IndData
# ══════════════════════════════════════════════════════════════════
async def _q_cr850_raw(client: httpx.AsyncClient, number: str) -> Optional[dict]:
try:
r = await client.get(f"{API_850CR}/{number}", timeout=API_850CR_TIMEOUT)
if r.status_code != 200:
log.debug(f"[850cr] HTTP {r.status_code} for {number}")
return None
return r.json()
except Exception as e:
log.debug(f"[850cr] {e!r}")
return None
async def _q_inddata_raw(client: httpx.AsyncClient, number: str) -> Optional[dict]:
try:
r = await client.get(API_INDDATA, params={"mobile": number},
timeout=API_INDDATA_TIMEOUT)
if r.status_code != 200:
log.debug(f"[inddata] HTTP {r.status_code} for {number}")
return None
return r.json()
except Exception as e:
log.debug(f"[inddata] {e!r}")
return None
def _cr850_to_records(raw: dict, number: str) -> list:
if not _is_valid_api_response("850cr", raw):
return []
out = []
for item in raw["results"]:
addr = item.get("address") or {}
full = addr.get("full_address", "") if isinstance(addr, dict) else ""
if full:
full = full.lstrip(", ").strip()
out.append({
"name": item.get("name"),
"fathersName": item.get("father_name"),
"phoneNumber": number,
"aadharNumber": None,
"otherNumber": item.get("alternate_number"),
"address": full,
"district": None,
"pincode": None,
"state": item.get("state"),
"town": None,
"source": SOURCE_LABEL["850cr"],
})
return _drop_empty_records(out)
def _inddata_to_records(raw: dict, number: str) -> list:
if not _is_valid_api_response("inddata", raw):
return []
item = raw["data"]
if not isinstance(item, dict):
return []
rec = {
"name": item.get("name"),
"fathersName": item.get("fname"),
"phoneNumber": number,
"aadharNumber": None,
"otherNumber": item.get("alt"),
"address": item.get("address"),
"district": None,
"pincode": None,
"state": None,
"town": item.get("circle"),
"source": SOURCE_LABEL["inddata"],
}
return _drop_empty_records([rec])
async def search_fast_apis_filtered(phone: str) -> dict:
"""
Phase 1 APIs — 850CR + IndData in parallel.
Returns:
{records, source_status, raw:{"850cr":…,"inddata":…}, elapsed}
"""
t0 = time.time()
raw_850cr = raw_inddata = None
async with httpx.AsyncClient(timeout=60.0, follow_redirects=True) as client:
r850, rind = await asyncio.gather(
_q_cr850_raw(client, phone),
_q_inddata_raw(client, phone),
return_exceptions=True,
)
if isinstance(r850, dict):
raw_850cr = r850
if isinstance(rind, dict):
raw_inddata = rind
records: list = []
status: dict = {}
if _is_valid_api_response("850cr", raw_850cr):
records.extend(_cr850_to_records(raw_850cr, phone))
status["850cr"] = "ok"
elif raw_850cr is None:
status["850cr"] = "empty"
else:
status["850cr"] = "error"
if _is_valid_api_response("inddata", raw_inddata):
records.extend(_inddata_to_records(raw_inddata, phone))
status["inddata"] = "ok"
elif raw_inddata is None:
status["inddata"] = "empty"
else:
status["inddata"] = "error"
return {
"records": _drop_empty_records(records),
"source_status": status,
"raw": {"850cr": raw_850cr, "inddata": raw_inddata},
"elapsed": time.time() - t0,
}
# ══════════════════════════════════════════════════════════════════
# 5. ASURPAPA APIs (a12pp.py)
# ══════════════════════════════════════════════════════════════════
async def fetch_asurpapa_all(mobile: str, aadhaar: Optional[str]) -> dict:
"""Fetch num_to_info + 3 aadhaar endpoints in parallel."""
results: dict = {}
async with httpx.AsyncClient(timeout=ASUR_HTTP_TIMEOUT) as cli:
# ── 1. num_to_info (always) ──
if API_ENABLED.get("num_to_info", True):
try:
r = await cli.get(
ASUR_API["num_to_info"],
params={"key": ASUR_KEY, "number": mobile},
)
results["num_to_info"] = r.json()
except Exception as e:
results["num_to_info"] = {"error": str(e)}
else:
results["num_to_info"] = {"error": "disabled"}
# ── 2-4. aadhaar APIs (only if aadhaar resolved) ──
if not aadhaar:
for k in ("aadhaar_to_info", "aadhaar_family", "aadhaar_ration"):
results[k] = {"error": "skipped: no aadhaar resolved"}
return results
async def _call(name: str):
if not API_ENABLED.get(name, True):
return name, {"error": "disabled"}
try:
r = await cli.get(
ASUR_API[name],
params={"key": ASUR_KEY, ASUR_PARAM_NAMES[name]: aadhaar},
)
return name, r.json()
except Exception as e:
return name, {"error": str(e)}
gathered = await asyncio.gather(
_call("aadhaar_to_info"),
_call("aadhaar_family"),
_call("aadhaar_ration"),
return_exceptions=False,
)
for name, res in gathered:
results[name] = res
return results
def _asur_num_to_info_to_records(raw: dict, mobile: str) -> list:
if not _is_valid_api_response("num_to_info", raw):
return []
d = raw["data"]
rec = {
"name": d.get("name"),
"fathersName": d.get("fname"),
"phoneNumber": mobile,
"aadharNumber": None,
"otherNumber": d.get("alt"),
"address": d.get("address"),
"district": None,
"pincode": None,
"state": None,
"town": d.get("circle"),
"source": SOURCE_LABEL["asur_num"],
}
return _drop_empty_records([rec])
def _asur_aadhaar_to_info_to_records(raw: dict) -> list:
if not _is_valid_api_response("aadhaar_to_info", raw):
return []
out = []
for item in raw["data"]:
if not isinstance(item, dict):
continue
out.append({
"name": item.get("name"),
"fathersName": None,
"phoneNumber": item.get("phoneNumber"),
"aadharNumber": None,
"otherNumber": None,
"address": None,
"district": None,
"pincode": None,
"state": None,
"town": None,
"source": SOURCE_LABEL["asur_aadhaar"],
})
return _drop_empty_records(out)
def _format_asur_extras(aadhaar_res: dict, api_results: dict) -> str:
"""Build the ASURPAPA HTML extras block (family / ration / email / etc.).
Returns "" if nothing valid to show."""
lines: List[str] = []
aad = aadhaar_res.get("aadhaar")
if aad:
masked = "XXXX-XXXX-" + aad[-4:]
lines.append(f"🆔 <b>Aadhaar:</b> <code>{masked}</code> "
f"<i>(via {esc(aadhaar_res.get('source') or '?')})</i>")
# Extra fields from num_to_info not visible in records
nti = api_results.get("num_to_info")
if _is_valid_api_response("num_to_info", nti):
d = nti["data"]
extras = []
if d.get("email"):
extras.append(f"📧 {esc(d['email'])}")
if d.get("alt"):
extras.append(f"📱 Alt: {esc(d['alt'])}")
if d.get("circle"):
extras.append(f"🌐 {esc(d['circle'])}")
if extras:
lines.append(" · ".join(extras))
fam = api_results.get("aadhaar_family")
if _is_valid_api_response("aadhaar_family", fam):
members = fam.get("members") or []
if members:
lines.append(f"👨👩👧 <b>Family ({len(members)}):</b>")
for m in members[:5]:
lines.append(
f" • {esc(m.get('name') or '?')} "
f"({esc(m.get('relation') or '?')})"
)
if len(members) > 5:
lines.append(f" <i>… and {len(members) - 5} more</i>")
rat = api_results.get("aadhaar_ration")
if _is_valid_api_response("aadhaar_ration", rat):
bits = []
if rat.get("head_family"):
bits.append(f"👤 {esc(rat['head_family'])}")
if rat.get("ration_number"):
bits.append(f"🔢 <code>{esc(rat['ration_number'])}</code>")
if rat.get("scheme"):
bits.append(f"📋 {esc(rat['scheme'])}")
if rat.get("fps_id"):
bits.append(f"🆔 {esc(rat['fps_id'])}")
if bits:
lines.append("🍚 <b>Ration:</b> " + " · ".join(bits))
if not lines:
return ""
return "🪪 <b>ASURPAPA Details</b>\n" + "\n".join(lines)
async def asur_lookup_filtered(phone: str) -> dict:
"""
Phase 2 — Resolve aadhaar (blocking → thread), then call 4 ASUR APIs.
Returns: {records, extras, aadhaar_res, api_results, source_status, elapsed}
"""
t0 = time.time()
# ── 1. Resolve aadhaar ──
aadhaar_res = {"aadhaar": None, "source": None, "raw_row": None}
try:
aadhaar_res = await asyncio.to_thread(find_aadhaar_by_mobile, phone)
except Exception as e:
log.warning(f"[asur] aadhaar resolution failed: {e!r}")
aadhaar_res["error"] = str(e)
# ── 2. Fetch APIs ──
api_results: dict = {}
try:
api_results = await fetch_asurpapa_all(phone, aadhaar_res.get("aadhaar"))
except Exception as e:
log.warning(f"[asur] api batch failed: {e!r}")
# ── 3. Filter + convert ──
records: list = []
status: dict = {}
for name, raw_key, converter in (
("num_to_info", "num_to_info", lambda r: _asur_num_to_info_to_records(r, phone)),
("aadhaar_to_info", "aadhaar_to_info", _asur_aadhaar_to_info_to_records),
):
raw = api_results.get(raw_key)
if _is_valid_api_response(name, raw):
records.extend(converter(raw))
status[f"asur_{name}"] = "ok"
elif raw is None:
status[f"asur_{name}"] = "empty"
elif isinstance(raw, dict) and "skipped" in str(raw.get("error", "")).lower():
status[f"asur_{name}"] = "skipped"
else:
status[f"asur_{name}"] = "error"
# family + ration status only (records go into extras)
for name in ("aadhaar_family", "aadhaar_ration"):
raw = api_results.get(name)
if _is_valid_api_response(name, raw):
status[f"asur_{name}"] = "ok"
elif raw is None:
status[f"asur_{name}"] = "empty"
elif isinstance(raw, dict) and "skipped" in str(raw.get("error", "")).lower():
status[f"asur_{name}"] = "skipped"
else:
status[f"asur_{name}"] = "error"
# ── 4. Extras ──
extras = _format_asur_extras(aadhaar_res, api_results)
return {
"records": _drop_empty_records(records),
"extras": extras,
"aadhaar_res": aadhaar_res,
"api_results": api_results,
"source_status": status,
"elapsed": time.time() - t0,
}
# ══════════════════════════════════════════════════════════════════
# 6. COMBINED API SEARCH (convenience for tests / batch)
# ══════════════════════════════════════════════════════════════════
async def search_apis_filtered(phone: str) -> dict:
"""Run fast + ASUR in parallel, merge into one dict."""
fast_task = asyncio.create_task(search_fast_apis_filtered(phone))
asur_task = asyncio.create_task(asur_lookup_filtered(phone))
fast, asur = await asyncio.gather(fast_task, asur_task, return_exceptions=True)
if isinstance(fast, Exception):
log.warning(f"[search_apis_filtered] fast failed: {fast!r}")
fast = {"records": [], "source_status": {}, "raw": {}, "elapsed": 0.0}
if isinstance(asur, Exception):
log.warning(f"[search_apis_filtered] asur failed: {asur!r}")
asur = {"records": [], "extras": "", "aadhaar_res": {},
"api_results": {}, "source_status": {}, "elapsed": 0.0}
return {
"records": fast["records"] + asur["records"],
"extras": asur["extras"],
"aadhaar_res": asur["aadhaar_res"],
"api_results": {**fast.get("raw", {}), **asur.get("api_results", {})},
"source_status": {**fast.get("source_status", {}), **asur.get("source_status", {})},
"elapsed": max(fast.get("elapsed", 0.0), asur.get("elapsed", 0.0)),
}
# Legacy: return only the records list (used by batch in bot.py)
async def search_apis(phone: str) -> list:
result = await search_apis_filtered(phone)
return result["records"]
# ══════════════════════════════════════════════════════════════════
# 7. DEDUPLICATION
# ══════════════════════════════════════════════════════════════════
def _norm(s) -> str:
if not s:
return ""
return re.sub(r"\s+", " ", str(s).strip().lower())
def _dedup_key(rec: dict):
name = _norm(rec.get("name"))
father = _norm(rec.get("fathersName"))
addr = _norm(rec.get("address"))
addr_n = re.sub(r"[^a-z0-9]+", " ", addr).strip()
if name and addr_n:
return ("na", name, addr_n)
if name and father:
return ("nf", name, father)
if addr_n:
return ("a", addr_n)
return None
def dedup_records(records: list) -> list:
"""Keep the richest record per key."""
seen: dict = {}
result: list = []
for rec in records:
if not isinstance(rec, dict):
continue
key = _dedup_key(rec)
if key is None:
result.append(rec)
continue
idx = seen.get(key)
if idx is None:
seen[key] = len(result)
result.append(rec)
else:
existing = result[idx]
ef = sum(1 for v in existing.values() if v)
nf = sum(1 for v in rec.values() if v)
if nf > ef:
result[idx] = rec
return result
# ══════════════════════════════════════════════════════════════════
# 8. FORMATTING
# ══════════════════════════════════════════════════════════════════
def format_result(idx: int, row: dict) -> str:
lines = [f"<b>━━━ #{idx} ━━━</b>"]
for key, emoji, label in FIELD_LABELS:
v = _tv(row.get(key), TRUNC.get(key, 60))
if v:
lines.append(f"{emoji} <b>{label}:</b> <code>{esc(v)}</code>")
return "\n".join(lines)
def _plain_record(idx: int, row: dict) -> str:
lines = [f"#{idx}"]
for key, _emoji, label in FIELD_LABELS:
v = _tv(row.get(key), TRUNC.get(key, 60))
if v:
lines.append(f"{label}: {v}")
return "\n".join(lines)
def render_page(results: list, page: int, total_pages: int, phone: str,
elapsed: float, source_note: str = "",
extras_block: str = "") -> str:
"""Render one page. Extras block shown only on page 0."""
start = page * PAGE_SIZE
chunk = results[start:start + PAGE_SIZE]
head = (
f"📱 <b>Phone:</b> <code>{esc(phone)}</code>\n"
f"📄 <b>Page {page+1}/{total_pages}</b> · "
f"{len(results)} result(s) · ⏱️ {elapsed:.1f}s"
)
if source_note:
head += f"\n⚠️ <i>{esc(source_note)}</i>"
parts: List[str] = [head]
if extras_block and page == 0:
parts.append(extras_block)
if chunk:
body = "\n\n".join(format_result(start + i + 1, r) for i, r in enumerate(chunk))
parts.append(body)
else:
parts.append("<i>No records to display.</i>")
return "\n\n".join(parts)
# ══════════════════════════════════════════════════════════════════
# 9. INPUT NORMALIZATION
# ══════════════════════════════════════════════════════════════════
def normalize_phone(text: str) -> tuple[Optional[str], Optional[str]]:
raw = text.strip()
digits = "".join(ch for ch in raw if ch.isdigit())
if not digits:
return None, "not a valid number"
if len(digits) == 11 and digits.startswith("0"):
digits = digits[1:]
if len(digits) == 12 and digits.startswith("91"):
digits = digits[2:]
elif len(digits) == 11 and digits.startswith("91"):
digits = digits[1:]
if len(digits) == 10:
if PHONE_REGEX.match(digits):
return digits, None
return None, "not a valid 10-digit number"
return None, f"expected 10 digits, got {len(digits)}"
# ══════════════════════════════════════════════════════════════════
# 10. API HEALTH CHECK (used by web panel + /apistatus)
# ══════════════════════════════════════════════════════════════════
async def check_api_health() -> dict:
"""Ping each API with a harmless test number. Returns per-endpoint status."""
results: dict = {}
TEST_NUM = "9999999999"
async def _probe(name: str, coro_factory):
t0 = time.time()
try:
ok = await coro_factory()
results[name] = {
"ok": ok,
"latency_ms": int((time.time() - t0) * 1000),
}
except Exception as e:
results[name] = {
"ok": False,
"error": str(e)[:100],
"latency_ms": int((time.time() - t0) * 1000),
}
async with httpx.AsyncClient(timeout=API_HEALTH_TIMEOUT) as client:
async def p_850cr():
r = await client.get(f"{API_850CR}/{TEST_NUM}")
return r.status_code in (200, 404)
async def p_inddata():
r = await client.get(API_INDDATA, params={"mobile": TEST_NUM})
return r.status_code == 200
async def p_asur(name: str):
r = await client.get(
ASUR_API[name],
params={"key": ASUR_KEY, ASUR_PARAM_NAMES[name]: TEST_NUM},
)
return r.status_code == 200
await asyncio.gather(
_probe("850cr", p_850cr),
_probe("inddata", p_inddata),
_probe("asur_num_to_info", lambda: p_asur("num_to_info")),
_probe("asur_aadhaar_to_info", lambda: p_asur("aadhaar_to_info")),
_probe("asur_aadhaar_family", lambda: p_asur("aadhaar_family")),
_probe("asur_aadhaar_ration", lambda: p_asur("aadhaar_ration")),
)
return results
# ══════════════════════════════════════════════════════════════════
# 11. ASUR WARM-UP (optional — primes aadhaar resolution)
# ══════════════════════════════════════════════════════════════════
def warm_asur_cache() -> None:
try:
t0 = time.time()
con = get_asur_con()
con.execute(
f"SELECT mobile FROM read_parquet("
f"'hf://datasets/{DATASET_INDATA}/0*/*.parquet', union_by_name=true) LIMIT 1"
).fetchall()
log.info(f"🔥 ASUR cache warmed in {time.time()-t0:.1f}s")
except Exception as e:
log.warning(f"⚠️ ASUR warm failed: {e!r}")
# ══════════════════════════════════════════════════════════════════
# SELF-TEST (python engine.py)
# ══════════════════════════════════════════════════════════════════
if __name__ == "__main__":
logging.basicConfig(level=logging.INFO,
format="%(asctime)s %(levelname)s %(message)s")
print("── normalize_phone tests ──")
for raw in ("9876543210", "+91 98765 43210", "09876543210",
"919876543210", "12345", "abc"):
print(f" {raw!r:25} → {normalize_phone(raw)}")
print("\n── dedup tests ──")
sample = [
{"name": "A", "address": "X", "source": "HiTeck"},
{"name": "a", "address": "x", "source": "Flipkart"}, # dup
{"name": "", "address": "", "source": "ASUR NumInfo"}, # empty → dropped
]
print(" before:", len(sample))
print(" after :", len(dedup_records(sample)), dedup_records(sample))
print("\n── asyncio: asur_lookup_filtered (live) ──")
async def _smoke():
r = await asur_lookup_filtered("9999999999")
print(f" records={len(r['records'])} extras={bool(r['extras'])} "
f"status={r['source_status']} elapsed={r['elapsed']:.1f}s")
try:
asyncio.run(_smoke())
except Exception as e:
print(f" skipped: {e!r}") |