testdeep123 commited on
Commit
b828189
·
verified ·
1 Parent(s): 6ad9353

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +5 -865
app.py CHANGED
@@ -1,865 +1,5 @@
1
-
2
- # Import necessary libraries
3
- from kokoro import KPipeline
4
- from IPython.display import display, Audio
5
- import soundfile as sf
6
- import torch
7
- from IPython.display import display, Audio, HTML
8
- import soundfile as sf
9
- import os
10
- from moviepy.editor import VideoFileClip, AudioFileClip, ImageClip
11
- from PIL import Image
12
- import tempfile
13
- import random
14
- import cv2
15
- import math
16
- import os, requests, io, time, re, random
17
- from moviepy.editor import (
18
- VideoFileClip, concatenate_videoclips, AudioFileClip, ImageClip,
19
- CompositeVideoClip, TextClip
20
- )
21
- import moviepy.video.fx.all as vfx
22
- import moviepy.config as mpy_config
23
- from pydub import AudioSegment
24
- from pydub.generators import Sine
25
- from google.colab import files
26
- from PIL import Image, ImageDraw, ImageFont
27
- import numpy as np
28
- from bs4 import BeautifulSoup
29
- import base64
30
- from urllib.parse import quote
31
- import pysrt
32
- from gtts import gTTS
33
- import gradio as gr # Import Gradio
34
-
35
- # Initialize Kokoro TTS pipeline (using American English)
36
- pipeline = KPipeline(lang_code='a') # Use voice 'af_heart' for American English
37
- # Ensure ImageMagick binary is set
38
- mpy_config.change_settings({"IMAGEMAGICK_BINARY": "/usr/bin/convert"})
39
-
40
- # ---------------- Global Configuration ---------------- #
41
- PEXELS_API_KEY = 'BhJqbcdm9Vi90KqzXKAhnEHGsuFNv4irXuOjWtT761U49lRzo03qBGna'
42
- OPENROUTER_API_KEY = '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'
43
- OPENROUTER_MODEL = "mistralai/mistral-small-3.1-24b-instruct:free"
44
- OUTPUT_VIDEO_FILENAME = "final_video.mp4"
45
- USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
46
-
47
- # ---------------- Helper Functions ---------------- #
48
- # (Your existing helper functions remain unchanged: generate_script, parse_script,
49
- # search_pexels_videos, search_pexels_images, search_google_images, download_image,
50
- # download_video, generate_media, generate_tts, apply_kenburns_effect,
51
- # resize_to_fill, find_mp3_files, add_background_music, create_clip,
52
- # fix_imagemagick_policy)
53
-
54
- # Define these globally as they were in your original code but will be set per run
55
- TARGET_RESOLUTION = None
56
- CAPTION_COLOR = None
57
- TEMP_FOLDER = None
58
-
59
- def generate_script(user_input):
60
- """Generate documentary script with proper OpenRouter handling."""
61
- headers = {
62
- 'Authorization': f'Bearer {OPENROUTER_API_KEY}',
63
- 'HTTP-Referer': 'https://your-domain.com',
64
- 'X-Title': 'AI Documentary Maker'
65
- }
66
-
67
- prompt = f"""Short Documentary Script GeneratorInstructions:
68
-
69
- If I say "use this," just output the script exactly as I gave it.
70
- If I only give topics, generate a script based on them.
71
- If I provide a full script, rewrite it without any changes. Make everything short simple and humarous funny and act as serious but humarous. And don't say anything off topic. Also alway say a funny statement to subscribe based on the video topic at the end. Use normal conversational text like a normal person talking and avoid AI phase make the statements humanize and normal conversational
72
- And always talk negative views don't really wants any positive statement and the full script will be one video about one topic so keep in mind
73
- Formatting Rules:
74
-
75
-
76
- Title in Square Brackets:
77
-
78
-
79
- Each section starts with a one-word title inside [ ] (max two words if necessary).
80
- This title will be used as a search term for Pexels footage.
81
-
82
-
83
-
84
- Casual & Funny Narration:
85
-
86
-
87
- Each section has 5-10 words of narration.
88
- Keep it natural, funny, and unpredictable (not robotic, poetic, or rhythmic).
89
-
90
-
91
-
92
- No Special Formatting:
93
-
94
-
95
- No bold, italics, or special characters. You are a assistant AI your task is to create script. You aren't a chatbot. So, don't write extra text
96
-
97
-
98
-
99
- Generalized Search Terms:
100
-
101
-
102
- If a term is too specific, make it more general for Pexels search.
103
-
104
-
105
-
106
- Scene-Specific Writing:
107
-
108
-
109
- Each section describes only what should be shown in the video.
110
-
111
-
112
-
113
- Output Only the Script, and also make it funny and humarous and helirous and also add to subscribe with a funny statement like subscribe now or .....
114
-
115
-
116
- No extra text, just the script.
117
-
118
-
119
-
120
- Example Output:
121
- [North Korea]
122
-
123
- Top 5 unknown facts about North Korea.
124
-
125
- [Invisibility]
126
-
127
- North Korea’s internet speed is so fast… it doesn’t exist.
128
-
129
- [Leadership]
130
-
131
- Kim Jong-un once won an election with 100% votes… against himself.
132
-
133
- [Magic]
134
-
135
- North Korea discovered time travel. That’s why their news is always from the past.
136
-
137
- [Warning]
138
-
139
- Subscribe now, or Kim Jong-un will send you a free one-way ticket… to North Korea.
140
-
141
- [Freedom]
142
-
143
- North Korean citizens can do anything… as long as it's government-approved.
144
- Now here is the Topic/scrip: {user_input}
145
- """
146
-
147
- data = {
148
- 'model': OPENROUTER_MODEL,
149
- 'messages': [{'role': 'user', 'content': prompt}],
150
- 'temperature': 0.4,
151
- 'max_tokens': 5000
152
- }
153
-
154
- try:
155
- response = requests.post(
156
- 'https://openrouter.ai/api/v1/chat/completions',
157
- headers=headers,
158
- json=data,
159
- timeout=30
160
- )
161
-
162
- if response.status_code == 200:
163
- response_data = response.json()
164
- if 'choices' in response_data and len(response_data['choices']) > 0:
165
- return response_data['choices'][0]['message']['content']
166
- else:
167
- print("Unexpected response format:", response_data)
168
- return None
169
- else:
170
- print(f"API Error {response.status_code}: {response.text}")
171
- return None
172
-
173
- except Exception as e:
174
- print(f"Request failed: {str(e)}")
175
- return None
176
-
177
- def parse_script(script_text):
178
- """
179
- Parse the generated script into a list of elements.
180
- For each section, create two elements:
181
- - A 'media' element using the section title as the visual prompt.
182
- - A 'tts' element with the narration text, voice info, and computed duration.
183
- """
184
- sections = {}
185
- current_title = None
186
- current_text = ""
187
-
188
- try:
189
- for line in script_text.splitlines():
190
- line = line.strip()
191
- if line.startswith("[") and "]" in line:
192
- bracket_start = line.find("[")
193
- bracket_end = line.find("]", bracket_start)
194
- if bracket_start != -1 and bracket_end != -1:
195
- if current_title is not None:
196
- sections[current_title] = current_text.strip()
197
- current_title = line[bracket_start+1:bracket_end]
198
- current_text = line[bracket_end+1:].strip()
199
- elif current_title:
200
- current_text += line + " "
201
-
202
- if current_title:
203
- sections[current_title] = current_text.strip()
204
-
205
- elements = []
206
- for title, narration in sections.items():
207
- if not title or not narration:
208
- continue
209
-
210
- media_element = {"type": "media", "prompt": title, "effects": "fade-in"}
211
- words = narration.split()
212
- duration = max(3, len(words) * 0.5)
213
- tts_element = {"type": "tts", "text": narration, "voice": "en", "duration": duration}
214
- elements.append(media_element)
215
- elements.append(tts_element)
216
-
217
- return elements
218
- except Exception as e:
219
- print(f"Error parsing script: {e}")
220
- return []
221
-
222
- def search_pexels_videos(query, pexels_api_key):
223
- """Search for a video on Pexels by query and return a random HD video."""
224
- headers = {'Authorization': pexels_api_key}
225
- base_url = "https://api.pexels.com/videos/search"
226
- num_pages = 3
227
- videos_per_page = 15
228
-
229
- max_retries = 3
230
- retry_delay = 1
231
-
232
- search_query = query
233
- all_videos = []
234
-
235
- for page in range(1, num_pages + 1):
236
- for attempt in range(max_retries):
237
- try:
238
- params = {"query": search_query, "per_page": videos_per_page, "page": page}
239
- response = requests.get(base_url, headers=headers, params=params, timeout=10)
240
-
241
- if response.status_code == 200:
242
- data = response.json()
243
- videos = data.get("videos", [])
244
-
245
- if not videos:
246
- print(f"No videos found on page {page}.")
247
- break
248
-
249
- for video in videos:
250
- video_files = video.get("video_files", [])
251
- for file in video_files:
252
- if file.get("quality") == "hd":
253
- all_videos.append(file.get("link"))
254
- break
255
-
256
- break
257
-
258
- elif response.status_code == 429:
259
- print(f"Rate limit hit (attempt {attempt+1}/{max_retries}). Retrying in {retry_delay} seconds...")
260
- time.sleep(retry_delay)
261
- retry_delay *= 2
262
- else:
263
- print(f"Error fetching videos: {response.status_code} {response.text}")
264
- if attempt < max_retries - 1:
265
- print(f"Retrying in {retry_delay} seconds...")
266
- time.sleep(retry_delay)
267
- retry_delay *= 2
268
- else:
269
- break
270
-
271
- except requests.exceptions.RequestException as e:
272
- print(f"Request exception: {e}")
273
- if attempt < max_retries - 1:
274
- print(f"Retrying in {retry_delay} seconds...")
275
- time.sleep(retry_delay)
276
- retry_delay *= 2
277
- else:
278
- break
279
-
280
- if all_videos:
281
- random_video = random.choice(all_videos)
282
- print(f"Selected random video from {len(all_videos)} HD videos")
283
- return random_video
284
- else:
285
- print("No suitable videos found after searching all pages.")
286
- return None
287
-
288
- def search_pexels_images(query, pexels_api_key):
289
- """Search for an image on Pexels by query."""
290
- headers = {'Authorization': pexels_api_key}
291
- url = "https://api.pexels.com/v1/search"
292
- params = {"query": query, "per_page": 5, "orientation": "landscape"}
293
-
294
- max_retries = 3
295
- retry_delay = 1
296
-
297
- for attempt in range(max_retries):
298
- try:
299
- response = requests.get(url, headers=headers, params=params, timeout=10)
300
-
301
- if response.status_code == 200:
302
- data = response.json()
303
- photos = data.get("photos", [])
304
- if photos:
305
- photo = random.choice(photos[:min(5, len(photos))])
306
- img_url = photo.get("src", {}).get("original")
307
- return img_url
308
- else:
309
- print(f"No images found for query: {query}")
310
- return None
311
-
312
- elif response.status_code == 429:
313
- print(f"Rate limit hit (attempt {attempt+1}/{max_retries}). Retrying in {retry_delay} seconds...")
314
- time.sleep(retry_delay)
315
- retry_delay *= 2
316
- else:
317
- print(f"Error fetching images: {response.status_code} {response.text}")
318
- if attempt < max_retries - 1:
319
- print(f"Retrying in {retry_delay} seconds...")
320
- time.sleep(retry_delay)
321
- retry_delay *= 2
322
-
323
- except requests.exceptions.RequestException as e:
324
- print(f"Request exception: {e}")
325
- if attempt < max_retries - 1:
326
- print(f"Retrying in {retry_delay} seconds...")
327
- time.sleep(retry_delay)
328
- retry_delay *= 2
329
-
330
- print(f"No Pexels images found for query: {query} after all attempts")
331
- return None
332
-
333
- def search_google_images(query):
334
- """Search for images on Google Images (for news-related queries)"""
335
- try:
336
- search_url = f"https://www.google.com/search?q={quote(query)}&tbm=isch"
337
- headers = {"User-Agent": USER_AGENT}
338
- response = requests.get(search_url, headers=headers, timeout=10)
339
- soup = BeautifulSoup(response.text, "html.parser")
340
-
341
- img_tags = soup.find_all("img")
342
- image_urls = []
343
- for img in img_tags:
344
- src = img.get("src", "")
345
- if src.startswith("http") and "gstatic" not in src:
346
- image_urls.append(src)
347
-
348
- if image_urls:
349
- return random.choice(image_urls[:5]) if len(image_urls) >= 5 else image_urls[0]
350
- else:
351
- print(f"No Google Images found for query: {query}")
352
- return None
353
- except Exception as e:
354
- print(f"Error in Google Images search: {e}")
355
- return None
356
-
357
- def download_image(image_url, filename):
358
- """Download an image from a URL to a local file with enhanced error handling."""
359
- try:
360
- headers = {"User-Agent": USER_AGENT}
361
- print(f"Downloading image from: {image_url} to {filename}")
362
- response = requests.get(image_url, headers=headers, stream=True, timeout=15)
363
- response.raise_for_status()
364
-
365
- with open(filename, 'wb') as f:
366
- for chunk in response.iter_content(chunk_size=8192):
367
- f.write(chunk)
368
-
369
- print(f"Image downloaded successfully to: {filename}")
370
-
371
- try:
372
- img = Image.open(filename)
373
- img.verify()
374
- img = Image.open(filename)
375
- if img.mode != 'RGB':
376
- img = img.convert('RGB')
377
- img.save(filename)
378
- print(f"Image validated and processed: {filename}")
379
- return filename
380
- except Exception as e_validate:
381
- print(f"Downloaded file is not a valid image: {e_validate}")
382
- if os.path.exists(filename):
383
- os.remove(filename)
384
- return None
385
-
386
- except requests.exceptions.RequestException as e_download:
387
- print(f"Image download error: {e_download}")
388
- if os.path.exists(filename):
389
- os.remove(filename)
390
- return None
391
- except Exception as e_general:
392
- print(f"General error during image processing: {e_general}")
393
- if os.path.exists(filename):
394
- os.remove(filename)
395
- return None
396
-
397
- def download_video(video_url, filename):
398
- """Download a video from a URL to a local file."""
399
- try:
400
- response = requests.get(video_url, stream=True, timeout=30)
401
- response.raise_for_status()
402
- with open(filename, 'wb') as f:
403
- for chunk in response.iter_content(chunk_size=8192):
404
- f.write(chunk)
405
- print(f"Video downloaded successfully to: {filename}")
406
- return filename
407
- except Exception as e:
408
- print(f"Video download error: {e}")
409
- if os.path.exists(filename):
410
- os.remove(filename)
411
- return None
412
-
413
- def generate_media(prompt, user_image=None, current_index=0, total_segments=1):
414
- """
415
- Generate a visual asset by first searching for a video or using a specific search strategy.
416
- For news-related queries, use Google Images.
417
- Returns a dict: {'path': <file_path>, 'asset_type': 'video' or 'image'}.
418
- """
419
- safe_prompt = re.sub(r'[^\w\s-]', '', prompt).strip().replace(' ', '_')
420
-
421
- if "news" in prompt.lower():
422
- print(f"News-related query detected: {prompt}. Using Google Images...")
423
- image_file = os.path.join(TEMP_FOLDER, f"{safe_prompt}_news.jpg")
424
- image_url = search_google_images(prompt)
425
- if image_url:
426
- downloaded_image = download_image(image_url, image_file)
427
- if downloaded_image:
428
- print(f"News image saved to {downloaded_image}")
429
- return {"path": downloaded_image, "asset_type": "image"}
430
- else:
431
- print(f"Google Images search failed for prompt: {prompt}")
432
-
433
- if random.random() < 0.25:
434
- video_file = os.path.join(TEMP_FOLDER, f"{safe_prompt}_video.mp4")
435
- video_url = search_pexels_videos(prompt, PEXELS_API_KEY)
436
- if video_url:
437
- downloaded_video = download_video(video_url, video_file)
438
- if downloaded_video:
439
- print(f"Video asset saved to {downloaded_video}")
440
- return {"path": downloaded_video, "asset_type": "video"}
441
- else:
442
- print(f"Pexels video search failed for prompt: {prompt}")
443
-
444
- image_file = os.path.join(TEMP_FOLDER, f"{safe_prompt}.jpg")
445
- image_url = search_pexels_images(prompt, PEXELS_API_KEY)
446
- if image_url:
447
- downloaded_image = download_image(image_url, image_file)
448
- if downloaded_image:
449
- print(f"Image asset saved to {downloaded_image}")
450
- return {"path": downloaded_image, "asset_type": "image"}
451
- else:
452
- print(f"Pexels image download failed for prompt: {prompt}")
453
-
454
- fallback_terms = ["nature", "people", "landscape", "technology", "business"]
455
- for term in fallback_terms:
456
- print(f"Trying fallback image search with term: {term}")
457
- fallback_file = os.path.join(TEMP_FOLDER, f"fallback_{term}.jpg")
458
- fallback_url = search_pexels_images(term, PEXELS_API_KEY)
459
- if fallback_url:
460
- downloaded_fallback = download_image(fallback_url, fallback_file)
461
- if downloaded_fallback:
462
- print(f"Fallback image saved to {downloaded_fallback}")
463
- return {"path": downloaded_fallback, "asset_type": "image"}
464
- else:
465
- print(f"Fallback image download failed for term: {term}")
466
- else:
467
- print(f"Fallback image search failed for term: {term}")
468
-
469
- print(f"Failed to generate visual asset for prompt: {prompt}")
470
- return None
471
-
472
- def generate_silent_audio(duration, sample_rate=24000):
473
- """Generate a silent WAV audio file lasting 'duration' seconds."""
474
- num_samples = int(duration * sample_rate)
475
- silence = np.zeros(num_samples, dtype=np.float32)
476
- silent_path = os.path.join(TEMP_FOLDER, f"silent_{int(time.time())}.wav")
477
- sf.write(silent_path, silence, sample_rate)
478
- print(f"Silent audio generated: {silent_path}")
479
- return silent_path
480
-
481
- def generate_tts(text, voice):
482
- """
483
- Generate TTS audio using Kokoro, falling back to gTTS or silent audio if needed.
484
- """
485
- safe_text = re.sub(r'[^\w\s-]', '', text[:10]).strip().replace(' ', '_')
486
- file_path = os.path.join(TEMP_FOLDER, f"tts_{safe_text}.wav")
487
-
488
- if os.path.exists(file_path):
489
- print(f"Using cached TTS for text '{text[:10]}...'")
490
- return file_path
491
-
492
- try:
493
- kokoro_voice = 'af_heart' if voice == 'en' else voice
494
- generator = pipeline(text, voice=kokoro_voice, speed=0.9, split_pattern=r'\n+')
495
- audio_segments = []
496
- for i, (gs, ps, audio) in enumerate(generator):
497
- audio_segments.append(audio)
498
- full_audio = np.concatenate(audio_segments) if len(audio_segments) > 1 else audio_segments[0]
499
- sf.write(file_path, full_audio, 24000)
500
- print(f"TTS audio saved to {file_path} (Kokoro)")
501
- return file_path
502
- except Exception as e:
503
- print(f"Error with Kokoro TTS: {e}")
504
- try:
505
- print("Falling back to gTTS...")
506
- tts = gTTS(text=text, lang='en')
507
- mp3_path = os.path.join(TEMP_FOLDER, f"tts_{safe_text}.mp3")
508
- tts.save(mp3_path)
509
- audio = AudioSegment.from_mp3(mp3_path)
510
- audio.export(file_path, format="wav")
511
- os.remove(mp3_path)
512
- print(f"Fallback TTS saved to {file_path} (gTTS)")
513
- return file_path
514
- except Exception as fallback_error:
515
- print(f"Both TTS methods failed: {fallback_error}")
516
- return generate_silent_audio(duration=max(3, len(text.split()) * 0.5))
517
-
518
- def apply_kenburns_effect(clip, target_resolution, effect_type=None):
519
- """Apply a smooth Ken Burns effect with a single movement pattern."""
520
- target_w, target_h = target_resolution
521
- clip_aspect = clip.w / clip.h
522
- target_aspect = target_w / target_h
523
-
524
- if clip_aspect > target_aspect:
525
- new_height = target_h
526
- new_width = int(new_height * clip_aspect)
527
- else:
528
- new_width = target_w
529
- new_height = int(new_width / clip_aspect)
530
-
531
- clip = clip.resize(newsize=(new_width, new_height))
532
- base_scale = 1.15
533
- new_width = int(new_width * base_scale)
534
- new_height = int(new_height * base_scale)
535
- clip = clip.resize(newsize=(new_width, new_height))
536
-
537
- max_offset_x = new_width - target_w
538
- max_offset_y = new_height - target_h
539
-
540
- available_effects = ["zoom-in", "zoom-out", "pan-left", "pan-right", "up-left"]
541
- if effect_type is None or effect_type == "random":
542
- effect_type = random.choice(available_effects)
543
-
544
- if effect_type == "zoom-in":
545
- start_zoom = 0.9
546
- end_zoom = 1.1
547
- start_center = (new_width / 2, new_height / 2)
548
- end_center = start_center
549
- elif effect_type == "zoom-out":
550
- start_zoom = 1.1
551
- end_zoom = 0.9
552
- start_center = (new_width / 2, new_height / 2)
553
- end_center = start_center
554
- elif effect_type == "pan-left":
555
- start_zoom = 1.0
556
- end_zoom = 1.0
557
- start_center = (max_offset_x + target_w / 2, (max_offset_y // 2) + target_h / 2)
558
- end_center = (target_w / 2, (max_offset_y // 2) + target_h / 2)
559
- elif effect_type == "pan-right":
560
- start_zoom = 1.0
561
- end_zoom = 1.0
562
- start_center = (target_w / 2, (max_offset_y // 2) + target_h / 2)
563
- end_center = (max_offset_x + target_w / 2, (max_offset_y // 2) + target_h / 2)
564
- elif effect_type == "up-left":
565
- start_zoom = 1.0
566
- end_zoom = 1.0
567
- start_center = (max_offset_x + target_w / 2, max_offset_y + target_h / 2)
568
- end_center = (target_w / 2, target_h / 2)
569
- else:
570
- raise ValueError(f"Unsupported effect_type: {effect_type}")
571
-
572
- def transform_frame(get_frame, t):
573
- frame = get_frame(t)
574
- ratio = t / clip.duration if clip.duration > 0 else 0
575
- ratio = 0.5 - 0.5 * math.cos(math.pi * ratio)
576
- current_zoom = start_zoom + (end_zoom - start_zoom) * ratio
577
- crop_w = int(target_w / current_zoom)
578
- crop_h = int(target_h / current_zoom)
579
- current_center_x = start_center[0] + (end_center[0] - start_center[0]) * ratio
580
- current_center_y = start_center[1] + (end_center[1] - start_center[1]) * ratio
581
- min_center_x = crop_w / 2
582
- max_center_x = new_width - crop_w / 2
583
- min_center_y = crop_h / 2
584
- max_center_y = new_height - crop_h / 2
585
- current_center_x = max(min_center_x, min(current_center_x, max_center_x))
586
- current_center_y = max(min_center_y, min(current_center_y, max_center_y))
587
- cropped_frame = cv2.getRectSubPix(frame, (crop_w, crop_h), (current_center_x, current_center_y))
588
- resized_frame = cv2.resize(cropped_frame, (target_w, target_h), interpolation=cv2.INTER_LANCZOS4)
589
- return resized_frame
590
-
591
- return clip.fl(transform_frame)
592
-
593
- def resize_to_fill(clip, target_resolution):
594
- """Resize and crop a clip to fill the target resolution while maintaining aspect ratio."""
595
- target_w, target_h = target_resolution
596
- clip_aspect = clip.w / clip.h
597
- target_aspect = target_w / target_h
598
-
599
- if clip_aspect > target_aspect:
600
- clip = clip.resize(height=target_h)
601
- crop_amount = (clip.w - target_w) / 2
602
- clip = clip.crop(x1=crop_amount, x2=clip.w - crop_amount, y1=0, y2=clip.h)
603
- else:
604
- clip = clip.resize(width=target_w)
605
- crop_amount = (clip.h - target_h) / 2
606
- clip = clip.crop(x1=0, x2=clip.w, y1=crop_amount, y2=clip.h - crop_amount)
607
-
608
- return clip
609
-
610
- def find_mp3_files():
611
- """Search for any MP3 files in the current directory and subdirectories."""
612
- mp3_files = []
613
- for root, dirs, files in os.walk('.'):
614
- for file in files:
615
- if file.endswith('.mp3'):
616
- mp3_path = os.path.join(root, file)
617
- mp3_files.append(mp3_path)
618
- print(f"Found MP3 file: {mp3_path}")
619
- return mp3_files[0] if mp3_files else None
620
-
621
- def add_background_music(final_video, bg_music_volume=0.08):
622
- """Add background music to the final video using any MP3 file found."""
623
- try:
624
- bg_music_path = find_mp3_files()
625
- if bg_music_path and os.path.exists(bg_music_path):
626
- print(f"Adding background music from: {bg_music_path}")
627
- bg_music = AudioFileClip(bg_music_path)
628
- if bg_music.duration < final_video.duration:
629
- loops_needed = math.ceil(final_video.duration / bg_music.duration)
630
- bg_segments = [bg_music] * loops_needed
631
- bg_music = concatenate_audioclips(bg_segments)
632
- bg_music = bg_music.subclip(0, final_video.duration)
633
- bg_music = bg_music.volumex(bg_music_volume)
634
- video_audio = final_video.audio
635
- mixed_audio = CompositeAudioClip([video_audio, bg_music])
636
- final_video = final_video.set_audio(mixed_audio)
637
- print("Background music added successfully")
638
- else:
639
- print("No MP3 files found, skipping background music")
640
- return final_video
641
- except Exception as e:
642
- print(f"Error adding background music: {e}")
643
- print("Continuing without background music")
644
- return final_video
645
-
646
- def create_clip(media_path, asset_type, tts_path, duration=None, effects=None, narration_text=None, segment_index=0):
647
- """Create a video clip with synchronized subtitles and narration."""
648
- try:
649
- print(f"Creating clip #{segment_index} with asset_type: {asset_type}, media_path: {media_path}")
650
- if not os.path.exists(media_path) or not os.path.exists(tts_path):
651
- print("Missing media or TTS file")
652
- return None
653
-
654
- audio_clip = AudioFileClip(tts_path).audio_fadeout(0.2)
655
- audio_duration = audio_clip.duration
656
- target_duration = audio_duration + 0.2
657
-
658
- if asset_type == "video":
659
- clip = VideoFileClip(media_path)
660
- clip = resize_to_fill(clip, TARGET_RESOLUTION)
661
- if clip.duration < target_duration:
662
- clip = clip.loop(duration=target_duration)
663
- else:
664
- clip = clip.subclip(0, target_duration)
665
- elif asset_type == "image":
666
- img = Image.open(media_path)
667
- if img.mode != 'RGB':
668
- with tempfile.NamedTemporaryFile(suffix='.jpg', delete=False) as temp:
669
- img.convert('RGB').save(temp.name)
670
- media_path = temp.name
671
- img.close()
672
- clip = ImageClip(media_path).set_duration(target_duration)
673
- clip = apply_kenburns_effect(clip, TARGET_RESOLUTION)
674
- clip = clip.fadein(0.3).fadeout(0.3)
675
- else:
676
- return None
677
-
678
- if narration_text and CAPTION_COLOR != "transparent":
679
- try:
680
- words = narration_text.split()
681
- chunks = []
682
- current_chunk = []
683
- for word in words:
684
- current_chunk.append(word)
685
- if len(current_chunk) >= 5:
686
- chunks.append(' '.join(current_chunk))
687
- current_chunk = []
688
- if current_chunk:
689
- chunks.append(' '.join(current_chunk))
690
-
691
- chunk_duration = audio_duration / len(chunks)
692
- subtitle_clips = []
693
- subtitle_y_position = int(TARGET_RESOLUTION[1] * 0.70)
694
-
695
- for i, chunk_text in enumerate(chunks):
696
- start_time = i * chunk_duration
697
- end_time = (i + 1) * chunk_duration
698
- txt_clip = TextClip(
699
- chunk_text,
700
- fontsize=45,
701
- font='Arial-Bold',
702
- color=CAPTION_COLOR,
703
- bg_color='rgba(0, 0, 0, 0.25)',
704
- method='caption',
705
- align='center',
706
- stroke_width=2,
707
- stroke_color=CAPTION_COLOR,
708
- size=(TARGET_RESOLUTION[0] * 0.8, None)
709
- ).set_start(start_time).set_end(end_time)
710
- txt_clip = txt_clip.set_position(('center', subtitle_y_position))
711
- subtitle_clips.append(txt_clip)
712
-
713
- clip = CompositeVideoClip([clip] + subtitle_clips)
714
- except Exception as sub_error:
715
- print(f"Subtitle error: {sub_error}")
716
- txt_clip = TextClip(
717
- narration_text,
718
- fontsize=28,
719
- color=CAPTION_COLOR,
720
- align='center',
721
- size=(TARGET_RESOLUTION[0] * 0.7, None)
722
- ).set_position(('center', int(TARGET_RESOLUTION[1] / 3))).set_duration(clip.duration)
723
- clip = CompositeVideoClip([clip, txt_clip])
724
-
725
- clip = clip.set_audio(audio_clip)
726
- print(f"Clip created: {clip.duration:.1f}s")
727
- return clip
728
- except Exception as e:
729
- print(f"Error in create_clip: {str(e)}")
730
- return None
731
-
732
- def fix_imagemagick_policy():
733
- """Fix ImageMagick security policies."""
734
- try:
735
- print("Attempting to fix ImageMagick security policies...")
736
- policy_paths = [
737
- "/etc/ImageMagick-6/policy.xml",
738
- "/etc/ImageMagick-7/policy.xml",
739
- "/etc/ImageMagick/policy.xml",
740
- "/usr/local/etc/ImageMagick-7/policy.xml"
741
- ]
742
- found_policy = next((path for path in policy_paths if os.path.exists(path)), None)
743
- if not found_policy:
744
- print("No policy.xml found. Using alternative subtitle method.")
745
- return False
746
- print(f"Modifying policy file at {found_policy}")
747
- os.system(f"sudo cp {found_policy} {found_policy}.bak")
748
- os.system(f"sudo sed -i 's/rights=\"none\"/rights=\"read|write\"/g' {found_policy}")
749
- os.system(f"sudo sed -i 's/<policy domain=\"path\" pattern=\"@\*\"[^>]*>/<policy domain=\"path\" pattern=\"@*\" rights=\"read|write\"/g' {found_policy}")
750
- os.system(f"sudo sed -i 's/<policy domain=\"coder\" rights=\"none\" pattern=\"PDF\"[^>]*>/<!-- <policy domain=\"coder\" rights=\"none\" pattern=\"PDF\"> -->/g' {found_policy}")
751
- print("ImageMagick policies updated successfully.")
752
- return True
753
- except Exception as e:
754
- print(f"Error fixing policies: {e}")
755
- return False
756
-
757
- # ---------------- Main Function with Gradio Integration ---------------- #
758
- def generate_video(user_input, resolution, caption_option):
759
- """Generate a video based on user input via Gradio."""
760
- global TARGET_RESOLUTION, CAPTION_COLOR, TEMP_FOLDER
761
- import shutil
762
-
763
- # Set resolution
764
- if resolution == "Full":
765
- TARGET_RESOLUTION = (1920, 1080)
766
- elif resolution == "Short":
767
- TARGET_RESOLUTION = (1080, 1920)
768
- else:
769
- TARGET_RESOLUTION = (1920, 1080) # Default
770
-
771
- # Set caption color
772
- CAPTION_COLOR = "white" if caption_option == "Yes" else "transparent"
773
-
774
- # Create a unique temporary folder
775
- TEMP_FOLDER = tempfile.mkdtemp()
776
-
777
- # Fix ImageMagick policy
778
- fix_success = fix_imagemagick_policy()
779
- if not fix_success:
780
- print("Will use alternative methods if needed")
781
-
782
- print("Generating script from API...")
783
- script = generate_script(user_input)
784
- if not script:
785
- print("Failed to generate script.")
786
- shutil.rmtree(TEMP_FOLDER)
787
- return None
788
- print("Generated Script:\n", script)
789
- elements = parse_script(script)
790
- if not elements:
791
- print("Failed to parse script into elements.")
792
- shutil.rmtree(TEMP_FOLDER)
793
- return None
794
- print(f"Parsed {len(elements)//2} script segments.")
795
-
796
- paired_elements = []
797
- for i in range(0, len(elements), 2):
798
- if i + 1 < len(elements):
799
- paired_elements.append((elements[i], elements[i + 1]))
800
-
801
- if not paired_elements:
802
- print("No valid script segments found.")
803
- shutil.rmtree(TEMP_FOLDER)
804
- return None
805
-
806
- clips = []
807
- for idx, (media_elem, tts_elem) in enumerate(paired_elements):
808
- print(f"\nProcessing segment {idx+1}/{len(paired_elements)} with prompt: '{media_elem['prompt']}'")
809
- media_asset = generate_media(media_elem['prompt'], current_index=idx, total_segments=len(paired_elements))
810
- if not media_asset:
811
- print(f"Skipping segment {idx+1} due to missing media asset.")
812
- continue
813
- tts_path = generate_tts(tts_elem['text'], tts_elem['voice'])
814
- if not tts_path:
815
- print(f"Skipping segment {idx+1} due to TTS generation failure.")
816
- continue
817
- clip = create_clip(
818
- media_path=media_asset['path'],
819
- asset_type=media_asset['asset_type'],
820
- tts_path=tts_path,
821
- duration=tts_elem['duration'],
822
- effects=media_elem.get('effects', 'fade-in'),
823
- narration_text=tts_elem['text'],
824
- segment_index=idx
825
- )
826
- if clip:
827
- clips.append(clip)
828
- else:
829
- print(f"Clip creation failed for segment {idx+1}.")
830
-
831
- if not clips:
832
- print("No clips were successfully created.")
833
- shutil.rmtree(TEMP_FOLDER)
834
- return None
835
-
836
- print("\nConcatenating clips...")
837
- final_video = concatenate_videoclips(clips, method="compose")
838
- final_video = add_background_music(final_video, bg_music_volume=0.08)
839
-
840
- print(f"Exporting final video to {OUTPUT_VIDEO_FILENAME}...")
841
- final_video.write_videofile(OUTPUT_VIDEO_FILENAME, codec='libx264', fps=24, preset='veryfast')
842
- print(f"Final video saved as {OUTPUT_VIDEO_FILENAME}")
843
-
844
- # Clean up
845
- print("Cleaning up temporary files...")
846
- shutil.rmtree(TEMP_FOLDER)
847
- print("Temporary files removed.")
848
-
849
- return OUTPUT_VIDEO_FILENAME
850
-
851
- # ---------------- Gradio Interface ---------------- #
852
- iface = gr.Interface(
853
- fn=generate_video,
854
- inputs=[
855
- gr.Textbox(label="Video Concept", placeholder="Enter your video concept here..."),
856
- gr.Radio(["Full", "Short"], label="Resolution", value="Full"),
857
- gr.Radio(["Yes", "No"], label="Captions", value="Yes")
858
- ],
859
- outputs=gr.Video(label="Generated Video"),
860
- title="AI Documentary Video Generator",
861
- description="Create a funny documentary-style video based on your concept. Note: Generation may take several minutes on CPU."
862
- )
863
-
864
- # Launch the interface
865
- iface.launch(share=True)
 
1
+ try:
2
+ from moviepy.editor import VideoFileClip, AudioFileClip, ImageClip
3
+ except Exception as e:
4
+ print("⚠️ moviepy import failed:", e)
5
+ VideoFileClip = AudioFileClip = ImageClip = None