mgbam commited on
Commit
b97795f
·
verified ·
1 Parent(s): 49a94ff

Update core/visual_engine.py

Browse files
Files changed (1) hide show
  1. core/visual_engine.py +107 -23
core/visual_engine.py CHANGED
@@ -8,48 +8,132 @@ class VisualEngine:
8
  self.output_dir = output_dir
9
  os.makedirs(self.output_dir, exist_ok=True)
10
  try:
11
- # Try to load a common font, adjust path or font name if needed
12
- self.font = ImageFont.truetype("arial.ttf", 24)
 
 
 
 
 
13
  except IOError:
14
- self.font = ImageFont.load_default() # Fallback
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
 
16
  def create_placeholder_image(self, text_description, filename, size=(1280, 720)):
17
- img = Image.new('RGB', size, color = (73, 109, 137)) # Blueish background
18
- d = ImageDraw.Draw(img)
19
-
20
- # Simple text wrapping
 
21
  lines = []
22
  words = text_description.split()
23
  current_line = ""
 
24
  for word in words:
25
- if d.textlength(current_line + word + " ", font=self.font) <= size[0] - 40: # 20px padding
26
- current_line += word + " "
 
 
 
27
  else:
28
- lines.append(current_line)
29
  current_line = word + " "
30
- lines.append(current_line)
 
 
 
 
 
 
31
 
32
- y_text = (size[1] - len(lines) * (self.font.size + 5)) / 2 # Center text block vertically
 
 
 
33
  for line in lines:
34
- text_width = d.textlength(line, font=self.font)
35
- d.text((size[0]-text_width)/2, y_text, line, fill=(255,255,0), font=self.font)
36
- y_text += self.font.size + 5 # Line spacing
 
 
 
 
 
 
 
 
37
 
38
  filepath = os.path.join(self.output_dir, filename)
39
- img.save(filepath)
 
 
 
 
 
40
  return filepath
41
 
 
42
  def create_video_from_images(self, image_paths, output_filename="final_video.mp4", fps=1, duration_per_image=3):
43
  if not image_paths:
44
  print("No images provided to create video.")
45
  return None
46
 
47
- clips = [ImageClip(m).set_duration(duration_per_image) for m in image_paths]
48
- if not clips:
49
- print("Could not create ImageClips.")
50
  return None
 
 
 
 
 
 
 
 
 
 
 
51
 
52
- video_clip = concatenate_videoclips(clips, method="compose")
53
- output_path = os.path.join(self.output_dir, output_filename)
54
- video_clip.write_videofile(output_path, fps=fps)
55
- return output_path
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
  self.output_dir = output_dir
9
  os.makedirs(self.output_dir, exist_ok=True)
10
  try:
11
+ # Try to load Arial font. Ensure it's installed in your Docker image.
12
+ # Common paths: "arial.ttf", "/usr/share/fonts/truetype/msttcorefonts/Arial.ttf"
13
+ # If using a custom font, ensure you COPY it into the Docker image and provide the correct path.
14
+ self.font_path = "arial.ttf" # This assumes Arial is in a standard font path or current dir
15
+ self.font_size_pil = 24 # For Pillow text drawing
16
+ self.font = ImageFont.truetype(self.font_path, self.font_size_pil)
17
+ print(f"Successfully loaded font: {self.font_path} with size {self.font_size_pil}")
18
  except IOError:
19
+ print(f"Warning: Could not load font '{self.font_path}'. Falling back to default font.")
20
+ self.font = ImageFont.load_default()
21
+ self.font_size_pil = 10 # Default font is smaller, adjust size for calculations
22
+
23
+
24
+ def _get_text_dimensions(self, text_content, font_obj):
25
+ """
26
+ Gets the width and height of a single line of text with the given font.
27
+ Returns (width, height).
28
+ """
29
+ if hasattr(font_obj, 'getbbox'): # For newer Pillow versions (>=8.0.0)
30
+ # getbbox returns (left, top, right, bottom)
31
+ bbox = font_obj.getbbox(text_content)
32
+ width = bbox[2] - bbox[0]
33
+ height = bbox[3] - bbox[1]
34
+ return width, height
35
+ elif hasattr(font_obj, 'getsize'): # For older Pillow versions
36
+ return font_obj.getsize(text_content)
37
+ else: # Fallback for very basic font objects (like default font)
38
+ # Estimate: average char width * num_chars, fixed height
39
+ # This is a rough estimate.
40
+ avg_char_width = self.font_size_pil * 0.6
41
+ height_estimate = self.font_size_pil * 1.2
42
+ return int(len(text_content) * avg_char_width), int(height_estimate)
43
+
44
 
