mgbam commited on
Commit
3084a6c
·
verified ·
1 Parent(s): d73d823

Update core/visual_engine.py

Browse files
Files changed (1) hide show
  1. core/visual_engine.py +294 -925
core/visual_engine.py CHANGED
@@ -12,36 +12,23 @@ import random
12
  import logging
13
 
14
  # --- MoviePy Imports ---
15
- from moviepy.editor import (
16
- ImageClip,
17
- VideoFileClip,
18
- concatenate_videoclips,
19
- TextClip,
20
- CompositeVideoClip,
21
- AudioFileClip,
22
- )
23
  import moviepy.video.fx.all as vfx
24
 
25
  # --- MONKEY PATCH for Pillow/MoviePy compatibility ---
26
  try:
27
- if hasattr(Image, "Resampling") and hasattr(Image.Resampling, "LANCZOS"): # Pillow 9+
28
- if not hasattr(Image, "ANTIALIAS"):
29
- Image.ANTIALIAS = Image.Resampling.LANCZOS
30
- elif hasattr(Image, "LANCZOS"): # Pillow 8
31
- if not hasattr(Image, "ANTIALIAS"):
32
- Image.ANTIALIAS = Image.LANCZOS
33
- elif not hasattr(Image, "ANTIALIAS"): # Fallback if no common resampling attributes found
34
- print(
35
- "WARNING: Pillow version lacks common Resampling attributes or ANTIALIAS. MoviePy effects might fail or look different."
36
- )
37
  except Exception as e_monkey_patch:
38
- print(
39
- f"WARNING: An unexpected error occurred during Pillow ANTIALIAS monkey-patch: {e_monkey_patch}"
40
- )
41
 
42
  logger = logging.getLogger(__name__)
43
- # Consider setting level in main app if not already configured:
44
- # logger.setLevel(logging.DEBUG) # For very verbose output during debugging
45
 
46
  # --- External Service Client Imports ---
47
  ELEVENLABS_CLIENT_IMPORTED = False
@@ -51,383 +38,157 @@ VoiceSettings = None
51
  try:
52
  from elevenlabs.client import ElevenLabs as ImportedElevenLabsClient
53
  from elevenlabs import Voice as ImportedVoice, VoiceSettings as ImportedVoiceSettings
54
-
55
  ElevenLabsAPIClient = ImportedElevenLabsClient
56
  Voice = ImportedVoice
57
  VoiceSettings = ImportedVoiceSettings
58
  ELEVENLABS_CLIENT_IMPORTED = True
59
  logger.info("ElevenLabs client components imported successfully.")
60
  except ImportError:
61
- logger.warning(
62
- "ElevenLabs SDK not found (pip install elevenlabs). Audio generation will be disabled."
63
- )
64
  except Exception as e_eleven_import:
65
- logger.warning(
66
- f"Error importing ElevenLabs client components: {e_eleven_import}. Audio generation disabled."
67
- )
68
 
69
  RUNWAYML_SDK_IMPORTED = False
70
- RunwayMLAPIClient = None # Using a more specific name for the client class
71
  try:
72
- from runwayml import RunwayML as ImportedRunwayMLClient # Actual SDK import
73
-
74
  RunwayMLAPIClient = ImportedRunwayMLClient
75
  RUNWAYML_SDK_IMPORTED = True
76
  logger.info("RunwayML SDK imported successfully.")
77
  except ImportError:
78
- logger.warning(
79
- "RunwayML SDK not found (pip install runwayml). RunwayML video generation will be disabled."
80
- )
81
  except Exception as e_runway_sdk_import:
82
- logger.warning(
83
- f"Error importing RunwayML SDK: {e_runway_sdk_import}. RunwayML features disabled."
84
- )
85
 
86
 
87
  class VisualEngine:
88
- DEFAULT_FONT_SIZE_PIL = 10 # For default Pillow font
89
- PREFERRED_FONT_SIZE_PIL = 20 # For custom font
90
  VIDEO_OVERLAY_FONT_SIZE = 30
91
- VIDEO_OVERLAY_FONT_COLOR = "white"
92
- # Standard font names ImageMagick (used by TextClip) is likely to find in Linux containers
93
- DEFAULT_MOVIEPY_FONT = "DejaVu-Sans-Bold"
94
- PREFERRED_MOVIEPY_FONT = "Liberation-Sans-Bold" # Often available
95
 
96
- def __init__(
97
- self, output_dir="temp_cinegen_media", default_elevenlabs_voice_id="Rachel"
98
- ):
99
  self.output_dir = output_dir
100
  os.makedirs(self.output_dir, exist_ok=True)
101
-
102
- self.font_filename_pil = "DejaVuSans-Bold.ttf" # A more standard Linux font
103
- font_paths_to_try = [
104
- self.font_filename_pil, # If in working dir or PATH
105
- f"/usr/share/fonts/truetype/dejavu/{self.font_filename_pil}",
106
- f"/usr/share/fonts/truetype/liberation/LiberationSans-Bold.ttf", # Alternative
107
- f"/System/Library/Fonts/Supplemental/Arial.ttf", # macOS fallback
108
- f"C:/Windows/Fonts/arial.ttf", # Windows fallback
109
- f"/usr/local/share/fonts/truetype/mycustomfonts/arial.ttf", # User's previous custom path
110
- ]
111
- self.font_path_pil_resolved = next(
112
- (p for p in font_paths_to_try if os.path.exists(p)), None
113
- )
114
-
115
- self.font_pil = ImageFont.load_default() # Default
116
- self.current_font_size_pil = self.DEFAULT_FONT_SIZE_PIL
117
-
118
  if self.font_path_pil_resolved:
119
- try:
120
- self.font_pil = ImageFont.truetype(
121
- self.font_path_pil_resolved, self.PREFERRED_FONT_SIZE_PIL
122
- )
123
- self.current_font_size_pil = self.PREFERRED_FONT_SIZE_PIL
124
- logger.info(
125
- f"Pillow font loaded: {self.font_path_pil_resolved} at size {self.current_font_size_pil}."
126
- )
127
- # Determine MoviePy font based on loaded PIL font
128
- if "dejavu" in self.font_path_pil_resolved.lower():
129
- self.video_overlay_font = "DejaVu-Sans-Bold"
130
- elif "liberation" in self.font_path_pil_resolved.lower():
131
- self.video_overlay_font = "Liberation-Sans-Bold"
132
- else: # Fallback if custom font doesn't have an obvious ImageMagick name
133
- self.video_overlay_font = self.DEFAULT_MOVIEPY_FONT
134
- except IOError as e_font_load:
135
- logger.error(
136
- f"Pillow font loading IOError for '{self.font_path_pil_resolved}': {e_font_load}. Using default."
137
- )
138
- else:
139
- logger.warning("Custom Pillow font not found. Using default.")
140
-
141
- self.openai_api_key = None
142
- self.USE_AI_IMAGE_GENERATION = False
143
- self.dalle_model = "dall-e-3"
144
- self.image_size_dalle3 = "1792x1024"
145
  self.video_frame_size = (1280, 720)
146
-
147
- self.elevenlabs_api_key = None
148
- self.USE_ELEVENLABS = False
149
- self.elevenlabs_client = None
150
- self.elevenlabs_voice_id = default_elevenlabs_voice_id
151
- if VoiceSettings and ELEVENLABS_CLIENT_IMPORTED:
152
- self.elevenlabs_voice_settings = VoiceSettings(
153
- stability=0.60,
154
- similarity_boost=0.80,
155
- style=0.15,
156
- use_speaker_boost=True,
157
- )
158
- else:
159
- self.elevenlabs_voice_settings = None
160
-
161
- self.pexels_api_key = None
162
- self.USE_PEXELS = False
163
- self.runway_api_key = None
164
- self.USE_RUNWAYML = False
165
- self.runway_ml_client_instance = None # More specific name
166
-
167
- # Attempt to initialize Runway client if SDK is present and env var might be set
168
- if (
169
- RUNWAYML_SDK_IMPORTED
170
- and RunwayMLAPIClient
171
- and os.getenv("RUNWAYML_API_SECRET")
172
- ):
173
- try:
174
- self.runway_ml_client_instance = RunwayMLAPIClient() # SDK uses env var
175
- self.USE_RUNWAYML = True # Assume enabled if client initializes
176
- logger.info(
177
- "RunwayML Client initialized from RUNWAYML_API_SECRET env var at startup."
178
- )
179
- except Exception as e_runway_init_startup:
180
- logger.error(
181
- f"Initial RunwayML client init failed (env var RUNWAYML_API_SECRET might be invalid): {e_runway_init_startup}"
182
- )
183
- self.USE_RUNWAYML = False
184
-
185
  logger.info("VisualEngine initialized.")
186
 
187
- # --- API Key Setters ---
188
- def set_openai_api_key(self, api_key):
189
- self.openai_api_key = api_key
190
- self.USE_AI_IMAGE_GENERATION = bool(api_key)
191
- logger.info(
192
- f"DALL-E ({self.dalle_model}) status: {'Ready' if self.USE_AI_IMAGE_GENERATION else 'Disabled'}"
193
- )
194
-
195
  def set_elevenlabs_api_key(self, api_key, voice_id_from_secret=None):
196
  self.elevenlabs_api_key = api_key
197
- if voice_id_from_secret:
198
- self.elevenlabs_voice_id = voice_id_from_secret
199
  if api_key and ELEVENLABS_CLIENT_IMPORTED and ElevenLabsAPIClient:
200
- try:
201
- self.elevenlabs_client = ElevenLabsAPIClient(api_key=api_key)
202
- self.USE_ELEVENLABS = bool(self.elevenlabs_client)
203
- logger.info(
204
- f"ElevenLabs Client status: {'Ready' if self.USE_ELEVENLABS else 'Failed Initialization'} (Using Voice ID: {self.elevenlabs_voice_id})"
205
- )
206
- except Exception as e:
207
- logger.error(
208
- f"ElevenLabs client initialization error: {e}. Service Disabled.",
209
- exc_info=True,
210
- )
211
- self.USE_ELEVENLABS = False
212
- self.elevenlabs_client = None
213
- else:
214
- self.USE_ELEVENLABS = False
215
- logger.info(
216
- f"ElevenLabs Service Disabled (API key not provided or SDK import issue)."
217
- )
218
-
219
- def set_pexels_api_key(self, api_key):
220
- self.pexels_api_key = api_key
221
- self.USE_PEXELS = bool(api_key)
222
- logger.info(
223
- f"Pexels Search status: {'Ready' if self.USE_PEXELS else 'Disabled'}"
224
- )
225
-
226
  def set_runway_api_key(self, api_key):
227
- self.runway_api_key = api_key # Store key regardless for potential direct HTTP use
228
  if api_key:
229
  if RUNWAYML_SDK_IMPORTED and RunwayMLAPIClient:
230
- if not self.runway_ml_client_instance: # If not already initialized by env var
231
  try:
232
- # The RunwayML Python SDK expects the API key via the RUNWAYML_API_SECRET env var.
233
- # If it's not set, we set it temporarily for client initialization.
234
  original_env_secret = os.getenv("RUNWAYML_API_SECRET")
