Cistern commited on
Commit
6cbc3d9
Β·
verified Β·
1 Parent(s): c3cc7e8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +166 -172
app.py CHANGED
@@ -1,207 +1,201 @@
1
  import os
2
  import time
3
  import shutil
 
4
  import streamlit as st
5
  import duckdb
6
  from huggingface_hub import HfApi, list_repo_files, hf_hub_download
7
 
8
  # ── Configuration ──────────────────────────────────────────────────────────────
9
  HF_TOKEN = os.environ.get("HF_TOKEN", "")
10
- SOURCE_DATASET = "Cistern/Datax" # Read-only source
11
- TARGET_DATASET = "Cistern/Inx" # Where indexes will be uploaded
12
  COLUMNS = ["mobile", "alt", "id", "email"]
13
 
14
- # Local temporary directories
15
  DOWNLOAD_DIR = "./tmp_data"
16
  INDEX_PARTS_DIR = "./index_parts"
17
-
18
  os.makedirs(DOWNLOAD_DIR, exist_ok=True)
 
19
 
20
- # ── DuckDB connection ──────────────────────────────────────────────────────────
21
- def get_con():
22
- con = getattr(st, "_duck_con", None)
23
- if con is None:
24
- con = duckdb.connect()
25
- con.execute("SET threads=4")
26
- con.execute("SET memory_limit='2GB'")
27
- st._duck_con = con
28
- return con
29
-
30
- def clean_temp():
31
- """Remove all temporary data."""
32
- for d in [DOWNLOAD_DIR, INDEX_PARTS_DIR]:
33
- if os.path.exists(d):
34
- shutil.rmtree(d)
35
- os.makedirs(DOWNLOAD_DIR, exist_ok=True)
36
- os.makedirs(INDEX_PARTS_DIR, exist_ok=True)
37
-
38
- # ── Index building ────────────────────────────────────────────────────────────
39
- def build_indexes(status_container, progress_bar):
 
 
40
  api = HfApi()
41
-
42
- # 1. List all files in source dataset, filter only Hi-Tek_Part_*.parquet
43
  try:
44
  all_files = list_repo_files(SOURCE_DATASET, repo_type="dataset", token=HF_TOKEN)
45
  data_files = [
46
  f for f in all_files
47
- if f.startswith("Hi-Tek_Part_") and f.endswith(".parquet")
48
  ]
49
- # Sort to process in order (000..851)
50
  data_files = sorted(data_files)
51
  if not data_files:
52
- st.error("No Hi-Tek_Part_*.parquet files found in source dataset.")
53
- return False
54
- except Exception as e:
55
- st.error(f"Error listing source dataset: {e}")
56
- return False
57
-
58
- total = len(data_files)
59
- status_container.info(f"Found {total} data files. Starting indexing…")
60
-
61
- # 2. Process each file one by one
62
- for idx, file_path in enumerate(data_files):
63
- fname = file_path # already includes full path from root
64
- st.text(f"Processing {idx+1}/{total}: {fname}")
65
-
66
- # Download the file
67
- try:
68
- local_path = hf_hub_download(
69
- repo_id=SOURCE_DATASET,
70
- filename=file_path,
71
- repo_type="dataset",
72
- token=HF_TOKEN,
73
- cache_dir=DOWNLOAD_DIR,
74
- force_download=False
75
- )
76
- except Exception as e:
77
- st.error(f"Download failed for {file_path}: {e}")
78
- return False
79
-
80
- try:
81
- con = get_con()
82
-
83
- # Get row-group boundaries for this file
84
- meta = con.execute(f"""
85
- SELECT row_group_id,
86
- row_group_num_rows,
87
- SUM(row_group_num_rows) OVER (ORDER BY row_group_id) - row_group_num_rows AS row_start,
88
- SUM(row_group_num_rows) OVER (ORDER BY row_group_id) - 1 AS row_end
89
- FROM parquet_metadata('{local_path}')
90
- WHERE row_group_id IS NOT NULL
91
- ORDER BY row_group_id
92
- """).fetchdf()
93
-
94
- if meta.empty:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95
  os.remove(local_path)
