From 899398a2ea55c822080bf2258c1b35206c337c98 Mon Sep 17 00:00:00 2001 From: Thelie Date: Mon, 16 May 2022 11:13:15 +0200 Subject: [PATCH] Added compatibility for different metadata terms. --- cook2tex.py | 37 ++++++++++++++++++++++++------------- 1 file changed, 24 insertions(+), 13 deletions(-) diff --git a/cook2tex.py b/cook2tex.py index 1362dbb..cb54973 100644 --- a/cook2tex.py +++ b/cook2tex.py @@ -1,7 +1,6 @@ -import sys, cooklang -from os.path import exists +import sys, os, cooklang -def parse_recipe(cooklang_source): +def parse_recipe(cooklang_source, title=""): """ Takes: string cooklang_source Returns: [ string ] tex @@ -12,9 +11,13 @@ def parse_recipe(cooklang_source): recipe = cooklang.parseRecipe(cooklang_source) - title = get_metadata_value("title", recipe) - servings = get_metadata_value("servings", recipe) - time = get_metadata_value("time", recipe) + if title: + title = get_metadata_value(["title"], recipe, title) + else: + title = get_metadata_value(["title"], recipe) + + servings = get_metadata_value(time_keys, recipe) + time = get_metadata_value(serving_keys, recipe) tex = [] @@ -53,18 +56,26 @@ def parse_recipe_from_file(path): Takes a recipe path as an argument and returns the cuisine recipe block. One element per line. """ - if not exists(path): + if not os.path.exists(path): raise ArgumentError + + name = os.path.basename(path) + split_name = os.path.splitext(name) + title = split_name[0] with open(path) as file: - return parse_recipe(file.read()) + return parse_recipe(file.read(), title) -def get_metadata_value(key, recipe): - if key in recipe["metadata"].keys(): - return recipe["metadata"][key] - else: - return "N/A" +serving_keys = ["servings", "serves"] +time_keys = ["time", "total time"] + +def get_metadata_value(keys, recipe, substitute="N/A"): + for key in keys: + if key in recipe["metadata"].keys(): + return recipe["metadata"][key] + + return substitute def get_step_ingredients(step):