Cistern commited on
Commit
2f3abe0
Β·
verified Β·
1 Parent(s): 40afc5d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +136 -21
app.py CHANGED
@@ -1,8 +1,10 @@
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
 
@@ -11,13 +13,14 @@ 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
- # Global state (thread‑safe enough for this use case)
21
  LOG_LINES = []
22
  PROGRESS = 0.0
23
  RUNNING = False
@@ -26,14 +29,13 @@ ERROR = False
26
  _lock = threading.Lock()
27
 
28
  def log(msg):
29
- """Thread‑safe logging to both terminal and the global list."""
30
  timestamp = time.strftime("%H:%M:%S")
31
  full_msg = f"[{timestamp}] {msg}"
32
  print(full_msg, flush=True)
33
  with _lock:
34
  LOG_LINES.append(full_msg)
35
 
36
- # ── Background indexing (no Streamlit calls!) ──────────────────────────────────
37
  def index_worker():
38
  global RUNNING, PROGRESS, DONE, ERROR
39
  RUNNING = True
@@ -160,11 +162,15 @@ def index_worker():
160
  RUNNING = False
161
  return
162
 
 
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
  DONE = True
170
 
@@ -174,20 +180,129 @@ def index_worker():
174
  finally:
175
  RUNNING = False
176
 
