Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
elebumm
GitHub Repository: elebumm/RedditVideoMakerBot
Path: blob/master/utils/imagenarator.py
327 views
1
import os
2
import re
3
import textwrap
4
5
from PIL import Image, ImageDraw, ImageFont
6
from rich.progress import track
7
8
from TTS.engine_wrapper import process_text
9
from utils.fonts import getheight, getsize
10
11
12
def draw_multiple_line_text(
13
image, text, font, text_color, padding, wrap=50, transparent=False
14
) -> None:
15
"""
16
Draw multiline text over given image
17
"""
18
draw = ImageDraw.Draw(image)
19
font_height = getheight(font, text)
20
image_width, image_height = image.size
21
lines = textwrap.wrap(text, width=wrap)
22
y = (image_height / 2) - (((font_height + (len(lines) * padding) / len(lines)) * len(lines)) / 2)
23
for line in lines:
24
line_width, line_height = getsize(font, line)
25
if transparent:
26
shadowcolor = "black"
27
for i in range(1, 5):
28
draw.text(
29
((image_width - line_width) / 2 - i, y - i),
30
line,
31
font=font,
32
fill=shadowcolor,
33
)
34
draw.text(
35
((image_width - line_width) / 2 + i, y - i),
36
line,
37
font=font,
38
fill=shadowcolor,
39
)
40
draw.text(
41
((image_width - line_width) / 2 - i, y + i),
42
line,
43
font=font,
44
fill=shadowcolor,
45
)
46
draw.text(
47
((image_width - line_width) / 2 + i, y + i),
48
line,
49
font=font,
50
fill=shadowcolor,
51
)
52
draw.text(((image_width - line_width) / 2, y), line, font=font, fill=text_color)
53
y += line_height + padding
54
55
56
def imagemaker(theme, reddit_obj: dict, txtclr, padding=5, transparent=False) -> None:
57
"""
58
Render Images for video
59
"""
60
texts = reddit_obj["thread_post"]
61
id = re.sub(r"[^\w\s-]", "", reddit_obj["thread_id"])
62
63
if transparent:
64
font = ImageFont.truetype(os.path.join("fonts", "Roboto-Bold.ttf"), 100)
65
else:
66
font = ImageFont.truetype(os.path.join("fonts", "Roboto-Regular.ttf"), 100)
67
size = (1920, 1080)
68
69
image = Image.new("RGBA", size, theme)
70
71
for idx, text in track(enumerate(texts), "Rendering Image"):
72
image = Image.new("RGBA", size, theme)
73
text = process_text(text, False)
74
draw_multiple_line_text(image, text, font, txtclr, padding, wrap=30, transparent=transparent)
75
image.save(f"assets/temp/{id}/png/img{idx}.png")
76
77