andreinigo commited on
Commit
0d7789c
·
1 Parent(s): 2c75d59

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +14 -8
app.py CHANGED
@@ -42,14 +42,20 @@ def generate_caption(image):
42
  font_size = 60
43
  font = ImageFont.truetype("impact.ttf", font_size)
44
 
45
- # Calculate the width for text wrap
46
- wrap_width = len(meme_text) // 2
47
-
48
- # Wrap the text to fit within the image width and have a maximum of 2 lines
49
- wrapped_text = textwrap.wrap(meme_text, width=wrap_width)
50
- text_lines = wrapped_text
51
-
52
- y = 10
 
 
 
 
 
 
53
  for line in text_lines:
54
  line_width = draw.textlength(line, font=font)
55
  line_mask = font.getmask(line)
 
42
  font_size = 60
43
  font = ImageFont.truetype("impact.ttf", font_size)
44
 
45
+ # Calculate the average character width for the font
46
+ alphabet = "ABCEMOPQRSTWXZ"
47
+ total_char_width = sum(draw.textlength(char, font=font) for char in alphabet)
48
+ average_char_width = total_char_width / len(alphabet)
49
+
50
+ # Calculate the number of characters that fit within the image width
51
+ chars_per_line = int(pil_image.width / average_char_width)
52
+
53
+ # Wrap the text to fit within the image width
54
+ wrapped_text = textwrap.fill(meme_text, width=chars_per_line)
55
+
56
+ # Calculate the position to place the text at the top and center horizontally
57
+ text_lines = wrapped_text.split('\n')
58
+ y = 10 # Adjust this value to add more or less padding from the top
59
  for line in text_lines:
60
  line_width = draw.textlength(line, font=font)
61
  line_mask = font.getmask(line)