gnosticdev commited on
Commit
9e5ee0a
verified
1 Parent(s): 68837b6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +121 -32
app.py CHANGED
@@ -3,7 +3,7 @@ import re
3
  import random
4
  import time
5
  import logging
6
- from typing import Optional, List
7
  from datetime import datetime
8
  from pathlib import Path
9
 
@@ -25,15 +25,28 @@ try:
25
  import numpy as np
26
  from transformers import pipeline
27
  import backoff
 
28
  except ImportError as e:
29
  logger.error(f"Error importing dependencies: {e}")
30
  raise
31
 
32
  # Constantes configurables
33
- MAX_VIDEOS = 3 # Reducir para evitar rate limiting
34
- VIDEO_SEGMENT_DURATION = 5 # Duraci贸n de cada segmento en segundos
35
- MAX_RETRIES = 3 # M谩ximo de reintentos para descargas
36
- REQUEST_TIMEOUT = 15 # Timeout para requests
 
 
 
 
 
 
 
 
 
 
 
 
37
 
38
  # Configuraci贸n de modelos
39
  MODEL_NAME = "facebook/mbart-large-50"
@@ -45,7 +58,7 @@ PEXELS_API_KEY = os.getenv("PEXELS_API_KEY", "")
45
  max_tries=MAX_RETRIES,
46
  max_time=30)
47
  def safe_download(url: str, timeout: int = REQUEST_TIMEOUT) -> Optional[str]:
48
- """Descarga segura con reintentos y manejo de rate limiting"""
49
  try:
50
  response = requests.get(url, stream=True, timeout=timeout)
51
  response.raise_for_status()
@@ -69,6 +82,25 @@ def safe_download(url: str, timeout: int = REQUEST_TIMEOUT) -> Optional[str]:
69
  logger.error(f"Unexpected download error: {str(e)}")
70
  return None
71
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72
  def download_video_segment(url: str, duration: float, output_path: str) -> bool:
73
  """Descarga y procesa un segmento de video"""
74
  temp_path = None
@@ -85,7 +117,6 @@ def download_video_segment(url: str, duration: float, output_path: str) -> bool:
85
  end_time = min(duration, clip.duration - 0.1)
86
  subclip = clip.subclip(0, end_time)
87
 
88
- # Configuraci贸n optimizada para HF Spaces
89
  subclip.write_videofile(
90
  output_path,
91
  codec="libx264",
@@ -93,10 +124,7 @@ def download_video_segment(url: str, duration: float, output_path: str) -> bool:
93
  threads=2,
94
  preset='ultrafast',
95
  verbose=False,
96
- ffmpeg_params=[
97
- '-max_muxing_queue_size', '1024',
98
- '-movflags', '+faststart'
99
- ]
100
  )
101
  return True
102
 
@@ -108,7 +136,7 @@ def download_video_segment(url: str, duration: float, output_path: str) -> bool:
108
  os.remove(temp_path)
109
 
110
  def fetch_pexels_videos(query: str) -> List[str]:
111
- """Busca videos en Pexels con manejo de errores"""
112
  if not PEXELS_API_KEY:
113
  logger.error("PEXELS_API_KEY no configurada")
114
  return []
@@ -123,7 +151,7 @@ def fetch_pexels_videos(query: str) -> List[str]:
123
  videos = []
124
  for video in response.json().get("videos", [])[:MAX_VIDEOS]:
125
  video_files = [vf for vf in video.get("video_files", [])
126
- if vf.get("width", 0) >= 720] # Calidad m铆nima
127
  if video_files:
128
  best_file = max(video_files, key=lambda x: x.get("width", 0))
129
  videos.append(best_file["link"])
@@ -134,8 +162,11 @@ def fetch_pexels_videos(query: str) -> List[str]:
134
  logger.error(f"Error fetching Pexels videos: {str(e)}")
135
  return []
136
 
137
- def generate_script(prompt: str) -> str:
138
- """Genera un script usando IA local con fallback"""
 
 
 
139
  try:
140
  generator = pipeline("text-generation", model=MODEL_NAME)
