Update to use Craiyon v3

This commit is contained in:
Mikkel Munch Mortensen 2023-05-09 10:19:07 +02:00
parent 756daa6c07
commit 0e4f3f6151

View file

@ -66,14 +66,17 @@ def get_photo_url(menu: str):
} }
request_data = { request_data = {
"model": "photo",
"negative_prompt": "",
"prompt": translation, "prompt": translation,
"version": "35s5hfwn9n78gb06",
"token": token, "token": token,
"version": "35s5hfwn9n78gb06",
} }
sys.stdout.write("Asking Craiyon to generate images for the menu...\n") sys.stdout.write("Asking Craiyon to generate images for the menu...\n")
craiyon_start = datetime.datetime.now()
try: try:
response = requests.post( response = requests.post(
"https://api.craiyon.com/draw", "https://api.craiyon.com/v3",
headers=headers, headers=headers,
json=request_data, json=request_data,
timeout=90, timeout=90,
@ -87,6 +90,7 @@ def get_photo_url(menu: str):
except JSONDecodeError: except JSONDecodeError:
sys.stderr.write("Unable to parse JSON from Craiyon response:\n") sys.stderr.write("Unable to parse JSON from Craiyon response:\n")
sys.stderr.write(f"{response.text}\n") sys.stderr.write(f"{response.text}\n")
sys.stderr.write("Waited for {datetime.datetime.now() - craiyon_start}.")
return None return None
return (f"https://img.craiyon.com/{image}", translation) return (f"https://img.craiyon.com/{image}", translation)
@ -119,96 +123,105 @@ response = requests.post(
) )
data = response.json() data = response.json()
sys.stdout.write("Data retrieved from SharePoint.\n") sys.stdout.write("Data retrieved from SharePoint.\n")
if response.status_code != 200:
# Extract today's menu from the SharePoint data.
today = datetime.date.today().strftime("%d-%m-%Y")
menu = None
if "error" in data:
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") photo = None
message = plain_message = (
f"SharePoint responded with status {response.status_code} :("
)
else: else:
hook_url = SLACK_SUCCESS_HOOK # Extract today's menu from the SharePoint data.
for entry in data["ListData"]["Row"]: today = datetime.date.today().strftime("%d-%m-%Y")
if entry.get("DAto") == today: menu = None
menu = entry if "error" in data:
break message = plain_message = f"Error: {data['error']['message']['value']}"
photo = None
if menu is None: hook_url = SLACK_ERROR_HOOK
sys.stderr.write("Unable to find the menu of today :(\n") sys.stderr.write(f"SharePoint {message}\n")
sys.exit(1)
menu = menu["Menutekst"]
sys.stdout.write(f"The menu of today ({today}) is: {menu}\n")
# Determine appropriate emojis for the menu.
emojis = []
for emoji, keywords in {
"flag-in": ["indisk", "indien"],
"flag-gr": ["græsk", "grækenland"],
"fish": ["fisk", "laks", "rødspætte", "sej "],
"shrimp": ["reje"],
"pig2": ["skinke", "gris", "nakkefilet"],
"cow": ["hakkebøf"],
"cow2": ["kalv", "okse"],
"chicken": ["kylling", "chicken"],
"turkey": ["kalkun"],
"rabbit2": [" hare"],
"rooster": ["coq au vin"],
"egg": [" æg ", " ægge"],
"falafel": ["falafel"],
"hot_pepper": ["chili", "hot sauce"],
"onion": ["løg"],
"mango": ["mango"],
"mushroom": ["svampe", "kantarel", "champignon"],
"eggplant": ["moussaka", "mousakka"],
"beans": ["bønne"],
"hamburger": ["burger"],
"sandwich": ["sandwich"],
"stuffed_flatbread": ["pita"],
"pie": ["tærte"],
"hotdog": ["hotdog"],
"wine_glass": ["coq au vin"],
"bowl_with_spoon": ["suppe"],
"stew": ["gryde", "gullasch"],
"rice": [" ris "],
"ramen": ["nudler"],
"cloud": ["sky"],
"potato": ["kartoffel", "kartofler"],
"apple": ["æble"],
"baguette_bread": ["flute"],
"flag-dk": ["tillykke", "fødselsdag"],
"wave": ["farvel"],
"gift_heart": ["valentines"],
}.items():
for keyword in keywords:
if keyword in f" {menu.lower()} ":
emojis.append(emoji)
break
if emojis:
emojis = f":{': :'.join(emojis)}:"
sys.stdout.write(f"Emojis determined: {emojis}\n")
else: else:
emojis = "" hook_url = SLACK_SUCCESS_HOOK
sys.stdout.write("No emojis determined.\n") for entry in data["ListData"]["Row"]:
if entry.get("DAto") == today:
menu = entry
break
# Pick an introduction for the menu. if menu is None:
introduction = random.choice([ sys.stderr.write("Unable to find the menu of today :(\n")
"Dagens menu er", sys.exit(1)
"I dag forkæler kantinen os med", menu = menu["Menutekst"]
"Du kan godt glæde dig til senere! For vi skal have", sys.stdout.write(f"The menu of today ({today}) is: {menu}\n")
"Der bliver knoklet i køkkenet for at blive klar til at servere",
"Klokken 11:30 har kantinen fremtryllet en lækker omgang",
])
sys.stdout.write(f"Introduction picked: {introduction}\n")
# Retrieve a photo of the menu from Craiyon. # Determine appropriate emojis for the menu.
photo = get_photo_url(menu) emojis = []
for emoji, keywords in {
"flag-in": ["indisk", "indien"],
"flag-gr": ["græsk", "grækenland"],
"fish": ["fisk", "laks", "rødspætte", "sej ", "kulmule"],
"shrimp": ["reje"],
"pig2": ["skinke", "gris", "nakkefilet"],
"cow": ["hakkebøf"],
"cow2": ["kalv", "okse"],
"chicken": ["kylling", "chicken"],
"turkey": ["kalkun"],
"rabbit2": [" hare"],
"rooster": ["coq au vin"],
"egg": [" æg ", " ægge"],
"falafel": ["falafel"],
"hot_pepper": ["chili", "hot sauce"],
"onion": ["løg"],
"mango": ["mango"],
"mushroom": ["svampe", "kantarel", "champignon"],
"eggplant": ["moussaka", "mousakka"],
"cheese_wedge": [" ost"],
"beans": ["bønne"],
"olive": ["oliven"],
"spaghetti": ["spaghetti"],
"hamburger": ["burger"],
"sandwich": ["sandwich"],
"stuffed_flatbread": ["pita"],
"pie": ["tærte"],
"hotdog": ["hotdog"],
"wine_glass": ["coq au vin"],
"bowl_with_spoon": ["suppe"],
"stew": ["gryde", "gullasch"],
"rice": [" ris "],
"ramen": ["nudler"],
"cloud": ["sky"],
"potato": ["kartoffel", "kartofler"],
"apple": ["æble"],
"baguette_bread": ["flute"],
"flag-dk": ["tillykke", "fødselsdag"],
"wave": ["farvel"],
"gift_heart": ["valentines"],
}.items():
for keyword in keywords:
if keyword in f" {menu.lower()} ":
emojis.append(emoji)
break
if emojis:
emojis = f":{': :'.join(emojis)}:"
sys.stdout.write(f"Emojis determined: {emojis}\n")
else:
emojis = ""
sys.stdout.write("No emojis determined.\n")
# Compose message for Slack. # Pick an introduction for the menu.
plain_message = f"{introduction} {menu}" introduction = random.choice([
menu_url = MENU_URL "Dagens menu er",
message = f"{introduction} {emojis} <{menu_url}|*{menu}*>".strip() "I dag forkæler kantinen os med",
"Du kan godt glæde dig til senere! For vi skal have",
"Der bliver knoklet i køkkenet for at blive klar til at servere",
"Klokken 11:30 har kantinen fremtryllet en lækker omgang",
])
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.
plain_message = f"{introduction} {menu}"
menu_url = MENU_URL
message = f"{introduction} {emojis} <{menu_url}|*{menu}*>".strip()
payload = { payload = {
"text": plain_message, "text": plain_message,
@ -224,13 +237,19 @@ payload = {
} }
if photo is not None: if photo is not None:
payload["blocks"][0]["accessory"] = { photo_text = "Et ukvalificeret bud på hvordan dagens menu kunne se ud"
"type": "image", payload["blocks"].insert(
"image_url": photo[0], 0,
"alt_text": ( {
"Et ukvalificeret bud på hvordan dagens menu kunne se ud" "type": "image",
), "image_url": photo[0],
} "alt_text": photo_text,
"title": {
"type": "plain_text",
"text": photo_text,
},
}
)
sys.stdout.write("Posting menu to Slack...\n") sys.stdout.write("Posting menu to Slack...\n")
hook = request.Request( hook = request.Request(