2024-01-08 00:45:22 +00:00
|
|
|
import sqlite3
|
2024-01-13 01:54:04 +00:00
|
|
|
import product, recipe, db
|
2024-01-08 00:45:22 +00:00
|
|
|
|
2024-01-13 01:54:04 +00:00
|
|
|
from pydantic import BaseModel
|
|
|
|
|
from typing import List, Annotated
|
|
|
|
|
from fastapi import FastAPI, Depends, Query
|
2024-01-08 00:38:17 +00:00
|
|
|
from fastapi.middleware.cors import CORSMiddleware
|
2024-01-07 00:33:40 +00:00
|
|
|
|
|
|
|
|
app = FastAPI()
|
|
|
|
|
|
2024-01-08 00:38:17 +00:00
|
|
|
# Add CORS middleware
|
|
|
|
|
app.add_middleware(
|
|
|
|
|
CORSMiddleware,
|
|
|
|
|
allow_origins=["*"],
|
|
|
|
|
allow_credentials=True,
|
|
|
|
|
allow_methods=["*"],
|
|
|
|
|
allow_headers=["*"]
|
|
|
|
|
)
|
2024-01-07 00:33:40 +00:00
|
|
|
|
2024-01-08 00:38:17 +00:00
|
|
|
# Dependency to create SQLite connection
|
|
|
|
|
async def get_db():
|
|
|
|
|
sql_db = await db.connect()
|
|
|
|
|
try:
|
|
|
|
|
yield sql_db
|
|
|
|
|
finally:
|
2024-01-13 01:54:04 +00:00
|
|
|
await sql_db.close()
|
2024-01-08 00:38:17 +00:00
|
|
|
|
|
|
|
|
@app.get("/recipes/parse")
|
2024-01-13 03:21:38 +00:00
|
|
|
async def parse_recipe_handler(url: str, conn: sqlite3.Connection = Depends(get_db)) -> recipe.Recipe:
|
2024-01-08 00:45:22 +00:00
|
|
|
return await recipe.parse_recipe(conn, url)
|
|
|
|
|
|
|
|
|
|
@app.get("/recipes/ingredients/parse")
|
2024-01-13 01:54:04 +00:00
|
|
|
async def parse_ingredients(lines: Annotated[
|
|
|
|
|
List[str],
|
|
|
|
|
Query(alias="ingredients",
|
|
|
|
|
title="Array of ingredients to parse")],
|
2024-01-13 03:21:38 +00:00
|
|
|
conn: sqlite3.Connection = Depends(get_db)) -> List[recipe.Ingredient]:
|
2024-01-08 00:45:22 +00:00
|
|
|
ingredients = recipe.parse_ingredient_from_nlp(lines)
|
|
|
|
|
recipe.match_existing_products(conn, ingredients)
|
|
|
|
|
return ingredients
|
2024-01-08 00:38:17 +00:00
|
|
|
|
2024-01-13 01:54:04 +00:00
|
|
|
class ProductUrl(BaseModel):
|
|
|
|
|
url: str
|
|
|
|
|
tags: List[str] = []
|
|
|
|
|
|
|
|
|
|
@app.post("/products/")
|
2024-01-13 03:21:38 +00:00
|
|
|
async def create_product(url: ProductUrl, conn: sqlite3.Connection = Depends(get_db)) -> product.Product:
|
2024-01-13 01:54:04 +00:00
|
|
|
return await product.get_or_create(conn, url.url, url.tags)
|