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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# ─── VCPro HLS Unified — versión Gradio / HuggingFace Spaces ────────────────
|
| 2 |
+
# Misma lógica de negocio que la app de escritorio (Tkinter), reescrita para
|
| 3 |
+
# correr como una HuggingFace Space con interfaz Gradio.
|
| 4 |
+
# ──────────────────────────────────────────────────────────────────────────
|
| 5 |
+
|
| 6 |
+
import sys, os, subprocess, threading, shutil, re, json, time, uuid, zipfile
|
| 7 |
+
import tarfile, queue, traceback
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
from concurrent.futures import ThreadPoolExecutor, as_completed
|
| 10 |
+
import unicodedata, urllib.request, urllib.parse
|
| 11 |
+
|
| 12 |
+
import gradio as gr
|
| 13 |
+
import spaces
|
| 14 |
+
|
| 15 |
+
# ─── DEPENDENCIAS ────────────────────────────────────────────────────────────
|
| 16 |
+
_NO_WINDOW = subprocess.CREATE_NO_WINDOW if os.name == "nt" else 0
|
| 17 |
+
|
| 18 |
+
def _pip_install(pkg):
|
| 19 |
+
subprocess.check_call(
|
| 20 |
+
[sys.executable, "-m", "pip", "install", "-U", pkg, "-q"],
|
| 21 |
+
)
|
| 22 |
+
|
| 23 |
+
HF_OK = False
|
| 24 |
+
try:
|
| 25 |
+
from huggingface_hub import HfApi, create_bucket, sync_bucket, list_buckets, list_bucket_tree
|
| 26 |
+
HF_OK = True
|
| 27 |
+
except ImportError:
|
| 28 |
+
try:
|
| 29 |
+
_pip_install("huggingface_hub")
|
| 30 |
+
from huggingface_hub import HfApi, create_bucket, sync_bucket, list_buckets, list_bucket_tree
|
| 31 |
+
HF_OK = True
|
| 32 |
+
except Exception:
|
| 33 |
+
HF_OK = False
|
| 34 |
+
|
| 35 |
+
try:
|
| 36 |
+
import requests
|
| 37 |
+
except ImportError:
|
| 38 |
+
try:
|
| 39 |
+
_pip_install("requests")
|
| 40 |
+
import requests
|
| 41 |
+
except Exception:
|
| 42 |
+
requests = None # GitHub upload will warn if missing
|
| 43 |
+
|
| 44 |
+
# ─── ARIA2C (BitTorrent — sin dependencias Python) ───────────────────────────
|
| 45 |
+
# En una Space (Linux), lo más fiable es agregar "aria2" a packages.txt para
|
| 46 |
+
# que el propio Space lo instale vía apt al construir la imagen. Como respaldo,
|
| 47 |
+
# intentamos localizarlo en PATH o descargar un binario estático (Linux/Win).
|
| 48 |
+
BASE_DIR = Path(__file__).parent.resolve()
|
| 49 |
+
ARIA2_DIR = BASE_DIR / "_aria2"
|
| 50 |
+
ARIA2_EXE = ARIA2_DIR / ("aria2c.exe" if os.name == "nt" else "aria2c")
|
| 51 |
+
|
| 52 |
+
_ARIA2_WIN_URL = ("https://github.com/aria2/aria2/releases/download/release-1.37.0/"
|
| 53 |
+
"aria2-1.37.0-win-64bit-build1.zip")
|
| 54 |
+
_ARIA2_LINUX_URL = ("https://github.com/aria2/aria2/releases/download/release-1.37.0/"
|
| 55 |
+
"aria2-1.37.0-linux-gnu-64bit-build1.tar.bz2")
|
| 56 |
+
|
| 57 |
+
def _find_aria2():
|
| 58 |
+
if ARIA2_EXE.exists():
|
| 59 |
+
return str(ARIA2_EXE)
|
| 60 |
+
found = shutil.which("aria2c")
|
| 61 |
+
return found
|
| 62 |
+
|
| 63 |
+
def _download_aria2(log_cb):
|
| 64 |
+
ARIA2_DIR.mkdir(parents=True, exist_ok=True)
|
| 65 |
+
if os.name == "nt":
|
| 66 |
+
log_cb("[Torrent] Descargando aria2c (Windows) desde GitHub...")
|
| 67 |
+
tmp_zip = ARIA2_DIR / "aria2.zip"
|
| 68 |
+
try:
|
| 69 |
+
urllib.request.urlretrieve(_ARIA2_WIN_URL, tmp_zip)
|
| 70 |
+
with zipfile.ZipFile(tmp_zip, "r") as z:
|
| 71 |
+
for member in z.namelist():
|
| 72 |
+
if member.endswith("aria2c.exe"):
|
| 73 |
+
ARIA2_EXE.write_bytes(z.read(member))
|
| 74 |
+
break
|
| 75 |
+
tmp_zip.unlink(missing_ok=True)
|
| 76 |
+
except Exception as e:
|
| 77 |
+
log_cb(f"[X] Error descargando aria2c: {e}")
|
| 78 |
+
return False
|
| 79 |
+
else:
|
| 80 |
+
log_cb("[Torrent] aria2c no encontrado. Intentando descargar binario estático (Linux)...")
|
| 81 |
+
tmp_tar = ARIA2_DIR / "aria2.tar.bz2"
|
| 82 |
+
try:
|
| 83 |
+
urllib.request.urlretrieve(_ARIA2_LINUX_URL, tmp_tar)
|
| 84 |
+
with tarfile.open(tmp_tar, "r:bz2") as t:
|
| 85 |
+
for member in t.getmembers():
|
| 86 |
+
if member.name.endswith("/aria2c") or member.name == "aria2c":
|
| 87 |
+
f = t.extractfile(member)
|
| 88 |
+
if f:
|
| 89 |
+
ARIA2_EXE.write_bytes(f.read())
|
| 90 |
+
ARIA2_EXE.chmod(0o755)
|
| 91 |
+
break
|
| 92 |
+
tmp_tar.unlink(missing_ok=True)
|
| 93 |
+
except Exception as e:
|
| 94 |
+
log_cb(f"[X] No se pudo descargar aria2c automáticamente: {e}")
|
| 95 |
+
log_cb("[Torrent] Agrega una línea 'aria2' al archivo packages.txt de "
|
| 96 |
+
"esta Space y reinicia; apt lo instalará al construir la imagen.")
|
| 97 |
+
return False
|
| 98 |
+
|
| 99 |
+
if ARIA2_EXE.exists():
|
| 100 |
+
log_cb("[Torrent] aria2c descargado correctamente.")
|
| 101 |
+
return True
|
| 102 |
+
log_cb("[X] No se encontró aria2c tras el intento de descarga.")
|
| 103 |
+
return False
|
| 104 |
+
|
| 105 |
+
def _ensure_aria2(log_cb=None):
|
| 106 |
+
_msg = log_cb or (lambda m: None)
|
| 107 |
+
path = _find_aria2()
|
| 108 |
+
if path:
|
| 109 |
+
return path
|
| 110 |
+
_msg("[Torrent] aria2c no encontrado, intentando resolverlo automáticamente...")
|
| 111 |
+
ok = _download_aria2(_msg)
|
| 112 |
+
if ok:
|
| 113 |
+
path = _find_aria2()
|
| 114 |
+
if not path:
|
| 115 |
+
_msg("[X] aria2c no disponible. La descarga por torrent no funcionará.")
|
| 116 |
+
return path
|
| 117 |
+
|
| 118 |
+
LT_OK = bool(_find_aria2())
|
| 119 |
+
|
| 120 |
+
# ─── CONSTANTES ──────────────────────────────────────────────────────────────
|
| 121 |
+
TMDB_KEY = "3633a0416ea666f002ec317f40bdcf58"
|
| 122 |
+
|
| 123 |
+
RENDER_PROFILES = {
|
| 124 |
+
720: {"label": "720p", "bitrate": "2800k", "maxrate": "3000k",
|
| 125 |
+
"bufsize": "6000k", "level": "4.0", "codec_tag": "avc1.4d4020"},
|
| 126 |
+
1080: {"label": "1080p", "bitrate": "5000k", "maxrate": "5350k",
|
| 127 |
+
"bufsize": "10700k", "level": "4.1", "codec_tag": "avc1.640029"},
|
| 128 |
+
2160: {"label": "2160p (4K, opcional)", "bitrate": "14000k", "maxrate": "15000k",
|
| 129 |
+
"bufsize": "30000k", "level": "5.1", "codec_tag": "avc1.640033"},
|
| 130 |
+
}
|
| 131 |
+
AUDIO_BITRATE = "128k"
|
| 132 |
+
AUDIO_RATE = "48000"
|
| 133 |
+
HLS_SEG_SECONDS = "6"
|
| 134 |
+
AUTO_THUMB_COUNT = 100
|
| 135 |
+
|
| 136 |
+
# ─── HERRAMIENTAS EXTERNAS ───────────────────────────────────────────────────
|
| 137 |
+
def _get_bin(names, folder=""):
|
| 138 |
+
sd = BASE_DIR
|
| 139 |
+
for n in names:
|
| 140 |
+
if (sd / n).exists(): return str(sd / n)
|
| 141 |
+
if folder and (sd / folder).exists():
|
| 142 |
+
for n in names:
|
| 143 |
+
if (sd / folder / n).exists(): return str(sd / folder / n)
|
| 144 |
+
for n in names:
|
| 145 |
+
if shutil.which(n): return n
|
| 146 |
+
return None
|
| 147 |
+
|
| 148 |
+
FFMPEG_PATH = _get_bin(["ffmpeg.exe", "ffmpeg"])
|
| 149 |
+
FFPROBE_PATH = _get_bin(["ffprobe.exe", "ffprobe"])
|
| 150 |
+
FFMPEG_OK = bool(FFMPEG_PATH and FFPROBE_PATH)
|
| 151 |
+
YTDLP_PATH = _get_bin(["yt-dlp.exe", "yt-dlp"], "yt-dlp")
|
| 152 |
+
YTDLP_OK = bool(YTDLP_PATH)
|
| 153 |
+
|
| 154 |
+
VIDEO_EXTS = {".mp4",".mkv",".avi",".mov",".ts",".m2ts",".wmv",".flv",".webm",".mpg",".mpeg"}
|
| 155 |
+
|
| 156 |
+
def safe_name(s, maxlen=120):
|
| 157 |
+
if not s: return "video"
|
| 158 |
+
s = "".join(c for c in unicodedata.normalize("NFD", s) if unicodedata.category(c) != "Mn")
|
| 159 |
+
s = s.replace(" ", "_")
|
| 160 |
+
s = re.sub(r'_+', '_', s)
|
| 161 |
+
return re.sub(r'[<>:"/\\|?*\x00-\x1f]', "_", s).strip("_")[:maxlen]
|
| 162 |
+
|
| 163 |
+
def to_leet(text):
|
| 164 |
+
if not text: return "video"
|
| 165 |
+
rep = {"a":"4","A":"4","i":"1","I":"1","t":"7","T":"7","o":"0","O":"0","e":"3","E":"3"}
|
| 166 |
+
return safe_name("".join(rep.get(c, c) for c in text))
|
| 167 |
+
|
| 168 |
+
def clean_repo(n):
|
| 169 |
+
n = re.sub(r"[^a-zA-Z0-9_-]", "-", n)
|
| 170 |
+
return re.sub(r"-+", "-", n).strip("-")[:100]
|
| 171 |
+
|
| 172 |
+
def fmt_dur(secs):
|
| 173 |
+
s = int(secs)
|
| 174 |
+
return f"{s//3600:02d}:{(s%3600)//60:02d}:{s%60:02d}"
|
| 175 |
+
|
| 176 |
+
def fmt_size(b):
|
| 177 |
+
if b < 1024: return f"{b} B"
|
| 178 |
+
if b < 1024**2: return f"{b/1024:.1f} KB"
|
| 179 |
+
if b < 1024**3: return f"{b/1024**2:.1f} MB"
|
| 180 |
+
return f"{b/1024**3:.2f} GB"
|
| 181 |
+
|
| 182 |
+
# ─── DIAGNÓSTICO DE CRASHES A NIVEL WINDOWS (NTSTATUS) ───────────────────────
|
| 183 |
+
_WIN_NTSTATUS_HINTS = {
|
| 184 |
+
0xC0000005: "ACCESS_VIOLATION — el proceso crasheó al iniciar (build corrupto, incompleto).",
|
| 185 |
+
0xC0000135: "DLL_NOT_FOUND — falta una DLL que el ejecutable necesita para arrancar.",
|
| 186 |
+
0xC0000138: "ORDINAL_NOT_FOUND — hay una DLL presente pero de versión incompatible.",
|
| 187 |
+
0xC0000139: "ENTRY_POINT_NOT_FOUND — una DLL cargada no tiene la función esperada.",
|
| 188 |
+
0xC000007B: "INVALID_IMAGE_FORMAT — arquitectura incorrecta.",
|
| 189 |
+
0xC0000409: "STACK_BUFFER_OVERRUN — el proceso crasheó de forma anómala.",
|
| 190 |
+
}
|
| 191 |
+
|
| 192 |
+
def _decode_return_code(code):
|
| 193 |
+
try:
|
| 194 |
+
code = int(code)
|
| 195 |
+
except Exception:
|
| 196 |
+
return None
|
| 197 |
+
unsigned = code + (1 << 32) if code < 0 else code
|
| 198 |
+
if unsigned >= 0xC0000000:
|
| 199 |
+
hexcode = f"0x{unsigned:08X}"
|
| 200 |
+
hint = _WIN_NTSTATUS_HINTS.get(unsigned)
|
| 201 |
+
if not hint:
|
| 202 |
+
hint = "el proceso crasheó a nivel de Windows antes de poder ejecutarse."
|
| 203 |
+
return (f"{hexcode} → {hint}\n")
|
| 204 |
+
return None
|
| 205 |
+
|
| 206 |
+
def fetch_tmdb(url):
|
| 207 |
+
req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"})
|
| 208 |
+
try:
|
| 209 |
+
ctx = None
|
| 210 |
+
try:
|
| 211 |
+
import ssl, certifi
|
| 212 |
+
ctx = ssl.create_default_context(cafile=certifi.where())
|
| 213 |
+
except Exception:
|
| 214 |
+
ctx = None
|
| 215 |
+
with urllib.request.urlopen(req, timeout=12, context=ctx) as r:
|
| 216 |
+
raw = r.read().decode()
|
| 217 |
+
return json.loads(raw)
|
| 218 |
+
except urllib.error.HTTPError as e:
|
| 219 |
+
body = ""
|
| 220 |
+
try: body = e.read().decode()[:200]
|
| 221 |
+
except Exception: pass
|
| 222 |
+
if e.code == 401:
|
| 223 |
+
raise RuntimeError("API key de TMDb inválida o revocada.") from e
|
| 224 |
+
raise RuntimeError(f"TMDb HTTP {e.code}: {body or e.reason}") from e
|
| 225 |
+
except urllib.error.URLError as e:
|
| 226 |
+
raise RuntimeError(f"Sin conexión a TMDb: {e.reason}") from e
|
| 227 |
+
except TimeoutError:
|
| 228 |
+
raise RuntimeError("TMDb no respondió a tiempo (timeout).")
|
| 229 |
+
except json.JSONDecodeError as e:
|
| 230 |
+
raise RuntimeError(f"TMDb devolvió una respuesta no válida: {e}") from e
|
| 231 |
+
|
| 232 |
+
def _even(n):
|
| 233 |
+
n = int(n)
|
| 234 |
+
return n if n % 2 == 0 else n - 1
|
| 235 |
+
|
| 236 |
+
def _calc_width(src_w, src_h, target_h):
|
| 237 |
+
if not src_w or not src_h:
|
| 238 |
+
return _even(target_h * 16 // 9)
|
| 239 |
+
w = target_h * (src_w / src_h)
|
| 240 |
+
return max(2, _even(round(w)))
|
| 241 |
+
|
| 242 |
+
# ─── FFPROBE ──────────────────────────────────────────────────────────────────
|
| 243 |
+
def probe(source, log_cb):
|
| 244 |
+
info = {"audio": [], "subs": [], "duration": 0.0, "title": "",
|
| 245 |
+
"bit_rate": 0, "width": 0, "height": 0}
|
| 246 |
+
|
| 247 |
+
if not re.match(r"^[a-zA-Z][a-zA-Z0-9+.\-]*://", str(source)):
|
| 248 |
+
p = Path(source)
|
| 249 |
+
if not p.exists():
|
| 250 |
+
log_cb(f"[X] ffprobe: el archivo no existe → {source}")
|
| 251 |
+
return info
|
| 252 |
+
try:
|
| 253 |
+
if p.stat().st_size <= 0:
|
| 254 |
+
log_cb(f"[X] ffprobe: el archivo está vacío (0 bytes) → {source}")
|
| 255 |
+
return info
|
| 256 |
+
except Exception:
|
| 257 |
+
pass
|
| 258 |
+
|
| 259 |
+
if not (FFPROBE_PATH or shutil.which("ffprobe")):
|
| 260 |
+
log_cb("[X] ffprobe: no se encontró el ejecutable ffprobe")
|
| 261 |
+
return info
|
| 262 |
+
|
| 263 |
+
try:
|
| 264 |
+
cmd = [FFPROBE_PATH or "ffprobe", "-v", "error",
|
| 265 |
+
"-print_format", "json", "-show_format", "-show_streams", source]
|
| 266 |
+
r = subprocess.run(cmd, capture_output=True, text=True, timeout=60,
|
| 267 |
+
creationflags=_NO_WINDOW)
|
| 268 |
+
if r.returncode != 0:
|
| 269 |
+
err_detail = (r.stderr or r.stdout or "(sin salida de error)").strip()
|
| 270 |
+
err_lines = [ln for ln in err_detail.splitlines() if ln.strip()][-6:]
|
| 271 |
+
log_cb(f"[X] ffprobe falló (code {r.returncode}) sobre: {source}")
|
| 272 |
+
hint = _decode_return_code(r.returncode)
|
| 273 |
+
if hint:
|
| 274 |
+
log_cb(f" │ {hint}")
|
| 275 |
+
else:
|
| 276 |
+
for ln in err_lines:
|
| 277 |
+
log_cb(f" │ {ln}")
|
| 278 |
+
return info
|
| 279 |
+
if not r.stdout.strip():
|
| 280 |
+
log_cb(f"[X] ffprobe: no devolvió datos (stdout vacío) sobre: {source}")
|
| 281 |
+
if r.stderr.strip():
|
| 282 |
+
log_cb(f" │ {r.stderr.strip()[:400]}")
|
| 283 |
+
return info
|
| 284 |
+
data = json.loads(r.stdout)
|
| 285 |
+
tags = data.get("format", {}).get("tags", {})
|
| 286 |
+
info["title"] = (tags.get("title") or tags.get("TITLE") or "").strip()
|
| 287 |
+
info["duration"] = float(data.get("format", {}).get("duration", 0) or 0)
|
| 288 |
+
info["bit_rate"] = int(data.get("format", {}).get("bit_rate", 0) or 0)
|
| 289 |
+
ai = si = 0
|
| 290 |
+
for s in data.get("streams", []):
|
| 291 |
+
t, ct = s.get("tags", {}), s.get("codec_type", "")
|
| 292 |
+
if ct == "video" and not info["width"]:
|
| 293 |
+
info["width"] = int(s.get("width") or 0)
|
| 294 |
+
info["height"] = int(s.get("height") or 0)
|
| 295 |
+
elif ct == "audio":
|
| 296 |
+
info["audio"].append({"idx": ai, "real_idx": s.get("index"),
|
| 297 |
+
"codec": s.get("codec_name","?"),
|
| 298 |
+
"lang": t.get("language","und"),
|
| 299 |
+
"title": t.get("title","")})
|
| 300 |
+
ai += 1
|
| 301 |
+
elif ct == "subtitle":
|
| 302 |
+
info["subs"].append({"idx": si, "real_idx": s.get("index"),
|
| 303 |
+
"codec": s.get("codec_name","?"),
|
| 304 |
+
"lang": t.get("language","und"),
|
| 305 |
+
"title": t.get("title","")})
|
| 306 |
+
si += 1
|
| 307 |
+
log_cb(f"[ffprobe] {fmt_dur(info['duration'])} | "
|
| 308 |
+
f"{info['width']}x{info['height']} | audio:{ai} | subs:{si}")
|
| 309 |
+
except Exception as e:
|
| 310 |
+
log_cb(f"[X] ffprobe: {e}")
|
| 311 |
+
return info
|
| 312 |
+
|
| 313 |
+
# ─── FFMPEG CON PROGRESO ──────────────────────────────────────────────────────
|
| 314 |
+
def run_ffmpeg(cmd, total, log_cb, progress_cb, label, cancel_flag, cwd=None):
|
| 315 |
+
from collections import deque
|
| 316 |
+
tail = deque(maxlen=25)
|
| 317 |
+
try:
|
| 318 |
+
proc = subprocess.Popen(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE,
|
| 319 |
+
universal_newlines=True, bufsize=1,
|
| 320 |
+
creationflags=_NO_WINDOW, cwd=cwd)
|
| 321 |
+
pat = re.compile(r"time=(\d+):(\d+):(\d+)\.(\d+)")
|
| 322 |
+
for line in proc.stderr:
|
| 323 |
+
if cancel_flag[0]: proc.terminate(); return False
|
| 324 |
+
tail.append(line.rstrip())
|
| 325 |
+
m = pat.search(line)
|
| 326 |
+
if m:
|
| 327 |
+
h, mi, s, cs = map(int, m.groups())
|
| 328 |
+
cur = h*3600 + mi*60 + s + cs/100
|
| 329 |
+
pct = min(99, int(cur / max(total, 1) * 100))
|
| 330 |
+
progress_cb(pct, f"{label} {pct}% [{fmt_dur(cur)}/{fmt_dur(total)}]")
|
| 331 |
+
proc.wait()
|
| 332 |
+
if proc.returncode != 0:
|
| 333 |
+
log_cb(f"[X] ffmpeg falló (code {proc.returncode}) en: {label}")
|
| 334 |
+
log_cb(f" │ cmd: {' '.join(str(c) for c in cmd)}")
|
| 335 |
+
hint = _decode_return_code(proc.returncode)
|
| 336 |
+
if hint:
|
| 337 |
+
log_cb(f" │ {hint}")
|
| 338 |
+
else:
|
| 339 |
+
useful = [ln for ln in tail if ln.strip()]
|
| 340 |
+
for ln in useful[-12:]:
|
| 341 |
+
log_cb(f" │ {ln}")
|
| 342 |
+
return proc.returncode == 0
|
| 343 |
+
except Exception as e:
|
| 344 |
+
log_cb(f"[ERR] ffmpeg: {e}")
|
| 345 |
+
for ln in tail:
|
| 346 |
+
log_cb(f" │ {ln}")
|
| 347 |
+
return False
|
| 348 |
+
|
| 349 |
+
# ─── DESCARGA YT-DLP ─────────────────────────────────────────────────────────
|
| 350 |
+
def download_with_ytdlp(url, tmp_dir, idx, log_cb, progress_cb, cancel_flag):
|
| 351 |
+
if not YTDLP_OK:
|
| 352 |
+
log_cb("[X] yt-dlp no encontrado."); return None
|
| 353 |
+
out = str(tmp_dir / f"source_{idx}.%(ext)s")
|
| 354 |
+
cmd = [YTDLP_PATH, "--newline", "--no-warnings", "-f", "bestvideo+bestaudio/best", "-o", out, url]
|
| 355 |
+
log_cb(f"[yt-dlp] Descargando {url} ...")
|
| 356 |
+
try:
|
| 357 |
+
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
|
| 358 |
+
universal_newlines=True, bufsize=1,
|
| 359 |
+
creationflags=_NO_WINDOW)
|
| 360 |
+
pat = re.compile(r"\[download\]\s+(\d+\.\d+)%")
|
| 361 |
+
for line in proc.stdout:
|
| 362 |
+
if cancel_flag[0]: proc.terminate(); return None
|
| 363 |
+
m = pat.search(line)
|
| 364 |
+
if m:
|
| 365 |
+
pct = float(m.group(1))
|
| 366 |
+
progress_cb(int(pct), f"[yt-dlp] {pct:.1f}%")
|
| 367 |
+
proc.wait()
|
| 368 |
+
if proc.returncode == 0:
|
| 369 |
+
dl = list(tmp_dir.glob(f"source_{idx}.*"))
|
| 370 |
+
if dl: log_cb("[yt-dlp] OK"); return str(dl[0])
|
| 371 |
+
log_cb(f"[yt-dlp] Exit code: {proc.returncode}"); return None
|
| 372 |
+
except Exception as e:
|
| 373 |
+
log_cb(f"[ERR] yt-dlp: {e}"); return None
|
| 374 |
+
|
| 375 |
+
# ─── DESCARGA BITTORRENT via aria2c ──────────────────────────────────────────
|
| 376 |
+
_ARIA2_PROG = re.compile(
|
| 377 |
+
r"\[#\w+\s+([\d.]+\w+)/([\d.]+\w+)\((\d+)%\).*?DL:([\d.]+\w+).*?ETA:(\S+)\]"
|
| 378 |
+
)
|
| 379 |
+
|
| 380 |
+
def download_torrent(torrent_src, save_dir, log_cb, progress_cb, cancel_flag):
|
| 381 |
+
aria2 = _ensure_aria2(log_cb)
|
| 382 |
+
if not aria2:
|
| 383 |
+
return []
|
| 384 |
+
|
| 385 |
+
save_dir = Path(save_dir)
|
| 386 |
+
save_dir.mkdir(parents=True, exist_ok=True)
|
| 387 |
+
|
| 388 |
+
cmd = [
|
| 389 |
+
aria2,
|
| 390 |
+
"--dir", str(save_dir),
|
| 391 |
+
"--seed-time=0",
|
| 392 |
+
"--max-connection-per-server=4",
|
| 393 |
+
"--split=4",
|
| 394 |
+
"--bt-enable-lpd=true",
|
| 395 |
+
"--enable-dht=true",
|
| 396 |
+
"--enable-dht6=false",
|
| 397 |
+
"--follow-torrent=mem",
|
| 398 |
+
"--console-log-level=warn",
|
| 399 |
+
"--summary-interval=2",
|
| 400 |
+
"--bt-stop-timeout=0",
|
| 401 |
+
"--file-allocation=none",
|
| 402 |
+
"--check-integrity=true",
|
| 403 |
+
"--bt-detach-seed-only=true",
|
| 404 |
+
]
|
| 405 |
+
|
| 406 |
+
if str(torrent_src).startswith("magnet:"):
|
| 407 |
+
cmd.append(str(torrent_src))
|
| 408 |
+
log_cb(f"[Torrent] Magnet: {str(torrent_src)[:72]}...")
|
| 409 |
+
else:
|
| 410 |
+
cmd.extend(["--input-file", str(torrent_src)])
|
| 411 |
+
log_cb(f"[Torrent] Archivo: {Path(torrent_src).name}")
|
| 412 |
+
|
| 413 |
+
log_cb(f"[Torrent] Iniciando aria2c en {save_dir}...")
|
| 414 |
+
|
| 415 |
+
try:
|
| 416 |
+
proc = subprocess.Popen(
|
| 417 |
+
cmd,
|
| 418 |
+
stdout=subprocess.PIPE,
|
| 419 |
+
stderr=subprocess.STDOUT,
|
| 420 |
+
text=True,
|
| 421 |
+
bufsize=1,
|
| 422 |
+
creationflags=_NO_WINDOW,
|
| 423 |
+
)
|
| 424 |
+
except Exception as e:
|
| 425 |
+
log_cb(f"[X] No se pudo lanzar aria2c: {e}")
|
| 426 |
+
return []
|
| 427 |
+
|
| 428 |
+
last_pct = 0
|
| 429 |
+
for raw in proc.stdout:
|
| 430 |
+
if cancel_flag[0]:
|
| 431 |
+
proc.terminate()
|
| 432 |
+
log_cb("[Torrent] Cancelado por usuario.")
|
| 433 |
+
return []
|
| 434 |
+
line = raw.rstrip()
|
| 435 |
+
if not line:
|
| 436 |
+
continue
|
| 437 |
+
|
| 438 |
+
m = _ARIA2_PROG.search(line)
|
| 439 |
+
if m:
|
| 440 |
+
done_str, total_str, pct_str, dl_str, eta_str = m.groups()
|
| 441 |
+
pct = int(pct_str)
|
| 442 |
+
label = (f"[Torrent] {pct}% {done_str}/{total_str}"
|
| 443 |
+
f" DL:{dl_str}/s ETA:{eta_str}")
|
| 444 |
+
progress_cb(pct, label)
|
| 445 |
+
if pct != last_pct and pct % 5 == 0:
|
| 446 |
+
log_cb(label)
|
| 447 |
+
last_pct = pct
|
| 448 |
+
elif any(k in line for k in ("Download complete", "Checksum")):
|
| 449 |
+
log_cb(f"[Torrent] {line}")
|
| 450 |
+
elif line.startswith("[ERROR]") or "Exception" in line:
|
| 451 |
+
log_cb(f"[X] aria2c: {line}")
|
| 452 |
+
|
| 453 |
+
proc.wait()
|
| 454 |
+
if proc.returncode not in (0, None):
|
| 455 |
+
log_cb(f"[WARN] aria2c salió con código {proc.returncode}")
|
| 456 |
+
|
| 457 |
+
videos = sorted(
|
| 458 |
+
[f for f in save_dir.rglob("*") if f.suffix.lower() in VIDEO_EXTS],
|
| 459 |
+
key=lambda f: f.stat().st_size, reverse=True,
|
| 460 |
+
)
|
| 461 |
+
if videos:
|
| 462 |
+
log_cb(f"[Torrent] {len(videos)} video(s) encontrado(s) en {save_dir.name}.")
|
| 463 |
+
else:
|
| 464 |
+
log_cb("[WARN] Torrent completado pero no se encontraron videos.")
|
| 465 |
+
return [str(v) for v in videos]
|
| 466 |
+
|
| 467 |
+
def download_torrents_all(torrent_sources, save_dir, log_cb, progress_cb, cancel_flag):
|
| 468 |
+
all_videos = []
|
| 469 |
+
total = len(torrent_sources)
|
| 470 |
+
for idx, src in enumerate(torrent_sources):
|
| 471 |
+
if cancel_flag[0]: break
|
| 472 |
+
log_cb(f"\n[Torrent {idx+1}/{total}] {src[:80]}...")
|
| 473 |
+
sub_dir = Path(save_dir) / f"torrent_{idx+1}"
|
| 474 |
+
def _prog(p, l, _idx=idx):
|
| 475 |
+
overall = int((_idx / total + p / total / 100) * 100)
|
| 476 |
+
progress_cb(overall, l)
|
| 477 |
+
videos = download_torrent(src, sub_dir, log_cb, _prog, cancel_flag)
|
| 478 |
+
all_videos.extend(videos)
|
| 479 |
+
return all_videos
|
| 480 |
+
|
| 481 |
+
|
| 482 |
+
# ─── EXTRAER SUBTÍTULOS → VTT ─────────────────────────────────────────────────
|
| 483 |
+
def extract_subs_vtt(src, work_dir, base_name, log_cb, progress_cb, dur, cancel_flag):
|
| 484 |
+
info = probe(src, log_cb)
|
| 485 |
+
for sub in info.get("subs", []):
|
| 486 |
+
if cancel_flag[0]: break
|
| 487 |
+
si, ri = sub["idx"], sub["real_idx"]
|
| 488 |
+
lang = sub.get("lang","und")
|
| 489 |
+
lbl = f"sub{si:02d}_{lang}_{safe_name(sub.get('title',''),30)}".strip("_")
|
| 490 |
+
srt = work_dir / f"{base_name}_{lbl}.srt"
|
| 491 |
+
vtt = work_dir / f"{base_name}_{lbl}.vtt"
|
| 492 |
+
run_ffmpeg([FFMPEG_PATH or "ffmpeg", "-y", "-i", src,
|
| 493 |
+
"-map", f"0:{ri}", "-c:s", "srt", str(srt)],
|
| 494 |
+
dur, log_cb, progress_cb, f"Sub {si}", cancel_flag)
|
| 495 |
+
if srt.exists() and srt.stat().st_size > 0:
|
| 496 |
+
try:
|
| 497 |
+
lines = srt.read_text(encoding="utf-8", errors="replace").splitlines()
|
| 498 |
+
vtt_lines = ["WEBVTT", ""]
|
| 499 |
+
i = 0
|
| 500 |
+
while i < len(lines):
|
| 501 |
+
ln = lines[i].strip()
|
| 502 |
+
if re.match(r"^\d+$", ln): i += 1; continue
|
| 503 |
+
ts = re.match(r"(\d{2}:\d{2}:\d{2}),(\d{3})\s*-->\s*(\d{2}:\d{2}:\d{2}),(\d{3})", ln)
|
| 504 |
+
if ts:
|
| 505 |
+
vtt_lines.append(f"{ts.group(1)}.{ts.group(2)} --> {ts.group(3)}.{ts.group(4)}")
|
| 506 |
+
i += 1
|
| 507 |
+
while i < len(lines) and lines[i].strip():
|
| 508 |
+
vtt_lines.append(lines[i].rstrip()); i += 1
|
| 509 |
+
vtt_lines.append(""); continue
|
| 510 |
+
i += 1
|
| 511 |
+
vtt.write_text("\n".join(vtt_lines), encoding="utf-8")
|
| 512 |
+
srt.unlink()
|
| 513 |
+
log_cb(f"[OK] Sub {lang} → VTT")
|
| 514 |
+
except Exception as e:
|
| 515 |
+
log_cb(f"[X] VTT conv: {e}")
|
| 516 |
+
|
| 517 |
+
|
| 518 |
+
def _lang_name(lang):
|
| 519 |
+
LANG_NAMES = {
|
| 520 |
+
"spa":"Español","eng":"English","jpn":"Japonés",
|
| 521 |
+
"por":"Portugués","lat":"Latino","fre":"Francés",
|
| 522 |
+
"ita":"Italiano","und":"Desconocido"
|
| 523 |
+
}
|
| 524 |
+
return LANG_NAMES.get((lang or "und").lower(), (lang or "und").upper())
|
| 525 |
+
|
| 526 |
+
def _generate_thumbnails_auto(source, ep_dir, dur, log_cb, progress_cb, cancel_flag,
|
| 527 |
+
num_thumbnails=AUTO_THUMB_COUNT):
|
| 528 |
+
thumbs_dir = ep_dir / "thumbnails"
|
| 529 |
+
thumbs_dir.mkdir(parents=True, exist_ok=True)
|
| 530 |
+
if num_thumbnails < 2:
|
| 531 |
+
num_thumbnails = 2
|
| 532 |
+
if dur <= 0:
|
| 533 |
+
dur = 1
|
| 534 |
+
interval = dur / (num_thumbnails - 1)
|
| 535 |
+
epsilon = 0.1
|
| 536 |
+
timestamps = [0.0]
|
| 537 |
+
for i in range(1, num_thumbnails - 1):
|
| 538 |
+
timestamps.append(min(interval * i, dur - epsilon))
|
| 539 |
+
timestamps.append(dur - epsilon if dur > epsilon else 0)
|
| 540 |
+
|
| 541 |
+
for idx, ts in enumerate(timestamps, start=1):
|
| 542 |
+
if cancel_flag[0]: break
|
| 543 |
+
h = int(ts // 3600); mnt = int((ts % 3600) // 60); s = ts % 60
|
| 544 |
+
ts_str = f"{h:02d}:{mnt:02d}:{s:06.3f}"
|
| 545 |
+
thumb_path = thumbs_dir / f"thumb{idx}.webp"
|
| 546 |
+
cmd = [FFMPEG_PATH or "ffmpeg", "-y", "-ss", ts_str, "-i", source,
|
| 547 |
+
"-vframes", "1", "-s", "160x90", "-f", "webp", str(thumb_path)]
|
| 548 |
+
try:
|
| 549 |
+
subprocess.run(cmd, capture_output=True, timeout=30, creationflags=_NO_WINDOW)
|
| 550 |
+
except Exception as e:
|
| 551 |
+
log_cb(f"[WARN] Miniatura {idx}: {e}")
|
| 552 |
+
if idx % 20 == 0 or idx == num_thumbnails:
|
| 553 |
+
progress_cb(min(99, int(idx / num_thumbnails * 100)),
|
| 554 |
+
f"Miniaturas {idx}/{num_thumbnails}")
|
| 555 |
+
log_cb(f"[OK] {num_thumbnails} miniaturas generadas → thumbnails/")
|
| 556 |
+
|
| 557 |
+
# ─── NÚCLEO: RENDERIZADO HLS ──────────────────────────────────────────────────
|
| 558 |
+
def render_hls(source, is_url, work_dir, file_name, log_cb, progress_cb, cancel_flag,
|
| 559 |
+
render_mode="copy", resolutions=None):
|
| 560 |
+
tmp_dl = work_dir.parent / f"tmp_dl_{uuid.uuid4().hex[:6]}"
|
| 561 |
+
tmp_dl.mkdir(parents=True, exist_ok=True)
|
| 562 |
+
direct = source
|
| 563 |
+
|
| 564 |
+
try:
|
| 565 |
+
if is_url and YTDLP_OK:
|
| 566 |
+
dl = download_with_ytdlp(source, tmp_dl, 0, log_cb, progress_cb, cancel_flag)
|
| 567 |
+
if not dl or cancel_flag[0]:
|
| 568 |
+
log_cb("[X] Descarga fallida o cancelada.")
|
| 569 |
+
return False
|
| 570 |
+
direct = dl
|
| 571 |
+
|
| 572 |
+
if cancel_flag[0]: return False
|
| 573 |
+
|
| 574 |
+
if not is_url:
|
| 575 |
+
p = Path(direct)
|
| 576 |
+
if not p.exists():
|
| 577 |
+
log_cb(f"[X] El archivo fuente no existe: {direct}")
|
| 578 |
+
return False
|
| 579 |
+
try:
|
| 580 |
+
sz = p.stat().st_size
|
| 581 |
+
except Exception:
|
| 582 |
+
sz = 0
|
| 583 |
+
if sz <= 0:
|
| 584 |
+
log_cb(f"[X] El archivo fuente está vacío (0 bytes): {direct}")
|
| 585 |
+
return False
|
| 586 |
+
log_cb(f"[OK] Fuente local verificada: {p.name} ({fmt_size(sz)})")
|
| 587 |
+
|
| 588 |
+
info = probe(direct, log_cb)
|
| 589 |
+
if info["duration"] <= 0 and info["width"] == 0 and info["height"] == 0:
|
| 590 |
+
log_cb("[X] ffprobe no pudo leer el archivo. Abortando este video.")
|
| 591 |
+
return False
|
| 592 |
+
dur = info["duration"] if info["duration"] > 0 else 1
|
| 593 |
+
audio_tracks = info.get("audio", [])
|
| 594 |
+
bit_rate = info.get("bit_rate", 0)
|
| 595 |
+
src_w, src_h = info.get("width", 0), info.get("height", 0)
|
| 596 |
+
|
| 597 |
+
# ─── NUEVA LÓGICA DE BITRATE Y RESOLUCIÓN ─────────────────────────────
|
| 598 |
+
# Si el bitrate es mayor a 5 Mbps (5,000,000 bps), forzamos renderización (auto).
|
| 599 |
+
# De lo contrario (<= 5 Mbps), simplemente copiamos (copy).
|
| 600 |
+
if bit_rate > 5_000_000:
|
| 601 |
+
render_mode = "auto"
|
| 602 |
+
else:
|
| 603 |
+
render_mode = "copy"
|
| 604 |
+
|
| 605 |
+
# Forzar siempre la resolución 1080p y omitir las demás
|
| 606 |
+
resolutions = [1080]
|
| 607 |
+
# ──────────────────────────────────────────────────────────────────────
|
| 608 |
+
|
| 609 |
+
ep_dir = work_dir / file_name
|
| 610 |
+
ep_dir.mkdir(parents=True, exist_ok=True)
|
| 611 |
+
|
| 612 |
+
if render_mode == "scratch":
|
| 613 |
+
ok = _render_scratch(direct, ep_dir, file_name, resolutions or [720, 1080],
|
| 614 |
+
audio_tracks, dur, src_w, src_h, bit_rate,
|
| 615 |
+
log_cb, progress_cb, cancel_flag)
|
| 616 |
+
elif render_mode == "auto":
|
| 617 |
+
ok = _render_auto(direct, ep_dir, file_name, resolutions or [720, 1080],
|
| 618 |
+
audio_tracks, dur, src_w, src_h, bit_rate,
|
| 619 |
+
log_cb, progress_cb, cancel_flag)
|
| 620 |
+
else:
|
| 621 |
+
ok = _render_copy(direct, work_dir, ep_dir, file_name, audio_tracks,
|
| 622 |
+
dur, bit_rate, log_cb, progress_cb, cancel_flag)
|
| 623 |
+
|
| 624 |
+
if not ok and not cancel_flag[0]:
|
| 625 |
+
log_cb("[X] Renderizado terminó con error.")
|
| 626 |
+
|
| 627 |
+
extract_subs_vtt(direct, work_dir, file_name, log_cb, progress_cb, dur, cancel_flag)
|
| 628 |
+
|
| 629 |
+
try:
|
| 630 |
+
dl_p = Path(direct)
|
| 631 |
+
if tmp_dl in dl_p.parents and dl_p.exists():
|
| 632 |
+
dl_p.unlink(); log_cb("[OK] Video descargado eliminado (espacio).")
|
| 633 |
+
except Exception as e:
|
| 634 |
+
log_cb(f"[WARN] No se pudo borrar video: {e}")
|
| 635 |
+
|
| 636 |
+
return ok and not cancel_flag[0]
|
| 637 |
+
|
| 638 |
+
finally:
|
| 639 |
+
shutil.rmtree(tmp_dl, ignore_errors=True)
|
| 640 |
+
|
| 641 |
+
|
| 642 |
+
def _render_copy(direct, work_dir, ep_dir, file_name, audio_tracks, dur, bit_rate,
|
| 643 |
+
log_cb, progress_cb, cancel_flag):
|
| 644 |
+
info2 = probe(direct, lambda *_: None)
|
| 645 |
+
h = info2.get("height", 1080)
|
| 646 |
+
res_label = f"{h}p" if h else "video"
|
| 647 |
+
|
| 648 |
+
tmp_master = f"_tmp_master_{file_name}.m3u8"
|
| 649 |
+
|
| 650 |
+
cmd = [FFMPEG_PATH or "ffmpeg", "-y", "-i", direct, "-map", "0:v:0"]
|
| 651 |
+
for i in range(len(audio_tracks)):
|
| 652 |
+
cmd += ["-map", f"0:a:{i}"]
|
| 653 |
+
|
| 654 |
+
cmd += ["-c:v", "copy"]
|
| 655 |
+
for i in range(len(audio_tracks)):
|
| 656 |
+
cmd += [f"-c:a:{i}", "libmp3lame", f"-b:a:{i}", AUDIO_BITRATE, f"-ac:{i}", "2"]
|
| 657 |
+
|
| 658 |
+
if audio_tracks:
|
| 659 |
+
var_map = f"v:0,name:{res_label} " + " ".join(
|
| 660 |
+
f"a:{i},name:Aud{i}_{t.get('lang','und')}"
|
| 661 |
+
for i, t in enumerate(audio_tracks)
|
| 662 |
+
)
|
| 663 |
+
else:
|
| 664 |
+
var_map = f"v:0,name:{res_label}"
|
| 665 |
+
|
| 666 |
+
cmd += ["-f", "hls", "-hls_time", "10", "-hls_playlist_type", "vod",
|
| 667 |
+
"-master_pl_name", tmp_master,
|
| 668 |
+
"-hls_segment_filename", f"{file_name}/%v/seg_%05d.ts",
|
| 669 |
+
"-var_stream_map", var_map.strip(),
|
| 670 |
+
f"{file_name}/%v/index.m3u8"]
|
| 671 |
+
|
| 672 |
+
log_cb("[ffmpeg] Codificando HLS (copiar simultáneo)...")
|
| 673 |
+
ok = run_ffmpeg(cmd, dur, log_cb, progress_cb, "Renderizando HLS (copiar)", cancel_flag, cwd=str(work_dir))
|
| 674 |
+
|
| 675 |
+
for f in work_dir.rglob(tmp_master): f.unlink(missing_ok=True)
|
| 676 |
+
for f in work_dir.rglob("master.m3u8"): f.unlink(missing_ok=True)
|
| 677 |
+
|
| 678 |
+
master_path = work_dir / f"{file_name}_master.m3u8"
|
| 679 |
+
if not cancel_flag[0]:
|
| 680 |
+
w = info2.get("width", 1920)
|
| 681 |
+
bw = bit_rate if bit_rate > 0 else 8_000_000
|
| 682 |
+
abw = int(bw * 0.6)
|
| 683 |
+
|
| 684 |
+
lines = ["#EXTM3U", "#EXT-X-VERSION:6", ""]
|
| 685 |
+
|
| 686 |
+
if audio_tracks:
|
| 687 |
+
lines.append("# AUDIO GROUP")
|
| 688 |
+
lang_count = {}
|
| 689 |
+
for i, t in enumerate(audio_tracks):
|
| 690 |
+
lang = t.get("lang", "und")
|
| 691 |
+
nice = _lang_name(lang)
|
| 692 |
+
cnt = lang_count.get(lang, 0)
|
| 693 |
+
if cnt: nice += f" {cnt+1}"
|
| 694 |
+
lang_count[lang] = cnt + 1
|
| 695 |
+
default = "YES" if i == 0 else "NO"
|
| 696 |
+
uri = f"{file_name}/Aud{i}_{lang}/index.m3u8"
|
| 697 |
+
lines.append(
|
| 698 |
+
f'#EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID="audio",'
|
| 699 |
+
f'NAME="{nice}",LANGUAGE="{lang}",'
|
| 700 |
+
f'DEFAULT={default},AUTOSELECT=YES,URI="{uri}"'
|
| 701 |
+
)
|
| 702 |
+
lines.append("")
|
| 703 |
+
|
| 704 |
+
audio_attr = ',AUDIO="audio"' if audio_tracks else ""
|
| 705 |
+
codec_v = RENDER_PROFILES.get(h, RENDER_PROFILES[1080])["codec_tag"]
|
| 706 |
+
|
| 707 |
+
lines.append(f"# VIDEO {res_label}")
|
| 708 |
+
lines.append(f'#EXT-X-STREAM-INF:BANDWIDTH={bw},AVERAGE-BANDWIDTH={abw},RESOLUTION={w}x{h},CODECS="{codec_v}"{audio_attr}')
|
| 709 |
+
lines.append(f"{file_name}/{res_label}/index.m3u8")
|
| 710 |
+
lines.append("")
|
| 711 |
+
|
| 712 |
+
master_path.write_text("\n".join(lines).strip(), encoding="utf-8")
|
| 713 |
+
log_cb(f"[OK] Master (copiar) → {file_name}_master.m3u8")
|
| 714 |
+
|
| 715 |
+
return ok
|
| 716 |
+
|
| 717 |
+
|
| 718 |
+
def _render_scratch(direct, ep_dir, file_name, resolutions, audio_tracks, dur,
|
| 719 |
+
src_w, src_h, bit_rate, log_cb, progress_cb, cancel_flag):
|
| 720 |
+
return _render_multi_res(direct, ep_dir, file_name, resolutions, audio_tracks,
|
| 721 |
+
dur, src_w, src_h, bit_rate, log_cb, progress_cb,
|
| 722 |
+
cancel_flag, gen_thumbnails=False)
|
| 723 |
+
|
| 724 |
+
|
| 725 |
+
def _render_auto(direct, ep_dir, file_name, resolutions, audio_tracks, dur,
|
| 726 |
+
src_w, src_h, bit_rate, log_cb, progress_cb, cancel_flag):
|
| 727 |
+
return _render_multi_res(direct, ep_dir, file_name, resolutions, audio_tracks,
|
| 728 |
+
dur, src_w, src_h, bit_rate, log_cb, progress_cb,
|
| 729 |
+
cancel_flag, gen_thumbnails=True)
|
| 730 |
+
|
| 731 |
+
|
| 732 |
+
def _render_multi_res(direct, ep_dir, file_name, resolutions, audio_tracks, dur,
|
| 733 |
+
src_w, src_h, bit_rate, log_cb, progress_cb, cancel_flag,
|
| 734 |
+
gen_thumbnails=False):
|
| 735 |
+
usable_res = sorted(resolutions) if resolutions else [720]
|
| 736 |
+
|
| 737 |
+
if src_h and max(usable_res) > src_h:
|
| 738 |
+
log_cb(f"[WARN] El video fuente ({src_h}p) es menor a algunas calidades elegidas. Se forzará el escalado (upscale).")
|
| 739 |
+
|
| 740 |
+
for res in usable_res:
|
| 741 |
+
(ep_dir / f"{res}p").mkdir(parents=True, exist_ok=True)
|
| 742 |
+
for i, track in enumerate(audio_tracks):
|
| 743 |
+
lang = track.get("lang", "und")
|
| 744 |
+
(ep_dir / f"Aud{i}_{lang}").mkdir(parents=True, exist_ok=True)
|
| 745 |
+
|
| 746 |
+
cmd = [FFMPEG_PATH or "ffmpeg", "-y", "-hwaccel", "auto", "-i", direct]
|
| 747 |
+
|
| 748 |
+
for _ in usable_res:
|
| 749 |
+
cmd.extend(["-map", "0:v:0"])
|
| 750 |
+
for track in audio_tracks:
|
| 751 |
+
cmd.extend(["-map", f"0:{track['real_idx']}"])
|
| 752 |
+
|
| 753 |
+
for i, res in enumerate(usable_res):
|
| 754 |
+
profile = RENDER_PROFILES.get(res, RENDER_PROFILES[720])
|
| 755 |
+
cmd.extend([
|
| 756 |
+
f"-c:v:{i}", "h264_nvenc",
|
| 757 |
+
f"-profile:v:{i}", "high", f"-level:v:{i}", profile["level"],
|
| 758 |
+
f"-preset:v:{i}", "p6",
|
| 759 |
+
f"-tune:v:{i}", "hq",
|
| 760 |
+
f"-rc:v:{i}", "cbr",
|
| 761 |
+
f"-spatial-aq:v:{i}", "1",
|
| 762 |
+
f"-temporal-aq:v:{i}", "1",
|
| 763 |
+
f"-b:v:{i}", profile["bitrate"],
|
| 764 |
+
f"-maxrate:v:{i}", profile["maxrate"],
|
| 765 |
+
f"-minrate:v:{i}", profile["bitrate"],
|
| 766 |
+
f"-bufsize:v:{i}", profile["bufsize"],
|
| 767 |
+
f"-filter:v:{i}", f"scale=-2:{res}:flags=lanczos",
|
| 768 |
+
f"-pix_fmt:v:{i}", "yuv420p",
|
| 769 |
+
f"-g:v:{i}", "48", f"-keyint_min:v:{i}", "48", f"-sc_threshold:v:{i}", "0"
|
| 770 |
+
])
|
| 771 |
+
|
| 772 |
+
for i, track in enumerate(audio_tracks):
|
| 773 |
+
cmd.extend([
|
| 774 |
+
f"-c:a:{i}", "libmp3lame",
|
| 775 |
+
f"-b:a:{i}", AUDIO_BITRATE,
|
| 776 |
+
f"-ar:a:{i}", AUDIO_RATE,
|
| 777 |
+
f"-ac:a:{i}", "2"
|
| 778 |
+
])
|
| 779 |
+
|
| 780 |
+
var_map = []
|
| 781 |
+
for i, res in enumerate(usable_res):
|
| 782 |
+
var_map.append(f"v:{i},name:{res}p")
|
| 783 |
+
for i, track in enumerate(audio_tracks):
|
| 784 |
+
lang = track.get("lang", "und")
|
| 785 |
+
var_map.append(f"a:{i},name:Aud{i}_{lang}")
|
| 786 |
+
|
| 787 |
+
cmd.extend([
|
| 788 |
+
"-max_muxing_queue_size", "9999",
|
| 789 |
+
"-f", "hls",
|
| 790 |
+
"-hls_time", HLS_SEG_SECONDS,
|
| 791 |
+
"-hls_playlist_type", "vod",
|
| 792 |
+
"-var_stream_map", " ".join(var_map),
|
| 793 |
+
"-master_pl_name", "dummy_master.m3u8",
|
| 794 |
+
"-hls_segment_filename", "%v/seg_%05d.ts",
|
| 795 |
+
"%v/index.m3u8"
|
| 796 |
+
])
|
| 797 |
+
|
| 798 |
+
log_cb(f"[Video] Renderizando simultáneamente {len(usable_res)} calidades (CBR, Rápido) y {len(audio_tracks)} audios...")
|
| 799 |
+
|
| 800 |
+
ok = run_ffmpeg(cmd, dur, log_cb, progress_cb, "Render Simultáneo", cancel_flag, cwd=str(ep_dir))
|
| 801 |
+
|
| 802 |
+
if not ok:
|
| 803 |
+
return False
|
| 804 |
+
|
| 805 |
+
dummy = ep_dir / "dummy_master.m3u8"
|
| 806 |
+
if dummy.exists():
|
| 807 |
+
dummy.unlink()
|
| 808 |
+
|
| 809 |
+
audio_results = [(i, t, f"Aud{i}_{t.get('lang', 'und')}/index.m3u8") for i, t in enumerate(audio_tracks)]
|
| 810 |
+
video_results = [(r, RENDER_PROFILES.get(r, RENDER_PROFILES[720]), f"{r}p/index.m3u8") for r in usable_res]
|
| 811 |
+
|
| 812 |
+
master_path = ep_dir.parent / f"{file_name}_master.m3u8"
|
| 813 |
+
lines = ["#EXTM3U", "#EXT-X-VERSION:6", ""]
|
| 814 |
+
|
| 815 |
+
if audio_results:
|
| 816 |
+
lines.append("# AUDIO GROUP")
|
| 817 |
+
lang_count = {}
|
| 818 |
+
for i, track, uri in audio_results:
|
| 819 |
+
lang = track.get("lang", "und")
|
| 820 |
+
nice = _lang_name(lang)
|
| 821 |
+
cnt = lang_count.get(lang, 0)
|
| 822 |
+
if cnt: nice += f" {cnt+1}"
|
| 823 |
+
lang_count[lang] = cnt + 1
|
| 824 |
+
default = "YES" if i == audio_results[0][0] else "NO"
|
| 825 |
+
full_uri = f"{file_name}/{uri}"
|
| 826 |
+
lines.append(
|
| 827 |
+
f'#EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID="audio",'
|
| 828 |
+
f'NAME="{nice}",LANGUAGE="{lang}",'
|
| 829 |
+
f'DEFAULT={default},AUTOSELECT=YES,URI="{full_uri}"'
|
| 830 |
+
)
|
| 831 |
+
lines.append("")
|
| 832 |
+
|
| 833 |
+
audio_attr = ',AUDIO="audio"' if audio_results else ""
|
| 834 |
+
audio_bw = int(AUDIO_BITRATE.rstrip("k")) * 1000
|
| 835 |
+
|
| 836 |
+
for res, profile, uri in sorted(video_results, key=lambda x: x[0]):
|
| 837 |
+
v_bw = int(profile["bitrate"].rstrip("k")) * 1000
|
| 838 |
+
total_bw = v_bw + (audio_bw if audio_results else 0)
|
| 839 |
+
width = _calc_width(src_w, src_h, res)
|
| 840 |
+
codecs = f'CODECS="{profile["codec_tag"]}"'
|
| 841 |
+
|
| 842 |
+
lines.append(f"# VIDEO {res}p")
|
| 843 |
+
lines.append(
|
| 844 |
+
f"#EXT-X-STREAM-INF:BANDWIDTH={total_bw},"
|
| 845 |
+
f"AVERAGE-BANDWIDTH={int(total_bw*0.85)},"
|
| 846 |
+
f"RESOLUTION={width}x{res},{codecs}{audio_attr}"
|
| 847 |
+
)
|
| 848 |
+
lines.append(f"{file_name}/{uri}")
|
| 849 |
+
lines.append("")
|
| 850 |
+
|
| 851 |
+
master_path.write_text("\n".join(lines).strip(), encoding="utf-8")
|
| 852 |
+
log_cb(f"[OK] Master ({len(video_results)} calidad(es) + "
|
| 853 |
+
f"{len(audio_results)} audio(s) simultáneos) → {file_name}_master.m3u8")
|
| 854 |
+
|
| 855 |
+
if gen_thumbnails and not cancel_flag[0]:
|
| 856 |
+
log_cb("[Auto] Generando miniaturas...")
|
| 857 |
+
_generate_thumbnails_auto(direct, ep_dir, dur, log_cb, progress_cb, cancel_flag)
|
| 858 |
+
|
| 859 |
+
return True
|
| 860 |
+
|
| 861 |
+
|
| 862 |
+
# ─── SUBIDA HUGGINGFACE BUCKETS ───────────────────────────────────────────────
|
| 863 |
+
def _parse_retry_after(msg):
|
| 864 |
+
m = re.search(r"[Rr]etry after (\d+) second", msg)
|
| 865 |
+
if m: return int(m.group(1)) + 5
|
| 866 |
+
m = re.search(r"retry.*?(\d+)\s*hour", msg)
|
| 867 |
+
if m: return int(m.group(1)) * 3600 + 30
|
| 868 |
+
m = re.search(r"retry.*?(\d+)\s*minute", msg)
|
| 869 |
+
if m: return int(m.group(1)) * 60 + 10
|
| 870 |
+
return 300
|
| 871 |
+
|
| 872 |
+
def _local_file_set(local_folder):
|
| 873 |
+
base = Path(local_folder)
|
| 874 |
+
out = set()
|
| 875 |
+
for p in base.rglob("*"):
|
| 876 |
+
if p.is_file():
|
| 877 |
+
out.add(p.relative_to(base).as_posix())
|
| 878 |
+
return out
|
| 879 |
+
|
| 880 |
+
def _remote_file_set(repo_id, remote_path, hf_token, log_cb):
|
| 881 |
+
out = set()
|
| 882 |
+
try:
|
| 883 |
+
for item in list_bucket_tree(repo_id, prefix=remote_path, recursive=True, token=hf_token):
|
| 884 |
+
path = getattr(item, "path", None)
|
| 885 |
+
if not path:
|
| 886 |
+
continue
|
| 887 |
+
itype = getattr(item, "type", None)
|
| 888 |
+
if itype and itype != "file":
|
| 889 |
+
continue
|
| 890 |
+
if path.endswith("/"):
|
| 891 |
+
continue
|
| 892 |
+
rel = path[len(remote_path):].lstrip("/") if path.startswith(remote_path) else path
|
| 893 |
+
if rel:
|
| 894 |
+
out.add(rel)
|
| 895 |
+
except Exception as e:
|
| 896 |
+
log_cb(f"[WARN] No se pudo listar el bucket para verificar ({e}); "
|
| 897 |
+
f"se asume que la subida está incompleta.")
|
| 898 |
+
return None
|
| 899 |
+
return out
|
| 900 |
+
|
| 901 |
+
def upload_huggingface(hf_token, repo_id, local_folder, remote_path,
|
| 902 |
+
log_cb, progress_cb, cancel_flag):
|
| 903 |
+
if not HF_OK:
|
| 904 |
+
log_cb("[WARN] huggingface_hub no disponible. Saltando subida HF.")
|
| 905 |
+
return False
|
| 906 |
+
|
| 907 |
+
local_files = _local_file_set(local_folder)
|
| 908 |
+
total_local = len(local_files)
|
| 909 |
+
if total_local == 0:
|
| 910 |
+
log_cb("[WARN] No hay archivos locales para subir.")
|
| 911 |
+
return True
|
| 912 |
+
|
| 913 |
+
MAX = 6
|
| 914 |
+
for attempt in range(1, MAX + 1):
|
| 915 |
+
if cancel_flag[0]: return False
|
| 916 |
+
try:
|
| 917 |
+
log_cb(f"\n[HF] Sincronizando al Bucket {repo_id}/{remote_path} "
|
| 918 |
+
f"(intento {attempt}/{MAX}, {total_local} archivo(s) locales)")
|
| 919 |
+
progress_cb(50, f"Enviando al Bucket... ({attempt}/{MAX})")
|
| 920 |
+
|
| 921 |
+
create_bucket(repo_id, exist_ok=True, token=hf_token)
|
| 922 |
+
remote_uri = f"hf://buckets/{repo_id}/{remote_path}"
|
| 923 |
+
sync_bucket(str(local_folder), remote_uri, token=hf_token)
|
| 924 |
+
|
| 925 |
+
log_cb("[HF] Verificando integridad de la subida...")
|
| 926 |
+
remote_files = _remote_file_set(repo_id, remote_path, hf_token, log_cb)
|
| 927 |
+
|
| 928 |
+
if remote_files is None:
|
| 929 |
+
log_cb(f"[WARN] Verificación no disponible en intento {attempt}. Reintentando...")
|
| 930 |
+
time.sleep(5 * attempt)
|
| 931 |
+
continue
|
| 932 |
+
|
| 933 |
+
missing = local_files - remote_files
|
| 934 |
+
if not missing:
|
| 935 |
+
log_cb(f"[OK] Verificado: los {total_local} archivo(s) están en el Bucket.")
|
| 936 |
+
progress_cb(70, "HuggingFace Bucket: listo (verificado)")
|
| 937 |
+
return True
|
| 938 |
+
|
| 939 |
+
pct_ok = int((total_local - len(missing)) / total_local * 100)
|
| 940 |
+
log_cb(f"[WARN] Faltan {len(missing)}/{total_local} archivo(s) en el Bucket "
|
| 941 |
+
f"({pct_ok}% completo). Reintentando solo lo faltante...")
|
| 942 |
+
for m in sorted(missing)[:10]:
|
| 943 |
+
log_cb(f" │ falta: {m}")
|
| 944 |
+
if len(missing) > 10:
|
| 945 |
+
log_cb(f" │ ... y {len(missing) - 10} más.")
|
| 946 |
+
time.sleep(3 * attempt)
|
| 947 |
+
|
| 948 |
+
except Exception as e:
|
| 949 |
+
err = str(e)
|
| 950 |
+
if any(x in err for x in ("401", "403", "unauthorized", "Unauthorized")):
|
| 951 |
+
log_cb(f"[X] HF auth error: {e}"); return False
|
| 952 |
+
elif "429" in err or "rate limit" in err.lower() or "Too Many Requests" in err:
|
| 953 |
+
wait = _parse_retry_after(err)
|
| 954 |
+
log_cb(f"[WARN] Rate limit 429. Esperando {wait}s...")
|
| 955 |
+
elapsed = 0
|
| 956 |
+
while elapsed < wait and not cancel_flag[0]:
|
| 957 |
+
chunk = min(30, wait - elapsed); time.sleep(chunk); elapsed += chunk
|
| 958 |
+
if wait - elapsed > 0: log_cb(f"[HF] {wait - elapsed}s restantes...")
|
| 959 |
+
elif "409" in err or "conflict" in err.lower():
|
| 960 |
+
wait = 10 * attempt; log_cb(f"[WARN] Conflicto 409. Esperando {wait}s..."); time.sleep(wait)
|
| 961 |
+
elif any(x in err for x in ("500", "502", "503", "504")):
|
| 962 |
+
wait = 15 * attempt; log_cb(f"[WARN] Error HF servidor. Esperando {wait}s..."); time.sleep(wait)
|
| 963 |
+
else:
|
| 964 |
+
log_cb(f"[WARN] Intento {attempt}: {e}"); time.sleep(5 * attempt)
|
| 965 |
+
|
| 966 |
+
log_cb(f"[X] HF: no se pudo confirmar la subida completa tras {MAX} intentos.")
|
| 967 |
+
return False
|
| 968 |
+
|
| 969 |
+
|
| 970 |
+
# ─── SUBIDA GITHUB ────────────────────────────────────────────────────────────
|
| 971 |
+
def _run_git(cmd, cwd, check=True):
|
| 972 |
+
res = subprocess.run(cmd, cwd=str(cwd), capture_output=True, text=True,
|
| 973 |
+
creationflags=_NO_WINDOW)
|
| 974 |
+
if check and res.returncode != 0:
|
| 975 |
+
raise RuntimeError(f"git error: {res.stderr.strip()[:400]}")
|
| 976 |
+
return res
|
| 977 |
+
|
| 978 |
+
def upload_github(gh_token, repo_name, local_folder, manifest_file,
|
| 979 |
+
batch_size, log_cb, progress_cb, cancel_flag):
|
| 980 |
+
if not requests:
|
| 981 |
+
log_cb("[X] 'requests' no instalado. Saltando subida GitHub."); return None
|
| 982 |
+
headers = {"Authorization": f"token {gh_token}"}
|
| 983 |
+
|
| 984 |
+
rr = requests.post("https://api.github.com/user/repos", headers=headers,
|
| 985 |
+
json={"name": repo_name, "private": True}, timeout=30)
|
| 986 |
+
if rr.status_code in (200, 201):
|
| 987 |
+
html_url = rr.json()["html_url"]
|
| 988 |
+
elif rr.status_code == 422:
|
| 989 |
+
u = requests.get("https://api.github.com/user", headers=headers, timeout=30)
|
| 990 |
+
uname = u.json()["login"]
|
| 991 |
+
html_url = f"https://github.com/{uname}/{repo_name}"
|
| 992 |
+
log_cb("[GH] Repositorio existente, actualizando...")
|
| 993 |
+
else:
|
| 994 |
+
log_cb(f"[X] GitHub API {rr.status_code}: {rr.text[:200]}"); return None
|
| 995 |
+
|
| 996 |
+
git_url = html_url.replace("https://", f"https://{gh_token}@") + ".git"
|
| 997 |
+
gd = str(local_folder)
|
| 998 |
+
|
| 999 |
+
_run_git(["git", "init"], gd)
|
| 1000 |
+
_run_git(["git", "config", "user.email", "vcpro@bot.com"], gd)
|
| 1001 |
+
_run_git(["git", "config", "user.name", "VCProBot"], gd)
|
| 1002 |
+
_run_git(["git", "checkout", "-b", "main"], gd)
|
| 1003 |
+
_run_git(["git", "remote", "remove", "origin"], gd, check=False)
|
| 1004 |
+
_run_git(["git", "remote", "add", "origin", git_url], gd)
|
| 1005 |
+
_run_git(["git", "config", "http.postBuffer", "524288000"], gd)
|
| 1006 |
+
|
| 1007 |
+
all_files_root = []
|
| 1008 |
+
for root, _dirs, files in os.walk(gd):
|
| 1009 |
+
for f in files:
|
| 1010 |
+
rel = os.path.relpath(os.path.join(root, f), gd)
|
| 1011 |
+
if ".git" not in rel.split(os.sep):
|
| 1012 |
+
all_files_root.append(rel)
|
| 1013 |
+
|
| 1014 |
+
is_dash = "mpd" in manifest_file.lower()
|
| 1015 |
+
ext_s = ".m4s" if is_dash else ".ts"
|
| 1016 |
+
ext_m = ".mpd" if is_dash else ".m3u8"
|
| 1017 |
+
segs = [f for f in all_files_root if f.endswith(ext_s)]
|
| 1018 |
+
mans = [f for f in all_files_root if f.endswith(ext_m)]
|
| 1019 |
+
|
| 1020 |
+
if mans:
|
| 1021 |
+
_run_git(["git", "add"] + mans, gd)
|
| 1022 |
+
_run_git(["git", "commit", "-m", f"init {repo_name}"], gd)
|
| 1023 |
+
log_cb("[GH] Subiendo manifiestos...")
|
| 1024 |
+
_run_git(["git", "push", "-u", "origin", "main", "--force"], gd)
|
| 1025 |
+
|
| 1026 |
+
log_cb(f"[GH] {len(segs)} segmentos → batch {batch_size}")
|
| 1027 |
+
for i in range(0, len(segs), batch_size):
|
| 1028 |
+
if cancel_flag[0]: break
|
| 1029 |
+
batch = segs[i:i+batch_size]
|
| 1030 |
+
if not batch: continue
|
| 1031 |
+
_run_git(["git", "add"] + batch, gd)
|
| 1032 |
+
_run_git(["git", "commit", "-m", f"segs {i}-{i+len(batch)}"], gd)
|
| 1033 |
+
for retry in range(3):
|
| 1034 |
+
try:
|
| 1035 |
+
_run_git(["git", "push", "origin", "main"], gd)
|
| 1036 |
+
log_cb(f"[GH] {min(i+batch_size,len(segs))}/{len(segs)} segmentos")
|
| 1037 |
+
break
|
| 1038 |
+
except Exception as e:
|
| 1039 |
+
if retry == 2: log_cb(f"[WARN] Error lote {i}: {e}")
|
| 1040 |
+
else: time.sleep(2)
|
| 1041 |
+
progress_cb(80 + int((i/max(len(segs),1))*15), f"GitHub: {min(i+batch_size,len(segs))}/{len(segs)}")
|
| 1042 |
+
|
| 1043 |
+
gp = f"https://gooplay.xyz/gp/stream.php?repo={repo_name}&branch=main&file={manifest_file}"
|
| 1044 |
+
gh = f"{html_url}/blob/main/{manifest_file}"
|
| 1045 |
+
log_cb(f"[OK] GitHub: {html_url}")
|
| 1046 |
+
return f"Gooplay: {gp}\nGitHub: {gh}"
|
| 1047 |
+
|
| 1048 |
+
|
| 1049 |
+
# ─── SUBIDA DE CARPETA CONTENEDORA (HLS YA RENDERIZADO) ───────────────────────
|
| 1050 |
+
def upload_container_folder(job, log_cb, progress_cb, done_cb):
|
| 1051 |
+
hf_token = job["hf_token"]
|
| 1052 |
+
hf_repo = job["hf_repo"]
|
| 1053 |
+
gh_enabled = job["gh_enabled"]
|
| 1054 |
+
gh_token = job["gh_token"]
|
| 1055 |
+
gh_batch = job["gh_batch"]
|
| 1056 |
+
cancel_flag = job["cancel_flag"]
|
| 1057 |
+
local_folder = Path(job["container_folder"])
|
| 1058 |
+
remote_path = job["container_remote_path"]
|
| 1059 |
+
|
| 1060 |
+
try:
|
| 1061 |
+
log_cb(f"[1/2] Subiendo carpeta contenedora al Bucket de HuggingFace...")
|
| 1062 |
+
log_cb(f" │ Local: {local_folder}")
|
| 1063 |
+
log_cb(f" │ Remoto: {hf_repo}/{remote_path}")
|
| 1064 |
+
hf_ok = upload_huggingface(
|
| 1065 |
+
hf_token, hf_repo, local_folder, remote_path,
|
| 1066 |
+
log_cb, progress_cb, cancel_flag
|
| 1067 |
+
)
|
| 1068 |
+
if not hf_ok:
|
| 1069 |
+
log_cb("[WARN] Subida al Bucket incompleta/fallida.")
|
| 1070 |
+
|
| 1071 |
+
gh_link = None
|
| 1072 |
+
if gh_enabled and not cancel_flag[0]:
|
| 1073 |
+
log_cb(f"[2/2] Subiendo a GitHub...")
|
| 1074 |
+
manifests = sorted(local_folder.rglob("*_master.m3u8"))
|
| 1075 |
+
if not manifests:
|
| 1076 |
+
manifests = sorted(local_folder.rglob("*.m3u8"))
|
| 1077 |
+
if manifests:
|
| 1078 |
+
manifest_file = manifests[0].relative_to(local_folder).as_posix()
|
| 1079 |
+
repo_name = clean_repo(local_folder.name)
|
| 1080 |
+
gh_link = upload_github(
|
| 1081 |
+
gh_token, repo_name, local_folder, manifest_file,
|
| 1082 |
+
gh_batch, log_cb, progress_cb, cancel_flag
|
| 1083 |
+
)
|
| 1084 |
+
else:
|
| 1085 |
+
log_cb("[WARN] No se encontró ningún .m3u8 en la carpeta; se omite GitHub.")
|
| 1086 |
+
else:
|
| 1087 |
+
log_cb("[2/2] GitHub desactivado, omitiendo.")
|
| 1088 |
+
|
| 1089 |
+
log_cb("\n=== CARPETA CONTENEDORA COMPLETADA ===")
|
| 1090 |
+
done_cb(bool(hf_ok) or not cancel_flag[0], gh_link or "")
|
| 1091 |
+
|
| 1092 |
+
except Exception as e:
|
| 1093 |
+
log_cb(f"\n[X] ERROR CRÍTICO: {e}\n{traceback.format_exc()}")
|
| 1094 |
+
done_cb(False, str(e))
|
| 1095 |
+
|
| 1096 |
+
|
| 1097 |
+
# ─── PROCESO PRINCIPAL ────────────────────────────────────────────────────────
|
| 1098 |
+
def run_job(job, log_cb, progress_cb, done_cb):
|
| 1099 |
+
hf_token = job["hf_token"]
|
| 1100 |
+
hf_repo = job["hf_repo"]
|
| 1101 |
+
gh_enabled = job["gh_enabled"]
|
| 1102 |
+
gh_token = job["gh_token"]
|
| 1103 |
+
gh_batch = job["gh_batch"]
|
| 1104 |
+
del_locals = job["del_locals"]
|
| 1105 |
+
sources = job["sources"]
|
| 1106 |
+
is_url = job["is_url"]
|
| 1107 |
+
is_torrent = job.get("is_torrent", False)
|
| 1108 |
+
series_name = job["series_name"]
|
| 1109 |
+
season_folder = job["season_folder"]
|
| 1110 |
+
file_names = job["file_names"]
|
| 1111 |
+
cancel_flag = job["cancel_flag"]
|
| 1112 |
+
render_mode = job.get("render_mode", "copy")
|
| 1113 |
+
resolutions = job.get("resolutions", [720, 1080])
|
| 1114 |
+
|
| 1115 |
+
output_root = BASE_DIR / "Videos_Procesados"
|
| 1116 |
+
output_root.mkdir(exist_ok=True)
|
| 1117 |
+
|
| 1118 |
+
all_links = []
|
| 1119 |
+
torrent_dl_dir = None
|
| 1120 |
+
|
| 1121 |
+
try:
|
| 1122 |
+
if is_torrent and sources:
|
| 1123 |
+
log_cb(f"\n[Torrent] Iniciando descarga de {len(sources)} torrent(s)...")
|
| 1124 |
+
progress_cb(0, "Descargando torrents...")
|
| 1125 |
+
torrent_dl_dir = output_root / f"torrent_dl_{uuid.uuid4().hex[:8]}"
|
| 1126 |
+
torrent_dl_dir.mkdir(parents=True, exist_ok=True)
|
| 1127 |
+
downloaded = download_torrents_all(
|
| 1128 |
+
sources, torrent_dl_dir, log_cb, progress_cb, cancel_flag
|
| 1129 |
+
)
|
| 1130 |
+
if not downloaded or cancel_flag[0]:
|
| 1131 |
+
log_cb("[X] No se descargó ningún video via torrent.")
|
| 1132 |
+
done_cb(False, "Sin videos descargados.")
|
| 1133 |
+
return
|
| 1134 |
+
log_cb(f"[OK] {len(downloaded)} video(s) listos para renderizar.")
|
| 1135 |
+
sources = downloaded
|
| 1136 |
+
is_url = False
|
| 1137 |
+
file_names = [to_leet(Path(p).stem) for p in sources]
|
| 1138 |
+
if len(sources) > 1:
|
| 1139 |
+
file_names = [f"{to_leet(series_name)}_E{i+1:02d}"
|
| 1140 |
+
for i in range(len(sources))]
|
| 1141 |
+
|
| 1142 |
+
total = len(sources)
|
| 1143 |
+
for idx, (src, fname) in enumerate(zip(sources, file_names)):
|
| 1144 |
+
if cancel_flag[0]: break
|
| 1145 |
+
|
| 1146 |
+
mode_label = {"scratch": "Renderizar desde cero",
|
| 1147 |
+
"auto": "Auto (audio separado + miniaturas)"}.get(render_mode, "Copiar")
|
| 1148 |
+
log_cb(f"\n[{idx+1}/{total}] {fname} (modo: {mode_label})")
|
| 1149 |
+
progress_cb(int(idx/total*10), f"[{idx+1}/{total}] Preparando...")
|
| 1150 |
+
|
| 1151 |
+
tmp_root = output_root / f"tmp_{uuid.uuid4().hex[:8]}"
|
| 1152 |
+
work_dir = tmp_root / series_name / season_folder
|
| 1153 |
+
work_dir.mkdir(parents=True, exist_ok=True)
|
| 1154 |
+
|
| 1155 |
+
log_cb(f"[1/4] Renderizando: {fname}")
|
| 1156 |
+
ok = render_hls(src, is_url, work_dir, fname,
|
| 1157 |
+
log_cb, progress_cb, cancel_flag,
|
| 1158 |
+
render_mode=render_mode, resolutions=resolutions)
|
| 1159 |
+
if not ok or cancel_flag[0]:
|
| 1160 |
+
log_cb("[X] Renderizado fallido o cancelado.")
|
| 1161 |
+
shutil.rmtree(tmp_root, ignore_errors=True)
|
| 1162 |
+
continue
|
| 1163 |
+
|
| 1164 |
+
log_cb(f"[2/4] Subiendo al Bucket de HuggingFace...")
|
| 1165 |
+
remote_path = f"{series_name}/{season_folder}"
|
| 1166 |
+
hf_ok = upload_huggingface(
|
| 1167 |
+
hf_token, hf_repo,
|
| 1168 |
+
work_dir, remote_path,
|
| 1169 |
+
log_cb, progress_cb, cancel_flag
|
| 1170 |
+
)
|
| 1171 |
+
if not hf_ok:
|
| 1172 |
+
log_cb("[WARN] Subida al Bucket incompleta/fallida.")
|
| 1173 |
+
|
| 1174 |
+
gh_link = None
|
| 1175 |
+
if gh_enabled and not cancel_flag[0]:
|
| 1176 |
+
log_cb(f"[3/4] Subiendo a GitHub...")
|
| 1177 |
+
manifest_file = f"{fname}_master.m3u8"
|
| 1178 |
+
repo_name = clean_repo(fname)
|
| 1179 |
+
gh_link = upload_github(
|
| 1180 |
+
gh_token, repo_name, work_dir, manifest_file,
|
| 1181 |
+
gh_batch, log_cb, progress_cb, cancel_flag
|
| 1182 |
+
)
|
| 1183 |
+
else:
|
| 1184 |
+
log_cb("[3/4] GitHub desactivado, omitiendo.")
|
| 1185 |
+
|
| 1186 |
+
if gh_link:
|
| 1187 |
+
all_links.append(f"{fname}\n{gh_link}")
|
| 1188 |
+
|
| 1189 |
+
if del_locals and hf_ok and not cancel_flag[0]:
|
| 1190 |
+
log_cb(f"[4/4] Borrando archivos temporales...")
|
| 1191 |
+
shutil.rmtree(tmp_root, ignore_errors=True)
|
| 1192 |
+
log_cb("[OK] Temporales eliminados.")
|
| 1193 |
+
else:
|
| 1194 |
+
final = output_root / series_name / season_folder
|
| 1195 |
+
final.parent.mkdir(parents=True, exist_ok=True)
|
| 1196 |
+
if final.exists(): shutil.rmtree(final, ignore_errors=True)
|
| 1197 |
+
shutil.move(str(work_dir), str(final))
|
| 1198 |
+
shutil.rmtree(tmp_root, ignore_errors=True)
|
| 1199 |
+
if not hf_ok:
|
| 1200 |
+
log_cb(f"[OK] Guardado en: {final} (conservado por subida incompleta)")
|
| 1201 |
+
else:
|
| 1202 |
+
log_cb(f"[OK] Guardado en: {final}")
|
| 1203 |
+
|
| 1204 |
+
progress_cb(int((idx+1)/total*100), f"[{idx+1}/{total}] Completado")
|
| 1205 |
+
|
| 1206 |
+
if is_torrent and del_locals and torrent_dl_dir is not None:
|
| 1207 |
+
try:
|
| 1208 |
+
shutil.rmtree(torrent_dl_dir, ignore_errors=True)
|
| 1209 |
+
log_cb("[OK] Directorio torrent eliminado.")
|
| 1210 |
+
except Exception:
|
| 1211 |
+
pass
|
| 1212 |
+
|
| 1213 |
+
result = "\n\n".join(all_links) if all_links else ""
|
| 1214 |
+
log_cb("\n=== TODOS COMPLETADOS ===\n" + (result or "(sin links de GitHub)"))
|
| 1215 |
+
done_cb(True, result)
|
| 1216 |
+
|
| 1217 |
+
except Exception as e:
|
| 1218 |
+
log_cb(f"\n[X] ERROR CRÍTICO: {e}\n{traceback.format_exc()}")
|
| 1219 |
+
done_cb(False, str(e))
|
| 1220 |
+
|
| 1221 |
+
# ══════════════════════════════════════════════════════════════════════════
|
| 1222 |
+
# INTERFAZ GRADIO (reemplaza la GUI Tkinter — misma lógica, misma función)
|
| 1223 |
+
# ══════════════════════════════════════════════════════════════════════════
|
| 1224 |
+
|
| 1225 |
+
_CANCEL_FLAG = [False]
|
| 1226 |
+
|
| 1227 |
+
|
| 1228 |
+
def _build_names(sources, is_url, use_tmdb, tmdb_title, tmdb_type, tmdb_season,
|
| 1229 |
+
tmdb_ep_offset, tmdb_eps, manual_name):
|
| 1230 |
+
total = len(sources)
|
| 1231 |
+
|
| 1232 |
+
if use_tmdb and tmdb_title:
|
| 1233 |
+
base = tmdb_title.split(" (")[0]
|
| 1234 |
+
if tmdb_type == "serie":
|
| 1235 |
+
snum = int(tmdb_season.split(" ")[1]) if tmdb_season else 1
|
| 1236 |
+
series_name = to_leet(base)
|
| 1237 |
+
season_folder = to_leet(f"Temporada_{snum}")
|
| 1238 |
+
ep_offset = max(tmdb_ep_offset, 0)
|
| 1239 |
+
names = []
|
| 1240 |
+
for i in range(total):
|
| 1241 |
+
ei = ep_offset + i
|
| 1242 |
+
ep_num = tmdb_eps[ei]["num"] if tmdb_eps and ei < len(tmdb_eps) else ei + 1
|
| 1243 |
+
names.append(f"{to_leet(base)}_T{snum}_E{ep_num:02d}")
|
| 1244 |
+
return series_name, season_folder, names
|
| 1245 |
+
else:
|
| 1246 |
+
series_name = to_leet(base)
|
| 1247 |
+
season_folder = to_leet("Peliculas")
|
| 1248 |
+
names = [to_leet(f"{base}_{i+1}" if total > 1 else base) for i in range(total)]
|
| 1249 |
+
return series_name, season_folder, names
|
| 1250 |
+
|
| 1251 |
+
if manual_name:
|
| 1252 |
+
series_name = to_leet(manual_name)
|
| 1253 |
+
season_folder = to_leet("Temporada_1")
|
| 1254 |
+
names = [f"{to_leet(manual_name)}_E{i+1:02d}" if total > 1 else to_leet(manual_name)
|
| 1255 |
+
for i in range(total)]
|
| 1256 |
+
return series_name, season_folder, names
|
| 1257 |
+
|
| 1258 |
+
if not is_url and sources:
|
| 1259 |
+
b = Path(sources[0]).stem
|
| 1260 |
+
series_name = to_leet(b)
|
| 1261 |
+
season_folder = to_leet("Temporada_1")
|
| 1262 |
+
names = [to_leet(Path(s).stem) for s in sources]
|
| 1263 |
+
return series_name, season_folder, names
|
| 1264 |
+
|
| 1265 |
+
series_name = "Uploads"
|
| 1266 |
+
season_folder = "Temporada_1"
|
| 1267 |
+
names = [f"V1d30_E{i+1:02d}" if total > 1 else "V1d30" for i in range(total)]
|
| 1268 |
+
return series_name, season_folder, names
|
| 1269 |
+
|
| 1270 |
+
|
| 1271 |
+
def status_line():
|
| 1272 |
+
parts = []
|
| 1273 |
+
parts.append("ffmpeg: OK" if FFMPEG_OK else "ffmpeg: NO")
|
| 1274 |
+
parts.append("yt-dlp: OK" if YTDLP_OK else "yt-dlp: NO")
|
| 1275 |
+
parts.append("HF Buckets: OK" if HF_OK else "HF: falta huggingface_hub")
|
| 1276 |
+
parts.append("aria2c: OK" if _find_aria2() else "aria2c: NO (se intentará descargar)")
|
| 1277 |
+
return " | ".join(parts)
|
| 1278 |
+
|
| 1279 |
+
|
| 1280 |
+
def selftest_tools():
|
| 1281 |
+
if not FFMPEG_OK:
|
| 1282 |
+
return "[X] ffmpeg/ffprobe no encontrados. Agrega 'ffmpeg' a packages.txt de esta Space."
|
| 1283 |
+
problems = []
|
| 1284 |
+
for name, path in (("ffmpeg", FFMPEG_PATH), ("ffprobe", FFPROBE_PATH)):
|
| 1285 |
+
try:
|
| 1286 |
+
r = subprocess.run([path or name, "-version"], capture_output=True,
|
| 1287 |
+
text=True, timeout=15, creationflags=_NO_WINDOW)
|
| 1288 |
+
if r.returncode != 0:
|
| 1289 |
+
problems.append(f"[X] {name} ({path}) falló al arrancar (code {r.returncode}).")
|
| 1290 |
+
except Exception as e:
|
| 1291 |
+
problems.append(f"[X] {name} ({path}): {e}")
|
| 1292 |
+
if problems:
|
| 1293 |
+
return "\n".join(problems)
|
| 1294 |
+
return "[OK] ffmpeg y ffprobe arrancan correctamente."
|
| 1295 |
+
|
| 1296 |
+
|
| 1297 |
+
# ─── HuggingFace: conectar y listar buckets ──────────────────────────────────
|
| 1298 |
+
def connect_hf(token):
|
| 1299 |
+
if not token or not token.strip():
|
| 1300 |
+
return gr.update(choices=[], value=None), "[X] Ingresa tu token de HuggingFace."
|
| 1301 |
+
token = token.strip()
|
| 1302 |
+
try:
|
| 1303 |
+
a = HfApi()
|
| 1304 |
+
w = a.whoami(token=token)
|
| 1305 |
+
au = w.get("name", "")
|
| 1306 |
+
try:
|
| 1307 |
+
buckets = list(list_buckets(token=token, namespace=au))
|
| 1308 |
+
except Exception:
|
| 1309 |
+
buckets = list(list_buckets(token=token))
|
| 1310 |
+
rs = [getattr(b, "id", None) or getattr(b, "bucket_id", None) for b in buckets]
|
| 1311 |
+
rs = [x for x in rs if x]
|
| 1312 |
+
msg = f"[OK] HF: {au} — {len(rs)} bucket(s) encontrado(s)."
|
| 1313 |
+
if not rs:
|
| 1314 |
+
msg += ("\n[WARN] No se encontraron buckets. Puedes escribir el nombre de un "
|
| 1315 |
+
"bucket nuevo directamente; se creará al subir el primer video.")
|
| 1316 |
+
return gr.update(choices=rs, value=(rs[0] if rs else None)), msg
|
| 1317 |
+
except Exception as e:
|
| 1318 |
+
return gr.update(choices=[], value=None), f"[X] HF Error: {e}\n{traceback.format_exc()}"
|
| 1319 |
+
|
| 1320 |
+
|
| 1321 |
+
# ─── TMDb ─────────────────────────────────────────────────────────────────
|
| 1322 |
+
def test_tmdb_key(key):
|
| 1323 |
+
key = (key or "").strip() or TMDB_KEY
|
| 1324 |
+
try:
|
| 1325 |
+
d = fetch_tmdb(f"https://api.themoviedb.org/3/configuration?api_key={key}")
|
| 1326 |
+
if isinstance(d, dict) and d.get("images"):
|
| 1327 |
+
return "[OK] TMDb: API key válida."
|
| 1328 |
+
return "[X] TMDb: respuesta inesperada."
|
| 1329 |
+
except Exception as e:
|
| 1330 |
+
return f"[X] TMDb: {e}"
|
| 1331 |
+
|
| 1332 |
+
|
| 1333 |
+
def search_tmdb(query, ttype, key):
|
| 1334 |
+
query = (query or "").strip()
|
| 1335 |
+
if not query:
|
| 1336 |
+
return gr.update(choices=[], value=None), {}, "Escribe un título para buscar."
|
| 1337 |
+
key = (key or "").strip() or TMDB_KEY
|
| 1338 |
+
t = "movie" if ttype == "pelicula" else "tv"
|
| 1339 |
+
try:
|
| 1340 |
+
d = fetch_tmdb(
|
| 1341 |
+
f"https://api.themoviedb.org/3/search/{t}"
|
| 1342 |
+
f"?api_key={key}&query={urllib.parse.quote(query)}&language=es-MX"
|
| 1343 |
+
)
|
| 1344 |
+
res, tmdb_map = [], {}
|
| 1345 |
+
for r in d.get("results", [])[:15]:
|
| 1346 |
+
lbl = (f"{r.get('title') or r.get('name')} "
|
| 1347 |
+
f"({(r.get('release_date') or r.get('first_air_date') or 'N/A')[:4]})")
|
| 1348 |
+
res.append(lbl)
|
| 1349 |
+
tmdb_map[lbl] = r.get("id")
|
| 1350 |
+
if not res:
|
| 1351 |
+
return gr.update(choices=[], value=None), {}, f"[TMDb] Sin resultados para '{query}'."
|
| 1352 |
+
return gr.update(choices=res, value=res[0]), tmdb_map, f"[OK] TMDb: {len(res)} resultado(s)."
|
| 1353 |
+
except Exception as e:
|
| 1354 |
+
return gr.update(choices=[], value=None), {}, f"[X] TMDb: {e}"
|
| 1355 |
+
|
| 1356 |
+
|
| 1357 |
+
def on_select_tmdb_result(result_label, ttype, key, tmdb_map):
|
| 1358 |
+
if ttype == "pelicula":
|
| 1359 |
+
return gr.update(choices=[], value=None, interactive=False), []
|
| 1360 |
+
tid = (tmdb_map or {}).get(result_label)
|
| 1361 |
+
if not tid:
|
| 1362 |
+
return gr.update(choices=[], value=None, interactive=False), []
|
| 1363 |
+
key = (key or "").strip() or TMDB_KEY
|
| 1364 |
+
try:
|
| 1365 |
+
d = fetch_tmdb(f"https://api.themoviedb.org/3/tv/{tid}?api_key={key}&language=es-MX")
|
| 1366 |
+
ss = [f"Temporada {s['season_number']}" for s in d.get("seasons", []) if s["season_number"] > 0]
|
| 1367 |
+
return gr.update(choices=ss, value=(ss[0] if ss else None), interactive=True), []
|
| 1368 |
+
except Exception:
|
| 1369 |
+
return gr.update(choices=[], value=None, interactive=False), []
|
| 1370 |
+
|
| 1371 |
+
|
| 1372 |
+
def on_select_season(result_label, season_label, ttype, key, tmdb_map):
|
| 1373 |
+
if ttype == "pelicula" or not season_label:
|
| 1374 |
+
return gr.update(choices=[], value=None, interactive=False), []
|
| 1375 |
+
tid = (tmdb_map or {}).get(result_label)
|
| 1376 |
+
snum = season_label.split(" ")[1] if season_label else "1"
|
| 1377 |
+
key = (key or "").strip() or TMDB_KEY
|
| 1378 |
+
try:
|
| 1379 |
+
d = fetch_tmdb(f"https://api.themoviedb.org/3/tv/{tid}/season/{snum}?api_key={key}&language=es-MX")
|
| 1380 |
+
eps = [{"num": e["episode_number"], "name": e["name"]} for e in d.get("episodes", [])]
|
| 1381 |
+
labels = [f"Ep {e['num']:02d}: {e['name']}" for e in eps]
|
| 1382 |
+
return gr.update(choices=labels, value=(labels[0] if labels else None), interactive=True), eps
|
| 1383 |
+
except Exception:
|
| 1384 |
+
return gr.update(choices=[], value=None, interactive=False), []
|
| 1385 |
+
|
| 1386 |
+
|
| 1387 |
+
# ─── Toggle de visibilidad de UI ─────────────────────────────────────────────
|
| 1388 |
+
def toggle_render_mode(mode):
|
| 1389 |
+
show_res = mode in ("scratch", "auto")
|
| 1390 |
+
return gr.update(visible=show_res)
|
| 1391 |
+
|
| 1392 |
+
|
| 1393 |
+
def toggle_source_mode(mode):
|
| 1394 |
+
return (
|
| 1395 |
+
gr.update(visible=(mode == "url")),
|
| 1396 |
+
gr.update(visible=(mode == "file")),
|
| 1397 |
+
gr.update(visible=(mode == "torrent")),
|
| 1398 |
+
gr.update(visible=(mode == "container")),
|
| 1399 |
+
gr.update(visible=(mode != "container")), # card render
|
| 1400 |
+
gr.update(visible=(mode != "container")), # card tmdb
|
| 1401 |
+
)
|
| 1402 |
+
|
| 1403 |
+
|
| 1404 |
+
def toggle_github(enabled):
|
| 1405 |
+
return gr.update(visible=bool(enabled))
|
| 1406 |
+
|
| 1407 |
+
|
| 1408 |
+
# ─── Directorio de carga para modo "Carpeta Contenedora" ─────────────────────
|
| 1409 |
+
def _materialize_container_upload(files, manual_path):
|
| 1410 |
+
"""Si el usuario subió archivos (gr.File file_count='multiple'), los
|
| 1411 |
+
copiamos a una carpeta local. Si no, usamos la ruta manual (útil si la
|
| 1412 |
+
Space tiene almacenamiento persistente y ya existe la carpeta ahí)."""
|
| 1413 |
+
if files:
|
| 1414 |
+
dest = BASE_DIR / "Videos_Procesados" / f"container_{uuid.uuid4().hex[:8]}"
|
| 1415 |
+
dest.mkdir(parents=True, exist_ok=True)
|
| 1416 |
+
for f in files:
|
| 1417 |
+
src_path = Path(f.name if hasattr(f, "name") else f)
|
| 1418 |
+
rel = getattr(f, "orig_name", None) or src_path.name
|
| 1419 |
+
target = dest / rel
|
| 1420 |
+
target.parent.mkdir(parents=True, exist_ok=True)
|
| 1421 |
+
shutil.copy2(src_path, target)
|
| 1422 |
+
return str(dest)
|
| 1423 |
+
return (manual_path or "").strip()
|
| 1424 |
+
|
| 1425 |
+
|
| 1426 |
+
# ─── Lanzamiento del job (generador para streaming de logs/progreso) ────────
|
| 1427 |
+
@spaces.GPU(duration=300)
|
| 1428 |
+
def start_job(source_mode,
|
| 1429 |
+
url_text, file_path, torrent_text, torrent_dir,
|
| 1430 |
+
container_files, container_manual_path, container_remote,
|
| 1431 |
+
hf_token, hf_repo,
|
| 1432 |
+
gh_enabled, gh_token, gh_batch,
|
| 1433 |
+
del_locals,
|
| 1434 |
+
render_mode, res_720, res_1080, res_2160,
|
| 1435 |
+
use_tmdb, tmdb_result, tmdb_type, tmdb_season, tmdb_ep_cb, tmdb_eps_state,
|
| 1436 |
+
tmdb_key, manual_name):
|
| 1437 |
+
|
| 1438 |
+
global _CANCEL_FLAG
|
| 1439 |
+
_CANCEL_FLAG = [False]
|
| 1440 |
+
|
| 1441 |
+
log_lines = []
|
| 1442 |
+
def _append(msg):
|
| 1443 |
+
log_lines.append(msg)
|
| 1444 |
+
return "\n".join(log_lines)
|
| 1445 |
+
|
| 1446 |
+
hf_token = (hf_token or "").strip()
|
| 1447 |
+
hf_repo = (hf_repo or "").strip()
|
| 1448 |
+
if not hf_token or not hf_repo:
|
| 1449 |
+
yield _append("[X] Ingresa el token HF y selecciona/escribe un bucket."), 0, ""
|
| 1450 |
+
return
|
| 1451 |
+
|
| 1452 |
+
try:
|
| 1453 |
+
gh_batch_i = int(gh_batch or 30)
|
| 1454 |
+
except Exception:
|
| 1455 |
+
gh_batch_i = 30
|
| 1456 |
+
|
| 1457 |
+
log_q = queue.Queue()
|
| 1458 |
+
def log_cb(m): log_q.put(("log", m))
|
| 1459 |
+
def progress_cb(p, l): log_q.put(("prog", p, l))
|
| 1460 |
+
def done_cb(ok, result): log_q.put(("done", ok, result))
|
| 1461 |
+
|
| 1462 |
+
# ─── Modo Carpeta Contenedora ───
|
| 1463 |
+
if source_mode == "container":
|
| 1464 |
+
folder = _materialize_container_upload(container_files, container_manual_path)
|
| 1465 |
+
if not folder:
|
| 1466 |
+
yield _append("[X] Sube archivos de la carpeta o indica una ruta local."), 0, ""
|
| 1467 |
+
return
|
| 1468 |
+
fp = Path(folder)
|
| 1469 |
+
if not fp.exists() or not fp.is_dir():
|
| 1470 |
+
yield _append(f"[X] La carpeta no existe: {folder}"), 0, ""
|
| 1471 |
+
return
|
| 1472 |
+
remote_path = (container_remote or "").strip() or fp.name
|
| 1473 |
+
|
| 1474 |
+
job = {
|
| 1475 |
+
"hf_token": hf_token, "hf_repo": hf_repo,
|
| 1476 |
+
"gh_enabled": gh_enabled, "gh_token": (gh_token or "").strip(), "gh_batch": gh_batch_i,
|
| 1477 |
+
"cancel_flag": _CANCEL_FLAG,
|
| 1478 |
+
"container_folder": str(fp),
|
| 1479 |
+
"container_remote_path": remote_path,
|
| 1480 |
+
}
|
| 1481 |
+
thread = threading.Thread(target=upload_container_folder,
|
| 1482 |
+
args=(job, log_cb, progress_cb, done_cb), daemon=True)
|
| 1483 |
+
thread.start()
|
| 1484 |
+
|
| 1485 |
+
else:
|
| 1486 |
+
if not FFMPEG_OK:
|
| 1487 |
+
yield _append("[X] No se encontró ffmpeg/ffprobe. Agrega 'ffmpeg' a packages.txt de la Space."), 0, ""
|
| 1488 |
+
return
|
| 1489 |
+
|
| 1490 |
+
resolutions = []
|
| 1491 |
+
if render_mode in ("scratch", "auto"):
|
| 1492 |
+
if res_720: resolutions.append(720)
|
| 1493 |
+
if res_1080: resolutions.append(1080)
|
| 1494 |
+
if res_2160: resolutions.append(2160)
|
| 1495 |
+
if not resolutions:
|
| 1496 |
+
yield _append("[X] Elige al menos una resolución (720p / 1080p / 4K)."), 0, ""
|
| 1497 |
+
return
|
| 1498 |
+
else:
|
| 1499 |
+
resolutions = [720, 1080]
|
| 1500 |
+
|
| 1501 |
+
is_url = source_mode == "url"
|
| 1502 |
+
is_torrent = source_mode == "torrent"
|
| 1503 |
+
|
| 1504 |
+
if source_mode == "url":
|
| 1505 |
+
sources = [l.strip() for l in (url_text or "").split("\n") if l.strip()]
|
| 1506 |
+
elif source_mode == "file":
|
| 1507 |
+
sources = [file_path] if file_path else []
|
| 1508 |
+
else:
|
| 1509 |
+
raw = (torrent_text or "").strip()
|
| 1510 |
+
if not raw:
|
| 1511 |
+
yield _append("[X] Agrega al menos un magnet link o ruta .torrent."), 0, ""
|
| 1512 |
+
return
|
| 1513 |
+
sources = [l.strip() for l in raw.split("\n") if l.strip() and not l.strip().startswith("#")]
|
| 1514 |
+
is_url = False
|
| 1515 |
+
|
| 1516 |
+
if not sources:
|
| 1517 |
+
yield _append("[X] Agrega URLs, sube un archivo o ingresa magnets."), 0, ""
|
| 1518 |
+
return
|
| 1519 |
+
|
| 1520 |
+
if source_mode == "file":
|
| 1521 |
+
fp = Path(sources[0])
|
| 1522 |
+
if not fp.exists():
|
| 1523 |
+
yield _append(f"[X] El archivo no existe: {sources[0]}"), 0, ""
|
| 1524 |
+
return
|
| 1525 |
+
if fp.stat().st_size <= 0:
|
| 1526 |
+
yield _append(f"[X] El archivo está vacío (0 bytes): {sources[0]}"), 0, ""
|
| 1527 |
+
return
|
| 1528 |
+
|
| 1529 |
+
tmdb_ep_offset = 0
|
| 1530 |
+
if tmdb_ep_cb and tmdb_eps_state:
|
| 1531 |
+
labels = [f"Ep {e['num']:02d}: {e['name']}" for e in tmdb_eps_state]
|
| 1532 |
+
if tmdb_ep_cb in labels:
|
| 1533 |
+
tmdb_ep_offset = labels.index(tmdb_ep_cb)
|
| 1534 |
+
|
| 1535 |
+
series_name, season_folder, file_names = _build_names(
|
| 1536 |
+
sources, is_url, use_tmdb, tmdb_result, tmdb_type, tmdb_season,
|
| 1537 |
+
tmdb_ep_offset, tmdb_eps_state, (manual_name or "").strip()
|
| 1538 |
+
)
|
| 1539 |
+
|
| 1540 |
+
job = {
|
| 1541 |
+
"hf_token": hf_token, "hf_repo": hf_repo,
|
| 1542 |
+
"gh_enabled": gh_enabled, "gh_token": (gh_token or "").strip(), "gh_batch": gh_batch_i,
|
| 1543 |
+
"del_locals": bool(del_locals),
|
| 1544 |
+
"sources": sources, "is_url": is_url, "is_torrent": is_torrent,
|
| 1545 |
+
"series_name": series_name, "season_folder": season_folder, "file_names": file_names,
|
| 1546 |
+
"cancel_flag": _CANCEL_FLAG,
|
| 1547 |
+
"render_mode": render_mode, "resolutions": resolutions,
|
| 1548 |
+
}
|
| 1549 |
+
thread = threading.Thread(target=run_job, args=(job, log_cb, progress_cb, done_cb), daemon=True)
|
| 1550 |
+
thread.start()
|
| 1551 |
+
|
| 1552 |
+
progress_val = 0
|
| 1553 |
+
while True:
|
| 1554 |
+
try:
|
| 1555 |
+
item = log_q.get(timeout=0.5)
|
| 1556 |
+
except queue.Empty:
|
| 1557 |
+
if not thread.is_alive():
|
| 1558 |
+
break
|
| 1559 |
+
yield "\n".join(log_lines), progress_val, gr.update()
|
| 1560 |
+
continue
|
| 1561 |
+
|
| 1562 |
+
kind = item[0]
|
| 1563 |
+
if kind == "log":
|
| 1564 |
+
yield _append(item[1]), progress_val, gr.update()
|
| 1565 |
+
elif kind == "prog":
|
| 1566 |
+
progress_val = item[1]
|
| 1567 |
+
yield "\n".join(log_lines), progress_val, gr.update()
|
| 1568 |
+
elif kind == "done":
|
| 1569 |
+
ok, result = item[1], item[2]
|
| 1570 |
+
final_pct = 100 if ok else progress_val
|
| 1571 |
+
yield "\n".join(log_lines), final_pct, (result or "(sin links de GitHub)")
|
| 1572 |
+
break
|
| 1573 |
+
|
| 1574 |
+
|
| 1575 |
+
def cancel_job():
|
| 1576 |
+
_CANCEL_FLAG[0] = True
|
| 1577 |
+
return "[!] Cancelado por el usuario."
|
| 1578 |
+
|
| 1579 |
+
|
| 1580 |
+
# ─── Construcción de la interfaz ─────────────────────────────────────────────
|
| 1581 |
+
with gr.Blocks(title="VCPro HLS Unified — HF Spaces") as demo:
|
| 1582 |
+
gr.Markdown("## VCPro HLS Unified\nRender · HuggingFace Buckets · GitHub — versión Gradio para Spaces")
|
| 1583 |
+
status_box = gr.Markdown(status_line())
|
| 1584 |
+
|
| 1585 |
+
tmdb_map_state = gr.State({})
|
| 1586 |
+
tmdb_eps_state = gr.State([])
|
| 1587 |
+
|
| 1588 |
+
with gr.Row():
|
| 1589 |
+
with gr.Column(scale=1, min_width=380):
|
| 1590 |
+
with gr.Group():
|
| 1591 |
+
gr.Markdown("### HuggingFace Buckets (obligatorio)")
|
| 1592 |
+
hf_token_in = gr.Textbox(label="Token HF", type="password")
|
| 1593 |
+
hf_connect_btn = gr.Button("Conectar", variant="primary")
|
| 1594 |
+
hf_repo_in = gr.Dropdown(label="Bucket", allow_custom_value=True, choices=[])
|
| 1595 |
+
hf_status_out = gr.Markdown("")
|
| 1596 |
+
gr.Markdown("Si la lista viene vacía, escribe el nombre del bucket manualmente "
|
| 1597 |
+
"(se creará automáticamente al subir).")
|
| 1598 |
+
|
| 1599 |
+
with gr.Group():
|
| 1600 |
+
gr.Markdown("### Opciones")
|
| 1601 |
+
del_locals_in = gr.Checkbox(label="Borrar temporales al finalizar (después de todo)", value=True)
|
| 1602 |
+
gr.Markdown("Orden: Render → HF Buckets → GitHub (si activo) → Borrar (si activo)")
|
| 1603 |
+
|
| 1604 |
+
with gr.Group():
|
| 1605 |
+
gr.Markdown("### GitHub (opcional)")
|
| 1606 |
+
gh_enabled_in = gr.Checkbox(label="Activar subida a GitHub", value=False)
|
| 1607 |
+
with gr.Group(visible=False) as gh_inner:
|
| 1608 |
+
gh_token_in = gr.Textbox(label="Token GH", type="password")
|
| 1609 |
+
gh_batch_in = gr.Textbox(label="Batch", value="30")
|
| 1610 |
+
|
| 1611 |
+
with gr.Group(visible=True) as card_render:
|
| 1612 |
+
gr.Markdown("### Modo de Renderizado (Automático)")
|
| 1613 |
+
gr.Markdown("El sistema elegirá automáticamente `copy` (≤ 5 Mbps) o `auto` (> 5 Mbps). La resolución única será 1080p.")
|
| 1614 |
+
render_mode_in = gr.State(value="auto")
|
| 1615 |
+
res_group = gr.State(value=False)
|
| 1616 |
+
res_720_in = gr.State(value=False)
|
| 1617 |
+
res_1080_in = gr.State(value=True)
|
| 1618 |
+
res_2160_in = gr.State(value=False)
|
| 1619 |
+
|
| 1620 |
+
with gr.Group(visible=True) as card_tmdb:
|
| 1621 |
+
gr.Markdown("### TMDb & Nombre")
|
| 1622 |
+
use_tmdb_in = gr.Checkbox(label="Usar TMDb para nombrar", value=False)
|
| 1623 |
+
tmdb_key_in = gr.Textbox(label="API Key TMDb", value=TMDB_KEY)
|
| 1624 |
+
tmdb_test_btn = gr.Button("Probar key")
|
| 1625 |
+
tmdb_test_out = gr.Markdown("")
|
| 1626 |
+
tmdb_type_in = gr.Radio(choices=[("Serie", "serie"), ("Película", "pelicula")],
|
| 1627 |
+
value="serie", label=None)
|
| 1628 |
+
tmdb_query_in = gr.Textbox(label="Buscar título")
|
| 1629 |
+
tmdb_search_btn = gr.Button("Buscar")
|
| 1630 |
+
tmdb_search_status = gr.Markdown("")
|
| 1631 |
+
tmdb_result_in = gr.Dropdown(label="Resultado", choices=[])
|
| 1632 |
+
tmdb_season_in = gr.Dropdown(label="Temporada", choices=[], interactive=False)
|
| 1633 |
+
tmdb_ep_in = gr.Dropdown(label="Episodio (desde)", choices=[], interactive=False)
|
| 1634 |
+
manual_name_in = gr.Textbox(label="O nombre manual")
|
| 1635 |
+
|
| 1636 |
+
with gr.Column(scale=1, min_width=420):
|
| 1637 |
+
with gr.Group():
|
| 1638 |
+
gr.Markdown("### Fuente de Video")
|
| 1639 |
+
source_mode_in = gr.Radio(
|
| 1640 |
+
choices=[("URLs", "url"), ("Archivo", "file"),
|
| 1641 |
+
("BitTorrent", "torrent"), ("Carpeta Contenedora", "container")],
|
| 1642 |
+
value="url", label=None)
|
| 1643 |
+
|
| 1644 |
+
with gr.Group(visible=True) as url_group:
|
| 1645 |
+
url_text_in = gr.Textbox(label="URLs (una por línea)", lines=5)
|
| 1646 |
+
|
| 1647 |
+
with gr.Group(visible=False) as file_group:
|
| 1648 |
+
file_in = gr.File(label="Archivo de video", type="filepath")
|
| 1649 |
+
|
| 1650 |
+
with gr.Group(visible=False) as torrent_group:
|
| 1651 |
+
torrent_text_in = gr.Textbox(label="Magnets o rutas a .torrent (uno por línea)", lines=5)
|
| 1652 |
+
torrent_dir_in = gr.Textbox(label="Carpeta de descarga",
|
| 1653 |
+
value=str(BASE_DIR / "Videos_Procesados" / "VCPro_Torrents"))
|
| 1654 |
+
gr.Markdown("Para BitTorrent en Spaces, agrega la línea `aria2` a packages.txt "
|
| 1655 |
+
"de este repositorio (instalación vía apt). Si no está presente, "
|
| 1656 |
+
"la app intentará descargar un binario estático automáticamente.")
|
| 1657 |
+
|
| 1658 |
+
with gr.Group(visible=False) as container_group:
|
| 1659 |
+
gr.Markdown("Carpeta ya renderizada (HLS) a subir tal cual.")
|
| 1660 |
+
container_files_in = gr.File(label="Sube los archivos de la carpeta renderizada",
|
| 1661 |
+
file_count="multiple")
|
| 1662 |
+
container_manual_path_in = gr.Textbox(
|
| 1663 |
+
label="...o ruta local ya existente en el servidor (almacenamiento persistente)")
|
| 1664 |
+
container_remote_in = gr.Textbox(label="Ruta remota dentro del Bucket")
|
| 1665 |
+
|
| 1666 |
+
with gr.Row():
|
| 1667 |
+
start_btn = gr.Button("INICIAR PROCESAMIENTO", variant="primary")
|
| 1668 |
+
cancel_btn = gr.Button("DETENER", variant="stop")
|
| 1669 |
+
|
| 1670 |
+
with gr.Group():
|
| 1671 |
+
gr.Markdown("### Links Generados")
|
| 1672 |
+
links_out = gr.Textbox(label=None, lines=4, interactive=False)
|
| 1673 |
+
|
| 1674 |
+
with gr.Group():
|
| 1675 |
+
gr.Markdown("### Estado y Progreso")
|
| 1676 |
+
progress_out = gr.Slider(label="Progreso %", minimum=0, maximum=100, value=0, interactive=False)
|
| 1677 |
+
log_out = gr.Textbox(label="Log", lines=22, interactive=False, autoscroll=True)
|
| 1678 |
+
|
| 1679 |
+
hf_connect_btn.click(fn=connect_hf, inputs=[hf_token_in], outputs=[hf_repo_in, hf_status_out])
|
| 1680 |
+
|
| 1681 |
+
gh_enabled_in.change(fn=toggle_github, inputs=[gh_enabled_in], outputs=[gh_inner])
|
| 1682 |
+
|
| 1683 |
+
# render_mode_in es ahora automático, no requiere evento de cambio.
|
| 1684 |
+
|
| 1685 |
+
source_mode_in.change(
|
| 1686 |
+
fn=toggle_source_mode, inputs=[source_mode_in],
|
| 1687 |
+
outputs=[url_group, file_group, torrent_group, container_group, card_render, card_tmdb]
|
| 1688 |
+
)
|
| 1689 |
+
|
| 1690 |
+
tmdb_test_btn.click(fn=test_tmdb_key, inputs=[tmdb_key_in], outputs=[tmdb_test_out])
|
| 1691 |
+
|
| 1692 |
+
tmdb_search_btn.click(
|
| 1693 |
+
fn=search_tmdb, inputs=[tmdb_query_in, tmdb_type_in, tmdb_key_in],
|
| 1694 |
+
outputs=[tmdb_result_in, tmdb_map_state, tmdb_search_status]
|
| 1695 |
+
)
|
| 1696 |
+
|
| 1697 |
+
tmdb_result_in.change(
|
| 1698 |
+
fn=on_select_tmdb_result,
|
| 1699 |
+
inputs=[tmdb_result_in, tmdb_type_in, tmdb_key_in, tmdb_map_state],
|
| 1700 |
+
outputs=[tmdb_season_in, tmdb_eps_state]
|
| 1701 |
+
)
|
| 1702 |
+
|
| 1703 |
+
tmdb_season_in.change(
|
| 1704 |
+
fn=on_select_season,
|
| 1705 |
+
inputs=[tmdb_result_in, tmdb_season_in, tmdb_type_in, tmdb_key_in, tmdb_map_state],
|
| 1706 |
+
outputs=[tmdb_ep_in, tmdb_eps_state]
|
| 1707 |
+
)
|
| 1708 |
+
|
| 1709 |
+
start_btn.click(
|
| 1710 |
+
fn=start_job,
|
| 1711 |
+
inputs=[source_mode_in,
|
| 1712 |
+
url_text_in, file_in, torrent_text_in, torrent_dir_in,
|
| 1713 |
+
container_files_in, container_manual_path_in, container_remote_in,
|
| 1714 |
+
hf_token_in, hf_repo_in,
|
| 1715 |
+
gh_enabled_in, gh_token_in, gh_batch_in,
|
| 1716 |
+
del_locals_in,
|
| 1717 |
+
render_mode_in, res_720_in, res_1080_in, res_2160_in,
|
| 1718 |
+
use_tmdb_in, tmdb_result_in, tmdb_type_in, tmdb_season_in, tmdb_ep_in, tmdb_eps_state,
|
| 1719 |
+
tmdb_key_in, manual_name_in],
|
| 1720 |
+
outputs=[log_out, progress_out, links_out],
|
| 1721 |
+
)
|
| 1722 |
+
|
| 1723 |
+
cancel_btn.click(fn=cancel_job, outputs=[log_out])
|
| 1724 |
+
|
| 1725 |
+
demo.load(fn=selftest_tools, outputs=[status_box])
|
| 1726 |
+
|
| 1727 |
+
|
| 1728 |
+
if __name__ == "__main__":
|
| 1729 |
+
demo.queue().launch()
|
packages.txt
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
ffmpeg
|
| 2 |
+
aria2
|
requirements.txt
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gradio
|
| 2 |
+
huggingface_hub
|
| 3 |
+
requests
|
| 4 |
+
spaces
|
| 5 |
+
yt-dlp
|