Emirona07 commited on
Commit
ffbb4de
·
verified ·
1 Parent(s): fb5a4c8

Deploy clip subtitle editor

Browse files
Files changed (2) hide show
  1. clip_workflow.py +89 -22
  2. subtitle_editor.py +14 -2
clip_workflow.py CHANGED
@@ -2242,33 +2242,55 @@ def detect_active_speaker_timeline(raw_clip: Path) -> list[dict] | None:
2242
  return merged
2243
 
2244
 
2245
- def encode_vertical_dynamic_zoom(raw_clip: Path, ass_path: Path, output_path: Path) -> None:
2246
- """
2247
- Produce 1080×1920 (9:16) clip with dynamic per-speaker zoom.
2248
 
2249
- Detects camera cuts + active speaker (mouth motion) to apply a different
2250
- 9:16 crop for each segment. The audio stream is passed through unchanged.
2251
- Falls back to static zoom → blurred background if detection yields nothing.
2252
 
2253
- ffmpeg strategy:
2254
- split → N copies of the input video
2255
- each copy: trim to segment timestamps, reset PTS, crop to speaker, scale to 1080×1920
2256
- concat → single continuous video stream
2257
- subtitles → burned on top
2258
- """
2259
- print(" → Detectando planos y speakers dinámicos…")
2260
- segments = detect_active_speaker_timeline(raw_clip)
 
 
 
2261
 
2262
- if not segments:
2263
- print(" → Sin cambios de plano detectados → zoom estático")
2264
- encode_vertical_zoom(raw_clip, ass_path, output_path)
2265
- return
2266
 
2267
- print(f" → {len(segments)} plano(s) con zoom dinámico:")
2268
- for seg in segments:
2269
- print(f" {seg['t_start']:.1f}s–{seg['t_end']:.1f}s "
2270
- f"crop {seg['w']}×{seg['h']} @ ({seg['x']},{seg['y']})")
 
 
 
 
 
 
 
2271
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2272
  with tempfile.TemporaryDirectory() as tmp:
2273
  tmp_ass = Path(tmp) / "sub.ass"
2274
  shutil.copy(ass_path, tmp_ass)
@@ -2320,6 +2342,51 @@ def encode_vertical_dynamic_zoom(raw_clip: Path, ass_path: Path, output_path: Pa
2320
  ])
2321
 
2322
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2323
  def encode_horizontal(raw_clip: Path, ass_path: Path, output_path: Path,
2324
  zoom: bool = False) -> None:
2325
  """
 
2242
  return merged
2243
 
2244
 
2245
+ def zoom_plan_path_for_output(output_path: Path) -> Path:
2246
+ return output_path.with_suffix(".zoom.json")
 
2247
 
 
 
 
2248
 
2249
+ def _zoom_plan_matches(plan: dict, raw_clip: Path) -> bool:
2250
+ try:
2251
+ return (
2252
+ int(plan.get("version", 0)) == 1
2253
+ and int(plan.get("raw_mtime", -1)) == int(raw_clip.stat().st_mtime)
2254
+ and int(plan.get("raw_size", -1)) == int(raw_clip.stat().st_size)
2255
+ and isinstance(plan.get("segments"), list)
2256
+ and bool(plan["segments"])
2257
+ )
2258
+ except OSError:
2259
+ return False
2260
 
 
 
 
 
2261
 
2262
+ def load_zoom_plan(plan_path: Path, raw_clip: Path) -> list[dict] | None:
2263
+ if not plan_path.exists():
2264
+ return None
2265
+ try:
2266
+ plan = json.loads(plan_path.read_text(encoding="utf-8"))
2267
+ except Exception:
2268
+ return None
2269
+ if not _zoom_plan_matches(plan, raw_clip):
2270
+ return None
2271
+ return plan["segments"]
2272
+
2273
 
2274
+ def save_zoom_plan(plan_path: Path, raw_clip: Path, segments: list[dict]) -> None:
2275
+ plan_path.parent.mkdir(parents=True, exist_ok=True)
2276
+ payload = {
2277
+ "version": 1,
2278
+ "raw": raw_clip.name,
2279
+ "raw_mtime": int(raw_clip.stat().st_mtime),
2280
+ "raw_size": int(raw_clip.stat().st_size),
2281
+ "segments": segments,
2282
+ }
2283
+ plan_path.write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
2284
+
2285
+
2286
+ def encode_vertical_dynamic_zoom_from_segments(
2287
+ raw_clip: Path,
2288
+ ass_path: Path,
2289
+ output_path: Path,
2290
+ segments: list[dict],
2291
+ ) -> None:
2292
+ """Encode a vertical clip using a previously detected crop timeline."""
2293
+ print(f" → Reutilizando {len(segments)} plano(s) de encuadre guardados")
2294
  with tempfile.TemporaryDirectory() as tmp:
2295
  tmp_ass = Path(tmp) / "sub.ass"
2296
  shutil.copy(ass_path, tmp_ass)
 
2342
  ])
2343
 
2344
 
2345
+ def encode_vertical_dynamic_zoom(
2346
+ raw_clip: Path,
2347
+ ass_path: Path,
2348
+ output_path: Path,
2349
+ *,
2350
+ reuse_zoom_plan: bool = False,
2351
+ zoom_plan_path: Path | None = None,
2352
+ ) -> None:
2353
+ """
2354
+ Produce 1080×1920 (9:16) clip with dynamic per-speaker zoom.
2355
+
2356
+ Detects camera cuts + active speaker (mouth motion) to apply a different
2357
+ 9:16 crop for each segment. The audio stream is passed through unchanged.
2358
+ Falls back to static zoom → blurred background if detection yields nothing.
2359
+
2360
+ ffmpeg strategy:
2361
+ split → N copies of the input video
2362
+ each copy: trim to segment timestamps, reset PTS, crop to speaker, scale to 1080×1920
2363
+ concat → single continuous video stream
2364
+ subtitles → burned on top
2365
+ """
2366
+ zoom_plan_path = zoom_plan_path or zoom_plan_path_for_output(output_path)
2367
+ if reuse_zoom_plan:
2368
+ cached_segments = load_zoom_plan(zoom_plan_path, raw_clip)
2369
+ if cached_segments:
2370
+ encode_vertical_dynamic_zoom_from_segments(raw_clip, ass_path, output_path, cached_segments)
2371
+ return
2372
+
2373
+ print(" → Detectando planos y speakers dinámicos…")
2374
+ segments = detect_active_speaker_timeline(raw_clip)
2375
+
2376
+ if not segments:
2377
+ print(" → Sin cambios de plano detectados → zoom estático")
2378
+ encode_vertical_zoom(raw_clip, ass_path, output_path)
2379
+ return
2380
+
2381
+ print(f" → {len(segments)} plano(s) con zoom dinámico:")
2382
+ for seg in segments:
2383
+ print(f" {seg['t_start']:.1f}s–{seg['t_end']:.1f}s "
2384
+ f"crop {seg['w']}×{seg['h']} @ ({seg['x']},{seg['y']})")
2385
+
2386
+ save_zoom_plan(zoom_plan_path, raw_clip, segments)
2387
+ encode_vertical_dynamic_zoom_from_segments(raw_clip, ass_path, output_path, segments)
2388
+
2389
+
2390
  def encode_horizontal(raw_clip: Path, ass_path: Path, output_path: Path,
2391
  zoom: bool = False) -> None:
2392
  """
