gnosticdev commited on
Commit
1e90d4c
·
verified ·
1 Parent(s): a45d148

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +295 -953
app.py CHANGED
@@ -1,993 +1,335 @@
1
  import os
 
2
  import logging
3
  import tempfile
4
  import requests
5
  from datetime import datetime
 
6
  import gradio as gr
7
  import torch
8
  from transformers import GPT2Tokenizer, GPT2LMHeadModel
9
  from keybert import KeyBERT
10
- from TTS.api import TTS
11
- from moviepy.editor import VideoFileClip, concatenate_videoclips, AudioFileClip, CompositeAudioClip, concatenate_audioclips, AudioClip
12
  import re
13
- import math
14
- import shutil
15
  import json
16
- from collections import Counter
17
-
18
- # Variable global para TTS
19
- tts_model = None
20
 
21
  # Configuración de logging
22
- logging.basicConfig(
23
- level=logging.DEBUG,
24
- format='%(asctime)s - %(levelname)s - %(message)s',
25
- handlers=[
26
- logging.StreamHandler(),
27
- logging.FileHandler('video_generator_full.log', encoding='utf-8')
28
- ]
29
- )
30
  logger = logging.getLogger(__name__)
31
- logger.info("="*80)
32
- logger.info("INICIO DE EJECUCIÓN - GENERADOR DE VIDEOS")
33
- logger.info("="*80)
34
-
35
- # Clave API de Pexels
36
- PEXELS_API_KEY = os.environ.get("PEXELS_API_KEY")
37
- if not PEXELS_API_KEY:
38
- logger.critical("NO SE ENCONTRÓ PEXELS_API_KEY EN VARIABLES DE ENTORNO")
39
-
40
- # Inicialización de modelos
41
- MODEL_NAME = "datificate/gpt2-small-spanish"
42
- logger.info(f"Inicializando modelo GPT-2: {MODEL_NAME}")
43
- tokenizer = None
44
- model = None
45
- try:
46
- tokenizer = GPT2Tokenizer.from_pretrained(MODEL_NAME)
47
- model = GPT2LMHeadModel.from_pretrained(MODEL_NAME).eval()
48
- if tokenizer.pad_token is None:
49
- tokenizer.pad_token = tokenizer.eos_token
50
- logger.info(f"Modelo GPT-2 cargado | Vocabulario: {len(tokenizer)} tokens")
51
- except Exception as e:
52
- logger.error(f"FALLA CRÍTICA al cargar GPT-2: {str(e)}", exc_info=True)
53
- tokenizer = model = None
54
-
55
- logger.info("Cargando modelo KeyBERT...")
56
- kw_model = None
57
- try:
58
- kw_model = KeyBERT('distilbert-base-multilingual-cased')
59
- logger.info("KeyBERT inicializado correctamente")
60
- except Exception as e:
61
- logger.error(f"FALLA al cargar KeyBERT: {str(e)}", exc_info=True)
62
- kw_model = None
63
 
64
- def buscar_videos_pexels(query, api_key, per_page=5):
65
- if not api_key:
66
- logger.warning("No se puede buscar en Pexels: API Key no configurada.")
67
- return []
68
-
69
- logger.debug(f"Buscando en Pexels: '{query}' | Resultados: {per_page}")
70
- headers = {"Authorization": api_key}
71
- try:
72
- params = {
73
- "query": query,
74
- "per_page": per_page,
75
- "orientation": "landscape",
76
- "size": "medium"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77
  }
78
 
79
- response = requests.get(
80
- "https://api.pexels.com/videos/search",
81
- headers=headers,
82
- params=params,
83
- timeout=20
84
- )
85
- response.raise_for_status()
86
-
87
- data = response.json()
88
- videos = data.get('videos', [])
89
- logger.info(f"Pexels: {len(videos)} videos encontrados para '{query}'")
90
- return videos
91
-
92
- except requests.exceptions.RequestException as e:
93
- logger.error(f"Error de conexión Pexels para '{query}': {str(e)}")
94
- except json.JSONDecodeError:
95
- logger.error(f"Pexels: JSON inválido recibido | Status: {response.status_code} | Respuesta: {response.text[:200]}...")
96
- except Exception as e:
97
- logger.error(f"Error inesperado Pexels para '{query}': {str(e)}", exc_info=True)
98
-
99
- return []
100
-
101
- def generate_script(prompt, max_length=150):
102
- logger.info(f"Generando guión | Prompt: '{prompt[:50]}...' | Longitud máxima: {max_length}")
103
- if not tokenizer or not model:
104
- logger.warning("Modelos GPT-2 no disponibles - Usando prompt original como guion.")
105
- return prompt.strip()
106
-
107
- instruction_phrase_start = "Escribe un guion corto, interesante y coherente sobre:"
108
- ai_prompt = f"{instruction_phrase_start} {prompt}"
109
-
110
- try:
111
- inputs = tokenizer(ai_prompt, return_tensors="pt", truncation=True, max_length=512)
112
- device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
113
- model.to(device)
114
- inputs = {k: v.to(device) for k, v in inputs.items()}
115
-
116
- outputs = model.generate(
117
- **inputs,
118
- max_length=max_length + inputs[list(inputs.keys())[0]].size(1),
119
- do_sample=True,
120
- top_p=0.9,
121
- top_k=40,
122
- temperature=0.7,
123
- repetition_penalty=1.2,
124
- pad_token_id=tokenizer.pad_token_id,
125
- eos_token_id=tokenizer.eos_token_id,
126
- no_repeat_ngram_size=3
127
- )
128
-
129
- text = tokenizer.decode(outputs[0], skip_special_tokens=True)
130
-
131
- cleaned_text = text.strip()
132
  try:
133
- instruction_end_idx = text.find(instruction_phrase_start)
134
- if instruction_end_idx != -1:
135
- cleaned_text = text[instruction_end_idx + len(instruction_phrase_start):].strip()
136
- logger.debug("Instrucción inicial encontrada y eliminada del guión generado.")
137
- else:
138
- instruction_start_idx = text.find(instruction_phrase_start)
139
- if instruction_start_idx != -1:
140
- prompt_in_output_idx = text.find(prompt, instruction_start_idx)
141
- if prompt_in_output_idx != -1:
142
- cleaned_text = text[prompt_in_output_idx + len(prompt):].strip()
143
- logger.debug("Instrucción base y prompt encontrados y eliminados del guión generado.")
144
- else:
145
- cleaned_text = text[instruction_start_idx + len(instruction_phrase_start):].strip()
146
- logger.debug("Instrucción base encontrada, eliminada del guión generado (sin prompt detectado).")
147
-
148
- except Exception as e:
149
- logger.warning(f"Error durante la limpieza heurística del guión de IA: {e}. Usando texto generado sin limpieza adicional.")
150
- cleaned_text = re.sub(r'<[^>]+>', '', text).strip()
151
-
152
- if not cleaned_text or len(cleaned_text) < 10:
153
- logger.warning("El guión generado parece muy corto o vacío después de la limpieza. Usando el texto generado original (sin limpieza heurística).")
154
- cleaned_text = re.sub(r'<[^>]+>', '', text).strip()
155
-
156
- cleaned_text = re.sub(r'<[^>]+>', '', cleaned_text).strip()
157
- cleaned_text = cleaned_text.lstrip(':').strip()
158
- cleaned_text = cleaned_text.lstrip('.').strip()
159
-
160
- sentences = cleaned_text.split('.')
161
- if sentences and sentences[0].strip():
162
- final_text = sentences[0].strip() + '.'
163
- if len(sentences) > 1 and sentences[1].strip() and len(final_text.split()) < max_length * 0.7:
164
- final_text += " " + sentences[1].strip() + "."
165
- final_text = final_text.replace("..", ".")
166
-
167
- logger.info(f"Guion generado final (Truncado a 100 chars): '{final_text[:100]}...'")
168
- return final_text.strip()
169
-
170
- logger.info(f"Guion generado final (sin oraciones completas detectadas - Truncado): '{cleaned_text[:100]}...'")
171
- return cleaned_text.strip()
172
-
173
- except Exception as e:
174
- logger.error(f"Error generando guion con GPT-2 (fuera del bloque de limpieza): {str(e)}", exc_info=True)
175
- logger.warning("Usando prompt original como guion debido al error de generación.")
176
- return prompt.strip()
177
 
