123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161 |
- import os
- from sys import stdin, stdout, argv
- from uuid import uuid4
- from json import dumps, load
- import psycopg
- from psycopg import Cursor
- import pandas as pd
- from app.data.QueryManager import QueryManager, display_mapper
- from app.parse_recipe import parse_recipe
- try:
- from db_credentials import HOST, PASSWORD
- host = f'host={HOST}'
- password = f'password={PASSWORD}'
- except:
- host = ''
- password = ''
- user = os.getenv('USER')
- conn = psycopg.connect(f"{host} dbname=grocery user={user} {password}")
- cur: Cursor = conn.cursor()
- query_manager = QueryManager(cur, display_mapper)
- with open(argv[1], 'rb') as f:
- units = { x['name']: x for x in load(f) }
- cur.execute("BEGIN;")
- with open('units.sql') as f:
- to_exec = ''
- quote = False
- conn.add_notice_handler(lambda x: print(f"[{x.severity}] {x.message_primary}"))
- 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
- cur.execute(to_exec)
- try:
- data = pd.DataFrame(cur.fetchall(), columns=[
- x.name for x in cur.description
- ])
- if not data.empty:
- print()
- print(cur._last_query)
- print(data.to_string(index=False))
- except psycopg.ProgrammingError:
- pass
- to_exec = ''
- parsed = parse_recipe(stdin, query_manager)
- cur.execute('ROLLBACK')
- def unit_mapper(unit):
- if 'Cup' in unit:
- return 'cup'
- return unit.replace(' (metric)', '').replace(' (US)', '')
- mealie = {
- 'recipeYield': parsed['feeds'],
- 'recipeInstructions': [{
- "id": str(uuid4()),
- "title": "",
- "text": line,
- "ingredientReferences": [],
- } for line in parsed['instructions'].splitlines()],
- 'recipeIngredient': [{
- "quantity": quantity,
- "unit": units[unit_mapper(unit)],
- "food": None,
- "note": product,
- "isFood": False,
- "disableAmount": False,
- "display": product,
- "title": None,
- "originalText": o,
- "referenceId": str(uuid4())
- } for product, quantity, unit, o in map(
- lambda x: (*x, ' '.join([*x[1:], x[0]])),
- parsed['ingredients']
- )]
- }
- stdout.write(dumps(mealie))
- cur.close()
- conn.close()
|