clips / subtitle_editor.py
Emirona07's picture
Deploy clip subtitle editor
923a92d verified
Raw History Blame Contribute Delete
106 kB
#!/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"""<!doctype html> <html lang="es"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>PYD Clips</title> <link rel="icon" type="image/png" href="/assets/pyd-favicon.png"> <link rel="apple-touch-icon" href="/assets/pyd-favicon.png"> <style> :root { color-scheme: light; --bg: #f6f6f1; --surface: #ffffff; --surface-soft: #fbfaf7; --ink: #171812; --ink-soft: #34362d; --muted: #797a70; --line: #e7e3d8; --line-strong: #d3cec0; --rail: #11120e; --rail-soft: #1a1b15; --rail-line: #2d2f25; --accent: #e6bd26; --accent-ink: #231d00; --accent-soft: #fff7d4; --ok: #148957; --ok-dark: #0d6f45; --ok-soft: #eaf7ef; --bad: #b2413a; --radius: 8px; --shadow: 0 18px 46px rgba(18, 18, 14, .12); } * { box-sizing: border-box; } html { background: var(--bg); } body { margin: 0; min-width: 1080px; font: 14px/1.45 Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; background: var(--bg); color: var(--ink); letter-spacing: 0; } button, textarea, input { font: inherit; } button { border: 1px solid var(--ink); background: var(--ink); color: #fff; min-height: 40px; padding: 0 15px; border-radius: var(--radius); cursor: pointer; font-weight: 760; letter-spacing: 0; white-space: nowrap; box-shadow: 0 1px 0 rgba(255,255,255,.12) inset, 0 10px 20px rgba(20,20,16,.08); transition: background .15s ease, border-color .15s ease, color .15s ease, opacity .15s ease, transform .15s ease, box-shadow .15s ease; } button.secondary { background: #fff; color: var(--ink); border-color: var(--line); box-shadow: 0 8px 18px rgba(18, 18, 14, .04); } button.subtle { min-height: 34px; padding: 0 11px; background: var(--surface-soft); color: var(--ink-soft); border-color: var(--line); font-size: 12px; box-shadow: none; } button:hover:not(:disabled) { background: #292925; border-color: #292925; transform: translateY(-1px); box-shadow: 0 14px 26px rgba(20,20,16,.13); } button.secondary:hover:not(:disabled) { background: var(--surface-soft); border-color: var(--line-strong); } button.subtle:hover:not(:disabled) { background: #fff; color: var(--ink); border-color: var(--line-strong); } button:disabled { cursor: default; opacity: .55; transform: none; box-shadow: none; } .shell { display: grid; grid-template-columns: 300px minmax(340px, 500px) minmax(420px, 1fr); height: 100dvh; min-width: 0; overflow: hidden; } aside { border-right: 1px solid var(--rail-line); background: var(--rail); color: #f7f4e7; min-width: 0; min-height: 0; display: flex; flex-direction: column; } .brand { padding: 18px 20px 17px; border-bottom: 1px solid var(--rail-line); display: grid; gap: 12px; min-height: 136px; } .brand-logo { width: 156px; height: auto; display: block; filter: drop-shadow(0 12px 18px rgba(0,0,0,.28)); } .brand-copy { display: grid; gap: 5px; min-width: 0; } h1, h2 { margin: 0; letter-spacing: 0; } h1 { font-size: 16px; line-height: 1.15; font-weight: 820; color: #fff8d9; } .program { color: #d6d2c4; font-size: 13px; line-height: 1.28; max-width: 260px; display: -webkit-box; -webkit-line-clamp: 3; -webkit-box-orient: vertical; overflow: hidden; } .program-picker { padding: 15px 20px 17px; border-bottom: 1px solid var(--rail-line); display: grid; gap: 8px; } .program-picker-label { color: #b9b6a8; font-size: 11px; font-weight: 780; letter-spacing: .08em; text-transform: uppercase; } .program-dropdown { position: relative; z-index: 6; } .program-trigger { width: 100%; min-height: 62px; display: grid; grid-template-columns: minmax(0, 1fr) 22px; align-items: start; gap: 10px; text-align: left; border: 1px solid rgba(230, 189, 38, .42); border-radius: 12px; padding: 11px 13px; background: linear-gradient(180deg, rgba(255,255,255,.055), rgba(255,255,255,.025)), var(--rail-soft); color: #fff8d9; box-shadow: 0 12px 24px rgba(0,0,0,.18); } .program-trigger:hover:not(:disabled), .program-trigger[aria-expanded="true"] { background: #22231c; border-color: rgba(230, 189, 38, .72); box-shadow: 0 16px 28px rgba(0,0,0,.24), 0 0 0 3px rgba(230, 189, 38, .08); transform: none; } .program-trigger:disabled { opacity: 1; } .program-trigger-text { min-width: 0; display: grid; gap: 4px; overflow: visible; white-space: normal; line-height: 1.2; } .program-trigger-title { display: block; color: #fff8d9; font-size: 14px; font-weight: 830; } .program-trigger-meta { display: block; color: #c8c2ae; font-size: 12px; font-weight: 650; } .program-trigger-icon { width: 18px; height: 18px; border-radius: 999px; position: relative; background: rgba(255,255,255,.08); margin-top: 3px; } .program-trigger-icon::after { content: ""; position: absolute; left: 5px; top: 4px; width: 8px; height: 8px; border-right: 2px solid var(--accent); border-bottom: 2px solid var(--accent); transform: rotate(45deg); transition: transform .16s ease, top .16s ease; } .program-trigger[aria-expanded="true"] .program-trigger-icon::after { top: 7px; transform: rotate(225deg); } .program-menu { position: absolute; left: 0; right: auto; top: calc(100% + 8px); width: min(520px, calc(100vw - 40px)); max-height: min(340px, calc(100vh - 230px)); overflow: auto; padding: 6px; border: 1px solid rgba(255,255,255,.12); border-radius: 14px; background: rgba(28, 29, 23, .98); box-shadow: 0 28px 60px rgba(0,0,0,.42), 0 0 0 1px rgba(230,189,38,.09); backdrop-filter: blur(14px); } .program-menu[hidden] { display: none; } .program-option { width: 100%; min-height: 64px; display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 10px; align-items: center; padding: 10px 11px; border: 1px solid transparent; border-radius: 10px; background: transparent; color: #f7f4e7; box-shadow: none; transform: none; text-align: left; } .program-option:hover:not(:disabled), .program-option.active { background: rgba(255,255,255,.08); border-color: rgba(230,189,38,.26); box-shadow: none; transform: none; } .program-option.active { background: rgba(230,189,38,.14); color: #fff5c4; } .program-option-title { display: block; min-width: 0; overflow: visible; text-overflow: clip; white-space: normal; font-weight: 790; line-height: 1.2; } .program-option-meta { display: block; margin-top: 3px; color: #aaa79a; font-size: 11.5px; font-weight: 620; } .program-option-check { width: 24px; height: 24px; border-radius: 999px; display: grid; place-items: center; color: var(--accent); background: rgba(230,189,38,.1); opacity: 0; font-weight: 900; } .program-option.active .program-option-check { opacity: 1; } .clip-list { flex: 1; min-height: 0; overflow: auto; padding: 12px 12px 16px; } .clip-button { width: 100%; display: grid; grid-template-columns: 34px minmax(0, 1fr); gap: 10px; align-items: center; text-align: left; border: 1px solid transparent; background: transparent; color: #f7f4e7; padding: 10px; min-height: 60px; border-radius: var(--radius); font-weight: 680; } .clip-button:hover:not(:disabled) { background: var(--rail-soft); border-color: transparent; box-shadow: none; transform: none; } .clip-button.active, .clip-button.active:hover:not(:disabled) { background: #fff8d9; color: var(--ink); border-color: rgba(230,189,38,.62); box-shadow: none; transform: none; } .num { width: 34px; height: 34px; border-radius: 8px; border: 1px solid rgba(255,255,255,.16); display: grid; place-items: center; font-size: 12px; font-weight: 850; background: rgba(255,255,255,.07); color: inherit; font-variant-numeric: tabular-nums; } .clip-button.active .num { background: var(--accent); border-color: var(--accent); color: var(--accent-ink); } .clip-copy { min-width: 0; } .clip-title { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .clip-meta { color: #aaa79a; font-size: 12px; margin-top: 2px; font-weight: 550; } .clip-button.active .clip-meta { color: var(--muted); } .video-pane, .edit-pane { min-height: 0; min-width: 0; } .video-pane { display: flex; flex-direction: column; gap: 14px; align-items: stretch; padding: 22px 24px; border-right: 1px solid var(--line); background: linear-gradient(180deg, rgba(255,255,255,.84), rgba(255,255,255,.28)), var(--bg); overflow: auto; } .video-frame { width: min(100%, 438px); align-self: center; border-radius: 12px; background: #070706; padding: 7px; box-shadow: var(--shadow); } video { width: 100%; aspect-ratio: 9 / 16; background: #050505; border-radius: 8px; border: 1px solid #050505; display: block; max-height: calc(100vh - 170px); object-fit: contain; } .actions { display: grid; grid-template-columns: 1fr 1fr; gap: 9px; align-items: center; width: min(100%, 438px); align-self: center; } .actions button { width: 100%; } .actions .download { grid-column: 1 / -1; } .actions #reloadBtn { grid-column: 1 / -1; } .status { border: 1px solid var(--line); background: rgba(255,255,255,.76); border-radius: var(--radius); padding: 12px 14px; min-height: 44px; color: var(--muted); white-space: pre-wrap; box-shadow: 0 1px 0 rgba(0,0,0,.02); width: min(100%, 438px); align-self: center; } .status.busy { color: var(--ink-soft); border-color: #ead991; background: #fffaf0; } .status.ok { color: var(--ok); } .status.bad { color: var(--bad); } .edit-pane { background: var(--surface); display: flex; flex-direction: column; overflow: hidden; } .edit-header { padding: 18px 24px 12px; border-bottom: 1px solid var(--line); display: grid; gap: 10px; min-width: 0; background: rgba(255,255,255,.94); backdrop-filter: blur(14px); } .title-row { display: block; min-width: 0; } .title-actions { display: flex; gap: 8px; flex-wrap: wrap; justify-content: flex-start; } .title-actions button { min-height: 38px; padding: 0 13px; } .title-block { min-width: 0; display: grid; gap: 5px; } .eyebrow { color: var(--muted); font-size: 11px; font-weight: 760; letter-spacing: .08em; text-transform: uppercase; } h2 { font-size: 22px; line-height: 1.2; font-weight: 850; width: 100%; max-width: 100%; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .subtitle-toolbar { display: grid; grid-template-columns: 1fr; gap: 8px; align-items: start; min-width: 0; } .search-tools { display: grid; grid-template-columns: minmax(190px, 1fr) auto auto auto auto; gap: 8px; align-items: center; min-width: 0; } .search-box { position: relative; min-width: 0; } .search-box::before { content: ""; position: absolute; left: 13px; top: 50%; width: 10px; height: 10px; border: 2px solid #8b8a82; border-radius: 50%; transform: translateY(-58%); pointer-events: none; } .search-box::after { content: ""; position: absolute; left: 25px; top: 23px; width: 8px; height: 2px; background: #8b8a82; border-radius: 2px; transform: rotate(45deg); pointer-events: none; } input[type="search"] { width: 100%; min-height: 38px; border: 1px solid var(--line); border-radius: var(--radius); padding: 0 13px 0 40px; color: var(--ink); background: var(--surface-soft); outline: 0; font-weight: 650; } input[type="search"]:focus { background: #fff; border-color: var(--accent); box-shadow: 0 0 0 3px rgba(226, 182, 0, .18); } .match-count { min-width: 54px; color: var(--muted); font-size: 12px; font-weight: 740; text-align: right; font-variant-numeric: tabular-nums; } .rows { flex: 1; min-height: 0; overflow: auto; padding: 10px 24px 24px; background: var(--surface); } .sub-row { display: grid; grid-template-columns: 150px minmax(0, 1fr); gap: 16px; padding: 13px 0; margin: 2px 0; border: 1px solid transparent; border-radius: var(--radius); background: transparent; transition: background .15s ease, border-color .15s ease, box-shadow .15s ease; } .sub-row:hover { background: #fafafa; border-color: #efeee9; } .sub-row.match { background: #fffdf1; border-color: #f0dda2; } .sub-row.current-match { background: var(--accent-soft); border-color: var(--accent); box-shadow: 0 10px 24px rgba(226, 182, 0, .14); } .time { color: var(--muted); font-size: 12px; font-variant-numeric: tabular-nums; white-space: nowrap; display: grid; gap: 8px; align-content: start; } .time label { display: grid; gap: 4px; color: #aaa79f; font-size: 10px; font-weight: 790; letter-spacing: .05em; text-transform: uppercase; } .time-input { width: 100%; min-height: 34px; border: 1px solid var(--line); border-radius: var(--radius); padding: 0 9px; color: var(--ink-soft); background: var(--surface-soft); outline: 0; font-size: 13px; font-weight: 720; font-variant-numeric: tabular-nums; letter-spacing: 0; } .time-input:focus { background: #fff; border-color: var(--accent); box-shadow: 0 0 0 3px rgba(226, 182, 0, .18); } .line-num { color: #aaa79f; font-size: 11px; font-weight: 760; letter-spacing: .04em; text-transform: uppercase; } .row-actions { display: flex; gap: 6px; flex-wrap: wrap; } .sub-main { display: grid; gap: 8px; min-width: 0; } textarea { width: 100%; min-height: 68px; resize: vertical; border: 1px solid var(--line); border-radius: var(--radius); padding: 12px 13px; color: var(--ink); background: var(--surface-soft); line-height: 1.35; font-weight: 760; letter-spacing: 0; transition: background .15s ease, border-color .15s ease, box-shadow .15s ease; } textarea:focus { background: #fff; outline: 0; border-color: var(--accent); box-shadow: 0 0 0 3px rgba(226, 182, 0, .18); } .copy-panel { flex: 0 0 auto; border: 1px solid var(--line); border-radius: 12px; background: var(--surface-soft); padding: 14px; margin: 0 24px 18px; max-height: min(38dvh, 360px); overflow: auto; display: grid; gap: 12px; box-shadow: 0 12px 28px rgba(18, 18, 14, .05); } .copy-panel-head { display: flex; justify-content: space-between; align-items: center; gap: 10px; } .copy-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(220px, 100%), 1fr)); gap: 10px; } .copy-card { min-width: 0; display: grid; gap: 8px; padding: 10px; border: 1px solid var(--line); border-radius: 10px; background: #fff; } .copy-card-head { display: flex; justify-content: space-between; align-items: center; gap: 8px; } .copy-platform { display: flex; align-items: center; gap: 7px; } .copy-logo { width: 32px; height: 32px; border-radius: 9px; display: grid; place-items: center; color: #fff; box-shadow: 0 8px 18px rgba(18,18,14,.1); } .copy-logo svg { width: 19px; height: 19px; display: block; } .copy-logo.instagram { background: radial-gradient(circle at 28% 105%, #feda75 0 22%, #fa7e1e 34%, #d62976 58%, #962fbf 78%, #4f5bd5 100%); } .copy-logo.twitter { background: #111; } .copy-logo.tiktok { background: #090909; } textarea.copy-text { min-height: 170px; font-size: 13px; font-weight: 650; line-height: 1.42; resize: vertical; } button.download { background: linear-gradient(180deg, #1aa463, var(--ok)); border-color: var(--ok); color: #fff; box-shadow: 0 1px 0 rgba(255,255,255,.18) inset, 0 16px 28px rgba(20, 137, 87, .22); } button.download:hover:not(:disabled) { background: linear-gradient(180deg, #168f57, var(--ok-dark)); border-color: var(--ok-dark); box-shadow: 0 18px 32px rgba(20, 137, 87, .28); } button.danger { background: var(--bad); border-color: var(--bad); color: #fff; } body.modal-open { overflow: hidden; } .modal-backdrop { position: fixed; inset: 0; z-index: 100; display: grid; place-items: center; padding: 24px; background: rgba(17, 18, 14, .44); backdrop-filter: blur(10px); } .modal-backdrop[hidden] { display: none; } .confirm-modal { width: min(100%, 430px); border: 1px solid rgba(255,255,255,.72); border-radius: var(--radius); background: #fff; color: var(--ink); box-shadow: 0 28px 80px rgba(15, 15, 12, .28); overflow: hidden; } .confirm-body { padding: 22px 22px 8px; display: grid; gap: 8px; } .confirm-body h3 { margin: 0; font-size: 20px; line-height: 1.2; } .confirm-body p { margin: 0; color: var(--muted); font-size: 14px; line-height: 1.45; } .confirm-actions { display: flex; justify-content: flex-end; gap: 8px; padding: 16px 22px 22px; } @media (max-width: 1280px) { h2 { white-space: normal; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; } .search-tools { grid-template-columns: minmax(0, 1fr) auto auto auto; } .search-tools .match-count { display: none; } } @media (max-width: 1080px) { body { min-width: 0; } .shell { grid-template-columns: 1fr; height: auto; min-height: 100vh; overflow: visible; } aside { max-height: none; border-right: 0; border-bottom: 1px solid var(--line); } .clip-list { flex: 0 0 auto; display: flex; gap: 8px; overflow-x: auto; overflow-y: hidden; padding: 10px 12px 12px; scroll-snap-type: x proximity; -webkit-overflow-scrolling: touch; } .clip-button { flex: 0 0 280px; max-width: calc(100vw - 32px); scroll-snap-align: start; } .video-pane { border-right: 0; border-bottom: 1px solid var(--line); } .program-picker { background: var(--rail); } video { max-height: 70vh; } .edit-pane { min-height: 520px; } } @media (max-width: 620px) { .brand { min-height: auto; padding: 12px 14px; grid-template-columns: 118px minmax(0, 1fr); align-items: center; gap: 12px; } .brand-logo { width: 118px; } h1 { font-size: 15px; } h2 { white-space: normal; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; } .program { max-width: none; font-size: 12px; -webkit-line-clamp: 2; } .program-picker { padding: 10px 14px 11px; } .program-trigger { min-height: 56px; padding: 10px 12px; } .clip-list { padding: 8px 12px 12px; } .clip-button { flex-basis: clamp(220px, 76vw, 300px); min-height: 56px; padding: 8px; } .video-pane { padding: 12px; } .sub-row { grid-template-columns: 1fr; gap: 6px; padding: 10px 0; border-radius: 0; } .time { padding-top: 0; } .search-tools { grid-template-columns: 1fr auto auto; } .subtitle-toolbar { grid-template-columns: 1fr; } .title-actions { justify-content: stretch; } .title-actions button { flex: 1; } .copy-grid { grid-template-columns: 1fr; } .copy-panel { max-height: none; overflow: visible; } .search-tools .match-count, .search-tools #clearSearchBtn { display: none; } } </style> </head> <body> <div class="shell"> <aside> <div class="brand"> <img class="brand-logo" src="/assets/pyd-logo.png" alt="PYD TV"> <div class="brand-copy"> <h1>Editor de subtítulos</h1> <div class="program" id="programName"></div> </div> </div> <div class="program-picker"> <div class="program-picker-label">Programa</div> <div class="program-dropdown" id="programDropdown"> <button class="program-trigger" id="programTrigger" type="button" aria-haspopup="listbox" aria-expanded="false"> <span class="program-trigger-text" id="programTriggerText">Cargando...</span> <span class="program-trigger-icon" aria-hidden="true"></span> </button> <div class="program-menu" id="programMenu" role="listbox" hidden></div> </div> </div> <div class="clip-list" id="clipList"></div> </aside> <section class="video-pane"> <div class="video-frame"> <video id="video" controls playsinline preload="metadata" controlslist="nodownload"></video> </div> <div class="actions"> <button id="saveBtn">Guardar</button> <button id="regenBtn">Regenerar clip</button> <button class="download" id="downloadBtn">Descargar final HQ</button> <button class="secondary" id="reloadBtn">Recargar</button> </div> <div class="status" id="status">Cargando...</div> </section> <section class="edit-pane"> <div class="edit-header"> <div class="title-row"> <div class="title-block"> <div class="eyebrow">Clip activo</div> <h2 id="clipTitle">Subtítulos</h2> </div> </div> <div class="subtitle-toolbar"> <div class="search-tools"> <label class="search-box"> <input id="searchInput" type="search" placeholder="Buscar en subtítulos" autocomplete="off"> </label> <button class="subtle" id="prevMatchBtn" type="button">Ant</button> <button class="subtle" id="nextMatchBtn" type="button">Sig</button> <button class="subtle" id="clearSearchBtn" type="button">Limpiar</button> <div class="match-count" id="searchCount">0</div> </div> <div class="title-actions"> <button class="secondary" id="addSubBtn">Agregar línea</button> <button class="secondary" id="openBtn">Abrir MP4</button> </div> </div> </div> <div class="rows" id="rows"></div> <div class="copy-panel"> <div class="copy-panel-head"> <div class="eyebrow">Copies por red</div> <button class="subtle" id="saveCopyBtn" type="button">Guardar copies</button> </div> <div class="copy-grid"> <section class="copy-card instagram"> <div class="copy-card-head"> <div class="copy-platform" title="Instagram" aria-label="Instagram"><span class="copy-logo instagram" aria-hidden="true"><svg viewBox="0 0 24 24" fill="none"><rect x="5" y="5" width="14" height="14" rx="4" stroke="currentColor" stroke-width="2"/><circle cx="12" cy="12" r="3.2" stroke="currentColor" stroke-width="2"/><circle cx="16.6" cy="7.4" r="1.2" fill="currentColor"/></svg></span></div> <button class="subtle copy-btn" type="button" data-platform="instagram">Copiar</button> </div> <textarea class="copy-text" id="copyInstagram" spellcheck="true"></textarea> </section> <section class="copy-card twitter"> <div class="copy-card-head"> <div class="copy-platform" title="X / Twitter" aria-label="X / Twitter"><span class="copy-logo twitter" aria-hidden="true"><svg viewBox="0 0 24 24" fill="currentColor"><path d="M14.6 10.4 21 3h-2.1l-5.2 6-4.1-6H3l6.8 9.9L3 21h2.1l5.6-6.5 4.5 6.5H21l-6.4-10.6Zm-2.2 2.5-.9-1.3L6.8 4.7h1.8l3.8 5.6.9 1.3 5 7.5h-1.8l-4.1-6.2Z"/></svg></span></div> <button class="subtle copy-btn" type="button" data-platform="twitter">Copiar</button> </div> <textarea class="copy-text" id="copyTwitter" spellcheck="true"></textarea> </section> <section class="copy-card tiktok"> <div class="copy-card-head"> <div class="copy-platform" title="TikTok" aria-label="TikTok"><span class="copy-logo tiktok" aria-hidden="true"><svg viewBox="0 0 24 24" fill="none"><path d="M14 4v10.1a4.3 4.3 0 1 1-4.3-4.3" stroke="#25f4ee" stroke-width="3.4" stroke-linecap="round" stroke-linejoin="round"/><path d="M15.2 4c.6 3 2.3 4.8 5 5.4" stroke="#fe2c55" stroke-width="3.4" stroke-linecap="round"/><path d="M14 4v10.1a4.3 4.3 0 1 1-4.3-4.3" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/><path d="M15.2 4c.6 3 2.3 4.8 5 5.4" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></svg></span></div> <button class="subtle copy-btn" type="button" data-platform="tiktok">Copiar</button> </div> <textarea class="copy-text" id="copyTiktok" spellcheck="true"></textarea> </section> </div> </div> </section> </div> <div class="modal-backdrop" id="confirmModal" hidden> <section class="confirm-modal" role="dialog" aria-modal="true" aria-labelledby="confirmTitle" aria-describedby="confirmText"> <div class="confirm-body"> <h3 id="confirmTitle">Confirmar acción</h3> <p id="confirmText"></p> </div> <div class="confirm-actions"> <button class="secondary" id="confirmCancel" type="button">Cancelar</button> <button id="confirmAccept" type="button">Aceptar</button> </div> </section> </div> <script> const state = { programs: [], currentProgram: null, clips: [], current: null, subtitles: [], dirty: false, jobTimer: null, search: { query: '', matches: [], current: -1 }, pendingConfirm: null, programMenuOpen: false, copyDirty: false, socialCopy: { instagram: '', twitter: '', tiktok: '' }, clipCache: new Map(), clipPromises: new Map(), subtitleCache: new Map(), subtitlePromises: new Map() }; const els = { programName: document.getElementById('programName'), programDropdown: document.getElementById('programDropdown'), programTrigger: document.getElementById('programTrigger'), programTriggerText: document.getElementById('programTriggerText'), programMenu: document.getElementById('programMenu'), clipList: document.getElementById('clipList'), video: document.getElementById('video'), rows: document.getElementById('rows'), clipTitle: document.getElementById('clipTitle'), saveBtn: document.getElementById('saveBtn'), regenBtn: document.getElementById('regenBtn'), downloadBtn: document.getElementById('downloadBtn'), reloadBtn: document.getElementById('reloadBtn'), addSubBtn: document.getElementById('addSubBtn'), openBtn: document.getElementById('openBtn'), searchInput: document.getElementById('searchInput'), searchCount: document.getElementById('searchCount'), prevMatchBtn: document.getElementById('prevMatchBtn'), nextMatchBtn: document.getElementById('nextMatchBtn'), clearSearchBtn: document.getElementById('clearSearchBtn'), saveCopyBtn: document.getElementById('saveCopyBtn'), copyInstagram: document.getElementById('copyInstagram'), copyTwitter: document.getElementById('copyTwitter'), copyTiktok: document.getElementById('copyTiktok'), copyButtons: document.querySelectorAll('.copy-btn'), confirmModal: document.getElementById('confirmModal'), confirmTitle: document.getElementById('confirmTitle'), confirmText: document.getElementById('confirmText'), confirmCancel: document.getElementById('confirmCancel'), confirmAccept: document.getElementById('confirmAccept'), status: document.getElementById('status') }; function setStatus(text, type = '') { els.status.textContent = text; els.status.className = 'status ' + type; } function friendlyJobMessage(job) { if (job.status === 'error' && job.error) return job.error; if (job.message) return job.message; if (job.status === 'queued') return 'Esperando para empezar...'; if (job.status === 'running') return 'Regenerando el clip. Puede tardar unos minutos...'; if (job.status === 'done') return 'Clip regenerado. Ya podés revisarlo arriba.'; if (job.status === 'error') return 'No se pudo regenerar el clip.'; return 'Preparando...'; } async function api(path, options = {}) { const res = await fetch(path, { headers: { 'Content-Type': 'application/json' }, ...options }); const body = await res.json().catch(() => ({})); if (!res.ok) throw new Error(body.error || res.statusText); return body; } function setConfirmOpen(open) { els.confirmModal.hidden = !open; document.body.classList.toggle('modal-open', open); } function askConfirm({ title = 'Confirmar acción', message = '', confirmText = 'Aceptar', cancelText = 'Cancelar', danger = false } = {}) { return new Promise(resolve => { state.pendingConfirm = resolve; els.confirmTitle.textContent = title; els.confirmText.textContent = message; els.confirmAccept.textContent = confirmText; els.confirmCancel.textContent = cancelText; els.confirmAccept.classList.toggle('danger', danger); setConfirmOpen(true); window.setTimeout(() => els.confirmCancel.focus(), 0); }); } function closeConfirm(result) { if (!state.pendingConfirm) return; const resolve = state.pendingConfirm; state.pendingConfirm = null; setConfirmOpen(false); resolve(Boolean(result)); } function clipLabel(clip) { return clip.title.replace(/_/g, ' '); } function programQuery() { return state.currentProgram ? `program=${encodeURIComponent(state.currentProgram)}` : ''; } function apiWithProgram(path) { const query = programQuery(); return query ? `${path}?${query}` : path; } function apiPathWithProgram(path, programId) { return programId ? `${path}?program=${encodeURIComponent(programId)}` : path; } function subtitleCacheKey(programId, clipId) { return `${programId || ''}::${clipId}`; } async function getClipData(programId) { if (state.clipCache.has(programId)) return state.clipCache.get(programId); if (state.clipPromises.has(programId)) return state.clipPromises.get(programId); const request = api(apiPathWithProgram('/api/clips', programId)) .then(data => { state.clipCache.set(programId, data); return data; }) .finally(() => state.clipPromises.delete(programId)); state.clipPromises.set(programId, request); return request; } async function getSubtitleData(programId, clipId) { const key = subtitleCacheKey(programId, clipId); if (state.subtitleCache.has(key)) return state.subtitleCache.get(key); if (state.subtitlePromises.has(key)) return state.subtitlePromises.get(key); const request = api(apiPathWithProgram(`/api/clips/${encodeURIComponent(clipId)}/subtitles`, programId)) .then(data => { state.subtitleCache.set(key, data); return data; }) .finally(() => state.subtitlePromises.delete(key)); state.subtitlePromises.set(key, request); return request; } function prefetchProgram(programId) { if (!programId || state.clipCache.has(programId) || state.clipPromises.has(programId)) return; getClipData(programId) .then(data => { const firstClip = data.clips && data.clips[0]; if (firstClip) getSubtitleData(programId, firstClip.id).catch(() => {}); }) .catch(() => {}); } function prefetchOtherPrograms() { const programs = state.programs .map(program => program.id) .filter(programId => programId && programId !== state.currentProgram); programs.forEach((programId, index) => { window.setTimeout(() => prefetchProgram(programId), index * 150); }); } function clearClientCaches() { state.clipCache.clear(); state.clipPromises.clear(); state.subtitleCache.clear(); state.subtitlePromises.clear(); } function hasUnsavedChanges() { return state.dirty || state.copyDirty; } function currentProgram() { return state.programs.find(program => program.id === state.currentProgram) || null; } function formatProgramMeta(program) { const parts = []; if (program.program_date) parts.push(program.program_date.split('-').reverse().join('/')); parts.push(`${program.clip_count} clips`); return parts.join(' · '); } function setProgramMenuOpen(open) { state.programMenuOpen = open && state.programs.length > 1; els.programMenu.hidden = !state.programMenuOpen; els.programTrigger.setAttribute('aria-expanded', state.programMenuOpen ? 'true' : 'false'); } function renderProgramSelect() { const selected = currentProgram(); els.programTriggerText.innerHTML = selected ? `<span class="program-trigger-title">${escapeHtml(selected.name)}</span><span class="program-trigger-meta">${escapeHtml(formatProgramMeta(selected))}</span>` : '<span class="program-trigger-title">Elegir programa</span>'; els.programTrigger.title = selected ? selected.name : ''; els.programTrigger.disabled = state.programs.length <= 1; els.programMenu.innerHTML = ''; state.programs.forEach(program => { const option = document.createElement('button'); option.type = 'button'; option.className = 'program-option' + (program.id === state.currentProgram ? ' active' : ''); option.setAttribute('role', 'option'); option.setAttribute('aria-selected', program.id === state.currentProgram ? 'true' : 'false'); option.innerHTML = ` <span> <span class="program-option-title">${escapeHtml(program.name)}</span> <span class="program-option-meta">${escapeHtml(formatProgramMeta(program))}</span> </span> <span class="program-option-check" aria-hidden="true">✓</span>`; option.onmouseenter = () => prefetchProgram(program.id); option.onfocus = () => prefetchProgram(program.id); option.onclick = () => chooseProgram(program.id); els.programMenu.appendChild(option); }); if (state.programs.length <= 1) { setProgramMenuOpen(false); } } async function chooseProgram(programId) { if (!programId || programId === state.currentProgram) { setProgramMenuOpen(false); return; } if (hasUnsavedChanges() && !(await askConfirm({ title: 'Cambios sin guardar', message: 'Hay cambios sin guardar. Si continuás, se van a descartar.', confirmText: 'Continuar', cancelText: 'Volver' }))) { renderProgramSelect(); return; } setProgramMenuOpen(false); state.currentProgram = programId; state.current = null; state.dirty = false; state.copyDirty = false; renderProgramSelect(); setStatus(state.clipCache.has(programId) ? 'Cargando programa...' : 'Cargando clips del programa...', ''); await loadClips(); } function renderClipList() { els.clipList.innerHTML = ''; state.clips.forEach((clip, index) => { const btn = document.createElement('button'); btn.className = 'clip-button' + (state.current && state.current.id === clip.id ? ' active' : ''); btn.innerHTML = ` <span class="num">${String(index + 1).padStart(2, '0')}</span> <span class="clip-copy"> <span class="clip-title">${escapeHtml(clipLabel(clip))}</span> <span class="clip-meta">${clip.has_output ? 'MP4 listo' : 'sin MP4 final'} - ${clip.subtitle_count} líneas</span> </span>`; btn.onclick = () => selectClip(clip.id); els.clipList.appendChild(btn); }); } function escapeHtml(value) { return String(value) .replaceAll('&', '&amp;') .replaceAll('<', '&lt;') .replaceAll('>', '&gt;') .replaceAll('"', '&quot;'); } function timeToSeconds(value) { const raw = String(value || '').trim().replace(',', '.'); if (!raw) return NaN; if (!raw.includes(':')) return Number(raw); const parts = raw.split(':').map(part => part.trim()); if (parts.length > 3 || parts.some(part => part === '')) return NaN; let seconds = Number(parts.pop()); let minutes = parts.length ? Number(parts.pop()) : 0; let hours = parts.length ? Number(parts.pop()) : 0; if (![seconds, minutes, hours].every(Number.isFinite)) return NaN; return hours * 3600 + minutes * 60 + seconds; } function formatTime(seconds) { const safe = Math.max(0, Number(seconds) || 0); const minutes = Math.floor(safe / 60); const rest = safe - minutes * 60; return `${String(minutes).padStart(2, '0')}:${rest.toFixed(2).padStart(5, '0')}`; } function markDirty() { state.dirty = true; } function normalizeSocialCopy(copy = {}) { return { instagram: String(copy.instagram || ''), twitter: String(copy.twitter || ''), tiktok: String(copy.tiktok || '') }; } function collectSocialCopy() { return { instagram: els.copyInstagram.value.trim(), twitter: els.copyTwitter.value.trim(), tiktok: els.copyTiktok.value.trim() }; } function renderSocialCopy(copy = {}) { state.socialCopy = normalizeSocialCopy(copy); els.copyInstagram.value = state.socialCopy.instagram; els.copyTwitter.value = state.socialCopy.twitter; els.copyTiktok.value = state.socialCopy.tiktok; state.copyDirty = false; } function markCopyDirty() { state.copyDirty = true; state.socialCopy = collectSocialCopy(); } async function saveSocialCopy() { if (!state.current) return; const socialCopy = collectSocialCopy(); await api(apiWithProgram(`/api/clips/${encodeURIComponent(state.current.id)}/social-copy`), { method: 'POST', body: JSON.stringify({ social_copy: socialCopy }) }); state.socialCopy = socialCopy; state.current.social_copy = socialCopy; const cached = state.clipCache.get(state.currentProgram); const cachedClip = cached?.clips?.find(clip => clip.id === state.current.id); if (cachedClip) cachedClip.social_copy = socialCopy; state.copyDirty = false; setStatus('Copies guardados.', 'ok'); } async function copySocialText(platform) { const value = collectSocialCopy()[platform] || ''; if (!value) return; await navigator.clipboard.writeText(value); const labels = { instagram: 'Instagram', twitter: 'X / Twitter', tiktok: 'TikTok' }; setStatus(`Copy de ${labels[platform]} copiado.`, 'ok'); } function validateAndNormalizeSubtitles() { const normalized = state.subtitles .map((sub, position) => { const startSeconds = timeToSeconds(sub.start); const endSeconds = timeToSeconds(sub.end); if (!Number.isFinite(startSeconds) || !Number.isFinite(endSeconds)) { throw new Error(`Revisá los tiempos de la línea ${position + 1}.`); } if (endSeconds <= startSeconds) { throw new Error(`El fin debe ser mayor al inicio en la línea ${position + 1}.`); } return { ...sub, start: formatTime(startSeconds), end: formatTime(endSeconds), _startSeconds: startSeconds }; }) .filter(sub => String(sub.text || '').trim()) .sort((a, b) => a._startSeconds - b._startSeconds) .map(({ _startSeconds, ...sub }) => sub); state.subtitles = normalized; return normalized; } function normalizeSearch(value) { return String(value) .normalize('NFD') .replace(/[\u0300-\u036f]/g, '') .toLowerCase() .trim(); } function resetSearch() { state.search.query = ''; state.search.matches = []; state.search.current = -1; els.searchInput.value = ''; applySearchState(); } function computeSearchMatches() { const query = normalizeSearch(state.search.query); if (!query) return []; const matches = []; state.subtitles.forEach((sub, index) => { if (normalizeSearch(sub.text).includes(query)) matches.push(index); }); return matches; } function applySearchState({ focus = false } = {}) { const query = normalizeSearch(state.search.query); state.search.matches = computeSearchMatches(); if (!query || !state.search.matches.length) { state.search.current = -1; } else if (!state.search.matches.includes(state.search.current)) { state.search.current = state.search.matches[0]; } const currentPosition = state.search.matches.indexOf(state.search.current); els.searchCount.textContent = !query ? `${state.subtitles.length} líneas` : state.search.matches.length ? `${currentPosition + 1}/${state.search.matches.length}` : '0'; const hasMatches = Boolean(query && state.search.matches.length); els.prevMatchBtn.disabled = !hasMatches; els.nextMatchBtn.disabled = !hasMatches; els.clearSearchBtn.disabled = !query; els.rows.querySelectorAll('.sub-row').forEach(row => { const index = Number(row.dataset.index); row.classList.toggle('match', state.search.matches.includes(index)); row.classList.toggle('current-match', index === state.search.current); }); if (focus && hasMatches) focusCurrentMatch(); } function focusCurrentMatch() { const index = state.search.current; const row = els.rows.querySelector(`.sub-row[data-index="${index}"]`); const area = els.rows.querySelector(`textarea[data-index="${index}"]`); if (!row || !area) return; row.scrollIntoView({ block: 'center', behavior: 'smooth' }); area.focus(); const query = state.search.query.toLowerCase().trim(); const position = area.value.toLowerCase().indexOf(query); if (position >= 0) { area.setSelectionRange(position, position + query.length); } } function moveSearch(direction) { if (!state.search.query) return; applySearchState(); if (!state.search.matches.length) return; const currentPosition = Math.max(0, state.search.matches.indexOf(state.search.current)); const nextPosition = (currentPosition + direction + state.search.matches.length) % state.search.matches.length; state.search.current = state.search.matches[nextPosition]; applySearchState({ focus: true }); } async function loadPrograms() { const data = await api('/api/programs'); state.programs = data.programs; if (!state.programs.length) { els.programName.textContent = ''; els.programName.title = ''; renderProgramSelect(); setStatus('No hay programas con clips.', 'bad'); return; } if (!state.currentProgram || !state.programs.some(p => p.id === state.currentProgram)) { state.currentProgram = state.programs[0].id; } renderProgramSelect(); prefetchOtherPrograms(); await loadClips(); prefetchOtherPrograms(); } async function loadClips(preferredClipId = null) { const programId = state.currentProgram; const data = await getClipData(programId); if (programId !== state.currentProgram) return; els.programName.textContent = data.program_name; els.programName.title = data.program_name; state.clips = data.clips; renderClipList(); if (state.clips.length) { const nextId = preferredClipId && state.clips.some(c => c.id === preferredClipId) ? preferredClipId : state.current && state.clips.some(c => c.id === state.current.id) ? state.current.id : state.clips[0].id; await selectClip(nextId); } else { state.current = null; state.subtitles = []; renderRows(); setStatus('No hay clips en este programa.', 'bad'); } } async function selectClip(id) { const programId = state.currentProgram; if (hasUnsavedChanges() && !(await askConfirm({ title: 'Cambios sin guardar', message: 'Hay cambios sin guardar. Si continuás, se van a descartar.', confirmText: 'Continuar', cancelText: 'Volver' }))) return; const clip = state.clips.find(c => c.id === id); state.current = clip; state.dirty = false; renderSocialCopy(clip.social_copy); renderClipList(); els.clipTitle.textContent = clipLabel(clip); els.video.src = clip.video_url; els.openBtn.disabled = !clip.has_output; els.openBtn.onclick = () => window.open(clip.output_url || clip.video_url, '_blank'); els.downloadBtn.disabled = !clip.has_output; els.downloadBtn.onclick = () => { if (clip.download_url) window.location.href = clip.download_url; }; const data = await getSubtitleData(programId, id); if (programId !== state.currentProgram || !state.current || state.current.id !== id) return; state.subtitles = data.subtitles; renderRows(); resetSearch(); setStatus(`${state.subtitles.length} subtítulos cargados.`, 'ok'); } function renderRows() { els.rows.innerHTML = ''; state.subtitles.forEach((sub, index) => { const row = document.createElement('div'); row.className = 'sub-row'; row.dataset.index = index; const time = document.createElement('div'); time.className = 'time'; time.innerHTML = ` <span class="line-num">Línea ${String(index + 1).padStart(2, '0')}</span> <label>Inicio <input class="time-input" data-index="${index}" data-field="start" value="${escapeHtml(sub.start)}" inputmode="decimal"> </label> <label>Fin <input class="time-input" data-index="${index}" data-field="end" value="${escapeHtml(sub.end)}" inputmode="decimal"> </label>`; time.querySelectorAll('.time-input').forEach(input => { input.addEventListener('input', () => { state.subtitles[index][input.dataset.field] = input.value; markDirty(); }); input.addEventListener('blur', () => { const seconds = timeToSeconds(input.value); if (Number.isFinite(seconds)) input.value = formatTime(seconds); state.subtitles[index][input.dataset.field] = input.value; }); }); const main = document.createElement('div'); main.className = 'sub-main'; const area = document.createElement('textarea'); area.value = sub.text; area.dataset.index = index; area.addEventListener('input', () => { state.subtitles[index].text = area.value; markDirty(); if (state.search.query) applySearchState(); }); const rowActions = document.createElement('div'); rowActions.className = 'row-actions'; const addBtn = document.createElement('button'); addBtn.className = 'subtle'; addBtn.type = 'button'; addBtn.textContent = 'Agregar debajo'; addBtn.onclick = () => addSubtitle(index); const deleteBtn = document.createElement('button'); deleteBtn.className = 'subtle'; deleteBtn.type = 'button'; deleteBtn.textContent = 'Borrar'; deleteBtn.onclick = () => deleteSubtitle(index).catch(err => setStatus(err.message, 'bad')); rowActions.appendChild(addBtn); rowActions.appendChild(deleteBtn); main.appendChild(area); main.appendChild(rowActions); row.appendChild(time); row.appendChild(main); els.rows.appendChild(row); }); applySearchState(); } function addSubtitle(afterIndex = null) { const current = Number.isFinite(els.video.currentTime) ? els.video.currentTime : 0; const base = afterIndex === null ? current : Math.max(current, timeToSeconds(state.subtitles[afterIndex]?.end) || current); const sub = { index: null, start: formatTime(base), end: formatTime(base + 2), text: '' }; const insertAt = afterIndex === null ? state.subtitles.length : afterIndex + 1; state.subtitles.splice(insertAt, 0, sub); markDirty(); renderRows(); const area = els.rows.querySelector(`textarea[data-index="${insertAt}"]`); if (area) { area.scrollIntoView({ block: 'center', behavior: 'smooth' }); area.focus(); } setStatus('Línea nueva creada. Ajustá inicio, fin y texto.', 'ok'); } async function deleteSubtitle(index) { if (!(await askConfirm({ title: 'Borrar línea', message: '¿Querés borrar esta línea de subtítulos?', confirmText: 'Borrar', cancelText: 'Cancelar', danger: true }))) return; state.subtitles.splice(index, 1); markDirty(); renderRows(); setStatus('Línea borrada. Guardá o regenerá para aplicar el cambio.', 'ok'); } async function saveSubtitles() { if (!state.current) return; const subtitles = validateAndNormalizeSubtitles(); await api(apiWithProgram(`/api/clips/${encodeURIComponent(state.current.id)}/subtitles`), { method: 'POST', body: JSON.stringify({ subtitles }) }); state.subtitleCache.set(subtitleCacheKey(state.currentProgram, state.current.id), { subtitles }); const cached = state.clipCache.get(state.currentProgram); const cachedClip = cached?.clips?.find(clip => clip.id === state.current.id); if (cachedClip) cachedClip.subtitle_count = subtitles.length; state.current.subtitle_count = subtitles.length; state.dirty = false; renderClipList(); renderRows(); setStatus('Subtítulos guardados.', 'ok'); } async function regenerateClip() { if (!state.current) return; els.regenBtn.disabled = true; els.saveBtn.disabled = true; setStatus('Preparando el clip...', 'busy'); const hadSubtitleChanges = state.dirty; if (hadSubtitleChanges) await saveSubtitles(); const data = await api(apiWithProgram(`/api/clips/${encodeURIComponent(state.current.id)}/regenerate`), { method: 'POST', body: JSON.stringify({}) }); pollJob(data.job_id); } async function pollJob(jobId) { clearInterval(state.jobTimer); const tick = async () => { const job = await api(`/api/jobs/${encodeURIComponent(jobId)}`); setStatus(friendlyJobMessage(job), job.status === 'error' ? 'bad' : 'busy'); if (job.status === 'done' || job.status === 'error') { clearInterval(state.jobTimer); els.regenBtn.disabled = false; els.saveBtn.disabled = false; if (job.status === 'done') { const currentId = state.current ? state.current.id : null; state.clipCache.delete(state.currentProgram); if (currentId) state.subtitleCache.delete(subtitleCacheKey(state.currentProgram, currentId)); await loadClips(currentId); const clip = state.clips.find(c => c.id === currentId); if (clip) { els.video.src = clip.video_url + '&refresh=' + Date.now(); els.video.load(); } setStatus(friendlyJobMessage(job), 'ok'); } else { setStatus(friendlyJobMessage(job), 'bad'); if (job.technical_log) console.warn(job.technical_log); } } }; await tick(); state.jobTimer = setInterval(tick, 1500); } els.confirmCancel.onclick = () => closeConfirm(false); els.confirmAccept.onclick = () => closeConfirm(true); els.confirmModal.addEventListener('click', event => { if (event.target === els.confirmModal) closeConfirm(false); }); document.addEventListener('keydown', event => { if (!els.confirmModal.hidden && event.key === 'Escape') closeConfirm(false); }); els.saveBtn.onclick = () => saveSubtitles().catch(err => setStatus(err.message, 'bad')); els.saveCopyBtn.onclick = () => saveSocialCopy().catch(err => setStatus(err.message, 'bad')); [els.copyInstagram, els.copyTwitter, els.copyTiktok].forEach(input => { input.addEventListener('input', markCopyDirty); }); els.copyButtons.forEach(button => { button.addEventListener('click', () => copySocialText(button.dataset.platform).catch(err => setStatus(err.message, 'bad'))); }); els.addSubBtn.onclick = () => addSubtitle(); els.regenBtn.onclick = () => regenerateClip().catch(err => { els.regenBtn.disabled = false; els.saveBtn.disabled = false; setStatus(err.message, 'bad'); }); els.reloadBtn.onclick = () => { clearClientCaches(); loadPrograms().catch(err => setStatus(err.message, 'bad')); }; els.programTrigger.addEventListener('click', () => { setProgramMenuOpen(!state.programMenuOpen); if (state.programMenuOpen) prefetchOtherPrograms(); }); document.addEventListener('click', event => { if (!els.programDropdown.contains(event.target)) setProgramMenuOpen(false); }); document.addEventListener('keydown', event => { if (event.key === 'Escape') setProgramMenuOpen(false); }); els.searchInput.addEventListener('input', () => { state.search.query = els.searchInput.value; state.search.current = -1; applySearchState(); }); els.searchInput.addEventListener('keydown', event => { if (event.key !== 'Enter') return; event.preventDefault(); moveSearch(event.shiftKey ? -1 : 1); }); els.prevMatchBtn.onclick = () => moveSearch(-1); els.nextMatchBtn.onclick = () => moveSearch(1); els.clearSearchBtn.onclick = () => { resetSearch(); els.searchInput.focus(); }; window.addEventListener('beforeunload', event => { if (!hasUnsavedChanges()) return; event.preventDefault(); event.returnValue = ''; }); loadPrograms().catch(err => setStatus(err.message, 'bad')); </script> </body> </html> """ @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"(?<!\d)(\d{1,2})/(\d{1,2})(?:/(\d{2,4}))?(?!\d)", value) if not match: return None day = int(match.group(1)) month = int(match.group(2)) year_text = match.group(3) if year_text: year = int(year_text) if year < 100: year += 2000 else: year = today.year try: parsed = date(year, month, day) except ValueError: return None if not year_text and parsed > 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()
#!/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"""<!doctype html>
<html lang="es">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>PYD Clips</title>
<link rel="icon" type="image/png" href="/assets/pyd-favicon.png">
<link rel="apple-touch-icon" href="/assets/pyd-favicon.png">
<style>
:root {
color-scheme: light;
--bg: #f6f6f1;
--surface: #ffffff;
--surface-soft: #fbfaf7;
--ink: #171812;
--ink-soft: #34362d;
--muted: #797a70;
--line: #e7e3d8;
--line-strong: #d3cec0;
--rail: #11120e;
--rail-soft: #1a1b15;
--rail-line: #2d2f25;
--accent: #e6bd26;
--accent-ink: #231d00;
--accent-soft: #fff7d4;
--ok: #148957;
--ok-dark: #0d6f45;
--ok-soft: #eaf7ef;
--bad: #b2413a;
--radius: 8px;
--shadow: 0 18px 46px rgba(18, 18, 14, .12);
}
* { box-sizing: border-box; }
html {
background: var(--bg);
}
body {
margin: 0;
min-width: 1080px;
font: 14px/1.45 Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
background: var(--bg);
color: var(--ink);
letter-spacing: 0;
}
button, textarea, input {