Samfredoly commited on
Commit
406a380
·
verified ·
1 Parent(s): 67a1cd2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +308 -375
app.py CHANGED
@@ -1,385 +1,318 @@
1
- """
2
- FastAPI application for HF Uploader Dashboard
3
- """
4
  import os
5
- import asyncio
 
 
 
 
 
 
6
  import logging
7
- from contextlib import asynccontextmanager
8
- from fastapi import FastAPI, Depends, HTTPException, UploadFile, File
9
- from fastapi.responses import FileResponse, JSONResponse
10
- from fastapi.staticfiles import StaticFiles
11
- from sqlalchemy.orm import Session
12
- from datetime import datetime
13
 
14
- from database import init_db, get_db, SessionLocal
15
- from models import (
16
- HFConfig,
17
- UploadQueue,
18
- UploadStatusEnum,
19
- ProcessingState,
20
- ProcessingStatusEnum,
21
- UploadErrorLog,
22
- )
23
- from schemas import (
24
- HFConfigUpdate,
25
- HFConfigResponse,
26
- UploadQueueItem,
27
- UploadQueueStats,
28
- ProcessingStateResponse,
29
- ProcessRequest,
30
- UploadRequest,
31
- FilePreviewRequest,
32
- FilePreviewResponse,
33
- RateLimitStatus,
34
- UploadStatus,
35
- ErrorLogResponse,
36
- )
37
- from file_processor import FileProcessor
38
- from hf_uploader import HFUploader
39
-
40
- # Configure logging
41
- logging.basicConfig(level=logging.INFO)
42
- logger = logging.getLogger(__name__)
43
-
44
- # Global instances
45
- file_processor = FileProcessor(processed_files_dir="processed_files")
46
- hf_uploader_instance = None
47
-
48
-
49
- @asynccontextmanager
50
- async def lifespan(app: FastAPI):
51
- """Lifespan context manager for startup and shutdown"""
52
- # Startup
53
- logger.info("Initializing database...")
54
- init_db()
55
- logger.info("Application started")
56
- yield
57
- # Shutdown
58
- logger.info("Application shutting down...")
59
-
60
-
61
- # Create FastAPI app
62
- app = FastAPI(
63
- title="HF Uploader Dashboard",
64
- description="Hugging Face Dataset Uploader with Rate Limiting",
65
- version="1.0.0",
66
- lifespan=lifespan,
67
- )
68
-
69
-
70
- # ============================================================================
71
- # Configuration Endpoints
72
- # ============================================================================
73
-
74
-
75
- @app.get("/api/config", response_model=HFConfigResponse)
76
- async def get_config(db: Session = Depends(get_db)):
77
- """Get current HF configuration"""
78
- config = db.query(HFConfig).first()
79
- if not config:
80
- # Create default config
81
- config = HFConfig()
82
- db.add(config)
83
- db.commit()
84
- db.refresh(config)
85
- return config
86
-
87
-
88
- @app.post("/api/config", response_model=HFConfigResponse)
89
- async def update_config(
90
- config_update: HFConfigUpdate, db: Session = Depends(get_db)
91
- ):
92
- """Update HF configuration"""
93
- config = db.query(HFConfig).first()
94
- if not config:
95
- config = HFConfig()
96
- db.add(config)
97
-
98
- # Update fields
99
- update_data = config_update.model_dump(exclude_unset=True)
100
- for field, value in update_data.items():
101
- setattr(config, field, value)
102
-
103
- config.updated_at = datetime.utcnow()
104
- db.commit()
105
- db.refresh(config)
106
-
107
- # Update global uploader instance
108
- global hf_uploader_instance
109
- if config.hf_token:
110
- hf_uploader_instance = HFUploader(config.hf_token, config.target_repo)
111
-
112
- return config
113
-
114
-
115
- # ============================================================================
116
- # Upload Queue Endpoints
117
- # ============================================================================
118
-
119
-
120
- @app.get("/api/queue", response_model=list[UploadQueueItem])
121
- async def get_upload_queue(
122
- status: str = None, db: Session = Depends(get_db)
123
- ):
124
- """Get upload queue items"""
125
- query = db.query(UploadQueue)
126
- if status:
127
- query = query.filter(UploadQueue.status == status)
128
- return query.all()
129
-
130
-
131
- @app.get("/api/queue/stats", response_model=UploadQueueStats)
132
- async def get_queue_stats(db: Session = Depends(get_db)):
133
- """Get upload queue statistics"""
134
- all_items = db.query(UploadQueue).all()
135
- return UploadQueueStats(
136
- pending=len([i for i in all_items if i.status == UploadStatusEnum.PENDING]),
137
- uploading=len(
138
- [i for i in all_items if i.status == UploadStatusEnum.UPLOADING]
139
- ),
140
- completed=len(
141
- [i for i in all_items if i.status == UploadStatusEnum.COMPLETED]
142
- ),
143
- failed=len([i for i in all_items if i.status == UploadStatusEnum.FAILED]),
144
- total=len(all_items),
145
- )
146
 
 
 
