Spaces:
Sleeping

Igoni Agent commited on
Commit
d688be6
·
1 Parent(s): 9ce7593

Make video inference CPU-safe on Spaces

Browse files
Files changed (2) hide show
  1. Dockerfile +1 -1
  2. app.py +31 -16
Dockerfile CHANGED
@@ -12,7 +12,7 @@ RUN pip install --no-cache-dir -r requirements.txt
12
  ENV HF_HUB_ENABLE_HF_TRANSFER=0
13
  ENV PORT=7860
14
  ENV PYTHONUNBUFFERED=1
15
- LABEL rebuild="image-cpu-fix-v1"
16
 
17
  COPY app.py .
18
  EXPOSE 7860
 
12
  ENV HF_HUB_ENABLE_HF_TRANSFER=0
13
  ENV PORT=7860
14
  ENV PYTHONUNBUFFERED=1
15
+ LABEL rebuild="image-video-cpu-fix-v2"
16
 
17
  COPY app.py .
18
  EXPOSE 7860
app.py CHANGED
@@ -154,7 +154,7 @@ def _score_preds(pred_array) -> dict:
154
  }
155
 
156
 
157
- def _video_to_events(video_path: str, transcript: str = "", include_audio: bool = True) -> "pd.DataFrame":
158
  """Convert video file to TRIBE v2 events DataFrame."""
159
  import pandas as pd
160
 
@@ -184,12 +184,12 @@ def _video_to_events(video_path: str, transcript: str = "", include_audio: bool
184
  t = end
185
 
186
  if include_audio:
187
- # CPU Spaces can fail in the audio extractor if it assumes CUDA, so keep this optional.
188
  events.append({
189
  "start": 0.0,
190
  "duration": round(duration, 3),
191
  "type": "Audio",
192
- "filepath": video_path,
193
  "timeline": "default",
194
  })
195
 
@@ -305,38 +305,53 @@ def predict_text():
305
 
306
  @app.route("/predict_video", methods=["POST"])
307
  def predict_video():
308
- """Video file → brain scores (Visual + Audio events, no Llama needed)."""
309
  if not _model_loaded:
310
  return jsonify({"error": "Model not loaded. Call /warmup first.",
311
  "model_loading": _model_loading,
312
  "load_error": _model_error}), 503
313
 
314
  try:
315
- import pandas as pd
316
  video_file = request.files.get("video")
317
  transcript = request.form.get("transcript", "")
318
  if not video_file:
319
  return jsonify({"error": "No video file provided"}), 400
320
 
321
- # Save video to temp file
322
  suffix = os.path.splitext(video_file.filename)[1] or ".mp4"
323
- with tempfile.NamedTemporaryFile(suffix=suffix, delete=False) as tmp:
324
- video_file.save(tmp.name)
325
- tmp_path = tmp.name
326
-
327
  try:
328
- events_df = _video_to_events(tmp_path, transcript)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
329
  if events_df.empty:
330
  return jsonify({"error": "Could not extract events from video"}), 400
331
 
332
  result = _model.predict(events_df, verbose=False)
333
  pred_array = result[0] if isinstance(result, tuple) else result
334
- return jsonify({"scores": _score_preds(pred_array), "status": "ok"})
335
  finally:
336
- try:
337
- os.unlink(tmp_path)
338
- except Exception:
339
- pass
 
 
340
 
341
  except Exception as e:
342
  return jsonify({"error": str(e), "trace": traceback.format_exc()}), 500
 
154
  }
155
 
156
 
157
+ def _video_to_events(video_path: str, transcript: str = "", include_audio: bool = True, audio_path: str | None = None) -> "pd.DataFrame":
158
  """Convert video file to TRIBE v2 events DataFrame."""
159
  import pandas as pd
160
 
 
184
  t = end
185
 
186
  if include_audio:
187
+ # Use an extracted WAV when available; raw MP4 paths fail validation in soundfile.
188
  events.append({
189
  "start": 0.0,
190
  "duration": round(duration, 3),
191
  "type": "Audio",
192
+ "filepath": audio_path or video_path,
193
  "timeline": "default",
194
  })
195
 
 
305
 
306
  @app.route("/predict_video", methods=["POST"])
307
  def predict_video():
308
+ """Video file → brain scores with CPU-safe visual fallback on Spaces."""
309
  if not _model_loaded:
310
  return jsonify({"error": "Model not loaded. Call /warmup first.",
311
  "model_loading": _model_loading,
312
  "load_error": _model_error}), 503
313
 
314
  try:
 
315
  video_file = request.files.get("video")
316
  transcript = request.form.get("transcript", "")
317
  if not video_file:
318
  return jsonify({"error": "No video file provided"}), 400
319
 
 
320
  suffix = os.path.splitext(video_file.filename)[1] or ".mp4"
321
+ tmp_path = None
322
+ wav_path = None
 
 
323
  try:
324
+ with tempfile.NamedTemporaryFile(suffix=suffix, delete=False) as tmp:
325
+ video_file.save(tmp.name)
326
+ tmp_path = tmp.name
327
+
328
+ include_audio = False
329
+ if os.environ.get("TRIBE_ENABLE_AUDIO", "0") == "1":
330
+ wav_path = tmp_path + ".wav"
331
+ result = subprocess.run([
332
+ "ffmpeg", "-y", "-i", tmp_path,
333
+ "-vn", "-acodec", "pcm_s16le", "-ar", "16000", "-ac", "1",
334
+ wav_path
335
+ ], capture_output=True, timeout=60)
336
+ if result.returncode == 0:
337
+ include_audio = True
338
+ else:
339
+ wav_path = None
340
+
341
+ events_df = _video_to_events(tmp_path, transcript, include_audio=include_audio, audio_path=wav_path)
342
  if events_df.empty:
343
  return jsonify({"error": "Could not extract events from video"}), 400
344
 
345
  result = _model.predict(events_df, verbose=False)
346
  pred_array = result[0] if isinstance(result, tuple) else result
347
+ return jsonify({"scores": _score_preds(pred_array), "status": "ok", "audio_included": include_audio})
348
  finally:
349
+ for p in [tmp_path, wav_path]:
350
+ if p:
351
+ try:
352
+ os.unlink(p)
353
+ except Exception:
354
+ pass
355
 
356
  except Exception as e:
357
  return jsonify({"error": str(e), "trace": traceback.format_exc()}), 500