ziddi shop Kzr0xx commited on
Commit
bc887c8
·
0 Parent(s):

Duplicate from Kzr0xx/icrm-hitek-full-db-mixed

Browse files

Co-authored-by: Kzr0x <Kzr0xx@users.noreply.huggingface.co>

.gitattributes ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.avro filter=lfs diff=lfs merge=lfs -text
4
+ *.bin filter=lfs diff=lfs merge=lfs -text
5
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
6
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
7
+ *.ftz filter=lfs diff=lfs merge=lfs -text
8
+ *.gz filter=lfs diff=lfs merge=lfs -text
9
+ *.h5 filter=lfs diff=lfs merge=lfs -text
10
+ *.joblib filter=lfs diff=lfs merge=lfs -text
11
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
12
+ *.lz4 filter=lfs diff=lfs merge=lfs -text
13
+ *.mds filter=lfs diff=lfs merge=lfs -text
14
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
15
+ *.model filter=lfs diff=lfs merge=lfs -text
16
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
17
+ *.npy filter=lfs diff=lfs merge=lfs -text
18
+ *.npz filter=lfs diff=lfs merge=lfs -text
19
+ *.onnx filter=lfs diff=lfs merge=lfs -text
20
+ *.ot filter=lfs diff=lfs merge=lfs -text
21
+ *.parquet filter=lfs diff=lfs merge=lfs -text
22
+ *.pb filter=lfs diff=lfs merge=lfs -text
23
+ *.pickle filter=lfs diff=lfs merge=lfs -text
24
+ *.pkl filter=lfs diff=lfs merge=lfs -text
25
+ *.pt filter=lfs diff=lfs merge=lfs -text
26
+ *.pth filter=lfs diff=lfs merge=lfs -text
27
+ *.rar filter=lfs diff=lfs merge=lfs -text
28
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
29
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
30
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
31
+ *.tar filter=lfs diff=lfs merge=lfs -text
32
+ *.tflite filter=lfs diff=lfs merge=lfs -text
33
+ *.tgz filter=lfs diff=lfs merge=lfs -text
34
+ *.wasm filter=lfs diff=lfs merge=lfs -text
35
+ *.xz filter=lfs diff=lfs merge=lfs -text
36
+ *.zip filter=lfs diff=lfs merge=lfs -text
37
+ *.zst filter=lfs diff=lfs merge=lfs -text
38
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
39
+ # Audio files - uncompressed
40
+ *.pcm filter=lfs diff=lfs merge=lfs -text
41
+ *.sam filter=lfs diff=lfs merge=lfs -text
42
+ *.raw filter=lfs diff=lfs merge=lfs -text
43
+ # Audio files - compressed
44
+ *.aac filter=lfs diff=lfs merge=lfs -text
45
+ *.flac filter=lfs diff=lfs merge=lfs -text
46
+ *.mp3 filter=lfs diff=lfs merge=lfs -text
47
+ *.ogg filter=lfs diff=lfs merge=lfs -text
48
+ *.wav filter=lfs diff=lfs merge=lfs -text
49
+ # Image files - uncompressed
50
+ *.bmp filter=lfs diff=lfs merge=lfs -text
51
+ *.gif filter=lfs diff=lfs merge=lfs -text
52
+ *.png filter=lfs diff=lfs merge=lfs -text
53
+ *.tiff filter=lfs diff=lfs merge=lfs -text
54
+ # Image files - compressed
55
+ *.jpg filter=lfs diff=lfs merge=lfs -text
56
+ *.jpeg filter=lfs diff=lfs merge=lfs -text
57
+ *.webp filter=lfs diff=lfs merge=lfs -text
58
+ # Video files - compressed
59
+ *.mp4 filter=lfs diff=lfs merge=lfs -text
60
+ *.webm filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: mit
3
+ ---
4
+
5
+ # ICMR + HITEK Full DB (Mixed) — Prebuilt Indexes + One-Click Setup
6
+
7
+ Prebuilt sorted indexes for the [Kzr0xx/Icmr-and-hitek](https://huggingface.co/datasets/Kzr0xx/Icmr-and-hitek) dataset (2.5B rows, 11 columns, ~104 GB raw parquet).
8
+
9
+ Building these indexes took **~17 hours** of compute. This repo saves you that work: download + run = API live in ~1-2 hours (download speed dependent).
10
+
11
+ ## Contents
12
+
13
+ The indexes are stored as **sorted parts** (each < 50 GB, split at row-group boundaries, order preserved) because HuggingFace's classic HTTP upload path caps files at 50 GB. The API reads all parts of an index with one glob — zone-map pruning still makes lookups milliseconds-fast.
14
+
15
+ | Files | Total | What |
16
+ |---|---|---|
17
+ | `idx_phone.0.parquet` … `idx_phone.6.parquet` | ~102 GB | Data sorted by phoneNumber → phone lookups ~1s |
18
+ | `idx_aadhar.0.parquet` … `idx_aadhar.6.parquet` | ~100 GB | Data sorted by aadharNumber → aadhar lookups ~2s |
19
+ | `main.py` | — | FastAPI app (DuckDB-backed, 15-way parallel, dedup max 2) |
20
+ | `build_index.py` | — | Rebuild indexes from raw parquet (only if you ever need to) |
21
+ | `split_idx.py` | — | Split a built index into < 50 GB parts |
22
+ | `setup.bat` | — | One-click restore (Windows) |
23
+ | `setup.ps1` | — | One-click restore (PowerShell) |
24
+ | `setup.sh` | — | One-click restore (Linux / VPS) |
25
+
26
+ Raw data files (`part1.parquet`, `part2a.parquet`, `part2b_new.parquet`, 104 GB) live in the **Icmr-and-hitek** repo — the setup scripts download them from there automatically.
27
+
28
+ ## One-click restore
29
+
30
+ Pick your platform, run ONE file. It downloads data + indexes + code, creates a venv, installs deps, starts the API.
31
+
32
+ **Windows:** double-click `setup.bat`
33
+ **PowerShell:** right-click → Run with PowerShell, or `powershell -ExecutionPolicy Bypass -File setup.ps1`
34
+ **Linux/VPS:**
35
+ ```bash
36
+ chmod +x setup.sh
37
+ ./setup.sh
38
+ ```
39
+
40
+ Total download: ~305 GB (104 GB data + ~200 GB index parts). Scripts resume interrupted downloads (`curl -C -`), so a dropped connection is not a problem — just re-run.
41
+
42
+ ## API
43
+
44
+ Base: `http://127.0.0.1:8001` (Linux: `0.0.0.0:8001`)
45
+
46
+ | Endpoint | Use |
47
+ |---|---|
48
+ | `GET /search?q=<phone>` | Phone search — **~1s** (indexed) |
49
+ | `GET /search?q=<aadhar>` | Aadhar search — **~2s** (indexed) |
50
+ | `GET /search?q=<name>&limit=10` | Name/text search (falls back to raw scan, slower) |
51
+ | `GET /search?q=X&field=district&mode=exact` | Single-field search |
52
+ | `POST /search/parallel` | Batch: up to 50 searches in parallel |
53
+ | `GET /health` | Status incl. which indexes are active |
54
+ | `GET /docs` | Interactive Swagger UI |
55
+
56
+ All 11 columns searchable: name, fathersName, phoneNumber, aadharNumber, otherNumber, address, district, pincode, state, town, source. Duplicates capped at 2 per person. `source` = `icmr` | `inddata` (hitek data is labelled inddata).
57
+
58
+ ## Manual start (if scripts already ran)
59
+
60
+ ```bash
61
+ # Windows
62
+ cd /d "C:\path\to\folder"
63
+ start "" .venv\Scripts\python.exe -m uvicorn main:app --host 127.0.0.1 --port 8001
64
+
65
+ # Linux
66
+ cd /path/to/folder
67
+ ICMR_DATA_DIR="$PWD/data" nohup .venv/bin/python -m uvicorn main:app --host 0.0.0.0 --port 8001 > api.log 2>&1 &
68
+ ```
69
+
70
+ `ICMR_DATA_DIR` points at the `data/` folder; if it is not set, `data/` next to `main.py` is used. `main.py` auto-detects index parts (`idx_phone.*.parquet`) — no config needed.
71
+
72
+ ## Rebuilding indexes (rarely needed)
73
+
74
+ ```bash
75
+ ICMR_DATA_DIR="$PWD/data" .venv/bin/python build_index.py
76
+ ```
77
+ Each index takes 6-11 hours on a typical machine. After building, `split_idx.py` can split them into upload-sized parts again.
build_index.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Build sorted parquet index copies so DuckDB zone-map pruning makes lookups fast.
2
+
3
+ Unsorted 104GB parquet forces a full scan (~90s) per query. A copy sorted by the
4
+ search key lets DuckDB skip all but the matching row groups (ms-level lookups).
5
+
6
+ Creates (skips files that already exist -> resumable):
7
+ idx_phone.parquet - sorted by phoneNumber
8
+ idx_aadhar.parquet - sorted by aadharNumber
9
+ idx_name.parquet - sorted by name
10
+ """
11
+ import duckdb
12
+ import os
13
+ import time
14
+
15
+ FILES = ["part1.parquet", "part2a.parquet", "part2b_new.parquet"]
16
+ FILES_SQL = ", ".join(f"'{f}'" for f in FILES)
17
+
18
+ def build(con, field: str, out: str):
19
+ if os.path.exists(out) and os.path.getsize(out) > 0:
20
+ print(f"{out} already exists, skipping", flush=True)
21
+ return
22
+ print(f"START {out} (sort by {field})", flush=True)
23
+ t = time.time()
24
+ con.execute(f"""
25
+ COPY (SELECT * FROM people ORDER BY {field} NULLS LAST)
26
+ TO '{out}' (FORMAT PARQUET, COMPRESSION ZSTD)
27
+ """)
28
+ print(f"DONE {out} in {time.time()-t:.1f}s", flush=True)
29
+
30
+ con = duckdb.connect()
31
+ con.execute("INSTALL parquet; LOAD parquet;")
32
+ con.execute("SET threads = 12")
33
+ con.execute("SET memory_limit = '27GB'")
34
+ con.execute(f"CREATE VIEW people AS SELECT * FROM read_parquet([{FILES_SQL}])")
35
+
36
+ build(con, "phoneNumber", "idx_phone.parquet")
37
+ build(con, "aadharNumber", "idx_aadhar.parquet")
38
+ build(con, "name", "idx_name.parquet")
39
+ print("ALL DONE", flush=True)
idx_aadhar.0.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1d30e32b5884fa366e8283ceca08fe97e4ce11783098439a86f30742af870e85
3
+ size 16856203726
idx_aadhar.1.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:23ae9c6458c9dc92608f68e5cf1034d7f889ec820f50638c6425604fbc3af0f7
3
+ size 15716468686
idx_aadhar.2.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:eb3a2aed1f01958a6817d471900c8573a8480ef0ed8a4839043a7d2087dedd72
3
+ size 15701861469
idx_aadhar.3.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:262dd17d014c2d191e77321f98f264f295a2ca25ea6c3d32e18817828926c95e
3
+ size 15702907795
idx_aadhar.4.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ff2b70012c8eda1394e5cc77ed85621245433ec88e59ef8f8adb5aada99eac89
3
+ size 21250330138
idx_aadhar.5.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bc76e2a67857e7cd9e8c24c7a803a5d8e67c659f85ef1aa968b27032d7729bfa
3
+ size 26123380421
idx_aadhar.6.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d047df27b2b91e2f61e25392ab2e3fb0f97d3523c9411d1a9f119b122a39cf01
3
+ size 11730300913
idx_phone.0.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c308a3bd32384546a3a64ad766a50003ff62d7a52d34537c5d0a05bff0b9b6e5
3
+ size 17050842079
idx_phone.1.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ae1a39a2fecb5484fda3ab8fb861caf506c021986827734b2c4183f3c4b39f48
3
+ size 16672917498
idx_phone.2.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c1bfe865a0e40475b12bf1d275d5dbad556426064d36f1b2d7a1f2ab04d7d6d4
3
+ size 16592087348
idx_phone.3.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9e22b118321237ec583f2f4de3f956fb66a68a2f92af1ebea6418489412d322c
3
+ size 17107452500
idx_phone.4.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6eaddca4bb538638243415c131531d6b9dd318cb9860265111f4ea8929c3b38e
3
+ size 16886880219
idx_phone.5.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:34f8083b4daffb93af1f9a79290592b981589514bc96660ffb7115e27e6c7971
3
+ size 16489637305
idx_phone.6.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2df73634c0ad9561691f8e5e988c2901b180a1119505a72e7349ea6a68e2320a
3
+ size 3210381696
main.py ADDED
@@ -0,0 +1,314 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """FastAPI backend over DuckDB - ICMR + HITEK combined dataset (2.5B rows, 11 cols).
2
+
3
+ Index-aware routing:
4
+ - idx_phone.parquet (sorted by phoneNumber) -> fast exact phone/other lookups
5
+ - idx_aadhar.parquet (sorted by aadharNumber) -> fast exact aadhar lookups
6
+ - idx_name.parquet (sorted by name) -> fast name prefix/exact
7
+ - Falls back to full scans of raw parquet while indexes are still building.
8
+ Dedup: max 2 rows per person. source column included (icmr / inddata "connected docs").
9
+ """
10
+ import asyncio
11
+ import glob
12
+ import json
13
+ import os
14
+ import threading
15
+ from concurrent.futures import ThreadPoolExecutor
16
+ from typing import Any
17
+
18
+ import duckdb
19
+ from fastapi import FastAPI, HTTPException, Query, Response
20
+ from pydantic import BaseModel
21
+
22
+ BASE = os.path.dirname(os.path.abspath(__file__))
23
+ # data files may live in BASE or BASE/data (setup scripts download into data/)
24
+ _DATA_DIR = os.environ.get("ICMR_DATA_DIR") or \
25
+ (os.path.join(BASE, "data") if os.path.isdir(os.path.join(BASE, "data")) else BASE)
26
+ PARQUET_FILES = [os.path.join(_DATA_DIR, f) for f in
27
+ ["part1.parquet", "part2a.parquet", "part2b_new.parquet"]]
28
+ IDX_PHONE = os.path.join(_DATA_DIR, "idx_phone.parquet")
29
+ IDX_AADHAR = os.path.join(_DATA_DIR, "idx_aadhar.parquet")
30
+ IDX_NAME = os.path.join(_DATA_DIR, "idx_name.parquet")
31
+ PARALLELISM = int(os.environ.get("ICMR_PARALLEL", "15"))
32
+ THREADS_PER_CONN = int(os.environ.get("ICMR_THREADS_PER_CONN", "8"))
33
+ DUPLICATE_CAP = 2 # max 2 copies of the same person in results
34
+
35
+ SEARCH_FIELDS = [
36
+ "name", "fathersName", "phoneNumber", "aadharNumber", "otherNumber",
37
+ "address", "district", "pincode", "state", "town", "source",
38
+ ]
39
+ NUMBER_FIELDS = ["phoneNumber", "aadharNumber", "otherNumber"]
40
+
41
+ app = FastAPI(title="ICMR + HITEK Search API",
42
+ description="DuckDB-backed search over 2.5B records (11 cols, dedup max 2)")
43
+
44
+ # ---- DuckDB connection pool (one connection per worker thread) ----
45
+ _conns: list[duckdb.DuckDBPyConnection] = []
46
+ _conns_lock = threading.Lock()
47
+ _thread_local = threading.local()
48
+ pool = ThreadPoolExecutor(max_workers=PARALLELISM, thread_name_prefix="duck")
49
+
50
+ _MISSING = [f for f in PARQUET_FILES if not os.path.exists(f)]
51
+
52
+
53
+ def _idx_files(path: str) -> list[str]:
54
+ """Index may be a single file or split into sorted parts (idx_phone.0.parquet...)."""
55
+ base, ext = os.path.splitext(path) # idx_phone.parquet -> idx_phone / .parquet
56
+ parts = sorted(glob.glob(f"{base}.*{ext}"))
57
+ if parts and all(os.path.getsize(p) > 0 for p in parts):
58
+ return parts
59
+ return [path] if os.path.exists(path) and os.path.getsize(path) > 0 else []
60
+
61
+
62
+ def _idx_ready(path: str) -> bool:
63
+ # index is usable when: file(s) exist+non-empty AND not caught mid-build
64
+ # (build writes in place, so a START without DONE in the log = partial file)
65
+ if not _idx_files(path):
66
+ return False
67
+ try:
68
+ with open(os.path.join(BASE, "build_index.log"), encoding="utf-8",
69
+ errors="ignore") as f:
70
+ log = f.read()
71
+ except OSError:
72
+ log = "" # no log (fresh download) -> trust the downloaded file
73
+ name = os.path.basename(path)
74
+ if f"DONE {name}" in log:
75
+ return True
76
+ if f"START {name}" in log:
77
+ return False # build in progress / was interrupted -> partial
78
+ return True # no build ever started here -> file was downloaded whole
79
+
80
+
81
+ def _new_conn() -> duckdb.DuckDBPyConnection:
82
+ con = duckdb.connect() # in-memory
83
+ con.execute("INSTALL parquet; LOAD parquet;")
84
+ files = ", ".join(f"'{f}'" for f in PARQUET_FILES if os.path.exists(f))
85
+ con.execute(f"CREATE VIEW people AS SELECT * FROM read_parquet([{files}])")
86
+ # sorted index views (only if built) - zone-map pruning makes lookups fast
87
+ for idx_path, view in [(IDX_PHONE, "people_phone"),
88
+ (IDX_AADHAR, "people_aadhar"),
89
+ (IDX_NAME, "people_name")]:
90
+ files = _idx_files(idx_path)
91
+ if files and _idx_ready(idx_path):
92
+ lst = ", ".join(f"'{f}'" for f in files)
93
+ con.execute(f"CREATE VIEW {view} AS SELECT * FROM read_parquet([{lst}])")
94
+ con.execute(f"SET threads = {THREADS_PER_CONN}")
95
+ return con
96
+
97
+
98
+ def _thread_id() -> int:
99
+ tid = getattr(_thread_local, "id", None)
100
+ if tid is None:
101
+ with _conns_lock:
102
+ tid = len(_conns)
103
+ _thread_local.id = tid
104
+ return tid
105
+
106
+
107
+ def _get_conn() -> duckdb.DuckDBPyConnection:
108
+ ident = _thread_id()
109
+ with _conns_lock:
110
+ while len(_conns) <= ident:
111
+ _conns.append(_new_conn())
112
+ return _conns[ident]
113
+
114
+
115
+ # ---- Dedup: max 2 copies per person ----
116
+ def _person_key(row: dict[str, Any]) -> tuple[str, ...]:
117
+ ph = (row.get("phoneNumber") or "").strip()
118
+ ad = (row.get("aadharNumber") or "").strip()
119
+ if ph or ad:
120
+ return (ph, ad)
121
+ return (row.get("name") or "").strip(), (row.get("fathersName") or "").strip()
122
+
123
+
124
+ def _cap_duplicates(rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
125
+ """Keep at most DUPLICATE_CAP rows per person (same phone+aadhar identity)."""
126
+ seen: dict[tuple[str, ...], int] = {}
127
+ out: list[dict[str, Any]] = []
128
+ for r in rows:
129
+ k = _person_key(r)
130
+ n = seen.get(k, 0)
131
+ if n < DUPLICATE_CAP:
132
+ seen[k] = n + 1
133
+ out.append(r)
134
+ return out
135
+
136
+
137
+ # ---- Query helpers ----
138
+ def _run_sql(sql: str) -> list[dict[str, Any]]:
139
+ con = _get_conn()
140
+ rows = con.execute(sql).fetchall()
141
+ cols = [d[0] for d in con.description]
142
+ return [dict(zip(cols, r)) for r in rows]
143
+
144
+
145
+ def _source_clause(source: str | None) -> str:
146
+ if source and source in ("icmr", "hitek", "inddata"):
147
+ src = "hitek" if source == "hitek" else source
148
+ return f" AND source = '{src}'"
149
+ return ""
150
+
151
+
152
+ def _exact_scan(field: str, value: str, limit: int, source: str | None = None) -> str:
153
+ v = value.replace("'", "''")
154
+ return (f"SELECT * FROM people WHERE {field} = '{v}'"
155
+ f"{_source_clause(source)} LIMIT {limit * DUPLICATE_CAP + 20}")
156
+
157
+
158
+ def _run_field_search(field: str, value: str, mode: str, limit: int,
159
+ source: str | None = None) -> dict[str, Any]:
160
+ if field not in SEARCH_FIELDS:
161
+ raise ValueError(f"Unknown field: {field}")
162
+ v = value.replace("'", "''")
163
+ view = "people"
164
+ # use sorted index view when available for the hot fields
165
+ if mode == "exact":
166
+ if field == "phoneNumber" and _idx_ready(IDX_PHONE):
167
+ view = "people_phone"
168
+ elif field == "aadharNumber" and _idx_ready(IDX_AADHAR):
169
+ view = "people_aadhar"
170
+ elif field == "name" and _idx_ready(IDX_NAME):
171
+ view = "people_name"
172
+ sql = (f"SELECT * FROM {view} WHERE {field} = '{v}'"
173
+ f"{_source_clause(source)} LIMIT {limit * DUPLICATE_CAP + 20}")
174
+ elif mode == "contains":
175
+ if field == "name" and _idx_ready(IDX_NAME):
176
+ view = "people_name" # sorted helps prefix; contains still scans but cached
177
+ v2 = v.replace("%", r"\%").replace("_", r"\_")
178
+ sql = (f"SELECT * FROM {view} WHERE {field} ILIKE '%{v2}%' ESCAPE '\\'"
179
+ f"{_source_clause(source)} LIMIT {limit * DUPLICATE_CAP + 20}")
180
+ else:
181
+ raise ValueError(f"Unknown mode: {mode}")
182
+ con = _get_conn()
183
+ rows = con.execute(sql).fetchall()
184
+ cols = [d[0] for d in con.description]
185
+ results = _cap_duplicates([dict(zip(cols, r)) for r in rows])[:limit]
186
+ return {"field": field, "value": value, "mode": mode, "count": len(results),
187
+ "results": results}
188
+
189
+
190
+ async def _parallel(queries: list[tuple[str, str, str, int]]) -> list[dict[str, Any]]:
191
+ loop = asyncio.get_running_loop()
192
+
193
+ async def one(t: tuple[str, str, str, int]) -> dict[str, Any]:
194
+ field, value, mode, limit = t
195
+ return await loop.run_in_executor(pool, _run_field_search, field, value, mode, limit)
196
+
197
+ return await asyncio.gather(*[one(t) for t in queries])
198
+
199
+
200
+ async def _unified_search(q: str, limit: int, source: str | None = None) -> dict[str, Any]:
201
+ """Smart unified search: uses sorted indexes per field, merges, dedups."""
202
+ q = q.strip()
203
+ is_num = q.isdigit() and len(q) >= 8
204
+ loop = asyncio.get_running_loop()
205
+
206
+ if is_num:
207
+ # number-like -> exact match, phone index first (fast), then aadhar, then other
208
+ all_rows: list[dict[str, Any]] = []
209
+ searched: list[str] = []
210
+ # phone index ready -> instant; else full scan (slow, skip if we already found hits)
211
+ if _idx_ready(IDX_PHONE):
212
+ r = await loop.run_in_executor(pool, _run_field_search, "phoneNumber", q,
213
+ "exact", limit, source)
214
+ all_rows.extend(r["results"])
215
+ searched.append("phoneNumber")
216
+ if not all_rows and _idx_ready(IDX_AADHAR):
217
+ r = await loop.run_in_executor(pool, _run_field_search, "aadharNumber", q,
218
+ "exact", limit, source)
219
+ all_rows.extend(r["results"])
220
+ searched.append("aadharNumber")
221
+ if not all_rows and _idx_ready(IDX_NAME):
222
+ r = await loop.run_in_executor(pool, _run_field_search, "otherNumber", q,
223
+ "exact", limit, source)
224
+ all_rows.extend(r["results"])
225
+ searched.append("otherNumber")
226
+ all_rows = _cap_duplicates(all_rows)[:limit]
227
+ return {"query": q, "searched_fields": searched or list(NUMBER_FIELDS),
228
+ "dedup": DUPLICATE_CAP, "count": len(all_rows), "results": all_rows}
229
+ else:
230
+ # text -> name + fathersName contains via name index, then address/district/etc.
231
+ jobs = [loop.run_in_executor(pool, _run_field_search, "name", q, "contains",
232
+ limit, source)]
233
+ if _idx_ready(IDX_NAME):
234
+ jobs.append(loop.run_in_executor(pool, _run_field_search, "fathersName", q,
235
+ "contains", limit, source))
236
+ # also check number fields exact (safety net, only if numbers typed)
237
+ results = await asyncio.gather(*jobs)
238
+ all_rows = []
239
+ for r in results:
240
+ all_rows.extend(r["results"])
241
+ all_rows = _cap_duplicates(all_rows)[:limit]
242
+ fields = ["name", "fathersName"] + NUMBER_FIELDS
243
+ return {"query": q, "searched_fields": fields, "dedup": DUPLICATE_CAP,
244
+ "count": len(all_rows), "results": all_rows}
245
+
246
+
247
+ def _pretty(data: dict[str, Any], pretty: bool) -> Response:
248
+ if pretty:
249
+ return Response(content=json.dumps(data, indent=2, ensure_ascii=False),
250
+ media_type="application/json")
251
+ return Response(content=json.dumps(data, ensure_ascii=False),
252
+ media_type="application/json")
253
+
254
+
255
+ # ---- API ----
256
+ class BatchRequest(BaseModel):
257
+ queries: list[dict[str, Any]]
258
+ limit: int = 10
259
+
260
+
261
+ @app.get("/")
262
+ def root():
263
+ return {"app": "ICMR + HITEK Search API", "records": 2_504_793_870,
264
+ "files": [os.path.basename(f) for f in PARQUET_FILES],
265
+ "indexes": {"phone": _idx_ready(IDX_PHONE), "aadhar": _idx_ready(IDX_AADHAR),
266
+ "name": _idx_ready(IDX_NAME)},
267
+ "columns": SEARCH_FIELDS, "parallelism": PARALLELISM, "dedup": DUPLICATE_CAP,
268
+ "docs": "/docs"}
269
+
270
+
271
+ @app.get("/health")
272
+ def health():
273
+ return {"status": "ok", "files_ready": len(PARQUET_FILES) - len(_MISSING),
274
+ "files_total": len(PARQUET_FILES),
275
+ "indexes": {"phone": _idx_ready(IDX_PHONE), "aadhar": _idx_ready(IDX_AADHAR),
276
+ "name": _idx_ready(IDX_NAME)},
277
+ "missing": [os.path.basename(f) for f in _MISSING]}
278
+
279
+
280
+ @app.get("/search")
281
+ async def search(
282
+ q: str = Query(..., description="Search term - matches name, phone, aadhar, other, address, district, pincode, state, town"),
283
+ field: str | None = Query(None, description=f"Restrict to one field: {SEARCH_FIELDS}"),
284
+ mode: str = Query("contains", pattern="^(exact|contains)$"),
285
+ limit: int = Query(10, ge=1, le=1000),
286
+ source: str | None = Query(None, pattern="^(icmr|hitek|inddata)$",
287
+ description="Filter by source: icmr, hitek (=inddata), inddata"),
288
+ pretty: bool = Query(True, description="Pretty-print JSON"),
289
+ ):
290
+ """Unified search across all 11 columns. Duplicates capped at 2 per person."""
291
+ if field:
292
+ try:
293
+ data = _run_field_search(field, q, mode, limit, source)
294
+ except ValueError as e:
295
+ raise HTTPException(400, str(e))
296
+ data = {"query": q, "field": field, "mode": mode, "dedup": DUPLICATE_CAP,
297
+ "count": data["count"], "results": data["results"]}
298
+ else:
299
+ data = await _unified_search(q, limit, source)
300
+ return _pretty(data, pretty)
301
+
302
+
303
+ @app.post("/search/parallel")
304
+ async def search_parallel(req: BatchRequest):
305
+ """Run up to 50 searches in parallel across a pool of DuckDB connections."""
306
+ if not req.queries:
307
+ raise HTTPException(400, "queries must not be empty")
308
+ if len(req.queries) > 50:
309
+ raise HTTPException(400, "max 50 queries per batch")
310
+ results = await _parallel([(item.get("field", "name"), item.get("value", ""),
311
+ item.get("mode", "contains"), int(item.get("limit", req.limit)))
312
+ for item in req.queries])
313
+ out = [{"error": str(r)} if isinstance(r, Exception) else r for r in results]
314
+ return _pretty({"searches": len(req.queries), "parallelism": PARALLELISM, "results": out}, True)
requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ fastapi>=0.110
2
+ uvicorn>=0.29
3
+ duckdb>=1.0
4
+ pydantic>=2.0
run_api.bat ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ @echo off
2
+ cd /d "%~dp0"
3
+ start "ICMR+HITEK API" /min "C:\Users\Administrator\Desktop\icmr\.venv\Scripts\python.exe" -m uvicorn main:app --host 127.0.0.1 --port 8001 --workers 1 > api.log 2>&1
4
+ echo API starting on http://127.0.0.1:8001 ... log: api.log
setup.bat ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ @echo off
2
+ setlocal enabledelayedexpansion
3
+ chcp 65001 >nul
4
+ title ICMR+HITEK API - One-Click Setup
5
+ echo ============================================================
6
+ echo ICMR + HITEK Search API - One-Click Setup (Windows)
7
+ echo Total download: ~305 GB. Make sure you have enough space!
8
+ echo ============================================================
9
+ echo.
10
+
11
+ set "DATA_REPO=Kzr0xx/Icmr-and-hitek"
12
+ set "FULL_REPO=Kzr0xx/icrm-hitek-full-db-mixed"
13
+ set "FILES=part1.parquet part2a.parquet part2b_new.parquet"
14
+ set "IDX=idx_phone.0.parquet idx_phone.1.parquet idx_phone.2.parquet idx_phone.3.parquet idx_phone.4.parquet idx_phone.5.parquet idx_phone.6.parquet idx_aadhar.0.parquet idx_aadhar.1.parquet idx_aadhar.2.parquet idx_aadhar.3.parquet idx_aadhar.4.parquet idx_aadhar.5.parquet idx_aadhar.6.parquet"
15
+ set "CODE=main.py build_index.py run_api.bat requirements.txt"
16
+
17
+ if not exist "%~dp0data" mkdir "%~dp0data"
18
+ cd /d "%~dp0"
19
+
20
+ echo [1/5] Downloading data files (104 GB)...
21
+ for %%f in (%FILES%) do (
22
+ if not exist "data\%%f" (
23
+ echo Downloading %%f ...
24
+ curl -L -C - -o "data\%%f" "https://huggingface.co/datasets/%DATA_REPO%/resolve/main/%%f"
25
+ if errorlevel 1 ( echo FAILED: %%f & pause & exit /b 1 )
26
+ ) else (
27
+ echo %%f already exists, skipping
28
+ )
29
+ )
30
+
31
+ echo [2/5] Downloading index parts (200 GB)...
32
+ for %%f in (%IDX%) do (
33
+ if not exist "data\%%f" (
34
+ echo Downloading %%f ...
35
+ curl -L -C - -o "data\%%f" "https://huggingface.co/datasets/%FULL_REPO%/resolve/main/%%f"
36
+ if errorlevel 1 ( echo FAILED: %%f & pause & exit /b 1 )
37
+ ) else (
38
+ echo %%f already exists, skipping
39
+ )
40
+ )
41
+
42
+ echo [3/5] Downloading code files...
43
+ for %%f in (%CODE%) do (
44
+ curl -L -C - -o "%%f" "https://huggingface.co/datasets/%FULL_REPO%/resolve/main/%%f"
45
+ )
46
+
47
+ echo [4/5] Setting up Python environment...
48
+ set "PYCMD=python"
49
+ where python >nul 2>nul
50
+ if errorlevel 1 (
51
+ where py >nul 2>nul
52
+ if errorlevel 1 (
53
+ echo Python not found! Install Python 3.11+ from https://www.python.org/downloads/
54
+ pause & exit /b 1
55
+ )
56
+ set "PYCMD=py -3"
57
+ )
58
+ if not exist ".venv" %PYCMD% -m venv .venv
59
+ ".venv\Scripts\python.exe" -m pip install -q --upgrade pip
60
+ ".venv\Scripts\python.exe" -m pip install -q -r requirements.txt
61
+
62
+ echo [5/5] Starting API server...
63
+ set "ICMR_DATA_DIR=%~dp0data"
64
+ start "ICMR+HITEK API" /min ".venv\Scripts\python.exe" -m uvicorn main:app --host 127.0.0.1 --port 8001 --workers 1
65
+ echo.
66
+ echo ============================================================
67
+ echo API is starting on http://127.0.0.1:8001
68
+ echo Docs: http://127.0.0.1:8001/docs
69
+ echo ============================================================
70
+ timeout /t 5 >nul
71
+ pause
setup.ps1 ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ICMR + HITEK Search API - One-Click Setup (PowerShell)
2
+ # Total download: ~305 GB. Make sure you have enough space!
3
+ $ErrorActionPreference = "Stop"
4
+ $ProgressPreference = "SilentlyContinue"
5
+
6
+ $DataRepo = "Kzr0xx/Icmr-and-hitek"
7
+ $FullRepo = "Kzr0xx/icrm-hitek-full-db-mixed"
8
+ $Files = @("part1.parquet", "part2a.parquet", "part2b_new.parquet")
9
+ $Idx = @("idx_phone.0.parquet", "idx_phone.1.parquet", "idx_phone.2.parquet", "idx_phone.3.parquet", "idx_phone.4.parquet", "idx_phone.5.parquet", "idx_phone.6.parquet", "idx_aadhar.0.parquet", "idx_aadhar.1.parquet", "idx_aadhar.2.parquet", "idx_aadhar.3.parquet", "idx_aadhar.4.parquet", "idx_aadhar.5.parquet", "idx_aadhar.6.parquet")
10
+ $Code = @("main.py", "build_index.py", "run_api.bat", "requirements.txt")
11
+
12
+ $Root = Split-Path -Parent $MyInvocation.MyCommand.Path
13
+ Set-Location $Root
14
+ $DataDir = Join-Path $Root "data"
15
+ New-Item -ItemType Directory -Force -Path $DataDir | Out-Null
16
+
17
+ function Download-File($Name, $Repo, $Dest) {
18
+ if (Test-Path $Dest) { Write-Host " $Name already exists, skipping"; return }
19
+ Write-Host " Downloading $Name ..."
20
+ $url = "https://huggingface.co/datasets/$Repo/resolve/main/$Name"
21
+ # curl.exe is bundled with Windows 10+ and supports resume (-C -)
22
+ & curl.exe -L -C - -o $Dest $url
23
+ if ($LASTEXITCODE -ne 0) { throw "FAILED: $Name" }
24
+ }
25
+
26
+ Write-Host "============================================================"
27
+ Write-Host " ICMR + HITEK Search API - One-Click Setup (PowerShell)"
28
+ Write-Host "============================================================"
29
+ Write-Host ""
30
+
31
+ Write-Host "[1/5] Downloading data files (104 GB)..."
32
+ foreach ($f in $Files) { Download-File $f $DataRepo (Join-Path $DataDir $f) }
33
+
34
+ Write-Host "[2/5] Downloading index parts (200 GB)..."
35
+ foreach ($f in $Idx) { Download-File $f $FullRepo (Join-Path $DataDir $f) }
36
+
37
+ Write-Host "[3/5] Downloading code files..."
38
+ foreach ($f in $Code) {
39
+ curl.exe -L -C - -o $f "https://huggingface.co/datasets/$FullRepo/resolve/main/$f"
40
+ }
41
+
42
+ Write-Host "[4/5] Setting up Python environment..."
43
+ $py = Get-Command python -ErrorAction SilentlyContinue
44
+ if (-not $py) {
45
+ $py = Get-Command py -ErrorAction SilentlyContinue
46
+ if (-not $py) { throw "Python not found! Install Python 3.11+ from https://www.python.org/downloads/" }
47
+ & py -3 -m venv .venv
48
+ } else {
49
+ if (-not (Test-Path ".venv")) { python -m venv .venv }
50
+ }
51
+ & ".venv\Scripts\python.exe" -m pip install -q --upgrade pip
52
+ & ".venv\Scripts\python.exe" -m pip install -q -r requirements.txt
53
+
54
+ Write-Host "[5/5] Starting API server..."
55
+ $env:ICMR_DATA_DIR = $DataDir
56
+ Start-Process -FilePath ".venv\Scripts\python.exe" -ArgumentList "-m","uvicorn","main:app","--host","127.0.0.1","--port","8001","--workers","1" -WorkingDirectory $Root -WindowStyle Minimized
57
+
58
+ Write-Host ""
59
+ Write-Host "============================================================"
60
+ Write-Host " API is starting on http://127.0.0.1:8001"
61
+ Write-Host " Docs: http://127.0.0.1:8001/docs"
62
+ Write-Host "============================================================"
setup.sh ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # ICMR + HITEK Search API - One-Click Setup (Linux / VPS)
3
+ # Total download: ~305 GB. Make sure you have enough space!
4
+ set -euo pipefail
5
+
6
+ DATA_REPO="Kzr0xx/Icmr-and-hitek"
7
+ FULL_REPO="Kzr0xx/icrm-hitek-full-db-mixed"
8
+ FILES=("part1.parquet" "part2a.parquet" "part2b_new.parquet")
9
+ IDX=("idx_phone.0.parquet" "idx_phone.1.parquet" "idx_phone.2.parquet" "idx_phone.3.parquet" "idx_phone.4.parquet" "idx_phone.5.parquet" "idx_phone.6.parquet" "idx_aadhar.0.parquet" "idx_aadhar.1.parquet" "idx_aadhar.2.parquet" "idx_aadhar.3.parquet" "idx_aadhar.4.parquet" "idx_aadhar.5.parquet" "idx_aadhar.6.parquet")
10
+ CODE=("main.py" "build_index.py" "run_api.bat" "requirements.txt")
11
+
12
+ ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
13
+ cd "$ROOT"
14
+ mkdir -p data
15
+
16
+ dl() { # dl <name> <repo> <dest>
17
+ local name="$1" repo="$2" dest="$3"
18
+ if [ -f "$dest" ]; then
19
+ echo " $name already exists, skipping"
20
+ return
21
+ fi
22
+ echo " Downloading $name ..."
23
+ curl -L -C - -o "$dest" "https://huggingface.co/datasets/$repo/resolve/main/$name"
24
+ }
25
+
26
+ echo "============================================================"
27
+ echo " ICMR + HITEK Search API - One-Click Setup (Linux/VPS)"
28
+ echo "============================================================"
29
+ echo ""
30
+
31
+ echo "[1/5] Downloading data files (104 GB)..."
32
+ for f in "${FILES[@]}"; do dl "$f" "$DATA_REPO" "data/$f"; done
33
+
34
+ echo "[2/5] Downloading index parts (200 GB)..."
35
+ for f in "${IDX[@]}"; do dl "$f" "$FULL_REPO" "data/$f"; done
36
+
37
+ echo "[3/5] Downloading code files..."
38
+ for f in "${CODE[@]}"; do
39
+ curl -L -C - -o "$f" "https://huggingface.co/datasets/$FULL_REPO/resolve/main/$f"
40
+ done
41
+
42
+ echo "[4/5] Setting up Python environment..."
43
+ if ! command -v python3 >/dev/null 2>&1; then
44
+ echo " Installing python3..."
45
+ sudo apt-get update -y && sudo apt-get install -y python3 python3-venv python3-pip
46
+ fi
47
+ if [ ! -d ".venv" ]; then python3 -m venv .venv; fi
48
+ ".venv/bin/python" -m pip install -q --upgrade pip
49
+ ".venv/bin/python" -m pip install -q -r requirements.txt
50
+
51
+ echo "[5/5] Starting API server (background, nohup)..."
52
+ export ICMR_DATA_DIR="$ROOT/data"
53
+ nohup ".venv/bin/python" -m uvicorn main:app --host 0.0.0.0 --port 8001 --workers 1 \
54
+ > api.log 2>&1 &
55
+
56
+ echo ""
57
+ echo "============================================================"
58
+ echo " API starting on http://0.0.0.0:8001"
59
+ echo " Docs: http://<server-ip>:8001/docs"
60
+ echo " Log: api.log"
61
+ echo "============================================================"
62
+ sleep 5
63
+ curl -s http://127.0.0.1:8001/health && echo ""
64
+ echo "Done!"
split_idx.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Parallel split of sorted index parquets into parts < 50 GB for HTTP upload to HF.
2
+
3
+ Windows Xet upload stalls on large files; the HTTP fallback caps at 50 GB/file.
4
+ Parts preserve sorted order (contiguous row-group ranges), so DuckDB zone-map
5
+ pruning still works across parts. Multiprocessing (N_WORKERS) since pyarrow's
6
+ writer is mostly single-threaded. Resumable: existing completed parts are skipped.
7
+ """
8
+ import multiprocessing as mp
9
+ import os
10
+ import time
11
+
12
+ import pyarrow.parquet as pq
13
+
14
+ BASE = os.path.dirname(os.path.abspath(__file__))
15
+ # budget on UNCOMPRESSED size; SNAPPY output lands well under the 50 GB cap
16
+ TARGET_UNCOMPRESSED = 45 * 1024**3
17
+ N_WORKERS = 5
18
+ BATCH_GROUPS = 100 # row groups read per batch (~1-3 GiB in RAM)
19
+
20
+ JOBS = ["idx_phone.parquet", "idx_aadhar.parquet"]
21
+
22
+
23
+ def plan_partitions(sizes, target):
24
+ """Split row-group size list into (start, end) buckets each ~target bytes."""
25
+ parts = []
26
+ acc = 0
27
+ start = 0
28
+ for i, s in enumerate(sizes):
29
+ acc += s
30
+ if acc >= target and i - start > 200: # at least 200 row groups per part
31
+ parts.append((start, i + 1))
32
+ start = i + 1
33
+ acc = 0
34
+ if start < len(sizes):
35
+ parts.append((start, len(sizes)))
36
+ return parts
37
+
38
+
39
+ def split_one(src, pi, a, b):
40
+ out = f"{os.path.splitext(src)[0]}.{pi}.parquet"
41
+ if os.path.exists(out) and os.path.getsize(out) > 0:
42
+ print(f" {out} exists, skip", flush=True)
43
+ return
44
+ tmp = out + ".tmp"
45
+ if os.path.exists(tmp):
46
+ os.remove(tmp)
47
+ t0 = time.time()
48
+ pf = pq.ParquetFile(src)
49
+ with pq.ParquetWriter(tmp, pf.schema_arrow, compression="snappy",
50
+ use_dictionary=True, data_page_version="2.0",
51
+ version="2.6") as w:
52
+ g = a
53
+ while g < b:
54
+ g2 = min(g + BATCH_GROUPS, b)
55
+ w.write_table(pf.read_row_groups(list(range(g, g2))))
56
+ g = g2
57
+ os.rename(tmp, out)
58
+ print(f" DONE {out} ({os.path.getsize(out)/1073741824:.1f} GiB) "
59
+ f"in {time.time()-t0:.0f}s", flush=True)
60
+
61
+
62
+ def worker(wid, tasklist):
63
+ for src, pi, a, b in tasklist:
64
+ print(f"[w{wid}] start {src} part {pi} (groups {a}-{b})", flush=True)
65
+ try:
66
+ split_one(src, pi, a, b)
67
+ except Exception as e:
68
+ print(f"[w{wid}] FAIL {src} part {pi}: {e}", flush=True)
69
+
70
+
71
+ def main():
72
+ jobs = [] # (src, [(a,b), ...])
73
+ for src in JOBS:
74
+ if not os.path.exists(src):
75
+ print(f"SKIP {src}: not found", flush=True)
76
+ continue
77
+ pf = pq.ParquetFile(src)
78
+ sizes = [pf.metadata.row_group(i).total_byte_size
79
+ for i in range(pf.num_row_groups)]
80
+ boundaries = plan_partitions(sizes, TARGET_UNCOMPRESSED)
81
+ print(f"{src}: {pf.num_row_groups} row groups, "
82
+ f"{sum(sizes)/1073741824:.1f} GiB uncompressed -> "
83
+ f"{len(boundaries)} parts", flush=True)
84
+ jobs.append((src, boundaries))
85
+
86
+ flat = [(src, i, a, b)
87
+ for src, bnd in jobs for i, (a, b) in enumerate(bnd)]
88
+ procs = []
89
+ for wi in range(N_WORKERS):
90
+ mine = flat[wi::N_WORKERS]
91
+ p = mp.Process(target=worker, args=(wi, mine))
92
+ p.start()
93
+ procs.append(p)
94
+ for p in procs:
95
+ p.join()
96
+ print("ALL DONE", flush=True)
97
+
98
+
99
+ if __name__ == "__main__":
100
+ main()
upload_parts.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Upload split index parts to HF via the classic HTTP path (Xet disabled).
2
+
3
+ Windows Xet upload stalls on big files; the HTTP fallback caps at 50 GB/file,
4
+ so the <50 GB parts from split_idx.py are uploaded here. Resumable: parts
5
+ already present on HF are skipped. Watches the folder until all parts done.
6
+ """
7
+ import glob
8
+ import os
9
+ import sys
10
+ import time
11
+
12
+ os.environ["HF_HUB_DISABLE_XET"] = "1"
13
+
14
+ from huggingface_hub import HfApi
15
+
16
+ BASE = os.path.dirname(os.path.abspath(__file__))
17
+ REPO = "Kzr0xx/icrm-hitek-full-db-mixed"
18
+
19
+
20
+ def get_token():
21
+ t = os.environ.get("HF_TOKEN")
22
+ if t:
23
+ return t
24
+ try:
25
+ with open(os.path.join(BASE, "hf_token.txt"), encoding="utf-8") as f:
26
+ t = f.read().strip()
27
+ if t:
28
+ return t
29
+ except OSError:
30
+ pass
31
+ sys.exit("HF_TOKEN env var or hf_token.txt required")
32
+
33
+
34
+ def main():
35
+ api = HfApi(token=get_token())
36
+ while True:
37
+ parts = sorted(glob.glob(os.path.join(BASE, "idx_*.?.parquet")))
38
+ pending = []
39
+ for p in parts:
40
+ name = os.path.basename(p)
41
+ try:
42
+ if api.file_exists(repo_id=REPO, filename=name,
43
+ repo_type="dataset"):
44
+ continue
45
+ except Exception as e:
46
+ print(f" check {name}: {e}", flush=True)
47
+ pending.append(p)
48
+ if not pending and parts:
49
+ print("ALL UPLOADED", flush=True)
50
+ break
51
+ for p in pending:
52
+ name = os.path.basename(p)
53
+ print(f"UPLOAD {name} ({os.path.getsize(p)/1073741824:.1f} GiB)",
54
+ flush=True)
55
+ t0 = time.time()
56
+ try:
57
+ api.upload_file(path_or_fileobj=p, path_in_repo=name,
58
+ repo_id=REPO, repo_type="dataset")
59
+ print(f"DONE {name} in {time.time()-t0:.0f}s", flush=True)
60
+ except Exception as e:
61
+ print(f"FAIL {name}: {e}", flush=True)
62
+ time.sleep(30)
63
+
64
+
65
+ if __name__ == "__main__":
66
+ main()