-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcreate_posts.py
More file actions
145 lines (110 loc) · 4.75 KB
/
create_posts.py
File metadata and controls
145 lines (110 loc) · 4.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
# Create posts from downloaded posts
import os
import pytesseract
from openai import OpenAI
from dotenv import load_dotenv
from config import DEVELOPER_PROMPT
from PIL import Image, ImageDraw, ImageFont
def is_mostly_black(image_path, threshold=30, ratio=0.9):
img = Image.open(image_path).convert("L") # Convert to grayscale
pixels = list(img.getdata())
dark_pixels = sum(p < threshold for p in pixels)
total_pixels = len(pixels)
return dark_pixels / total_pixels >= ratio
def wrap_text(text, font, max_width, draw):
"""
Wraps text to fit within the max_width.
"""
words = text.split()
lines = [] # Holds each line in the text box
current_line = [] # Holds each word in the current line under evaluation.
for word in words:
# Check the width of the current line with the new word added
test_line = ' '.join(current_line + [word])
width = draw.textlength(test_line, font=font)
if width <= max_width:
current_line.append(word)
else:
# If the line is too wide, finalize the current line and start a new one
lines.append(' '.join(current_line))
current_line = [word]
# Add the last line
if current_line:
lines.append(' '.join(current_line))
return lines
def create_posts(downloaded_posts):
# Create "created_posts" directory
os.makedirs("created_posts", exist_ok=True)
for post in downloaded_posts:
print(f"Creating post for: {post['shortcode']}")
image_path = "downloaded_posts/" + post['shortcode'] + '.jpg'
# Load the image file
try:
img = Image.open(image_path)
except Exception as e:
print(f"Error loading image {image_path}: {e}")
continue
# Use pytesseract to extract text from the image
post_text = pytesseract.image_to_string(img, lang='eng')
# Read the caption text from the corresponding text file
with open("downloaded_posts/" + post['shortcode'] + '.txt', 'r') as f:
caption_text = f.read()
# Create prompts for translation
post_prompt = "Traduce coerent in română:\" " + post_text + "\""
caption_prompt = "Traduce coerent in română:\" " + caption_text + "\". Nu tradu cuvintele care încep cu '#' și lasă-le neatinse."
# Translate the post text and caption to a different language (coherently, with AI)
load_dotenv()
api_key = os.getenv('OPENAI_API_KEY')
client = OpenAI(api_key=api_key)
post_completion = client.chat.completions.create(
model="gpt-4.1",
messages=[
{"role": "developer", "content": DEVELOPER_PROMPT},
{"role": "user", "content": post_prompt}
]
)
translated_post_text = post_completion.choices[0].message.content
caption_completion = client.chat.completions.create(
model="gpt-4.1",
messages=[
{"role": "developer", "content": DEVELOPER_PROMPT},
{"role": "user", "content": caption_prompt}
]
)
translated_caption_text = caption_completion.choices[0].message.content
# Place text on square(1080x1080) black image
# Open Image
img = Image.open('black_square.png')
# Call draw Method to add 2D graphics in an image
draw = ImageDraw.Draw(img)
# Custom font style and font size
font = ImageFont.truetype('Lato-Light.ttf', 45)
# Width for the text box
max_width = 780
# Wrap text into lines
wrapped_lines = wrap_text(translated_post_text, font, max_width, draw)
# Starting position for the text box
x = 150
y = 540 - 55 * int(len(wrapped_lines)) // 2 # A line occupies around 55 pixels
end_x, end_y = x + max_width, 930 # Ending position for the text box
# Dimensions for the background box
background_box = [(x, y), (end_x, end_y)]
# Draw background box
draw.rectangle(background_box, fill="black")
description = ""
for line in wrapped_lines:
description += line + "\n"
# Draw multiline text.
draw.multiline_text((x, y), description, font=font, fill="white", spacing=4)
if is_mostly_black(image_path):
# Save the post
img.save("created_posts/" + post['shortcode'] + '.png')
# Save caption
with open("created_posts/" + post['shortcode'] + '.txt', 'w') as f:
f.write(translated_caption_text)
else:
# Skip posts that are not mostly black
continue
print(f"Created post for {post['shortcode']}")
print("-" * 50)
print("All posts created successfully.")