gnosticdev commited on
Commit
0a28283
verified
1 Parent(s): 24d97f6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +55 -29
app.py CHANGED
@@ -4,7 +4,7 @@ from pixabay_api import search_pixabay
4
  from moviepy.editor import (
5
  AudioFileClip, VideoFileClip, CompositeAudioClip,
6
  concatenate_audioclips, concatenate_videoclips, vfx, CompositeVideoClip,
7
- ColorClip
8
  )
9
  import asyncio
10
  import os
@@ -29,42 +29,64 @@ os.makedirs(output_folder, exist_ok=True)
29
  # ID de la carpeta de destino en Google Drive
30
  FOLDER_ID = "12S6adpanAXjf71pKKGRRPqpzbJa5XEh3" # Reemplaza con tu ID de carpeta
31
 
32
- def resize_and_blur_video(clip, target_width=1920, target_height=1080):
33
- """Redimensiona el video al tama帽o 1080p (16:9) y aplica desenfoque si es necesario."""
 
 
 
 
 
 
 
 
34
  try:
35
  w, h = clip.size
36
  current_aspect_ratio = w / h
37
  target_aspect_ratio = target_width / target_height
38
 
39
- if abs(current_aspect_ratio - target_aspect_ratio) < 0.1:
40
- # Si la relaci贸n de aspecto ya es cercana a 16:9, solo redimensionamos
41
- return clip.resize((target_width, target_height))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
 
43
- # Crear un fondo borroso con las dimensiones objetivo
44
- background = ColorClip(size=(target_width, target_height), color=[0, 0, 0]).set_duration(clip.duration)
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
- # Redimensionar el video original para mantener su proporci贸n
51
- if current_aspect_ratio < target_aspect_ratio: # Video vertical
52
- new_height = target_height
53
- new_width = int(new_height * current_aspect_ratio)
54
- x_center = (target_width - new_width) / 2
55
- resized_clip = clip.resize(width=new_width).set_position((x_center, 0))
56
- else: # Video horizontal
57
- new_width = target_width
58
- new_height = int(new_width / current_aspect_ratio)
59
- y_center = (target_height - new_height) / 2
60
- resized_clip = clip.resize(height=new_height).set_position((0, y_center))
61
-
62
- # Combinar el fondo borroso con el video redimensionado
63
  return CompositeVideoClip([background, resized_clip], size=(target_width, target_height))
64
  except Exception as e:
65
- print(f"Error en resize_and_blur_video: {e}")
66
  return clip
67
 
 
68
  def concatenate_pixabay_videos(keywords, num_videos_per_keyword=1):
69
  """Concatena videos de Pixabay basados en palabras clave."""
70
  keyword_list = [keyword.strip() for keyword in keywords.split(",") if keyword.strip()]
@@ -88,7 +110,7 @@ def concatenate_pixabay_videos(keywords, num_videos_per_keyword=1):
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
  os.unlink(tmp_video.name) # Limpiamos el archivo temporal
94
  except Exception as e:
@@ -100,6 +122,7 @@ def concatenate_pixabay_videos(keywords, num_videos_per_keyword=1):
100
  random.shuffle(video_clips)
101
  return concatenate_videoclips(video_clips, method="compose")
102
 
 
103
  def adjust_background_music(video_duration, music_file):
104
  """Ajusta la m煤sica de fondo para que coincida con la duraci贸n del video."""
105
  try:
@@ -114,6 +137,7 @@ def adjust_background_music(video_duration, music_file):
114
  print(f"Error ajustando m煤sica: {e}")
115
  return None
116
 
 
117
  def combine_audio_video(audio_file, video_clip, music_clip=None):
118
  """Combina el audio y el video en un archivo final."""
119
  try:
@@ -151,6 +175,7 @@ def combine_audio_video(audio_file, video_clip, music_clip=None):
151
  final_clip.close()
152
  return None
153
 
 
154
  def process_input(text, txt_file, mp3_file, selected_voice, rate, pitch, keywords):
155
  """Procesa la entrada del usuario y genera el video final."""
156
  try:
@@ -189,6 +214,7 @@ def process_input(text, txt_file, mp3_file, selected_voice, rate, pitch, keyword
189
  print(f"Error durante el procesamiento: {e}")
190
  return None
191
 
 
192
  # Interfaz Gradio
193
  with gr.Blocks() as demo:
194
  gr.Markdown("# Text-to-Video Generator")
@@ -219,4 +245,4 @@ with gr.Blocks() as demo:
219
  port = int(os.getenv("PORT", 7860))
220
 
221
  # Lanzar la aplicaci贸n
222
- demo.launch(server_name="0.0.0.0", server_port=port, share=True, show_error=True)
 
4
  from moviepy.editor import (
5
  AudioFileClip, VideoFileClip, CompositeAudioClip,
6
  concatenate_audioclips, concatenate_videoclips, vfx, CompositeVideoClip,
7
+ ColorClip, ImageClip
8
  )
9
  import asyncio
10
  import os
 
29
  # ID de la carpeta de destino en Google Drive
30
  FOLDER_ID = "12S6adpanAXjf71pKKGRRPqpzbJa5XEh3" # Reemplaza con tu ID de carpeta
31
 
32
+ def resize_and_add_background(clip, target_width=1920, target_height=1080, background_url="https://wallpaperaccess.com/full/231401.jpg"):
33
+ """
34
+ Redimensiona el video al tama帽o 1080p (16:9) y a帽ade una imagen de fondo descargada desde una URL.
35
+
36
+ :param clip: VideoFileClip original.
37
+ :param target_width: Ancho objetivo del video final (por defecto: 1920).
38
+ :param target_height: Alto objetivo del video final (por defecto: 1080).
39
+ :param background_url: URL de la imagen de fondo.
40
+ :return: VideoFileClip procesado con fondo agregado.
41
+ """
42
  try:
43
  w, h = clip.size
44
  current_aspect_ratio = w / h
45
  target_aspect_ratio = target_width / target_height
46
 
47
+ # Descargar la imagen de fondo desde la URL
48
+ response = requests.get(background_url)
49
+ if response.status_code != 200:
50
+ print("Error al descargar la imagen de fondo, usando un fondo negro.")
51
+ background = (
52
+ ImageClip(
53
+ np.zeros((target_height, target_width, 3), dtype=np.uint8),
54
+ duration=clip.duration,
55
+ )
56
+ .set_duration(clip.duration)
57
+ .resize((target_width, target_height))
58
+ )
59
+ else:
60
+ image_data = BytesIO(response.content)
61
+ background = (
62
+ ImageClip(image_data)
63
+ .set_duration(clip.duration)
64
+ .resize((target_width, target_height))
65
+ )
66
 
67
+ # Si el video ya tiene una relaci贸n de aspecto cercana a 16:9, solo redimensionarlo
68
+ if abs(current_aspect_ratio - target_aspect_ratio) < 0.1:
69
+ resized_clip = clip.resize((target_width, target_height))
70
+ else:
71
+ # Redimensionar el video manteniendo su proporci贸n y centrarlo sobre el fondo
72
+ if current_aspect_ratio < target_aspect_ratio: # Video vertical
73
+ new_height = target_height
74
+ new_width = int(new_height * current_aspect_ratio)
75
+ x_center = (target_width - new_width) / 2
76
+ resized_clip = clip.resize(width=new_width).set_position((x_center, 0))
77
+ else: # Video horizontal
78
+ new_width = target_width
79
+ new_height = int(new_width / current_aspect_ratio)
80
+ y_center = (target_height - new_height) / 2
81
+ resized_clip = clip.resize(height=new_height).set_position((0, y_center))
82
+
83
+ # Combinar el fondo con el video redimensionado
 
 
 
84
  return CompositeVideoClip([background, resized_clip], size=(target_width, target_height))
85
  except Exception as e:
86
+ print(f"Error en resize_and_add_background: {e}")
87
  return clip
88
 
89
+
90
  def concatenate_pixabay_videos(keywords, num_videos_per_keyword=1):
91
  """Concatena videos de Pixabay basados en palabras clave."""
92
  keyword_list = [keyword.strip() for keyword in keywords.split(",") if keyword.strip()]
 
110
  with tempfile.NamedTemporaryFile(delete=False, suffix=".mp4") as tmp_video:
111
  tmp_video.write(video_response.content)
112
  clip = VideoFileClip(tmp_video.name)
113
+ processed_clip = resize_and_add_background(clip) # Usa la nueva funci贸n
114
  video_clips.append(processed_clip)
115
  os.unlink(tmp_video.name) # Limpiamos el archivo temporal
116
  except Exception as e:
 
122
  random.shuffle(video_clips)
123
  return concatenate_videoclips(video_clips, method="compose")
124
 
125
+
126
  def adjust_background_music(video_duration, music_file):
127
  """Ajusta la m煤sica de fondo para que coincida con la duraci贸n del video."""
128
  try:
 
137
  print(f"Error ajustando m煤sica: {e}")
138
  return None
139
 
140
+
141
  def combine_audio_video(audio_file, video_clip, music_clip=None):
142
  """Combina el audio y el video en un archivo final."""
143
  try:
 
175
  final_clip.close()
176
  return None
177
 
178
+
179
  def process_input(text, txt_file, mp3_file, selected_voice, rate, pitch, keywords):
180
  """Procesa la entrada del usuario y genera el video final."""
181
  try:
 
214
  print(f"Error durante el procesamiento: {e}")
215
  return None
216
 
217
+
218
  # Interfaz Gradio
219
  with gr.Blocks() as demo:
220
  gr.Markdown("# Text-to-Video Generator")
 
245
  port = int(os.getenv("PORT", 7860))
246
 
247
  # Lanzar la aplicaci贸n
248
+ demo.launch(server_name="0.0.0.0", server_port=port, share=True, show_error=True, enable_queue=True)