Update app.py
Browse files
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"
|
| 11 |
-
TARGET_DATASET = "Cistern/Inx"
|
| 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 |
-
#
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
|
|
|
|
|
|
| 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 |
-
|
| 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 |
os.remove(local_path)
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 109 |
)
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 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 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 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 |
-
|
| 184 |
-
|
| 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 |
-
|
| 193 |
-
|
|
|
|
|
|
|
| 194 |
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
st.session_state.running = True
|
| 198 |
-
st.rerun()
|
| 199 |
-
else:
|
| 200 |
-
status = st.empty()
|
| 201 |
-
progress = st.progress(0)
|
| 202 |
|
| 203 |
-
|
| 204 |
-
|
|
|
|
|
|
|
| 205 |
|
| 206 |
-
|
| 207 |
-
|
|
|
|
|
|
| 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()
|