Recipes-Search / app.py
mfraz's picture
Update app.py
807c861 verified
raw
history blame
5.22 kB
import streamlit as st
import requests
import chromadb
from sentence_transformers import SentenceTransformer
import json
import googlemaps
# 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")
# Google Places API Key (Replace with your key)
GOOGLE_API_KEY = "YOUR_GOOGLE_PLACES_API_KEY"
gmaps = googlemaps.Client(key=GOOGLE_API_KEY)
# 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 Google Places API
def get_restaurants(city, recipe):
query = f"{recipe} restaurant in {city}"
places_result = gmaps.places(query=query, type="restaurant")
restaurant_list = []
if "results" in places_result:
for place in places_result["results"][:5]: # Get top 5 restaurants
name = place.get("name", "Unknown Restaurant")
address = place.get("vicinity", "Unknown Address")
restaurant_list.append(f"{name} - {address}")
return restaurant_list
# 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, query)
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
for recipe_name in recipe_categories[recipe_type]:
restaurants = get_restaurants(city, recipe_name)
if restaurants:
st.subheader(f"Where to find {recipe_name}:")
for r in restaurants:
st.write(f"- {r}")
else:
st.warning("Please enter a city name.")