Pragmaticl commited on
Commit
e4a5110
·
verified ·
1 Parent(s): ce4fb96

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +172 -14
app.py CHANGED
@@ -15,6 +15,8 @@ import time
15
  from datetime import datetime
16
  import json
17
  import traceback
 
 
18
 
19
  # Khởi tạo model Whisper
20
  model = WhisperModel("large-v3-turbo", device="cpu", compute_type="int8")
@@ -315,6 +317,47 @@ def process_audio_background(task_id: str, input_file: str, original_filename: s
315
  'percent': 0
316
  })
317
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
318
  def submit_task(input_file):
319
  """Submit task mới"""
320
  if input_file is None:
@@ -345,6 +388,76 @@ def submit_task(input_file):
345
 
346
  return f"✅ Task {task_id} đã được tạo và đang xử lý trong background!", task_id
347
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
348
  def load_all_tasks():
349
  """Load tất cả tasks từ storage"""
350
  with TASK_LOCK:
@@ -486,23 +599,62 @@ with gr.Blocks(title="Audio Transcription & Dataset Creator", theme=gr.themes.So
486
  with gr.Tab("📤 Upload & Submit"):
487
  gr.Markdown("### Tải lên file và submit task")
488
 
489
- with gr.Row():
490
- with gr.Column():
491
- input_file = gr.File(
492
- label="Upload Audio File hoặc ZIP",
493
- file_types=['.wav', '.mp3', '.flac', '.ogg', '.m4a', '.aac', '.zip']
494
- )
495
- submit_btn = gr.Button("🚀 Submit Task", variant="primary", size="lg")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
496
 
497
- with gr.Column():
498
- submit_status = gr.Textbox(label="📋 Trạng thái Submit", lines=3)
499
- current_task_id = gr.Textbox(label="Task ID", visible=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
500
 
501
  gr.Markdown("""
502
- ### ℹ️ Hướng dẫn:
503
- 1. Upload file audio hoặc ZIP chứa nhiều file audio
504
- 2. Click "Submit Task" - task sẽ chạy trong background
505
- 3. Chuyển sang tab "History" để xem tiến trình và tải kết quả
 
506
  """)
507
 
508
  # Tab History
@@ -532,6 +684,12 @@ with gr.Blocks(title="Audio Transcription & Dataset Creator", theme=gr.themes.So
532
  outputs=[submit_status, current_task_id]
533
  )
534
 
 
 
 
 
 
 
535
  refresh_btn.click(
536
  fn=refresh_task_list,
537
  outputs=task_dropdown
 
15
  from datetime import datetime
16
  import json
17
  import traceback
18
+ import requests
19
+ from urllib.parse import urlparse
20
 
21
  # Khởi tạo model Whisper
22
  model = WhisperModel("large-v3-turbo", device="cpu", compute_type="int8")
 
317
  'percent': 0
318
  })
319
 
320
+ def download_file_from_url(url: str, output_dir: str) -> tuple[str, str]:
321
+ """Tải file từ URL và trả về đường dẫn file"""
322
+ try:
323
+ # Parse URL để lấy tên file
324
+ parsed_url = urlparse(url)
325
+ filename = os.path.basename(parsed_url.path)
326
+
327
+ # Nếu không có tên file, tạo tên mặc định
328
+ if not filename or '.' not in filename:
329
+ # Thử detect từ Content-Disposition header
330
+ response = requests.head(url, allow_redirects=True, timeout=10)
331
+ content_disp = response.headers.get('Content-Disposition', '')
332
+ if 'filename=' in content_disp:
333
+ filename = content_disp.split('filename=')[1].strip('"\'')
334
+ else:
335
+ # Tạo tên mặc định
336
+ filename = f"download_{int(time.time())}.zip"
337
+
338
+ output_path = os.path.join(output_dir, filename)
339
+
340
+ # Download file với progress
341
+ response = requests.get(url, stream=True, timeout=30)
342
+ response.raise_for_status()
343
+
344
+ total_size = int(response.headers.get('content-length', 0))
345
+
346
+ with open(output_path, 'wb') as f:
347
+ if total_size == 0:
348
+ f.write(response.content)
349
+ else:
350
+ downloaded = 0
351
+ for chunk in response.iter_content(chunk_size=8192):
352
+ if chunk:
353
+ f.write(chunk)
354
+ downloaded += len(chunk)
355
+
356
+ return output_path, filename
357
+
358
+ except Exception as e:
359
+ raise Exception(f"Lỗi khi tải file từ URL: {str(e)}")
360
+
361
  def submit_task(input_file):
362
  """Submit task mới"""
363
  if input_file is None:
 
388
 
389
  return f"✅ Task {task_id} đã được tạo và đang xử lý trong background!", task_id
390
 
391
+ def submit_task_from_url(url: str):
392
+ """Submit task từ URL"""
393
+ if not url or not url.strip():
394
+ return "❌ Vui lòng nhập URL!", ""
395
+
396
+ url = url.strip()
397
+
398
+ # Validate URL
399
+ if not url.startswith(('http://', 'https://')):
400
+ return "❌ URL phải bắt đầu với http:// hoặc https://", ""
401
+
402
+ task_id = f"task_{int(time.time() * 1000)}"
403
+
404
+ task_info = {
405
+ 'task_id': task_id,
406
+ 'status': TaskStatus.WAITING,
407
+ 'created_at': datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
408
+ 'updated_at': datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
409
+ 'original_filename': f"URL: {url}",
410
+ 'download_url': url,
411
+ 'progress': 'Đang tải file từ URL...'
412
+ }
413
+
414
+ with TASK_LOCK:
415
+ TASKS[task_id] = task_info
416
+
417
+ # Chạy background thread
418
+ thread = threading.Thread(
419
+ target=process_audio_from_url,
420
+ args=(task_id, url),
421
+ daemon=True
422
+ )
423
+ thread.start()
424
+
425
+ return f"✅ Task {task_id} đã được tạo. Đang tải file từ URL...", task_id
426
+
427
+ def process_audio_from_url(task_id: str, url: str):
428
+ """Tải file từ URL và xử lý"""
429
+ try:
430
+ # Tạo thư mục tạm để download
431
+ download_dir = os.path.join(STORAGE_DIR, task_id, 'download')
432
+ os.makedirs(download_dir, exist_ok=True)
433
+
434
+ update_task_status(task_id, TaskStatus.PROCESSING, {
435
+ 'progress': f'Đang tải file từ URL: {url}',
436
+ 'step': 0,
437
+ 'total_steps': 5,
438
+ 'step_name': 'Tải file từ URL',
439
+ 'percent': 5
440
+ })
441
+
442
+ # Download file
443
+ file_path, filename = download_file_from_url(url, download_dir)
444
+
445
+ update_task_status(task_id, TaskStatus.PROCESSING, {
446
+ 'progress': f'Đã tải xong file: {filename}. Bắt đầu xử lý...',
447
+ 'original_filename': filename,
448
+ 'percent': 15
449
+ })
450
+
451
+ # Gọi hàm xử lý audio như bình thường
452
+ process_audio_background(task_id, file_path, filename)
453
+
454
+ except Exception as e:
455
+ error_msg = f"Lỗi khi tải file từ URL: {str(e)}\n\n{traceback.format_exc()}"
456
+ update_task_status(task_id, TaskStatus.ERROR, {
457
+ 'error': error_msg,
458
+ 'percent': 0
459
+ })
460
+
461
  def load_all_tasks():
462
  """Load tất cả tasks từ storage"""
463
  with TASK_LOCK:
 
599
  with gr.Tab("📤 Upload & Submit"):
600
  gr.Markdown("### Tải lên file và submit task")
601
 
602
+ with gr.Tabs():
603
+ # Subtab: Upload File
604
+ with gr.Tab("📁 Upload File"):
605
+ with gr.Row():
606
+ with gr.Column():
607
+ input_file = gr.File(
608
+ label="Upload Audio File hoặc ZIP",
609
+ file_types=['.wav', '.mp3', '.flac', '.ogg', '.m4a', '.aac', '.zip']
610
+ )
611
+ submit_btn = gr.Button("🚀 Submit Task", variant="primary", size="lg")
612
+
613
+ with gr.Column():
614
+ submit_status = gr.Textbox(label="📋 Trạng thái Submit", lines=3)
615
+ current_task_id = gr.Textbox(label="Task ID", visible=False)
616
+
617
+ gr.Markdown("""
618
+ #### ℹ️ Hướng dẫn:
619
+ - Upload file audio đơn (.wav, .mp3, .flac, .ogg, .m4a, .aac)
620
+ - Hoặc upload file ZIP chứa nhiều file audio
621
+ - Click "Submit Task" để bắt đầu xử lý
622
+ """)
623
 
624
+ # Subtab: Download from URL
625
+ with gr.Tab("🔗 Tải từ URL"):
626
+ with gr.Row():
627
+ with gr.Column():
628
+ url_input = gr.Textbox(
629
+ label="Nhập URL của file audio hoặc ZIP",
630
+ placeholder="https://example.com/audio.zip hoặc https://example.com/audio.mp3",
631
+ lines=2
632
+ )
633
+ submit_url_btn = gr.Button("🌐 Tải và Submit Task", variant="primary", size="lg")
634
+
635
+ with gr.Column():
636
+ submit_url_status = gr.Textbox(label="📋 Trạng thái Submit", lines=3)
637
+ current_url_task_id = gr.Textbox(label="Task ID", visible=False)
638
+
639
+ gr.Markdown("""
640
+ #### ℹ️ Hướng dẫn:
641
+ - Nhập URL trực tiếp đến file audio hoặc file ZIP
642
+ - Hỗ trợ: Google Drive, Dropbox, OneDrive, hoặc bất kỳ URL công khai nào
643
+ - File sẽ được tải về tự động và xử lý trong background
644
+ - **Lưu ý**: URL phải là link download trực tiếp (không qua trang xem trước)
645
+
646
+ **Ví dụ URL hợp lệ:**
647
+ - `https://example.com/dataset.zip`
648
+ - `https://drive.google.com/uc?export=download&id=FILE_ID`
649
+ - `https://www.dropbox.com/s/xxx/audio.mp3?dl=1`
650
+ """)
651
 
652
  gr.Markdown("""
653
+ ---
654
+ ### 💡 Sau khi submit:
655
+ 1. Bạn sẽ nhận được Task ID
656
+ 2. Chuyển sang tab **"History"** để xem tiến trình real-time
657
+ 3. Tải về kết quả khi xử lý hoàn thành
658
  """)
659
 
660
  # Tab History
 
684
  outputs=[submit_status, current_task_id]
685
  )
686
 
687
+ submit_url_btn.click(
688
+ fn=submit_task_from_url,
689
+ inputs=url_input,
690
+ outputs=[submit_url_status, current_url_task_id]
691
+ )
692
+
693
  refresh_btn.click(
694
  fn=refresh_task_list,
695
  outputs=task_dropdown