Emirona07 commited on
Commit
213947c
·
verified ·
1 Parent(s): 3c505b4

Deploy clip subtitle editor

Browse files
Files changed (1) hide show
  1. subtitle_editor.py +107 -4
subtitle_editor.py CHANGED
@@ -42,6 +42,11 @@ from urllib.parse import parse_qs, unquote, urlparse
42
  CLIENT_DISCONNECT_ERRORS = (BrokenPipeError, ConnectionResetError)
43
  APP_ASSETS_DIR = Path(__file__).resolve().parent / "assets"
44
  CACHE_TTL_SECONDS = 30.0
 
 
 
 
 
45
 
46
 
47
  APP_HTML = r"""<!doctype html>
@@ -1910,10 +1915,11 @@ APP_HTML = r"""<!doctype html>
1910
  els.regenBtn.disabled = true;
1911
  els.saveBtn.disabled = true;
1912
  setStatus('Preparando el clip...', 'busy');
1913
- if (state.dirty) await saveSubtitles();
 
1914
  const data = await api(apiWithProgram(`/api/clips/${encodeURIComponent(state.current.id)}/regenerate`), {
1915
  method: 'POST',
1916
- body: JSON.stringify({})
1917
  });
1918
  pollJob(data.job_id);
1919
  }
@@ -2707,6 +2713,70 @@ def make_web_preview(source_path: Path, preview_path: Path, ffmpeg_bin: str) ->
2707
  os.replace(tmp_path, preview_path)
2708
 
2709
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2710
  def install_import_stubs() -> None:
2711
  """Let the editor import clip_workflow.py without API-only dependencies."""
2712
  existing = sys.modules.get("anthropic")
@@ -2750,7 +2820,12 @@ def load_clip_workflow(root_dir: Path):
2750
  raise RuntimeError("No encontre clip_workflow.py junto a la app o en el proyecto.")
2751
 
2752
 
2753
- def regenerate_clip(server: ThreadingHTTPServer, clip: ClipInfo, job_id: str) -> None:
 
 
 
 
 
2754
  job = server.jobs[job_id] # type: ignore[attr-defined]
2755
  job["status"] = "running"
2756
  job["technical_log"] = ""
@@ -2773,6 +2848,25 @@ def regenerate_clip(server: ThreadingHTTPServer, clip: ClipInfo, job_id: str) ->
2773
  clip.output_path.parent.mkdir(parents=True, exist_ok=True)
2774
  tmp_output = clip.output_path.with_name(f".{clip.output_path.stem}.tmp{clip.output_path.suffix}")
2775
  zoom_plan_path = clip.output_path.with_suffix(".zoom.json")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2776
  if zoom_plan_path.exists():
2777
  set_job_message(job, "Actualizando subtítulos sin recalcular el encuadre...")
2778
  else:
@@ -2788,6 +2882,9 @@ def regenerate_clip(server: ThreadingHTTPServer, clip: ClipInfo, job_id: str) ->
2788
  set_job_message(job, "Guardando el clip actualizado...")
2789
  os.replace(tmp_output, clip.output_path)
2790
  upload_sync_file(server, clip.output_path)
 
 
 
2791
  if zoom_plan_path.exists():
2792
  upload_sync_file(server, zoom_plan_path)
2793
  set_job_message(job, "Preparando una vista rápida para la web...")
@@ -3068,6 +3165,8 @@ class Handler(BaseHTTPRequestHandler):
3068
  if path.startswith("/api/clips/") and path.endswith("/regenerate"):
3069
  clip_id = unquote(path.removeprefix("/api/clips/").removesuffix("/regenerate")).strip("/")
3070
  clip = find_clip(self.server, clip_id, self.program_id_from_query(parsed))
 
 
3071
  clip_key = str(clip.output_path.resolve())
3072
  with self.server.job_lock: # type: ignore[attr-defined]
3073
  existing_job_id = self.server.active_clip_jobs.get(clip_key) # type: ignore[attr-defined]
@@ -3083,7 +3182,11 @@ class Handler(BaseHTTPRequestHandler):
3083
  "technical_log": "",
3084
  }
3085
  self.server.active_clip_jobs[clip_key] = job_id # type: ignore[attr-defined]
3086
- thread = threading.Thread(target=regenerate_clip, args=(self.server, clip, job_id), daemon=True)
 
 
 
 
3087
  thread.start()
