Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
elebumm
GitHub Repository: elebumm/RedditVideoMakerBot
Path: blob/master/utils/imagenarator.py
493 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
from utils.id import extract_id
11
12
13
def draw_multiple_line_text(
14
image, text, font, text_color, padding, wrap=50, transparent=False
15
) -> None:
16
"""
17
Draw multiline text over given image
18
"""
19
draw = ImageDraw.Draw(image)
20
font_height = getheight(font, text)
21
image_width, image_height = image.size
22
lines = textwrap.wrap(text, width=wrap)
23
y = (image_height / 2) - (((font_height + (len(lines) * padding) / len(lines)) * len(lines)) / 2)
24
for line in lines:
25
line_width, line_height = getsize(font, line)
26
if transparent:
27
shadowcolor = "black"
28
for i in range(1, 5):
29
draw.text(
30
((image_width - line_width) / 2 - i, y - i),
31
line,
32
font=font,
33
fill=shadowcolor,
34
)
35
draw.text(
36
((image_width - line_width) / 2 + i, y - i),
37
line,
38
font=font,
39
fill=shadowcolor,
40
)
41
draw.text(
42
((image_width - line_width) / 2 - i, y + i),
43
line,
44
font=font,
45
fill=shadowcolor,
46
)
47
draw.text(
48
((image_width - line_width) / 2 + i, y + i),
49
line,
50
font=font,
51
fill=shadowcolor,
52
)
53
draw.text(((image_width - line_width) / 2, y), line, font=font, fill=text_color)
54
y += line_height + padding
55
56
57
def imagemaker(theme, reddit_obj: dict, txtclr, padding=5, transparent=False) -> None:
58
"""
59
Render Images for video
60
"""
61
texts = reddit_obj["thread_post"]
62
reddit_id = extract_id(reddit_obj)
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
68
size = (1920, 1080)
69
70
for idx, text in track(enumerate(texts), "Rendering Image"):
71
image = Image.new("RGBA", size, theme)
72
text = process_text(text, False)
73
draw_multiple_line_text(image, text, font, txtclr, padding, wrap=30, transparent=transparent)
74
image.save(f"assets/temp/{reddit_id}/png/img{idx}.png")
75
76