Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,150 +1,33 @@
|
|
| 1 |
-
import
|
| 2 |
-
import
|
| 3 |
-
import gradio as gr
|
| 4 |
-
from gtts import gTTS
|
| 5 |
-
from datetime import datetime
|
| 6 |
-
from openpyxl import Workbook, load_workbook
|
| 7 |
-
from langchain.memory import ConversationBufferMemory
|
| 8 |
-
|
| 9 |
-
from transformers import AutoTokenizer, AutoModelForCausalLM
|
| 10 |
import torch
|
| 11 |
|
| 12 |
-
|
| 13 |
-
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 14 |
-
tokenizer = AutoTokenizer.from_pretrained("distilgpt2")
|
| 15 |
-
model = AutoModelForCausalLM.from_pretrained("distilgpt2").to(device)
|
| 16 |
-
model.eval()
|
| 17 |
-
|
| 18 |
-
# --- Restaurant menu ---
|
| 19 |
-
MENU = {
|
| 20 |
-
"Cheeseburger": 5.99,
|
| 21 |
-
"Fries": 2.99,
|
| 22 |
-
"Coke": 1.99,
|
| 23 |
-
"Pizza": 12.99,
|
| 24 |
-
"Chicken Wings": 7.99,
|
| 25 |
-
"Salad": 6.99
|
| 26 |
-
}
|
| 27 |
-
|
| 28 |
-
# --- Memory with LangChain ---
|
| 29 |
-
memory = ConversationBufferMemory(return_messages=True)
|
| 30 |
-
order = []
|
| 31 |
-
customer_name = ""
|
| 32 |
-
|
| 33 |
-
# --- Excel Setup ---
|
| 34 |
-
EXCEL_FILE = "orders.xlsx"
|
| 35 |
-
def setup_excel():
|
| 36 |
-
if not os.path.exists(EXCEL_FILE):
|
| 37 |
-
wb = Workbook()
|
| 38 |
-
ws = wb.active
|
| 39 |
-
ws.title = "Orders"
|
| 40 |
-
ws.append(["Order ID", "Date", "Customer", "Items", "Total", "Time"])
|
| 41 |
-
wb.save(EXCEL_FILE)
|
| 42 |
-
setup_excel()
|
| 43 |
-
|
| 44 |
-
def save_to_excel(name, items):
|
| 45 |
-
wb = load_workbook(EXCEL_FILE)
|
| 46 |
-
ws = wb.active
|
| 47 |
-
order_id = f"ORD{ws.max_row:04d}"
|
| 48 |
-
now = datetime.now()
|
| 49 |
-
total = sum(qty * MENU[item] for item, qty in items)
|
| 50 |
-
items_str = ", ".join(f"{qty} x {item}" for item, qty in items)
|
| 51 |
-
ws.append([order_id, now.strftime("%Y-%m-%d"), name, items_str, f"${total:.2f}", now.strftime("%H:%M:%S")])
|
| 52 |
-
wb.save(EXCEL_FILE)
|
| 53 |
-
return order_id
|
| 54 |
-
|
| 55 |
-
# --- TTS ---
|
| 56 |
-
def clean_text(text):
|
| 57 |
-
text = re.sub(r"\*\*(.*?)\*\*", r"\1", text)
|
| 58 |
-
text = re.sub(r"Bot\s*:\s*", "", text, flags=re.IGNORECASE)
|
| 59 |
-
return text.strip()
|
| 60 |
-
|
| 61 |
-
def speak(text, filename="response.mp3"):
|
| 62 |
-
tts = gTTS(text=clean_text(text))
|
| 63 |
-
tts.save(filename)
|
| 64 |
-
return filename
|
| 65 |
-
|
| 66 |
-
# --- Generate GPT-2 response ---
|
| 67 |
-
def generate_response(user_input):
|
| 68 |
-
global order, customer_name
|
| 69 |
-
|
| 70 |
-
menu_str = "\n".join([f"{item}: ${price}" for item, price in MENU.items()])
|
| 71 |
-
order_summary = ", ".join([f"{qty} x {item}" for item, qty in order]) if order else "No items yet"
|
| 72 |
-
|
| 73 |
-
prompt = f"""
|
| 74 |
-
You are a friendly restaurant assistant at 'Systaurant'.
|
| 75 |
-
Here is the menu:
|
| 76 |
-
{menu_str}
|
| 77 |
-
|
| 78 |
-
Customer name: {customer_name or "Unknown"}
|
| 79 |
-
Current order: {order_summary}
|
| 80 |
-
|
| 81 |
-
Instructions:
|
| 82 |
-
- Ask for the customer's name if not known
|
| 83 |
-
- Show the menu if asked
|
| 84 |
-
- Detect food items and quantity
|
| 85 |
-
- Provide order summary and ask to confirm
|
| 86 |
-
|
| 87 |
-
Conversation history:
|
| 88 |
-
"""
|
| 89 |
-
|
| 90 |
-
for m in memory.chat_memory.messages:
|
| 91 |
-
role = "Customer" if m.type == "human" else "Bot"
|
| 92 |
-
prompt += f"{role}: {m.content}\n"
|
| 93 |
-
|
| 94 |
-
prompt += f"Customer: {user_input}\nBot:"
|
| 95 |
-
|
| 96 |
-
inputs = tokenizer(prompt, return_tensors="pt", truncation=True).to(device)
|
| 97 |
-
|
| 98 |
-
outputs = model.generate(
|
| 99 |
-
**inputs,
|
| 100 |
-
max_new_tokens=80,
|
| 101 |
-
temperature=0.7,
|
| 102 |
-
top_p=0.9,
|
| 103 |
-
do_sample=True,
|
| 104 |
-
pad_token_id=tokenizer.eos_token_id
|
| 105 |
-
)
|
| 106 |
-
|
| 107 |
-
output_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
| 108 |
-
bot_reply = output_text.split("Bot:")[-1].strip()
|
| 109 |
-
return bot_reply
|
| 110 |
-
|
| 111 |
-
# --- Chat handler ---
|
| 112 |
-
def handle_chat(user_input):
|
| 113 |
-
global customer_name, order
|
| 114 |
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
|
|
|
| 118 |
|
| 119 |
-
|
| 120 |
-
customer_name = user_input.split("my name is")[-1].strip().split()[0].title()
|
| 121 |
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
break
|
| 129 |
-
order.append((item, qty))
|
| 130 |
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 135 |
|
| 136 |
-
|
| 137 |
-
return bot_reply, audio_file
|
| 138 |
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
fn=handle_chat,
|
| 142 |
-
inputs=gr.Textbox(label="π€ You", placeholder="Type your order here..."),
|
| 143 |
-
outputs=[
|
| 144 |
-
gr.Textbox(label="π€ Bot Response"),
|
| 145 |
-
gr.Audio(label="π Speaking", autoplay=True)
|
| 146 |
-
],
|
| 147 |
-
title="π Systaurant Voice Bot",
|
| 148 |
-
description="A smart voice-enabled assistant to take food orders.",
|
| 149 |
-
theme="soft"
|
| 150 |
-
).launch(share=True)
|
|
|
|
| 1 |
+
from flask import Flask, request, jsonify
|
| 2 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
import torch
|
| 4 |
|
| 5 |
+
app = Flask(__name__)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
|
| 7 |
+
# Load OpenChat model and tokenizer
|
| 8 |
+
MODEL_NAME = "openchat/openchat-3.5-0106"
|
| 9 |
+
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
|
| 10 |
+
model = AutoModelForCausalLM.from_pretrained(MODEL_NAME, torch_dtype=torch.float16, device_map="auto")
|
| 11 |
|
| 12 |
+
chatbot = pipeline("text-generation", model=model, tokenizer=tokenizer)
|
|
|
|
| 13 |
|
| 14 |
+
@app.route("/chat", methods=["POST"])
|
| 15 |
+
def chat():
|
| 16 |
+
data = request.get_json()
|
| 17 |
+
prompt = data.get("message", "")
|
| 18 |
+
if not prompt:
|
| 19 |
+
return jsonify({"error": "Empty message"}), 400
|
|
|
|
|
|
|
| 20 |
|
| 21 |
+
system_prompt = "<|system|>\nYou are a helpful assistant for food ordering.\n<|user|>\n" + prompt + "\n<|assistant|>\n"
|
| 22 |
+
output = chatbot(system_prompt, max_new_tokens=200, do_sample=True, temperature=0.7)[0]["generated_text"]
|
| 23 |
+
|
| 24 |
+
# Extract response after <|assistant|>
|
| 25 |
+
if "<|assistant|>" in output:
|
| 26 |
+
reply = output.split("<|assistant|>")[-1].strip()
|
| 27 |
+
else:
|
| 28 |
+
reply = output
|
| 29 |
|
| 30 |
+
return jsonify({"response": reply})
|
|
|
|
| 31 |
|
| 32 |
+
if __name__ == "__main__":
|
| 33 |
+
app.run(debug=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|