Update core/visual_engine.py
Browse files- core/visual_engine.py +82 -73
core/visual_engine.py
CHANGED
@@ -1,5 +1,4 @@
|
|
1 |
# core/visual_engine.py
|
2 |
-
# ... (imports: PIL, MoviePy, numpy, os, openai, requests, io, time, elevenlabs - same) ...
|
3 |
from PIL import Image, ImageDraw, ImageFont
|
4 |
from moviepy.editor import (ImageClip, concatenate_videoclips, TextClip,
|
5 |
CompositeVideoClip, AudioFileClip)
|
@@ -10,25 +9,23 @@ import openai
|
|
10 |
import requests
|
11 |
import io
|
12 |
import time
|
13 |
-
import random
|
14 |
from elevenlabs import generate as elevenlabs_generate_audio, set_api_key as elevenlabs_set_api_key_func
|
15 |
|
16 |
class VisualEngine:
|
17 |
def __init__(self, output_dir="temp_cinegen_media"):
|
18 |
-
# ... (font setup, API key initializations, DALL-E settings - same) ...
|
19 |
self.output_dir = output_dir; os.makedirs(self.output_dir, exist_ok=True)
|
20 |
self.font_filename="arial.ttf"; self.font_path_in_container=f"/usr/local/share/fonts/truetype/mycustomfonts/{self.font_filename}"
|
21 |
self.font_size_pil=20; self.video_overlay_font_size=30; self.video_overlay_font_color='white'; self.video_overlay_font='Arial-Bold'
|
22 |
try: self.font = ImageFont.truetype(self.font_path_in_container, self.font_size_pil); print(f"Placeholder font: {self.font_path_in_container}.")
|
23 |
except IOError: print(f"Warn: Placeholder font '{self.font_path_in_container}' fail. Default."); self.font = ImageFont.load_default(); self.font_size_pil = 10
|
24 |
self.openai_api_key = None; self.USE_AI_IMAGE_GENERATION = False
|
25 |
-
self.dalle_model = "dall-e-3"; self.image_size_dalle3 = "1792x1024"
|
26 |
self.video_frame_size = (1280, 720)
|
27 |
self.elevenlabs_api_key = None; self.USE_ELEVENLABS = False; self.elevenlabs_voice_id = "Rachel"
|
28 |
self.pexels_api_key = None; self.USE_PEXELS = False
|
29 |
|
30 |
-
|
31 |
-
def set_openai_api_key(self,k): # Pythonic shortened
|
32 |
self.openai_api_key=k; self.USE_AI_IMAGE_GENERATION=bool(k)
|
33 |
print(f"DALL-E ({self.dalle_model}) {'Ready' if k else 'Disabled'}.")
|
34 |
def set_elevenlabs_api_key(self,k):
|
@@ -41,15 +38,15 @@ class VisualEngine:
|
|
41 |
self.pexels_api_key=k; self.USE_PEXELS=bool(k)
|
42 |
print(f"Pexels {'Ready' if k else 'Disabled'}.")
|
43 |
|
44 |
-
|
45 |
-
def _get_text_dimensions(self,t,f): # Shortened
|
46 |
if not t: return 0,self.font_size_pil
|
47 |
try:
|
48 |
if hasattr(f,'getbbox'): bb=f.getbbox(t);w=bb[2]-bb[0];h=bb[3]-bb[1];return w,h if h>0 else self.font_size_pil
|
49 |
elif hasattr(f,'getsize'): w,h=f.getsize(t);return w,h if h>0 else self.font_size_pil
|
50 |
else: return int(len(t)*self.font_size_pil*.6),int(self.font_size_pil*1.2 if self.font_size_pil*1.2>0 else self.font_size_pil)
|
51 |
except: return int(len(t)*self.font_size_pil*.6),int(self.font_size_pil*1.2)
|
52 |
-
|
|
|
53 |
img=Image.new('RGB',s,color=(20,20,40));d=ImageDraw.Draw(img);p=25;max_w=s[0]-(2*p);ls=[];
|
54 |
if not td: td="(Placeholder)"
|
55 |
ws=td.split();cl=""
|
@@ -65,46 +62,36 @@ class VisualEngine:
|
|
65 |
max_ls=min(len(ls),(s[1]-2*p)//(sh+2));
|
66 |
yt=p+(s[1]-2*p-max_ls*(sh+2))/2.0
|
67 |
for i in range(max_ls):
|
68 |
-
|
69 |
-
d.text((xt,yt),
|
70 |
if i==6 and max_ls>7:d.text((xt,yt),"...",font=self.font,fill=(200,200,180));break
|
71 |
fp=os.path.join(self.output_dir,fn);
|
72 |
try:img.save(fp);return fp
|
73 |
except Exception as e:print(f"Err placeholder save: {e}");return None
|
74 |
|
75 |
-
# ... (_search_pexels_image - same logic, ensure query is good) ...
|
76 |
def _search_pexels_image(self, query, output_filename):
|
77 |
if not self.USE_PEXELS or not self.pexels_api_key: return None
|
78 |
headers = {"Authorization": self.pexels_api_key}
|
79 |
-
# Use a broader query, let Pexels do its magic, then maybe allow user to pick from a few
|
80 |
params = {"query": query, "per_page": 3, "orientation": "landscape", "size": "large"}
|
81 |
pexels_filename = output_filename.replace(".png", f"_pexels_{random.randint(100,999)}.jpg")
|
82 |
filepath = os.path.join(self.output_dir, pexels_filename)
|
83 |
try:
|
84 |
print(f"Searching Pexels for: '{query}'")
|
|
|
|
|
85 |
response = requests.get("https://api.pexels.com/v1/search", headers=headers, params=params, timeout=15)
|
86 |
response.raise_for_status(); data = response.json()
|
87 |
if data.get("photos"):
|
88 |
-
# For now, just take the first one. UI could let user pick.
|
89 |
photo_url = data["photos"][0]["src"]["large2x"]
|
90 |
image_response = requests.get(photo_url, timeout=45); image_response.raise_for_status()
|
91 |
img_data = Image.open(io.BytesIO(image_response.content))
|
92 |
if img_data.mode != 'RGB': img_data = img_data.convert('RGB')
|
93 |
img_data.save(filepath); print(f"Pexels image saved: {filepath}"); return filepath
|
94 |
-
else: print(f"No photos on Pexels for: '{
|
95 |
except Exception as e: print(f"Pexels error for '{query}': {e}")
|
96 |
return None
|
97 |
|
98 |
-
# generate_image_visual - The Pexels fallback query should use the specific `pexels_search_query_감독`
|
99 |
def generate_image_visual(self, image_prompt_text, scene_data, scene_identifier_filename):
|
100 |
-
# ... (DALL-E logic same as previous version including retries) ...
|
101 |
-
# Fallback logic:
|
102 |
-
# print("DALL-E failed. Trying Pexels...")
|
103 |
-
# pexels_query = scene_data.get('pexels_search_query_감독', "abstract background") # Use Gemini's suggestion
|
104 |
-
# pexels_path = self._search_pexels_image(pexels_query, scene_identifier_filename)
|
105 |
-
# if pexels_path: return pexels_path
|
106 |
-
# return self._create_placeholder_image_content(...)
|
107 |
-
# For brevity, pasting the core DALL-E logic again:
|
108 |
filepath = os.path.join(self.output_dir, scene_identifier_filename)
|
109 |
if self.USE_AI_IMAGE_GENERATION and self.openai_api_key:
|
110 |
max_retries = 2
|
@@ -112,40 +99,75 @@ class VisualEngine:
|
|
112 |
try:
|
113 |
print(f"Attempt {attempt+1}: DALL-E ({self.dalle_model}) for: {image_prompt_text[:120]}...")
|
114 |
client = openai.OpenAI(api_key=self.openai_api_key, timeout=90.0)
|
115 |
-
response = client.images.generate(
|
116 |
-
|
117 |
-
|
118 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
119 |
img_data = Image.open(io.BytesIO(image_response.content))
|
120 |
-
if img_data.mode != 'RGB':
|
121 |
-
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
except
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
128 |
|
129 |
-
|
130 |
-
#
|
|
|
131 |
pexels_query_text = scene_data.get('pexels_search_query_감독', f"{scene_data.get('emotional_beat','')} {scene_data.get('setting_description','')}")
|
132 |
pexels_path = self._search_pexels_image(pexels_query_text, scene_identifier_filename)
|
133 |
-
if pexels_path:
|
|
|
134 |
|
135 |
print("Pexels also failed/disabled. Using placeholder.")
|
136 |
-
return self._create_placeholder_image_content(
|
|
|
|
|
|
|
137 |
else: # AI image generation not enabled
|
138 |
-
return self._create_placeholder_image_content(
|
139 |
-
|
|
|
140 |
|
141 |
-
def generate_narration_audio(self, text_to_narrate, output_filename="narration_overall.mp3"):
|
142 |
if not self.USE_ELEVENLABS or not self.elevenlabs_api_key or not text_to_narrate:
|
143 |
print("ElevenLabs disabled/no text. Skipping audio."); return None
|
144 |
audio_filepath = os.path.join(self.output_dir, output_filename)
|
145 |
try:
|
146 |
print(f"Generating ElevenLabs audio (Voice: {self.elevenlabs_voice_id}) for: {text_to_narrate[:70]}...")
|
147 |
-
#
|
148 |
-
# elevenlabs_set_api_key_func(self.elevenlabs_api_key) # Ensure key is set for the library
|
149 |
audio_data = elevenlabs_generate_audio(text=text_to_narrate, voice=self.elevenlabs_voice_id, model="eleven_multilingual_v2")
|
150 |
with open(audio_filepath, "wb") as f: f.write(audio_data)
|
151 |
print(f"ElevenLabs audio saved: {audio_filepath}"); return audio_filepath
|
@@ -153,12 +175,12 @@ class VisualEngine:
|
|
153 |
except Exception as e: print(f"Error ElevenLabs audio: {e}")
|
154 |
return None
|
155 |
|
156 |
-
def create_video_from_images(self, image_data_list, overall_narration_path=None, output_filename="final_video.mp4", fps=24, duration_per_image=4.5):
|
157 |
-
# ... (Image processing, Ken Burns, Text Overlay from previous full version) ...
|
158 |
-
# Add slight random variation to Ken Burns
|
159 |
if not image_data_list: return None
|
|
|
160 |
processed_clips = []
|
161 |
-
narration_audio_clip = None
|
|
|
162 |
|
163 |
for i, data in enumerate(image_data_list):
|
164 |
img_path, scene_num, key_action = data.get('path'), data.get('scene_num', i+1), data.get('key_action', '')
|
@@ -166,43 +188,29 @@ class VisualEngine:
|
|
166 |
try:
|
167 |
pil_img = Image.open(img_path);
|
168 |
if pil_img.mode != 'RGB': pil_img = pil_img.convert('RGB')
|
169 |
-
|
170 |
-
# Ensure image fits within video_frame_size, letter/pillarboxing
|
171 |
img_copy = pil_img.copy()
|
172 |
img_copy.thumbnail(self.video_frame_size, Image.Resampling.LANCZOS)
|
173 |
-
canvas = Image.new('RGB', self.video_frame_size, (random.randint(0,15), random.randint(0,15), random.randint(0,15)))
|
174 |
xo, yo = (self.video_frame_size[0]-img_copy.width)//2, (self.video_frame_size[1]-img_copy.height)//2
|
175 |
canvas.paste(img_copy, (xo,yo))
|
176 |
frame_np = np.array(canvas)
|
177 |
-
|
178 |
img_clip = ImageClip(frame_np).set_duration(duration_per_image)
|
179 |
-
|
180 |
-
# Enhanced Ken Burns: Random start/end zoom & slight pan
|
181 |
-
start_scale = 1.0
|
182 |
-
end_scale = random.uniform(1.05, 1.15) # Random zoom between 5% and 15%
|
183 |
-
|
184 |
-
# Subtle random panning (values between -0.05 and 0.05 relative to image dimension)
|
185 |
-
# Pan is (fraction_of_width, fraction_of_height)
|
186 |
-
# For this, it's easier if the image is slightly larger than the crop area initially.
|
187 |
-
# A simpler way is to resize and then use set_position with a lambda for movement.
|
188 |
-
# Let's simplify to just zoom for now to avoid overcomplicating the resize lambda.
|
189 |
img_clip = img_clip.fx(vfx.resize, lambda t: 1 + (end_scale - 1) * (t / duration_per_image))
|
190 |
img_clip = img_clip.set_position('center')
|
191 |
-
|
192 |
if key_action:
|
193 |
txt_clip = TextClip(f"Scene {scene_num}\n{key_action}", fontsize=self.video_overlay_font_size,
|
194 |
color=self.video_overlay_font_color, font=self.video_overlay_font,
|
195 |
bg_color='rgba(10,10,20,0.75)', method='caption', align='West',
|
196 |
size=(self.video_frame_size[0]*0.9, None), kerning=-1, stroke_color='black', stroke_width=1
|
197 |
-
).set_duration(duration_per_image - 1.0).set_start(0.5).set_position(('center', 0.9), relative=True)
|
198 |
final_scene_clip = CompositeVideoClip([img_clip, txt_clip], size=self.video_frame_size)
|
199 |
else: final_scene_clip = img_clip
|
200 |
processed_clips.append(final_scene_clip)
|
201 |
except Exception as e: print(f"Error clip for {img_path}: {e}.")
|
202 |
|
203 |
if not processed_clips: print("No clips for video."); return None
|
204 |
-
|
205 |
-
transition = 0.8 # Slightly longer crossfade
|
206 |
final_video_clip_obj = concatenate_videoclips(processed_clips, padding=-transition, method="compose")
|
207 |
if final_video_clip_obj.duration > transition*2:
|
208 |
final_video_clip_obj = final_video_clip_obj.fx(vfx.fadein, transition).fx(vfx.fadeout, transition)
|
@@ -211,7 +219,6 @@ class VisualEngine:
|
|
211 |
try:
|
212 |
narration_audio_clip = AudioFileClip(overall_narration_path)
|
213 |
final_video_clip_obj = final_video_clip_obj.set_audio(narration_audio_clip)
|
214 |
-
# Adjust video duration to match audio if audio is shorter.
|
215 |
if narration_audio_clip.duration < final_video_clip_obj.duration:
|
216 |
final_video_clip_obj = final_video_clip_obj.subclip(0, narration_audio_clip.duration)
|
217 |
print("Overall narration added.")
|
@@ -219,12 +226,14 @@ class VisualEngine:
|
|
219 |
|
220 |
output_path = os.path.join(self.output_dir, output_filename)
|
221 |
try:
|
222 |
-
final_video_clip_obj.write_videofile(output_path, fps=fps, codec='libx264', preset='
|
|
|
223 |
temp_audiofile=os.path.join(self.output_dir, f'temp-audio-{os.urandom(4).hex()}.m4a'),
|
224 |
-
remove_temp=True, threads=os.cpu_count() or 2, logger='bar', bitrate="5000k")
|
225 |
print(f"Video created: {output_path}"); return output_path
|
226 |
except Exception as e: print(f"Error writing video: {e}"); return None
|
227 |
finally:
|
228 |
-
for c in processed_clips:
|
229 |
-
|
230 |
-
if
|
|
|
|
1 |
# core/visual_engine.py
|
|
|
2 |
from PIL import Image, ImageDraw, ImageFont
|
3 |
from moviepy.editor import (ImageClip, concatenate_videoclips, TextClip,
|
4 |
CompositeVideoClip, AudioFileClip)
|
|
|
9 |
import requests
|
10 |
import io
|
11 |
import time
|
12 |
+
import random
|
13 |
from elevenlabs import generate as elevenlabs_generate_audio, set_api_key as elevenlabs_set_api_key_func
|
14 |
|
15 |
class VisualEngine:
|
16 |
def __init__(self, output_dir="temp_cinegen_media"):
|
|
|
17 |
self.output_dir = output_dir; os.makedirs(self.output_dir, exist_ok=True)
|
18 |
self.font_filename="arial.ttf"; self.font_path_in_container=f"/usr/local/share/fonts/truetype/mycustomfonts/{self.font_filename}"
|
19 |
self.font_size_pil=20; self.video_overlay_font_size=30; self.video_overlay_font_color='white'; self.video_overlay_font='Arial-Bold'
|
20 |
try: self.font = ImageFont.truetype(self.font_path_in_container, self.font_size_pil); print(f"Placeholder font: {self.font_path_in_container}.")
|
21 |
except IOError: print(f"Warn: Placeholder font '{self.font_path_in_container}' fail. Default."); self.font = ImageFont.load_default(); self.font_size_pil = 10
|
22 |
self.openai_api_key = None; self.USE_AI_IMAGE_GENERATION = False
|
23 |
+
self.dalle_model = "dall-e-3"; self.image_size_dalle3 = "1792x1024"
|
24 |
self.video_frame_size = (1280, 720)
|
25 |
self.elevenlabs_api_key = None; self.USE_ELEVENLABS = False; self.elevenlabs_voice_id = "Rachel"
|
26 |
self.pexels_api_key = None; self.USE_PEXELS = False
|
27 |
|
28 |
+
def set_openai_api_key(self,k):
|
|
|
29 |
self.openai_api_key=k; self.USE_AI_IMAGE_GENERATION=bool(k)
|
30 |
print(f"DALL-E ({self.dalle_model}) {'Ready' if k else 'Disabled'}.")
|
31 |
def set_elevenlabs_api_key(self,k):
|
|
|
38 |
self.pexels_api_key=k; self.USE_PEXELS=bool(k)
|
39 |
print(f"Pexels {'Ready' if k else 'Disabled'}.")
|
40 |
|
41 |
+
def _get_text_dimensions(self,t,f):
|
|
|
42 |
if not t: return 0,self.font_size_pil
|
43 |
try:
|
44 |
if hasattr(f,'getbbox'): bb=f.getbbox(t);w=bb[2]-bb[0];h=bb[3]-bb[1];return w,h if h>0 else self.font_size_pil
|
45 |
elif hasattr(f,'getsize'): w,h=f.getsize(t);return w,h if h>0 else self.font_size_pil
|
46 |
else: return int(len(t)*self.font_size_pil*.6),int(self.font_size_pil*1.2 if self.font_size_pil*1.2>0 else self.font_size_pil)
|
47 |
except: return int(len(t)*self.font_size_pil*.6),int(self.font_size_pil*1.2)
|
48 |
+
|
49 |
+
def _create_placeholder_image_content(self,td,fn,s=(1280,720)):
|
50 |
img=Image.new('RGB',s,color=(20,20,40));d=ImageDraw.Draw(img);p=25;max_w=s[0]-(2*p);ls=[];
|
51 |
if not td: td="(Placeholder)"
|
52 |
ws=td.split();cl=""
|
|
|
62 |
max_ls=min(len(ls),(s[1]-2*p)//(sh+2));
|
63 |
yt=p+(s[1]-2*p-max_ls*(sh+2))/2.0
|
64 |
for i in range(max_ls):
|
65 |
+
line=ls[i];lw,_=self._get_text_dimensions(line,self.font);xt=(s[0]-lw)/2.0
|
66 |
+
d.text((xt,yt),line,font=self.font,fill=(200,200,180));yt+=sh+2
|
67 |
if i==6 and max_ls>7:d.text((xt,yt),"...",font=self.font,fill=(200,200,180));break
|
68 |
fp=os.path.join(self.output_dir,fn);
|
69 |
try:img.save(fp);return fp
|
70 |
except Exception as e:print(f"Err placeholder save: {e}");return None
|
71 |
|
|
|
72 |
def _search_pexels_image(self, query, output_filename):
|
73 |
if not self.USE_PEXELS or not self.pexels_api_key: return None
|
74 |
headers = {"Authorization": self.pexels_api_key}
|
|
|
75 |
params = {"query": query, "per_page": 3, "orientation": "landscape", "size": "large"}
|
76 |
pexels_filename = output_filename.replace(".png", f"_pexels_{random.randint(100,999)}.jpg")
|
77 |
filepath = os.path.join(self.output_dir, pexels_filename)
|
78 |
try:
|
79 |
print(f"Searching Pexels for: '{query}'")
|
80 |
+
query_parts = query.split(); effective_query = " ".join(query_parts[:5])
|
81 |
+
params["query"] = effective_query
|
82 |
response = requests.get("https://api.pexels.com/v1/search", headers=headers, params=params, timeout=15)
|
83 |
response.raise_for_status(); data = response.json()
|
84 |
if data.get("photos"):
|
|
|
85 |
photo_url = data["photos"][0]["src"]["large2x"]
|
86 |
image_response = requests.get(photo_url, timeout=45); image_response.raise_for_status()
|
87 |
img_data = Image.open(io.BytesIO(image_response.content))
|
88 |
if img_data.mode != 'RGB': img_data = img_data.convert('RGB')
|
89 |
img_data.save(filepath); print(f"Pexels image saved: {filepath}"); return filepath
|
90 |
+
else: print(f"No photos on Pexels for: '{effective_query}'")
|
91 |
except Exception as e: print(f"Pexels error for '{query}': {e}")
|
92 |
return None
|
93 |
|
|
|
94 |
def generate_image_visual(self, image_prompt_text, scene_data, scene_identifier_filename):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
95 |
filepath = os.path.join(self.output_dir, scene_identifier_filename)
|
96 |
if self.USE_AI_IMAGE_GENERATION and self.openai_api_key:
|
97 |
max_retries = 2
|
|
|
99 |
try:
|
100 |
print(f"Attempt {attempt+1}: DALL-E ({self.dalle_model}) for: {image_prompt_text[:120]}...")
|
101 |
client = openai.OpenAI(api_key=self.openai_api_key, timeout=90.0)
|
102 |
+
response = client.images.generate(
|
103 |
+
model=self.dalle_model,
|
104 |
+
prompt=image_prompt_text,
|
105 |
+
n=1,
|
106 |
+
size=self.image_size_dalle3,
|
107 |
+
quality="hd",
|
108 |
+
response_format="url",
|
109 |
+
style="vivid"
|
110 |
+
)
|
111 |
+
image_url = response.data[0].url
|
112 |
+
revised_prompt = getattr(response.data[0], 'revised_prompt', None)
|
113 |
+
if revised_prompt:
|
114 |
+
print(f"DALL-E 3 revised_prompt: {revised_prompt[:100]}...")
|
115 |
+
|
116 |
+
image_response = requests.get(image_url, timeout=120)
|
117 |
+
image_response.raise_for_status()
|
118 |
img_data = Image.open(io.BytesIO(image_response.content))
|
119 |
+
if img_data.mode != 'RGB':
|
120 |
+
img_data = img_data.convert('RGB')
|
121 |
+
|
122 |
+
img_data.save(filepath)
|
123 |
+
print(f"AI Image (DALL-E) saved: {filepath}")
|
124 |
+
return filepath
|
125 |
+
|
126 |
+
except openai.RateLimitError as e:
|
127 |
+
print(f"OpenAI Rate Limit: {e}. Retrying after {5*(attempt+1)}s...")
|
128 |
+
time.sleep(5 * (attempt + 1))
|
129 |
+
# CORRECTED INDENTATION FOR THIS BLOCK
|
130 |
+
if attempt == max_retries - 1:
|
131 |
+
print("Max retries reached for RateLimitError.")
|
132 |
+
break # Break from the for loop if max retries hit for RateLimitError
|
133 |
+
else:
|
134 |
+
continue # Go to the next attempt in the for loop
|
135 |
+
|
136 |
+
except openai.APIError as e:
|
137 |
+
print(f"OpenAI API Error: {e}")
|
138 |
+
break # Break from loop, will try Pexels/placeholder
|
139 |
+
except requests.exceptions.RequestException as e:
|
140 |
+
print(f"Requests Error (DALL-E image download): {e}")
|
141 |
+
break # Break from loop
|
142 |
+
except Exception as e:
|
143 |
+
print(f"Generic error (DALL-E gen): {e}")
|
144 |
+
break # Break from loop
|
145 |
|
146 |
+
# This code block is reached if the 'for' loop completes (max retries)
|
147 |
+
# or if it 'break's due to an error other than RateLimitError (where it 'continue's)
|
148 |
+
print("DALL-E generation failed or max retries reached. Trying Pexels fallback...")
|
149 |
pexels_query_text = scene_data.get('pexels_search_query_감독', f"{scene_data.get('emotional_beat','')} {scene_data.get('setting_description','')}")
|
150 |
pexels_path = self._search_pexels_image(pexels_query_text, scene_identifier_filename)
|
151 |
+
if pexels_path:
|
152 |
+
return pexels_path
|
153 |
|
154 |
print("Pexels also failed/disabled. Using placeholder.")
|
155 |
+
return self._create_placeholder_image_content(
|
156 |
+
f"[AI/Pexels Failed] Original Prompt: {image_prompt_text[:100]}...",
|
157 |
+
scene_identifier_filename, size=self.video_frame_size
|
158 |
+
)
|
159 |
else: # AI image generation not enabled
|
160 |
+
return self._create_placeholder_image_content(
|
161 |
+
image_prompt_text, scene_identifier_filename, size=self.video_frame_size
|
162 |
+
)
|
163 |
|
164 |
+
def generate_narration_audio(self, text_to_narrate, output_filename="narration_overall.mp3"):
|
165 |
if not self.USE_ELEVENLABS or not self.elevenlabs_api_key or not text_to_narrate:
|
166 |
print("ElevenLabs disabled/no text. Skipping audio."); return None
|
167 |
audio_filepath = os.path.join(self.output_dir, output_filename)
|
168 |
try:
|
169 |
print(f"Generating ElevenLabs audio (Voice: {self.elevenlabs_voice_id}) for: {text_to_narrate[:70]}...")
|
170 |
+
# elevenlabs_set_api_key_func(self.elevenlabs_api_key) # Set key if library requires it per call
|
|
|
171 |
audio_data = elevenlabs_generate_audio(text=text_to_narrate, voice=self.elevenlabs_voice_id, model="eleven_multilingual_v2")
|
172 |
with open(audio_filepath, "wb") as f: f.write(audio_data)
|
173 |
print(f"ElevenLabs audio saved: {audio_filepath}"); return audio_filepath
|
|
|
175 |
except Exception as e: print(f"Error ElevenLabs audio: {e}")
|
176 |
return None
|
177 |
|
178 |
+
def create_video_from_images(self, image_data_list, overall_narration_path=None, output_filename="final_video.mp4", fps=24, duration_per_image=4.5):
|
|
|
|
|
179 |
if not image_data_list: return None
|
180 |
+
print(f"Creating video from {len(image_data_list)} image sets.")
|
181 |
processed_clips = []
|
182 |
+
narration_audio_clip = None
|
183 |
+
final_video_clip_obj = None
|
184 |
|
185 |
for i, data in enumerate(image_data_list):
|
186 |
img_path, scene_num, key_action = data.get('path'), data.get('scene_num', i+1), data.get('key_action', '')
|
|
|
188 |
try:
|
189 |
pil_img = Image.open(img_path);
|
190 |
if pil_img.mode != 'RGB': pil_img = pil_img.convert('RGB')
|
|
|
|
|
191 |
img_copy = pil_img.copy()
|
192 |
img_copy.thumbnail(self.video_frame_size, Image.Resampling.LANCZOS)
|
193 |
+
canvas = Image.new('RGB', self.video_frame_size, (random.randint(0,15), random.randint(0,15), random.randint(0,15)))
|
194 |
xo, yo = (self.video_frame_size[0]-img_copy.width)//2, (self.video_frame_size[1]-img_copy.height)//2
|
195 |
canvas.paste(img_copy, (xo,yo))
|
196 |
frame_np = np.array(canvas)
|
|
|
197 |
img_clip = ImageClip(frame_np).set_duration(duration_per_image)
|
198 |
+
end_scale = random.uniform(1.05, 1.12) # Ken Burns zoom
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
199 |
img_clip = img_clip.fx(vfx.resize, lambda t: 1 + (end_scale - 1) * (t / duration_per_image))
|
200 |
img_clip = img_clip.set_position('center')
|
|
|
201 |
if key_action:
|
202 |
txt_clip = TextClip(f"Scene {scene_num}\n{key_action}", fontsize=self.video_overlay_font_size,
|
203 |
color=self.video_overlay_font_color, font=self.video_overlay_font,
|
204 |
bg_color='rgba(10,10,20,0.75)', method='caption', align='West',
|
205 |
size=(self.video_frame_size[0]*0.9, None), kerning=-1, stroke_color='black', stroke_width=1
|
206 |
+
).set_duration(duration_per_image - 1.0).set_start(0.5).set_position(('center', 0.9), relative=True)
|
207 |
final_scene_clip = CompositeVideoClip([img_clip, txt_clip], size=self.video_frame_size)
|
208 |
else: final_scene_clip = img_clip
|
209 |
processed_clips.append(final_scene_clip)
|
210 |
except Exception as e: print(f"Error clip for {img_path}: {e}.")
|
211 |
|
212 |
if not processed_clips: print("No clips for video."); return None
|
213 |
+
transition = 0.8
|
|
|
214 |
final_video_clip_obj = concatenate_videoclips(processed_clips, padding=-transition, method="compose")
|
215 |
if final_video_clip_obj.duration > transition*2:
|
216 |
final_video_clip_obj = final_video_clip_obj.fx(vfx.fadein, transition).fx(vfx.fadeout, transition)
|
|
|
219 |
try:
|
220 |
narration_audio_clip = AudioFileClip(overall_narration_path)
|
221 |
final_video_clip_obj = final_video_clip_obj.set_audio(narration_audio_clip)
|
|
|
222 |
if narration_audio_clip.duration < final_video_clip_obj.duration:
|
223 |
final_video_clip_obj = final_video_clip_obj.subclip(0, narration_audio_clip.duration)
|
224 |
print("Overall narration added.")
|
|
|
226 |
|
227 |
output_path = os.path.join(self.output_dir, output_filename)
|
228 |
try:
|
229 |
+
final_video_clip_obj.write_videofile(output_path, fps=fps, codec='libx264', preset='medium', # 'medium' or 'slow'
|
230 |
+
audio_codec='aac',
|
231 |
temp_audiofile=os.path.join(self.output_dir, f'temp-audio-{os.urandom(4).hex()}.m4a'),
|
232 |
+
remove_temp=True, threads=os.cpu_count() or 2, logger='bar', bitrate="5000k")
|
233 |
print(f"Video created: {output_path}"); return output_path
|
234 |
except Exception as e: print(f"Error writing video: {e}"); return None
|
235 |
finally:
|
236 |
+
for c in processed_clips:
|
237 |
+
if hasattr(c, 'close'): c.close()
|
238 |
+
if narration_audio_clip and hasattr(narration_audio_clip, 'close'): narration_audio_clip.close()
|
239 |
+
if final_video_clip_obj and hasattr(final_video_clip_obj, 'close'): final_video_clip_obj.close()
|