subtitle_editor.py CHANGED
@@ -2739,12 +2739,24 @@ def regenerate_clip(server: ThreadingHTTPServer, clip: ClipInfo, job_id: str) ->
2739
 
2740
  clip.output_path.parent.mkdir(parents=True, exist_ok=True)
2741
  tmp_output = clip.output_path.with_name(f".{clip.output_path.stem}.tmp{clip.output_path.suffix}")
2742
- set_job_message(job, "Analizando el video para seguir a quien habla...")
 
 
 
 
2743
  with contextlib.redirect_stdout(Capture(job)), contextlib.redirect_stderr(Capture(job)):
2744
- module.encode_vertical_dynamic_zoom(clip.raw_path, clip.ass_path, tmp_output)
 
 
 
 
 
 
2745
  set_job_message(job, "Guardando el clip actualizado...")
2746
  os.replace(tmp_output, clip.output_path)
2747
  upload_sync_file(server, clip.output_path)
 
 
2748
  set_job_message(job, "Preparando una vista rápida para la web...")
2749
  make_web_preview(clip.output_path, clip.preview_path, ffmpeg_bin)
2750
  upload_sync_file(server, clip.preview_path)
 
2739
 
2740
  clip.output_path.parent.mkdir(parents=True, exist_ok=True)
2741
  tmp_output = clip.output_path.with_name(f".{clip.output_path.stem}.tmp{clip.output_path.suffix}")
2742
+ zoom_plan_path = clip.output_path.with_suffix(".zoom.json")
2743
+ if zoom_plan_path.exists():
2744
+ set_job_message(job, "Actualizando subtítulos sin recalcular el encuadre...")
2745
+ else:
2746
+ set_job_message(job, "Analizando el video para seguir a quien habla...")
2747
  with contextlib.redirect_stdout(Capture(job)), contextlib.redirect_stderr(Capture(job)):
2748
+ module.encode_vertical_dynamic_zoom(
2749
+ clip.raw_path,
2750
+ clip.ass_path,
2751
+ tmp_output,
2752
+ reuse_zoom_plan=True,
2753
+ zoom_plan_path=zoom_plan_path,
2754
+ )
2755
  set_job_message(job, "Guardando el clip actualizado...")
2756
  os.replace(tmp_output, clip.output_path)
2757
  upload_sync_file(server, clip.output_path)
2758
+ if zoom_plan_path.exists():
2759
+ upload_sync_file(server, zoom_plan_path)
2760
  set_job_message(job, "Preparando una vista rápida para la web...")
2761
  make_web_preview(clip.output_path, clip.preview_path, ffmpeg_bin)
2762
  upload_sync_file(server, clip.preview_path)