Hfzune commited on
Commit
542e5e3
·
verified ·
1 Parent(s): 62d737c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +144 -85
app.py CHANGED
@@ -26,6 +26,9 @@ import pandas as pd
26
  import gradio as gr
27
  from huggingface_hub import HfApi, hf_hub_download
28
  from bharataddress import parse
 
 
 
29
 
30
  # -------------------------------------------------------------------
31
  # 2. CONFIGURATION & GLOBAL STATE
@@ -40,10 +43,12 @@ api = HfApi()
40
  PROCESSING_STATE = {
41
  "status": "idle", # idle, running, paused, finished, error
42
  "current_file": "",
43
- "current_batch": 0,
44
- "total_rows_processed": 0,
45
- "message": "Waiting to start...",
46
- "target_repo": DEFAULT_TARGET
 
 
47
  }
48
 
49
  STOP_FLAG = threading.Event()
@@ -69,14 +74,41 @@ def get_state_safe(addr):
69
  pass
70
  return "Unknown"
71
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72
  def background_worker(file_list, target_repo, test_mode):
73
  global PROCESSING_STATE
74
 
75
  PROCESSING_STATE["status"] = "running"
76
- PROCESSING_STATE["message"] = "Starting background worker..."
 
 
 
77
 
78
- # Load or create checkpoint
79
- checkpoint_file = "checkpoint.json"
80
  processed_files = []
81
  if os.path.exists(checkpoint_file):
82
  with open(checkpoint_file, "r") as f:
@@ -85,124 +117,115 @@ def background_worker(file_list, target_repo, test_mode):
85
  work_dir = "./temp_processing"
86
  os.makedirs(work_dir, exist_ok=True)
87
 
88
- total_records_processed = 0
89
- MAX_TEST_RECORDS = 2000
 
 
 
90
 
91
- for filename in file_list:
92
- if STOP_FLAG.is_set():
93
- PROCESSING_STATE["status"] = "idle"
94
- PROCESSING_STATE["message"] = "Stopped by user."
95
- return
96
-
97
- if filename in processed_files:
98
- continue
99
 
100
  PROCESSING_STATE["current_file"] = filename
101
- PROCESSING_STATE["current_batch"] = 0
102
- PROCESSING_STATE["message"] = f"Downloading {filename}..."
103
 
104
  try:
105
- # 1. Download the file
106
  local_path = hf_hub_download(
107
  repo_id=DEFAULT_SOURCE, filename=filename, repo_type="dataset", token=HF_TOKEN, local_dir=work_dir
108
  )
109
 
110
- # 2. Open as ParquetFile to read in batches
111
  pf = pq.ParquetFile(local_path)
112
- batch_size = 1000
113
 
114
- # 3. Process batches
115
- for batch in pf.iter_batches(batch_size=batch_size):
116
- if STOP_FLAG.is_set():
117
- PROCESSING_STATE["status"] = "idle"
118
- PROCESSING_STATE["message"] = "Stopped by user."
119
- return
120
-
121
  while PAUSE_FLAG.is_set():
122
  PROCESSING_STATE["status"] = "paused"
123
  time.sleep(1)
124
  if STOP_FLAG.is_set(): return
125
 
126
  PROCESSING_STATE["status"] = "running"
127
- PROCESSING_STATE["current_batch"] += 1
128
- PROCESSING_STATE["message"] = f"Processing {filename} - Batch {PROCESSING_STATE['current_batch']}..."
129
-
130
  df = batch.to_pandas()
131
- if 'address' not in df.columns:
132
- break
133
 
134
- # Parse states
135
  df['state_extracted'] = df['address'].apply(get_state_safe)
136
- df['source_file'] = filename
137
 
138
- # Upload grouped data
 
 
 
 
 
 
 
 
 
 
 
 
 
139
  grouped = df.groupby('state_extracted')
140
  for state_name, state_df in grouped:
141
- # Save batch uniquely so we don't overwrite previous batches
142
- repo_path = f"{state_name}/{filename}_batch_{PROCESSING_STATE['current_batch']}.parquet"
143
- local_state_path = f"{work_dir}/temp_batch.parquet"
144
-
145
- state_df.to_parquet(local_state_path, index=False)
146
 
147
- api.upload_file(
148
- path_or_fileobj=local_state_path,
149
- path_in_repo=repo_path,
150
- repo_id=target_repo,
151
- repo_type="dataset",
152
- token=HF_TOKEN
153
- )
154
-
155
- total_records_processed += len(df)
156
 
