mfraz commited on
Commit
807c861
·
verified ·
1 Parent(s): 515863e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +43 -24
app.py CHANGED
@@ -2,8 +2,8 @@ import streamlit as st
2
  import requests
3
  import chromadb
4
  from sentence_transformers import SentenceTransformer
5
- from bs4 import BeautifulSoup
6
- import json # Import json to convert dictionary to string
7
 
8
  # Initialize embedding model
9
  model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
@@ -13,6 +13,18 @@ DB_PATH = "./recipe_db"
13
  client = chromadb.PersistentClient(path=DB_PATH)
14
  collection = client.get_or_create_collection("recipes")
15
 
 
 
 
 
 
 
 
 
 
 
 
 
16
  # Check if ChromaDB has data, if not, insert sample data
17
  if not collection.count():
18
  sample_recipes = [
@@ -22,29 +34,27 @@ if not collection.count():
22
  {"name": "Chapli Kebab", "city": "Peshawar", "price": 400, "image": "https://example.com/chapli.jpg"},
23
  {"name": "Saag", "city": "Multan", "price": 600, "image": "https://example.com/saag.jpg"}
24
  ]
25
-
26
  for recipe in sample_recipes:
27
  embedding = model.encode(recipe["city"]).tolist()
28
  collection.add(
29
- ids=[recipe["name"]], # IDs should be unique
30
  embeddings=[embedding],
31
  documents=[json.dumps(recipe)] # Convert dictionary to string
32
  )
33
  print("Sample data added to ChromaDB")
34
 
35
- # Function to scrape restaurant data
36
- def scrape_restaurant_info(city, recipe):
37
- search_url = f"https://www.foodpanda.pk/restaurants?search={recipe}+{city}"
38
- headers = {"User-Agent": "Mozilla/5.0"}
39
- response = requests.get(search_url, headers=headers)
40
-
41
  restaurant_list = []
42
- if response.status_code == 200:
43
- soup = BeautifulSoup(response.text, "html.parser")
44
- items = soup.find_all("div", class_="vendor-info")
45
- for item in items[:5]: # Get top 5 restaurants
46
- name = item.find("span", class_="name").text if item.find("span", class_="name") else "Unknown"
47
- restaurant_list.append(name)
48
  return restaurant_list
49
 
50
  # Streamlit UI
@@ -53,12 +63,15 @@ st.title("Pakistani Famous Recipes Finder 🍛")
53
  # User inputs city
54
  city = st.text_input("Enter a Pakistani City (e.g., Lahore, Karachi, Islamabad)").strip()
55
 
 
 
 
56
  # Optional: User inputs recipe (not mandatory)
57
- query = st.text_input("Enter a Recipe Name (Optional)").strip()
58
 
59
  if st.button("Find Recipes & Restaurants"):
60
  if city:
61
- if query:
62
  # Retrieve specific recipe info from vector DB
63
  query_embedding = model.encode(query).tolist()
64
  results = collection.query(query_embedding, n_results=5)
@@ -69,11 +82,11 @@ if st.button("Find Recipes & Restaurants"):
69
  for recipe_json in doc:
70
  recipe = json.loads(recipe_json) # Convert back to dictionary
71
  st.write(f"**Recipe:** {recipe['name']}")
72
- st.image(recipe["image"], caption=recipe["name"], use_column_width=True)
73
  st.write(f"Price: {recipe['price']} PKR")
74
 
75
- # Fetch restaurant data via scraping
76
- restaurants = scrape_restaurant_info(city, query)
77
  if restaurants:
78
  st.subheader("Available at These Restaurants:")
79
  for r in restaurants:
@@ -94,9 +107,15 @@ if st.button("Find Recipes & Restaurants"):
94
  for recipe_json in doc:
95
  recipe = json.loads(recipe_json) # Convert back to dictionary
96
  st.write(f"**Recipe:** {recipe['name']}")
97
- st.image(recipe["image"], caption=recipe["name"], use_column_width=True)
98
  st.write(f"Price: {recipe['price']} PKR")
99
- else:
100
- st.write(f"No famous recipes found for {city}.")
 
 
 
 
 
 
101
  else:
102
  st.warning("Please enter a city name.")
 
2
  import requests
3
  import chromadb
4
  from sentence_transformers import SentenceTransformer
5
+ import json
6
+ import googlemaps
7
 