147
 
148
- @app.post("/api/queue/add")
149
- async def add_to_queue(db: Session = Depends(get_db)):
150
- """Add processed files to upload queue"""
151
- processed_files = file_processor.get_processed_files()
152
- added_count = 0
153
 
154
- for filename in processed_files:
155
- # Check if already in queue
156
- existing = (
157
- db.query(UploadQueue)
158
- .filter(UploadQueue.file_name == filename)
159
- .first()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
160
  )
161
- if existing:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
162
  continue
163
-
164
- file_path = str(file_processor.processed_files_dir / filename)
165
- file_size = file_processor.get_file_size(filename) or 0
166
-
167
- queue_item = UploadQueue(
168
- file_name=filename,
169
- file_path=file_path,
170
- file_size=file_size,
171
- status=UploadStatusEnum.PENDING,
172
- )
173
- db.add(queue_item)
174
- added_count += 1
175
-
176
- db.commit()
177
- return {"added": added_count, "total": len(processed_files)}
178
-
179
-
180
- @app.post("/api/queue/clear")
181
- async def clear_queue(db: Session = Depends(get_db)):
182
- """Clear upload queue"""
183
- db.query(UploadQueue).delete()
184
- db.commit()
185
- return {"message": "Queue cleared"}
186
-
187
-
188
- # ============================================================================
189
- # Processing Endpoints
190
- # ============================================================================
191
-
192
-
193
- @app.get("/api/processing/state", response_model=ProcessingStateResponse)
194
- async def get_processing_state(db: Session = Depends(get_db)):
195
- """Get current processing state"""
196
- state = db.query(ProcessingState).first()
197
- if not state:
198
- state = ProcessingState(status=ProcessingStatusEnum.IDLE)
199
- db.add(state)
200
- db.commit()
201
- db.refresh(state)
202
- return state
203
-
204
-
205
- @app.post("/api/processing/start")
206
- async def start_processing(
207
- request: ProcessRequest, db: Session = Depends(get_db)
208
- ):
209
- """Start dataset processing"""
210
- config = db.query(HFConfig).first()
211
- if not config:
212
- raise HTTPException(status_code=400, detail="Configuration not set")
213
-
214
- if not config.hf_token:
215
- raise HTTPException(status_code=400, detail="HF token not configured")
216
-
217
- # Run processing in background
218
- asyncio.create_task(
219
- file_processor.process_datasets(
220
- all_repo_id=config.source_all_repo,
221
- ato_repo_id=config.source_ato_repo,
222
- hf_token=config.hf_token,
223
- max_files=request.max_files,
224
- db=db,
225
- )
226
- )
227
-
228
- return {"message": "Processing started"}
229
-
230
-
231
- @app.get("/api/processing/files")
232
- async def get_processed_files():
233
- """Get list of processed files"""
234
- files = file_processor.get_processed_files()
235
- return {"files": files, "count": len(files)}
236
-
237
-
238
- # ============================================================================
239
- # Upload Endpoints
240
- # ============================================================================
241
-
242
-
243
- @app.post("/api/upload/start")
244
- async def start_upload(request: UploadRequest, db: Session = Depends(get_db)):
245
- """Start uploading files"""
246
- global hf_uploader_instance
247
-
248
- config = db.query(HFConfig).first()
249
- if not config or not config.hf_token:
250
- raise HTTPException(status_code=400, detail="HF token not configured")
251
-
252
- if not hf_uploader_instance:
253
- hf_uploader_instance = HFUploader(config.hf_token, config.target_repo)
254
-
255
- # Get files to upload
256
- files_to_upload = (
257
- db.query(UploadQueue)
258
- .filter(UploadQueue.id.in_(request.file_ids))
259
- .all()
260
- )
261
-
262
- if not files_to_upload:
263
- raise HTTPException(status_code=400, detail="No files found")
264
-
265
- # Convert to upload format
266
- upload_files = [
267
- {
268
- "id": f.id,
269
- "file_name": f.file_name,
270
- "file_path": f.file_path,
271
- }
272
- for f in files_to_upload
273
- ]
274
-
275
- # Run upload in background
276
- asyncio.create_task(
277
- hf_uploader_instance.upload_files_batch(
278
- files=upload_files,
279
- db=db,
280
- batch_size=config.upload_batch_size,
281
- )
282
- )
283
-
284
- return {"message": "Upload started", "file_count": len(upload_files)}
285
-
286
-
287
- @app.get("/api/upload/status", response_model=UploadStatus)
288
- async def get_upload_status(db: Session = Depends(get_db)):
289
- """Get current upload status"""
290
- global hf_uploader_instance
291
-
292
- config = db.query(HFConfig).first()
293
- if not config or not config.hf_token:
294
- raise HTTPException(status_code=400, detail="HF token not configured")
295
-
296
- if not hf_uploader_instance:
297
- hf_uploader_instance = HFUploader(config.hf_token, config.target_repo)
298
-
299
- return await hf_uploader_instance.get_upload_status(db)
300
-
301
-
302
- @app.post("/api/upload/retry/{item_id}")
303
- async def retry_upload(item_id: int, db: Session = Depends(get_db)):
304
- """Retry uploading a failed file"""
305
- queue_item = db.query(UploadQueue).filter(UploadQueue.id == item_id).first()
306
- if not queue_item:
307
- raise HTTPException(status_code=404, detail="Item not found")
308
-
309
- queue_item.status = UploadStatusEnum.PENDING
310
- queue_item.retry_count = 0
311
- db.commit()
312
-
313
- return {"message": "Retry scheduled"}
314
-
315
-
316
- # ============================================================================
317
- # File Preview Endpoints
318
- # ============================================================================
319
-
320
-
321
- @app.post("/api/file/preview", response_model=FilePreviewResponse)
322
- async def preview_file(request: FilePreviewRequest):
323
- """Get file preview"""
324
- content = file_processor.get_file_content(request.filename)
325
- if not content:
326
- raise HTTPException(status_code=404, detail="File not found")
327
-
328
- file_size = file_processor.get_file_size(request.filename) or 0
329
-
330
- return FilePreviewResponse(
331
- filename=request.filename, size=file_size, content=content
332
- )
333
-
334
-
335
- # ============================================================================
336
- # Error Log Endpoints
337
- # ============================================================================
338
-
339
-
340
- @app.get("/api/errors", response_model=list[ErrorLogResponse])
341
- async def get_error_logs(limit: int = 50, db: Session = Depends(get_db)):
342
- """Get error logs"""
343
- return (
344
- db.query(UploadErrorLog)
345
- .order_by(UploadErrorLog.created_at.desc())
346
- .limit(limit)
347
- .all()
348
- )
349
-
350
-
351
- @app.delete("/api/errors")
352
- async def clear_error_logs(db: Session = Depends(get_db)):
353
- """Clear error logs"""
354
- db.query(UploadErrorLog).delete()
355
- db.commit()
356
- return {"message": "Error logs cleared"}
357
-
358
-
359
- # ============================================================================
360
- # Static Files
361
- # ============================================================================
362
-
363
-
364
- # Create static directory if it doesn't exist
365
- os.makedirs("static", exist_ok=True)
366
-
367
- # Mount static files
368
- app.mount("/static", StaticFiles(directory="static"), name="static")
369
-
370
-
371
- # ============================================================================
372
- # Root Endpoint
373
- # ============================================================================
374
-
375
-
376
- @app.get("/")
377
- async def root():
378
- """Root endpoint - serve dashboard"""
379
- return FileResponse("static/index.html")
380
-
381
 
