-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgenerate.py
80 lines (56 loc) · 2.22 KB
/
generate.py
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
import os
import argparse
import time
from io import BytesIO
from urllib.parse import urlparse
import requests
from PIL import Image
from lxml import html
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
def get_article_data(article: str) -> tuple[str, str]:
url = urlparse(article)
assert all([url.scheme, url.netloc]), 'Article is not a valid URL :('
resp = requests.get(article)
assert 199 < resp.status_code < 300, f'Received a status code of {resp.status_code} :('
tree = html.fromstring(resp.text)
url = tree.xpath('//head/meta[@property="og:image"]/@content')
if not url: raise Exception('No og:image found :(')
title = tree.xpath('//head/title/text()')
if not title: raise Exception('No title tag found :(')
return url[0], title[0]
def choose_font_color(image_url: str) -> str:
resp = requests.get(image_url)
assert 199 < resp.status_code < 300, f'Received a status code of {resp.status_code} :('
img = Image.open(BytesIO(resp.content))
img_gray = img.convert('L')
pixels = list(img_gray.getdata())
num_pixels = len(pixels)
avg_brightness = sum(pixels) / num_pixels
if avg_brightness < 127:
return "snow"
else:
return "black"
def main():
parser = argparse.ArgumentParser()
parser.add_argument('article')
args = parser.parse_args()
og_image, title = get_article_data(args.article)
print(f'{og_image = }\n{title = }\nGenerating image...')
chrome_options = Options()
chrome_options.add_argument("--headless")
driver = webdriver.Chrome(options=chrome_options)
driver.set_window_size(2500, 3500)
driver.get(f'file://{os.path.join(os.getcwd(), 'index.html')}')
# Instantiate stuff
driver.execute_script(f'setImages("{og_image}")')
driver.execute_script(f'setFigCaption("{title.strip()}")')
driver.execute_script(f'setFontColor("{choose_font_color(og_image)}")')
time.sleep(2)
# Take screenshot
container = driver.find_element(By.ID, 'story-container')
container.screenshot(f'images/article_story-[{'-'.join(title.lower().split())}].png')
driver.quit()
if __name__ == '__main__':
main()