Restaurants / app.py
Jacksonnavigator7's picture
Rename app to app.py
1339e4f verified
import json
import requests
import gradio as gr
import os
GROQ_API_KEY = os.getenv("GROQ_API_KEY") # Use environment variable for security
GROQ_MODEL = "mixtral-8x7b-32768"
with open("data/restaurants.json", "r") as f:
RESTAURANTS = json.load(f)
def query_groq(prompt: str) -> dict:
url = "https://api.groq.com/openai/v1/chat/completions"
headers = {
"Authorization": f"Bearer {GROQ_API_KEY}",
"Content-Type": "application/json"
}
data = {
"model": GROQ_MODEL,
"messages": [
{"role": "user", "content": prompt}
],
"temperature": 0.3
}
res = requests.post(url, headers=headers, json=data)
res.raise_for_status()
result = res.json()["choices"][0]["message"]["content"]
return json.loads(result)
def extract_preferences(query: str) -> dict:
prompt = f'''
Extract the following preferences from this user query:
- cuisine
- budget (in TZS)
- location
- ambiance
Query: "{query}"
Return as JSON with those exact keys.
'''
return query_groq(prompt)
def score_restaurant(r: dict, prefs: dict) -> float:
score = 0
if prefs.get("cuisine") and prefs["cuisine"].lower() in r["cuisine"].lower():
score += 1
if prefs.get("location") and prefs["location"].lower() in r["location"].lower():
score += 1
if prefs.get("ambiance") and prefs["ambiance"].lower() in r.get("ambiance", "").lower():
score += 1
if prefs.get("budget") and r.get("average_price", 0) <= prefs["budget"]:
score += 1
return score
def recommend_restaurants(query: str) -> str:
try:
prefs = extract_preferences(query)
scored = [(r, score_restaurant(r, prefs)) for r in RESTAURANTS]
ranked = sorted(scored, key=lambda x: x[1], reverse=True)
top = [r for r, s in ranked if s > 0][:5]
if not top:
return "Sorry, no matches found. Try another query."
return "\n\n".join([
f"🍽️ {r['name']}\nπŸ“ {r['location']}\nπŸ’° Avg Price: {r['average_price']} TZS\nπŸ₯˜ Cuisine: {r['cuisine']}\n🌟 Features: {', '.join(r.get('features', []))}" for r in top
])
except Exception as e:
return f"Error: {str(e)}"
iface = gr.Interface(
fn=recommend_restaurants,
inputs=gr.Textbox(label="Ask for a restaurant (e.g. Romantic place under 30,000 TZS)"),
outputs=gr.Textbox(label="Top Recommendations"),
title="🍴 Arusha Restaurant Recommender",
description="Powered by Groq LLM β€” Get smart, personalized restaurant suggestions in Arusha, Tanzania."
)
if __name__ == "__main__":
iface.launch()