382
  if __name__ == "__main__":
383
- import uvicorn
384
-
385
- uvicorn.run(app, host="0.0.0.0", port=8000)
 
 
 
 
 
 
 
1
+ import json
 
 
2
  import os
3
+ import time
4
+ import datetime
5
+ import threading
6
+ from huggingface_hub import hf_hub_download, list_repo_files, HfApi
7
+ from fastapi import FastAPI
8
+ from fastapi.responses import HTMLResponse
9
+ from uvicorn import run as uvicorn_run
10
  import logging
 
 
 
 
 
 
11
 
12
+ # --- Configuration ---
13
+ ALL_REPO_ID = "samfred2/ALL"
14
+ ATO_REPO_ID = "samfred2/ATO"
15
+ OUTPUT_REPO_ID = "samfred2/ALL2"
16
+ OUTPUT_DIR = "processed_files"
17
+ HF_TOKEN = os.getenv("HF_TOKEN", "")
18
+ MAX_UPLOADS_PER_HOUR = 128
19
+ RATE_LIMIT_DELAY = 3600 # 1 hour in seconds
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
 
21
+ os.makedirs(OUTPUT_DIR, exist_ok=True)
22
+ api = HfApi(token=HF_TOKEN)
23
 
24
+ # Logging setup
25
+ logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
26
+ logger = logging.getLogger(__name__)
 
 
27
 
