Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
@@ -9,7 +9,7 @@ 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, concatenate_audioclips
|
13 |
import re
|
14 |
import math
|
15 |
import shutil
|
@@ -55,7 +55,7 @@ except Exception as e:
|
|
55 |
logger.info("Loading KeyBERT model...")
|
56 |
kw_model = None
|
57 |
try:
|
58 |
-
kw_model =
|
59 |
logger.info("KeyBERT initialized successfully")
|
60 |
except Exception as e:
|
61 |
logger.error(f"FAILURE loading KeyBERT: {str(e)}", exc_info=True)
|
@@ -204,36 +204,68 @@ def download_video_file(url, temp_dir):
|
|
204 |
|
205 |
def loop_audio_to_length(audio_clip, target_duration):
|
206 |
logger.debug(f"Adjusting audio | Current duration: {audio_clip.duration:.2f}s | Target: {target_duration:.2f}s")
|
207 |
-
|
208 |
-
|
209 |
-
|
|
|
|
|
210 |
try:
|
211 |
-
|
212 |
-
|
|
|
213 |
except Exception as e:
|
214 |
-
logger.error(f"Could not create silence clip: {e}")
|
215 |
-
return AudioFileClip(filename="")
|
216 |
|
217 |
if audio_clip.duration >= target_duration:
|
218 |
-
logger.debug("Audio clip already longer or equal to target.")
|
219 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
220 |
|
221 |
loops = math.ceil(target_duration / audio_clip.duration)
|
222 |
logger.debug(f"Creating {loops} audio loops")
|
223 |
|
224 |
audio_segments = [audio_clip] * loops
|
225 |
looped_audio = None # Initialize for finally block
|
|
|
226 |
try:
|
227 |
looped_audio = concatenate_audioclips(audio_segments)
|
|
|
|
|
|
|
|
|
|
|
|
|
228 |
final_looped_audio = looped_audio.subclip(0, target_duration)
|
|
|
|
|
|
|
|
|
|
|
|
|
229 |
return final_looped_audio
|
|
|
230 |
except Exception as e:
|
231 |
-
logger.error(f"Error concatenating audio clips for looping: {str(e)}", exc_info=True)
|
232 |
-
# Fallback:
|
233 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
234 |
finally:
|
235 |
-
# Clean up the temporary concatenated clip
|
236 |
-
if looped_audio is not None:
|
237 |
try: looped_audio.close()
|
238 |
except: pass
|
239 |
|
@@ -301,8 +333,10 @@ def crear_video(prompt_type, input_text, musica_file=None):
|
|
301 |
temp_dir_intermediate = None
|
302 |
|
303 |
# Initialize clips and audio objects to None for cleanup in finally
|
304 |
-
|
305 |
-
|
|
|
|
|
306 |
video_base = None # This will hold the final video base clip before adding audio
|
307 |
video_final = None # This will hold the final clip with video and audio
|
308 |
source_clips = [] # Clips loaded from downloaded files for proper closing
|
@@ -333,7 +367,18 @@ def crear_video(prompt_type, input_text, musica_file=None):
|
|
333 |
raise ValueError("Error generating voice audio.")
|
334 |
temp_intermediate_files.append(voz_path)
|
335 |
|
336 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
337 |
audio_duration = audio_tts.duration
|
338 |
logger.info(f"Voice audio duration: {audio_duration:.2f} seconds")
|
339 |
|
@@ -494,8 +539,7 @@ def crear_video(prompt_type, input_text, musica_file=None):
|
|
494 |
concatenated_base = concatenate_videoclips(clips_to_concatenate, method="chain")
|
495 |
logger.info(f"Base video duration after initial concatenation: {concatenated_base.duration:.2f}s")
|
496 |
|
497 |
-
# Verify the resulting concatenated clip is valid
|
498 |
-
# CORRECTED CHECK for CompositeVideoClip: Check existence and duration
|
499 |
if concatenated_base is None or concatenated_base.duration is None or concatenated_base.duration <= 0:
|
500 |
logger.critical("Concatenated video base clip is invalid after first concatenation (None or zero duration).")
|
501 |
raise ValueError("Failed to create valid video base from segments.")
|
@@ -521,7 +565,7 @@ def crear_video(prompt_type, input_text, musica_file=None):
|
|
521 |
num_full_repeats = int(audio_duration // final_video_base.duration)
|
522 |
remaining_duration = audio_duration % final_video_base.duration
|
523 |
|
524 |
-
repeated_clips_list = [final_video_base] * num_full_repeats
|
525 |
|
526 |
if remaining_duration > 0:
|
527 |
try:
|
@@ -543,30 +587,36 @@ def crear_video(prompt_type, input_text, musica_file=None):
|
|
543 |
video_base_repeated = None # Hold result temporarily
|
544 |
try:
|
545 |
# Concatenate the repeated parts
|
|
|
546 |
video_base_repeated = concatenate_videoclips(repeated_clips_list, method="chain")
|
547 |
logger.info(f"Duration of repeated video base: {video_base_repeated.duration:.2f}s")
|
548 |
|
549 |
# Verify the repeated clip is valid
|
550 |
-
# CORRECTED CHECK: Check existence and duration
|
551 |
if video_base_repeated is None or video_base_repeated.duration is None or video_base_repeated.duration <= 0:
|
552 |
logger.critical("Concatenated repeated video base clip is invalid.")
|
553 |
raise ValueError("Failed to create valid repeated video base.")
|
554 |
|
555 |
-
# Close the old base clip
|
556 |
-
|
557 |
-
|
|
|
|
|
558 |
# Assign the new valid repeated clip
|
559 |
final_video_base = video_base_repeated
|
560 |
|
561 |
except Exception as e:
|
562 |
logger.critical(f"Error during repetition concatenation: {str(e)}", exc_info=True)
|
|
|
563 |
raise ValueError("Failed during video repetition.")
|
564 |
finally:
|
565 |
# Close the clips in the repeated list, EXCEPT the one assigned to final_video_base
|
566 |
-
|
567 |
-
|
568 |
-
|
569 |
-
|
|
|
|
|
|
|
570 |
|
571 |
|
572 |
# After repetition (or if no repetition happened), ensure duration matches audio exactly
|
@@ -576,14 +626,15 @@ def crear_video(prompt_type, input_text, musica_file=None):
|
|
576 |
try:
|
577 |
trimmed_video_base = final_video_base.subclip(0, audio_duration)
|
578 |
# Verify the trimmed clip is valid
|
579 |
-
# CORRECTED CHECK: Check existence and duration
|
580 |
if trimmed_video_base is None or trimmed_video_base.duration is None or trimmed_video_base.duration <= 0:
|
581 |
logger.critical("Trimmed video base clip is invalid.")
|
582 |
raise ValueError("Failed to create valid trimmed video base.")
|
583 |
|
584 |
# Close the old clip
|
585 |
-
|
586 |
-
|
|
|
|
|
587 |
# Assign the new valid trimmed clip
|
588 |
final_video_base = trimmed_video_base
|
589 |
|
@@ -593,89 +644,128 @@ def crear_video(prompt_type, input_text, musica_file=None):
|
|
593 |
|
594 |
|
595 |
# Final check on video_base before setting audio/writing
|
596 |
-
# CORRECTED CHECK: Check existence and duration
|
597 |
if final_video_base is None or final_video_base.duration is None or final_video_base.duration <= 0:
|
598 |
-
logger.critical("Final video base clip is invalid before audio/writing.")
|
599 |
raise ValueError("Final video base clip is invalid.")
|
600 |
|
|
|
|
|
|
|
|
|
|
|
601 |
video_base = final_video_base # Use the final adjusted video_base for subsequent steps
|
602 |
|
603 |
# 6. Handle background music
|
604 |
logger.info("Processing audio...")
|
605 |
|
606 |
-
final_audio = audio_tts
|
607 |
-
|
|
|
|
|
608 |
if musica_file:
|
609 |
-
|
610 |
try:
|
611 |
music_path = os.path.join(temp_dir_intermediate, "musica_bg.mp3")
|
612 |
shutil.copyfile(musica_file, music_path)
|
613 |
temp_intermediate_files.append(music_path)
|
614 |
logger.info(f"Background music copied to: {music_path}")
|
615 |
|
616 |
-
|
617 |
|
618 |
-
|
|
|
619 |
logger.warning("Background music clip seems invalid or has zero duration. Skipping music.")
|
620 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
621 |
|
622 |
-
|
623 |
-
|
624 |
-
|
|
|
|
|
|
|
|
|
625 |
|
626 |
-
# Close the original music audio clip
|
627 |
-
try: musica_audio.close()
|
628 |
-
except: pass
|
629 |
-
musica_audio = musica_audio_looped # Assign the looped/trimmed clip
|
630 |
|
|
|
|
|
631 |
final_audio = CompositeAudioClip([
|
632 |
-
|
633 |
-
audio_tts.volumex(1.0)
|
634 |
])
|
635 |
# Verify the resulting composite audio
|
636 |
if final_audio.duration is None or final_audio.duration <= 0:
|
637 |
logger.warning("Composite audio clip is invalid (None or zero duration). Using voice audio only.")
|
638 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
639 |
else:
|
640 |
logger.info("Audio mix completed (voice + music).")
|
|
|
|
|
|
|
|
|
641 |
|
642 |
except Exception as e:
|
643 |
logger.warning(f"Error processing background music: {str(e)}", exc_info=True)
|
644 |
-
|
|
|
|
|
|
|
645 |
logger.warning("Using voice audio only due to music processing error.")
|
646 |
-
# No finally here for musica_audio, it's handled in the main finally block
|
647 |
|
648 |
-
|
649 |
-
|
|
|
|
|
650 |
logger.warning(f"Final audio duration ({final_audio.duration:.2f}s) differs significantly from video base ({video_base.duration:.2f}s). Attempting trim/extend.")
|
651 |
try:
|
|
|
652 |
if final_audio.duration > video_base.duration:
|
653 |
-
|
654 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
655 |
# MoviePy often extends audio automatically if it's too short, so we don't explicitly extend here.
|
656 |
except Exception as e:
|
657 |
logger.warning(f"Error adjusting final audio duration: {str(e)}")
|
658 |
|
659 |
|
660 |
-
#
|
661 |
-
|
662 |
video_final = video_base.set_audio(final_audio)
|
663 |
|
664 |
-
# Final check on the combined video+audio clip
|
665 |
-
# CORRECTED CHECK: Check existence and duration
|
666 |
if video_final is None or video_final.duration is None or video_final.duration <= 0:
|
667 |
-
logger.critical("Final video clip (with audio) is invalid before writing.")
|
668 |
raise ValueError("Final video clip is invalid before writing.")
|
669 |
|
|
|
670 |
output_filename = "final_video.mp4"
|
671 |
output_path = os.path.join(temp_dir_intermediate, output_filename)
|
672 |
logger.info(f"Writing final video to: {output_path}")
|
673 |
|
674 |
-
# Check if video_base has a valid size before writing
|
675 |
-
if video_base.size is None or video_base.size[0] <= 0 or video_base.size[1] <= 0:
|
676 |
-
logger.critical(f"Video base has invalid size: {video_base.size}. Cannot write video.")
|
677 |
-
raise ValueError("Video base has invalid size before writing.")
|
678 |
-
|
679 |
|
680 |
video_final.write_videofile(
|
681 |
output_path,
|
@@ -701,21 +791,38 @@ def crear_video(prompt_type, input_text, musica_file=None):
|
|
701 |
finally:
|
702 |
logger.info("Starting cleanup of clips and intermediate temporary files...")
|
703 |
|
704 |
-
# Close all initially opened source clips
|
705 |
for clip in source_clips:
|
706 |
try: clip.close()
|
707 |
-
except Exception as e: logger.warning(f"Error closing source clip in finally: {str(e)}")
|
708 |
|
709 |
-
# Close any segments left in the list (should be empty if successful)
|
710 |
for clip_segment in clips_to_concatenate:
|
711 |
try: clip_segment.close()
|
712 |
-
except Exception as e: logger.warning(f"Error closing segment clip in finally: {str(e)}")
|
713 |
|
714 |
# Close the main MoviePy objects if they were successfully created
|
715 |
try:
|
716 |
-
|
717 |
-
|
718 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
719 |
if video_final is not None:
|
720 |
try: video_final.close()
|
721 |
except Exception as e: logger.warning(f"Error closing video_final in finally: {str(e)}")
|
@@ -724,6 +831,7 @@ def crear_video(prompt_type, input_text, musica_file=None):
|
|
724 |
try: video_base.close()
|
725 |
except Exception as e: logger.warning(f"Error closing video_base in finally: {str(e)}")
|
726 |
|
|
|
727 |
except Exception as e:
|
728 |
logger.warning(f"Error during final clip closing in finally: {str(e)}")
|
729 |
|
@@ -873,23 +981,16 @@ with gr.Blocks(title="Generador de Videos con IA", theme=gr.themes.Soft(), css="
|
|
873 |
if __name__ == "__main__":
|
874 |
logger.info("Verifying critical dependencies...")
|
875 |
try:
|
876 |
-
# Try importing something that requires FFmpeg/ImageMagick backend
|
877 |
from moviepy.editor import ColorClip
|
878 |
-
# Check if basic clip creation works
|
879 |
try:
|
880 |
-
temp_clip = ColorClip((100,100), color=(255,0,0), duration=1)
|
881 |
temp_clip.close()
|
882 |
-
logger.info("MoviePy base clips (like ColorClip) created successfully. FFmpeg seems accessible.")
|
883 |
except Exception as e:
|
884 |
-
logger.critical(f"Failed to create basic MoviePy clip. Often indicates FFmpeg/ImageMagick issues. Error: {e}")
|
885 |
-
# Decide whether to raise or just log
|
886 |
-
# raise RuntimeError(f"MoviePy/FFmpeg dependency issue: {e}") # Uncomment to force exit
|
887 |
|
888 |
except Exception as e:
|
889 |
logger.critical(f"Failed to import MoviePy. Ensure it is installed. Error: {e}", exc_info=True)
|
890 |
-
# Decide whether to raise or just log
|
891 |
-
# raise RuntimeError(f"MoviePy import failed: {e}") # Uncomment to force exit
|
892 |
-
|
893 |
|
894 |
logger.info("Starting Gradio app...")
|
895 |
try:
|
|
|
9 |
import torch
|
10 |
from transformers import GPT2Tokenizer, GPT2LMHeadModel
|
11 |
from keybert import KeyBERT
|
12 |
+
from moviepy.editor import VideoFileClip, concatenate_videoclips, AudioFileClip, CompositeAudioClip, concatenate_audioclips, AudioClip
|
13 |
import re
|
14 |
import math
|
15 |
import shutil
|
|
|
55 |
logger.info("Loading KeyBERT model...")
|
56 |
kw_model = None
|
57 |
try:
|
58 |
+
kw_model = KeyBert('distilbert-base-multilingual-cased')
|
59 |
logger.info("KeyBERT initialized successfully")
|
60 |
except Exception as e:
|
61 |
logger.error(f"FAILURE loading KeyBERT: {str(e)}", exc_info=True)
|
|
|
204 |
|
205 |
def loop_audio_to_length(audio_clip, target_duration):
|
206 |
logger.debug(f"Adjusting audio | Current duration: {audio_clip.duration:.2f}s | Target: {target_duration:.2f}s")
|
207 |
+
|
208 |
+
# Handle cases where the input audio clip is invalid
|
209 |
+
if audio_clip is None or audio_clip.duration is None or audio_clip.duration <= 0:
|
210 |
+
logger.warning("Input audio clip is invalid (None or zero duration), cannot loop.")
|
211 |
+
# Return a silent clip of target duration as fallback
|
212 |
try:
|
213 |
+
# Ensure sampling rate is set, default is 44100
|
214 |
+
sr = getattr(audio_clip, 'fps', 44100) if audio_clip else 44100 # Use fps for audio clips
|
215 |
+
return AudioClip(lambda t: 0, duration=target_duration, sr=sr)
|
216 |
except Exception as e:
|
217 |
+
logger.error(f"Could not create silence clip: {e}", exc_info=True)
|
218 |
+
return AudioFileClip(filename="") # Return empty clip on failure
|
219 |
|
220 |
if audio_clip.duration >= target_duration:
|
221 |
+
logger.debug("Audio clip already longer or equal to target. Trimming.")
|
222 |
+
trimmed_clip = audio_clip.subclip(0, target_duration)
|
223 |
+
# Check trimmed clip validity (should be ok, but good practice)
|
224 |
+
if trimmed_clip.duration is None or trimmed_clip.duration <= 0:
|
225 |
+
logger.error("Trimmed audio clip is invalid.")
|
226 |
+
try: trimmed_clip.close()
|
227 |
+
except: pass
|
228 |
+
return AudioFileClip(filename="")
|
229 |
+
return trimmed_clip
|
230 |
|
231 |
loops = math.ceil(target_duration / audio_clip.duration)
|
232 |
logger.debug(f"Creating {loops} audio loops")
|
233 |
|
234 |
audio_segments = [audio_clip] * loops
|
235 |
looped_audio = None # Initialize for finally block
|
236 |
+
final_looped_audio = None # Initialize for return value
|
237 |
try:
|
238 |
looped_audio = concatenate_audioclips(audio_segments)
|
239 |
+
|
240 |
+
# Verify the concatenated audio clip is valid
|
241 |
+
if looped_audio.duration is None or looped_audio.duration <= 0:
|
242 |
+
logger.error("Concatenated audio clip is invalid (None or zero duration).")
|
243 |
+
raise ValueError("Invalid concatenated audio.")
|
244 |
+
|
245 |
final_looped_audio = looped_audio.subclip(0, target_duration)
|
246 |
+
|
247 |
+
# Verify the final subclipped audio clip is valid
|
248 |
+
if final_looped_audio.duration is None or final_looped_audio.duration <= 0:
|
249 |
+
logger.error("Final subclipped audio clip is invalid (None or zero duration).")
|
250 |
+
raise ValueError("Invalid final subclipped audio.")
|
251 |
+
|
252 |
return final_looped_audio
|
253 |
+
|
254 |
except Exception as e:
|
255 |
+
logger.error(f"Error concatenating/subclipping audio clips for looping: {str(e)}", exc_info=True)
|
256 |
+
# Fallback: try returning the original clip trimmed if possible
|
257 |
+
try:
|
258 |
+
if audio_clip.duration is not None and audio_clip.duration > 0:
|
259 |
+
logger.warning("Returning original audio clip (may be too short).")
|
260 |
+
return audio_clip.subclip(0, min(audio_clip.duration, target_duration))
|
261 |
+
except:
|
262 |
+
pass # Ignore errors during fallback
|
263 |
+
logger.error("Fallback to original audio clip failed.")
|
264 |
+
return AudioFileClip(filename="") # Return empty clip if fallback fails
|
265 |
+
|
266 |
finally:
|
267 |
+
# Clean up the temporary concatenated clip if it was created but not returned
|
268 |
+
if looped_audio is not None and looped_audio is not final_looped_audio:
|
269 |
try: looped_audio.close()
|
270 |
except: pass
|
271 |
|
|
|
333 |
temp_dir_intermediate = None
|
334 |
|
335 |
# Initialize clips and audio objects to None for cleanup in finally
|
336 |
+
audio_tts_original = None # Keep original TTS clip for cleanup
|
337 |
+
musica_audio_original = None # Keep original music clip for cleanup
|
338 |
+
audio_tts = None # This will be the potentially modified/validated TTS clip
|
339 |
+
musica_audio = None # This will be the potentially modified/validated music clip
|
340 |
video_base = None # This will hold the final video base clip before adding audio
|
341 |
video_final = None # This will hold the final clip with video and audio
|
342 |
source_clips = [] # Clips loaded from downloaded files for proper closing
|
|
|
367 |
raise ValueError("Error generating voice audio.")
|
368 |
temp_intermediate_files.append(voz_path)
|
369 |
|
370 |
+
audio_tts_original = AudioFileClip(voz_path)
|
371 |
+
|
372 |
+
# Verify initial TTS audio clip
|
373 |
+
if audio_tts_original.reader is None or audio_tts_original.duration is None or audio_tts_original.duration <= 0:
|
374 |
+
logger.critical("Initial TTS audio clip is invalid (reader is None or duration <= 0).")
|
375 |
+
# Try to close the invalid clip before raising
|
376 |
+
try: audio_tts_original.close()
|
377 |
+
except: pass
|
378 |
+
audio_tts_original = None # Ensure it's None
|
379 |
+
raise ValueError("Generated voice audio is invalid.")
|
380 |
+
|
381 |
+
audio_tts = audio_tts_original # Use the original valid TTS clip
|
382 |
audio_duration = audio_tts.duration
|
383 |
logger.info(f"Voice audio duration: {audio_duration:.2f} seconds")
|
384 |
|
|
|
539 |
concatenated_base = concatenate_videoclips(clips_to_concatenate, method="chain")
|
540 |
logger.info(f"Base video duration after initial concatenation: {concatenated_base.duration:.2f}s")
|
541 |
|
542 |
+
# Verify the resulting concatenated clip is valid (CompositeVideoClip)
|
|
|
543 |
if concatenated_base is None or concatenated_base.duration is None or concatenated_base.duration <= 0:
|
544 |
logger.critical("Concatenated video base clip is invalid after first concatenation (None or zero duration).")
|
545 |
raise ValueError("Failed to create valid video base from segments.")
|
|
|
565 |
num_full_repeats = int(audio_duration // final_video_base.duration)
|
566 |
remaining_duration = audio_duration % final_video_base.duration
|
567 |
|
568 |
+
repeated_clips_list = [final_video_base] * num_full_repeats # List contains the *same* clip object repeated
|
569 |
|
570 |
if remaining_duration > 0:
|
571 |
try:
|
|
|
587 |
video_base_repeated = None # Hold result temporarily
|
588 |
try:
|
589 |
# Concatenate the repeated parts
|
590 |
+
# If repeated_clips_list contains duplicates of the same object, this is fine for concatenate_videoclips
|
591 |
video_base_repeated = concatenate_videoclips(repeated_clips_list, method="chain")
|
592 |
logger.info(f"Duration of repeated video base: {video_base_repeated.duration:.2f}s")
|
593 |
|
594 |
# Verify the repeated clip is valid
|
|
|
595 |
if video_base_repeated is None or video_base_repeated.duration is None or video_base_repeated.duration <= 0:
|
596 |
logger.critical("Concatenated repeated video base clip is invalid.")
|
597 |
raise ValueError("Failed to create valid repeated video base.")
|
598 |
|
599 |
+
# Close the old base clip *only if it's different from the new one*
|
600 |
+
if final_video_base is not video_base_repeated:
|
601 |
+
try: final_video_base.close()
|
602 |
+
except: pass
|
603 |
+
|
604 |
# Assign the new valid repeated clip
|
605 |
final_video_base = video_base_repeated
|
606 |
|
607 |
except Exception as e:
|
608 |
logger.critical(f"Error during repetition concatenation: {str(e)}", exc_info=True)
|
609 |
+
# If repetition fails, the error is raised. The original final_video_base will be closed in main finally.
|
610 |
raise ValueError("Failed during video repetition.")
|
611 |
finally:
|
612 |
# Close the clips in the repeated list, EXCEPT the one assigned to final_video_base
|
613 |
+
# This needs care as list items might be the same object
|
614 |
+
if 'repeated_clips_list' in locals():
|
615 |
+
for clip in repeated_clips_list:
|
616 |
+
# Only close if it's not the final clip and not already closed (MoviePy tracks this)
|
617 |
+
if clip is not final_video_base:
|
618 |
+
try: clip.close()
|
619 |
+
except: pass
|
620 |
|
621 |
|
622 |
# After repetition (or if no repetition happened), ensure duration matches audio exactly
|
|
|
626 |
try:
|
627 |
trimmed_video_base = final_video_base.subclip(0, audio_duration)
|
628 |
# Verify the trimmed clip is valid
|
|
|
629 |
if trimmed_video_base is None or trimmed_video_base.duration is None or trimmed_video_base.duration <= 0:
|
630 |
logger.critical("Trimmed video base clip is invalid.")
|
631 |
raise ValueError("Failed to create valid trimmed video base.")
|
632 |
|
633 |
# Close the old clip
|
634 |
+
if final_video_base is not trimmed_video_base:
|
635 |
+
try: final_video_base.close()
|
636 |
+
except: pass
|
637 |
+
|
638 |
# Assign the new valid trimmed clip
|
639 |
final_video_base = trimmed_video_base
|
640 |
|
|
|
644 |
|
645 |
|
646 |
# Final check on video_base before setting audio/writing
|
|
|
647 |
if final_video_base is None or final_video_base.duration is None or final_video_base.duration <= 0:
|
648 |
+
logger.critical("Final video base clip is invalid before audio/writing (None or zero duration).")
|
649 |
raise ValueError("Final video base clip is invalid.")
|
650 |
|
651 |
+
# Also check size, as MoviePy needs it for writing
|
652 |
+
if final_video_base.size is None or final_video_base.size[0] <= 0 or final_video_base.size[1] <= 0:
|
653 |
+
logger.critical(f"Final video base has invalid size: {final_video_base.size}. Cannot write video.")
|
654 |
+
raise ValueError("Final video base has invalid size before writing.")
|
655 |
+
|
656 |
video_base = final_video_base # Use the final adjusted video_base for subsequent steps
|
657 |
|
658 |
# 6. Handle background music
|
659 |
logger.info("Processing audio...")
|
660 |
|
661 |
+
final_audio = audio_tts # Start with TTS audio
|
662 |
+
|
663 |
+
musica_audio_looped = None # Initialize for cleanup
|
664 |
+
|
665 |
if musica_file:
|
666 |
+
musica_audio_original = None # Initialize for cleanup
|
667 |
try:
|
668 |
music_path = os.path.join(temp_dir_intermediate, "musica_bg.mp3")
|
669 |
shutil.copyfile(musica_file, music_path)
|
670 |
temp_intermediate_files.append(music_path)
|
671 |
logger.info(f"Background music copied to: {music_path}")
|
672 |
|
673 |
+
musica_audio_original = AudioFileClip(music_path)
|
674 |
|
675 |
+
# Verify initial music audio clip
|
676 |
+
if musica_audio_original.reader is None or musica_audio_original.duration is None or musica_audio_original.duration <= 0:
|
677 |
logger.warning("Background music clip seems invalid or has zero duration. Skipping music.")
|
678 |
+
# Close the invalid clip before skipping
|
679 |
+
try: musica_audio_original.close()
|
680 |
+
except: pass
|
681 |
+
musica_audio_original = None # Ensure it's None
|
682 |
+
else:
|
683 |
+
musica_audio_looped = loop_audio_to_length(musica_audio_original, video_base.duration)
|
684 |
+
logger.debug(f"Music adjusted to video duration: {musica_audio_looped.duration:.2f}s")
|
685 |
|
686 |
+
# Verify the looped music clip is valid
|
687 |
+
if musica_audio_looped is None or musica_audio_looped.duration is None or musica_audio_looped.duration <= 0:
|
688 |
+
logger.warning("Looped background music clip is invalid. Skipping music.")
|
689 |
+
# Close the invalid looped clip
|
690 |
+
try: musica_audio_looped.close()
|
691 |
+
except: pass
|
692 |
+
musica_audio_looped = None # Ensure it's None
|
693 |
|
|
|
|
|
|
|
|
|
694 |
|
695 |
+
if musica_audio_looped: # Only proceed if looped music is valid
|
696 |
+
# CompositeAudioClip uses the *current* audio_tts and musica_audio_looped clips
|
697 |
final_audio = CompositeAudioClip([
|
698 |
+
musica_audio_looped.volumex(0.2), # Apply effect to the looped clip
|
699 |
+
audio_tts.volumex(1.0) # Apply effect to the TTS clip (safer than assuming no effects needed)
|
700 |
])
|
701 |
# Verify the resulting composite audio
|
702 |
if final_audio.duration is None or final_audio.duration <= 0:
|
703 |
logger.warning("Composite audio clip is invalid (None or zero duration). Using voice audio only.")
|
704 |
+
# If CompositeAudioClip fails, need to close its components if they are not the originals
|
705 |
+
try:
|
706 |
+
if musica_audio_looped is not musica_audio_original: musica_audio_looped.close()
|
707 |
+
if audio_tts is not audio_tts_original: audio_tts.close()
|
708 |
+
# Close the invalid composite audio
|
709 |
+
try: final_audio.close()
|
710 |
+
except: pass
|
711 |
+
except: pass # Ignore errors during cleanup
|
712 |
+
final_audio = audio_tts_original # Fallback to the original valid TTS
|
713 |
+
musica_audio = None # Ensure musica_audio variable is None
|
714 |
+
audio_tts = audio_tts_original # Ensure audio_tts variable points to the original valid TTS
|
715 |
+
|
716 |
else:
|
717 |
logger.info("Audio mix completed (voice + music).")
|
718 |
+
# composite audio is valid, set musica_audio variable for later cleanup
|
719 |
+
musica_audio = musica_audio_looped
|
720 |
+
# audio_tts variable already points to original which is handled in main finally
|
721 |
+
|
722 |
|
723 |
except Exception as e:
|
724 |
logger.warning(f"Error processing background music: {str(e)}", exc_info=True)
|
725 |
+
# Fallback to just TTS audio
|
726 |
+
final_audio = audio_tts_original
|
727 |
+
musica_audio = None # Ensure variable is None
|
728 |
+
audio_tts = audio_tts_original # Ensure variable is original
|
729 |
logger.warning("Using voice audio only due to music processing error.")
|
|
|
730 |
|
731 |
+
|
732 |
+
# Ensure final_audio duration matches video_base duration if possible
|
733 |
+
# Check for significant duration mismatch allowing small floating point differences
|
734 |
+
if final_audio.duration is not None and abs(final_audio.duration - video_base.duration) > 0.2:
|
735 |
logger.warning(f"Final audio duration ({final_audio.duration:.2f}s) differs significantly from video base ({video_base.duration:.2f}s). Attempting trim/extend.")
|
736 |
try:
|
737 |
+
# Need to create a *new* clip if trimming, and handle closing the old one
|
738 |
if final_audio.duration > video_base.duration:
|
739 |
+
trimmed_final_audio = final_audio.subclip(0, video_base.duration)
|
740 |
+
if trimmed_final_audio.duration is None or trimmed_final_audio.duration <= 0:
|
741 |
+
logger.warning("Trimmed final audio is invalid. Using original final_audio.")
|
742 |
+
try: trimmed_final_audio.close()
|
743 |
+
except: pass # Close the invalid trimmed clip
|
744 |
+
else:
|
745 |
+
# Safely close the old final_audio if it's different
|
746 |
+
if final_audio is not trimmed_final_audio:
|
747 |
+
try: final_audio.close()
|
748 |
+
except: pass
|
749 |
+
final_audio = trimmed_final_audio # Use the valid trimmed clip
|
750 |
+
logger.warning("Trimmed final audio to match video duration.")
|
751 |
# MoviePy often extends audio automatically if it's too short, so we don't explicitly extend here.
|
752 |
except Exception as e:
|
753 |
logger.warning(f"Error adjusting final audio duration: {str(e)}")
|
754 |
|
755 |
|
756 |
+
# Final check on video_final before writing
|
757 |
+
# video_final is a composite of video_base and final_audio
|
758 |
video_final = video_base.set_audio(final_audio)
|
759 |
|
|
|
|
|
760 |
if video_final is None or video_final.duration is None or video_final.duration <= 0:
|
761 |
+
logger.critical("Final video clip (with audio) is invalid before writing (None or zero duration).")
|
762 |
raise ValueError("Final video clip is invalid before writing.")
|
763 |
|
764 |
+
|
765 |
output_filename = "final_video.mp4"
|
766 |
output_path = os.path.join(temp_dir_intermediate, output_filename)
|
767 |
logger.info(f"Writing final video to: {output_path}")
|
768 |
|
|
|
|
|
|
|
|
|
|
|
769 |
|
770 |
video_final.write_videofile(
|
771 |
output_path,
|
|
|
791 |
finally:
|
792 |
logger.info("Starting cleanup of clips and intermediate temporary files...")
|
793 |
|
794 |
+
# Close all initially opened source *video* clips
|
795 |
for clip in source_clips:
|
796 |
try: clip.close()
|
797 |
+
except Exception as e: logger.warning(f"Error closing source video clip in finally: {str(e)}")
|
798 |
|
799 |
+
# Close any video segments left in the list (should be empty if successful)
|
800 |
for clip_segment in clips_to_concatenate:
|
801 |
try: clip_segment.close()
|
802 |
+
except Exception as e: logger.warning(f"Error closing video segment clip in finally: {str(e)}")
|
803 |
|
804 |
# Close the main MoviePy objects if they were successfully created
|
805 |
try:
|
806 |
+
# Close the audio clips
|
807 |
+
# Start with the potentially looped/trimmed music clip if it exists
|
808 |
+
if musica_audio is not None:
|
809 |
+
try: musica_audio.close()
|
810 |
+
except Exception as e: logger.warning(f"Error closing musica_audio in finally: {str(e)}")
|
811 |
+
# Then close the original music audio clip if it exists and is different
|
812 |
+
if musica_audio_original is not None and musica_audio_original is not musica_audio:
|
813 |
+
try: musica_audio_original.close()
|
814 |
+
except Exception as e: logger.warning(f"Error closing musica_audio_original in finally: {str(e)}")
|
815 |
+
|
816 |
+
# Close the potentially modified/trimmed TTS clip if it exists and is different from original
|
817 |
+
if audio_tts is not None and audio_tts is not audio_tts_original:
|
818 |
+
try: audio_tts.close()
|
819 |
+
except Exception as e: logger.warning(f"Error closing audio_tts (modified) in finally: {str(e)}")
|
820 |
+
# Close the original TTS clip if it exists (it's the base)
|
821 |
+
if audio_tts_original is not None:
|
822 |
+
try: audio_tts_original.close()
|
823 |
+
except Exception as e: logger.warning(f"Error closing audio_tts_original in finally: {str(e)}")
|
824 |
+
|
825 |
+
# Close video_final first, which should cascade to video_base and final_audio (and their components)
|
826 |
if video_final is not None:
|
827 |
try: video_final.close()
|
828 |
except Exception as e: logger.warning(f"Error closing video_final in finally: {str(e)}")
|
|
|
831 |
try: video_base.close()
|
832 |
except Exception as e: logger.warning(f"Error closing video_base in finally: {str(e)}")
|
833 |
|
834 |
+
|
835 |
except Exception as e:
|
836 |
logger.warning(f"Error during final clip closing in finally: {str(e)}")
|
837 |
|
|
|
981 |
if __name__ == "__main__":
|
982 |
logger.info("Verifying critical dependencies...")
|
983 |
try:
|
|
|
984 |
from moviepy.editor import ColorClip
|
|
|
985 |
try:
|
986 |
+
temp_clip = ColorClip((100,100), color=(255,0,0), duration=0.1) # Use a very short duration
|
987 |
temp_clip.close()
|
988 |
+
logger.info("MoviePy base clips (like ColorClip) created and closed successfully. FFmpeg seems accessible.")
|
989 |
except Exception as e:
|
990 |
+
logger.critical(f"Failed to create basic MoviePy clip. Often indicates FFmpeg/ImageMagick issues. Error: {e}", exc_info=True)
|
|
|
|
|
991 |
|
992 |
except Exception as e:
|
993 |
logger.critical(f"Failed to import MoviePy. Ensure it is installed. Error: {e}", exc_info=True)
|
|
|
|
|
|
|
994 |
|
995 |
logger.info("Starting Gradio app...")
|
996 |
try:
|