Include generated photo from Craiyon of the menu

This commit is contained in:
Mikkel Munch Mortensen 2023-03-06 13:47:43 +01:00
parent beb88558ac
commit 925e896991
2 changed files with 66 additions and 7 deletions

View file

@ -14,6 +14,7 @@ from urllib import error, parse, request
import browser_cookie3 import browser_cookie3
from googletrans import Translator from googletrans import Translator
import requests import requests
from requests.exceptions import JSONDecodeError, ReadTimeout
# Load configuration. # Load configuration.
@ -30,6 +31,53 @@ except KeyError as e:
sys.exit(1) sys.exit(1)
sys.stdout.write("Configuration loaded.\n") sys.stdout.write("Configuration loaded.\n")
def get_photo_url(menu: str):
"""Retrieve a photo of the menu."""
# Translate menu from Danish to English.
translation = Translator().translate(menu, src="da", dest="en").text
sys.stdout.write(f"English translation of the menu is: {translation}\n")
# Ask Crayion to be creative.
cookies = browser_cookie3.firefox(domain_name="craiyon.com")
cookie = None
for cookie in cookies:
if cookie.name == "supabase-auth-token":
cookie = parse.unquote(cookie.value)
break
if cookie is None:
sys.stderr.write("Unable to extract Craiyon cookie.\n")
sys.exit(1)
token = json.loads(cookie)[0]
headers = {
"Accept": "application/json;odata=verbose",
"Content-Type": "application/json;odata=verbose",
}
request_data = {
"prompt": translation,
"version": "35s5hfwn9n78gb06",
"token": token,
}
sys.stdout.write("Asking Craiyon to generate images for the menu...\n")
try:
response = requests.post(
"https://api.craiyon.com/draw",
headers=headers,
json=request_data,
timeout=90,
)
except ReadTimeout:
sys.stderr.write("Timeout while waiting for Craiyon :(\n")
return None
try:
image = random.choice(response.json()["images"])
except JSONDecodeError:
sys.stderr.write("Unable to parse JSON from Craiyon response:\n")
sys.stderr.write(f"{response.text}\n")
return None
return (f"https://img.craiyon.com/{image}", translation)
# Set up and execute request to SharePoint. # Set up and execute request to SharePoint.
cookies = browser_cookie3.firefox( cookies = browser_cookie3.firefox(
@ -64,6 +112,7 @@ today = datetime.date.today().strftime("%d-%m-%Y")
menu = None menu = None
if "error" in data: if "error" in data:
message = plain_message = f"Error: {data['error']['message']['value']}" message = plain_message = f"Error: {data['error']['message']['value']}"
photo = None
hook_url = SLACK_ERROR_HOOK hook_url = SLACK_ERROR_HOOK
sys.stderr.write(f"SharePoint {message}\n") sys.stderr.write(f"SharePoint {message}\n")
else: else:
@ -79,15 +128,11 @@ else:
menu = menu["Menutekst"] menu = menu["Menutekst"]
sys.stdout.write(f"The menu of today ({today}) is: {menu}\n") sys.stdout.write(f"The menu of today ({today}) is: {menu}\n")
# Translate menu from Danish to English.
translation = Translator().translate(menu, src="da", dest="en").text
sys.stdout.write(f"English translation of the menu is: {translation}\n")
# Determine appropriate emojis for the menu. # Determine appropriate emojis for the menu.
emojis = [] emojis = []
for emoji, keywords in { for emoji, keywords in {
"flag-in": ["indisk", "indien"], "flag-in": ["indisk", "indien"],
"hamburger": ["burger"], "flag-gr": ["græsk", "grækenland"],
"fish": ["fisk", "laks", "rødspætte", "sej "], "fish": ["fisk", "laks", "rødspætte", "sej "],
"shrimp": ["reje"], "shrimp": ["reje"],
"pig2": ["skinke", "gris"], "pig2": ["skinke", "gris"],
@ -102,7 +147,9 @@ else:
"onion": ["løg"], "onion": ["løg"],
"mango": ["mango"], "mango": ["mango"],
"mushroom": ["svampe", "kantarel", "champignon"], "mushroom": ["svampe", "kantarel", "champignon"],
"eggplant": ["moussaka", "mousakka"],
"beans": ["bønne"], "beans": ["bønne"],
"hamburger": ["burger"],
"sandwich": ["sandwich"], "sandwich": ["sandwich"],
"stuffed_flatbread": ["pita"], "stuffed_flatbread": ["pita"],
"pie": ["tærte"], "pie": ["tærte"],
@ -141,6 +188,9 @@ else:
]) ])
sys.stdout.write(f"Introduction picked: {introduction}\n") sys.stdout.write(f"Introduction picked: {introduction}\n")
# Retrieve a photo of the menu from Craiyon.
photo = get_photo_url(menu)
# Compose message for Slack. # Compose message for Slack.
plain_message = f"{introduction} {menu}" plain_message = f"{introduction} {menu}"
menu_url = MENU_URL menu_url = MENU_URL
@ -159,6 +209,15 @@ payload = {
], ],
} }
if photo is not None:
payload["blocks"][0]["accessory"] = {
"type": "image",
"image_url": photo[0],
"alt_text": (
f"En kunstig intelligens' fortolkning af dagens menu på engelsk: {photo[1]}"
),
}
sys.stdout.write("Posting menu to Slack...\n") sys.stdout.write("Posting menu to Slack...\n")
hook = request.Request( hook = request.Request(
hook_url, hook_url,

View file

@ -9,8 +9,8 @@
## Improve the post by including a photo of the menu. ## Improve the post by including a photo of the menu.
Requirements: Requirements:
[x] Ask Google Translate to translate menu from Danish to English. [x] Ask Google Translate to translate menu from Danish to English.
[ ] Ask Crayion to generate images of the menu in English. [x] Ask Crayion to generate images of the menu in English.
[ ] Include a random image from the Crayion results as an attachment in [x] Include a random image from the Crayion results as an attachment in
the Slack post. the Slack post.
## Improve the post with an extended description. ## Improve the post with an extended description.