96
- continue
97
-
98
- # Process each column
99
- for col in COLUMNS:
100
- query = f"""
101
- WITH raw AS (
102
- SELECT "{col}", file_row_number
103
- FROM read_parquet('{local_path}', file_row_number=true)
104
- WHERE "{col}" IS NOT NULL
105
- ),
106
- boundaries AS (
107
- SELECT row_group_id, row_start, row_end
108
- FROM meta
 
 
 
 
 
 
 
 
 
 
109
  )
110
- SELECT raw."{col}" AS search_value,
111
- '{fname}' AS filename,
112
- boundaries.row_group_id,
113
- boundaries.row_start,
114
- boundaries.row_end
115
- FROM raw
116
- ASOF LEFT JOIN boundaries
117
- ON raw.file_row_number >= boundaries.row_start
118
- """
119
- part_df = con.execute(query).fetchdf()
120
- if not part_df.empty:
121
- # Store per-column, per-file part
122
- part_dir = os.path.join(INDEX_PARTS_DIR, col)
123
- os.makedirs(part_dir, exist_ok=True)
124
- out_path = os.path.join(part_dir, f"{idx:04d}_{fname}.parquet")
125
- part_df.to_parquet(out_path, index=False)
126
-
127
- # Remove the downloaded data file to free disk
128
- os.remove(local_path)
129
-
130
- except Exception as e:
131
- st.error(f"Error processing {fname}: {e}")
132
- return False
133
-
134
- # Update progress bar
135
- progress_bar.progress((idx + 1) / total)
136
-
137
- # 3. Merge all parts for each column into a final index and upload
138
- st.success("All files processed. Merging index parts…")
139
- for col in COLUMNS:
140
- status_container.text(f"Merging {col} index...")
141
- part_dir = os.path.join(INDEX_PARTS_DIR, col)
142
- all_parts = os.path.join(part_dir, "*.parquet")
143
- final_path = os.path.join(os.getcwd(), f"{col}_index.parquet")
144
-
145
- try:
146
- con = get_con()
147
- # Merge and write final compressed index
148
- con.execute(f"""
149
- COPY (
150
- SELECT * FROM read_parquet('{all_parts}')
151
- ORDER BY search_value
152
- ) TO '{final_path}' (
153
- FORMAT PARQUET,
154
- COMPRESSION ZSTD,
155
- ROW_GROUP_SIZE 1000000
156
  )
157
- """)
158
-
159
- # Upload to target dataset
160
- api.upload_file(
161
- path_or_fileobj=final_path,
162
- path_in_repo=f"{col}_index.parquet",
163
- repo_id=TARGET_DATASET,
164
- repo_type="dataset",
165
- token=HF_TOKEN,
166
- )
167
- st.success(f"βœ… Uploaded {col}_index.parquet to {TARGET_DATASET}")
168
- except Exception as e:
169
- st.error(f"Merge/upload failed for {col}: {e}")
170
- return False
171
-
172
- # 4. Final cleanup
173
- clean_temp()
174
- st.balloons()
175
- st.success("All indexes built, uploaded, and temporary files cleaned!")
176
- return True
177
 
178
  # ── Streamlit UI ────────────────────────────────────────────────────────────────
179
  st.set_page_config(page_title="Index Builder", layout="centered")
180
-
181
- st.title("πŸ“‡ Index Builder for Cistern/Datax")
182
  st.markdown(f"""
183
- This tool will create **four index files** (`mobile`, `alt`, `id`, `email`) from the
184
- **{SOURCE_DATASET}** dataset and upload them to **{TARGET_DATASET}**.
185
-
186
- - It processes **one data file at a time**, keeping disk usage minimal.
187
- - The source dataset is **never modified** β€” it only reads the files.
188
- - After completion all temporary files are deleted.
189
- - Your `HF_TOKEN` must have **read** access to the source and **write** access to the target.
190
  """)
191
 
192
- if "running" not in st.session_state:
193
- st.session_state.running = False
 
 
194
 
195
- if not st.session_state.running:
196
- if st.button("πŸš€ Start Building Indexes", type="primary"):
197
- st.session_state.running = True
198
- st.rerun()
199
- else:
200
- status = st.empty()
201
- progress = st.progress(0)
202
 
203
- with st.spinner("Indexing in progress – this may take a while…"):
204
- success = build_indexes(status, progress)
 
 
205
 
206
- if success:
207
- st.session_state.running = False
 
 
1
  import os
2
  import time
3
  import shutil
4
+ import threading
5
  import streamlit as st
6
  import duckdb
