Skip to content

Commit

Permalink
Fixed DB
Browse files Browse the repository at this point in the history
  • Loading branch information
richardp23 committed Jul 10, 2024
1 parent 64740af commit 4365262
Show file tree
Hide file tree
Showing 6 changed files with 178 additions and 29 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
.env
__pycache__/
*.db
4 changes: 0 additions & 4 deletions api_integration/edamam_integration.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
import json
import requests

# from db.recipe_sql import store_original_recipe


def get_recipe(app_id, app_key, dish):
EDAMAM_URL = "https://api.edamam.com/api/recipes/v2"
Expand All @@ -25,8 +23,6 @@ def get_recipe(app_id, app_key, dish):
ingredient_lines = recipe['ingredientLines']
recipe_url = recipe['url']

# store_original_recipe(recipe_name, ingredient_lines, recipe_url)

recipe_details = {
'name': recipe_name,
'ingredients': ingredient_lines,
Expand Down
5 changes: 1 addition & 4 deletions api_integration/openai_integration.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
import openai
from openai import OpenAI

def alt_recipe_query(key, diet, recipe_query):

def alt_recipe_query(key, diet, recipe_query):
client = OpenAI(api_key=key)


completion = client.chat.completions.create(
model="gpt-3.5-turbo",
messages=[
Expand Down Expand Up @@ -40,7 +39,6 @@ def parse_alternative_recipe_string(recipe_string):
alt_ingredients = ['\n ' + line.strip() for line in ingredients_section.splitlines() if line.strip()]
formatted_ingredients = ''.join(alt_ingredients)


instructions_start = recipe_string.find("Instructions:") + len("Instructions:")
if instructions_start != -1:
instructions_section = recipe_string[instructions_start:].strip()
Expand All @@ -59,7 +57,6 @@ def parse_alternative_recipe_string(recipe_string):

alt_instructions = "\n" + "\n".join(formatted_instructions)


return alt_name, alt_ingredients, alt_instructions

alt_name, alt_ingredients, alt_instructions = parse_alternative_recipe_string(alt_recipe_content)
Expand Down
1 change: 1 addition & 0 deletions db/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
from db.recipe_sql import *
149 changes: 149 additions & 0 deletions db/recipe_sql.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
import sqlite3

def create_tables():
try:
with sqlite3.connect('recipes.db') as connection:
cursor = connection.cursor()

cursor.execute('''
CREATE TABLE IF NOT EXISTS original_recipes (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
ingredients TEXT NOT NULL,
recipe_link TEXT NOT NULL
)
''')

cursor.execute('''
CREATE TABLE IF NOT EXISTS alt_recipes (
id INTEGER PRIMARY KEY AUTOINCREMENT,
original_recipe_id INTEGER NOT NULL,
name TEXT NOT NULL,
ingredients TEXT NOT NULL,
instructions TEXT NOT NULL,
FOREIGN KEY (original_recipe_id) REFERENCES original_recipes(id)
)
''')

print("Tables created successfully")
except sqlite3.Error as e:
print(f"An error occurred: {e}")

def check_existing_recipe(cursor, table, **conditions):
query = f"SELECT id FROM {table} WHERE " + " AND ".join(f"{key} = ?" for key in conditions)
cursor.execute(query, tuple(conditions.values()))
return cursor.fetchone()

def store_recipe(table, **data):
try:
with sqlite3.connect('recipes.db') as connection:
cursor = connection.cursor()

existing_recipe = check_existing_recipe(cursor, table, **data)
if existing_recipe:
print(f"Recipe already exists in the {table} table.")
return existing_recipe[0]

columns = ', '.join(data.keys())
placeholders = ', '.join('?' * len(data))
query = f"INSERT INTO {table} ({columns}) VALUES ({placeholders})"

cursor.execute(query, tuple(data.values()))
print(f"Inserted recipe into {table} with ID: {cursor.lastrowid}")
return cursor.lastrowid
except sqlite3.Error as e:
print(f"An error occurred: {e}")
return None

def store_original_recipe(name, ingredients, recipe_link):
ingredients_str = ', '.join(ingredients)
return store_recipe('original_recipes', name=name, ingredients=ingredients_str, recipe_link=recipe_link)

def store_alt_recipe(original_recipe_id, name, ingredients, instructions):
ingredients_str = ', '.join(ingredients)
return store_recipe('alt_recipes', original_recipe_id=original_recipe_id, name=name, ingredients=ingredients_str, instructions=instructions)

def lookup_prev_recipe():
try:
with sqlite3.connect('recipes.db') as connection:
cursor = connection.cursor()

cursor.execute('''
SELECT o.id, o.name AS original_name, a.name AS alt_name
FROM original_recipes o
LEFT JOIN alt_recipes a ON o.id = a.original_recipe_id
''')
recipes = cursor.fetchall()

if recipes:
print("\nPreviously made recipes:")
for recipe in recipes:
original_id, original_name, alt_name = recipe
alt_name = alt_name if alt_name else "No alternative recipe found"
print(f"{original_id}. {original_name} (Alternative Recipe: {alt_name})")
return True
else:
print("\nNo recipes found.")
return False
except sqlite3.Error as e:
print(f"An error occurred: {e}")
return False

def select_recipe():
try:
recipe_id = int(input("Enter the ID of the recipe you want to view: "))
except ValueError:
print("Invalid input. Please enter a number.")
return

try:
with sqlite3.connect('recipes.db') as connection:
cursor = connection.cursor()

cursor.execute('''
SELECT name, ingredients, recipe_link
FROM original_recipes
WHERE id = ?
''', (recipe_id,))
original_recipe = cursor.fetchone()

cursor.execute('''
SELECT name, ingredients, instructions
FROM alt_recipes
WHERE original_recipe_id = ?
''', (recipe_id,))
alt_recipe = cursor.fetchone()

if original_recipe:
print("\nOriginal Recipe:")
print(f"Name: {original_recipe[0]}")
print(f"Ingredients: {original_recipe[1]}")
print(f"Link: {original_recipe[2]}")
else:
print("\nOriginal recipe not found.")

if alt_recipe:
print("\nAlternative Recipe:")
print(f"Name: {alt_recipe[0]}")
print(f"Ingredients: {alt_recipe[1]}")
print(f"Instructions: {alt_recipe[2]}")
else:
print("\nAlternative recipe not found.")
except sqlite3.Error as e:
print(f"An error occurred: {e}")

def reset_database():
try:
with sqlite3.connect('recipes.db') as connection:
cursor = connection.cursor()
cursor.execute('DROP TABLE IF EXISTS alt_recipes')
cursor.execute('DROP TABLE IF EXISTS original_recipes')

create_tables()
print("Database reset successfully")
except sqlite3.Error as e:
print(f"An error occurred: {e}")

# Main execution
if __name__ == "__main__":
create_tables()
47 changes: 26 additions & 21 deletions main.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import dotenv
# import sqlite3
import sqlite3
import os

from dotenv import load_dotenv
from api_integration.edamam_integration import get_recipe
from api_integration.openai_integration import alt_recipe_query
# from db.recipe_sql import (create_tables, store_original_recipe, store_alt_recipe, lookup_prev_recipe, reset_database)
from db.recipe_sql import (create_tables, store_original_recipe, store_alt_recipe, lookup_prev_recipe, select_recipe, reset_database)

# Importing env variables for API authentication
load_dotenv()
Expand All @@ -23,18 +23,18 @@ def main():
choice = input(
"Type \"make\" to make a recipe,"
" \"lookup\" to find a previously made recipe,"
" \"exit\" to quit the program! "
"or \"reset\" to clear database "
" \"exit\" to quit the program,"
" or \"reset\" to clear database! "
)

if choice.lower() == "reset":
reset_database()
elif choice.lower() == "make":
make_recipe()
# elif choice.lower() == "lookup":
# lookup_prev_recipe()
elif choice.lower() == "lookup":
lookup_db()
elif choice.lower() == "exit":
break
exit()
else:
print("Choice not valid, please try again!\n")

Expand All @@ -49,32 +49,37 @@ def make_recipe():
for ingredient in recipe_query['ingredients']:
ingredients.append(ingredient)
recipe_link = recipe_query['url']
# store_original_recipe(original_name, ingredients, recipe_link)
store_original_recipe(original_name, ingredients, recipe_link)

alt_recipe = alt_recipe_query(OPENAI_KEY, diet, recipe_query)
alt_name = alt_recipe['name']
alt_ingredients = alt_recipe['ingredients']
alt_instructions = alt_recipe['instructions']

# original_recipe_id = lookup_original_recipe_id(original_name, ingredients, recipe_link)
# store_alt_recipe(original_recipe_id, alt_name, alt_ingredients, alt_instructions)
original_recipe_id = lookup_original_recipe_id(original_name, ingredients, recipe_link)
store_alt_recipe(original_recipe_id, alt_name, alt_ingredients, alt_instructions)

print(f"\nAlternative Recipe: {alt_name}\nIngredients: {', '.join(alt_ingredients)}\nInstructions: {alt_instructions}\n")


# def lookup_original_recipe_id(name, ingredients, recipe_link):
# ingredients_str = ', '.join(ingredients)
def lookup_original_recipe_id(name, ingredients, recipe_link):
ingredients_str = ', '.join(ingredients)

with sqlite3.connect('recipes.db') as connection:
cursor = connection.cursor()
cursor.execute('SELECT id FROM original_recipes WHERE name = ? AND ingredients = ? AND recipe_link = ?', (name, ingredients_str, recipe_link))
row = cursor.fetchone()
if row:
return row[0]
else:
raise ValueError("Original recipe not found in the database.")

# with sqlite3.connect('recipes.db') as connection:
# cursor = connection.cursor()
# cursor.execute('SELECT id FROM original_recipes WHERE name = ? AND ingredients = ? AND recipe_link = ?', (name, ingredients_str, recipe_link))
# row = cursor.fetchone()
# if row:
# return row[0]
# else:
# raise ValueError("Original recipe not found in the database.")

def lookup_db():
if lookup_prev_recipe():
select_recipe()


if __name__ == "__main__":
# create_tables()
create_tables()
main()

0 comments on commit 4365262

Please sign in to comment.