gpn23-recipes/fruehstueck.py

119 lines
3.3 KiB
Python
Raw Normal View History

2025-06-18 23:03:32 +02:00
import json
import sys
from pathlib import Path
from datetime import timedelta
import re
import os
from tqdm import tqdm
import csv
from collections import defaultdict
from config import *
def grams(ingredient):
conversion = None
for c in ingredient["conversions"]:
if c["unit"] in ["g / Gramm", "g"]:
conversion = c
if conversion:
return conversion.get('amount')
def allergens_for_step_ingredients(step):
l = []
for ingredient in step["ingredients"]:
if not ingredient.get("food"):
raise ValueError("No food in ingredient")
continue
i_grams = grams(ingredient)
i_name = ingredient["food"]["name"]
i_description = ingredient["food"]["description"]
if match := re.search(r"^Allergene: (.*)$", i_description, re.MULTILINE):
i_allergens = match.group(1)
else:
i_allergens = "❗ keine Allergene hinterlegt"
l.append((i_grams, i_name, i_allergens))
return l
def allergens_for_recipe(recipe):
l = []
for step in recipe["steps"]:
l += allergens_for_step_ingredients(step)
return l
def link(recipe):
return f"{TANDOOR_URL + "/view/recipe/" + str(recipe["id"])}"
def wiki_link(recipe):
wiki_slug = recipe["name"]
wiki_slug = re.sub(" ", "_", wiki_slug)
return f"{WIKI_URL + WIKI_ARTICLE_PREFIX + wiki_slug}"
def decruft_ingredient(i_name: str):
i_name = i_name.replace(" (trocken)", "")
i_name = i_name.replace(" (frisch)", "")
i_name = i_name.replace(" (TK)", "")
i_name = i_name.replace(" (Dose)", "")
i_name = i_name.replace(" (getrocknet)", "")
return i_name
def aggregate_zutaten(data):
result = defaultdict(int)
for grams, item in data:
result[item] += grams
return [(g, n) for n, g in result.items()]
def main():
Path("fruehstueck.csv").unlink(missing_ok=True)
recipes = []
for json_file in os.listdir(OUTDIR_JSON):
with open(os.path.join(OUTDIR_JSON, json_file), "r", encoding="utf-8") as f:
data = json.load(f)
recipes.append(data)
# filter "Frühstück"
recipes = [r for r in recipes if any(k["name"] == "Fr\u00fchst\u00fcck" for k in r["keywords"])]
with open("fruehstueck.csv", "w") as f:
fwriter = csv.writer(f, delimiter=';', quotechar='"', quoting=csv.QUOTE_MINIMAL)
fwriter.writerow(["title", "url", "isVegan", "ingredients", "comment"])
for recipe in recipes:
zutaten = []
for i_grams, i_name, i_allergens in allergens_for_recipe(recipe):
if i_grams is None:
i_grams = 0
zn = decruft_ingredient(i_name)
if i_allergens != "(keine)":
i_allergens = i_allergens.replace("\ufe0f", "\\faExclamationTriangle")
zn += f" (\\Alg{{{i_allergens}}})"
zutaten.append((i_grams, zn))
zutaten = aggregate_zutaten(zutaten)
zutaten.sort(key=lambda z: z[0], reverse=True)
fwriter.writerow([
recipe["name"],
wiki_link(recipe),
1, # XXX hardcoded
", ".join(z[1] for z in zutaten),
""
])
if __name__ == "__main__":
main()