7
  from huggingface_hub import HfApi, list_repo_files, hf_hub_download
8
 
9
  # ── Configuration ──────────────────────────────────────────────────────────────
10
  HF_TOKEN = os.environ.get("HF_TOKEN", "")
11
+ SOURCE_DATASET = "Cistern/Datax"
12
+ TARGET_DATASET = "Cistern/Inx"
13
  COLUMNS = ["mobile", "alt", "id", "email"]
14
 
 
15
  DOWNLOAD_DIR = "./tmp_data"
16
  INDEX_PARTS_DIR = "./index_parts"
 
17
  os.makedirs(DOWNLOAD_DIR, exist_ok=True)
18
+ os.makedirs(INDEX_PARTS_DIR, exist_ok=True)
19
 
20
+ # Shared state between background thread and UI
21
+ if "log_lines" not in st.session_state:
22
+ st.session_state.log_lines = []
23
+ if "progress" not in st.session_state:
24
+ st.session_state.progress = 0.0
25
+ if "running" not in st.session_state:
26
+ st.session_state.running = False
27
+ if "done" not in st.session_state:
28
+ st.session_state.done = False
29
+ if "error" not in st.session_state:
30
+ st.session_state.error = False
31
+
32
+ def log(msg):
33
+ """Log a message to both the terminal and the Streamlit UI."""
34
+ timestamp = time.strftime("%H:%M:%S")
35
+ full_msg = f"[{timestamp}] {msg}"
36
+ print(full_msg) # terminal / Space logs
37
+ st.session_state.log_lines.append(full_msg)
38
+
39
+ # ── Background indexing function ───────────────────────────────────────────────
40
+ def index_worker():
41
+ st.session_state.running = True
42
  api = HfApi()
 
 
43
  try:
44
  all_files = list_repo_files(SOURCE_DATASET, repo_type="dataset", token=HF_TOKEN)
45
  data_files = [
46
  f for f in all_files
47
+ if f.startswith("data/Hi-Tek_Part_") and f.endswith(".parquet")
48
  ]
 
49
  data_files = sorted(data_files)
50
  if not data_files:
51
+ log("❌ No Hi-Tek_Part_*.parquet files found in data/ folder.")
52
+ st.session_state.running = False
53
+ st.session_state.error = True
54
+ return
55
+
56
+ total = len(data_files)
57
+ log(f"πŸ” Found {total} data files. Starting indexing…")
58
+
59
+ # Use a dedicated DuckDB connection for this thread
60
+ con = duckdb.connect()
61
+ con.execute("SET threads=4")
62
+ con.execute("SET memory_limit='2GB'")
63
+
64
+ for idx, file_path in enumerate(data_files):
65
+ log(f"⬇️ Downloading {file_path} ({idx+1}/{total})")
66
+ try:
67
+ local_path = hf_hub_download(
68
+ repo_id=SOURCE_DATASET,
69
+ filename=file_path,
70
+ repo_type="dataset",
71
+ token=HF_TOKEN,
72
+ cache_dir=DOWNLOAD_DIR,
73
+ force_download=False
74
+ )
75
+ except Exception as e:
76
+ log(f"❌ Download failed: {e}")
77
+ st.session_state.error = True
78
+ return
79
+
80
+ try:
81
+ meta = con.execute(f"""
82
+ SELECT row_group_id,
83
+ row_group_num_rows,
84
+ SUM(row_group_num_rows) OVER (ORDER BY row_group_id) - row_group_num_rows AS row_start,
85
+ SUM(row_group_num_rows) OVER (ORDER BY row_group_id) - 1 AS row_end
86
+ FROM parquet_metadata('{local_path}')
87
+ WHERE row_group_id IS NOT NULL
88
+ ORDER BY row_group_id
89
+ """).fetchdf()
90
+
91
+ if meta.empty:
92
+ os.remove(local_path)
93
+ continue
94
+
95
+ for col in COLUMNS:
96
+ query = f"""
97
+ WITH raw AS (
98
+ SELECT "{col}", file_row_number
99
+ FROM read_parquet('{local_path}', file_row_number=true)
100
+ WHERE "{col}" IS NOT NULL
101
+ ),
102
+ boundaries AS (
103
+ SELECT row_group_id, row_start, row_end
104
+ FROM meta
105
+ )
106
+ SELECT raw."{col}" AS search_value,
107
+ '{file_path}' AS filename,
108
+ boundaries.row_group_id,
109
+ boundaries.row_start,
110
+ boundaries.row_end
111
+ FROM raw
112
+ ASOF LEFT JOIN boundaries
113
+ ON raw.file_row_number >= boundaries.row_start
114
+ """
115
+ part_df = con.execute(query).fetchdf()
116
+ if not part_df.empty:
117
+ part_dir = os.path.join(INDEX_PARTS_DIR, col)
118
+ os.makedirs(part_dir, exist_ok=True)
119
+ out_path = os.path.join(part_dir, f"{idx:04d}_{os.path.basename(file_path)}.parquet")
120
+ part_df.to_parquet(out_path, index=False)
121
+
122
  os.remove(local_path)
