mgbam commited on
Commit
9d84ba9
·
verified ·
1 Parent(s): 5876552

Update core/visual_engine.py

Browse files
Files changed (1) hide show
  1. core/visual_engine.py +133 -187
core/visual_engine.py CHANGED
@@ -1,27 +1,26 @@
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
10
  import io
 
11
 
12
  class VisualEngine:
13
- def __init__(self, output_dir="temp_generated_media"):
14
  self.output_dir = output_dir
15
  os.makedirs(self.output_dir, exist_ok=True)
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)
@@ -29,236 +28,183 @@ class VisualEngine:
29
  except IOError:
30
  print(f"Warning: Could not load font from '{self.font_path_in_container}'. Placeholders will use default font.")
31
  self.font = ImageFont.load_default()
32
- self.font_size_pil = 11
33
 
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:
48
  self.USE_AI_IMAGE_GENERATION = False
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:
64
- avg_char_width = self.font_size_pil * 0.6
65
- height_estimate = self.font_size_pil * 1.2
66
- return int(len(text_content) * avg_char_width), int(height_estimate if height_estimate > 0 else self.font_size_pil)
67
- except Exception as e:
68
- print(f"Warning: Error getting text dimensions for '{text_content}': {e}. Using estimates.")
69
- avg_char_width = self.font_size_pil * 0.6
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
77
  max_text_width = size[0] - (2 * padding)
78
  lines = []
79
- if not text_description: text_description = "(No description provided for placeholder)"
 
80
  words = text_description.split()
81
  current_line = ""
82
  for word in words:
83
- test_line_candidate = current_line + word + " "
84
- line_width, _ = self._get_text_dimensions(test_line_candidate.strip(), self.font)
85
- if line_width <= max_text_width and current_line != "": current_line = test_line_candidate
86
- elif line_width <= max_text_width and current_line == "": current_line = test_line_candidate
87
- elif current_line != "":
88
- lines.append(current_line.strip())
89
- current_line = word + " "
90
  else:
91
- temp_word = word
92
- while self._get_text_dimensions(temp_word, self.font)[0] > max_text_width and len(temp_word) > 0: temp_word = temp_word[:-1]
93
- lines.append(temp_word)
94
- current_line = ""
95
- if current_line.strip(): lines.append(current_line.strip())
96
- if not lines: lines.append("(Text error in placeholder)")
97
- _, single_line_height = self._get_text_dimensions("Tg", self.font)
98
- if single_line_height == 0: single_line_height = self.font_size_pil
99
- line_spacing_factor = 1.3
100
- estimated_line_block_height = len(lines) * single_line_height * line_spacing_factor
101
- y_text = (size[1] - estimated_line_block_height) / 2.0
102
- if y_text < padding: y_text = float(padding)
103
- for line_idx, line in enumerate(lines):
104
- if line_idx >= 7 and len(lines) > 8:
105
- draw.text(xy=(float(padding), y_text), text="...", fill=(200, 200, 130), font=self.font)
106
- break
107
  line_width, _ = self._get_text_dimensions(line, self.font)
108
  x_text = (size[0] - line_width) / 2.0
109
- if x_text < padding: x_text = float(padding)
110
- draw.text(xy=(x_text, y_text), text=line, fill=(220, 220, 150), font=self.font)
111
- y_text += single_line_height * line_spacing_factor
 
 
112
  filepath = os.path.join(self.output_dir, filename)
113
- try:
114
- img.save(filepath)
115
- except Exception as e:
116
- print(f"Error saving placeholder image {filepath}: {e}")
117
- return None
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:
124
- print(f"Generating DALL-E ({self.dalle_model}) image for: {image_prompt_text[:100]}...")
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
146
- except openai.APIError as e:
147
- print(f"OpenAI API Error: {e}")
148
- except requests.exceptions.RequestException as e:
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
170
-
171
- print(f"Attempting to create video from {len(image_data_list)} images.")
172
  processed_clips = []
173
 
174
  for i, data in enumerate(image_data_list):
175
- img_path = data.get('path')
176
- scene_num = data.get('scene_num', i + 1)
177
- key_action = data.get('key_action', '')
178
-
179
  if not (img_path and os.path.exists(img_path)):
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
-
235
- except Exception as e_clip:
236
- print(f"Error processing image/creating clip for {img_path}: {e_clip}. Skipping.")
237
 
