Prathmesh Gawali commited on
Commit
f69578c
Β·
1 Parent(s): 9fff0f1

improvement in performance

Browse files
Files changed (1) hide show
  1. app.py +271 -201
app.py CHANGED
@@ -10,6 +10,8 @@ import uuid
10
  import re
11
  import base64
12
  import asyncio
 
 
13
 
14
  # Try to import main module
15
  try:
@@ -50,41 +52,48 @@ is_processing = False
50
  processing_thread = None
51
  first_frame_path = None
52
 
53
- # Pre-load models flag
54
- MODELS_PRELOADED = False
55
- MODELS_PRELOADING = False
56
 
57
- def preload_models():
58
- """Pre-load models in background to reduce startup delay"""
59
- global MODELS_PRELOADED, MODELS_PRELOADING
60
 
61
- if MODELS_PRELOADING or MODELS_PRELOADED:
62
  return
63
 
64
- MODELS_PRELOADING = True
65
- print("πŸ”„ Pre-loading models in background...")
66
 
67
- def background_preload():
 
68
  try:
69
- # Import and initialize main module
 
70
  if MAIN_AVAILABLE:
71
- # This will trigger model loading in main.py
72
- from main import setup_gpu, configure_multithreading
 
 
 
 
 
 
 
 
 
73
 
74
- # Force model loading by creating dummy structures
75
- # This warms up the GPU and loads models
76
- print("βœ… Models pre-loaded successfully")
77
- MODELS_PRELOADED = True
78
- MODELS_PRELOADING = False
79
  except Exception as e:
80
- print(f"⚠️ Model pre-loading failed: {e}")
81
- MODELS_PRELOADING = False
 
82
 
83
- # Start in background thread
84
- threading.Thread(target=background_preload, daemon=True).start()
85
 
86
- # Start model preloading on import
87
- preload_models()
88
 
89
  def cleanup_old_files():
90
  """Clean up files older than 1 hour"""
@@ -102,36 +111,49 @@ def cleanup_old_files():
102
 
103
  def extract_first_frame_fast(video_path, output_path):
104
  """
105
- Fast first frame extraction using minimal OpenCV operations
106
  """
107
  try:
108
- import cv2
 
 
 
 
 
 
 
109
 
110
- # Use minimal settings for faster reading
111
- cap = cv2.VideoCapture(str(video_path))
112
-
113
- # Set low resolution for faster read (we only need the frame for display)
114
- cap.set(cv2.CAP_PROP_BUFFERSIZE, 1)
 
 
115
 
116
- ret, frame = cap.read()
117
- if ret:
118
- # Save as lower quality JPEG for faster processing
119
- cv2.imwrite(str(output_path), frame, [cv2.IMWRITE_JPEG_QUALITY, 70])
120
- cap.release()
121
- return output_path if ret else None
 
 
 
 
 
122
  except Exception as e:
123
  print(f"Error extracting first frame: {e}")
124
  return None
125
 
126
- async def extract_first_frame_async(video_path, output_path):
127
- """
128
- Asynchronous first frame extraction
129
- """
130
- return await asyncio.to_thread(extract_first_frame_fast, video_path, output_path)
131
-
132
- async def copy_file_async(src, dst):
133
- """Asynchronous file copy"""
134
- return await asyncio.to_thread(shutil.copy, src, dst)
135
 
136
  def process_video_in_thread(input_path, output_path, progress_queue):
137
  """Process video in a separate thread with time tracking"""
@@ -245,7 +267,7 @@ def format_time(seconds):
245
  secs = int(seconds % 60)
246
  return f"{hours:02d}:{minutes:02d}:{secs:02d}"
247
 
248
- def create_progress_overlay_html(progress_data, first_frame_image=None, show_overlay=True, status="uploading"):
249
  """Create HTML overlay with circular progress indicator over blurred video frame"""
250
 
251
  percent = progress_data.get("percent", 0)
