83 lines
2.1 KiB
Python
83 lines
2.1 KiB
Python
from pathlib import Path
|
|
from datetime import datetime
|
|
|
|
def parse_timestamp(timestamp):
|
|
return datetime.strptime(timestamp, '%Y-%m-%d %H:%M:%S')
|
|
|
|
def parse_foods_file():
|
|
path = Path.home() / 'projects' / 'open-journal' / 'foods'
|
|
text = path.read_text()
|
|
foods, recipes = text.split('---')
|
|
|
|
def parse_macro(macro):
|
|
if macro == '...':
|
|
return ('INVALID', 0.0)
|
|
|
|
name, value = macro.split()
|
|
value = float(value.removesuffix('g').removesuffix('kcal'))
|
|
return (name, value)
|
|
|
|
foods = {
|
|
macros[0]: dict(parse_macro(macro) for macro in macros[1:])
|
|
for macros in [food.split('\n') for food in foods.strip().split('\n\n')]
|
|
}
|
|
|
|
def combine_values(fst, snd):
|
|
result = fst.copy()
|
|
for k,v in snd.items():
|
|
if k in fst:
|
|
result[k] += v
|
|
else:
|
|
result[k] = v
|
|
return result
|
|
|
|
def evaluate_ingredients(ingredients):
|
|
result = {}
|
|
|
|
total_weight = 0.0
|
|
for ingredient in ingredients:
|
|
k,v = parse_macro(ingredient)
|
|
if k == 'TOTAL':
|
|
result[k] = v
|
|
break
|
|
else:
|
|
total_weight += v
|
|
|
|
|
|
food = foods[k]
|
|
|
|
for kk,vv in food.items():
|
|
if kk not in result:
|
|
result[kk] = 0.0
|
|
|
|
result[kk] += vv * (v/100.0)
|
|
|
|
if 'TOTAL' not in result:
|
|
result['TOTAL'] = total_weight
|
|
|
|
return result
|
|
|
|
recipes = {
|
|
ingredients[0]: evaluate_ingredients(ingredients[1:])
|
|
for ingredients in [
|
|
recipe.split('\n') for recipe in recipes.strip().split('\n\n')
|
|
]
|
|
}
|
|
|
|
def get_calories_from_macros(mm):
|
|
calories = 0.0
|
|
for k,v in mm.items():
|
|
calories += v * {
|
|
'Carbs': 4,
|
|
'Fat': 9,
|
|
'Protein': 4
|
|
}.get(k, 0.0)
|
|
return calories
|
|
|
|
#for k,v in foods.items():
|
|
# print(round(v.get('Energy') - get_calories_from_macros(v)), k)
|
|
|
|
return foods, recipes
|
|
|
|
|