File size: 5,286 Bytes
d1f76d7 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 | # app.py
import pandas as pd
import gradio as gr
import re
from sentence_transformers import SentenceTransformer
from sklearn.neighbors import NearestNeighbors
# -------------------------------
# Load dataset
# -------------------------------
df = pd.read_csv("food_order_cleaned.csv")
df['rating'] = pd.to_numeric(df['rating'], errors='coerce')
df['search_text'] = df['restaurant_name'].astype(str) + " | " + df['cuisine_type'].astype(str) + " | " + df['rating'].astype(str)
# -------------------------------
# Rule-based functions
# -------------------------------
def find_by_cuisine(cuisine, limit=10):
mask = df['cuisine_type'].str.strip().str.lower() == cuisine.strip().lower()
cols = ['restaurant_name', 'cuisine_type', 'cost_of_the_order', 'rating']
return df.loc[mask, cols].head(limit)
def best_rated_by_cuisine(cuisine, top_n=10):
mask = df['cuisine_type'].str.strip().str.lower() == cuisine.strip().lower()
subset = df[mask].dropna(subset=['rating']).sort_values('rating', ascending=False)
cols = ['restaurant_name', 'cuisine_type', 'cost_of_the_order', 'rating']
return subset[cols].head(top_n)
def cheapest_high_rated(max_cost=None, min_rating=4.0, top_n=10):
subset = df.dropna(subset=['rating'])
subset = subset[subset['rating'] >= min_rating]
if max_cost is not None:
subset = subset[subset['cost_of_the_order'] <= max_cost]
subset = subset.sort_values('cost_of_the_order')
cols = ['restaurant_name', 'cuisine_type', 'cost_of_the_order', 'rating']
return subset[cols].head(top_n)
def personalized_recall(customer_id, day):
mask = (df['customer_id'].astype(str) == str(customer_id)) & \
(df['day_of_the_week'].str.strip().str.lower() == day.strip().lower())
cols = ['order_id', 'restaurant_name', 'cuisine_type', 'cost_of_the_order', 'rating', 'day_of_the_week']
return df.loc[mask, cols]
# -------------------------------
# Semantic Search
# -------------------------------
model = SentenceTransformer('all-MiniLM-L6-v2')
corpus = df['search_text'].tolist()
corpus_embeddings = model.encode(corpus, show_progress_bar=True)
nn = NearestNeighbors(n_neighbors=10, metric='cosine').fit(corpus_embeddings)
def semantic_search(query, k=5):
q_emb = model.encode([query])
dists, idxs = nn.kneighbors(q_emb, n_neighbors=k)
results = df.iloc[idxs[0]].copy()
results['score'] = 1 - dists[0]
cols = ['restaurant_name', 'cuisine_type', 'cost_of_the_order', 'rating', 'score']
return results[cols]
# -------------------------------
# Combined Chat Handler
# -------------------------------
def handle_query(message, customer_id="", history=[]):
text = message.strip().lower()
# Rule-Based: Specific Recommendation
if 'find' in text and 'restaurant' in text:
known = set(df['cuisine_type'].str.strip().str.lower().unique())
words = text.split()
found = [w for w in words if w in known]
if found:
res = find_by_cuisine(found[0])
return res.to_html(index=False)
else:
return semantic_search(message).to_html(index=False)
# Rule-Based: Best Rated
if 'best' in text and ('place' in text or 'best-rated' in text):
known = set(df['cuisine_type'].str.strip().str.lower().unique())
words = text.split()
found = [w for w in words if w in known]
if found:
res = best_rated_by_cuisine(found[0])
return res.to_html(index=False)
else:
return semantic_search(message).to_html(index=False)
# Rule-Based: Cheapest / Value Search
if 'cheapest' in text or 'cheap' in text or 'value' in text:
res = cheapest_high_rated(min_rating=4.0, top_n=10)
return res.to_html(index=False)
# Rule-Based: Personalized Recall
if 'what did i order' in text:
day_match = re.search(r'on (\w+)', text)
day = day_match.group(1) if day_match else ''
if customer_id == '':
return "Please enter your customer_id in the input box."
if day == '':
return "Please specify the day, e.g. 'on Weekend'."
res = personalized_recall(customer_id, day)
if res.empty:
return "No orders found for that customer/day."
return res.to_html(index=False)
# Fallback: Semantic Search
return semantic_search(message).to_html(index=False)
# -------------------------------
# Gradio Chatbot Interface
# -------------------------------
def chat_reply(history, message, customer_id):
reply = handle_query(message, customer_id)
history.append((message, reply))
return history, ""
with gr.Blocks(title="Restaurant Guide Chatbot") as demo:
gr.Markdown("## Restaurant Guide Chatbot\nAsk queries like:\n- Find me a Thai restaurant\n- What are the best Italian places?\n- Show me the cheapest highly-rated places\n- What did I order on Weekend? (enter customer_id)")
chatbot = gr.Chatbot()
with gr.Row():
user_msg = gr.Textbox(placeholder="Type your message here...")
cust_id = gr.Textbox(label="Customer ID (optional)")
send = gr.Button("Send")
send.click(chat_reply, inputs=[chatbot, user_msg, cust_id], outputs=[chatbot, user_msg])
demo.launch()
|