CineMax commited on
Commit
91e6b0b
·
verified ·
1 Parent(s): fd31252

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +68 -45
app.py CHANGED
@@ -72,15 +72,34 @@ class MediaAnalyzer:
72
  @staticmethod
73
  def get_media_info(source: str) -> MediaInfo:
74
  info = MediaInfo(path=source)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75
  try:
76
- cmd = ["ffprobe", "-v", "quiet", "-print_format", "json",
77
- "-show_format", "-show_streams", source]
78
- # Análisis un poco más profundo para URLs difíciles
79
- if source.startswith("http"):
80
- cmd.extend(["-analyzeduration", "50000000", "-probesize", "10000000"])
81
 
82
- result = subprocess.run(cmd, capture_output=True, text=True, timeout=60)
83
- if result.returncode != 0: return info
 
 
 
 
84
  data = json.loads(result.stdout)
85
  format_tags = data.get("format", {}).get("tags", {})
86
  info.title = format_tags.get("title") or format_tags.get("TITLE")
@@ -106,7 +125,13 @@ class MediaAnalyzer:
106
  tags.get("title", ""),
107
  disposition.get("forced", 0) == 1)
108
  info.subtitle_tracks.append(track); sub_idx += 1
109
- except Exception as e: print(f"Error analyzing: {e}")
 
 
 
 
 
 
110
  return info
111
 
112
  class VideoConverter:
@@ -130,6 +155,9 @@ class VideoConverter:
130
  current = h * 3600 + m * 60 + s + ms / 100
131
  percent = min(100, (current / duration) * 100)
132
  if progress: progress(percent / 100, desc=f"{msg}: {percent:.0f}%")
 
 
 
133
  self.current_process.wait()
134
  return self.current_process.returncode == 0, "OK"
135
  except Exception as e: print(f"FFmpeg error: {e}"); return False, str(e)
@@ -140,47 +168,39 @@ class VideoConverter:
140
  self.cancelled = False
141
  temp_folder = None
142
  try:
143
- # Preparación de inputs para URL
144
  extra_input_options = []
145
  if is_url:
146
- log_func("Detectado Stream URL. Iniciando configuración agresiva para MKV/Proxy...")
147
-
148
- # Flags mejorados para MKV y Servidores Proxy
149
  extra_input_options = [
150
- # 1. User Agent realista para evitar bloqueos
151
  "-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",
 
 
152
 
153
- # 2. Headers para fingir ser un navegador
154
- "-headers", "Referer: https://google.com\r\nAccept: */*\r\nConnection: keep-alive",
155
-
156
- # 3. Aumentamos el tamaño de lectura inicial para encontrar el header del MKV
157
- # Necesitamos más bytes para encontrar la info en MKV que en MP4
158
  "-probesize", "5000000",
159
- "-analyzeduration", "10000000",
160
-
161
- # 4. Flags críticos para streaming sin cabecera completa
162
- # +genpts: Genera timestamps si faltan
163
- # +discardcorrupt: Ignora errores menores en el stream
164
- # +igndts: Ignora DTS para evitar desfases
165
- # nobuffer: No guarda buffer
166
  "-fflags", "+genpts+discardcorrupt+igndts+nobuffer",
167
-
168
- # 5. Manejo de timestamps negativos (común en streams)
169
  "-avoid_negative_ts", "make_zero",
170
-
171
- # 6. Baja el delay máximo
172
  "-max_delay", "0",
173
-
174
- # 7. Prioridad a baja latencia
175
  "-flags", "low_delay"
176
  ]
177
 
178
  info = MediaAnalyzer.get_media_info(source)
 
 
 
 
 
179
  duration = info.duration if info.duration > 0 else 1
180
 
181
  base_name = info.title if info.title else (Path(source).stem if not is_url else "video_stream")
182
  if not base_name or base_name.strip() == "": base_name = "video_sin_nombre"
183
 
 
 
 
 
