Cistern commited on
Commit
e184dea
·
verified ·
1 Parent(s): 008b54f

Rename app.py to pinger.py

Browse files
Files changed (2) hide show
  1. app.py +0 -323
  2. pinger.py +13 -0
app.py DELETED
@@ -1,323 +0,0 @@
1
- import os
2
- import time
3
- import shutil
4
- import threading
5
- import json
6
- import requests
7
- from http.server import HTTPServer, BaseHTTPRequestHandler
8
- from datetime import datetime
9
-
10
- import duckdb
11
- from huggingface_hub import HfApi, list_repo_files, hf_hub_download
12
- from huggingface_hub.utils import HfHubHTTPError
13
-
14
- # ── Configuration ──────────────────────────────────────────────────────────────
15
- HF_TOKEN = os.environ.get("HF_TOKEN", "")
16
- SOURCE_DATASET = "Cistern/Datax"
17
- TARGET_DATASET = "Cistern/Inx"
18
- COLUMNS = ["mobile", "alt", "email", "id"] # processed in this order per file
19
- PORT = int(os.environ.get("PORT", 7860))
20
-
21
- DOWNLOAD_DIR = "./tmp_data"
22
- INDEX_PARTS_DIR = "./index_parts"
23
- os.makedirs(DOWNLOAD_DIR, exist_ok=True)
24
- os.makedirs(INDEX_PARTS_DIR, exist_ok=True)
25
-
26
- # Global state
27
- LOG_LINES = []
28
- PROGRESS = 0.0
29
- RUNNING = False
30
- DONE = False
31
- ERROR = False
32
- TOTAL_FILES = 0
33
- PROCESSED_FILES = 0
34
- _lock = threading.Lock()
35
-
36
- def log(msg):
37
- timestamp = time.strftime("%H:%M:%S")
38
- full_msg = f"[{timestamp}] {msg}"
39
- print(full_msg, flush=True)
40
- with _lock:
41
- LOG_LINES.append(full_msg)
42
-
43
- # ── Retry helper ──────────────────────────────────────────────────────────────
44
- def retry(func, *args, max_retries=5, initial_delay=2, **kwargs):
45
- delay = initial_delay
46
- for attempt in range(max_retries):
47
- try:
48
- return func(*args, **kwargs)
49
- except (HfHubHTTPError, requests.exceptions.RequestException) as e:
50
- status = getattr(e, 'response', None) and getattr(e.response, 'status_code', None)
51
- if status == 429 or (status and status >= 500):
52
- log(f"⚠️ Rate limited (HTTP {status}). Retrying in {delay}s (attempt {attempt+1}/{max_retries})...")
53
- time.sleep(delay)
54
- delay *= 2
55
- else:
56
- raise
57
- return func(*args, **kwargs)
58
-
59
- # ── Upload progress.json ──────────────────────────────────────────────────────
60
- def upload_progress():
61
- progress = {
62
- "processed_files": PROCESSED_FILES,
63
- "total_files": TOTAL_FILES,
64
- "last_updated": datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S UTC"),
65
- "last_log_lines": LOG_LINES[-5:] if LOG_LINES else []
66
- }
67
- progress_path = "./progress.json"
68
- with open(progress_path, "w") as f:
69
- json.dump(progress, f, indent=2)
70
- try:
71
- api = HfApi()
72
- retry(
73
- api.upload_file,
74
- path_or_fileobj=progress_path,
75
- path_in_repo="progress.json",
76
- repo_id=TARGET_DATASET,
77
- repo_type="dataset",
78
- token=HF_TOKEN,
79
- )
80
- except Exception as e:
81
- log(f" ⚠️ Failed to upload progress.json: {e}")
82
- os.remove(progress_path)
83
-
84
- # ── Final merge and upload of all index parts ────────────────────────────────
85
- def final_merge_and_upload(con, total_files):
86
- api = HfApi()
87
- for col in COLUMNS:
88
- part_dir = os.path.join(INDEX_PARTS_DIR, col)
89
- if not os.path.exists(part_dir) or not os.listdir(part_dir):
90
- log(f" ❌ No parts found for {col} – skipping.")
91
- continue
92
- all_parts = os.path.join(part_dir, "*.parquet")
93
- final_path = os.path.join(os.getcwd(), f"{col}_index.parquet")
94
- try:
95
- log(f" 📦 Merging all {len(os.listdir(part_dir))} parts for {col} ...")
96
- con.execute(f"""
97
- COPY (
98
- SELECT * FROM read_parquet('{all_parts}')
99
- ORDER BY search_value
100
- ) TO '{final_path}' (
101
- FORMAT PARQUET,
102
- COMPRESSION ZSTD,
103
- ROW_GROUP_SIZE 1000000
104
- )
105
- """)
106
- file_size = os.path.getsize(final_path) / (1024**2)
107
- log(f" ✅ {col} index size: {file_size:.1f} MB. Uploading...")
108
- retry(
109
- api.upload_file,
110
- path_or_fileobj=final_path,
111
- path_in_repo=f"{col}_index.parquet",
112
- repo_id=TARGET_DATASET,
113
- repo_type="dataset",
114
- token=HF_TOKEN,
115
- )
116
- log(f" 📤 Uploaded {col}_index.parquet")
117
- except Exception as e:
118
- log(f" ❌ Final merge/upload failed for {col}: {e}")
119
- raise
120
-
121
- # ── Index worker ─────────────────────────────────────────────────────────────
122
- def index_worker():
123
- global RUNNING, PROGRESS, DONE, ERROR, TOTAL_FILES, PROCESSED_FILES
124
- RUNNING = True
125
- api = HfApi()
126
- try:
127
- all_files = retry(list_repo_files, SOURCE_DATASET, repo_type="dataset", token=HF_TOKEN)
128
- data_files = [
129
- f for f in all_files
130
- if f.startswith("data/Hi-Tek_Part_") and f.endswith(".parquet")
131
- ]
132
- data_files = sorted(data_files)
133
- if not data_files:
134
- log("❌ No Hi-Tek_Part_*.parquet files found in data/ folder.")
135
- ERROR = True
136
- RUNNING = False
137
- return
138
-
139
- TOTAL_FILES = len(data_files)
140
- PROCESSED_FILES = 0
141
- log(f"🔍 Found {TOTAL_FILES} data files. Processing columns together: {COLUMNS}")
142
-
143
- # Ensure clean start – delete any leftover parts from previous runs
144
- for col in COLUMNS:
145
- col_dir = os.path.join(INDEX_PARTS_DIR, col)
146
- if os.path.exists(col_dir):
147
- shutil.rmtree(col_dir)
148
- os.makedirs(col_dir, exist_ok=True)
149
-
150
- con = duckdb.connect()
151
- con.execute("SET threads=4")
152
- con.execute("SET memory_limit='2GB'")
153
-
154
- for idx, file_path in enumerate(data_files):
155
- log(f"⬇️ Downloading {file_path} ({idx+1}/{TOTAL_FILES})")
156
- try:
157
- local_path = retry(
158
- hf_hub_download,
159
- repo_id=SOURCE_DATASET,
160
- filename=file_path,
161
- repo_type="dataset",
162
- token=HF_TOKEN,
163
- cache_dir=DOWNLOAD_DIR,
164
- force_download=False
165
- )
166
- file_size_mb = os.path.getsize(local_path) / (1024**2)
167
- log(f" 📦 Downloaded {file_size_mb:.1f} MB")
168
- except Exception as e:
169
- log(f"❌ Download failed after retries: {e}")
170
- ERROR = True
171
- RUNNING = False
172
- return
173
-
174
- try:
175
- meta = con.execute(f"""
176
- SELECT row_group_id,
177
- row_group_num_rows,
178
- SUM(row_group_num_rows) OVER (ORDER BY row_group_id) - row_group_num_rows AS row_start,
179
- SUM(row_group_num_rows) OVER (ORDER BY row_group_id) - 1 AS row_end
180
- FROM parquet_metadata('{local_path}')
181
- WHERE row_group_id IS NOT NULL
182
- ORDER BY row_group_id
183
- """).fetchdf()
184
-
185
- if meta.empty:
186
- os.remove(local_path)
187
- continue
188
-
189
- rows_indexed = {}
190
- for col in COLUMNS:
191
- # ✅ ORDER BY row_start fix for ASOF join
192
- query = f"""
193
- WITH raw AS (
194
- SELECT "{col}", file_row_number
195
- FROM read_parquet('{local_path}', file_row_number=true)
196
- WHERE "{col}" IS NOT NULL
197
- ),
198
- boundaries AS (
199
- SELECT row_group_id, row_start, row_end
200
- FROM meta
201
- ORDER BY row_start
202
- )
203
- SELECT raw."{col}" AS search_value,
204
- '{file_path}' AS filename,
205
- boundaries.row_group_id,
206
- boundaries.row_start,
207
- boundaries.row_end
208
- FROM raw
209
- ASOF LEFT JOIN boundaries
210
- ON raw.file_row_number >= boundaries.row_start
211
- """
212
- part_df = con.execute(query).fetchdf()
213
- if not part_df.empty:
214
- part_dir = os.path.join(INDEX_PARTS_DIR, col)
215
- out_path = os.path.join(part_dir, f"{idx:04d}_{os.path.basename(file_path)}.parquet")
216
- part_df.to_parquet(out_path, index=False)
217
- rows_indexed[col] = len(part_df)
218
-
219
- os.remove(local_path)
220
- log(f"✅ Processed {file_path} (rows indexed: {rows_indexed})")
221
- PROCESSED_FILES = idx + 1
222
- with _lock:
223
- PROGRESS = PROCESSED_FILES / TOTAL_FILES
224
-
225
- # Every 100 files, log progress and upload progress.json (no partial index uploads)
226
- if PROCESSED_FILES % 100 == 0:
227
- log(f"📊 {PROCESSED_FILES}/{TOTAL_FILES} files processed.")
228
- upload_progress()
229
-
230
- except Exception as e:
231
- log(f"❌ Error processing {file_path}: {e}")
232
- ERROR = True
233
- RUNNING = False
234
- return
235
-
236
- # All files processed – now merge and upload final index files
237
- log("🎉 All files processed. Starting final merge & upload...")
238
- final_merge_and_upload(con, TOTAL_FILES)
239
-
240
- # Final cleanup
241
- shutil.rmtree(DOWNLOAD_DIR, ignore_errors=True)
242
- shutil.rmtree(INDEX_PARTS_DIR, ignore_errors=True)
243
- os.makedirs(DOWNLOAD_DIR, exist_ok=True)
244
- os.makedirs(INDEX_PARTS_DIR, exist_ok=True)
245
-
246
- with open("indexing_done.txt", "w") as f:
247
- f.write("success")
248
- log("✅ All indexes built, uploaded, and temp files cleaned.")
249
- DONE = True
250
-
251
- except Exception as e:
252
- log(f"💥 Unexpected error: {e}")
253
- ERROR = True
254
- finally:
255
- RUNNING = False
256
-
257
- # ── Minimal dark UI ───────────────────────────────────────────────────────────
258
- def build_html():
259
- if ERROR:
260
- status = "❌ An error occurred."
261
- elif DONE:
262
- status = "✅ Indexing completed successfully!"
263
- elif RUNNING:
264
- status = f"⏳ Processing file {PROCESSED_FILES} of {TOTAL_FILES}"
265
- else:
266
- status = "⏳ Waiting to start…"
267
-
268
- pct = int(PROGRESS * 100)
269
- if pct > 100: pct = 100
270
-
271
- with _lock:
272
- recent_logs = LOG_LINES[-50:] if LOG_LINES else ["No log entries yet."]
273
-
274
- logs_text = "\n".join(recent_logs)
275
-
276
- html = f"""<html>
277
- <head>
278
- <meta charset="UTF-8">
279
- <meta http-equiv="refresh" content="2">
280
- <title>Index Builder</title>
281
- </head>
282
- <body style="background:#000000; color:#00ff88; font-family:'Courier New',monospace; font-size:14px; margin:0; padding:10px; white-space:pre-wrap;">
283
- Progress: {pct}% {status}
284
- ────────────────────────────────────────────────────
285
- {logs_text}
286
- ────────────────────────────────────────────────────
287
- Indexing runs on the server – you can safely close this page.
288
- </body>
289
- </html>"""
290
- return html
291
-
292
- class Handler(BaseHTTPRequestHandler):
293
- def do_GET(self):
294
- try:
295
- if self.path == "/":
296
- self.send_response(200)
297
- self.send_header("Content-type", "text/html; charset=utf-8")
298
- self.end_headers()
299
- self.wfile.write(build_html().encode("utf-8"))
300
- else:
301
- self.send_response(404)
302
- self.end_headers()
303
- except Exception as e:
304
- self.send_response(500)
305
- self.end_headers()
306
- self.wfile.write(f"Error generating page: {e}".encode())
307
-
308
- def log_message(self, format, *args):
309
- pass
310
-
311
- # ── Start server and indexing ─────────────────────────────────────────────────
312
- if __name__ == "__main__":
313
- print(f"Starting server on port {PORT}...", flush=True)
314
-
315
- if not os.path.exists("indexing_done.txt"):
316
- threading.Thread(target=index_worker, daemon=False).start()
317
- else:
318
- DONE = True
319
- log("✅ Previous indexing run completed. Skipping re‑index.")
320
-
321
- httpd = HTTPServer(("0.0.0.0", PORT), Handler)
322
- print(f"Server running at http://0.0.0.0:{PORT}", flush=True)
323
- httpd.serve_forever()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
pinger.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import time
2
+ import requests
3
+
4
+ # Yahan wahi URL dalein jisme ye file rakhi hai
5
+ URL = "https://Cistern-Cxv.hf.space"
6
+
7
+ while True:
8
+ try:
9
+ requests.get(URL)
10
+ print(f"Pinged {URL} successfully!")
11
+ except Exception as e:
12
+ print(f"Error: {e}")
13
+ time.sleep(300) # 5 minute