157
- # Test mode limit
158
- if test_mode and total_records_processed >= MAX_TEST_RECORDS:
159
- PROCESSING_STATE["message"] = f"✅ Test Mode Complete! Processed {total_records_processed} records."
160
- PROCESSING_STATE["status"] = "finished"
161
- return
162
 
163
- # Mark file as completed
164
  processed_files.append(filename)
165
  with open(checkpoint_file, "w") as f:
166
  json.dump({"processed_files": processed_files}, f)
167
 
168
  os.remove(local_path)
 
169
 
170
  except Exception as e:
171
- PROCESSING_STATE["message"] = f"❌ Error on {filename}: {str(e)}"
172
  PROCESSING_STATE["status"] = "error"
173
  return
174
 
 
 
 
 
 
175
  PROCESSING_STATE["status"] = "finished"
176
- PROCESSING_STATE["message"] = "🎉 All selected files processed successfully!"
177
 
178
  # -------------------------------------------------------------------
179
  # 5. GRADIO UI & CONTROLS
180
  # -------------------------------------------------------------------
181
- def start_processing(target_repo, start_idx, end_idx, test_mode):
182
- global PROCESSING_STATE
183
  if PROCESSING_STATE["status"] == "running":
184
  return "Already running!"
185
 
186
- # Reset flags
187
  STOP_FLAG.clear()
188
  PAUSE_FLAG.clear()
189
 
190
- # Get files
191
  try:
192
  files = api.list_repo_files(repo_id=DEFAULT_SOURCE, repo_type="dataset")
193
  parquet_files = sorted([f for f in files if f.endswith('.parquet')])
194
- selected_files = parquet_files[int(start_idx):int(end_idx)]
 
 
 
195
  except Exception as e:
196
  return f"Failed to get file list: {e}"
197
 
198
  if not selected_files:
199
  return "No files selected."
200
 