178
- def text_to_speech(text, output_path, voice=None):
179
- logger.info(f"Convirtiendo texto a voz con Coqui TTS | Caracteres: {len(text)} | Salida: {output_path}")
180
- if not text or not text.strip():
181
- logger.warning("Texto vacío para TTS")
182
- return False
183
-
184
  try:
185
- # Usar modelo específico para español, sin GPU
186
- tts = TTS(model_name="tts_models/es/css10/vits", progress_bar=False, gpu=False)
 
187
 
188
- # Limpiar y truncar texto
189
- text = text.replace("na hora", "A la hora")
190
- text = re.sub(r'[^\w\s.,!?áéíóúñÁÉÍÓÚÑ]', '', text)
191
- if len(text) > 500:
192
- logger.warning("Texto demasiado largo, truncando a 500 caracteres")
193
- text = text[:500]
194
 
195
- # Generar audio sin especificar idioma
196
- tts.tts_to_file(text=text, file_path=output_path)
197
-
198
- # Verificar archivo generado
199
- if os.path.exists(output_path) and os.path.getsize(output_path) > 1000:
200
- logger.info(f"Audio creado: {output_path} | Tamaño: {os.path.getsize(output_path)} bytes")
201
- return True
202
  else:
203
- logger.error("Archivo de audio vacío o no creado")
204
- return False
205
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
206
  except Exception as e:
207
- logger.error(f"Error TTS: {str(e)}", exc_info=True)
208
- return False
209
-
210
- def download_video_file(url, temp_dir):
211
- if not url:
212
- logger.warning("URL de video no proporcionada para descargar")
213
- return None
214
-
215
- try:
216
- logger.info(f"Descargando video desde: {url[:80]}...")
217
- os.makedirs(temp_dir, exist_ok=True)
218
- file_name = f"video_dl_{datetime.now().strftime('%Y%m%d_%H%M%S_%f')}.mp4"
219
- output_path = os.path.join(temp_dir, file_name)
220
-
221
- with requests.get(url, stream=True, timeout=60) as r:
222
- r.raise_for_status()
223
- with open(output_path, 'wb') as f:
224
- for chunk in r.iter_content(chunk_size=8192):
225
- f.write(chunk)
226
-
227
- if os.path.exists(output_path) and os.path.getsize(output_path) > 1000:
228
- logger.info(f"Video descargado exitosamente: {output_path} | Tamaño: {os.path.getsize(output_path)} bytes")
229
- return output_path
230
- else:
231
- logger.warning(f"Descarga parece incompleta o vacía para {url[:80]}... Archivo: {output_path} Tamaño: {os.path.getsize(output_path) if os.path.exists(output_path) else 'N/A'} bytes")
232
- if os.path.exists(output_path):
233
- os.remove(output_path)
234
- return None
235
-
236
- except requests.exceptions.RequestException as e:
237
- logger.error(f"Error de descarga para {url[:80]}... : {str(e)}")
238
- except Exception as e:
239
- logger.error(f"Error inesperado descargando {url[:80]}... : {str(e)}", exc_info=True)
240
-
241
- return None
242
-
243
- def loop_audio_to_length(audio_clip, target_duration):
244
- logger.debug(f"Ajustando audio | Duración actual: {audio_clip.duration:.2f}s | Objetivo: {target_duration:.2f}s")
245
-
246
- if audio_clip is None or audio_clip.duration is None or audio_clip.duration <= 0:
247
- logger.warning("Input audio clip is invalid (None or zero duration), cannot loop.")
248
- try:
249
- sr = getattr(audio_clip, 'fps', 44100) if audio_clip else 44100
250
- return AudioClip(lambda t: 0, duration=target_duration, sr=sr)
251
- except Exception as e:
252
- logger.error(f"Could not create silence clip: {e}", exc_info=True)
253
- return AudioFileClip(filename="")
254
-
255
- if audio_clip.duration >= target_duration:
256
- logger.debug("Audio clip already longer or equal to target. Trimming.")
257
- trimmed_clip = audio_clip.subclip(0, target_duration)
258
- if trimmed_clip.duration is None or trimmed_clip.duration <= 0:
259
- logger.error("Trimmed audio clip is invalid.")
260
- try: trimmed_clip.close()
261
- except: pass
262
- return AudioFileClip(filename="")
263
- return trimmed_clip
264
-
265
- loops = math.ceil(target_duration / audio_clip.duration)
266
- logger.debug(f"Creando {loops} loops de audio")
267
-
268
- audio_segments = [audio_clip] * loops
269
- looped_audio = None
270
- final_looped_audio = None
271
- try:
272
- looped_audio = concatenate_audioclips(audio_segments)
273
-
274
- if looped_audio.duration is None or looped_audio.duration <= 0:
275
- logger.error("Concatenated audio clip is invalid (None or zero duration).")
276
- raise ValueError("Invalid concatenated audio.")
277
-
278
- final_looped_audio = looped_audio.subclip(0, target_duration)
279
-
280
- if final_looped_audio.duration is None or final_looped_audio.duration <= 0:
281
- logger.error("Final subclipped audio clip is invalid (None or zero duration).")
282
- raise ValueError("Invalid final subclipped audio.")
283
-
284
- return final_looped_audio
285
-
286
- except Exception as e:
287
- logger.error(f"Error concatenating/subclipping audio clips for looping: {str(e)}", exc_info=True)
288
- try:
289
- if audio_clip.duration is not None and audio_clip.duration > 0:
290
- logger.warning("Returning original audio clip (may be too short).")
291
- return audio_clip.subclip(0, min(audio_clip.duration, target_duration))
292
- except:
293
- pass
294
- logger.error("Fallback to original audio clip failed.")
295
- return AudioFileClip(filename="")
296
-
297
- finally:
298
- if looped_audio is not None and looped_audio is not final_looped_audio:
299
- try: looped_audio.close()
300
- except: pass
301
-
302
- def extract_visual_keywords_from_script(script_text):
303
- logger.info("Extrayendo palabras clave del guion")
304
- if not script_text or not script_text.strip():
305
- logger.warning("Guion vacío, no se pueden extraer palabras clave.")
306
- return ["naturaleza", "ciudad", "paisaje"]
307
-
308
- clean_text = re.sub(r'[^\w\sáéíóúñÁÉÍÓÚÑ]', '', script_text)
309
- keywords_list = []
310
-
311
- if kw_model:
312
- try:
313
- logger.debug("Intentando extracción con KeyBERT...")
314
- keywords1 = kw_model.extract_keywords(clean_text, keyphrase_ngram_range=(1, 1), stop_words='spanish', top_n=5)
315
- keywords2 = kw_model.extract_keywords(clean_text, keyphrase_ngram_range=(2, 2), stop_words='spanish', top_n=3)
316
-
317
- all_keywords = keywords1 + keywords2
318
- all_keywords.sort(key=lambda item: item[1], reverse=True)
319
-
320
- seen_keywords = set()
321
- for keyword, score in all_keywords:
322
- formatted_keyword = keyword.lower().replace(" ", "+")
323
- if formatted_keyword and formatted_keyword not in seen_keywords:
324
- keywords_list.append(formatted_keyword)
325
- seen_keywords.add(formatted_keyword)
326
- if len(keywords_list) >= 5:
327
- break
328
-
329
- if keywords_list:
330
- logger.debug(f"Palabras clave extraídas por KeyBERT: {keywords_list}")
331
- return keywords_list
332
-
333
- except Exception as e:
334
- logger.warning(f"KeyBERT falló: {str(e)}. Intentando método simple.")
335
-
336
- logger.debug("Extrayendo palabras clave con método simple...")
337
- words = clean_text.lower().split()
338
- stop_words = {"el", "la", "los", "las", "de", "en", "y", "a", "que", "es", "un", "una", "con", "para", "del", "al", "por", "su", "sus", "se", "lo", "le", "me", "te", "nos", "os", "les", "mi", "tu",
339
- "nuestro", "vuestro", "este", "ese", "aquel", "esta", "esa", "aquella", "esto", "eso", "aquello", "mis", "tus",
340
- "nuestros", "vuestros", "estas", "esas", "aquellas", "si", "no", "más", "menos", "sin", "sobre", "bajo", "entre", "hasta", "desde", "durante", "mediante", "según", "versus", "via", "cada", "todo", "todos", "toda", "todas", "poco", "pocos", "poca", "pocas", "mucho", "muchos", "mucha", "muchas", "varios", "varias", "otro", "otros", "otra", "otras", "mismo", "misma", "mismos", "mismas", "tan", "tanto", "tanta", "tantos", "tantas", "tal", "tales", "cual", "cuales", "cuyo", "cuya", "cuyos", "cuyas", "quien", "quienes", "cuan", "cuanto", "cuanta", "cuantos", "cuantas", "como", "donde", "cuando", "porque", "aunque", "mientras", "siempre", "nunca", "jamás", "muy", "casi", "solo", "solamente", "incluso", "apenas", "quizás", "tal vez", "acaso", "claro", "cierto", "obvio", "evidentemente", "realmente", "simplemente", "generalmente", "especialmente", "principalmente", "posiblemente", "probablemente", "difícilmente", "fácilmente", "rápidamente", "lentamente", "bien", "mal", "mejor", "peor", "arriba", "abajo", "adelante", "atrás", "cerca", "lejos", "dentro", "fuera", "encima", "debajo", "frente", "detrás", "antes", "después", "luego", "pronto", "tarde", "todavía", "ya", "aun", "aún", "quizá"}
341
-
342
- valid_words = [word for word in words if len(word) > 3 and word not in stop_words]
343
-
344
- if not valid_words:
345
- logger.warning("No se encontraron palabras clave válidas con método simple. Usando palabras clave predeterminadas.")
346
- return ["naturaleza", "ciudad", "paisaje"]
347
-
348
- word_counts = Counter(valid_words)
349
- top_keywords = [word.replace(" ", "+") for word, _ in word_counts.most_common(5)]
350
-
351
- if not top_keywords:
352
- logger.warning("El método simple no produjo keywords. Usando palabras clave predeterminadas.")
353
- return ["naturaleza", "ciudad", "paisaje"]
354
-
355
- logger.info(f"Palabras clave finales: {top_keywords}")
356
- return top_keywords
357
-
358
- def crear_video(prompt_type, input_text, musica_file=None):
359
- logger.info("="*80)
360
- logger.info(f"INICIANDO CREACIÓN DE VIDEO | Tipo: {prompt_type}")
361
- logger.debug(f"Input: '{input_text[:100]}...'")
362
-
363
- start_time = datetime.now()
364
- temp_dir_intermediate = None
365
-
366
- audio_tts_original = None
367
- musica_audio_original = None
368
- audio_tts = None
369
- musica_audio = None
370
- video_base = None
371
- video_final = None
372
- source_clips = []
373
- clips_to_concatenate = []
374
-
375
  try:
376
- # 1. Generar o usar guion
377
- if prompt_type == "Generar Guion con IA":
378
- guion = generate_script(input_text)
379
- else:
380
- guion = input_text.strip()
381
-
382
- logger.info(f"Guion final ({len(guion)} chars): '{guion[:100]}...'")
383
-
384
- if not guion.strip():
385
- logger.error("El guion resultante está vacío o solo contiene espacios.")
386
- raise ValueError("El guion está vacío.")
387
-
388
- # Corregir error tipográfico en el guion
389
- guion = guion.replace("na hora", "A la hora")
390
-
391
- temp_dir_intermediate = tempfile.mkdtemp(prefix="video_gen_intermediate_")
392
- logger.info(f"Directorio temporal intermedio creado: {temp_dir_intermediate}")
393
- temp_intermediate_files = []
394
-
395
- # 2. Generar audio de voz
396
- logger.info("Generando audio de voz...")
397
- voz_path = os.path.join(temp_dir_intermediate, "voz.mp3")
398
-
399
- # Llamar a text_to_speech directamente
400
- tts_success = text_to_speech(guion, voz_path)
401
-
402
- if not tts_success or not os.path.exists(voz_path) or os.path.getsize(voz_path) <= 1000:
403
- logger.error(f"Fallo en la generación de voz. Archivo de audio no creado o es muy pequeño: {voz_path}")
404
- raise ValueError("Error generando voz a partir del guion (fallo de TTS).")
405
-
406
- temp_intermediate_files.append(voz_path)
407
-
408
- audio_tts_original = AudioFileClip(voz_path)
409
-
410
- if audio_tts_original.reader is None or audio_tts_original.duration is None or audio_tts_original.duration <= 0:
411
- logger.critical("Clip de audio TTS inicial es inválido (reader is None o duración <= 0) *después* de crear AudioFileClip.")
412
- try: audio_tts_original.close()
413
- except: pass
414
- audio_tts_original = None
415
- raise ValueError("Audio de voz generado es inválido después de procesamiento inicial.")
416
-
417
- audio_tts = audio_tts_original
418
- audio_duration = audio_tts_original.duration
419
- logger.info(f"Duración audio voz: {audio_duration:.2f} segundos")
420
-
421
- if audio_duration < 1.0:
422
- logger.error(f"Duración audio voz ({audio_duration:.2f}s) es muy corta.")
423
- raise ValueError("Generated voice audio is too short (min 1 second required).")
424
-
425
- # 3. Extraer palabras clave
426
- logger.info("Extrayendo palabras clave...")
427
- try:
428
- keywords = extract_visual_keywords_from_script(guion)
429
- logger.info(f"Palabras clave identificadas: {keywords}")
430
- except Exception as e:
431
- logger.error(f"Error extrayendo keywords: {str(e)}", exc_info=True)
432
- keywords = ["naturaleza", "paisaje"]
433
-
434
- if not keywords:
435
- keywords = ["video", "background"]
436
-
437
- # 4. Buscar y descargar videos
438
- logger.info("Buscando videos en Pexels...")
439
- videos_data = []
440
- total_desired_videos = 10
441
- per_page_per_keyword = max(1, total_desired_videos // len(keywords))
442
-
443
- for keyword in keywords:
444
- if len(videos_data) >= total_desired_videos: break
445
- try:
446
- videos = buscar_videos_pexels(keyword, PEXELS_API_KEY, per_page=per_page_per_keyword)
447
- if videos:
448
- videos_data.extend(videos)
449
- logger.info(f"Encontrados {len(videos)} videos para '{keyword}'. Total data: {len(videos_data)}")
450
- except Exception as e:
451
- logger.warning(f"Error buscando videos para '{keyword}': {str(e)}")
452
-
453
- if len(videos_data) < total_desired_videos / 2:
454
- logger.warning(f"Pocos videos encontrados ({len(videos_data)}). Intentando con palabras clave genéricas.")
455
- generic_keywords = ["nature", "city", "background", "abstract"]
456
- for keyword in generic_keywords:
457
- if len(videos_data) >= total_desired_videos: break
458
- try:
459
- videos = buscar_videos_pexels(keyword, PEXELS_API_KEY, per_page=2)
460
- if videos:
461
- videos_data.extend(videos)
462
- logger.info(f"Encontrados {len(videos)} videos para '{keyword}' (genérico). Total data: {len(videos_data)}")
463
- except Exception as e:
464
- logger.warning(f"Error buscando videos genéricos para '{keyword}': {str(e)}")
465
-
466
- if not videos_data:
467
- logger.error("No se encontraron videos en Pexels para ninguna palabra clave.")
468
- raise ValueError("No se encontraron videos adecuados en Pexels.")
469
-
470
- video_paths = []
471
- logger.info(f"Intentando descargar {len(videos_data)} videos encontrados...")
472
- for video in videos_data:
473
- if 'video_files' not in video or not video['video_files']:
474
- logger.debug(f"Saltando video sin archivos de video: {video.get('id')}")
475
- continue
476
-
477
- try:
478
- best_quality = None
479
- for vf in sorted(video['video_files'], key=lambda x: x.get('width', 0) * x.get('height', 0), reverse=True):
480
- if 'link' in vf:
481
- best_quality = vf
482
- break
483
-
484
- if best_quality and 'link' in best_quality:
485
- path = download_video_file(best_quality['link'], temp_dir_intermediate)
486
- if path:
487
- video_paths.append(path)
488
- temp_intermediate_files.append(path)
489
- logger.info(f"Video descargado OK desde {best_quality['link'][:50]}...")
490
- else:
491
- logger.warning(f"No se pudo descargar video desde {best_quality['link'][:50]}...")
492
- else:
493
- logger.warning(f"No se encontró enlace de descarga válido para video {video.get('id')}.")
494
-
495
- except Exception as e:
496
- logger.warning(f"Error procesando/descargando video {video.get('id')}: {str(e)}")
497
-
498
- logger.info(f"Descargados {len(video_paths)} archivos de video utilizables.")
499
- if not video_paths:
500
- logger.error("No se pudo descargar ningún archivo de video utilizable.")
501
- raise ValueError("No se pudo descargar ningún video utilizable de Pexels.")
502
-
503
- # 5. Procesar y concatenar clips de video
504
- logger.info("Procesando y concatenando videos descargados...")
505
- current_duration = 0
506
- min_clip_duration = 0.5
507
- max_clip_segment = 10.0
508
-
509
- for i, path in enumerate(video_paths):
510
- if current_duration >= audio_duration + max_clip_segment:
511
- logger.debug(f"Video base suficiente ({current_duration:.1f}s >= {audio_duration:.1f}s + {max_clip_segment:.1f}s buffer). Dejando de procesar clips fuente restantes.")
512
- break
513
-
514
- clip = None
515
- try:
516
- logger.debug(f"[{i+1}/{len(video_paths)}] Abriendo clip: {path}")
517
- clip = VideoFileClip(path)
518
- source_clips.append(clip)
519
-
520
- if clip.reader is None or clip.duration is None or clip.duration <= 0:
521
- logger.warning(f"[{i+1}/{len(video_paths)}] Clip fuente {path} parece inválido (reader is None o duración <= 0). Saltando.")
522
- continue
523
-
524
- remaining_needed = audio_duration - current_duration
525
- potential_use_duration = min(clip.duration, max_clip_segment)
526
-
527
- if remaining_needed > 0:
528
- segment_duration = min(potential_use_duration, remaining_needed + min_clip_duration)
529
- segment_duration = max(min_clip_duration, segment_duration)
530
- segment_duration = min(segment_duration, clip.duration)
531
-
532
- if segment_duration >= min_clip_duration:
533
- try:
534
- sub = clip.subclip(0, segment_duration)
535
- if sub.reader is None or sub.duration is None or sub.duration <= 0:
536
- logger.warning(f"[{i+1}/{len(video_paths)}] Subclip generado de {path} es inválido. Saltando.")
537
- try: sub.close()
538
- except: pass
539
- continue
540
-
541
- clips_to_concatenate.append(sub)
542
- current_duration += sub.duration
543
- logger.debug(f"[{i+1}/{len(video_paths)}] Segmento añadido: {sub.duration:.1f}s (total video: {current_duration:.1f}/{audio_duration:.1f}s)")
544
-
545
- except Exception as sub_e:
546
- logger.warning(f"[{i+1}/{len(video_paths)}] Error creando subclip de {path} ({segment_duration:.1f}s): {str(sub_e)}")
547
- continue
548
- else:
549
- logger.debug(f"[{i+1}/{len(video_paths)}] Clip {path} ({clip.duration:.1f}s) no contribuye un segmento suficiente ({segment_duration:.1f}s necesario). Saltando.")
550
- else:
551
- logger.debug(f"[{i+1}/{len(video_paths)}] Duración de video base ya alcanzada. Saltando clip.")
552
-
553
- except Exception as e:
554
- logger.warning(f"[{i+1}/{len(video_paths)}] Error procesando video {path}: {str(e)}", exc_info=True)
555
- continue
556
-
557
- logger.info(f"Procesamiento de clips fuente finalizado. Se obtuvieron {len(clips_to_concatenate)} segmentos válidos.")
558
-
559
- if not clips_to_concatenate:
560
- logger.error("No hay segmentos de video válidos disponibles para crear la secuencia.")
561
- raise ValueError("No hay segmentos de video válidos disponibles para crear el video.")
562
-
563
- logger.info(f"Concatenando {len(clips_to_concatenate)} segmentos de video.")
564
- concatenated_base = None
565
- try:
566
- concatenated_base = concatenate_videoclips(clips_to_concatenate, method="chain")
567
- logger.info(f"Duración video base después de concatenación inicial: {concatenated_base.duration:.2f}s")
568
-
569
- if concatenated_base is None or concatenated_base.duration is None or concatenated_base.duration <= 0:
570
- logger.critical("Video base concatenado es inválido después de la primera concatenación (None o duración cero).")
571
- raise ValueError("Fallo al crear video base válido a partir de segmentos.")
572
-
573
- except Exception as e:
574
- logger.critical(f"Error durante la concatenación inicial: {str(e)}", exc_info=True)
575
- raise ValueError("Fallo durante la concatenación de video inicial.")
576
- finally:
577
- for clip_segment in clips_to_concatenate:
578
- try: clip_segment.close()
579
- except: pass
580
- clips_to_concatenate = []
581
-
582
- video_base = concatenated_base
583
-
584
- final_video_base = video_base
585
-
586
- if final_video_base.duration < audio_duration:
587
- logger.info(f"Video base ({final_video_base.duration:.2f}s) es más corto que el audio ({audio_duration:.2f}s). Repitiendo...")
588
-
589
- num_full_repeats = int(audio_duration // final_video_base.duration)
590
- remaining_duration = audio_duration % final_video_base.duration
591
-
592
- repeated_clips_list = [final_video_base] * num_full_repeats
593
- if remaining_duration > 0:
594
- try:
595
- remaining_clip = final_video_base.subclip(0, remaining_duration)
596
- if remaining_clip is None or remaining_clip.duration is None or remaining_clip.duration <= 0:
597
- logger.warning(f"Subclip generado para duración restante {remaining_duration:.2f}s es inválido. Saltando.")
598
- try: remaining_clip.close()
599
- except: pass
600
- else:
601
- repeated_clips_list.append(remaining_clip)
602
- logger.debug(f"Añadiendo segmento restante: {remaining_duration:.2f}s")
603
-
604
- except Exception as e:
605
- logger.warning(f"Error creando subclip para duración restante {remaining_duration:.2f}s: {str(e)}")
606
-
607
- if repeated_clips_list:
608
- logger.info(f"Concatenando {len(repeated_clips_list)} partes para repetición.")
609
- video_base_repeated = None
610
- try:
611
- video_base_repeated = concatenate_videoclips(repeated_clips_list, method="chain")
612
- logger.info(f"Duración del video base repetido: {video_base_repeated.duration:.2f}s")
613
-
614
- if video_base_repeated is None or video_base_repeated.duration is None or video_base_repeated.duration <= 0:
615
- logger.critical("Video base repetido concatenado es inválido.")
616
- raise ValueError("Fallo al crear video base repetido válido.")
617
-
618
- if final_video_base is not video_base_repeated:
619
- try: final_video_base.close()
620
- except: pass
621
-
622
- final_video_base = video_base_repeated
623
-
624
- except Exception as e:
625
- logger.critical(f"Error durante la concatenación de repetición: {str(e)}", exc_info=True)
626
- raise ValueError("Fallo durante la repetición de video.")
627
- finally:
628
- if 'repeated_clips_list' in locals():
629
- for clip in repeated_clips_list:
630
- if clip is not final_video_base:
631
- try: clip.close()
632
- except: pass
633
-
634
- if final_video_base.duration > audio_duration:
635
- logger.info(f"Recortando video base ({final_video_base.duration:.2f}s) para que coincida con la duración del audio ({audio_duration:.2f}s).")
636
- trimmed_video_base = None
637
- try:
638
- trimmed_video_base = final_video_base.subclip(0, audio_duration)
639
- if trimmed_video_base is None or trimmed_video_base.duration is None or trimmed_video_base.duration <= 0:
640
- logger.critical("Video base recortado es inválido.")
641
- raise ValueError("Fallo al crear video base recortado válido.")
642
-
643
- if final_video_base is not trimmed_video_base:
644
- try: final_video_base.close()
645
- except: pass
646
-
647
- final_video_base = trimmed_video_base
648
-
649
- except Exception as e:
650
- logger.critical(f"Error durante el recorte: {str(e)}", exc_info=True)
651
- raise ValueError("Fallo durante el recorte de video.")
652
-
653
- if final_video_base is None or final_video_base.duration is None or final_video_base.duration <= 0:
654
- logger.critical("Video base final es inválido antes de audio/escritura (None o duración cero).")
655
- raise ValueError("Video base final es inválido.")
656
-
657
- if final_video_base.size is None or final_video_base.size[0] <= 0 or final_video_base.size[1] <= 0:
658
- logger.critical(f"Video base final tiene tamaño inválido: {final_video_base.size}. No se puede escribir video.")
659
- raise ValueError("Video base final tiene tamaño inválido antes de escribir.")
660
-
661
- video_base = final_video_base
662
-
663
- # 6. Manejar música de fondo
664
- logger.info("Procesando audio...")
665
-
666
- final_audio = audio_tts_original
667
-
668
- musica_audio_looped = None
669
-
670
- if musica_file:
671
- musica_audio_original = None
672
- try:
673
- music_path = os.path.join(temp_dir_intermediate, "musica_bg.mp3")
674
- shutil.copyfile(musica_file, music_path)
675
- temp_intermediate_files.append(music_path)
676
- logger.info(f"Música de fondo copiada a: {music_path}")
677
-
678
- musica_audio_original = AudioFileClip(music_path)
679
-
680
- if musica_audio_original.reader is None or musica_audio_original.duration is None or musica_audio_original.duration <= 0:
681
- logger.warning("Clip de música de fondo parece inválido o tiene duración cero. Saltando música.")
682
- try: musica_audio_original.close()
683
- except: pass
684
- musica_audio_original = None
685
- else:
686
- musica_audio_looped = loop_audio_to_length(musica_audio_original, video_base.duration)
687
- logger.debug(f"Música ajustada a duración del video: {musica_audio_looped.duration:.2f}s")
688
-
689
- if musica_audio_looped is None or musica_audio_looped.duration is None or musica_audio_looped.duration <= 0:
690
- logger.warning("Clip de música de fondo loopeado es inválido. Saltando música.")
691
- try: musica_audio_looped.close()
692
- except: pass
693
- musica_audio_looped = None
694
-
695
- if musica_audio_looped:
696
- composite_audio = CompositeAudioClip([
697
- musica_audio_looped.volumex(0.2), # Volumen 20% para música
698
- audio_tts_original.volumex(1.0) # Volumen 100% para voz
699
- ])
700
-
701
- if composite_audio.duration is None or composite_audio.duration <= 0:
702
- logger.warning("Clip de audio compuesto es inválido (None o duración cero). Usando solo audio de voz.")
703
- try: composite_audio.close()
704
- except: pass
705
- final_audio = audio_tts_original
706
- else:
707
- logger.info("Mezcla de audio completada (voz + música).")
708
- final_audio = composite_audio
709
- musica_audio = musica_audio_looped # Asignar para limpieza
710
-
711
- except Exception as e:
712
- logger.warning(f"Error procesando música de fondo: {str(e)}", exc_info=True)
713
- final_audio = audio_tts_original
714
- musica_audio = None
715
- logger.warning("Usando solo audio de voz debido a un error con la música.")
716
-
717
- if final_audio.duration is not None and abs(final_audio.duration - video_base.duration) > 0.2:
718
- logger.warning(f"Duración del audio final ({final_audio.duration:.2f}s) difiere significativamente del video base ({video_base.duration:.2f}s). Intentando recorte.")
719
- try:
720
- if final_audio.duration > video_base.duration:
721
- trimmed_final_audio = final_audio.subclip(0, video_base.duration)
722
- if trimmed_final_audio is None or trimmed_final_audio.duration <= 0:
723
- logger.warning("Audio final recortado es inválido. Usando audio final original.")
724
- try: trimmed_final_audio.close()
725
- except: pass
726
- else:
727
- if final_audio is not trimmed_final_audio:
728
- try: final_audio.close()
729
- except: pass
730
- final_audio = trimmed_final_audio
731
- logger.warning("Audio final recortado para que coincida con la duración del video.")
732
- except Exception as e:
733
- logger.warning(f"Error ajustando duración del audio final: {str(e)}")
734
-
735
- # 7. Crear video final
736
- logger.info("Renderizando video final...")
737
- video_final = video_base.set_audio(final_audio)
738
-
739
- if video_final is None or video_final.duration is None or video_final.duration <= 0:
740
- logger.critical("Clip de video final (con audio) es inválido antes de escribir (None o duración cero).")
741
- raise ValueError("Clip de video final es inválido antes de escribir.")
742
-
743
- output_filename = "final_video.mp4"
744
- output_path = os.path.join(temp_dir_intermediate, output_filename)
745
- logger.info(f"Escribiendo video final a: {output_path}")
746
-
747
- if not output_path or not isinstance(output_path, str):
748
- logger.critical(f"output_path no es válido: {output_path}")
749
- raise ValueError("El nombre del archivo de salida no es válido.")
750
-
751
- try:
752
- video_final.write_videofile(
753
- filename=output_path,
754
- fps=24,
755
- threads=4,
756
- codec="libx264",
757
- audio_codec="aac",
758
- preset="medium",
759
- logger='bar'
760
- )
761
- except Exception as e:
762
- logger.critical(f"Error al escribir el video final: {str(e)}", exc_info=True)
763
- raise ValueError(f"Fallo al escribir el video final: {str(e)}")
764
-
765
- total_time = (datetime.now() - start_time).total_seconds()
766
- logger.info(f"PROCESO DE VIDEO FINALIZADO | Output: {output_path} | Tiempo total: {total_time:.2f}s")
767
-
768
- return output_path
769
-
770
- except ValueError as ve:
771
- logger.error(f"ERROR CONTROLADO en crear_video: {str(ve)}")
772
- raise ve
773
- except Exception as e:
774
- logger.critical(f"ERROR CRÍTICO NO CONTROLADO en crear_video: {str(e)}", exc_info=True)
775
- raise e
776
- finally:
777
- logger.info("Iniciando limpieza de clips y archivos temporales intermedios...")
778
-
779
- for clip in source_clips:
780
- try:
781
- clip.close()
782
- except Exception as e:
783
- logger.warning(f"Error cerrando clip de video fuente en finally: {str(e)}")
784
-
785
- for clip_segment in clips_to_concatenate:
786
- try:
787
- clip_segment.close()
788
- except Exception as e:
789
- logger.warning(f"Error cerrando segmento de video en finally: {str(e)}")
790
-
791
- if musica_audio is not None:
792
- try:
793
- musica_audio.close()
794
- except Exception as e:
795
- logger.warning(f"Error cerrando musica_audio (procesada) en finally: {str(e)}")
796
-
797
- if musica_audio_original is not None and musica_audio_original is not musica_audio:
798
- try:
799
- musica_audio_original.close()
800
- except Exception as e:
801
- logger.warning(f"Error cerrando musica_audio_original en finally: {str(e)}")
802
-
803
- if audio_tts is not None and audio_tts is not audio_tts_original:
804
- try:
805
- audio_tts.close()
806
- except Exception as e:
807
- logger.warning(f"Error cerrando audio_tts (procesada) en finally: {str(e)}")
808
-
809
- if audio_tts_original is not None:
810
- try:
811
- audio_tts_original.close()
812
- except Exception as e:
813
- logger.warning(f"Error cerrando audio_tts_original en finally: {str(e)}")
814
-
815
- if video_final is not None:
816
- try:
817
- video_final.close()
818
- except Exception as e:
819
- logger.warning(f"Error cerrando video_final en finally: {str(e)}")
820
- elif video_base is not None and video_base is not video_final:
821
- try:
822
- video_base.close()
823
- except Exception as e:
824
- logger.warning(f"Error cerrando video_base en finally: {str(e)}")
825
-
826
- if temp_dir_intermediate and os.path.exists(temp_dir_intermediate):
827
- final_output_in_temp = os.path.join(temp_dir_intermediate, "final_video.mp4")
828
-
829
- for path in temp_intermediate_files:
830
- try:
831
- if os.path.isfile(path) and path != final_output_in_temp:
832
- logger.debug(f"Eliminando archivo temporal intermedio: {path}")
833
- os.remove(path)
834
- elif os.path.isfile(path) and path == final_output_in_temp:
835
- logger.debug(f"Saltando eliminación del archivo de video final: {path}")
836
- except Exception as e:
837
- logger.warning(f"No se pudo eliminar archivo temporal intermedio {path}: {str(e)}")
838
-
839
- logger.info(f"Directorio temporal intermedio {temp_dir_intermediate} persistirá para que Gradio lea el video final.")
840
-
841
- def run_app(prompt_type, prompt_ia, prompt_manual, musica_file):
842
- logger.info("="*80)
843
- logger.info("SOLICITUD RECIBIDA EN INTERFAZ")
844
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
845
  input_text = prompt_ia if prompt_type == "Generar Guion con IA" else prompt_manual
846
-
847
- output_video = None
848
- output_file = gr.update(value=None, visible=False)
849
- status_msg = gr.update(value="⏳ Procesando...", interactive=False)
850
-
851
  if not input_text or not input_text.strip():
852
- logger.warning("Texto de entrada vacío.")
853
- status_msg = gr.update(value="⚠️ Por favor, ingresa texto para el guion o el tema.", interactive=False)
854
- return output_video, output_file, status_msg
855
-
856
- logger.info(f"Tipo de entrada: {prompt_type}")
857
- logger.debug(f"Texto de entrada: '{input_text[:100]}...'")
858
- if musica_file:
859
- logger.info(f"Archivo de música recibido: {musica_file}")
860
- else:
861
- logger.info("No se proporcionó archivo de música.")
862
-
863
- try:
864
- logger.info("Llamando a crear_video...")
865
- video_path = crear_video(prompt_type, input_text, musica_file)
866
 
867
- if video_path and os.path.exists(video_path):
868
- logger.info(f"crear_video retornó path: {video_path}")
869
- logger.info(f"Tamaño del archivo de video retornado: {os.path.getsize(video_path)} bytes")
870
- output_video = video_path
871
- output_file = gr.update(value=video_path, visible=True)
872
- status_msg = gr.update(value="✅ Video generado exitosamente.", interactive=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
873
  else:
874
- logger.error(f"crear_video no retornó un path válido o el archivo no existe: {video_path}")
875
- status_msg = gr.update(value="❌ Error: La generación del video falló o el archivo no se creó correctamente.", interactive=False)
876
-
877
- except ValueError as ve:
878
- logger.warning(f"Error de validación durante la creación del video: {str(ve)}")
879
- status_msg = gr.update(value=f"⚠️ Error de validación: {str(ve)}", interactive=False)
880
- except Exception as e:
881
- logger.critical(f"Error crítico durante la creación del video: {str(e)}", exc_info=True)
882
- status_msg = gr.update(value=f"❌ Error inesperado: {str(e)}", interactive=False)
883
- finally:
884
- logger.info("Fin del handler run_app.")
885
- return output_video, output_file, status_msg
886
-
887
- with gr.Blocks(title="Generador de Videos con IA", theme=gr.themes.Soft(), css="""
888
- .gradio-container {max-width: 800px; margin: auto;}
889
- h1 {text-align: center;}
890
- """) as app:
891
-
892
- gr.Markdown("# 🎬 Generador Automático de Videos con IA")
893
- gr.Markdown("Genera videos cortos a partir de un tema o guion, usando imágenes de archivo de Pexels y voz generada.")
894
-
895
- with gr.Row():
896
- with gr.Column():
897
- prompt_type = gr.Radio(
898
- ["Generar Guion con IA", "Usar Mi Guion"],
899
- label="Método de Entrada",
900
- value="Generar Guion con IA"
901
- )
902
-
903
- with gr.Column(visible=True) as ia_guion_column:
904
- prompt_ia = gr.Textbox(
905
- label="Tema para IA",
906
- lines=2,
907
- placeholder="Ej: Un paisaje natural con montañas y ríos al amanecer, mostrando la belleza de la naturaleza...",
908
- max_lines=4,
909
- value=""
910
- )
911
-
912
- with gr.Column(visible=False) as manual_guion_column:
913
- prompt_manual = gr.Textbox(
914
- label="Tu Guion Completo",
915
- lines=5,
916
- placeholder="Ej: En este video exploraremos los misterios del océano. Veremos la vida marina fascinante y los arrecifes de coral vibrantes. ¡Acompáñanos en esta aventura subacuática!",
917
- max_lines=10,
918
- value=""
919
- )
920
-
921
- musica_input = gr.Audio(
922
- label="Música de fondo (opcional)",
923
- type="filepath",
924
- interactive=True,
925
- value=None
926
- )
927
-
928
- generate_btn = gr.Button("✨ Generar Video", variant="primary")
929
-
930
- with gr.Column():
931
- video_output = gr.Video(
932
- label="Previsualización del Video Generado",
933
- interactive=False,
934
- height=400
935
- )
936
- file_output = gr.File(
937
- label="Descargar Archivo de Video",
938
- interactive=False,
939
- visible=False
940
- )
941
- status_output = gr.Textbox(
942
- label="Estado",
943
- interactive=False,
944
- show_label=False,
945
- placeholder="Esperando acción...",
946
- value="Esperando entrada..."
947
- )
948
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
949
  prompt_type.change(
950
- lambda x: (gr.update(visible=x == "Generar Guion con IA"),
951
- gr.update(visible=x == "Usar Mi Guion")),
 
 
952
  inputs=prompt_type,
953
- outputs=[ia_guion_column, manual_guion_column]
954
  )
955
-
956
- generate_btn.click(
957
- lambda: (None, None, gr.update(value="⏳ Procesando... Esto puede tomar varios minutos.", interactive=False)),
958
- outputs=[video_output, file_output, status_output],
959
- queue=True,
960
- ).then(
961
- run_app,
962
  inputs=[prompt_type, prompt_ia, prompt_manual, musica_input],
963
- outputs=[video_output, file_output, status_output]
 
 
 
 
 
 
964
  )
965
-
966
- gr.Markdown("### Instrucciones:")
967
- gr.Markdown("""
968
- 1. **Clave API de Pexels:** Asegúrate de haber configurado la variable de entorno `PEXELS_API_KEY` con tu clave.
969
 
970
- """)
971
- gr.Markdown("---")
972
- gr.Markdown("Desarrollado por [Tu Nombre/Empresa/Alias - Opcional]")
 
 
 
 
 
 
 
 
973
 
974
  if __name__ == "__main__":
975
- logger.info("Verificando dependencias críticas...")
976
- try:
977
- from moviepy.editor import ColorClip
978
- try:
979
- temp_clip = ColorClip((100,100), color=(255,0,0), duration=0.1)
980
- temp_clip.close()
981
- logger.info("Clips base de MoviePy (como ColorClip) creados y cerrados exitosamente. FFmpeg parece accesible.")
982
- except Exception as e:
983
- logger.critical(f"Fallo al crear clip base de MoviePy. A menudo indica problemas con FFmpeg/ImageMagick. Error: {e}", exc_info=True)
984
-
985
- except Exception as e:
986
- logger.critical(f"Fallo al importar MoviePy. Asegúrate de que está instalado. Error: {e}", exc_info=True)
987
-
988
- logger.info("Iniciando aplicación Gradio...")
989
- try:
990
- app.launch(server_name="0.0.0.0", server_port=7860, share=False)
991
- except Exception as e:
992
- logger.critical(f"No se pudo iniciar la app: {str(e)}", exc_info=True)
993
- raise
 
1
  import os
2
+ import asyncio
3
  import logging
4
  import tempfile
5
  import requests
6
  from datetime import datetime
7
+ import edge_tts
8
  import gradio as gr
9
  import torch
10
  from transformers import GPT2Tokenizer, GPT2LMHeadModel
11
  from keybert import KeyBERT
12
+ from moviepy.editor import VideoFileClip, concatenate_videoclips, AudioFileClip, CompositeAudioClip
 
13
  import re
 
 
14
  import json
15
+ import uuid
16
+ import threading
17
+ from queue import Queue
18
+ import time
19
 
20
  # Configuración de logging
21
+ logging.basicConfig(level=logging.INFO)
 
 
 
 
 
 
 
22
  logger = logging.getLogger(__name__)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
 
24
+ # Directorio persistente para archivos
25
+ PERSIST_DIR = "persistent_data"
26
+ os.makedirs(PERSIST_DIR, exist_ok=True)
27
+
28
+ # Cola de procesamiento
29
+ processing_queue = Queue()
30
+ task_status = {}
31
+
32
+ # Clase para manejar tareas
33
+ class VideoTask:
34
+ def __init__(self, task_id, prompt_type, input_text, musica_file=None):
35
+ self.task_id = task_id
36
+ self.prompt_type = prompt_type
37
+ self.input_text = input_text
38
+ self.musica_file = musica_file
39
+ self.status = "pending"
40
+ self.progress = 0
41
+ self.result = None
42
+ self.error = None
43
+ self.steps_completed = []
44
+
45
+ def to_dict(self):
46
+ return {
47
+ "task_id": self.task_id,
48
+ "status": self.status,
49
+ "progress": self.progress,
50
+ "result": self.result,
51
+ "error": self.error,
52
+ "steps_completed": self.steps_completed
53
  }
54
 
55
+ # Worker thread para procesar videos
56
+ def video_processor_worker():
57
+ while True:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58
  try:
59
+ task = processing_queue.get(timeout=1)
60
+ if task is None:
61
+ break
62
+
63
+ logger.info(f"Procesando tarea: {task.task_id}")
64
+ process_video_task(task)
65
+
66
+ except:
67
+ time.sleep(0.1)
68
+ continue
69
+
70
+ # Iniciar worker thread
71
+ worker_thread = threading.Thread(target=video_processor_worker, daemon=True)
72
+ worker_thread.start()
73
+
74
+ def save_task_state(task):
75
+ """Guarda el estado de la tarea en un archivo JSON"""
76
+ task_file = os.path.join(PERSIST_DIR, f"{task.task_id}.json")
77
+ with open(task_file, 'w') as f:
78
+ json.dump(task.to_dict(), f)
79
+
80
+ def load_task_state(task_id):
81
+ """Carga el estado de una tarea desde archivo"""
82
+ task_file = os.path.join(PERSIST_DIR, f"{task_id}.json")
83
+ if os.path.exists(task_file):
84
+ with open(task_file, 'r') as f:
85
+ return json.load(f)
86
+ return None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
87
 
88
+ def process_video_task(task):
89
+ """Procesa una tarea de video paso a paso"""
 
 
 
 
90
  try:
91
+ task.status = "processing"
92
+ task.progress = 0
93
+ save_task_state(task)
94
 
95
+ # Paso 1: Generar guión
96
+ task.progress = 10
97
+ save_task_state(task)
 
 
 
98
 
99
+ if task.prompt_type == "Generar Guion con IA":
100
+ guion = generate_script_simple(task.input_text)
 
 
 
 
 
101
  else:
102
+ guion = task.input_text.strip()
 
103
 
104
+ task.steps_completed.append("guion_generado")
105
+ task.progress = 20
106
+ save_task_state(task)
107
+
108
+ # Paso 2: Generar audio TTS
109
+ audio_path = os.path.join(PERSIST_DIR, f"{task.task_id}_audio.mp3")
110
+ success = asyncio.run(text_to_speech_simple(guion, audio_path))
111
+
112
+ if not success:
113
+ raise Exception("Error generando audio")
114
+
115
+ task.steps_completed.append("audio_generado")
116
+ task.progress = 40
117
+ save_task_state(task)
118
+
119
+ # Paso 3: Buscar videos (simplificado)
120
+ keywords = extract_keywords_simple(guion)
121
+ video_urls = search_videos_simple(keywords)
122
+
123
+ task.steps_completed.append("videos_encontrados")
124
+ task.progress = 60
125
+ save_task_state(task)
126
+
127
+ # Paso 4: Crear video final (simplificado)
128
+ output_path = os.path.join(PERSIST_DIR, f"{task.task_id}_final.mp4")
129
+
130
+ # Simulación de creación de video
131
+ # En producción, aquí iría tu lógica de moviepy
132
+ create_simple_video(video_urls, audio_path, output_path, task.musica_file)
133
+
134
+ task.steps_completed.append("video_creado")
135
+ task.progress = 100
136
+ task.status = "completed"
137
+ task.result = output_path
138
+ save_task_state(task)
139
+
140
  except Exception as e:
141
+ logger.error(f"Error procesando tarea {task.task_id}: {str(e)}")
142
+ task.status = "error"
143
+ task.error = str(e)
144
+ save_task_state(task)
145
+
146
+ # Funciones simplificadas
147
+ def generate_script_simple(prompt):
148
+ """Versión simplificada de generación de guión"""
149
+ # Aquí puedes usar tu lógica GPT-2 existente
150
+ return f"Este es un video sobre {prompt}. Es fascinante y educativo."
151
+
152
+ async def text_to_speech_simple(text, output_path):
153
+ """TTS simplificado"""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
154
  try:
155
+ communicate = edge_tts.Communicate(text, "es-ES-JuanNeural")
156
+ await communicate.save(output_path)
157
+ return os.path.exists(output_path)
158
+ except:
159
+ return False
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
160
 
161
+ def extract_keywords_simple(text):
162
+ """Extracción simple de keywords"""
163
+ words = text.lower().split()
164
+ # Filtrar palabras comunes
165
+ keywords = [w for w in words if len(w) > 4][:3]
166
+ return keywords if keywords else ["nature", "video", "background"]
167
+
168
+ def search_videos_simple(keywords):
169
+ """Búsqueda simplificada de videos"""
170
+ # Aquí iría tu lógica de Pexels
171
+ # Por ahora retornamos URLs de ejemplo
172
+ return ["video1.mp4", "video2.mp4"]
173
+
174
+ def create_simple_video(video_urls, audio_path, output_path, music_path=None):
175
+ """Creación simplificada de video"""
176
+ # Aquí iría tu lógica de MoviePy
177
+ # Por ahora creamos un archivo dummy
178
+ with open(output_path, 'w') as f:
179
+ f.write("dummy video content")
180
+ time.sleep(2) # Simular procesamiento
181
+
182
+ # Interfaz Gradio mejorada
183
+ def submit_video_request(prompt_type, prompt_ia, prompt_manual, musica_file):
184
+ """Envía una solicitud de video a la cola"""
185
  input_text = prompt_ia if prompt_type == "Generar Guion con IA" else prompt_manual
186
+
 
 
 
 
187
  if not input_text or not input_text.strip():
188
+ return None, "Por favor ingresa un texto"
189
+
190
+ task_id = str(uuid.uuid4())
191
+ task = VideoTask(task_id, prompt_type, input_text, musica_file)
192
+
193
+ # Guardar estado inicial
194
+ task_status[task_id] = task
195
+ save_task_state(task)
196
+
197
+ # Añadir a la cola
198
+ processing_queue.put(task)
199
+
200
+ return task_id, f"Tarea creada: {task_id}"
 
201
 
202
+ def check_video_status(task_id):
203
+ """Verifica el estado de una tarea"""
204
+ if not task_id:
205
+ return "No hay ID de tarea", None, None
206
+
207
+ # Intentar cargar desde archivo
208
+ task_data = load_task_state(task_id)
209
+
210
+ if not task_data:
211
+ return "Tarea no encontrada", None, None
212
+
213
+ status = task_data['status']
214
+ progress = task_data['progress']
215
+
216
+ if status == "pending":
217
+ return f"⏳ En cola... ({progress}%)", None, None
218
+ elif status == "processing":
219
+ steps = ", ".join(task_data['steps_completed'])
220
+ return f"🔄 Procesando... ({progress}%) - Completado: {steps}", None, None
221
+ elif status == "completed":
222
+ video_path = task_data['result']
223
+ if os.path.exists(video_path):
224
+ return "✅ Video completado!", video_path, video_path
225
  else:
226
+ return " Video completado pero archivo no encontrado", None, None
227
+ elif status == "error":
228
+ return f"❌ Error: {task_data['error']}", None, None
229
+
230
+ return "Estado desconocido", None, None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
231
 
232
+ # Interfaz Gradio
233
+ with gr.Blocks(title="Generador de Videos con IA") as app:
234
+ gr.Markdown("# 🎬 Generador de Videos con IA (Sistema de Cola)")
235
+
236
+ with gr.Tabs():
237
+ with gr.TabItem("Crear Video"):
238
+ with gr.Row():
239
+ with gr.Column():
240
+ prompt_type = gr.Radio(
241
+ ["Generar Guion con IA", "Usar Mi Guion"],
242
+ label="Método de Entrada",
243
+ value="Generar Guion con IA"
244
+ )
245
+
246
+ prompt_ia = gr.Textbox(
247
+ label="Tema para IA",
248
+ placeholder="Describe el tema del video..."
249
+ )
250
+
251
+ prompt_manual = gr.Textbox(
252
+ label="Tu Guion Completo",
253
+ placeholder="Escribe tu guion aquí...",
254
+ visible=False
255
+ )
256
+
257
+ musica_input = gr.Audio(
258
+ label="Música de fondo (opcional)",
259
+ type="filepath"
260
+ )
261
+
262
+ submit_btn = gr.Button("📤 Enviar a Cola", variant="primary")
263
+
264
+ with gr.Column():
265
+ task_id_output = gr.Textbox(
266
+ label="ID de Tarea",
267
+ interactive=False
268
+ )
269
+ submit_status = gr.Textbox(
270
+ label="Estado de Envío",
271
+ interactive=False
272
+ )
273
+
274
+ with gr.TabItem("Verificar Estado"):
275
+ with gr.Row():
276
+ with gr.Column():
277
+ task_id_input = gr.Textbox(
278
+ label="ID de Tarea",
279
+ placeholder="Pega aquí el ID de tu tarea..."
280
+ )
281
+ check_btn = gr.Button("🔍 Verificar Estado")
282
+ auto_check = gr.Checkbox(
283
+ label="Verificar automáticamente cada 5 segundos"
284
+ )
285
+
286
+ with gr.Column():
287
+ status_output = gr.Textbox(
288
+ label="Estado Actual",
289
+ interactive=False
290
+ )
291
+ video_output = gr.Video(
292
+ label="Video Generado",
293
+ interactive=False
294
+ )
295
+ download_output = gr.File(
296
+ label="Descargar Video",
297
+ interactive=False
298
+ )
299
+
300
+ # Eventos
301
  prompt_type.change(
302
+ lambda x: (
303
+ gr.update(visible=x == "Generar Guion con IA"),
304
+ gr.update(visible=x == "Usar Mi Guion")
305
+ ),
306
  inputs=prompt_type,
307
+ outputs=[prompt_ia, prompt_manual]
308
  )
309
+
310
+ submit_btn.click(
311
+ submit_video_request,
 
 
 
 
312
  inputs=[prompt_type, prompt_ia, prompt_manual, musica_input],
313
+ outputs=[task_id_output, submit_status]
314
+ )
315
+
316
+ check_btn.click(
317
+ check_video_status,
318
+ inputs=[task_id_input],
319
+ outputs=[status_output, video_output, download_output]
320
  )
 
 
 
 
321
 
322
+ # Auto-check cada 5 segundos si está activado
323
+ def auto_check_status(task_id, should_check):
324
+ if should_check and task_id:
325
+ return check_video_status(task_id)
326
+ return gr.update(), gr.update(), gr.update()
327
+
328
+ auto_check.change(
329
+ lambda x: gr.update(visible=x),
330
+ inputs=[auto_check],
331
+ outputs=[check_btn]
332
+ )
333
 
334
  if __name__ == "__main__":
335
+ app.launch(server_name="0.0.0.0", server_port=7860)