177
- # ── Streamlit UI (minimal) ─────────────────────────────────────────────────────
178
- st.set_page_config(page_title="Index Builder", layout="centered")
179
- st.title("πŸ“‡ Auto‑Index Builder (Cistern/Datax β†’ Cistern/Inx)")
180
- st.markdown("The indexing process runs **automatically in the background**.")
181
-
182
- # Start the worker thread once
183
- if not RUNNING and not DONE and not ERROR:
184
- thread = threading.Thread(target=index_worker, daemon=False)
185
- thread.start()
186
-
187
- # Show static status
188
- if RUNNING:
189
- st.info("⏳ Indexing is running. **Check the container logs** for detailed progress.")
190
- elif DONE:
191
- st.success("βœ… Indexing completed successfully! Four index files are now in `Cistern/Inx`.")
192
- elif ERROR:
193
- st.error("❌ An error occurred. Check the container logs for details.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import os
2
  import time
3
  import shutil
4
+ import json
5
  import threading
6
+ from http.server import HTTPServer, BaseHTTPRequestHandler
7
+
8
  import duckdb
9
  from huggingface_hub import HfApi, list_repo_files, hf_hub_download
10
 
 
13
  SOURCE_DATASET = "Cistern/Datax"
14
  TARGET_DATASET = "Cistern/Inx"
15
  COLUMNS = ["mobile", "alt", "id", "email"]
16
+ PORT = int(os.environ.get("PORT", 7860))
17
 
18
  DOWNLOAD_DIR = "./tmp_data"
19
  INDEX_PARTS_DIR = "./index_parts"
20
  os.makedirs(DOWNLOAD_DIR, exist_ok=True)
21
  os.makedirs(INDEX_PARTS_DIR, exist_ok=True)
22
 
23
+ # Global state (thread‑safe enough)
24
  LOG_LINES = []
25
  PROGRESS = 0.0
26
  RUNNING = False
 
29
  _lock = threading.Lock()
30
 
31
  def log(msg):
 
32
  timestamp = time.strftime("%H:%M:%S")
33
  full_msg = f"[{timestamp}] {msg}"
34
  print(full_msg, flush=True)
35
  with _lock:
36
  LOG_LINES.append(full_msg)
37
 
38
+ # ── Index worker (unchanged logic) ────────────────────────────────────────────
39
  def index_worker():
40
  global RUNNING, PROGRESS, DONE, ERROR
41
  RUNNING = True
 
162
  RUNNING = False
163
  return
164
 
165
+ # Cleanup & mark as done
166
  shutil.rmtree(DOWNLOAD_DIR, ignore_errors=True)
167
  shutil.rmtree(INDEX_PARTS_DIR, ignore_errors=True)
168
  os.makedirs(DOWNLOAD_DIR, exist_ok=True)
169
  os.makedirs(INDEX_PARTS_DIR, exist_ok=True)
170
 
171
+ # Write marker file to prevent re‑indexing on restart
172
+ with open("indexing_done.txt", "w") as f:
173
+ f.write("success")
174
  log("πŸŽ‰ All indexes built, uploaded, and temp files cleaned.")
175
  DONE = True
176
 
 
180
  finally:
181
  RUNNING = False
182
 
183
+ # ── Minimal HTTP server ───────────────────────────────────────────────────────
184
+ HTML = """<!DOCTYPE html>
185
+ <html lang="en">
186
+ <head>
187
+ <meta charset="UTF-8">
188
+ <meta http-equiv="refresh" content="5">
189
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
190
+ <title>Index Builder</title>
191
+ <style>
192
+ body {
193
+ background: #0e0b24;
194
+ color: #e0e0f0;
195
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
196
+ max-width: 700px;
197
+ margin: 2rem auto;
198
+ padding: 1rem;
199
+ }
200
+ h1 {
201
+ color: #a78bfa;
202
+ font-size: 1.8rem;
203
+ }
204
+ .status {
205
+ margin: 1.5rem 0;
206
+ padding: 1rem;
207
+ border-radius: 12px;
208
+ background: rgba(255,255,255,0.05);
209
+ border: 1px solid rgba(255,255,255,0.1);
210
+ }
211
+ .progress-bar {
212
+ width: 100%;
213
+ height: 12px;
214
+ background: rgba(255,255,255,0.1);
215
+ border-radius: 6px;
216
+ overflow: hidden;
217
+ margin: 1rem 0;
218
+ }
219
+ .progress-fill {
220
+ height: 100%;
221
+ width: PERCENT%;
222
+ background: linear-gradient(90deg, #6c5ce7, #a855f7);
223
+ border-radius: 6px;
224
+ transition: width 0.3s;
225
+ }
226
+ .logs {
227
+ background: #0a0820;
228
+ padding: 0.8rem;
229
+ border-radius: 8px;
230
+ font-family: monospace;
231
+ font-size: 0.85rem;
232
+ max-height: 60vh;
233
+ overflow-y: auto;
234
+ white-space: pre-wrap;
235
+ border: 1px solid #2a2a3e;
236
+ }
237
+ .footer {
238
+ margin-top: 2rem;
239
+ font-size: 0.75rem;
240
+ color: #888;
241
+ }
242
+ </style>
243
+ </head>
244
+ <body>
245
+ <h1>πŸ“‡ Auto‑Index Builder</h1>
246
+ <div class="status">
247
+ STATUS_TEXT
248
+ </div>
249
+ <div class="progress-bar">
250
+ <div class="progress-fill"></div>
251
+ </div>
252
+ <div class="logs">LOGS</div>
253
+ <div class="footer">Refresh to see latest progress | Source: Cistern/Datax β†’ Target: Cistern/Inx</div>
254
+ </body>
255
+ </html>"""
256
+
257
+ class Handler(BaseHTTPRequestHandler):
258
+ def do_GET(self):
259
+ if self.path == "/":
260
+ self.send_response(200)
261
+ self.send_header("Content-type", "text/html")
262
+ self.end_headers()
263
+
264
+ # Determine status text & progress
265
+ if ERROR:
266
+ status = "❌ An error occurred. Check logs below."
267
+ elif DONE:
268
+ status = "βœ… Indexing completed successfully! Four index files are now in Cistern/Inx."
269
+ elif RUNNING:
270
+ status = "⏳ Indexing is running…"
271
+ else:
272
+ status = "⏳ Waiting to start…"
273
+
274
+ # Progress percentage (0‑100)
275
+ pct = int(PROGRESS * 100)
276
+ if pct > 100: pct = 100
277
+
278
+ # Logs (last 50 lines to keep page light)
279
+ with _lock:
280
+ logs = "\n".join(LOG_LINES[-50:]) if LOG_LINES else "No log entries yet."
281
+
282
+ html = HTML.replace("STATUS_TEXT", status)
283
+ html = html.replace("PERCENT", str(pct))
284
+ html = html.replace("LOGS", logs)
285
+
286
+ self.wfile.write(html.encode("utf-8"))
287
+ else:
288
+ self.send_response(404)
289
+ self.end_headers()
290
+
291
+ def log_message(self, format, *args):
292
+ # Suppress HTTP access logs to keep terminal clean
293
+ pass
294
+
295
+ # ── Start server and indexing ─────────────────────────────────────────────────
296
+ if __name__ == "__main__":
297
+ print(f"Starting server on port {PORT}...", flush=True)
298
+
299
+ # If a previous run finished successfully, don't restart indexing
300
+ if not os.path.exists("indexing_done.txt"):
301
+ threading.Thread(target=index_worker, daemon=False).start()
302
+ else:
303
+ DONE = True
304
+ log("βœ… Previous indexing run completed. Skipping re‑index.")
305
+
306
+ httpd = HTTPServer(("0.0.0.0", PORT), Handler)
307
+ print(f"Server running at http://0.0.0.0:{PORT}", flush=True)
308
+ httpd.serve_forever()