Sean Carnahan commited on
Commit
cd361a4
·
1 Parent(s): fbef789

Update for HF Spaces deployment: Add memory management, error handling, and logging

Browse files
Files changed (5) hide show
  1. .gitignore +43 -0
  2. Dockerfile +14 -20
  3. README.md +49 -0
  4. app.py +82 -154
  5. requirements.txt +1 -0
.gitignore ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Python
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+ *.so
6
+ .Python
7
+ env/
8
+ build/
9
+ develop-eggs/
10
+ dist/
11
+ downloads/
12
+ eggs/
13
+ .eggs/
14
+ lib/
15
+ lib64/
16
+ parts/
17
+ sdist/
18
+ var/
19
+ wheels/
20
+ *.egg-info/
21
+ .installed.cfg
22
+ *.egg
23
+
24
+ # Virtual Environment
25
+ venv/
26
+ ENV/
27
+
28
+ # IDE
29
+ .idea/
30
+ .vscode/
31
+ *.swp
32
+ *.swo
33
+
34
+ # Project specific
35
+ static/uploads/
36
+ temp_frame_for_cnn_*.jpg
37
+ *.mp4
38
+ *.avi
39
+ *.mov
40
+ *.mkv
41
+
42
+ # Logs
43
+ *.log
Dockerfile CHANGED
@@ -1,35 +1,29 @@
1
- # Use a Python version that matches your (keras2env) as closely as possible
2
- FROM python:3.9-slim
3
 
4
- WORKDIR /app
5
 
6
  # Install system dependencies
7
- RUN apt-get update && apt-get install -y --no-install-recommends \
8
  libgl1-mesa-glx \
9
  libglib2.0-0 \