28
+ # Global state
29
+ processing_state = {
30
+ 'running': False,
31
+ 'status': 'idle',
32
+ 'processed': 0,
33
+ 'uploaded': 0,
34
+ 'total': 0,
35
+ 'current_file': '',
36
+ 'error': None,
37
+ 'start_time': None,
38
+ 'eta': None
39
+ }
40
+
41
+ # FastAPI app
42
+ app = FastAPI(title="Dataset Merger & Uploader", version="1.0.0")
43
+
44
+ # HTML Dashboard embedded
45
+ HTML_DASHBOARD = """<!DOCTYPE html>
46
+ <html><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Dataset Merger & Uploader</title><style>*{margin:0;padding:0;box-sizing:border-box}body{font-family:'Segoe UI',Tahoma,Geneva,Verdana,sans-serif;background:linear-gradient(135deg,#667eea 0%,#764ba2 100%);min-height:100vh;padding:20px}.container{max-width:1200px;margin:0 auto}.header{text-align:center;color:white;margin-bottom:30px}.header h1{font-size:2.5em;margin-bottom:10px;text-shadow:2px 2px 4px rgba(0,0,0,.3)}.header p{font-size:1.1em;opacity:.9}.dashboard{display:grid;grid-template-columns:repeat(auto-fit,minmax(250px,1fr));gap:20px;margin-bottom:30px}.card{background:white;border-radius:10px;padding:25px;box-shadow:0 10px 30px rgba(0,0,0,.2);transition:transform .3s,box-shadow .3s}.card:hover{transform:translateY(-5px);box-shadow:0 15px 40px rgba(0,0,0,.3)}.card-title{font-size:.9em;color:#666;text-transform:uppercase;letter-spacing:1px;margin-bottom:15px;font-weight:600}.card-value{font-size:2.5em;font-weight:700;color:#333;margin-bottom:10px}.card-subtitle{font-size:.9em;color:#999}.status-badge{display:inline-block;padding:8px 16px;border-radius:20px;font-size:.85em;font-weight:600;margin-top:15px}.status-running{background:#4CAF50;color:white}.status-idle{background:#9E9E9E;color:white}.status-completed{background:#2196F3;color:white}.status-error{background:#f44336;color:white}.progress-section{background:white;border-radius:10px;padding:30px;box-shadow:0 10px 30px rgba(0,0,0,.2);margin-bottom:30px}.progress-title{font-size:1.3em;font-weight:700;margin-bottom:20px;color:#333}.progress-bar-container{width:100%;height:30px;background:#e0e0e0;border-radius:15px;overflow:hidden;margin-bottom:15px}.progress-bar{height:100%;background:linear-gradient(90deg,#667eea 0%,#764ba2 100%);transition:width .3s;display:flex;align-items:center;justify-content:center;color:white;font-weight:700;font-size:.9em}.progress-text{display:flex;justify-content:space-between;margin-bottom:20px;font-size:.95em}.current-file{padding:15px;background:#f5f5f5;border-left:4px solid #667eea;border-radius:5px;margin-bottom:15px;word-break:break-all}.current-file-label{font-size:.85em;color:#666;margin-bottom:5px}.current-file-name{font-weight:600;color:#333}.controls{display:flex;gap:10px;margin-top:20px}.btn{padding:12px 24px;border:none;border-radius:5px;font-size:1em;font-weight:600;cursor:pointer;transition:all .3s}.btn-stop{background:#f44336;color:white;flex:1}.btn-stop:hover{background:#d32f2f}.btn-stop:disabled{background:#ccc;cursor:not-allowed}.stats-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(200px,1fr));gap:15px;margin-top:20px}.stat-item{background:#f5f5f5;padding:15px;border-radius:5px;border-left:4px solid #667eea}.stat-label{font-size:.85em;color:#666;margin-bottom:5px}.stat-value{font-size:1.8em;font-weight:700;color:#333}.error-message{background:#ffebee;border-left:4px solid #f44336;color:#c62828;padding:15px;border-radius:5px;margin-top:15px;display:none}.error-message.show{display:block}@keyframes pulse{0%,100%{opacity:1}50%{opacity:.5}}.pulse{animation:pulse 1s infinite}</style></head><body><div class="container"><div class="header"><h1>📊 Dataset Merger & Uploader</h1><p>Real-time processing dashboard for samfred2/ALL → samfred2/ALL2</p></div><div class="dashboard"><div class="card"><div class="card-title">Status</div><div class="card-value"><span id="status-icon">⏸️</span></div><div class="card-subtitle">Current state</div><div class="status-badge idle" id="status-badge">IDLE</div></div><div class="card"><div class="card-title">Processed</div><div class="card-value"><span id="processed">0</span></div><div class="card-subtitle">files completed</div></div><div class="card"><div class="card-title">Uploaded</div><div class="card-value"><span id="uploaded">0</span></div><div class="card-subtitle">files to samfred2/ALL2</div></div><div class="card"><div class="card-title">Total</div><div class="card-value"><span id="total">0</span></div><div class="card-subtitle">matched pairs</div></div><div class="card"><div class="card-title">Elapsed Time</div><div class="card-value"><span id="elapsed">0s</span></div><div class="card-subtitle">since start</div></div><div class="card"><div class="card-title">ETA</div><div class="card-value"><span id="eta">--</span></div><div class="card-subtitle">estimated remaining</div></div></div><div class="progress-section"><div class="progress-title">Overall Progress</div><div class="progress-text"><span id="progress-label">0%</span><span id="progress-counter">0 / 0</span></div><div class="progress-bar-container"><div class="progress-bar" id="progress-bar" style="width: 0%"><span id="progress-percent"></span></div></div><div class="current-file" id="current-file-container" style="display: none;"><div class="current-file-label">Currently Processing</div><div class="current-file-name pulse" id="current-file">--</div></div><div class="stats-grid"><div class="stat-item"><div class="stat-label">Processing Rate</div><div class="stat-value"><span id="rate">0</span>/min</div></div><div class="stat-item"><div class="stat-label">Upload Rate</div><div class="stat-value"><span id="upload-rate">0</span>/min</div></div><div class="stat-item"><div class="stat-label">Avg Time/File</div><div class="stat-value"><span id="avg-time">0</span>s</div></div></div><div class="error-message" id="error-message"></div><div class="controls"><button class="btn btn-stop" id="stop-btn" onclick="stopProcessing()" disabled>Stop Processing</button></div></div></div><script>let startTime=null,lastProcessed=0,lastUploaded=0;async function updateDashboard(){try{const e=await fetch('/status'),t=await e.json();document.getElementById('processed').textContent=t.processed,document.getElementById('uploaded').textContent=t.uploaded,document.getElementById('total').textContent=t.total;const a=document.getElementById('status-badge'),s=document.getElementById('status-icon');if(a.className='status-badge status-'+t.status,a.textContent=t.status.toUpperCase(),'running'===t.status?(s.textContent='▶️',document.getElementById('stop-btn').disabled=!1,startTime||(startTime=Date.now())):'completed'===t.status?(s.textContent='✅',document.getElementById('stop-btn').disabled=!0):'error'===t.status?(s.textContent='❌',document.getElementById('stop-btn').disabled=!0,document.getElementById('error-message').textContent='Error: '+(t.error||'Unknown error'),document.getElementById('error-message').classList.add('show')):(s.textContent='⏸️',document.getElementById('stop-btn').disabled=!0),0===t.total)document.getElementById('progress-bar').style.width='0%';else{const e=Math.round(t.processed/t.total*100);document.getElementById('progress-bar').style.width=e+'%',document.getElementById('progress-label').textContent=e+'%',document.getElementById('progress-percent').textContent=e+'%'}document.getElementById('progress-counter').textContent=t.processed+' / '+t.total,t.current_file?(document.getElementById('current-file-container').style.display='block',document.getElementById('current-file').textContent=t.current_file):document.getElementById('current-file-container').style.display='none','running'===t.status&&startTime&&(function(){const e=Math.floor((Date.now()-startTime)/1e3);document.getElementById('elapsed').textContent=function(e){return e<60?e+'s':(t=>t<60?t+'m':(e=>e+'h '+e%60+'m')(Math.floor(t/60)))(Math.floor(e/60))};const a=t.processed-lastProcessed,s=t.uploaded-lastUploaded;lastProcessed=t.processed,lastUploaded=t.uploaded;const o=Math.round(t.processed/e*60),n=Math.round(t.uploaded/e*60);document.getElementById('rate').textContent=o,document.getElementById('upload-rate').textContent=n;if(t.processed>0){const a=Math.round(e/t.processed);document.getElementById('avg-time').textContent=a,o>0&&t.processed<t.total&&(document.getElementById('eta').textContent=function(e){return e<60?e+'s':(t=>t<60?t+'m':(e=>e+'h '+e%60+'m')(Math.floor(t/60)))(Math.floor(e/60))}(Math.round((t.total-t.processed)/(o/60))))}}())}catch(e){console.error('Error fetching status:',e)}}async function stopProcessing(){confirm('Are you sure you want to stop processing?')&&(await fetch('/stop',{method:'POST'}),updateDashboard())}setInterval(updateDashboard,2e3),updateDashboard()</script></body></html>"""
47
+
48
+ @app.on_event("startup")
49
+ async def startup_event():
50
+ """Auto-start processing when server starts."""
51
+ logger.info("Server startup - Auto-starting processing...")
52
+ processing_state['running'] = True
53
+ processing_state['status'] = 'starting'
54
+ processing_state['start_time'] = time.time()
55
+ thread = threading.Thread(target=run_processing_thread, daemon=True)
56
+ thread.start()
57
+
58
+ @app.get("/", response_class=HTMLResponse)
59
+ def get_dashboard():
60
+ """Serve dashboard HTML."""
61
+ return HTML_DASHBOARD
62
+
63
+ @app.get("/status")
64
+ def get_status():
65
+ """Get current processing status."""
66
+ return processing_state
67
+
68
+ @app.post("/stop")
69
+ def stop_processing():
70
+ """Stop the processing."""
71
+ processing_state['running'] = False
72
+ return {"message": "Stop signal sent"}
73
+
74
+ # --- Helper Functions ---
75
+
76
+ def download_file(repo_id, filename, local_dir):
77
+ """Downloads a single file with a delay to mitigate rate-limiting."""
78
+ logger.info(f"Downloading {filename} from {repo_id}...")
79
+ try:
80
+ time.sleep(1)
81
+ local_path = hf_hub_download(
82
+ repo_id=repo_id,
83
+ filename=filename,
84
+ repo_type="dataset",
85
+ local_dir=local_dir,
86
+ local_dir_use_symlinks=False,
87
+ token=HF_TOKEN
88
  )
