Files
o2o-weather/admin/nalssigak/scripts/render.py
T

90 lines
3.7 KiB
Python
Executable File

"""templates/ 의 HTML을 헤드리스 크롬으로 PNG로 찍는다.
usage:
python3 render.py title --age 30 --who 여성 --label 하객룩 --out title_woman.png
python3 render.py bubble --text "*크롭 재킷*으로 시크하게" --out bubbles/w1.png
python3 render.py frame --out frame.png
python3 render.py outro --out outro.png
python3 render.py mask --out mask.png
자막: *단어* 는 주황 강조, | 는 띄어쓰기로 바뀐다(한 줄). title·bubble 은 영상 위에 얹는 투명 PNG, frame 은 흐린 배경과 영상 사이의 창 그림자.
"""
import argparse
import os
import shutil
import subprocess
import sys
import tempfile
import urllib.parse
from pathlib import Path
TEMPLATES = Path(__file__).resolve().parent.parent / "templates"
def _chrome():
env = os.environ.get("CHROME_BIN") or os.environ.get("CHROME_PATH")
if env:
return env
if sys.platform == "win32":
for base in (os.environ.get("PROGRAMFILES"), os.environ.get("PROGRAMFILES(X86)"), os.environ.get("LOCALAPPDATA")):
path = Path(base or "") / "Google/Chrome/Application/chrome.exe"
if base and path.is_file():
return str(path)
return "chrome.exe"
return "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" if sys.platform == "darwin" else "google-chrome"
CHROME = _chrome()
# compose.sh 의 영상 창 크기와 같아야 한다
CARD = (816, 1440)
def shoot(url, out, size=(1080, 1920), transparent=False):
profile = tempfile.mkdtemp(prefix="render-")
command = [CHROME, "--headless=new", "--disable-gpu", "--hide-scrollbars", f"--user-data-dir={profile}",
"--force-device-scale-factor=1", f"--window-size={size[0]},{size[1]}", "--virtual-time-budget=6000",
f"--screenshot={Path(out).resolve()}", url]
if transparent:
command.insert(-1, "--default-background-color=00000000")
Path(out).parent.mkdir(parents=True, exist_ok=True)
Path(out).unlink(missing_ok=True)
try:
# 크롬이 가끔 멈추므로 40초에서 끊는다
subprocess.run(command, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=40)
except subprocess.TimeoutExpired:
pass
finally:
shutil.rmtree(profile, ignore_errors=True)
if not Path(out).is_file():
sys.exit(f"찍지 못했어요: {out}")
print("saved", out)
def page(name, **query):
return (TEMPLATES / name).as_uri() + ("?" + urllib.parse.urlencode(query) if query else "")
def main():
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("kind", choices=["title", "bubble", "frame", "outro", "mask"])
parser.add_argument("--out", required=True)
parser.add_argument("--age", default="20")
parser.add_argument("--who", default="여성")
parser.add_argument("--label", default="코디")
parser.add_argument("--text")
args = parser.parse_args()
if args.kind == "title":
shoot(page("title.html", age=args.age, who=args.who, label=args.label), args.out, transparent=True)
elif args.kind == "bubble":
if args.text is None:
sys.exit("bubble 은 --text 가 필요해요")
shoot(page("bubble.html", t=args.text), args.out, transparent=True)
elif args.kind == "frame":
shoot(page("frame.html"), args.out, transparent=True)
elif args.kind == "outro":
shoot(page("outro.html"), args.out)
else:
html = f"<body style='margin:0;background:transparent'><div style='width:{CARD[0]}px;height:{CARD[1]}px;border-radius:40px;background:white'></div></body>"
shoot("data:text/html," + urllib.parse.quote(html), args.out, size=CARD, transparent=True)
if __name__ == "__main__":
main()