CineMax commited on
Commit
82f3097
·
verified ·
1 Parent(s): 814dccf

Upload 3 files

Browse files
Files changed (3) hide show
  1. app.py +742 -0
  2. packages.txt +2 -0
  3. requirements.txt +3 -0
app.py ADDED
@@ -0,0 +1,742 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import subprocess
3
+ import os
4
+ import json
5
+ import re
6
+ import shutil
7
+ from pathlib import Path
8
+ from urllib.parse import urlparse, unquote
9
+ from concurrent.futures import ThreadPoolExecutor, as_completed
10
+ import tempfile
11
+
12
+ try:
13
+ import requests
14
+ except ImportError:
15
+ print("Error: Falta instalar 'requests'")
16
+
17
+ # === CONFIGURACIÓN DE RAM DISK Y CPU ===
18
+ def setup_ramdisk():
19
+ """
20
+ Usa /dev/shm (tmpfs nativo) para procesamiento ultra-rápido.
21
+ """
22
+ try:
23
+ ramdisk_path = Path("/dev/shm/video_processing")
24
+ ramdisk_path.mkdir(exist_ok=True, parents=True)
25
+ print(f"✅ RAM Disk configurado: {ramdisk_path}")
26
+ return ramdisk_path
27
+ except Exception as e:
28
+ print(f"⚠️ Error configurando RAM disk: {e}, usando /tmp")
29
+ tmp_path = Path("/tmp/video_processing")
30
+ tmp_path.mkdir(exist_ok=True)
31
+ return tmp_path
32
+
33
+ def get_optimal_threads():
34
+ """Retorna número óptimo de threads (99% de CPU)"""
35
+ try:
36
+ cpu_count = len(os.sched_getaffinity(0))
37
+ except:
38
+ cpu_count = os.cpu_count() or 4
39
+ return max(cpu_count - 1, 1)
40
+
41
+ # Configuración global
42
+ RAMDISK_PATH = setup_ramdisk()
43
+ OPTIMAL_THREADS = get_optimal_threads()
44
+
45
+ print(f"🔥 CPU Threads: {OPTIMAL_THREADS}")
46
+ print(f"💾 RAM Disk: {RAMDISK_PATH}")
47
+
48
+ # --- Configuración Global Git ---
49
+ subprocess.run(["git", "config", "--global", "user.email", "actions@github.com"], check=False, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
50
+ subprocess.run(["git", "config", "--global", "user.name", "Hugging Face Space"], check=False, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
51
+ subprocess.run(["git", "config", "--global", "core.compression", "0"], check=False, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
52
+ subprocess.run(["git", "config", "--global", "pack.threads", str(OPTIMAL_THREADS)], check=False, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
53
+
54
+ # --- Funciones Auxiliares ---
55
+
56
+ def get_input_args(source_path):
57
+ """Argumentos FFmpeg optimizados para URLs y archivos"""
58
+ if source_path.startswith('http://') or source_path.startswith('https://'):
59
+ user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
60
+ return [
61
+ '-user_agent', user_agent,
62
+ '-timeout', '10000000',
63
+ '-reconnect', '1',
64
+ '-reconnect_streamed', '1',
65
+ '-reconnect_delay_max', '5',
66
+ '-multiple_requests', '1',
67
+ '-fflags', '+fastseek+genpts',
68
+ '-probesize', '10M',
69
+ '-analyzeduration', '5M'
70
+ ]
71
+ else:
72
+ return [
73
+ '-fflags', '+fastseek+genpts',
74
+ '-probesize', '10M',
75
+ '-analyzeduration', '5M'
76
+ ]
77
+
78
+ def get_copy_optimization_args():
79
+ """Argumentos FFmpeg para COPY usando 99% recursos"""
80
+ return [
81
+ '-max_muxing_queue_size', '9999',
82
+ '-avoid_negative_ts', 'make_zero',
83
+ '-fflags', '+genpts+igndts+flush_packets',
84
+ '-copytb', '1',
85
+ '-start_at_zero',
86
+ '-threads', str(OPTIMAL_THREADS),
87
+ '-thread_queue_size', '4096',
88
+ ]
89
+
90
+ def get_render_optimization_args():
91
+ """Argumentos FFmpeg para RENDER H.264 usando 99% CPU"""
92
+ return [
93
+ '-threads', str(OPTIMAL_THREADS),
94
+ '-thread_type', 'slice+frame',
95
+ '-slices', str(OPTIMAL_THREADS),
96
+ '-max_muxing_queue_size', '9999',
97
+ '-thread_queue_size', '4096',
98
+ ]
99
+
100
+ def clean_for_folder(name):
101
+ return re.sub(r'[<>:"/\\|?*]', '_', name).strip()[:200]
102
+
103
+ def clean_for_repo(name):
104
+ name = re.sub(r'[^a-zA-Z0-9_-]', '-', name)
105
+ return re.sub(r'-+', '-', name).strip('-')[:100]
106
+
107
+ def get_filename_from_url(url):
108
+ try:
109
+ parsed = urlparse(url)
110
+ path = unquote(parsed.path)
111
+ basename = os.path.basename(path)
112
+ if basename and '.' in basename:
113
+ return Path(basename).stem
114
+ except:
115
+ pass
116
+ return "video"
117
+
118
+ def log_generator(message, log_list):
119
+ log_list.append(message)
120
+ return "\n".join(log_list), log_list
121
+
122
+ def detect_audio_streams(source_val):
123
+ """Detecta todos los streams de audio"""
124
+ input_args = get_input_args(source_val)
125
+
126
+ cmd_probe = [
127
+ 'ffprobe', '-v', 'error'
128
+ ] + input_args + [
129
+ '-select_streams', 'a',
130
+ '-show_entries', 'stream=index,codec_name:stream_tags=language,title',
131
+ '-of', 'json',
132
+ '-i', source_val
133
+ ]
134
+
135
+ try:
136
+ res = subprocess.run(cmd_probe, capture_output=True, text=True, timeout=60)
137
+ data = json.loads(res.stdout)
138
+ streams = data.get('streams', [])
139
+
140
+ audio_tracks = []
141
+ for stream in streams:
142
+ index = stream.get('index', 0)
143
+ tags = stream.get('tags', {})
144
+ language = tags.get('language', 'und')
145
+ title = tags.get('title', f'Audio {index}')
146
+ codec = stream.get('codec_name', 'unknown')
147
+
148
+ audio_tracks.append({
149
+ 'index': index,
150
+ 'language': language.lower(),
151
+ 'title': title,
152
+ 'codec': codec
153
+ })
154
+
155
+ return audio_tracks
156
+ except Exception as e:
157
+ print(f"Error detectando audio: {e}")
158
+ return []
159
+
160
+ def prioritize_audio_tracks(tracks):
161
+ """Ordena los tracks priorizando español/latino"""
162
+ priority_langs = ['spa', 'es', 'spanish', 'español', 'latino', 'lat', 'es-mx', 'es-419']
163
+
164
+ def get_priority(track):
165
+ lang = track['language'].lower()
166
+ title = track['title'].lower()
167
+
168
+ for term in priority_langs:
169
+ if term in lang or term in title:
170
+ return 0
171
+
172
+ if lang == 'und':
173
+ return 1
174
+
175
+ return 2
176
+
177
+ return sorted(tracks, key=get_priority)
178
+
179
+ def create_master_m3u8(output_dir, video_streams, audio_playlists):
180
+ """Crea Master Playlist M3U8 versión 7"""
181
+ master_content = "#EXTM3U\n#EXT-X-VERSION:7\n\n"
182
+
183
+ for i, audio_info in enumerate(audio_playlists):
184
+ default = "YES" if audio_info['is_default'] else "NO"
185
+ autoselect = "YES" if audio_info['is_default'] else "NO"
186
+
187
+ master_content += f'#EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID="audio",NAME="{audio_info["title"]}",LANGUAGE="{audio_info["language"]}",DEFAULT={default},AUTOSELECT={autoselect},URI="{audio_info["file"]}"\n'
188
+
189
+ master_content += "\n"
190
+
191
+ for vid in video_streams:
192
+ master_content += f'#EXT-X-STREAM-INF:BANDWIDTH={vid["bandwidth"]},RESOLUTION={vid["resolution"]},CODECS="{vid["codecs"]}",AUDIO="audio"\n{vid["file"]}\n'
193
+
194
+ with open(output_dir / "master.m3u8", "w") as f:
195
+ f.write(master_content)
196
+
197
+ def process_audio_track_parallel(args):
198
+ """Procesa un track de audio en paralelo usando RAM DISK"""
199
+ track, i, total, source_val, output_dir, is_copy_mode, ffmpeg_input_args = args
200
+
201
+ try:
202
+ # Usar RAM disk
203
+ temp_dir = RAMDISK_PATH / f"audio_temp_{os.getpid()}_{i}"
204
+ temp_dir.mkdir(exist_ok=True)
205
+
206
+ audio_file = temp_dir / f"audio_{i}.m3u8"
207
+ seg_audio = temp_dir / f"audio_{i}_%03d.ts"
208
+
209
+ if is_copy_mode:
210
+ audio_params = ['-c:a', 'copy']
211
+ extra_args = get_copy_optimization_args()
212
+ else:
213
+ audio_params = [
214
+ '-c:a', 'libmp3lame',
215
+ '-b:a', '192k',
216
+ '-ar', '48000',
217
+ '-compression_level', '0',
218
+ ]
219
+ extra_args = [
220
+ '-threads', str(OPTIMAL_THREADS),
221
+ '-max_muxing_queue_size', '9999',
222
+ '-thread_queue_size', '4096',
223
+ ]
224
+
225
+ cmd_audio = [
226
+ 'ffmpeg', '-hide_banner',
227
+ '-threads', str(OPTIMAL_THREADS)
228
+ ] + ffmpeg_input_args + [
229
+ '-i', source_val,
230
+ '-map', f"0:{track['index']}"
231
+ ] + audio_params + extra_args + [
232
+ '-hls_time', '10',
233
+ '-hls_list_size', '0',
234
+ '-hls_segment_filename', str(seg_audio),
235
+ '-hls_flags', 'independent_segments+omit_endlist+temp_file',
236
+ '-hls_segment_type', 'mpegts',
237
+ str(audio_file),
238
+ '-y',
239
+ '-loglevel', 'error'
240
+ ]
241
+
242
+ result = subprocess.run(cmd_audio, capture_output=True, text=True, timeout=3600)
243
+
244
+ if result.returncode != 0:
245
+ shutil.rmtree(temp_dir, ignore_errors=True)
246
+ return {'success': False, 'index': i, 'error': result.stderr[-500:], 'track': track}
247
+
248
+ # Mover de RAM disk a output_dir
249
+ final_audio = output_dir / f"audio_{i}.m3u8"
250
+ shutil.move(str(audio_file), str(final_audio))
251
+
252
+ for ts_file in temp_dir.glob(f"audio_{i}_*.ts"):
253
+ shutil.move(str(ts_file), str(output_dir / ts_file.name))
254
+
255
+ shutil.rmtree(temp_dir, ignore_errors=True)
256
+
257
+ return {
258
+ 'success': True,
259
+ 'index': i,
260
+ 'track': track,
261
+ 'playlist': {
262
+ 'file': f"audio_{i}.m3u8",
263
+ 'language': track['language'],
264
+ 'title': track['title'],
265
+ 'is_default': i == 0
266
+ }
267
+ }
268
+
269
+ except Exception as e:
270
+ shutil.rmtree(temp_dir, ignore_errors=True)
271
+ return {'success': False, 'index': i, 'error': str(e), 'track': track}
272
+
273
+ # --- Lógica de Procesamiento ---
274
+
275
+ def process_bulk(
276
+ token, input_file, input_urls, conversion_option, stream_format, batch_size_vid, delete_local, max_workers,
277
+ progress=gr.Progress()
278
+ ):
279
+ logs = [f"🚀 Iniciando EXTREME v4.0 (CPU: {OPTIMAL_THREADS} threads, RAM Disk: {RAMDISK_PATH})"]
280
+
281
+ try:
282
+ if not token:
283
+ raise Exception("❌ Se requiere un Token de GitHub válido.")
284
+
285
+ sources = []
286
+ files_list = []
287
+
288
+ if input_file:
289
+ if isinstance(input_file, list):
290
+ files_list = input_file
291
+ else:
292
+ files_list = [input_file]
293
+
294
+ for f in files_list:
295
+ sources.append({"type": "file", "value": f.name})
296
+
297
+ if input_urls:
298
+ for line in input_urls.split('\n'):
299
+ url = line.strip()
300
+ if url:
301
+ sources.append({"type": "url", "value": url})
302
+
303
+ if not sources:
304
+ raise Exception("⚠️ Agrega archivos o URLs para procesar.")
305
+
306
+ total_sources = len(sources)
307
+ progress(0, desc="Iniciando conversión")
308
+
309
+ final_links = []
310
+
311
+ for idx, source in enumerate(sources):
312
+ is_file = source['type'] == 'file'
313
+ source_val = source['value']
314
+
315
+ msg, logs = log_generator(f"📦 Procesando {idx+1}/{total_sources}: {os.path.basename(source_val) if is_file else source_val}", logs)
316
+ yield msg, logs, ""
317
+
318
+ ffmpeg_input_args = get_input_args(source_val)
319
+
320
+ if is_file:
321
+ base_name = Path(source_val).stem
322
+ base_dir = Path(source_val).parent
323
+ else:
324
+ base_name = get_filename_from_url(source_val)
325
+ base_dir = Path.cwd()
326
+
327
+ folder_name = clean_for_folder(base_name) + f"_{stream_format.lower()}"
328
+ repo_name = clean_for_repo(base_name)
329
+ output_dir = base_dir / folder_name
330
+ output_dir.mkdir(exist_ok=True)
331
+
332
+ msg, logs = log_generator(f"📂 Output: {output_dir}", logs)
333
+ yield msg, logs, ""
334
+
335
+ msg, logs = log_generator("🔍 Detectando streams de audio...", logs)
336
+ yield msg, logs, ""
337
+
338
+ audio_tracks = detect_audio_streams(source_val)
339
+
340
+ if not audio_tracks:
341
+ msg, logs = log_generator("⚠️ No se detectaron streams, usando track 0", logs)
342
+ yield msg, logs, ""
343
+ audio_tracks = [{'index': 0, 'language': 'und', 'title': 'Audio', 'codec': 'unknown'}]
344
+
345
+ audio_tracks = prioritize_audio_tracks(audio_tracks)
346
+
347
+ msg, logs = log_generator(f"🎵 {len(audio_tracks)} streams detectados", logs)
348
+ yield msg, logs, ""
349
+
350
+ manifest_file = ""
351
+ is_copy_mode = (conversion_option == "Opción 1: Copy Video + Copy Audio")
352
+
353
+ # HLS
354
+ if stream_format == "HLS (M3U8)":
355
+ msg, logs = log_generator(f"🎵 Procesando {len(audio_tracks)} audios EN PARALELO (RAM)...", logs)
356
+ yield msg, logs, ""
357
+
358
+ audio_args = [
359
+ (track, i, len(audio_tracks), source_val, output_dir, is_copy_mode, ffmpeg_input_args)
360
+ for i, track in enumerate(audio_tracks)
361
+ ]
362
+
363
+ audio_playlists = []
364
+
365
+ with ThreadPoolExecutor(max_workers=max_workers) as executor:
366
+ futures = {executor.submit(process_audio_track_parallel, arg): arg for arg in audio_args}
367
+
368
+ for future in as_completed(futures):
369
+ result = future.result()
370
+
371
+ if result['success']:
372
+ audio_playlists.append(result['playlist'])
373
+ msg, logs = log_generator(f" ✅ Audio {result['index']+1}: {result['track']['title']}", logs)
374
+ yield msg, logs, ""
375
+ else:
376
+ msg, logs = log_generator(f" ⚠️ Error Audio {result['index']+1}", logs)
377
+ yield msg, logs, ""
378
+
379
+ audio_playlists.sort(key=lambda x: int(x['file'].split('_')[1].split('.')[0]))
380
+
381
+ if not audio_playlists:
382
+ raise Exception("No se pudo procesar ningún audio")
383
+
384
+ video_streams = []
385
+
386
+ # COPY MODE
387
+ if conversion_option in ["Opción 1: Copy Video + Copy Audio", "Opción 2: Copy Video + MP3 Audio"]:
388
+ msg, logs = log_generator("⚡ COPY Video en RAM (ULTRA RÁPIDO)...", logs)
389
+ yield msg, logs, ""
390
+
391
+ temp_video_dir = RAMDISK_PATH / f"video_temp_{idx}"
392
+ temp_video_dir.mkdir(exist_ok=True)
393
+
394
+ video_file_1080 = temp_video_dir / "video_1080p.m3u8"
395
+ seg_video_1080 = temp_video_dir / "video_1080p_%03d.ts"
396
+
397
+ copy_args = get_copy_optimization_args()
398
+
399
+ cmd_video = [
400
+ 'ffmpeg', '-hide_banner',
401
+ '-threads', str(OPTIMAL_THREADS)
402
+ ] + ffmpeg_input_args + [
403
+ '-i', source_val,
404
+ '-map', '0:v:0',
405
+ '-c:v', 'copy',
406
+ '-an',
407
+ ] + copy_args + [
408
+ '-hls_time', '10',
409
+ '-hls_list_size', '0',
410
+ '-hls_segment_filename', str(seg_video_1080),
411
+ '-hls_flags', 'independent_segments+omit_endlist+temp_file',
412
+ '-hls_segment_type', 'mpegts',
413
+ str(video_file_1080),
414
+ '-y',
415
+ '-loglevel', 'error'
416
+ ]
417
+
418
+ result = subprocess.run(cmd_video, capture_output=True, text=True, timeout=3600)
419
+
420
+ if result.returncode != 0:
421
+ shutil.rmtree(temp_video_dir, ignore_errors=True)
422
+ raise Exception(f"FFmpeg copy falló: {result.stderr[-500:]}")
423
+
424
+ final_1080 = output_dir / "video_1080p.m3u8"
425
+ shutil.move(str(video_file_1080), str(final_1080))
426
+
427
+ for ts_file in temp_video_dir.glob("video_1080p_*.ts"):
428
+ shutil.move(str(ts_file), str(output_dir / ts_file.name))
429
+
430
+ # Hardlinks
431
+ video_file_720 = output_dir / "video_720p.m3u8"
432
+ shutil.copy(final_1080, video_file_720)
433
+
434
+ for ts_file in output_dir.glob("video_1080p_*.ts"):
435
+ new_name = ts_file.name.replace("1080p", "720p")
436
+ try:
437
+ os.link(ts_file, output_dir / new_name)
438
+ except:
439
+ shutil.copy(ts_file, output_dir / new_name)
440
+
441
+ shutil.rmtree(temp_video_dir, ignore_errors=True)
442
+
443
+ video_streams.append({'file': 'video_1080p.m3u8', 'resolution': '1920x1080', 'bandwidth': 5000000, 'codecs': 'avc1.640028'})
444
+ video_streams.append({'file': 'video_720p.m3u8', 'resolution': '1280x720', 'bandwidth': 3000000, 'codecs': 'avc1.640028'})
445
+
446
+ msg, logs = log_generator("✅ Video COPY completado (RAM + hardlinks)", logs)
447
+ yield msg, logs, ""
448
+
449
+ # RENDER MODE
450
+ elif conversion_option in ["Opción 3: Multi-Res (1080p + 720p) H.264", "Opción 4: Multi-Res (4K + 1080p + 720p) H.264"]:
451
+
452
+ if conversion_option == "Opción 3: Multi-Res (1080p + 720p) H.264":
453
+ resolutions = [
454
+ {'label': '1080p', 'scale': 'scale=-2:1080', 'bitrate': '5000k', 'bufsize': '10000k', 'res': '1920x1080'},
455
+ {'label': '720p', 'scale': 'scale=-2:720', 'bitrate': '2800k', 'bufsize': '5600k', 'res': '1280x720'}
456
+ ]
457
+ else:
458
+ resolutions = [
459
+ {'label': '4K', 'scale': 'scale=-2:2160', 'bitrate': '15000k', 'bufsize': '30000k', 'res': '3840x2160'},
460
+ {'label': '1080p', 'scale': 'scale=-2:1080', 'bitrate': '5000k', 'bufsize': '10000k', 'res': '1920x1080'},
461
+ {'label': '720p', 'scale': 'scale=-2:720', 'bitrate': '2800k', 'bufsize': '5600k', 'res': '1280x720'}
462
+ ]
463
+
464
+ msg, logs = log_generator(f"🎬 Renderizando {len(resolutions)} resoluciones EN PARALELO (RAM)...", logs)
465
+ yield msg, logs, ""
466
+
467
+ # Renderizar cada resolución (secuencial por limitaciones de RAM)
468
+ for res_config in resolutions:
469
+ msg, logs = log_generator(f" 🔄 {res_config['label']}...", logs)
470
+ yield msg, logs, ""
471
+
472
+ temp_dir = RAMDISK_PATH / f"render_{res_config['label']}"
473
+ temp_dir.mkdir(exist_ok=True)
474
+
475
+ video_file = temp_dir / f"video_{res_config['label']}.m3u8"
476
+ seg_video = temp_dir / f"video_{res_config['label']}_%03d.ts"
477
+
478
+ render_args = get_render_optimization_args()
479
+
480
+ cmd_video = [
481
+ 'ffmpeg', '-hide_banner',
482
+ '-threads', str(OPTIMAL_THREADS)
483
+ ] + ffmpeg_input_args + [
484
+ '-i', source_val,
485
+ '-map', '0:v:0', '-an',
486
+ '-c:v', 'libx264',
487
+ '-preset', 'ultrafast',
488
+ '-crf', '23',
489
+ '-vf', res_config['scale'],
490
+ '-b:v', res_config['bitrate'],
491
+ '-maxrate', res_config['bitrate'],
492
+ '-bufsize', res_config['bufsize'],
493
+ '-pix_fmt', 'yuv420p',
494
+ ] + render_args + [
495
+ '-hls_time', '10',
496
+ '-hls_list_size', '0',
497
+ '-hls_segment_filename', str(seg_video),
498
+ '-hls_flags', 'independent_segments+omit_endlist+temp_file',
499
+ '-hls_segment_type', 'mpegts',
500
+ str(video_file),
501
+ '-y',
502
+ '-loglevel', 'error'
503
+ ]
504
+
505
+ result = subprocess.run(cmd_video, capture_output=True, text=True, timeout=7200)
506
+
507
+ if result.returncode != 0:
508
+ shutil.rmtree(temp_dir, ignore_errors=True)
509
+ msg, logs = log_generator(f" ⚠️ Error en {res_config['label']}", logs)
510
+ yield msg, logs, ""
511
+ continue
512
+
513
+ final_m3u8 = output_dir / f"video_{res_config['label']}.m3u8"
514
+ shutil.move(str(video_file), str(final_m3u8))
515
+
516
+ for ts_file in temp_dir.glob(f"video_{res_config['label']}_*.ts"):
517
+ shutil.move(str(ts_file), str(output_dir / ts_file.name))
518
+
519
+ shutil.rmtree(temp_dir, ignore_errors=True)
520
+
521
+ video_streams.append({
522
+ 'file': f"video_{res_config['label']}.m3u8",
523
+ 'resolution': res_config['res'],
524
+ 'bandwidth': int(res_config['bitrate'].replace('k', '000')) + 192000,
525
+ 'codecs': 'avc1.640028'
526
+ })
527
+
528
+ msg, logs = log_generator(f" ✅ {res_config['label']} OK", logs)
529
+ yield msg, logs, ""
530
+
531
+ if not video_streams:
532
+ raise Exception("No se generó video")
533
+
534
+ create_master_m3u8(output_dir, video_streams, audio_playlists)
535
+ manifest_file = "master.m3u8"
536
+
537
+ # DASH
538
+ elif stream_format == "DASH (MPD)":
539
+ msg, logs = log_generator("🎬 Generando DASH en RAM...", logs)
540
+ yield msg, logs, ""
541
+
542
+ temp_dash_dir = RAMDISK_PATH / f"dash_{idx}"
543
+ temp_dash_dir.mkdir(exist_ok=True)
544
+
545
+ cmd = ['ffmpeg', '-hide_banner', '-threads', str(OPTIMAL_THREADS)] + ffmpeg_input_args
546
+ cmd.extend(['-i', source_val])
547
+
548
+ audio_codec = 'copy' if is_copy_mode else 'aac'
549
+ video_codec = 'copy' if is_copy_mode else 'libx264'
550
+
551
+ extra_args = get_copy_optimization_args() if is_copy_mode else get_render_optimization_args()
552
+
553
+ if is_copy_mode:
554
+ cmd.extend(['-map', '0:v:0', '-c:v:0', video_codec])
555
+ else:
556
+ if conversion_option == "Opción 3: Multi-Res (1080p + 720p) H.264":
557
+ res_list = [
558
+ {'idx': 0, 'scale': 'scale=-2:1080', 'br': '5000k'},
559
+ {'idx': 1, 'scale': 'scale=-2:720', 'br': '2800k'}
560
+ ]
561
+ elif conversion_option == "Opción 4: Multi-Res (4K + 1080p + 720p) H.264":
562
+ res_list = [
563
+ {'idx': 0, 'scale': 'scale=-2:2160', 'br': '15000k'},
564
+ {'idx': 1, 'scale': 'scale=-2:1080', 'br': '5000k'},
565
+ {'idx': 2, 'scale': 'scale=-2:720', 'br': '2800k'}
566
+ ]
567
+ else:
568
+ res_list = []
569
+ cmd.extend(['-map', '0:v:0', '-c:v:0', 'copy'])
570
+
571
+ for r in res_list:
572
+ cmd.extend(['-map', '0:v:0'])
573
+ cmd.extend([f'-c:v:{r["idx"]}', video_codec, '-preset', 'ultrafast', '-crf', '23'])
574
+ cmd.extend([f'-vf:v:{r["idx"]}', r['scale']])
575
+ cmd.extend([f'-b:v:{r["idx"]}', r['br'], '-maxrate', r['br']])
576
+
577
+ for i, track in enumerate(audio_tracks):
578
+ cmd.extend(['-map', f"0:{track['index']}"])
579
+ cmd.extend([f'-c:a:{i}', audio_codec, f'-b:a:{i}', '192k'])
580
+
581
+ mpd_output = temp_dash_dir / "manifest.mpd"
582
+
583
+ cmd.extend(extra_args)
584
+ cmd.extend([
585
+ '-f', 'dash',
586
+ '-seg_duration', '10',
587
+ '-use_template', '1',
588
+ '-use_timeline', '0',
589
+ '-init_seg_name', 'init-$RepresentationID$.m4s',
590
+ '-media_seg_name', 'chunk-$RepresentationID$-$Number%05d$.m4s',
591
+ str(mpd_output),
592
+ '-y',
593
+ '-loglevel', 'error'
594
+ ])
595
+
596
+ result = subprocess.run(cmd, capture_output=True, text=True, timeout=7200)
597
+
598
+ if result.returncode != 0:
599
+ shutil.rmtree(temp_dash_dir, ignore_errors=True)
600
+ raise Exception(f"DASH falló: {result.stderr[-500:]}")
601
+
602
+ final_mpd = output_dir / "manifest.mpd"
603
+ shutil.move(str(mpd_output), str(final_mpd))
604
+
605
+ for m4s in temp_dash_dir.glob("*.m4s"):
606
+ shutil.move(str(m4s), str(output_dir / m4s.name))
607
+
608
+ shutil.rmtree(temp_dash_dir, ignore_errors=True)
609
+
610
+ msg, logs = log_generator("✅ DASH OK", logs)
611
+ yield msg, logs, ""
612
+
613
+ manifest_file = "manifest.mpd"
614
+
615
+ # SUBIR A GITHUB
616
+ msg, logs = log_generator("☁️ Subiendo a GitHub...", logs)
617
+ yield msg, logs, ""
618
+
619
+ url_api = "https://api.github.com/user/repos"
620
+ headers = {"Authorization": f"token {token}"}
621
+ data = {"name": repo_name, "private": True}
622
+
623
+ r = requests.post(url_api, headers=headers, json=data, timeout=30)
624
+
625
+ if r.status_code == 422:
626
+ u = requests.get("https://api.github.com/user", headers=headers)
627
+ username = u.json()['login']
628
+ html_url = f"https://github.com/{username}/{repo_name}"
629
+ else:
630
+ html_url = r.json()['html_url']
631
+
632
+ repo_git_url = html_url.replace('https://', f'https://{token}@') + '.git'
633
+
634
+ git_dir = str(output_dir)
635
+ subprocess.run(['git', 'init'], cwd=git_dir, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
636
+ subprocess.run(['git', 'remote', 'add', 'origin', repo_git_url], cwd=git_dir, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
637
+ subprocess.run(['git', 'config', 'http.postBuffer', '524288000'], cwd=git_dir, check=True)
638
+
639
+ files = os.listdir(git_dir)
640
+
641
+ if stream_format == "DASH (MPD)":
642
+ seg_files = [f for f in files if f.endswith('.m4s')]
643
+ manifest_files = [f for f in files if f.endswith('.mpd')]
644
+ else:
645
+ seg_files = [f for f in files if f.endswith('.ts')]
646
+ manifest_files = [f for f in files if f.endswith('.m3u8')]
647
+
648
+ subprocess.run(['git', 'add'] + manifest_files, cwd=git_dir, check=True)
649
+ subprocess.run(['git', 'commit', '-m', 'Add manifests'], cwd=git_dir, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
650
+
651
+ try:
652
+ subprocess.run(['git', 'push', '-u', 'origin', 'main'], cwd=git_dir, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=600)
653
+ except:
654
+ subprocess.run(['git', 'push', '-f', 'origin', 'HEAD:main'], cwd=git_dir, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=600)
655
+
656
+ batch_size = int(batch_size_vid)
657
+
658
+ for i in range(0, len(seg_files), batch_size):
659
+ batch = seg_files[i:i+batch_size]
660
+ subprocess.run(['git', 'add'] + batch, cwd=git_dir, check=True)
661
+ subprocess.run(['git', 'commit', '-m', f'Batch {i}'], cwd=git_dir, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
662
+ subprocess.run(['git', 'push', 'origin', 'main'], cwd=git_dir, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=600)
663
+ progress((idx + (i/len(seg_files))) / total_sources)
664
+
665
+ gooplay_link = f'https://gooplay.xyz/gp/stream.php?repo={repo_name}&branch=main&file={manifest_file}'
666
+ github_link = f'{html_url}/blob/main/{manifest_file}'
667
+
668
+ final_links.append(f"**{base_name}**\n🔗 Gooplay: {gooplay_link}\n📂 GitHub: {github_link}")
669
+
670
+ msg, logs = log_generator(f"✅ Completado: {base_name}", logs)
671
+ yield msg, logs, ""
672
+
673
+ if delete_local:
674
+ shutil.rmtree(output_dir)
675
+
676
+ final_text = "\n\n".join(final_links)
677
+ yield "\n".join(logs), logs, final_text
678
+
679
+ except Exception as e:
680
+ import traceback
681
+ error_detail = traceback.format_exc()
682
+ error_msg = f"❌ ERROR: {str(e)}"
683
+ print(error_detail)
684
+ error_log = logs + [error_msg]
685
+ yield "\n".join(error_log), error_log, ""
686
+
687
+ # --- Interfaz Gradio ---
688
+
689
+ with gr.Blocks() as demo:
690
+ gr.Markdown("# ⚡ HLS/DASH Converter EXTREME v4.0")
691
+ gr.Markdown(f"**CPU: {OPTIMAL_THREADS} threads | RAM Disk: {RAMDISK_PATH}**")
692
+
693
+ with gr.Row():
694
+ with gr.Column(scale=1):
695
+ gr.Markdown("### ⚙️ Configuración")
696
+ token = gr.Textbox(label="GitHub Token", type="password", placeholder="ghp_...")
697
+
698
+ input_file = gr.File(label="Archivos", file_count="multiple")
699
+ input_urls = gr.Textbox(label="URLs (línea por línea)", lines=3)
700
+
701
+ conversion_option = gr.Dropdown(
702
+ [
703
+ "Opción 1: Copy Video + Copy Audio",
704
+ "Opción 2: Copy Video + MP3 Audio",
705
+ "Opción 3: Multi-Res (1080p + 720p) H.264",
706
+ "Opción 4: Multi-Res (4K + 1080p + 720p) H.264"
707
+ ],
708
+ value="Opción 1: Copy Video + Copy Audio",
709
+ label="Modo"
710
+ )
711
+
712
+ stream_format = gr.Dropdown(["HLS (M3U8)", "DASH (MPD)"], value="HLS (M3U8)", label="Formato")
713
+
714
+ with gr.Row():
715
+ batch_vid = gr.Number(value=30, label="Batch Git", precision=0)
716
+ max_workers = gr.Slider(1, 8, 4, step=1, label="Workers Audio")
717
+
718
+ delete_local = gr.Checkbox(value=True, label="Borrar local")
719
+
720
+ btn = gr.Button("🚀 PROCESAR (99% CPU+RAM)", variant="primary", size="lg")
721
+
722
+ with gr.Column(scale=2):
723
+ log_output = gr.Textbox(label="Logs", lines=25, interactive=False)
724
+ final_links = gr.Textbox(label="Links", lines=8, interactive=False)
725
+
726
+ gr.Markdown(f"""
727
+ ---
728
+ ### ⚡ OPTIMIZACIONES EXTREMAS
729
+ - **RAM Disk:** /dev/shm (tmpfs) - 100-1000x más rápido que SSD
730
+ - **CPU:** {OPTIMAL_THREADS} threads simultáneos
731
+ - **COPY:** Procesamiento en RAM + hardlinks (casi instantáneo)
732
+ - **RENDER:** preset=ultrafast + procesamiento paralelo multi-audio
733
+ """)
734
+
735
+ btn.click(
736
+ fn=process_bulk,
737
+ inputs=[token, input_file, input_urls, conversion_option, stream_format, batch_vid, delete_local, max_workers],
738
+ outputs=[log_output, gr.State(), final_links]
739
+ )
740
+
741
+ if __name__ == "__main__":
742
+ demo.launch()
packages.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ ffmpeg
2
+ git
requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ gradio==4.44.0
2
+ requests
3
+ psutil