Update core/visual_engine.py
Browse files- core/visual_engine.py +131 -67
core/visual_engine.py
CHANGED
@@ -1,18 +1,26 @@
|
|
1 |
# core/visual_engine.py
|
2 |
-
from PIL import Image, ImageDraw, ImageFont, ImageOps
|
3 |
# --- MONKEY PATCH FOR Image.ANTIALIAS ---
|
4 |
# This is applied at module load time.
|
|
|
5 |
try:
|
6 |
if hasattr(Image, 'Resampling') and hasattr(Image.Resampling, 'LANCZOS'): # Pillow 9+
|
7 |
if not hasattr(Image, 'ANTIALIAS'):
|
8 |
Image.ANTIALIAS = Image.Resampling.LANCZOS
|
9 |
-
print("INFO: Monkey-patched PIL.Image.ANTIALIAS with Image.Resampling.LANCZOS.")
|
10 |
elif hasattr(Image, 'LANCZOS'): # Pillow 8 used Image.LANCZOS directly
|
11 |
if not hasattr(Image, 'ANTIALIAS'):
|
12 |
-
Image.ANTIALIAS = Image.LANCZOS
|
13 |
-
print("INFO: Monkey-patched PIL.Image.ANTIALIAS with Image.LANCZOS.")
|
|
|
|
|
|
|
|
|
|
|
14 |
except AttributeError:
|
15 |
-
print("WARNING: Could not
|
|
|
|
|
16 |
# --- END MONKEY PATCH ---
|
17 |
|
18 |
from moviepy.editor import (ImageClip, concatenate_videoclips, TextClip,
|
@@ -29,60 +37,112 @@ import subprocess
|
|
29 |
import logging
|
30 |
|
31 |
logger = logging.getLogger(__name__)
|
32 |
-
logger.setLevel(logging.INFO)
|
33 |
|
34 |
ELEVENLABS_CLIENT_IMPORTED = False
|
35 |
-
ElevenLabsAPIClient = None
|
|
|
|
|
36 |
try:
|
37 |
from elevenlabs.client import ElevenLabs as ImportedElevenLabsClient
|
38 |
from elevenlabs import Voice as ImportedVoice, VoiceSettings as ImportedVoiceSettings
|
39 |
-
ElevenLabsAPIClient = ImportedElevenLabsClient
|
40 |
-
|
41 |
-
|
42 |
-
|
|
|
|
|
|
|
|
|
|
|
43 |
|
44 |
|
45 |
class VisualEngine:
|
46 |
def __init__(self, output_dir="temp_cinegen_media", default_elevenlabs_voice_id="Rachel"):
|
47 |
-
self.output_dir = output_dir
|
48 |
-
|
49 |
-
self.font_size_pil = 20; self.video_overlay_font_size = 30; self.video_overlay_font_color = 'white'; self.video_overlay_font = 'Liberation-Sans-Bold' # Or 'Arial-Bold'
|
50 |
-
try: self.font = ImageFont.truetype(self.font_path_in_container, self.font_size_pil); logger.info(f"Placeholder font loaded: {self.font_path_in_container}.")
|
51 |
-
except IOError: logger.warning(f"Placeholder font '{self.font_path_in_container}' fail. Default."); self.font = ImageFont.load_default(); self.font_size_pil = 10
|
52 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
53 |
self.openai_api_key = None; self.USE_AI_IMAGE_GENERATION = False
|
54 |
-
self.dalle_model = "dall-e-3"; self.image_size_dalle3 = "1792x1024"
|
55 |
-
self.
|
|
|
|
|
|
|
56 |
self.elevenlabs_voice_id = default_elevenlabs_voice_id
|
57 |
if VoiceSettings and ELEVENLABS_CLIENT_IMPORTED:
|
58 |
-
self.elevenlabs_voice_settings = VoiceSettings(
|
59 |
-
|
|
|
|
|
|
|
|
|
|
|
60 |
self.pexels_api_key = None; self.USE_PEXELS = False
|
61 |
logger.info("VisualEngine initialized.")
|
62 |
|
63 |
-
def set_openai_api_key(self,k):
|
|
|
|
|
|
|
64 |
def set_elevenlabs_api_key(self,api_key, voice_id_from_secret=None):
|
65 |
self.elevenlabs_api_key=api_key
|
66 |
-
if voice_id_from_secret:
|
|
|
|
|
|
|
67 |
if api_key and ELEVENLABS_CLIENT_IMPORTED and ElevenLabsAPIClient:
|
68 |
try:
|
69 |
self.elevenlabs_client = ElevenLabsAPIClient(api_key=api_key)
|
70 |
-
if self.elevenlabs_client:
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
76 |
|
77 |
-
def _get_text_dimensions(self,text_content,font_obj):
|
78 |
if not text_content: return 0,self.font_size_pil
|
79 |
try:
|
80 |
-
if hasattr(font_obj,'getbbox'):
|
81 |
-
|
82 |
-
|
83 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
84 |
|
85 |
-
def _create_placeholder_image_content(self,text_description,filename,size=None):
|
86 |
if size is None: size = self.video_frame_size
|
87 |
img=Image.new('RGB',size,color=(20,20,40));d=ImageDraw.Draw(img);padding=25;max_w=size[0]-(2*padding);lines=[];
|
88 |
if not text_description: text_description="(Placeholder: No prompt text)"
|
@@ -91,12 +151,19 @@ class VisualEngine:
|
|
91 |
test_line=current_line+word+" ";
|
92 |
if self._get_text_dimensions(test_line,self.font)[0] <= max_w: current_line=test_line
|
93 |
else:
|
94 |
-
if current_line: lines.append(current_line.strip());
|
95 |
-
|
96 |
-
if
|
|
|
|
|
|
|
97 |
_,single_line_h=self._get_text_dimensions("Ay",self.font); single_line_h = single_line_h if single_line_h > 0 else self.font_size_pil + 2
|
98 |
-
|
|
|
|
|
|
|
99 |
y_text=padding + (size[1]-(2*padding) - max_lines_to_display*(single_line_h+2))/2.0
|
|
|
100 |
for i in range(max_lines_to_display):
|
101 |
line_content=lines[i];line_w,_=self._get_text_dimensions(line_content,self.font);x_text=(size[0]-line_w)/2.0
|
102 |
d.text((x_text,y_text),line_content,font=self.font,fill=(200,200,180));y_text+=single_line_h+2
|
@@ -105,7 +172,7 @@ class VisualEngine:
|
|
105 |
try:img.save(filepath);return filepath
|
106 |
except Exception as e:logger.error(f"Saving placeholder image {filepath}: {e}", exc_info=True);return None
|
107 |
|
108 |
-
def _search_pexels_image(self, query, output_filename_base):
|
109 |
if not self.USE_PEXELS or not self.pexels_api_key: return None
|
110 |
headers = {"Authorization": self.pexels_api_key}; params = {"query": query, "per_page": 1, "orientation": "landscape", "size": "large"}
|
111 |
pexels_filename = output_filename_base.replace(".png", f"_pexels_{random.randint(1000,9999)}.jpg")
|
@@ -120,11 +187,11 @@ class VisualEngine:
|
|
120 |
img_data = Image.open(io.BytesIO(image_response.content))
|
121 |
if img_data.mode != 'RGB': img_data = img_data.convert('RGB')
|
122 |
img_data.save(filepath); logger.info(f"Pexels image saved: {filepath}"); return filepath
|
123 |
-
else: logger.info(f"No photos on Pexels for query: '{effective_query}'")
|
124 |
except Exception as e: logger.error(f"Pexels search/download for query '{query}': {e}", exc_info=True)
|
125 |
return None
|
126 |
|
127 |
-
def generate_image_visual(self, image_prompt_text, scene_data, scene_identifier_filename):
|
128 |
filepath = os.path.join(self.output_dir, scene_identifier_filename)
|
129 |
if self.USE_AI_IMAGE_GENERATION and self.openai_api_key:
|
130 |
max_retries = 2
|
@@ -155,32 +222,33 @@ class VisualEngine:
|
|
155 |
else:
|
156 |
return self._create_placeholder_image_content(image_prompt_text, scene_identifier_filename)
|
157 |
|
158 |
-
def generate_narration_audio(self, text_to_narrate, output_filename="narration_overall.mp3"):
|
159 |
if not self.USE_ELEVENLABS or not self.elevenlabs_client or not text_to_narrate:
|
160 |
-
logger.info("ElevenLabs conditions not met. Skipping audio
|
161 |
return None
|
162 |
|
163 |
audio_filepath = os.path.join(self.output_dir, output_filename)
|
164 |
try:
|
165 |
logger.info(f"Generating ElevenLabs audio (Voice ID: {self.elevenlabs_voice_id}) for: {text_to_narrate[:70]}...")
|
166 |
|
167 |
-
#
|
168 |
if hasattr(self.elevenlabs_client, 'text_to_speech') and hasattr(self.elevenlabs_client.text_to_speech, 'stream'):
|
169 |
logger.info("Using elevenlabs_client.text_to_speech.stream()")
|
170 |
audio_data_iterator = self.elevenlabs_client.text_to_speech.stream(
|
171 |
text=text_to_narrate,
|
172 |
-
voice_id=str(self.elevenlabs_voice_id),
|
173 |
-
model_id="eleven_multilingual_v2",
|
174 |
-
# voice_settings=self.elevenlabs_voice_settings # Pass VoiceSettings if
|
175 |
)
|
176 |
-
# Fallback
|
|
|
177 |
elif hasattr(self.elevenlabs_client, 'generate') and Voice and self.elevenlabs_voice_settings:
|
178 |
logger.info("Using elevenlabs_client.generate() with Voice object as fallback.")
|
179 |
voice_param = Voice(voice_id=str(self.elevenlabs_voice_id), settings=self.elevenlabs_voice_settings)
|
180 |
audio_data_iterator = self.elevenlabs_client.generate(
|
181 |
text=text_to_narrate, voice=voice_param, model="eleven_multilingual_v2")
|
182 |
else:
|
183 |
-
logger.error("No recognized audio generation method found on ElevenLabs client
|
184 |
return None
|
185 |
|
186 |
with open(audio_filepath, "wb") as f:
|
@@ -189,7 +257,7 @@ class VisualEngine:
|
|
189 |
logger.info(f"ElevenLabs audio saved: {audio_filepath}")
|
190 |
return audio_filepath
|
191 |
except AttributeError as ae:
|
192 |
-
logger.error(f"AttributeError with ElevenLabs client: {ae}. SDK method
|
193 |
except Exception as e:
|
194 |
logger.error(f"Error generating ElevenLabs audio: {e}", exc_info=True)
|
195 |
return None
|
@@ -207,7 +275,6 @@ class VisualEngine:
|
|
207 |
if pil_img.mode != 'RGB': pil_img = pil_img.convert('RGB')
|
208 |
|
209 |
img_copy = pil_img.copy()
|
210 |
-
# Using modern Resampling.LANCZOS
|
211 |
img_copy.thumbnail(self.video_frame_size, Image.Resampling.LANCZOS)
|
212 |
|
213 |
canvas = Image.new('RGB', self.video_frame_size, (random.randint(0,5), random.randint(0,5), random.randint(0,5)))
|
@@ -217,24 +284,17 @@ class VisualEngine:
|
|
217 |
|
218 |
img_clip_base = ImageClip(frame_np).set_duration(duration_per_image)
|
219 |
|
220 |
-
# Ken Burns Effect (vfx.resize)
|
221 |
-
#
|
222 |
-
|
223 |
-
# For now, we assume the monkey patch or correct versions will fix it.
|
224 |
try:
|
225 |
-
end_scale = random.uniform(1.03, 1.08)
|
226 |
-
img_clip = img_clip_base.fx(vfx.resize, lambda t: 1
|
227 |
img_clip = img_clip.set_position('center')
|
228 |
-
except AttributeError as e_alias:
|
229 |
-
if 'ANTIALIAS' in str(e_alias):
|
230 |
-
|
231 |
-
|
232 |
-
else:
|
233 |
-
raise # Re-raise other AttributeErrors
|
234 |
-
except Exception as e_fx: # Catch other errors from fx
|
235 |
-
logger.error(f"Error applying vfx.resize for {img_path}. Using base clip. Error: {e_fx}")
|
236 |
-
img_clip = img_clip_base
|
237 |
-
|
238 |
|
239 |
if key_action:
|
240 |
txt_clip = TextClip(f"Scene {scene_num}\n{key_action}", fontsize=self.video_overlay_font_size,
|
@@ -258,8 +318,12 @@ class VisualEngine:
|
|
258 |
if overall_narration_path and os.path.exists(overall_narration_path):
|
259 |
try:
|
260 |
narration_audio_clip = AudioFileClip(overall_narration_path)
|
|
|
|
|
261 |
if narration_audio_clip.duration < final_video_clip_obj.duration:
|
|
|
262 |
final_video_clip_obj = final_video_clip_obj.subclip(0, narration_audio_clip.duration)
|
|
|
263 |
final_video_clip_obj = final_video_clip_obj.set_audio(narration_audio_clip); logger.info("Overall narration added.")
|
264 |
except Exception as e: logger.error(f"Adding overall narration: {e}", exc_info=True)
|
265 |
|
|
|
1 |
# core/visual_engine.py
|
2 |
+
from PIL import Image, ImageDraw, ImageFont, ImageOps
|
3 |
# --- MONKEY PATCH FOR Image.ANTIALIAS ---
|
4 |
# This is applied at module load time.
|
5 |
+
# Attempting to make MoviePy's internal calls to Image.ANTIALIAS work with Pillow 10+
|
6 |
try:
|
7 |
if hasattr(Image, 'Resampling') and hasattr(Image.Resampling, 'LANCZOS'): # Pillow 9+
|
8 |
if not hasattr(Image, 'ANTIALIAS'):
|
9 |
Image.ANTIALIAS = Image.Resampling.LANCZOS
|
10 |
+
print("INFO: Monkey-patched PIL.Image.ANTIALIAS with Image.Resampling.LANCZOS for MoviePy compatibility.")
|
11 |
elif hasattr(Image, 'LANCZOS'): # Pillow 8 used Image.LANCZOS directly
|
12 |
if not hasattr(Image, 'ANTIALIAS'):
|
13 |
+
Image.ANTIALIAS = Image.LANCZOS # Pillow 8 had Image.LANCZOS
|
14 |
+
print("INFO: Monkey-patched PIL.Image.ANTIALIAS with Image.LANCZOS for MoviePy compatibility.")
|
15 |
+
else:
|
16 |
+
# This case means Pillow is too old, or an unexpected version.
|
17 |
+
# If ANTIALIAS is already present, no action needed.
|
18 |
+
if not hasattr(Image, 'ANTIALIAS'):
|
19 |
+
print("WARNING: Pillow version does not have common Resampling attributes or ANTIALIAS. Video effects might fail if MoviePy relies on ANTIALIAS.")
|
20 |
except AttributeError:
|
21 |
+
print("WARNING: Could not perform ANTIALIAS monkey-patch due to AttributeError (Image module might be incomplete).")
|
22 |
+
except Exception as e_mp:
|
23 |
+
print(f"WARNING: An unexpected error occurred during ANTIALIAS monkey-patch: {e_mp}")
|
24 |
# --- END MONKEY PATCH ---
|
25 |
|
26 |
from moviepy.editor import (ImageClip, concatenate_videoclips, TextClip,
|
|
|
37 |
import logging
|
38 |
|
39 |
logger = logging.getLogger(__name__)
|
40 |
+
logger.setLevel(logging.INFO) # Ensure logs from this module are visible
|
41 |
|
42 |
ELEVENLABS_CLIENT_IMPORTED = False
|
43 |
+
ElevenLabsAPIClient = None
|
44 |
+
Voice = None
|
45 |
+
VoiceSettings = None
|
46 |
try:
|
47 |
from elevenlabs.client import ElevenLabs as ImportedElevenLabsClient
|
48 |
from elevenlabs import Voice as ImportedVoice, VoiceSettings as ImportedVoiceSettings
|
49 |
+
ElevenLabsAPIClient = ImportedElevenLabsClient
|
50 |
+
Voice = ImportedVoice
|
51 |
+
VoiceSettings = ImportedVoiceSettings
|
52 |
+
ELEVENLABS_CLIENT_IMPORTED = True
|
53 |
+
logger.info("Successfully imported ElevenLabs client components (SDK v1.x.x pattern).")
|
54 |
+
except ImportError as e_eleven:
|
55 |
+
logger.warning(f"Could not import ElevenLabs client components: {e_eleven}. ElevenLabs audio will be disabled.")
|
56 |
+
except Exception as e_gen_eleven:
|
57 |
+
logger.warning(f"General error importing ElevenLabs: {e_gen_eleven}. ElevenLabs audio will be disabled.")
|
58 |
|
59 |
|
60 |
class VisualEngine:
|
61 |
def __init__(self, output_dir="temp_cinegen_media", default_elevenlabs_voice_id="Rachel"):
|
62 |
+
self.output_dir = output_dir
|
63 |
+
os.makedirs(self.output_dir, exist_ok=True)
|
|
|
|
|
|
|
64 |
|
65 |
+
self.font_filename = "arial.ttf"
|
66 |
+
self.font_path_in_container = f"/usr/local/share/fonts/truetype/mycustomfonts/{self.font_filename}"
|
67 |
+
self.font_size_pil = 20
|
68 |
+
self.video_overlay_font_size = 30
|
69 |
+
self.video_overlay_font_color = 'white'
|
70 |
+
self.video_overlay_font = 'Liberation-Sans-Bold' # More likely to be found by ImageMagick on Linux
|
71 |
+
|
72 |
+
try:
|
73 |
+
self.font = ImageFont.truetype(self.font_path_in_container, self.font_size_pil)
|
74 |
+
logger.info(f"Placeholder font loaded: {self.font_path_in_container}.")
|
75 |
+
except IOError:
|
76 |
+
logger.warning(f"Placeholder font '{self.font_path_in_container}' not found. Using default.")
|
77 |
+
self.font = ImageFont.load_default()
|
78 |
+
self.font_size_pil = 10
|
79 |
+
|
80 |
self.openai_api_key = None; self.USE_AI_IMAGE_GENERATION = False
|
81 |
+
self.dalle_model = "dall-e-3"; self.image_size_dalle3 = "1792x1024"
|
82 |
+
self.video_frame_size = (1280, 720)
|
83 |
+
|
84 |
+
self.elevenlabs_api_key = None; self.USE_ELEVENLABS = False
|
85 |
+
self.elevenlabs_client = None
|
86 |
self.elevenlabs_voice_id = default_elevenlabs_voice_id
|
87 |
if VoiceSettings and ELEVENLABS_CLIENT_IMPORTED:
|
88 |
+
self.elevenlabs_voice_settings = VoiceSettings(
|
89 |
+
stability=0.60, similarity_boost=0.80,
|
90 |
+
style=0.15, use_speaker_boost=True
|
91 |
+
)
|
92 |
+
else:
|
93 |
+
self.elevenlabs_voice_settings = None
|
94 |
+
|
95 |
self.pexels_api_key = None; self.USE_PEXELS = False
|
96 |
logger.info("VisualEngine initialized.")
|
97 |
|
98 |
+
def set_openai_api_key(self,k):
|
99 |
+
self.openai_api_key=k; self.USE_AI_IMAGE_GENERATION=bool(k)
|
100 |
+
logger.info(f"DALL-E ({self.dalle_model}) {'Ready.' if k else 'Disabled (no API key).'}")
|
101 |
+
|
102 |
def set_elevenlabs_api_key(self,api_key, voice_id_from_secret=None):
|
103 |
self.elevenlabs_api_key=api_key
|
104 |
+
if voice_id_from_secret:
|
105 |
+
self.elevenlabs_voice_id = voice_id_from_secret
|
106 |
+
logger.info(f"ElevenLabs Voice ID set from config: {self.elevenlabs_voice_id}")
|
107 |
+
|
108 |
if api_key and ELEVENLABS_CLIENT_IMPORTED and ElevenLabsAPIClient:
|
109 |
try:
|
110 |
self.elevenlabs_client = ElevenLabsAPIClient(api_key=api_key)
|
111 |
+
if self.elevenlabs_client:
|
112 |
+
self.USE_ELEVENLABS=True
|
113 |
+
logger.info(f"ElevenLabs Client Ready (Using Voice ID: {self.elevenlabs_voice_id}).")
|
114 |
+
else:
|
115 |
+
self.USE_ELEVENLABS=False; logger.warning("ElevenLabs client is None after initialization attempt.")
|
116 |
+
except Exception as e:
|
117 |
+
logger.error(f"Error initializing ElevenLabs client: {e}. ElevenLabs Disabled.", exc_info=True);
|
118 |
+
self.USE_ELEVENLABS=False; self.elevenlabs_client = None
|
119 |
+
else:
|
120 |
+
self.USE_ELEVENLABS=False; self.elevenlabs_client = None
|
121 |
+
if not (ELEVENLABS_CLIENT_IMPORTED and ElevenLabsAPIClient):
|
122 |
+
pass # Already logged at import time if client class itself failed to import
|
123 |
+
else: # Client class imported, but API key was not provided
|
124 |
+
logger.info("ElevenLabs API Key not provided. ElevenLabs Disabled.")
|
125 |
+
|
126 |
+
def set_pexels_api_key(self,k):
|
127 |
+
self.pexels_api_key=k; self.USE_PEXELS=bool(k)
|
128 |
+
logger.info(f"Pexels Search {'Ready.' if k else 'Disabled (no API key).'}")
|
129 |
|
130 |
+
def _get_text_dimensions(self,text_content,font_obj):
|
131 |
if not text_content: return 0,self.font_size_pil
|
132 |
try:
|
133 |
+
if hasattr(font_obj,'getbbox'):
|
134 |
+
bbox=font_obj.getbbox(text_content);w=bbox[2]-bbox[0];h=bbox[3]-bbox[1]
|
135 |
+
return w, h if h > 0 else self.font_size_pil
|
136 |
+
elif hasattr(font_obj,'getsize'):
|
137 |
+
w,h=font_obj.getsize(text_content)
|
138 |
+
return w, h if h > 0 else self.font_size_pil
|
139 |
+
else:
|
140 |
+
return int(len(text_content)*self.font_size_pil*0.6),int(self.font_size_pil*1.2 if self.font_size_pil*1.2>0 else self.font_size_pil)
|
141 |
+
except Exception as e:
|
142 |
+
logger.warning(f"Error in _get_text_dimensions for '{text_content[:20]}...': {e}")
|
143 |
+
return int(len(text_content)*self.font_size_pil*0.6),int(self.font_size_pil*1.2) # Fallback
|
144 |
|
145 |
+
def _create_placeholder_image_content(self,text_description,filename,size=None):
|
146 |
if size is None: size = self.video_frame_size
|
147 |
img=Image.new('RGB',size,color=(20,20,40));d=ImageDraw.Draw(img);padding=25;max_w=size[0]-(2*padding);lines=[];
|
148 |
if not text_description: text_description="(Placeholder: No prompt text)"
|
|
|
151 |
test_line=current_line+word+" ";
|
152 |
if self._get_text_dimensions(test_line,self.font)[0] <= max_w: current_line=test_line
|
153 |
else:
|
154 |
+
if current_line: lines.append(current_line.strip());
|
155 |
+
current_line=word+" "
|
156 |
+
if current_line.strip(): lines.append(current_line.strip()) # Add last line
|
157 |
+
if not lines and text_description: lines.append(text_description[:max_w//int(self.font_size_pil*0.6 +1)]+"..." if text_description else "(Text too long)") # Handle single very long word
|
158 |
+
elif not lines: lines.append("(Placeholder Text Error)")
|
159 |
+
|
160 |
_,single_line_h=self._get_text_dimensions("Ay",self.font); single_line_h = single_line_h if single_line_h > 0 else self.font_size_pil + 2
|
161 |
+
|
162 |
+
max_lines_to_display=min(len(lines),(size[1]-(2*padding))//(single_line_h+2)) if single_line_h > 0 else 1
|
163 |
+
if max_lines_to_display <=0: max_lines_to_display = 1 # Ensure at least one line can be attempted
|
164 |
+
|
165 |
y_text=padding + (size[1]-(2*padding) - max_lines_to_display*(single_line_h+2))/2.0
|
166 |
+
|
167 |
for i in range(max_lines_to_display):
|
168 |
line_content=lines[i];line_w,_=self._get_text_dimensions(line_content,self.font);x_text=(size[0]-line_w)/2.0
|
169 |
d.text((x_text,y_text),line_content,font=self.font,fill=(200,200,180));y_text+=single_line_h+2
|
|
|
172 |
try:img.save(filepath);return filepath
|
173 |
except Exception as e:logger.error(f"Saving placeholder image {filepath}: {e}", exc_info=True);return None
|
174 |
|
175 |
+
def _search_pexels_image(self, query, output_filename_base):
|
176 |
if not self.USE_PEXELS or not self.pexels_api_key: return None
|
177 |
headers = {"Authorization": self.pexels_api_key}; params = {"query": query, "per_page": 1, "orientation": "landscape", "size": "large"}
|
178 |
pexels_filename = output_filename_base.replace(".png", f"_pexels_{random.randint(1000,9999)}.jpg")
|
|
|
187 |
img_data = Image.open(io.BytesIO(image_response.content))
|
188 |
if img_data.mode != 'RGB': img_data = img_data.convert('RGB')
|
189 |
img_data.save(filepath); logger.info(f"Pexels image saved: {filepath}"); return filepath
|
190 |
+
else: logger.info(f"No photos found on Pexels for query: '{effective_query}'")
|
191 |
except Exception as e: logger.error(f"Pexels search/download for query '{query}': {e}", exc_info=True)
|
192 |
return None
|
193 |
|
194 |
+
def generate_image_visual(self, image_prompt_text, scene_data, scene_identifier_filename):
|
195 |
filepath = os.path.join(self.output_dir, scene_identifier_filename)
|
196 |
if self.USE_AI_IMAGE_GENERATION and self.openai_api_key:
|
197 |
max_retries = 2
|
|
|
222 |
else:
|
223 |
return self._create_placeholder_image_content(image_prompt_text, scene_identifier_filename)
|
224 |
|
225 |
+
def generate_narration_audio(self, text_to_narrate, output_filename="narration_overall.mp3"):
|
226 |
if not self.USE_ELEVENLABS or not self.elevenlabs_client or not text_to_narrate:
|
227 |
+
logger.info("ElevenLabs conditions not met (API key, client init, or text). Skipping audio.")
|
228 |
return None
|
229 |
|
230 |
audio_filepath = os.path.join(self.output_dir, output_filename)
|
231 |
try:
|
232 |
logger.info(f"Generating ElevenLabs audio (Voice ID: {self.elevenlabs_voice_id}) for: {text_to_narrate[:70]}...")
|
233 |
|
234 |
+
# Using client.text_to_speech.stream() for newer SDKs (e.g., elevenlabs >= 1.0)
|
235 |
if hasattr(self.elevenlabs_client, 'text_to_speech') and hasattr(self.elevenlabs_client.text_to_speech, 'stream'):
|
236 |
logger.info("Using elevenlabs_client.text_to_speech.stream()")
|
237 |
audio_data_iterator = self.elevenlabs_client.text_to_speech.stream(
|
238 |
text=text_to_narrate,
|
239 |
+
voice_id=str(self.elevenlabs_voice_id),
|
240 |
+
model_id="eleven_multilingual_v2",
|
241 |
+
# voice_settings=self.elevenlabs_voice_settings # Pass VoiceSettings object if supported by stream
|
242 |
)
|
243 |
+
# Fallback to direct .generate() if text_to_speech.stream isn't there
|
244 |
+
# AND Voice/VoiceSettings were successfully imported
|
245 |
elif hasattr(self.elevenlabs_client, 'generate') and Voice and self.elevenlabs_voice_settings:
|
246 |
logger.info("Using elevenlabs_client.generate() with Voice object as fallback.")
|
247 |
voice_param = Voice(voice_id=str(self.elevenlabs_voice_id), settings=self.elevenlabs_voice_settings)
|
248 |
audio_data_iterator = self.elevenlabs_client.generate(
|
249 |
text=text_to_narrate, voice=voice_param, model="eleven_multilingual_v2")
|
250 |
else:
|
251 |
+
logger.error("No recognized audio generation method found on ElevenLabs client or Voice/VoiceSettings not imported.")
|
252 |
return None
|
253 |
|
254 |
with open(audio_filepath, "wb") as f:
|
|
|
257 |
logger.info(f"ElevenLabs audio saved: {audio_filepath}")
|
258 |
return audio_filepath
|
259 |
except AttributeError as ae:
|
260 |
+
logger.error(f"AttributeError with ElevenLabs client: {ae}. SDK method might be different.", exc_info=True)
|
261 |
except Exception as e:
|
262 |
logger.error(f"Error generating ElevenLabs audio: {e}", exc_info=True)
|
263 |
return None
|
|
|
275 |
if pil_img.mode != 'RGB': pil_img = pil_img.convert('RGB')
|
276 |
|
277 |
img_copy = pil_img.copy()
|
|
|
278 |
img_copy.thumbnail(self.video_frame_size, Image.Resampling.LANCZOS)
|
279 |
|
280 |
canvas = Image.new('RGB', self.video_frame_size, (random.randint(0,5), random.randint(0,5), random.randint(0,5)))
|
|
|
284 |
|
285 |
img_clip_base = ImageClip(frame_np).set_duration(duration_per_image)
|
286 |
|
287 |
+
# Ken Burns Effect (vfx.resize)
|
288 |
+
# The monkey patch at the top of this file should address Image.ANTIALIAS
|
289 |
+
img_clip = img_clip_base # Start with base
|
|
|
290 |
try:
|
291 |
+
end_scale = random.uniform(1.03, 1.08);
|
292 |
+
img_clip = img_clip_base.fx(vfx.resize, lambda t: 1+(end_scale-1)*(t/duration_per_image))
|
293 |
img_clip = img_clip.set_position('center')
|
294 |
+
except AttributeError as e_alias:
|
295 |
+
if 'ANTIALIAS' in str(e_alias): logger.error(f"ANTIALIAS error in vfx.resize for {img_path}. Ken Burns disabled for this clip. Error: {e_alias}")
|
296 |
+
else: raise # Re-raise other AttributeErrors
|
297 |
+
except Exception as e_fx: logger.error(f"Error in vfx.resize for {img_path}: {e_fx}. Ken Burns disabled for this clip.")
|
|
|
|
|
|
|
|
|
|
|
|
|
298 |
|
299 |
if key_action:
|
300 |
txt_clip = TextClip(f"Scene {scene_num}\n{key_action}", fontsize=self.video_overlay_font_size,
|
|
|
318 |
if overall_narration_path and os.path.exists(overall_narration_path):
|
319 |
try:
|
320 |
narration_audio_clip = AudioFileClip(overall_narration_path)
|
321 |
+
# Adjust video duration to match audio if audio is shorter.
|
322 |
+
# If audio is longer, MoviePy's set_audio will truncate audio to video length.
|
323 |
if narration_audio_clip.duration < final_video_clip_obj.duration:
|
324 |
+
logger.info(f"Narration shorter than visuals. Trimming video to {narration_audio_clip.duration}s.")
|
325 |
final_video_clip_obj = final_video_clip_obj.subclip(0, narration_audio_clip.duration)
|
326 |
+
|
327 |
final_video_clip_obj = final_video_clip_obj.set_audio(narration_audio_clip); logger.info("Overall narration added.")
|
328 |
except Exception as e: logger.error(f"Adding overall narration: {e}", exc_info=True)
|
329 |
|