123
+ log(f"βœ… Processed {file_path}")
124
+ st.session_state.progress = (idx + 1) / total
125
+
126
+ except Exception as e:
127
+ log(f"❌ Error processing {file_path}: {e}")
128
+ st.session_state.error = True
129
+ return
130
+
131
+ log("πŸ“¦ Merging index parts and uploading…")
132
+ for col in COLUMNS:
133
+ part_dir = os.path.join(INDEX_PARTS_DIR, col)
134
+ all_parts = os.path.join(part_dir, "*.parquet")
135
+ final_path = os.path.join(os.getcwd(), f"{col}_index.parquet")
136
+
137
+ try:
138
+ con.execute(f"""
139
+ COPY (
140
+ SELECT * FROM read_parquet('{all_parts}')
141
+ ORDER BY search_value
142
+ ) TO '{final_path}' (
143
+ FORMAT PARQUET,
144
+ COMPRESSION ZSTD,
145
+ ROW_GROUP_SIZE 1000000
146
  )
147
+ """)
148
+
149
+ api.upload_file(
150
+ path_or_fileobj=final_path,
151
+ path_in_repo=f"{col}_index.parquet",
152
+ repo_id=TARGET_DATASET,
153
+ repo_type="dataset",
154
+ token=HF_TOKEN,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
155
  )
156
+ log(f"βœ… Uploaded {col}_index.parquet to {TARGET_DATASET}")
157
+ except Exception as e:
158
+ log(f"❌ Merge/upload failed for {col}: {e}")
159
+ st.session_state.error = True
160
+ return
161
+
162
+ # Clean up
163
+ shutil.rmtree(DOWNLOAD_DIR, ignore_errors=True)
164
+ shutil.rmtree(INDEX_PARTS_DIR, ignore_errors=True)
165
+ os.makedirs(DOWNLOAD_DIR, exist_ok=True)
166
+ os.makedirs(INDEX_PARTS_DIR, exist_ok=True)
167
+
168
+ log("πŸŽ‰ All indexes built, uploaded, and temp files cleaned.")
169
+ st.session_state.done = True
170
+
171
+ except Exception as e:
172
+ log(f"πŸ’₯ Unexpected error: {e}")
173
+ st.session_state.error = True
174
+ finally:
175
+ st.session_state.running = False
176
 
177
  # ── Streamlit UI ────────────────────────────────────────────────────────────────
178
  st.set_page_config(page_title="Index Builder", layout="centered")
179
+ st.title("πŸ“‡ Auto‑Index Builder")
 
180
  st.markdown(f"""
181
+ Building search indexes for **{SOURCE_DATASET}** β†’ **{TARGET_DATASET}**
182
+ The process runs **automatically in the background**.
183
+ You can close this browser β€” it will keep working as long as the Space is alive.
 
 
 
 
184
  """)
185
 
186
+ # Start the worker thread on first load
187
+ if not st.session_state.running and not st.session_state.done and not st.session_state.error:
188
+ thread = threading.Thread(target=index_worker, daemon=False)
189
+ thread.start()
190
 
191
+ # Show progress bar
192
+ progress_bar = st.progress(st.session_state.progress)
 
 
 
 
 
193
 
194
+ # Show logs in real-time (reverse so latest at top, or just show all)
195
+ log_display = st.empty()
196
+ log_text = "\n".join(st.session_state.log_lines[-30:]) # show last 30 lines
197
+ log_display.code(log_text, language="bash")
198
 
199
+ # Auto-refresh every second to keep UI updated
200
+ time.sleep(1)
201
+ st.rerun()