45
  def create_placeholder_image(self, text_description, filename, size=(1280, 720)):
46
+ img = Image.new('RGB', size, color=(73, 109, 137)) # Blueish background
47
+ draw = ImageDraw.Draw(img)
48
+
49
+ padding = 40
50
+ max_text_width = size[0] - (2 * padding)
51
  lines = []
52
  words = text_description.split()
53
  current_line = ""
54
+
55
  for word in words:
56
+ test_line = current_line + word + " "
57
+ line_width, _ = self._get_text_dimensions(test_line.strip(), self.font)
58
+
59
+ if line_width <= max_text_width:
60
+ current_line = test_line
61
  else:
62
+ lines.append(current_line.strip())
63
  current_line = word + " "
64
+ lines.append(current_line.strip()) # Add the last line
65
+
66
+ # Calculate starting y position to center the text block
67
+ # Use the height from the first line as an estimate for line height
68
+ _, single_line_height = self._get_text_dimensions("Tg", self.font) # Get height of a typical line
69
+ line_spacing_factor = 1.2 # Adjust for spacing between lines
70
+ total_text_height = len(lines) * single_line_height * line_spacing_factor
71
 
72
+ y_text = (size[1] - total_text_height) / 2
73
+ if y_text < padding: # Ensure text doesn't start too high if too much text
74
+ y_text = padding
75
+
76
  for line in lines:
77
+ line_width, _ = self._get_text_dimensions(line, self.font)
78
+ x_text = (size[0] - line_width) / 2
79
+
80
+ # Corrected ImageDraw.text() call with explicit keyword arguments
81
+ draw.text(
82
+ xy=(x_text, y_text),
83
+ text=line,
84
+ fill=(255, 255, 0), # Yellow text
85
+ font=self.font
86
+ )
87
+ y_text += single_line_height * line_spacing_factor
88
 
89
  filepath = os.path.join(self.output_dir, filename)
90
+ try:
91
+ img.save(filepath)
92
+ print(f"Placeholder image saved: {filepath}")
93
+ except Exception as e:
94
+ print(f"Error saving image {filepath}: {e}")
95
+ return None
96
  return filepath
97
 
98
+
99
  def create_video_from_images(self, image_paths, output_filename="final_video.mp4", fps=1, duration_per_image=3):
100
  if not image_paths:
101
  print("No images provided to create video.")
102
  return None
103
 
104
+ valid_image_paths = [p for p in image_paths if p and os.path.exists(p)]
105
+ if not valid_image_paths:
106
+ print("No valid image paths found to create video.")
107
  return None
108
+
109
+ print(f"Creating video from images: {valid_image_paths}")
110
+
111
+ try:
112
+ clips = [ImageClip(m).set_duration(duration_per_image) for m in valid_image_paths]
113
+ if not clips:
114
+ print("Could not create ImageClips from the provided image paths.")
115
+ return None
116
+
117
+ video_clip = concatenate_videoclips(clips, method="compose")
118
+ output_path = os.path.join(self.output_dir, output_filename)
119
 
120
+ # Using recommended parameters for write_videofile, especially in headless environments
121
+ video_clip.write_videofile(
122
+ output_path,
123
+ fps=fps,
124
+ codec='libx264', # A common and good codec
125
+ audio_codec='aac', # If you ever add audio
126
+ temp_audiofile='temp-audio.m4a', # For temporary audio processing
127
+ remove_temp=True, # Clean up temporary audio file
128
+ threads=os.cpu_count() or 2, # Use available CPUs or default to 2
129
+ logger=None # Suppress verbose ffmpeg output, use 'bar' for progress
130
+ )
131
+ print(f"Video successfully created: {output_path}")
132
+ return output_path
133
+ except Exception as e:
134
+ print(f"Error creating video: {e}")
135
+ # Print more details if it's an OSError, which can happen with ffmpeg issues
136
+ if isinstance(e, OSError):
137
+ print("OSError during video creation. This often indicates an issue with ffmpeg.")
138
+ print("Ensure ffmpeg is correctly installed and accessible in the environment PATH.")
139
+ return None