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

Upload hugv3.py

Browse files
Files changed (1) hide show
  1. hugv3.py +930 -0
hugv3.py ADDED
@@ -0,0 +1,930 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ import ctypes
4
+ import subprocess
5
+ import threading
6
+ import shutil
7
+ import re
8
+ import json
9
+ import uuid
10
+ import urllib.request
11
+ import urllib.parse
12
+ import tkinter as tk
13
+ from tkinter import ttk, filedialog, messagebox
14
+ from pathlib import Path
15
+
16
+ def is_admin():
17
+ try:
18
+ return ctypes.windll.shell32.IsUserAnAdmin()
19
+ except:
20
+ return False
21
+
22
+ def elevate():
23
+ if not is_admin():
24
+ ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, " ".join(sys.argv), None, 1)
25
+ sys.exit()
26
+
27
+ # ═══════════════════════════════════════════════════════════════════
28
+ # DETECCIΓ“N HF
29
+ # ═══════════════════════════════════════════════════════════════════
30
+ HF_OK = False
31
+ 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 = (
46
+ f"No se encuentra 'huggingface_hub'\n"
47
+ f"Python: {HF_PYTHON_PATH} v{HF_PYTHON_VERSION}\n"
48
+ f'SoluciΓ³n: "{HF_PYTHON_PATH}" -m pip install huggingface_hub'
49
+ )
50
+ except Exception as e:
51
+ HF_ERROR = f"Error: {type(e).__name__}: {e}\nPython: {HF_PYTHON_PATH}"
52
+
53
+
54
+ BG = "#0f172a"
55
+ CARD_BG = "#1e293b"
56
+ ACCENT = "#3b82f6"
57
+ ACCENT_H = "#2563eb"
58
+ GREEN = "#22c55e"
59
+ RED = "#ef4444"
60
+ YELLOW = "#f59e0b"
61
+ VIOLET = "#a78bfa"
62
+ ORANGE = "#fb923c"
63
+ CYAN = "#22d3ee"
64
+ FG = "#f1f5f9"
65
+ FG2 = "#94a3b8"
66
+ BORDER = "#334155"
67
+ FONT_MAIN = ("Segoe UI", 10)
68
+ FONT_BOLD = ("Segoe UI", 10, "bold")
69
+ FONT_TITLE= ("Segoe UI", 14, "bold")
70
+ 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):
82
+ if not s: return "video"
83
+ return re.sub(r'[<>:"/\\|?*\x00-\x1f]', '_', s).strip()[:maxlen]
84
+
85
+ def to_leet(text):
86
+ if not text: return "video"
87
+ rep = {'a':'4','A':'4','i':'1','I':'1','t':'7','T':'7','o':'0','O':'0','e':'3','E':'3'}
88
+ return safe_name("".join(rep.get(c, c) for c in text))
89
+
90
+ def fmt_dur(secs):
91
+ s = int(secs)
92
+ return f"{s//3600:02d}:{(s%3600)//60:02d}:{s%60:02d}"
93
+
94
+ def fmt_size_path(path):
95
+ try:
96
+ b = os.path.getsize(path)
97
+ for u in ['B','KB','MB','GB']:
98
+ if b < 1024: return f"{b:.1f} {u}"
99
+ b /= 1024
100
+ return f"{b:.1f} TB"
101
+ except: return "?"
102
+
103
+ def fetch_tmdb(url):
104
+ req = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0'})
105
+ with urllib.request.urlopen(req) as resp:
106
+ return json.loads(resp.read().decode())
107
+
108
+ def is_spanish(lang):
109
+ return lang.lower().strip() in SPANISH_CODES
110
+
111
+ def probe(source):
112
+ info = {"audio":[], "subs":[], "video":{"width":0,"height":0,"codec":"?","bitrate":0}, "duration":0.0, "title":"", "size":0}
113
+ try:
114
+ r = subprocess.run(["ffprobe","-v","quiet","-print_format","json","-show_format","-show_streams", source],
115
+ capture_output=True, text=True, timeout=90)
116
+ if r.returncode != 0: return info
117
+ data = json.loads(r.stdout)
118
+ tags = data.get("format",{}).get("tags",{})
119
+ info["title"] = (tags.get("title") or tags.get("TITLE") or "").strip()
120
+ info["duration"] = float(data.get("format",{}).get("duration",0) or 0)
121
+ info["size"] = int(data.get("format",{}).get("size",0) or 0)
122
+ ai = si = 0
123
+ for s in data.get("streams",[]):
124
+ t = s.get("tags",{}); ct = s.get("codec_type","")
125
+ if ct == "video":
126
+ info["video"] = {"width":s.get("width",0),"height":s.get("height",0),
127
+ "codec":s.get("codec_name","?"),"bitrate":int(s.get("bit_rate",0) or 0)}
128
+ elif ct == "audio":
129
+ info["audio"].append({"idx":ai,"codec":s.get("codec_name","?"),
130
+ "lang":t.get("language","und"),"ch":s.get("channels",2),"title":t.get("title","")})
131
+ ai += 1
132
+ elif ct == "subtitle":
133
+ info["subs"].append({"idx":si,"codec":s.get("codec_name","?"),
134
+ "lang":t.get("language","und"),"title":t.get("title",""),
135
+ "forced":s.get("disposition",{}).get("forced",0)==1})
136
+ si += 1
137
+ except: pass
138
+ return info
139
+
140
+ NET_ARGS = ["-user_agent","Mozilla/5.0","-headers","Referer: https://google.com\r\n",
141
+ "-timeout","180000000","-reconnect","1","-reconnect_streamed","1",
142
+ "-reconnect_at_eof","1","-reconnect_delay_max","30","-rw_timeout","180000000","-multiple_requests","1"]
143
+
144
+ def run_ffmpeg(cmd, total, log_cb, progress_cb, label):
145
+ try:
146
+ proc = subprocess.Popen(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, universal_newlines=True, bufsize=1)
147
+ pat = re.compile(r"time=(\d+):(\d+):(\d+)\.(\d+)")
148
+ for line in proc.stderr:
149
+ m = pat.search(line)
150
+ if m:
151
+ h,mi,s,cs = map(int, m.groups())
152
+ cur = h*3600+mi*60+s+cs/100
153
+ pct = min(99, int(cur/max(total,1)*100))
154
+ progress_cb(pct, f"{label}: {pct}% [{fmt_dur(cur)}/{fmt_dur(total)}]")
155
+ proc.wait()
156
+ return proc.returncode == 0
157
+ except Exception as e:
158
+ log_cb(f" βœ— ffmpeg: {e}")
159
+ return False
160
+
161
+ def generate_master_m3u8(qualities_info, audio_tracks, subs_list, pl_type):
162
+ lines = ["#EXTM3U"]
163
+ if pl_type: lines.append(f"#EXT-X-PLAYLIST-TYPE:{pl_type.upper()}")
164
+ has_audio = len(audio_tracks) > 0; has_subs = len(subs_list) > 0
165
+ if has_audio:
166
+ for aud in audio_tracks:
167
+ d = "YES" if aud.get("default") else "NO"
168
+ lines.append(f'#EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID="audio",NAME="{aud["name"]}",DEFAULT={d},AUTOSELECT=YES,LANGUAGE="{aud["lang"]}",URI="{aud["uri"]}"')
169
+ for q in qualities_info:
170
+ attrs = [f'BANDWIDTH={q["bandwidth"]}']
171
+ if q.get("resolution"): attrs.append(f'RESOLUTION={q["resolution"]}')
172
+ if has_audio: attrs.append('AUDIO="audio"')
173
+ if has_subs: attrs.append('SUBTITLES="subs"')
174
+ lines.append(f'#EXT-X-STREAM-INF:{",".join(attrs)}')
175
+ lines.append(q["uri"])
176
+ if has_subs:
177
+ for sub in subs_list:
178
+ d = "YES" if sub.get("default") else "NO"
179
+ lines.append(f'#EXT-X-MEDIA:TYPE=SUBTITLES,GROUP-ID="subs",NAME="{sub["name"]}",DEFAULT={d},AUTOSELECT=YES,LANGUAGE="{sub["lang"]}",URI="{sub["uri"]}"')
180
+ lines.append("")
181
+ return "\n".join(lines)
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(
233
+ folder_path=local_folder,
234
+ path_in_repo=path_in_repo,
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")
251
+ return True, total, 0
252
+ except Exception as e2:
253
+ if intento < 2: continue
254
+ log_cb(f" ⚠ upload_folder no soportado, usando archivo por archivo con delays...")
255
+ return upload_one_by_one_safe(token, repo_id, local_folder, path_in_repo, log_cb, progress_cb, pct_start, pct_end)
256
+
257
+ except Exception as e:
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):
273
+ log_cb(f" ⏳ {remaining}s restantes...")
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)
281
+
282
+ return False, 0, total
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()
293
+ repo_type = "model"
294
+
295
+ all_files = sorted([f for f in Path(local_folder).rglob("*") if f.is_file()])
296
+ total = len(all_files)
297
+ uploaded = 0; failed = 0
298
+
299
+ log_cb(f" ⚠ Modo seguro: 1 archivo cada 3s ({total} archivos, ~{total*3//60}min)")
300
+
301
+ for i, f in enumerate(all_files):
302
+ rel = f.relative_to(local_folder)
303
+ rpath = f"{path_in_repo}/{rel}".replace("\\", "/")
304
+
305
+ pct = pct_start + int((i / max(total, 1)) * (pct_end - pct_start))
306
+ progress_cb(min(pct_end, pct), f"⬆ {i+1}/{total}: {rel}")
307
+
308
+ for intento in range(3):
309
+ try:
310
+ api.upload_file(path_or_fileobj=str(f), path_in_repo=rpath,
311
+ repo_id=repo_id, repo_type=repo_type, token=token)
312
+ uploaded += 1
313
+ break
314
+ except Exception as e:
315
+ err = str(e)
316
+ if "rate limit" in err.lower() or "429" in err:
317
+ wait = 130
318
+ m = re.search(r'retry after (\d+) seconds', err, re.IGNORECASE)
319
+ if m: wait = int(m.group(1)) + 10
320
+ log_cb(f" ⏳ Rate limit, esperando {wait}s...")
321
+ time.sleep(wait)
322
+ continue
323
+ if intento < 2:
324
+ time.sleep(5)
325
+ continue
326
+ log_cb(f" βœ— {rel}: {err[:100]}")
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
+
334
+ log_cb(f" βœ“ Subida: {uploaded} OK, {failed} fallidos")
335
+ return failed == 0, uploaded, failed
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,
342
+ hls_segment_time, hls_playlist_type,
343
+ log_cb, progress_cb, done_cb):
344
+ try:
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
+
462
+ if not HF_OK:
463
+ log_cb(f" βœ— {HF_ERROR.split(chr(10))[0]}")
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.")
478
+ else:
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
+ # ═══════════════════════════════════════════════════════════════════
495
+ class App(tk.Tk):
496
+ def __init__(self):
497
+ super().__init__()
498
+ self.title("HLS Converter Pro β†’ HuggingFace")
499
+ self.geometry("1280x940")
500
+ self.configure(bg=BG)
501
+ self.resizable(True, True)
502
+ self._queue = []; self._total_queue = 0; self._current_idx = 0
503
+ self._build()
504
+
505
+ def _build(self):
506
+ style = ttk.Style(self)
507
+ style.theme_use("clam")
508
+ for s in [".","TFrame","TLabel","Card.TLabel","Header.TLabel","TRadiobutton","TCheckbutton"]:
509
+ style.configure(s, background=BG, foreground=FG, font=FONT_MAIN, borderwidth=0)
510
+ style.configure("Card.TFrame", background=CARD_BG)
511
+ style.configure("TRadiobutton", background=CARD_BG)
512
+ style.configure("TCheckbutton", background=CARD_BG)
513
+ style.configure("Header.TLabel", font=FONT_TITLE)
514
+ style.configure("Accent.TButton", background=ACCENT, foreground="white", font=FONT_BOLD, padding=10)
515
+ style.map("Accent.TButton", background=[("active", ACCENT_H)])
516
+ style.configure("Horizontal.TProgressbar", troughcolor=BG, background=ACCENT, thickness=8)
517
+
518
+ main = tk.Frame(self, bg=BG); main.pack(fill="both", expand=True, padx=20, pady=20)
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)
530
+ self._build_quality_section(left); self._build_audio_section(left)
531
+ self._build_options(left); self._build_tracks(left)
532
+ self._build_source(right); self._build_log(right)
533
+
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)
576
+ def _go():
577
+ cmd = [sys.executable, "-m", "pip", "install", "huggingface_hub"]
578
+ self.after(0, lambda: self._log(f"⟳ {' '.join(cmd)}"))
579
+ try:
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})"))
612
+ self.after(0, self._load_repos)
613
+ except Exception as e:
614
+ self.after(0, lambda: self._hf_status_lbl.configure(text=f"βœ— {e}", fg=RED))
615
+ finally:
616
+ self.after(0, lambda: self._btn_test_hf.configure(state="normal"))
617
+ threading.Thread(target=_go, daemon=True).start()
618
+
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()
626
+ try:
627
+ ui = api.whoami(token=token)
628
+ username = ui.name if hasattr(ui,'name') else (ui.get('name','') if isinstance(ui,dict) else str(ui))
629
+ except Exception as e:
630
+ self.after(0, lambda: self._hf_user_lbl.configure(text=f"βœ— {e}", fg=RED)); return
631
+ repos = []
632
+ try:
633
+ for m in api.list_models(author=username, token=token, limit=200):
634
+ repos.append(m.id if hasattr(m,'id') else str(m))
635
+ except TypeError:
636
+ try:
637
+ for m in api.list_models(author=username, token=token, limit=200):
638
+ repos.append(getattr(m,'id',getattr(m,'modelId',str(m))))
639
+ except: pass
640
+ except: pass
641
+ try:
642
+ for sp in api.list_spaces(author=username, token=token, limit=200):
643
+ repos.append(sp.id if hasattr(sp,'id') else str(sp))
644
+ except: pass
645
+ repos = sorted(set(repos))
646
+ if repos:
647
+ self.after(0, lambda: self._repo_cb.configure(values=repos))
648
+ self.after(0, lambda: self._repo_cb.set(repos[0]))
649
+ self.after(0, lambda: self._hf_user_lbl.configure(text=f"@{username} | {len(repos)} repos", fg=GREEN))
650
+ self.after(0, lambda: self._log(f"βœ“ {len(repos)} repos"))
651
+ else:
652
+ self.after(0, lambda: self._hf_user_lbl.configure(text=f"@{username} | 0 repos", fg=ORANGE))
653
+ self.after(0, lambda: self._log("⚠ Sin repos. Escribe manualmente."))
654
+ except Exception as e:
655
+ self.after(0, lambda: self._hf_user_lbl.configure(text=f"βœ— {e}", fg=RED))
656
+ threading.Thread(target=_go, daemon=True).start()
657
+
658
+ def _build_tmdb(self, p):
659
+ s = self._sec(p, "Metadatos TMDb")
660
+ self._use_tmdb = tk.BooleanVar(value=False)
661
+ ttk.Checkbutton(s, text="Usar TMDb", variable=self._use_tmdb).pack(anchor="w", pady=(0,4))
662
+ tk.Label(s, text="API Key:", bg=CARD_BG, fg=FG2, font=FONT_MAIN).pack(anchor="w")
663
+ self._tmdb_key = tk.StringVar()
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)
671
+ tk.Button(fs, text="πŸ”", bg=BG, fg=ACCENT, bd=0, command=self._search_tmdb).pack(side="right", padx=(5,0))
672
+ self._tmdb_res_cb = ttk.Combobox(s, state="readonly", font=FONT_MAIN); self._tmdb_res_cb.pack(fill="x", pady=(0,4))
673
+ self._tmdb_res_cb.bind("<<ComboboxSelected>>", self._on_tmdb_res)
674
+ fe = tk.Frame(s, bg=CARD_BG); fe.pack(fill="x")
675
+ self._tmdb_season_cb = ttk.Combobox(fe, state="disabled", font=FONT_MAIN, width=14); self._tmdb_season_cb.pack(side="left", padx=(0,5))
676
+ self._tmdb_season_cb.bind("<<ComboboxSelected>>", self._on_tmdb_season)
677
+ self._tmdb_ep_cb = ttk.Combobox(fe, state="disabled", font=FONT_MAIN); self._tmdb_ep_cb.pack(side="left", fill="x", expand=True)
678
+ self._tmdb_id_map = {}; self._tmdb_episodes = []
679
+
680
+ def _tmdb_clear(self, *a):
681
+ self._tmdb_res_cb.set(""); self._tmdb_res_cb.configure(values=[])
682
+ self._tmdb_season_cb.set(""); self._tmdb_season_cb.configure(state="disabled")
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):
727
+ s = self._sec(p, "HLS Config")
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
+
761
+ def _build_audio_section(self, p):
762
+ s = self._sec(p, "Audio (separado MP3 320k)")
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
+
770
+ def _build_options(self, p):
771
+ s = self._sec(p, "Opciones")
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,
915
+ int(self._hls_seg.get()), self._hls_pl_type.get(),
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__":
923
+ if not HF_OK:
924
+ print(f"\n{'='*60}")
925
+ print(f" ⚠ {HF_ERROR.split(chr(10))[0]}")
926
+ print(f" Python: {HF_PYTHON_VERSION} β†’ {HF_PYTHON_PATH}")
927
+ print(f' SoluciΓ³n: "{HF_PYTHON_PATH}" -m pip install huggingface_hub')
928
+ print(f"{'='*60}\n")
929
+ app = App()
930
+ app.mainloop()