Spaces:
Building
Building
Update app.py
Browse files
app.py
CHANGED
@@ -3,7 +3,7 @@ import gradio as gr
|
|
3 |
from tts_module import get_voices, text_to_speech
|
4 |
from moviepy.editor import (
|
5 |
AudioFileClip, ImageClip, CompositeAudioClip,
|
6 |
-
|
7 |
ColorClip
|
8 |
)
|
9 |
import asyncio
|
@@ -12,12 +12,12 @@ import json
|
|
12 |
import time
|
13 |
import requests
|
14 |
import random
|
15 |
-
from
|
16 |
from google.oauth2 import service_account
|
17 |
from googleapiclient.http import MediaFileUpload
|
18 |
from io import BytesIO
|
19 |
from PIL import Image
|
20 |
-
import numpy as
|
21 |
|
22 |
MIN_WIDTH = 1920
|
23 |
MIN_HEIGHT = 1080
|
@@ -26,121 +26,121 @@ TARGET_ASPECT_RATIO = 16/9
|
|
26 |
output_folder = "outputs"
|
27 |
temp_dir = "temp_files"
|
28 |
os.makedirs(output_folder, exist_ok=True)
|
29 |
-
os.makedirs(temp_dir,
|
30 |
|
31 |
FOLDER_ID = "12S6adpanAXjf71pKKGRRPqpzbJa5XEh3"
|
32 |
|
33 |
def load_proxies(proxy_file="proxys.txt"):
|
34 |
try:
|
35 |
with open(proxy_file, 'r') as f:
|
36 |
-
proxies =
|
37 |
print(f"Loaded {len(proxies)} proxies from file")
|
38 |
-
return [requests_proxy.ProxyInfo(proxy=f"http://{proxy}") for proxy
|
39 |
except Exception as e:
|
40 |
print(f"Error loading proxies: {e}")
|
41 |
return []
|
42 |
|
43 |
def search_google_images(query, num_images=1):
|
44 |
try:
|
45 |
-
api_key = os.
|
46 |
cse_id = os.getenv('GOOGLE_CSE_ID')
|
47 |
proxies = load_proxies()
|
48 |
|
49 |
print(f"Buscando imágenes para: {query}")
|
50 |
|
51 |
-
if
|
52 |
print("No proxies available, trying without proxy")
|
53 |
with requests.Session() as session:
|
54 |
result = session.get(
|
55 |
-
|
56 |
params={
|
57 |
"q": query,
|
58 |
"cx": cse_id,
|
59 |
-
"
|
60 |
"num": num_images * 3,
|
61 |
"safe": 'off',
|
62 |
"imgSize": 'LARGE',
|
63 |
-
"
|
64 |
"rights": 'cc_publicdomain|cc_attribute|cc_sharealike',
|
65 |
"key": api_key
|
66 |
}
|
67 |
-
|
68 |
else:
|
69 |
with requests_proxy.ProxyManager(proxies) as proxy_manager:
|
70 |
result = proxy_manager.get(
|
71 |
-
f"https://www.
|
72 |
params={
|
73 |
"q": query,
|
74 |
"cx": cse_id,
|
75 |
"searchType": "image",
|
76 |
-
|
77 |
"safe": 'off',
|
78 |
"imgSize": 'LARGE',
|
79 |
-
"imgType": 'imgTypeUndefined
|
80 |
"rights": 'cc_publicdomain|cc_attribute|cc_sharealike',
|
81 |
"key": api_key
|
82 |
}
|
83 |
).json()
|
84 |
-
|
85 |
with requests_proxy.ProxyManager(proxies) as proxy_manager:
|
86 |
result = proxy_manager.get(
|
87 |
-
f"https://www.googleapis.com/customsearch/
|
88 |
params={
|
89 |
"q": query,
|
90 |
"cx": cse_id,
|
91 |
"searchType": "image",
|
92 |
-
"
|
93 |
"safe": 'off',
|
94 |
"imgSize": 'HUGE',
|
95 |
"imgType": 'photo',
|
96 |
-
"rights":
|
97 |
"key": api_key
|
98 |
}
|
99 |
).json()
|
100 |
|
101 |
if 'items' in result:
|
102 |
-
|
103 |
for item in result.get('items', []):
|
104 |
if 'image' in item:
|
105 |
width = int(item['image'].get('width', 0))
|
106 |
-
|
107 |
if width >= MIN_WIDTH and height >= MIN_HEIGHT:
|
108 |
image_urls.append(item['link'])
|
109 |
-
|
110 |
break
|
111 |
|
112 |
-
print(f"Encontradas {len(image_urls)} imágenes de tamaño adecuado"
|
113 |
return image_urls
|
114 |
|
115 |
print("No se encontraron imágenes después de probar todos los proxies")
|
116 |
return []
|
117 |
|
118 |
except Exception as e:
|
119 |
-
|
120 |
return []
|
121 |
|
122 |
|
123 |
def process_image(image):
|
124 |
try:
|
125 |
width, height = image.size
|
126 |
-
current_ratio
|
127 |
|
128 |
if current_ratio > TARGET_ASPECT_RATIO:
|
129 |
new_width = max(MIN_WIDTH, width)
|
130 |
-
new_height = int(new_width / TARGET_ASPECT_RATIO
|
131 |
else:
|
132 |
new_height = max(MIN_HEIGHT, height)
|
133 |
new_width = int(new_height * TARGET_ASPECT_RATIO)
|
134 |
|
135 |
-
image = image.resize((new_width,
|
136 |
background = Image.new('RGB', (max(new_width, MIN_WIDTH), max(new_height, MIN_HEIGHT)), 'black')
|
137 |
|
138 |
-
offset = ((background.
|
139 |
(background.height - image.height) // 2)
|
140 |
background.paste(image, offset)
|
141 |
|
142 |
return background
|
143 |
-
except Exception
|
144 |
print(f"Error processing image: {e}")
|
145 |
return None
|
146 |
|
@@ -149,193 +149,193 @@ def download_image(url):
|
|
149 |
if not proxies:
|
150 |
proxies = [None]
|
151 |
|
152 |
-
|
153 |
try:
|
154 |
response = requests.get(url, proxies=proxy, timeout=10)
|
155 |
image = Image.open(BytesIO(response.content))
|
156 |
|
157 |
-
|
158 |
background = Image.new('RGB', image.size, (0, 0, 0))
|
159 |
-
|
160 |
image = background
|
161 |
|
162 |
processed_image = process_image(image)
|
163 |
-
if processed_image:
|
164 |
return processed_image
|
165 |
|
166 |
except Exception as e:
|
167 |
print(f"Error downloading image with proxy {proxy}: {e}")
|
168 |
continue
|
169 |
-
|
170 |
|
171 |
def create_animated_clip(image, duration=5, zoom_factor=1.1):
|
172 |
img_array = np.array(image)
|
173 |
img_clip = ImageClip(img_array).set_duration(duration)
|
174 |
|
175 |
-
if
|
176 |
img_clip = img_clip.resize(width=MIN_WIDTH, height=MIN_HEIGHT)
|
177 |
|
178 |
return img_clip.resize(lambda t: 1 + (zoom_factor - 1) * t / duration)
|
179 |
|
180 |
-
def
|
181 |
keyword_list = [keyword.strip() for keyword in keywords.split(",") if keyword.strip()]
|
182 |
-
if not
|
183 |
keyword_list = ["nature"]
|
184 |
|
185 |
video_clips = []
|
186 |
for keyword in keyword_list:
|
187 |
try:
|
188 |
print(f"Searching images for keyword '{keyword}'...")
|
189 |
-
|
190 |
for url in image_urls:
|
191 |
image = download_image(url)
|
192 |
-
|
193 |
clip = create_animated_clip(image, duration=clip_duration)
|
194 |
video_clips.append(clip)
|
195 |
time.sleep(1)
|
196 |
-
|
197 |
print(f"Error processing keyword '{keyword}': {e}")
|
198 |
continue
|
199 |
|
200 |
if not video_clips:
|
201 |
-
return ColorClip(size=(MIN_WIDTH,
|
202 |
|
203 |
random.shuffle(video_clips)
|
204 |
return concatenate_videoclips(video_clips, method="compose")
|
205 |
|
206 |
-
def adjust_background_music(
|
207 |
try:
|
208 |
music = AudioFileClip(music_file)
|
209 |
-
if music.duration
|
210 |
repetitions = int(video_duration / music.duration) + 1
|
211 |
music_clips = [music] * repetitions
|
212 |
-
music = concatenate_audioclips(
|
213 |
music = music.subclip(0, video_duration)
|
214 |
return music.volumex(0.2)
|
215 |
except Exception as e:
|
216 |
print(f"Error adjusting music: {e}")
|
217 |
-
return
|
218 |
|
219 |
def combine_audio_video(audio_file, video_clip, music_clip=None):
|
220 |
try:
|
221 |
audio_clip = AudioFileClip(audio_file)
|
222 |
total_duration = audio_clip.duration + 2
|
223 |
-
|
224 |
video_clip = video_clip.loop(duration=total_duration)
|
225 |
video_clip = video_clip.set_duration(total_duration).fadeout(2)
|
226 |
|
227 |
-
final_clip = video_clip.
|
228 |
if music_clip:
|
229 |
music_clip = music_clip.set_duration(total_duration).audio_fadeout(2)
|
230 |
-
final_clip = final_clip.set_audio(
|
231 |
|
232 |
output_filename = f"final_video_{int(time.time())}.mp4"
|
233 |
output_path = os.path.join(output_folder, output_filename)
|
234 |
-
|
235 |
final_clip.write_videofile(output_path, codec="libx264", audio_codec="aac", fps=24)
|
236 |
|
237 |
final_clip.close()
|
238 |
video_clip.close()
|
239 |
-
|
240 |
if music_clip:
|
241 |
music_clip.close()
|
242 |
|
243 |
return output_path
|
244 |
except Exception as e:
|
245 |
-
print(f"Error combining audio and video:
|
246 |
if 'final_clip' in locals():
|
247 |
final_clip.close()
|
248 |
return None
|
249 |
|
250 |
def upload_to_google_drive(file_path, folder_id):
|
251 |
try:
|
252 |
-
creds =
|
253 |
json.loads(os.getenv('GOOGLE_SERVICE_ACCOUNT')),
|
254 |
scopes=['https://www.googleapis.com/auth/drive']
|
255 |
)
|
256 |
-
|
257 |
|
258 |
file_metadata = {
|
259 |
'name': os.path.basename(file_path),
|
260 |
'parents': [folder_id]
|
261 |
}
|
262 |
-
|
263 |
file = service.files().create(body=file_metadata, media_body=media, fields='id').execute()
|
264 |
|
265 |
permission = {
|
266 |
-
|
267 |
'role': 'reader'
|
268 |
}
|
269 |
service.permissions().create(fileId=file['id'], body=permission).execute()
|
270 |
|
271 |
file_id = file['id']
|
272 |
-
|
273 |
return download_link
|
274 |
except Exception as e:
|
275 |
print(f"Error uploading to Google Drive: {e}")
|
276 |
return None
|
277 |
|
278 |
-
def process_input(text, txt_file,
|
279 |
try:
|
280 |
if text.strip():
|
281 |
final_text = text
|
282 |
elif txt_file is not None:
|
283 |
-
final_text =
|
284 |
else:
|
285 |
raise ValueError("No text input provided")
|
286 |
|
287 |
-
audio_file = asyncio.run(text_to_speech(final_text, selected_voice, rate,
|
288 |
if not audio_file:
|
289 |
raise ValueError("Failed to generate audio")
|
290 |
|
291 |
-
video_clip = concatenate_google_images(keywords, clip_duration=5,
|
292 |
if not video_clip:
|
293 |
raise ValueError("Failed to generate video")
|
294 |
|
295 |
music_clip = None
|
296 |
if mp3_file is not None:
|
297 |
-
|
298 |
|
299 |
final_video_path = combine_audio_video(audio_file, video_clip, music_clip)
|
300 |
-
if
|
301 |
raise ValueError("Failed to combine audio and video")
|
302 |
|
303 |
-
download_link = upload_to_google_drive(final_video_path, folder_id=
|
304 |
if download_link:
|
305 |
print(f"Video uploaded to Google Drive. Download link: {download_link}")
|
306 |
return f"[Download video]({download_link})"
|
307 |
-
|
308 |
raise ValueError("Error uploading video to Google Drive")
|
309 |
except Exception as e:
|
310 |
print(f"Error during processing: {e}")
|
311 |
return None
|
312 |
-
finally
|
313 |
cleanup_temp_files()
|
314 |
|
315 |
with gr.Blocks() as demo:
|
316 |
gr.Markdown("# Text-to-Video Generator")
|
317 |
with gr.Row():
|
318 |
with gr.Column():
|
319 |
-
text_input = gr.
|
320 |
txt_file_input = gr.File(label="Or upload a .txt file", file_types=[".txt"])
|
321 |
-
mp3_file_input = gr.File(label="
|
322 |
keyword_input = gr.Textbox(
|
323 |
label="Enter keywords separated by commas",
|
324 |
-
value="fear,
|
325 |
-
|
326 |
voices = asyncio.run(get_voices())
|
327 |
voice_dropdown = gr.Dropdown(choices=list(voices.keys()), label="Select Voice")
|
328 |
-
rate_slider = gr.Slider(
|
329 |
-
pitch_slider = gr.Slider(minimum=-20, maximum=20, value=0, label="Pitch Adjustment (Hz)",
|
330 |
with gr.Column():
|
331 |
output_link = gr.Markdown("")
|
332 |
|
333 |
btn = gr.Button("Generate Video")
|
334 |
btn.click(
|
335 |
process_input,
|
336 |
-
inputs=[text_input,
|
337 |
outputs=output_link
|
338 |
)
|
339 |
|
340 |
port = int(os.getenv("PORT", 7860))
|
341 |
-
demo.launch(
|
|
|
3 |
from tts_module import get_voices, text_to_speech
|
4 |
from moviepy.editor import (
|
5 |
AudioFileClip, ImageClip, CompositeAudioClip,
|
6 |
+
concatenate_audioclips, concatenate_videoclips, vfx, CompositeVideoClip,
|
7 |
ColorClip
|
8 |
)
|
9 |
import asyncio
|
|
|
12 |
import time
|
13 |
import requests
|
14 |
import random
|
15 |
+
from googleapiclient.discovery import build
|
16 |
from google.oauth2 import service_account
|
17 |
from googleapiclient.http import MediaFileUpload
|
18 |
from io import BytesIO
|
19 |
from PIL import Image
|
20 |
+
import numpy as np
|
21 |
|
22 |
MIN_WIDTH = 1920
|
23 |
MIN_HEIGHT = 1080
|
|
|
26 |
output_folder = "outputs"
|
27 |
temp_dir = "temp_files"
|
28 |
os.makedirs(output_folder, exist_ok=True)
|
29 |
+
os.makedirs(temp_dir, exist_ok=True)
|
30 |
|
31 |
FOLDER_ID = "12S6adpanAXjf71pKKGRRPqpzbJa5XEh3"
|
32 |
|
33 |
def load_proxies(proxy_file="proxys.txt"):
|
34 |
try:
|
35 |
with open(proxy_file, 'r') as f:
|
36 |
+
proxies = [line.strip() for line in f if line.strip()]
|
37 |
print(f"Loaded {len(proxies)} proxies from file")
|
38 |
+
return [requests_proxy.ProxyInfo(proxy=f"http://{proxy}") for proxy in proxies]
|
39 |
except Exception as e:
|
40 |
print(f"Error loading proxies: {e}")
|
41 |
return []
|
42 |
|
43 |
def search_google_images(query, num_images=1):
|
44 |
try:
|
45 |
+
api_key = os.getenv('GOOGLE_API_KEY')
|
46 |
cse_id = os.getenv('GOOGLE_CSE_ID')
|
47 |
proxies = load_proxies()
|
48 |
|
49 |
print(f"Buscando imágenes para: {query}")
|
50 |
|
51 |
+
if not proxies:
|
52 |
print("No proxies available, trying without proxy")
|
53 |
with requests.Session() as session:
|
54 |
result = session.get(
|
55 |
+
f"https://www.googleapis.com/customsearch/v1",
|
56 |
params={
|
57 |
"q": query,
|
58 |
"cx": cse_id,
|
59 |
+
"searchType": "image",
|
60 |
"num": num_images * 3,
|
61 |
"safe": 'off',
|
62 |
"imgSize": 'LARGE',
|
63 |
+
"imgType": 'imgTypeUndefined',
|
64 |
"rights": 'cc_publicdomain|cc_attribute|cc_sharealike',
|
65 |
"key": api_key
|
66 |
}
|
67 |
+
).json()
|
68 |
else:
|
69 |
with requests_proxy.ProxyManager(proxies) as proxy_manager:
|
70 |
result = proxy_manager.get(
|
71 |
+
f"https://www.googleapis.com/customsearch/v1",
|
72 |
params={
|
73 |
"q": query,
|
74 |
"cx": cse_id,
|
75 |
"searchType": "image",
|
76 |
+
"num": num_images * 3,
|
77 |
"safe": 'off',
|
78 |
"imgSize": 'LARGE',
|
79 |
+
"imgType": 'imgTypeUndefined',
|
80 |
"rights": 'cc_publicdomain|cc_attribute|cc_sharealike',
|
81 |
"key": api_key
|
82 |
}
|
83 |
).json()
|
84 |
+
else:
|
85 |
with requests_proxy.ProxyManager(proxies) as proxy_manager:
|
86 |
result = proxy_manager.get(
|
87 |
+
f"https://www.googleapis.com/customsearch/v1",
|
88 |
params={
|
89 |
"q": query,
|
90 |
"cx": cse_id,
|
91 |
"searchType": "image",
|
92 |
+
"num": num_images * 3,
|
93 |
"safe": 'off',
|
94 |
"imgSize": 'HUGE',
|
95 |
"imgType": 'photo',
|
96 |
+
"rights": 'cc_publicdomain|cc_attribute|cc_sharealike',
|
97 |
"key": api_key
|
98 |
}
|
99 |
).json()
|
100 |
|
101 |
if 'items' in result:
|
102 |
+
image_urls = []
|
103 |
for item in result.get('items', []):
|
104 |
if 'image' in item:
|
105 |
width = int(item['image'].get('width', 0))
|
106 |
+
height = int(item['image'].get('height', 0))
|
107 |
if width >= MIN_WIDTH and height >= MIN_HEIGHT:
|
108 |
image_urls.append(item['link'])
|
109 |
+
if len(image_urls) >= num_images:
|
110 |
break
|
111 |
|
112 |
+
print(f"Encontradas {len(image_urls)} imágenes de tamaño adecuado")
|
113 |
return image_urls
|
114 |
|
115 |
print("No se encontraron imágenes después de probar todos los proxies")
|
116 |
return []
|
117 |
|
118 |
except Exception as e:
|
119 |
+
print(f"Error general en la búsqueda de imágenes: {str(e)}")
|
120 |
return []
|
121 |
|
122 |
|
123 |
def process_image(image):
|
124 |
try:
|
125 |
width, height = image.size
|
126 |
+
current_ratio = width / height
|
127 |
|
128 |
if current_ratio > TARGET_ASPECT_RATIO:
|
129 |
new_width = max(MIN_WIDTH, width)
|
130 |
+
new_height = int(new_width / TARGET_ASPECT_RATIO)
|
131 |
else:
|
132 |
new_height = max(MIN_HEIGHT, height)
|
133 |
new_width = int(new_height * TARGET_ASPECT_RATIO)
|
134 |
|
135 |
+
image = image.resize((new_width, new_height), Image.Resampling.LANCZOS)
|
136 |
background = Image.new('RGB', (max(new_width, MIN_WIDTH), max(new_height, MIN_HEIGHT)), 'black')
|
137 |
|
138 |
+
offset = ((background.width - image.width) // 2,
|
139 |
(background.height - image.height) // 2)
|
140 |
background.paste(image, offset)
|
141 |
|
142 |
return background
|
143 |
+
except Exception as e:
|
144 |
print(f"Error processing image: {e}")
|
145 |
return None
|
146 |
|
|
|
149 |
if not proxies:
|
150 |
proxies = [None]
|
151 |
|
152 |
+
for proxy in proxies:
|
153 |
try:
|
154 |
response = requests.get(url, proxies=proxy, timeout=10)
|
155 |
image = Image.open(BytesIO(response.content))
|
156 |
|
157 |
+
if image.mode in ('RGBA', 'LA') or (image.mode == 'P' and 'transparency' in image.info):
|
158 |
background = Image.new('RGB', image.size, (0, 0, 0))
|
159 |
+
background.paste(image, mask=image.split()[-1])
|
160 |
image = background
|
161 |
|
162 |
processed_image = process_image(image)
|
163 |
+
if processed_image:
|
164 |
return processed_image
|
165 |
|
166 |
except Exception as e:
|
167 |
print(f"Error downloading image with proxy {proxy}: {e}")
|
168 |
continue
|
169 |
+
return None
|
170 |
|
171 |
def create_animated_clip(image, duration=5, zoom_factor=1.1):
|
172 |
img_array = np.array(image)
|
173 |
img_clip = ImageClip(img_array).set_duration(duration)
|
174 |
|
175 |
+
if img_clip.size[0] < MIN_WIDTH or img_clip.size[1] < MIN_HEIGHT:
|
176 |
img_clip = img_clip.resize(width=MIN_WIDTH, height=MIN_HEIGHT)
|
177 |
|
178 |
return img_clip.resize(lambda t: 1 + (zoom_factor - 1) * t / duration)
|
179 |
|
180 |
+
def concatenate_google_images(keywords, clip_duration=5, num_images_per_keyword=1):
|
181 |
keyword_list = [keyword.strip() for keyword in keywords.split(",") if keyword.strip()]
|
182 |
+
if not keyword_list:
|
183 |
keyword_list = ["nature"]
|
184 |
|
185 |
video_clips = []
|
186 |
for keyword in keyword_list:
|
187 |
try:
|
188 |
print(f"Searching images for keyword '{keyword}'...")
|
189 |
+
image_urls = search_google_images(keyword, num_images=num_images_per_keyword)
|
190 |
for url in image_urls:
|
191 |
image = download_image(url)
|
192 |
+
if image:
|
193 |
clip = create_animated_clip(image, duration=clip_duration)
|
194 |
video_clips.append(clip)
|
195 |
time.sleep(1)
|
196 |
+
except Exception as e:
|
197 |
print(f"Error processing keyword '{keyword}': {e}")
|
198 |
continue
|
199 |
|
200 |
if not video_clips:
|
201 |
+
return ColorClip(size=(MIN_WIDTH, MIN_HEIGHT), color=[0, 0, 0], duration=5)
|
202 |
|
203 |
random.shuffle(video_clips)
|
204 |
return concatenate_videoclips(video_clips, method="compose")
|
205 |
|
206 |
+
def adjust_background_music(video_duration, music_file):
|
207 |
try:
|
208 |
music = AudioFileClip(music_file)
|
209 |
+
if music.duration < video_duration:
|
210 |
repetitions = int(video_duration / music.duration) + 1
|
211 |
music_clips = [music] * repetitions
|
212 |
+
music = concatenate_audioclips(music_clips)
|
213 |
music = music.subclip(0, video_duration)
|
214 |
return music.volumex(0.2)
|
215 |
except Exception as e:
|
216 |
print(f"Error adjusting music: {e}")
|
217 |
+
return None
|
218 |
|
219 |
def combine_audio_video(audio_file, video_clip, music_clip=None):
|
220 |
try:
|
221 |
audio_clip = AudioFileClip(audio_file)
|
222 |
total_duration = audio_clip.duration + 2
|
223 |
+
|
224 |
video_clip = video_clip.loop(duration=total_duration)
|
225 |
video_clip = video_clip.set_duration(total_duration).fadeout(2)
|
226 |
|
227 |
+
final_clip = video_clip.set_audio(audio_clip)
|
228 |
if music_clip:
|
229 |
music_clip = music_clip.set_duration(total_duration).audio_fadeout(2)
|
230 |
+
final_clip = final_clip.set_audio(CompositeAudioClip([audio_clip, music_clip]))
|
231 |
|
232 |
output_filename = f"final_video_{int(time.time())}.mp4"
|
233 |
output_path = os.path.join(output_folder, output_filename)
|
234 |
+
|
235 |
final_clip.write_videofile(output_path, codec="libx264", audio_codec="aac", fps=24)
|
236 |
|
237 |
final_clip.close()
|
238 |
video_clip.close()
|
239 |
+
audio_clip.close()
|
240 |
if music_clip:
|
241 |
music_clip.close()
|
242 |
|
243 |
return output_path
|
244 |
except Exception as e:
|
245 |
+
print(f"Error combining audio and video: {e}")
|
246 |
if 'final_clip' in locals():
|
247 |
final_clip.close()
|
248 |
return None
|
249 |
|
250 |
def upload_to_google_drive(file_path, folder_id):
|
251 |
try:
|
252 |
+
creds = service_account.Credentials.from_service_account_info(
|
253 |
json.loads(os.getenv('GOOGLE_SERVICE_ACCOUNT')),
|
254 |
scopes=['https://www.googleapis.com/auth/drive']
|
255 |
)
|
256 |
+
service = build('drive', 'v3', credentials=creds)
|
257 |
|
258 |
file_metadata = {
|
259 |
'name': os.path.basename(file_path),
|
260 |
'parents': [folder_id]
|
261 |
}
|
262 |
+
media = MediaFileUpload(file_path, resumable=True)
|
263 |
file = service.files().create(body=file_metadata, media_body=media, fields='id').execute()
|
264 |
|
265 |
permission = {
|
266 |
+
'type': 'anyone',
|
267 |
'role': 'reader'
|
268 |
}
|
269 |
service.permissions().create(fileId=file['id'], body=permission).execute()
|
270 |
|
271 |
file_id = file['id']
|
272 |
+
download_link = f"https://drive.google.com/uc?export=download&id={file_id}"
|
273 |
return download_link
|
274 |
except Exception as e:
|
275 |
print(f"Error uploading to Google Drive: {e}")
|
276 |
return None
|
277 |
|
278 |
+
def process_input(text, txt_file, mp3_file, selected_voice, rate, pitch, keywords):
|
279 |
try:
|
280 |
if text.strip():
|
281 |
final_text = text
|
282 |
elif txt_file is not None:
|
283 |
+
final_text = txt_file.decode("utf-8")
|
284 |
else:
|
285 |
raise ValueError("No text input provided")
|
286 |
|
287 |
+
audio_file = asyncio.run(text_to_speech(final_text, selected_voice, rate, pitch))
|
288 |
if not audio_file:
|
289 |
raise ValueError("Failed to generate audio")
|
290 |
|
291 |
+
video_clip = concatenate_google_images(keywords, clip_duration=5, num_images_per_keyword=1)
|
292 |
if not video_clip:
|
293 |
raise ValueError("Failed to generate video")
|
294 |
|
295 |
music_clip = None
|
296 |
if mp3_file is not None:
|
297 |
+
music_clip = adjust_background_music(video_clip.duration, mp3_file.name)
|
298 |
|
299 |
final_video_path = combine_audio_video(audio_file, video_clip, music_clip)
|
300 |
+
if not final_video_path:
|
301 |
raise ValueError("Failed to combine audio and video")
|
302 |
|
303 |
+
download_link = upload_to_google_drive(final_video_path, folder_id=FOLDER_ID)
|
304 |
if download_link:
|
305 |
print(f"Video uploaded to Google Drive. Download link: {download_link}")
|
306 |
return f"[Download video]({download_link})"
|
307 |
+
else:
|
308 |
raise ValueError("Error uploading video to Google Drive")
|
309 |
except Exception as e:
|
310 |
print(f"Error during processing: {e}")
|
311 |
return None
|
312 |
+
finally:
|
313 |
cleanup_temp_files()
|
314 |
|
315 |
with gr.Blocks() as demo:
|
316 |
gr.Markdown("# Text-to-Video Generator")
|
317 |
with gr.Row():
|
318 |
with gr.Column():
|
319 |
+
text_input = gr.Textbox(label="Write your text here", lines=5)
|
320 |
txt_file_input = gr.File(label="Or upload a .txt file", file_types=[".txt"])
|
321 |
+
mp3_file_input = gr.File(label="Upload background music (.mp3)", file_types=[".mp3"])
|
322 |
keyword_input = gr.Textbox(
|
323 |
label="Enter keywords separated by commas",
|
324 |
+
value="fear, religion, god, demons, aliens, possession, galaxy, mysterious, dystopian, astral, warfare, space, space, galaxy, moon, fear, astral, god, evil, mystery, cosmos, stars, paranormal, inexplicable, hidden, enigma, unknown, unusual, intriguing, curious, strange, supernatural, esoteric, arcane, occultism, supernatural, mystery, phenomenon, rare, unusual, enigmatic, sinister, gloomy, dark, shadowy, macabre, eerie, chilling, cursed, fantastic, unreal, unknown, mysterious, enigmatic, inexplicable, unusual, strange, unusual, arcane, esoteric, hidden, shadowy, dark, gloomy, sinister, macabre, eerie, chilling, cursed, fantastic, unreal, paranormal, supernatural, occultism, phenomenon, rare, intriguing, curious"
|
325 |
+
)
|
326 |
voices = asyncio.run(get_voices())
|
327 |
voice_dropdown = gr.Dropdown(choices=list(voices.keys()), label="Select Voice")
|
328 |
+
rate_slider = gr.Slider(minimum=-50, maximum=50, value=0, label="Speech Rate Adjustment (%)", step=1)
|
329 |
+
pitch_slider = gr.Slider(minimum=-20, maximum=20, value=0, label="Pitch Adjustment (Hz)", step=1)
|
330 |
with gr.Column():
|
331 |
output_link = gr.Markdown("")
|
332 |
|
333 |
btn = gr.Button("Generate Video")
|
334 |
btn.click(
|
335 |
process_input,
|
336 |
+
inputs=[text_input, txt_file_input, mp3_file_input, voice_dropdown, rate_slider, pitch_slider, keyword_input],
|
337 |
outputs=output_link
|
338 |
)
|
339 |
|
340 |
port = int(os.getenv("PORT", 7860))
|
341 |
+
demo.launch(server_name="0.0.0.0", server_port=port, share=True, show_error=True)
|