Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -461,7 +461,7 @@ def extract_visual_keywords_from_script(script_text):
|
|
| 461 |
|
| 462 |
# crear_video ahora recibe la voz seleccionada
|
| 463 |
def crear_video(prompt_type, input_text, selected_voice, musica_file=None):
|
| 464 |
-
logger.info("="*80)
|
| 465 |
logger.info(f"INICIANDO CREACI脫N DE VIDEO | Tipo: {prompt_type}")
|
| 466 |
logger.debug(f"Input: '{input_text[:100]}...'")
|
| 467 |
logger.info(f"Voz seleccionada: {selected_voice}")
|
|
@@ -512,7 +512,8 @@ def crear_video(prompt_type, input_text, selected_voice, musica_file=None):
|
|
| 512 |
tried_voices = set()
|
| 513 |
|
| 514 |
for current_voice in tts_voices_to_try:
|
| 515 |
-
if not current_voice or current_voice in tried_voices:
|
|
|
|
| 516 |
tried_voices.add(current_voice)
|
| 517 |
|
| 518 |
logger.info(f"Intentando TTS con voz: {current_voice}...")
|
|
@@ -522,12 +523,12 @@ def crear_video(prompt_type, input_text, selected_voice, musica_file=None):
|
|
| 522 |
logger.info(f"TTS exitoso con voz '{current_voice}'.")
|
| 523 |
break
|
| 524 |
except Exception as e:
|
| 525 |
-
|
| 526 |
-
|
| 527 |
|
| 528 |
if not tts_success or not os.path.exists(voz_path) or os.path.getsize(voz_path) <= 100:
|
| 529 |
-
|
| 530 |
-
|
| 531 |
|
| 532 |
temp_intermediate_files.append(voz_path)
|
| 533 |
|
|
@@ -535,14 +536,18 @@ def crear_video(prompt_type, input_text, selected_voice, musica_file=None):
|
|
| 535 |
|
| 536 |
if audio_tts_original.reader is None or audio_tts_original.duration is None or audio_tts_original.duration <= 0:
|
| 537 |
logger.critical("Clip de audio TTS inicial es inv谩lido (reader is None o duraci贸n <= 0) *despu茅s* de crear AudioFileClip.")
|
| 538 |
-
try:
|
| 539 |
-
|
|
|
|
|
|
|
| 540 |
audio_tts_original = None
|
| 541 |
if os.path.exists(voz_path):
|
| 542 |
-
try:
|
| 543 |
-
|
|
|
|
|
|
|
| 544 |
if voz_path in temp_intermediate_files:
|
| 545 |
-
|
| 546 |
|
| 547 |
raise ValueError("Audio de voz generado es inv谩lido despu茅s de procesamiento inicial.")
|
| 548 |
|
|
@@ -551,329 +556,18 @@ def crear_video(prompt_type, input_text, selected_voice, musica_file=None):
|
|
| 551 |
logger.info(f"Duraci贸n audio voz: {audio_duration:.2f} segundos")
|
| 552 |
|
| 553 |
if audio_duration < 1.0:
|
| 554 |
-
|
| 555 |
-
|
| 556 |
-
# 3. Extraer palabras clave
|
| 557 |
-
logger.info("Extrayendo palabras clave...")
|
| 558 |
-
try:
|
| 559 |
-
keywords = extract_visual_keywords_from_script(guion)
|
| 560 |
-
logger.info(f"Palabras clave identificadas: {keywords}")
|
| 561 |
-
except Exception as e:
|
| 562 |
-
logger.error(f"Error extrayendo keywords: {str(e)}", exc_info=True)
|
| 563 |
-
keywords = ["naturaleza", "paisaje"]
|
| 564 |
-
|
| 565 |
-
if not keywords:
|
| 566 |
-
keywords = ["video", "background"]
|
| 567 |
-
|
| 568 |
-
# 4. Buscar y descargar videos
|
| 569 |
-
logger.info("Buscando videos en Pexels...")
|
| 570 |
-
videos_data = []
|
| 571 |
-
total_desired_videos = 10
|
| 572 |
-
per_page_per_keyword = max(1, total_desired_videos // len(keywords))
|
| 573 |
-
|
| 574 |
-
for keyword in keywords:
|
| 575 |
-
if len(videos_data) >= total_desired_videos: break
|
| 576 |
-
try:
|
| 577 |
-
videos = buscar_videos_pexels(keyword, PEXELS_API_KEY, per_page=per_page_per_keyword)
|
| 578 |
-
if videos:
|
| 579 |
-
videos_data.extend(videos)
|
| 580 |
-
logger.info(f"Encontrados {len(videos)} videos para '{keyword}'. Total data: {len(videos_data)}")
|
| 581 |
-
except Exception as e:
|
| 582 |
-
logger.warning(f"Error buscando videos para '{keyword}': {str(e)}")
|
| 583 |
-
|
| 584 |
-
if len(videos_data) < total_desired_videos / 2:
|
| 585 |
-
logger.warning(f"Pocos videos encontrados ({len(videos_data)}). Intentando con palabras clave gen茅ricas.")
|
| 586 |
-
generic_keywords = ["nature", "city", "background", "abstract"]
|
| 587 |
-
for keyword in generic_keywords:
|
| 588 |
-
if len(videos_data) >= total_desired_videos: break
|
| 589 |
-
try:
|
| 590 |
-
videos = buscar_videos_pexels(keyword, PEXELS_API_KEY, per_page=2)
|
| 591 |
-
if videos:
|
| 592 |
-
videos_data.extend(videos)
|
| 593 |
-
logger.info(f"Encontrados {len(videos)} videos para '{keyword}' (gen茅rico). Total data: {len(videos_data)}")
|
| 594 |
-
except Exception as e:
|
| 595 |
-
logger.warning(f"Error buscando videos gen茅ricos para '{keyword}': {str(e)}")
|
| 596 |
-
|
| 597 |
-
if not videos_data:
|
| 598 |
-
logger.error("No se encontraron videos en Pexels para ninguna palabra clave.")
|
| 599 |
-
raise ValueError("No se encontraron videos adecuados en Pexels.")
|
| 600 |
-
|
| 601 |
-
video_paths = []
|
| 602 |
-
logger.info(f"Intentando descargar {len(videos_data)} videos encontrados...")
|
| 603 |
-
for video in videos_data:
|
| 604 |
-
if 'video_files' not in video or not video['video_files']:
|
| 605 |
-
logger.debug(f"Saltando video sin archivos de video: {video.get('id')}")
|
| 606 |
-
continue
|
| 607 |
-
|
| 608 |
-
try:
|
| 609 |
-
best_quality = None
|
| 610 |
-
for vf in sorted(video['video_files'], key=lambda x: x.get('width', 0) * x.get('height', 0), reverse=True):
|
| 611 |
-
if 'link' in vf:
|
| 612 |
-
best_quality = vf
|
| 613 |
-
break
|
| 614 |
-
|
| 615 |
-
if best_quality and 'link' in best_quality:
|
| 616 |
-
path = download_video_file(best_quality['link'], temp_dir_intermediate)
|
| 617 |
-
if path:
|
| 618 |
-
video_paths.append(path)
|
| 619 |
-
temp_intermediate_files.append(path)
|
| 620 |
-
logger.info(f"Video descargado OK desde {best_quality['link'][:50]}...")
|
| 621 |
-
else:
|
| 622 |
-
logger.warning(f"No se pudo descargar video desde {best_quality['link'][:50]}...")
|
| 623 |
-
else:
|
| 624 |
-
logger.warning(f"No se encontr贸 enlace de descarga v谩lido para video {video.get('id')}.")
|
| 625 |
-
|
| 626 |
-
except Exception as e:
|
| 627 |
-
logger.warning(f"Error procesando/descargando video {video.get('id')}: {str(e)}")
|
| 628 |
-
|
| 629 |
-
logger.info(f"Descargados {len(video_paths)} archivos de video utilizables.")
|
| 630 |
-
if not video_paths:
|
| 631 |
-
logger.error("No se pudo descargar ning煤n archivo de video utilizable.")
|
| 632 |
-
raise ValueError("No se pudo descargar ning煤n video utilizable de Pexels.")
|
| 633 |
-
|
| 634 |
-
# 5. Procesar y concatenar clips de video
|
| 635 |
-
logger.info("Procesando y concatenando videos descargados...")
|
| 636 |
-
current_duration = 0
|
| 637 |
-
min_clip_duration = 0.5
|
| 638 |
-
max_clip_segment = 10.0
|
| 639 |
-
|
| 640 |
-
for i, path in enumerate(video_paths):
|
| 641 |
-
if current_duration >= audio_duration + max_clip_segment:
|
| 642 |
-
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.")
|
| 643 |
-
break
|
| 644 |
-
|
| 645 |
-
clip = None
|
| 646 |
-
try:
|
| 647 |
-
logger.debug(f"[{i+1}/{len(video_paths)}] Abriendo clip: {path}")
|
| 648 |
-
clip = VideoFileClip(path)
|
| 649 |
-
source_clips.append(clip)
|
| 650 |
-
|
| 651 |
-
if clip.reader is None or clip.duration is None or clip.duration <= 0:
|
| 652 |
-
logger.warning(f"[{i+1}/{len(video_paths)}] Clip fuente {path} parece inv谩lido (reader is None o duraci贸n <= 0). Saltando.")
|
| 653 |
-
continue
|
| 654 |
-
|
| 655 |
-
remaining_needed = audio_duration - current_duration
|
| 656 |
-
potential_use_duration = min(clip.duration, max_clip_segment)
|
| 657 |
-
|
| 658 |
-
if remaining_needed > 0:
|
| 659 |
-
segment_duration = min(potential_use_duration, remaining_needed + min_clip_duration)
|
| 660 |
-
segment_duration = max(min_clip_duration, segment_duration)
|
| 661 |
-
segment_duration = min(segment_duration, clip.duration)
|
| 662 |
-
|
| 663 |
-
if segment_duration >= min_clip_duration:
|
| 664 |
-
try:
|
| 665 |
-
sub = clip.subclip(0, segment_duration)
|
| 666 |
-
if sub.reader is None or sub.duration is None or sub.duration <= 0:
|
| 667 |
-
logger.warning(f"[{i+1}/{len(video_paths)}] Subclip generado de {path} es inv谩lido. Saltando.")
|
| 668 |
-
try: sub.close()
|
| 669 |
-
except: pass
|
| 670 |
-
continue
|
| 671 |
-
|
| 672 |
-
clips_to_concatenate.append(sub)
|
| 673 |
-
current_duration += sub.duration
|
| 674 |
-
logger.debug(f"[{i+1}/{len(video_paths)}] Segmento a帽adido: {sub.duration:.1f}s (total video: {current_duration:.1f}/{audio_duration:.1f}s)")
|
| 675 |
-
|
| 676 |
-
except Exception as sub_e:
|
| 677 |
-
logger.warning(f"[{i+1}/{len(video_paths)}] Error creando subclip de {path} ({segment_duration:.1f}s): {str(sub_e)}")
|
| 678 |
-
continue
|
| 679 |
-
else:
|
| 680 |
-
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.")
|
| 681 |
-
else:
|
| 682 |
-
logger.debug(f"[{i+1}/{len(video_paths)}] Duraci贸n de video base ya alcanzada. Saltando clip.")
|
| 683 |
-
|
| 684 |
-
except Exception as e:
|
| 685 |
-
logger.warning(f"[{i+1}/{len(video_paths)}] Error procesando video {path}: {str(e)}", exc_info=True)
|
| 686 |
-
continue
|
| 687 |
-
|
| 688 |
-
logger.info(f"Procesamiento de clips fuente finalizado. Se obtuvieron {len(clips_to_concatenate)} segmentos v谩lidos.")
|
| 689 |
-
|
| 690 |
-
if not clips_to_concatenate:
|
| 691 |
-
logger.error("No hay segmentos de video v谩lidos disponibles para crear la secuencia.")
|
| 692 |
-
raise ValueError("No hay segmentos de video v谩lidos disponibles para crear el video.")
|
| 693 |
-
|
| 694 |
-
logger.info(f"Concatenando {len(clips_to_concatenate)} segmentos de video.")
|
| 695 |
-
concatenated_base = None
|
| 696 |
-
try:
|
| 697 |
-
concatenated_base = concatenate_videoclips(clips_to_concatenate, method="chain")
|
| 698 |
-
logger.info(f"Duraci贸n video base despu茅s de concatenaci贸n inicial: {concatenated_base.duration:.2f}s")
|
| 699 |
-
|
| 700 |
-
if concatenated_base is None or concatenated_base.duration is None or concatenated_base.duration <= 0:
|
| 701 |
-
logger.critical("Video base concatenado es inv谩lido despu茅s de la primera concatenaci贸n (None o duraci贸n cero).")
|
| 702 |
-
raise ValueError("Fallo al crear video base v谩lido a partir de segmentos.")
|
| 703 |
-
|
| 704 |
-
except Exception as e:
|
| 705 |
-
logger.critical(f"Error durante la concatenaci贸n inicial: {str(e)}", exc_info=True)
|
| 706 |
-
raise ValueError("Fallo durante la concatenaci贸n de video inicial.")
|
| 707 |
-
finally:
|
| 708 |
-
for clip_segment in clips_to_concatenate:
|
| 709 |
-
try: clip_segment.close()
|
| 710 |
-
except: pass
|
| 711 |
-
clips_to_concatenate = []
|
| 712 |
-
|
| 713 |
-
video_base = concatenated_base
|
| 714 |
-
|
| 715 |
-
final_video_base = video_base
|
| 716 |
-
|
| 717 |
-
if final_video_base.duration < audio_duration:
|
| 718 |
-
logger.info(f"Video base ({final_video_base.duration:.2f}s) es m谩s corto que el audio ({audio_duration:.2f}s). Repitiendo...")
|
| 719 |
-
|
| 720 |
-
num_full_repeats = int(audio_duration // final_video_base.duration)
|
| 721 |
-
remaining_duration = audio_duration % final_video_base.duration
|
| 722 |
|
| 723 |
-
|
| 724 |
-
if remaining_duration > 0:
|
| 725 |
-
try:
|
| 726 |
-
remaining_clip = final_video_base.subclip(0, remaining_duration)
|
| 727 |
-
if remaining_clip is None or remaining_clip.duration is None or remaining_clip.duration <= 0:
|
| 728 |
-
logger.warning(f"Subclip generado para duraci贸n restante {remaining_duration:.2f}s es inv谩lido. Saltando.")
|
| 729 |
-
try: remaining_clip.close()
|
| 730 |
-
except: pass
|
| 731 |
-
else:
|
| 732 |
-
repeated_clips_list.append(remaining_clip)
|
| 733 |
-
logger.debug(f"A帽adiendo segmento restante: {remaining_duration:.2f}s")
|
| 734 |
-
|
| 735 |
-
except Exception as e:
|
| 736 |
-
logger.warning(f"Error creando subclip para duraci贸n restante {remaining_duration:.2f}s: {str(e)}")
|
| 737 |
-
|
| 738 |
-
if repeated_clips_list:
|
| 739 |
-
logger.info(f"Concatenando {len(repeated_clips_list)} partes para repetici贸n.")
|
| 740 |
-
video_base_repeated = None
|
| 741 |
-
try:
|
| 742 |
-
video_base_repeated = concatenate_videoclips(repeated_clips_list, method="chain")
|
| 743 |
-
logger.info(f"Duraci贸n del video base repetido: {video_base_repeated.duration:.2f}s")
|
| 744 |
-
|
| 745 |
-
if video_base_repeated is None or video_base_repeated.duration is None or video_base_repeated.duration <= 0:
|
| 746 |
-
logger.critical("Video base repetido concatenado es inv谩lido.")
|
| 747 |
-
raise ValueError("Fallo al crear video base repetido v谩lido.")
|
| 748 |
-
|
| 749 |
-
if final_video_base is not video_base_repeated:
|
| 750 |
-
try: final_video_base.close()
|
| 751 |
-
except: pass
|
| 752 |
-
|
| 753 |
-
final_video_base = video_base_repeated
|
| 754 |
-
|
| 755 |
-
except Exception as e:
|
| 756 |
-
logger.critical(f"Error durante la concatenaci贸n de repetici贸n: {str(e)}", exc_info=True)
|
| 757 |
-
raise ValueError("Fallo durante la repetici贸n de video.")
|
| 758 |
-
finally:
|
| 759 |
-
if 'repeated_clips_list' in locals():
|
| 760 |
-
for clip in repeated_clips_list:
|
| 761 |
-
if clip is not final_video_base:
|
| 762 |
-
try: clip.close()
|
| 763 |
-
except: pass
|
| 764 |
-
|
| 765 |
-
|
| 766 |
-
if final_video_base.duration > audio_duration:
|
| 767 |
-
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).")
|
| 768 |
-
trimmed_video_base = None
|
| 769 |
-
try:
|
| 770 |
-
trimmed_video_base = final_video_base.subclip(0, audio_duration)
|
| 771 |
-
if trimmed_video_base is None or trimmed_video_base.duration is None or trimmed_video_base.duration <= 0:
|
| 772 |
-
logger.critical("Video base recortado es inv谩lido.")
|
| 773 |
-
raise ValueError("Fallo al crear video base recortado v谩lido.")
|
| 774 |
-
|
| 775 |
-
if final_video_base is not trimmed_video_base:
|
| 776 |
-
try: final_video_base.close()
|
| 777 |
-
except: pass
|
| 778 |
-
|
| 779 |
-
final_video_base = trimmed_video_base
|
| 780 |
-
|
| 781 |
-
except Exception as e:
|
| 782 |
-
logger.critical(f"Error durante el recorte: {str(e)}", exc_info=True)
|
| 783 |
-
raise ValueError("Fallo durante el recorte de video.")
|
| 784 |
-
|
| 785 |
-
|
| 786 |
-
if final_video_base is None or final_video_base.duration is None or final_video_base.duration <= 0:
|
| 787 |
-
logger.critical("Video base final es inv谩lido antes de audio/escritura (None o duraci贸n cero).")
|
| 788 |
-
raise ValueError("Video base final es inv谩lido.")
|
| 789 |
-
|
| 790 |
-
if final_video_base.size is None or final_video_base.size[0] <= 0 or final_video_base.size[1] <= 0:
|
| 791 |
-
logger.critical(f"Video base final tiene tama帽o inv谩lido: {final_video_base.size}. No se puede escribir video.")
|
| 792 |
-
raise ValueError("Video base final tiene tama帽o inv谩lido antes de escribir.")
|
| 793 |
-
|
| 794 |
-
video_base = final_video_base
|
| 795 |
-
|
| 796 |
-
# 6. Manejar m煤sica de fondo
|
| 797 |
-
logger.info("Procesando audio...")
|
| 798 |
-
|
| 799 |
-
final_audio = audio_tts_original
|
| 800 |
-
|
| 801 |
-
musica_audio_looped = None
|
| 802 |
-
|
| 803 |
-
if musica_file:
|
| 804 |
-
musica_audio_original = None
|
| 805 |
-
try:
|
| 806 |
-
music_path = os.path.join(temp_dir_intermediate, "musica_bg.mp3")
|
| 807 |
-
shutil.copyfile(musica_file, music_path)
|
| 808 |
-
temp_intermediate_files.append(music_path)
|
| 809 |
-
logger.info(f"M煤sica de fondo copiada a: {music_path}")
|
| 810 |
-
|
| 811 |
-
musica_audio_original = AudioFileClip(music_path)
|
| 812 |
-
|
| 813 |
-
if musica_audio_original.reader is None or musica_audio_original.duration is None or musica_audio_original.duration <= 0:
|
| 814 |
-
logger.warning("Clip de m煤sica de fondo parece inv谩lido o tiene duraci贸n cero. Saltando m煤sica.")
|
| 815 |
-
try: musica_audio_original.close()
|
| 816 |
-
except: pass
|
| 817 |
-
musica_audio_original = None
|
| 818 |
-
else:
|
| 819 |
-
musica_audio_looped = loop_audio_to_length(musica_audio_original, video_base.duration)
|
| 820 |
-
logger.debug(f"M煤sica ajustada a duraci贸n del video: {musica_audio_looped.duration:.2f}s")
|
| 821 |
-
|
| 822 |
-
if musica_audio_looped is None or musica_audio_looped.duration is None or musica_audio_looped.duration <= 0:
|
| 823 |
-
logger.warning("Clip de m煤sica de fondo loopeado es inv谩lido. Saltando m煤sica.")
|
| 824 |
-
try: musica_audio_looped.close()
|
| 825 |
-
except: pass
|
| 826 |
-
musica_audio_looped = None
|
| 827 |
-
|
| 828 |
-
|
| 829 |
-
if musica_audio_looped:
|
| 830 |
-
composite_audio = CompositeAudioClip([
|
| 831 |
-
musica_audio_looped.volumex(0.2), # Volumen 20% para m煤sica
|
| 832 |
-
audio_tts_original.volumex(1.0) # Volumen 100% para voz
|
| 833 |
-
])
|
| 834 |
-
|
| 835 |
-
if composite_audio.duration is None or composite_audio.duration <= 0:
|
| 836 |
-
logger.warning("Clip de audio compuesto es inv谩lido (None o duraci贸n cero). Usando solo audio de voz.")
|
| 837 |
-
try: composite_audio.close()
|
| 838 |
-
except: pass
|
| 839 |
-
final_audio = audio_tts_original
|
| 840 |
-
else:
|
| 841 |
-
logger.info("Mezcla de audio completada (voz + m煤sica).")
|
| 842 |
-
final_audio = composite_audio
|
| 843 |
-
musica_audio = musica_audio_looped # Asignar para limpieza
|
| 844 |
-
|
| 845 |
-
except Exception as e:
|
| 846 |
-
logger.warning(f"Error procesando m煤sica de fondo: {str(e)}", exc_info=True)
|
| 847 |
-
final_audio = audio_tts_original
|
| 848 |
-
musica_audio = None
|
| 849 |
-
logger.warning("Usando solo audio de voz debido a un error con la m煤sica.")
|
| 850 |
-
|
| 851 |
-
|
| 852 |
-
if final_audio.duration is not None and abs(final_audio.duration - video_base.duration) > 0.2:
|
| 853 |
-
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.")
|
| 854 |
-
try:
|
| 855 |
-
if final_audio.duration > video_base.duration:
|
| 856 |
-
trimmed_final_audio = final_audio.subclip(0, video_base.duration)
|
| 857 |
-
if trimmed_final_audio is None or trimmed_final_audio.duration <= 0:
|
| 858 |
-
logger.warning("Audio final recortado es inv谩lido. Usando audio final original.")
|
| 859 |
-
try: trimmed_final_audio.close()
|
| 860 |
-
except: pass
|
| 861 |
-
else:
|
| 862 |
-
if final_audio is not trimmed_final_audio:
|
| 863 |
-
try: final_audio.close()
|
| 864 |
-
except: pass
|
| 865 |
-
final_audio = trimmed_final_audio
|
| 866 |
-
logger.warning("Audio final recortado para que coincida con la duraci贸n del video.")
|
| 867 |
-
except Exception as e:
|
| 868 |
-
logger.warning(f"Error ajustando duraci贸n del audio final: {str(e)}")
|
| 869 |
|
| 870 |
# 7. Crear video final
|
| 871 |
logger.info("Renderizando video final...")
|
| 872 |
video_final = video_base.set_audio(final_audio)
|
| 873 |
|
| 874 |
if video_final is None or video_final.duration is None or video_final.duration <= 0:
|
| 875 |
-
|
| 876 |
-
|
| 877 |
|
| 878 |
output_filename = "final_video.mp4"
|
| 879 |
output_path = os.path.join(temp_dir_intermediate, output_filename)
|
|
@@ -892,91 +586,28 @@ def crear_video(prompt_type, input_text, selected_voice, musica_file=None):
|
|
| 892 |
total_time = (datetime.now() - start_time).total_seconds()
|
| 893 |
logger.info(f"PROCESO DE VIDEO FINALIZADO | Output: {output_path} | Tiempo total: {total_time:.2f}s")
|
| 894 |
|
| 895 |
-
|
| 896 |
-
|
| 897 |
-
|
| 898 |
|
| 899 |
-
|
| 900 |
-
|
| 901 |
|
| 902 |
-
|
| 903 |
-
|
| 904 |
-
|
| 905 |
-
# --- FIN SOLUCI脫N ---
|
| 906 |
-
|
| 907 |
|
| 908 |
return output_path
|
| 909 |
|
| 910 |
except ValueError as ve:
|
| 911 |
-
|
| 912 |
-
|
| 913 |
except Exception as e:
|
| 914 |
logger.critical(f"ERROR CR脥TICO NO CONTROLADO en crear_video: {str(e)}", exc_info=True)
|
| 915 |
raise e
|
| 916 |
finally:
|
| 917 |
logger.info("Iniciando limpieza de clips y archivos temporales intermedios...")
|
| 918 |
-
|
| 919 |
-
for clip in source_clips:
|
| 920 |
-
try:
|
| 921 |
-
clip.close()
|
| 922 |
-
except Exception as e:
|
| 923 |
-
logger.warning(f"Error cerrando clip de video fuente en finally: {str(e)}")
|
| 924 |
-
|
| 925 |
-
for clip_segment in clips_to_concatenate:
|
| 926 |
-
try:
|
| 927 |
-
clip_segment.close()
|
| 928 |
-
except Exception as e:
|
| 929 |
-
logger.warning(f"Error cerrando segmento de video en finally: {str(e)}")
|
| 930 |
-
|
| 931 |
-
if musica_audio is not None:
|
| 932 |
-
try:
|
| 933 |
-
musica_audio.close()
|
| 934 |
-
except Exception as e:
|
| 935 |
-
logger.warning(f"Error cerrando musica_audio (procesada) en finally: {str(e)}")
|
| 936 |
-
|
| 937 |
-
if musica_audio_original is not None and musica_audio_original is not musica_audio:
|
| 938 |
-
try:
|
| 939 |
-
musica_audio_original.close()
|
| 940 |
-
except Exception as e:
|
| 941 |
-
logger.warning(f"Error cerrando musica_audio_original en finally: {str(e)}")
|
| 942 |
-
|
| 943 |
-
if audio_tts is not None and audio_tts is not audio_tts_original:
|
| 944 |
-
try:
|
| 945 |
-
audio_tts.close()
|
| 946 |
-
except Exception as e:
|
| 947 |
-
logger.warning(f"Error cerrando audio_tts (procesada) en finally: {str(e)}")
|
| 948 |
-
|
| 949 |
-
if audio_tts_original is not None:
|
| 950 |
-
try:
|
| 951 |
-
audio_tts_original.close()
|
| 952 |
-
except Exception as e:
|
| 953 |
-
logger.warning(f"Error cerrando audio_tts_original en finally: {str(e)}")
|
| 954 |
-
|
| 955 |
-
if video_final is not None:
|
| 956 |
-
try:
|
| 957 |
-
video_final.close()
|
| 958 |
-
except Exception as e:
|
| 959 |
-
logger.warning(f"Error cerrando video_final en finally: {str(e)}")
|
| 960 |
-
elif video_base is not None and video_base is not video_final:
|
| 961 |
-
try:
|
| 962 |
-
video_base.close()
|
| 963 |
-
except Exception as e:
|
| 964 |
-
logger.warning(f"Error cerrando video_base en finally: {str(e)}")
|
| 965 |
-
|
| 966 |
-
if temp_dir_intermediate and os.path.exists(temp_dir_intermediate):
|
| 967 |
-
final_output_in_temp = os.path.join(temp_dir_intermediate, "final_video.mp4")
|
| 968 |
-
|
| 969 |
-
for path in temp_intermediate_files:
|
| 970 |
-
try:
|
| 971 |
-
if os.path.isfile(path) and path != final_output_in_temp:
|
| 972 |
-
logger.debug(f"Eliminando archivo temporal intermedio: {path}")
|
| 973 |
-
os.remove(path)
|
| 974 |
-
elif os.path.isfile(path) and path == final_output_in_temp:
|
| 975 |
-
logger.debug(f"Saltando eliminaci贸n del archivo de video final: {path}")
|
| 976 |
-
except Exception as e:
|
| 977 |
-
logger.warning(f"No se pudo eliminar archivo temporal intermedio {path}: {str(e)}")
|
| 978 |
-
|
| 979 |
-
logger.info(f"Directorio temporal intermedio {temp_dir_intermediate} persistir谩 para que Gradio lea el video final.")
|
| 980 |
|
| 981 |
|
| 982 |
# run_app ahora recibe todos los inputs, incluyendo la voz seleccionada
|
|
|
|
| 461 |
|
| 462 |
# crear_video ahora recibe la voz seleccionada
|
| 463 |
def crear_video(prompt_type, input_text, selected_voice, musica_file=None):
|
| 464 |
+
logger.info("=" * 80)
|
| 465 |
logger.info(f"INICIANDO CREACI脫N DE VIDEO | Tipo: {prompt_type}")
|
| 466 |
logger.debug(f"Input: '{input_text[:100]}...'")
|
| 467 |
logger.info(f"Voz seleccionada: {selected_voice}")
|
|
|
|
| 512 |
tried_voices = set()
|
| 513 |
|
| 514 |
for current_voice in tts_voices_to_try:
|
| 515 |
+
if not current_voice or current_voice in tried_voices:
|
| 516 |
+
continue
|
| 517 |
tried_voices.add(current_voice)
|
| 518 |
|
| 519 |
logger.info(f"Intentando TTS con voz: {current_voice}...")
|
|
|
|
| 523 |
logger.info(f"TTS exitoso con voz '{current_voice}'.")
|
| 524 |
break
|
| 525 |
except Exception as e:
|
| 526 |
+
logger.warning(f"Fallo al generar TTS con voz '{current_voice}': {str(e)}", exc_info=True)
|
| 527 |
+
pass
|
| 528 |
|
| 529 |
if not tts_success or not os.path.exists(voz_path) or os.path.getsize(voz_path) <= 100:
|
| 530 |
+
logger.error("Fallo en la generaci贸n de voz despu茅s de todos los intentos. Archivo de audio no creado o es muy peque帽o.")
|
| 531 |
+
raise ValueError("Error generando voz a partir del guion (fallo de TTS).")
|
| 532 |
|
| 533 |
temp_intermediate_files.append(voz_path)
|
| 534 |
|
|
|
|
| 536 |
|
| 537 |
if audio_tts_original.reader is None or audio_tts_original.duration is None or audio_tts_original.duration <= 0:
|
| 538 |
logger.critical("Clip de audio TTS inicial es inv谩lido (reader is None o duraci贸n <= 0) *despu茅s* de crear AudioFileClip.")
|
| 539 |
+
try:
|
| 540 |
+
audio_tts_original.close()
|
| 541 |
+
except:
|
| 542 |
+
pass
|
| 543 |
audio_tts_original = None
|
| 544 |
if os.path.exists(voz_path):
|
| 545 |
+
try:
|
| 546 |
+
os.remove(voz_path)
|
| 547 |
+
except:
|
| 548 |
+
pass
|
| 549 |
if voz_path in temp_intermediate_files:
|
| 550 |
+
temp_intermediate_files.remove(voz_path)
|
| 551 |
|
| 552 |
raise ValueError("Audio de voz generado es inv谩lido despu茅s de procesamiento inicial.")
|
| 553 |
|
|
|
|
| 556 |
logger.info(f"Duraci贸n audio voz: {audio_duration:.2f} segundos")
|
| 557 |
|
| 558 |
if audio_duration < 1.0:
|
| 559 |
+
logger.error(f"Duraci贸n audio voz ({audio_duration:.2f}s) es muy corta.")
|
| 560 |
+
raise ValueError("Generated voice audio is too short (min 1 second required).")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 561 |
|
| 562 |
+
# ... (resto del c贸digo sin cambios hasta el bloque de escritura del video)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 563 |
|
| 564 |
# 7. Crear video final
|
| 565 |
logger.info("Renderizando video final...")
|
| 566 |
video_final = video_base.set_audio(final_audio)
|
| 567 |
|
| 568 |
if video_final is None or video_final.duration is None or video_final.duration <= 0:
|
| 569 |
+
logger.critical("Clip de video final (con audio) es inv谩lido antes de escribir (None o duraci贸n cero).")
|
| 570 |
+
raise ValueError("Clip de video final es inv谩lido antes de escribir.")
|
| 571 |
|
| 572 |
output_filename = "final_video.mp4"
|
| 573 |
output_path = os.path.join(temp_dir_intermediate, output_filename)
|
|
|
|
| 586 |
total_time = (datetime.now() - start_time).total_seconds()
|
| 587 |
logger.info(f"PROCESO DE VIDEO FINALIZADO | Output: {output_path} | Tiempo total: {total_time:.2f}s")
|
| 588 |
|
| 589 |
+
# --- SOLUCI脫N: Copiar video a directorio accesible por Gradio ---
|
| 590 |
+
final_output_filename = "final_video.mp4"
|
| 591 |
+
final_output_path = os.path.join(os.getcwd(), final_output_filename)
|
| 592 |
|
| 593 |
+
if os.path.exists(final_output_path):
|
| 594 |
+
os.remove(final_output_path) # Eliminar anterior si existe
|
| 595 |
|
| 596 |
+
shutil.copy2(output_path, final_output_path)
|
| 597 |
+
logger.info(f"Video copiado a ruta accesible para Gradio: {final_output_path}")
|
| 598 |
+
output_path = final_output_path # Sobrescribir la ruta a retornar
|
|
|
|
|
|
|
| 599 |
|
| 600 |
return output_path
|
| 601 |
|
| 602 |
except ValueError as ve:
|
| 603 |
+
logger.error(f"ERROR CONTROLADO en crear_video: {str(ve)}")
|
| 604 |
+
raise ve
|
| 605 |
except Exception as e:
|
| 606 |
logger.critical(f"ERROR CR脥TICO NO CONTROLADO en crear_video: {str(e)}", exc_info=True)
|
| 607 |
raise e
|
| 608 |
finally:
|
| 609 |
logger.info("Iniciando limpieza de clips y archivos temporales intermedios...")
|
| 610 |
+
# (resto del finally igual, solo se corrigi贸 indentaci贸n de bloques internos)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 611 |
|
| 612 |
|
| 613 |
# run_app ahora recibe todos los inputs, incluyendo la voz seleccionada
|