Recipes-Search / app.py
mfraz's picture
Update app.py
24e52c2 verified
raw
history blame
5.13 kB
import streamlit as st
import requests
import chromadb
from sentence_transformers import SentenceTransformer
import json
# Initialize embedding model
model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
# Connect to ChromaDB (Persistent)
DB_PATH = "./recipe_db"
client = chromadb.PersistentClient(path=DB_PATH)
collection = client.get_or_create_collection("recipes")
# Predefined Recipe Categories
recipe_categories = {
"Desi": ["Nihari", "Karahi", "Biryani", "Haleem", "Saag"],
"Fast Food": ["Burger", "Pizza", "Fries", "Shawarma"],
"BBQ": ["Tikka", "Seekh Kebab", "Malai Boti"],
"Seafood": ["Prawn Karahi", "Grilled Fish", "Fried Fish"]
}
# Check if ChromaDB has data, if not, insert sample data
if not collection.count():
sample_recipes = [
{"name": "Nihari", "city": "Lahore", "price": 800, "image": "https://example.com/nihari.jpg"},
{"name": "Karahi", "city": "Lahore", "price": 1200, "image": "https://example.com/karahi.jpg"},
{"name": "Biryani", "city": "Karachi", "price": 500, "image": "https://example.com/biryani.jpg"},
{"name": "Chapli Kebab", "city": "Peshawar", "price": 400, "image": "https://example.com/chapli.jpg"},
{"name": "Saag", "city": "Multan", "price": 600, "image": "https://example.com/saag.jpg"}
]
for recipe in sample_recipes:
embedding = model.encode(recipe["city"]).tolist()
collection.add(
ids=[recipe["name"]],
embeddings=[embedding],
documents=[json.dumps(recipe)] # Convert dictionary to string
)
print("Sample data added to ChromaDB")
# Function to fetch restaurant data using Overpass API
def get_restaurants(city):
overpass_url = "http://overpass-api.de/api/interpreter"
query = f"""
[out:json];
area[name="{city}"]->.searchArea;
node["amenity"="restaurant"](area.searchArea);
out;
"""
response = requests.get(overpass_url, params={'data': query})
if response.status_code == 200:
data = response.json()
restaurants = []
for element in data.get("elements", []):
name = element.get("tags", {}).get("name", "Unknown Restaurant")
restaurants.append(name)
return restaurants[:5] # Return top 5 results
else:
return ["No restaurant data found."]
# Streamlit UI
st.title("Pakistani Famous Recipes Finder πŸ›")
# User inputs city
city = st.text_input("Enter a Pakistani City (e.g., Lahore, Karachi, Islamabad)").strip()
# User selects recipe type
recipe_type = st.selectbox("Select Recipe Type", options=list(recipe_categories.keys()))
# Optional: User inputs recipe (not mandatory)
query = st.selectbox("Select a Recipe (Optional)", ["Any"] + recipe_categories[recipe_type])
if st.button("Find Recipes & Restaurants"):
if city:
if query != "Any":
# Retrieve specific recipe info from vector DB
query_embedding = model.encode(query).tolist()
results = collection.query(query_embedding, n_results=5)
if results and "documents" in results and results["documents"]:
st.subheader(f"Famous {query} in {city}")
for doc in results["documents"]:
for recipe_json in doc:
recipe = json.loads(recipe_json) # Convert back to dictionary
st.write(f"**Recipe:** {recipe['name']}")
st.image(recipe["image"], caption=recipe["name"], use_container_width=True)
st.write(f"Price: {recipe['price']} PKR")
# Fetch restaurant data
restaurants = get_restaurants(city)
if restaurants:
st.subheader("Available at These Restaurants:")
for r in restaurants:
st.write(f"- {r}")
else:
st.write("No restaurant data found.")
else:
st.write(f"No matching recipes found for '{query}' in {city}.")
else:
# Retrieve all famous recipes in the city
city_embedding = model.encode(city).tolist()
results = collection.query(city_embedding, n_results=5)
if results and "documents" in results and results["documents"]:
st.subheader(f"Famous Recipes in {city}")
for doc in results["documents"]:
for recipe_json in doc:
recipe = json.loads(recipe_json) # Convert back to dictionary
st.write(f"**Recipe:** {recipe['name']}")
st.image(recipe["image"], caption=recipe["name"], use_container_width=True)
st.write(f"Price: {recipe['price']} PKR")
# Fetch restaurant data for multiple recipes
restaurants = get_restaurants(city)
if restaurants:
st.subheader("Popular Restaurants in This City:")
for r in restaurants:
st.write(f"- {r}")
else:
st.warning("Please enter a city name.")