@@ -404,47 +426,34 @@ def create_progress_overlay_html(progress_data, first_frame_image=None, show_ove
404
  padding: 0 20px;
405
  text-shadow: 0 2px 10px rgba(0,0,0,0.5);
406
  ">{message}</div>
407
-
408
- <!-- Status indicator -->
409
- <div style="
410
- margin-top: 10px;
411
- padding: 5px 15px;
412
- background: {status_color};
413
- color: white;
414
- border-radius: 20px;
415
- font-size: 12px;
416
- font-weight: 600;
417
- text-transform: uppercase;
418
- letter-spacing: 1px;
419
- ">
420
- {status}
421
- </div>
422
  </div>
423
  </div>
424
  """
425
 
426
  return html
427
 
428
- async def upload_and_process_async(video_file):
429
- """Handle video upload and processing with immediate feedback"""
430
  global is_processing, current_progress, processing_thread, first_frame_path
431
 
432
  if not video_file:
433
  # Return both: empty video output and hidden progress overlay
434
- return (
435
  None, # video_output
436
  create_progress_overlay_html({"percent": 0, "message": "Please upload a video file", "elapsed": "00:00", "remaining": "--:--"}, show_overlay=False), # progress_overlay (hidden)
437
  gr.update(visible=True), # progress_overlay visibility
438
  gr.update(visible=False) # video_output visibility
439
  )
 
440
 
441
  if is_processing:
442
- return (
443
  None, # video_output
444
  create_progress_overlay_html({"percent": 0, "message": "Already processing another video", "elapsed": "00:00", "remaining": "--:--"}, show_overlay=True, status="waiting"), # progress_overlay
445
  gr.update(visible=True), # progress_overlay visibility
446
  gr.update(visible=False) # video_output visibility
447
  )
 
448
 
449
  try:
450
  is_processing = True
@@ -460,18 +469,21 @@ async def upload_and_process_async(video_file):
460
  output_path = OUTPUT_DIR / f"processed_{timestamp}_{unique_id}_{input_filename}.mp4"
461
  first_frame_path = OUTPUT_DIR / f"frame_{timestamp}_{unique_id}.jpg"
462
 
463
- # STEP 1: Immediately show progress overlay with uploading status
464
- current_progress = {"percent": 5, "message": "Preparing video...", "elapsed": "00:00", "remaining": "--:--"}
465
 
466
  yield (
467
  None, # video_output
468
- create_progress_overlay_html(current_progress, None, show_overlay=True, status="preparing"), # progress_overlay
469
  gr.update(visible=True), # progress_overlay visibility
470
  gr.update(visible=False) # video_output visibility
471
  )
472
 
473
- # STEP 2: Fast file copy with progress
474
- current_progress = {"percent": 10, "message": "Copying video file...", "elapsed": "00:00", "remaining": "--:--"}
 
 
 
475
 
476
  yield (
477
  None, # video_output
@@ -480,11 +492,27 @@ async def upload_and_process_async(video_file):
480
  gr.update(visible=False) # video_output visibility
481
  )
482
 
483
- # Use asyncio for non-blocking file operations
484
- await copy_file_async(video_file, upload_path)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
485
 
486
- # STEP 3: Extract first frame (async)
487
- current_progress = {"percent": 20, "message": "Extracting preview...", "elapsed": "00:00", "remaining": "--:--"}
488
 
489
  yield (
490
  None, # video_output
@@ -493,20 +521,37 @@ async def upload_and_process_async(video_file):
493
  gr.update(visible=False) # video_output visibility
494
  )
495
 
496
- await extract_first_frame_async(upload_path, first_frame_path)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
497
 
498
  # Read first frame as base64
499
  first_frame_base64 = None
500
  if first_frame_path and first_frame_path.exists():
501
- with open(first_frame_path, "rb") as f:
502
- first_frame_base64 = base64.b64encode(f.read()).decode()
 
 
 
503
 
504
- # STEP 4: Start processing thread immediately
505
- current_progress = {"percent": 25, "message": "Initializing models...", "elapsed": "00:00", "remaining": "--:--"}
506
 
507
  yield (
508
  None, # video_output
509
- create_progress_overlay_html(current_progress, first_frame_base64, show_overlay=True, status="initializing"), # progress_overlay
510
  gr.update(visible=True), # progress_overlay visibility
511
  gr.update(visible=False) # video_output visibility
512
  )
@@ -514,91 +559,129 @@ async def upload_and_process_async(video_file):
514
  # Create progress queue
515
  progress_queue = queue.Queue()
516
 
517
- # Start processing in thread
518
- processing_thread = threading.Thread(
519
- target=process_video_in_thread,
520
- args=(upload_path, output_path, progress_queue),
521
- daemon=True
522
- )
523
- processing_thread.start()
524
-
525
- # Variables to track if we've reached 99%
526
- reached_99_percent = False
527
- last_update_time = time.time()
528
-
529
- # Monitor progress
530
- while processing_thread.is_alive():
531
- try:
532
- # Check for progress updates
533
- while True:
534
- try:
535
- progress_update = progress_queue.get_nowait()
536
- current_progress = progress_update
537
-
538
- # Check if we've reached 99%
539
- if progress_update.get("percent", 0) >= 99:
540
- reached_99_percent = True
541
-
542
- # Create HTML progress overlay
543
- html_content = create_progress_overlay_html(progress_update, first_frame_base64, show_overlay=True, status="processing")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
544
 
545
- # Update progress overlay, keep video hidden
546
  yield (
547
- None, # video_output
548
- html_content, # progress_overlay
549
- gr.update(visible=True), # progress_overlay visibility
550
- gr.update(visible=False) # video_output visibility
551
  )
552
-
553
  last_update_time = time.time()
554
- except queue.Empty:
555
- break
556
-
557
- # Check for timeout (thread stuck)
558
- if time.time() - last_update_time > 30: # 30 seconds without update
559
- print("Warning: Processing thread may be stuck")
560
- current_progress = {"percent": 30, "message": "Processing... (taking longer than usual)", "elapsed": format_time(time.time() - start_time), "remaining": "--:--"}
561
 
562
- yield (
563
- None, # video_output
564
- create_progress_overlay_html(current_progress, first_frame_base64, show_overlay=True, status="processing"), # progress_overlay
565
- gr.update(visible=True), # progress_overlay visibility
566
- gr.update(visible=False) # video_output visibility
567
- )
568
-
569
- await asyncio.sleep(0.1)
 
570
  except Exception as e:
571
- print(f"Error monitoring progress: {e}")
572
- break
573
 
574
- # Get final result
575
- processing_thread.join()
576
-
577
- # If we reached 99%, show 100% for 1 second
578
  if reached_99_percent:
579
- # Show 100% completion
580
  completion_progress = {
581
  "percent": 100,
582
- "message": "Finalizing...",
583
  "elapsed": current_progress.get("elapsed", "00:00"),
584
  "remaining": "00:00"
585
  }
586
 
587
- html_content = create_progress_overlay_html(completion_progress, first_frame_base64, show_overlay=True, status="finalizing")
588
-
589
  yield (
590
- None, # video_output
591
- html_content, # progress_overlay with 100%
592
- gr.update(visible=True), # progress_overlay visibility
593
- gr.update(visible=False) # video_output visibility
594
  )
595
 
596
- await asyncio.sleep(1)
597
 
598
- # Final step: hide progress overlay and show video output
599
  yield (
600
  str(output_path), # video_output
601
- create_progress_overlay_html(current_progress, first_frame_base64, show_overlay=False), # progress_overlay (hidden)
602
  gr.update(visible=False), # progress_overlay visibility
603
  gr.update(visible=True) # video_output visibility
604
  )
@@ -611,32 +694,14 @@ async def upload_and_process_async(video_file):
611
  status="error"
612
  )
613
  yield (
614
- None, # video_output
615
- html_content, # progress_overlay
616
- gr.update(visible=True), # progress_overlay visibility
617
- gr.update(visible=False) # video_output visibility
618
  )
619
  finally:
620
  is_processing = False
621
 
622
- # Wrapper function for Gradio (since Gradio doesn't support async directly)
623
- def upload_and_process(video_file):
624
- """Wrapper to run async function in a thread for Gradio compatibility"""
625
- import asyncio
626
-
627
- # Create a new event loop for this thread
628
- loop = asyncio.new_event_loop()
629
- asyncio.set_event_loop(loop)
630
-
631
- # Run the async function
632
- async def run_async():
633
- async for result in upload_and_process_async(video_file):
634
- yield result
635
-
636
- # Return a generator that runs the async function
637
- for result in loop.run_until_complete(run_async().__anext__()):
638
- yield result
639
-
640
  # Create Gradio interface
641
  with gr.Blocks(title="🏈 Football Field Detection", theme=gr.themes.Soft(), css="""
642
  .video-container {
@@ -673,39 +738,40 @@ with gr.Blocks(title="🏈 Football Field Detection", theme=gr.themes.Soft(), cs
673
  display: block !important;
674
  }
675
 
676
- .upload-notice {
677
- background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
678
- padding: 20px;
679
- border-radius: 12px;
 
 
 
 
 
 
 
 
 
 
680
  color: white;
681
- margin-bottom: 20px;
682
  text-align: center;
 
683
  }
684
  """) as demo:
685
  gr.Markdown(f"""
686
  # 🏈 Football Field Detection System
687
- **{get_gpu_info()}**
688
-
689
- Upload a football game video for automated detection of yard lines, numbers, and hash marks.
690
  """)
691
 
692
- # Upload notice
693
- with gr.Column(elem_classes="upload-notice"):
694
- gr.Markdown("""
695
- **Note for large videos:**
696
- - Initial upload may take a moment
697
- - Progress wheel will appear immediately
698
- - Processing starts as soon as upload is ready
699
- """)
700
-
701
  with gr.Row():
702
  with gr.Column(scale=1):
703
  gr.Markdown("### πŸ“€ Upload Video")
704
 
 
705
  video_input = gr.Video(
706
  label="Select Football Video",
707
  sources=["upload"],
708
- type="filepath" # Use filepath instead of numpy array for faster handling
709
  )
710
 
711
  upload_button = gr.Button(
@@ -718,8 +784,8 @@ with gr.Blocks(title="🏈 Football Field Detection", theme=gr.themes.Soft(), cs
718
  gr.Markdown("""
719
  1. Upload a football video (MP4, MOV, AVI, etc.)
720
  2. Click "Start Processing"
721
- 3. Progress wheel appears immediately
722
- 4. Processing begins after quick preparation
723
  5. Final video appears when complete
724
 
725
  **What gets detected:**
@@ -733,9 +799,11 @@ with gr.Blocks(title="🏈 Football Field Detection", theme=gr.themes.Soft(), cs
733
 
734
  if not MAIN_AVAILABLE:
735
  gr.Markdown("""
 
736
  ⚠️ **Warning**: Main processing module not available.
737
  Running in simulation mode.
738
- """, visible=True)
 
739
 
740
  with gr.Column(scale=2):
741
  gr.Markdown("### 🎬 Video Processing & Output")
@@ -758,11 +826,11 @@ with gr.Blocks(title="🏈 Football Field Detection", theme=gr.themes.Soft(), cs
758
  visible=False
759
  )
760
 
761
- # Handle button click - now updating 4 components
762
  upload_button.click(
763
  fn=upload_and_process,
764
  inputs=[video_input],
765
- outputs=[video_output, progress_overlay, progress_overlay, video_output] # Last two are for visibility updates
766
  )
767
 
768
  # HF Spaces deployment setup
@@ -771,25 +839,27 @@ if __name__ == "__main__":
771
  cleanup_old_files()
772
 
773
  print("=" * 60)
774
- print("🏈 Football Field Detection System - Enhanced UI")
775
  print("=" * 60)
776
  print(f"Upload directory: {UPLOAD_DIR.absolute()}")
777
  print(f"Output directory: {OUTPUT_DIR.absolute()}")
778
  print(f"Main module available: {MAIN_AVAILABLE}")
779
- print(f"Models preloaded: {MODELS_PRELOADED}")
780
- print("Layout: Overlapping frames with smooth transitions")
781
- print("Progress: 0-99% β†’ 100% (1s) β†’ Video")
 
 
 
782
  print("=" * 60)
783
- print("Starting Gradio interface on Hugging Face Spaces...")
784
  print("=" * 60)
785
 
786
- # Launch the app with optimized settings
787
  demo.launch(
788
  share=True,
789
- debug=True,
790
  server_name="0.0.0.0",
791
  server_port=7860,
792
- # Optimize for Hugging Face Spaces
793
- enable_queue=True,
794
- max_threads=2 # Reduce threading for better stability
795
  )
 
10
  import re
11
  import base64
12
  import asyncio
13
+ from concurrent.futures import ThreadPoolExecutor
14
+ import subprocess
15
 
16
  # Try to import main module
17
  try:
 
52
  processing_thread = None
53
  first_frame_path = None
54
 
55
+ # Model preloading
56
+ MODELS_LOADED = False
57
+ MODELS_LOADING = False
58
 
59
+ def load_models_in_background():
60
+ """Pre-load models in background for faster startup"""
61
+ global MODELS_LOADED, MODELS_LOADING
62
 
63
+ if MODELS_LOADING or MODELS_LOADED:
64
  return
65
 
66
+ MODELS_LOADING = True
 
67
 
68
+ def background_load():
69
+ global MODELS_LOADED
70
  try:
71
+ print("πŸ”„ Pre-loading models in background...")
72
+
73
  if MAIN_AVAILABLE:
74
+ # Import torch to force GPU initialization
75
+ import torch
76
+ print(f"βœ… PyTorch device: {torch.device('cuda' if torch.cuda.is_available() else 'mps' if hasattr(torch.backends, 'mps') and torch.backends.mps.is_available() else 'cpu')}")
77
+
78
+ # Minimal imports to trigger model loading
79
+ import cv2
80
+ import numpy as np
81
+
82
+ print("βœ… Background model loading complete")
83
+ else:
84
+ print("βœ… Running in simulation mode")
85
 
86
+ MODELS_LOADED = True
 
 
 
 
87
  except Exception as e:
88
+ print(f"⚠️ Background model loading failed: {e}")
89
+ finally:
90
+ MODELS_LOADING = False
91
 
92
+ # Start loading in background
93
+ threading.Thread(target=background_load, daemon=True).start()
94
 
95
+ # Start model preloading immediately
96
+ load_models_in_background()
97
 
98
  def cleanup_old_files():
99
  """Clean up files older than 1 hour"""
 
111
 
112
  def extract_first_frame_fast(video_path, output_path):
113
  """
114
+ Ultra-fast first frame extraction using ffmpeg (faster than OpenCV)
115
  """
116
  try:
117
+ # Use ffmpeg for faster frame extraction
118
+ cmd = [
119
+ 'ffmpeg', '-i', str(video_path),
120
+ '-vframes', '1',
121
+ '-q:v', '2', # Quality 2 (best) to 31 (worst)
122
+ '-y', # Overwrite output
123
+ str(output_path)
124
+ ]
125
 
126
+ # Run with suppressed output
127
+ result = subprocess.run(
128
+ cmd,
129
+ stdout=subprocess.DEVNULL,
130
+ stderr=subprocess.DEVNULL,
131
+ check=False
132
+ )
133
 
134
+ if result.returncode == 0 and output_path.exists():
135
+ return output_path
136
+ else:
137
+ # Fallback to OpenCV
138
+ import cv2
139
+ cap = cv2.VideoCapture(str(video_path))
140
+ ret, frame = cap.read()
141
+ if ret:
142
+ cv2.imwrite(str(output_path), frame, [cv2.IMWRITE_JPEG_QUALITY, 85])
143
+ cap.release()
144
+ return output_path if ret else None
145
  except Exception as e:
146
  print(f"Error extracting first frame: {e}")
147
  return None
148
 
149
+ def copy_file_fast(src, dst):
150
+ """Fast file copy using shutil with optimized buffer"""
151
+ try:
152
+ shutil.copy2(src, dst)
153
+ return True
154
+ except Exception as e:
155
+ print(f"Error copying file: {e}")
156
+ return False
 
157
 
158
  def process_video_in_thread(input_path, output_path, progress_queue):
159
  """Process video in a separate thread with time tracking"""
 
267
  secs = int(seconds % 60)
268
  return f"{hours:02d}:{minutes:02d}:{secs:02d}"
269
 
270
+ def create_progress_overlay_html(progress_data, first_frame_image=None, show_overlay=True, status="processing"):
271
  """Create HTML overlay with circular progress indicator over blurred video frame"""
272
 
273
  percent = progress_data.get("percent", 0)
 
426
  padding: 0 20px;
427
  text-shadow: 0 2px 10px rgba(0,0,0,0.5);
428
  ">{message}</div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
429
  </div>
430
  </div>
431
  """
432
 
433
  return html
434
 
435
+ def upload_and_process(video_file):
436
+ """Handle video upload and processing with IMMEDIATE feedback"""
437
  global is_processing, current_progress, processing_thread, first_frame_path
438
 
439
  if not video_file:
440
  # Return both: empty video output and hidden progress overlay
441
+ yield (
442
  None, # video_output
443
  create_progress_overlay_html({"percent": 0, "message": "Please upload a video file", "elapsed": "00:00", "remaining": "--:--"}, show_overlay=False), # progress_overlay (hidden)
444
  gr.update(visible=True), # progress_overlay visibility
445
  gr.update(visible=False) # video_output visibility
446
  )
447
+ return
448
 
449
  if is_processing:
450
+ yield (
451
  None, # video_output
452
  create_progress_overlay_html({"percent": 0, "message": "Already processing another video", "elapsed": "00:00", "remaining": "--:--"}, show_overlay=True, status="waiting"), # progress_overlay
453
  gr.update(visible=True), # progress_overlay visibility
454
  gr.update(visible=False) # video_output visibility
455
  )
456
+ return
457
 
458
  try:
459
  is_processing = True
 
469
  output_path = OUTPUT_DIR / f"processed_{timestamp}_{unique_id}_{input_filename}.mp4"
470
  first_frame_path = OUTPUT_DIR / f"frame_{timestamp}_{unique_id}.jpg"
471
 
472
+ # STEP 1: IMMEDIATELY show progress overlay (within 100ms)
473
+ current_progress = {"percent": 0, "message": "Initializing...", "elapsed": "00:00", "remaining": "--:--"}
474
 
475
  yield (
476
  None, # video_output
477
+ create_progress_overlay_html(current_progress, None, show_overlay=True, status="initializing"), # progress_overlay
478
  gr.update(visible=True), # progress_overlay visibility
479
  gr.update(visible=False) # video_output visibility
480
  )
481
 
482
+ # Small delay to ensure UI updates (but don't sleep too long)
483
+ time.sleep(0.05)
484
+
485
+ # STEP 2: Fast file copy (non-blocking)
486
+ current_progress = {"percent": 10, "message": "Uploading video...", "elapsed": "00:00", "remaining": "--:--"}
487
 
488
  yield (
489
  None, # video_output
 
492
  gr.update(visible=False) # video_output visibility
493
  )
494
 
495
+ # Copy file using ThreadPoolExecutor for non-blocking operation
496
+ with ThreadPoolExecutor(max_workers=2) as executor:
497
+ copy_future = executor.submit(copy_file_fast, video_file, upload_path)
498
+
499
+ # While copying, update progress
500
+ while not copy_future.done():
501
+ time.sleep(0.05) # Small sleep to prevent busy waiting
502
+ # Just keep showing uploading progress
503
+ yield (
504
+ None,
505
+ create_progress_overlay_html(current_progress, None, show_overlay=True, status="uploading"),
506
+ gr.update(visible=True),
507
+ gr.update(visible=False)
508
+ )
509
+
510
+ # Check if copy was successful
511
+ if not copy_future.result():
512
+ raise Exception("Failed to copy video file")
513
 
514
+ # STEP 3: Fast first frame extraction
515
+ current_progress = {"percent": 25, "message": "Extracting preview...", "elapsed": "00:00", "remaining": "--:--"}
516
 
517
  yield (
518
  None, # video_output
 
521
  gr.update(visible=False) # video_output visibility
522
  )
523
 
524
+ # Extract first frame using ThreadPoolExecutor
525
+ with ThreadPoolExecutor(max_workers=2) as executor:
526
+ extract_future = executor.submit(extract_first_frame_fast, upload_path, first_frame_path)
527
+
528
+ # While extracting, update progress
529
+ while not extract_future.done():
530
+ time.sleep(0.05)
531
+ yield (
532
+ None,
533
+ create_progress_overlay_html(current_progress, None, show_overlay=True, status="preparing"),
534
+ gr.update(visible=True),
535
+ gr.update(visible=False)
536
+ )
537
+
538
+ extract_future.result() # Wait for completion
539
 
540
  # Read first frame as base64
541
  first_frame_base64 = None
542
  if first_frame_path and first_frame_path.exists():
543
+ try:
544
+ with open(first_frame_path, "rb") as f:
545
+ first_frame_base64 = base64.b64encode(f.read()).decode()
546
+ except:
547
+ first_frame_base64 = None
548
 
549
+ # STEP 4: Start main processing immediately
550
+ current_progress = {"percent": 35, "message": "Loading models...", "elapsed": "00:00", "remaining": "--:--"}
551
 
552
  yield (
553
  None, # video_output
554
+ create_progress_overlay_html(current_progress, first_frame_base64, show_overlay=True, status="loading"), # progress_overlay
555
  gr.update(visible=True), # progress_overlay visibility
556
  gr.update(visible=False) # video_output visibility
557
  )
 
559
  # Create progress queue
560
  progress_queue = queue.Queue()
561
 
562
+ # Use ThreadPoolExecutor for processing
563
+ with ThreadPoolExecutor(max_workers=1) as executor:
564
+ processing_future = executor.submit(
565
+ process_video_in_thread,
566
+ upload_path,
567
+ output_path,
568
+ progress_queue
569
+ )
570
+
571
+ # Variables to track progress
572
+ reached_99_percent = False
573
+ last_update_time = time.time()
574
+ start_time = time.time()
575
+ consecutive_no_updates = 0
576
+
577
+ # Monitor progress with timeout protection
578
+ while not processing_future.done():
579
+ try:
580
+ # Check for progress updates
581
+ got_update = False
582
+ while True:
583
+ try:
584
+ progress_update = progress_queue.get_nowait()
585
+ current_progress = progress_update
586
+ got_update = True
587
+
588
+ # Check if we've reached 99%
589
+ if progress_update.get("percent", 0) >= 99:
590
+ reached_99_percent = True
591
+
592
+ # Create HTML progress overlay
593
+ html_content = create_progress_overlay_html(progress_update, first_frame_base64, show_overlay=True, status="processing")
594
+
595
+ # Update progress overlay
596
+ yield (
597
+ None,
598
+ html_content,
599
+ gr.update(visible=True),
600
+ gr.update(visible=False)
601
+ )
602
+
603
+ last_update_time = time.time()
604
+ consecutive_no_updates = 0
605
+
606
+ except queue.Empty:
607
+ break
608
+
609
+ # If no update for a while, still update UI to show we're alive
610
+ if not got_update:
611
+ consecutive_no_updates += 1
612
+ if consecutive_no_updates > 20: # ~1 second without updates
613
+ # Show a heartbeat update
614
+ elapsed = time.time() - start_time
615
+ heartbeat_progress = {
616
+ "percent": current_progress.get("percent", 35),
617
+ "message": f"Processing... ({int(elapsed)}s)",
618
+ "elapsed": format_time(elapsed),
619
+ "remaining": "--:--"
620
+ }
621
+
622
+ yield (
623
+ None,
624
+ create_progress_overlay_html(heartbeat_progress, first_frame_base64, show_overlay=True, status="processing"),
625
+ gr.update(visible=True),
626
+ gr.update(visible=False)
627
+ )
628
+ consecutive_no_updates = 0
629
+
630
+ # Check for timeout (thread stuck for more than 30 seconds)
631
+ if time.time() - last_update_time > 30:
632
+ print("Warning: Processing thread may be stuck")
633
+ elapsed = time.time() - start_time
634
+ current_progress = {
635
+ "percent": max(35, current_progress.get("percent", 35)),
636
+ "message": "Processing... (taking longer than usual)",
637
+ "elapsed": format_time(elapsed),
638
+ "remaining": "--:--"
639
+ }
640
 
 
641
  yield (
642
+ None,
643
+ create_progress_overlay_html(current_progress, first_frame_base64, show_overlay=True, status="processing"),
644
+ gr.update(visible=True),
645
+ gr.update(visible=False)
646
  )
 
647
  last_update_time = time.time()
 
 
 
 
 
 
 
648
 
649
+ time.sleep(0.05) # Small sleep for responsiveness
650
+
651
+ except Exception as e:
652
+ print(f"Error monitoring progress: {e}")
653
+ break
654
+
655
+ # Get final result
656
+ try:
657
+ result = processing_future.result(timeout=10)
658
  except Exception as e:
659
+ print(f"Error getting processing result: {e}")
660
+ result = None
661
 
662
+ # Final step: hide progress overlay and show video output
 
 
 
663
  if reached_99_percent:
664
+ # Show 100% completion briefly
665
  completion_progress = {
666
  "percent": 100,
667
+ "message": "Processing complete!",
668
  "elapsed": current_progress.get("elapsed", "00:00"),
669
  "remaining": "00:00"
670
  }
671
 
 
 
672
  yield (
673
+ None,
674
+ create_progress_overlay_html(completion_progress, first_frame_base64, show_overlay=True, status="complete"),
675
+ gr.update(visible=True),
676
+ gr.update(visible=False)
677
  )
678
 
679
+ time.sleep(0.5) # Brief pause to show completion
680
 
681
+ # Show final video
682
  yield (
683
  str(output_path), # video_output
684
+ create_progress_overlay_html({"percent": 100, "message": "Complete", "elapsed": "00:00", "remaining": "00:00"}, show_overlay=False), # Hidden overlay
685
  gr.update(visible=False), # progress_overlay visibility
686
  gr.update(visible=True) # video_output visibility
687
  )
 
694
  status="error"
695
  )
696
  yield (
697
+ None,
698
+ html_content,
699
+ gr.update(visible=True),
700
+ gr.update(visible=False)
701
  )
702
  finally:
703
  is_processing = False
704
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
705
  # Create Gradio interface
706
  with gr.Blocks(title="🏈 Football Field Detection", theme=gr.themes.Soft(), css="""
707
  .video-container {
 
738
  display: block !important;
739
  }
740
 
741
+ .gpu-info {
742
+ background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
743
+ padding: 10px;
744
+ border-radius: 8px;
745
+ color: white;
746
+ margin-bottom: 10px;
747
+ text-align: center;
748
+ font-size: 14px;
749
+ }
750
+
751
+ .warning-box {
752
+ background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
753
+ padding: 10px;
754
+ border-radius: 8px;
755
  color: white;
756
+ margin: 10px 0;
757
  text-align: center;
758
+ font-size: 14px;
759
  }
760
  """) as demo:
761
  gr.Markdown(f"""
762
  # 🏈 Football Field Detection System
763
+ **{get_gpu_info()} | Models: {'βœ… Pre-loaded' if MODELS_LOADED else 'πŸ”„ Loading...'}**
 
 
764
  """)
765
 
 
 
 
 
 
 
 
 
 
766
  with gr.Row():
767
  with gr.Column(scale=1):
768
  gr.Markdown("### πŸ“€ Upload Video")
769
 
770
+ # FIXED: Using correct Gradio Video component parameters
771
  video_input = gr.Video(
772
  label="Select Football Video",
773
  sources=["upload"],
774
+ format="mp4" # Changed from 'type' to 'format'
775
  )
776
 
777
  upload_button = gr.Button(
 
784
  gr.Markdown("""
785
  1. Upload a football video (MP4, MOV, AVI, etc.)
786
  2. Click "Start Processing"
787
+ 3. Watch the circular progress indicator
788
+ 4. The blur will fade as processing progresses
789
  5. Final video appears when complete
790
 
791
  **What gets detected:**
 
799
 
800
  if not MAIN_AVAILABLE:
801
  gr.Markdown("""
802
+ <div class="warning-box">
803
  ⚠️ **Warning**: Main processing module not available.
804
  Running in simulation mode.
805
+ </div>
806
+ """)
807
 
808
  with gr.Column(scale=2):
809
  gr.Markdown("### 🎬 Video Processing & Output")
 
826
  visible=False
827
  )
828
 
829
+ # Handle button click
830
  upload_button.click(
831
  fn=upload_and_process,
832
  inputs=[video_input],
833
+ outputs=[video_output, progress_overlay, progress_overlay, video_output]
834
  )
835
 
836
  # HF Spaces deployment setup
 
839
  cleanup_old_files()
840
 
841
  print("=" * 60)
842
+ print("🏈 Football Field Detection System")
843
  print("=" * 60)
844
  print(f"Upload directory: {UPLOAD_DIR.absolute()}")
845
  print(f"Output directory: {OUTPUT_DIR.absolute()}")
846
  print(f"Main module available: {MAIN_AVAILABLE}")
847
+ print(f"Models preloaded: {MODELS_LOADED}")
848
+ print("Optimizations:")
849
+ print(" - ThreadPoolExecutor for parallel operations")
850
+ print(" - ffmpeg for fast frame extraction")
851
+ print(" - Immediate UI feedback")
852
+ print(" - Heartbeat updates during processing")
853
  print("=" * 60)
854
+ print("Starting Gradio interface...")
855
  print("=" * 60)
856
 
857
+ # FIXED: Using correct launch parameters for Gradio 4.x
858
  demo.launch(
859
  share=True,
860
+ debug=False,
861
  server_name="0.0.0.0",
862
  server_port=7860,
863
+ # Newer Gradio versions don't have enable_queue parameter
864
+ # Queue is enabled by default when using yield/generator functions
 
865
  )