xv / video_converter_pro.py
CineMax's picture
Upload 2 files
8f9c0c8 verified
"""
Video Converter Pro β€” App nativa Windows
Convierte video y sube a HuggingFace. Sin Gradio.
Auto-elevaciΓ³n a administrador.
"""
import sys
import os
import ctypes
import subprocess
import threading
import tempfile
import shutil
import re
import json
import uuid
import tkinter as tk
from tkinter import ttk, filedialog, messagebox
from pathlib import Path
# ─── AUTO-ELEVACIΓ“N ADMINISTRADOR ───────────────────────────
def is_admin():
try:
return ctypes.windll.shell32.IsUserAnAdmin()
except:
return False
def elevate():
if not is_admin():
ctypes.windll.shell32.ShellExecuteW(
None, "runas", sys.executable, " ".join(sys.argv), None, 1
)
sys.exit()
elevate()
# ─── HF IMPORT ──────────────────────────────────────────────
try:
from huggingface_hub import HfApi, list_models
HF_OK = True
except ImportError:
HF_OK = False
# ─── COLORES / TEMA ─────────────────────────────────────────
BG = "#0b0f1a"
BG2 = "#111827"
BG3 = "#1a2235"
ACCENT = "#3b82f6"
ACCENT2 = "#6366f1"
GREEN = "#22c55e"
RED = "#ef4444"
YELLOW = "#f59e0b"
FG = "#e2e8f0"
FG2 = "#94a3b8"
FG3 = "#475569"
BORDER = "#1e2d42"
FONT_MAIN = ("Consolas", 10)
FONT_BIG = ("Consolas", 12, "bold")
FONT_SM = ("Consolas", 9)
# ─── UTILS ──────────────────────────────────────────────────
def safe_name(s, maxlen=120):
return re.sub(r'[<>:"/\\|?*\x00-\x1f]', '_', s).strip()[:maxlen]
def fmt_dur(secs):
s = int(secs)
return f"{s//3600:02d}:{(s%3600)//60:02d}:{s%60:02d}"
# ─── FFPROBE ────────────────────────────────────────────────
def probe(source):
info = {"audio": [], "subs": [], "duration": 0.0, "title": ""}
try:
r = subprocess.run(
["ffprobe", "-v", "quiet", "-print_format", "json",
"-show_format", "-show_streams", source],
capture_output=True, text=True, timeout=90
)
if r.returncode != 0:
return info
data = json.loads(r.stdout)
tags = data.get("format", {}).get("tags", {})
info["title"] = (tags.get("title") or tags.get("TITLE") or "").strip()
info["duration"] = float(data.get("format", {}).get("duration", 0) or 0)
ai = si = 0
for s in data.get("streams", []):
t = s.get("tags", {})
ct = s.get("codec_type", "")
if ct == "audio":
info["audio"].append({
"idx": ai, "codec": s.get("codec_name", "?"),
"lang": t.get("language", "und"), "ch": s.get("channels", 2),
"title": t.get("title", ""),
})
ai += 1
elif ct == "subtitle":
info["subs"].append({
"idx": si, "codec": s.get("codec_name", "?"),
"lang": t.get("language", "und"), "title": t.get("title", ""),
"forced": s.get("disposition", {}).get("forced", 0) == 1,
})
si += 1
except Exception as e:
pass
return info
# ─── FFMPEG ─────────────────────────────────────────────────
NET_ARGS = [
"-user_agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64)",
"-headers", "Referer: https://google.com\r\n",
"-timeout", "180000000",
"-reconnect", "1", "-reconnect_streamed", "1",
"-reconnect_at_eof", "1", "-reconnect_delay_max", "30",
"-rw_timeout", "180000000", "-multiple_requests", "1",
]
def run_ffmpeg(cmd, total, log_cb, progress_cb, label):
try:
proc = subprocess.Popen(
cmd, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE,
universal_newlines=True, bufsize=1
)
pat = re.compile(r"time=(\d+):(\d+):(\d+)\.(\d+)")
for line in proc.stderr:
m = pat.search(line)
if m:
h, mi, s, cs = map(int, m.groups())
cur = h*3600 + mi*60 + s + cs/100
pct = min(99, int(cur / max(total, 1) * 100))
progress_cb(pct, f"{label}: {pct}% [{fmt_dur(cur)} / {fmt_dur(total)}]")
proc.wait()
return proc.returncode == 0
except Exception as e:
log_cb(f" βœ— ffmpeg: {e}")
return False
# ─── HF UPLOAD ──────────────────────────────────────────────
def hf_upload(token, repo_id, folder_path, log_cb, progress_cb):
if not HF_OK:
log_cb(" βœ— huggingface_hub no instalado")
return False
try:
api = HfApi(token=token)
try:
api.create_repo(repo_id=repo_id, repo_type="model", private=True, exist_ok=True)
except:
pass
files = list(Path(folder_path).iterdir())
for i, f in enumerate(files):
if f.is_file():
rpath = f"videos/{Path(folder_path).name}/{f.name}"
log_cb(f" ↑ {f.name}")
progress_cb(int(i/len(files)*100), f"Subiendo {i+1}/{len(files)}")
api.upload_file(
path_or_fileobj=str(f),
path_in_repo=rpath,
repo_id=repo_id,
repo_type="model",
)
progress_cb(100, "Subida completa")
log_cb(f" βœ“ Subido β†’ {repo_id}/videos/{Path(folder_path).name}/")
return True
except Exception as e:
log_cb(f" βœ— upload error: {e}")
return False
# ─── PROCESO PRINCIPAL ──────────────────────────────────────
def process_video(token, repo_id, source, is_url, mode,
audio_idx, gen_single, extract_sub, sub_idx,
delete_local, log_cb, progress_cb, done_cb):
try:
extra = NET_ARGS if is_url else []
log_cb("⟳ Analizando fuente…")
info = probe(source)
dur = info["duration"] if info["duration"] > 0 else 1
log_cb(f" βœ“ {fmt_dur(dur)} | {len(info['audio'])} audio | {len(info['subs'])} sub")
base = info["title"] if info["title"] else Path(source).stem or "video"
fname = safe_name(base)
tmp = tempfile.mkdtemp(prefix="vcpro_")
out_mp4 = os.path.join(tmp, f"{fname}.mp4")
cmd = ["ffmpeg", "-y"] + extra + ["-i", source, "-map", "0:v:0"]
for i in range(len(info["audio"])):
cmd.extend(["-map", f"0:a:{i}"])
if mode == "Copy + MP3":
cmd += ["-c:v", "copy"]
for i in range(len(info["audio"])):
cmd += [f"-c:a:{i}", "libmp3lame", f"-b:a:{i}", "320k", f"-ar:a:{i}", "48000"]
elif mode == "Copy + FLAC":
cmd += ["-c:v", "copy"]
for i in range(len(info["audio"])):
cmd += [f"-c:a:{i}", "flac", f"-compression_level:a:{i}", "0"]
else:
cmd += ["-c:v", "libx264", "-vf", "scale=-2:1080", "-preset", "slow", "-crf", "18"]
for i in range(len(info["audio"])):
cmd += [f"-c:a:{i}", "libmp3lame", f"-b:a:{i}", "320k", f"-ar:a:{i}", "48000"]
cmd += ["-map_metadata", "0", out_mp4]
log_cb(f"βš™ Convirtiendo ({mode})…")
ok = run_ffmpeg(cmd, dur, log_cb, progress_cb, "Convirtiendo")
if not ok:
log_cb("βœ— ConversiΓ³n fallΓ³")
if delete_local:
shutil.rmtree(tmp, ignore_errors=True)
done_cb(False)
return
progress_cb(100, "ConversiΓ³n OK")
log_cb(" βœ“ ConversiΓ³n OK")
if gen_single and info["audio"] and audio_idx < len(info["audio"]):
sp = os.path.join(tmp, f"{fname}_aud{audio_idx}.mp4")
sc = ["ffmpeg", "-y", "-i", out_mp4,
"-map", "0:v:0", "-map", f"0:a:{audio_idx}", "-c", "copy", sp]
run_ffmpeg(sc, dur, log_cb, progress_cb, "Audio individual")
log_cb(" βœ“ Audio individual extraΓ­do")
if extract_sub and info["subs"] and sub_idx < len(info["subs"]):
vtt = os.path.join(tmp, f"{fname}_sub{sub_idx}.vtt")
sc = ["ffmpeg", "-y"] + extra + [
"-i", source, "-map", f"0:s:{sub_idx}", "-c:s", "webvtt", vtt]
try:
subprocess.run(sc, capture_output=True, check=True, timeout=120)
log_cb(" βœ“ SubtΓ­tulo extraΓ­do")
except Exception as e:
log_cb(f" ⚠ sub error: {e}")
log_cb(f"☁ Subiendo a HuggingFace β†’ {repo_id}")
ok2 = hf_upload(token, repo_id, tmp, log_cb, progress_cb)
if delete_local:
shutil.rmtree(tmp, ignore_errors=True)
log_cb(" βœ“ Archivos locales borrados")
else:
log_cb(f" β„Ή Archivos guardados en: {tmp}")
done_cb(ok2)
except Exception as e:
import traceback
log_cb(f"βœ— Error: {e}\n{traceback.format_exc()}")
done_cb(False)
# ════════════════════════════════════════════════════════════
# GUI
# ════════════════════════════════════════════════════════════
class App(tk.Tk):
def __init__(self):
super().__init__()
self.title("Video Converter Pro")
self.geometry("960x700")
self.minsize(820, 600)
self.configure(bg=BG)
self.resizable(True, True)
self._repos = []
self._info = None
self._build()
self._center()
def _center(self):
self.update_idletasks()
w, h = self.winfo_width(), self.winfo_height()
sw = self.winfo_screenwidth()
sh = self.winfo_screenheight()
self.geometry(f"{w}x{h}+{(sw-w)//2}+{(sh-h)//2}")
# ── ESTILOS ────────────────────────────────────────────
def _style(self):
s = ttk.Style(self)
s.theme_use("clam")
s.configure(".", background=BG, foreground=FG, font=FONT_MAIN,
fieldbackground=BG2, borderwidth=0)
s.configure("TFrame", background=BG)
s.configure("TLabel", background=BG, foreground=FG, font=FONT_MAIN)
s.configure("Dim.TLabel", foreground=FG2, font=FONT_SM)
s.configure("H.TLabel", foreground=ACCENT, font=FONT_BIG)
s.configure("TEntry", fieldbackground=BG2, foreground=FG,
insertcolor=FG, borderwidth=1, relief="flat")
s.configure("TCombobox", fieldbackground=BG2, background=BG3,
foreground=FG, arrowcolor=FG2, borderwidth=1)
s.map("TCombobox", fieldbackground=[("readonly", BG2)],
foreground=[("readonly", FG)])
s.configure("TCheckbutton", background=BG, foreground=FG2,
activebackground=BG, activeforeground=FG)
s.map("TCheckbutton", background=[("active", BG)])
s.configure("TRadiobutton", background=BG, foreground=FG2)
s.map("TRadiobutton", background=[("active", BG)])
s.configure("Horizontal.TProgressbar",
troughcolor=BG3, background=ACCENT,
darkcolor=ACCENT2, lightcolor=ACCENT,
borderwidth=0, thickness=6)
# ── BUILD ──────────────────────────────────────────────
def _build(self):
self._style()
# ── HEADER ──
hdr = tk.Frame(self, bg=BG, pady=10)
hdr.pack(fill="x", padx=20)
tk.Label(hdr, text="VIDEO CONVERTER PRO", bg=BG, fg=ACCENT,
font=("Consolas", 16, "bold")).pack(side="left")
tk.Label(hdr, text=" β†’ HuggingFace", bg=BG, fg=FG3,
font=("Consolas", 10)).pack(side="left")
self._lbl_status = tk.Label(hdr, text="● Listo", bg=BG, fg=GREEN,
font=FONT_SM)
self._lbl_status.pack(side="right")
sep = tk.Frame(self, bg=BORDER, height=1)
sep.pack(fill="x", padx=20)
# ── BODY ──
body = tk.Frame(self, bg=BG)
body.pack(fill="both", expand=True, padx=20, pady=10)
# ─ LEFT PANEL ─
left = tk.Frame(body, bg=BG, width=320)
left.pack(side="left", fill="y", padx=(0, 10))
left.pack_propagate(False)
# HF Token
self._section(left, "HUGGING FACE")
self._hf_token = self._entry(left, "Token (hf_…)", show="*")
f_repo = tk.Frame(left, bg=BG)
f_repo.pack(fill="x", pady=(2, 6))
self._repo_cb = ttk.Combobox(f_repo, state="readonly",
font=FONT_SM, height=8)
self._repo_cb.pack(side="left", fill="x", expand=True)
tk.Button(f_repo, text="β†Ί", bg=BG3, fg=ACCENT, bd=0,
font=FONT_SM, cursor="hand2",
command=self._load_repos).pack(side="right", padx=(4, 0))
# Mode
self._section(left, "MODO DE CONVERSIΓ“N")
self._mode = tk.StringVar(value="Copy + MP3")
for m in ["Copy + MP3", "Copy + FLAC", "H264 1080p"]:
ttk.Radiobutton(left, text=m, variable=self._mode,
value=m).pack(anchor="w")
# Opciones
self._section(left, "OPCIONES")
self._gen_single = tk.BooleanVar(value=False)
self._ext_sub = tk.BooleanVar(value=False)
self._del_local = tk.BooleanVar(value=True)
ttk.Checkbutton(left, text="Generar audio individual",
variable=self._gen_single).pack(anchor="w")
ttk.Checkbutton(left, text="Extraer subtΓ­tulo (.vtt)",
variable=self._ext_sub).pack(anchor="w")
ttk.Checkbutton(left, text="Borrar archivos locales al terminar",
variable=self._del_local).pack(anchor="w")
# Pistas
self._section(left, "PISTAS")
tk.Label(left, text="Audio:", bg=BG, fg=FG2,
font=FONT_SM).pack(anchor="w")
self._aud_cb = ttk.Combobox(left, state="readonly",
font=FONT_SM, height=6)
self._aud_cb.pack(fill="x", pady=(0, 4))
tk.Label(left, text="SubtΓ­tulo:", bg=BG, fg=FG2,
font=FONT_SM).pack(anchor="w")
self._sub_cb = ttk.Combobox(left, state="readonly",
font=FONT_SM, height=6)
self._sub_cb.pack(fill="x")
# BotΓ³n analizar
tk.Button(left, text="⟳ ANALIZAR",
bg=BG3, fg=ACCENT, bd=0, padx=12, pady=6,
font=FONT_MAIN, cursor="hand2",
command=self._do_analyze).pack(fill="x", pady=(10, 2))
# ─ RIGHT PANEL ─
right = tk.Frame(body, bg=BG)
right.pack(side="right", fill="both", expand=True)
# Source tabs
nb_frame = tk.Frame(right, bg=BG)
nb_frame.pack(fill="x", pady=(0, 6))
self._src_mode = tk.StringVar(value="file")
tk.Button(nb_frame, text="πŸ“ Archivo", bg=ACCENT, fg="white",
bd=0, padx=10, pady=4, font=FONT_SM, cursor="hand2",
command=lambda: self._switch_src("file")).pack(side="left")
tk.Button(nb_frame, text="πŸ”— URL", bg=BG3, fg=FG2,
bd=0, padx=10, pady=4, font=FONT_SM, cursor="hand2",
command=lambda: self._switch_src("url")).pack(side="left", padx=4)
self._file_frame = tk.Frame(right, bg=BG)
self._file_frame.pack(fill="x", pady=(0, 4))
self._file_var = tk.StringVar()
e_file = tk.Entry(self._file_frame, textvariable=self._file_var,
bg=BG2, fg=FG, insertbackground=FG,
font=FONT_SM, bd=0, relief="flat")
e_file.pack(side="left", fill="x", expand=True, ipady=6, padx=(0, 4))
tk.Button(self._file_frame, text="Buscar…", bg=BG3, fg=FG2,
bd=0, padx=8, pady=4, font=FONT_SM, cursor="hand2",
command=self._browse).pack(side="right")
self._url_frame = tk.Frame(right, bg=BG)
self._url_var = tk.StringVar()
tk.Entry(self._url_frame, textvariable=self._url_var,
bg=BG2, fg=FG, insertbackground=FG,
font=FONT_SM, bd=0, relief="flat",
).pack(fill="x", ipady=6)
# Info strip
self._lbl_info = tk.Label(right, text="Sin fuente analizada",
bg=BG3, fg=FG2, font=FONT_SM,
anchor="w", padx=8, pady=4)
self._lbl_info.pack(fill="x", pady=(0, 8))
# Progress
self._lbl_prog = tk.Label(right, text="", bg=BG, fg=FG2, font=FONT_SM)
self._lbl_prog.pack(anchor="w")
self._pbar = ttk.Progressbar(right, mode="determinate",
style="Horizontal.TProgressbar")
self._pbar.pack(fill="x", pady=(2, 8))
# Log
tk.Label(right, text="LOG", bg=BG, fg=FG3,
font=("Consolas", 8, "bold")).pack(anchor="w")
log_f = tk.Frame(right, bg=BORDER)
log_f.pack(fill="both", expand=True, pady=(2, 8))
self._log_txt = tk.Text(
log_f, bg="#050d18", fg="#22d3ee", font=("Consolas", 9),
bd=0, relief="flat", state="disabled", wrap="word",
insertbackground=FG, selectbackground=ACCENT2
)
sb = ttk.Scrollbar(log_f, command=self._log_txt.yview)
self._log_txt.configure(yscrollcommand=sb.set)
sb.pack(side="right", fill="y")
self._log_txt.pack(fill="both", expand=True, padx=1, pady=1)
# PROCESAR button
self._btn_proc = tk.Button(
right, text="⬆ PROCESAR Y SUBIR",
bg=ACCENT, fg="white", bd=0, padx=16, pady=10,
font=("Consolas", 12, "bold"), cursor="hand2",
command=self._do_process
)
self._btn_proc.pack(fill="x")
# ── HELPERS ───────────────────────────────────────────
def _section(self, parent, text):
f = tk.Frame(parent, bg=BG)
f.pack(fill="x", pady=(10, 2))
tk.Label(f, text=text, bg=BG, fg=FG3,
font=("Consolas", 8, "bold")).pack(side="left")
tk.Frame(f, bg=BORDER, height=1).pack(side="right",
fill="x", expand=True,
padx=(6, 0), pady=4)
def _entry(self, parent, placeholder, show=None):
v = tk.StringVar()
kw = {"show": show} if show else {}
e = tk.Entry(parent, textvariable=v, bg=BG2, fg=FG2,
insertbackground=FG, font=FONT_SM,
bd=0, relief="flat", **kw)
e.pack(fill="x", ipady=6, pady=(0, 4))
return v
def _switch_src(self, mode):
if mode == "file":
self._file_frame.pack(fill="x", pady=(0, 4))
self._url_frame.pack_forget()
else:
self._url_frame.pack(fill="x", pady=(0, 4))
self._file_frame.pack_forget()
self._src_mode.set(mode)
def _browse(self):
p = filedialog.askopenfilename(
filetypes=[("Video", "*.mp4 *.mkv *.avi *.mov *.ts *.m2ts *.webm"),
("Todos", "*.*")]
)
if p:
self._file_var.set(p)
def _log(self, msg):
self._log_txt.configure(state="normal")
self._log_txt.insert("end", msg + "\n")
self._log_txt.see("end")
self._log_txt.configure(state="disabled")
def _set_progress(self, pct, label=""):
self._pbar["value"] = pct
self._lbl_prog.configure(text=label)
self.update_idletasks()
def _get_source(self):
if self._src_mode.get() == "file":
v = self._file_var.get().strip()
return v, False
else:
v = self._url_var.get().strip()
return v, True
# ── LOAD REPOS ────────────────────────────────────────
def _load_repos(self):
token = self._hf_token.get().strip()
if not token or not HF_OK:
messagebox.showwarning("Token", "IngresΓ‘ un token HF vΓ‘lido")
return
def _go():
try:
api = HfApi(token=token)
uname = api.whoami(token=token)["name"]
repos = [m.modelId for m in list(
list_models(token=token, author=uname, limit=200)
)]
self._repos = repos
self._repo_cb["values"] = repos
if repos:
self._repo_cb.set(repos[0])
self._log(f"βœ“ {len(repos)} repositorios cargados")
except Exception as e:
self._log(f"βœ— Error cargando repos: {e}")
threading.Thread(target=_go, daemon=True).start()
# ── ANALIZAR ──────────────────────────────────────────
def _do_analyze(self):
source, _ = self._get_source()
if not source:
messagebox.showwarning("Fuente", "SeleccionΓ‘ archivo o ingresΓ‘ URL")
return
def _go():
self._log(f"⟳ Analizando…")
info = probe(source)
self._info = info
ac = [f"[{t['idx']}] {t['lang']} Β· {t['codec']} Β· {t['ch']}ch" for t in info["audio"]]
sc = [f"[{t['idx']}] {t['lang']} Β· {t['codec']}" + (" (Forzado)" if t["forced"] else "") for t in info["subs"]]
self._aud_cb["values"] = ac
self._sub_cb["values"] = sc
if ac: self._aud_cb.set(ac[0])
if sc: self._sub_cb.set(sc[0])
txt = f"βœ“ {info['title'] or 'β€”'} Β· {fmt_dur(info['duration'])} Β· {len(ac)} aud Β· {len(sc)} sub"
self._lbl_info.configure(text=txt, fg=GREEN)
self._log(txt)
threading.Thread(target=_go, daemon=True).start()
# ── PROCESAR ──────────────────────────────────────────
def _do_process(self):
token = self._hf_token.get().strip()
repo_id = self._repo_cb.get().strip()
source, is_url = self._get_source()
if not token:
messagebox.showwarning("Token", "IngresΓ‘ tu token de HuggingFace")
return
if not repo_id:
messagebox.showwarning("Repo", "SeleccionΓ‘ o cargΓ‘ un repositorio")
return
if not source:
messagebox.showwarning("Fuente", "SeleccionΓ‘ archivo o ingresΓ‘ URL")
return
ai = 0
si = 0
if self._aud_cb.get():
try: ai = int(self._aud_cb.get().split("]")[0].strip("["))
except: ai = 0
if self._sub_cb.get():
try: si = int(self._sub_cb.get().split("]")[0].strip("["))
except: si = 0
self._btn_proc.configure(state="disabled", bg=FG3)
self._lbl_status.configure(text="● Procesando…", fg=YELLOW)
self._log_txt.configure(state="normal")
self._log_txt.delete("1.0", "end")
self._log_txt.configure(state="disabled")
self._pbar["value"] = 0
def _done(ok):
self._btn_proc.configure(state="normal", bg=ACCENT)
if ok:
self._lbl_status.configure(text="● Completado", fg=GREEN)
self._log("βœ“ COMPLETADO")
self._set_progress(100, "Completado")
else:
self._lbl_status.configure(text="● Error", fg=RED)
self._log("βœ— FALLΓ“")
threading.Thread(
target=process_video,
args=(token, repo_id, source, is_url, self._mode.get(),
ai, self._gen_single.get(), self._ext_sub.get(), si,
self._del_local.get(),
lambda m: self.after(0, self._log, m),
lambda p, l: self.after(0, self._set_progress, p, l),
lambda ok: self.after(0, _done, ok)),
daemon=True
).start()
if __name__ == "__main__":
app = App()
app.mainloop()