3088
  self.send_json({"job_id": job_id})
3089
  return
 
42
  CLIENT_DISCONNECT_ERRORS = (BrokenPipeError, ConnectionResetError)
43
  APP_ASSETS_DIR = Path(__file__).resolve().parent / "assets"
44
  CACHE_TTL_SECONDS = 30.0
45
+ BRAND_VERSION = 1
46
+ PYD_LOGO_PATH = APP_ASSETS_DIR / "pyd-logo.png"
47
+ PYD_LOGO_VERTICAL_WIDTH = 210
48
+ PYD_LOGO_VERTICAL_MARGIN_X = 38
49
+ PYD_LOGO_VERTICAL_MARGIN_Y = 42
50
 
51
 
52
  APP_HTML = r"""<!doctype html>
 
1915
  els.regenBtn.disabled = true;
1916
  els.saveBtn.disabled = true;
1917
  setStatus('Preparando el clip...', 'busy');
1918
+ const hadSubtitleChanges = state.dirty;
1919
+ if (hadSubtitleChanges) await saveSubtitles();
1920
  const data = await api(apiWithProgram(`/api/clips/${encodeURIComponent(state.current.id)}/regenerate`), {
1921
  method: 'POST',
1922
+ body: JSON.stringify({ preserve_video: !hadSubtitleChanges })
1923
  });
1924
  pollJob(data.job_id);
1925
  }
 
2713
  os.replace(tmp_path, preview_path)
2714
 
2715
 
2716
+ def brand_marker_path(output_path: Path) -> Path:
2717
+ return output_path.with_suffix(".brand.json")
2718
+
2719
+
2720
+ def write_brand_marker(output_path: Path) -> Path:
2721
+ marker_path = brand_marker_path(output_path)
2722
+ logo_stat = PYD_LOGO_PATH.stat() if PYD_LOGO_PATH.exists() else None
2723
+ output_stat = output_path.stat()
2724
+ marker = {
2725
+ "version": BRAND_VERSION,
2726
+ "logo": PYD_LOGO_PATH.name,
2727
+ "logo_size": logo_stat.st_size if logo_stat else None,
2728
+ "logo_mtime": int(logo_stat.st_mtime) if logo_stat else None,
2729
+ "output_size": output_stat.st_size,
2730
+ "output_mtime": int(output_stat.st_mtime),
2731
+ "created_at": datetime.now().isoformat(timespec="seconds"),
2732
+ }
2733
+ marker_path.write_text(json.dumps(marker, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
2734
+ return marker_path
2735
+
2736
+
2737
+ def add_logo_to_existing_final(source_path: Path, output_path: Path, ffmpeg_bin: str) -> None:
2738
+ if not PYD_LOGO_PATH.exists():
2739
+ raise RuntimeError("No encontre el logo PyDTV para aplicar al clip.")
2740
+ output_path.parent.mkdir(parents=True, exist_ok=True)
2741
+ tmp_path = output_path.with_name(f".{output_path.stem}.brandtmp{output_path.suffix}")
2742
+ cmd = [
2743
+ ffmpeg_bin,
2744
+ "-y",
2745
+ "-i",
2746
+ str(source_path),
2747
+ "-i",
2748
+ str(PYD_LOGO_PATH),
2749
+ "-filter_complex",
2750
+ (
2751
+ f"[1:v]scale={PYD_LOGO_VERTICAL_WIDTH}:-1:flags=lanczos[pyd_logo];"
2752
+ f"[0:v][pyd_logo]overlay={PYD_LOGO_VERTICAL_MARGIN_X}:{PYD_LOGO_VERTICAL_MARGIN_Y}:format=auto[vout]"
2753
+ ),
2754
+ "-map",
2755
+ "[vout]",
2756
+ "-map",
2757
+ "0:a?",
2758
+ "-c:v",
2759
+ "libx264",
2760
+ "-preset",
2761
+ os.environ.get("CLIP_EDITOR_PRESET", "medium"),
2762
+ "-crf",
2763
+ os.environ.get("CLIP_EDITOR_CRF", "18"),
2764
+ "-c:a",
2765
+ "aac",
2766
+ "-b:a",
2767
+ "320k",
2768
+ "-movflags",
2769
+ "+faststart",
2770
+ str(tmp_path),
2771
+ ]
2772
+ result = subprocess.run(cmd, capture_output=True, text=True)
2773
+ if result.returncode != 0:
2774
+ if tmp_path.exists():
2775
+ tmp_path.unlink()
2776
+ raise RuntimeError(f"No pude aplicar el logo PyDTV: {result.stderr[-1200:]}")
2777
+ os.replace(tmp_path, output_path)
2778
+
2779
+
2780
  def install_import_stubs() -> None:
2781
  """Let the editor import clip_workflow.py without API-only dependencies."""
2782
  existing = sys.modules.get("anthropic")
 
2820
  raise RuntimeError("No encontre clip_workflow.py junto a la app o en el proyecto.")
2821
 
2822
 
2823
+ def regenerate_clip(
2824
+ server: ThreadingHTTPServer,
2825
+ clip: ClipInfo,
2826
+ job_id: str,
2827
+ preserve_video: bool = False,
2828
+ ) -> None:
2829
  job = server.jobs[job_id] # type: ignore[attr-defined]
2830
  job["status"] = "running"
2831
  job["technical_log"] = ""
 
2848
  clip.output_path.parent.mkdir(parents=True, exist_ok=True)
2849
  tmp_output = clip.output_path.with_name(f".{clip.output_path.stem}.tmp{clip.output_path.suffix}")
2850
  zoom_plan_path = clip.output_path.with_suffix(".zoom.json")
2851
+ marker_path = brand_marker_path(clip.output_path)
2852
+ if preserve_video and clip.output_path.exists() and not zoom_plan_path.exists():
2853
+ if marker_path.exists():
2854
+ set_job_message(job, "El logo ya estaba aplicado. Actualizando la vista rápida...")
2855
+ else:
2856
+ set_job_message(job, "Agregando el logo sin tocar el encuadre...")
2857
+ add_logo_to_existing_final(clip.output_path, tmp_output, ffmpeg_bin)
2858
+ os.replace(tmp_output, clip.output_path)
2859
+ marker_path = write_brand_marker(clip.output_path)
2860
+ upload_sync_file(server, clip.output_path)
2861
+ upload_sync_file(server, marker_path)
2862
+ set_job_message(job, "Preparando una vista rápida para la web...")
2863
+ make_web_preview(clip.output_path, clip.preview_path, ffmpeg_bin)
2864
+ upload_sync_file(server, clip.preview_path)
2865
+ invalidate_server_cache(server)
2866
+ job["status"] = "done"
2867
+ set_job_message(job, "Clip actualizado. El encuadre original quedó intacto.")
2868
+ return
2869
+
2870
  if zoom_plan_path.exists():
2871
  set_job_message(job, "Actualizando subtítulos sin recalcular el encuadre...")
2872
  else:
 
2882
  set_job_message(job, "Guardando el clip actualizado...")
2883
  os.replace(tmp_output, clip.output_path)
2884
  upload_sync_file(server, clip.output_path)
2885
+ if PYD_LOGO_PATH.exists():
2886
+ marker_path = write_brand_marker(clip.output_path)
2887
+ upload_sync_file(server, marker_path)
2888
  if zoom_plan_path.exists():
2889
  upload_sync_file(server, zoom_plan_path)
2890
  set_job_message(job, "Preparando una vista rápida para la web...")
 
3165
  if path.startswith("/api/clips/") and path.endswith("/regenerate"):
3166
  clip_id = unquote(path.removeprefix("/api/clips/").removesuffix("/regenerate")).strip("/")
3167
  clip = find_clip(self.server, clip_id, self.program_id_from_query(parsed))
3168
+ body = self.read_json()
3169
+ preserve_video = bool(body.get("preserve_video"))
3170
  clip_key = str(clip.output_path.resolve())
3171
  with self.server.job_lock: # type: ignore[attr-defined]
3172
  existing_job_id = self.server.active_clip_jobs.get(clip_key) # type: ignore[attr-defined]
 
3182
  "technical_log": "",
3183
  }
3184
  self.server.active_clip_jobs[clip_key] = job_id # type: ignore[attr-defined]
3185
+ thread = threading.Thread(
3186
+ target=regenerate_clip,
3187
+ args=(self.server, clip, job_id, preserve_video),
3188
+ daemon=True,
3189
+ )
3190
  thread.start()
3191
  self.send_json({"job_id": job_id})
3192
  return