184
  folder_name = re.sub(r'[<>:"/\\|?*]', '_', base_name)
185
  folder_name = re.sub(r'\s+', ' ', folder_name).strip().replace(' ', '_')
186
  for old, new in [("a", "4"), ("A", "4"), ("i", "1"), ("I", "1"), ("o", "0"), ("O", "0")]:
@@ -190,7 +210,7 @@ class VideoConverter:
190
  temp_folder = tempfile.mkdtemp(prefix="video_conv_")
191
  out_folder = os.path.join(temp_folder, folder_name)
192
  os.makedirs(out_folder, exist_ok=True)
193
- log_func(f"Carpeta de trabajo creada: {folder_name}")
194
 
195
  all_audio_path = os.path.join(out_folder, f"{folder_name}_all_audio.mp4")
196
  cmd = ["ffmpeg", "-y"] + extra_input_options + ["-i", source, "-map", "0:v:0", "-map", "0:a?"]
@@ -201,24 +221,21 @@ class VideoConverter:
201
  cmd.extend(["-map_metadata", "0", "-metadata", "copyright=Power Prods", all_audio_path])
202
 
203
  success, msg = self.run_ffmpeg(cmd, duration, progress, "Convirtiendo")
204
- if not success or self.cancelled: return False, f"Error: {msg}", None, None
205
 
206
- # Guardamos el nombre del archivo para generar el link después
207
  target_filename = f"{folder_name}_all_audio.mp4"
208
 
209
  if extract_sub and info.subtitle_tracks:
210
  log_func("Extrayendo subtítulo...")
211
  vtt_path = os.path.join(out_folder, f"{folder_name}_sub_{sub_index}.vtt")
212
- # Usamos los mismos flags para el subtítulo
213
  sub_cmd = ["ffmpeg", "-y"] + extra_input_options + ["-i", source, "-map", f"0:s:{sub_index}", "-c:s", "webvtt", vtt_path]
214
  subprocess.run(sub_cmd, capture_output=True)
215
 
216
  if generate_single:
217
  log_func("Generando versión individual...")
218
  single_path = os.path.join(out_folder, f"{folder_name}_audio_{selected_audio}.mp4")
219
- # No hace falta streaming para la versión individual, porque es un archivo local (el all_audio_path)
220
  single_cmd = ["ffmpeg", "-y", "-i", all_audio_path, "-map", "0:v:0", "-map", f"0:a:{selected_audio}", "-c:v", "copy", "-c:a", "copy", "-map_metadata", "0", single_path]
221
- success, msg = self.run_ffmpeg(single_cmd, duration, progress, "Generando individual")
222
  if not success: return False, f"Error: {msg}", None, None
223
  target_filename = f"{folder_name}_audio_{selected_audio}.mp4"
224
 
@@ -252,7 +269,6 @@ def upload_to_hf(folder_path: str, repo_id: str, token: str, log_func=print, tar
252
  commit_message=f"Upload {folder_name}"
253
  )
254
 
255
- # Generar enlace directo
256
  if target_filename:
257
  direct_link = f"https://huggingface.co/{repo_id}/resolve/main/{repo_path}/{target_filename}"
258
  else:
@@ -269,13 +285,20 @@ def analyze_media(file_input, url_input):
269
  if file_input: source = file_input.name
270
  elif url_input: source = url_input; is_url = True
271
  else: return None, None, "Selecciona archivo o URL."
 
272
  info = MediaAnalyzer.get_media_info(source)
 
 
 
 
 
273
  audio_choices = [f"{i}: {t.display_name()}" for i, t in enumerate(info.audio_tracks)]
274
  sub_choices = [f"{i}: {t.display_name()}" for i, t in enumerate(info.subtitle_tracks)]
 
275
  return (
276
  gr.Dropdown(choices=audio_choices, value=0 if audio_choices else None, interactive=True),
277
  gr.Dropdown(choices=sub_choices, value=0 if sub_choices else None, interactive=True),
278
- f"Analizado: {info.title or os.path.basename(source)}\nDuración: {info.duration}s"
279
  )