89
+ logger.info(f"Downloaded to {local_path}")
90
+ return local_path
91
+ except Exception as e:
92
+ logger.error(f"Could not download {filename}. Error: {e}")
93
+ return None
94
+
95
+ def upload_file_with_rate_limit(api, file_path, path_in_repo, upload_state):
96
+ """
97
+ Uploads a file to HF with rate limiting (128 files per hour).
98
+ Handles 429 errors by waiting an hour and resuming.
99
+ """
100
+ while True:
101
+ try:
102
+ # Check if we've reached the limit
103
+ if upload_state['count'] >= MAX_UPLOADS_PER_HOUR:
104
+ elapsed = time.time() - upload_state['hour_start']
105
+ if elapsed < RATE_LIMIT_DELAY:
106
+ wait_time = RATE_LIMIT_DELAY - elapsed
107
+ wait_until = datetime.datetime.now() + datetime.timedelta(seconds=wait_time)
108
+ logger.info(f"Rate limit reached ({MAX_UPLOADS_PER_HOUR} uploads/hour). Waiting until {wait_until}")
109
+ time.sleep(wait_time)
110
+ upload_state['hour_start'] = time.time()
111
+ upload_state['count'] = 0
112
+
113
+ logger.info(f"Uploading {path_in_repo}... ({upload_state['count']+1}/{MAX_UPLOADS_PER_HOUR})")
114
+ api.upload_file(
115
+ path_or_fileobj=file_path,
116
+ path_in_repo=path_in_repo,
117
+ repo_id=OUTPUT_REPO_ID,
118
+ repo_type="dataset",
119
+ token=HF_TOKEN
120
+ )
121
+ upload_state['count'] += 1
122
+ logger.info(f"Uploaded {path_in_repo}")
123
+ break
124
+ except Exception as e:
125
+ if "429" in str(e) or "rate" in str(e).lower():
126
+ wait_until = datetime.datetime.now() + datetime.timedelta(seconds=RATE_LIMIT_DELAY)
127
+ logger.warning(f"Rate limit hit (429). Waiting 1 hour until {wait_until}")
128
+ time.sleep(RATE_LIMIT_DELAY)
129
+ upload_state['hour_start'] = time.time()
130
+ upload_state['count'] = 0
131
+ else:
132
+ logger.error(f"Could not upload {path_in_repo}. Error: {e}")
133
+ break
134
+
135
+ def load_json_file(local_path):
136
+ """Loads and returns content of a JSON file."""
137
+ try:
138
+ with open(local_path, 'r') as f:
139
+ return json.load(f)
140
+ except json.JSONDecodeError:
141
+ logger.error(f"Could not decode JSON for {local_path}. Skipping.")
142
+ return None
143
+ except Exception as e:
144
+ logger.error(f"Could not read file {local_path}. Error: {e}")
145
+ return None
146
+
147
+ def find_matching_all_file(ato_filename, all_file_names):
148
+ """
149
+ Finds the full course file name in the 'all' dataset that corresponds
150
+ to the given lesson file name from the 'ato' dataset using suffix matching.
151
+ """
152
+ for all_name in all_file_names:
153
+ if all_name.endswith(ato_filename):
154
+ return all_name
155
+ return None
156
+
157
+ def load_progress(progress_file):
158
+ """Load progress tracking file."""
159
+ if os.path.exists(progress_file):
160
+ try:
161
+ with open(progress_file, 'r') as f:
162
+ return json.load(f)
163
+ except:
164
+ return {'processed': [], 'uploaded': []}
165
+ return {'processed': [], 'uploaded': []}
166
+
167
+ def save_progress(progress_file, progress):
168
+ """Save progress tracking file."""
169
+ with open(progress_file, 'w') as f:
170
+ json.dump(progress, f, indent=2)
171
+
172
+ def run_processing_thread():
173
+ """Wrapper to run process_datasets in thread with error handling."""
174
+ try:
175
+ processing_state['status'] = 'running'
176
+ process_datasets()
177
+ processing_state['status'] = 'completed'
178
+ except Exception as e:
179
+ processing_state['status'] = 'error'
180
+ processing_state['error'] = str(e)
181
+ logger.error(f"Processing error: {e}", exc_info=True)
182
+ finally:
183
+ processing_state['running'] = False
184
+ logger.info("Processing thread finished")
185
+
186
+ # --- Main Logic ---
187
+
188
+ def process_datasets():
189
+ """
190
+ Downloads file lists, matches them, downloads the content, integrates
191
+ the transcription data into the full course files, and uploads to samfred2/ALL2.
192
+ Processes entire dataset with rate limiting (128 files/hour, 429 error handling).
193
+ """
194
+
195
+ # Load progress
196
+ progress_file = os.path.join(OUTPUT_DIR, "progress.json")
197
+ progress = load_progress(progress_file)
198
+ upload_state = {'count': 0, 'hour_start': time.time()}
199
+
200
+ # Ensure output repo exists
201
+ try:
202
+ api.create_repo(OUTPUT_REPO_ID, repo_type="dataset", exist_ok=True)
203
+ logger.info(f"Using repo: {OUTPUT_REPO_ID}")
204
+ except Exception as e:
205
+ logger.warning(f"Could not create repo. {e}")
206
+
207
+ # 1. Get the list of all files in both repositories
208
+ logger.info("--- 1. Listing Repository Files ---")
209
+ try:
210
+ all_file_list = list_repo_files(repo_id=ALL_REPO_ID, repo_type="dataset", token=HF_TOKEN)
211
+ ato_file_list = list_repo_files(repo_id=ATO_REPO_ID, repo_type="dataset", token=HF_TOKEN)
212
+ except Exception as e:
213
+ logger.error(f"Could not list repository files. {e}")
214
+ processing_state['error'] = str(e)
215
+ return
216
+
217
+ # Filter for JSON files
218
+ all_json_files = [f for f in all_file_list if f.endswith(".json")]
219
+ ato_json_files = [f for f in ato_file_list if f.endswith(".json")]
220
+
221
+ logger.info(f"Found {len(all_json_files)} JSON files in {ALL_REPO_ID}")
222
+ logger.info(f"Found {len(ato_json_files)} JSON files in {ATO_REPO_ID}")
223
+
224
+ # 2. Match ATO files to ALL files
225
+ logger.info("--- 2. Matching ATO to ALL Files ---")
226
+ match_map = {}
227
+ for ato_file in ato_json_files:
228
+ matching_all_file = find_matching_all_file(ato_file, all_json_files)
229
+ if matching_all_file:
230
+ match_map[ato_file] = matching_all_file
231
+
232
+ logger.info(f"Found {len(match_map)} matching pairs.")
233
+ processing_state['total'] = len(match_map)
234
+
235
+ # 3. Process the matched files
236
+ logger.info("--- 3. Downloading, Integrating, and Uploading Files ---")
237
+ logger.info(f"Total pairs to process: {len(match_map)}")
238
+ logger.info(f"Already processed: {len(progress['processed'])}")
239
+ logger.info(f"Already uploaded: {len(progress['uploaded'])}")
240
+
241
+ # Create temporary directories for downloads
242
+ all_download_dir = os.path.join(OUTPUT_DIR, "all_raw")
243
+ ato_download_dir = os.path.join(OUTPUT_DIR, "ato_raw")
244
+ os.makedirs(all_download_dir, exist_ok=True)
245
+ os.makedirs(ato_download_dir, exist_ok=True)
246
+
247
+ # Iterate over ALL matched pairs
248
+ processed_count = 0
249
+ for ato_filename, all_filename in match_map.items():
250
+ if not processing_state['running']:
251
+ logger.info("Processing stopped by user")
252
+ break
253
+
254
+ # Skip if already processed
255
+ if all_filename in progress['processed']:
256
+ logger.info(f"Skipping already processed: {all_filename}")
257
  continue
