Update core/visual_engine.py
Browse files- core/visual_engine.py +82 -73
core/visual_engine.py
CHANGED
@@ -1,9 +1,9 @@
|
|
1 |
# core/visual_engine.py
|
2 |
-
from PIL import Image, ImageDraw, ImageFont
|
3 |
from moviepy.editor import (ImageClip, concatenate_videoclips, TextClip,
|
4 |
-
CompositeVideoClip
|
5 |
-
import moviepy.video.fx.all as vfx #
|
6 |
-
import numpy as np
|
7 |
import os
|
8 |
import openai
|
9 |
import requests
|
@@ -16,12 +16,12 @@ class VisualEngine:
|
|
16 |
|
17 |
self.font_filename = "arial.ttf"
|
18 |
self.font_path_in_container = f"/usr/local/share/fonts/truetype/mycustomfonts/{self.font_filename}"
|
19 |
-
self.font_size_pil = 24
|
20 |
-
self.video_overlay_font_size = 36
|
21 |
self.video_overlay_font_color = 'white'
|
22 |
-
# For video overlays,
|
23 |
-
#
|
24 |
-
self.video_overlay_font = 'Arial'
|
25 |
|
26 |
try:
|
27 |
self.font = ImageFont.truetype(self.font_path_in_container, self.font_size_pil)
|
@@ -34,16 +34,14 @@ class VisualEngine:
|
|
34 |
self.openai_api_key = None
|
35 |
self.USE_AI_IMAGE_GENERATION = False
|
36 |
self.dalle_model = "dall-e-3"
|
37 |
-
self.image_size = "1024x1024"
|
38 |
-
#
|
39 |
-
|
40 |
-
|
41 |
|
42 |
def set_openai_api_key(self, api_key):
|
43 |
-
# ... (remains the same) ...
|
44 |
if api_key:
|
45 |
self.openai_api_key = api_key
|
46 |
-
# openai.api_key = self.openai_api_key # Older versions. New client takes key per call.
|
47 |
self.USE_AI_IMAGE_GENERATION = True
|
48 |
print("OpenAI API key set. AI Image Generation Enabled with DALL-E.")
|
49 |
else:
|
@@ -51,16 +49,15 @@ class VisualEngine:
|
|
51 |
print("OpenAI API key not provided. AI Image Generation Disabled. Using placeholders.")
|
52 |
|
53 |
def _get_text_dimensions(self, text_content, font_obj):
|
54 |
-
# ... (remains the same) ...
|
55 |
if text_content == "" or text_content is None:
|
56 |
return 0, self.font_size_pil
|
57 |
try:
|
58 |
-
if hasattr(font_obj, 'getbbox'):
|
59 |
bbox = font_obj.getbbox(text_content)
|
60 |
width = bbox[2] - bbox[0]
|
61 |
height = bbox[3] - bbox[1]
|
62 |
return width, height if height > 0 else self.font_size_pil
|
63 |
-
elif hasattr(font_obj, 'getsize'):
|
64 |
width, height = font_obj.getsize(text_content)
|
65 |
return width, height if height > 0 else self.font_size_pil
|
66 |
else:
|
@@ -73,8 +70,7 @@ class VisualEngine:
|
|
73 |
height_estimate = self.font_size_pil * 1.2
|
74 |
return int(len(text_content) * avg_char_width), int(height_estimate if height_estimate > 0 else self.font_size_pil)
|
75 |
|
76 |
-
def _create_placeholder_image_content(self, text_description, filename, size=(1024, 576)):
|
77 |
-
# ... (remains the same) ...
|
78 |
img = Image.new('RGB', size, color=(30, 30, 60))
|
79 |
draw = ImageDraw.Draw(img)
|
80 |
padding = 30
|
@@ -122,7 +118,6 @@ class VisualEngine:
|
|
122 |
return filepath
|
123 |
|
124 |
def generate_image_visual(self, image_prompt_text, scene_identifier_filename):
|
125 |
-
# ... (DALL-E logic remains the same, including fallback to _create_placeholder_image_content) ...
|
126 |
filepath = os.path.join(self.output_dir, scene_identifier_filename)
|
127 |
if self.USE_AI_IMAGE_GENERATION and self.openai_api_key:
|
128 |
try:
|
@@ -130,19 +125,21 @@ class VisualEngine:
|
|
130 |
client = openai.OpenAI(api_key=self.openai_api_key)
|
131 |
response = client.images.generate(
|
132 |
model=self.dalle_model, prompt=image_prompt_text, n=1,
|
133 |
-
size=self.image_size, quality="standard", response_format="url"
|
|
|
134 |
)
|
135 |
image_url = response.data[0].url
|
136 |
-
revised_prompt_dalle3 = response.data[0]
|
137 |
if revised_prompt_dalle3: print(f"DALL-E 3 revised prompt: {revised_prompt_dalle3[:150]}...")
|
138 |
-
|
|
|
139 |
image_response.raise_for_status()
|
140 |
-
img_data = Image.open(io.BytesIO(image_response.content))
|
141 |
|
142 |
-
|
143 |
-
if img_data.mode == 'RGBA':
|
144 |
img_data = img_data.convert('RGB')
|
145 |
|
|
|
146 |
img_data.save(filepath)
|
147 |
print(f"AI Image (DALL-E) saved: {filepath}")
|
148 |
return filepath
|
@@ -152,23 +149,21 @@ class VisualEngine:
|
|
152 |
print(f"Requests Error downloading DALL-E image: {e}")
|
153 |
except Exception as e:
|
154 |
print(f"Generic error during DALL-E image generation: {e}")
|
|
|
155 |
print("Falling back to placeholder image due to DALL-E error.")
|
|
|
156 |
return self._create_placeholder_image_content(
|
157 |
f"[DALL-E Failed] Prompt: {image_prompt_text[:150]}...",
|
158 |
-
scene_identifier_filename, size=self.video_frame_size
|
159 |
)
|
160 |
-
else:
|
|
|
|
|
161 |
return self._create_placeholder_image_content(
|
162 |
image_prompt_text, scene_identifier_filename, size=self.video_frame_size
|
163 |
)
|
164 |
|
165 |
-
|
166 |
def create_video_from_images(self, image_data_list, output_filename="final_video.mp4", fps=24, duration_per_image=3):
|
167 |
-
"""
|
168 |
-
Creates a video from a list of image file paths and associated text.
|
169 |
-
image_data_list: List of dictionaries, each like:
|
170 |
-
{'path': 'path/to/image.png', 'scene_num': 1, 'key_action': 'Some action'}
|
171 |
-
"""
|
172 |
if not image_data_list:
|
173 |
print("No image data provided to create video.")
|
174 |
return None
|
@@ -185,44 +180,55 @@ class VisualEngine:
|
|
185 |
print(f"Image path invalid or not found: {img_path}. Skipping for video.")
|
186 |
continue
|
187 |
try:
|
188 |
-
|
189 |
-
pil_image = Image.open(img_path)
|
190 |
-
pil_image.thumbnail(self.video_frame_size, Image.Resampling.LANCZOS) # Resize in place
|
191 |
-
|
192 |
-
# Create a background matching video_frame_size
|
193 |
-
background = Image.new('RGB', self.video_frame_size, (0,0,0)) # Black background
|
194 |
-
# Paste the thumbnail onto the center of the background
|
195 |
-
paste_x = (self.video_frame_size[0] - pil_image.width) // 2
|
196 |
-
paste_y = (self.video_frame_size[1] - pil_image.height) // 2
|
197 |
-
background.paste(pil_image, (paste_x, paste_y))
|
198 |
|
199 |
-
|
200 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
201 |
img_clip = ImageClip(frame_np).set_duration(duration_per_image)
|
202 |
|
203 |
-
#
|
204 |
-
|
205 |
-
|
206 |
-
img_clip = img_clip.
|
207 |
-
|
208 |
-
|
209 |
-
|
210 |
-
|
211 |
-
#
|
212 |
-
|
213 |
-
|
214 |
-
|
215 |
-
|
216 |
-
|
217 |
-
|
218 |
-
|
219 |
-
|
220 |
-
|
221 |
-
|
|
|
|
|
|
|
|
|
|
|
222 |
|
223 |
-
txt_clip = txt_clip.set_position(('center', 0.
|
224 |
|
225 |
-
# Composite the image and text
|
226 |
video_with_text_overlay = CompositeVideoClip([img_clip, txt_clip], size=self.video_frame_size)
|
227 |
processed_clips.append(video_with_text_overlay)
|
228 |
|
@@ -233,9 +239,11 @@ class VisualEngine:
|
|
233 |
print("No clips could be processed for the video.")
|
234 |
return None
|
235 |
|
236 |
-
# Concatenate with crossfade
|
237 |
-
final_video_clip = concatenate_videoclips(processed_clips, padding=-0.5, method="compose")
|
238 |
-
#
|
|
|
|
|
239 |
|
240 |
output_path = os.path.join(self.output_dir, output_filename)
|
241 |
print(f"Writing final video to: {output_path}")
|
@@ -250,6 +258,7 @@ class VisualEngine:
|
|
250 |
except Exception as e:
|
251 |
print(f"Error writing final video file: {e}")
|
252 |
return None
|
253 |
-
finally:
|
254 |
-
for
|
|
|
255 |
if hasattr(final_video_clip, 'close'): final_video_clip.close()
|
|
|
1 |
# core/visual_engine.py
|
2 |
+
from PIL import Image, ImageDraw, ImageFont # Pillow should be >= 10.0.0
|
3 |
from moviepy.editor import (ImageClip, concatenate_videoclips, TextClip,
|
4 |
+
CompositeVideoClip)
|
5 |
+
import moviepy.video.fx.all as vfx # For effects like resize, fadein, fadeout
|
6 |
+
import numpy as np
|
7 |
import os
|
8 |
import openai
|
9 |
import requests
|
|
|
16 |
|
17 |
self.font_filename = "arial.ttf"
|
18 |
self.font_path_in_container = f"/usr/local/share/fonts/truetype/mycustomfonts/{self.font_filename}"
|
19 |
+
self.font_size_pil = 24
|
20 |
+
self.video_overlay_font_size = 36
|
21 |
self.video_overlay_font_color = 'white'
|
22 |
+
# For video overlays, TextClip will use ImageMagick. 'Arial' is a common system font name.
|
23 |
+
# If issues, use self.font_path_in_container (if ImageMagick can access it via moviepy)
|
24 |
+
self.video_overlay_font = 'Arial'
|
25 |
|
26 |
try:
|
27 |
self.font = ImageFont.truetype(self.font_path_in_container, self.font_size_pil)
|
|
|
34 |
self.openai_api_key = None
|
35 |
self.USE_AI_IMAGE_GENERATION = False
|
36 |
self.dalle_model = "dall-e-3"
|
37 |
+
self.image_size = "1024x1024" # DALL-E 3 output size
|
38 |
+
# Target video frame size (e.g., 16:9 aspect ratio)
|
39 |
+
# DALL-E 3 images (1024x1024) will be letter/pillar-boxed to fit this.
|
40 |
+
self.video_frame_size = (1280, 720)
|
41 |
|
42 |
def set_openai_api_key(self, api_key):
|
|
|
43 |
if api_key:
|
44 |
self.openai_api_key = api_key
|
|
|
45 |
self.USE_AI_IMAGE_GENERATION = True
|
46 |
print("OpenAI API key set. AI Image Generation Enabled with DALL-E.")
|
47 |
else:
|
|
|
49 |
print("OpenAI API key not provided. AI Image Generation Disabled. Using placeholders.")
|
50 |
|
51 |
def _get_text_dimensions(self, text_content, font_obj):
|
|
|
52 |
if text_content == "" or text_content is None:
|
53 |
return 0, self.font_size_pil
|
54 |
try:
|
55 |
+
if hasattr(font_obj, 'getbbox'): # Pillow >= 8.0.0
|
56 |
bbox = font_obj.getbbox(text_content)
|
57 |
width = bbox[2] - bbox[0]
|
58 |
height = bbox[3] - bbox[1]
|
59 |
return width, height if height > 0 else self.font_size_pil
|
60 |
+
elif hasattr(font_obj, 'getsize'): # Older Pillow
|
61 |
width, height = font_obj.getsize(text_content)
|
62 |
return width, height if height > 0 else self.font_size_pil
|
63 |
else:
|
|
|
70 |
height_estimate = self.font_size_pil * 1.2
|
71 |
return int(len(text_content) * avg_char_width), int(height_estimate if height_estimate > 0 else self.font_size_pil)
|
72 |
|
73 |
+
def _create_placeholder_image_content(self, text_description, filename, size=(1024, 576)): # Default placeholder size
|
|
|
74 |
img = Image.new('RGB', size, color=(30, 30, 60))
|
75 |
draw = ImageDraw.Draw(img)
|
76 |
padding = 30
|
|
|
118 |
return filepath
|
119 |
|
120 |
def generate_image_visual(self, image_prompt_text, scene_identifier_filename):
|
|
|
121 |
filepath = os.path.join(self.output_dir, scene_identifier_filename)
|
122 |
if self.USE_AI_IMAGE_GENERATION and self.openai_api_key:
|
123 |
try:
|
|
|
125 |
client = openai.OpenAI(api_key=self.openai_api_key)
|
126 |
response = client.images.generate(
|
127 |
model=self.dalle_model, prompt=image_prompt_text, n=1,
|
128 |
+
size=self.image_size, quality="standard", response_format="url"
|
129 |
+
# style="vivid" # or "natural" for DALL-E 3, optional
|
130 |
)
|
131 |
image_url = response.data[0].url
|
132 |
+
revised_prompt_dalle3 = getattr(response.data[0], 'revised_prompt', None) # Safely access
|
133 |
if revised_prompt_dalle3: print(f"DALL-E 3 revised prompt: {revised_prompt_dalle3[:150]}...")
|
134 |
+
|
135 |
+
image_response = requests.get(image_url, timeout=60)
|
136 |
image_response.raise_for_status()
|
|
|
137 |
|
138 |
+
img_data = Image.open(io.BytesIO(image_response.content))
|
139 |
+
if img_data.mode == 'RGBA': # Ensure RGB for consistency, PNG can be RGBA
|
140 |
img_data = img_data.convert('RGB')
|
141 |
|
142 |
+
# Save the AI generated image (typically 1024x1024 from DALL-E)
|
143 |
img_data.save(filepath)
|
144 |
print(f"AI Image (DALL-E) saved: {filepath}")
|
145 |
return filepath
|
|
|
149 |
print(f"Requests Error downloading DALL-E image: {e}")
|
150 |
except Exception as e:
|
151 |
print(f"Generic error during DALL-E image generation: {e}")
|
152 |
+
|
153 |
print("Falling back to placeholder image due to DALL-E error.")
|
154 |
+
# Fallback uses video_frame_size to match what video expects if AI fails
|
155 |
return self._create_placeholder_image_content(
|
156 |
f"[DALL-E Failed] Prompt: {image_prompt_text[:150]}...",
|
157 |
+
scene_identifier_filename, size=self.video_frame_size
|
158 |
)
|
159 |
+
else: # AI not enabled or key missing
|
160 |
+
# print(f"AI image generation not enabled/ready. Creating placeholder.")
|
161 |
+
# Placeholder also uses video_frame_size for consistency in video pipeline
|
162 |
return self._create_placeholder_image_content(
|
163 |
image_prompt_text, scene_identifier_filename, size=self.video_frame_size
|
164 |
)
|
165 |
|
|
|
166 |
def create_video_from_images(self, image_data_list, output_filename="final_video.mp4", fps=24, duration_per_image=3):
|
|
|
|
|
|
|
|
|
|
|
167 |
if not image_data_list:
|
168 |
print("No image data provided to create video.")
|
169 |
return None
|
|
|
180 |
print(f"Image path invalid or not found: {img_path}. Skipping for video.")
|
181 |
continue
|
182 |
try:
|
183 |
+
pil_image_original = Image.open(img_path)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
184 |
|
185 |
+
if pil_image_original.mode != 'RGB': # Ensure RGB for video
|
186 |
+
pil_image_original = pil_image_original.convert('RGB')
|
187 |
+
|
188 |
+
# Create a copy to resize (thumbnail modifies in-place)
|
189 |
+
pil_image_for_frame = pil_image_original.copy()
|
190 |
+
# Resize image to fit within self.video_frame_size, maintaining aspect ratio
|
191 |
+
pil_image_for_frame.thumbnail(self.video_frame_size, Image.Resampling.LANCZOS)
|
192 |
+
|
193 |
+
# Create a background canvas of the exact video_frame_size (e.g., 1280x720)
|
194 |
+
# This will letterbox/pillarbox the image if its aspect ratio differs from video_frame_size
|
195 |
+
background_canvas = Image.new('RGB', self.video_frame_size, (0,0,0)) # Black background
|
196 |
+
paste_x = (self.video_frame_size[0] - pil_image_for_frame.width) // 2
|
197 |
+
paste_y = (self.video_frame_size[1] - pil_image_for_frame.height) // 2
|
198 |
+
background_canvas.paste(pil_image_for_frame, (paste_x, paste_y))
|
199 |
+
|
200 |
+
frame_np = np.array(background_canvas) # Convert final PIL image to numpy array
|
201 |
+
|
202 |
+
# Base image clip
|
203 |
img_clip = ImageClip(frame_np).set_duration(duration_per_image)
|
204 |
|
205 |
+
# Ken Burns Effect (Simple Zoom In)
|
206 |
+
end_scale = 1.08 # Zoom to 108% of original size by the end
|
207 |
+
img_clip = img_clip.fx(vfx.resize, lambda t: 1 + (end_scale - 1) * (t / duration_per_image))
|
208 |
+
img_clip = img_clip.set_position('center') # Keep centered during zoom
|
209 |
+
|
210 |
+
# Text Overlay
|
211 |
+
overlay_text = f"Scene {scene_num}: {key_action}"
|
212 |
+
# Ensure font path is used if 'Arial' isn't found by ImageMagick/MoviePy
|
213 |
+
# For TextClip, moviepy relies on ImageMagick which has its own font discovery.
|
214 |
+
# Using a common font name like 'Arial' is often okay if mscorefonts are installed.
|
215 |
+
# If not, you might need to point to self.font_path_in_container
|
216 |
+
# Check if ImageMagick is installed in Docker, moviepy might need it for TextClip.
|
217 |
+
# `apt-get install imagemagick` in Dockerfile if TextClip has issues.
|
218 |
+
txt_clip = TextClip(
|
219 |
+
overlay_text,
|
220 |
+
fontsize=self.video_overlay_font_size,
|
221 |
+
color=self.video_overlay_font_color,
|
222 |
+
font=self.video_overlay_font, # Or self.font_path_in_container
|
223 |
+
bg_color='rgba(0,0,0,0.6)',
|
224 |
+
size=(self.video_frame_size[0] * 0.9, None), # Width 90% of video, height auto
|
225 |
+
method='caption',
|
226 |
+
align='West',
|
227 |
+
kerning=-1
|
228 |
+
).set_duration(duration_per_image - 0.5).set_start(0.25) # Start after 0.25s, end 0.25s before clip end
|
229 |
|
230 |
+
txt_clip = txt_clip.set_position(('center', 0.88), relative=True) # Position near bottom
|
231 |
|
|
|
232 |
video_with_text_overlay = CompositeVideoClip([img_clip, txt_clip], size=self.video_frame_size)
|
233 |
processed_clips.append(video_with_text_overlay)
|
234 |
|
|
|
239 |
print("No clips could be processed for the video.")
|
240 |
return None
|
241 |
|
242 |
+
# Concatenate with crossfade (0.5s)
|
243 |
+
final_video_clip = concatenate_videoclips(processed_clips, padding=-0.5, method="compose")
|
244 |
+
# Add fade in/out for the whole video
|
245 |
+
if final_video_clip.duration > 1: # Ensure video is long enough for fades
|
246 |
+
final_video_clip = final_video_clip.fx(vfx.fadein, 0.5).fx(vfx.fadeout, 0.5)
|
247 |
|
248 |
output_path = os.path.join(self.output_dir, output_filename)
|
249 |
print(f"Writing final video to: {output_path}")
|
|
|
258 |
except Exception as e:
|
259 |
print(f"Error writing final video file: {e}")
|
260 |
return None
|
261 |
+
finally:
|
262 |
+
for clip_item in processed_clips:
|
263 |
+
if hasattr(clip_item, 'close'): clip_item.close()
|
264 |
if hasattr(final_video_clip, 'close'): final_video_clip.close()
|