280
 
281
  def process_and_upload(file_input, url_input, token, target_model, mode,
@@ -314,8 +337,8 @@ def process_and_upload(file_input, url_input, token, target_model, mode,
314
  return final_msg, final_msg
315
 
316
  with gr.Blocks(theme=gr.themes.Soft(), css=CUSTOM_CSS) as demo:
317
- gr.Markdown("# 🎬 Video Converter Pro (MKV/Stream Optimized)")
318
- gr.Markdown("Convierte videos difíciles (MKV/Proxy) y sube a Hugging Face. Obtiene enlace para Rumble.")
319
 
320
  with gr.Row():
321
  with gr.Column(scale=1):
@@ -337,13 +360,13 @@ with gr.Blocks(theme=gr.themes.Soft(), css=CUSTOM_CSS) as demo:
337
 
338
  with gr.Column(scale=2):
339
  with gr.Tab("Archivo"): file_input = gr.File(label="Subir Video", file_types=["video"])
340
- with gr.Tab("URL"): url_input = gr.Textbox(label="Enlace Video")
341
 
342
- btn_analyze = gr.Button("🔍 Analizar", variant="secondary")
343
- analysis_info = gr.Textbox(label="Info", lines=2, interactive=False)
344
  btn_process = gr.Button("🚀 PROCESAR Y SUBIR", variant="primary", size="lg")
345
 
346
- output_box = gr.Textbox(label="Resultados y Enlace", lines=8, interactive=False)
347
 
348
  btn_load_models.click(fn=get_user_models, inputs=[token_input], outputs=[target_model_dd])
349
  btn_analyze.click(fn=analyze_media, inputs=[file_input, url_input], outputs=[audio_dd, sub_dd, analysis_info])
 
72
  @staticmethod
73
  def get_media_info(source: str) -> MediaInfo:
74
  info = MediaInfo(path=source)
75
+
76
+ # Configuración de headers para URL (CRUCIAL para Workers de GDrive)
77
+ is_url = source.startswith("http")
78
+
79
+ cmd = ["ffprobe", "-v", "quiet", "-print_format", "json",
80
+ "-show_format", "-show_streams"]
81
+
82
+ if is_url:
83
+ # AÑADIDO: Headers necesarios para que el Worker permita la conexión
84
+ cmd.extend([
85
+ "-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",
86
+ "-headers", "Accept: */*\r\nConnection: keep-alive",
87
+ "-analyzeduration", "50000000", # 50s para esperar el stream inicial
88
+ "-probesize", "10000000" # Leer hasta 10MB para encontrar header en MKV
89
+ ])
90
+
91
+ cmd.append(source)
92
+
93
  try:
94
+ # Timeout aumentado a 90 segundos para darle tiempo al worker
95
+ result = subprocess.run(cmd, capture_output=True, text=True, timeout=90)
 
 
 
96
 
97
+ if result.returncode != 0:
98
+ # Devolvemos información del error para depuración
99
+ print(f"FFProbe Error: {result.stderr}")
100
+ info.error_message = f"Error de análisis (Posible bloqueo del Worker): {result.stderr[:200]}"
101
+ return info
102
+
103
  data = json.loads(result.stdout)
104
  format_tags = data.get("format", {}).get("tags", {})
105
  info.title = format_tags.get("title") or format_tags.get("TITLE")
 
125
  tags.get("title", ""),
126
  disposition.get("forced", 0) == 1)
127
  info.subtitle_tracks.append(track); sub_idx += 1
128
+ except subprocess.TimeoutExpired:
129
+ info.error_message = "Tiempo de espera agotado. El Worker es muy lento para responder."
130
+ print("Timeout en análisis")
131
+ except Exception as e:
132
+ info.error_message = f"Error crítico: {str(e)}"
133
+ print(f"Error analyzing: {e}")
134
+
135
  return info
136
 
137
  class VideoConverter:
 
155
  current = h * 3600 + m * 60 + s + ms / 100
156
  percent = min(100, (current / duration) * 100)
157
  if progress: progress(percent / 100, desc=f"{msg}: {percent:.0f}%")
158
+ # Log de errores para ver qué pasa
159
+ if "Error" in line or "Invalid data" in line:
160
+ print(f"FFmpeg Warning: {line.strip()}")
161
  self.current_process.wait()
162
  return self.current_process.returncode == 0, "OK"
163
  except Exception as e: print(f"FFmpeg error: {e}"); return False, str(e)
 
168
  self.cancelled = False
169
  temp_folder = None
170
  try:
 
171
  extra_input_options = []
172
  if is_url:
173
+ log_func("Configurando Stream para URL compleja...")
174
+ # Headers y Flags ajustados para Workers que requieran imitar navegador
 
175
  extra_input_options = [
 
176
  "-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",
177
+ # Eliminamos Referer específico para evitar bloqueos en algunos workers, dejamos Accept
178
+ "-headers", "Accept: */*\r\nConnection: keep-alive\r\nAccept-Encoding: identity",
179
 
180
+ # Configuración para MKV y streams lentos
 
 
 
 
181
  "-probesize", "5000000",
182
+ "-analyzeduration", "15000000", # 15 segundos para analizar inicio
 
 
 
 
 
 
183
  "-fflags", "+genpts+discardcorrupt+igndts+nobuffer",
 
 
184
  "-avoid_negative_ts", "make_zero",
 
 
185
  "-max_delay", "0",
 
 
186
  "-flags", "low_delay"
187
  ]
188
 
189
  info = MediaAnalyzer.get_media_info(source)
190
+
191
+ # Si el análisis falló pero tiene un mensaje de error, lo devolvemos
192
+ if hasattr(info, 'error_message') and info.error_message:
193
+ return False, f"Fallo al leer el video: {info.error_message}", None, None
194
+
195
  duration = info.duration if info.duration > 0 else 1
196
 
197
  base_name = info.title if info.title else (Path(source).stem if not is_url else "video_stream")
198
  if not base_name or base_name.strip() == "": base_name = "video_sin_nombre"
199
 
200
+ # Sanitizar nombre: Quitamos ?id=... si quedó en el nombre
201
+ if is_url and "?" in base_name:
202
+ base_name = base_name.split("?")[0]
203
+
204
  folder_name = re.sub(r'[<>:"/\\|?*]', '_', base_name)
205
  folder_name = re.sub(r'\s+', ' ', folder_name).strip().replace(' ', '_')
206
  for old, new in [("a", "4"), ("A", "4"), ("i", "1"), ("I", "1"), ("o", "0"), ("O", "0")]:
 
210
  temp_folder = tempfile.mkdtemp(prefix="video_conv_")
211
  out_folder = os.path.join(temp_folder, folder_name)
212
  os.makedirs(out_folder, exist_ok=True)
213
+ log_func(f"Carpeta creada: {folder_name}")
214
 
215
  all_audio_path = os.path.join(out_folder, f"{folder_name}_all_audio.mp4")
216
  cmd = ["ffmpeg", "-y"] + extra_input_options + ["-i", source, "-map", "0:v:0", "-map", "0:a?"]
 
221
  cmd.extend(["-map_metadata", "0", "-metadata", "copyright=Power Prods", all_audio_path])
222
 
223
  success, msg = self.run_ffmpeg(cmd, duration, progress, "Convirtiendo")
224
+ if not success or self.cancelled: return False, f"Error conversión: {msg}", None, None
225
 
 
226
  target_filename = f"{folder_name}_all_audio.mp4"
227
 
228
  if extract_sub and info.subtitle_tracks:
229
  log_func("Extrayendo subtítulo...")
230
  vtt_path = os.path.join(out_folder, f"{folder_name}_sub_{sub_index}.vtt")
 
231
  sub_cmd = ["ffmpeg", "-y"] + extra_input_options + ["-i", source, "-map", f"0:s:{sub_index}", "-c:s", "webvtt", vtt_path]
232
  subprocess.run(sub_cmd, capture_output=True)
233
 
234
  if generate_single:
235
  log_func("Generando versión individual...")
236
  single_path = os.path.join(out_folder, f"{folder_name}_audio_{selected_audio}.mp4")
 
237
  single_cmd = ["ffmpeg", "-y", "-i", all_audio_path, "-map", "0:v:0", "-map", f"0:a:{selected_audio}", "-c:v", "copy", "-c:a", "copy", "-map_metadata", "0", single_path]
238
+ success, msg = self.run_ffmpeg(single_cmd, duration, progress, "Individual")
239
  if not success: return False, f"Error: {msg}", None, None
240
  target_filename = f"{folder_name}_audio_{selected_audio}.mp4"
241
 
 
269
  commit_message=f"Upload {folder_name}"
270
  )
