126 lines
No EOL
3 KiB
Python
126 lines
No EOL
3 KiB
Python
import datetime
|
|
import os
|
|
import hashlib
|
|
import time
|
|
|
|
from playwright.sync_api import sync_playwright
|
|
from jinja2 import Template
|
|
|
|
from config.config import TMP
|
|
|
|
# configuration
|
|
TIMEZONE = 8
|
|
IMAGE_WIDTH = 1280
|
|
IMAGE_HEIGHT = 1280
|
|
|
|
def render(text, filename, width=IMAGE_WIDTH, height=IMAGE_HEIGHT, font_size=60, text_color="black", margin=50) -> int:
|
|
err = 0
|
|
|
|
browser = None
|
|
page = None
|
|
context = None
|
|
try:
|
|
with sync_playwright() as p:
|
|
browser = p.chromium.launch(headless=True)
|
|
context = browser.new_context()
|
|
page = context.new_page()
|
|
|
|
# template
|
|
template = Template("{{ text }}")
|
|
processed_text = template.render(text=text)
|
|
html_content = f"""
|
|
<html>
|
|
<head>
|
|
<style>
|
|
body {{
|
|
margin: 0;
|
|
background-size: {width}px {height}px;
|
|
width: {width}px;
|
|
height: {height}px;
|
|
display: flex;
|
|
justify-content: center;
|
|
align-items: center;
|
|
overflow: hidden;
|
|
}}
|
|
.text-container {{
|
|
font-size: {font_size}px;
|
|
color: {text_color};
|
|
width: calc(100% - {2 * margin}px);
|
|
text-align: center;
|
|
line-height: 1.2;
|
|
white-space: pre-wrap;
|
|
overflow-wrap: break-word;
|
|
}}
|
|
</style>
|
|
</head>
|
|
<body>
|
|
<div class="text-container">{processed_text}</div>
|
|
</body>
|
|
</html>
|
|
"""
|
|
page.set_content(html_content)
|
|
|
|
# set window size
|
|
page.set_viewport_size({"width": width, "height": height})
|
|
|
|
# screenshot
|
|
page.screenshot(path=filename)
|
|
except Exception as e:
|
|
# exception
|
|
print(e)
|
|
err = 1
|
|
finally:
|
|
if page:
|
|
try: page.close()
|
|
except: pass
|
|
if context:
|
|
try: context.close()
|
|
except: pass
|
|
if browser:
|
|
try: browser.close()
|
|
except: pass
|
|
|
|
return err
|
|
|
|
|
|
def gen(context:dict) -> str | None:
|
|
"""
|
|
Generate a image that has the content of the post in it.
|
|
|
|
Args:
|
|
context (dict): data of a post
|
|
|
|
Returns:
|
|
str: filename of the generated image.
|
|
None: An error occurred, and nothing was returned.
|
|
"""
|
|
|
|
# data preparation
|
|
content = context["content"]["text"]
|
|
|
|
# generate image
|
|
filename = TMP + hashlib.sha512( str(time.time()).encode() ).hexdigest() + ".jpg"
|
|
filename = os.path.abspath(filename)
|
|
err = render(content, filename, width=IMAGE_WIDTH, height=IMAGE_HEIGHT)
|
|
if err:
|
|
return None
|
|
|
|
return filename
|
|
|
|
|
|
def gen_caption(context:dict) -> str:
|
|
"""
|
|
Generate caption of the IG post.
|
|
|
|
Args:
|
|
context (dict): data of a post
|
|
|
|
Returns:
|
|
str: caption.
|
|
"""
|
|
|
|
caption = f"""[TCIVS Niming #{context["id"]}]
|
|
{context["content"]["text"]}
|
|
"""
|
|
|
|
return caption |