| """ |
| HLS/DASH Converter EXTREME β App nativa Windows |
| Convierte a HLS/DASH y sube a GitHub. Sin Gradio. |
| Auto-elevaciΓ³n a administrador. |
| """ |
| import sys |
| import os |
| import ctypes |
| import subprocess |
| import threading |
| import tempfile |
| import shutil |
| import re |
| import json |
| import time |
| import uuid |
| import tkinter as tk |
| from tkinter import ttk, filedialog, messagebox, scrolledtext |
| from pathlib import Path |
| from concurrent.futures import ThreadPoolExecutor, as_completed |
|
|
| |
| def is_admin(): |
| try: |
| return ctypes.windll.shell32.IsUserAnAdmin() |
| except: |
| return False |
|
|
| def elevate(): |
| if not is_admin(): |
| ctypes.windll.shell32.ShellExecuteW( |
| None, "runas", sys.executable, " ".join(sys.argv), None, 1 |
| ) |
| sys.exit() |
|
|
| elevate() |
|
|
| try: |
| import requests |
| except ImportError: |
| requests = None |
|
|
| |
| BG = "#080d18" |
| BG2 = "#0f1629" |
| BG3 = "#17213a" |
| ACCENT = "#6366f1" |
| ACCENT2 = "#8b5cf6" |
| GREEN = "#22c55e" |
| RED = "#ef4444" |
| YELLOW = "#f59e0b" |
| CYAN = "#22d3ee" |
| FG = "#e2e8f0" |
| FG2 = "#94a3b8" |
| FG3 = "#3a5070" |
| BORDER = "#1a2a40" |
| FM = ("Consolas", 10) |
| FB = ("Consolas", 11, "bold") |
| FS = ("Consolas", 9) |
|
|
| |
| def get_threads(): |
| try: |
| return max(len(os.sched_getaffinity(0)) - 1, 1) |
| except: |
| return max((os.cpu_count() or 4) - 1, 1) |
|
|
| N_THREADS = get_threads() |
|
|
| def clean_folder(n): return re.sub(r'[<>:"/\\|?*]', '_', n).strip()[:200] |
| def clean_repo(n): |
| n = re.sub(r'[^a-zA-Z0-9_-]', '-', n) |
| return re.sub(r'-+', '-', n).strip('-')[:100] |
|
|
| def build_name(ctype, mname, sname, season, ep_start, idx): |
| if ctype == "PelΓcula": |
| b = mname.strip() or "Pelicula" |
| return clean_folder(b), clean_repo(b) |
| name = sname.strip() or "Serie" |
| try: t = int(season) |
| except: t = 1 |
| try: e = int(ep_start) + idx |
| except: e = idx + 1 |
| lbl = f"{name}_T{t}_Ep{e}" |
| return clean_folder(lbl), clean_repo(lbl) |
|
|
| def is_live(url): |
| if not url.startswith(("http://", "https://")): return False |
| lo = url.lower() |
| if any(lo.endswith(x) for x in ['.mp4','.mkv','.avi','.mov','.ts']): return False |
| return any(p in lo for p in ['/live/','/stream/','.m3u8','.mpd','/hls/','/dash/']) |
|
|
| def input_args(src): |
| ua = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36" |
| if src.startswith(("http://", "https://")): |
| if is_live(src): |
| return ['-user_agent', ua, '-timeout', '60000000', |
| '-reconnect','1','-reconnect_streamed','1', |
| '-fflags','+genpts+igndts','-probesize','100M','-analyzeduration','50M'] |
| return ['-user_agent', ua, '-timeout', '120000000', |
| '-reconnect','1','-reconnect_streamed','1','-reconnect_delay_max','10', |
| '-analyzeduration','500000000','-probesize','500000000', |
| '-fflags','+genpts+igndts','-err_detect','ignore_err', |
| '-max_delay','10000000','-rw_timeout','120000000'] |
| return ['-analyzeduration','100000000','-probesize','100000000','-fflags','+genpts+igndts'] |
|
|
| def render_args(): |
| return ['-threads', str(N_THREADS), '-thread_type', 'slice+frame', |
| '-slices', str(N_THREADS), '-max_muxing_queue_size', '9999', |
| '-thread_queue_size', '4096'] |
|
|
| def detect_duration(src, iargs): |
| try: |
| cmd = ['ffprobe','-v','error'] + iargs + ['-show_entries','format=duration','-of','json','-i',src] |
| r = subprocess.run(cmd, capture_output=True, text=True, timeout=120) |
| d = json.loads(r.stdout).get('format',{}).get('duration') |
| return float(d) if d and d != 'N/A' else None |
| except: return None |
|
|
| def detect_audio(src, iargs): |
| try: |
| cmd = ['ffprobe','-v','error'] + iargs + [ |
| '-select_streams','a', |
| '-show_entries','stream=index,codec_name:stream_tags=language,title', |
| '-of','json','-i',src] |
| r = subprocess.run(cmd, capture_output=True, text=True, timeout=120) |
| tracks = [] |
| for s in json.loads(r.stdout).get('streams',[]): |
| tags = s.get('tags',{}) |
| tracks.append({'index': s.get('index',0), |
| 'language': tags.get('language','und').lower(), |
| 'title': tags.get('title', f"Audio {s.get('index',0)}"), |
| 'codec': s.get('codec_name','unknown')}) |
| return tracks |
| except: return [] |
|
|
| def prioritize_audio(tracks): |
| prio = ['spa','es','spanish','espaΓ±ol','latino','lat','es-mx','es-419'] |
| def key(t): |
| l, ti = t['language'], t['title'].lower() |
| for p in prio: |
| if p in l or p in ti: return 0 |
| return 1 if l == 'und' else 2 |
| return sorted(tracks, key=key) |
|
|
| def make_master_m3u8(out_dir, video_streams, audio_playlists): |
| c = "#EXTM3U\n#EXT-X-VERSION:7\n\n" |
| for a in audio_playlists: |
| d = "YES" if a['is_default'] else "NO" |
| c += f'#EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID="audio",NAME="{a["title"]}",LANGUAGE="{a["language"]}",DEFAULT={d},AUTOSELECT={d},URI="{a["file"]}"\n' |
| c += "\n" |
| for v in video_streams: |
| c += f'#EXT-X-STREAM-INF:BANDWIDTH={v["bandwidth"]},RESOLUTION={v["resolution"]},CODECS="{v["codecs"]}",AUDIO="audio"\n{v["file"]}\n' |
| (out_dir / "master.m3u8").write_text(c) |
|
|
| RAMDISK_PATH = None |
| def setup_ramdisk(): |
| global RAMDISK_PATH |
| for p in [r"C:\Temp\hls_tmp", tempfile.gettempdir() + r"\hls_tmp"]: |
| try: |
| Path(p).mkdir(parents=True, exist_ok=True) |
| RAMDISK_PATH = Path(p) |
| return Path(p) |
| except: continue |
| RAMDISK_PATH = Path(tempfile.gettempdir()) |
| return RAMDISK_PATH |
|
|
| RAMDISK = setup_ramdisk() |
|
|
| def process_audio_track(args): |
| track, i, total, src, out_dir, iargs = args |
| tmp = RAMDISK / f"aud_{os.getpid()}_{i}_{int(time.time())}" |
| tmp.mkdir(exist_ok=True) |
| try: |
| af = tmp / f"audio_{i}.m3u8" |
| sf = tmp / f"audio_{i}_%03d.ts" |
| wav_tmp = tmp / f"audio_{i}_raw.wav" |
|
|
| r_dec = subprocess.run( |
| ['ffmpeg','-hide_banner','-threads',str(N_THREADS)] + iargs + [ |
| '-i',src,'-map',f"0:{track['index']}",'-vn', |
| '-c:a','pcm_s16le','-ar','48000','-ac','2','-f','wav', |
| str(wav_tmp),'-y','-loglevel','error'], |
| capture_output=True, text=True, timeout=7200) |
| if r_dec.returncode != 0 or not wav_tmp.exists(): |
| raise Exception(f"Decode PCM fallΓ³: {r_dec.stderr[-300:]}") |
|
|
| r_enc = subprocess.run( |
| ['ffmpeg','-hide_banner','-threads',str(N_THREADS), |
| '-i',str(wav_tmp),'-c:a','libmp3lame','-b:a','192k', |
| '-ar','48000','-ac','2','-compression_level','0', |
| '-max_muxing_queue_size','9999','-thread_queue_size','4096', |
| '-hls_time','5','-hls_list_size','0', |
| '-hls_segment_filename',str(sf), |
| '-hls_flags','independent_segments+append_list+temp_file', |
| '-hls_playlist_type','vod','-hls_segment_type','mpegts', |
| str(af),'-y','-loglevel','error'], |
| capture_output=True, text=True, timeout=7200) |
| wav_tmp.unlink(missing_ok=True) |
|
|
| if r_enc.returncode != 0 or not af.exists(): |
| raise Exception(f"Encode MP3 fallΓ³: {r_enc.stderr[-300:]}") |
|
|
| ts_files = list(tmp.glob(f"audio_{i}_*.ts")) |
| if not ts_files: raise Exception("Sin segmentos TS") |
|
|
| shutil.move(str(af), str(out_dir / f"audio_{i}.m3u8")) |
| for ts in ts_files: shutil.move(str(ts), str(out_dir / ts.name)) |
|
|
| return {'success': True, 'index': i, 'track': track, |
| 'segments_count': len(ts_files), |
| 'playlist': {'file': f"audio_{i}.m3u8", |
| 'language': track['language'], |
| 'title': track['title'], 'is_default': i == 0}} |
| except Exception as e: |
| return {'success': False, 'index': i, 'error': str(e), 'track': track} |
| finally: |
| shutil.rmtree(tmp, ignore_errors=True) |
|
|
| def process_video_copy(src, iargs, out_dir, tmp_v, vf, sf, log_cb): |
| hls = ['-hls_time','5','-hls_list_size','0','-hls_segment_filename',str(sf), |
| '-hls_flags','independent_segments+append_list+temp_file+split_by_time', |
| '-hls_playlist_type','vod','-hls_segment_type','mpegts',str(vf),'-y','-loglevel','error'] |
| base = ['ffmpeg','-hide_banner','-threads',str(N_THREADS)] + iargs + [ |
| '-i',src,'-map','0:v:0','-an', |
| '-max_muxing_queue_size','9999','-avoid_negative_ts','make_zero', |
| '-fflags','+genpts+igndts+flush_packets+discardcorrupt', |
| '-err_detect','ignore_err','-copytb','1','-start_at_zero','-thread_queue_size','4096'] |
|
|
| r1 = subprocess.run(base + ['-c:v','copy','-bsf:v','h264_mp4toannexb,dump_extra'] + hls, |
| capture_output=True, text=True, timeout=7200) |
| if r1.returncode == 0 and vf.exists() and list(tmp_v.glob("video_1080p_*.ts")): |
| log_cb(" β Video COPY OK (h264_mp4toannexb)"); return True |
|
|
| vf.unlink(missing_ok=True) |
| for f in tmp_v.glob("video_1080p_*.ts"): f.unlink(missing_ok=True) |
| log_cb(" β Copy con bsf fallΓ³, reintentando sin bsfβ¦") |
|
|
| r2 = subprocess.run(base + ['-c:v','copy'] + hls, |
| capture_output=True, text=True, timeout=7200) |
| if r2.returncode == 0 and vf.exists() and list(tmp_v.glob("video_1080p_*.ts")): |
| log_cb(" β Video COPY OK (sin bsf)"); return True |
|
|
| vf.unlink(missing_ok=True) |
| for f in tmp_v.glob("video_1080p_*.ts"): f.unlink(missing_ok=True) |
| log_cb(" β Copy fallΓ³, re-encode H.264 ultrafastβ¦") |
|
|
| hls2 = ['-hls_time','5','-hls_list_size','0','-hls_segment_filename',str(sf), |
| '-hls_flags','independent_segments+append_list+temp_file', |
| '-hls_playlist_type','vod','-hls_segment_type','mpegts',str(vf),'-y','-loglevel','error'] |
| r3 = subprocess.run( |
| ['ffmpeg','-hide_banner','-threads',str(N_THREADS)] + iargs + [ |
| '-i',src,'-map','0:v:0','-an','-c:v','libx264','-preset','ultrafast','-crf','23', |
| '-pix_fmt','yuv420p','-threads',str(N_THREADS), |
| '-max_muxing_queue_size','9999','-thread_queue_size','4096'] + hls2, |
| capture_output=True, text=True, timeout=14400) |
| if r3.returncode == 0 and vf.exists() and list(tmp_v.glob("video_1080p_*.ts")): |
| log_cb(" β Video re-encode H.264 OK"); return True |
| raise Exception(f"Video fallΓ³ en todos los modos: {r3.stderr[-400:]}") |
|
|
| def git_push_retry(gd, args, retries=3, timeout=600): |
| for attempt in range(retries): |
| try: |
| subprocess.run(['git','push'] + args, cwd=gd, check=True, |
| capture_output=True, timeout=timeout) |
| return True |
| except: |
| if attempt == retries-1: return False |
| time.sleep(3) |
| return False |
|
|
| def run_conversion(job, log_cb, progress_cb, done_cb): |
| """Hilo principal de conversiΓ³n""" |
| token = job['token'] |
| sources = job['sources'] |
| conv_opt = job['conv_opt'] |
| stream_fmt = job['stream_fmt'] |
| batch_size = job['batch_size'] |
| delete_local = job['delete_local'] |
| max_workers = job['max_workers'] |
| ctype = job['ctype'] |
| mname = job['mname'] |
| sname = job['sname'] |
| season = job['season'] |
| ep_start = job['ep_start'] |
|
|
| final_links = [] |
| try: |
| log_cb(f"π EXTREME v5.1 | Threads: {N_THREADS} | Temp: {RAMDISK}") |
|
|
| for idx, source in enumerate(sources): |
| src = source['value'] |
| folder_name, repo_name = build_name(ctype, mname, sname, season, ep_start, idx) |
| log_cb(f"\nπ¦ [{idx+1}/{len(sources)}] {folder_name}") |
| progress_cb(int(idx/len(sources)*100), f"[{idx+1}/{len(sources)}] {folder_name}") |
|
|
| out_dir = RAMDISK / "outputs" / folder_name |
| out_dir.mkdir(parents=True, exist_ok=True) |
|
|
| iargs = input_args(src) |
| dur = detect_duration(src, iargs) |
| if dur: |
| h, m, s2 = int(dur//3600), int((dur%3600)//60), int(dur%60) |
| log_cb(f" β± DuraciΓ³n: {h:02d}:{m:02d}:{s2:02d}") |
|
|
| audio_tracks = detect_audio(src, iargs) or [{'index':0,'language':'und','title':'Audio','codec':'unk'}] |
| audio_tracks = prioritize_audio(audio_tracks) |
| log_cb(f" π΅ {len(audio_tracks)} pista(s)") |
|
|
| manifest_file = "" |
|
|
| if stream_fmt == "HLS (M3U8)": |
| log_cb(f" π΅ Procesando {len(audio_tracks)} audio(s) β PCM β MP3") |
| aargs_list = [(t, i, len(audio_tracks), src, out_dir, iargs) for i, t in enumerate(audio_tracks)] |
| audio_playlists = [] |
| with ThreadPoolExecutor(max_workers=max_workers) as ex: |
| futures = {ex.submit(process_audio_track, a): a for a in aargs_list} |
| for fut in as_completed(futures): |
| res = fut.result() |
| if res['success']: |
| audio_playlists.append(res['playlist']) |
| log_cb(f" β Audio {res['index']+1}: {res['track']['title']} ({res['segments_count']} segs)") |
| else: |
| log_cb(f" β Audio {res['index']+1}: {res.get('error','')[:120]}") |
|
|
| audio_playlists.sort(key=lambda x: int(x['file'].split('_')[1].split('.')[0])) |
| if not audio_playlists: raise Exception("Sin audio procesado") |
|
|
| video_streams = [] |
| if "Copy" in conv_opt: |
| log_cb(" β‘ Video COPY β HLS") |
| tmp_v = RAMDISK / f"vid_{idx}" |
| tmp_v.mkdir(exist_ok=True) |
| vf = tmp_v / "video_1080p.m3u8" |
| sf = tmp_v / "video_1080p_%03d.ts" |
| process_video_copy(src, iargs, out_dir, tmp_v, vf, sf, log_cb) |
| final_1080 = out_dir / "video_1080p.m3u8" |
| shutil.move(str(vf), str(final_1080)) |
| for ts in tmp_v.glob("video_1080p_*.ts"): |
| shutil.move(str(ts), str(out_dir / ts.name)) |
| shutil.rmtree(tmp_v, ignore_errors=True) |
| (out_dir / "video_720p.m3u8").write_text(final_1080.read_text()) |
| video_streams = [ |
| {'file':'video_1080p.m3u8','resolution':'1920x1080','bandwidth':5000000,'codecs':'avc1.640028'}, |
| {'file':'video_720p.m3u8', 'resolution':'1280x720', 'bandwidth':3000000,'codecs':'avc1.640028'}, |
| ] |
| else: |
| rlist = ([{'label':'4K','scale':'scale=-2:2160','br':'15000k','bufsize':'30000k','res':'3840x2160'}, |
| {'label':'1080p','scale':'scale=-2:1080','br':'5000k','bufsize':'10000k','res':'1920x1080'}, |
| {'label':'720p','scale':'scale=-2:720','br':'2800k','bufsize':'5600k','res':'1280x720'}] |
| if "4K" in conv_opt else |
| [{'label':'1080p','scale':'scale=-2:1080','br':'5000k','bufsize':'10000k','res':'1920x1080'}, |
| {'label':'720p','scale':'scale=-2:720','br':'2800k','bufsize':'5600k','res':'1280x720'}]) |
| for rc in rlist: |
| log_cb(f" π Renderizando {rc['label']}β¦") |
| tmp_r = RAMDISK / f"render_{rc['label']}" |
| tmp_r.mkdir(exist_ok=True) |
| vf = tmp_r / f"video_{rc['label']}.m3u8" |
| sf = tmp_r / f"video_{rc['label']}_%03d.ts" |
| r = subprocess.run( |
| ['ffmpeg','-hide_banner','-threads',str(N_THREADS)] + iargs + [ |
| '-i',src,'-map','0:v:0','-an','-c:v','libx264', |
| '-preset','ultrafast','-crf','23','-vf',rc['scale'], |
| '-b:v',rc['br'],'-maxrate',rc['br'],'-bufsize',rc['bufsize'], |
| '-pix_fmt','yuv420p'] + render_args() + [ |
| '-hls_time','5','-hls_list_size','0', |
| '-hls_segment_filename',str(sf), |
| '-hls_flags','independent_segments+append_list+temp_file', |
| '-hls_playlist_type','vod','-hls_segment_type','mpegts', |
| str(vf),'-y','-loglevel','error'], |
| capture_output=True, text=True, timeout=14400) |
| if r.returncode != 0: |
| shutil.rmtree(tmp_r, ignore_errors=True) |
| log_cb(f" β Error {rc['label']}") |
| continue |
| shutil.move(str(vf), str(out_dir / f"video_{rc['label']}.m3u8")) |
| for ts in tmp_r.glob(f"video_{rc['label']}_*.ts"): |
| shutil.move(str(ts), str(out_dir / ts.name)) |
| shutil.rmtree(tmp_r, ignore_errors=True) |
| video_streams.append({'file':f"video_{rc['label']}.m3u8", |
| 'resolution':rc['res'], |
| 'bandwidth':int(rc['br'].replace('k','000'))+192000, |
| 'codecs':'avc1.640028'}) |
| log_cb(f" β {rc['label']} OK") |
|
|
| if not video_streams: raise Exception("Sin video generado") |
| make_master_m3u8(out_dir, video_streams, audio_playlists) |
| manifest_file = "master.m3u8" |
|
|
| elif stream_fmt == "DASH (MPD)": |
| log_cb(" π¬ Generando DASHβ¦") |
| tmp_d = RAMDISK / f"dash_{idx}" |
| tmp_d.mkdir(exist_ok=True) |
| cmd = ['ffmpeg','-hide_banner','-threads',str(N_THREADS)] + iargs + ['-i',src] |
| vc = "copy" if "Copy" in conv_opt else "libx264" |
| cmd += ['-map','0:v:0','-c:v:0',vc] |
| if vc != "copy": cmd += ['-preset','ultrafast','-crf','23'] |
| for i2, t2 in enumerate(audio_tracks): |
| cmd += ['-map',f"0:{t2['index']}",f'-c:a:{i2}','aac',f'-b:a:{i2}','192k', |
| f'-ar:a:{i2}','48000',f'-ac:a:{i2}','2'] |
| mpd_out = tmp_d / "manifest.mpd" |
| cmd += (render_args() if vc != "copy" else |
| ['-max_muxing_queue_size','9999','-copytb','1','-start_at_zero','-thread_queue_size','4096']) |
| cmd += ['-f','dash','-seg_duration','5','-use_template','1','-use_timeline','0', |
| '-init_seg_name','init-$RepresentationID$.m4s', |
| '-media_seg_name','chunk-$RepresentationID$-$Number%05d$.m4s', |
| str(mpd_out),'-y','-loglevel','error'] |
| r = subprocess.run(cmd, capture_output=True, text=True, timeout=14400) |
| if r.returncode != 0: |
| shutil.rmtree(tmp_d, ignore_errors=True) |
| raise Exception(f"DASH fallΓ³: {r.stderr[-400:]}") |
| shutil.move(str(mpd_out), str(out_dir / "manifest.mpd")) |
| for m4s in tmp_d.glob("*.m4s"): shutil.move(str(m4s), str(out_dir / m4s.name)) |
| shutil.rmtree(tmp_d, ignore_errors=True) |
| manifest_file = "manifest.mpd" |
| log_cb(" β DASH OK") |
|
|
| |
| log_cb(f" β Subiendo a GitHub: {repo_name}") |
| if not requests: |
| raise Exception("requests no instalado β pip install requests") |
| headers = {"Authorization": f"token {token}"} |
| rr = requests.post("https://api.github.com/user/repos", headers=headers, |
| json={"name": repo_name, "private": True}, timeout=30) |
| if rr.status_code == 422: |
| u = requests.get("https://api.github.com/user", headers=headers, timeout=30) |
| html_url = f"https://github.com/{u.json()['login']}/{repo_name}" |
| elif rr.status_code in [200, 201]: |
| html_url = rr.json()['html_url'] |
| else: |
| raise Exception(f"GitHub API {rr.status_code}: {rr.text[:200]}") |
|
|
| git_url = html_url.replace('https://', f'https://{token}@') + '.git' |
| gd = str(out_dir) |
|
|
| for gc in [['git','init'],['git','checkout','-b','main'], |
| ['git','remote','add','origin',git_url], |
| ['git','config','http.postBuffer','524288000'], |
| ['git','config','core.compression','0']]: |
| subprocess.run(gc, cwd=gd, check=True, capture_output=True) |
|
|
| all_files = os.listdir(gd) |
| ext_s = '.m4s' if stream_fmt == "DASH (MPD)" else '.ts' |
| ext_m = '.mpd' if stream_fmt == "DASH (MPD)" else '.m3u8' |
| segs = [f for f in all_files if f.endswith(ext_s)] |
| mans = [f for f in all_files if f.endswith(ext_m)] |
|
|
| subprocess.run(['git','add'] + mans, cwd=gd, check=True, capture_output=True) |
| subprocess.run(['git','commit','-m',f'init {folder_name}'], cwd=gd, check=True, capture_output=True) |
| git_push_retry(gd, ['-u','origin','main']) |
|
|
| log_cb(f" π¦ {len(segs)} segmentos β batch {batch_size}") |
| for i3 in range(0, len(segs), batch_size): |
| batch = segs[i3:i3+batch_size] |
| subprocess.run(['git','add']+batch, cwd=gd, check=True, capture_output=True) |
| subprocess.run(['git','commit','-m',f'segs {i3}-{i3+len(batch)}'], |
| cwd=gd, check=True, capture_output=True) |
| ok = git_push_retry(gd, ['origin','main']) |
| if ok: log_cb(f" π€ {min(i3+batch_size,len(segs))}/{len(segs)}") |
| else: log_cb(f" β Batch {i3} error") |
|
|
| gp = f"https://gooplay.xyz/gp/stream.php?repo={repo_name}&branch=main&file={manifest_file}" |
| gh = f"{html_url}/blob/main/{manifest_file}" |
| final_links.append(f"{folder_name}\nGooplay: {gp}\nGitHub: {gh}") |
| log_cb(f" β Completado: {folder_name}") |
|
|
| if delete_local: |
| shutil.rmtree(out_dir, ignore_errors=True) |
| log_cb(" β Archivos locales borrados") |
| else: |
| log_cb(f" βΉ Archivos en: {out_dir}") |
|
|
| result = "\n\n".join(final_links) |
| log_cb("\nπ TODOS COMPLETADOS\n" + "="*40 + "\n" + result) |
| done_cb(True, result) |
|
|
| except Exception as e: |
| import traceback |
| log_cb(f"\nβ ERROR: {e}\n{traceback.format_exc()}") |
| done_cb(False, str(e)) |
|
|
|
|
| |
| |
| |
| class AppHLS(tk.Tk): |
| def __init__(self): |
| super().__init__() |
| self.title("HLS/DASH Converter EXTREME") |
| self.geometry("1100x750") |
| self.minsize(900, 620) |
| self.configure(bg=BG) |
| self.resizable(True, True) |
| self._build() |
| self._center() |
|
|
| def _center(self): |
| self.update_idletasks() |
| w, h = self.winfo_width(), self.winfo_height() |
| sw, sh = self.winfo_screenwidth(), self.winfo_screenheight() |
| self.geometry(f"{w}x{h}+{(sw-w)//2}+{(sh-h)//2}") |
|
|
| def _style(self): |
| s = ttk.Style(self) |
| s.theme_use("clam") |
| s.configure(".", background=BG, foreground=FG, font=FM, |
| fieldbackground=BG2, borderwidth=0) |
| s.configure("TFrame", background=BG) |
| s.configure("TLabel", background=BG, foreground=FG) |
| s.configure("TEntry", fieldbackground=BG2, foreground=FG, |
| insertcolor=FG, borderwidth=1) |
| s.configure("TCombobox", fieldbackground=BG2, background=BG3, |
| foreground=FG, arrowcolor=FG2) |
| s.map("TCombobox", fieldbackground=[("readonly", BG2)], |
| foreground=[("readonly", FG)]) |
| s.configure("TCheckbutton", background=BG, foreground=FG2) |
| s.map("TCheckbutton", background=[("active", BG)]) |
| s.configure("TRadiobutton", background=BG, foreground=FG2) |
| s.map("TRadiobutton", background=[("active", BG)]) |
| s.configure("Horizontal.TProgressbar", |
| troughcolor=BG3, background=ACCENT, |
| borderwidth=0, thickness=6) |
|
|
| def _build(self): |
| self._style() |
|
|
| |
| hdr = tk.Frame(self, bg=BG, pady=8) |
| hdr.pack(fill="x", padx=20) |
| tk.Label(hdr, text="HLS/DASH CONVERTER EXTREME", bg=BG, fg=ACCENT, |
| font=("Consolas", 15, "bold")).pack(side="left") |
| tk.Label(hdr, text=f" Β· {N_THREADS} threads Β· {RAMDISK}", |
| bg=BG, fg=FG3, font=FS).pack(side="left") |
| self._lbl_status = tk.Label(hdr, text="β Listo", bg=BG, fg=GREEN, font=FS) |
| self._lbl_status.pack(side="right") |
|
|
| tk.Frame(self, bg=BORDER, height=1).pack(fill="x", padx=20) |
|
|
| body = tk.Frame(self, bg=BG) |
| body.pack(fill="both", expand=True, padx=20, pady=8) |
|
|
| |
| left = tk.Frame(body, bg=BG, width=340) |
| left.pack(side="left", fill="y", padx=(0, 10)) |
| left.pack_propagate(False) |
|
|
| self._section(left, "GITHUB TOKEN") |
| self._gh_token = self._entry_var(left, "ghp_β¦", show="*") |
|
|
| self._section(left, "FUENTES") |
| |
| f_files = tk.Frame(left, bg=BG) |
| f_files.pack(fill="x", pady=(0, 4)) |
| self._file_lbl = tk.Label(f_files, text="Sin archivos", bg=BG3, fg=FG3, |
| font=FS, anchor="w", padx=6, pady=3) |
| self._file_lbl.pack(side="left", fill="x", expand=True) |
| tk.Button(f_files, text="π Archivos", bg=BG3, fg=FG2, bd=0, |
| font=FS, cursor="hand2", command=self._browse_files, |
| padx=6, pady=3).pack(side="right") |
| self._files_list = [] |
|
|
| |
| tk.Label(left, text="URLs (una por lΓnea):", bg=BG, fg=FG2, font=FS).pack(anchor="w") |
| self._urls_txt = tk.Text(left, bg=BG2, fg=FG, insertbackground=FG, |
| font=FS, bd=0, relief="flat", height=5, wrap="none") |
| self._urls_txt.pack(fill="x", pady=(0, 6)) |
|
|
| self._section(left, "CONVERSIΓN") |
| self._conv_opt = ttk.Combobox(left, state="readonly", font=FS, height=6, |
| values=["OpciΓ³n 1: Copy Video", |
| "OpciΓ³n 2: Copy Video MP3", |
| "OpciΓ³n 3: 1080p+720p H.264", |
| "OpciΓ³n 4: 4K+1080p+720p H.264"]) |
| self._conv_opt.set("OpciΓ³n 1: Copy Video") |
| self._conv_opt.pack(fill="x", pady=(0, 4)) |
|
|
| self._stream_fmt = ttk.Combobox(left, state="readonly", font=FS, |
| values=["HLS (M3U8)", "DASH (MPD)"]) |
| self._stream_fmt.set("HLS (M3U8)") |
| self._stream_fmt.pack(fill="x", pady=(0, 6)) |
|
|
| f_nums = tk.Frame(left, bg=BG) |
| f_nums.pack(fill="x", pady=(0, 4)) |
| tk.Label(f_nums, text="Batch git:", bg=BG, fg=FG2, font=FS).pack(side="left") |
| self._batch_var = tk.StringVar(value="30") |
| tk.Entry(f_nums, textvariable=self._batch_var, bg=BG2, fg=FG, |
| insertbackground=FG, font=FS, bd=0, width=5, |
| relief="flat").pack(side="left", padx=4) |
| tk.Label(f_nums, text="Workers:", bg=BG, fg=FG2, font=FS).pack(side="left") |
| self._workers_var = tk.StringVar(value="4") |
| tk.Entry(f_nums, textvariable=self._workers_var, bg=BG2, fg=FG, |
| insertbackground=FG, font=FS, bd=0, width=4, |
| relief="flat").pack(side="left", padx=4) |
|
|
| self._del_local = tk.BooleanVar(value=True) |
| ttk.Checkbutton(left, text="Borrar archivos locales al terminar", |
| variable=self._del_local).pack(anchor="w") |
|
|
| self._section(left, "CONTENIDO") |
| self._ctype = tk.StringVar(value="Serie") |
| f_ct = tk.Frame(left, bg=BG) |
| f_ct.pack(fill="x") |
| for ct in ["PelΓcula", "Serie"]: |
| ttk.Radiobutton(f_ct, text=ct, variable=self._ctype, |
| value=ct, command=self._toggle_ctype).pack(side="left", padx=4) |
|
|
| self._movie_frame = tk.Frame(left, bg=BG) |
| tk.Label(self._movie_frame, text="Nombre:", bg=BG, fg=FG2, font=FS).pack(anchor="w") |
| self._mname = self._entry_var(self._movie_frame, "El Padrino") |
|
|
| self._serie_frame = tk.Frame(left, bg=BG) |
| tk.Label(self._serie_frame, text="Serie:", bg=BG, fg=FG2, font=FS).pack(anchor="w") |
| self._sname = self._entry_var(self._serie_frame, "Breaking Bad") |
| f_ss = tk.Frame(self._serie_frame, bg=BG) |
| f_ss.pack(fill="x") |
| tk.Label(f_ss, text="Temp:", bg=BG, fg=FG2, font=FS).pack(side="left") |
| self._season = tk.StringVar(value="1") |
| tk.Entry(f_ss, textvariable=self._season, bg=BG2, fg=FG, |
| insertbackground=FG, font=FS, bd=0, width=4, |
| relief="flat").pack(side="left", padx=4) |
| tk.Label(f_ss, text="Ep inicial:", bg=BG, fg=FG2, font=FS).pack(side="left") |
| self._ep_start = tk.StringVar(value="1") |
| tk.Entry(f_ss, textvariable=self._ep_start, bg=BG2, fg=FG, |
| insertbackground=FG, font=FS, bd=0, width=4, |
| relief="flat").pack(side="left", padx=4) |
| self._serie_frame.pack(fill="x", pady=(4, 0)) |
|
|
| |
| right = tk.Frame(body, bg=BG) |
| right.pack(side="right", fill="both", expand=True) |
|
|
| |
| self._lbl_prog = tk.Label(right, text="", bg=BG, fg=FG2, font=FS, anchor="w") |
| self._lbl_prog.pack(fill="x") |
| self._pbar = ttk.Progressbar(right, mode="determinate", |
| style="Horizontal.TProgressbar") |
| self._pbar.pack(fill="x", pady=(2, 6)) |
|
|
| |
| tk.Label(right, text="LOG DE PROCESAMIENTO", bg=BG, fg=FG3, |
| font=("Consolas", 8, "bold")).pack(anchor="w") |
| log_f = tk.Frame(right, bg=BORDER) |
| log_f.pack(fill="both", expand=True, pady=(2, 6)) |
| self._log_txt = tk.Text( |
| log_f, bg="#030810", fg=CYAN, font=("Consolas", 9), |
| bd=0, relief="flat", state="disabled", wrap="word", |
| insertbackground=FG, selectbackground=ACCENT2 |
| ) |
| sb = ttk.Scrollbar(log_f, command=self._log_txt.yview) |
| self._log_txt.configure(yscrollcommand=sb.set) |
| sb.pack(side="right", fill="y") |
| self._log_txt.pack(fill="both", expand=True, padx=1, pady=1) |
|
|
| |
| tk.Label(right, text="LINKS GENERADOS", bg=BG, fg=FG3, |
| font=("Consolas", 8, "bold")).pack(anchor="w") |
| lnk_f = tk.Frame(right, bg=BORDER) |
| lnk_f.pack(fill="x", pady=(2, 6)) |
| self._links_txt = tk.Text( |
| lnk_f, bg="#020c08", fg=GREEN, font=("Consolas", 9), |
| bd=0, relief="flat", state="disabled", height=6, |
| insertbackground=FG |
| ) |
| lsb = ttk.Scrollbar(lnk_f, command=self._links_txt.yview) |
| self._links_txt.configure(yscrollcommand=lsb.set) |
| lsb.pack(side="right", fill="y") |
| self._links_txt.pack(fill="x", padx=1, pady=1) |
|
|
| |
| bf = tk.Frame(right, bg=BG) |
| bf.pack(fill="x") |
| self._btn_start = tk.Button( |
| bf, text="π INICIAR CONVERSIΓN", |
| bg=ACCENT, fg="white", bd=0, padx=16, pady=10, |
| font=("Consolas", 12, "bold"), cursor="hand2", |
| command=self._do_start |
| ) |
| self._btn_start.pack(side="left", fill="x", expand=True) |
| tk.Button( |
| bf, text="β", bg=BG3, fg=RED, bd=0, |
| padx=14, pady=10, font=FB, cursor="hand2", |
| command=self._do_cancel |
| ).pack(side="right", padx=(6, 0)) |
|
|
| self._cancelled = False |
|
|
| |
| def _section(self, parent, text): |
| f = tk.Frame(parent, bg=BG) |
| f.pack(fill="x", pady=(10, 2)) |
| tk.Label(f, text=text, bg=BG, fg=FG3, |
| font=("Consolas", 8, "bold")).pack(side="left") |
| tk.Frame(f, bg=BORDER, height=1).pack(side="right", fill="x", |
| expand=True, padx=(6, 0), pady=4) |
|
|
| def _entry_var(self, parent, placeholder, show=None): |
| v = tk.StringVar() |
| kw = {"show": show} if show else {} |
| tk.Entry(parent, textvariable=v, bg=BG2, fg=FG2, |
| insertbackground=FG, font=FS, bd=0, relief="flat", |
| **kw).pack(fill="x", ipady=5, pady=(0, 4)) |
| return v |
|
|
| def _toggle_ctype(self): |
| if self._ctype.get() == "PelΓcula": |
| self._serie_frame.pack_forget() |
| self._movie_frame.pack(fill="x", pady=(4, 0)) |
| else: |
| self._movie_frame.pack_forget() |
| self._serie_frame.pack(fill="x", pady=(4, 0)) |
|
|
| def _browse_files(self): |
| files = filedialog.askopenfilenames( |
| filetypes=[("Video", "*.mp4 *.mkv *.avi *.mov *.ts *.m2ts *.webm"), |
| ("Todos", "*.*")] |
| ) |
| if files: |
| self._files_list = list(files) |
| names = ", ".join(Path(f).name for f in files) |
| self._file_lbl.configure( |
| text=names[:60] + ("β¦" if len(names) > 60 else ""), fg=FG2 |
| ) |
|
|
| def _log(self, msg): |
| self._log_txt.configure(state="normal") |
| self._log_txt.insert("end", msg + "\n") |
| self._log_txt.see("end") |
| self._log_txt.configure(state="disabled") |
|
|
| def _set_progress(self, pct, label=""): |
| self._pbar["value"] = pct |
| self._lbl_prog.configure(text=label) |
| self.update_idletasks() |
|
|
| def _set_links(self, text): |
| self._links_txt.configure(state="normal") |
| self._links_txt.delete("1.0", "end") |
| self._links_txt.insert("1.0", text) |
| self._links_txt.configure(state="disabled") |
|
|
| |
| def _do_start(self): |
| token = self._gh_token.get().strip() |
| if not token: |
| messagebox.showwarning("Token", "IngresΓ‘ tu token de GitHub") |
| return |
|
|
| sources = [] |
| for f in self._files_list: |
| sources.append({"type": "file", "value": f}) |
| for line in self._urls_txt.get("1.0", "end").strip().split("\n"): |
| u = line.strip() |
| if u: sources.append({"type": "url", "value": u}) |
|
|
| if not sources: |
| messagebox.showwarning("Fuente", "AgregΓ‘ archivos o URLs") |
| return |
|
|
| self._btn_start.configure(state="disabled", bg=FG3) |
| self._lbl_status.configure(text="β Procesandoβ¦", fg=YELLOW) |
| self._log_txt.configure(state="normal") |
| self._log_txt.delete("1.0", "end") |
| self._log_txt.configure(state="disabled") |
| self._pbar["value"] = 0 |
| self._cancelled = False |
|
|
| try: |
| batch_size = int(self._batch_var.get() or 30) |
| max_workers = int(self._workers_var.get() or 4) |
| season = int(self._season.get() or 1) |
| ep_start = int(self._ep_start.get() or 1) |
| except: |
| batch_size, max_workers, season, ep_start = 30, 4, 1, 1 |
|
|
| job = { |
| 'token': token, 'sources': sources, |
| 'conv_opt': self._conv_opt.get(), |
| 'stream_fmt': self._stream_fmt.get(), |
| 'batch_size': batch_size, |
| 'delete_local': self._del_local.get(), |
| 'max_workers': max_workers, |
| 'ctype': self._ctype.get(), |
| 'mname': self._mname.get().strip(), |
| 'sname': self._sname.get().strip(), |
| 'season': season, 'ep_start': ep_start, |
| } |
|
|
| def _done(ok, result): |
| self.after(0, self._btn_start.configure, {"state": "normal", "bg": ACCENT}) |
| if ok: |
| self.after(0, self._lbl_status.configure, {"text": "β Completado", "fg": GREEN}) |
| self.after(0, self._set_links, result) |
| self.after(0, self._set_progress, 100, "Completado") |
| else: |
| self.after(0, self._lbl_status.configure, {"text": "β Error", "fg": RED}) |
|
|
| threading.Thread( |
| target=run_conversion, |
| args=(job, |
| lambda m: self.after(0, self._log, m), |
| lambda p, l: self.after(0, self._set_progress, p, l), |
| _done), |
| daemon=True |
| ).start() |
|
|
| def _do_cancel(self): |
| self._cancelled = True |
| self._lbl_status.configure(text="β Cancelado", fg=RED) |
| self._log("β Cancelado por usuario") |
| self._btn_start.configure(state="normal", bg=ACCENT) |
|
|
|
|
| if __name__ == "__main__": |
| app = AppHLS() |
| app.mainloop() |
|
|