Spaces:
Sleeping
Sleeping
File size: 4,162 Bytes
c2b6ff9 401512a c2b6ff9 2549820 4679a37 778c37c 4679a37 778c37c 4679a37 c2b6ff9 4679a37 778c37c 4679a37 c2b6ff9 4679a37 c2b6ff9 4679a37 c2b6ff9 4679a37 c2b6ff9 4679a37 63a20dd 4679a37 63a20dd 4679a37 63a20dd 4679a37 63a20dd 4679a37 778c37c a892d49 4679a37 778c37c c2b6ff9 778c37c c2b6ff9 778c37c c2b6ff9 778c37c 63a20dd 4679a37 63a20dd 778c37c c2b6ff9 4679a37 c2b6ff9 4679a37 c2b6ff9 778c37c c2b6ff9 4679a37 c2b6ff9 |
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 130 131 132 133 134 135 136 137 138 139 140 141 142 |
import os
import re
import gradio as gr
from gtts import gTTS
from datetime import datetime
from openpyxl import Workbook, load_workbook
from langchain.memory import ConversationBufferMemory
# --- Gemini setup ---
import google.generativeai as genai
genai.configure(api_key="AIzaSyBJFmohAmhmqXQlM3fVxj8MLegVb26kyJk")
model = genai.GenerativeModel("models/gemini-1.5-flash-latest")
# --- Restaurant menu ---
MENU = {
"Cheeseburger": 5.99,
"Fries": 2.99,
"Coke": 1.99,
"Pizza": 12.99,
"Chicken Wings": 7.99,
"Salad": 6.99
}
# --- Memory with LangChain ---
memory = ConversationBufferMemory(return_messages=True)
chat_history = []
order = []
customer_name = ""
# --- Excel Setup ---
EXCEL_FILE = "orders.xlsx"
def setup_excel():
if not os.path.exists(EXCEL_FILE):
wb = Workbook()
ws = wb.active
ws.title = "Orders"
ws.append(["Order ID", "Date", "Customer", "Items", "Total", "Time"])
wb.save(EXCEL_FILE)
setup_excel()
def save_to_excel(name, items):
wb = load_workbook(EXCEL_FILE)
ws = wb.active
order_id = f"ORD{ws.max_row:04d}"
now = datetime.now()
total = sum(qty * MENU[item] for item, qty in items)
items_str = ", ".join(f"{qty} x {item}" for item, qty in items)
ws.append([order_id, now.strftime("%Y-%m-%d"), name, items_str, f"${total:.2f}", now.strftime("%H:%M:%S")])
wb.save(EXCEL_FILE)
return order_id
# --- TTS ---
def clean_text(text):
text = re.sub(r"\*\*(.*?)\*\*", r"\1", text) # Remove bold
text = re.sub(r"Bot\s*:\s*", "", text, flags=re.IGNORECASE) # Remove "Bot:"
return text.strip()
def speak(text, filename="response.mp3"):
tts = gTTS(text=clean_text(text))
tts.save(filename)
return filename
# --- Generate Gemini response ---
def generate_response(user_input):
global order, customer_name
menu_str = "\n".join([f"{item}: ${price}" for item, price in MENU.items()])
order_summary = ", ".join([f"{qty} x {item}" for item, qty in order]) if order else "No items yet"
prompt = f"""
You are a friendly, intelligent restaurant assistant at 'Systaurant'.
Menu:
{menu_str}
Customer Name: {customer_name}
Current Order: {order_summary}
Instructions:
- Ask for name if not known
- Show menu if asked
- Extract food items and quantity
- Say "Order summary" and ask "Confirm?" when user is done
- Respond naturally, no "Bot:" prefix
Conversation so far:
"""
for m in memory.chat_memory.messages:
role = "Customer" if m.type == "human" else "Bot"
prompt += f"{role}: {m.content}\n"
prompt += f"Customer: {user_input}\nBot:"
try:
response = model.generate_content(prompt)
return response.text
except Exception as e:
return f"β Gemini Error: {e}"
# --- Chat handler ---
def handle_chat(user_input):
global customer_name, order
memory.chat_memory.add_user_message(user_input)
bot_reply = generate_response(user_input)
memory.chat_memory.add_ai_message(bot_reply)
if "my name is" in user_input.lower():
customer_name = user_input.split("my name is")[-1].strip().split()[0].title()
for item in MENU:
if item.lower() in user_input.lower():
qty = 1
for word in user_input.lower().split():
if word.isdigit():
qty = int(word)
break
order.append((item, qty))
if "confirm" in user_input.lower() or "yes" in user_input.lower():
if customer_name and order:
order_id = save_to_excel(customer_name, order)
bot_reply += f"\nβ
Your order ID is {order_id}. Thank you for ordering from Systaurant!"
audio_file = speak(bot_reply)
return bot_reply, audio_file
# --- Gradio UI ---
gr.Interface(
fn=handle_chat,
inputs=gr.Textbox(label="π€ You", placeholder="Type your order here..."),
outputs=[
gr.Textbox(label="π€ Bot Response"),
gr.Audio(label="π Speaking", autoplay=True)
],
title="π Systaurant Voice Bot",
description="A smart voice-enabled assistant to take food orders.",
theme="soft"
).launch(share=True)
|