CineMax commited on
Commit
8a44903
·
verified ·
1 Parent(s): f39b5f8

Upload 3 files

Browse files
Files changed (3) hide show
  1. app.py +699 -2
  2. packages.txt +2 -0
  3. requirements.txt +2 -1
app.py CHANGED
@@ -1,3 +1,700 @@
1
- import trackio
 
 
 
 
 
 
 
2
 
3
- trackio.show()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
 
10
+ try:
11
+ import requests
12
+ except ImportError:
13
+ print("Error: Falta instalar 'requests'")
14
+
15
+ # --- Configuración Global ---
16
+ subprocess.run(["git", "config", "--global", "user.email", "actions@github.com"], check=False, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
17
+ subprocess.run(["git", "config", "--global", "user.name", "Hugging Face Space"], check=False, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
18
+
19
+ # --- Funciones Auxiliares ---
20
+
21
+ def clean_for_folder(name):
22
+ return re.sub(r'[<>:"/\\|?*]', '_', name).strip()[:200]
23
+
24
+ def clean_for_repo(name):
25
+ name = re.sub(r'[^a-zA-Z0-9_-]', '-', name)
26
+ return re.sub(r'-+', '-', name).strip('-')[:100]
27
+
28
+ def get_filename_from_url(url):
29
+ try:
30
+ parsed = urlparse(url)
31
+ path = unquote(parsed.path)
32
+ basename = os.path.basename(path)
33
+ if basename and '.' in basename:
34
+ return Path(basename).stem
35
+ except:
36
+ pass
37
+ return "video"
38
+
39
+ def log_generator(message, log_list):
40
+ log_list.append(message)
41
+ return "\n".join(log_list), log_list
42
+
43
+ def detect_audio_streams(source_val):
44
+ """Detecta todos los streams de audio con sus metadatos"""
45
+ cmd_probe = [
46
+ 'ffprobe', '-v', 'error',
47
+ '-select_streams', 'a',
48
+ '-show_entries', 'stream=index,codec_name:stream_tags=language,title',
49
+ '-of', 'json',
50
+ '-i', source_val
51
+ ]
52
+
53
+ try:
54
+ res = subprocess.run(cmd_probe, capture_output=True, text=True, timeout=60)
55
+ data = json.loads(res.stdout)
56
+ streams = data.get('streams', [])
57
+
58
+ audio_tracks = []
59
+ for stream in streams:
60
+ index = stream.get('index', 0)
61
+ tags = stream.get('tags', {})
62
+ language = tags.get('language', 'und')
63
+ title = tags.get('title', f'Audio {index}')
64
+ codec = stream.get('codec_name', 'unknown')
65
+
66
+ audio_tracks.append({
67
+ 'index': index,
68
+ 'language': language.lower(),
69
+ 'title': title,
70
+ 'codec': codec
71
+ })
72
+
73
+ return audio_tracks
74
+ except Exception as e:
75
+ print(f"Error detectando audio: {e}")
76
+ return []
77
+
78
+ def prioritize_audio_tracks(tracks):
79
+ """Ordena los tracks priorizando español/latino"""
80
+ priority_langs = ['spa', 'es', 'spanish', 'español', 'latino', 'lat', 'es-mx', 'es-419']
81
+
82
+ def get_priority(track):
83
+ lang = track['language'].lower()
84
+ title = track['title'].lower()
85
+
86
+ for term in priority_langs:
87
+ if term in lang or term in title:
88
+ return 0
89
+
90
+ if lang == 'und':
91
+ return 1
92
+
93
+ return 2
94
+
95
+ return sorted(tracks, key=get_priority)
96
+
97
+ def create_master_m3u8(output_dir, video_streams, audio_playlists):
98
+ """Crea Master Playlist M3U8 versión 7"""
99
+ master_content = "#EXTM3U\n#EXT-X-VERSION:7\n\n"
100
+
101
+ # Agregar streams de audio
102
+ for i, audio_info in enumerate(audio_playlists):
103
+ default = "YES" if audio_info['is_default'] else "NO"
104
+ autoselect = "YES" if audio_info['is_default'] else "NO"
105
+
106
+ 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'
107
+
108
+ master_content += "\n"
109
+
110
+ # Agregar streams de video
111
+ for vid in video_streams:
112
+ master_content += f'#EXT-X-STREAM-INF:BANDWIDTH={vid["bandwidth"]},RESOLUTION={vid["resolution"]},CODECS="{vid["codecs"]}",AUDIO="audio"\n{vid["file"]}\n'
113
+
114
+ with open(output_dir / "master.m3u8", "w") as f:
115
+ f.write(master_content)
116
+
117
+ # --- Lógica de Procesamiento ---
118
+
119
+ def process_bulk(
120
+ token, input_file, input_urls, conversion_option, stream_format, batch_size_vid, delete_local,
121
+ progress=gr.Progress()
122
+ ):
123
+ logs = ["🚀 Iniciando proceso Bulk..."]
124
+
125
+ try:
126
+ if not token:
127
+ raise Exception("❌ Se requiere un Token de GitHub válido.")
128
+
129
+ # Preparar fuentes
130
+ sources = []
131
+ files_list = []
132
+
133
+ if input_file:
134
+ if isinstance(input_file, list):
135
+ files_list = input_file
136
+ else:
137
+ files_list = [input_file]
138
+
139
+ for f in files_list:
140
+ sources.append({"type": "file", "value": f.name})
141
+
142
+ if input_urls:
143
+ for line in input_urls.split('\n'):
144
+ url = line.strip()
145
+ if url:
146
+ sources.append({"type": "url", "value": url})
147
+
148
+ if not sources:
149
+ raise Exception("⚠️ Agrega archivos o URLs para procesar.")
150
+
151
+ total_sources = len(sources)
152
+ progress(0, desc="Iniciando conversión")
153
+
154
+ final_links = []
155
+
156
+ for idx, source in enumerate(sources):
157
+ is_file = source['type'] == 'file'
158
+ source_val = source['value']
159
+
160
+ msg, logs = log_generator(f"📦 Procesando {idx+1}/{total_sources}: {os.path.basename(source_val) if is_file else source_val}", logs)
161
+ yield msg, logs, ""
162
+
163
+ # Determinar nombre
164
+ if is_file:
165
+ base_name = Path(source_val).stem
166
+ base_dir = Path(source_val).parent
167
+ else:
168
+ base_name = get_filename_from_url(source_val)
169
+ base_dir = Path.cwd()
170
+
171
+ folder_name = clean_for_folder(base_name) + f"_{stream_format.lower()}"
172
+ repo_name = clean_for_repo(base_name)
173
+ output_dir = base_dir / folder_name
174
+ output_dir.mkdir(exist_ok=True)
175
+
176
+ msg, logs = log_generator(f"📂 Output: {output_dir}", logs)
177
+ yield msg, logs, ""
178
+
179
+ # Detectar audio
180
+ msg, logs = log_generator("🔍 Detectando streams de audio...", logs)
181
+ yield msg, logs, ""
182
+
183
+ audio_tracks = detect_audio_streams(source_val)
184
+
185
+ if not audio_tracks:
186
+ msg, logs = log_generator("⚠️ No se detectaron streams, usando track 0", logs)
187
+ yield msg, logs, ""
188
+ audio_tracks = [{'index': 0, 'language': 'und', 'title': 'Audio', 'codec': 'unknown'}]
189
+
190
+ audio_tracks = prioritize_audio_tracks(audio_tracks)
191
+
192
+ msg, logs = log_generator(f"🎵 {len(audio_tracks)} streams de audio detectados", logs)
193
+ yield msg, logs, ""
194
+
195
+ for track in audio_tracks:
196
+ msg, logs = log_generator(f" - Track {track['index']}: {track['title']} ({track['language']})", logs)
197
+ yield msg, logs, ""
198
+
199
+ manifest_file = ""
200
+
201
+ # =========================================================================
202
+ # LÓGICA PARA HLS (M3U8)
203
+ # =========================================================================
204
+ if stream_format == "HLS (M3U8)":
205
+ # ===== PROCESAR TODOS LOS AUDIOS POR SEPARADO (M3U8) =====
206
+ audio_playlists = []
207
+
208
+ msg, logs = log_generator("🎵 Codificando streams de audio (HLS)...", logs)
209
+ yield msg, logs, ""
210
+
211
+ for i, track in enumerate(audio_tracks):
212
+ try:
213
+ msg, logs = log_generator(f" 🔄 Audio {i+1}/{len(audio_tracks)}: {track['title']}", logs)
214
+ yield msg, logs, ""
215
+
216
+ audio_file = output_dir / f"audio_{i}.m3u8"
217
+ seg_audio = output_dir / f"audio_{i}_%03d.ts"
218
+
219
+ # Determinar codec de audio según opción
220
+ if conversion_option == "Opción 1: Copy Video + Copy Audio":
221
+ audio_params = ['-c:a', 'copy']
222
+ else:
223
+ # MP3 para HLS
224
+ audio_params = ['-c:a', 'libmp3lame', '-b:a', '192k', '-ar', '48000']
225
+
226
+ cmd_audio = [
227
+ 'ffmpeg', '-i', source_val,
228
+ '-map', f"0:{track['index']}"
229
+ ] + audio_params + [
230
+ '-hls_time', '10',
231
+ '-hls_list_size', '0',
232
+ '-hls_segment_filename', str(seg_audio),
233
+ str(audio_file),
234
+ '-y',
235
+ '-loglevel', 'warning'
236
+ ]
237
+
238
+ result = subprocess.run(cmd_audio, capture_output=True, text=True, timeout=3600)
239
+
240
+ if result.returncode != 0:
241
+ msg, logs = log_generator(f" ⚠️ Error en Audio {i+1}, continuando...", logs)
242
+ yield msg, logs, ""
243
+ continue
244
+
245
+ audio_playlists.append({
246
+ 'file': f"audio_{i}.m3u8",
247
+ 'language': track['language'],
248
+ 'title': track['title'],
249
+ 'is_default': i == 0
250
+ })
251
+
252
+ msg, logs = log_generator(f" ✅ Audio {i+1} codificado: {track['title']}", logs)
253
+ yield msg, logs, ""
254
+
255
+ except subprocess.TimeoutExpired:
256
+ msg, logs = log_generator(f" ⏱️ Timeout en Audio {i+1}, saltando...", logs)
257
+ yield msg, logs, ""
258
+ continue
259
+ except Exception as e:
260
+ msg, logs = log_generator(f" ❌ Error en Audio {i+1}: {str(e)}", logs)
261
+ yield msg, logs, ""
262
+ continue
263
+
264
+ if not audio_playlists:
265
+ raise Exception("No se pudo codificar ningún stream de audio")
266
+
267
+ # ===== PROCESAR VIDEO SEGÚN OPCIÓN (HLS) =====
268
+ video_streams = []
269
+
270
+ msg, logs = log_generator("🎬 Preparando conversión de video (HLS)...", logs)
271
+ yield msg, logs, ""
272
+
273
+ if conversion_option in ["Opción 1: Copy Video + Copy Audio", "Opción 2: Copy Video + MP3 Audio"]:
274
+ msg, logs = log_generator("🎬 Modo: Copy Video (Duplicado 1080p + 720p)", logs)
275
+ yield msg, logs, ""
276
+
277
+ video_file_1080 = output_dir / "video_1080p.m3u8"
278
+ seg_video_1080 = output_dir / "video_1080p_%03d.ts"
279
+
280
+ cmd_video = [
281
+ 'ffmpeg', '-i', source_val,
282
+ '-map', '0:v', '-c:v', 'copy', '-an',
283
+ '-hls_time', '10',
284
+ '-hls_list_size', '0',
285
+ '-hls_segment_filename', str(seg_video_1080),
286
+ str(video_file_1080),
287
+ '-y',
288
+ '-loglevel', 'warning'
289
+ ]
290
+
291
+ result = subprocess.run(cmd_video, capture_output=True, text=True, timeout=7200)
292
+
293
+ if result.returncode != 0:
294
+ raise Exception(f"FFmpeg falló: {result.stderr}")
295
+
296
+ video_file_720 = output_dir / "video_720p.m3u8"
297
+ shutil.copy(video_file_1080, video_file_720)
298
+
299
+ for ts_file in output_dir.glob("video_1080p_*.ts"):
300
+ new_name = ts_file.name.replace("1080p", "720p")
301
+ shutil.copy(ts_file, output_dir / new_name)
302
+
303
+ video_streams.append({'file': 'video_1080p.m3u8', 'resolution': '1920x1080', 'bandwidth': 5000000, 'codecs': 'avc1.640028'})
304
+ video_streams.append({'file': 'video_720p.m3u8', 'resolution': '1280x720', 'bandwidth': 3000000, 'codecs': 'avc1.640028'})
305
+
306
+ msg, logs = log_generator("✅ Video copiado y duplicado (1080p + 720p)", logs)
307
+ yield msg, logs, ""
308
+
309
+ elif conversion_option == "Opción 3: Multi-Res (1080p + 720p) H.264":
310
+ msg, logs = log_generator("🎬 Modo: Render H.264 (1080p + 720p)", logs)
311
+ yield msg, logs, ""
312
+
313
+ resolutions = [
314
+ {'label': '1080p', 'scale': 'scale=-2:1080', 'bitrate': '5000k', 'bufsize': '10000k', 'res': '1920x1080'},
315
+ {'label': '720p', 'scale': 'scale=-2:720', 'bitrate': '2800k', 'bufsize': '5600k', 'res': '1280x720'}
316
+ ]
317
+
318
+ for res_config in resolutions:
319
+ msg, logs = log_generator(f" 🔄 Renderizando {res_config['label']}...", logs)
320
+ yield msg, logs, ""
321
+
322
+ video_file = output_dir / f"video_{res_config['label']}.m3u8"
323
+ seg_video = output_dir / f"video_{res_config['label']}_%03d.ts"
324
+
325
+ cmd_video = [
326
+ 'ffmpeg', '-i', source_val,
327
+ '-map', '0:v', '-an',
328
+ '-c:v', 'libx264', '-preset', 'medium', '-crf', '20',
329
+ '-vf', res_config['scale'],
330
+ '-b:v', res_config['bitrate'],
331
+ '-maxrate', res_config['bitrate'],
332
+ '-bufsize', res_config['bufsize'],
333
+ '-pix_fmt', 'yuv420p',
334
+ '-hls_time', '10',
335
+ '-hls_list_size', '0',
336
+ '-hls_segment_filename', str(seg_video),
337
+ str(video_file),
338
+ '-y',
339
+ '-loglevel', 'warning'
340
+ ]
341
+
342
+ result = subprocess.run(cmd_video, capture_output=True, text=True, timeout=7200)
343
+
344
+ if result.returncode != 0:
345
+ msg, logs = log_generator(f" ⚠️ Error en {res_config['label']}", logs)
346
+ yield msg, logs, ""
347
+ continue
348
+
349
+ video_streams.append({
350
+ 'file': f"video_{res_config['label']}.m3u8",
351
+ 'resolution': res_config['res'],
352
+ 'bandwidth': int(res_config['bitrate'].replace('k', '000')) + 192000,
353
+ 'codecs': 'avc1.640028'
354
+ })
355
+
356
+ msg, logs = log_generator(f" ✅ {res_config['label']} completado", logs)
357
+ yield msg, logs, ""
358
+
359
+ elif conversion_option == "Opción 4: Multi-Res (4K + 1080p + 720p) H.264":
360
+ msg, logs = log_generator("🎬 Modo: Render H.264 (4K + 1080p + 720p)", logs)
361
+ yield msg, logs, ""
362
+
363
+ resolutions = [
364
+ {'label': '4K', 'scale': 'scale=-2:2160', 'bitrate': '15000k', 'bufsize': '30000k', 'res': '3840x2160'},
365
+ {'label': '1080p', 'scale': 'scale=-2:1080', 'bitrate': '5000k', 'bufsize': '10000k', 'res': '1920x1080'},
366
+ {'label': '720p', 'scale': 'scale=-2:720', 'bitrate': '2800k', 'bufsize': '5600k', 'res': '1280x720'}
367
+ ]
368
+
369
+ for res_config in resolutions:
370
+ msg, logs = log_generator(f" 🔄 Renderizando {res_config['label']}...", logs)
371
+ yield msg, logs, ""
372
+
373
+ video_file = output_dir / f"video_{res_config['label']}.m3u8"
374
+ seg_video = output_dir / f"video_{res_config['label']}_%03d.ts"
375
+
376
+ cmd_video = [
377
+ 'ffmpeg', '-i', source_val,
378
+ '-map', '0:v', '-an',
379
+ '-c:v', 'libx264', '-preset', 'medium', '-crf', '20',
380
+ '-vf', res_config['scale'],
381
+ '-b:v', res_config['bitrate'],
382
+ '-maxrate', res_config['bitrate'],
383
+ '-bufsize', res_config['bufsize'],
384
+ '-pix_fmt', 'yuv420p',
385
+ '-hls_time', '10',
386
+ '-hls_list_size', '0',
387
+ '-hls_segment_filename', str(seg_video),
388
+ str(video_file),
389
+ '-y',
390
+ '-loglevel', 'warning'
391
+ ]
392
+
393
+ result = subprocess.run(cmd_video, capture_output=True, text=True, timeout=7200)
394
+
395
+ if result.returncode != 0:
396
+ msg, logs = log_generator(f" ⚠️ Error en {res_config['label']}", logs)
397
+ yield msg, logs, ""
398
+ continue
399
+
400
+ video_streams.append({
401
+ 'file': f"video_{res_config['label']}.m3u8",
402
+ 'resolution': res_config['res'],
403
+ 'bandwidth': int(res_config['bitrate'].replace('k', '000')) + 192000,
404
+ 'codecs': 'avc1.640028'
405
+ })
406
+
407
+ msg, logs = log_generator(f" ✅ {res_config['label']} completado", logs)
408
+ yield msg, logs, ""
409
+
410
+ if not video_streams:
411
+ raise Exception("No se generó ningún stream de video válido")
412
+
413
+ # ===== CREAR MASTER PLAYLIST HLS =====
414
+ msg, logs = log_generator("📝 Creando master.m3u8...", logs)
415
+ yield msg, logs, ""
416
+
417
+ create_master_m3u8(output_dir, video_streams, audio_playlists)
418
+ manifest_file = "master.m3u8"
419
+
420
+ # =========================================================================
421
+ # LÓGICA PARA DASH (MPD) - FULL MPD, NO TS
422
+ # =========================================================================
423
+ elif stream_format == "DASH (MPD)":
424
+ msg, logs = log_generator("🎬 Iniciando generación DASH (fMP4)...", logs)
425
+ yield msg, logs, ""
426
+
427
+ cmd = ['ffmpeg', '-i', source_val]
428
+
429
+ # Configuración de Codec
430
+ is_copy_mode = (conversion_option == "Opción 1: Copy Video + Copy Audio")
431
+
432
+ # Audio: MP3 no es bien soportado en DASH fMP4, usamos AAC para compatibilidad
433
+ # Si es opción 1 (Copy), copiamos. Si no, recodificamos a AAC.
434
+ audio_codec = 'copy' if is_copy_mode else 'aac'
435
+ audio_bitrate = '192k'
436
+
437
+ # Video
438
+ video_codec = 'copy' if is_copy_mode else 'libx264'
439
+
440
+ # Mapas de Video
441
+ video_maps = []
442
+
443
+ if is_copy_mode:
444
+ # Solo copiamos el video original
445
+ cmd.extend(['-map', '0:v:0', '-c:v:0', video_codec])
446
+ video_maps.append(0)
447
+ else:
448
+ # Definir resoluciones según opción
449
+ if conversion_option == "Opción 3: Multi-Res (1080p + 720p) H.264":
450
+ res_list = [
451
+ {'idx': 0, 'scale': 'scale=-2:1080', 'br': '5000k', 'res': '1920x1080'},
452
+ {'idx': 1, 'scale': 'scale=-2:720', 'br': '2800k', 'res': '1280x720'}
453
+ ]
454
+ elif conversion_option == "Opción 4: Multi-Res (4K + 1080p + 720p) H.264":
455
+ res_list = [
456
+ {'idx': 0, 'scale': 'scale=-2:2160', 'br': '15000k', 'res': '3840x2160'},
457
+ {'idx': 1, 'scale': 'scale=-2:1080', 'br': '5000k', 'res': '1920x1080'},
458
+ {'idx': 2, 'scale': 'scale=-2:720', 'br': '2800k', 'res': '1280x720'}
459
+ ]
460
+ else:
461
+ # Opción 2 (Copy video, audio mp3) -> Como el video es copy, igual que opción 1 para video
462
+ res_list = []
463
+ cmd.extend(['-map', '0:v:0', '-c:v:0', 'copy'])
464
+
465
+ for r in res_list:
466
+ cmd.extend(['-map', '0:v:0'])
467
+ cmd.extend([f'-c:v:{r["idx"]}', video_codec, '-preset', 'medium', '-crf', '20'])
468
+ cmd.extend([f'-vf:v:{r["idx"]}', r['scale']])
469
+ cmd.extend([f'-b:v:{r["idx"]}', r['br'], '-maxrate', r['br'], '-bufsize', str(int(r['br'].replace('k',''))*2) + 'k'])
470
+ cmd.extend(['-pix_fmt', 'yuv420p'])
471
+
472
+ # Mapas de Audio
473
+ for i, track in enumerate(audio_tracks):
474
+ cmd.extend(['-map', f"0:{track['index']}"])
475
+ cmd.extend([f'-c:a:{i}', audio_codec, f'-b:a:{i}', audio_bitrate, '-ar', '48000'])
476
+
477
+ # Comando final DASH
478
+ mpd_output_path = output_dir / "manifest.mpd"
479
+
480
+ cmd.extend([
481
+ '-f', 'dash',
482
+ '-seg_duration', '10',
483
+ '-use_template', '1',
484
+ '-use_timeline', '0',
485
+ '-init_seg_name', 'init-$RepresentationID$.m4s',
486
+ '-media_seg_name', 'chunk-$RepresentationID$-$Number%05d$.m4s',
487
+ str(mpd_output_path),
488
+ '-y',
489
+ '-loglevel', 'warning'
490
+ ])
491
+
492
+ msg, logs = log_generator("⚙️ Ejecutando FFmpeg DASH...", logs)
493
+ yield msg, logs, ""
494
+
495
+ result = subprocess.run(cmd, capture_output=True, text=True, timeout=7200)
496
+
497
+ if result.returncode != 0:
498
+ raise Exception(f"FFmpeg DASH falló: {result.stderr}")
499
+
500
+ if not mpd_output_path.exists():
501
+ raise Exception("No se generó el archivo manifest.mpd")
502
+
503
+ msg, logs = log_generator("✅ DASH MPD generado exitosamente", logs)
504
+ yield msg, logs, ""
505
+
506
+ manifest_file = "manifest.mpd"
507
+
508
+ # ===== SUBIR A GITHUB =====
509
+ msg, logs = log_generator("☁️ Creando repositorio en GitHub...", logs)
510
+ yield msg, logs, ""
511
+
512
+ url_api = "https://api.github.com/user/repos"
513
+ headers = {"Authorization": f"token {token}"}
514
+ # REPOSITORIO PRIVADO
515
+ data = {"name": repo_name, "private": True}
516
+
517
+ r = requests.post(url_api, headers=headers, json=data, timeout=30)
518
+
519
+ if r.status_code == 422:
520
+ u = requests.get("https://api.github.com/user", headers=headers)
521
+ username = u.json()['login']
522
+ html_url = f"https://github.com/{username}/{repo_name}"
523
+ else:
524
+ html_url = r.json()['html_url']
525
+
526
+ repo_git_url = html_url.replace('https://', f'https://{token}@') + '.git'
527
+
528
+ msg, logs = log_generator(f"📦 Repo: {html_url}", logs)
529
+ yield msg, logs, ""
530
+
531
+ # Git operations
532
+ git_dir = str(output_dir)
533
+ subprocess.run(['git', 'init'], cwd=git_dir, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
534
+ subprocess.run(['git', 'remote', 'add', 'origin', repo_git_url], cwd=git_dir, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
535
+
536
+ # AUMENTAR EL BUFFER DE GIT PARA EVITAR ERRORES DE PUSH
537
+ msg, logs = log_generator("🛠️ Configurando buffer de Git...", logs)
538
+ yield msg, logs, ""
539
+ subprocess.run(['git', 'config', 'http.postBuffer', '524288000'], cwd=git_dir, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
540
+
541
+ files = os.listdir(git_dir)
542
+
543
+ # Determinar extensiones según el formato
544
+ if stream_format == "DASH (MPD)":
545
+ seg_files = [f for f in files if f.endswith('.m4s')]
546
+ manifest_files = [f for f in files if f.endswith('.mpd')]
547
+ else:
548
+ seg_files = [f for f in files if f.endswith('.ts')]
549
+ manifest_files = [f for f in files if f.endswith('.m3u8')]
550
+
551
+ # Commit manifests
552
+ subprocess.run(['git', 'add'] + manifest_files, cwd=git_dir, check=True)
553
+ subprocess.run(['git', 'commit', '-m', 'Add manifests'], cwd=git_dir, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
554
+
555
+ try:
556
+ subprocess.run(['git', 'push', '-f', 'origin', 'HEAD:main'], cwd=git_dir, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=600)
557
+ except Exception as e:
558
+ msg, logs = log_generator(f"⚠️ Error inicial push manifest: {e}", logs)
559
+ yield msg, logs, ""
560
+
561
+ # Commit segments por lotes
562
+ batch_size = int(batch_size_vid)
563
+ if batch_size < 10:
564
+ batch_size = 20 # Reducido a 20 por defecto si es menor a 10 para mayor estabilidad
565
+
566
+ msg, logs = log_generator(f"🚶 Subiendo {len(seg_files)} segmentos ({stream_format}) (Batch: {batch_size})...", logs)
567
+ yield msg, logs, ""
568
+
569
+ for i in range(0, len(seg_files), batch_size):
570
+ batch = seg_files[i:i+batch_size]
571
+ subprocess.run(['git', 'add'] + batch, cwd=git_dir, check=True)
572
+ subprocess.run(['git', 'commit', '-m', f'Batch {i}'], cwd=git_dir, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
573
+
574
+ try:
575
+ # Push con timeout de 10 minutos y captura de stderr
576
+ subprocess.run(
577
+ ['git', 'push', '-f', 'origin', 'HEAD:main'],
578
+ cwd=git_dir,
579
+ check=True,
580
+ stdout=subprocess.DEVNULL,
581
+ stderr=subprocess.PIPE, # Capturar stderr para ver el error real
582
+ timeout=600
583
+ )
584
+ except subprocess.TimeoutExpired:
585
+ msg, logs = log_generator(f" ⏱️ Timeout en batch {i}-{i+batch_size}. Reintentando...", logs)
586
+ yield msg, logs, ""
587
+ # Reintento simple
588
+ try:
589
+ subprocess.run(['git', 'push', '-f', 'origin', 'HEAD:main'], cwd=git_dir, check=True, timeout=600)
590
+ except Exception as e:
591
+ raise Exception(f"Fallo definitivo en batch {i}: {str(e)}")
592
+ except subprocess.CalledProcessError as e:
593
+ # Decodificar el error para mostrarlo
594
+ error_detail = e.stderr.decode() if e.stderr else "Error desconocido"
595
+ msg, logs = log_generator(f" ❌ Error Push Batch {i}: {error_detail[:200]}", logs)
596
+ yield msg, logs, ""
597
+ raise Exception(f"Error Git Push: {error_detail}")
598
+
599
+ progress((idx + (i/len(seg_files))) / total_sources, desc=f"Subiendo segmentos {i}/{len(seg_files)}")
600
+
601
+ # Link final
602
+ gooplay_link = f'https://gooplay.xyz/gp/stream.php?repo={repo_name}&branch=main&file={manifest_file}'
603
+ github_link = f'{html_url}/blob/main/{manifest_file}'
604
+
605
+ final_links.append(f"**{base_name}**\n🔗 Gooplay: {gooplay_link}\n📂 GitHub: {github_link}")
606
+
607
+ msg, logs = log_generator(f"✅ Completado: {base_name}", logs)
608
+ yield msg, logs, ""
609
+
610
+ if delete_local:
611
+ shutil.rmtree(output_dir)
612
+ msg, logs = log_generator(f"🗑️ Archivos locales eliminados", logs)
613
+ yield msg, logs, ""
614
+
615
+ # Yield final con todos los links
616
+ final_text = "\n\n".join(final_links)
617
+ yield "\n".join(logs), logs, final_text
618
+
619
+ except Exception as e:
620
+ import traceback
621
+ error_detail = traceback.format_exc()
622
+ error_msg = f"❌ ERROR: {str(e)}"
623
+ print(error_detail)
624
+ error_log = logs + [error_msg]
625
+ yield "\n".join(error_log), error_log, ""
626
+
627
+ # --- Interfaz Gradio ---
628
+
629
+ with gr.Blocks() as demo:
630
+ gr.Markdown("# 🎬 HLS/DASH Converter Pro - Bulk Multi-Audio (Private Repo)")
631
+ gr.Markdown("Convierte videos a **HLS (M3U8)** o **DASH (MPD)** con soporte completo multi-audio.")
632
+ gr.Markdown("⚠️ **Nota:** Los repositorios se crearán como **Privados** por defecto.")
633
+
634
+ with gr.Row():
635
+ with gr.Column(scale=1):
636
+ gr.Markdown("### ⚙️ Configuración")
637
+ token = gr.Textbox(label="GitHub Token", type="password", placeholder="ghp_...")
638
+
639
+ gr.Markdown("### 📁 Fuentes (Archivos o URLs)")
640
+ input_file = gr.File(label="Subir Archivos", file_count="multiple")
641
+ input_urls = gr.Textbox(label="URLs (una por línea)", placeholder="https://ejemplo.com/video.mkv", lines=3)
642
+
643
+ gr.Markdown("### 🎨 Opciones de Conversión")
644
+
645
+ conversion_option = gr.Dropdown(
646
+ [
647
+ "Opción 1: Copy Video + Copy Audio",
648
+ "Opción 2: Copy Video + MP3 Audio",
649
+ "Opción 3: Multi-Res (1080p + 720p) H.264",
650
+ "Opción 4: Multi-Res (4K + 1080p + 720p) H.264"
651
+ ],
652
+ value="Opción 3: Multi-Res (1080p + 720p) H.264",
653
+ label="Modo de Conversión"
654
+ )
655
+
656
+ stream_format = gr.Dropdown(
657
+ ["HLS (M3U8)", "DASH (MPD)"],
658
+ value="HLS (M3U8)",
659
+ label="Formato de Streaming"
660
+ )
661
+
662
+ gr.Markdown("### 🔧 Configuración Avanzada")
663
+
664
+ with gr.Row():
665
+ batch_vid = gr.Number(value=20, label="Tamaño de Lote (Git Push)", precision=0) # Reducido a 20
666
+
667
+ delete_local = gr.Checkbox(value=True, label="Eliminar archivos locales después de subir")
668
+
669
+ btn = gr.Button("🚀 Iniciar Conversión Bulk", variant="primary", size="lg")
670
+
671
+ with gr.Column(scale=2):
672
+ gr.Markdown("### 📜 Registros en Tiempo Real")
673
+ log_output = gr.Textbox(label="Consola", lines=25, interactive=False)
674
+
675
+ gr.Markdown("### 🔗 Links Generados")
676
+ final_links = gr.Textbox(label="Links de Streaming", lines=8, interactive=False)
677
+
678
+ gr.Markdown("""
679
+ ---
680
+ ### 📖 Guía de Uso
681
+
682
+ **Formatos:**
683
+ - **HLS (M3U8)**: Genera archivos `.ts` y playlists `.m3u8`. Estándar web y móvil.
684
+ - **DASH (MPD)**: Genera segmentos `.m4s` (fMP4) y archivo `manifest.mpd`. Estándar MPEG-DASH nativo. **No usa .ts**.
685
+
686
+ **Multi-Audio & Privacidad:**
687
+ - HLS: Codifica cada audio en un stream separado `.m3u8` + `.ts` (o MP3 en TS).
688
+ - DASH: Incluye todos los streams de audio dentro del mismo `manifest.mpd`.
689
+ - Los repositorios creados serán **Privados**. Los links directos (como gooplay) pueden requerir autenticación si no soportan repos privados, pero los archivos estarán seguros en GitHub.
690
+ """)
691
+
692
+ btn.click(
693
+ fn=process_bulk,
694
+ inputs=[token, input_file, input_urls, conversion_option, stream_format, batch_vid, delete_local],
695
+ outputs=[log_output, gr.State(), final_links]
696
+ )
697
+
698
+
699
+ if __name__ == "__main__":
700
+ demo.launch()
packages.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ ffmpeg
2
+ git
requirements.txt CHANGED
@@ -1 +1,2 @@
1
- trackio<1.0
 
 
1
+ gradio==4.44.0
2
+ requests