238
- if not processed_clips:
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}")
250
  try:
251
- final_video_clip.write_videofile(
252
- output_path, fps=fps, codec='libx264', audio_codec='aac',
253
- temp_audiofile=os.path.join(self.output_dir, f'temp-audio-{os.urandom(4).hex()}.m4a'),
254
- remove_temp=True, threads=os.cpu_count() or 2, logger='bar'
255
- )
256
- print(f"Video successfully created: {output_path}")
257
- return 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()
 
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
10
  import io
11
+ import time # For adding slight delay if API rate limits are hit
12
 
13
  class VisualEngine:
14
+ def __init__(self, output_dir="temp_cinegen_media"):
15
  self.output_dir = output_dir
16
  os.makedirs(self.output_dir, exist_ok=True)
17
 
18
  self.font_filename = "arial.ttf"
19
  self.font_path_in_container = f"/usr/local/share/fonts/truetype/mycustomfonts/{self.font_filename}"
20
+ self.font_size_pil = 20 # Slightly smaller for placeholder text to fit more
21
+ self.video_overlay_font_size = 32
22
  self.video_overlay_font_color = 'white'
23
+ self.video_overlay_font = 'Arial-Bold' # Try specific variant; ensure ImageMagick can find it or use full path
 
 
24
 
25
  try:
26
  self.font = ImageFont.truetype(self.font_path_in_container, self.font_size_pil)
 
28
  except IOError:
29
  print(f"Warning: Could not load font from '{self.font_path_in_container}'. Placeholders will use default font.")
30
  self.font = ImageFont.load_default()
31
+ self.font_size_pil = 10 # Default font size estimate
32
 
33
  self.openai_api_key = None
34
  self.USE_AI_IMAGE_GENERATION = False
35
  self.dalle_model = "dall-e-3"
36
+ # DALL-E 3 standard size for highest quality generally. Other options: "1792x1024", "1024x1792"
37
+ self.image_size_dalle3 = "1792x1024" # Landscape, good for cinematic
38
+ self.video_frame_size = (1280, 720) # 16:9 aspect ratio for video output
 
39
 
40
  def set_openai_api_key(self, api_key):
41
  if api_key:
42
  self.openai_api_key = api_key
43
  self.USE_AI_IMAGE_GENERATION = True
44
+ print(f"OpenAI API key set. AI Image Generation Enabled with {self.dalle_model}.")
45
  else:
46
  self.USE_AI_IMAGE_GENERATION = False
47
  print("OpenAI API key not provided. AI Image Generation Disabled. Using placeholders.")
48
 
49
+ def _get_text_dimensions(self, text_content, font_obj): # Remains the same
50
+ if not text_content: return 0, self.font_size_pil
 
51
  try:
52
+ if hasattr(font_obj, 'getbbox'):
53
+ bbox = font_obj.getbbox(text_content); width = bbox[2] - bbox[0]; height = bbox[3] - bbox[1]
 
 
54
  return width, height if height > 0 else self.font_size_pil
55
+ elif hasattr(font_obj, 'getsize'):
56
  width, height = font_obj.getsize(text_content)
57
  return width, height if height > 0 else self.font_size_pil
58
  else:
59
+ 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)
60
+ except Exception: return int(len(text_content) * self.font_size_pil*0.6), int(self.font_size_pil*1.2)
 
 
 
 
 
 
61
 
62
+ def _create_placeholder_image_content(self, text_description, filename, size=(1280, 720)): # Default to video_frame_size
63
+ img = Image.new('RGB', size, color=(20, 20, 40)) # Darker
64
  draw = ImageDraw.Draw(img)
65
+ padding = 25
66
  max_text_width = size[0] - (2 * padding)
67
  lines = []
68
+ if not text_description: text_description = "(Placeholder: No prompt provided)"
69
+ # Simplified text wrapping for placeholder
70
  words = text_description.split()
71
  current_line = ""
72
  for word in words:
73
+ test_line = current_line + word + " "
74
+ if self._get_text_dimensions(test_line, self.font)[0] <= max_text_width:
75
+ current_line = test_line
 
 
 
 
76
  else:
77
+ if current_line: lines.append(current_line.strip())
78
+ current_line = word + " "
79
+ if current_line: lines.append(current_line.strip())
80
+ if not lines: lines.append("(Text too long or unrenderable for placeholder)")
81
+
82
+ _, single_line_height = self._get_text_dimensions("Ay", self.font)
83
+ if single_line_height == 0: single_line_height = self.font_size_pil + 2
84
+
85
+ num_lines_to_display = min(len(lines), (size[1] - 2 * padding) // (single_line_height + 2)) # Max lines based on height
86
+
87
+ y_text = padding + (size[1] - 2*padding - num_lines_to_display * (single_line_height + 2)) / 2.0
88
+
89
+ for i in range(num_lines_to_display):
90
+ line = lines[i]
 
 
91
  line_width, _ = self._get_text_dimensions(line, self.font)
92
  x_text = (size[0] - line_width) / 2.0
93
+ draw.text((x_text, y_text), line, font=self.font, fill=(200, 200, 180))
94
+ y_text += single_line_height + 2 # Line spacing
95
+ if i == 6 and num_lines_to_display > 7: # Show ellipsis if more text
96
+ draw.text((x_text, y_text), "...", font=self.font, fill=(200, 200, 180))
97
+ break
98
  filepath = os.path.join(self.output_dir, filename)
99
+ try: img.save(filepath); return filepath
100
+ except Exception as e: print(f"Error saving placeholder: {e}"); return None
 
 
 
 
101
 
102
  def generate_image_visual(self, image_prompt_text, scene_identifier_filename):
103
  filepath = os.path.join(self.output_dir, scene_identifier_filename)
104
  if self.USE_AI_IMAGE_GENERATION and self.openai_api_key:
105
+ max_retries = 2
106
+ for attempt in range(max_retries):
107
+ try:
108
+ print(f"Attempt {attempt+1}: DALL-E ({self.dalle_model}) for: {image_prompt_text[:120]}...")
109
+ client = openai.OpenAI(api_key=self.openai_api_key, timeout=60.0) # Timeout for client
110
+
111
+ response = client.images.generate(
112
+ model=self.dalle_model,
113
+ prompt=image_prompt_text,
114
+ n=1,
115
+ size=self.image_size_dalle3,
116
+ quality="hd", # Use "hd" for DALL-E 3 for better detail, "standard" for faster/cheaper
117
+ response_format="url",
118
+ style="vivid" # "vivid" or "natural" for DALL-E 3
119
+ )
120
+ image_url = response.data[0].url
121
+ revised_prompt = getattr(response.data[0], 'revised_prompt', None)
122
+ if revised_prompt: print(f"DALL-E 3 revised_prompt: {revised_prompt[:100]}...")
123
+
124
+ image_response = requests.get(image_url, timeout=90) # Increased download timeout
125
+ image_response.raise_for_status()
126
+
127
+ img_data = Image.open(io.BytesIO(image_response.content))
128
+ if img_data.mode != 'RGB': img_data = img_data.convert('RGB')
129
+
130
+ img_data.save(filepath)
131
+ print(f"AI Image (DALL-E) saved: {filepath}")
132
+ return filepath
133
+ except openai.RateLimitError as e:
134
+ print(f"OpenAI Rate Limit Error: {e}. Retrying after delay...")
135
+ if attempt < max_retries - 1: time.sleep(5 * (attempt + 1)); continue
136
+ else: print("Max retries reached for RateLimitError."); break
137
+ except openai.APIError as e: print(f"OpenAI API Error: {e}"); break
138
+ except requests.exceptions.RequestException as e: print(f"Requests Error (DALL-E image download): {e}"); break
139
+ except Exception as e: print(f"Generic error (DALL-E image gen): {e}"); break
140
 
141
+ print("DALL-E generation failed after retries. Falling back to placeholder.")
 
142
  return self._create_placeholder_image_content(
143
+ f"[AI Gen Failed] Prompt: {image_prompt_text[:100]}...",
144
  scene_identifier_filename, size=self.video_frame_size
145
  )
146
+ else:
 
 
147
  return self._create_placeholder_image_content(
148
  image_prompt_text, scene_identifier_filename, size=self.video_frame_size
149
  )
150
 
151
+ def create_video_from_images(self, image_data_list, output_filename="final_video.mp4", fps=24, duration_per_image=4):
152
+ if not image_data_list: return None
153
+ print(f"Creating video from {len(image_data_list)} image sets.")
 
 
 
154
  processed_clips = []
155
 
156
  for i, data in enumerate(image_data_list):
157
+ img_path, scene_num, key_action = data.get('path'), data.get('scene_num', i+1), data.get('key_action', '')
 
 
 
158
  if not (img_path and os.path.exists(img_path)):
159
+ print(f"Image not found: {img_path}. Skipping."); continue
 
160
  try:
161
+ pil_img_orig = Image.open(img_path)
162
+ if pil_img_orig.mode != 'RGB': pil_img_orig = pil_img_orig.convert('RGB')
163
+
164
+ # Resize and letterbox/pillarbox to video_frame_size
165
+ img_for_frame = pil_img_orig.copy()
166
+ img_for_frame.thumbnail(self.video_frame_size, Image.Resampling.LANCZOS)
167
+ canvas = Image.new('RGB', self.video_frame_size, (0,0,0))
168
+ x_offset = (self.video_frame_size[0] - img_for_frame.width) // 2
169
+ y_offset = (self.video_frame_size[1] - img_for_frame.height) // 2
170
+ canvas.paste(img_for_frame, (x_offset, y_offset))
171
 
172
+ frame_np = np.array(canvas)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
173
  img_clip = ImageClip(frame_np).set_duration(duration_per_image)
174
 
175
+ # Ken Burns: zoom from 100% to 110%
176
+ img_clip = img_clip.fx(vfx.resize, lambda t: 1 + 0.1 * (t / duration_per_image))
177
+ img_clip = img_clip.set_position('center')
 
178
 
179
  # Text Overlay
180
+ if key_action:
181
+ overlay_text = f"Scene {scene_num}\n{key_action}"
182
+ txt_clip = TextClip(overlay_text, fontsize=self.video_overlay_font_size,
183
+ color=self.video_overlay_font_color, font=self.video_overlay_font,
184
+ bg_color='rgba(0,0,0,0.7)', method='caption', align='West',
185
+ size=(self.video_frame_size[0]*0.85, None), kerning=-1, stroke_color='black', stroke_width=0.5
186
+ ).set_duration(duration_per_image - 1.0).set_start(0.5) # Show for duration-1s, slight delay
187
+ txt_clip = txt_clip.set_position(('center', 0.88), relative=True)
188
+ final_scene_clip = CompositeVideoClip([img_clip, txt_clip], size=self.video_frame_size)
189
+ else:
190
+ final_scene_clip = img_clip
191
+ processed_clips.append(final_scene_clip)
192
+ except Exception as e: print(f"Error processing clip for {img_path}: {e}. Skipping.")
193
+
194
+ if not processed_clips: print("No clips processed for video."); return None
195
+
196
+ transition_duration = 0.75 # Crossfade duration
197
+ final_video = concatenate_videoclips(processed_clips, padding=-transition_duration, method="compose")
198
+ if final_video.duration > transition_duration*2: # Ensure enough duration for fades
199
+ final_video = final_video.fx(vfx.fadein, transition_duration).fx(vfx.fadeout, transition_duration)
 
 
 
 
 
 
200
 
 
 
 
 
 
 
 
 
 
 
201
  output_path = os.path.join(self.output_dir, output_filename)
 
202
  try:
203
+ final_video.write_videofile(output_path, fps=fps, codec='libx264', preset='medium', audio_codec='aac',
204
+ temp_audiofile=os.path.join(self.output_dir, f'temp-audio-{os.urandom(4).hex()}.m4a'),
205
+ remove_temp=True, threads=os.cpu_count() or 2, logger='bar')
206
+ print(f"Video created: {output_path}"); return output_path
207
+ except Exception as e: print(f"Error writing video file: {e}"); return None
208
+ finally:
209
+ for clip in processed_clips: clip.close()
210
+ if hasattr(final_video, 'close'): final_video.close()