201
- PROCESSING_STATE["target_repo"] = target_repo
202
- PROCESSING_STATE["total_rows_processed"] = 0
203
- PROCESSING_STATE["status"] = "running"
204
-
205
- # Start thread
206
  thread = threading.Thread(
207
  target=background_worker,
208
  args=(selected_files, target_repo, test_mode),
@@ -225,30 +248,41 @@ def stop_processing():
225
  return "Stopping..."
226
 
227
  def get_status():
228
- if not HF_TOKEN:
229
- return "HF_TOKEN missing!"
230
 
231
  status = PROCESSING_STATE["status"].upper()
232
- msg = PROCESSING_STATE["message"]
233
  file = PROCESSING_STATE.get("current_file", "")
234
- rows = PROCESSING_STATE.get("total_rows_processed", 0)
 
 
 
 
235
 
236
- return f"[{status}]\n\nCurrent File: {file}\nTotal Rows Processed: {rows}\n\nStatus: {msg}"
 
 
 
 
 
 
 
 
237
 
238
  with gr.Blocks(title="Massive Dataset State Splitter") as demo:
239
- gr.Markdown("# 🗂️ Robust State Splitter (Chunked & Background)")
240
 
241
- # ZeroGPU dummy button
242
  _zerogpu_btn = gr.Button("init-gpu", visible=False)
243
  _zerogpu_btn.click(fn=_zerogpu_register, inputs=None, outputs=None)
244
 
245
  with gr.Row():
246
  with gr.Column():
247
- target_input = gr.Textbox(label="Target Repo ID", value=DEFAULT_TARGET)
248
- with gr.Row():
 
 
249
  start_idx = gr.Number(label="Start File Index", value=0, precision=0)
250
  end_idx = gr.Number(label="End File Index", value=1, precision=0)
251
- test_mode_cb = gr.Checkbox(label="🧪 Test Mode (Stops after 2000 rows)", value=True)
252
 
253
  with gr.Row():
254
  start_btn = gr.Button("▶️ Start", variant="primary")
@@ -257,18 +291,43 @@ with gr.Blocks(title="Massive Dataset State Splitter") as demo:
257
  stop_btn = gr.Button("⏹️ Stop", variant="stop")
258
 
259
  with gr.Column():
260
- status_box = gr.Textbox(label="Live Status", lines=8, interactive=False)
261
- gr.Markdown("*Tip: You can close this tab and it will keep running in the background. Re-open to check status.*")
262
 
263
- # Wire up buttons
264
- start_btn.click(start_processing, [target_input, start_idx, end_idx, test_mode_cb], status_box)
 
 
 
265
  pause_btn.click(pause_processing, None, status_box)
266
  resume_btn.click(resume_processing, None, status_box)
267
  stop_btn.click(stop_processing, None, status_box)
268
 
269
- # Auto-refresh status every 2 seconds
270
  timer = gr.Timer(2.0)
271
  timer.tick(get_status, None, status_box)
272
 
 
 
 
 
 
 
 
 
 
 
273
  if __name__ == "__main__":
274
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26
  import gradio as gr
27
  from huggingface_hub import HfApi, hf_hub_download
28
  from bharataddress import parse
29
+ from fastapi import Request
30
+ from fastapi.responses import JSONResponse
31
+ from starlette.routing import Route as StarletteRoute
32
 
33
  # -------------------------------------------------------------------
34
  # 2. CONFIGURATION & GLOBAL STATE
 
43
  PROCESSING_STATE = {
44
  "status": "idle", # idle, running, paused, finished, error
45
  "current_file": "",
46
+ "total_records": 0,
47
+ "states_found": set(),
48
+ "start_time": 0,
49
+ "eta": "Calculating...",
50
+ "speed": 0,
51
+ "logs": []
52
  }
53
 
54
  STOP_FLAG = threading.Event()
 
74
  pass
75
  return "Unknown"
76
 
77
+ def flush_buffer(state_name, buffer_list, target_repo, work_dir):
78
+ """Combines buffered dataframes and uploads as a single large parquet file."""
79
+ if not buffer_list: return
80
+ try:
81
+ combined_df = pd.concat(buffer_list, ignore_index=True)
82
+ # Create a unique filename based on state and timestamp
83
+ filename = f"{state_name}/part_{int(time.time() * 1000)}_{len(combined_df)}rows.parquet"
84
+ local_path = os.path.join(work_dir, "temp_upload.parquet")
85
+
86
+ combined_df.to_parquet(local_path, index=False)
87
+
88
+ api.upload_file(
89
+ path_or_fileobj=local_path,
90
+ path_in_repo=filename,
91
+ repo_id=target_repo,
92
+ repo_type="dataset",
93
+ token=HF_TOKEN
94
+ )
95
+ os.remove(local_path)
96
+ PROCESSING_STATE["logs"].append(f"📤 Uploaded {len(combined_df)} rows to {filename}")
97
+ if len(PROCESSING_STATE["logs"]) > 50: PROCESSING_STATE["logs"].pop(0)
98
+ except Exception as e:
99
+ PROCESSING_STATE["logs"].append(f"❌ Upload failed for {state_name}: {e}")
100
+
101
  def background_worker(file_list, target_repo, test_mode):
102
  global PROCESSING_STATE
103
 
104
  PROCESSING_STATE["status"] = "running"
105
+ PROCESSING_STATE["start_time"] = time.time()
106
+ PROCESSING_STATE["total_records"] = 0
107
+ PROCESSING_STATE["states_found"] = set()
108
+ PROCESSING_STATE["logs"] = ["🚀 Worker started..."]
109
 
110
+ # Checkpoint file scoped to the specific target repo
111
+ checkpoint_file = f"checkpoint_{target_repo.replace('/', '_')}.json"
112
  processed_files = []
113
  if os.path.exists(checkpoint_file):
114
  with open(checkpoint_file, "r") as f:
 
117
  work_dir = "./temp_processing"
118
  os.makedirs(work_dir, exist_ok=True)
119
 
120
+ MAX_TEST_RECORDS = 5000
121
+ FLUSH_THRESHOLD = 50000 # Buffer 50k rows before creating a file
122
+
123
+ state_buffers = {} # Dictionary to hold pandas DataFrames per state
124
+ total_files = len(file_list)
125
 
126
+ for i, filename in enumerate(file_list):
127
+ if STOP_FLAG.is_set(): break
128
+ if filename in processed_files: continue
 
 
 
 
 
129
 
130
  PROCESSING_STATE["current_file"] = filename
131
+ PROCESSING_STATE["logs"].append(f"📥 Processing {filename} ({i+1}/{total_files})")
 
132
 
133
  try:
 
134
  local_path = hf_hub_download(
135
  repo_id=DEFAULT_SOURCE, filename=filename, repo_type="dataset", token=HF_TOKEN, local_dir=work_dir
136
  )
137
 
 
138
  pf = pq.ParquetFile(local_path)
 
139
 
140
+ for batch in pf.iter_batches(batch_size=2000):
141
+ if STOP_FLAG.is_set(): break
142
+
 
 
 
 
143
  while PAUSE_FLAG.is_set():
144
  PROCESSING_STATE["status"] = "paused"
145
  time.sleep(1)
146
  if STOP_FLAG.is_set(): return
147
 
148
  PROCESSING_STATE["status"] = "running"
149
+
 
 
150
  df = batch.to_pandas()
151
+ if 'address' not in df.columns: break
 
152
 
 
153
  df['state_extracted'] = df['address'].apply(get_state_safe)
 
154
 
155
+ # Update Metrics
156
+ PROCESSING_STATE["total_records"] += len(df)
157
+ PROCESSING_STATE["states_found"].update(df['state_extracted'].unique())
158
+
159
+ elapsed = time.time() - PROCESSING_STATE["start_time"]
160
+ PROCESSING_STATE["speed"] = PROCESSING_STATE["total_records"] / elapsed if elapsed > 0 else 0
161
+
162
+ # ETA Calculation (Based on files processed)
163
+ files_done = i + 1
164
+ avg_time_per_file = elapsed / files_done
165
+ eta_sec = avg_time_per_file * (total_files - files_done)
166
+ PROCESSING_STATE["eta"] = f"{int(eta_sec // 60)}m {int(eta_sec % 60)}s"
167
+
168
+ # Append to buffers
169
  grouped = df.groupby('state_extracted')
170
  for state_name, state_df in grouped:
171
+ if state_name not in state_buffers:
172
+ state_buffers[state_name] = []
173
+ state_buffers[state_name].append(state_df)
 
 
174
 
175
+ # Check if buffer is large enough to flush
176
+ current_buffer_size = sum(len(d) for d in state_buffers[state_name])
177
+ if current_buffer_size >= FLUSH_THRESHOLD:
178
+ flush_buffer(state_name, state_buffers[state_name], target_repo, work_dir)
179
+ state_buffers[state_name] = [] # Clear buffer
 
 
 
 
180
 
181
+ if test_mode and PROCESSING_STATE["total_records"] >= MAX_TEST_RECORDS:
182
+ PROCESSING_STATE["logs"].append("🧪 Test mode limit reached.")
183
+ STOP_FLAG.set()
184
+ break
 
185
 
 
186
  processed_files.append(filename)
187
  with open(checkpoint_file, "w") as f:
188
  json.dump({"processed_files": processed_files}, f)
189
 
190
  os.remove(local_path)
191
+ if STOP_FLAG.is_set(): break
192
 
193
  except Exception as e:
194
+ PROCESSING_STATE["logs"].append(f"❌ Error on {filename}: {e}")
195
  PROCESSING_STATE["status"] = "error"
196
  return
197
 
198
+ # Flush any remaining data in buffers
199
+ PROCESSING_STATE["logs"].append("🧹 Flushing remaining buffers to Hub...")
200
+ for state_name, buf in state_buffers.items():
201
+ flush_buffer(state_name, buf, target_repo, work_dir)
202
+
203
  PROCESSING_STATE["status"] = "finished"
204
+ PROCESSING_STATE["logs"].append("🎉 All selected files processed successfully!")
205
 
206
  # -------------------------------------------------------------------
207
  # 5. GRADIO UI & CONTROLS
208
  # -------------------------------------------------------------------
209
+ def start_processing(target_repo, test_mode, one_shot_mode, start_idx, end_idx):
 
210
  if PROCESSING_STATE["status"] == "running":
211
  return "Already running!"
212
 
 
213
  STOP_FLAG.clear()
214
  PAUSE_FLAG.clear()
215
 
 
216
  try:
217
  files = api.list_repo_files(repo_id=DEFAULT_SOURCE, repo_type="dataset")
218
  parquet_files = sorted([f for f in files if f.endswith('.parquet')])
219
+ if one_shot_mode:
220
+ selected_files = parquet_files
221
+ else:
222
+ selected_files = parquet_files[int(start_idx):int(end_idx)]
223
  except Exception as e:
224
  return f"Failed to get file list: {e}"
225
 
226
  if not selected_files:
227
  return "No files selected."
228
 
 
 
 
 
 
229
  thread = threading.Thread(
230
  target=background_worker,
231
  args=(selected_files, target_repo, test_mode),
 
248
  return "Stopping..."
249
 
250
  def get_status():
251
+ if not HF_TOKEN: return "HF_TOKEN missing!"
 
252
 
253
  status = PROCESSING_STATE["status"].upper()
 
254
  file = PROCESSING_STATE.get("current_file", "")
255
+ rows = PROCESSING_STATE.get("total_records", 0)
256
+ speed = PROCESSING_STATE.get("speed", 0)
257
+ eta = PROCESSING_STATE.get("eta", "N/A")
258
+ states = ", ".join(list(PROCESSING_STATE.get("states_found", []))[:5])
259
+ if len(PROCESSING_STATE.get("states_found", [])) > 5: states += "..."
260
 
261
+ header = f"**STATUS:** {status}\n"
262
+ header += f"**Records Processed:** {rows:,} ({speed:.1f} rec/sec)\n"
263
+ header += f"**ETA:** {eta}\n"
264
+ header += f"**States Found:** {len(PROCESSING_STATE.get('states_found', []))} ({states})\n"
265
+ header += f"**Current File:** {file}\n\n"
266
+ header += "### Live Logs:\n"
267
+ header += "\n".join(PROCESSING_STATE.get("logs", [])[-10:])
268
+
269
+ return header
270
 
271
  with gr.Blocks(title="Massive Dataset State Splitter") as demo:
272
+ gr.Markdown("# 🗂️ One-Shot State Splitter & Speed Metrics")
273
 
 
274
  _zerogpu_btn = gr.Button("init-gpu", visible=False)
275
  _zerogpu_btn.click(fn=_zerogpu_register, inputs=None, outputs=None)
276
 
277
  with gr.Row():
278
  with gr.Column():
279
+ target_input = gr.Textbox(label="Target Repo ID (Will be created if missing)", value=DEFAULT_TARGET)
280
+ one_shot_cb = gr.Checkbox(label="🚀 ONE-SHOT MODE (Process all 851 files)", value=True)
281
+
282
+ with gr.Accordion("Advanced Settings (Ignore if One-Shot)", open=False):
283
  start_idx = gr.Number(label="Start File Index", value=0, precision=0)
284
  end_idx = gr.Number(label="End File Index", value=1, precision=0)
285
+ test_mode_cb = gr.Checkbox(label="🧪 Test Mode (Stops after 5000 rows)", value=False)
286
 
287
  with gr.Row():
288
  start_btn = gr.Button("▶️ Start", variant="primary")
 
291
  stop_btn = gr.Button("⏹️ Stop", variant="stop")
292
 
293
  with gr.Column():
294
+ status_box = gr.Markdown("Waiting to start...")
 
295
 
296
+ start_btn.click(
297
+ start_processing,
298
+ [target_input, test_mode_cb, one_shot_cb, start_idx, end_idx],
299
+ status_box
300
+ )
301
  pause_btn.click(pause_processing, None, status_box)
302
  resume_btn.click(resume_processing, None, status_box)
303
  stop_btn.click(stop_processing, None, status_box)
304
 
 
305
  timer = gr.Timer(2.0)
306
  timer.tick(get_status, None, status_box)
307
 
308
+ # -------------------------------------------------------------------
309
+ # 6. HEALTH ENDPOINT FOR CRON JOBS
310
+ # -------------------------------------------------------------------
311
+ async def health_check(request: Request):
312
+ return JSONResponse({
313
+ "status": "ok",
314
+ "worker_status": PROCESSING_STATE["status"],
315
+ "records_processed": PROCESSING_STATE["total_records"]
316
+ })
317
+
318
  if __name__ == "__main__":
319
+ # Launch with thread lock prevention and SSR disabled for route injection
320
+ demo.launch(
321
+ server_name="0.0.0.0",
322
+ server_port=7860,
323
+ share=False,
324
+ ssr_mode=False,
325
+ prevent_thread_lock=True
326
+ )
327
+
328
+ # Inject /health at index 0 to override Gradio's catch-all
329
+ live_app = demo.app
330
+ live_app.router.routes.insert(0, StarletteRoute("/health", health_check, methods=["GET"]))
331
+ live_app.build_middleware_stack()
332
+
333
+ demo.block_thread()