CineMax commited on
Commit
7909810
Β·
verified Β·
1 Parent(s): 1b0d2c4

Update hugv3.py

Browse files
Files changed (1) hide show
  1. hugv3.py +448 -254
hugv3.py CHANGED
@@ -32,14 +32,13 @@ HF_ERROR = ""
32
  HF_VERSION = ""
33
  HF_PYTHON_PATH = sys.executable
34
  HF_PYTHON_VERSION = f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}"
35
- HF_HAS_UPLOAD_FOLDER = False # upload_folder() disponible?
36
 
37
  try:
38
  import huggingface_hub
39
  HF_VERSION = getattr(huggingface_hub, "__version__", "?")
40
  from huggingface_hub import HfApi
41
  HF_OK = True
42
- # Verificar si upload_folder existe
43
  HF_HAS_UPLOAD_FOLDER = hasattr(HfApi, 'upload_folder')
44
  except ImportError as e:
45
  HF_ERROR = (
@@ -71,11 +70,20 @@ FONT_MONO = ("Consolas", 8)
71
 
72
  SPANISH_CODES = {"spa", "es", "es-419", "es-mx", "es-es", "lat", "spanish"}
73
 
 
 
 
 
 
 
 
 
74
  QUALITY_DEFS = {
75
- "1080p": {"vf": "scale=-2:1080", "crf": "20", "bw": 5000000, "res": "1920x1080", "h": 1080},
76
- "720p": {"vf": "scale=-2:720", "crf": "23", "bw": 3000000, "res": "1280x720", "h": 720},
77
- "480p": {"vf": "scale=-2:480", "crf": "26", "bw": 1500000, "res": "854x480", "h": 480},
78
- "copy": {"vf": None, "crf": None, "bw": 0, "res": None, "h": 0},
 
79
  }
80
 
81
  def safe_name(s, maxlen=120):
@@ -182,51 +190,24 @@ def generate_master_m3u8(qualities_info, audio_tracks, subs_list, pl_type):
182
 
183
 
184
  # ═══════════════════════════════════════════════════════════════════
185
- # SUBIDA A HUGGINGFACE β€” SIN RATE LIMIT
186
- #
187
- # La clave: upload_folder() = 1 commit para TODA la carpeta
188
- # En vez de upload_file() = 1 commit por archivo (rate limit!)
189
- #
190
- # upload_folder maneja automΓ‘ticamente:
191
- # - Archivos grandes via Git LFS
192
- # - Reintentos internos
193
- # - Subida en paralelo cuando es posible
194
  # ═══════════════════════════════════════════════════════════════════
195
 
196
  def upload_folder_to_hf(token, repo_id, local_folder, path_in_repo, log_cb, progress_cb, pct_start, pct_end):
197
- """
198
- Sube una carpeta completa en 1 solo commit usando upload_folder().
199
- Esto evita el rate limit de 128 commits/hora.
200
- """
201
  from huggingface_hub import HfApi
202
  api = HfApi()
203
  repo_type = "model"
204
 
205
- # Crear repo si no existe
206
  try:
207
  api.create_repo(repo_id=repo_id, repo_type=repo_type, token=token, exist_ok=True, private=False)
208
  except Exception as e:
209
  if "already exists" not in str(e).lower():
210
  log_cb(f" ⚠ Creando repo: {e}")
211
 
212
- # Contar archivos para progreso
213
  all_files = [f for f in Path(local_folder).rglob("*") if f.is_file()]
214
  total = len(all_files)
215
  log_cb(f" ⬆ Subiendo {total} archivos en 1 commit...")
216
 
217
- # Callback de progreso interno
218
- uploaded_count = [0]
219
- def on_progress(file_path, progress):
220
- uploaded_count[0] += 1
221
- # Interpolar progreso entre pct_start y pct_end
222
- if total > 0:
223
- pct = pct_start + int((uploaded_count[0] / total) * (pct_end - pct_start))
224
- else:
225
- pct = pct_start
226
- fname = Path(file_path).name
227
- progress_cb(min(pct_end, pct), f"⬆ {uploaded_count[0]}/{total}: {fname}")
228
-
229
- # ── Intentar upload_folder (1 commit) ──
230
  for intento in range(3):
231
  try:
232
  api.upload_folder(
@@ -235,16 +216,12 @@ def upload_folder_to_hf(token, repo_id, local_folder, path_in_repo, log_cb, prog
235
  repo_id=repo_id,
236
  repo_type=repo_type,
237
  token=token,
238
- # allow_patterns=None β†’ sube todo
239
- # ignore_patterns=None β†’ no ignora nada
240
  )
241
  log_cb(f" βœ“ Carpeta subida: {total} archivos β†’ {path_in_repo}/")
242
  return True, total, 0
243
 
244
  except TypeError as te:
245
- # ParΓ‘metro no soportado en esta versiΓ³n
246
  log_cb(f" ⚠ upload_folder fallback ({te})...")
247
- # Intentar sin parΓ‘metros extras
248
  try:
249
  api.upload_folder(local_folder, path_in_repo, repo_id=repo_id, repo_type=repo_type, token=token)
250
  log_cb(f" βœ“ Carpeta subida (fallback): {total} archivos")
@@ -258,15 +235,12 @@ def upload_folder_to_hf(token, repo_id, local_folder, path_in_repo, log_cb, prog
258
  err = str(e)
259
  log_cb(f" ⚠ Intento {intento+1}/3: {err[:200]}")
260
 
261
- # Si es rate limit, esperar y reintentar
262
  if "rate limit" in err.lower() or "429" in err or "retry after" in err.lower():
263
- # Extraer segundos de espera si estΓ‘n en el mensaje
264
- wait_secs = 130 # default
265
  m = re.search(r'retry after (\d+) seconds', err, re.IGNORECASE)
266
  if m: wait_secs = int(m.group(1)) + 10
267
  m2 = re.search(r'retry.*?(\d+) second', err, re.IGNORECASE)
268
  if m2: wait_secs = int(m2.group(1)) + 10
269
-
270
  log_cb(f" ⏳ Rate limit. Esperando {wait_secs}s...")
271
  import time
272
  for remaining in range(wait_secs, 0, -10):
@@ -274,7 +248,6 @@ def upload_folder_to_hf(token, repo_id, local_folder, path_in_repo, log_cb, prog
274
  time.sleep(min(10, remaining))
275
  continue
276
 
277
- # Si es otro error fatal, intentar mΓ©todo alternativo
278
  if intento >= 2:
279
  log_cb(f" ⚠ upload_folder fallΓ³, usando mΓ©todo alternativo...")
280
  return upload_one_by_one_safe(token, repo_id, local_folder, path_in_repo, log_cb, progress_cb, pct_start, pct_end)
@@ -283,10 +256,6 @@ def upload_folder_to_hf(token, repo_id, local_folder, path_in_repo, log_cb, prog
283
 
284
 
285
  def upload_one_by_one_safe(token, repo_id, local_folder, path_in_repo, log_cb, progress_cb, pct_start, pct_end):
286
- """
287
- MÉTODO DE EMERGENCIA: Sube archivo por archivo CON delays para evitar rate limit.
288
- Solo se usa si upload_folder() no funciona.
289
- """
290
  from huggingface_hub import HfApi
291
  import time
292
  api = HfApi()
@@ -327,7 +296,6 @@ def upload_one_by_one_safe(token, repo_id, local_folder, path_in_repo, log_cb, p
327
  failed += 1
328
  break
329
 
330
- # Delay entre archivos para no golpear el rate limit
331
  if i < total - 1:
332
  time.sleep(3)
333
 
@@ -336,6 +304,52 @@ def upload_one_by_one_safe(token, repo_id, local_folder, path_in_repo, log_cb, p
336
 
337
 
338
  # ═══════════════════════════════════════════════════════════════════
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
339
  def process_video(token, repo_id, source, is_url,
340
  selected_qualities, audio_mode, extract_subs,
341
  delete_local, folder_name, file_name,
@@ -345,117 +359,164 @@ def process_video(token, repo_id, source, is_url,
345
  extra = NET_ARGS if is_url else []
346
  log_cb(f"⟳ Analizando: {source[:60]}...")
347
  info = probe(source)
348
- dur = info["duration"] if info["duration"] > 0 else 1
349
- vid = info["video"]; size_mb = info["size"]/(1024*1024) if info["size"] else 0
 
350
  log_cb(f" πŸ“Ή {vid['codec']} {vid['width']}x{vid['height']} | {fmt_dur(dur)} | {size_mb:.0f}MB")
351
  log_cb(f" πŸ”Š {len(info['audio'])} audios | πŸ“ {len(info['subs'])} subs")
352
 
353
  if audio_mode == "spanish":
354
  spa = [a for a in info["audio"] if is_spanish(a["lang"])]
355
  if not spa and info["audio"]:
356
- spa = [info["audio"][0]]; spa[0] = {**spa[0], "lang": "spa", "title": "EspaΓ±ol"}
 
357
  audios_to_process = spa
358
- else: audios_to_process = info["audio"]
359
- if not audios_to_process: log_cb(" ⚠ Sin pistas de audio")
 
 
360
 
 
 
 
361
  valid_q = []
362
  for q in selected_qualities:
363
- if q == "copy": valid_q.append(q)
 
 
 
 
 
364
  else:
365
- th = QUALITY_DEFS[q]["h"]
366
- if vid["height"] < th: log_cb(f" ⚠ {q} omitido: {vid['height']}p < {th}p")
367
- else: valid_q.append(q)
368
- if not valid_q: log_cb("βœ— Sin calidades vΓ‘lidas"); done_cb(False); return
369
-
370
- script_dir = Path(sys.argv[0]).parent.resolve()
371
- output_root = script_dir / "Videos_Procesados"; output_root.mkdir(exist_ok=True)
372
- uid = str(uuid.uuid4())[:8]
373
- tmp = output_root / f"temp_{uid}"; tmp.mkdir(exist_ok=True, parents=True)
374
- hls_dir = tmp / folder_name; hls_dir.mkdir(exist_ok=True, parents=True)
375
-
376
- total_steps = len(valid_q) + len(audios_to_process) + (len(info["subs"]) if extract_subs else 0) + 1
377
- step_n = [0]; base_p = [0.0]
 
 
 
 
 
 
 
 
 
 
 
 
378
  def next_step(label):
379
- step_n[0] += 1; base_p[0] = (step_n[0]-1)/max(total_steps,1)*80
 
380
  log_cb(f" ⟳ [{step_n[0]}/{total_steps}] {label}")
 
381
  def step_prog(pct, label=""):
382
- sub = pct/max(total_steps,1)*80
383
- progress_cb(min(80, int(base_p[0]+sub)), f"[{step_n[0]}/{total_steps}] {label}")
384
 
385
- seg = hls_segment_time
386
  pl_type_final = hls_playlist_type if hls_playlist_type else "vod"
387
  qualities_info = []
388
 
389
  for qual in valid_q:
390
- qdef = QUALITY_DEFS[qual]; qdir = hls_dir / qual; qdir.mkdir(exist_ok=True)
391
- next_step(f"Video {qual}...")
392
- cmd = ["ffmpeg","-y"] + extra + ["-i",source,"-map","0:v:0","-an"]
393
- if qual == "copy": cmd += ["-c:v","copy"]
394
- else: cmd += ["-c:v","libx264","-vf",qdef["vf"],"-preset","fast","-crf",qdef["crf"],
395
- "-keyint_min",str(seg*2),"-g",str(seg*2),"-sc_threshold","0"]
396
- cmd += ["-f","hls","-hls_time",str(seg),"-hls_list_size","0",
397
- "-hls_playlist_type",pl_type_final,"-hls_segment_type","mpegts",
398
- "-hls_flags","independent_segments",
399
- "-hls_segment_filename",str(qdir/"seg_%04d.ts"), str(qdir/"playlist.m3u8")]
400
  ok = run_ffmpeg(cmd, dur, log_cb, step_prog, f"Video {qual}")
401
- if not ok: log_cb(f" βœ— FallΓ³ video {qual}"); shutil.rmtree(tmp, ignore_errors=True); done_cb(False); return
402
- ts_count = len(list(qdir.glob("seg_*.ts"))); log_cb(f" βœ“ {qual}: {ts_count} segmentos")
403
- if qual == "copy":
404
- res = f"{vid['width']}x{vid['height']}" if vid['width'] else "1920x1080"
405
- bw = vid['bitrate'] if vid['bitrate'] > 100000 else 5000000
406
- else: res = qdef["res"]; bw = qdef["bw"]
407
- qualities_info.append({"resolution":res,"bandwidth":bw+400000,"uri":f"{qual}/playlist.m3u8"})
408
-
409
- audio_dir = hls_dir / "audio"; audio_dir.mkdir(exist_ok=True)
410
- audio_tracks_info = []; has_spanish = any(is_spanish(a["lang"]) for a in audios_to_process)
 
 
 
 
 
 
 
 
 
 
411
  for ai, atrack in enumerate(audios_to_process):
412
  lang = atrack["lang"]
413
- if lang == "und": lang = "spa" if not has_spanish else "und"
 
414
  next_step(f"Audio [{lang}] MP3 320k...")
415
- cmd = ["ffmpeg","-y"] + extra + ["-i",source,"-map",f"0:a:{atrack['idx']}",
416
- "-c:a","libmp3lame","-b:a","320k","-vn",
417
- "-f","hls","-hls_time",str(seg),"-hls_list_size","0",
418
- "-hls_playlist_type",pl_type_final,"-hls_segment_type","mpegts",
419
- "-hls_flags","independent_segments",
420
- "-hls_segment_filename",str(audio_dir/f"{lang}_%04d.ts"), str(audio_dir/f"{lang}.m3u8")]
421
- ok = run_ffmpeg(cmd, dur, log_cb, step_prog, f"Audio {lang}")
 
 
 
 
 
 
422
  ts_count = len(list(audio_dir.glob(f"{lang}_*.ts")))
423
- disp = atrack.get("title") or lang.upper()
424
- is_def = is_spanish(atrack["lang"]) or (not has_spanish and ai == 0)
425
- audio_tracks_info.append({"lang":lang,"name":disp,"default":is_def,"uri":f"audio/{lang}.m3u8"})
426
- star = " β˜…" if is_def else ""; log_cb(f" βœ“ Audio [{lang}]: {ts_count} seg{star}")
427
- if not ok: log_cb(f" ⚠ Audio [{lang}] con errores")
 
 
428
 
429
- subs_dir = hls_dir / "subs"; subs_info = []
 
430
  if extract_subs and info["subs"]:
431
  subs_dir.mkdir(exist_ok=True)
432
  for strack in info["subs"]:
433
  lang = strack["lang"]
434
- if lang == "und": lang = "spa"
 
435
  next_step(f"Sub [{lang}]...")
436
  vtt_path = subs_dir / f"{lang}.vtt"
437
- r = subprocess.run(["ffmpeg","-y"]+extra+["-i",source,"-map",f"0:s:{strack['idx']}",
438
- "-c:s","webvtt",str(vtt_path)], capture_output=True, text=True, timeout=120)
 
 
439
  if r.returncode == 0 and vtt_path.exists():
440
  is_def = is_spanish(lang)
441
- subs_info.append({"lang":lang,"name":strack.get("title") or lang.upper(),
442
- "default":is_def,"uri":f"subs/{lang}.vtt"})
443
  log_cb(f" βœ“ Sub [{lang}]" + (" β˜…" if is_def else ""))
444
- else: log_cb(f" βœ— Sub [{lang}] fallΓ³")
 
445
 
446
  next_step("Generando master.m3u8...")
447
  master_content = generate_master_m3u8(qualities_info, audio_tracks_info, subs_info, pl_type_final)
448
- master_path = hls_dir / "master.m3u8"
449
- with open(master_path, "w", encoding="utf-8") as f: f.write(master_content)
450
- log_cb(" βœ“ master.m3u8 generado"); progress_cb(80, "master.m3u8 OK")
 
 
451
 
452
  total_files = len(list(hls_dir.rglob("*")))
453
- total_size = sum(f.stat().st_size for f in hls_dir.rglob("*") if f.is_file())
454
  log_cb(f"\nπŸ“Š {total_files} archivos | {total_size/(1024*1024):.1f} MB")
455
 
456
- # ═══════════════════════════════════════════════
457
- # SUBIDA β€” 1 SOLO COMMIT PARA TODA LA CARPETA
458
- # ═══════════════════════════════════════════════
459
  log_cb(f"\n☁ Subiendo carpeta completa β†’ {repo_id}")
460
  log_cb(f" πŸ“‚ Ruta: videos/{folder_name}/")
461
 
@@ -464,14 +525,11 @@ def process_video(token, repo_id, source, is_url,
464
  log_cb(f" β„Ή Archivos guardados localmente en: {hls_dir}")
465
  else:
466
  ok, up_ok, up_fail = upload_folder_to_hf(
467
- token=token,
468
- repo_id=repo_id,
469
  local_folder=str(hls_dir),
470
  path_in_repo=f"videos/{folder_name}",
471
- log_cb=log_cb,
472
- progress_cb=progress_cb,
473
- pct_start=80,
474
- pct_end=99
475
  )
476
  if not ok:
477
  log_cb(f" βœ— La subida fallΓ³ parcialmente. Los archivos estΓ‘n en local.")
@@ -479,16 +537,23 @@ def process_video(token, repo_id, source, is_url,
479
  log_cb(f" βœ“βœ“ Subida completada en 1 commit (sin rate limit)")
480
 
481
  if delete_local:
482
- shutil.rmtree(tmp, ignore_errors=True); log_cb(" βœ“ Temporales borrados")
 
483
  else:
484
  final_dir = output_root / folder_name
485
- if final_dir.exists(): shutil.rmtree(final_dir, ignore_errors=True)
486
- shutil.move(str(hls_dir), str(final_dir)); shutil.rmtree(tmp, ignore_errors=True)
 
 
487
  log_cb(f" β„Ή Local: {final_dir}")
488
 
489
- progress_cb(100, "βœ“ Completado"); done_cb(True)
 
 
490
  except Exception as e:
491
- import traceback; log_cb(f"βœ— Error: {e}\n{traceback.format_exc()}"); done_cb(False)
 
 
492
 
493
 
494
  # ═══════════════════════════════════════════════════════════════════
@@ -519,11 +584,12 @@ class App(tk.Tk):
519
  header = tk.Frame(main, bg=BG); header.pack(fill="x", pady=(0,15))
520
  tk.Label(header, text="⬑ HLS CONVERTER PRO", bg=BG, fg=VIOLET, font=FONT_TITLE).pack(side="left")
521
  tk.Label(header, text="Video sin audio + Audios MP3 separados", bg=BG, fg=FG2, font=("Segoe UI",9)).pack(side="left", padx=(12,0))
522
- self._lbl_status = tk.Label(header, text="● Listo", bg=BG, fg=GREEN, font=FONT_MAIN); self._lbl_status.pack(side="right")
 
523
 
524
  body = tk.Frame(main, bg=BG); body.pack(fill="both", expand=True)
525
  body.columnconfigure(0, weight=0, minsize=350); body.columnconfigure(1, weight=1); body.rowconfigure(0, weight=1)
526
- left = tk.Frame(body, bg=CARD_BG, padx=15, pady=15); left.grid(row=0, column=0, sticky="nsew", padx=(0,10))
527
  right = tk.Frame(body, bg=CARD_BG, padx=15, pady=15); right.grid(row=0, column=1, sticky="nsew", padx=(10,0))
528
 
529
  self._build_hf(left); self._build_tmdb(left); self._build_hls_config(left)
@@ -534,42 +600,54 @@ class App(tk.Tk):
534
  def _sec(self, parent, title):
535
  f = tk.Frame(parent, bg=CARD_BG, pady=2); f.pack(fill="x", pady=(0,6))
536
  tk.Label(f, text=title.upper(), bg=CARD_BG, fg=FG2, font=("Segoe UI",8,"bold")).pack(anchor="w")
537
- tk.Frame(f, bg=BORDER, height=1).pack(fill="x", pady=(4,7)); return f
 
538
 
539
  def _build_hf(self, p):
540
  s = self._sec(p, "HuggingFace")
541
  if HF_OK:
542
- uf = "βœ“ upload_folder disponible" if HF_HAS_UPLOAD_FOLDER else "⚠ upload_folder NO disponible (se usarΓ‘ alternativo)"
543
- self._hf_status_lbl = tk.Label(s, text=f"βœ“ huggingface_hub v{HF_VERSION}\n{uf}", bg=CARD_BG, fg=GREEN, font=("Segoe UI",9,"bold"), anchor="w", justify="left")
 
544
  else:
545
- self._hf_status_lbl = tk.Label(s, text=f"βœ— huggingface_hub NO disponible", bg=CARD_BG, fg=RED, font=("Segoe UI",9,"bold"), anchor="w")
 
546
  self._hf_status_lbl.pack(fill="x", pady=(0,2))
547
 
548
- self._hf_py_lbl = tk.Label(s, text=f"Python {HF_PYTHON_VERSION} β†’ {HF_PYTHON_PATH}", bg="#0b1120", fg=FG2, font=FONT_MONO, anchor="w", padx=6, pady=3)
 
549
  self._hf_py_lbl.pack(fill="x", pady=(0,4))
550
 
551
  if not HF_OK:
552
- self._btn_install = tk.Button(s, text="πŸ“¦ INSTALAR huggingface_hub", bg=ORANGE, fg="white", bd=0, padx=8, pady=5, font=FONT_BOLD, cursor="hand2", command=self._auto_install_hf)
 
 
553
  self._btn_install.pack(fill="x", pady=(0,5))
554
- else: self._btn_install = None
 
555
 
556
  tk.Label(s, text="Token:", bg=CARD_BG, fg=FG2, font=FONT_MAIN).pack(anchor="w")
557
  self._hf_token = tk.StringVar()
558
- tk.Entry(s, textvariable=self._hf_token, show="*", bg=BG, fg=FG, insertbackground=FG, relief="flat").pack(fill="x", ipady=4, pady=(0,5))
 
559
 
560
- self._btn_test_hf = tk.Button(s, text="πŸ”— Probar ConexiΓ³n", bg=BG, fg=ACCENT, bd=0, padx=8, pady=4, font=FONT_MAIN, cursor="hand2", command=self._test_hf_connection)
 
 
561
  self._btn_test_hf.pack(fill="x", pady=(0,5))
562
 
563
  tk.Label(s, text="Repositorio (usuario/nombre):", bg=CARD_BG, fg=FG2, font=FONT_MAIN).pack(anchor="w")
564
  cf = tk.Frame(s, bg=CARD_BG); cf.pack(fill="x")
565
  self._repo_cb = ttk.Combobox(cf, font=FONT_MAIN); self._repo_cb.pack(side="left", fill="x", expand=True)
566
- tk.Button(cf, text="↻", bg=BG, fg=ACCENT, bd=0, font=FONT_BOLD, cursor="hand2", command=self._load_repos, width=3).pack(side="right", padx=(5,0))
 
567
 
568
  ft = tk.Frame(s, bg=CARD_BG); ft.pack(fill="x", pady=(3,0))
569
  self._repo_type = tk.StringVar(value="model")
570
  ttk.Radiobutton(ft, text="Model", variable=self._repo_type, value="model").pack(side="left")
571
  ttk.Radiobutton(ft, text="Space", variable=self._repo_type, value="space").pack(side="left", padx=(8,0))
572
- self._hf_user_lbl = tk.Label(s, text="", bg=CARD_BG, fg=FG2, font=("Segoe UI",8), anchor="w"); self._hf_user_lbl.pack(fill="x", pady=(3,0))
 
573
 
574
  def _auto_install_hf(self):
575
  if self._btn_install: self._btn_install.configure(text="⟳ Instalando...", state="disabled", bg=FG2)
@@ -580,32 +658,37 @@ class App(tk.Tk):
580
  r = subprocess.run(cmd, capture_output=True, text=True, timeout=300)
581
  if r.returncode == 0:
582
  self.after(0, lambda: self._log("βœ“ Instalado β€” cierra y abre de nuevo"))
583
- if self._btn_install: self.after(0, lambda: self._btn_install.configure(text="βœ“ INSTALADO β€” reinicia", bg=GREEN, state="disabled"))
 
584
  self.after(0, lambda: messagebox.showinfo("Listo", "Instalado. Cierra y abre de nuevo."))
585
  else:
586
  self.after(0, lambda: self._log(f"βœ— {r.stderr[-400:]}"))
587
- if self._btn_install: self.after(0, lambda: self._btn_install.configure(text="βœ— FallΓ³", bg=RED))
 
588
  except Exception as e:
589
  self.after(0, lambda: self._log(f"βœ— {e}"))
590
- if self._btn_install: self.after(0, lambda: self._btn_install.configure(text="βœ— Error", bg=RED))
 
591
  threading.Thread(target=_go, daemon=True).start()
592
 
593
  def _test_hf_connection(self):
594
  token = self._hf_token.get().strip()
595
  if not token: self._log("βœ— Ingresa token"); return
596
  if not HF_OK: self._log(f"βœ— {HF_ERROR.split(chr(10))[0]}"); return
597
- self._hf_status_lbl.configure(text="⟳ Conectando...", fg=YELLOW); self._btn_test_hf.configure(state="disabled")
 
598
  def _go():
599
  try:
600
  api = HfApi()
601
  try:
602
  ui = api.whoami(token=token)
603
- if hasattr(ui,'name'): username=ui.name; fullname=getattr(ui,'fullname',username)
604
- elif isinstance(ui,dict): username=ui.get('name','?'); fullname=ui.get('fullname',username)
605
- else: username=str(ui); fullname=username
606
  except Exception as e:
607
  self.after(0, lambda: self._hf_status_lbl.configure(text=f"βœ— Token invΓ‘lido: {e}", fg=RED))
608
- self.after(0, lambda: self._btn_test_hf.configure(state="normal")); return
 
609
  self.after(0, lambda: self._hf_status_lbl.configure(text=f"βœ“ {fullname}", fg=GREEN))
610
  self.after(0, lambda: self._hf_user_lbl.configure(text=f"@{username}", fg=FG2))
611
  self.after(0, lambda: self._log(f"βœ“ HF: {fullname} (@{username})"))
@@ -619,7 +702,8 @@ class App(tk.Tk):
619
  def _load_repos(self):
620
  token = self._hf_token.get().strip()
621
  if not token or not HF_OK: return
622
- self._log("⟳ Cargando repos..."); self._hf_user_lbl.configure(text="⟳ Cargando...", fg=YELLOW)
 
623
  def _go():
624
  try:
625
  api = HfApi()
@@ -664,7 +748,7 @@ class App(tk.Tk):
664
  tk.Entry(s, textvariable=self._tmdb_key, bg=BG, fg=FG, insertbackground=FG, relief="flat", show="*").pack(fill="x", ipady=3, pady=(0,4))
665
  fs = tk.Frame(s, bg=CARD_BG); fs.pack(fill="x", pady=(0,4))
666
  self._tmdb_type = tk.StringVar(value="serie")
667
- ttk.Radiobutton(fs, text="Serie", variable=self._tmdb_type, value="serie", command=self._tmdb_clear).pack(side="left")
668
  ttk.Radiobutton(fs, text="PelΓ­cula", variable=self._tmdb_type, value="pelicula", command=self._tmdb_clear).pack(side="left", padx=(5,10))
669
  self._tmdb_query = tk.StringVar()
670
  tk.Entry(fs, textvariable=self._tmdb_query, bg=BG, fg=FG, insertbackground=FG, relief="flat").pack(side="left", fill="x", expand=True, ipady=3)
@@ -683,44 +767,57 @@ class App(tk.Tk):
683
  self._tmdb_ep_cb.set(""); self._tmdb_ep_cb.configure(state="disabled")
684
 
685
  def _search_tmdb(self):
686
- k=self._tmdb_key.get().strip(); q=self._tmdb_query.get().strip()
687
  if not k or not q: return
688
- t="movie" if self._tmdb_type.get()=="pelicula" else "tv"
689
- url=f"https://api.themoviedb.org/3/search/{t}?api_key={k}&query={urllib.parse.quote(q)}&language=es-MX"
690
  def _go():
691
  try:
692
- data=fetch_tmdb(url); res=[]; self._tmdb_id_map={}
693
- for r in data.get('results',[])[:15]:
694
- title=r.get('title') or r.get('name'); dt=r.get('release_date') or r.get('first_air_date') or ""
695
- yr=dt.split('-')[0] if dt else "N/A"; lbl=f"{title} ({yr})"; res.append(lbl); self._tmdb_id_map[lbl]=r.get('id')
 
 
696
  self.after(0, lambda: self._tmdb_res_cb.configure(values=res))
697
- if res: self.after(0, lambda: self._tmdb_res_cb.set(res[0])); self.after(0, self._on_tmdb_res)
698
- except Exception as e: self.after(0, lambda: self._log(f"βœ— TMDb: {e}"))
 
 
 
699
  threading.Thread(target=_go, daemon=True).start()
700
 
701
  def _on_tmdb_res(self, *a):
702
- if self._tmdb_type.get()=="pelicula": self._tmdb_season_cb.configure(state="disabled"); self._tmdb_ep_cb.configure(state="disabled"); return
703
- self._tmdb_season_cb.configure(state="readonly"); tid=self._tmdb_id_map.get(self._tmdb_res_cb.get())
 
 
704
  if not tid: return
705
  def _go():
706
  try:
707
- data=fetch_tmdb(f"https://api.themoviedb.org/3/tv/{tid}?api_key={self._tmdb_key.get().strip()}&language=es-MX")
708
- ss=[f"T{s['season_number']}" for s in data.get('seasons',[]) if s['season_number']>0]
709
  self.after(0, lambda: self._tmdb_season_cb.configure(values=ss))
710
- if ss: self.after(0, lambda: self._tmdb_season_cb.set(ss[0])); self.after(0, self._on_tmdb_season)
711
- except Exception as e: self.after(0, lambda: self._log(f"βœ— TMDb: {e}"))
 
 
 
712
  threading.Thread(target=_go, daemon=True).start()
713
 
714
  def _on_tmdb_season(self, *a):
715
- self._tmdb_ep_cb.configure(state="readonly"); tid=self._tmdb_id_map.get(self._tmdb_res_cb.get()); sn=self._tmdb_season_cb.get().replace("T","")
 
 
716
  def _go():
717
  try:
718
- data=fetch_tmdb(f"https://api.themoviedb.org/3/tv/{tid}/season/{sn}?api_key={self._tmdb_key.get().strip()}&language=es-MX")
719
- self._tmdb_episodes=[{'num':e['episode_number'],'name':e['name']} for e in data.get('episodes',[])]
720
- es=[f"E{e['num']:02d}: {e['name']}" for e in self._tmdb_episodes]
721
  self.after(0, lambda: self._tmdb_ep_cb.configure(values=es))
722
  if es: self.after(0, lambda: self._tmdb_ep_cb.set(es[0]))
723
- except Exception as e: self.after(0, lambda: self._log(f"βœ— TMDb: {e}"))
 
724
  threading.Thread(target=_go, daemon=True).start()
725
 
726
  def _build_hls_config(self, p):
@@ -728,33 +825,69 @@ class App(tk.Tk):
728
  ft = tk.Frame(s, bg=CARD_BG); ft.pack(fill="x", pady=(0,6))
729
  tk.Label(ft, text="Tipo:", bg=CARD_BG, fg=FG2, font=FONT_MAIN).pack(side="left")
730
  self._hls_pl_type = tk.StringVar(value="vod")
731
- for v, l in [("vod","VOD"),("event","Event"),("","Live")]: ttk.Radiobutton(ft, text=l, variable=self._hls_pl_type, value=v).pack(side="left", padx=(0,8))
 
732
  fs = tk.Frame(s, bg=CARD_BG); fs.pack(fill="x")
733
  tk.Label(fs, text="Segmento:", bg=CARD_BG, fg=FG2, font=FONT_MAIN).pack(side="left")
734
  self._hls_seg = tk.StringVar(value="10")
735
- ttk.Combobox(fs, textvariable=self._hls_seg, values=["4","6","8","10","15","20","30"], width=5, state="readonly").pack(side="left", padx=(5,0))
 
736
  tk.Label(fs, text="s", bg=CARD_BG, fg=FG2, font=FONT_MAIN).pack(side="left", padx=(3,0))
737
 
738
  def _build_quality_section(self, p):
739
  s = self._sec(p, "Calidades Video (sin audio)")
 
 
740
  fp = tk.Frame(s, bg=CARD_BG); fp.pack(fill="x", pady=(0,5))
741
  tk.Label(fp, text="Presets:", bg=CARD_BG, fg=FG2, font=FONT_MAIN).pack(side="left")
742
- for lbl, qs in [("Multi+Copy",["1080p","720p","480p","copy"]),("Multi (3)",["1080p","720p","480p"]),("Solo Copy",["copy"]),("Solo 1080",["1080p"]),("Solo 720",["720p"]),("Solo 480",["480p"])]:
743
- tk.Button(fp, text=lbl, bg=BG, fg=ACCENT, bd=0, padx=5, pady=1, font=("Segoe UI",8), cursor="hand2", command=lambda q=qs: self._set_qualities(q)).pack(side="left", padx=(0,2))
744
- self._q_1080=tk.BooleanVar(value=True); self._q_720=tk.BooleanVar(value=True); self._q_480=tk.BooleanVar(value=True); self._q_copy=tk.BooleanVar(value=False)
745
- for var, name, desc in [(self._q_1080,"1080p","H264 CRF20 5Mbps"),(self._q_720,"720p","H264 CRF23 3Mbps"),(self._q_480,"480p","H264 CRF26 1.5Mbps"),(self._q_copy,"Copy","Original")]:
746
- row=tk.Frame(s,bg=CARD_BG); row.pack(fill="x", pady=1)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
747
  ttk.Checkbutton(row, text=name, variable=var, command=self._update_preview).pack(side="left")
748
- tk.Label(row, text=desc, bg=CARD_BG, fg=FG2, font=("Segoe UI",8)).pack(side="left", padx=(8,0))
 
749
 
750
  def _set_qualities(self, qs):
751
- self._q_1080.set("1080p" in qs); self._q_720.set("720p" in qs); self._q_480.set("480p" in qs); self._q_copy.set("copy" in qs); self._update_preview()
 
 
 
 
 
752
 
753
  def _get_qualities(self):
754
  qs = []
 
755
  if self._q_1080.get(): qs.append("1080p")
756
- if self._q_720.get(): qs.append("720p")
757
- if self._q_480.get(): qs.append("480p")
758
  if self._q_copy.get(): qs.append("copy")
759
  return qs
760
 
@@ -763,7 +896,7 @@ class App(tk.Tk):
763
  tk.Label(s, text="Codec: MP3 320kbps (siempre)", bg=CARD_BG, fg=CYAN, font=("Segoe UI",9,"bold")).pack(anchor="w", pady=(0,3))
764
  self._audio_mode = tk.StringVar(value="all")
765
  fa = tk.Frame(s, bg=CARD_BG); fa.pack(fill="x")
766
- ttk.Radiobutton(fa, text="Todos", variable=self._audio_mode, value="all", command=self._update_preview).pack(side="left")
767
  ttk.Radiobutton(fa, text="Solo espaΓ±ol β˜…", variable=self._audio_mode, value="spanish", command=self._update_preview).pack(side="left", padx=(10,0))
768
  tk.Label(s, text="⚠ Video .ts SIN audio", bg=CARD_BG, fg=YELLOW, font=("Segoe UI",8)).pack(anchor="w", pady=(3,0))
769
 
@@ -772,143 +905,203 @@ class App(tk.Tk):
772
  tk.Label(s, text="Nombre manual:", bg=CARD_BG, fg=FG2, font=FONT_MAIN).pack(anchor="w")
773
  self._manual_name = tk.StringVar()
774
  tk.Entry(s, textvariable=self._manual_name, bg=BG, fg=FG, insertbackground=FG, relief="flat").pack(fill="x", ipady=4, pady=(0,5))
775
- self._ext_sub = tk.BooleanVar(value=True); self._del_local = tk.BooleanVar(value=True)
 
776
  fo = tk.Frame(s, bg=CARD_BG); fo.pack(fill="x")
777
- ttk.Checkbutton(fo, text="Subs .vtt", variable=self._ext_sub, command=self._update_preview).pack(side="left")
778
  ttk.Checkbutton(fo, text="Borrar local", variable=self._del_local).pack(side="left", padx=10)
779
 
780
  def _build_tracks(self, p):
781
- s = self._sec(p, "Pistas Info"); f = tk.Frame(s, bg=CARD_BG); f.pack(fill="x")
 
782
  tk.Label(f, text="Aud:", bg=CARD_BG, fg=FG2, font=FONT_MAIN).pack(side="left")
783
- self._aud_cb = ttk.Combobox(f, state="readonly", font=FONT_MAIN, width=20); self._aud_cb.pack(side="left", fill="x", expand=True, padx=(5,10))
 
784
  tk.Label(f, text="Sub:", bg=CARD_BG, fg=FG2, font=FONT_MAIN).pack(side="left")
785
- self._sub_cb = ttk.Combobox(f, state="readonly", font=FONT_MAIN, width=20); self._sub_cb.pack(side="left", fill="x", expand=True, padx=(5,0))
 
786
 
787
  def _build_source(self, p):
788
  s = self._sec(p, "Fuente")
789
  tabs = tk.Frame(s, bg=CARD_BG); tabs.pack(fill="x", pady=(0,6))
790
  self._src_mode = tk.StringVar(value="url")
791
- self._btn_url = tk.Button(tabs, text="🌐 URLs", bg=ACCENT, fg="white", bd=0, padx=12, pady=5, font=FONT_MAIN, command=lambda: self._switch_src("url")); self._btn_url.pack(side="left")
792
- self._btn_file = tk.Button(tabs, text="πŸ“ Archivo", bg=BG, fg=FG2, bd=0, padx=12, pady=5, font=FONT_MAIN, command=lambda: self._switch_src("file")); self._btn_file.pack(side="left", padx=5)
 
 
793
  self._file_frame = tk.Frame(s, bg=CARD_BG); self._file_var = tk.StringVar()
794
- 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=4, padx=(0,5))
795
- tk.Button(self._file_frame, text="Buscar", bg=BG, fg=ACCENT, bd=0, padx=8, pady=4, font=FONT_MAIN, command=self._browse).pack(side="right")
796
- self._url_frame = tk.Frame(s, bg=CARD_BG); self._url_text = tk.Text(self._url_frame, bg=BG, fg=FG, insertbackground=FG, font=FONT_MAIN, relief="flat", height=4)
797
- sb = ttk.Scrollbar(self._url_frame, command=self._url_text.yview); self._url_text.configure(yscrollcommand=sb.set)
798
- self._url_text.pack(side="left", fill="both", expand=True, pady=2); sb.pack(side="right", fill="y", pady=2)
799
- self._lbl_info = tk.Label(s, text="Sin anΓ‘lisis", bg=BG, fg=FG2, font=FONT_MAIN, anchor="w", padx=10, pady=5); self._lbl_info.pack(fill="x", pady=(6,0))
800
- self._lbl_struct = tk.Label(s, text="", bg="#0b1120", fg=VIOLET, font=FONT_MONO, anchor="nw", padx=10, pady=6, justify="left", relief="flat"); self._lbl_struct.pack(fill="x", pady=(2,0))
 
 
 
 
 
 
 
 
 
 
 
 
801
  btns = tk.Frame(s, bg=CARD_BG); btns.pack(fill="x", pady=(10,0))
802
- tk.Button(btns, text="πŸ” ANALIZAR", bg=BG, fg=ACCENT, bd=0, padx=12, pady=8, font=FONT_BOLD, cursor="hand2", command=self._do_analyze).pack(side="left")
803
- self._btn_proc = tk.Button(btns, text="⬑ PROCESAR COLA HLS", bg=VIOLET, fg="white", bd=0, padx=12, pady=8, font=FONT_BOLD, cursor="hand2", command=self._do_process)
 
 
 
804
  self._btn_proc.pack(side="right", fill="x", expand=True, padx=(10,0))
805
  self._switch_src("url"); self._update_preview()
806
 
807
  def _build_log(self, p):
808
  s = self._sec(p, "Progreso")
809
- self._lbl_prog = tk.Label(s, text="Esperando...", bg=CARD_BG, fg=FG2, anchor="w"); self._lbl_prog.pack(fill="x")
810
- self._pbar = ttk.Progressbar(s, mode="determinate", style="Horizontal.TProgressbar"); self._pbar.pack(fill="x", pady=(5,6))
 
 
811
  lf = tk.Frame(s, bg=BG, padx=1, pady=1); lf.pack(fill="both", expand=True)
812
- self._log_txt = tk.Text(lf, bg=BG, fg="#0ea5e9", font=("Consolas",9), bd=0, relief="flat", state="disabled", wrap="word")
813
- sb = ttk.Scrollbar(lf, command=self._log_txt.yview); self._log_txt.configure(yscrollcommand=sb.set)
 
 
814
  sb.pack(side="right", fill="y"); self._log_txt.pack(fill="both", expand=True)
815
- for tag, color in [("green","#22c55e"),("red","#ef4444"),("yellow","#f59e0b"),("violet","#a78bfa"),("cyan","#22d3ee"),("dim","#64748b")]: self._log_txt.tag_configure(tag, foreground=color)
 
 
816
 
817
  def _switch_src(self, mode):
818
  self._src_mode.set(mode)
819
- if mode == "file": self._file_frame.pack(fill="x"); self._url_frame.pack_forget(); self._btn_file.configure(bg=ACCENT, fg="white"); self._btn_url.configure(bg=BG, fg=FG2)
820
- else: self._url_frame.pack(fill="x"); self._file_frame.pack_forget(); self._btn_url.configure(bg=ACCENT, fg="white"); self._btn_file.configure(bg=BG, fg=FG2)
 
 
 
 
821
 
822
  def _browse(self):
823
  p = filedialog.askopenfilename(filetypes=[("Video","*.mp4 *.mkv *.avi *.mov *.ts *.m3u8"),("Todos","*.*")])
824
  if p: self._file_var.set(p)
825
 
826
  def _get_sources(self):
827
- if self._src_mode.get()=="file": p=self._file_var.get().strip(); return ([p] if p else []), False
 
 
828
  return [ln.strip() for ln in self._url_text.get("1.0","end").split("\n") if ln.strip()], True
829
 
830
  def _log(self, msg):
831
- self._log_txt.configure(state="normal"); tag=""
832
- if "βœ“" in msg: tag="green"
833
- elif "βœ—" in msg: tag="red"
834
- elif "⚠" in msg: tag="yellow"
835
- elif "⬑" in msg or "HLS" in msg or "master" in msg: tag="violet"
836
- elif "Audio" in msg or "MP3" in msg: tag="cyan"
837
- elif "β„Ή" in msg: tag="dim"
838
- self._log_txt.insert("end", msg+"\n", tag); self._log_txt.see("end"); self._log_txt.configure(state="disabled")
 
 
839
 
840
  def _set_progress(self, pct, label=""):
841
- self._pbar["value"]=pct; self._lbl_prog.configure(text=label); self.update_idletasks()
842
 
843
  def _update_preview(self, *a):
844
- qs=self._get_qualities(); am=self._audio_mode.get(); es=self._ext_sub.get()
845
- if not qs: qs=["1080p"]
846
- lines=[f"videos/{to_leet(self._manual_name.get() or 'Nombre')}/","β”œβ”€β”€ master.m3u8"]
847
- for q in qs: lines+=[f"β”œβ”€β”€ {q}/",f"β”‚ β”œβ”€β”€ playlist.m3u8",f"β”‚ └── seg_XXXX.ts (solo video)"]
 
 
 
 
848
  lines.append("β”œβ”€β”€ audio/")
849
- if am=="spanish": lines+=["β”‚ β”œβ”€β”€ spa.m3u8 β˜…","β”‚ └── spa_XXXX.ts (MP3)"]
850
- else: lines+=["β”‚ β”œβ”€β”€ spa.m3u8 β˜…","β”‚ β”œβ”€β”€ eng.m3u8","β”‚ └── ..._XXXX.ts (MP3)"]
851
- if es: lines+=["└── subs/"," β”œβ”€β”€ spa.vtt β˜…"," └── eng.vtt"]
852
- else: lines.append("└── (sin subs)")
 
 
 
 
853
  self._lbl_struct.configure(text="\n".join(lines))
854
 
855
  def _do_analyze(self):
856
  sources, is_url = self._get_sources()
857
  if not sources: messagebox.showwarning("Error","Selecciona fuente."); return
858
  def _go():
859
- self._log("⟳ Analizando..."); info=probe(sources[0])
860
- ac=[f"[{t['idx']}] {t['lang']} Β· {t['codec']} Β· {t['ch']}ch" for t in info["audio"]]
861
- sc=[f"[{t['idx']}] {t['lang']} Β· {t['codec']}" for t in info["subs"]]
 
862
  self.after(0, lambda: self._aud_cb.configure(values=ac))
863
  self.after(0, lambda: self._sub_cb.configure(values=sc))
864
  if ac: self.after(0, lambda: self._aud_cb.set(ac[0]))
865
  if sc: self.after(0, lambda: self._sub_cb.set(sc[0]))
866
- v=info["video"]; dur=info["duration"]; sz=info["size"]/(1024*1024) if info["size"] else 0
867
- spa=sum(1 for a in info["audio"] if is_spanish(a["lang"]))
868
- txt=f"βœ“ {v['codec']} {v['width']}x{v['height']} | {fmt_dur(dur)} | {sz:.0f}MB | {len(ac)} aud ({spa} spa) | {len(sc)} sub"
869
- if len(sources)>1: txt=f"βœ“ {len(sources)} elementos | Bulk"
870
- self.after(0, lambda: self._lbl_info.configure(text=txt, fg=GREEN)); self._log(txt)
 
871
  threading.Thread(target=_go, daemon=True).start()
872
 
873
  def _do_process(self):
874
- tok=self._hf_token.get().strip(); rep=self._repo_cb.get().strip(); sources, is_url = self._get_sources()
875
- if not tok: messagebox.showwarning("Error","Ingresa Token."); return
876
- if not rep: messagebox.showwarning("Error","Ingresa repositorio."); return
 
877
  if "/" not in rep: messagebox.showwarning("Error","Formato: usuario/nombre"); return
878
  if not sources: messagebox.showwarning("Error","Selecciona fuente."); return
879
- qs=self._get_qualities()
880
  if not qs: messagebox.showwarning("Error","Selecciona calidad."); return
881
  if not HF_OK:
882
  if not messagebox.askyesno("Sin HF", f"{HF_ERROR.split(chr(10))[0]}\n\nΒΏGuardar localmente?"): return
883
- self._queue=sources.copy(); self._total_queue=len(self._queue); self._current_idx=0
884
  self._btn_proc.configure(state="disabled", bg=FG2)
885
  self._log_txt.configure(state="normal"); self._log_txt.delete("1.0","end"); self._log_txt.configure(state="disabled")
886
  self._log("⬑ Iniciando cola..."); self._process_next()
887
 
888
  def _process_next(self):
889
  if not self._queue:
890
- self._btn_proc.configure(state="normal", bg=VIOLET); self._lbl_status.configure(text="● Completado βœ“", fg=GREEN)
891
- self._set_progress(100, "βœ“ Todos completados"); return self._log("\n⬑⬑ COLA FINALIZADA ⬑⬑")
892
- src=self._queue.pop(0); self._current_idx+=1
 
 
893
  self._lbl_status.configure(text=f"● [{self._current_idx}/{self._total_queue}]", fg=YELLOW)
894
  self._log(f"\nβ–Ά ═══ [{self._current_idx}/{self._total_queue}] ═══")
895
  folder_name, file_name = "Bulk_Upload", f"Video_{self._current_idx}"
896
  if self._use_tmdb.get() and self._tmdb_res_cb.get():
897
- bl=self._tmdb_res_cb.get().split(" (")[0]
898
- if self._tmdb_type.get()=="pelicula": folder_name=to_leet(bl); file_name=to_leet(bl) if self._total_queue<=1 else to_leet(f"{bl}_P{self._current_idx}")
 
 
899
  else:
900
- sn=self._tmdb_season_cb.get().replace("T","") if self._tmdb_season_cb.get() else "1"; folder_name=to_leet(f"{bl}_S{int(sn):02d}")
901
- ei=self._tmdb_ep_cb.current() if self._tmdb_ep_cb.current()>=0 else 0; tgt=ei+self._current_idx-1
902
- if tgt<len(self._tmdb_episodes): ep=self._tmdb_episodes[tgt]; file_name=to_leet(f"{bl}_S{int(sn):02d}E{ep['num']:02d}_{ep['name']}")
903
- else: file_name=to_leet(f"{bl}_S{int(sn):02d}E{(tgt+1):02d}")
 
 
 
 
 
904
  else:
905
- mn=self._manual_name.get().strip()
906
- if mn: folder_name=to_leet(mn); file_name=to_leet(mn) if self._total_queue<=1 else to_leet(f"{mn}_{self._current_idx}")
 
 
907
  else:
908
- _, iu=self._get_sources()
909
- if not iu: base=Path(src).stem; folder_name=to_leet(base); file_name=to_leet(base)
910
- self._log(f" πŸ“‚ videos/{folder_name}/"); _, iuc=self._get_sources()
911
- threading.Thread(target=process_video,
 
 
 
912
  args=(self._hf_token.get().strip(), self._repo_cb.get().strip(), src, iuc,
913
  self._get_qualities(), self._audio_mode.get(), self._ext_sub.get(),
914
  self._del_local.get(), folder_name, file_name,
@@ -916,7 +1109,8 @@ class App(tk.Tk):
916
  lambda m: self.after(0, self._log, m),
917
  lambda p, l: self.after(0, self._set_progress, p, l),
918
  lambda ok: self.after(0, self._process_next)),
919
- daemon=True).start()
 
920
 
921
 
922
  if __name__ == "__main__":
 
32
  HF_VERSION = ""
33
  HF_PYTHON_PATH = sys.executable
34
  HF_PYTHON_VERSION = f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}"
35
+ HF_HAS_UPLOAD_FOLDER = False
36
 
37
  try:
38
  import huggingface_hub
39
  HF_VERSION = getattr(huggingface_hub, "__version__", "?")
40
  from huggingface_hub import HfApi
41
  HF_OK = True
 
42
  HF_HAS_UPLOAD_FOLDER = hasattr(HfApi, 'upload_folder')
43
  except ImportError as e:
44
  HF_ERROR = (
 
70
 
71
  SPANISH_CODES = {"spa", "es", "es-419", "es-mx", "es-es", "lat", "spanish"}
72
 
73
+ # ═══════════════════════════════════════════════════════════════════
74
+ # CALIDADES
75
+ # 4K = copy si ya es 4K, sino escala
76
+ # 1080 = SIEMPRE copy (nunca se omite, nunca re-encodea)
77
+ # 720 = fast (re-encodar rΓ‘pido, preset fast)
78
+ # 480 = fast (re-encodar rΓ‘pido, preset fast)
79
+ # copy = copia exacta del stream original
80
+ # ═══════════════════════════════════════════════════════════════════
81
  QUALITY_DEFS = {
82
+ "4k": {"vf": "scale=-2:2160", "crf": "18", "preset": "fast", "bw": 20000000, "res": "3840x2160", "h": 2160, "force_copy": False},
83
+ "1080p": {"vf": None, "crf": None, "preset": None, "bw": 8000000, "res": "1920x1080", "h": 1080, "force_copy": True},
84
+ "720p": {"vf": "scale=-2:720", "crf": "23", "preset": "fast", "bw": 3000000, "res": "1280x720", "h": 720, "force_copy": False},
85
+ "480p": {"vf": "scale=-2:480", "crf": "26", "preset": "fast", "bw": 1500000, "res": "854x480", "h": 480, "force_copy": False},
86
+ "copy": {"vf": None, "crf": None, "preset": None, "bw": 0, "res": None, "h": 0, "force_copy": True},
87
  }
88
 
89
  def safe_name(s, maxlen=120):
 
190
 
191
 
192
  # ═══════════════════════════════════════════════════════════════════
193
+ # SUBIDA A HUGGINGFACE
 
 
 
 
 
 
 
 
194
  # ═══════════════════════════════════════════════════════════════════
195
 
196
  def upload_folder_to_hf(token, repo_id, local_folder, path_in_repo, log_cb, progress_cb, pct_start, pct_end):
 
 
 
 
197
  from huggingface_hub import HfApi
198
  api = HfApi()
199
  repo_type = "model"
200
 
 
201
  try:
202
  api.create_repo(repo_id=repo_id, repo_type=repo_type, token=token, exist_ok=True, private=False)
203
  except Exception as e:
204
  if "already exists" not in str(e).lower():
205
  log_cb(f" ⚠ Creando repo: {e}")
206
 
 
207
  all_files = [f for f in Path(local_folder).rglob("*") if f.is_file()]
208
  total = len(all_files)
209
  log_cb(f" ⬆ Subiendo {total} archivos en 1 commit...")
210
 
 
 
 
 
 
 
 
 
 
 
 
 
 
211
  for intento in range(3):
212
  try:
213
  api.upload_folder(
 
216
  repo_id=repo_id,
217
  repo_type=repo_type,
218
  token=token,
 
 
219
  )
220
  log_cb(f" βœ“ Carpeta subida: {total} archivos β†’ {path_in_repo}/")
221
  return True, total, 0
222
 
223
  except TypeError as te:
 
224
  log_cb(f" ⚠ upload_folder fallback ({te})...")
 
225
  try:
226
  api.upload_folder(local_folder, path_in_repo, repo_id=repo_id, repo_type=repo_type, token=token)
227
  log_cb(f" βœ“ Carpeta subida (fallback): {total} archivos")
 
235
  err = str(e)
236
  log_cb(f" ⚠ Intento {intento+1}/3: {err[:200]}")
237
 
 
238
  if "rate limit" in err.lower() or "429" in err or "retry after" in err.lower():
239
+ wait_secs = 130
 
240
  m = re.search(r'retry after (\d+) seconds', err, re.IGNORECASE)
241
  if m: wait_secs = int(m.group(1)) + 10
242
  m2 = re.search(r'retry.*?(\d+) second', err, re.IGNORECASE)
243
  if m2: wait_secs = int(m2.group(1)) + 10
 
244
  log_cb(f" ⏳ Rate limit. Esperando {wait_secs}s...")
245
  import time
246
  for remaining in range(wait_secs, 0, -10):
 
248
  time.sleep(min(10, remaining))
249
  continue
250
 
 
251
  if intento >= 2:
252
  log_cb(f" ⚠ upload_folder fallΓ³, usando mΓ©todo alternativo...")
253
  return upload_one_by_one_safe(token, repo_id, local_folder, path_in_repo, log_cb, progress_cb, pct_start, pct_end)
 
256
 
257
 
258
  def upload_one_by_one_safe(token, repo_id, local_folder, path_in_repo, log_cb, progress_cb, pct_start, pct_end):
 
 
 
 
259
  from huggingface_hub import HfApi
260
  import time
261
  api = HfApi()
 
296
  failed += 1
297
  break
298
 
 
299
  if i < total - 1:
300
  time.sleep(3)
301
 
 
304
 
305
 
306
  # ═══════════════════════════════════════════════════════════════════
307
+ # LΓ“GICA DE CALIDAD:
308
+ #
309
+ # 4k β†’ re-encodar a 2160p (solo si el video es >= 2160p)
310
+ # 1080p β†’ SIEMPRE copy, NUNCA se omite, NUNCA re-encodea
311
+ # 720p β†’ re-encodar con preset fast
312
+ # 480p β†’ re-encodar con preset fast
313
+ # copy β†’ copia exacta del stream original
314
+ # ═══════════════════════════════════════════════════════════════════
315
+
316
+ def build_video_cmd(qual, qdef, source, extra, seg, pl_type_final, qdir, vid_info):
317
+ cmd = ["ffmpeg", "-y"] + extra + ["-i", source, "-map", "0:v:0", "-an"]
318
+
319
+ force_copy = qdef.get("force_copy", False)
320
+
321
+ if force_copy:
322
+ # 1080p y copy: nunca re-encodar
323
+ cmd += ["-c:v", "copy"]
324
+ res = f"{vid_info['width']}x{vid_info['height']}" if vid_info['width'] else "1920x1080"
325
+ bw = vid_info['bitrate'] if vid_info['bitrate'] > 100000 else qdef["bw"] or 5000000
326
+ else:
327
+ # 4k, 720p, 480p: re-encodar con preset fast
328
+ cmd += [
329
+ "-c:v", "libx264",
330
+ "-vf", qdef["vf"],
331
+ "-preset", qdef["preset"],
332
+ "-crf", qdef["crf"],
333
+ "-keyint_min", str(seg * 2),
334
+ "-g", str(seg * 2),
335
+ "-sc_threshold", "0",
336
+ ]
337
+ res = qdef["res"]
338
+ bw = qdef["bw"]
339
+
340
+ cmd += [
341
+ "-f", "hls",
342
+ "-hls_time", str(seg),
343
+ "-hls_list_size", "0",
344
+ "-hls_playlist_type", pl_type_final,
345
+ "-hls_segment_type", "mpegts",
346
+ "-hls_flags", "independent_segments",
347
+ "-hls_segment_filename", str(qdir / "seg_%04d.ts"),
348
+ str(qdir / "playlist.m3u8"),
349
+ ]
350
+ return cmd, res, bw
351
+
352
+
353
  def process_video(token, repo_id, source, is_url,
354
  selected_qualities, audio_mode, extract_subs,
355
  delete_local, folder_name, file_name,
 
359
  extra = NET_ARGS if is_url else []
360
  log_cb(f"⟳ Analizando: {source[:60]}...")
361
  info = probe(source)
362
+ dur = info["duration"] if info["duration"] > 0 else 1
363
+ vid = info["video"]
364
+ size_mb = info["size"] / (1024 * 1024) if info["size"] else 0
365
  log_cb(f" πŸ“Ή {vid['codec']} {vid['width']}x{vid['height']} | {fmt_dur(dur)} | {size_mb:.0f}MB")
366
  log_cb(f" πŸ”Š {len(info['audio'])} audios | πŸ“ {len(info['subs'])} subs")
367
 
368
  if audio_mode == "spanish":
369
  spa = [a for a in info["audio"] if is_spanish(a["lang"])]
370
  if not spa and info["audio"]:
371
+ spa = [info["audio"][0]]
372
+ spa[0] = {**spa[0], "lang": "spa", "title": "EspaΓ±ol"}
373
  audios_to_process = spa
374
+ else:
375
+ audios_to_process = info["audio"]
376
+ if not audios_to_process:
377
+ log_cb(" ⚠ Sin pistas de audio")
378
 
379
+ # ── Validar calidades ──────────────────────────────────────
380
+ # 1080p NUNCA se omite (force_copy=True β†’ siempre copy)
381
+ # 4k/720p/480p se omiten si el video es menor que la resoluciΓ³n target
382
  valid_q = []
383
  for q in selected_qualities:
384
+ qdef = QUALITY_DEFS[q]
385
+ if qdef.get("force_copy", False):
386
+ # 1080p y "copy" nunca se omiten
387
+ valid_q.append(q)
388
+ if q == "1080p" and vid["height"] < 1080:
389
+ log_cb(f" β„Ή 1080p: video es {vid['height']}p β†’ usando copy igual (sin re-encodar)")
390
  else:
391
+ th = qdef["h"]
392
+ if th > 0 and vid["height"] < th:
393
+ log_cb(f" ⚠ {q} omitido: {vid['height']}p < {th}p")
394
+ else:
395
+ valid_q.append(q)
396
+
397
+ if not valid_q:
398
+ log_cb("βœ— Sin calidades vΓ‘lidas")
399
+ done_cb(False)
400
+ return
401
+
402
+ script_dir = Path(sys.argv[0]).parent.resolve()
403
+ output_root = script_dir / "Videos_Procesados"
404
+ output_root.mkdir(exist_ok=True)
405
+ uid = str(uuid.uuid4())[:8]
406
+ tmp = output_root / f"temp_{uid}"
407
+ tmp.mkdir(exist_ok=True, parents=True)
408
+ hls_dir = tmp / folder_name
409
+ hls_dir.mkdir(exist_ok=True, parents=True)
410
+
411
+ total_steps = (len(valid_q) + len(audios_to_process)
412
+ + (len(info["subs"]) if extract_subs else 0) + 1)
413
+ step_n = [0]
414
+ base_p = [0.0]
415
+
416
  def next_step(label):
417
+ step_n[0] += 1
418
+ base_p[0] = (step_n[0] - 1) / max(total_steps, 1) * 80
419
  log_cb(f" ⟳ [{step_n[0]}/{total_steps}] {label}")
420
+
421
  def step_prog(pct, label=""):
422
+ sub = pct / max(total_steps, 1) * 80
423
+ progress_cb(min(80, int(base_p[0] + sub)), f"[{step_n[0]}/{total_steps}] {label}")
424
 
425
+ seg = hls_segment_time
426
  pl_type_final = hls_playlist_type if hls_playlist_type else "vod"
427
  qualities_info = []
428
 
429
  for qual in valid_q:
430
+ qdef = QUALITY_DEFS[qual]
431
+ qdir = hls_dir / qual
432
+ qdir.mkdir(exist_ok=True)
433
+
434
+ label_enc = "copy" if qdef.get("force_copy") else f"preset:{qdef['preset']}"
435
+ next_step(f"Video {qual} ({label_enc})...")
436
+
437
+ cmd, res, bw = build_video_cmd(qual, qdef, source, extra, seg, pl_type_final, qdir, vid)
 
 
438
  ok = run_ffmpeg(cmd, dur, log_cb, step_prog, f"Video {qual}")
439
+
440
+ if not ok:
441
+ log_cb(f" βœ— FallΓ³ video {qual}")
442
+ shutil.rmtree(tmp, ignore_errors=True)
443
+ done_cb(False)
444
+ return
445
+
446
+ ts_count = len(list(qdir.glob("seg_*.ts")))
447
+ log_cb(f" βœ“ {qual}: {ts_count} segmentos [{label_enc}] res={res}")
448
+ qualities_info.append({
449
+ "resolution": res,
450
+ "bandwidth": bw + 400000,
451
+ "uri": f"{qual}/playlist.m3u8",
452
+ })
453
+
454
+ audio_dir = hls_dir / "audio"
455
+ audio_dir.mkdir(exist_ok=True)
456
+ audio_tracks_info = []
457
+ has_spanish = any(is_spanish(a["lang"]) for a in audios_to_process)
458
+
459
  for ai, atrack in enumerate(audios_to_process):
460
  lang = atrack["lang"]
461
+ if lang == "und":
462
+ lang = "spa" if not has_spanish else "und"
463
  next_step(f"Audio [{lang}] MP3 320k...")
464
+ cmd = (["ffmpeg", "-y"] + extra +
465
+ ["-i", source,
466
+ "-map", f"0:a:{atrack['idx']}",
467
+ "-c:a", "libmp3lame", "-b:a", "320k", "-vn",
468
+ "-f", "hls",
469
+ "-hls_time", str(seg),
470
+ "-hls_list_size", "0",
471
+ "-hls_playlist_type", pl_type_final,
472
+ "-hls_segment_type", "mpegts",
473
+ "-hls_flags", "independent_segments",
474
+ "-hls_segment_filename", str(audio_dir / f"{lang}_%04d.ts"),
475
+ str(audio_dir / f"{lang}.m3u8")])
476
+ ok = run_ffmpeg(cmd, dur, log_cb, step_prog, f"Audio {lang}")
477
  ts_count = len(list(audio_dir.glob(f"{lang}_*.ts")))
478
+ disp = atrack.get("title") or lang.upper()
479
+ is_def = is_spanish(atrack["lang"]) or (not has_spanish and ai == 0)
480
+ audio_tracks_info.append({"lang": lang, "name": disp, "default": is_def, "uri": f"audio/{lang}.m3u8"})
481
+ star = " β˜…" if is_def else ""
482
+ log_cb(f" βœ“ Audio [{lang}]: {ts_count} seg{star}")
483
+ if not ok:
484
+ log_cb(f" ⚠ Audio [{lang}] con errores")
485
 
486
+ subs_dir = hls_dir / "subs"
487
+ subs_info = []
488
  if extract_subs and info["subs"]:
489
  subs_dir.mkdir(exist_ok=True)
490
  for strack in info["subs"]:
491
  lang = strack["lang"]
492
+ if lang == "und":
493
+ lang = "spa"
494
  next_step(f"Sub [{lang}]...")
495
  vtt_path = subs_dir / f"{lang}.vtt"
496
+ r = subprocess.run(
497
+ ["ffmpeg", "-y"] + extra +
498
+ ["-i", source, "-map", f"0:s:{strack['idx']}", "-c:s", "webvtt", str(vtt_path)],
499
+ capture_output=True, text=True, timeout=120)
500
  if r.returncode == 0 and vtt_path.exists():
501
  is_def = is_spanish(lang)
502
+ subs_info.append({"lang": lang, "name": strack.get("title") or lang.upper(),
503
+ "default": is_def, "uri": f"subs/{lang}.vtt"})
504
  log_cb(f" βœ“ Sub [{lang}]" + (" β˜…" if is_def else ""))
505
+ else:
506
+ log_cb(f" βœ— Sub [{lang}] fallΓ³")
507
 
508
  next_step("Generando master.m3u8...")
509
  master_content = generate_master_m3u8(qualities_info, audio_tracks_info, subs_info, pl_type_final)
510
+ master_path = hls_dir / "master.m3u8"
511
+ with open(master_path, "w", encoding="utf-8") as f:
512
+ f.write(master_content)
513
+ log_cb(" βœ“ master.m3u8 generado")
514
+ progress_cb(80, "master.m3u8 OK")
515
 
516
  total_files = len(list(hls_dir.rglob("*")))
517
+ total_size = sum(f.stat().st_size for f in hls_dir.rglob("*") if f.is_file())
518
  log_cb(f"\nπŸ“Š {total_files} archivos | {total_size/(1024*1024):.1f} MB")
519
 
 
 
 
520
  log_cb(f"\n☁ Subiendo carpeta completa β†’ {repo_id}")
521
  log_cb(f" πŸ“‚ Ruta: videos/{folder_name}/")
522
 
 
525
  log_cb(f" β„Ή Archivos guardados localmente en: {hls_dir}")
526
  else:
527
  ok, up_ok, up_fail = upload_folder_to_hf(
528
+ token=token, repo_id=repo_id,
 
529
  local_folder=str(hls_dir),
530
  path_in_repo=f"videos/{folder_name}",
531
+ log_cb=log_cb, progress_cb=progress_cb,
532
+ pct_start=80, pct_end=99,
 
 
533
  )
534
  if not ok:
535
  log_cb(f" βœ— La subida fallΓ³ parcialmente. Los archivos estΓ‘n en local.")
 
537
  log_cb(f" βœ“βœ“ Subida completada en 1 commit (sin rate limit)")
538
 
539
  if delete_local:
540
+ shutil.rmtree(tmp, ignore_errors=True)
541
+ log_cb(" βœ“ Temporales borrados")
542
  else:
543
  final_dir = output_root / folder_name
544
+ if final_dir.exists():
545
+ shutil.rmtree(final_dir, ignore_errors=True)
546
+ shutil.move(str(hls_dir), str(final_dir))
547
+ shutil.rmtree(tmp, ignore_errors=True)
548
  log_cb(f" β„Ή Local: {final_dir}")
549
 
550
+ progress_cb(100, "βœ“ Completado")
551
+ done_cb(True)
552
+
553
  except Exception as e:
554
+ import traceback
555
+ log_cb(f"βœ— Error: {e}\n{traceback.format_exc()}")
556
+ done_cb(False)
557
 
558
 
559
  # ═══════════════════════════════════════════════════════════════════
 
584
  header = tk.Frame(main, bg=BG); header.pack(fill="x", pady=(0,15))
585
  tk.Label(header, text="⬑ HLS CONVERTER PRO", bg=BG, fg=VIOLET, font=FONT_TITLE).pack(side="left")
586
  tk.Label(header, text="Video sin audio + Audios MP3 separados", bg=BG, fg=FG2, font=("Segoe UI",9)).pack(side="left", padx=(12,0))
587
+ self._lbl_status = tk.Label(header, text="● Listo", bg=BG, fg=GREEN, font=FONT_MAIN)
588
+ self._lbl_status.pack(side="right")
589
 
590
  body = tk.Frame(main, bg=BG); body.pack(fill="both", expand=True)
591
  body.columnconfigure(0, weight=0, minsize=350); body.columnconfigure(1, weight=1); body.rowconfigure(0, weight=1)
592
+ left = tk.Frame(body, bg=CARD_BG, padx=15, pady=15); left.grid(row=0, column=0, sticky="nsew", padx=(0,10))
593
  right = tk.Frame(body, bg=CARD_BG, padx=15, pady=15); right.grid(row=0, column=1, sticky="nsew", padx=(10,0))
594
 
595
  self._build_hf(left); self._build_tmdb(left); self._build_hls_config(left)
 
600
  def _sec(self, parent, title):
601
  f = tk.Frame(parent, bg=CARD_BG, pady=2); f.pack(fill="x", pady=(0,6))
602
  tk.Label(f, text=title.upper(), bg=CARD_BG, fg=FG2, font=("Segoe UI",8,"bold")).pack(anchor="w")
603
+ tk.Frame(f, bg=BORDER, height=1).pack(fill="x", pady=(4,7))
604
+ return f
605
 
606
  def _build_hf(self, p):
607
  s = self._sec(p, "HuggingFace")
608
  if HF_OK:
609
+ uf = "βœ“ upload_folder disponible" if HF_HAS_UPLOAD_FOLDER else "⚠ upload_folder NO disponible"
610
+ self._hf_status_lbl = tk.Label(s, text=f"βœ“ huggingface_hub v{HF_VERSION}\n{uf}",
611
+ bg=CARD_BG, fg=GREEN, font=("Segoe UI",9,"bold"), anchor="w", justify="left")
612
  else:
613
+ self._hf_status_lbl = tk.Label(s, text="βœ— huggingface_hub NO disponible",
614
+ bg=CARD_BG, fg=RED, font=("Segoe UI",9,"bold"), anchor="w")
615
  self._hf_status_lbl.pack(fill="x", pady=(0,2))
616
 
617
+ self._hf_py_lbl = tk.Label(s, text=f"Python {HF_PYTHON_VERSION} β†’ {HF_PYTHON_PATH}",
618
+ bg="#0b1120", fg=FG2, font=FONT_MONO, anchor="w", padx=6, pady=3)
619
  self._hf_py_lbl.pack(fill="x", pady=(0,4))
620
 
621
  if not HF_OK:
622
+ self._btn_install = tk.Button(s, text="πŸ“¦ INSTALAR huggingface_hub", bg=ORANGE, fg="white",
623
+ bd=0, padx=8, pady=5, font=FONT_BOLD, cursor="hand2",
624
+ command=self._auto_install_hf)
625
  self._btn_install.pack(fill="x", pady=(0,5))
626
+ else:
627
+ self._btn_install = None
628
 
629
  tk.Label(s, text="Token:", bg=CARD_BG, fg=FG2, font=FONT_MAIN).pack(anchor="w")
630
  self._hf_token = tk.StringVar()
631
+ tk.Entry(s, textvariable=self._hf_token, show="*", bg=BG, fg=FG,
632
+ insertbackground=FG, relief="flat").pack(fill="x", ipady=4, pady=(0,5))
633
 
634
+ self._btn_test_hf = tk.Button(s, text="πŸ”— Probar ConexiΓ³n", bg=BG, fg=ACCENT,
635
+ bd=0, padx=8, pady=4, font=FONT_MAIN, cursor="hand2",
636
+ command=self._test_hf_connection)
637
  self._btn_test_hf.pack(fill="x", pady=(0,5))
638
 
639
  tk.Label(s, text="Repositorio (usuario/nombre):", bg=CARD_BG, fg=FG2, font=FONT_MAIN).pack(anchor="w")
640
  cf = tk.Frame(s, bg=CARD_BG); cf.pack(fill="x")
641
  self._repo_cb = ttk.Combobox(cf, font=FONT_MAIN); self._repo_cb.pack(side="left", fill="x", expand=True)
642
+ tk.Button(cf, text="↻", bg=BG, fg=ACCENT, bd=0, font=FONT_BOLD, cursor="hand2",
643
+ command=self._load_repos, width=3).pack(side="right", padx=(5,0))
644
 
645
  ft = tk.Frame(s, bg=CARD_BG); ft.pack(fill="x", pady=(3,0))
646
  self._repo_type = tk.StringVar(value="model")
647
  ttk.Radiobutton(ft, text="Model", variable=self._repo_type, value="model").pack(side="left")
648
  ttk.Radiobutton(ft, text="Space", variable=self._repo_type, value="space").pack(side="left", padx=(8,0))
649
+ self._hf_user_lbl = tk.Label(s, text="", bg=CARD_BG, fg=FG2, font=("Segoe UI",8), anchor="w")
650
+ self._hf_user_lbl.pack(fill="x", pady=(3,0))
651
 
652
  def _auto_install_hf(self):
653
  if self._btn_install: self._btn_install.configure(text="⟳ Instalando...", state="disabled", bg=FG2)
 
658
  r = subprocess.run(cmd, capture_output=True, text=True, timeout=300)
659
  if r.returncode == 0:
660
  self.after(0, lambda: self._log("βœ“ Instalado β€” cierra y abre de nuevo"))
661
+ if self._btn_install:
662
+ self.after(0, lambda: self._btn_install.configure(text="βœ“ INSTALADO β€” reinicia", bg=GREEN, state="disabled"))
663
  self.after(0, lambda: messagebox.showinfo("Listo", "Instalado. Cierra y abre de nuevo."))
664
  else:
665
  self.after(0, lambda: self._log(f"βœ— {r.stderr[-400:]}"))
666
+ if self._btn_install:
667
+ self.after(0, lambda: self._btn_install.configure(text="βœ— FallΓ³", bg=RED))
668
  except Exception as e:
669
  self.after(0, lambda: self._log(f"βœ— {e}"))
670
+ if self._btn_install:
671
+ self.after(0, lambda: self._btn_install.configure(text="βœ— Error", bg=RED))
672
  threading.Thread(target=_go, daemon=True).start()
673
 
674
  def _test_hf_connection(self):
675
  token = self._hf_token.get().strip()
676
  if not token: self._log("βœ— Ingresa token"); return
677
  if not HF_OK: self._log(f"βœ— {HF_ERROR.split(chr(10))[0]}"); return
678
+ self._hf_status_lbl.configure(text="⟳ Conectando...", fg=YELLOW)
679
+ self._btn_test_hf.configure(state="disabled")
680
  def _go():
681
  try:
682
  api = HfApi()
683
  try:
684
  ui = api.whoami(token=token)
685
+ if hasattr(ui, 'name'): username = ui.name; fullname = getattr(ui, 'fullname', username)
686
+ elif isinstance(ui, dict): username = ui.get('name','?'); fullname = ui.get('fullname', username)
687
+ else: username = str(ui); fullname = username
688
  except Exception as e:
689
  self.after(0, lambda: self._hf_status_lbl.configure(text=f"βœ— Token invΓ‘lido: {e}", fg=RED))
690
+ self.after(0, lambda: self._btn_test_hf.configure(state="normal"))
691
+ return
692
  self.after(0, lambda: self._hf_status_lbl.configure(text=f"βœ“ {fullname}", fg=GREEN))
693
  self.after(0, lambda: self._hf_user_lbl.configure(text=f"@{username}", fg=FG2))
694
  self.after(0, lambda: self._log(f"βœ“ HF: {fullname} (@{username})"))
 
702
  def _load_repos(self):
703
  token = self._hf_token.get().strip()
704
  if not token or not HF_OK: return
705
+ self._log("⟳ Cargando repos...")
706
+ self._hf_user_lbl.configure(text="⟳ Cargando...", fg=YELLOW)
707
  def _go():
708
  try:
709
  api = HfApi()
 
748
  tk.Entry(s, textvariable=self._tmdb_key, bg=BG, fg=FG, insertbackground=FG, relief="flat", show="*").pack(fill="x", ipady=3, pady=(0,4))
749
  fs = tk.Frame(s, bg=CARD_BG); fs.pack(fill="x", pady=(0,4))
750
  self._tmdb_type = tk.StringVar(value="serie")
751
+ ttk.Radiobutton(fs, text="Serie", variable=self._tmdb_type, value="serie", command=self._tmdb_clear).pack(side="left")
752
  ttk.Radiobutton(fs, text="PelΓ­cula", variable=self._tmdb_type, value="pelicula", command=self._tmdb_clear).pack(side="left", padx=(5,10))
753
  self._tmdb_query = tk.StringVar()
754
  tk.Entry(fs, textvariable=self._tmdb_query, bg=BG, fg=FG, insertbackground=FG, relief="flat").pack(side="left", fill="x", expand=True, ipady=3)
 
767
  self._tmdb_ep_cb.set(""); self._tmdb_ep_cb.configure(state="disabled")
768
 
769
  def _search_tmdb(self):
770
+ k = self._tmdb_key.get().strip(); q = self._tmdb_query.get().strip()
771
  if not k or not q: return
772
+ t = "movie" if self._tmdb_type.get() == "pelicula" else "tv"
773
+ url = f"https://api.themoviedb.org/3/search/{t}?api_key={k}&query={urllib.parse.quote(q)}&language=es-MX"
774
  def _go():
775
  try:
776
+ data = fetch_tmdb(url); res = []; self._tmdb_id_map = {}
777
+ for r in data.get('results', [])[:15]:
778
+ title = r.get('title') or r.get('name')
779
+ dt = r.get('release_date') or r.get('first_air_date') or ""
780
+ yr = dt.split('-')[0] if dt else "N/A"
781
+ lbl = f"{title} ({yr})"; res.append(lbl); self._tmdb_id_map[lbl] = r.get('id')
782
  self.after(0, lambda: self._tmdb_res_cb.configure(values=res))
783
+ if res:
784
+ self.after(0, lambda: self._tmdb_res_cb.set(res[0]))
785
+ self.after(0, self._on_tmdb_res)
786
+ except Exception as e:
787
+ self.after(0, lambda: self._log(f"βœ— TMDb: {e}"))
788
  threading.Thread(target=_go, daemon=True).start()
789
 
790
  def _on_tmdb_res(self, *a):
791
+ if self._tmdb_type.get() == "pelicula":
792
+ self._tmdb_season_cb.configure(state="disabled"); self._tmdb_ep_cb.configure(state="disabled"); return
793
+ self._tmdb_season_cb.configure(state="readonly")
794
+ tid = self._tmdb_id_map.get(self._tmdb_res_cb.get())
795
  if not tid: return
796
  def _go():
797
  try:
798
+ data = fetch_tmdb(f"https://api.themoviedb.org/3/tv/{tid}?api_key={self._tmdb_key.get().strip()}&language=es-MX")
799
+ ss = [f"T{s['season_number']}" for s in data.get('seasons', []) if s['season_number'] > 0]
800
  self.after(0, lambda: self._tmdb_season_cb.configure(values=ss))
801
+ if ss:
802
+ self.after(0, lambda: self._tmdb_season_cb.set(ss[0]))
803
+ self.after(0, self._on_tmdb_season)
804
+ except Exception as e:
805
+ self.after(0, lambda: self._log(f"βœ— TMDb: {e}"))
806
  threading.Thread(target=_go, daemon=True).start()
807
 
808
  def _on_tmdb_season(self, *a):
809
+ self._tmdb_ep_cb.configure(state="readonly")
810
+ tid = self._tmdb_id_map.get(self._tmdb_res_cb.get())
811
+ sn = self._tmdb_season_cb.get().replace("T", "")
812
  def _go():
813
  try:
814
+ data = fetch_tmdb(f"https://api.themoviedb.org/3/tv/{tid}/season/{sn}?api_key={self._tmdb_key.get().strip()}&language=es-MX")
815
+ self._tmdb_episodes = [{'num': e['episode_number'], 'name': e['name']} for e in data.get('episodes', [])]
816
+ es = [f"E{e['num']:02d}: {e['name']}" for e in self._tmdb_episodes]
817
  self.after(0, lambda: self._tmdb_ep_cb.configure(values=es))
818
  if es: self.after(0, lambda: self._tmdb_ep_cb.set(es[0]))
819
+ except Exception as e:
820
+ self.after(0, lambda: self._log(f"βœ— TMDb: {e}"))
821
  threading.Thread(target=_go, daemon=True).start()
822
 
823
  def _build_hls_config(self, p):
 
825
  ft = tk.Frame(s, bg=CARD_BG); ft.pack(fill="x", pady=(0,6))
826
  tk.Label(ft, text="Tipo:", bg=CARD_BG, fg=FG2, font=FONT_MAIN).pack(side="left")
827
  self._hls_pl_type = tk.StringVar(value="vod")
828
+ for v, l in [("vod","VOD"),("event","Event"),("","Live")]:
829
+ ttk.Radiobutton(ft, text=l, variable=self._hls_pl_type, value=v).pack(side="left", padx=(0,8))
830
  fs = tk.Frame(s, bg=CARD_BG); fs.pack(fill="x")
831
  tk.Label(fs, text="Segmento:", bg=CARD_BG, fg=FG2, font=FONT_MAIN).pack(side="left")
832
  self._hls_seg = tk.StringVar(value="10")
833
+ ttk.Combobox(fs, textvariable=self._hls_seg, values=["4","6","8","10","15","20","30"],
834
+ width=5, state="readonly").pack(side="left", padx=(5,0))
835
  tk.Label(fs, text="s", bg=CARD_BG, fg=FG2, font=FONT_MAIN).pack(side="left", padx=(3,0))
836
 
837
  def _build_quality_section(self, p):
838
  s = self._sec(p, "Calidades Video (sin audio)")
839
+
840
+ # ── Presets ──────────────────────────────────────────────
841
  fp = tk.Frame(s, bg=CARD_BG); fp.pack(fill="x", pady=(0,5))
842
  tk.Label(fp, text="Presets:", bg=CARD_BG, fg=FG2, font=FONT_MAIN).pack(side="left")
843
+ presets = [
844
+ ("4K+Multi", ["4k","1080p","720p","480p"]),
845
+ ("Multi", ["1080p","720p","480p"]),
846
+ ("Solo 4K", ["4k"]),
847
+ ("Solo 1080", ["1080p"]),
848
+ ("Solo 720", ["720p"]),
849
+ ("Solo 480", ["480p"]),
850
+ ("Copy", ["copy"]),
851
+ ]
852
+ for lbl, qs in presets:
853
+ tk.Button(fp, text=lbl, bg=BG, fg=ACCENT, bd=0, padx=5, pady=1,
854
+ font=("Segoe UI",8), cursor="hand2",
855
+ command=lambda q=qs: self._set_qualities(q)).pack(side="left", padx=(0,2))
856
+
857
+ # ── Checkboxes con descripciΓ³n del modo ──────────────────
858
+ self._q_4k = tk.BooleanVar(value=False)
859
+ self._q_1080 = tk.BooleanVar(value=True)
860
+ self._q_720 = tk.BooleanVar(value=True)
861
+ self._q_480 = tk.BooleanVar(value=True)
862
+ self._q_copy = tk.BooleanVar(value=False)
863
+
864
+ rows = [
865
+ (self._q_4k, "4K", "H264 CRF18 fast 20Mbps (re-encodea)"),
866
+ (self._q_1080, "1080p", "COPY β˜… nunca se omite, nunca re-encodea"),
867
+ (self._q_720, "720p", "H264 CRF23 fast 3Mbps (re-encodea rΓ‘pido)"),
868
+ (self._q_480, "480p", "H264 CRF26 fast 1.5Mbps (re-encodea rΓ‘pido)"),
869
+ (self._q_copy, "Copy", "Copia exacta del stream original"),
870
+ ]
871
+ for var, name, desc in rows:
872
+ row = tk.Frame(s, bg=CARD_BG); row.pack(fill="x", pady=1)
873
  ttk.Checkbutton(row, text=name, variable=var, command=self._update_preview).pack(side="left")
874
+ color = CYAN if "COPY" in desc else FG2
875
+ tk.Label(row, text=desc, bg=CARD_BG, fg=color, font=("Segoe UI",8)).pack(side="left", padx=(8,0))
876
 
877
  def _set_qualities(self, qs):
878
+ self._q_4k.set("4k" in qs)
879
+ self._q_1080.set("1080p" in qs)
880
+ self._q_720.set("720p" in qs)
881
+ self._q_480.set("480p" in qs)
882
+ self._q_copy.set("copy" in qs)
883
+ self._update_preview()
884
 
885
  def _get_qualities(self):
886
  qs = []
887
+ if self._q_4k.get(): qs.append("4k")
888
  if self._q_1080.get(): qs.append("1080p")
889
+ if self._q_720.get(): qs.append("720p")
890
+ if self._q_480.get(): qs.append("480p")
891
  if self._q_copy.get(): qs.append("copy")
892
  return qs
893
 
 
896
  tk.Label(s, text="Codec: MP3 320kbps (siempre)", bg=CARD_BG, fg=CYAN, font=("Segoe UI",9,"bold")).pack(anchor="w", pady=(0,3))
897
  self._audio_mode = tk.StringVar(value="all")
898
  fa = tk.Frame(s, bg=CARD_BG); fa.pack(fill="x")
899
+ ttk.Radiobutton(fa, text="Todos", variable=self._audio_mode, value="all", command=self._update_preview).pack(side="left")
900
  ttk.Radiobutton(fa, text="Solo espaΓ±ol β˜…", variable=self._audio_mode, value="spanish", command=self._update_preview).pack(side="left", padx=(10,0))
901
  tk.Label(s, text="⚠ Video .ts SIN audio", bg=CARD_BG, fg=YELLOW, font=("Segoe UI",8)).pack(anchor="w", pady=(3,0))
902
 
 
905
  tk.Label(s, text="Nombre manual:", bg=CARD_BG, fg=FG2, font=FONT_MAIN).pack(anchor="w")
906
  self._manual_name = tk.StringVar()
907
  tk.Entry(s, textvariable=self._manual_name, bg=BG, fg=FG, insertbackground=FG, relief="flat").pack(fill="x", ipady=4, pady=(0,5))
908
+ self._ext_sub = tk.BooleanVar(value=True)
909
+ self._del_local = tk.BooleanVar(value=True)
910
  fo = tk.Frame(s, bg=CARD_BG); fo.pack(fill="x")
911
+ ttk.Checkbutton(fo, text="Subs .vtt", variable=self._ext_sub, command=self._update_preview).pack(side="left")
912
  ttk.Checkbutton(fo, text="Borrar local", variable=self._del_local).pack(side="left", padx=10)
913
 
914
  def _build_tracks(self, p):
915
+ s = self._sec(p, "Pistas Info")
916
+ f = tk.Frame(s, bg=CARD_BG); f.pack(fill="x")
917
  tk.Label(f, text="Aud:", bg=CARD_BG, fg=FG2, font=FONT_MAIN).pack(side="left")
918
+ self._aud_cb = ttk.Combobox(f, state="readonly", font=FONT_MAIN, width=20)
919
+ self._aud_cb.pack(side="left", fill="x", expand=True, padx=(5,10))
920
  tk.Label(f, text="Sub:", bg=CARD_BG, fg=FG2, font=FONT_MAIN).pack(side="left")
921
+ self._sub_cb = ttk.Combobox(f, state="readonly", font=FONT_MAIN, width=20)
922
+ self._sub_cb.pack(side="left", fill="x", expand=True, padx=(5,0))
923
 
924
  def _build_source(self, p):
925
  s = self._sec(p, "Fuente")
926
  tabs = tk.Frame(s, bg=CARD_BG); tabs.pack(fill="x", pady=(0,6))
927
  self._src_mode = tk.StringVar(value="url")
928
+ self._btn_url = tk.Button(tabs, text="🌐 URLs", bg=ACCENT, fg="white", bd=0, padx=12, pady=5, font=FONT_MAIN, command=lambda: self._switch_src("url"))
929
+ self._btn_file = tk.Button(tabs, text="πŸ“ Archivo", bg=BG, fg=FG2, bd=0, padx=12, pady=5, font=FONT_MAIN, command=lambda: self._switch_src("file"))
930
+ self._btn_url.pack(side="left"); self._btn_file.pack(side="left", padx=5)
931
+
932
  self._file_frame = tk.Frame(s, bg=CARD_BG); self._file_var = tk.StringVar()
933
+ tk.Entry(self._file_frame, textvariable=self._file_var, bg=BG, fg=FG, insertbackground=FG,
934
+ font=FONT_MAIN, relief="flat").pack(side="left", fill="x", expand=True, ipady=4, padx=(0,5))
935
+ tk.Button(self._file_frame, text="Buscar", bg=BG, fg=ACCENT, bd=0, padx=8, pady=4,
936
+ font=FONT_MAIN, command=self._browse).pack(side="right")
937
+
938
+ self._url_frame = tk.Frame(s, bg=CARD_BG)
939
+ self._url_text = tk.Text(self._url_frame, bg=BG, fg=FG, insertbackground=FG,
940
+ font=FONT_MAIN, relief="flat", height=4)
941
+ sb = ttk.Scrollbar(self._url_frame, command=self._url_text.yview)
942
+ self._url_text.configure(yscrollcommand=sb.set)
943
+ self._url_text.pack(side="left", fill="both", expand=True, pady=2)
944
+ sb.pack(side="right", fill="y", pady=2)
945
+
946
+ self._lbl_info = tk.Label(s, text="Sin anΓ‘lisis", bg=BG, fg=FG2, font=FONT_MAIN, anchor="w", padx=10, pady=5)
947
+ self._lbl_info.pack(fill="x", pady=(6,0))
948
+ self._lbl_struct = tk.Label(s, text="", bg="#0b1120", fg=VIOLET, font=FONT_MONO,
949
+ anchor="nw", padx=10, pady=6, justify="left", relief="flat")
950
+ self._lbl_struct.pack(fill="x", pady=(2,0))
951
+
952
  btns = tk.Frame(s, bg=CARD_BG); btns.pack(fill="x", pady=(10,0))
953
+ tk.Button(btns, text="πŸ” ANALIZAR", bg=BG, fg=ACCENT, bd=0, padx=12, pady=8,
954
+ font=FONT_BOLD, cursor="hand2", command=self._do_analyze).pack(side="left")
955
+ self._btn_proc = tk.Button(btns, text="⬑ PROCESAR COLA HLS", bg=VIOLET, fg="white",
956
+ bd=0, padx=12, pady=8, font=FONT_BOLD, cursor="hand2",
957
+ command=self._do_process)
958
  self._btn_proc.pack(side="right", fill="x", expand=True, padx=(10,0))
959
  self._switch_src("url"); self._update_preview()
960
 
961
  def _build_log(self, p):
962
  s = self._sec(p, "Progreso")
963
+ self._lbl_prog = tk.Label(s, text="Esperando...", bg=CARD_BG, fg=FG2, anchor="w")
964
+ self._lbl_prog.pack(fill="x")
965
+ self._pbar = ttk.Progressbar(s, mode="determinate", style="Horizontal.TProgressbar")
966
+ self._pbar.pack(fill="x", pady=(5,6))
967
  lf = tk.Frame(s, bg=BG, padx=1, pady=1); lf.pack(fill="both", expand=True)
968
+ self._log_txt = tk.Text(lf, bg=BG, fg="#0ea5e9", font=("Consolas",9), bd=0,
969
+ relief="flat", state="disabled", wrap="word")
970
+ sb = ttk.Scrollbar(lf, command=self._log_txt.yview)
971
+ self._log_txt.configure(yscrollcommand=sb.set)
972
  sb.pack(side="right", fill="y"); self._log_txt.pack(fill="both", expand=True)
973
+ for tag, color in [("green","#22c55e"),("red","#ef4444"),("yellow","#f59e0b"),
974
+ ("violet","#a78bfa"),("cyan","#22d3ee"),("dim","#64748b")]:
975
+ self._log_txt.tag_configure(tag, foreground=color)
976
 
977
  def _switch_src(self, mode):
978
  self._src_mode.set(mode)
979
+ if mode == "file":
980
+ self._file_frame.pack(fill="x"); self._url_frame.pack_forget()
981
+ self._btn_file.configure(bg=ACCENT, fg="white"); self._btn_url.configure(bg=BG, fg=FG2)
982
+ else:
983
+ self._url_frame.pack(fill="x"); self._file_frame.pack_forget()
984
+ self._btn_url.configure(bg=ACCENT, fg="white"); self._btn_file.configure(bg=BG, fg=FG2)
985
 
986
  def _browse(self):
987
  p = filedialog.askopenfilename(filetypes=[("Video","*.mp4 *.mkv *.avi *.mov *.ts *.m3u8"),("Todos","*.*")])
988
  if p: self._file_var.set(p)
989
 
990
  def _get_sources(self):
991
+ if self._src_mode.get() == "file":
992
+ p = self._file_var.get().strip()
993
+ return ([p] if p else []), False
994
  return [ln.strip() for ln in self._url_text.get("1.0","end").split("\n") if ln.strip()], True
995
 
996
  def _log(self, msg):
997
+ self._log_txt.configure(state="normal")
998
+ tag = ""
999
+ if "βœ“" in msg: tag = "green"
1000
+ elif "βœ—" in msg: tag = "red"
1001
+ elif "⚠" in msg: tag = "yellow"
1002
+ elif "⬑" in msg or "HLS" in msg or "master" in msg: tag = "violet"
1003
+ elif "Audio" in msg or "MP3" in msg: tag = "cyan"
1004
+ elif "β„Ή" in msg: tag = "dim"
1005
+ self._log_txt.insert("end", msg+"\n", tag)
1006
+ self._log_txt.see("end"); self._log_txt.configure(state="disabled")
1007
 
1008
  def _set_progress(self, pct, label=""):
1009
+ self._pbar["value"] = pct; self._lbl_prog.configure(text=label); self.update_idletasks()
1010
 
1011
  def _update_preview(self, *a):
1012
+ qs = self._get_qualities(); am = self._audio_mode.get(); es = self._ext_sub.get()
1013
+ if not qs: qs = ["1080p"]
1014
+ lines = [f"videos/{to_leet(self._manual_name.get() or 'Nombre')}/", "β”œβ”€β”€ master.m3u8"]
1015
+ for q in qs:
1016
+ enc = "copy" if QUALITY_DEFS[q].get("force_copy") else f"fast"
1017
+ lines += [f"β”œβ”€β”€ {q}/ [{enc}]",
1018
+ f"β”‚ β”œβ”€β”€ playlist.m3u8",
1019
+ f"β”‚ └── seg_XXXX.ts (solo video)"]
1020
  lines.append("β”œβ”€β”€ audio/")
1021
+ if am == "spanish":
1022
+ lines += ["β”‚ β”œβ”€β”€ spa.m3u8 β˜…", "β”‚ └── spa_XXXX.ts (MP3)"]
1023
+ else:
1024
+ lines += ["β”‚ β”œβ”€β”€ spa.m3u8 β˜…", "β”‚ β”œβ”€β”€ eng.m3u8", "β”‚ └── ..._XXXX.ts (MP3)"]
1025
+ if es:
1026
+ lines += ["└── subs/", " β”œβ”€β”€ spa.vtt β˜…", " └── eng.vtt"]
1027
+ else:
1028
+ lines.append("└── (sin subs)")
1029
  self._lbl_struct.configure(text="\n".join(lines))
1030
 
1031
  def _do_analyze(self):
1032
  sources, is_url = self._get_sources()
1033
  if not sources: messagebox.showwarning("Error","Selecciona fuente."); return
1034
  def _go():
1035
+ self._log("⟳ Analizando...")
1036
+ info = probe(sources[0])
1037
+ ac = [f"[{t['idx']}] {t['lang']} Β· {t['codec']} Β· {t['ch']}ch" for t in info["audio"]]
1038
+ sc = [f"[{t['idx']}] {t['lang']} Β· {t['codec']}" for t in info["subs"]]
1039
  self.after(0, lambda: self._aud_cb.configure(values=ac))
1040
  self.after(0, lambda: self._sub_cb.configure(values=sc))
1041
  if ac: self.after(0, lambda: self._aud_cb.set(ac[0]))
1042
  if sc: self.after(0, lambda: self._sub_cb.set(sc[0]))
1043
+ v = info["video"]; dur = info["duration"]; sz = info["size"]/(1024*1024) if info["size"] else 0
1044
+ spa = sum(1 for a in info["audio"] if is_spanish(a["lang"]))
1045
+ txt = f"βœ“ {v['codec']} {v['width']}x{v['height']} | {fmt_dur(dur)} | {sz:.0f}MB | {len(ac)} aud ({spa} spa) | {len(sc)} sub"
1046
+ if len(sources) > 1: txt = f"βœ“ {len(sources)} elementos | Bulk"
1047
+ self.after(0, lambda: self._lbl_info.configure(text=txt, fg=GREEN))
1048
+ self._log(txt)
1049
  threading.Thread(target=_go, daemon=True).start()
1050
 
1051
  def _do_process(self):
1052
+ tok = self._hf_token.get().strip(); rep = self._repo_cb.get().strip()
1053
+ sources, is_url = self._get_sources()
1054
+ if not tok: messagebox.showwarning("Error","Ingresa Token."); return
1055
+ if not rep: messagebox.showwarning("Error","Ingresa repositorio."); return
1056
  if "/" not in rep: messagebox.showwarning("Error","Formato: usuario/nombre"); return
1057
  if not sources: messagebox.showwarning("Error","Selecciona fuente."); return
1058
+ qs = self._get_qualities()
1059
  if not qs: messagebox.showwarning("Error","Selecciona calidad."); return
1060
  if not HF_OK:
1061
  if not messagebox.askyesno("Sin HF", f"{HF_ERROR.split(chr(10))[0]}\n\nΒΏGuardar localmente?"): return
1062
+ self._queue = sources.copy(); self._total_queue = len(self._queue); self._current_idx = 0
1063
  self._btn_proc.configure(state="disabled", bg=FG2)
1064
  self._log_txt.configure(state="normal"); self._log_txt.delete("1.0","end"); self._log_txt.configure(state="disabled")
1065
  self._log("⬑ Iniciando cola..."); self._process_next()
1066
 
1067
  def _process_next(self):
1068
  if not self._queue:
1069
+ self._btn_proc.configure(state="normal", bg=VIOLET)
1070
+ self._lbl_status.configure(text="● Completado βœ“", fg=GREEN)
1071
+ self._set_progress(100, "βœ“ Todos completados")
1072
+ return self._log("\n⬑⬑ COLA FINALIZADA ⬑⬑")
1073
+ src = self._queue.pop(0); self._current_idx += 1
1074
  self._lbl_status.configure(text=f"● [{self._current_idx}/{self._total_queue}]", fg=YELLOW)
1075
  self._log(f"\nβ–Ά ═══ [{self._current_idx}/{self._total_queue}] ═══")
1076
  folder_name, file_name = "Bulk_Upload", f"Video_{self._current_idx}"
1077
  if self._use_tmdb.get() and self._tmdb_res_cb.get():
1078
+ bl = self._tmdb_res_cb.get().split(" (")[0]
1079
+ if self._tmdb_type.get() == "pelicula":
1080
+ folder_name = to_leet(bl)
1081
+ file_name = to_leet(bl) if self._total_queue <= 1 else to_leet(f"{bl}_P{self._current_idx}")
1082
  else:
1083
+ sn = self._tmdb_season_cb.get().replace("T","") if self._tmdb_season_cb.get() else "1"
1084
+ folder_name = to_leet(f"{bl}_S{int(sn):02d}")
1085
+ ei = self._tmdb_ep_cb.current() if self._tmdb_ep_cb.current() >= 0 else 0
1086
+ tgt = ei + self._current_idx - 1
1087
+ if tgt < len(self._tmdb_episodes):
1088
+ ep = self._tmdb_episodes[tgt]
1089
+ file_name = to_leet(f"{bl}_S{int(sn):02d}E{ep['num']:02d}_{ep['name']}")
1090
+ else:
1091
+ file_name = to_leet(f"{bl}_S{int(sn):02d}E{(tgt+1):02d}")
1092
  else:
1093
+ mn = self._manual_name.get().strip()
1094
+ if mn:
1095
+ folder_name = to_leet(mn)
1096
+ file_name = to_leet(mn) if self._total_queue <= 1 else to_leet(f"{mn}_{self._current_idx}")
1097
  else:
1098
+ _, iu = self._get_sources()
1099
+ if not iu:
1100
+ base = Path(src).stem; folder_name = to_leet(base); file_name = to_leet(base)
1101
+ self._log(f" πŸ“‚ videos/{folder_name}/")
1102
+ _, iuc = self._get_sources()
1103
+ threading.Thread(
1104
+ target=process_video,
1105
  args=(self._hf_token.get().strip(), self._repo_cb.get().strip(), src, iuc,
1106
  self._get_qualities(), self._audio_mode.get(), self._ext_sub.get(),
1107
  self._del_local.get(), folder_name, file_name,
 
1109
  lambda m: self.after(0, self._log, m),
1110
  lambda p, l: self.after(0, self._set_progress, p, l),
1111
  lambda ok: self.after(0, self._process_next)),
1112
+ daemon=True,
1113
+ ).start()
1114
 
1115
 
1116
  if __name__ == "__main__":