File size: 2,658 Bytes
fc9a5bc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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()