antonelli commited on
Commit
ed56c60
·
1 Parent(s): e33689b
Files changed (1) hide show
  1. video_generator.py +19 -9
video_generator.py CHANGED
@@ -2,31 +2,41 @@ from PIL import Image, ImageDraw, ImageFont
2
  import cv2
3
  import numpy as np
4
 
 
 
5
  def generate_lyric_frame(lyric, image_size):
6
  # If image_size is None, provide a default value
7
  if image_size is None:
8
  image_size = (800, 600) # Example default size, you can change this
9
 
10
  # Ensure image_size is a tuple
11
- if not isinstance(image_size, tuple):
12
- image_size = tuple(image_size)
13
 
14
  image = Image.new('RGB', image_size, color='black')
15
  draw = ImageDraw.Draw(image)
16
 
17
- # Define font and text alignment
18
  font = ImageFont.load_default()
19
- text_width = draw.textlength(lyric, font=font) # Getting text width
20
 
21
- # Getting text height, with a check for empty text
22
- text_bbox = font.getmask(lyric).getbbox()
23
- text_height = text_bbox[3] if text_bbox else 0
 
24
 
 
 
 
 
 
25
  text_x = (image_size[0] - text_width) / 2
26
  text_y = (image_size[1] - text_height) / 2
27
 
28
- # Draw the text on the image
29
- draw.text((text_x, text_y), lyric, font=font, fill='white')
 
 
 
 
30
  return image
31
 
32
  def generate_video(lyrics_with_timing, image_size=(800, 600), frame_rate=30):
 
2
  import cv2
3
  import numpy as np
4
 
5
+ import textwrap
6
+
7
  def generate_lyric_frame(lyric, image_size):
8
  # If image_size is None, provide a default value
9
  if image_size is None:
10
  image_size = (800, 600) # Example default size, you can change this
11
 
12
  # Ensure image_size is a tuple
13
+ image_size = tuple(image_size)
 
14
 
15
  image = Image.new('RGB', image_size, color='black')
16
  draw = ImageDraw.Draw(image)
17
 
18
+ # Use PIL's default font
19
  font = ImageFont.load_default()
 
20
 
21
+ # Wrap text
22
+ max_width = image_size[0] - 40 # Keeping 20 pixels margin on each side
23
+ wrapped_text = textwrap.fill(lyric, width=40)
24
+ lines = wrapped_text.split('\n')
25
 
26
+ # Calculate text width and height
27
+ text_width = max(draw.textlength(line, font=font) for line in lines) # Corrected line here
28
+ text_height = sum([font.getmask(line).getbbox()[3] for line in lines if font.getmask(line).getbbox()]) # Corrected line here
29
+
30
+ # Calculate starting coordinates to center the text block
31
  text_x = (image_size[0] - text_width) / 2
32
  text_y = (image_size[1] - text_height) / 2
33
 
34
+ # Draw the wrapped text on the image
35
+ y = text_y
36
+ for line in lines:
37
+ draw.text((text_x, y), line, font=font, fill='white')
38
+ y += font.getmask(line).getbbox()[3] if font.getmask(line).getbbox() else 0 # Corrected line here
39
+
40
  return image
41
 
42
  def generate_video(lyrics_with_timing, image_size=(800, 600), frame_rate=30):