gnosticdev commited on
Commit
de0afc9
·
verified ·
1 Parent(s): 39c1e26

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +65 -146
app.py CHANGED
@@ -25,160 +25,98 @@ def clean_text_for_search(text):
25
  text = re.sub(r'[^\w\s]', '', text).strip()
26
  return text
27
 
28
- def resize_and_blur_video(clip, target_width=1920, target_height=1080):
29
  """
30
- Redimensiona y aplica desenfoque al video para mantener aspecto 16:9 con resolución objetivo.
31
- Los videos más pequeños se redimensionan y los verticales se convierten en horizontales con blur.
32
-
33
- Args:
34
- clip: VideoFileClip object
35
- target_width: Ancho objetivo (default 1920 para 1080p)
36
- target_height: Alto objetivo (default 1080 para 1080p)
37
  """
38
  try:
39
  w, h = clip.size
40
- current_ratio = w / h
41
- target_ratio = target_width / target_height
42
-
43
- print(f"Video original: {w}x{h}, ratio: {current_ratio}")
44
-
45
- if current_ratio < target_ratio: # Video vertical o más cuadrado que 16:9
46
- # Crear un fondo desenfocado escalado
47
- background = (clip
48
- .resize(width=target_width)
49
- .resize(width=target_width * 2) # Hacer el blur más suave
50
- .fx(vfx.blur, sigma=10)
51
- .resize(width=target_width))
52
-
53
- # Calcular el tamaño para el video principal
54
- new_height = target_height
55
- new_width = int(h * current_ratio)
56
- if new_width > target_width:
57
- new_width = target_width
58
- new_height = int(new_width / current_ratio)
59
-
60
- # Redimensionar video principal
61
- foreground = clip.resize(width=new_width, height=new_height)
62
-
63
- # Centrar el video
64
- x_center = (target_width - new_width) // 2
65
- y_center = (target_height - new_height) // 2
66
-
67
- final = CompositeVideoClip(
68
- [background,
69
- foreground.set_position((x_center, y_center))],
70
- size=(target_width, target_height)
71
  )
72
-
73
- return final
74
-
75
  else: # Video horizontal
76
- # Si es más ancho que 16:9, recortamos los bordes
77
- return clip.resize(width=target_width, height=target_height)
78
-
79
- except Exception as e:
80
- print(f"Error en resize_and_blur_video: {e}")
81
- return clip.resize(width=target_width, height=target_height)
82
 
83
  except Exception as e:
84
  print(f"Error en resize_and_blur_video: {e}")
85
  return clip
86
 
87
- def concatenate_pexels_videos(keywords, num_videos_per_keyword=1, target_width=1920, target_height=1080):
88
  """
89
- Concatena videos de Pexels manteniendo una calidad y resolución consistentes.
90
-
91
- Args:
92
- keywords (str): Palabras clave separadas por comas
93
- num_videos_per_keyword (int): Número de videos por palabra clave
94
- target_width (int): Ancho objetivo para los videos
95
- target_height (int): Alto objetivo para los videos
96
  """
97
  keyword_list = [keyword.strip() for keyword in keywords.split(",") if keyword.strip()]
98
  if not keyword_list:
99
- raise ValueError("No se proporcionaron palabras clave válidas.")
100
 
101
  video_clips = []
102
- processed_keywords = []
103
 
104
  for keyword in keyword_list:
105
  try:
106
- print(f"Buscando videos para: '{keyword}'...")
107
- # Limpiar la palabra clave para búsqueda
108
- clean_keyword = clean_text_for_search(keyword)
109
-
110
- # Obtener videos con la nueva API
111
- links = search_pexels(clean_keyword, num_results=num_videos_per_keyword)
112
  if not links:
113
- print(f"No se encontraron videos para: '{keyword}'")
114
  continue
115
 
116
- for link in links:
117
- try:
118
- print(f"Descargando video para: '{keyword}'...")
119
- with tempfile.NamedTemporaryFile(delete=False, suffix=".mp4") as tmp_video:
120
- video_response = requests.get(link, stream=True)
121
- if video_response.status_code != 200:
122
- print(f"Error descargando video: {video_response.status_code}")
123
- continue
124
-
125
- # Guardar el video
126
- for chunk in video_response.iter_content(chunk_size=8192):
127
- if chunk:
128
- tmp_video.write(chunk)
129
-
130
- tmp_video.flush()
131
-
132
- # Procesar el video
133
- try:
134
- clip = VideoFileClip(tmp_video.name)
135
-
136
- # Verificar duración mínima
137
- if clip.duration < 3:
138
- print(f"Video demasiado corto ({clip.duration}s), saltando...")
139
- clip.close()
140
- continue
141
-
142
- # Procesar y agregar el clip
143
- processed_clip = resize_and_blur_video(clip, target_width, target_height)
144
- if processed_clip:
145
- video_clips.append(processed_clip)
146
- processed_keywords.append(keyword)
147
- print(f"Video procesado exitosamente para: '{keyword}'")
148
-
149
- except Exception as e:
150
- print(f"Error procesando video: {e}")
151
- if 'clip' in locals():
152
- clip.close()
153
- continue
154
-
155
- finally:
156
- # Limpiar archivo temporal
157
- if os.path.exists(tmp_video.name):
158
- try:
159
- os.unlink(tmp_video.name)
160
- except Exception as e:
161
- print(f"Error eliminando archivo temporal: {e}")
162
 
