Bläddra i källkod

add product unit conversions and fix minor bugs in recipe parser and editor

Daniel Sheffield 2 år sedan
förälder
incheckning
0bc0afbb61
4 ändrade filer med 44 tillägg och 14 borttagningar
  1. 5 2
      app/activities/RecipeEditor.py
  2. 10 11
      app/parse_recipe.py
  3. 21 1
      recipe.py
  4. 8 0
      units.sql

+ 5 - 2
app/activities/RecipeEditor.py

@@ -220,7 +220,10 @@ class RecipeEditor(FocusWidget):
             except InvalidOperation:
                 quantity = None
 
-            if None in (sort, product, unit, quantity):
+            if (product or None, unit or None, quantity or None) == (None, None, None):
+                continue
+
+            if None in (sort or None, product or None, unit or None, quantity or None):
                 not_found = '>'
                 continue
 
@@ -341,7 +344,7 @@ class RecipeEditor(FocusWidget):
                 ]))
             ], dividechars=1),
             'bottom_pane': Pile(bottom_pane),
-            'right_pane': (9, Pile(right_pane)),
+            'right_pane': (15, Pile(right_pane)),
             'middle_pane': (12, Pile(middle_pane)),
             'left_pane': Pile(left_pane),
             'gutter': (8, Pile(gutter))

+ 10 - 11
app/parse_recipe.py

@@ -17,19 +17,18 @@ def parse_recipe(fh, query_manager: QueryManager):
         'instructions': None,
     }
     for ingredient in contents['ingredients']:
-        units = query_manager.unique_suggestions('unit', unit='')
-        for u in units:
-            match = re.search(
-                r'(?P<product>.*) (?P<quantity>[0-9\.]+)(?P<unit>' f'{u}' r')', ingredient
-            )
-            if not match:
-                continue
-            recipe['ingredients'].append(
-                [match.group('product'), match.group('quantity'), match.group('unit')]
-            )
+        match = re.search(
+            r'(?P<product>.*) (?P<quantity>[0-9\.]+) ?(?P<unit>.*)', ingredient
+        )
+        assert match is not None, f'Could parse {ingredient}'
+        units = query_manager.unique_suggestions('unit', unit=match.group('unit'))
+        assert match.group('unit') in units, f"Unknown unit: '{match.group('unit')}'"
+        recipe['ingredients'].append(
+            [match.group('product').strip(), match.group('quantity'), match.group('unit')]
+        )
     for k in set(recipe.keys()) - set(['ingredients']):
         if k in contents:
             recipe[k] = contents[k]
     return recipe
-    
+
 

+ 21 - 1
recipe.py

@@ -41,7 +41,26 @@ class Recipe(WidgetPlaceholder):
         self.activity_manager.show(self)
         self.activity_manager.show(recipe)
 
-cur.execute("BEGIN")
+cur.execute("BEGIN;")
+with open('units.sql') as f:
+    to_exec = ''
+    quote = False
+    for line in filter(lambda x: x.strip() not in ('BEGIN;','ROLLBACK;'), f):
+        if line.startswith("""$$"""):
+            quote = True if not quote else False
+        to_exec += line
+        if not line.strip().endswith(';'):
+            continue
+        if quote:
+            continue
+        #print(f'exec {to_exec}')
+        #input()
+        cur.execute(to_exec)
+        try:
+            print(cur.fetchall())
+        except psycopg.ProgrammingError:
+            pass
+        to_exec = ''
 
 activity_manager = ActivityManager()
 query_manager = QueryManager(cur, display_mapper)
@@ -73,5 +92,6 @@ loop = MainLoop(app, next(palettes), screen=screen,
         pop_ups=True)
 loop.run()
 
+cur.execute("ROLLBACK")
 cur.close()
 conn.close()

+ 8 - 0
units.sql

@@ -10,6 +10,7 @@ CALL insert_unit ('Gallon (US)');
 CALL insert_unit ('tsp (metric)');
 CALL insert_unit ('Tbsp (metric)');
 CALL insert_unit ('Cup (metric)');
+SELECT * FROM units;
 -- using customary cup as per https://en.wikipedia.org/wiki/Cup_(unit)
 CALL insert_unit_conversion ('tsp (metric)', 'mL', 5);
 CALL insert_unit_conversion ('Tbsp (metric)', 'mL', 15);
@@ -22,6 +23,13 @@ CALL insert_unit_conversion ('Cup (US)', 'fl. oz. (US)', 8);
 CALL insert_unit_conversion ('Pint (US)', 'Cup (US)', 2);
 CALL insert_unit_conversion ('Quart (US)', 'Cup (US)', 4);
 CALL insert_unit_conversion ('Gallon (US)', 'Cup (US)', 16);
+CALL insert_unit_conversion ('Cup (metric)', 'kg', 'Whole Oats', 0.214/2);
+CALL insert_unit_conversion ('Cup (metric)', 'kg', 'Puffed Rice', .03);
+CALL insert_unit_conversion ('Cup (metric)', 'kg', 'Coconut Desiccated', .071*2);
+-- CALL insert_unit_conversion ('Cup (metric)', 'kg', 'Peanut butter', .24);
+CALL insert_unit_conversion ('Cup (metric)', 'kg', 'Honey', .68);
+CALL insert_unit_conversion ('Cup (metric)', 'kg', 'Brown Sugar', .055*4);
+
 SELECT * FROM conversions;
 DO
 $$