8
  # Initialize embedding model
9
  model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
 
13
  client = chromadb.PersistentClient(path=DB_PATH)
14
  collection = client.get_or_create_collection("recipes")
15
 
16
+ # Google Places API Key (Replace with your key)
17
+ GOOGLE_API_KEY = "YOUR_GOOGLE_PLACES_API_KEY"
18
+ gmaps = googlemaps.Client(key=GOOGLE_API_KEY)
19
+
20
+ # Predefined Recipe Categories
21
+ recipe_categories = {
22
+ "Desi": ["Nihari", "Karahi", "Biryani", "Haleem", "Saag"],
23
+ "Fast Food": ["Burger", "Pizza", "Fries", "Shawarma"],
24
+ "BBQ": ["Tikka", "Seekh Kebab", "Malai Boti"],
25
+ "Seafood": ["Prawn Karahi", "Grilled Fish", "Fried Fish"]
26
+ }
27
+
28
  # Check if ChromaDB has data, if not, insert sample data
29
  if not collection.count():
30
  sample_recipes = [
 
34
  {"name": "Chapli Kebab", "city": "Peshawar", "price": 400, "image": "https://example.com/chapli.jpg"},
35
  {"name": "Saag", "city": "Multan", "price": 600, "image": "https://example.com/saag.jpg"}
36
  ]
37
+
38
  for recipe in sample_recipes:
39
  embedding = model.encode(recipe["city"]).tolist()
40
  collection.add(
41
+ ids=[recipe["name"]],
42
  embeddings=[embedding],
43
  documents=[json.dumps(recipe)] # Convert dictionary to string
44
  )
45
  print("Sample data added to ChromaDB")
46
 
47
+ # Function to fetch restaurant data using Google Places API
48
+ def get_restaurants(city, recipe):
49
+ query = f"{recipe} restaurant in {city}"
50
+ places_result = gmaps.places(query=query, type="restaurant")
51
+
 
52
  restaurant_list = []
53
+ if "results" in places_result:
54
+ for place in places_result["results"][:5]: # Get top 5 restaurants
55
+ name = place.get("name", "Unknown Restaurant")
56
+ address = place.get("vicinity", "Unknown Address")
57
+ restaurant_list.append(f"{name} - {address}")
 
58
  return restaurant_list
59
 
60
  # Streamlit UI
 
63
  # User inputs city
64
  city = st.text_input("Enter a Pakistani City (e.g., Lahore, Karachi, Islamabad)").strip()
65
 
66
+ # User selects recipe type
67
+ recipe_type = st.selectbox("Select Recipe Type", options=list(recipe_categories.keys()))
68
+
69
  # Optional: User inputs recipe (not mandatory)
70
+ query = st.selectbox("Select a Recipe (Optional)", ["Any"] + recipe_categories[recipe_type])
71
 
72
  if st.button("Find Recipes & Restaurants"):
73
  if city:
74
+ if query != "Any":
75
  # Retrieve specific recipe info from vector DB
76
  query_embedding = model.encode(query).tolist()
77
  results = collection.query(query_embedding, n_results=5)
 
82
  for recipe_json in doc:
83
  recipe = json.loads(recipe_json) # Convert back to dictionary
84
  st.write(f"**Recipe:** {recipe['name']}")
85
+ st.image(recipe["image"], caption=recipe["name"], use_container_width=True)
86
  st.write(f"Price: {recipe['price']} PKR")
87
 
88
+ # Fetch restaurant data
89
+ restaurants = get_restaurants(city, query)
90
  if restaurants:
91
  st.subheader("Available at These Restaurants:")
92
  for r in restaurants:
 
107
  for recipe_json in doc:
108
  recipe = json.loads(recipe_json) # Convert back to dictionary
109
  st.write(f"**Recipe:** {recipe['name']}")
110
+ st.image(recipe["image"], caption=recipe["name"], use_container_width=True)
111
  st.write(f"Price: {recipe['price']} PKR")
112
+
113
+ # Fetch restaurant data for multiple recipes
114
+ for recipe_name in recipe_categories[recipe_type]:
115
+ restaurants = get_restaurants(city, recipe_name)
116
+ if restaurants:
117
+ st.subheader(f"Where to find {recipe_name}:")
118
+ for r in restaurants:
119
+ st.write(f"- {r}")
120
  else:
121
  st.warning("Please enter a city name.")