235
- if not original_env_secret:
236
- logger.info(
237
- "Temporarily setting RUNWAYML_API_SECRET from provided key for SDK client init."
238
- )
239
- os.environ["RUNWAYML_API_SECRET"] = api_key
240
-
241
- self.runway_ml_client_instance = RunwayMLAPIClient()
242
- self.USE_RUNWAYML = True # SDK client successfully initialized
243
- logger.info(
244
- "RunwayML Client initialized successfully using provided API key."
245
- )
246
-
247
- if not original_env_secret: # Clean up if we set it
248
- del os.environ["RUNWAYML_API_SECRET"]
249
- logger.info(
250
- "Cleared temporary RUNWAYML_API_SECRET env var."
251
- )
252
-
253
- except Exception as e_client_init:
254
- logger.error(
255
- f"RunwayML Client initialization via set_runway_api_key failed: {e_client_init}",
256
- exc_info=True,
257
- )
258
- self.USE_RUNWAYML = False
259
- self.runway_ml_client_instance = None
260
- else: # Client was already initialized (likely via env var during __init__)
261
- self.USE_RUNWAYML = True
262
- logger.info(
263
- "RunwayML Client was already initialized (likely from env var). API key stored."
264
- )
265
- else: # SDK not imported
266
- logger.warning(
267
- "RunwayML SDK not imported. API key stored, but integration requires SDK. Service effectively disabled."
268
- )
269
- self.USE_RUNWAYML = False
270
- else: # No API key provided
271
- self.USE_RUNWAYML = False
272
- self.runway_ml_client_instance = None
273
- logger.info("RunwayML Service Disabled (no API key provided).")
274
 
275
- # --- Helper Methods ---
276
  def _image_to_data_uri(self, image_path):
277
- try:
278
- mime_type, _ = mimetypes.guess_type(image_path)
279
- if not mime_type:
280
- ext = os.path.splitext(image_path)[1].lower()
281
- mime_map = {".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg"}
282
- mime_type = mime_map.get(ext, "application/octet-stream")
283
- if mime_type == "application/octet-stream":
284
- logger.warning(
285
- f"Could not determine MIME type for {image_path}, using default."
286
- )
287
-
288
- with open(image_path, "rb") as image_file:
289
- encoded_string = base64.b64encode(image_file.read()).decode("utf-8")
290
- data_uri = f"data:{mime_type};base64,{encoded_string}"
291
- logger.debug(
292
- f"Generated data URI for {os.path.basename(image_path)} (first 100 chars): {data_uri[:100]}..."
293
- )
294
- return data_uri
295
- except FileNotFoundError:
296
- logger.error(f"Image file not found at {image_path} for data URI conversion.")
297
- return None
298
- except Exception as e:
299
- logger.error(
300
- f"Error converting image {image_path} to data URI: {e}", exc_info=True
301
- )
302
- return None
303
 
304
  def _map_resolution_to_runway_ratio(self, width, height):
305
- ratio_str = f"{width}:{height}"
306
- # Gen-4 supports: "1280:720", "720:1280", "1104:832", "832:1104", "960:960", "1584:672"
307
- supported_ratios_gen4 = [
308
- "1280:720",
309
- "720:1280",
310
- "1104:832",
311
- "832:1104",
312
- "960:960",
313
- "1584:672",
314
- ]
315
- if ratio_str in supported_ratios_gen4:
316
- return ratio_str
317
- # Fallback or find closest - for now, strict matching or default
318
- logger.warning(
319
- f"Resolution {ratio_str} not directly in Gen-4 supported list. Defaulting to 1280:720."
320
- )
321
- return "1280:720"
322
 
323
  def _get_text_dimensions(self, text_content, font_object):
324
- # (Robust version from before)
325
- default_char_height = getattr(font_object, "size", self.current_font_size_pil)
326
- if not text_content:
327
- return 0, default_char_height
328
  try:
329
- if hasattr(font_object, "getbbox"):
330
- bbox = font_object.getbbox(text_content)
331
- w = bbox[2] - bbox[0]
332
- h = bbox[3] - bbox[1]
333
- return w, h if h > 0 else default_char_height
334
- elif hasattr(font_object, "getsize"):
335
- w, h = font_object.getsize(text_content)
336
- return w, h if h > 0 else default_char_height
337
- else:
338
- return (
339
- int(len(text_content) * default_char_height * 0.6),
340
- int(default_char_height * 1.2),
341
- )
342
- except Exception as e:
343
- logger.warning(f"Error in _get_text_dimensions: {e}")
344
- return (
345
- int(len(text_content) * self.current_font_size_pil * 0.6),
346
- int(self.current_font_size_pil * 1.2),
347
- )
348
-
349
- def _create_placeholder_image_content(self, text_description, filename, size=None):
350
- # (Corrected version from previous response)
351
- if size is None:
352
- size = self.video_frame_size
353
- img = Image.new("RGB", size, color=(20, 20, 40))
354
- d = ImageDraw.Draw(img)
355
- padding = 25
356
- max_w = size[0] - (2 * padding)
357
- lines = []
358
- if not text_description:
359
- text_description = "(Placeholder Image)"
360
- words = text_description.split()
361
- current_line_text = ""
362
  for word_idx, word in enumerate(words):
363
  prospective_addition = word + (" " if word_idx < len(words) - 1 else "")
364
  test_line_text = current_line_text + prospective_addition
365
  current_w, _ = self._get_text_dimensions(test_line_text, self.font_pil)
366
- if current_w == 0 and test_line_text.strip():
367
- current_w = len(test_line_text) * (self.current_font_size_pil * 0.6) # Estimate
368
 
369
- if current_w <= max_w:
370
- current_line_text = test_line_text
371
  else:
372
- if current_line_text.strip():
373
- lines.append(current_line_text.strip())
374
- current_line_text = prospective_addition # Start new line
375
- if current_line_text.strip():
376
- lines.append(current_line_text.strip())
377
 
378
  if not lines and text_description:
379
- avg_char_w, _ = self._get_text_dimensions("W", self.font_pil)
380
- avg_char_w = avg_char_w or (self.current_font_size_pil * 0.6)
381
  chars_per_line = int(max_w / avg_char_w) if avg_char_w > 0 else 20