10
  && rm -rf /var/lib/apt/lists/*
11
 
 
12
  COPY requirements.txt .
13
  RUN pip install --no-cache-dir -r requirements.txt
14
 
15
- # Fix permissions for mediapipe model files
16
- RUN chmod -R 755 /usr/local/lib/python3.9/site-packages/mediapipe
17
 
18
- # Copy all necessary application files and folders from HFup/ to /app in the container
19
- # These paths are relative to the Dockerfile's location (i.e., inside HFup/)
20
- COPY app.py .
21
- RUN echo "Listing files:" && ls -la # Debug: List files in the build context root
22
- COPY bodybuilding_pose_analyzer bodybuilding_pose_analyzer
23
- COPY external external
24
- # COPY yolov7 yolov7
25
- # COPY yolov7-w6-pose.pt .
26
- COPY static static
27
- COPY templates templates
28
 
29
- # Ensure the uploads directory within static exists and is writable
30
- RUN mkdir -p static/uploads && chmod -R 777 static/uploads
 
31
 
 
32
  EXPOSE 7860
33
 
34
- # Command to run app with Gunicorn
35
- CMD ["gunicorn", "--bind", "0.0.0.0:7860", "--workers", "1", "--threads", "2", "--timeout", "300", "app:app"]
 
1
+ FROM python:3.10-slim
 
2
 
3
+ WORKDIR /code
4
 
5
  # Install system dependencies
6
+ RUN apt-get update && apt-get install -y \
7
  libgl1-mesa-glx \
8
  libglib2.0-0 \
9
  && rm -rf /var/lib/apt/lists/*
10
 
11
+ # Copy requirements first to leverage Docker cache
12
  COPY requirements.txt .
13
  RUN pip install --no-cache-dir -r requirements.txt
14
 
15
+ # Copy the rest of the application
16
+ COPY . .
17
 
18
+ # Create necessary directories
19
+ RUN mkdir -p static/uploads
 
 
 
 
 
 
 
 
20
 
21
+ # Set environment variables
22
+ ENV PYTHONUNBUFFERED=1
23
+ ENV FLASK_APP=app.py
24
 
25
+ # Expose the port
26
  EXPOSE 7860
27
 
28
+ # Run the application
29
+ CMD ["python", "app.py"]
README.md CHANGED
@@ -71,6 +71,55 @@ This Space uses a Flask backend with various machine learning models for pose es
71
  * The feedback provided is based on predefined angle ranges and may not cover all nuances of perfect form.
72
  * Processing time can be significant for longer videos or when using more computationally intensive models.
73
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74
  ---
75
 
76
  *Remember to replace placeholder links and add any other specific information relevant to your project!*
 
71
  * The feedback provided is based on predefined angle ranges and may not cover all nuances of perfect form.
72
  * Processing time can be significant for longer videos or when using more computationally intensive models.
73
 
74
+ ## Setup
75
+
76
+ 1. Install dependencies:
77
+ ```bash
78
+ pip install -r requirements.txt
79
+ ```
80
+
81
+ 2. Ensure the model files are in place:
82
+ - CNN model: `external/BodybuildingPoseClassifier/bodybuilding_pose_classifier.h5`
83
+
84
+ 3. Run the application:
85
+ ```bash
86
+ python app.py
87
+ ```
88
+
89
+ The application will be available at `http://localhost:7860`
90
+
91
+ ## Usage
92
+
93
+ 1. Open the web interface
94
+ 2. Select a video file (supported formats: mp4, avi, mov, mkv)
95
+ 3. Choose the model (Gladiator SupaDot or MoveNet)
96
+ 4. Upload and wait for processing
97
+ 5. View the results with pose detection, angles, and corrections
98
+
99
+ ## Models
100
+
101
+ - **Gladiator SupaDot**: Custom pose analyzer with detailed angle measurements and form corrections
102
+ - **MoveNet**: Google's pose detection model for basic pose tracking
103
+
104
+ ## Dependencies
105
+
106
+ - Flask
107
+ - OpenCV
108
+ - TensorFlow
109
+ - MediaPipe
110
+ - NumPy
111
+ - Other dependencies listed in requirements.txt
112
+
113
+ ## Notes
114
+
115
+ - Maximum video file size: 100MB
116
+ - Processing time depends on video length and available hardware
117
+ - GPU acceleration is automatically enabled if available
118
+
119
+ ## License
120
+
121
+ This project is licensed under the MIT License - see the LICENSE file for details.
122
+
123
  ---
124
 
125
  *Remember to replace placeholder links and add any other specific information relevant to your project!*
app.py CHANGED
@@ -12,6 +12,9 @@ from tensorflow.keras.models import load_model
12
  from tensorflow.keras.preprocessing import image
13
  import time
14
  import tensorflow_hub as hub
 
 
 
15
 
16
  # Check GPU availability
17
  print("[GPU] Checking GPU availability...")
@@ -32,13 +35,20 @@ sys.path.append('.') # Assuming app.py is at the root of cv.github.io
32
  from bodybuilding_pose_analyzer.src.movenet_analyzer import MoveNetAnalyzer
33
  from bodybuilding_pose_analyzer.src.pose_analyzer import PoseAnalyzer
34
 
35
- # Add YOLOv7 to path
36
- # sys.path.append('yolov7')
 
37
 
38
- # from yolov7.models.experimental import attempt_load
39
- # from yolov7.utils.general import check_img_size, non_max_suppression_kpt, scale_coords
40
- # from yolov7.utils.torch_utils import select_device
41
- # from yolov7.utils.plots import plot_skeleton_kpts
 
 
 
 
 
 
42
 
43
  def wrap_text(text: str, font_face: int, font_scale: float, thickness: int, max_width: int) -> list[str]:
44
  """Wrap text to fit within max_width."""
@@ -83,25 +93,6 @@ app.config['MAX_CONTENT_LENGTH'] = 100 * 1024 * 1024 # 100MB max file size
83
  # Ensure upload directory exists
84
  os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
85
 
86
- # Initialize YOLOv7 model
87
- # device = select_device('')
88
- # yolo_model = None # Initialize as None
89
- # stride = None
90
- # imgsz = None
91
-
92
- # try:
93
- # yolo_model = attempt_load('yolov7-w6-pose.pt', map_location=device)
94
- # stride = int(yolo_model.stride.max())
95
- # imgsz = check_img_size(640, s=stride)
96
- # print("YOLOv7 Model loaded successfully")
97
- # except Exception as e:
98
- # print(f"Error loading YOLOv7 model: {e}")
99
- # traceback.print_exc()
100
- # Not raising here to allow app to run if only MoveNet is used. Error will be caught if YOLOv7 is selected.
101
-
102
- # YOLOv7 pose model expects 17 keypoints
103
- # kpt_shape = (17, 3)
104
-
105
  # Load CNN model for bodybuilding pose classification
106
  cnn_model_path = 'external/BodybuildingPoseClassifier/bodybuilding_pose_classifier.h5'
107
  cnn_model = load_model(cnn_model_path)
@@ -109,31 +100,34 @@ cnn_class_labels = ['side_chest', 'front_double_biceps', 'back_double_biceps', '
109
 
110
  def predict_pose_cnn(img_path):
111
  try:
 
112
  if gpus:
113
- print("[CNN_DEBUG] Using GPU for CNN prediction")
114
  with tf.device('/GPU:0'):
115
  img = image.load_img(img_path, target_size=(150, 150))
116
  img_array = image.img_to_array(img)
117
  img_array = np.expand_dims(img_array, axis=0) / 255.0
118
- predictions = cnn_model.predict(img_array)
119
  predicted_class = np.argmax(predictions, axis=1)
120
  confidence = float(np.max(predictions))
121
  else:
122
- print("[CNN_DEBUG] No GPU found, using CPU for CNN prediction")
123
  with tf.device('/CPU:0'):
124
  img = image.load_img(img_path, target_size=(150, 150))
125
  img_array = image.img_to_array(img)
126
  img_array = np.expand_dims(img_array, axis=0) / 255.0
127
- predictions = cnn_model.predict(img_array)
128
  predicted_class = np.argmax(predictions, axis=1)
129
  confidence = float(np.max(predictions))
130
 
131
- print(f"[CNN_DEBUG] Prediction successful: {cnn_class_labels[predicted_class[0]]}")
132
  return cnn_class_labels[predicted_class[0]], confidence
133
  except Exception as e:
134
- print(f"[CNN_ERROR] Exception during CNN prediction: {e}")
135
  traceback.print_exc()
136
  raise
 
 
137
 
138
  @app.route('/static/uploads/<path:filename>')
139
  def serve_video(filename):
@@ -150,88 +144,6 @@ def after_request(response):
150
  response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS')
151
  return response
152
 
153
- # def process_video_yolov7(video_path): # Renamed from process_video
154
- # global yolo_model, imgsz, stride # Ensure global model is used
155
- # if yolo_model is None:
156
- # raise RuntimeError("YOLOv7 model failed to load. Cannot process video.")
157
- # try:
158
- # if not os.path.exists(video_path):
159
- # raise FileNotFoundError(f"Video file not found: {video_path}")
160
- #
161
- # cap = cv2.VideoCapture(video_path)
162
- # if not cap.isOpened():
163
- # raise ValueError(f"Failed to open video file: {video_path}")
164
- #
165
- # fps = int(cap.get(cv2.CAP_PROP_FPS))
166
- # width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
167
- # height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
168
- #
169
- # print(f"Processing video: {width}x{height} @ {fps}fps")
170
- #
171
- # # Create output video writer
172
- # output_path = os.path.join(app.config['UPLOAD_FOLDER'], 'output.mp4')
173
- # fourcc = cv2.VideoWriter_fourcc(*'avc1')
174
- # out = cv2.VideoWriter(output_path, fourcc, fps, (width, height))
175
- #
176
- # frame_count = 0
177
- # while cap.isOpened():
178
- # ret, frame = cap.read()
179
- # if not ret:
180
- # break
181
- #
182
- # frame_count += 1
183
- # print(f"Processing frame {frame_count}")
184
- #
185
- # # Prepare image
186
- # img = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
187
- # img = cv2.resize(img, (imgsz, imgsz))
188
- # img = img.transpose((2, 0, 1)) # HWC to CHW
189
- # img = np.ascontiguousarray(img)
190
- # img = torch.from_numpy(img).to(device)
191
- # img = img.float() / 255.0
192
- # if img.ndimension() == 3:
193
- # img = img.unsqueeze(0)
194
- #
195
- # # Inference
196
- # with torch.no_grad():
197
- # pred = yolo_model(img)[0] # Use yolo_model
198
- # pred = non_max_suppression_kpt(pred, conf_thres=0.25, iou_thres=0.45, nc=yolo_model.yaml['nc'], kpt_label=True)
199
- #
200
- # # Draw results
201
- # output_frame = frame.copy()
202
- # poses_detected = False
203
- # for det in pred:
204
- # if len(det):
205
- # poses_detected = True
206
- # det[:, :4] = scale_coords(img.shape[2:], det[:, :4], frame.shape).round()
207
- # for row in det:
208
- # xyxy = row[:4]
209
- # conf = row[4]
210
- # cls = row[5]
211
- # kpts = row[6:]
212
- # kpts = torch.tensor(kpts).view(kpt_shape)
213
- # output_frame = plot_skeleton_kpts(output_frame, kpts, steps=3, orig_shape=output_frame.shape[:2])
214
- #
215
- # if not poses_detected:
216
- # print(f"No poses detected in frame {frame_count}")
217
- #
218
- # out.write(output_frame)
219
- #
220
- # cap.release()
221
- # out.release()
222
- #
223
- # if frame_count == 0:
224
- # raise ValueError("No frames were processed from the video")
225
- #
226
- # print(f"Video processing completed. Processed {frame_count} frames")
227
- # # Return URL for the client, using the 'serve_video' endpoint
228
- # output_filename = 'output.mp4'
229
- # return url_for('serve_video', filename=output_filename, _external=False)
230
- # except Exception as e:
231
- # print('Error in process_video:', e)
232
- # traceback.print_exc()
233
- # raise
234
-
235
  def process_video_movenet(video_path):
236
  try:
237
  print("[DEBUG] Starting MoveNet video processing")
@@ -328,7 +240,8 @@ def process_video_movenet(video_path):
328
 
329
  def process_video_mediapipe(video_path):
330
  try:
331
- print(f"[PROCESS_VIDEO_MEDIAPIPE] Called with video_path: {video_path}")
 
332
  if not os.path.exists(video_path):
333
  raise FileNotFoundError(f"Video file not found: {video_path}")
334
 
@@ -365,7 +278,8 @@ def process_video_mediapipe(video_path):
365
  break
366
  frame_count += 1
367
  if frame_count % 30 == 0:
368
- print(f"Processing frame {frame_count}")
 
369
 
370
  # Process frame with MediaPipe
371
  processed_frame, current_analysis_results, landmarks = analyzer.process_frame(frame, last_valid_landmarks=last_valid_landmarks)
@@ -379,14 +293,14 @@ def process_video_mediapipe(video_path):
379
  cv2.imwrite(temp_img_path, frame)
380
  try:
381
  cnn_pose_pred, cnn_conf = predict_pose_cnn(temp_img_path)
382
- print(f"[CNN] Frame {frame_count}: Pose: {cnn_pose_pred}, Conf: {cnn_conf:.2f}")
383
  if cnn_conf >= 0.3:
384
  current_pose = cnn_pose_pred # Update current_pose to be displayed
385
  except Exception as e:
386
- print(f"[CNN] Error predicting pose on frame {frame_count}: {e}")
387
  finally:
388
- if os.path.exists(temp_img_path):
389
- os.remove(temp_img_path)
390
 
391
  # Create side panel
392
  panel = np.zeros((height, panel_width, 3), dtype=np.uint8)
@@ -395,33 +309,29 @@ def process_video_mediapipe(video_path):
395
  current_font = cv2.FONT_HERSHEY_DUPLEX
396
 
397
  # Base font scale and reference video height for scaling
398
- # Adjust base_font_scale_at_ref_height if text is generally too large or too small
399
  base_font_scale_at_ref_height = 0.6
400
- reference_height_for_font_scale = 640.0 # e.g., a common video height like 480p, 720p
401
 
402
  # Calculate dynamic font_scale
403
  font_scale = (height / reference_height_for_font_scale) * base_font_scale_at_ref_height
404
- # Clamp font_scale to a min/max range to avoid extremes
405
  font_scale = max(0.4, min(font_scale, 1.2))
406
 
407
  # Calculate dynamic thickness
408
  thickness = 1 if font_scale < 0.7 else 2
409
 
410
- # Calculate dynamic line_height based on actual text height
411
- # Using a sample string like "Ag" which has ascenders and descenders
412
  (_, text_actual_height), _ = cv2.getTextSize("Ag", current_font, font_scale, thickness)
413
- line_spacing_factor = 1.8 # Adjust for more or less space between lines
414
  line_height = int(text_actual_height * line_spacing_factor)
415
- line_height = max(line_height, 15) # Ensure a minimum line height
416
 
417
- # Initial y_offset for the first line of text
418
- y_offset_panel = max(line_height, 20) # Start considering top margin and text height
419
- # --- End of Dynamic Text Parameter Calculations ---
420
 
421
  cv2.putText(panel, "Model: Gladiator SupaDot", (10, y_offset_panel), current_font, font_scale, (0, 255, 255), thickness, lineType=cv2.LINE_AA)
422
  y_offset_panel += line_height
423
- if frame_count % 30 == 0: # Print every 30 frames to avoid flooding console
424
- print(f"[MEDIAPIPE_PANEL] Frame {frame_count} - Current Pose for Panel: {current_pose}")
425
  cv2.putText(panel, f"Pose: {current_pose}", (10, y_offset_panel), current_font, font_scale, (255, 0, 0), thickness, lineType=cv2.LINE_AA)
426
  y_offset_panel += int(line_height * 1.5)
427
 
@@ -441,10 +351,9 @@ def process_video_mediapipe(video_path):
441
  cv2.putText(panel, f"• {correction}", (20, y_offset_panel), current_font, font_scale, (0, 0, 255), thickness, lineType=cv2.LINE_AA)
442
  y_offset_panel += line_height
443
 
444
- # Display notes if any
445
  if analysis_results.get('notes'):
446
  y_offset_panel += line_height
447
- cv2.putText(panel, "Notes:", (10, y_offset_panel), current_font, font_scale, (200, 200, 200), thickness, lineType=cv2.LINE_AA) # Grey color for notes
448
  y_offset_panel += line_height
449
  for note in analysis_results.get('notes', []):
450
  cv2.putText(panel, f"• {note}", (20, y_offset_panel), current_font, font_scale, (200, 200, 200), thickness, lineType=cv2.LINE_AA)
@@ -454,19 +363,22 @@ def process_video_mediapipe(video_path):
454
  y_offset_panel += line_height
455
  cv2.putText(panel, analysis_results.get('error', 'Unknown error'), (20, y_offset_panel), current_font, font_scale, (0, 0, 255), thickness, lineType=cv2.LINE_AA)
456
 
457
- combined_frame = np.hstack((processed_frame, panel)) # Use processed_frame from analyzer
458
  out.write(combined_frame)
459
 
460
  cap.release()
461
  out.release()
 
462
  if frame_count == 0:
463
  raise ValueError("No frames were processed from the video by MediaPipe")
464
- print(f"MediaPipe video processing completed. Processed {frame_count} frames. Output: {output_path}")
465
  return url_for('serve_video', filename=output_filename, _external=False)
466
  except Exception as e:
467
- print(f'Error in process_video_mediapipe: {e}')
468
  traceback.print_exc()
469
  raise
 
 
470
 
471
  @app.route('/')
472
  def index():
@@ -475,55 +387,56 @@ def index():
475
  @app.route('/upload', methods=['POST'])
476
  def upload_file():
477
  try:
 
478
  if 'video' not in request.files:
479
- print("[UPLOAD] No video file in request")
480
  return jsonify({'error': 'No video file provided'}), 400
481
 
482
  file = request.files['video']
483
  if file.filename == '':
484
- print("[UPLOAD] Empty filename")
485
  return jsonify({'error': 'No selected file'}), 400
486
 
487
  if file:
488
  allowed_extensions = {'mp4', 'avi', 'mov', 'mkv'}
489
  if '.' not in file.filename or file.filename.rsplit('.', 1)[1].lower() not in allowed_extensions:
490
- print(f"[UPLOAD] Invalid file format: {file.filename}")
491
  return jsonify({'error': 'Invalid file format. Allowed formats: mp4, avi, mov, mkv'}), 400
492
 
493
  # Ensure the filename is properly sanitized
494
  filename = secure_filename(file.filename)
495
- print(f"[UPLOAD] Original filename: {file.filename}")
496
- print(f"[UPLOAD] Sanitized filename: {filename}")
497
 
498
  # Create a unique filename to prevent conflicts
499
  base, ext = os.path.splitext(filename)
500
  unique_filename = f"{base}_{int(time.time())}{ext}"
501
  filepath = os.path.join(app.config['UPLOAD_FOLDER'], unique_filename)
502
 
503
- print(f"[UPLOAD] Saving file to: {filepath}")
504
  file.save(filepath)
505
 
506
  if not os.path.exists(filepath):
507
- print(f"[UPLOAD] File not found after save: {filepath}")
508
  return jsonify({'error': 'Failed to save uploaded file'}), 500
509
 
510
- print(f"[UPLOAD] File saved successfully. Size: {os.path.getsize(filepath)} bytes")
511
 
512
  try:
513
  model_choice = request.form.get('model_choice', 'Gladiator SupaDot')
514
- print(f"[UPLOAD] Processing with model: {model_choice}")
515
 
516
  if model_choice == 'movenet':
517
  movenet_variant = request.form.get('movenet_variant', 'lightning')
518
- print(f"[UPLOAD] Using MoveNet variant: {movenet_variant}")
519
  output_path_url = process_video_movenet(filepath)
520
  else:
521
  output_path_url = process_video_mediapipe(filepath)
522
 
523
- print(f"[UPLOAD] Processing complete. Output URL: {output_path_url}")
524
 
525
  if not os.path.exists(os.path.join(app.config['UPLOAD_FOLDER'], os.path.basename(output_path_url))):
526
- print(f"[UPLOAD] Output file not found: {output_path_url}")
527
  return jsonify({'error': 'Output video file not found'}), 500
528
 
529
  return jsonify({
@@ -532,22 +445,37 @@ def upload_file():
532
  })
533
 
534
  except Exception as e:
535
- print(f"[UPLOAD] Error processing video: {str(e)}")
536
  traceback.print_exc()
537
  return jsonify({'error': f'Error processing video: {str(e)}'}), 500
538
 
539
  finally:
540
  try:
541
- if os.path.exists(filepath):
542
- os.remove(filepath)
543
- print(f"[UPLOAD] Cleaned up input file: {filepath}")
544
  except Exception as e:
545
- print(f"[UPLOAD] Error cleaning up file: {str(e)}")
546
 
547
  except Exception as e:
548
- print(f"[UPLOAD] Unexpected error: {str(e)}")
549
  traceback.print_exc()
550
  return jsonify({'error': 'Internal server error'}), 500
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
551
 
552
  if __name__ == '__main__':
553
  # Ensure the port is 7860 and debug is False for HF Spaces deployment
 
12
  from tensorflow.keras.preprocessing import image
13
  import time
14
  import tensorflow_hub as hub
15
+ import gc
16
+ import psutil
17
+ import logging
18
 
19
  # Check GPU availability
20
  print("[GPU] Checking GPU availability...")
 
35
  from bodybuilding_pose_analyzer.src.movenet_analyzer import MoveNetAnalyzer
36
  from bodybuilding_pose_analyzer.src.pose_analyzer import PoseAnalyzer
37
 
38
+ # Configure logging
39
+ logging.basicConfig(level=logging.INFO)
40
+ logger = logging.getLogger(__name__)
41
 
42
+ def log_memory_usage():
43
+ """Log current memory usage."""
44
+ process = psutil.Process()
45
+ memory_info = process.memory_info()
46
+ logger.info(f"Memory usage: {memory_info.rss / 1024 / 1024:.2f} MB")
47
+
48
+ def cleanup_memory():
49
+ """Force garbage collection and log memory usage."""
50
+ gc.collect()
51
+ log_memory_usage()
52
 
53
  def wrap_text(text: str, font_face: int, font_scale: float, thickness: int, max_width: int) -> list[str]:
54
  """Wrap text to fit within max_width."""
 
93
  # Ensure upload directory exists
94
  os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
95
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96
  # Load CNN model for bodybuilding pose classification
97
  cnn_model_path = 'external/BodybuildingPoseClassifier/bodybuilding_pose_classifier.h5'
98
  cnn_model = load_model(cnn_model_path)
 
100
 
101
  def predict_pose_cnn(img_path):
102
  try:
103
+ cleanup_memory() # Clean up before prediction
104
  if gpus:
105
+ logger.info("[CNN_DEBUG] Using GPU for CNN prediction")
106
  with tf.device('/GPU:0'):
107
  img = image.load_img(img_path, target_size=(150, 150))
108
  img_array = image.img_to_array(img)
109
  img_array = np.expand_dims(img_array, axis=0) / 255.0
110
+ predictions = cnn_model.predict(img_array, verbose=0) # Disable progress bar
111
  predicted_class = np.argmax(predictions, axis=1)
112
  confidence = float(np.max(predictions))
113
  else:
114
+ logger.info("[CNN_DEBUG] No GPU found, using CPU for CNN prediction")
115
  with tf.device('/CPU:0'):
116
  img = image.load_img(img_path, target_size=(150, 150))
117
  img_array = image.img_to_array(img)
118
  img_array = np.expand_dims(img_array, axis=0) / 255.0
119
+ predictions = cnn_model.predict(img_array, verbose=0) # Disable progress bar
120
  predicted_class = np.argmax(predictions, axis=1)
121
  confidence = float(np.max(predictions))
122
 
123
+ logger.info(f"[CNN_DEBUG] Prediction successful: {cnn_class_labels[predicted_class[0]]}")
124
  return cnn_class_labels[predicted_class[0]], confidence
125
  except Exception as e:
126
+ logger.error(f"[CNN_ERROR] Exception during CNN prediction: {e}")
127
  traceback.print_exc()
128
  raise
129
+ finally:
130
+ cleanup_memory() # Clean up after prediction
131
 
132
  @app.route('/static/uploads/<path:filename>')
133
  def serve_video(filename):
 
144
  response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS')
145
  return response
146
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
147
  def process_video_movenet(video_path):
148
  try:
149
  print("[DEBUG] Starting MoveNet video processing")
 
240
 
241
  def process_video_mediapipe(video_path):
242
  try:
243
+ cleanup_memory() # Clean up before processing
244
+ logger.info(f"[PROCESS_VIDEO_MEDIAPIPE] Called with video_path: {video_path}")
245
  if not os.path.exists(video_path):
246
  raise FileNotFoundError(f"Video file not found: {video_path}")
247
 
 
278
  break
279
  frame_count += 1
280
  if frame_count % 30 == 0:
281
+ logger.info(f"Processing frame {frame_count}")
282
+ cleanup_memory() # Clean up periodically
283
 
284
  # Process frame with MediaPipe
285
  processed_frame, current_analysis_results, landmarks = analyzer.process_frame(frame, last_valid_landmarks=last_valid_landmarks)
 
293
  cv2.imwrite(temp_img_path, frame)
294
  try:
295
  cnn_pose_pred, cnn_conf = predict_pose_cnn(temp_img_path)
296
+ logger.info(f"[CNN] Frame {frame_count}: Pose: {cnn_pose_pred}, Conf: {cnn_conf:.2f}")
297
  if cnn_conf >= 0.3:
298
  current_pose = cnn_pose_pred # Update current_pose to be displayed
299
  except Exception as e:
300
+ logger.error(f"[CNN] Error predicting pose on frame {frame_count}: {e}")
301
  finally:
302
+ if os.path.exists(temp_img_path):
303
+ os.remove(temp_img_path)
304
 
305
  # Create side panel
306
  panel = np.zeros((height, panel_width, 3), dtype=np.uint8)
 
309
  current_font = cv2.FONT_HERSHEY_DUPLEX
310
 
311
  # Base font scale and reference video height for scaling
 
312
  base_font_scale_at_ref_height = 0.6
313
+ reference_height_for_font_scale = 640.0
314
 
315
  # Calculate dynamic font_scale
316
  font_scale = (height / reference_height_for_font_scale) * base_font_scale_at_ref_height
 
317
  font_scale = max(0.4, min(font_scale, 1.2))
318
 
319
  # Calculate dynamic thickness
320
  thickness = 1 if font_scale < 0.7 else 2
321
 
322
+ # Calculate dynamic line_height
 
323
  (_, text_actual_height), _ = cv2.getTextSize("Ag", current_font, font_scale, thickness)
324
+ line_spacing_factor = 1.8
325
  line_height = int(text_actual_height * line_spacing_factor)
326
+ line_height = max(line_height, 15)
327
 
328
+ # Initial y_offset
329
+ y_offset_panel = max(line_height, 20)
 
330
 
331
  cv2.putText(panel, "Model: Gladiator SupaDot", (10, y_offset_panel), current_font, font_scale, (0, 255, 255), thickness, lineType=cv2.LINE_AA)
332
  y_offset_panel += line_height
333
+ if frame_count % 30 == 0:
334
+ logger.info(f"[MEDIAPIPE_PANEL] Frame {frame_count} - Current Pose for Panel: {current_pose}")
335
  cv2.putText(panel, f"Pose: {current_pose}", (10, y_offset_panel), current_font, font_scale, (255, 0, 0), thickness, lineType=cv2.LINE_AA)
336
  y_offset_panel += int(line_height * 1.5)
337
 
 
351
  cv2.putText(panel, f"• {correction}", (20, y_offset_panel), current_font, font_scale, (0, 0, 255), thickness, lineType=cv2.LINE_AA)
352
  y_offset_panel += line_height
353
 
 
354
  if analysis_results.get('notes'):
355
  y_offset_panel += line_height
356
+ cv2.putText(panel, "Notes:", (10, y_offset_panel), current_font, font_scale, (200, 200, 200), thickness, lineType=cv2.LINE_AA)
357
  y_offset_panel += line_height
358
  for note in analysis_results.get('notes', []):
359
  cv2.putText(panel, f"• {note}", (20, y_offset_panel), current_font, font_scale, (200, 200, 200), thickness, lineType=cv2.LINE_AA)
 
363
  y_offset_panel += line_height
364
  cv2.putText(panel, analysis_results.get('error', 'Unknown error'), (20, y_offset_panel), current_font, font_scale, (0, 0, 255), thickness, lineType=cv2.LINE_AA)
365
 
366
+ combined_frame = np.hstack((processed_frame, panel))
367
  out.write(combined_frame)
368
 
369
  cap.release()
370
  out.release()
371
+ cleanup_memory() # Clean up after processing
372
  if frame_count == 0:
373
  raise ValueError("No frames were processed from the video by MediaPipe")
374
+ logger.info(f"MediaPipe video processing completed. Processed {frame_count} frames. Output: {output_path}")
375
  return url_for('serve_video', filename=output_filename, _external=False)
376
  except Exception as e:
377
+ logger.error(f'Error in process_video_mediapipe: {e}')
378
  traceback.print_exc()
379
  raise
380
+ finally:
381
+ cleanup_memory() # Clean up in case of error
382
 
383
  @app.route('/')
384
  def index():
 
387
  @app.route('/upload', methods=['POST'])
388
  def upload_file():
389
  try:
390
+ cleanup_memory() # Clean up before processing
391
  if 'video' not in request.files:
392
+ logger.error("[UPLOAD] No video file in request")
393
  return jsonify({'error': 'No video file provided'}), 400
394
 
395
  file = request.files['video']
396
  if file.filename == '':
397
+ logger.error("[UPLOAD] Empty filename")
398
  return jsonify({'error': 'No selected file'}), 400
399
 
400
  if file:
401
  allowed_extensions = {'mp4', 'avi', 'mov', 'mkv'}
402
  if '.' not in file.filename or file.filename.rsplit('.', 1)[1].lower() not in allowed_extensions:
403
+ logger.error(f"[UPLOAD] Invalid file format: {file.filename}")
404
  return jsonify({'error': 'Invalid file format. Allowed formats: mp4, avi, mov, mkv'}), 400
405
 
406
  # Ensure the filename is properly sanitized
407
  filename = secure_filename(file.filename)
408
+ logger.info(f"[UPLOAD] Original filename: {file.filename}")
409
+ logger.info(f"[UPLOAD] Sanitized filename: {filename}")
410
 
411
  # Create a unique filename to prevent conflicts
412
  base, ext = os.path.splitext(filename)
413
  unique_filename = f"{base}_{int(time.time())}{ext}"
414
  filepath = os.path.join(app.config['UPLOAD_FOLDER'], unique_filename)
415
 
416
+ logger.info(f"[UPLOAD] Saving file to: {filepath}")
417
  file.save(filepath)
418
 
419
  if not os.path.exists(filepath):
420
+ logger.error(f"[UPLOAD] File not found after save: {filepath}")
421
  return jsonify({'error': 'Failed to save uploaded file'}), 500
422
 
423
+ logger.info(f"[UPLOAD] File saved successfully. Size: {os.path.getsize(filepath)} bytes")
424
 
425
  try:
426
  model_choice = request.form.get('model_choice', 'Gladiator SupaDot')
427
+ logger.info(f"[UPLOAD] Processing with model: {model_choice}")
428
 
429
  if model_choice == 'movenet':
430
  movenet_variant = request.form.get('movenet_variant', 'lightning')
431
+ logger.info(f"[UPLOAD] Using MoveNet variant: {movenet_variant}")
432
  output_path_url = process_video_movenet(filepath)
433
  else:
434
  output_path_url = process_video_mediapipe(filepath)
435
 
436
+ logger.info(f"[UPLOAD] Processing complete. Output URL: {output_path_url}")
437
 
438
  if not os.path.exists(os.path.join(app.config['UPLOAD_FOLDER'], os.path.basename(output_path_url))):
439
+ logger.error(f"[UPLOAD] Output file not found: {output_path_url}")
440
  return jsonify({'error': 'Output video file not found'}), 500
441
 
442
  return jsonify({
 
445
  })
446
 
447
  except Exception as e:
448
+ logger.error(f"[UPLOAD] Error processing video: {str(e)}")
449
  traceback.print_exc()
450
  return jsonify({'error': f'Error processing video: {str(e)}'}), 500
451
 
452
  finally:
453
  try:
454
+ if os.path.exists(filepath):
455
+ os.remove(filepath)
456
+ logger.info(f"[UPLOAD] Cleaned up input file: {filepath}")
457
  except Exception as e:
458
+ logger.error(f"[UPLOAD] Error cleaning up file: {str(e)}")
459
 
460
  except Exception as e:
461
+ logger.error(f"[UPLOAD] Unexpected error: {str(e)}")
462
  traceback.print_exc()
463
  return jsonify({'error': 'Internal server error'}), 500
464
+ finally:
465
+ cleanup_memory() # Clean up after processing
466
+
467
+ # Add error handlers
468
+ @app.errorhandler(413)
469
+ def request_entity_too_large(error):
470
+ return jsonify({'error': 'File too large. Maximum size is 100MB'}), 413
471
+
472
+ @app.errorhandler(500)
473
+ def internal_server_error(error):
474
+ return jsonify({'error': 'Internal server error. Please try again later.'}), 500
475
+
476
+ @app.errorhandler(404)
477
+ def not_found_error(error):
478
+ return jsonify({'error': 'Resource not found'}), 404
479
 
480
  if __name__ == '__main__':
481
  # Ensure the port is 7860 and debug is False for HF Spaces deployment
requirements.txt CHANGED
@@ -78,3 +78,4 @@ tzdata==2025.2
78
  urllib3==2.4.0
79
  Werkzeug==3.1.3
80
  wrapt==1.17.2
 
 
78
  urllib3==2.4.0
79
  Werkzeug==3.1.3
80
  wrapt==1.17.2
81
+ psutil==5.9.8