Ahmadkhan12 commited on
Commit
06a1546
·
verified ·
1 Parent(s): 768257d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +44 -50
app.py CHANGED
@@ -3,12 +3,10 @@ import moviepy.editor as mp
3
  import numpy as np
4
  from PIL import Image
5
  import os
 
6
 
7
- # Utility function to log messages
8
- def log_message(message):
9
- with open("/tmp/video_generation_log.txt", "a") as log_file:
10
- log_file.write(message + "\n")
11
- print(message)
12
 
13
  # Resize image while maintaining aspect ratio
14
  def resize_and_fit_image(img, target_size=(1280, 720), padding_color=(0, 0, 0)):
@@ -26,13 +24,8 @@ def resize_and_fit_image(img, target_size=(1280, 720), padding_color=(0, 0, 0)):
26
  new_width = int(new_height * aspect_ratio)
27
 
28
  img_resized = img.resize((new_width, new_height))
29
-
30
- if new_width > target_width:
31
- left = (new_width - target_width) // 2
32
- img_resized = img_resized.crop((left, 0, left + target_width, target_height))
33
-
34
  final_img = Image.new('RGB', target_size, padding_color)
35
- final_img.paste(img_resized, (0, 0))
36
 
37
  return final_img
38
 
@@ -41,58 +34,55 @@ def apply_zoom_effect(image_clip):
41
  zoomed_clip = image_clip.resize(lambda t: 1 + 0.05 * t) # Zoom in gradually
42
  return zoomed_clip
43
 
 
44
  def process_and_generate_video(audio_file, images):
45
  try:
46
- log_message("Starting video generation...")
47
 
48
- # Check if the file paths are strings, and convert to actual file-like objects
49
- if isinstance(audio_file, str):
50
- log_message(f"Audio file path: {audio_file}")
51
- audio = mp.AudioFileClip(audio_file)
52
- else:
53
- raise ValueError("Expected a valid file path for audio.")
54
 
 
 
 
55
  audio_duration = audio.duration
56
- image_clips = []
57
- image_count = len(images)
58
- image_duration = audio_duration / image_count
59
-
60
- log_message(f"Audio duration: {audio_duration} seconds, Image count: {image_count}")
61
 
62
- # Iterate over images, resize them, and create video clips
63
- for img_path in images:
64
- if isinstance(img_path, str): # Ensure img_path is a string (file path)
65
- log_message(f"Processing image: {img_path}")
66
- img = Image.open(img_path)
67
- img = resize_and_fit_image(img, target_size=(1280, 720))
68
 
69
- # Create image clip and apply zoom effect
70
- img_clip = mp.ImageClip(np.array(img)).set_duration(image_duration).set_fps(30)
71
- img_clip = apply_zoom_effect(img_clip)
72
 
73
- # Add transition effect - Crossfade In
74
- if len(image_clips) > 0:
75
- img_clip = img_clip.crossfadein(1)
 
76
 
77
- image_clips.append(img_clip)
 
 
 
78
 
79
- log_message(f"Image clips: {len(image_clips)} clips created.")
80
 
81
- # Concatenate image clips with audio
82
  video = mp.concatenate_videoclips(image_clips, method="compose")
83
  video = video.set_audio(audio)
84
 
85
- # Set output path
86
- output_path = '/tmp/generated_video.mp4'
87
- log_message(f"Saving video to {output_path}")
88
- video.write_videofile(output_path, codec='libx264', audio_codec='aac', threads=4, fps=30, preset='ultrafast')
89
 
90
- return output_path # Return the file path for Gradio output
91
 
92
  except Exception as e:
93
- error_message = f"Error during video generation: {str(e)}"
94
- log_message(error_message)
95
- return error_message
96
 
97
  # Gradio interface setup
98
  def gradio_interface():
@@ -104,11 +94,15 @@ def gradio_interface():
104
  generate_button = gr.Button("Generate Video")
105
 
106
  output_video = gr.Video(label="Generated Video")
107
-
108
- # Generate button triggers video creation process
109
- generate_button.click(fn=process_and_generate_video, inputs=[mp3_input, image_input], outputs=output_video)
 
 
 
 
110
 
111
  demo.launch()
112
 
113
- # Run the interface
114
  gradio_interface()
 
3
  import numpy as np
4
  from PIL import Image
5
  import os
6
+ import sys
7
 
8
+ # Redirect stdout to ensure logs are visible
9
+ sys.stdout = sys.stderr
 
 
 
10
 
11
  # Resize image while maintaining aspect ratio
12
  def resize_and_fit_image(img, target_size=(1280, 720), padding_color=(0, 0, 0)):
 
24
  new_width = int(new_height * aspect_ratio)
25
 
26
  img_resized = img.resize((new_width, new_height))
 
 
 
 
 
27
  final_img = Image.new('RGB', target_size, padding_color)
28
+ final_img.paste(img_resized, ((target_width - new_width) // 2, (target_height - new_height) // 2))
29
 
30
  return final_img
31
 
 
34
  zoomed_clip = image_clip.resize(lambda t: 1 + 0.05 * t) # Zoom in gradually
35
  return zoomed_clip
36
 
37
+ # Video generation function
38
  def process_and_generate_video(audio_file, images):
39
  try:
40
+ print("Starting video generation...")
41
 
42
+ # Validate input files
43
+ if not audio_file:
44
+ raise ValueError("No audio file provided.")
45
+ if not images or len(images) == 0:
46
+ raise ValueError("No images provided.")
 
47
 
48
+ # Load audio file
49
+ print(f"Audio file path: {audio_file}")
50
+ audio = mp.AudioFileClip(audio_file)
51
  audio_duration = audio.duration
 
 
 
 
 
52
 
53
+ print(f"Audio duration: {audio_duration} seconds")
 
 
 
 
 
54
 
55
+ # Process images
56
+ image_clips = []
57
+ image_duration = audio_duration / len(images)
58
 
59
+ for img_path in images:
60
+ print(f"Processing image: {img_path}")
61
+ img = Image.open(img_path)
62
+ img = resize_and_fit_image(img, target_size=(1280, 720))
63
 
64
+ # Create image clip with zoom effect
65
+ img_clip = mp.ImageClip(np.array(img)).set_duration(image_duration).set_fps(30)
66
+ img_clip = apply_zoom_effect(img_clip)
67
+ image_clips.append(img_clip)
68
 
69
+ print(f"Generated {len(image_clips)} image clips.")
70
 
71
+ # Concatenate image clips and set audio
72
  video = mp.concatenate_videoclips(image_clips, method="compose")
73
  video = video.set_audio(audio)
74
 
75
+ # Save video to temporary directory
76
+ output_path = "/tmp/generated_video.mp4"
77
+ print(f"Saving video to {output_path}...")
78
+ video.write_videofile(output_path, codec="libx264", audio_codec="aac")
79
 
80
+ return output_path
81
 
82
  except Exception as e:
83
+ error_message = f"Error during video generation: {e}"
84
+ print(error_message) # Log error
85
+ return error_message # Return error as feedback
86
 
87
  # Gradio interface setup
88
  def gradio_interface():
 
94
  generate_button = gr.Button("Generate Video")
95
 
96
  output_video = gr.Video(label="Generated Video")
97
+ error_output = gr.Textbox(label="Error Log", interactive=False)
98
+
99
+ generate_button.click(
100
+ fn=process_and_generate_video,
101
+ inputs=[mp3_input, image_input],
102
+ outputs=[output_video, error_output]
103
+ )
104
 
105
  demo.launch()
106
 
107
+ # Run the Gradio interface
108
  gradio_interface()