CineMax commited on
Commit
8f9c0c8
Β·
verified Β·
1 Parent(s): 3fe5934

Upload 2 files

Browse files
Files changed (2) hide show
  1. hls_dash_converter.py +815 -0
  2. video_converter_pro.py +597 -0
hls_dash_converter.py ADDED
@@ -0,0 +1,815 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ HLS/DASH Converter EXTREME β€” App nativa Windows
3
+ Convierte a HLS/DASH y sube a GitHub. Sin Gradio.
4
+ Auto-elevaciΓ³n a administrador.
5
+ """
6
+ import sys
7
+ import os
8
+ import ctypes
9
+ import subprocess
10
+ import threading
11
+ import tempfile
12
+ import shutil
13
+ import re
14
+ import json
15
+ import time
16
+ import uuid
17
+ import tkinter as tk
18
+ from tkinter import ttk, filedialog, messagebox, scrolledtext
19
+ from pathlib import Path
20
+ from concurrent.futures import ThreadPoolExecutor, as_completed
21
+
22
+ # ─── AUTO-ELEVACIΓ“N ADMINISTRADOR ───────────────────────────
23
+ def is_admin():
24
+ try:
25
+ return ctypes.windll.shell32.IsUserAnAdmin()
26
+ except:
27
+ return False
28
+
29
+ def elevate():
30
+ if not is_admin():
31
+ ctypes.windll.shell32.ShellExecuteW(
32
+ None, "runas", sys.executable, " ".join(sys.argv), None, 1
33
+ )
34
+ sys.exit()
35
+
36
+ elevate()
37
+
38
+ try:
39
+ import requests
40
+ except ImportError:
41
+ requests = None
42
+
43
+ # ─── COLORES ────────────────────────────────────────────────
44
+ BG = "#080d18"
45
+ BG2 = "#0f1629"
46
+ BG3 = "#17213a"
47
+ ACCENT = "#6366f1"
48
+ ACCENT2 = "#8b5cf6"
49
+ GREEN = "#22c55e"
50
+ RED = "#ef4444"
51
+ YELLOW = "#f59e0b"
52
+ CYAN = "#22d3ee"
53
+ FG = "#e2e8f0"
54
+ FG2 = "#94a3b8"
55
+ FG3 = "#3a5070"
56
+ BORDER = "#1a2a40"
57
+ FM = ("Consolas", 10)
58
+ FB = ("Consolas", 11, "bold")
59
+ FS = ("Consolas", 9)
60
+
61
+ # ─── UTILS ──────────────────────────────────────────────────
62
+ def get_threads():
63
+ try:
64
+ return max(len(os.sched_getaffinity(0)) - 1, 1)
65
+ except:
66
+ return max((os.cpu_count() or 4) - 1, 1)
67
+
68
+ N_THREADS = get_threads()
69
+
70
+ def clean_folder(n): return re.sub(r'[<>:"/\\|?*]', '_', n).strip()[:200]
71
+ def clean_repo(n):
72
+ n = re.sub(r'[^a-zA-Z0-9_-]', '-', n)
73
+ return re.sub(r'-+', '-', n).strip('-')[:100]
74
+
75
+ def build_name(ctype, mname, sname, season, ep_start, idx):
76
+ if ctype == "PelΓ­cula":
77
+ b = mname.strip() or "Pelicula"
78
+ return clean_folder(b), clean_repo(b)
79
+ name = sname.strip() or "Serie"
80
+ try: t = int(season)
81
+ except: t = 1
82
+ try: e = int(ep_start) + idx
83
+ except: e = idx + 1
84
+ lbl = f"{name}_T{t}_Ep{e}"
85
+ return clean_folder(lbl), clean_repo(lbl)
86
+
87
+ def is_live(url):
88
+ if not url.startswith(("http://", "https://")): return False
89
+ lo = url.lower()
90
+ if any(lo.endswith(x) for x in ['.mp4','.mkv','.avi','.mov','.ts']): return False
91
+ return any(p in lo for p in ['/live/','/stream/','.m3u8','.mpd','/hls/','/dash/'])
92
+
93
+ def input_args(src):
94
+ ua = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
95
+ if src.startswith(("http://", "https://")):
96
+ if is_live(src):
97
+ return ['-user_agent', ua, '-timeout', '60000000',
98
+ '-reconnect','1','-reconnect_streamed','1',
99
+ '-fflags','+genpts+igndts','-probesize','100M','-analyzeduration','50M']
100
+ return ['-user_agent', ua, '-timeout', '120000000',
101
+ '-reconnect','1','-reconnect_streamed','1','-reconnect_delay_max','10',
102
+ '-analyzeduration','500000000','-probesize','500000000',
103
+ '-fflags','+genpts+igndts','-err_detect','ignore_err',
104
+ '-max_delay','10000000','-rw_timeout','120000000']
105
+ return ['-analyzeduration','100000000','-probesize','100000000','-fflags','+genpts+igndts']
106
+
107
+ def render_args():
108
+ return ['-threads', str(N_THREADS), '-thread_type', 'slice+frame',
109
+ '-slices', str(N_THREADS), '-max_muxing_queue_size', '9999',
110
+ '-thread_queue_size', '4096']
111
+
112
+ def detect_duration(src, iargs):
113
+ try:
114
+ cmd = ['ffprobe','-v','error'] + iargs + ['-show_entries','format=duration','-of','json','-i',src]
115
+ r = subprocess.run(cmd, capture_output=True, text=True, timeout=120)
116
+ d = json.loads(r.stdout).get('format',{}).get('duration')
117
+ return float(d) if d and d != 'N/A' else None
118
+ except: return None
119
+
120
+ def detect_audio(src, iargs):
121
+ try:
122
+ cmd = ['ffprobe','-v','error'] + iargs + [
123
+ '-select_streams','a',
124
+ '-show_entries','stream=index,codec_name:stream_tags=language,title',
125
+ '-of','json','-i',src]
126
+ r = subprocess.run(cmd, capture_output=True, text=True, timeout=120)
127
+ tracks = []
128
+ for s in json.loads(r.stdout).get('streams',[]):
129
+ tags = s.get('tags',{})
130
+ tracks.append({'index': s.get('index',0),
131
+ 'language': tags.get('language','und').lower(),
132
+ 'title': tags.get('title', f"Audio {s.get('index',0)}"),
133
+ 'codec': s.get('codec_name','unknown')})
134
+ return tracks
135
+ except: return []
136
+
137
+ def prioritize_audio(tracks):
138
+ prio = ['spa','es','spanish','espaΓ±ol','latino','lat','es-mx','es-419']
139
+ def key(t):
140
+ l, ti = t['language'], t['title'].lower()
141
+ for p in prio:
142
+ if p in l or p in ti: return 0
143
+ return 1 if l == 'und' else 2
144
+ return sorted(tracks, key=key)
145
+
146
+ def make_master_m3u8(out_dir, video_streams, audio_playlists):
147
+ c = "#EXTM3U\n#EXT-X-VERSION:7\n\n"
148
+ for a in audio_playlists:
149
+ d = "YES" if a['is_default'] else "NO"
150
+ c += f'#EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID="audio",NAME="{a["title"]}",LANGUAGE="{a["language"]}",DEFAULT={d},AUTOSELECT={d},URI="{a["file"]}"\n'
151
+ c += "\n"
152
+ for v in video_streams:
153
+ c += f'#EXT-X-STREAM-INF:BANDWIDTH={v["bandwidth"]},RESOLUTION={v["resolution"]},CODECS="{v["codecs"]}",AUDIO="audio"\n{v["file"]}\n'
154
+ (out_dir / "master.m3u8").write_text(c)
155
+
156
+ RAMDISK_PATH = None
157
+ def setup_ramdisk():
158
+ global RAMDISK_PATH
159
+ for p in [r"C:\Temp\hls_tmp", tempfile.gettempdir() + r"\hls_tmp"]:
160
+ try:
161
+ Path(p).mkdir(parents=True, exist_ok=True)
162
+ RAMDISK_PATH = Path(p)
163
+ return Path(p)
164
+ except: continue
165
+ RAMDISK_PATH = Path(tempfile.gettempdir())
166
+ return RAMDISK_PATH
167
+
168
+ RAMDISK = setup_ramdisk()
169
+
170
+ def process_audio_track(args):
171
+ track, i, total, src, out_dir, iargs = args
172
+ tmp = RAMDISK / f"aud_{os.getpid()}_{i}_{int(time.time())}"
173
+ tmp.mkdir(exist_ok=True)
174
+ try:
175
+ af = tmp / f"audio_{i}.m3u8"
176
+ sf = tmp / f"audio_{i}_%03d.ts"
177
+ wav_tmp = tmp / f"audio_{i}_raw.wav"
178
+
179
+ r_dec = subprocess.run(
180
+ ['ffmpeg','-hide_banner','-threads',str(N_THREADS)] + iargs + [
181
+ '-i',src,'-map',f"0:{track['index']}",'-vn',
182
+ '-c:a','pcm_s16le','-ar','48000','-ac','2','-f','wav',
183
+ str(wav_tmp),'-y','-loglevel','error'],
184
+ capture_output=True, text=True, timeout=7200)
185
+ if r_dec.returncode != 0 or not wav_tmp.exists():
186
+ raise Exception(f"Decode PCM fallΓ³: {r_dec.stderr[-300:]}")
187
+
188
+ r_enc = subprocess.run(
189
+ ['ffmpeg','-hide_banner','-threads',str(N_THREADS),
190
+ '-i',str(wav_tmp),'-c:a','libmp3lame','-b:a','192k',
191
+ '-ar','48000','-ac','2','-compression_level','0',
192
+ '-max_muxing_queue_size','9999','-thread_queue_size','4096',
193
+ '-hls_time','5','-hls_list_size','0',
194
+ '-hls_segment_filename',str(sf),
195
+ '-hls_flags','independent_segments+append_list+temp_file',
196
+ '-hls_playlist_type','vod','-hls_segment_type','mpegts',
197
+ str(af),'-y','-loglevel','error'],
198
+ capture_output=True, text=True, timeout=7200)
199
+ wav_tmp.unlink(missing_ok=True)
200
+
201
+ if r_enc.returncode != 0 or not af.exists():
202
+ raise Exception(f"Encode MP3 fallΓ³: {r_enc.stderr[-300:]}")
203
+
204
+ ts_files = list(tmp.glob(f"audio_{i}_*.ts"))
205
+ if not ts_files: raise Exception("Sin segmentos TS")
206
+
207
+ shutil.move(str(af), str(out_dir / f"audio_{i}.m3u8"))
208
+ for ts in ts_files: shutil.move(str(ts), str(out_dir / ts.name))
209
+
210
+ return {'success': True, 'index': i, 'track': track,
211
+ 'segments_count': len(ts_files),
212
+ 'playlist': {'file': f"audio_{i}.m3u8",
213
+ 'language': track['language'],
214
+ 'title': track['title'], 'is_default': i == 0}}
215
+ except Exception as e:
216
+ return {'success': False, 'index': i, 'error': str(e), 'track': track}
217
+ finally:
218
+ shutil.rmtree(tmp, ignore_errors=True)
219
+
220
+ def process_video_copy(src, iargs, out_dir, tmp_v, vf, sf, log_cb):
221
+ hls = ['-hls_time','5','-hls_list_size','0','-hls_segment_filename',str(sf),
222
+ '-hls_flags','independent_segments+append_list+temp_file+split_by_time',
223
+ '-hls_playlist_type','vod','-hls_segment_type','mpegts',str(vf),'-y','-loglevel','error']
224
+ base = ['ffmpeg','-hide_banner','-threads',str(N_THREADS)] + iargs + [
225
+ '-i',src,'-map','0:v:0','-an',
226
+ '-max_muxing_queue_size','9999','-avoid_negative_ts','make_zero',
227
+ '-fflags','+genpts+igndts+flush_packets+discardcorrupt',
228
+ '-err_detect','ignore_err','-copytb','1','-start_at_zero','-thread_queue_size','4096']
229
+
230
+ r1 = subprocess.run(base + ['-c:v','copy','-bsf:v','h264_mp4toannexb,dump_extra'] + hls,
231
+ capture_output=True, text=True, timeout=7200)
232
+ if r1.returncode == 0 and vf.exists() and list(tmp_v.glob("video_1080p_*.ts")):
233
+ log_cb(" βœ“ Video COPY OK (h264_mp4toannexb)"); return True
234
+
235
+ vf.unlink(missing_ok=True)
236
+ for f in tmp_v.glob("video_1080p_*.ts"): f.unlink(missing_ok=True)
237
+ log_cb(" ⚠ Copy con bsf fallΓ³, reintentando sin bsf…")
238
+
239
+ r2 = subprocess.run(base + ['-c:v','copy'] + hls,
240
+ capture_output=True, text=True, timeout=7200)
241
+ if r2.returncode == 0 and vf.exists() and list(tmp_v.glob("video_1080p_*.ts")):
242
+ log_cb(" βœ“ Video COPY OK (sin bsf)"); return True
243
+
244
+ vf.unlink(missing_ok=True)
245
+ for f in tmp_v.glob("video_1080p_*.ts"): f.unlink(missing_ok=True)
246
+ log_cb(" ⚠ Copy fallΓ³, re-encode H.264 ultrafast…")
247
+
248
+ hls2 = ['-hls_time','5','-hls_list_size','0','-hls_segment_filename',str(sf),
249
+ '-hls_flags','independent_segments+append_list+temp_file',
250
+ '-hls_playlist_type','vod','-hls_segment_type','mpegts',str(vf),'-y','-loglevel','error']
251
+ r3 = subprocess.run(
252
+ ['ffmpeg','-hide_banner','-threads',str(N_THREADS)] + iargs + [
253
+ '-i',src,'-map','0:v:0','-an','-c:v','libx264','-preset','ultrafast','-crf','23',
254
+ '-pix_fmt','yuv420p','-threads',str(N_THREADS),
255
+ '-max_muxing_queue_size','9999','-thread_queue_size','4096'] + hls2,
256
+ capture_output=True, text=True, timeout=14400)
257
+ if r3.returncode == 0 and vf.exists() and list(tmp_v.glob("video_1080p_*.ts")):
258
+ log_cb(" βœ“ Video re-encode H.264 OK"); return True
259
+ raise Exception(f"Video fallΓ³ en todos los modos: {r3.stderr[-400:]}")
260
+
261
+ def git_push_retry(gd, args, retries=3, timeout=600):
262
+ for attempt in range(retries):
263
+ try:
264
+ subprocess.run(['git','push'] + args, cwd=gd, check=True,
265
+ capture_output=True, timeout=timeout)
266
+ return True
267
+ except:
268
+ if attempt == retries-1: return False
269
+ time.sleep(3)
270
+ return False
271
+
272
+ def run_conversion(job, log_cb, progress_cb, done_cb):
273
+ """Hilo principal de conversiΓ³n"""
274
+ token = job['token']
275
+ sources = job['sources']
276
+ conv_opt = job['conv_opt']
277
+ stream_fmt = job['stream_fmt']
278
+ batch_size = job['batch_size']
279
+ delete_local = job['delete_local']
280
+ max_workers = job['max_workers']
281
+ ctype = job['ctype']
282
+ mname = job['mname']
283
+ sname = job['sname']
284
+ season = job['season']
285
+ ep_start = job['ep_start']
286
+
287
+ final_links = []
288
+ try:
289
+ log_cb(f"πŸš€ EXTREME v5.1 | Threads: {N_THREADS} | Temp: {RAMDISK}")
290
+
291
+ for idx, source in enumerate(sources):
292
+ src = source['value']
293
+ folder_name, repo_name = build_name(ctype, mname, sname, season, ep_start, idx)
294
+ log_cb(f"\nπŸ“¦ [{idx+1}/{len(sources)}] {folder_name}")
295
+ progress_cb(int(idx/len(sources)*100), f"[{idx+1}/{len(sources)}] {folder_name}")
296
+
297
+ out_dir = RAMDISK / "outputs" / folder_name
298
+ out_dir.mkdir(parents=True, exist_ok=True)
299
+
300
+ iargs = input_args(src)
301
+ dur = detect_duration(src, iargs)
302
+ if dur:
303
+ h, m, s2 = int(dur//3600), int((dur%3600)//60), int(dur%60)
304
+ log_cb(f" ⏱ Duración: {h:02d}:{m:02d}:{s2:02d}")
305
+
306
+ audio_tracks = detect_audio(src, iargs) or [{'index':0,'language':'und','title':'Audio','codec':'unk'}]
307
+ audio_tracks = prioritize_audio(audio_tracks)
308
+ log_cb(f" 🎡 {len(audio_tracks)} pista(s)")
309
+
310
+ manifest_file = ""
311
+
312
+ if stream_fmt == "HLS (M3U8)":
313
+ log_cb(f" 🎡 Procesando {len(audio_tracks)} audio(s) β†’ PCM β†’ MP3")
314
+ aargs_list = [(t, i, len(audio_tracks), src, out_dir, iargs) for i, t in enumerate(audio_tracks)]
315
+ audio_playlists = []
316
+ with ThreadPoolExecutor(max_workers=max_workers) as ex:
317
+ futures = {ex.submit(process_audio_track, a): a for a in aargs_list}
318
+ for fut in as_completed(futures):
319
+ res = fut.result()
320
+ if res['success']:
321
+ audio_playlists.append(res['playlist'])
322
+ log_cb(f" βœ“ Audio {res['index']+1}: {res['track']['title']} ({res['segments_count']} segs)")
323
+ else:
324
+ log_cb(f" βœ— Audio {res['index']+1}: {res.get('error','')[:120]}")
325
+
326
+ audio_playlists.sort(key=lambda x: int(x['file'].split('_')[1].split('.')[0]))
327
+ if not audio_playlists: raise Exception("Sin audio procesado")
328
+
329
+ video_streams = []
330
+ if "Copy" in conv_opt:
331
+ log_cb(" ⚑ Video COPY β†’ HLS")
332
+ tmp_v = RAMDISK / f"vid_{idx}"
333
+ tmp_v.mkdir(exist_ok=True)
334
+ vf = tmp_v / "video_1080p.m3u8"
335
+ sf = tmp_v / "video_1080p_%03d.ts"
336
+ process_video_copy(src, iargs, out_dir, tmp_v, vf, sf, log_cb)
337
+ final_1080 = out_dir / "video_1080p.m3u8"
338
+ shutil.move(str(vf), str(final_1080))
339
+ for ts in tmp_v.glob("video_1080p_*.ts"):
340
+ shutil.move(str(ts), str(out_dir / ts.name))
341
+ shutil.rmtree(tmp_v, ignore_errors=True)
342
+ (out_dir / "video_720p.m3u8").write_text(final_1080.read_text())
343
+ video_streams = [
344
+ {'file':'video_1080p.m3u8','resolution':'1920x1080','bandwidth':5000000,'codecs':'avc1.640028'},
345
+ {'file':'video_720p.m3u8', 'resolution':'1280x720', 'bandwidth':3000000,'codecs':'avc1.640028'},
346
+ ]
347
+ else:
348
+ rlist = ([{'label':'4K','scale':'scale=-2:2160','br':'15000k','bufsize':'30000k','res':'3840x2160'},
349
+ {'label':'1080p','scale':'scale=-2:1080','br':'5000k','bufsize':'10000k','res':'1920x1080'},
350
+ {'label':'720p','scale':'scale=-2:720','br':'2800k','bufsize':'5600k','res':'1280x720'}]
351
+ if "4K" in conv_opt else
352
+ [{'label':'1080p','scale':'scale=-2:1080','br':'5000k','bufsize':'10000k','res':'1920x1080'},
353
+ {'label':'720p','scale':'scale=-2:720','br':'2800k','bufsize':'5600k','res':'1280x720'}])
354
+ for rc in rlist:
355
+ log_cb(f" πŸ”„ Renderizando {rc['label']}…")
356
+ tmp_r = RAMDISK / f"render_{rc['label']}"
357
+ tmp_r.mkdir(exist_ok=True)
358
+ vf = tmp_r / f"video_{rc['label']}.m3u8"
359
+ sf = tmp_r / f"video_{rc['label']}_%03d.ts"
360
+ r = subprocess.run(
361
+ ['ffmpeg','-hide_banner','-threads',str(N_THREADS)] + iargs + [
362
+ '-i',src,'-map','0:v:0','-an','-c:v','libx264',
363
+ '-preset','ultrafast','-crf','23','-vf',rc['scale'],
364
+ '-b:v',rc['br'],'-maxrate',rc['br'],'-bufsize',rc['bufsize'],
365
+ '-pix_fmt','yuv420p'] + render_args() + [
366
+ '-hls_time','5','-hls_list_size','0',
367
+ '-hls_segment_filename',str(sf),
368
+ '-hls_flags','independent_segments+append_list+temp_file',
369
+ '-hls_playlist_type','vod','-hls_segment_type','mpegts',
370
+ str(vf),'-y','-loglevel','error'],
371
+ capture_output=True, text=True, timeout=14400)
372
+ if r.returncode != 0:
373
+ shutil.rmtree(tmp_r, ignore_errors=True)
374
+ log_cb(f" ⚠ Error {rc['label']}")
375
+ continue
376
+ shutil.move(str(vf), str(out_dir / f"video_{rc['label']}.m3u8"))
377
+ for ts in tmp_r.glob(f"video_{rc['label']}_*.ts"):
378
+ shutil.move(str(ts), str(out_dir / ts.name))
379
+ shutil.rmtree(tmp_r, ignore_errors=True)
380
+ video_streams.append({'file':f"video_{rc['label']}.m3u8",
381
+ 'resolution':rc['res'],
382
+ 'bandwidth':int(rc['br'].replace('k','000'))+192000,
383
+ 'codecs':'avc1.640028'})
384
+ log_cb(f" βœ“ {rc['label']} OK")
385
+
386
+ if not video_streams: raise Exception("Sin video generado")
387
+ make_master_m3u8(out_dir, video_streams, audio_playlists)
388
+ manifest_file = "master.m3u8"
389
+
390
+ elif stream_fmt == "DASH (MPD)":
391
+ log_cb(" 🎬 Generando DASH…")
392
+ tmp_d = RAMDISK / f"dash_{idx}"
393
+ tmp_d.mkdir(exist_ok=True)
394
+ cmd = ['ffmpeg','-hide_banner','-threads',str(N_THREADS)] + iargs + ['-i',src]
395
+ vc = "copy" if "Copy" in conv_opt else "libx264"
396
+ cmd += ['-map','0:v:0','-c:v:0',vc]
397
+ if vc != "copy": cmd += ['-preset','ultrafast','-crf','23']
398
+ for i2, t2 in enumerate(audio_tracks):
399
+ cmd += ['-map',f"0:{t2['index']}",f'-c:a:{i2}','aac',f'-b:a:{i2}','192k',
400
+ f'-ar:a:{i2}','48000',f'-ac:a:{i2}','2']
401
+ mpd_out = tmp_d / "manifest.mpd"
402
+ cmd += (render_args() if vc != "copy" else
403
+ ['-max_muxing_queue_size','9999','-copytb','1','-start_at_zero','-thread_queue_size','4096'])
404
+ cmd += ['-f','dash','-seg_duration','5','-use_template','1','-use_timeline','0',
405
+ '-init_seg_name','init-$RepresentationID$.m4s',
406
+ '-media_seg_name','chunk-$RepresentationID$-$Number%05d$.m4s',
407
+ str(mpd_out),'-y','-loglevel','error']
408
+ r = subprocess.run(cmd, capture_output=True, text=True, timeout=14400)
409
+ if r.returncode != 0:
410
+ shutil.rmtree(tmp_d, ignore_errors=True)
411
+ raise Exception(f"DASH fallΓ³: {r.stderr[-400:]}")
412
+ shutil.move(str(mpd_out), str(out_dir / "manifest.mpd"))
413
+ for m4s in tmp_d.glob("*.m4s"): shutil.move(str(m4s), str(out_dir / m4s.name))
414
+ shutil.rmtree(tmp_d, ignore_errors=True)
415
+ manifest_file = "manifest.mpd"
416
+ log_cb(" βœ“ DASH OK")
417
+
418
+ # ── GITHUB ──
419
+ log_cb(f" ☁ Subiendo a GitHub: {repo_name}")
420
+ if not requests:
421
+ raise Exception("requests no instalado β€” pip install requests")
422
+ headers = {"Authorization": f"token {token}"}
423
+ rr = requests.post("https://api.github.com/user/repos", headers=headers,
424
+ json={"name": repo_name, "private": True}, timeout=30)
425
+ if rr.status_code == 422:
426
+ u = requests.get("https://api.github.com/user", headers=headers, timeout=30)
427
+ html_url = f"https://github.com/{u.json()['login']}/{repo_name}"
428
+ elif rr.status_code in [200, 201]:
429
+ html_url = rr.json()['html_url']
430
+ else:
431
+ raise Exception(f"GitHub API {rr.status_code}: {rr.text[:200]}")
432
+
433
+ git_url = html_url.replace('https://', f'https://{token}@') + '.git'
434
+ gd = str(out_dir)
435
+
436
+ for gc in [['git','init'],['git','checkout','-b','main'],
437
+ ['git','remote','add','origin',git_url],
438
+ ['git','config','http.postBuffer','524288000'],
439
+ ['git','config','core.compression','0']]:
440
+ subprocess.run(gc, cwd=gd, check=True, capture_output=True)
441
+
442
+ all_files = os.listdir(gd)
443
+ ext_s = '.m4s' if stream_fmt == "DASH (MPD)" else '.ts'
444
+ ext_m = '.mpd' if stream_fmt == "DASH (MPD)" else '.m3u8'
445
+ segs = [f for f in all_files if f.endswith(ext_s)]
446
+ mans = [f for f in all_files if f.endswith(ext_m)]
447
+
448
+ subprocess.run(['git','add'] + mans, cwd=gd, check=True, capture_output=True)
449
+ subprocess.run(['git','commit','-m',f'init {folder_name}'], cwd=gd, check=True, capture_output=True)
450
+ git_push_retry(gd, ['-u','origin','main'])
451
+
452
+ log_cb(f" πŸ“¦ {len(segs)} segmentos β†’ batch {batch_size}")
453
+ for i3 in range(0, len(segs), batch_size):
454
+ batch = segs[i3:i3+batch_size]
455
+ subprocess.run(['git','add']+batch, cwd=gd, check=True, capture_output=True)
456
+ subprocess.run(['git','commit','-m',f'segs {i3}-{i3+len(batch)}'],
457
+ cwd=gd, check=True, capture_output=True)
458
+ ok = git_push_retry(gd, ['origin','main'])
459
+ if ok: log_cb(f" πŸ“€ {min(i3+batch_size,len(segs))}/{len(segs)}")
460
+ else: log_cb(f" ⚠ Batch {i3} error")
461
+
462
+ gp = f"https://gooplay.xyz/gp/stream.php?repo={repo_name}&branch=main&file={manifest_file}"
463
+ gh = f"{html_url}/blob/main/{manifest_file}"
464
+ final_links.append(f"{folder_name}\nGooplay: {gp}\nGitHub: {gh}")
465
+ log_cb(f" βœ“ Completado: {folder_name}")
466
+
467
+ if delete_local:
468
+ shutil.rmtree(out_dir, ignore_errors=True)
469
+ log_cb(" βœ“ Archivos locales borrados")
470
+ else:
471
+ log_cb(f" β„Ή Archivos en: {out_dir}")
472
+
473
+ result = "\n\n".join(final_links)
474
+ log_cb("\nπŸŽ‰ TODOS COMPLETADOS\n" + "="*40 + "\n" + result)
475
+ done_cb(True, result)
476
+
477
+ except Exception as e:
478
+ import traceback
479
+ log_cb(f"\nβœ— ERROR: {e}\n{traceback.format_exc()}")
480
+ done_cb(False, str(e))
481
+
482
+
483
+ # ════════════════════════════════════════════════════════════
484
+ # GUI
485
+ # ════════════════════════════════════════════════════════════
486
+ class AppHLS(tk.Tk):
487
+ def __init__(self):
488
+ super().__init__()
489
+ self.title("HLS/DASH Converter EXTREME")
490
+ self.geometry("1100x750")
491
+ self.minsize(900, 620)
492
+ self.configure(bg=BG)
493
+ self.resizable(True, True)
494
+ self._build()
495
+ self._center()
496
+
497
+ def _center(self):
498
+ self.update_idletasks()
499
+ w, h = self.winfo_width(), self.winfo_height()
500
+ sw, sh = self.winfo_screenwidth(), self.winfo_screenheight()
501
+ self.geometry(f"{w}x{h}+{(sw-w)//2}+{(sh-h)//2}")
502
+
503
+ def _style(self):
504
+ s = ttk.Style(self)
505
+ s.theme_use("clam")
506
+ s.configure(".", background=BG, foreground=FG, font=FM,
507
+ fieldbackground=BG2, borderwidth=0)
508
+ s.configure("TFrame", background=BG)
509
+ s.configure("TLabel", background=BG, foreground=FG)
510
+ s.configure("TEntry", fieldbackground=BG2, foreground=FG,
511
+ insertcolor=FG, borderwidth=1)
512
+ s.configure("TCombobox", fieldbackground=BG2, background=BG3,
513
+ foreground=FG, arrowcolor=FG2)
514
+ s.map("TCombobox", fieldbackground=[("readonly", BG2)],
515
+ foreground=[("readonly", FG)])
516
+ s.configure("TCheckbutton", background=BG, foreground=FG2)
517
+ s.map("TCheckbutton", background=[("active", BG)])
518
+ s.configure("TRadiobutton", background=BG, foreground=FG2)
519
+ s.map("TRadiobutton", background=[("active", BG)])
520
+ s.configure("Horizontal.TProgressbar",
521
+ troughcolor=BG3, background=ACCENT,
522
+ borderwidth=0, thickness=6)
523
+
524
+ def _build(self):
525
+ self._style()
526
+
527
+ # HEADER
528
+ hdr = tk.Frame(self, bg=BG, pady=8)
529
+ hdr.pack(fill="x", padx=20)
530
+ tk.Label(hdr, text="HLS/DASH CONVERTER EXTREME", bg=BG, fg=ACCENT,
531
+ font=("Consolas", 15, "bold")).pack(side="left")
532
+ tk.Label(hdr, text=f" Β· {N_THREADS} threads Β· {RAMDISK}",
533
+ bg=BG, fg=FG3, font=FS).pack(side="left")
534
+ self._lbl_status = tk.Label(hdr, text="● Listo", bg=BG, fg=GREEN, font=FS)
535
+ self._lbl_status.pack(side="right")
536
+
537
+ tk.Frame(self, bg=BORDER, height=1).pack(fill="x", padx=20)
538
+
539
+ body = tk.Frame(self, bg=BG)
540
+ body.pack(fill="both", expand=True, padx=20, pady=8)
541
+
542
+ # ─ LEFT ─
543
+ left = tk.Frame(body, bg=BG, width=340)
544
+ left.pack(side="left", fill="y", padx=(0, 10))
545
+ left.pack_propagate(False)
546
+
547
+ self._section(left, "GITHUB TOKEN")
548
+ self._gh_token = self._entry_var(left, "ghp_…", show="*")
549
+
550
+ self._section(left, "FUENTES")
551
+ # Files
552
+ f_files = tk.Frame(left, bg=BG)
553
+ f_files.pack(fill="x", pady=(0, 4))
554
+ self._file_lbl = tk.Label(f_files, text="Sin archivos", bg=BG3, fg=FG3,
555
+ font=FS, anchor="w", padx=6, pady=3)
556
+ self._file_lbl.pack(side="left", fill="x", expand=True)
557
+ tk.Button(f_files, text="πŸ“ Archivos", bg=BG3, fg=FG2, bd=0,
558
+ font=FS, cursor="hand2", command=self._browse_files,
559
+ padx=6, pady=3).pack(side="right")
560
+ self._files_list = []
561
+
562
+ # URLs
563
+ tk.Label(left, text="URLs (una por lΓ­nea):", bg=BG, fg=FG2, font=FS).pack(anchor="w")
564
+ self._urls_txt = tk.Text(left, bg=BG2, fg=FG, insertbackground=FG,
565
+ font=FS, bd=0, relief="flat", height=5, wrap="none")
566
+ self._urls_txt.pack(fill="x", pady=(0, 6))
567
+
568
+ self._section(left, "CONVERSIΓ“N")
569
+ self._conv_opt = ttk.Combobox(left, state="readonly", font=FS, height=6,
570
+ values=["OpciΓ³n 1: Copy Video",
571
+ "OpciΓ³n 2: Copy Video MP3",
572
+ "OpciΓ³n 3: 1080p+720p H.264",
573
+ "OpciΓ³n 4: 4K+1080p+720p H.264"])
574
+ self._conv_opt.set("OpciΓ³n 1: Copy Video")
575
+ self._conv_opt.pack(fill="x", pady=(0, 4))
576
+
577
+ self._stream_fmt = ttk.Combobox(left, state="readonly", font=FS,
578
+ values=["HLS (M3U8)", "DASH (MPD)"])
579
+ self._stream_fmt.set("HLS (M3U8)")
580
+ self._stream_fmt.pack(fill="x", pady=(0, 6))
581
+
582
+ f_nums = tk.Frame(left, bg=BG)
583
+ f_nums.pack(fill="x", pady=(0, 4))
584
+ tk.Label(f_nums, text="Batch git:", bg=BG, fg=FG2, font=FS).pack(side="left")
585
+ self._batch_var = tk.StringVar(value="30")
586
+ tk.Entry(f_nums, textvariable=self._batch_var, bg=BG2, fg=FG,
587
+ insertbackground=FG, font=FS, bd=0, width=5,
588
+ relief="flat").pack(side="left", padx=4)
589
+ tk.Label(f_nums, text="Workers:", bg=BG, fg=FG2, font=FS).pack(side="left")
590
+ self._workers_var = tk.StringVar(value="4")
591
+ tk.Entry(f_nums, textvariable=self._workers_var, bg=BG2, fg=FG,
592
+ insertbackground=FG, font=FS, bd=0, width=4,
593
+ relief="flat").pack(side="left", padx=4)
594
+
595
+ self._del_local = tk.BooleanVar(value=True)
596
+ ttk.Checkbutton(left, text="Borrar archivos locales al terminar",
597
+ variable=self._del_local).pack(anchor="w")
598
+
599
+ self._section(left, "CONTENIDO")
600
+ self._ctype = tk.StringVar(value="Serie")
601
+ f_ct = tk.Frame(left, bg=BG)
602
+ f_ct.pack(fill="x")
603
+ for ct in ["PelΓ­cula", "Serie"]:
604
+ ttk.Radiobutton(f_ct, text=ct, variable=self._ctype,
605
+ value=ct, command=self._toggle_ctype).pack(side="left", padx=4)
606
+
607
+ self._movie_frame = tk.Frame(left, bg=BG)
608
+ tk.Label(self._movie_frame, text="Nombre:", bg=BG, fg=FG2, font=FS).pack(anchor="w")
609
+ self._mname = self._entry_var(self._movie_frame, "El Padrino")
610
+
611
+ self._serie_frame = tk.Frame(left, bg=BG)
612
+ tk.Label(self._serie_frame, text="Serie:", bg=BG, fg=FG2, font=FS).pack(anchor="w")
613
+ self._sname = self._entry_var(self._serie_frame, "Breaking Bad")
614
+ f_ss = tk.Frame(self._serie_frame, bg=BG)
615
+ f_ss.pack(fill="x")
616
+ tk.Label(f_ss, text="Temp:", bg=BG, fg=FG2, font=FS).pack(side="left")
617
+ self._season = tk.StringVar(value="1")
618
+ tk.Entry(f_ss, textvariable=self._season, bg=BG2, fg=FG,
619
+ insertbackground=FG, font=FS, bd=0, width=4,
620
+ relief="flat").pack(side="left", padx=4)
621
+ tk.Label(f_ss, text="Ep inicial:", bg=BG, fg=FG2, font=FS).pack(side="left")
622
+ self._ep_start = tk.StringVar(value="1")
623
+ tk.Entry(f_ss, textvariable=self._ep_start, bg=BG2, fg=FG,
624
+ insertbackground=FG, font=FS, bd=0, width=4,
625
+ relief="flat").pack(side="left", padx=4)
626
+ self._serie_frame.pack(fill="x", pady=(4, 0))
627
+
628
+ # ─ RIGHT ─
629
+ right = tk.Frame(body, bg=BG)
630
+ right.pack(side="right", fill="both", expand=True)
631
+
632
+ # Progress
633
+ self._lbl_prog = tk.Label(right, text="", bg=BG, fg=FG2, font=FS, anchor="w")
634
+ self._lbl_prog.pack(fill="x")
635
+ self._pbar = ttk.Progressbar(right, mode="determinate",
636
+ style="Horizontal.TProgressbar")
637
+ self._pbar.pack(fill="x", pady=(2, 6))
638
+
639
+ # Log
640
+ tk.Label(right, text="LOG DE PROCESAMIENTO", bg=BG, fg=FG3,
641
+ font=("Consolas", 8, "bold")).pack(anchor="w")
642
+ log_f = tk.Frame(right, bg=BORDER)
643
+ log_f.pack(fill="both", expand=True, pady=(2, 6))
644
+ self._log_txt = tk.Text(
645
+ log_f, bg="#030810", fg=CYAN, font=("Consolas", 9),
646
+ bd=0, relief="flat", state="disabled", wrap="word",
647
+ insertbackground=FG, selectbackground=ACCENT2
648
+ )
649
+ sb = ttk.Scrollbar(log_f, command=self._log_txt.yview)
650
+ self._log_txt.configure(yscrollcommand=sb.set)
651
+ sb.pack(side="right", fill="y")
652
+ self._log_txt.pack(fill="both", expand=True, padx=1, pady=1)
653
+
654
+ # Links output
655
+ tk.Label(right, text="LINKS GENERADOS", bg=BG, fg=FG3,
656
+ font=("Consolas", 8, "bold")).pack(anchor="w")
657
+ lnk_f = tk.Frame(right, bg=BORDER)
658
+ lnk_f.pack(fill="x", pady=(2, 6))
659
+ self._links_txt = tk.Text(
660
+ lnk_f, bg="#020c08", fg=GREEN, font=("Consolas", 9),
661
+ bd=0, relief="flat", state="disabled", height=6,
662
+ insertbackground=FG
663
+ )
664
+ lsb = ttk.Scrollbar(lnk_f, command=self._links_txt.yview)
665
+ self._links_txt.configure(yscrollcommand=lsb.set)
666
+ lsb.pack(side="right", fill="y")
667
+ self._links_txt.pack(fill="x", padx=1, pady=1)
668
+
669
+ # Buttons
670
+ bf = tk.Frame(right, bg=BG)
671
+ bf.pack(fill="x")
672
+ self._btn_start = tk.Button(
673
+ bf, text="πŸš€ INICIAR CONVERSIΓ“N",
674
+ bg=ACCENT, fg="white", bd=0, padx=16, pady=10,
675
+ font=("Consolas", 12, "bold"), cursor="hand2",
676
+ command=self._do_start
677
+ )
678
+ self._btn_start.pack(side="left", fill="x", expand=True)
679
+ tk.Button(
680
+ bf, text="βœ•", bg=BG3, fg=RED, bd=0,
681
+ padx=14, pady=10, font=FB, cursor="hand2",
682
+ command=self._do_cancel
683
+ ).pack(side="right", padx=(6, 0))
684
+
685
+ self._cancelled = False
686
+
687
+ # ── HELPERS ──────────────────────────────────────────
688
+ def _section(self, parent, text):
689
+ f = tk.Frame(parent, bg=BG)
690
+ f.pack(fill="x", pady=(10, 2))
691
+ tk.Label(f, text=text, bg=BG, fg=FG3,
692
+ font=("Consolas", 8, "bold")).pack(side="left")
693
+ tk.Frame(f, bg=BORDER, height=1).pack(side="right", fill="x",
694
+ expand=True, padx=(6, 0), pady=4)
695
+
696
+ def _entry_var(self, parent, placeholder, show=None):
697
+ v = tk.StringVar()
698
+ kw = {"show": show} if show else {}
699
+ tk.Entry(parent, textvariable=v, bg=BG2, fg=FG2,
700
+ insertbackground=FG, font=FS, bd=0, relief="flat",
701
+ **kw).pack(fill="x", ipady=5, pady=(0, 4))
702
+ return v
703
+
704
+ def _toggle_ctype(self):
705
+ if self._ctype.get() == "PelΓ­cula":
706
+ self._serie_frame.pack_forget()
707
+ self._movie_frame.pack(fill="x", pady=(4, 0))
708
+ else:
709
+ self._movie_frame.pack_forget()
710
+ self._serie_frame.pack(fill="x", pady=(4, 0))
711
+
712
+ def _browse_files(self):
713
+ files = filedialog.askopenfilenames(
714
+ filetypes=[("Video", "*.mp4 *.mkv *.avi *.mov *.ts *.m2ts *.webm"),
715
+ ("Todos", "*.*")]
716
+ )
717
+ if files:
718
+ self._files_list = list(files)
719
+ names = ", ".join(Path(f).name for f in files)
720
+ self._file_lbl.configure(
721
+ text=names[:60] + ("…" if len(names) > 60 else ""), fg=FG2
722
+ )
723
+
724
+ def _log(self, msg):
725
+ self._log_txt.configure(state="normal")
726
+ self._log_txt.insert("end", msg + "\n")
727
+ self._log_txt.see("end")
728
+ self._log_txt.configure(state="disabled")
729
+
730
+ def _set_progress(self, pct, label=""):
731
+ self._pbar["value"] = pct
732
+ self._lbl_prog.configure(text=label)
733
+ self.update_idletasks()
734
+
735
+ def _set_links(self, text):
736
+ self._links_txt.configure(state="normal")
737
+ self._links_txt.delete("1.0", "end")
738
+ self._links_txt.insert("1.0", text)
739
+ self._links_txt.configure(state="disabled")
740
+
741
+ # ── START ──────────────────────���─────────────────────
742
+ def _do_start(self):
743
+ token = self._gh_token.get().strip()
744
+ if not token:
745
+ messagebox.showwarning("Token", "IngresΓ‘ tu token de GitHub")
746
+ return
747
+
748
+ sources = []
749
+ for f in self._files_list:
750
+ sources.append({"type": "file", "value": f})
751
+ for line in self._urls_txt.get("1.0", "end").strip().split("\n"):
752
+ u = line.strip()
753
+ if u: sources.append({"type": "url", "value": u})
754
+
755
+ if not sources:
756
+ messagebox.showwarning("Fuente", "AgregΓ‘ archivos o URLs")
757
+ return
758
+
759
+ self._btn_start.configure(state="disabled", bg=FG3)
760
+ self._lbl_status.configure(text="● Procesando…", fg=YELLOW)
761
+ self._log_txt.configure(state="normal")
762
+ self._log_txt.delete("1.0", "end")
763
+ self._log_txt.configure(state="disabled")
764
+ self._pbar["value"] = 0
765
+ self._cancelled = False
766
+
767
+ try:
768
+ batch_size = int(self._batch_var.get() or 30)
769
+ max_workers = int(self._workers_var.get() or 4)
770
+ season = int(self._season.get() or 1)
771
+ ep_start = int(self._ep_start.get() or 1)
772
+ except:
773
+ batch_size, max_workers, season, ep_start = 30, 4, 1, 1
774
+
775
+ job = {
776
+ 'token': token, 'sources': sources,
777
+ 'conv_opt': self._conv_opt.get(),
778
+ 'stream_fmt': self._stream_fmt.get(),
779
+ 'batch_size': batch_size,
780
+ 'delete_local': self._del_local.get(),
781
+ 'max_workers': max_workers,
782
+ 'ctype': self._ctype.get(),
783
+ 'mname': self._mname.get().strip(),
784
+ 'sname': self._sname.get().strip(),
785
+ 'season': season, 'ep_start': ep_start,
786
+ }
787
+
788
+ def _done(ok, result):
789
+ self.after(0, self._btn_start.configure, {"state": "normal", "bg": ACCENT})
790
+ if ok:
791
+ self.after(0, self._lbl_status.configure, {"text": "● Completado", "fg": GREEN})
792
+ self.after(0, self._set_links, result)
793
+ self.after(0, self._set_progress, 100, "Completado")
794
+ else:
795
+ self.after(0, self._lbl_status.configure, {"text": "● Error", "fg": RED})
796
+
797
+ threading.Thread(
798
+ target=run_conversion,
799
+ args=(job,
800
+ lambda m: self.after(0, self._log, m),
801
+ lambda p, l: self.after(0, self._set_progress, p, l),
802
+ _done),
803
+ daemon=True
804
+ ).start()
805
+
806
+ def _do_cancel(self):
807
+ self._cancelled = True
808
+ self._lbl_status.configure(text="● Cancelado", fg=RED)
809
+ self._log("β›” Cancelado por usuario")
810
+ self._btn_start.configure(state="normal", bg=ACCENT)
811
+
812
+
813
+ if __name__ == "__main__":
814
+ app = AppHLS()
815
+ app.mainloop()
video_converter_pro.py ADDED
@@ -0,0 +1,597 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Video Converter Pro β€” App nativa Windows
3
+ Convierte video y sube a HuggingFace. Sin Gradio.
4
+ Auto-elevaciΓ³n a administrador.
5
+ """
6
+ import sys
7
+ import os
8
+ import ctypes
9
+ import subprocess
10
+ import threading
11
+ import tempfile
12
+ import shutil
13
+ import re
14
+ import json
15
+ import uuid
16
+ import tkinter as tk
17
+ from tkinter import ttk, filedialog, messagebox
18
+ from pathlib import Path
19
+
20
+ # ─── AUTO-ELEVACIΓ“N ADMINISTRADOR ───────────────────────────
21
+ def is_admin():
22
+ try:
23
+ return ctypes.windll.shell32.IsUserAnAdmin()
24
+ except:
25
+ return False
26
+
27
+ def elevate():
28
+ if not is_admin():
29
+ ctypes.windll.shell32.ShellExecuteW(
30
+ None, "runas", sys.executable, " ".join(sys.argv), None, 1
31
+ )
32
+ sys.exit()
33
+
34
+ elevate()
35
+
36
+ # ─── HF IMPORT ──────────────────────────────────────────────
37
+ try:
38
+ from huggingface_hub import HfApi, list_models
39
+ HF_OK = True
40
+ except ImportError:
41
+ HF_OK = False
42
+
43
+ # ─── COLORES / TEMA ─────────────────────────────────────────
44
+ BG = "#0b0f1a"
45
+ BG2 = "#111827"
46
+ BG3 = "#1a2235"
47
+ ACCENT = "#3b82f6"
48
+ ACCENT2 = "#6366f1"
49
+ GREEN = "#22c55e"
50
+ RED = "#ef4444"
51
+ YELLOW = "#f59e0b"
52
+ FG = "#e2e8f0"
53
+ FG2 = "#94a3b8"
54
+ FG3 = "#475569"
55
+ BORDER = "#1e2d42"
56
+ FONT_MAIN = ("Consolas", 10)
57
+ FONT_BIG = ("Consolas", 12, "bold")
58
+ FONT_SM = ("Consolas", 9)
59
+
60
+ # ─── UTILS ──────────────────────────────────────────────────
61
+ def safe_name(s, maxlen=120):
62
+ return re.sub(r'[<>:"/\\|?*\x00-\x1f]', '_', s).strip()[:maxlen]
63
+
64
+ def fmt_dur(secs):
65
+ s = int(secs)
66
+ return f"{s//3600:02d}:{(s%3600)//60:02d}:{s%60:02d}"
67
+
68
+ # ─── FFPROBE ────────────────────────────────────────────────
69
+ def probe(source):
70
+ info = {"audio": [], "subs": [], "duration": 0.0, "title": ""}
71
+ try:
72
+ r = subprocess.run(
73
+ ["ffprobe", "-v", "quiet", "-print_format", "json",
74
+ "-show_format", "-show_streams", source],
75
+ capture_output=True, text=True, timeout=90
76
+ )
77
+ if r.returncode != 0:
78
+ return info
79
+ data = json.loads(r.stdout)
80
+ tags = data.get("format", {}).get("tags", {})
81
+ info["title"] = (tags.get("title") or tags.get("TITLE") or "").strip()
82
+ info["duration"] = float(data.get("format", {}).get("duration", 0) or 0)
83
+ ai = si = 0
84
+ for s in data.get("streams", []):
85
+ t = s.get("tags", {})
86
+ ct = s.get("codec_type", "")
87
+ if ct == "audio":
88
+ info["audio"].append({
89
+ "idx": ai, "codec": s.get("codec_name", "?"),
90
+ "lang": t.get("language", "und"), "ch": s.get("channels", 2),
91
+ "title": t.get("title", ""),
92
+ })
93
+ ai += 1
94
+ elif ct == "subtitle":
95
+ info["subs"].append({
96
+ "idx": si, "codec": s.get("codec_name", "?"),
97
+ "lang": t.get("language", "und"), "title": t.get("title", ""),
98
+ "forced": s.get("disposition", {}).get("forced", 0) == 1,
99
+ })
100
+ si += 1
101
+ except Exception as e:
102
+ pass
103
+ return info
104
+
105
+ # ─── FFMPEG ─────────────────────────────────────────────────
106
+ NET_ARGS = [
107
+ "-user_agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64)",
108
+ "-headers", "Referer: https://google.com\r\n",
109
+ "-timeout", "180000000",
110
+ "-reconnect", "1", "-reconnect_streamed", "1",
111
+ "-reconnect_at_eof", "1", "-reconnect_delay_max", "30",
112
+ "-rw_timeout", "180000000", "-multiple_requests", "1",
113
+ ]
114
+
115
+ def run_ffmpeg(cmd, total, log_cb, progress_cb, label):
116
+ try:
117
+ proc = subprocess.Popen(
118
+ cmd, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE,
119
+ universal_newlines=True, bufsize=1
120
+ )
121
+ pat = re.compile(r"time=(\d+):(\d+):(\d+)\.(\d+)")
122
+ for line in proc.stderr:
123
+ m = pat.search(line)
124
+ if m:
125
+ h, mi, s, cs = map(int, m.groups())
126
+ cur = h*3600 + mi*60 + s + cs/100
127
+ pct = min(99, int(cur / max(total, 1) * 100))
128
+ progress_cb(pct, f"{label}: {pct}% [{fmt_dur(cur)} / {fmt_dur(total)}]")
129
+ proc.wait()
130
+ return proc.returncode == 0
131
+ except Exception as e:
132
+ log_cb(f" βœ— ffmpeg: {e}")
133
+ return False
134
+
135
+ # ─── HF UPLOAD ────────────────────────────────────────────��─
136
+ def hf_upload(token, repo_id, folder_path, log_cb, progress_cb):
137
+ if not HF_OK:
138
+ log_cb(" βœ— huggingface_hub no instalado")
139
+ return False
140
+ try:
141
+ api = HfApi(token=token)
142
+ try:
143
+ api.create_repo(repo_id=repo_id, repo_type="model", private=True, exist_ok=True)
144
+ except:
145
+ pass
146
+ files = list(Path(folder_path).iterdir())
147
+ for i, f in enumerate(files):
148
+ if f.is_file():
149
+ rpath = f"videos/{Path(folder_path).name}/{f.name}"
150
+ log_cb(f" ↑ {f.name}")
151
+ progress_cb(int(i/len(files)*100), f"Subiendo {i+1}/{len(files)}")
152
+ api.upload_file(
153
+ path_or_fileobj=str(f),
154
+ path_in_repo=rpath,
155
+ repo_id=repo_id,
156
+ repo_type="model",
157
+ )
158
+ progress_cb(100, "Subida completa")
159
+ log_cb(f" βœ“ Subido β†’ {repo_id}/videos/{Path(folder_path).name}/")
160
+ return True
161
+ except Exception as e:
162
+ log_cb(f" βœ— upload error: {e}")
163
+ return False
164
+
165
+ # ─── PROCESO PRINCIPAL ──────────────────────────────────────
166
+ def process_video(token, repo_id, source, is_url, mode,
167
+ audio_idx, gen_single, extract_sub, sub_idx,
168
+ delete_local, log_cb, progress_cb, done_cb):
169
+ try:
170
+ extra = NET_ARGS if is_url else []
171
+ log_cb("⟳ Analizando fuente…")
172
+ info = probe(source)
173
+ dur = info["duration"] if info["duration"] > 0 else 1
174
+ log_cb(f" βœ“ {fmt_dur(dur)} | {len(info['audio'])} audio | {len(info['subs'])} sub")
175
+
176
+ base = info["title"] if info["title"] else Path(source).stem or "video"
177
+ fname = safe_name(base)
178
+
179
+ tmp = tempfile.mkdtemp(prefix="vcpro_")
180
+ out_mp4 = os.path.join(tmp, f"{fname}.mp4")
181
+
182
+ cmd = ["ffmpeg", "-y"] + extra + ["-i", source, "-map", "0:v:0"]
183
+ for i in range(len(info["audio"])):
184
+ cmd.extend(["-map", f"0:a:{i}"])
185
+
186
+ if mode == "Copy + MP3":
187
+ cmd += ["-c:v", "copy"]
188
+ for i in range(len(info["audio"])):
189
+ cmd += [f"-c:a:{i}", "libmp3lame", f"-b:a:{i}", "320k", f"-ar:a:{i}", "48000"]
190
+ elif mode == "Copy + FLAC":
191
+ cmd += ["-c:v", "copy"]
192
+ for i in range(len(info["audio"])):
193
+ cmd += [f"-c:a:{i}", "flac", f"-compression_level:a:{i}", "0"]
194
+ else:
195
+ cmd += ["-c:v", "libx264", "-vf", "scale=-2:1080", "-preset", "slow", "-crf", "18"]
196
+ for i in range(len(info["audio"])):
197
+ cmd += [f"-c:a:{i}", "libmp3lame", f"-b:a:{i}", "320k", f"-ar:a:{i}", "48000"]
198
+
199
+ cmd += ["-map_metadata", "0", out_mp4]
200
+
201
+ log_cb(f"βš™ Convirtiendo ({mode})…")
202
+ ok = run_ffmpeg(cmd, dur, log_cb, progress_cb, "Convirtiendo")
203
+ if not ok:
204
+ log_cb("βœ— ConversiΓ³n fallΓ³")
205
+ if delete_local:
206
+ shutil.rmtree(tmp, ignore_errors=True)
207
+ done_cb(False)
208
+ return
209
+
210
+ progress_cb(100, "ConversiΓ³n OK")
211
+ log_cb(" βœ“ ConversiΓ³n OK")
212
+
213
+ if gen_single and info["audio"] and audio_idx < len(info["audio"]):
214
+ sp = os.path.join(tmp, f"{fname}_aud{audio_idx}.mp4")
215
+ sc = ["ffmpeg", "-y", "-i", out_mp4,
216
+ "-map", "0:v:0", "-map", f"0:a:{audio_idx}", "-c", "copy", sp]
217
+ run_ffmpeg(sc, dur, log_cb, progress_cb, "Audio individual")
218
+ log_cb(" βœ“ Audio individual extraΓ­do")
219
+
220
+ if extract_sub and info["subs"] and sub_idx < len(info["subs"]):
221
+ vtt = os.path.join(tmp, f"{fname}_sub{sub_idx}.vtt")
222
+ sc = ["ffmpeg", "-y"] + extra + [
223
+ "-i", source, "-map", f"0:s:{sub_idx}", "-c:s", "webvtt", vtt]
224
+ try:
225
+ subprocess.run(sc, capture_output=True, check=True, timeout=120)
226
+ log_cb(" βœ“ SubtΓ­tulo extraΓ­do")
227
+ except Exception as e:
228
+ log_cb(f" ⚠ sub error: {e}")
229
+
230
+ log_cb(f"☁ Subiendo a HuggingFace β†’ {repo_id}")
231
+ ok2 = hf_upload(token, repo_id, tmp, log_cb, progress_cb)
232
+
233
+ if delete_local:
234
+ shutil.rmtree(tmp, ignore_errors=True)
235
+ log_cb(" βœ“ Archivos locales borrados")
236
+ else:
237
+ log_cb(f" β„Ή Archivos guardados en: {tmp}")
238
+
239
+ done_cb(ok2)
240
+
241
+ except Exception as e:
242
+ import traceback
243
+ log_cb(f"βœ— Error: {e}\n{traceback.format_exc()}")
244
+ done_cb(False)
245
+
246
+
247
+ # ════════════════════════════════════════════════════════════
248
+ # GUI
249
+ # ════════════════════════════════════════════════════════════
250
+ class App(tk.Tk):
251
+ def __init__(self):
252
+ super().__init__()
253
+ self.title("Video Converter Pro")
254
+ self.geometry("960x700")
255
+ self.minsize(820, 600)
256
+ self.configure(bg=BG)
257
+ self.resizable(True, True)
258
+ self._repos = []
259
+ self._info = None
260
+ self._build()
261
+ self._center()
262
+
263
+ def _center(self):
264
+ self.update_idletasks()
265
+ w, h = self.winfo_width(), self.winfo_height()
266
+ sw = self.winfo_screenwidth()
267
+ sh = self.winfo_screenheight()
268
+ self.geometry(f"{w}x{h}+{(sw-w)//2}+{(sh-h)//2}")
269
+
270
+ # ── ESTILOS ────────────────────────────────────────────
271
+ def _style(self):
272
+ s = ttk.Style(self)
273
+ s.theme_use("clam")
274
+ s.configure(".", background=BG, foreground=FG, font=FONT_MAIN,
275
+ fieldbackground=BG2, borderwidth=0)
276
+ s.configure("TFrame", background=BG)
277
+ s.configure("TLabel", background=BG, foreground=FG, font=FONT_MAIN)
278
+ s.configure("Dim.TLabel", foreground=FG2, font=FONT_SM)
279
+ s.configure("H.TLabel", foreground=ACCENT, font=FONT_BIG)
280
+ s.configure("TEntry", fieldbackground=BG2, foreground=FG,
281
+ insertcolor=FG, borderwidth=1, relief="flat")
282
+ s.configure("TCombobox", fieldbackground=BG2, background=BG3,
283
+ foreground=FG, arrowcolor=FG2, borderwidth=1)
284
+ s.map("TCombobox", fieldbackground=[("readonly", BG2)],
285
+ foreground=[("readonly", FG)])
286
+ s.configure("TCheckbutton", background=BG, foreground=FG2,
287
+ activebackground=BG, activeforeground=FG)
288
+ s.map("TCheckbutton", background=[("active", BG)])
289
+ s.configure("TRadiobutton", background=BG, foreground=FG2)
290
+ s.map("TRadiobutton", background=[("active", BG)])
291
+ s.configure("Horizontal.TProgressbar",
292
+ troughcolor=BG3, background=ACCENT,
293
+ darkcolor=ACCENT2, lightcolor=ACCENT,
294
+ borderwidth=0, thickness=6)
295
+
296
+ # ── BUILD ──────────────────────────────────────────────
297
+ def _build(self):
298
+ self._style()
299
+
300
+ # ── HEADER ──
301
+ hdr = tk.Frame(self, bg=BG, pady=10)
302
+ hdr.pack(fill="x", padx=20)
303
+ tk.Label(hdr, text="VIDEO CONVERTER PRO", bg=BG, fg=ACCENT,
304
+ font=("Consolas", 16, "bold")).pack(side="left")
305
+ tk.Label(hdr, text=" β†’ HuggingFace", bg=BG, fg=FG3,
306
+ font=("Consolas", 10)).pack(side="left")
307
+ self._lbl_status = tk.Label(hdr, text="● Listo", bg=BG, fg=GREEN,
308
+ font=FONT_SM)
309
+ self._lbl_status.pack(side="right")
310
+
311
+ sep = tk.Frame(self, bg=BORDER, height=1)
312
+ sep.pack(fill="x", padx=20)
313
+
314
+ # ── BODY ──
315
+ body = tk.Frame(self, bg=BG)
316
+ body.pack(fill="both", expand=True, padx=20, pady=10)
317
+
318
+ # ─ LEFT PANEL ─
319
+ left = tk.Frame(body, bg=BG, width=320)
320
+ left.pack(side="left", fill="y", padx=(0, 10))
321
+ left.pack_propagate(False)
322
+
323
+ # HF Token
324
+ self._section(left, "HUGGING FACE")
325
+ self._hf_token = self._entry(left, "Token (hf_…)", show="*")
326
+ f_repo = tk.Frame(left, bg=BG)
327
+ f_repo.pack(fill="x", pady=(2, 6))
328
+ self._repo_cb = ttk.Combobox(f_repo, state="readonly",
329
+ font=FONT_SM, height=8)
330
+ self._repo_cb.pack(side="left", fill="x", expand=True)
331
+ tk.Button(f_repo, text="β†Ί", bg=BG3, fg=ACCENT, bd=0,
332
+ font=FONT_SM, cursor="hand2",
333
+ command=self._load_repos).pack(side="right", padx=(4, 0))
334
+
335
+ # Mode
336
+ self._section(left, "MODO DE CONVERSIΓ“N")
337
+ self._mode = tk.StringVar(value="Copy + MP3")
338
+ for m in ["Copy + MP3", "Copy + FLAC", "H264 1080p"]:
339
+ ttk.Radiobutton(left, text=m, variable=self._mode,
340
+ value=m).pack(anchor="w")
341
+
342
+ # Opciones
343
+ self._section(left, "OPCIONES")
344
+ self._gen_single = tk.BooleanVar(value=False)
345
+ self._ext_sub = tk.BooleanVar(value=False)
346
+ self._del_local = tk.BooleanVar(value=True)
347
+ ttk.Checkbutton(left, text="Generar audio individual",
348
+ variable=self._gen_single).pack(anchor="w")
349
+ ttk.Checkbutton(left, text="Extraer subtΓ­tulo (.vtt)",
350
+ variable=self._ext_sub).pack(anchor="w")
351
+ ttk.Checkbutton(left, text="Borrar archivos locales al terminar",
352
+ variable=self._del_local).pack(anchor="w")
353
+
354
+ # Pistas
355
+ self._section(left, "PISTAS")
356
+ tk.Label(left, text="Audio:", bg=BG, fg=FG2,
357
+ font=FONT_SM).pack(anchor="w")
358
+ self._aud_cb = ttk.Combobox(left, state="readonly",
359
+ font=FONT_SM, height=6)
360
+ self._aud_cb.pack(fill="x", pady=(0, 4))
361
+ tk.Label(left, text="SubtΓ­tulo:", bg=BG, fg=FG2,
362
+ font=FONT_SM).pack(anchor="w")
363
+ self._sub_cb = ttk.Combobox(left, state="readonly",
364
+ font=FONT_SM, height=6)
365
+ self._sub_cb.pack(fill="x")
366
+
367
+ # BotΓ³n analizar
368
+ tk.Button(left, text="⟳ ANALIZAR",
369
+ bg=BG3, fg=ACCENT, bd=0, padx=12, pady=6,
370
+ font=FONT_MAIN, cursor="hand2",
371
+ command=self._do_analyze).pack(fill="x", pady=(10, 2))
372
+
373
+ # ─ RIGHT PANEL ─
374
+ right = tk.Frame(body, bg=BG)
375
+ right.pack(side="right", fill="both", expand=True)
376
+
377
+ # Source tabs
378
+ nb_frame = tk.Frame(right, bg=BG)
379
+ nb_frame.pack(fill="x", pady=(0, 6))
380
+ self._src_mode = tk.StringVar(value="file")
381
+ tk.Button(nb_frame, text="πŸ“ Archivo", bg=ACCENT, fg="white",
382
+ bd=0, padx=10, pady=4, font=FONT_SM, cursor="hand2",
383
+ command=lambda: self._switch_src("file")).pack(side="left")
384
+ tk.Button(nb_frame, text="πŸ”— URL", bg=BG3, fg=FG2,
385
+ bd=0, padx=10, pady=4, font=FONT_SM, cursor="hand2",
386
+ command=lambda: self._switch_src("url")).pack(side="left", padx=4)
387
+
388
+ self._file_frame = tk.Frame(right, bg=BG)
389
+ self._file_frame.pack(fill="x", pady=(0, 4))
390
+ self._file_var = tk.StringVar()
391
+ e_file = tk.Entry(self._file_frame, textvariable=self._file_var,
392
+ bg=BG2, fg=FG, insertbackground=FG,
393
+ font=FONT_SM, bd=0, relief="flat")
394
+ e_file.pack(side="left", fill="x", expand=True, ipady=6, padx=(0, 4))
395
+ tk.Button(self._file_frame, text="Buscar…", bg=BG3, fg=FG2,
396
+ bd=0, padx=8, pady=4, font=FONT_SM, cursor="hand2",
397
+ command=self._browse).pack(side="right")
398
+
399
+ self._url_frame = tk.Frame(right, bg=BG)
400
+ self._url_var = tk.StringVar()
401
+ tk.Entry(self._url_frame, textvariable=self._url_var,
402
+ bg=BG2, fg=FG, insertbackground=FG,
403
+ font=FONT_SM, bd=0, relief="flat",
404
+ ).pack(fill="x", ipady=6)
405
+
406
+ # Info strip
407
+ self._lbl_info = tk.Label(right, text="Sin fuente analizada",
408
+ bg=BG3, fg=FG2, font=FONT_SM,
409
+ anchor="w", padx=8, pady=4)
410
+ self._lbl_info.pack(fill="x", pady=(0, 8))
411
+
412
+ # Progress
413
+ self._lbl_prog = tk.Label(right, text="", bg=BG, fg=FG2, font=FONT_SM)
414
+ self._lbl_prog.pack(anchor="w")
415
+ self._pbar = ttk.Progressbar(right, mode="determinate",
416
+ style="Horizontal.TProgressbar")
417
+ self._pbar.pack(fill="x", pady=(2, 8))
418
+
419
+ # Log
420
+ tk.Label(right, text="LOG", bg=BG, fg=FG3,
421
+ font=("Consolas", 8, "bold")).pack(anchor="w")
422
+ log_f = tk.Frame(right, bg=BORDER)
423
+ log_f.pack(fill="both", expand=True, pady=(2, 8))
424
+ self._log_txt = tk.Text(
425
+ log_f, bg="#050d18", fg="#22d3ee", font=("Consolas", 9),
426
+ bd=0, relief="flat", state="disabled", wrap="word",
427
+ insertbackground=FG, selectbackground=ACCENT2
428
+ )
429
+ sb = ttk.Scrollbar(log_f, command=self._log_txt.yview)
430
+ self._log_txt.configure(yscrollcommand=sb.set)
431
+ sb.pack(side="right", fill="y")
432
+ self._log_txt.pack(fill="both", expand=True, padx=1, pady=1)
433
+
434
+ # PROCESAR button
435
+ self._btn_proc = tk.Button(
436
+ right, text="⬆ PROCESAR Y SUBIR",
437
+ bg=ACCENT, fg="white", bd=0, padx=16, pady=10,
438
+ font=("Consolas", 12, "bold"), cursor="hand2",
439
+ command=self._do_process
440
+ )
441
+ self._btn_proc.pack(fill="x")
442
+
443
+ # ── HELPERS ───────────────────────────────────────────
444
+ def _section(self, parent, text):
445
+ f = tk.Frame(parent, bg=BG)
446
+ f.pack(fill="x", pady=(10, 2))
447
+ tk.Label(f, text=text, bg=BG, fg=FG3,
448
+ font=("Consolas", 8, "bold")).pack(side="left")
449
+ tk.Frame(f, bg=BORDER, height=1).pack(side="right",
450
+ fill="x", expand=True,
451
+ padx=(6, 0), pady=4)
452
+
453
+ def _entry(self, parent, placeholder, show=None):
454
+ v = tk.StringVar()
455
+ kw = {"show": show} if show else {}
456
+ e = tk.Entry(parent, textvariable=v, bg=BG2, fg=FG2,
457
+ insertbackground=FG, font=FONT_SM,
458
+ bd=0, relief="flat", **kw)
459
+ e.pack(fill="x", ipady=6, pady=(0, 4))
460
+ return v
461
+
462
+ def _switch_src(self, mode):
463
+ if mode == "file":
464
+ self._file_frame.pack(fill="x", pady=(0, 4))
465
+ self._url_frame.pack_forget()
466
+ else:
467
+ self._url_frame.pack(fill="x", pady=(0, 4))
468
+ self._file_frame.pack_forget()
469
+ self._src_mode.set(mode)
470
+
471
+ def _browse(self):
472
+ p = filedialog.askopenfilename(
473
+ filetypes=[("Video", "*.mp4 *.mkv *.avi *.mov *.ts *.m2ts *.webm"),
474
+ ("Todos", "*.*")]
475
+ )
476
+ if p:
477
+ self._file_var.set(p)
478
+
479
+ def _log(self, msg):
480
+ self._log_txt.configure(state="normal")
481
+ self._log_txt.insert("end", msg + "\n")
482
+ self._log_txt.see("end")
483
+ self._log_txt.configure(state="disabled")
484
+
485
+ def _set_progress(self, pct, label=""):
486
+ self._pbar["value"] = pct
487
+ self._lbl_prog.configure(text=label)
488
+ self.update_idletasks()
489
+
490
+ def _get_source(self):
491
+ if self._src_mode.get() == "file":
492
+ v = self._file_var.get().strip()
493
+ return v, False
494
+ else:
495
+ v = self._url_var.get().strip()
496
+ return v, True
497
+
498
+ # ── LOAD REPOS ────────────────────────────────────────
499
+ def _load_repos(self):
500
+ token = self._hf_token.get().strip()
501
+ if not token or not HF_OK:
502
+ messagebox.showwarning("Token", "IngresΓ‘ un token HF vΓ‘lido")
503
+ return
504
+ def _go():
505
+ try:
506
+ api = HfApi(token=token)
507
+ uname = api.whoami(token=token)["name"]
508
+ repos = [m.modelId for m in list(
509
+ list_models(token=token, author=uname, limit=200)
510
+ )]
511
+ self._repos = repos
512
+ self._repo_cb["values"] = repos
513
+ if repos:
514
+ self._repo_cb.set(repos[0])
515
+ self._log(f"βœ“ {len(repos)} repositorios cargados")
516
+ except Exception as e:
517
+ self._log(f"βœ— Error cargando repos: {e}")
518
+ threading.Thread(target=_go, daemon=True).start()
519
+
520
+ # ── ANALIZAR ──────────────────────────────────────────
521
+ def _do_analyze(self):
522
+ source, _ = self._get_source()
523
+ if not source:
524
+ messagebox.showwarning("Fuente", "SeleccionΓ‘ archivo o ingresΓ‘ URL")
525
+ return
526
+ def _go():
527
+ self._log(f"⟳ Analizando…")
528
+ info = probe(source)
529
+ self._info = info
530
+ ac = [f"[{t['idx']}] {t['lang']} Β· {t['codec']} Β· {t['ch']}ch" for t in info["audio"]]
531
+ sc = [f"[{t['idx']}] {t['lang']} Β· {t['codec']}" + (" (Forzado)" if t["forced"] else "") for t in info["subs"]]
532
+ self._aud_cb["values"] = ac
533
+ self._sub_cb["values"] = sc
534
+ if ac: self._aud_cb.set(ac[0])
535
+ if sc: self._sub_cb.set(sc[0])
536
+ txt = f"βœ“ {info['title'] or 'β€”'} Β· {fmt_dur(info['duration'])} Β· {len(ac)} aud Β· {len(sc)} sub"
537
+ self._lbl_info.configure(text=txt, fg=GREEN)
538
+ self._log(txt)
539
+ threading.Thread(target=_go, daemon=True).start()
540
+
541
+ # ── PROCESAR ──────────────────────────────────────────
542
+ def _do_process(self):
543
+ token = self._hf_token.get().strip()
544
+ repo_id = self._repo_cb.get().strip()
545
+ source, is_url = self._get_source()
546
+
547
+ if not token:
548
+ messagebox.showwarning("Token", "IngresΓ‘ tu token de HuggingFace")
549
+ return
550
+ if not repo_id:
551
+ messagebox.showwarning("Repo", "SeleccionΓ‘ o cargΓ‘ un repositorio")
552
+ return
553
+ if not source:
554
+ messagebox.showwarning("Fuente", "SeleccionΓ‘ archivo o ingresΓ‘ URL")
555
+ return
556
+
557
+ ai = 0
558
+ si = 0
559
+ if self._aud_cb.get():
560
+ try: ai = int(self._aud_cb.get().split("]")[0].strip("["))
561
+ except: ai = 0
562
+ if self._sub_cb.get():
563
+ try: si = int(self._sub_cb.get().split("]")[0].strip("["))
564
+ except: si = 0
565
+
566
+ self._btn_proc.configure(state="disabled", bg=FG3)
567
+ self._lbl_status.configure(text="● Procesando…", fg=YELLOW)
568
+ self._log_txt.configure(state="normal")
569
+ self._log_txt.delete("1.0", "end")
570
+ self._log_txt.configure(state="disabled")
571
+ self._pbar["value"] = 0
572
+
573
+ def _done(ok):
574
+ self._btn_proc.configure(state="normal", bg=ACCENT)
575
+ if ok:
576
+ self._lbl_status.configure(text="● Completado", fg=GREEN)
577
+ self._log("βœ“ COMPLETADO")
578
+ self._set_progress(100, "Completado")
579
+ else:
580
+ self._lbl_status.configure(text="● Error", fg=RED)
581
+ self._log("βœ— FALLΓ“")
582
+
583
+ threading.Thread(
584
+ target=process_video,
585
+ args=(token, repo_id, source, is_url, self._mode.get(),
586
+ ai, self._gen_single.get(), self._ext_sub.get(), si,
587
+ self._del_local.get(),
588
+ lambda m: self.after(0, self._log, m),
589
+ lambda p, l: self.after(0, self._set_progress, p, l),
590
+ lambda ok: self.after(0, _done, ok)),
591
+ daemon=True
592
+ ).start()
593
+
594
+
595
+ if __name__ == "__main__":
596
+ app = App()
597
+ app.mainloop()