258
+
259
+ processing_state['current_file'] = all_filename
260
+ logger.info(f"Processing {processed_count + 1}/{len(match_map)}: {ato_filename} <-> {all_filename}")
261
+
262
+ # a. Download ATO file
263
+ ato_local_path = download_file(ATO_REPO_ID, ato_filename, ato_download_dir)
264
+ if not ato_local_path:
265
+ continue
266
+
267
+ ato_data = load_json_file(ato_local_path)
268
+ if not ato_data:
269
+ continue
270
+
271
+ # b. Download ALL file
272
+ all_local_path = download_file(ALL_REPO_ID, all_filename, all_download_dir)
273
+ if not all_local_path:
274
+ continue
275
+
276
+ all_data = load_json_file(all_local_path)
277
+ if not all_data:
278
+ continue
279
+
280
+ # c. Integrate transcription
281
+ logger.info("Integrating transcription...")
282
+ all_data["transcription_content"] = ato_data
283
+ all_data["transcription_content"]["full_course_name"] = all_filename
284
+
285
+ # d. Save locally
286
+ final_output_path = os.path.join(OUTPUT_DIR, all_filename)
287
+ with open(final_output_path, 'w') as f:
288
+ json.dump(all_data, f, indent=4)
289
+
290
+ logger.info(f"Saved locally to {final_output_path}")
291
+
292
+ # e. Upload to samfred2/ALL2
293
+ if all_filename not in progress['uploaded']:
294
+ upload_file_with_rate_limit(api, final_output_path, all_filename, upload_state)
295
+ progress['uploaded'].append(all_filename)
296
+ processing_state['uploaded'] += 1
297
+
298
+ progress['processed'].append(all_filename)
299
+ save_progress(progress_file, progress)
300
+ processed_count += 1
301
+ processing_state['processed'] = processed_count
302
+
303
+ logger.info(f"Progress: {processed_count}/{len(match_map)} | Uploaded: {len(progress['uploaded'])}")
304
+
305
+ logger.info("--- Process Complete ---")
306
+ logger.info(f"Total processed: {len(progress['processed'])}")
307
+ logger.info(f"Total uploaded: {len(progress['uploaded'])}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
308
 
309
  if __name__ == "__main__":
310
+ import sys
311
+
312
+ logger.info(f"Starting server on http://127.0.0.1:8000")
313
+ logger.info(f"Dashboard: http://127.0.0.1:8000")
314
+ logger.info(f"Status: http://127.0.0.1:8000/status")
315
+ logger.info(f"Stop: POST http://127.0.0.1:8000/stop")
316
+ logger.info("Processing will auto-start on server startup...")
317
+
318
+ uvicorn_run(app, host="127.0.0.1", port=8000)