141
  result = generator(
@@ -148,10 +179,10 @@ def generate_script(prompt: str) -> str:
148
  logger.error(f"Error generating script: {str(e)}")
149
  return f"1. Punto uno sobre {prompt}\n2. Punto dos\n3. Punto tres"
150
 
151
- async def generate_voice(text: str, output_file: str = "voice.mp3") -> bool:
152
- """Genera narraci贸n de voz con manejo de errores"""
153
  try:
154
- communicate = edge_tts.Communicate(text, voice="es-MX-DaliaNeural")
155
  await communicate.save(output_file)
156
  return True
157
  except Exception as e:
@@ -159,7 +190,7 @@ async def generate_voice(text: str, output_file: str = "voice.mp3") -> bool:
159
  return False
160
 
161
  def run_async(coro):
162
- """Ejecuta corrutinas as铆ncronas desde c贸digo s铆ncrono"""
163
  import asyncio
164
  loop = asyncio.new_event_loop()
165
  asyncio.set_event_loop(loop)
@@ -168,11 +199,16 @@ def run_async(coro):
168
  finally:
169
  loop.close()
170
 
171
- def create_video(prompt: str) -> Optional[str]:
 
 
 
 
 
172
  """Funci贸n principal para crear el video"""
173
  try:
174
  # 1. Generar contenido
175
- script = generate_script(prompt)
176
  logger.info(f"Script generado: {script[:100]}...")
177
 
178
  # 2. Buscar videos
@@ -183,11 +219,20 @@ def create_video(prompt: str) -> Optional[str]:
183
 
184
  # 3. Generar voz
185
  voice_file = "voice.mp3"
186
- if not run_async(generate_voice(script, voice_file)):
187
  logger.error("No se pudo generar voz")
188
  return None
189
 
190
- # 4. Procesar videos
 
 
 
 
 
 
 
 
 
191
  output_dir = "output"
192
  os.makedirs(output_dir, exist_ok=True)
193
  output_path = os.path.join(output_dir, f"video_{datetime.now().strftime('%Y%m%d_%H%M%S')}.mp4")
@@ -204,10 +249,17 @@ def create_video(prompt: str) -> Optional[str]:
204
  logger.error("No se pudieron procesar los videos")
205
  return None
206
 
207
- # 5. Ensamblar video final
208
  final_video = concatenate_videoclips(clips, method="compose")
209
- audio_clip = AudioFileClip(voice_file)
210
- final_video = final_video.set_audio(audio_clip)
 
 
 
 
 
 
 
211
 
212
  final_video.write_videofile(
213
  output_path,
@@ -229,31 +281,68 @@ def create_video(prompt: str) -> Optional[str]:
229
  clip.close()
230
  if os.path.exists(voice_file):
231
  os.remove(voice_file)
 
 
232
  for i in range(len(video_urls)):
233
  if os.path.exists(f"segment_{i}.mp4"):
234
  os.remove(f"segment_{i}.mp4")
235
 
236
- # Interfaz Gradio optimizada
237
- with gr.Blocks(title="Generador de Videos HF", theme=gr.themes.Soft()) as app:
238
- gr.Markdown("# 馃帴 Generador Autom谩tico de Videos")
239
 
240
  with gr.Row():
241
  with gr.Column():
242
  prompt_input = gr.Textbox(
243
  label="Tema del video",
244
- placeholder="Ej: Paisajes naturales de Chile",
245
  max_lines=2
246
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
247
  generate_btn = gr.Button("Generar Video", variant="primary")
248
 
249
  with gr.Column():
250
- output_video = gr.Video(label="Resultado", interactive=False)
 
 
 
 
251
 
252
  generate_btn.click(
253
  fn=create_video,
254
- inputs=prompt_input,
 
 
 
 
 
255
  outputs=output_video
256
  )
 
 
 
 
 
 
 
257
 
258
  # Para Hugging Face Spaces
259
  if __name__ == "__main__":
 
3
  import random
4
  import time
5
  import logging
6
+ from typing import Optional, List, Dict
7
  from datetime import datetime
8
  from pathlib import Path
9
 
 
25
  import numpy as np
26
  from transformers import pipeline
27
  import backoff
28
+ from pydub import AudioSegment
29
  except ImportError as e:
30
  logger.error(f"Error importing dependencies: {e}")
31
  raise
32
 
33
  # Constantes configurables
34
+ MAX_VIDEOS = 3
35
+ VIDEO_SEGMENT_DURATION = 5
36
+ MAX_RETRIES = 3
37
+ REQUEST_TIMEOUT = 15
38
+
39
+ # Voces disponibles en Edge TTS (espa帽ol)
40
+ VOICES = {
41
+ "Femenino MX": "es-MX-DaliaNeural",
42
+ "Masculino MX": "es-MX-JorgeNeural",
43
+ "Femenino ES": "es-ES-ElviraNeural",
44
+ "Masculino ES": "es-ES-AlvaroNeural",
45
+ "Femenino CO": "es-CO-SalomeNeural",
46
+ "Masculino CO": "es-CO-GonzaloNeural",
47
+ "Femenino AR": "es-AR-ElenaNeural",
48
+ "Masculino AR": "es-AR-TomasNeural"
49
+ }
50
 
51
  # Configuraci贸n de modelos
52
  MODEL_NAME = "facebook/mbart-large-50"
 
58
  max_tries=MAX_RETRIES,
59
  max_time=30)
60
  def safe_download(url: str, timeout: int = REQUEST_TIMEOUT) -> Optional[str]:
61
+ """Descarga segura con reintentos"""
62
  try:
63
  response = requests.get(url, stream=True, timeout=timeout)
64
  response.raise_for_status()
 
82
  logger.error(f"Unexpected download error: {str(e)}")
83
  return None
84
 
85
+ def process_music(music_path: str, target_duration: float) -> str:
86
+ """Procesa m煤sica para loop y duraci贸n correcta"""
87
+ processed_path = "processed_music.mp3"
88
+ try:
89
+ audio = AudioSegment.from_file(music_path)
90
+
91
+ # Crear loop si es m谩s corto que el video
92
+ if len(audio) < target_duration * 1000:
93
+ loops_needed = int(target_duration * 1000 / len(audio)) + 1
94
+ audio = audio * loops_needed
95
+
96
+ # Recortar a la duraci贸n exacta
97
+ audio = audio[:int(target_duration * 1000)]
98
+ audio.export(processed_path, format="mp3")
99
+ return processed_path
100
+ except Exception as e:
101
+ logger.error(f"Error processing music: {str(e)}")
102
+ return music_path # Fallback al original
103
+
104
  def download_video_segment(url: str, duration: float, output_path: str) -> bool:
105
  """Descarga y procesa un segmento de video"""
106
  temp_path = None
 
117
  end_time = min(duration, clip.duration - 0.1)
118
  subclip = clip.subclip(0, end_time)
119
 
 
120
  subclip.write_videofile(
121
  output_path,
122
  codec="libx264",
 
124
  threads=2,
125
  preset='ultrafast',
126
  verbose=False,
127
+ ffmpeg_params=['-max_muxing_queue_size', '1024']
 
 
 
128
  )
129
  return True
130
 
 
136
  os.remove(temp_path)
137
 
138
  def fetch_pexels_videos(query: str) -> List[str]:
139
+ """Busca videos en Pexels"""
140
  if not PEXELS_API_KEY:
141
  logger.error("PEXELS_API_KEY no configurada")
142
  return []
 
151
  videos = []
152
  for video in response.json().get("videos", [])[:MAX_VIDEOS]:
153
  video_files = [vf for vf in video.get("video_files", [])
154
+ if vf.get("width", 0) >= 720]
155
  if video_files:
156
  best_file = max(video_files, key=lambda x: x.get("width", 0))
157
  videos.append(best_file["link"])
 
162
  logger.error(f"Error fetching Pexels videos: {str(e)}")
163
  return []
164
 
165
+ def generate_script(prompt: str, custom_script: Optional[str] = None) -> str:
166
+ """Genera un script usando IA o custom text"""
167
+ if custom_script and custom_script.strip():
168
+ return custom_script.strip()
169
+
170
  try:
171
  generator = pipeline("text-generation", model=MODEL_NAME)
172
  result = generator(
 
179
  logger.error(f"Error generating script: {str(e)}")
180
  return f"1. Punto uno sobre {prompt}\n2. Punto dos\n3. Punto tres"
181
 
182
+ async def generate_voice(text: str, voice_id: str, output_file: str = "voice.mp3") -> bool:
183
+ """Genera narraci贸n de voz"""
184
  try:
185
+ communicate = edge_tts.Communicate(text, voice=voice_id)
186
  await communicate.save(output_file)
187
  return True
188
  except Exception as e:
 
190
  return False
191
 
192
  def run_async(coro):
193
+ """Ejecuta corrutinas as铆ncronas"""
194
  import asyncio
195
  loop = asyncio.new_event_loop()
196
  asyncio.set_event_loop(loop)
 
199
  finally:
200
  loop.close()
201
 
202
+ def create_video(
203
+ prompt: str,
204
+ custom_script: Optional[str] = None,
205
+ voice_choice: str = "es-MX-DaliaNeural",
206
+ music_file: Optional[str] = None
207
+ ) -> Optional[str]:
208
  """Funci贸n principal para crear el video"""
209
  try:
210
  # 1. Generar contenido
211
+ script = generate_script(prompt, custom_script)
212
  logger.info(f"Script generado: {script[:100]}...")
213
 
214
  # 2. Buscar videos
 
219
 
220
  # 3. Generar voz
221
  voice_file = "voice.mp3"
222
+ if not run_async(generate_voice(script, voice_choice, voice_file)):
223
  logger.error("No se pudo generar voz")
224
  return None
225
 
226
+ # 4. Procesar m煤sica si existe
227
+ music_path = None
228
+ if music_file:
229
+ audio_clip = AudioFileClip(voice_file)
230
+ target_duration = audio_clip.duration
231
+ audio_clip.close()
232
+
233
+ music_path = process_music(music_file.name, target_duration)
234
+
235
+ # 5. Procesar videos
236
  output_dir = "output"
237
  os.makedirs(output_dir, exist_ok=True)
238
  output_path = os.path.join(output_dir, f"video_{datetime.now().strftime('%Y%m%d_%H%M%S')}.mp4")
 
249
  logger.error("No se pudieron procesar los videos")
250
  return None
251
 
252
+ # 6. Ensamblar video final
253
  final_video = concatenate_videoclips(clips, method="compose")
254
+ voice_audio = AudioFileClip(voice_file)
255
+
256
+ if music_path:
257
+ music_audio = AudioFileClip(music_path)
258
+ final_audio = CompositeAudioClip([voice_audio, music_audio.volumex(0.3)])
259
+ else:
260
+ final_audio = voice_audio
261
+
262
+ final_video = final_video.set_audio(final_audio)
263
 
264
  final_video.write_videofile(
265
  output_path,
 
281
  clip.close()
282
  if os.path.exists(voice_file):
283
  os.remove(voice_file)
284
+ if music_path and os.path.exists(music_path):
285
+ os.remove(music_path)
286
  for i in range(len(video_urls)):
287
  if os.path.exists(f"segment_{i}.mp4"):
288
  os.remove(f"segment_{i}.mp4")
289
 
290
+ # Interfaz Gradio completa
291
+ with gr.Blocks(title="Generador de Videos Avanzado", theme=gr.themes.Soft()) as app:
292
+ gr.Markdown("# 馃幀 Generador de Videos con IA")
293
 
294
  with gr.Row():
295
  with gr.Column():
296
  prompt_input = gr.Textbox(
297
  label="Tema del video",
298
+ placeholder="Ej: Lugares tur铆sticos de Argentina",
299
  max_lines=2
300
  )
301
+
302
+ custom_script_input = gr.TextArea(
303
+ label="Guion personalizado (opcional)",
304
+ placeholder="Pega aqu铆 tu propio guion si lo tienes...",
305
+ lines=5
306
+ )
307
+
308
+ voice_dropdown = gr.Dropdown(
309
+ label="Selecciona una voz",
310
+ choices=list(VOICES.keys()),
311
+ value="Femenino MX"
312
+ )
313
+
314
+ music_input = gr.File(
315
+ label="M煤sica de fondo (opcional)",
316
+ type="file",
317
+ file_types=["audio"]
318
+ )
319
+
320
  generate_btn = gr.Button("Generar Video", variant="primary")
321
 
322
  with gr.Column():
323
+ output_video = gr.Video(
324
+ label="Video Resultante",
325
+ interactive=False,
326
+ format="mp4"
327
+ )
328
 
329
  generate_btn.click(
330
  fn=create_video,
331
+ inputs=[
332
+ prompt_input,
333
+ custom_script_input,
334
+ gr.Dropdown(value="es-MX-DaliaNeural", visible=False), # Valor real de voz
335
+ music_input
336
+ ],
337
  outputs=output_video
338
  )
339
+
340
+ # Actualizar el valor de voz real cuando cambia el dropdown
341
+ voice_dropdown.change(
342
+ lambda x: VOICES[x],
343
+ inputs=voice_dropdown,
344
+ outputs=gr.Dropdown(visible=False)
345
+ )
346
 
347
  # Para Hugging Face Spaces
348
  if __name__ == "__main__":