Spaces:
Sleeping
Sleeping
Download subtitle_editor.py from Emirona07/clip-editor: direct link, hf CLI and curl.
- Browser
- Download file 66 kB
-
https://huggingface.co/spaces/Emirona07/clip-editor/resolve/main/subtitle_editor.py
- Command line
-
hf download hf://spaces/Emirona07/clip-editor/subtitle_editor.py
-
curl -L -o subtitle_editor.py https://huggingface.co/spaces/Emirona07/clip-editor/resolve/main/subtitle_editor.py
66 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 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"""<!doctype html>
<html lang="es">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Editor de subtitulos</title>
<style>
:root {
color-scheme: light;
--bg: #f4f5f4;
--surface: #ffffff;
--surface-soft: #f8f8f6;
--ink: #171714;
--ink-soft: #33332d;
--muted: #76766f;
--line: #e5e3dc;
--line-strong: #d2cfc4;
--rail: #151512;
--rail-soft: #20201b;
--rail-line: #303027;
--accent: #e2b600;
--accent-ink: #2b2400;
--accent-soft: #fff7d3;
--ok: #207a4b;
--bad: #b2413a;
--radius: 10px;
--shadow: 0 18px 48px rgba(15, 15, 12, .09);
}
* { box-sizing: border-box; }
html {
background: var(--bg);
}
body {
margin: 0;
min-width: 1120px;
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: 38px;
padding: 0 14px;
border-radius: var(--radius);
cursor: pointer;
font-weight: 760;
letter-spacing: 0;
white-space: nowrap;
transition: background .15s ease, border-color .15s ease, color .15s ease, opacity .15s ease, transform .15s ease;
}
button.secondary {
background: #fff;
color: var(--ink);
border-color: var(--line);
}
button.subtle {
min-height: 34px;
padding: 0 11px;
background: var(--surface-soft);
color: var(--ink-soft);
border-color: var(--line);
font-size: 12px;
}
button:hover:not(:disabled) {
background: #292925;
border-color: #292925;
transform: translateY(-1px);
}
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;
}
.shell {
display: grid;
grid-template-columns: 300px minmax(360px, 500px) minmax(520px, 1fr);
height: 100vh;
min-width: 0;
}
aside {
border-right: 1px solid var(--rail-line);
background: var(--rail);
color: #f7f4e7;
min-width: 0;
display: flex;
flex-direction: column;
}
.brand {
padding: 18px 18px 16px;
border-bottom: 1px solid var(--rail-line);
display: flex;
gap: 12px;
align-items: center;
min-height: 78px;
}
.mark {
width: 30px;
height: 30px;
border-radius: 9px;
background: var(--accent);
box-shadow: inset 0 -8px 0 rgba(0,0,0,.13);
flex: 0 0 auto;
}
h1, h2 {
margin: 0;
letter-spacing: 0;
}
h1 {
font-size: 17px;
line-height: 1.15;
font-weight: 820;
}
.program {
color: #a9a79a;
font-size: 12.5px;
margin-top: 4px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
max-width: 205px;
}
.program-picker {
padding: 13px 18px 15px;
border-bottom: 1px solid var(--rail-line);
display: grid;
gap: 8px;
}
.program-picker > span:first-child {
color: #a9a79a;
font-size: 11px;
font-weight: 780;
letter-spacing: .08em;
text-transform: uppercase;
}
.program-select-wrap {
position: relative;
display: block;
}
.program-select-wrap::after {
content: "";
position: absolute;
right: 13px;
top: 50%;
width: 8px;
height: 8px;
border-right: 2px solid #bfbcae;
border-bottom: 2px solid #bfbcae;
transform: translateY(-68%) rotate(45deg);
pointer-events: none;
}
select {
width: 100%;
min-height: 44px;
border: 1px solid var(--rail-line);
border-radius: 8px;
padding: 0 34px 0 13px;
background: var(--rail-soft);
color: #f7f4e7;
outline: 0;
font-size: 14px;
line-height: 1.25;
font-weight: 760;
appearance: none;
-webkit-appearance: none;
text-overflow: ellipsis;
}
select:focus {
border-color: var(--accent);
box-shadow: 0 0 0 3px rgba(226, 182, 0, .18);
}
.clip-list {
overflow: auto;
padding: 10px 10px 14px;
}
.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: 58px;
border-radius: 12px;
font-weight: 680;
}
.clip-button:hover {
background: var(--rail-soft);
}
.clip-button.active {
background: #fff;
color: var(--ink);
border-color: transparent;
}
.num {
width: 34px;
height: 34px;
border-radius: 9px;
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: 20px 22px;
border-right: 1px solid var(--line);
background:
linear-gradient(180deg, rgba(255,255,255,.76), rgba(255,255,255,.22)),
var(--bg);
overflow: auto;
}
.video-frame {
width: min(100%, 420px);
align-self: center;
border-radius: 16px;
background: #070706;
padding: 8px;
box-shadow: var(--shadow);
}
video {
width: 100%;
aspect-ratio: 9 / 16;
background: #050505;
border-radius: 10px;
border: 1px solid #050505;
display: block;
max-height: calc(100vh - 170px);
object-fit: contain;
}
.actions {
display: flex;
gap: 9px;
flex-wrap: wrap;
align-items: center;
width: min(100%, 420px);
align-self: center;
}
.status {
border: 1px solid var(--line);
background: rgba(255,255,255,.76);
border-radius: 12px;
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%, 420px);
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: 22px 24px 16px;
border-bottom: 1px solid var(--line);
display: grid;
gap: 16px;
background: rgba(255,255,255,.94);
backdrop-filter: blur(14px);
}
.title-row {
display: flex;
justify-content: space-between;
align-items: start;
gap: 16px;
}
.title-actions {
display: flex;
gap: 8px;
flex-wrap: wrap;
justify-content: flex-end;
}
.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: 20px;
line-height: 1.2;
font-weight: 850;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.search-tools {
display: grid;
grid-template-columns: minmax(190px, 1fr) auto auto auto auto;
gap: 8px;
align-items: center;
}
.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: 11px;
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 {
overflow: auto;
padding: 6px 24px 24px;
background: var(--surface);
}
.sub-row {
display: grid;
grid-template-columns: 150px minmax(0, 1fr);
gap: 16px;
padding: 12px;
margin: 8px 0;
border: 1px solid transparent;
border-radius: 14px;
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: 9px;
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: 12px;
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);
}
@media (max-width: 1180px) {
body {
min-width: 0;
}
.shell {
grid-template-columns: 1fr;
height: auto;
min-height: 100vh;
}
aside {
max-height: 270px;
border-right: 0;
border-bottom: 1px solid var(--line);
}
.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) {
.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;
}
.search-tools .match-count,
.search-tools #clearSearchBtn {
display: none;
}
}
</style>
</head>
<body>
<div class="shell">
<aside>
<div class="brand">
<div class="mark" aria-hidden="true"></div>
<div>
<h1>Editor de subtitulos</h1>
<div class="program" id="programName"></div>
</div>
</div>
<label class="program-picker">
<span>Programa</span>
<span class="program-select-wrap">
<select id="programSelect"></select>
</span>
</label>
<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="secondary" 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">Subtitulos</h2>
</div>
<div class="title-actions">
<button class="secondary" id="addSubBtn">Agregar linea</button>
<button class="secondary" id="openBtn">Abrir MP4</button>
</div>
</div>
<div class="search-tools">
<label class="search-box">
<input id="searchInput" type="search" placeholder="Buscar en subtitulos" 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>
<div class="rows" id="rows"></div>
</section>
</div>
<script>
const state = {
programs: [],
currentProgram: null,
clips: [],
current: null,
subtitles: [],
dirty: false,
jobTimer: null,
search: {
query: '',
matches: [],
current: -1
}
};
const els = {
programName: document.getElementById('programName'),
programSelect: document.getElementById('programSelect'),
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'),
status: document.getElementById('status')
};
function setStatus(text, type = '') {
els.status.textContent = text;
els.status.className = 'status ' + type;
}
function friendlyJobMessage(job) {
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 podes 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 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 renderProgramSelect() {
els.programSelect.innerHTML = '';
state.programs.forEach(program => {
const option = document.createElement('option');
option.value = program.id;
option.textContent = program.name;
option.selected = program.id === state.currentProgram;
els.programSelect.appendChild(option);
});
els.programSelect.disabled = state.programs.length <= 1;
}
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} lineas</span>
</span>`;
btn.onclick = () => selectClip(clip.id);
els.clipList.appendChild(btn);
});
}
function escapeHtml(value) {
return String(value)
.replaceAll('&', '&')
.replaceAll('<', '<')
.replaceAll('>', '>')
.replaceAll('"', '"');
}
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 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(`Revisa los tiempos de la linea ${position + 1}.`);
}
if (endSeconds <= startSeconds) {
throw new Error(`El fin debe ser mayor al inicio en la linea ${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} lineas`
: 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 = '';
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();
await loadClips();
}
async function loadClips(preferredClipId = null) {
const data = await api(apiWithProgram('/api/clips'));
els.programName.textContent = 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) {
if (state.dirty && !confirm('Hay cambios sin guardar. Continuar?')) return;
const clip = state.clips.find(c => c.id === id);
state.current = clip;
state.dirty = false;
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 api(apiWithProgram(`/api/clips/${encodeURIComponent(id)}/subtitles`));
state.subtitles = data.subtitles;
renderRows();
resetSearch();
setStatus(`${state.subtitles.length} subtitulos 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">Linea ${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);
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('Linea nueva creada. Ajusta inicio, fin y texto.', 'ok');
}
function deleteSubtitle(index) {
if (!confirm('Borrar esta linea de subtitulos?')) return;
state.subtitles.splice(index, 1);
markDirty();
renderRows();
setStatus('Linea borrada. Guarda o regenera 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.dirty = false;
renderRows();
setStatus('Subtitulos guardados.', 'ok');
}
async function regenerateClip() {
if (!state.current) return;
els.regenBtn.disabled = true;
els.saveBtn.disabled = true;
setStatus('Preparando el clip...', 'busy');
if (state.dirty) 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;
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.saveBtn.onclick = () => saveSubtitles().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 = () => loadPrograms().catch(err => setStatus(err.message, 'bad'));
els.programSelect.addEventListener('change', async () => {
if (state.dirty && !confirm('Hay cambios sin guardar. Continuar?')) {
renderProgramSelect();
return;
}
state.currentProgram = els.programSelect.value;
state.current = null;
state.dirty = false;
await loadClips();
});
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 (!state.dirty) 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
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()
#!/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"""<!doctype html>
<html lang="es">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Editor de subtitulos</title>
<style>
:root {
color-scheme: light;
--bg: #f4f5f4;
--surface: #ffffff;
--surface-soft: #f8f8f6;
--ink: #171714;
--ink-soft: #33332d;
--muted: #76766f;
--line: #e5e3dc;
--line-strong: #d2cfc4;
--rail: #151512;
--rail-soft: #20201b;
--rail-line: #303027;
--accent: #e2b600;
--accent-ink: #2b2400;
--accent-soft: #fff7d3;
--ok: #207a4b;
--bad: #b2413a;
--radius: 10px;
--shadow: 0 18px 48px rgba(15, 15, 12, .09);
}
* { box-sizing: border-box; }
html {
background: var(--bg);
}
body {
margin: 0;
min-width: 1120px;
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: 38px;
padding: 0 14px;
border-radius: var(--radius);
cursor: pointer;
font-weight: 760;