271
 
 
272
  if target_filename:
273
  direct_link = f"https://huggingface.co/{repo_id}/resolve/main/{repo_path}/{target_filename}"
274
  else:
 
285
  if file_input: source = file_input.name
286
  elif url_input: source = url_input; is_url = True
287
  else: return None, None, "Selecciona archivo o URL."
288
+
289
  info = MediaAnalyzer.get_media_info(source)
290
+
291
+ # Verificar si hubo error en el análisis
292
+ if hasattr(info, 'error_message'):
293
+ return None, None, f"❌ ERROR: {info.error_message}"
294
+
295
  audio_choices = [f"{i}: {t.display_name()}" for i, t in enumerate(info.audio_tracks)]
296
  sub_choices = [f"{i}: {t.display_name()}" for i, t in enumerate(info.subtitle_tracks)]
297
+
298
  return (
299
  gr.Dropdown(choices=audio_choices, value=0 if audio_choices else None, interactive=True),
300
  gr.Dropdown(choices=sub_choices, value=0 if sub_choices else None, interactive=True),
301
+ f"✅ Analizado: {info.title or os.path.basename(source)}\nDuración: {info.duration}s\nAudios: {len(info.audio_tracks)} | Subs: {len(info.subtitle_tracks)}"
302
  )
303
 
