#!/usr/bin/env python3 """ Local subtitle editor for clip-workflow program folders. Run: python subtitle_editor.py --program-dir programas/estacion_YYYYMMDD_slug The program folder must include: raw/*.mp4 raw/*_v.ass vertical_9x16/*_9x16.mp4 """ from __future__ import annotations import argparse import base64 import contextlib import html import importlib.util import json import os import re import shutil import subprocess import sys import threading import time import traceback import types import uuid import webbrowser from dataclasses import dataclass from datetime import date, datetime from http import HTTPStatus from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from pathlib import Path from typing import Any from urllib.parse import parse_qs, unquote, urlparse CLIENT_DISCONNECT_ERRORS = (BrokenPipeError, ConnectionResetError) APP_ASSETS_DIR = Path(__file__).resolve().parent / "assets" CACHE_TTL_SECONDS = 30.0 BRAND_VERSION = 1 PYD_LOGO_PATH = APP_ASSETS_DIR / "pyd-logo.png" PYD_LOGO_VERTICAL_WIDTH = 210 PYD_LOGO_VERTICAL_MARGIN_X = 38 PYD_LOGO_VERTICAL_MARGIN_Y = 42 APP_HTML = r""" PYD Clips
Cargando...
Clip activo

Subtítulos

0
Copies por red
""" @dataclass class ClipInfo: id: str title: str raw_path: Path ass_path: Path output_path: Path preview_path: Path subtitle_count: int @dataclass class ProgramInfo: id: str name: str path: Path clip_count: int program_date: date | None = None program_datetime: datetime | None = None source_id: str = "" source_url: str = "" class Capture: def __init__(self, job: dict[str, Any]): self.job = job def write(self, value: str) -> int: if value.strip(): self.job["technical_log"] += value self.job["technical_log"] = self.job["technical_log"][-12000:] update_job_message_from_log(self.job, value) return len(value) def flush(self) -> None: return None def set_job_message(job: dict[str, Any], message: str) -> None: job["message"] = message job["log"] = message def concise_error_message(exc: BaseException, technical_log: str = "") -> str: log = technical_log.lower() if isinstance(exc, SystemExit): if "no such file or directory" in log or "no existe" in log: return "No se pudo regenerar el clip porque falta un archivo base. Recargá la página y probá de nuevo." if "permission denied" in log: return "No se pudo regenerar el clip porque la app no tiene permiso para escribir el MP4." if "command failed" in log or "conversion failed" in log or "ffmpeg" in log: return "No se pudo regenerar el clip porque falló la generación del MP4. El clip anterior quedó intacto." return "No se pudo regenerar el clip. El clip anterior quedó intacto." text = str(exc).strip() if not text: return "No se pudo regenerar el clip. Revisá que el archivo siga en la carpeta y probá de nuevo." text = re.sub(r"\s+", " ", text) if len(text) > 180: text = text[:177].rstrip() + "..." return f"No se pudo regenerar el clip: {text}" def update_job_message_from_log(job: dict[str, Any], value: str) -> None: text = value.lower() if "detectando planos" in text or "layout panel" in text: set_job_message(job, "Analizando el video para seguir a quien habla...") elif "segmentos" in text or "plano(s) con zoom" in text: set_job_message(job, "Ajustando el encuadre y los cambios de cámara...") elif "ffmpeg" in text or "filter_complex" in text: set_job_message(job, "Generando el MP4 final. Puede tardar unos minutos...") def ass_time_to_seconds(value: str) -> float: h, m, s = value.split(":") return int(h) * 3600 + int(m) * 60 + float(s) def pretty_time(value: str) -> str: seconds = ass_time_to_seconds(value) minutes = int(seconds // 60) rest = seconds - minutes * 60 return f"{minutes:02d}:{rest:05.2f}" def edit_time_to_seconds(value: Any) -> float: text = str(value or "").strip().replace(",", ".") if not text: raise ValueError("tiempo vacío") if ":" not in text: return float(text) parts = [part.strip() for part in text.split(":")] if len(parts) > 3 or any(not part for part in parts): raise ValueError(f"tiempo inválido: {text}") seconds = float(parts.pop()) minutes = float(parts.pop()) if parts else 0 hours = float(parts.pop()) if parts else 0 return hours * 3600 + minutes * 60 + seconds def seconds_to_ass_time(seconds: float) -> str: seconds = max(0, seconds) hours = int(seconds // 3600) seconds -= hours * 3600 minutes = int(seconds // 60) seconds -= minutes * 60 return f"{hours}:{minutes:02d}:{seconds:05.2f}" def split_ass_text(text: str) -> tuple[str, str]: prefixes: list[str] = [] rest = text while rest.startswith("{"): end = rest.find("}") if end == -1: break prefixes.append(rest[: end + 1]) rest = rest[end + 1 :] return "".join(prefixes), rest def plain_from_ass(text: str) -> str: _, rest = split_ass_text(text) return rest.replace(r"\N", "\n").replace(r"\n", "\n").strip() def ass_from_plain(text: str) -> str: clean_lines = [] for line in text.replace("\r", "").split("\n"): line = line.strip() if not line: continue line = line.replace("\\", "/").replace("{", "(").replace("}", ")") clean_lines.append(line) return r"\N".join(clean_lines) def parse_ass(path: Path) -> list[dict[str, Any]]: subtitles: list[dict[str, Any]] = [] lines = path.read_text(encoding="utf-8").splitlines() event_index = 0 for line_index, line in enumerate(lines): if not line.startswith("Dialogue:"): continue parts = line.split(",", 9) if len(parts) < 10: continue subtitles.append( { "index": event_index, "line_index": line_index, "start": pretty_time(parts[1]), "end": pretty_time(parts[2]), "text": plain_from_ass(parts[9]), } ) event_index += 1 return subtitles def save_ass(path: Path, incoming: list[dict[str, Any]]) -> None: lines = path.read_text(encoding="utf-8").splitlines() original_events: list[tuple[int, list[str]]] = [] event_index = 0 for line_index, line in enumerate(lines): if not line.startswith("Dialogue:"): continue parts = line.split(",", 9) if len(parts) < 10: continue original_events.append((line_index, parts)) event_index += 1 fallback = ( original_events[0][1][:] if original_events else ["Dialogue: 0", "0:00:00.00", "0:00:02.00", "Default", "", "0", "0", "0", "", ""] ) by_index = {index: parts for index, (_line_index, parts) in enumerate(original_events)} rendered: list[tuple[float, str]] = [] for position, item in enumerate(incoming): plain_text = str(item.get("text", "")).strip() if not plain_text: continue try: start_seconds = edit_time_to_seconds(item.get("start")) end_seconds = edit_time_to_seconds(item.get("end")) except Exception as exc: raise ValueError(f"Tiempo inválido en línea {position + 1}.") from exc if end_seconds <= start_seconds: raise ValueError(f"El fin debe ser mayor al inicio en línea {position + 1}.") try: original_index = int(item.get("index")) except Exception: original_index = -1 parts = (by_index.get(original_index) or fallback)[:] prefix, _ = split_ass_text(parts[9]) parts[1] = seconds_to_ass_time(start_seconds) parts[2] = seconds_to_ass_time(end_seconds) parts[9] = prefix + ass_from_plain(plain_text) rendered.append((start_seconds, ",".join(parts))) rendered_lines = [line for _start, line in sorted(rendered, key=lambda item: item[0])] if original_events: first_line = original_events[0][0] old_event_lines = {line_index for line_index, _parts in original_events} rebuilt: list[str] = [] inserted = False for line_index, line in enumerate(lines): if line_index == first_line: rebuilt.extend(rendered_lines) inserted = True if line_index in old_event_lines: continue rebuilt.append(line) if not inserted: rebuilt.extend(rendered_lines) lines = rebuilt else: lines.extend(rendered_lines) path.write_text("\n".join(lines) + "\n", encoding="utf-8") def build_clip_id(base: str) -> str: return re.sub(r"[^A-Za-z0-9_.-]+", "_", base) def build_program_id(name: str) -> str: return build_clip_id(name) def is_program_dir(path: Path) -> bool: return (path / "raw").is_dir() and (path / "vertical_9x16").is_dir() def parse_yyyymmdd(value: str) -> date | None: match = re.search(r"(20\d{2})[-_]?(\d{2})[-_]?(\d{2})", value) if not match: return None try: return date(int(match.group(1)), int(match.group(2)), int(match.group(3))) except ValueError: return None def parse_iso_datetime(value: str) -> datetime | None: value = value.strip() if not value: return None if value.endswith("Z"): value = value[:-1] + "+00:00" try: parsed = datetime.fromisoformat(value) except ValueError: return None if parsed.tzinfo: parsed = parsed.astimezone().replace(tzinfo=None) return parsed def parse_title_date(value: str, today: date | None = None) -> date | None: today = today or date.today() match = re.search(r"(? today: try: parsed = date(year - 1, month, day) except ValueError: return None return parsed def program_metadata_candidates(program_dir: Path) -> list[Path]: return [ program_dir / "program.json", *sorted(program_dir.glob("*.info.json")), *sorted((program_dir / "raw").glob("*.info.json")), ] def infer_program_date(program_dir: Path, metadata: dict[str, Any] | None = None) -> date | None: parsed = parse_yyyymmdd(program_dir.name) if parsed: return parsed if metadata: parsed = parse_yyyymmdd(str(metadata.get("program_date") or "")) if parsed: return parsed title = str(metadata.get("title") or "") parsed = parse_title_date(title) if parsed: return parsed for path in program_metadata_candidates(program_dir): if not path.exists(): continue try: data = json.loads(path.read_text(encoding="utf-8")) except Exception: continue for key in ("program_date", "upload_date", "release_date", "modified_date"): parsed = parse_yyyymmdd(str(data.get(key) or "")) if parsed: return parsed for key in ("timestamp", "release_timestamp", "modified_timestamp"): value = data.get(key) if isinstance(value, (int, float)): return datetime.fromtimestamp(value).date() parsed = parse_title_date(str(data.get("title") or data.get("fulltitle") or "")) if parsed: return parsed return None def infer_program_datetime(program_dir: Path, metadata: dict[str, Any] | None = None) -> datetime | None: if metadata: parsed = parse_iso_datetime(str(metadata.get("program_datetime") or "")) if parsed: return parsed for path in program_metadata_candidates(program_dir): if not path.exists(): continue try: data = json.loads(path.read_text(encoding="utf-8")) except Exception: continue for key in ("program_datetime", "release_datetime", "upload_datetime"): parsed = parse_iso_datetime(str(data.get(key) or "")) if parsed: return parsed for path in program_metadata_candidates(program_dir): if not path.exists(): continue try: data = json.loads(path.read_text(encoding="utf-8")) except Exception: continue for key in ("release_timestamp", "timestamp", "modified_timestamp"): value = data.get(key) if isinstance(value, (int, float)): return datetime.fromtimestamp(value) program_date = infer_program_date(program_dir, metadata) if program_date: return datetime.combine(program_date, datetime.min.time()) return None def load_program_metadata(program_dir: Path) -> dict[str, Any]: for path in program_metadata_candidates(program_dir): if not path.exists(): continue try: data = json.loads(path.read_text(encoding="utf-8")) except Exception: continue title = str(data.get("title") or data.get("fulltitle") or "").strip() video_id = str(data.get("video_id") or data.get("id") or "").strip() url = str(data.get("webpage_url") or data.get("url") or "").strip() return { "title": title, "video_id": video_id, "url": url, "hidden": bool(data.get("hidden")), "program_date": str(data.get("program_date") or ""), "program_datetime": str(data.get("program_datetime") or ""), } return {"title": "", "video_id": "", "url": "", "hidden": False, "program_date": "", "program_datetime": ""} def program_sort_key(program: ProgramInfo) -> tuple[int, str]: name = program.path.name.lower() is_hq = int(name.endswith("_hq") or "_hq" in name) return (is_hq, name) def discover_clips(program_dir: Path) -> list[ClipInfo]: raw_dir = program_dir / "raw" output_dir = program_dir / "vertical_9x16" preview_dir = program_dir / "web_preview" clips: list[ClipInfo] = [] for ass_path in sorted(raw_dir.glob("*_v.ass")): base = ass_path.name[: -len("_v.ass")] raw_path = raw_dir / f"{base}.mp4" output_path = output_dir / f"{base}_9x16.mp4" preview_path = preview_dir / f"{base}_preview.mp4" if not raw_path.exists(): continue clips.append( ClipInfo( id=build_clip_id(base), title=base, raw_path=raw_path, ass_path=ass_path, output_path=output_path, preview_path=preview_path, subtitle_count=len(parse_ass(ass_path)), ) ) return clips def discover_programs(root_dir: Path | None, single_program_dir: Path) -> list[ProgramInfo]: program_dirs: list[Path] = [] if root_dir: nested_root = root_dir / "programs" search_roots = [nested_root, root_dir] if nested_root.exists() else [root_dir] for search_root in search_roots: if not search_root.exists(): continue for candidate in sorted(search_root.iterdir()): if candidate.is_dir() and is_program_dir(candidate): program_dirs.append(candidate) if is_program_dir(root_dir): program_dirs.append(root_dir) else: program_dirs.append(single_program_dir) unique: dict[Path, ProgramInfo] = {} by_source: dict[str, ProgramInfo] = {} for program_dir in program_dirs: resolved = program_dir.resolve() if resolved in unique: continue metadata = load_program_metadata(resolved) if metadata.get("hidden"): continue clips = discover_clips(resolved) if not clips: continue program = ProgramInfo( id=build_program_id(resolved.name), name=metadata["title"] or resolved.name.replace("_", " "), path=resolved, clip_count=len(clips), program_date=infer_program_date(resolved, metadata), program_datetime=infer_program_datetime(resolved, metadata), source_id=metadata["video_id"], source_url=metadata["url"], ) source_key = program.source_id or program.source_url if source_key: previous = by_source.get(source_key) if previous and program_sort_key(previous) >= program_sort_key(program): continue if previous: unique.pop(previous.path.resolve(), None) by_source[source_key] = program unique[resolved] = program return sorted( unique.values(), key=lambda program: ( program.program_datetime or datetime.combine(program.program_date or date.min, datetime.min.time()), program.path.name.lower(), ), reverse=True, ) def cached_programs(server: ThreadingHTTPServer) -> list[ProgramInfo]: now = time.monotonic() cache = getattr(server, "program_cache", None) if cache and now - cache.get("time", 0) < CACHE_TTL_SECONDS: return cache["items"] programs = discover_programs( getattr(server, "programs_root", None), server.program_dir, # type: ignore[attr-defined] ) server.program_cache = {"time": now, "items": programs} # type: ignore[attr-defined] return programs def cached_clips(server: ThreadingHTTPServer, program: ProgramInfo) -> list[ClipInfo]: now = time.monotonic() cache = getattr(server, "clip_cache", {}) key = str(program.path) entry = cache.get(key) if entry and now - entry.get("time", 0) < CACHE_TTL_SECONDS: return entry["items"] clips = discover_clips(program.path) cache[key] = {"time": now, "items": clips} server.clip_cache = cache # type: ignore[attr-defined] return clips def invalidate_server_cache(server: ThreadingHTTPServer, program: ProgramInfo | None = None) -> None: if program is None: server.program_cache = None # type: ignore[attr-defined] server.clip_cache = {} # type: ignore[attr-defined] return cache = getattr(server, "clip_cache", {}) cache.pop(str(program.path), None) server.clip_cache = cache # type: ignore[attr-defined] def find_program(server: ThreadingHTTPServer, program_id: str | None = None) -> ProgramInfo: programs = cached_programs(server) if not programs: raise KeyError("No hay programas con clips en la biblioteca.") if not program_id: return programs[0] for program in programs: if program.id == program_id or program.name == program_id: return program raise KeyError(f"Programa no encontrado: {program_id}") def find_clip(server: ThreadingHTTPServer, clip_id: str, program_id: str | None = None) -> ClipInfo: program = find_program(server, program_id) for clip in cached_clips(server, program): if clip.id == clip_id: return clip raise KeyError(f"Clip no encontrado: {clip_id}") def json_bytes(value: Any) -> bytes: return json.dumps(value, ensure_ascii=False).encode("utf-8") SOCIAL_COPY_KEYS = ("instagram", "twitter", "tiktok") def social_copy_path(program_dir: Path) -> Path: return program_dir / "social_copy.json" def empty_social_copy() -> dict[str, str]: return {key: "" for key in SOCIAL_COPY_KEYS} def normalize_social_copy(value: Any) -> dict[str, str]: if not isinstance(value, dict): return empty_social_copy() return {key: str(value.get(key) or "").strip() for key in SOCIAL_COPY_KEYS} def load_social_copy(program_dir: Path) -> dict[str, dict[str, str]]: path = social_copy_path(program_dir) if not path.exists(): return {} try: data = json.loads(path.read_text(encoding="utf-8")) except Exception: return {} clips = data.get("clips") if isinstance(data, dict) else data if not isinstance(clips, dict): return {} return {str(clip_id): normalize_social_copy(copy) for clip_id, copy in clips.items()} def save_social_copy(program_dir: Path, copies: dict[str, dict[str, str]]) -> Path: path = social_copy_path(program_dir) payload = { "version": 1, "clips": { clip_id: normalize_social_copy(copy) for clip_id, copy in sorted(copies.items()) }, } path.write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") return path def update_clip_social_copy(program_dir: Path, clip_id: str, social_copy: dict[str, Any]) -> Path: copies = load_social_copy(program_dir) copies[clip_id] = normalize_social_copy(social_copy) return save_social_copy(program_dir, copies) def hf_token() -> str | None: return ( os.environ.get("CLIP_EDITOR_HF_TOKEN") or os.environ.get("HF_TOKEN") or os.environ.get("HUGGINGFACEHUB_API_TOKEN") ) def hf_sync_repo() -> str | None: return os.environ.get("CLIP_EDITOR_SYNC_REPO") or os.environ.get("CLIP_DATA_REPO") def download_sync_data(target_dir: Path, library_mode: bool = False) -> None: repo_id = hf_sync_repo() if not repo_id: return try: from huggingface_hub import snapshot_download except Exception as exc: raise RuntimeError("huggingface_hub no está instalado; no puedo bajar los clips de la nube.") from exc target_dir.mkdir(parents=True, exist_ok=True) allow_patterns = ["raw/*", "vertical_9x16/*", "web_preview/*", "social_copy.json"] if library_mode: allow_patterns = ["programs/**"] snapshot_download( repo_id=repo_id, repo_type="dataset", token=hf_token(), local_dir=str(target_dir), allow_patterns=allow_patterns, ) def sync_base_dir(server: ThreadingHTTPServer) -> Path: return getattr(server, "programs_root", None) or server.program_dir # type: ignore[attr-defined] def upload_sync_file(server: ThreadingHTTPServer, path: Path) -> None: repo_id = hf_sync_repo() token = hf_token() if not repo_id or not token: return try: from huggingface_hub import HfApi except Exception: return try: rel_path = path.resolve().relative_to(sync_base_dir(server).resolve()).as_posix() except ValueError: return HfApi(token=token).upload_file( repo_id=repo_id, repo_type="dataset", path_or_fileobj=str(path), path_in_repo=rel_path, commit_message=f"Actualizar {rel_path}", ) def find_ffmpeg() -> str | None: app_dir = Path(__file__).resolve().parent candidates = [ "/opt/homebrew/opt/ffmpeg-full/bin/ffmpeg", "/opt/homebrew/bin/ffmpeg", "/usr/local/bin/ffmpeg", app_dir / "ffmpeg" / "bin" / "ffmpeg.exe", app_dir / "bin" / "ffmpeg.exe", app_dir / "ffmpeg.exe", shutil.which("ffmpeg"), shutil.which("ffmpeg.exe"), ] for candidate in candidates: if candidate and Path(candidate).exists(): return str(candidate) return None def make_web_preview(source_path: Path, preview_path: Path, ffmpeg_bin: str) -> None: preview_path.parent.mkdir(parents=True, exist_ok=True) tmp_path = preview_path.with_name(f".{preview_path.stem}.tmp{preview_path.suffix}") cmd = [ ffmpeg_bin, "-y", "-i", str(source_path), "-vf", "scale=720:1280:flags=lanczos,fps=30", "-c:v", "libx264", "-preset", "veryfast", "-crf", "28", "-c:a", "aac", "-b:a", "96k", "-movflags", "+faststart", str(tmp_path), ] result = subprocess.run(cmd, capture_output=True, text=True) if result.returncode != 0: if tmp_path.exists(): tmp_path.unlink() raise RuntimeError(f"No pude crear preview web: {result.stderr[-1200:]}") os.replace(tmp_path, preview_path) def brand_marker_path(output_path: Path) -> Path: return output_path.with_suffix(".brand.json") def write_brand_marker(output_path: Path) -> Path: marker_path = brand_marker_path(output_path) logo_stat = PYD_LOGO_PATH.stat() if PYD_LOGO_PATH.exists() else None output_stat = output_path.stat() marker = { "version": BRAND_VERSION, "logo": PYD_LOGO_PATH.name, "logo_size": logo_stat.st_size if logo_stat else None, "logo_mtime": int(logo_stat.st_mtime) if logo_stat else None, "output_size": output_stat.st_size, "output_mtime": int(output_stat.st_mtime), "created_at": datetime.now().isoformat(timespec="seconds"), } marker_path.write_text(json.dumps(marker, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") return marker_path def install_import_stubs() -> None: """Let the editor import clip_workflow.py without API-only dependencies.""" existing = sys.modules.get("anthropic") if existing is not None: if getattr(existing, "__spec__", None) is None: existing.__spec__ = importlib.util.spec_from_loader("anthropic", loader=None) return try: anthropic_spec = importlib.util.find_spec("anthropic") except ValueError: anthropic_spec = None if anthropic_spec is None: module = types.ModuleType("anthropic") module.__spec__ = importlib.util.spec_from_loader("anthropic", loader=None) module.__package__ = "" class MissingAnthropic: def __init__(self, *_args: Any, **_kwargs: Any) -> None: raise RuntimeError("anthropic no está instalado; no hace falta para regenerar subtítulos.") module.Anthropic = MissingAnthropic # type: ignore[attr-defined] sys.modules["anthropic"] = module def load_clip_workflow(root_dir: Path): candidates = [ root_dir / "clip_workflow.py", Path(__file__).resolve().parent / "clip_workflow.py", Path(__file__).resolve().parent.parent / "clip_workflow.py", Path.cwd() / "clip_workflow.py", ] for candidate in candidates: if candidate.exists(): install_import_stubs() spec = importlib.util.spec_from_file_location("clip_workflow_editor", candidate) if spec and spec.loader: module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) return module raise RuntimeError("No encontre clip_workflow.py junto a la app o en el proyecto.") def regenerate_clip( server: ThreadingHTTPServer, clip: ClipInfo, job_id: str, ) -> None: job = server.jobs[job_id] # type: ignore[attr-defined] job["status"] = "running" job["technical_log"] = "" set_job_message(job, "Preparando el clip...") try: ffmpeg_bin = find_ffmpeg() if not ffmpeg_bin: raise RuntimeError("No encontre ffmpeg. Instalar ffmpeg o ffmpeg-full.") set_job_message(job, "Cargando el motor de video...") module = load_clip_workflow(server.root_dir) # type: ignore[attr-defined] module.FFMPEG_BIN = ffmpeg_bin module.VIDEO_PRESET = os.environ.get("CLIP_EDITOR_PRESET", "medium") module.VIDEO_CRF = os.environ.get("CLIP_EDITOR_CRF", getattr(module, "VIDEO_CRF", "18")) if importlib.util.find_spec("cv2") is None: job["technical_log"] += "Aviso: OpenCV no está instalado; se usará zoom estático.\n" set_job_message(job, "Regenerando con encuadre simple porque falta OpenCV...") clip.output_path.parent.mkdir(parents=True, exist_ok=True) tmp_output = clip.output_path.with_name(f".{clip.output_path.stem}.tmp{clip.output_path.suffix}") zoom_plan_path = clip.output_path.with_suffix(".zoom.json") if zoom_plan_path.exists(): set_job_message(job, "Actualizando subtítulos sin recalcular el encuadre...") else: set_job_message(job, "Analizando el video para seguir a quien habla...") with contextlib.redirect_stdout(Capture(job)), contextlib.redirect_stderr(Capture(job)): module.encode_vertical_dynamic_zoom( clip.raw_path, clip.ass_path, tmp_output, reuse_zoom_plan=True, zoom_plan_path=zoom_plan_path, ) set_job_message(job, "Guardando el clip actualizado...") os.replace(tmp_output, clip.output_path) upload_sync_file(server, clip.output_path) if PYD_LOGO_PATH.exists(): marker_path = write_brand_marker(clip.output_path) upload_sync_file(server, marker_path) if zoom_plan_path.exists(): upload_sync_file(server, zoom_plan_path) set_job_message(job, "Preparando una vista rápida para la web...") make_web_preview(clip.output_path, clip.preview_path, ffmpeg_bin) upload_sync_file(server, clip.preview_path) invalidate_server_cache(server) job["status"] = "done" set_job_message(job, "Clip regenerado. Ya podés revisarlo arriba.") except (Exception, SystemExit) as exc: job["status"] = "error" job["error"] = concise_error_message(exc, job.get("technical_log", "")) set_job_message(job, job["error"]) job["technical_log"] += "\n" + traceback.format_exc() finally: clip_key = str(clip.output_path.resolve()) job_lock = getattr(server, "job_lock", None) active_clip_jobs = getattr(server, "active_clip_jobs", None) if job_lock is not None and active_clip_jobs is not None: with job_lock: if active_clip_jobs.get(clip_key) == job_id: del active_clip_jobs[clip_key] class Handler(BaseHTTPRequestHandler): server_version = "SubtitleEditor/1.0" def log_message(self, fmt: str, *args: Any) -> None: return None def is_authorized(self) -> bool: username = os.environ.get("CLIP_EDITOR_USERNAME", "editor") password = os.environ.get("CLIP_EDITOR_PASSWORD", "") if not password: return True header = self.headers.get("Authorization", "") if not header.startswith("Basic "): return False try: decoded = base64.b64decode(header.removeprefix("Basic ").strip()).decode("utf-8") except Exception: return False provided_username, sep, provided_password = decoded.partition(":") return bool(sep) and provided_username == username and provided_password == password def require_auth(self) -> None: self.send_response(HTTPStatus.UNAUTHORIZED) self.send_header("WWW-Authenticate", 'Basic realm="Clip editor"') self.send_header("Content-Type", "text/plain; charset=utf-8") self.end_headers() self.wfile.write("Necesitas la contraseña del editor.\n".encode("utf-8")) def send_json(self, value: Any, status: HTTPStatus = HTTPStatus.OK) -> None: payload = json_bytes(value) self.send_response(status) self.send_header("Content-Type", "application/json; charset=utf-8") self.send_header("Content-Length", str(len(payload))) self.end_headers() self.wfile.write(payload) def send_text(self, value: str, content_type: str = "text/html; charset=utf-8") -> None: payload = value.encode("utf-8") self.send_response(HTTPStatus.OK) self.send_header("Content-Type", content_type) self.send_header("Content-Length", str(len(payload))) self.end_headers() self.wfile.write(payload) def send_binary(self, payload: bytes, content_type: str, cache_control: str = "private, max-age=86400") -> None: self.send_response(HTTPStatus.OK) self.send_header("Content-Type", content_type) self.send_header("Content-Length", str(len(payload))) self.send_header("Cache-Control", cache_control) self.end_headers() self.wfile.write(payload) def send_asset(self, asset_name: str) -> None: if not re.fullmatch(r"[A-Za-z0-9_.-]+", asset_name): self.send_error(HTTPStatus.NOT_FOUND) return path = APP_ASSETS_DIR / asset_name if not path.exists() or not path.is_file(): self.send_error(HTTPStatus.NOT_FOUND) return content_type = "image/png" if path.suffix.lower() == ".png" else "application/octet-stream" self.send_binary(path.read_bytes(), content_type, cache_control="public, max-age=604800, immutable") def send_file(self, path: Path, send_body: bool = True, disposition: str = "inline") -> None: if not path.exists() or not path.is_file(): self.send_error(HTTPStatus.NOT_FOUND) return size = path.stat().st_size range_header = self.headers.get("Range", "") start = 0 end = size - 1 status = HTTPStatus.OK if range_header.startswith("bytes="): match = re.match(r"bytes=(\d*)-(\d*)", range_header) if match: if match.group(1): start = int(match.group(1)) if match.group(2): end = int(match.group(2)) end = min(end, size - 1) if start > end or start >= size: self.send_response(HTTPStatus.REQUESTED_RANGE_NOT_SATISFIABLE) self.send_header("Content-Range", f"bytes */{size}") self.end_headers() return status = HTTPStatus.PARTIAL_CONTENT length = end - start + 1 self.send_response(status) self.send_header("Content-Type", "video/mp4") self.send_header("Accept-Ranges", "bytes") if status == HTTPStatus.PARTIAL_CONTENT: self.send_header("Content-Range", f"bytes {start}-{end}/{size}") self.send_header("Content-Length", str(length)) self.send_header("Cache-Control", "private, max-age=86400, immutable") self.send_header("Content-Disposition", f'{disposition}; filename="{path.name}"') self.end_headers() if send_body: with path.open("rb") as file: file.seek(start) remaining = length while remaining > 0: chunk = file.read(min(1024 * 1024, remaining)) if not chunk: break try: self.wfile.write(chunk) except CLIENT_DISCONNECT_ERRORS: return remaining -= len(chunk) def read_json(self) -> dict[str, Any]: length = int(self.headers.get("Content-Length", "0")) if length <= 0: return {} raw = self.rfile.read(length) return json.loads(raw.decode("utf-8")) def program_id_from_query(self, parsed) -> str | None: return parse_qs(parsed.query).get("program", [""])[0] or None def do_GET(self) -> None: if not self.is_authorized(): self.require_auth() return parsed = urlparse(self.path) path = parsed.path try: if path == "/": self.send_text(APP_HTML) return if path.startswith("/assets/"): self.send_asset(unquote(path.removeprefix("/assets/")).strip("/")) return if path == "/api/programs": programs = cached_programs(self.server) self.send_json( { "programs": [ { "id": program.id, "name": program.name, "clip_count": program.clip_count, "program_date": program.program_date.isoformat() if program.program_date else "", "program_datetime": program.program_datetime.isoformat(timespec="seconds") if program.program_datetime else "", } for program in programs ] } ) return if path == "/api/clips": program = find_program(self.server, self.program_id_from_query(parsed)) clips = cached_clips(self.server, program) social_copies = load_social_copy(program.path) self.send_json( { "program_id": program.id, "program_name": program.name, "clips": [self.clip_payload(clip, program, social_copies) for clip in clips], } ) return if path.startswith("/api/clips/") and path.endswith("/subtitles"): clip_id = unquote(path.removeprefix("/api/clips/").removesuffix("/subtitles")).strip("/") clip = find_clip(self.server, clip_id, self.program_id_from_query(parsed)) self.send_json({"subtitles": parse_ass(clip.ass_path)}) return if path.startswith("/api/clips/") and path.endswith("/social-copy"): program = find_program(self.server, self.program_id_from_query(parsed)) clip_id = unquote(path.removeprefix("/api/clips/").removesuffix("/social-copy")).strip("/") clip = next((item for item in cached_clips(self.server, program) if item.id == clip_id), None) if not clip: raise KeyError(f"Clip no encontrado: {clip_id}") self.send_json({"social_copy": load_social_copy(program.path).get(clip.id, empty_social_copy())}) return if path.startswith("/api/jobs/"): job_id = unquote(path.removeprefix("/api/jobs/")).strip("/") job = self.server.jobs.get(job_id) # type: ignore[attr-defined] if not job: self.send_json({"error": "Job no encontrado"}, HTTPStatus.NOT_FOUND) return self.send_json(job) return if path.startswith("/media/"): qs = parse_qs(parsed.query) clip_id = qs.get("clip", [""])[0] clip = find_clip(self.server, clip_id, qs.get("program", [""])[0] or None) media_path = clip.preview_path if path.endswith("/preview") and clip.preview_path.exists() else clip.output_path disposition = "attachment" if path.endswith("/download") else "inline" self.send_file(media_path, disposition=disposition) return self.send_error(HTTPStatus.NOT_FOUND) except CLIENT_DISCONNECT_ERRORS: return except Exception as exc: self.send_json({"error": str(exc)}, HTTPStatus.INTERNAL_SERVER_ERROR) def do_HEAD(self) -> None: if not self.is_authorized(): self.require_auth() return parsed = urlparse(self.path) path = parsed.path try: if path.startswith("/media/"): qs = parse_qs(parsed.query) clip_id = qs.get("clip", [""])[0] clip = find_clip(self.server, clip_id, qs.get("program", [""])[0] or None) media_path = clip.preview_path if path.endswith("/preview") and clip.preview_path.exists() else clip.output_path disposition = "attachment" if path.endswith("/download") else "inline" self.send_file(media_path, send_body=False, disposition=disposition) return self.send_error(HTTPStatus.NOT_FOUND) except CLIENT_DISCONNECT_ERRORS: return except Exception as exc: self.send_json({"error": str(exc)}, HTTPStatus.INTERNAL_SERVER_ERROR) def do_POST(self) -> None: if not self.is_authorized(): self.require_auth() return parsed = urlparse(self.path) path = parsed.path try: if path.startswith("/api/clips/") and path.endswith("/subtitles"): clip_id = unquote(path.removeprefix("/api/clips/").removesuffix("/subtitles")).strip("/") clip = find_clip(self.server, clip_id, self.program_id_from_query(parsed)) body = self.read_json() subtitles = body.get("subtitles") if not isinstance(subtitles, list): self.send_json({"error": "Payload inválido"}, HTTPStatus.BAD_REQUEST) return save_ass(clip.ass_path, subtitles) invalidate_server_cache(self.server) upload_sync_file(self.server, clip.ass_path) self.send_json({"ok": True}) return if path.startswith("/api/clips/") and path.endswith("/social-copy"): program = find_program(self.server, self.program_id_from_query(parsed)) clip_id = unquote(path.removeprefix("/api/clips/").removesuffix("/social-copy")).strip("/") clip = next((item for item in cached_clips(self.server, program) if item.id == clip_id), None) if not clip: raise KeyError(f"Clip no encontrado: {clip_id}") body = self.read_json() saved_path = update_clip_social_copy(program.path, clip.id, body.get("social_copy", {})) invalidate_server_cache(self.server, program) upload_sync_file(self.server, saved_path) self.send_json({"ok": True, "social_copy": load_social_copy(program.path).get(clip.id, empty_social_copy())}) return if path.startswith("/api/clips/") and path.endswith("/regenerate"): clip_id = unquote(path.removeprefix("/api/clips/").removesuffix("/regenerate")).strip("/") clip = find_clip(self.server, clip_id, self.program_id_from_query(parsed)) self.read_json() clip_key = str(clip.output_path.resolve()) with self.server.job_lock: # type: ignore[attr-defined] existing_job_id = self.server.active_clip_jobs.get(clip_key) # type: ignore[attr-defined] existing_job = self.server.jobs.get(existing_job_id) if existing_job_id else None # type: ignore[attr-defined] if existing_job and existing_job.get("status") in {"queued", "running"}: self.send_json({"job_id": existing_job_id, "already_running": True}) return job_id = uuid.uuid4().hex[:12] self.server.jobs[job_id] = { # type: ignore[attr-defined] "status": "queued", "message": "Esperando para empezar...", "log": "Esperando para empezar...", "technical_log": "", } self.server.active_clip_jobs[clip_key] = job_id # type: ignore[attr-defined] thread = threading.Thread( target=regenerate_clip, args=(self.server, clip, job_id), daemon=True, ) thread.start() self.send_json({"job_id": job_id}) return self.send_error(HTTPStatus.NOT_FOUND) except Exception as exc: self.send_json({"error": str(exc)}, HTTPStatus.INTERNAL_SERVER_ERROR) def clip_payload( self, clip: ClipInfo, program: ProgramInfo, social_copies: dict[str, dict[str, str]] | None = None, ) -> dict[str, Any]: mtime = int(clip.output_path.stat().st_mtime) if clip.output_path.exists() else int(time.time()) preview_mtime = int(clip.preview_path.stat().st_mtime) if clip.preview_path.exists() else mtime video_kind = "preview" if clip.preview_path.exists() else "output" social_copies = social_copies or load_social_copy(program.path) return { "id": clip.id, "title": clip.title, "has_output": clip.output_path.exists(), "subtitle_count": clip.subtitle_count, "video_url": f"/media/{video_kind}?program={program.id}&clip={clip.id}&v={preview_mtime}", "output_url": f"/media/output?program={program.id}&clip={clip.id}&v={mtime}", "download_url": f"/media/download?program={program.id}&clip={clip.id}&v={mtime}", "has_preview": clip.preview_path.exists(), "social_copy": social_copies.get(clip.id, empty_social_copy()), } def main() -> None: parser = argparse.ArgumentParser(description="Editor local de subtítulos ASS para clip-workflow.") parser.add_argument("--program-dir", default=".", help="Carpeta del programa con raw/ y vertical_9x16/") parser.add_argument("--programs-root", help="Biblioteca con varios programas (usa subcarpetas con raw/ y vertical_9x16/)") parser.add_argument("--host", default="127.0.0.1") parser.add_argument("--port", type=int, default=8787) parser.add_argument("--no-open", action="store_true", help="No abrir el navegador automaticamente") args = parser.parse_args() programs_root = Path(args.programs_root).expanduser().resolve() if args.programs_root else None program_dir = Path(args.program_dir).expanduser().resolve() if programs_root: download_sync_data(programs_root, library_mode=True) programs = discover_programs(programs_root, program_dir) if not programs: raise SystemExit(f"No hay programas con raw/ y vertical_9x16/ en {programs_root}") program_dir = programs[0].path else: download_sync_data(program_dir) if not (program_dir / "raw").exists(): raise SystemExit(f"No existe raw/ en {program_dir}") httpd = ThreadingHTTPServer((args.host, args.port), Handler) httpd.program_dir = program_dir # type: ignore[attr-defined] httpd.programs_root = programs_root # type: ignore[attr-defined] httpd.root_dir = Path(__file__).resolve().parent # type: ignore[attr-defined] httpd.jobs = {} # type: ignore[attr-defined] httpd.job_lock = threading.Lock() # type: ignore[attr-defined] httpd.active_clip_jobs = {} # type: ignore[attr-defined] httpd.program_cache = None # type: ignore[attr-defined] httpd.clip_cache = {} # type: ignore[attr-defined] url = f"http://{args.host}:{args.port}" print(f"Editor abierto en {url}") print(f"Biblioteca: {programs_root or program_dir}") if not args.no_open: webbrowser.open(url) httpd.serve_forever() if __name__ == "__main__": main()