163
  except Exception as e:
164
  print(f"Error procesando palabra clave '{keyword}': {e}")
165
  continue
166
 
167
  if not video_clips:
168
- raise Exception("No se pudieron obtener videos válidos para ninguna palabra clave.")
169
 
170
- print(f"Videos procesados exitosamente para las palabras: {', '.join(processed_keywords)}")
171
-
172
- # Aleatorizar el orden de los clips
173
  random.shuffle(video_clips)
174
-
175
- # Concatenar los clips
 
 
176
  try:
177
- final_clip = concatenate_videoclips(video_clips, method="compose")
178
- print(f"Video final generado: {final_clip.size}")
179
- return final_clip
 
 
 
 
 
 
180
  except Exception as e:
181
- raise Exception(f"Error concatenando clips: {e}")
 
182
 
183
  def combine_audio_video(audio_file, video_clip, music_clip=None):
184
  try:
@@ -210,57 +148,38 @@ def combine_audio_video(audio_file, video_clip, music_clip=None):
210
 
211
  def process_input(text, txt_file, mp3_file, selected_voice, rate, pitch, keywords):
212
  try:
213
- # Validar entrada de texto
214
  if text.strip():
215
  final_text = text
216
  elif txt_file is not None:
217
  final_text = txt_file.decode("utf-8")
218
  else:
219
- # Retornar None en lugar de string de error
220
- return None
221
 
222
- # Validar voces
223
  voices = asyncio.run(get_voices())
224
  if selected_voice not in voices:
225
- return None
226
 
227
- # Generar audio
228
  try:
229
  audio_file = asyncio.run(text_to_speech(final_text, selected_voice, rate, pitch))
230
  except Exception as e:
231
- print(f"Error generando audio: {e}")
232
- return None
233
 
234
- # Procesar videos
235
  try:
236
  video_clip = concatenate_pexels_videos(keywords, num_videos_per_keyword=1)
237
  except Exception as e:
238
- print(f"Error concatenando videos: {e}")
239
- return None
240
 
241
- # Procesar música de fondo si existe
242
  if mp3_file is not None:
243
  music_clip = adjust_background_music(video_clip.duration, mp3_file.name)
244
  else:
245
  music_clip = None
246
 
247
- # Combinar audio y video
248
  final_video_path = combine_audio_video(audio_file, video_clip, music_clip)
249
- if final_video_path is None:
250
- return None
251
-
252
- # Subir a Google Drive
253
  upload_to_google_drive(final_video_path)
254
-
255
- # Verificar que el archivo existe antes de retornarlo
256
- if os.path.exists(final_video_path):
257
- return final_video_path
258
- else:
259
- return None
260
 
261
  except Exception as e:
262
- print(f"Error en process_input: {e}")
263
- return None
264
 
265
  def upload_to_google_drive(file_path):
266
  try:
 
25
  text = re.sub(r'[^\w\s]', '', text).strip()
26
  return text
27
 
28
+ def resize_and_blur_video(clip, target_aspect_ratio=16/9):
29
  """
30
+ Redimensiona y aplica desenfoque al fondo del video para mantener el aspecto 16:9.
 
 
 
 
 
 
31
  """
32
  try:
33
  w, h = clip.size
34
+ current_aspect_ratio = w / h
35
+
36
+ print(f"Procesando video: {w}x{h}, ratio: {current_aspect_ratio}")
37
+ if abs(current_aspect_ratio - target_aspect_ratio) < 0.1:
38
+ return clip
39
+
40
+ if current_aspect_ratio < target_aspect_ratio: # Video vertical
41
+ target_w = int(h * target_aspect_ratio)
42
+ target_h = h
43
+
44
+ background = clip.resize(width=target_w)
45
+ try:
46
+ background = background.fx(vfx.blur, sigma=50)
47
+ except Exception as e:
48
+ print(f"Error al aplicar blur: {e}")
49
+
50
+ foreground = clip.resize(height=target_h)
51
+ x_center = (target_w - foreground.w) / 2
52
+ return CompositeVideoClip(
53
+ [background, foreground.set_position((x_center, 0))],
54
+ size=(target_w, target_h)
 
 
 
 
 
 
 
 
 
 
55
  )
 
 
 