304
  def process_and_upload(file_input, url_input, token, target_model, mode,
 
337
  return final_msg, final_msg
338
 
339
  with gr.Blocks(theme=gr.themes.Soft(), css=CUSTOM_CSS) as demo:
340
+ gr.Markdown("# 🎬 Video Converter Pro (GDrive Worker Fix)")
341
+ gr.Markdown("Convierte enlaces complicados (Workers/Proxies) analizando primero con headers correctos.")
342
 
343
  with gr.Row():
344
  with gr.Column(scale=1):
 
360
 
361
  with gr.Column(scale=2):
362
  with gr.Tab("Archivo"): file_input = gr.File(label="Subir Video", file_types=["video"])
363
+ with gr.Tab("URL"): url_input = gr.Textbox(label="Enlace Video (Soporta GDrive Workers)")
364
 
365
+ btn_analyze = gr.Button("🔍 Analizar Video", variant="secondary")
366
+ analysis_info = gr.Textbox(label="Info", lines=3, interactive=False)
367
  btn_process = gr.Button("🚀 PROCESAR Y SUBIR", variant="primary", size="lg")
368
 
369
+ output_box = gr.Textbox(label="Resultados", lines=8, interactive=False)
370
 
371
  btn_load_models.click(fn=get_user_models, inputs=[token_input], outputs=[target_model_dd])
372
  btn_analyze.click(fn=analyze_media, inputs=[file_input, url_input], outputs=[audio_dd, sub_dd, analysis_info])