#!/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 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_HTML = r"""
Editor de subtitulos
Cargando...
"""
@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
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 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 vacio")
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 invalido: {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 invalido en linea {position + 1}.") from exc
if end_seconds <= start_seconds:
raise ValueError(f"El fin debe ser mayor al inicio en linea {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 load_program_metadata(program_dir: Path) -> dict[str, Any]:
candidates = [
program_dir / "program.json",
*sorted(program_dir.glob("*.info.json")),
*sorted((program_dir / "raw").glob("*.info.json")),
]
for path in candidates:
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")),
}
return {"title": "", "video_id": "", "url": "", "hidden": False}
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),
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 list(unique.values())
def find_program(server: ThreadingHTTPServer, program_id: str | None = None) -> ProgramInfo:
programs = discover_programs(
getattr(server, "programs_root", None),
server.program_dir, # type: ignore[attr-defined]
)
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 discover_clips(program.path):
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")
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 esta 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/*"]
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 install_import_stubs() -> None:
"""Let the editor import clip_workflow.py without API-only dependencies."""
if importlib.util.find_spec("anthropic") is None and "anthropic" not in sys.modules:
module = types.ModuleType("anthropic")
class MissingAnthropic:
def __init__(self, *_args: Any, **_kwargs: Any) -> None:
raise RuntimeError("anthropic no esta instalado; no hace falta para regenerar subtitulos.")
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 esta instalado; se usara zoom estatico.\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}")
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)
set_job_message(job, "Guardando el clip actualizado...")
os.replace(tmp_output, clip.output_path)
upload_sync_file(server, clip.output_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)
job["status"] = "done"
set_job_message(job, "Clip regenerado. Ya podes revisarlo arriba.")
except Exception:
job["status"] = "error"
set_job_message(job, "No se pudo regenerar el clip. Revisá que el archivo siga en la carpeta y probá de nuevo.")
job["technical_log"] += "\n" + traceback.format_exc()
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_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 == "/api/programs":
programs = discover_programs(
getattr(self.server, "programs_root", None),
self.server.program_dir, # type: ignore[attr-defined]
)
self.send_json(
{
"programs": [
{"id": program.id, "name": program.name, "clip_count": program.clip_count}
for program in programs
]
}
)
return
if path == "/api/clips":
program = find_program(self.server, self.program_id_from_query(parsed))
clips = discover_clips(program.path)
self.send_json(
{
"program_id": program.id,
"program_name": program.name,
"clips": [self.clip_payload(clip, program) 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/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 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 invalido"}, HTTPStatus.BAD_REQUEST)
return
save_ass(clip.ass_path, subtitles)
upload_sync_file(self.server, clip.ass_path)
self.send_json({"ok": True})
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))
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": "",
}
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) -> 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"
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(),
}
def main() -> None:
parser = argparse.ArgumentParser(description="Editor local de subtitulos 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]
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()