Ujeshhh's picture
Update app.py
77bf577 verified
import gradio as gr
import os
import google.generativeai as genai
import logging
# Suppress unnecessary logs
logging.getLogger().setLevel(logging.ERROR)
# Load the Gemini API key from Hugging Face secrets
GEMINI_API_KEY = os.getenv('GEMINI_API_KEY')
# Configure Gemini API
if GEMINI_API_KEY:
genai.configure(api_key=GEMINI_API_KEY)
else:
print("Error: Gemini API key not found. Please set GEMINI_API_KEY in Hugging Face secrets.")
# Initialize Gemini model
model = None
try:
model = genai.GenerativeModel('learnlm-2.0-flash-experimental')
except Exception as e:
print(f"Error initializing Gemini model: {e}. Falling back to gemini-1.5-flash.")
try:
model = genai.GenerativeModel('gemini-1.5-flash')
except Exception as fallback_e:
print(f"Error initializing fallback model: {fallback_e}")
# Chatbot function using Gemini
def gradio_chatbot(user_query, *args, **kwargs):
if not user_query.strip():
return "Please enter a valid query."
if not model:
return "Error: Gemini model not initialized. Check API key and try again."
# Prompt to restrict Gemini to restaurant-related responses
prompt = """
You are a helpful and friendly restaurant recommendation chatbot. A user will provide their preferences or ask for restaurant information in their message. Your goal is to respond with relevant details about Chennai-based restaurants, focusing on their key features, estimated cost, and customer ratings. If you don't have specific information about a restaurant or cannot address the user's request based on the available data, please state that you don't have enough information or cannot find a suitable match.
Based on the user's message, please try to identify and provide information about restaurants, addressing the following aspects where possible:
* **Restaurant Name:** The name of the restaurant.
* **Cuisine:** What type of food does this restaurant primarily serve? If the user expressed a cuisine preference, how well does this restaurant align?
* **Ambiance:** Describe the atmosphere and decor of the restaurant. If the user mentioned a desired ambiance, is this restaurant likely to match?
* **Key Features:** What are some notable features or highlights of this restaurant (e.g., rooftop seating, live music, private dining rooms, special dietary options)? Are any of these features relevant to the user's request?
* **Cost:** What is the estimated cost for a typical meal for two people (appetizers, main courses, and drinks)? Please provide a price range if possible (e.g., ₹500-₹1500, $$).
* **Ratings:** What is the average customer rating for this restaurant (e.g., out of 5 stars, percentage)? If available, mention the source of the rating (e.g., Google Reviews, Zomato).
* **Why it might be a good fit (if applicable):** Briefly explain why this restaurant might be a good option based on the user's query.
* **Location (Optional):** Briefly mention the general location or a nearby landmark in Chennai.
Please provide your response in a clear and informative manner. If the user asked for a specific restaurant, provide details about it. If they asked for recommendations based on preferences, suggest a few suitable options.
User query: {user_query}
Answer:
"""
try:
response = model.generate_content(prompt.format(user_query=user_query))
if hasattr(response, 'text') and response.text:
return response.text.strip()
else:
return "Error: No valid response from Gemini model."
except Exception as e:
return f"Error generating response: {e}"
# Create Gradio ChatInterface for messenger-like UI
iface = gr.ChatInterface(
fn=gradio_chatbot,
title="Restaurant Chatbot",
description="Ask about restaurants, such as cuisine, ambiance, features, costs, or ratings.",
theme="soft",
examples=[
"What are the features of Amethyst Cafe?",
"Recommend a romantic dinner spot in Chennai",
"What is the cost for two at Barbeque Nation?",
"Recommend some budget friendly restaurants"
]
)
# Launch the app
if __name__ == "__main__":
iface.launch(server_name="0.0.0.0", server_port=7860)