382
- lines.append(
383
- text_description[:chars_per_line]
384
- + ("..." if len(text_description) > chars_per_line else "")
385
- )
386
- elif not lines:
387
- lines.append("(Placeholder Error)")
388
-
389
- _, single_line_h = self._get_text_dimensions("Ay", self.font_pil)
390
- single_line_h = single_line_h if single_line_h > 0 else self.current_font_size_pil + 2
391
- max_lines = (
392
- min(len(lines), (size[1] - (2 * padding)) // (single_line_h + 2))
393
- if single_line_h > 0
394
- else 1
395
- )
396
- max_lines = max(1, max_lines) # Ensure at least one line
397
 
 
 
 
 
398
  y_pos = padding + (size[1] - (2 * padding) - max_lines * (single_line_h + 2)) / 2.0
399
  for i in range(max_lines):
400
- line_text = lines[i]
401
- line_w, _ = self._get_text_dimensions(line_text, self.font_pil)
402
- if line_w == 0 and line_text.strip():
403
- line_w = len(line_text) * (self.current_font_size_pil * 0.6)
404
  x_pos = (size[0] - line_w) / 2.0
405
- try:
406
- d.text((x_pos, y_pos), line_text, font=self.font_pil, fill=(200, 200, 180))
407
- except Exception as e_draw:
408
- logger.error(f"Pillow d.text error: {e_draw} for '{line_text}'")
409
  y_pos += single_line_h + 2
410
  if i == 6 and max_lines > 7:
411
- try:
412
- d.text((x_pos, y_pos), "...", font=self.font_pil, fill=(200, 200, 180))
413
- except Exception as e_elip:
414
- logger.error(f"Pillow d.text ellipsis error: {e_elip}")
415
- break
416
-
417
  filepath = os.path.join(self.output_dir, filename)
418
- try:
419
- img.save(filepath)
420
- return filepath
421
- except Exception as e_save:
422
- logger.error(
423
- f"Saving placeholder image '{filepath}' error: {e_save}", exc_info=True
424
- )
425
- return None
426
 
427
  def _search_pexels_image(self, query, output_filename_base):
428
- # <<< THIS IS THE CORRECTED METHOD >>>
429
- if not self.USE_PEXELS or not self.pexels_api_key:
430
- return None
431
  headers = {"Authorization": self.pexels_api_key}
432
  params = {"query": query, "per_page": 1, "orientation": "landscape", "size": "large2x"}
433
  base_name_for_pexels, _ = os.path.splitext(output_filename_base)
@@ -437,621 +198,229 @@ class VisualEngine:
437
  logger.info(f"Pexels: Searching for '{query}'")
438
  effective_query = " ".join(query.split()[:5])
439
  params["query"] = effective_query
440
- response = requests.get(
441
- "https://api.pexels.com/v1/search", headers=headers, params=params, timeout=20
442
- )
443
  response.raise_for_status()
444
  data = response.json()
445
  if data.get("photos") and len(data["photos"]) > 0:
446
  photo_details = data["photos"][0]
447
  photo_url = photo_details.get("src", {}).get("large2x")
448
- if not photo_url:
449
- logger.warning(
450
- f"Pexels: 'large2x' URL missing for '{effective_query}'. Details: {photo_details}"
451
- )
452
- return None
453
- image_response = requests.get(photo_url, timeout=60)
454
- image_response.raise_for_status()
455
  img_data_pil = Image.open(io.BytesIO(image_response.content))
456
- if img_data_pil.mode != "RGB":
457
- img_data_pil = img_data_pil.convert("RGB")
458
- img_data_pil.save(filepath)
459
- logger.info(f"Pexels: Image saved to {filepath}")
460
- return filepath
461
- else:
462
- logger.info(f"Pexels: No photos for '{effective_query}'.")
463
- return None
464
- except requests.exceptions.RequestException as e_req:
465
- logger.error(f"Pexels: RequestException for '{query}': {e_req}", exc_info=False)
466
- return None # Less verbose for network
467
- except Exception as e:
468
- logger.error(f"Pexels: General error for '{query}': {e}", exc_info=True)
469
- return None
470
-
471
- # --- RunwayML Video Generation (Gen-4 Aligned with SDK) ---
472
- def _generate_video_clip_with_runwayml(
473
- self,
474
- text_prompt_for_motion,
475
- input_image_path,
476
- scene_identifier_filename_base,
477
- target_duration_seconds=5,
478
- ):
479
- if not self.USE_RUNWAYML or not self.runway_ml_client_instance:
480
- logger.warning("RunwayML not enabled or client not initialized. Cannot generate video clip.")
481
- return None
482
- if not input_image_path or not os.path.exists(input_image_path):
483
- logger.error(
484
- f"Runway Gen-4 requires an input image. Path not provided or invalid: {input_image_path}"
485
- )
486
- return None
487
-
488
  image_data_uri = self._image_to_data_uri(input_image_path)
489
- if not image_data_uri:
490
- return None
491
-
492
- runway_duration = 10 if target_duration_seconds >= 8 else 5 # Map to 5s or 10s for Gen-4
493
- runway_ratio_str = self._map_resolution_to_runway_ratio(
494
- self.video_frame_size[0], self.video_frame_size[1]
495
- )
496
-
497
- # Use a more descriptive output filename for Runway videos
498
- base_name_for_runway, _ = os.path.splitext(scene_identifier_filename_base)
499
- output_video_filename = base_name_for_runway + f"_runway_gen4_d{runway_duration}s.mp4"
500
  output_video_filepath = os.path.join(self.output_dir, output_video_filename)
501
-
502
- logger.info(
503
- f"Initiating Runway Gen-4 task: motion='{text_prompt_for_motion[:100]}...', image='{os.path.basename(input_image_path)}', dur={runway_duration}s, ratio='{runway_ratio_str}'"
504
- )
505
  try:
506
- # Using the RunwayML Python SDK structure
507
- task_submission = self.runway_ml_client_instance.image_to_video.create(
508
- model="gen4_turbo",
509
- prompt_image=image_data_uri,
510
- prompt_text=text_prompt_for_motion, # This is the motion prompt
511
- duration=runway_duration,
512
- ratio=runway_ratio_str,
513
- # seed=random.randint(0, 4294967295), # Optional: for reproducibility
514
- # Other Gen-4 params (motion_score, upscale, watermark etc. can be added here if available in SDK)
515
- )
516
- task_id = task_submission.id
517
- logger.info(f"Runway Gen-4 task created with ID: {task_id}. Polling for completion...")
518
-
519
- poll_interval_seconds = 10
520
- max_polling_duration_seconds = 6 * 60 # 6 minutes
521
- start_time = time.time()
522
-
523
- while time.time() - start_time < max_polling_duration_seconds:
524
- time.sleep(poll_interval_seconds)
525
- task_details = self.runway_ml_client_instance.tasks.retrieve(id=task_id)
526
  logger.info(f"Runway task {task_id} status: {task_details.status}")
527
-
528
- if task_details.status == "SUCCEEDED":
529
- # Determine output URL (this structure might vary based on SDK version)
530
- output_url = None
531
- if hasattr(task_details, "output") and task_details.output and hasattr(
532
- task_details.output, "url"
533
- ):
534
- output_url = task_details.output.url
535
- elif (
536
- hasattr(task_details, "artifacts")
537
- and task_details.artifacts
538
- and isinstance(task_details.artifacts, list)
539
- and len(task_details.artifacts) > 0
540
- ):
541
- first_artifact = task_details.artifacts[0]
542
- if hasattr(first_artifact, "url"):
543
- output_url = first_artifact.url
544
- elif hasattr(first_artifact, "download_url"):
545
- output_url = first_artifact.download_url
546
-
547
- if not output_url:
548
- logger.error(
549
- f"Runway task {task_id} SUCCEEDED, but no output URL found. Details: {vars(task_details) if hasattr(task_details,'__dict__') else str(task_details)}"
550
- )
551
- return None
552
-
553
- logger.info(f"Runway task {task_id} SUCCEEDED. Downloading video from: {output_url}")
554
- video_response = requests.get(output_url, stream=True, timeout=300)
555
- video_response.raise_for_status()
556
- with open(output_video_filepath, "wb") as f:
557
- for chunk in video_response.iter_content(chunk_size=8192):
558
- f.write(chunk)
559
- logger.info(
560
- f"Runway Gen-4 video successfully downloaded to: {output_video_filepath}"
561
- )
562
- return output_video_filepath
563
-
564
- elif task_details.status in ["FAILED", "ABORTED", "ERROR"]: # Added ERROR
565
- error_msg = (
566
- getattr(task_details, "error_message", None)
567
- or getattr(getattr(task_details, "output", None), "error", "Unknown error from Runway task.")
568
- )
569
- logger.error(
570
- f"Runway task {task_id} final status: {task_details.status}. Error: {error_msg}"
571
- )
572
- return None
573
-
574
- logger.warning(
575
- f"Runway task {task_id} timed out polling after {max_polling_duration_seconds} seconds."
576
- )
577
- return None
578
-
579
- except AttributeError as ae: # If SDK methods are not as expected
580
- logger.error(
581
- f"AttributeError with RunwayML SDK: {ae}. Ensure SDK is up to date and methods/attributes match documentation.",
582
- exc_info=True,
583
- )
584
- return None
585
- except Exception as e_runway_call:
586
- logger.error(
587
- f"General error during Runway Gen-4 API call or processing: {e_runway_call}",
588
- exc_info=True,
589
- )
590
- return None
591
-
592
- def _create_placeholder_video_content(self, text_description, filename, duration=4, size=None):
593
- # (Keeping as before)
594
- if size is None:
595
- size = self.video_frame_size
596
- fp = os.path.join(self.output_dir, filename)
597
- tc = None
598
- try:
599
- tc = TextClip(
600
- text_description,
601
- fontsize=50,
602
- color="white",
603
- font=self.video_overlay_font,
604
- bg_color="black",
605
- size=size,
606
- method="caption",
607
- ).set_duration(duration)
608
- tc.write_videofile(
609
- fp, fps=24, codec="libx264", preset="ultrafast", logger=None, threads=2
610
- )
611
- logger.info(f"Generic placeholder video: {fp}")
612
- return fp
613
- except Exception as e:
614
- logger.error(f"Generic placeholder video error {fp}: {e}", exc_info=True)
615
- return None
616
  finally:
617
- if tc and hasattr(tc, "close"):
618
- tc.close()
619
 
620
- # --- generate_scene_asset (Main asset generation logic using Runway Gen-4 workflow) ---
621
- def generate_scene_asset(
622
- self,
623
- image_generation_prompt_text,
624
- motion_prompt_text_for_video,
625
- scene_data,
626
- scene_identifier_filename_base,
627
- generate_as_video_clip=False,
628
- runway_target_duration=5,
629
- ):
630
- # (Logic updated for Runway Gen-4 workflow)
631
  base_name, _ = os.path.splitext(scene_identifier_filename_base)
632
- asset_info = {
633
- "path": None,
634
- "type": "none",
635
- "error": True,
636
- "prompt_used": image_generation_prompt_text,
637
- "error_message": "Asset generation init failed",
638
- }
639
  input_image_for_runway_path = None
640
- # Use a distinct name for the base image if it's only an intermediate step for video
641
  base_image_filename = base_name + ("_base_for_video.png" if generate_as_video_clip else ".png")
642
  base_image_filepath = os.path.join(self.output_dir, base_image_filename)
643
-
644
- # STEP 1: Generate/acquire the base image
645
- # Try DALL-E
646
  if self.USE_AI_IMAGE_GENERATION and self.openai_api_key:
647
- max_r, att_n = 2, 0
648
- for att_n in range(max_r):
649
- try:
650
- logger.info(f"Att {att_n+1} DALL-E (base img): {image_generation_prompt_text[:70]}...")
651
- cl = openai.OpenAI(api_key=self.openai_api_key, timeout=90.0)
652
- r = cl.images.generate(
653
- model=self.dalle_model,
654
- prompt=image_generation_prompt_text,
655
- n=1,
656
- size=self.image_size_dalle3,
657
- quality="hd",
658
- response_format="url",
659
- style="vivid",
660
- )
661
- iu = r.data[0].url
662
- rp = getattr(r.data[0], "revised_prompt", None)
663
- if rp:
664
- logger.info(f"DALL-E revised: {rp[:70]}...")
665
- ir = requests.get(iu, timeout=120)
666
- ir.raise_for_status()
667
- id_img = Image.open(io.BytesIO(ir.content))
668
- if id_img.mode != "RGB":
669
- id_img = id_img.convert("RGB")
670
- id_img.save(base_image_filepath)
671
- logger.info(f"DALL-E base img saved: {base_image_filepath}")
672
- input_image_for_runway_path = base_image_filepath
673
- asset_info = {
674
- "path": base_image_filepath,
675
- "type": "image",
676
- "error": False,
677
- "prompt_used": image_generation_prompt_text,
678
- "revised_prompt": rp,
679
- }
680
- break
681
- except openai.RateLimitError as e:
682
- logger.warning(f"OpenAI RateLimit {att_n+1}:{e}.Retry...")
683
- time.sleep(5 * (att_n + 1))
684
- asset_info["error_message"] = str(e)
685
- except Exception as e:
686
- logger.error(f"DALL-E base img error:{e}", exc_info=True)
687
- asset_info["error_message"] = str(e)
688
- break
689
-
690
- if asset_info["error"]:
691
- logger.warning(f"DALL-E failed after {att_n+1} attempts for base img.")
692
 
693
- if asset_info["error"] and self.USE_PEXELS:
694
- # Pexels Fallback
695
- logger.info("Trying Pexels for base img.")
696
- pqt = scene_data.get("pexels_search_query_감독", f"{scene_data.get('emotional_beat','')} {scene_data.get('setting_description','')}")
697
- pp = self._search_pexels_image(pqt, base_image_filename) # Use base_image_filename
698
- if pp:
699
- input_image_for_runway_path = pp
700
- asset_info = {
701
- "path": pp,
702
- "type": "image",
703
- "error": False,
704
- "prompt_used": f"Pexels:{pqt}",
705
- }
706
- else:
707
- current_em = asset_info.get("error_message", "")
708
- asset_info["error_message"] = (current_em + " Pexels failed for base.").strip()
709
-
710
- if asset_info["error"]:
711
- # Placeholder Fallback
712
- logger.warning("Base img (DALL-E/Pexels) failed. Using placeholder.")
713
- ppt = asset_info.get("prompt_used", image_generation_prompt_text)
714
- php = self._create_placeholder_image_content(f"[Base Placeholder]{ppt[:70]}...", base_image_filename) # Use base_image_filename
715
- if php:
716
- input_image_for_runway_path = php
717
- asset_info = {
718
- "path": php,
719
- "type": "image",
720
- "error": False,
721
- "prompt_used": ppt,
722
- }
723
- else:
724
- current_em = asset_info.get("error_message", "")
725
- asset_info["error_message"] = (current_em + " Base placeholder failed.").strip()
726
-
727
- # STEP 2: If video clip is requested, use the generated base image with RunwayML
728
  if generate_as_video_clip:
729
- if not input_image_for_runway_path:
730
- logger.error("RunwayML video: base image generation failed entirely. Cannot proceed.")
731
- asset_info["error"] = True
732
- asset_info["error_message"] = (
733
- asset_info.get("error_message", "") + " Base img completely failed, Runway abort."
734
- ).strip()
735
- asset_info["type"] = "none"
736
- return asset_info
737
-
738
  if self.USE_RUNWAYML:
739
- # This check is now more about if the service is generally enabled
740
- video_path = self._generate_video_clip_with_runwayml(
741
- motion_prompt_text_for_video,
742
- input_image_for_runway_path,
743
- base_name,
744
- runway_target_duration,
745
- ) # Pass base_name for runway output filename
746
- if video_path and os.path.exists(video_path):
747
- asset_info = {
748
- "path": video_path,
749
- "type": "video",
750
- "error": False,
751
- "prompt_used": motion_prompt_text_for_video,
752
- "base_image_path": input_image_for_runway_path,
753
- }
754
- else:
755
- logger.warning(f"RunwayML video failed for {base_name}. Fallback to base img.")
756
- asset_info["error"] = True
757
- asset_info["error_message"] = (
758
- asset_info.get("error_message", "Base img ok.")
759
- + " RunwayML video step failed; use base img."
760
- ).strip()
761
- asset_info["path"] = input_image_for_runway_path
762
- asset_info["type"] = "image"
763
- asset_info["prompt_used"] = image_generation_prompt_text
764
- else:
765
- logger.warning("RunwayML selected but not enabled/client not ready. Use base img.")
766
- asset_info["error"] = True
767
- asset_info["error_message"] = (
768
- asset_info.get("error_message", "Base img ok.")
769
- + " RunwayML disabled; use base img."
770
- ).strip()
771
- asset_info["path"] = input_image_for_runway_path
772
- asset_info["type"] = "image"
773
- asset_info["prompt_used"] = image_generation_prompt_text
774
-
775
  return asset_info
776
 
777
  def generate_narration_audio(self, text_to_narrate, output_filename="narration_overall.mp3"):
778
- # (Keep as before - robust enough)
779
- if not self.USE_ELEVENLABS or not self.elevenlabs_client or not text_to_narrate:
780
- logger.info("11L skip.")
781
- return None
782
-
783
- afp = os.path.join(self.output_dir, output_filename)
784
- try:
785
- logger.info(f"11L audio (Voice:{self.elevenlabs_voice_id}): {text_to_narrate[:70]}...")
786
- asm = None
787
-
788
- if hasattr(self.elevenlabs_client, "text_to_speech") and hasattr(
789
- self.elevenlabs_client.text_to_speech, "stream"
790
- ):
791
- asm = self.elevenlabs_client.text_to_speech.stream
792
- logger.info("Using 11L .text_to_speech.stream()")
793
- elif hasattr(self.elevenlabs_client, "generate_stream"):
794
- asm = self.elevenlabs_client.generate_stream
795
- logger.info("Using 11L .generate_stream()")
796
- elif hasattr(self.elevenlabs_client, "generate"):
797
- logger.info("Using 11L .generate()")
798
- vp = (
799
- Voice(voice_id=str(self.elevenlabs_voice_id), settings=self.elevenlabs_voice_settings)
800
- if Voice and self.elevenlabs_voice_settings
801
- else str(self.elevenlabs_voice_id)
802
- )
803
- ab = self.elevenlabs_client.generate(
804
- text=text_to_narrate, voice=vp, model="eleven_multilingual_v2"
805
- )
806
- with open(afp, "wb") as f:
807
- f.write(ab)
808
- logger.info(f"11L audio (non-stream): {afp}")
809
- return afp
810
- else:
811
- logger.error("No 11L audio method.")
812
- return None
813
-
814
- # If we have a streaming method (asm), use it
815
- if asm:
816
- vps = {"voice_id": str(self.elevenlabs_voice_id)}
817
- if self.elevenlabs_voice_settings:
818
- if hasattr(self.elevenlabs_voice_settings, "model_dump"):
819
- vps["voice_settings"] = self.elevenlabs_voice_settings.model_dump()
820
- elif hasattr(self.elevenlabs_voice_settings, "dict"):
821
- vps["voice_settings"] = self.elevenlabs_voice_settings.dict()
822
- else:
823
- vps["voice_settings"] = self.elevenlabs_voice_settings
824
-
825
- adi = asm(text=text_to_narrate, model_id="eleven_multilingual_v2", **vps)
826
- with open(afp, "wb") as f:
827
- for c in adi:
828
- if c:
829
- f.write(c)
830
- logger.info(f"11L audio (stream): {afp}")
831
- return afp
832
-
833
- except Exception as e:
834
- logger.error(f"11L audio error: {e}", exc_info=True)
835
- return None
836
-
837
- # --- assemble_animatic_from_assets (Still contains crucial debug saves for blank video issue) ---
838
- def assemble_animatic_from_assets(
839
- self, asset_data_list, overall_narration_path=None, output_filename="final_video.mp4", fps=24
840
- ):
841
- # (Keep the version with robust image processing, C-contiguous arrays, debug saves, and pix_fmt)
842
- if not asset_data_list:
843
- logger.warning("No assets for animatic.")
844
- return None
845
-
846
- processed_clips = []
847
- narration_clip = None
848
- final_clip = None
849
  logger.info(f"Assembling from {len(asset_data_list)} assets. Frame: {self.video_frame_size}.")
850
-
851
- for i, asset_info in enumerate(asset_data_list):
852
- asset_path = asset_info.get("path")
853
- asset_type = asset_info.get("type")
854
- scene_dur = asset_info.get("duration", 4.5)
855
- scene_num = asset_info.get("scene_num", i + 1)
856
- key_action = asset_info.get("key_action", "")
857
- logger.info(f"S{scene_num}: Path='{asset_path}', Type='{asset_type}', Dur='{scene_dur}'s")
858
-
859
- if not (asset_path and os.path.exists(asset_path)):
860
- logger.warning(f"S{scene_num}: Not found '{asset_path}'. Skip.")
861
- continue
862
- if scene_dur <= 0:
863
- logger.warning(f"S{scene_num}: Invalid duration ({scene_dur}s). Skip.")
864
- continue
865
-
866
- current_scene_mvpy_clip = None
867
  try:
868
- if asset_type == "image":
869
- pil_img = Image.open(asset_path)
870
- logger.debug(f"S{scene_num}: Loaded img. Mode:{pil_img.mode}, Size:{pil_img.size}")
871
- img_rgba = pil_img.convert("RGBA") if pil_img.mode != "RGBA" else pil_img.copy()
872
- thumb = img_rgba.copy()
873
- rf = Image.Resampling.LANCZOS if hasattr(Image.Resampling, "LANCZOS") else Image.BILINEAR
874
- thumb.thumbnail(self.video_frame_size, rf)
875
- cv_rgba = Image.new("RGBA", self.video_frame_size, (0, 0, 0, 0))
876
- xo, yo = (
877
- (self.video_frame_size[0] - thumb.width) // 2,
878
- (self.video_frame_size[1] - thumb.height) // 2,
879
- )
880
- cv_rgba.paste(thumb, (xo, yo), thumb)
881
- final_rgb_pil = Image.new("RGB", self.video_frame_size, (0, 0, 0))
882
- final_rgb_pil.paste(cv_rgba, mask=cv_rgba.split()[3])
883
- dbg_path = os.path.join(self.output_dir, f"debug_PRE_NUMPY_S{scene_num}.png")
884
- final_rgb_pil.save(dbg_path)
885
- logger.info(f"DEBUG: Saved PRE_NUMPY_S{scene_num} to {dbg_path}")
886
- frame_np = np.array(final_rgb_pil, dtype=np.uint8)
887
- if not frame_np.flags["C_CONTIGUOUS"]:
888
- frame_np = np.ascontiguousarray(frame_np, dtype=np.uint8)
889
- logger.debug(
890
- f"S{scene_num}: NumPy for MoviePy. Shape:{frame_np.shape}, DType:{frame_np.dtype}, C-Contig:{frame_np.flags['C_CONTIGUOUS']}"
891
- )
892
- if frame_np.size == 0 or frame_np.ndim != 3 or frame_np.shape[2] != 3:
893
- logger.error(f"S{scene_num}: Invalid NumPy. Skip.")
894
- continue
895
- clip_base = ImageClip(frame_np, transparent=False).set_duration(scene_dur)
896
- mvpy_dbg_path = os.path.join(self.output_dir, f"debug_MOVIEPY_FRAME_S{scene_num}.png")
897
- clip_base.save_frame(mvpy_dbg_path, t=0.1)
898
- logger.info(f"DEBUG: Saved MOVIEPY_FRAME_S{scene_num} to {mvpy_dbg_path}")
899
- clip_fx = clip_base
900
- try:
901
- es = random.uniform(1.03, 1.08)
902
- clip_fx = clip_base.fx(
903
- vfx.resize, lambda t: 1 + (es - 1) * (t / scene_dur) if scene_dur > 0 else 1
904
- ).set_position("center")
905
- except Exception as e:
906
- logger.error(f"S{scene_num} Ken Burns error: {e}", exc_info=False)
907
- current_scene_mvpy_clip = clip_fx
908
-
909
- elif asset_type == "video":
910
- src_clip = None
911
  try:
912
- src_clip = VideoFileClip(
913
- asset_path,
914
- target_resolution=(
915
- self.video_frame_size[1],
916
- self.video_frame_size[0],
917
- )
918
- if self.video_frame_size
919
- else None,
920
- audio=False,
921
- )
922
- tmp_clip = src_clip
923
- if src_clip.duration != scene_dur:
924
- if src_clip.duration > scene_dur:
925
- tmp_clip = src_clip.subclip(0, scene_dur)
926
  else:
927
- if scene_dur / src_clip.duration > 1.5 and src_clip.duration > 0.1:
928
- tmp_clip = src_clip.loop(duration=scene_dur)
929
- else:
930
- tmp_clip = src_clip.set_duration(src_clip.duration)
931
- logger.info(
932
- f"S{scene_num} Video clip ({src_clip.duration:.2f}s) shorter than target ({scene_dur:.2f}s)."
933
- )
934
- current_scene_mvpy_clip = tmp_clip.set_duration(scene_dur)
935
- if current_scene_mvpy_clip.size != list(self.video_frame_size):
936
- current_scene_mvpy_clip = current_scene_mvpy_clip.resize(self.video_frame_size)
937
- except Exception as e:
938
- logger.error(f"S{scene_num} Video load error '{asset_path}':{e}", exc_info=True)
939
- continue
940
  finally:
941
- if src_clip and src_clip is not current_scene_mvpy_clip and hasattr(src_clip, "close"):
942
- src_clip.close()
943
- else:
944
- logger.warning(f"S{scene_num} Unknown asset type '{asset_type}'. Skip.")
945
- continue
946
-
947
- if current_scene_mvpy_clip and key_action:
948
  try:
949
- to_dur = (
950
- min(current_scene_mvpy_clip.duration - 0.5, current_scene_mvpy_clip.duration * 0.8)
951
- if current_scene_mvpy_clip.duration > 0.5
952
- else current_scene_mvpy_clip.duration
953
- )
954
- to_start = 0.25
955
- if to_dur > 0:
956
- txt_c = TextClip(
957
- f"Scene {scene_num}\n{key_action}",
958
- fontsize=self.VIDEO_OVERLAY_FONT_SIZE,
959
- color=self.VIDEO_OVERLAY_FONT_COLOR,
960
- font=self.video_overlay_font,
961
- bg_color="rgba(10,10,20,0.7)",
962
- method="caption",
963
- align="West",
964
- size=(self.video_frame_size[0] * 0.9, None),
965
- kerning=-1,
966
- stroke_color="black",
967
- stroke_width=1.5,
968
- ).set_duration(to_dur).set_start(to_start).set_position(
969
- ("center", 0.92), relative=True
970
- )
971
- current_scene_mvpy_clip = CompositeVideoClip(
972
- [current_scene_mvpy_clip, txt_c], size=self.video_frame_size, use_bgclip=True
973
- )
974
- else:
975
- logger.warning(f"S{scene_num}: Text overlay duration is zero. Skip text.")
976
- except Exception as e:
977
- logger.error(f"S{scene_num} TextClip error:{e}. No text.", exc_info=True)
978
-
979
- if current_scene_mvpy_clip:
980
- processed_clips.append(current_scene_mvpy_clip)
981
- logger.info(f"S{scene_num} Processed. Dur:{current_scene_mvpy_clip.duration:.2f}s.")
982
- except Exception as e:
983
- logger.error(f"MAJOR Error S{scene_num} ({asset_path}):{e}", exc_info=True)
984
  finally:
985
- if current_scene_mvpy_clip and hasattr(current_scene_mvpy_clip, "close"):
986
- try:
987
- current_scene_mvpy_clip.close()
988
- except:
989
- pass
990
 
991
- if not processed_clips:
992
- logger.warning("No clips processed. Abort.")
993
- return None
994
-
995
- td = 0.75
996
  try:
997
- logger.info(f"Concatenating {len(processed_clips)} clips.")
998
- if len(processed_clips) > 1:
999
- final_clip = concatenate_videoclips(processed_clips, padding=-td if td > 0 else 0, method="compose")
1000
- elif processed_clips:
1001
- final_clip = processed_clips[0]
1002
- if not final_clip:
1003
- logger.error("Concatenation failed.")
1004
- return None
1005
-
1006
- logger.info(f"Concatenated dur:{final_clip.duration:.2f}s")
1007
- if td > 0 and final_clip.duration > 0:
1008
- if final_clip.duration > td * 2:
1009
- final_clip = final_clip.fx(vfx.fadein, td).fx(vfx.fadeout, td)
1010
- else:
1011
- final_clip = final_clip.fx(vfx.fadein, min(td, final_clip.duration / 2.0))
1012
-
1013
- if overall_narration_path and os.path.exists(overall_narration_path) and final_clip.duration > 0:
1014
- try:
1015
- narration_clip = AudioFileClip(overall_narration_path)
1016
- final_clip = final_clip.set_audio(narration_clip)
1017
- logger.info("Narration added.")
1018
- except Exception as e:
1019
- logger.error(f"Narration add error:{e}", exc_info=True)
1020
- elif final_clip.duration <= 0:
1021
- logger.warning("Video no duration. No audio.")
1022
-
1023
- if final_clip and final_clip.duration > 0:
1024
- op = os.path.join(self.output_dir, output_filename)
1025
- logger.info(f"Writing video:{op} (Dur:{final_clip.duration:.2f}s)")
1026
- final_clip.write_videofile(
1027
- op,
1028
- fps=fps,
1029
- codec="libx264",
1030
- preset="medium",
1031
- audio_codec="aac",
1032
- temp_audiofile=os.path.join(self.output_dir, f"temp-audio-{os.urandom(4).hex()}.m4a"),
1033
- remove_temp=True,
1034
- threads=os.cpu_count() or 2,
1035
- logger="bar",
1036
- bitrate="5000k",
1037
- ffmpeg_params=["-pix_fmt", "yuv420p"],
1038
- )
1039
- logger.info(f"Video created:{op}")
1040
- return op
1041
- else:
1042
- logger.error("Final clip invalid. No write.")
1043
- return None
1044
- except Exception as e:
1045
- logger.error(f"Video write error:{e}", exc_info=True)
1046
- return None
1047
  finally:
1048
  logger.debug("Closing all MoviePy clips in `assemble_animatic_from_assets` finally block.")
1049
- all_clips_to_close = processed_clips + ([narration_clip] if narration_clip else []) + ([final_clip] if final_clip else [])
1050
- for clip_obj_to_close in all_clips_to_close:
1051
- if clip_obj_to_close and hasattr(clip_obj_to_close, "close"):
1052
- try:
1053
- clip_obj_to_close.close()
1054
- except Exception as e_close:
1055
- logger.warning(
1056
- f"Ignoring error while closing a clip: {type(clip_obj_to_close).__name__} - {e_close}"
1057
- )
 
12
  import logging
13
 
14
  # --- MoviePy Imports ---
15
+ from moviepy.editor import (ImageClip, VideoFileClip, concatenate_videoclips, TextClip,
16
+ CompositeVideoClip, AudioFileClip)
 
 
 
 
 
 
17
  import moviepy.video.fx.all as vfx
18
 
19
  # --- MONKEY PATCH for Pillow/MoviePy compatibility ---
20
  try:
21
+ if hasattr(Image, 'Resampling') and hasattr(Image.Resampling, 'LANCZOS'): # Pillow 9+
22
+ if not hasattr(Image, 'ANTIALIAS'): Image.ANTIALIAS = Image.Resampling.LANCZOS
23
+ elif hasattr(Image, 'LANCZOS'): # Pillow 8
24
+ if not hasattr(Image, 'ANTIALIAS'): Image.ANTIALIAS = Image.LANCZOS
25
+ elif not hasattr(Image, 'ANTIALIAS'):
26
+ print("WARNING: Pillow version lacks common Resampling attributes or ANTIALIAS. MoviePy effects might fail or look different.")
 
 
 
 
27
  except Exception as e_monkey_patch:
28
+ print(f"WARNING: An unexpected error occurred during Pillow ANTIALIAS monkey-patch: {e_monkey_patch}")
 
 
29
 
30
  logger = logging.getLogger(__name__)
31
+ # logger.setLevel(logging.DEBUG) # Uncomment for very verbose debugging
 
32
 
33
  # --- External Service Client Imports ---
34
  ELEVENLABS_CLIENT_IMPORTED = False
 
38
  try:
39
  from elevenlabs.client import ElevenLabs as ImportedElevenLabsClient
40
  from elevenlabs import Voice as ImportedVoice, VoiceSettings as ImportedVoiceSettings
 
41
  ElevenLabsAPIClient = ImportedElevenLabsClient
42
  Voice = ImportedVoice
43
  VoiceSettings = ImportedVoiceSettings
44
  ELEVENLABS_CLIENT_IMPORTED = True
45
  logger.info("ElevenLabs client components imported successfully.")
46
  except ImportError:
47
+ logger.warning("ElevenLabs SDK not found (pip install elevenlabs). Audio generation will be disabled.")
 
 
48
  except Exception as e_eleven_import:
49
+ logger.warning(f"Error importing ElevenLabs client components: {e_eleven_import}. Audio generation disabled.")
 
 
50
 
51
  RUNWAYML_SDK_IMPORTED = False
52
+ RunwayMLAPIClient = None
53
  try:
54
+ from runwayml import RunwayML as ImportedRunwayMLClient
 
55
  RunwayMLAPIClient = ImportedRunwayMLClient
56
  RUNWAYML_SDK_IMPORTED = True
57
  logger.info("RunwayML SDK imported successfully.")
58
  except ImportError:
59
+ logger.warning("RunwayML SDK not found (pip install runwayml). RunwayML video generation will be disabled.")
 
 
60
  except Exception as e_runway_sdk_import:
61
+ logger.warning(f"Error importing RunwayML SDK: {e_runway_sdk_import}. RunwayML features disabled.")
 
 
62
 
63
 
64
  class VisualEngine:
65
+ DEFAULT_FONT_SIZE_PIL = 10
66
+ PREFERRED_FONT_SIZE_PIL = 20
67
  VIDEO_OVERLAY_FONT_SIZE = 30
68
+ VIDEO_OVERLAY_FONT_COLOR = 'white'
69
+ DEFAULT_MOVIEPY_FONT = 'DejaVu-Sans-Bold'
70
+ PREFERRED_MOVIEPY_FONT = 'Liberation-Sans-Bold'
 
71
 
72
+ def __init__(self, output_dir="temp_cinegen_media", default_elevenlabs_voice_id="Rachel"):
 
 
73
  self.output_dir = output_dir
74
  os.makedirs(self.output_dir, exist_ok=True)
75
+ self.font_filename_pil = "DejaVuSans-Bold.ttf"
76
+ font_paths_to_try = [ self.font_filename_pil, f"/usr/share/fonts/truetype/dejavu/{self.font_filename_pil}", f"/usr/share/fonts/truetype/liberation/LiberationSans-Bold.ttf", f"/System/Library/Fonts/Supplemental/Arial.ttf", f"C:/Windows/Fonts/arial.ttf", f"/usr/local/share/fonts/truetype/mycustomfonts/arial.ttf"]
77
+ self.font_path_pil_resolved = next((p for p in font_paths_to_try if os.path.exists(p)), None)
78
+ self.font_pil = ImageFont.load_default(); self.current_font_size_pil = self.DEFAULT_FONT_SIZE_PIL
 
 
 
 
 
 
 
 
 
 
 
 
 
79
  if self.font_path_pil_resolved:
80
+ try: self.font_pil = ImageFont.truetype(self.font_path_pil_resolved, self.PREFERRED_FONT_SIZE_PIL); self.current_font_size_pil = self.PREFERRED_FONT_SIZE_PIL; logger.info(f"Pillow font: {self.font_path_pil_resolved} sz {self.current_font_size_pil}."); self.video_overlay_font = 'DejaVu-Sans-Bold' if "dejavu" in self.font_path_pil_resolved.lower() else ('Liberation-Sans-Bold' if "liberation" in self.font_path_pil_resolved.lower() else self.DEFAULT_MOVIEPY_FONT)
81
+ except IOError as e_font_load: logger.error(f"Pillow font IOError '{self.font_path_pil_resolved}': {e_font_load}. Default.")
82
+ else: logger.warning("Custom Pillow font not found. Default.")
83
+ self.openai_api_key = None; self.USE_AI_IMAGE_GENERATION = False; self.dalle_model = "dall-e-3"; self.image_size_dalle3 = "1792x1024"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84
  self.video_frame_size = (1280, 720)
85
+ self.elevenlabs_api_key = None; self.USE_ELEVENLABS = False; self.elevenlabs_client = None; self.elevenlabs_voice_id = default_elevenlabs_voice_id
86
+ if VoiceSettings and ELEVENLABS_CLIENT_IMPORTED: self.elevenlabs_voice_settings = VoiceSettings(stability=0.60, similarity_boost=0.80, style=0.15, use_speaker_boost=True)
87
+ else: self.elevenlabs_voice_settings = None
88
+ self.pexels_api_key = None; self.USE_PEXELS = False
89
+ self.runway_api_key = None; self.USE_RUNWAYML = False; self.runway_ml_client_instance = None
90
+ if RUNWAYML_SDK_IMPORTED and RunwayMLAPIClient and os.getenv("RUNWAYML_API_SECRET"):
91
+ try: self.runway_ml_client_instance = RunwayMLAPIClient(); self.USE_RUNWAYML = True; logger.info("RunwayML Client init from env var at startup.")
92
+ except Exception as e_runway_init_startup: logger.error(f"Initial RunwayML client init failed: {e_runway_init_startup}"); self.USE_RUNWAYML = False
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93
  logger.info("VisualEngine initialized.")
94
 
95
+ def set_openai_api_key(self, api_key): self.openai_api_key = api_key; self.USE_AI_IMAGE_GENERATION = bool(api_key); logger.info(f"DALL-E status: {'Ready' if self.USE_AI_IMAGE_GENERATION else 'Disabled'}")
 
 
 
 
 
 
 
96
  def set_elevenlabs_api_key(self, api_key, voice_id_from_secret=None):
97
  self.elevenlabs_api_key = api_key
98
+ if voice_id_from_secret: self.elevenlabs_voice_id = voice_id_from_secret
 
99
  if api_key and ELEVENLABS_CLIENT_IMPORTED and ElevenLabsAPIClient:
100
+ try: self.elevenlabs_client = ElevenLabsAPIClient(api_key=api_key); self.USE_ELEVENLABS = bool(self.elevenlabs_client); logger.info(f"11L Client: {'Ready' if self.USE_ELEVENLABS else 'Failed'} (Voice: {self.elevenlabs_voice_id})")
101
+ except Exception as e: logger.error(f"11L client init error: {e}. Disabled.", exc_info=True); self.USE_ELEVENLABS=False; self.elevenlabs_client=None
102
+ else: self.USE_ELEVENLABS = False; logger.info(f"11L Disabled (key/SDK).")
103
+ def set_pexels_api_key(self, api_key): self.pexels_api_key = api_key; self.USE_PEXELS = bool(api_key); logger.info(f"Pexels status: {'Ready' if self.USE_PEXELS else 'Disabled'}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
104
  def set_runway_api_key(self, api_key):
105
+ self.runway_api_key = api_key
106
  if api_key:
107
  if RUNWAYML_SDK_IMPORTED and RunwayMLAPIClient:
108
+ if not self.runway_ml_client_instance:
109
  try:
 
 
110
  original_env_secret = os.getenv("RUNWAYML_API_SECRET")
111
+ if not original_env_secret: os.environ["RUNWAYML_API_SECRET"] = api_key; logger.info("Temp set RUNWAYML_API_SECRET for SDK.")
112
+ self.runway_ml_client_instance = RunwayMLAPIClient(); self.USE_RUNWAYML = True; logger.info("RunwayML Client init via set_runway_api_key.")
113
+ if not original_env_secret: del os.environ["RUNWAYML_API_SECRET"]; logger.info("Cleared temp RUNWAYML_API_SECRET.")
114
+ except Exception as e: logger.error(f"RunwayML Client init in set_runway_api_key fail: {e}", exc_info=True); self.USE_RUNWAYML=False;self.runway_ml_client_instance=None
115
+ else: self.USE_RUNWAYML = True; logger.info("RunwayML Client already init.")
116
+ else: logger.warning("RunwayML SDK not imported. Service disabled."); self.USE_RUNWAYML = False
117
+ else: self.USE_RUNWAYML = False; self.runway_ml_client_instance = None; logger.info("RunwayML Disabled (no API key).")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
118
 
 
119
  def _image_to_data_uri(self, image_path):
120
+ # (Implementation from before)
121
+ try: mime_type,_=mimetypes.guess_type(image_path)
122
+ if not mime_type:ext=os.path.splitext(image_path)[1].lower();mime_map={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg"};mime_type=mime_map.get(ext,"application/octet-stream");
123
+ if mime_type=="application/octet-stream":logger.warning(f"Unknown MIME for {image_path}, using {mime_type}.")
124
+ with open(image_path,"rb")as image_file:encoded_string=base64.b64encode(image_file.read()).decode('utf-8')
125
+ data_uri=f"data:{mime_type};base64,{encoded_string}";logger.debug(f"Data URI for {os.path.basename(image_path)} (start): {data_uri[:100]}...");return data_uri
126
+ except FileNotFoundError:logger.error(f"Img not found {image_path} for data URI.");return None
127
+ except Exception as e:logger.error(f"Error converting {image_path} to data URI:{e}",exc_info=True);return None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
128
 
129
  def _map_resolution_to_runway_ratio(self, width, height):
130
+ # (Implementation from before)
131
+ ratio_str=f"{width}:{height}";supported_ratios_gen4=["1280:720","720:1280","1104:832","832:1104","960:960","1584:672"];
132
+ if ratio_str in supported_ratios_gen4:return ratio_str
133
+ logger.warning(f"Res {ratio_str} not in Gen-4 list. Default 1280:720.");return "1280:720"
 
 
 
 
 
 
 
 
 
 
 
 
 
134
 
135
  def _get_text_dimensions(self, text_content, font_object):
136
+ # (Implementation from before)
137
+ dch=getattr(font_object,'size',self.current_font_size_pil);
138
+ if not text_content:return 0,dch
 
139
  try:
140
+ if hasattr(font_object,'getbbox'):bb=font_object.getbbox(text_content);w=bb[2]-bb[0];h=bb[3]-bb[1];return w,h if h>0 else dch
141
+ elif hasattr(font_object,'getsize'):w,h=font_object.getsize(text_content);return w,h if h>0 else dch
142
+ else:return int(len(text_content)*dch*0.6),int(dch*1.2)
143
+ except Exception as e:logger.warning(f"Error in _get_text_dimensions:{e}");return int(len(text_content)*self.current_font_size_pil*0.6),int(self.current_font_size_pil*1.2)
144
+
145
+ def _create_placeholder_image_content(self,text_description,filename,size=None):
146
+ # <<< CORRECTED VERSION OF THIS METHOD >>>
147
+ if size is None: size = self.video_frame_size
148
+ img = Image.new('RGB', size, color=(20, 20, 40)); d = ImageDraw.Draw(img); padding = 25
149
+ max_w = size[0] - (2 * padding); lines = []
150
+ if not text_description: text_description = "(Placeholder Image)"
151
+ words = text_description.split(); current_line_text = ""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
152
  for word_idx, word in enumerate(words):
153
  prospective_addition = word + (" " if word_idx < len(words) - 1 else "")
154
  test_line_text = current_line_text + prospective_addition
155
  current_w, _ = self._get_text_dimensions(test_line_text, self.font_pil)
156
+ if current_w == 0 and test_line_text.strip(): current_w = len(test_line_text) * (self.current_font_size_pil * 0.6)
 
157
 
158
+ if current_w <= max_w: current_line_text = test_line_text
 
159
  else:
160
+ if current_line_text.strip(): lines.append(current_line_text.strip())
161
+ current_line_text = prospective_addition
162
+ if current_line_text.strip(): lines.append(current_line_text.strip())
 
 
163
 
164
  if not lines and text_description:
165
+ avg_char_w, _ = self._get_text_dimensions("W", self.font_pil); avg_char_w = avg_char_w or (self.current_font_size_pil * 0.6)
 
166
  chars_per_line = int(max_w / avg_char_w) if avg_char_w > 0 else 20
167
+ lines.append(text_description[:chars_per_line] + ("..." if len(text_description) > chars_per_line else ""))
168
+ elif not lines: lines.append("(Placeholder Error)")
 
 
 
 
 
 
 
 
 
 
 
 
 
169
 
170
+ _, single_line_h = self._get_text_dimensions("Ay", self.font_pil); single_line_h = single_line_h if single_line_h > 0 else self.current_font_size_pil + 2
171
+ max_lines = min(len(lines), (size[1] - (2 * padding)) // (single_line_h + 2)) if single_line_h > 0 else 1
172
+ max_lines = max(1, max_lines)
173
+
174
  y_pos = padding + (size[1] - (2 * padding) - max_lines * (single_line_h + 2)) / 2.0
175
  for i in range(max_lines):
176
+ line_text = lines[i]; line_w, _ = self._get_text_dimensions(line_text, self.font_pil)
177
+ if line_w == 0 and line_text.strip(): line_w = len(line_text) * (self.current_font_size_pil * 0.6)
 
 
178
  x_pos = (size[0] - line_w) / 2.0
179
+ try: d.text((x_pos, y_pos), line_text, font=self.font_pil, fill=(200, 200, 180))
180
+ except Exception as e_draw: logger.error(f"Pillow d.text error: {e_draw} for '{line_text}'")
 
 
181
  y_pos += single_line_h + 2
182
  if i == 6 and max_lines > 7:
183
+ try: d.text((x_pos, y_pos), "...", font=self.font_pil, fill=(200, 200, 180))
184
+ except Exception as e_elip: logger.error(f"Pillow d.text ellipsis error: {e_elip}"); break
 
 
 
 
185
  filepath = os.path.join(self.output_dir, filename)
186
+ try: img.save(filepath); return filepath
187
+ except Exception as e_save: logger.error(f"Saving placeholder image '{filepath}' error: {e_save}", exc_info=True); return None
 
 
 
 
 
 
188
 
189
  def _search_pexels_image(self, query, output_filename_base):
190
+ # <<< CORRECTED VERSION OF THIS METHOD >>>
191
+ if not self.USE_PEXELS or not self.pexels_api_key: return None
 
192
  headers = {"Authorization": self.pexels_api_key}
193
  params = {"query": query, "per_page": 1, "orientation": "landscape", "size": "large2x"}
194
  base_name_for_pexels, _ = os.path.splitext(output_filename_base)
 
198
  logger.info(f"Pexels: Searching for '{query}'")
199
  effective_query = " ".join(query.split()[:5])
200
  params["query"] = effective_query
201
+ response = requests.get("https://api.pexels.com/v1/search", headers=headers, params=params, timeout=20)
 
 
202
  response.raise_for_status()
203
  data = response.json()
204
  if data.get("photos") and len(data["photos"]) > 0:
205
  photo_details = data["photos"][0]
206
  photo_url = photo_details.get("src", {}).get("large2x")
207
+ if not photo_url: logger.warning(f"Pexels: 'large2x' URL missing for '{effective_query}'. Details: {photo_details}"); return None
208
+ image_response = requests.get(photo_url, timeout=60); image_response.raise_for_status()
 
 
 
 
 
209
  img_data_pil = Image.open(io.BytesIO(image_response.content))
210
+ if img_data_pil.mode != 'RGB': img_data_pil = img_data_pil.convert('RGB')
211
+ img_data_pil.save(filepath); logger.info(f"Pexels: Image saved to {filepath}"); return filepath
212
+ else: logger.info(f"Pexels: No photos for '{effective_query}'."); return None
213
+ except requests.exceptions.RequestException as e_req: logger.error(f"Pexels: RequestException for '{query}': {e_req}", exc_info=False); return None
214
+ except Exception as e: logger.error(f"Pexels: General error for '{query}': {e}", exc_info=True); return None
215
+
216
+ def _generate_video_clip_with_runwayml(self, text_prompt_for_motion, input_image_path, scene_identifier_filename_base, target_duration_seconds=5):
217
+ # (Implementation from previous response, with Runway SDK calls)
218
+ if not self.USE_RUNWAYML or not self.runway_ml_client_instance: logger.warning("RunwayML not enabled/client not init. Skip video."); return None
219
+ if not input_image_path or not os.path.exists(input_image_path): logger.error(f"Runway Gen-4 needs input image. Path invalid: {input_image_path}"); return None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
220
  image_data_uri = self._image_to_data_uri(input_image_path)
221
+ if not image_data_uri: return None
222
+ runway_duration = 10 if target_duration_seconds >= 8 else 5
223
+ runway_ratio_str = self._map_resolution_to_runway_ratio(self.video_frame_size[0], self.video_frame_size[1])
224
+ base_name_runway, _ = os.path.splitext(scene_identifier_filename_base); output_video_filename = base_name_runway + f"_runway_gen4_d{runway_duration}s.mp4" # Corrected base name usage
 
 
 
 
 
 
 
225
  output_video_filepath = os.path.join(self.output_dir, output_video_filename)
226
+ logger.info(f"Runway Gen-4 task: motion='{text_prompt_for_motion[:100]}...', img='{os.path.basename(input_image_path)}', dur={runway_duration}s, ratio='{runway_ratio_str}'")
 
 
 
227
  try:
228
+ task_submission = self.runway_ml_client_instance.image_to_video.create(model='gen4_turbo', prompt_image=image_data_uri, prompt_text=text_prompt_for_motion, duration=runway_duration, ratio=runway_ratio_str)
229
+ task_id = task_submission.id; logger.info(f"Runway Gen-4 task ID: {task_id}. Polling...")
230
+ poll_interval=10; max_polls=36; start_poll_time = time.time()
231
+ while time.time() - start_poll_time < max_polls * poll_interval:
232
+ time.sleep(poll_interval); task_details = self.runway_ml_client_instance.tasks.retrieve(id=task_id)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
233
  logger.info(f"Runway task {task_id} status: {task_details.status}")
234
+ if task_details.status == 'SUCCEEDED':
235
+ output_url = getattr(getattr(task_details,'output',None),'url',None) or (getattr(task_details,'artifacts',None) and task_details.artifacts[0].url if task_details.artifacts and hasattr(task_details.artifacts[0],'url') else None) or (getattr(task_details,'artifacts',None) and task_details.artifacts[0].download_url if task_details.artifacts and hasattr(task_details.artifacts[0],'download_url') else None)
236
+ if not output_url: logger.error(f"Runway task {task_id} SUCCEEDED, but no output URL. Details: {vars(task_details) if hasattr(task_details,'__dict__') else task_details}"); return None
237
+ logger.info(f"Runway task {task_id} SUCCEEDED. Downloading: {output_url}")
238
+ video_response = requests.get(output_url, stream=True, timeout=300); video_response.raise_for_status()
239
+ with open(output_video_filepath,'wb') as f:
240
+ for chunk in video_response.iter_content(chunk_size=8192): f.write(chunk)
241
+ logger.info(f"Runway Gen-4 video saved: {output_video_filepath}"); return output_video_filepath
242
+ elif task_details.status in ['FAILED','ABORTED','ERROR']:
243
+ em = getattr(task_details,'error_message',None) or getattr(getattr(task_details,'output',None),'error',"Unknown Runway error.")
244
+ logger.error(f"Runway task {task_id} status: {task_details.status}. Error: {em}"); return None
245
+ logger.warning(f"Runway task {task_id} timed out."); return None
246
+ except AttributeError as ae: logger.error(f"RunwayML SDK AttrError: {ae}. SDK/methods changed?", exc_info=True); return None
247
+ except Exception as e: logger.error(f"Runway Gen-4 API error: {e}", exc_info=True); return None
248
+
249
+ def _create_placeholder_video_content(self, td, fn, dur=4, sz=None):
250
+ # (Keep as before)
251
+ if sz is None: sz = self.video_frame_size; fp = os.path.join(self.output_dir, fn); tc = None
252
+ try: tc = TextClip(td, fontsize=50, color='white', font=self.video_overlay_font, bg_color='black', size=sz, method='caption').set_duration(dur); tc.write_videofile(fp, fps=24, codec='libx264', preset='ultrafast', logger=None, threads=2); logger.info(f"Generic placeholder video: {fp}"); return fp
253
+ except Exception as e: logger.error(f"Generic placeholder video error {fp}: {e}", exc_info=True); return None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
254
  finally:
255
+ if tc and hasattr(tc, 'close'): tc.close()
 
256
 
257
+ def generate_scene_asset(self, image_generation_prompt_text, motion_prompt_text_for_video,
258
+ scene_data, scene_identifier_filename_base,
259
+ generate_as_video_clip=False, runway_target_duration=5):
260
+ # <<< THIS IS THE CORRECTED METHOD with fixed DALL-E loop >>>
 
 
 
 
 
 
 
261
  base_name, _ = os.path.splitext(scene_identifier_filename_base)
262
+ asset_info = {'path': None, 'type': 'none', 'error': True,
263
+ 'prompt_used': image_generation_prompt_text,
264
+ 'error_message': 'Asset generation init failed'}
 
 
 
 
265
  input_image_for_runway_path = None
 
266
  base_image_filename = base_name + ("_base_for_video.png" if generate_as_video_clip else ".png")
267
  base_image_filepath = os.path.join(self.output_dir, base_image_filename)
268
+
 
 
269
  if self.USE_AI_IMAGE_GENERATION and self.openai_api_key:
270
+ max_retries = 2; attempt_count_dalle = 0
271
+ for attempt_num_dalle in range(max_retries):
272
+ attempt_count_dalle = attempt_num_dalle + 1
273
+ try: # DALL-E attempt try block
274
+ logger.info(f"Attempt {attempt_count_dalle} DALL-E (base img): {image_generation_prompt_text[:70]}...")
275
+ client_oai = openai.OpenAI(api_key=self.openai_api_key, timeout=90.0)
276
+ response_oai = client_oai.images.generate(model=self.dalle_model,prompt=image_generation_prompt_text,n=1,size=self.image_size_dalle3,quality="hd",response_format="url",style="vivid")
277
+ img_url_oai = response_oai.data[0].url
278
+ revised_prompt_oai = getattr(response_oai.data[0],'revised_prompt',None)
279
+ if revised_prompt_oai: logger.info(f"DALL-E revised: {revised_prompt_oai[:70]}...")
280
+ img_response_get = requests.get(img_url_oai,timeout=120); img_response_get.raise_for_status()
281
+ pil_img_oai = Image.open(io.BytesIO(img_response_get.content))
282
+ if pil_img_oai.mode!='RGB': pil_img_oai=pil_img_oai.convert('RGB')
283
+ pil_img_oai.save(base_image_filepath); logger.info(f"DALL-E base img saved: {base_image_filepath}")
284
+ input_image_for_runway_path=base_image_filepath
285
+ asset_info={'path':base_image_filepath,'type':'image','error':False,'prompt_used':image_generation_prompt_text,'revised_prompt':revised_prompt_oai}
286
+ break # Success, exit loop
287
+ except openai.RateLimitError as e_rl: logger.warning(f"OpenAI RateLimit Att {attempt_count_dalle}:{e_rl}.Retry...");time.sleep(5*attempt_count_dalle);asset_info['error_message']=str(e_rl)
288
+ except openai.APIError as e_api_oai: logger.error(f"OpenAI APIError Att {attempt_count_dalle}:{e_api_oai}");asset_info['error_message']=str(e_api_oai);break
289
+ except requests.exceptions.RequestException as e_req_oai: logger.error(f"Requests Err DALL-E Att {attempt_count_dalle}:{e_req_oai}");asset_info['error_message']=str(e_req_oai);break
290
+ except Exception as e_gen_oai: logger.error(f"General DALL-E Err Att {attempt_count_dalle}:{e_gen_oai}",exc_info=True);asset_info['error_message']=str(e_gen_oai);break
291
+ if asset_info['error']: logger.warning(f"DALL-E failed after {attempt_count_dalle} attempts for base img.")
292
+
293
+ if asset_info['error'] and self.USE_PEXELS:
294
+ logger.info("Trying Pexels for base img.");pqt=scene_data.get('pexels_search_query_감독',f"{scene_data.get('emotional_beat','')} {scene_data.get('setting_description','')}");pp=self._search_pexels_image(pqt,base_image_filename);
295
+ if pp:input_image_for_runway_path=pp;asset_info={'path':pp,'type':'image','error':False,'prompt_used':f"Pexels:{pqt}"}
296
+ else:current_em=asset_info.get('error_message',"");asset_info['error_message']=(current_em+" Pexels failed for base.").strip()
297
+
298
+ if asset_info['error']:
299
+ logger.warning("Base img (DALL-E/Pexels) failed. Using placeholder.");ppt=asset_info.get('prompt_used',image_generation_prompt_text);php=self._create_placeholder_image_content(f"[Base Placeholder]{ppt[:70]}...",base_image_filename);
300
+ if php:input_image_for_runway_path=php;asset_info={'path':php,'type':'image','error':False,'prompt_used':ppt}
301
+ else:current_em=asset_info.get('error_message',"");asset_info['error_message']=(current_em+" Base placeholder failed.").strip()
 
 
 
 
 
 
 
 
 
 
 
 
 
302
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
303
  if generate_as_video_clip:
304
+ if not input_image_for_runway_path:logger.error("RunwayML video: base img failed.");asset_info['error']=True;asset_info['error_message']=(asset_info.get('error_message',"")+" Base img miss, Runway abort.").strip();asset_info['type']='none';return asset_info
 
 
 
 
 
 
 
 
305
  if self.USE_RUNWAYML:
306
+ video_path=self._generate_video_clip_with_runwayml(motion_prompt_text_for_video,input_image_for_runway_path,base_name,runway_target_duration)
307
+ if video_path and os.path.exists(video_path):asset_info={'path':video_path,'type':'video','error':False,'prompt_used':motion_prompt_text_for_video,'base_image_path':input_image_for_runway_path}
308
+ else:logger.warning(f"RunwayML video failed for {base_name}. Fallback to base img.");asset_info['error']=True;asset_info['error_message']=(asset_info.get('error_message',"Base img ok.")+" RunwayML video fail; use base img.").strip();asset_info['path']=input_image_for_runway_path;asset_info['type']='image';asset_info['prompt_used']=image_generation_prompt_text
309
+ else:logger.warning("RunwayML selected but disabled. Use base img.");asset_info['error']=True;asset_info['error_message']=(asset_info.get('error_message',"Base img ok.")+" RunwayML disabled; use base img.").strip();asset_info['path']=input_image_for_runway_path;asset_info['type']='image';asset_info['prompt_used']=image_generation_prompt_text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
310
  return asset_info
311
 
312
  def generate_narration_audio(self, text_to_narrate, output_filename="narration_overall.mp3"):
313
+ # (Keep as before)
314
+ if not self.USE_ELEVENLABS or not self.elevenlabs_client or not text_to_narrate: logger.info("11L skip."); return None; afp=os.path.join(self.output_dir,output_filename)
315
+ try: logger.info(f"11L audio (Voice:{self.elevenlabs_voice_id}): {text_to_narrate[:70]}..."); asm=None
316
+ if hasattr(self.elevenlabs_client,'text_to_speech')and hasattr(self.elevenlabs_client.text_to_speech,'stream'):asm=self.elevenlabs_client.text_to_speech.stream;logger.info("Using 11L .text_to_speech.stream()")
317
+ elif hasattr(self.elevenlabs_client,'generate_stream'):asm=self.elevenlabs_client.generate_stream;logger.info("Using 11L .generate_stream()")
318
+ elif hasattr(self.elevenlabs_client,'generate'):logger.info("Using 11L .generate()");vp=Voice(voice_id=str(self.elevenlabs_voice_id),settings=self.elevenlabs_voice_settings)if Voice and self.elevenlabs_voice_settings else str(self.elevenlabs_voice_id);ab=self.elevenlabs_client.generate(text=text_to_narrate,voice=vp,model="eleven_multilingual_v2");
319
+ with open(afp,"wb")as f:f.write(ab);logger.info(f"11L audio (non-stream): {afp}");return afp
320
+ else:logger.error("No 11L audio method.");return None
321
+ if asm:vps={"voice_id":str(self.elevenlabs_voice_id)}
322
+ if self.elevenlabs_voice_settings:
323
+ if hasattr(self.elevenlabs_voice_settings,'model_dump'):vps["voice_settings"]=self.elevenlabs_voice_settings.model_dump()
324
+ elif hasattr(self.elevenlabs_voice_settings,'dict'):vps["voice_settings"]=self.elevenlabs_voice_settings.dict()
325
+ else:vps["voice_settings"]=self.elevenlabs_voice_settings
326
+ adi=asm(text=text_to_narrate,model_id="eleven_multilingual_v2",**vps)
327
+ with open(afp,"wb")as f:
328
+ for c_chunk in adi: # Renamed c to c_chunk
329
+ if c_chunk:f.write(c_chunk)
330
+ logger.info(f"11L audio (stream): {afp}");return afp
331
+ except Exception as e_11l:logger.error(f"11L audio error: {e_11l}",exc_info=True);return None # Renamed e to e_11l
332
+
333
+ def assemble_animatic_from_assets(self, asset_data_list, overall_narration_path=None, output_filename="final_video.mp4", fps=24):
334
+ # (Keep as in the version with robust image processing, C-contiguous array, debug saves, and pix_fmt)
335
+ if not asset_data_list: logger.warning("No assets for animatic."); return None
336
+ processed_clips = []; narration_clip_mvpy = None; final_composite_video_clip = None # Renamed variables
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
337
  logger.info(f"Assembling from {len(asset_data_list)} assets. Frame: {self.video_frame_size}.")
338
+ for i, asset_info_dict in enumerate(asset_data_list): # Renamed asset_info to asset_info_dict
339
+ asset_p, asset_t, scene_d = asset_info_dict.get('path'), asset_info_dict.get('type'), asset_info_dict.get('duration', 4.5)
340
+ scene_n, key_act = asset_info_dict.get('scene_num', i + 1), asset_info_dict.get('key_action', '')
341
+ logger.info(f"S{scene_n}: Path='{asset_p}', Type='{asset_t}', Dur='{scene_d}'s")
342
+ if not (asset_p and os.path.exists(asset_p)): logger.warning(f"S{scene_n}: Not found '{asset_p}'. Skip."); continue
343
+ if scene_d <= 0: logger.warning(f"S{scene_n}: Invalid duration ({scene_d}s). Skip."); continue
344
+ current_scene_clip_mvpy = None # Renamed current_scene_mvpy_clip
 
 
 
 
 
 
 
 
 
 
345
  try:
346
+ if asset_t == 'image':
347
+ # ... (Robust image processing logic from previous full version) ...
348
+ pil_img_opened = Image.open(asset_p); logger.debug(f"S{scene_n}: Loaded img. Mode:{pil_img_opened.mode}, Size:{pil_img_opened.size}")
349
+ img_rgba_converted = pil_img_opened.convert('RGBA') if pil_img_opened.mode != 'RGBA' else pil_img_opened.copy()
350
+ thumb_img = img_rgba_converted.copy(); res_filter = Image.Resampling.LANCZOS if hasattr(Image.Resampling,'LANCZOS') else Image.BILINEAR; thumb_img.thumbnail(self.video_frame_size,res_filter)
351
+ canvas_for_rgba = Image.new('RGBA',self.video_frame_size,(0,0,0,0)); x_offset,y_offset=(self.video_frame_size[0]-thumb_img.width)//2,(self.video_frame_size[1]-thumb_img.height)//2
352
+ canvas_for_rgba.paste(thumb_img,(x_offset,y_offset),thumb_img)
353
+ final_rgb_for_pil = Image.new("RGB",self.video_frame_size,(0,0,0)); final_rgb_for_pil.paste(canvas_for_rgba,mask=canvas_for_rgba.split()[3])
354
+ debug_path_pre_numpy = os.path.join(self.output_dir,f"debug_PRE_NUMPY_S{scene_n}.png"); final_rgb_for_pil.save(debug_path_pre_numpy); logger.info(f"DEBUG: Saved PRE_NUMPY_S{scene_n} to {debug_path_pre_numpy}")
355
+ numpy_frame = np.array(final_rgb_for_pil,dtype=np.uint8);
356
+ if not numpy_frame.flags['C_CONTIGUOUS']: numpy_frame=np.ascontiguousarray(numpy_frame,dtype=np.uint8)
357
+ logger.debug(f"S{scene_n}: NumPy for MoviePy. Shape:{numpy_frame.shape}, DType:{numpy_frame.dtype}, C-Contig:{numpy_frame.flags['C_CONTIGUOUS']}")
358
+ if numpy_frame.size==0 or numpy_frame.ndim!=3 or numpy_frame.shape[2]!=3: logger.error(f"S{scene_n}: Invalid NumPy. Skip."); continue
359
+ image_clip_base = ImageClip(numpy_frame,transparent=False).set_duration(scene_d)
360
+ moviepy_debug_frame_save_path=os.path.join(self.output_dir,f"debug_MOVIEPY_FRAME_S{scene_n}.png"); image_clip_base.save_frame(moviepy_debug_frame_save_path,t=0.1); logger.info(f"DEBUG: Saved MOVIEPY_FRAME_S{scene_n} to {moviepy_debug_frame_save_path}")
361
+ image_clip_with_fx = image_clip_base
362
+ try: end_scale_kb=random.uniform(1.03,1.08); image_clip_with_fx=image_clip_base.fx(vfx.resize,lambda time_t:1+(end_scale_kb-1)*(time_t/scene_d) if scene_d>0 else 1).set_position('center')
363
+ except Exception as e_kb: logger.error(f"S{scene_n} Ken Burns error: {e_kb}",exc_info=False)
364
+ current_scene_mvpy_clip = image_clip_with_fx
365
+ elif asset_t == 'video':
366
+ # ... (Video processing logic from previous full version) ...
367
+ source_video_file_clip=None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
368
  try:
369
+ source_video_file_clip=VideoFileClip(asset_p,target_resolution=(self.video_frame_size[1],self.video_frame_size[0])if self.video_frame_size else None, audio=False)
370
+ temp_video_clip_obj=source_video_file_clip
371
+ if source_video_file_clip.duration!=scene_d:
372
+ if source_video_file_clip.duration>scene_d:temp_video_clip_obj=source_video_file_clip.subclip(0,scene_d)
 
 
 
 
 
 
 
 
 
 
373
  else:
374
+ if scene_d/source_video_file_clip.duration > 1.5 and source_video_file_clip.duration>0.1:temp_video_clip_obj=source_video_file_clip.loop(duration=scene_d)
375
+ else:temp_video_clip_obj=source_video_file_clip.set_duration(source_video_file_clip.duration);logger.info(f"S{scene_n} Video clip ({source_video_file_clip.duration:.2f}s) shorter than target ({scene_d:.2f}s).")
376
+ current_scene_mvpy_clip=temp_video_clip_obj.set_duration(scene_d)
377
+ if current_scene_mvpy_clip.size!=list(self.video_frame_size):current_scene_mvpy_clip=current_scene_mvpy_clip.resize(self.video_frame_size)
378
+ except Exception as e_vidload:logger.error(f"S{scene_n} Video load error '{asset_p}':{e_vidload}",exc_info=True);continue
 
 
 
 
 
 
 
 
379
  finally:
380
+ if source_video_file_clip and source_video_file_clip is not current_scene_mvpy_clip and hasattr(source_video_file_clip,'close'):source_video_file_clip.close()
381
+ else: logger.warning(f"S{scene_n} Unknown asset type '{asset_t}'. Skip."); continue
382
+
383
+ if current_scene_mvpy_clip and key_act: # Text Overlay
 
 
 
384
  try:
385
+ text_overlay_dur=min(current_scene_mvpy_clip.duration-0.5,current_scene_mvpy_clip.duration*0.8)if current_scene_mvpy_clip.duration>0.5 else current_scene_mvpy_clip.duration
386
+ text_overlay_s_time=0.25
387
+ if text_overlay_dur > 0:
388
+ text_clip_obj=TextClip(f"Scene {scene_n}\n{key_act}",fontsize=self.VIDEO_OVERLAY_FONT_SIZE,color=self.VIDEO_OVERLAY_FONT_COLOR,font=self.video_overlay_font,bg_color='rgba(10,10,20,0.7)',method='caption',align='West',size=(self.video_frame_size[0]*0.9,None),kerning=-1,stroke_color='black',stroke_width=1.5).set_duration(text_overlay_dur).set_start(text_overlay_s_time).set_position(('center',0.92),relative=True)
389
+ current_scene_mvpy_clip=CompositeVideoClip([current_scene_mvpy_clip,text_clip_obj],size=self.video_frame_size,use_bgclip=True)
390
+ else: logger.warning(f"S{scene_n}: Text overlay duration zero. Skip text.")
391
+ except Exception as e_txtclip:logger.error(f"S{scene_n} TextClip error:{e_txtclip}. No text.",exc_info=True)
392
+ if current_scene_mvpy_clip:processed_clips.append(current_scene_mvpy_clip);logger.info(f"S{scene_n} Processed. Dur:{current_scene_mvpy_clip.duration:.2f}s.")
393
+ except Exception as e_asset_loop:logger.error(f"MAJOR Error S{scene_n} ({asset_p}):{e_asset_loop}",exc_info=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
394
  finally:
395
+ if current_scene_mvpy_clip and hasattr(current_scene_mvpy_clip,'close'):
396
+ try: current_scene_mvpy_clip.close()
397
+ except: pass
 
 
398
 
399
+ if not processed_clips:logger.warning("No clips processed. Abort.");return None
400
+ transition_val=0.75
 
 
 
401
  try:
402
+ logger.info(f"Concatenating {len(processed_clips)} clips.");
403
+ if len(processed_clips)>1:final_composite_video_clip=concatenate_videoclips(processed_clips,padding=-transition_val if transition_val>0 else 0,method="compose")
404
+ elif processed_clips:final_composite_video_clip=processed_clips[0]
405
+ if not final_composite_video_clip:logger.error("Concatenation failed.");return None
406
+ logger.info(f"Concatenated dur:{final_composite_video_clip.duration:.2f}s")
407
+ if transition_val>0 and final_composite_video_clip.duration>0:
408
+ if final_composite_video_clip.duration>transition_val*2:final_composite_video_clip=final_composite_video_clip.fx(vfx.fadein,transition_val).fx(vfx.fadeout,transition_val)
409
+ else:final_composite_video_clip=final_composite_video_clip.fx(vfx.fadein,min(transition_val,final_composite_video_clip.duration/2.0))
410
+ if overall_narration_path and os.path.exists(overall_narration_path) and final_composite_video_clip.duration>0:
411
+ try:narration_clip_mvpy=AudioFileClip(overall_narration_path);final_composite_video_clip=final_composite_video_clip.set_audio(narration_clip_mvpy);logger.info("Narration added.")
412
+ except Exception as e_narr:logger.error(f"Narration add error:{e_narr}",exc_info=True)
413
+ elif final_composite_video_clip.duration<=0:logger.warning("Video no duration. No audio.")
414
+ if final_composite_video_clip and final_composite_video_clip.duration>0:
415
+ output_vid_path=os.path.join(self.output_dir,output_filename);logger.info(f"Writing video:{output_vid_path} (Dur:{final_composite_video_clip.duration:.2f}s)")
416
+ final_composite_video_clip.write_videofile(output_vid_path,fps=fps,codec='libx264',preset='medium',audio_codec='aac',temp_audiofile=os.path.join(self.output_dir,f'temp-audio-{os.urandom(4).hex()}.m4a'),remove_temp=True,threads=os.cpu_count()or 2,logger='bar',bitrate="5000k",ffmpeg_params=["-pix_fmt", "yuv420p"])
417
+ logger.info(f"Video created:{output_vid_path}");return output_vid_path
418
+ else:logger.error("Final clip invalid. No write.");return None
419
+ except Exception as e_vid_write:logger.error(f"Video write error:{e_vid_write}",exc_info=True);return None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
420
  finally:
421
  logger.debug("Closing all MoviePy clips in `assemble_animatic_from_assets` finally block.")
422
+ all_clips_to_close_list = processed_clips + ([narration_clip_mvpy] if narration_clip_mvpy else []) + ([final_composite_video_clip] if final_composite_video_clip else [])
423
+ for clip_to_close_item in all_clips_to_close_list:
424
+ if clip_to_close_item and hasattr(clip_to_close_item, 'close'):
425
+ try: clip_to_close_item.close()
426
+ except Exception as e_final_close: logger.warning(f"Ignoring error while closing a clip: {type(clip_to_close_item).__name__} - {e_final_close}")