56
  else: # Video horizontal
57
+ return clip.resize(width=int(h * target_aspect_ratio), height=h)
 
 
 
 
 
58
 
59
  except Exception as e:
60
  print(f"Error en resize_and_blur_video: {e}")
61
  return clip
62
 
63
+ def concatenate_pexels_videos(keywords, num_videos_per_keyword=1):
64
  """
65
+ Concatena videos de Pexels basados en palabras clave proporcionadas por el usuario.
66
+ :param keywords: Palabras clave separadas por comas (ejemplo: "universo, galaxia, bosque, gato").
 
 
 
 
 
67
  """
68
  keyword_list = [keyword.strip() for keyword in keywords.split(",") if keyword.strip()]
69
  if not keyword_list:
70
+ raise Exception("No se proporcionaron palabras clave válidas.")
71
 
72
  video_clips = []
 
73
 
74
  for keyword in keyword_list:
75
  try:
76
+ print(f"Buscando videos para la palabra clave '{keyword}'...")
77
+ links = search_pexels(keyword, num_results=num_videos_per_keyword)
 
 
 
 
78
  if not links:
79
+ print(f"No se encontraron videos para la palabra clave '{keyword}'.")
80
  continue
81
 
82
+ link = links[0] # Usamos solo el primer video encontrado
83
+ video_response = requests.get(link)
84
+ if video_response.status_code != 200:
85
+ print(f"Error al descargar video desde {link}: Código de estado {video_response.status_code}")
86
+ continue
87
+
88
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".mp4") as tmp_video:
89
+ tmp_video.write(video_response.content)
90
+ clip = VideoFileClip(tmp_video.name)
91
+ processed_clip = resize_and_blur_video(clip)
92
+ video_clips.append(processed_clip)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93
 
94
  except Exception as e:
95
  print(f"Error procesando palabra clave '{keyword}': {e}")
96
  continue
97
 
98
  if not video_clips:
99
+ raise Exception("No se pudieron obtener videos válidos.")
100
 
101
+ # Aleatorizar el orden de los clips si es necesario
 
 
102
  random.shuffle(video_clips)
103
+
104
+ return concatenate_videoclips(video_clips, method="compose")
105
+
106
+ def adjust_background_music(video_duration, music_file):
107
  try:
108
+ music = AudioFileClip(music_file)
109
+ if music.duration < video_duration:
110
+ repetitions = int(video_duration / music.duration) + 1
111
+ music_clips = [music] * repetitions
112
+ music = concatenate_audioclips(music_clips)
113
+ if music.duration > video_duration:
114
+ music = music.subclip(0, video_duration)
115
+ music = music.volumex(0.2)
116
+ return music
117
  except Exception as e:
118
+ print(f"Error ajustando música: {e}")
119
+ return None
120
 
121
  def combine_audio_video(audio_file, video_clip, music_clip=None):
122
  try:
 
148
 
149
  def process_input(text, txt_file, mp3_file, selected_voice, rate, pitch, keywords):
150
  try:
 
151
  if text.strip():
152
  final_text = text
153
  elif txt_file is not None:
154
  final_text = txt_file.decode("utf-8")
155
  else:
156
+ return "No input provided"
 
157
 
 
158
  voices = asyncio.run(get_voices())
159
  if selected_voice not in voices:
160
+ return f"La voz '{selected_voice}' no es válida. Por favor, seleccione una de las siguientes voces: {', '.join(voices.keys())}"
161
 
 
162
  try:
163
  audio_file = asyncio.run(text_to_speech(final_text, selected_voice, rate, pitch))
164
  except Exception as e:
165
+ return f"Error generando audio: {e}"
 
166
 
 
167
  try:
168
  video_clip = concatenate_pexels_videos(keywords, num_videos_per_keyword=1)
169
  except Exception as e:
170
+ return f"Error concatenando videos: {e}"
 
171
 
 
172
  if mp3_file is not None:
173
  music_clip = adjust_background_music(video_clip.duration, mp3_file.name)
174
  else:
175
  music_clip = None
176
 
 
177
  final_video_path = combine_audio_video(audio_file, video_clip, music_clip)
 
 
 
 
178
  upload_to_google_drive(final_video_path)
179
+ return final_video_path
 
 
 
 
 
180
 
181
  except Exception as e:
182
+ return f"Error durante el procesamiento: {e}"
 
183
 
184
  def upload_to_google_drive(file_path):
185
  try: