Spaces:
Building
Building
Update app.py
Browse files
app.py
CHANGED
@@ -31,20 +31,16 @@ def resize_and_blur_video(clip, target_aspect_ratio=16/9):
|
|
31 |
try:
|
32 |
w, h = clip.size
|
33 |
current_aspect_ratio = w / h
|
34 |
-
|
35 |
if abs(current_aspect_ratio - target_aspect_ratio) < 0.1:
|
36 |
return clip
|
37 |
-
|
38 |
if current_aspect_ratio < target_aspect_ratio: # Video vertical
|
39 |
target_w = int(h * target_aspect_ratio)
|
40 |
target_h = h
|
41 |
-
|
42 |
background = clip.resize(width=target_w)
|
43 |
try:
|
44 |
background = background.fx(vfx.blur, sigma=50)
|
45 |
except Exception as e:
|
46 |
print(f"Error al aplicar blur: {e}")
|
47 |
-
|
48 |
foreground = clip.resize(height=target_h)
|
49 |
x_center = (target_w - foreground.w) / 2
|
50 |
return CompositeVideoClip(
|
@@ -53,7 +49,6 @@ def resize_and_blur_video(clip, target_aspect_ratio=16/9):
|
|
53 |
)
|
54 |
else: # Video horizontal
|
55 |
return clip.resize(width=int(h * target_aspect_ratio), height=h)
|
56 |
-
|
57 |
except Exception as e:
|
58 |
print(f"Error en resize_and_blur_video: {e}")
|
59 |
return clip
|
@@ -63,9 +58,7 @@ def concatenate_pixabay_videos(keywords, num_videos_per_keyword=1):
|
|
63 |
keyword_list = [keyword.strip() for keyword in keywords.split(",") if keyword.strip()]
|
64 |
if not keyword_list:
|
65 |
keyword_list = ["nature"] # Palabra clave por defecto
|
66 |
-
|
67 |
video_clips = []
|
68 |
-
|
69 |
for keyword in keyword_list:
|
70 |
try:
|
71 |
print(f"Buscando videos para la palabra clave '{keyword}'...")
|
@@ -75,28 +68,23 @@ def concatenate_pixabay_videos(keywords, num_videos_per_keyword=1):
|
|
75 |
links = search_pixabay("nature", num_results=num_videos_per_keyword)
|
76 |
if not links:
|
77 |
continue
|
78 |
-
|
79 |
link = links[0]
|
80 |
video_response = requests.get(link)
|
81 |
if video_response.status_code != 200:
|
82 |
print(f"Error al descargar video desde {link}")
|
83 |
continue
|
84 |
-
|
85 |
with tempfile.NamedTemporaryFile(delete=False, suffix=".mp4") as tmp_video:
|
86 |
tmp_video.write(video_response.content)
|
87 |
clip = VideoFileClip(tmp_video.name)
|
88 |
processed_clip = resize_and_blur_video(clip)
|
89 |
video_clips.append(processed_clip)
|
90 |
os.unlink(tmp_video.name) # Limpiamos el archivo temporal
|
91 |
-
|
92 |
except Exception as e:
|
93 |
print(f"Error procesando palabra clave '{keyword}': {e}")
|
94 |
continue
|
95 |
-
|
96 |
if not video_clips:
|
97 |
# Si no hay videos, creamos un clip negro de 5 segundos
|
98 |
return ColorClip(size=(1920, 1080), color=[0, 0, 0], duration=5)
|
99 |
-
|
100 |
random.shuffle(video_clips)
|
101 |
return concatenate_videoclips(video_clips, method="compose")
|
102 |
|
@@ -126,12 +114,10 @@ def combine_audio_video(audio_file, video_clip, music_clip=None):
|
|
126 |
|
127 |
# Combinamos el audio principal
|
128 |
final_clip = video_clip.set_audio(audio_clip)
|
129 |
-
|
130 |
# A帽adimos la m煤sica de fondo si existe
|
131 |
if music_clip:
|
132 |
music_clip = music_clip.set_duration(total_duration).audio_fadeout(2)
|
133 |
final_clip = final_clip.set_audio(CompositeAudioClip([audio_clip, music_clip]))
|
134 |
-
|
135 |
# Generamos el nombre del archivo y la ruta
|
136 |
output_filename = f"final_video_{int(time.time())}.mp4"
|
137 |
output_path = os.path.join(output_folder, output_filename)
|
@@ -147,7 +133,6 @@ def combine_audio_video(audio_file, video_clip, music_clip=None):
|
|
147 |
music_clip.close()
|
148 |
|
149 |
return output_path
|
150 |
-
|
151 |
except Exception as e:
|
152 |
print(f"Error combinando audio y video: {e}")
|
153 |
if 'final_clip' in locals():
|
@@ -164,32 +149,26 @@ def process_input(text, txt_file, mp3_file, selected_voice, rate, pitch, keyword
|
|
164 |
final_text = txt_file.decode("utf-8")
|
165 |
else:
|
166 |
raise ValueError("No text input provided")
|
167 |
-
|
168 |
# Generamos el audio
|
169 |
audio_file = asyncio.run(text_to_speech(final_text, selected_voice, rate, pitch))
|
170 |
if not audio_file:
|
171 |
raise ValueError("Failed to generate audio")
|
172 |
-
|
173 |
# Generamos el video
|
174 |
video_clip = concatenate_pixabay_videos(keywords, num_videos_per_keyword=1)
|
175 |
if not video_clip:
|
176 |
raise ValueError("Failed to generate video")
|
177 |
-
|
178 |
# Procesamos la m煤sica de fondo si existe
|
179 |
music_clip = None
|
180 |
if mp3_file is not None:
|
181 |
music_clip = adjust_background_music(video_clip.duration, mp3_file.name)
|
182 |
-
|
183 |
# Combinamos todo
|
184 |
final_video_path = combine_audio_video(audio_file, video_clip, music_clip)
|
185 |
if not final_video_path:
|
186 |
raise ValueError("Failed to combine audio and video")
|
187 |
-
|
188 |
# Subimos a Google Drive
|
189 |
upload_to_google_drive(final_video_path)
|
190 |
|
191 |
return final_video_path
|
192 |
-
|
193 |
except Exception as e:
|
194 |
print(f"Error durante el procesamiento: {e}")
|
195 |
return None
|
@@ -213,8 +192,6 @@ with gr.Blocks() as demo:
|
|
213 |
with gr.Column():
|
214 |
output_video = gr.File(label="Generated Video") # En lugar de gr.Video
|
215 |
|
216 |
-
|
217 |
-
|
218 |
btn = gr.Button("Generate Video")
|
219 |
btn.click(
|
220 |
process_input,
|
@@ -226,4 +203,4 @@ with gr.Blocks() as demo:
|
|
226 |
port = int(os.getenv("PORT", 7860))
|
227 |
|
228 |
# Lanzar la aplicaci贸n
|
229 |
-
demo.launch(server_name="0.0.0.0", server_port=port, share=True, show_error=
|
|
|
31 |
try:
|
32 |
w, h = clip.size
|
33 |
current_aspect_ratio = w / h
|
|
|
34 |
if abs(current_aspect_ratio - target_aspect_ratio) < 0.1:
|
35 |
return clip
|
|
|
36 |
if current_aspect_ratio < target_aspect_ratio: # Video vertical
|
37 |
target_w = int(h * target_aspect_ratio)
|
38 |
target_h = h
|
|
|
39 |
background = clip.resize(width=target_w)
|
40 |
try:
|
41 |
background = background.fx(vfx.blur, sigma=50)
|
42 |
except Exception as e:
|
43 |
print(f"Error al aplicar blur: {e}")
|
|
|
44 |
foreground = clip.resize(height=target_h)
|
45 |
x_center = (target_w - foreground.w) / 2
|
46 |
return CompositeVideoClip(
|
|
|
49 |
)
|
50 |
else: # Video horizontal
|
51 |
return clip.resize(width=int(h * target_aspect_ratio), height=h)
|
|
|
52 |
except Exception as e:
|
53 |
print(f"Error en resize_and_blur_video: {e}")
|
54 |
return clip
|
|
|
58 |
keyword_list = [keyword.strip() for keyword in keywords.split(",") if keyword.strip()]
|
59 |
if not keyword_list:
|
60 |
keyword_list = ["nature"] # Palabra clave por defecto
|
|
|
61 |
video_clips = []
|
|
|
62 |
for keyword in keyword_list:
|
63 |
try:
|
64 |
print(f"Buscando videos para la palabra clave '{keyword}'...")
|
|
|
68 |
links = search_pixabay("nature", num_results=num_videos_per_keyword)
|
69 |
if not links:
|
70 |
continue
|
|
|
71 |
link = links[0]
|
72 |
video_response = requests.get(link)
|
73 |
if video_response.status_code != 200:
|
74 |
print(f"Error al descargar video desde {link}")
|
75 |
continue
|
|
|
76 |
with tempfile.NamedTemporaryFile(delete=False, suffix=".mp4") as tmp_video:
|
77 |
tmp_video.write(video_response.content)
|
78 |
clip = VideoFileClip(tmp_video.name)
|
79 |
processed_clip = resize_and_blur_video(clip)
|
80 |
video_clips.append(processed_clip)
|
81 |
os.unlink(tmp_video.name) # Limpiamos el archivo temporal
|
|
|
82 |
except Exception as e:
|
83 |
print(f"Error procesando palabra clave '{keyword}': {e}")
|
84 |
continue
|
|
|
85 |
if not video_clips:
|
86 |
# Si no hay videos, creamos un clip negro de 5 segundos
|
87 |
return ColorClip(size=(1920, 1080), color=[0, 0, 0], duration=5)
|
|
|
88 |
random.shuffle(video_clips)
|
89 |
return concatenate_videoclips(video_clips, method="compose")
|
90 |
|
|
|
114 |
|
115 |
# Combinamos el audio principal
|
116 |
final_clip = video_clip.set_audio(audio_clip)
|
|
|
117 |
# A帽adimos la m煤sica de fondo si existe
|
118 |
if music_clip:
|
119 |
music_clip = music_clip.set_duration(total_duration).audio_fadeout(2)
|
120 |
final_clip = final_clip.set_audio(CompositeAudioClip([audio_clip, music_clip]))
|
|
|
121 |
# Generamos el nombre del archivo y la ruta
|
122 |
output_filename = f"final_video_{int(time.time())}.mp4"
|
123 |
output_path = os.path.join(output_folder, output_filename)
|
|
|
133 |
music_clip.close()
|
134 |
|
135 |
return output_path
|
|
|
136 |
except Exception as e:
|
137 |
print(f"Error combinando audio y video: {e}")
|
138 |
if 'final_clip' in locals():
|
|
|
149 |
final_text = txt_file.decode("utf-8")
|
150 |
else:
|
151 |
raise ValueError("No text input provided")
|
|
|
152 |
# Generamos el audio
|
153 |
audio_file = asyncio.run(text_to_speech(final_text, selected_voice, rate, pitch))
|
154 |
if not audio_file:
|
155 |
raise ValueError("Failed to generate audio")
|
|
|
156 |
# Generamos el video
|
157 |
video_clip = concatenate_pixabay_videos(keywords, num_videos_per_keyword=1)
|
158 |
if not video_clip:
|
159 |
raise ValueError("Failed to generate video")
|
|
|
160 |
# Procesamos la m煤sica de fondo si existe
|
161 |
music_clip = None
|
162 |
if mp3_file is not None:
|
163 |
music_clip = adjust_background_music(video_clip.duration, mp3_file.name)
|
|
|
164 |
# Combinamos todo
|
165 |
final_video_path = combine_audio_video(audio_file, video_clip, music_clip)
|
166 |
if not final_video_path:
|
167 |
raise ValueError("Failed to combine audio and video")
|
|
|
168 |
# Subimos a Google Drive
|
169 |
upload_to_google_drive(final_video_path)
|
170 |
|
171 |
return final_video_path
|
|
|
172 |
except Exception as e:
|
173 |
print(f"Error durante el procesamiento: {e}")
|
174 |
return None
|
|
|
192 |
with gr.Column():
|
193 |
output_video = gr.File(label="Generated Video") # En lugar de gr.Video
|
194 |
|
|
|
|
|
195 |
btn = gr.Button("Generate Video")
|
196 |
btn.click(
|
197 |
process_input,
|
|
|
203 |
port = int(os.getenv("PORT", 7860))
|
204 |
|
205 |
# Lanzar la aplicaci贸n
|
206 |
+
demo.launch(server_name="0.0.0.0", server_port=port, share=True, show_error=True)
|