CineMax commited on
Commit
ac5fb1e
·
verified ·
1 Parent(s): 60b08fe

Create render.py

Browse files
Files changed (1) hide show
  1. render.py +861 -0
render.py ADDED
@@ -0,0 +1,861 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import ctypes
3
+ import subprocess
4
+ import threading
5
+ import shutil
6
+ import re
7
+ import json
8
+ import uuid
9
+ import urllib.request
10
+ import urllib.parse
11
+ import tkinter as tk
12
+ from tkinter import ttk, filedialog, messagebox
13
+ from pathlib import Path
14
+
15
+ # ─── IMPORTS DEFERIDOS ──────────────────────────────────────
16
+ def get_sys():
17
+ import sys
18
+ return sys
19
+
20
+ # ─── AUTO-ELEVACIÓN ADMINISTRADOR ───────────────────────────
21
+ def is_admin():
22
+ try:
23
+ return ctypes.windll.shell32.IsUserAnAdmin()
24
+ except:
25
+ return False
26
+
27
+ def elevate():
28
+ if not is_admin():
29
+ sys = get_sys()
30
+ ctypes.windll.shell32.ShellExecuteW(
31
+ None, "runas", sys.executable, " ".join(sys.argv), None, 1
32
+ )
33
+ sys.exit()
34
+
35
+ # ─── ESTILOS Y COLORES ──────────────────────────────────────
36
+ BG = "#0f172a"
37
+ CARD_BG = "#1e293b"
38
+ ACCENT = "#3b82f6"
39
+ ACCENT_H = "#2563eb"
40
+ GREEN = "#22c55e"
41
+ RED = "#ef4444"
42
+ YELLOW = "#f59e0b"
43
+ ORANGE = "#f97316"
44
+ FG = "#f1f5f9"
45
+ FG2 = "#94a3b8"
46
+ BORDER = "#334155"
47
+ FONT_MAIN = ("Segoe UI", 10)
48
+ FONT_BOLD = ("Segoe UI", 10, "bold")
49
+ FONT_TITLE= ("Segoe UI", 16, "bold")
50
+ FONT_SUB = ("Segoe UI", 9)
51
+
52
+ # ─── FUNCIONES UTILITARIAS ──────────────────────────────────
53
+ def safe_name(s, maxlen=120):
54
+ if not s: return "video"
55
+ return re.sub(r'[<>:"/\\|?*\x00-\x1f]', '_', s).strip()[:maxlen]
56
+
57
+ def to_leet(text):
58
+ if not text: return "video"
59
+ rep = {
60
+ 'a': '4', 'A': '4',
61
+ 'i': '1', 'I': '1',
62
+ 't': '7', 'T': '7',
63
+ 'o': '0', 'O': '0',
64
+ 'e': '3', 'E': '3',
65
+ 's': '5', 'S': '5',
66
+ 'g': '9', 'G': '9',
67
+ }
68
+ res = "".join(rep.get(c, c) for c in text)
69
+ return safe_name(res)
70
+
71
+ def fmt_size(bytes_val):
72
+ for unit in ['B', 'KB', 'MB', 'GB']:
73
+ if bytes_val < 1024.0:
74
+ return f"{bytes_val:.1f} {unit}"
75
+ bytes_val /= 1024.0
76
+ return f"{bytes_val:.1f} TB"
77
+
78
+ def fmt_dur(secs):
79
+ s = int(secs)
80
+ return f"{s//3600:02d}:{(s%3600)//60:02d}:{s%60:02d}"
81
+
82
+ def fetch_tmdb(url):
83
+ req = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0'})
84
+ with urllib.request.urlopen(req) as resp:
85
+ return json.loads(resp.read().decode())
86
+
87
+ def probe(source):
88
+ info = {"audio": [], "subs": [], "video": {}, "duration": 0.0, "title": "", "size": 0, "bitrate": 0}
89
+ try:
90
+ r = subprocess.run(
91
+ ["ffprobe", "-v", "quiet", "-print_format", "json",
92
+ "-show_format", "-show_streams", source],
93
+ capture_output=True, text=True, timeout=90
94
+ )
95
+ if r.returncode != 0:
96
+ return info
97
+ data = json.loads(r.stdout)
98
+ fmt = data.get("format", {})
99
+ tags = fmt.get("tags", {})
100
+ info["title"] = (tags.get("title") or tags.get("TITLE") or "").strip()
101
+ info["duration"] = float(fmt.get("duration", 0) or 0)
102
+ info["size"] = int(fmt.get("size", 0) or 0)
103
+ info["bitrate"] = int(fmt.get("bit_rate", 0) or 0)
104
+ ai = si = 0
105
+ for s in data.get("streams", []):
106
+ t = s.get("tags", {})
107
+ ct = s.get("codec_type", "")
108
+ if ct == "video" and not info["video"]:
109
+ info["video"] = {
110
+ "codec": s.get("codec_name", "?"),
111
+ "width": s.get("width", 0),
112
+ "height": s.get("height", 0),
113
+ "fps": s.get("r_frame_rate", "?"),
114
+ "pix_fmt": s.get("pix_fmt", "?"),
115
+ }
116
+ elif ct == "audio":
117
+ info["audio"].append({
118
+ "idx": ai, "codec": s.get("codec_name", "?"),
119
+ "lang": t.get("language", "und"),
120
+ "ch": s.get("channels", 2),
121
+ "title": t.get("title", ""),
122
+ "sample_rate": s.get("sample_rate", "?"),
123
+ "bit_depth": s.get("bits_per_sample", 0),
124
+ })
125
+ ai += 1
126
+ elif ct == "subtitle":
127
+ info["subs"].append({
128
+ "idx": si, "codec": s.get("codec_name", "?"),
129
+ "lang": t.get("language", "und"),
130
+ "title": t.get("title", ""),
131
+ "forced": s.get("disposition", {}).get("forced", 0) == 1,
132
+ })
133
+ si += 1
134
+ except Exception:
135
+ pass
136
+ return info
137
+
138
+ NET_ARGS = [
139
+ "-user_agent", "Mozilla/5.0",
140
+ "-headers", "Referer: https://google.com\r\n",
141
+ "-timeout", "180000000",
142
+ "-reconnect", "1", "-reconnect_streamed", "1",
143
+ "-reconnect_at_eof", "1", "-reconnect_delay_max", "30",
144
+ "-rw_timeout", "180000000", "-multiple_requests", "1",
145
+ ]
146
+
147
+ def run_ffmpeg(cmd, total, log_cb, progress_cb, label):
148
+ try:
149
+ proc = subprocess.Popen(
150
+ cmd, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE,
151
+ universal_newlines=True, bufsize=1
152
+ )
153
+ pat = re.compile(r"time=(\d+):(\d+):(\d+)\.(\d+)")
154
+ for line in proc.stderr:
155
+ m = pat.search(line)
156
+ if m:
157
+ h, mi, s, cs = map(int, m.groups())
158
+ cur = h*3600 + mi*60 + s + cs/100
159
+ pct = min(99, int(cur / max(total, 1) * 100))
160
+ progress_cb(pct, f"{label}: {pct}% [{fmt_dur(cur)} / {fmt_dur(total)}]")
161
+ proc.wait()
162
+ return proc.returncode == 0
163
+ except Exception as e:
164
+ log_cb(f" ✗ ffmpeg: {e}")
165
+ return False
166
+
167
+ def check_ffmpeg():
168
+ try:
169
+ r = subprocess.run(["ffmpeg", "-version"], capture_output=True, timeout=10)
170
+ return r.returncode == 0
171
+ except:
172
+ return False
173
+
174
+ def check_ffprobe():
175
+ try:
176
+ r = subprocess.run(["ffprobe", "-version"], capture_output=True, timeout=10)
177
+ return r.returncode == 0
178
+ except:
179
+ return False
180
+
181
+ # ─── RENDERIZADOR PRINCIPAL ────────────────────────────────
182
+ def render_video(source, is_url, mode, audio_idx, gen_single, extract_sub, sub_idx,
183
+ folder_name, file_name, output_dir, log_cb, progress_cb, done_cb):
184
+ try:
185
+ extra = NET_ARGS if is_url else []
186
+ log_cb(f"⟳ Analizando: {source[:80]}{'...' if len(source)>80 else ''}")
187
+ info = probe(source)
188
+ dur = info["duration"] if info["duration"] > 0 else 1
189
+
190
+ uid = str(uuid.uuid4())[:8]
191
+ tmp = Path(output_dir) / f"temp_{uid}"
192
+ tmp.mkdir(exist_ok=True, parents=True)
193
+
194
+ out_mp4 = tmp / f"{file_name}.mp4"
195
+
196
+ # ─── CONSTRUIR COMANDO FFMPEG ───
197
+ cmd = ["ffmpeg", "-y"] + extra + ["-i", source, "-map", "0:v:0"]
198
+
199
+ if info["audio"]:
200
+ for i in range(len(info["audio"])):
201
+ cmd.extend(["-map", f"0:a:{i}"])
202
+ else:
203
+ cmd.extend(["-an"])
204
+
205
+ # Modo de conversión
206
+ if mode == "Copy + MP3":
207
+ cmd += ["-c:v", "copy"]
208
+ for i in range(len(info["audio"])):
209
+ cmd += [f"-c:a:{i}", "libmp3lame", f"-b:a:{i}", "320k"]
210
+ elif mode == "Copy + FLAC":
211
+ cmd += ["-c:v", "copy"]
212
+ for i in range(len(info["audio"])):
213
+ cmd += [f"-c:a:{i}", "flac"]
214
+ elif mode == "Copy + AAC 256k":
215
+ cmd += ["-c:v", "copy"]
216
+ for i in range(len(info["audio"])):
217
+ cmd += [f"-c:a:{i}", "aac", f"-b:a:{i}", "256k"]
218
+ elif mode == "H264 1080p + MP3":
219
+ cmd += ["-c:v", "libx264", "-vf", "scale=-2:1080", "-preset", "fast", "-crf", "18"]
220
+ for i in range(len(info["audio"])):
221
+ cmd += [f"-c:a:{i}", "libmp3lame", f"-b:a:{i}", "320k"]
222
+ elif mode == "H264 720p + MP3":
223
+ cmd += ["-c:v", "libx264", "-vf", "scale=-2:720", "-preset", "fast", "-crf", "20"]
224
+ for i in range(len(info["audio"])):
225
+ cmd += [f"-c:a:{i}", "libmp3lame", f"-b:a:{i}", "320k"]
226
+ elif mode == "H264 480p + MP3":
227
+ cmd += ["-c:v", "libx264", "-vf", "scale=-2:480", "-preset", "fast", "-crf", "23"]
228
+ for i in range(len(info["audio"])):
229
+ cmd += [f"-c:a:{i}", "libmp3lame", f"-b:a:{i}", "192k"]
230
+ elif mode == "H265 1080p + MP3":
231
+ cmd += ["-c:v", "libx265", "-vf", "scale=-2:1080", "-preset", "fast", "-crf", "22"]
232
+ for i in range(len(info["audio"])):
233
+ cmd += [f"-c:a:{i}", "libmp3lame", f"-b:a:{i}", "320k"]
234
+ elif mode == "Solo Video (sin audio)":
235
+ cmd += ["-c:v", "copy", "-an"]
236
+ else:
237
+ cmd += ["-c:v", "copy"]
238
+ for i in range(len(info["audio"])):
239
+ cmd += [f"-c:a:{i}", "copy"]
240
+
241
+ cmd += ["-map_metadata", "0", "-movflags", "+faststart", str(out_mp4)]
242
+
243
+ log_cb(f"⚙ Modo: {mode}")
244
+ log_cb(f"⚙ Convirtiendo…")
245
+ ok = run_ffmpeg(cmd, dur, log_cb, progress_cb, "Convirtiendo")
246
+ if not ok:
247
+ log_cb("✗ Conversión fallida")
248
+ shutil.rmtree(tmp, ignore_errors=True)
249
+ done_cb(False, None)
250
+ return
251
+
252
+ progress_cb(100, "Conversión OK ✓")
253
+
254
+ # ─── EXTRAER AUDIO INDIVIDUAL ───
255
+ if gen_single and info["audio"] and audio_idx < len(info["audio"]):
256
+ ext = "mp3" if "mp3" in mode.lower() else "flac" if "flac" in mode.lower() else "aac" if "aac" in mode.lower() else "mp3"
257
+ sp = tmp / f"{file_name}_aud{audio_idx}.{ext}"
258
+ sc = ["ffmpeg", "-y", "-i", str(out_mp4),
259
+ "-map", f"0:a:{audio_idx}", "-vn",
260
+ "-c:a", "libmp3lame" if ext == "mp3" else "flac" if ext == "flac" else "aac",
261
+ "-b:a" if ext != "flac" else "-compression_level",
262
+ "320k" if ext != "flac" else "5",
263
+ str(sp)]
264
+ run_ffmpeg(sc, dur, log_cb, progress_cb, f"Audio → {ext}")
265
+
266
+ # ─── EXTRAER SUBTÍTULO ───
267
+ if extract_sub and info["subs"] and sub_idx < len(info["subs"]):
268
+ vtt = tmp / f"{file_name}_sub{sub_idx}.vtt"
269
+ sc = ["ffmpeg", "-y"] + extra + [
270
+ "-i", source, "-map", f"0:s:{sub_idx}", "-c:s", "webvtt", str(vtt)]
271
+ r = subprocess.run(sc, capture_output=True, text=True, check=False)
272
+ if r.returncode == 0:
273
+ log_cb(f" ✓ Subtítulo extraído")
274
+ else:
275
+ log_cb(f" ✗ Error extrayendo subtítulo")
276
+
277
+ # ─── MOVER A CARPETA FINAL ───
278
+ final_dir = Path(output_dir) / folder_name
279
+ final_dir.mkdir(exist_ok=True, parents=True)
280
+
281
+ result_files = []
282
+ for f in tmp.iterdir():
283
+ if f.is_file():
284
+ dest = final_dir / f.name
285
+ # Evitar sobreescribir si ya existe
286
+ if dest.exists():
287
+ base = dest.stem
288
+ ext = dest.suffix
289
+ c = 1
290
+ while dest.exists():
291
+ dest = final_dir / f"{base}_{c}{ext}"
292
+ c += 1
293
+ shutil.move(str(f), str(dest))
294
+ result_files.append(str(dest))
295
+ size = dest.stat().st_size
296
+ log_cb(f" ✓ {dest.name} ({fmt_size(size)})")
297
+
298
+ shutil.rmtree(tmp, ignore_errors=True)
299
+ log_cb(f"📂 Carpeta: {final_dir}")
300
+ done_cb(True, result_files)
301
+
302
+ except Exception as e:
303
+ import traceback
304
+ log_cb(f"✗ Error: {e}\n{traceback.format_exc()}")
305
+ done_cb(False, None)
306
+
307
+
308
+ # ─── APLICACIÓN TKINTER ────────────────────────────────────
309
+ class App(tk.Tk):
310
+ def __init__(self):
311
+ super().__init__()
312
+ self.title("Video Renderer Pro")
313
+ self.geometry("1200x880")
314
+ self.configure(bg=BG)
315
+ self.resizable(True, True)
316
+ self.minsize(900, 650)
317
+
318
+ self._queue = []
319
+ self._total_queue = 0
320
+ self._current_idx = 0
321
+ self._processed_count = 0
322
+ self._failed_count = 0
323
+
324
+ self._tmdb_id_map = {}
325
+ self._tmdb_episodes = []
326
+
327
+ self._build()
328
+
329
+ def _build(self):
330
+ style = ttk.Style(self)
331
+ style.theme_use("clam")
332
+ style.configure(".", background=BG, foreground=FG, font=FONT_MAIN, borderwidth=0)
333
+ style.configure("TFrame", background=BG)
334
+ style.configure("TLabel", background=BG, foreground=FG, font=FONT_MAIN)
335
+ style.configure("Card.TFrame", background=CARD_BG)
336
+ style.configure("Horizontal.TProgressbar", troughcolor=BG, background=ACCENT, thickness=10)
337
+ style.configure("TCheckbutton", background=CARD_BG, foreground=FG, font=FONT_MAIN)
338
+ style.configure("TRadiobutton", background=CARD_BG, foreground=FG, font=FONT_MAIN)
339
+ style.map("TCheckbutton", background=[("active", CARD_BG)])
340
+ style.map("TRadiobutton", background=[("active", CARD_BG)])
341
+
342
+ main = tk.Frame(self, bg=BG)
343
+ main.pack(fill="both", expand=True, padx=16, pady=16)
344
+
345
+ # ─── HEADER ───
346
+ header = tk.Frame(main, bg=BG)
347
+ header.pack(fill="x", pady=(0, 16))
348
+ tk.Label(header, text="🎬 VIDEO RENDERER PRO", bg=BG, fg=ACCENT, font=FONT_TITLE).pack(side="left")
349
+ self._lbl_ffmpeg = tk.Label(header, text="", bg=BG, fg=FG2, font=FONT_SUB)
350
+ self._lbl_ffmpeg.pack(side="right", padx=(10, 0))
351
+ self._lbl_status = tk.Label(header, text="● Listo", bg=BG, fg=GREEN, font=FONT_MAIN)
352
+ self._lbl_status.pack(side="right")
353
+
354
+ self._check_tools()
355
+
356
+ # ─── BODY ───
357
+ body = tk.Frame(main, bg=BG)
358
+ body.pack(fill="both", expand=True)
359
+ body.columnconfigure(0, weight=1, uniform="col")
360
+ body.columnconfigure(1, weight=1, uniform="col")
361
+ body.rowconfigure(0, weight=1)
362
+
363
+ # Panel izquierdo
364
+ left = tk.Frame(body, bg=CARD_BG, padx=14, pady=14)
365
+ left.grid(row=0, column=0, sticky="nsew", padx=(0, 8))
366
+ self._build_tmdb_section(left)
367
+ self._build_options_section(left)
368
+ self._build_output_section(left)
369
+
370
+ # Panel derecho
371
+ right = tk.Frame(body, bg=CARD_BG, padx=14, pady=14)
372
+ right.grid(row=0, column=1, sticky="nsew", padx=(8, 0))
373
+ self._build_source_section(right)
374
+ self._build_tracks_section(right)
375
+ self._build_log_section(right)
376
+
377
+ def _check_tools(self):
378
+ ff = check_ffmpeg()
379
+ fp = check_ffprobe()
380
+ if ff and fp:
381
+ self._lbl_ffmpeg.configure(text="✓ ffmpeg + ffprobe", fg=GREEN)
382
+ elif ff:
383
+ self._lbl_ffmpeg.configure(text="⚠ ffprobe no encontrado", fg=YELLOW)
384
+ else:
385
+ self._lbl_ffmpeg.configure(text="✗ ffmpeg no encontrado", fg=RED)
386
+
387
+ def _section(self, parent, title):
388
+ f = tk.Frame(parent, bg=CARD_BG, pady=2)
389
+ f.pack(fill="x", pady=(0, 8))
390
+ tk.Label(f, text=title.upper(), bg=CARD_BG, fg=FG2, font=("Segoe UI", 8, "bold")).pack(anchor="w")
391
+ tk.Frame(f, bg=BORDER, height=1).pack(fill="x", pady=(4, 8))
392
+ return f
393
+
394
+ # ─── TMDb ───
395
+ def _build_tmdb_section(self, parent):
396
+ s = self._section(parent, "Metadatos TMDb (Opcional)")
397
+ self._use_tmdb = tk.BooleanVar(value=False)
398
+ ttk.Checkbutton(s, text="Generar nombres usando TMDb", variable=self._use_tmdb).pack(anchor="w", pady=(0, 6))
399
+
400
+ tk.Label(s, text="API Key TMDb:", bg=CARD_BG, fg=FG2, font=FONT_SUB).pack(anchor="w")
401
+ self._tmdb_key = tk.StringVar()
402
+ tk.Entry(s, textvariable=self._tmdb_key, bg=BG, fg=FG, insertbackground=FG, relief="flat", show="*", font=FONT_MAIN).pack(fill="x", ipady=3, pady=(0, 6))
403
+
404
+ f_type = tk.Frame(s, bg=CARD_BG)
405
+ f_type.pack(fill="x", pady=(0, 6))
406
+ self._tmdb_type = tk.StringVar(value="serie")
407
+ ttk.Radiobutton(f_type, text="Serie", variable=self._tmdb_type, value="serie", command=self._tmdb_clear).pack(side="left")
408
+ ttk.Radiobutton(f_type, text="Película", variable=self._tmdb_type, value="pelicula", command=self._tmdb_clear).pack(side="left", padx=(8, 8))
409
+
410
+ f_search = tk.Frame(s, bg=CARD_BG)
411
+ f_search.pack(fill="x", pady=(0, 6))
412
+ self._tmdb_query = tk.StringVar()
413
+ tk.Entry(f_search, textvariable=self._tmdb_query, bg=BG, fg=FG, insertbackground=FG, relief="flat", font=FONT_MAIN).pack(side="left", fill="x", expand=True, ipady=3)
414
+ tk.Button(f_search, text="🔍 Buscar", bg=BG, fg=ACCENT, bd=0, padx=10, font=FONT_MAIN, cursor="hand2", command=self._search_tmdb).pack(side="right", padx=(6, 0))
415
+
416
+ self._tmdb_res_cb = ttk.Combobox(s, state="readonly", font=FONT_MAIN)
417
+ self._tmdb_res_cb.pack(fill="x", pady=(0, 6))
418
+ self._tmdb_res_cb.bind("<<ComboboxSelected>>", self._on_tmdb_res_select)
419
+
420
+ f_ep = tk.Frame(s, bg=CARD_BG)
421
+ f_ep.pack(fill="x")
422
+ self._tmdb_season_cb = ttk.Combobox(f_ep, state="disabled", font=FONT_MAIN, width=16)
423
+ self._tmdb_season_cb.pack(side="left", padx=(0, 6))
424
+ self._tmdb_season_cb.bind("<<ComboboxSelected>>", self._on_tmdb_season_select)
425
+ self._tmdb_ep_cb = ttk.Combobox(f_ep, state="disabled", font=FONT_MAIN)
426
+ self._tmdb_ep_cb.pack(side="left", fill="x", expand=True)
427
+
428
+ def _tmdb_clear(self, *a):
429
+ self._tmdb_res_cb.set("")
430
+ self._tmdb_res_cb.configure(values=[])
431
+ self._tmdb_season_cb.set("")
432
+ self._tmdb_season_cb.configure(state="disabled")
433
+ self._tmdb_ep_cb.set("")
434
+ self._tmdb_ep_cb.configure(state="disabled")
435
+
436
+ def _search_tmdb(self):
437
+ k, q = self._tmdb_key.get().strip(), self._tmdb_query.get().strip()
438
+ if not k or not q: return
439
+ t = "movie" if self._tmdb_type.get() == "pelicula" else "tv"
440
+ url = f"https://api.themoviedb.org/3/search/{t}?api_key={k}&query={urllib.parse.quote(q)}&language=es-MX"
441
+ def _go():
442
+ try:
443
+ data = fetch_tmdb(url)
444
+ res, self._tmdb_id_map = [], {}
445
+ for r in data.get('results', [])[:15]:
446
+ title = r.get('title') or r.get('name')
447
+ dt = r.get('release_date') or r.get('first_air_date') or ""
448
+ yr = dt.split('-')[0] if dt else "N/A"
449
+ lbl = f"{title} ({yr})"
450
+ res.append(lbl)
451
+ self._tmdb_id_map[lbl] = r.get('id')
452
+ self.after(0, lambda: self._tmdb_res_cb.configure(values=res))
453
+ if res:
454
+ self.after(0, lambda: self._tmdb_res_cb.set(res[0]))
455
+ self.after(0, self._on_tmdb_res_select)
456
+ except Exception as e:
457
+ self.after(0, lambda: self._log(f"✗ TMDb: {e}"))
458
+ threading.Thread(target=_go, daemon=True).start()
459
+
460
+ def _on_tmdb_res_select(self, *a):
461
+ if self._tmdb_type.get() == "pelicula":
462
+ self._tmdb_season_cb.configure(state="disabled")
463
+ self._tmdb_ep_cb.configure(state="disabled")
464
+ return
465
+ self._tmdb_season_cb.configure(state="readonly")
466
+ tid = self._tmdb_id_map.get(self._tmdb_res_cb.get())
467
+ if not tid: return
468
+ url = f"https://api.themoviedb.org/3/tv/{tid}?api_key={self._tmdb_key.get().strip()}&language=es-MX"
469
+ def _go():
470
+ try:
471
+ data = fetch_tmdb(url)
472
+ seasons = [f"Temporada {s['season_number']}" for s in data.get('seasons', []) if s['season_number'] > 0]
473
+ self.after(0, lambda: self._tmdb_season_cb.configure(values=seasons))
474
+ if seasons:
475
+ self.after(0, lambda: self._tmdb_season_cb.set(seasons[0]))
476
+ self.after(0, self._on_tmdb_season_select)
477
+ except Exception as e:
478
+ self.after(0, lambda: self._log(f"✗ TMDb: {e}"))
479
+ threading.Thread(target=_go, daemon=True).start()
480
+
481
+ def _on_tmdb_season_select(self, *a):
482
+ self._tmdb_ep_cb.configure(state="readonly")
483
+ tid = self._tmdb_id_map.get(self._tmdb_res_cb.get())
484
+ if not tid: return
485
+ s_num = self._tmdb_season_cb.get().split(" ")[1] if self._tmdb_season_cb.get() else "1"
486
+ url = f"https://api.themoviedb.org/3/tv/{tid}/season/{s_num}?api_key={self._tmdb_key.get().strip()}&language=es-MX"
487
+ def _go():
488
+ try:
489
+ data = fetch_tmdb(url)
490
+ self._tmdb_episodes = [{'num': e['episode_number'], 'name': e['name']} for e in data.get('episodes', [])]
491
+ ep_strs = [f"Ep {e['num']:02d}: {e['name']}" for e in self._tmdb_episodes]
492
+ self.after(0, lambda: self._tmdb_ep_cb.configure(values=ep_strs))
493
+ if ep_strs: self.after(0, lambda: self._tmdb_ep_cb.set(ep_strs[0]))
494
+ except Exception as e:
495
+ self.after(0, lambda: self._log(f"✗ TMDb: {e}"))
496
+ threading.Thread(target=_go, daemon=True).start()
497
+
498
+ # ─── OPCIONES DE CONVERSIÓN ───
499
+ def _build_options_section(self, parent):
500
+ s = self._section(parent, "Modo de Renderizado")
501
+
502
+ self._mode = tk.StringVar(value="Copy + MP3")
503
+ modes = [
504
+ ("Copy Video + MP3 320k", "Copy + MP3"),
505
+ ("Copy Video + FLAC", "Copy + FLAC"),
506
+ ("Copy Video + AAC 256k", "Copy + AAC 256k"),
507
+ ("H264 1080p + MP3", "H264 1080p + MP3"),
508
+ ("H264 720p + MP3", "H264 720p + MP3"),
509
+ ("H264 480p + MP3", "H264 480p + MP3"),
510
+ ("H265 1080p + MP3", "H265 1080p + MP3"),
511
+ ("Solo Video (sin audio)", "Solo Video (sin audio)"),
512
+ ("Copy Todo (sin recodificar)", "Copy Todo"),
513
+ ]
514
+
515
+ f_grid = tk.Frame(s, bg=CARD_BG)
516
+ f_grid.pack(fill="x")
517
+ for i, (label, val) in enumerate(modes):
518
+ r, c = divmod(i, 2)
519
+ ttk.Radiobutton(f_grid, text=label, variable=self._mode, value=val).grid(row=r, column=c, sticky="w", padx=(0, 12), pady=2)
520
+
521
+ tk.Frame(s, bg=BORDER, height=1).pack(fill="x", pady=(8, 8))
522
+
523
+ self._gen_single = tk.BooleanVar(value=False)
524
+ self._ext_sub = tk.BooleanVar(value=False)
525
+
526
+ opts = tk.Frame(s, bg=CARD_BG)
527
+ opts.pack(fill="x")
528
+ ttk.Checkbutton(opts, text="Extract pista de audio", variable=self._gen_single).pack(side="left")
529
+ ttk.Checkbutton(opts, text="Extract subtítulo (.vtt)", variable=self._ext_sub).pack(side="left", padx=(12, 0))
530
+
531
+ # ─── SALIDA ───
532
+ def _build_output_section(self, parent):
533
+ s = self._section(parent, "Nombre y Salida")
534
+
535
+ tk.Label(s, text="Nombre manual (si no usas TMDb):", bg=CARD_BG, fg=FG2, font=FONT_SUB).pack(anchor="w")
536
+ self._manual_name = tk.StringVar()
537
+ tk.Entry(s, textvariable=self._manual_name, bg=BG, fg=FG, insertbackground=FG, relief="flat", font=FONT_MAIN).pack(fill="x", ipady=3, pady=(0, 10))
538
+
539
+ self._use_leet = tk.BooleanVar(value=True)
540
+ ttk.Checkbutton(s, text="Aplicar estilo L33T a nombres", variable=self._use_leet).pack(anchor="w", pady=(0, 8))
541
+
542
+ tk.Label(s, text="Carpeta de salida:", bg=CARD_BG, fg=FG2, font=FONT_SUB).pack(anchor="w")
543
+ f_out = tk.Frame(s, bg=CARD_BG)
544
+ f_out.pack(fill="x")
545
+ sys = get_sys()
546
+ default_out = str(Path(sys.argv[0]).parent.resolve() / "Videos_Renderizados")
547
+ self._output_dir = tk.StringVar(value=default_out)
548
+ tk.Entry(f_out, textvariable=self._output_dir, bg=BG, fg=FG, insertbackground=FG, relief="flat", font=FONT_MAIN).pack(side="left", fill="x", expand=True, ipady=3)
549
+ tk.Button(f_out, text="📁", bg=BG, fg=ACCENT, bd=0, padx=8, font=FONT_MAIN, cursor="hand2", command=self._browse_output).pack(side="right", padx=(6, 0))
550
+ tk.Button(f_out, text="Abrir", bg=BG, fg=GREEN, bd=0, padx=8, font=FONT_SUB, cursor="hand2", command=self._open_output).pack(side="right", padx=(0, 4))
551
+
552
+ def _browse_output(self):
553
+ p = filedialog.askdirectory(initialdir=self._output_dir.get())
554
+ if p:
555
+ self._output_dir.set(p)
556
+
557
+ def _open_output(self):
558
+ d = self._output_dir.get()
559
+ Path(d).mkdir(exist_ok=True, parents=True)
560
+ os.startfile(d)
561
+
562
+ # ─── FUENTE ───
563
+ def _build_source_section(self, parent):
564
+ s = self._section(parent, "Fuente de Video")
565
+
566
+ tabs = tk.Frame(s, bg=CARD_BG)
567
+ tabs.pack(fill="x", pady=(0, 8))
568
+ self._src_mode = tk.StringVar(value="url")
569
+ self._btn_url = tk.Button(tabs, text="🌐 URLs", bg=ACCENT, fg="white", bd=0, padx=12, pady=5, font=FONT_BOLD, cursor="hand2", command=lambda: self._switch_src("url"))
570
+ self._btn_url.pack(side="left")
571
+ self._btn_file = tk.Button(tabs, text="📁 Archivo(s)", bg=BG, fg=FG2, bd=0, padx=12, pady=5, font=FONT_BOLD, cursor="hand2", command=lambda: self._switch_src("file"))
572
+ self._btn_file.pack(side="left", padx=4)
573
+
574
+ self._url_frame = tk.Frame(s, bg=CARD_BG)
575
+ self._url_text = tk.Text(self._url_frame, bg=BG, fg=FG, insertbackground=FG, font=("Consolas", 9), relief="flat", height=6)
576
+ sb = ttk.Scrollbar(self._url_frame, command=self._url_text.yview)
577
+ self._url_text.configure(yscrollcommand=sb.set)
578
+ self._url_text.pack(side="left", fill="both", expand=True, pady=2)
579
+ sb.pack(side="right", fill="y", pady=2)
580
+
581
+ self._file_frame = tk.Frame(s, bg=CARD_BG)
582
+ self._file_var = tk.StringVar()
583
+ tk.Entry(self._file_frame, textvariable=self._file_var, bg=BG, fg=FG, insertbackground=FG, font=FONT_MAIN, relief="flat").pack(side="left", fill="x", expand=True, ipady=3, padx=(0, 4))
584
+ tk.Button(self._file_frame, text="Buscar", bg=BG, fg=ACCENT, bd=0, padx=8, pady=3, font=FONT_MAIN, cursor="hand2", command=self._browse_file).pack(side="right")
585
+ self._multi_file = tk.BooleanVar(value=False)
586
+ ttk.Checkbutton(self._file_frame, text="Múltiples", variable=self._multi_file).pack(side="right", padx=(0, 8))
587
+
588
+ self._lbl_info = tk.Label(s, text="", bg=BG, fg=FG2, font=FONT_SUB, anchor="w", padx=8, pady=4, wraplength=500, justify="left")
589
+ self._lbl_info.pack(fill="x", pady=(6, 0))
590
+
591
+ btns = tk.Frame(s, bg=CARD_BG)
592
+ btns.pack(fill="x", pady=(8, 0))
593
+ tk.Button(btns, text="🔍 ANALIZAR", bg=BG, fg=ACCENT, bd=0, padx=12, pady=7, font=FONT_BOLD, cursor="hand2", command=self._do_analyze).pack(side="left")
594
+ self._btn_proc = tk.Button(btns, text="▶ PROCESAR COLA", bg=GREEN, fg="white", bd=0, padx=12, pady=7, font=FONT_BOLD, cursor="hand2", command=self._do_process)
595
+ self._btn_proc.pack(side="right", fill="x", expand=True, padx=(8, 0))
596
+ self._btn_cancel = tk.Button(btns, text="✕", bg=RED, fg="white", bd=0, padx=10, pady=7, font=FONT_BOLD, cursor="hand2", command=self._cancel_queue, state="disabled")
597
+ self._btn_cancel.pack(side="right")
598
+
599
+ self._switch_src("url")
600
+
601
+ def _switch_src(self, mode):
602
+ self._src_mode.set(mode)
603
+ if mode == "file":
604
+ self._file_frame.pack(fill="x")
605
+ self._url_frame.pack_forget()
606
+ self._btn_file.configure(bg=ACCENT, fg="white")
607
+ self._btn_url.configure(bg=BG, fg=FG2)
608
+ else:
609
+ self._url_frame.pack(fill="x")
610
+ self._file_frame.pack_forget()
611
+ self._btn_url.configure(bg=ACCENT, fg="white")
612
+ self._btn_file.configure(bg=BG, fg=FG2)
613
+
614
+ def _browse_file(self):
615
+ if self._multi_file.get():
616
+ files = filedialog.askopenfilenames(filetypes=[("Video", "*.mp4 *.mkv *.avi *.mov *.ts *.m4v *.webm"), ("Todos", "*.*")])
617
+ if files:
618
+ self._file_var.set("\n".join(files))
619
+ else:
620
+ p = filedialog.askopenfilename(filetypes=[("Video", "*.mp4 *.mkv *.avi *.mov *.ts *.m4v *.webm"), ("Todos", "*.*")])
621
+ if p:
622
+ self._file_var.set(p)
623
+
624
+ def _get_sources(self):
625
+ if self._src_mode.get() == "file":
626
+ raw = self._file_var.get().strip()
627
+ lines = [l.strip() for l in raw.split("\n") if l.strip()]
628
+ return lines, False
629
+ else:
630
+ srcs = [ln.strip() for ln in self._url_text.get("1.0", "end").split("\n") if ln.strip()]
631
+ return srcs, True
632
+
633
+ # ─── PISTAS ───
634
+ def _build_tracks_section(self, parent):
635
+ s = self._section(parent, "Pistas")
636
+ f = tk.Frame(s, bg=CARD_BG)
637
+ f.pack(fill="x")
638
+ tk.Label(f, text="Audio:", bg=CARD_BG, fg=FG2, font=FONT_SUB).pack(side="left")
639
+ self._aud_cb = ttk.Combobox(f, state="readonly", font=FONT_MAIN, width=18)
640
+ self._aud_cb.pack(side="left", fill="x", expand=True, padx=(4, 12))
641
+ tk.Label(f, text="Sub:", bg=CARD_BG, fg=FG2, font=FONT_SUB).pack(side="left")
642
+ self._sub_cb = ttk.Combobox(f, state="readonly", font=FONT_MAIN, width=18)
643
+ self._sub_cb.pack(side="left", fill="x", expand=True, padx=(4, 0))
644
+
645
+ # ─── LOG ───
646
+ def _build_log_section(self, parent):
647
+ s = self._section(parent, "Progreso")
648
+ self._lbl_prog = tk.Label(s, text="Esperando...", bg=CARD_BG, fg=FG2, anchor="w", font=FONT_SUB)
649
+ self._lbl_prog.pack(fill="x")
650
+ self._pbar = ttk.Progressbar(s, mode="determinate", style="Horizontal.TProgressbar")
651
+ self._pbar.pack(fill="x", pady=(4, 8))
652
+
653
+ log_f = tk.Frame(s, bg=BG, padx=1, pady=1)
654
+ log_f.pack(fill="both", expand=True)
655
+ self._log_txt = tk.Text(log_f, bg="#0c1222", fg="#38bdf8", font=("Consolas", 9), bd=0, relief="flat", state="disabled", wrap="word")
656
+ sb = ttk.Scrollbar(log_f, command=self._log_txt.yview)
657
+ self._log_txt.configure(yscrollcommand=sb.set)
658
+ sb.pack(side="right", fill="y")
659
+ self._log_txt.pack(fill="both", expand=True)
660
+
661
+ # Tags de colores
662
+ self._log_txt.tag_configure("ok", foreground=GREEN)
663
+ self._log_txt.tag_configure("err", foreground=RED)
664
+ self._log_txt.tag_configure("warn", foreground=YELLOW)
665
+ self._log_txt.tag_configure("info", foreground=FG2)
666
+
667
+ def _log(self, msg):
668
+ self._log_txt.configure(state="normal")
669
+ tag = "info"
670
+ if "✓" in msg: tag = "ok"
671
+ elif "✗" in msg: tag = "err"
672
+ elif "⚠" in msg: tag = "warn"
673
+ self._log_txt.insert("end", msg + "\n", tag)
674
+ self._log_txt.see("end")
675
+ self._log_txt.configure(state="disabled")
676
+
677
+ def _set_progress(self, pct, label=""):
678
+ self._pbar["value"] = pct
679
+ self._lbl_prog.configure(text=label)
680
+ self.update_idletasks()
681
+
682
+ # ─── ACCIONES ───
683
+ def _do_analyze(self):
684
+ sources, is_url = self._get_sources()
685
+ if not sources:
686
+ messagebox.showwarning("Sin fuente", "Agrega al menos una URL o archivo.")
687
+ return
688
+
689
+ def _go():
690
+ self._log("⟳ Analizando fuentes…")
691
+
692
+ # Analizar primer elemento para mostrar pistas
693
+ src = sources[0]
694
+ info = probe(src)
695
+
696
+ ac = [f"[{t['idx']}] {t['lang']} · {t['codec']} · {t.get('sample_rate','?')}Hz · {t['ch']}ch" for t in info["audio"]]
697
+ sc = [f"[{t['idx']}] {t['lang']} · {t['codec']}" + (" [FORCED]" if t['forced'] else "") for t in info["subs"]]
698
+
699
+ self.after(0, lambda: self._aud_cb.configure(values=ac))
700
+ self.after(0, lambda: self._sub_cb.configure(values=sc))
701
+ if ac: self.after(0, lambda: self._aud_cb.set(ac[0]))
702
+ if sc: self.after(0, lambda: self._sub_cb.set(sc[0]))
703
+
704
+ v = info["video"]
705
+ v_info = f"{v.get('width','?')}x{v.get('height','?')} {v.get('codec','?')} {v.get('pix_fmt','?')}" if v else "Sin video"
706
+
707
+ parts = []
708
+ if len(sources) > 1:
709
+ parts.append(f"📦 {len(sources)} elementos en cola")
710
+ else:
711
+ parts.append(f"🎬 {info['title'] or 'Sin título'}")
712
+ parts.append(f"⏱ {fmt_dur(info['duration'])}")
713
+ parts.append(f"📐 {v_info}")
714
+ parts.append(f"🔊 {len(ac)} pistas")
715
+ parts.append(f"💬 {len(sc)} subs")
716
+ if info["size"]:
717
+ parts.append(f"💾 {fmt_size(info['size'])}")
718
+
719
+ txt = " | ".join(parts)
720
+ self.after(0, lambda: self._lbl_info.configure(text=txt, fg=GREEN))
721
+ self._log(txt)
722
+
723
+ # Si hay múltiples, analizar todos para detectar duración total
724
+ if len(sources) > 1:
725
+ total_dur = info["duration"]
726
+ failed = 0
727
+ for s2 in sources[1:]:
728
+ i2 = probe(s2)
729
+ if i2["duration"] > 0:
730
+ total_dur += i2["duration"]
731
+ else:
732
+ failed += 1
733
+ self._log(f"⏱ Duración total estimada: {fmt_dur(total_dur)}" + (f" ({failed} sin duración)" if failed else ""))
734
+
735
+ threading.Thread(target=_go, daemon=True).start()
736
+
737
+ def _cancel_queue(self):
738
+ self._queue.clear()
739
+ self._log("⚠ Cola cancelada por el usuario.")
740
+ self._btn_proc.configure(state="normal", bg=GREEN, text="▶ PROCESAR COLA")
741
+ self._btn_cancel.configure(state="disabled")
742
+ self._lbl_status.configure(text="● Cancelado", fg=RED)
743
+
744
+ def _do_process(self):
745
+ sources, is_url = self._get_sources()
746
+ if not sources:
747
+ return messagebox.showwarning("Sin fuente", "Agrega al menos una URL o archivo.")
748
+
749
+ out_dir = self._output_dir.get().strip()
750
+ if not out_dir:
751
+ return messagebox.showwarning("Sin carpeta", "Selecciona una carpeta de salida.")
752
+
753
+ Path(out_dir).mkdir(exist_ok=True, parents=True)
754
+
755
+ self._queue = sources.copy()
756
+ self._total_queue = len(self._queue)
757
+ self._current_idx = 0
758
+ self._processed_count = 0
759
+ self._failed_count = 0
760
+
761
+ self._btn_proc.configure(state="disabled", bg=FG2)
762
+ self._btn_cancel.configure(state="normal")
763
+ self._log_txt.configure(state="normal")
764
+ self._log_txt.delete("1.0", "end")
765
+ self._log_txt.configure(state="disabled")
766
+
767
+ self._log(f"🚀 Iniciando cola: {self._total_queue} elementos")
768
+ self._log(f"📂 Salida: {out_dir}")
769
+ self._log(f"⚙ Modo: {self._mode.get()}")
770
+ self._log("─" * 50)
771
+
772
+ self._process_next()
773
+
774
+ def _process_next(self):
775
+ if not self._queue:
776
+ self._btn_proc.configure(state="normal", bg=GREEN, text="▶ PROCESAR COLA")
777
+ self._btn_cancel.configure(state="disabled")
778
+ color = GREEN if self._failed_count == 0 else YELLOW
779
+ self._lbl_status.configure(text=f"● {self._processed_count} OK / {self._failed_count} Error", fg=color)
780
+ self._set_progress(100, f"Completado: {self._processed_count} exitosos, {self._failed_count} errores")
781
+ self._log("═" * 50)
782
+ self._log(f"✓ COLA FINALIZADA: {self._processed_count} OK, {self._failed_count} errores")
783
+ return
784
+
785
+ src = self._queue.pop(0)
786
+ self._current_idx += 1
787
+ self._lbl_status.configure(text=f"● Procesando {self._current_idx}/{self._total_queue}…", fg=YELLOW)
788
+ self._log(f"\n▶ [{self._current_idx}/{self._total_queue}] {src[:60]}{'...' if len(src)>60 else ''}")
789
+
790
+ # ─── LÓGICA DE NOMBRES ───
791
+ folder_name, file_name = "Render", f"Video_{self._current_idx:03d}"
792
+
793
+ if self._use_tmdb.get() and self._tmdb_res_cb.get():
794
+ base_lbl = self._tmdb_res_cb.get().split(" (")[0]
795
+ if self._tmdb_type.get() == "pelicula":
796
+ raw_folder = base_lbl
797
+ raw_file = f"{base_lbl} Parte {self._current_idx}" if self._total_queue > 1 else base_lbl
798
+ else:
799
+ s_num = self._tmdb_season_cb.get().split(" ")[1] if self._tmdb_season_cb.get() else "1"
800
+ raw_folder = f"{base_lbl} S{int(s_num):02d}"
801
+ ep_idx = self._tmdb_ep_cb.current() if self._tmdb_ep_cb.current() >= 0 else 0
802
+ tgt = ep_idx + self._current_idx - 1
803
+ if tgt < len(self._tmdb_episodes):
804
+ ep = self._tmdb_episodes[tgt]
805
+ raw_file = f"{base_lbl} S{int(s_num):02d}E{ep['num']:02d} {ep['name']}"
806
+ else:
807
+ raw_file = f"{base_lbl} S{int(s_num):02d}E{(tgt+1):02d}"
808
+ else:
809
+ m_name = self._manual_name.get().strip()
810
+ if m_name:
811
+ raw_folder = m_name
812
+ raw_file = f"{m_name} {self._current_idx:03d}" if self._total_queue > 1 else m_name
813
+ else:
814
+ if self._src_mode.get() == "file":
815
+ base = Path(src).stem
816
+ raw_folder = base
817
+ raw_file = base if self._total_queue == 1 else f"{base}_{self._current_idx:03d}"
818
+ else:
819
+ raw_folder = "URL_Render"
820
+ raw_file = f"URL_{self._current_idx:03d}"
821
+
822
+ if self._use_leet.get():
823
+ folder_name = to_leet(raw_folder)
824
+ file_name = to_leet(raw_file)
825
+ else:
826
+ folder_name = safe_name(raw_folder)
827
+ file_name = safe_name(raw_file)
828
+
829
+ ai, si = 0, 0
830
+ try:
831
+ if self._aud_cb.get(): ai = int(self._aud_cb.get().split("]")[0].strip("["))
832
+ if self._sub_cb.get(): si = int(self._sub_cb.get().split("]")[0].strip("["))
833
+ except:
834
+ pass
835
+
836
+ _, is_url_flag = self._get_sources()
837
+
838
+ def on_done(ok, files):
839
+ if ok:
840
+ self._processed_count += 1
841
+ self._log(f" ✅ Completado")
842
+ else:
843
+ self._failed_count += 1
844
+ self._log(f" ❌ Falló")
845
+ self.after(0, self._process_next)
846
+
847
+ threading.Thread(
848
+ target=render_video,
849
+ args=(src, is_url_flag, self._mode.get(), ai, self._gen_single.get(),
850
+ self._ext_sub.get(), si, folder_name, file_name,
851
+ self._output_dir.get().strip(),
852
+ lambda m: self.after(0, self._log, m),
853
+ lambda p, l: self.after(0, self._set_progress, p, l),
854
+ on_done),
855
+ daemon=True
856
+ ).start()
857
+
858
+
859
+ if __name__ == "__main__":
860
+ app = App()
861
+ app.mainloop()