File size: 9,089 Bytes
408a4d8 |
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 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 |
import pyttsx3
import speech_recognition as sr
from datetime import datetime
from flask import Flask, render_template_string, request, jsonify
app = Flask(__name__)
# Initialize text-to-speech engine
engine = pyttsx3.init()
# Initialize an empty list to store orders
orders = []
user_preferences = {"diet": "all"} # Default to all
# HTML code for the frontend
html_code = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AI Dining Assistant</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f4f4f9;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100vh;
margin: 0;
}
h1 {
color: #333;
}
.mic-button {
width: 80px;
height: 80px;
border-radius: 50%;
background-color: #007bff;
color: white;
font-size: 24px;
border: none;
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
box-shadow: 0px 4px 6px rgba(0, 0, 0, 0.1);
transition: background-color 0.3s;
}
.mic-button:hover {
background-color: #0056b3;
}
.status {
margin-top: 20px;
font-size: 18px;
color: #666;
}
.listening {
color: green;
font-weight: bold;
}
.response {
margin-top: 20px;
padding: 10px;
background-color: #fff;
border: 1px solid #ddd;
border-radius: 5px;
box-shadow: 0px 4px 6px rgba(0, 0, 0, 0.1);
width: 300px;
text-align: center;
}
</style>
</head>
<body>
<h1>AI Dining Assistant</h1>
<button class="mic-button" id="mic-button">🎤</button>
<div class="status" id="status">Press the mic button to start listening...</div>
<div class="response" id="response" style="display: none;">Response will appear here...</div>
<script>
const micButton = document.getElementById('mic-button');
const status = document.getElementById('status');
const response = document.getElementById('response');
if (!window.MediaRecorder) {
alert("Your browser does not support audio recording.");
}
let mediaRecorder;
let audioChunks = [];
micButton.addEventListener('click', async () => {
navigator.mediaDevices.getUserMedia({ audio: true })
.then(stream => {
mediaRecorder = new MediaRecorder(stream);
mediaRecorder.start();
status.textContent = 'Listening...';
status.classList.add('listening');
mediaRecorder.ondataavailable = event => {
audioChunks.push(event.data);
};
mediaRecorder.onstop = async () => {
const audioBlob = new Blob(audioChunks, { type: 'audio/wav' });
const formData = new FormData();
formData.append('audio', audioBlob);
status.textContent = 'Processing...';
status.classList.remove('listening');
try {
const result = await fetch('/process-audio', {
method: 'POST',
body: formData,
});
const data = await result.json();
response.textContent = data.response;
response.style.display = 'block';
status.textContent = 'Press the mic button to start listening...';
} catch (error) {
response.textContent = 'Error occurred. Please try again.';
response.style.display = 'block';
status.textContent = 'Press the mic button to start listening...';
}
};
setTimeout(() => {
mediaRecorder.stop();
}, 5000); // Stop recording after 5 seconds
})
.catch(err => {
status.textContent = 'Microphone access denied.';
});
});
</script>
</body>
</html>
"""
@app.route('/')
def index():
return render_template_string(html_code)
@app.route('/process-audio', methods=['POST'])
def process_audio():
try:
audio_file = request.files['audio']
recognizer = sr.Recognizer()
with sr.AudioFile(audio_file) as source:
audio_data = recognizer.record(source)
command = recognizer.recognize_google(audio_data)
response = process_command(command)
return jsonify({"response": response})
except Exception as e:
return jsonify({"response": f"An error occurred: {str(e)}"})
def speak_text(text):
"""Speak the provided text."""
engine.say(text)
engine.runAndWait()
def get_greeting():
"""Return a greeting based on the current time."""
current_hour = datetime.now().hour
if current_hour < 12:
return "Good morning!"
elif 12 <= current_hour < 18:
return "Good afternoon!"
else:
return "Good evening!"
def filter_menu(menu):
"""Filter menu based on user preferences."""
filtered_menu = {}
for dish, details in menu.items():
if user_preferences["diet"] in details["type"] or user_preferences["diet"] == "all":
filtered_menu[dish] = details
return filtered_menu
def process_command(command):
"""Process the user's voice command and return a response."""
global orders, user_preferences
command = command.lower()
# Menu options
menu = {
# Veg items
"paneer butter masala": {"type": "veg"},
"dal makhani": {"type": "veg"},
"masala dosa": {"type": "veg"},
"idli sambhar": {"type": "veg"},
"fried rice": {"type": "veg"},
"hakka noodles": {"type": "veg"},
# Non-veg items
"butter chicken": {"type": "non-veg"},
"hyderabadi biryani": {"type": "non-veg"},
"chilli chicken": {"type": "non-veg"},
"fish curry": {"type": "non-veg"},
"tandoori chicken": {"type": "non-veg"},
"prawns masala": {"type": "non-veg"},
# Drinks
"masala chai": {"type": "all"},
"lassi": {"type": "all"},
"cold coffee": {"type": "all"},
"fresh lime soda": {"type": "all"}
}
# Handle preferences
if "veg" in command or "vegetarian" in command:
user_preferences["diet"] = "veg"
return "Vegetarian preference set."
elif "non-veg" in command or "non-vegetarian" in command:
user_preferences["diet"] = "non-veg"
return "Non-vegetarian preference set."
elif "mix" in command:
user_preferences["diet"] = "all"
return "Mixed preference set."
# Filtered menu based on preferences
filtered_menu = filter_menu(menu)
# Show menu
if "menu" in command:
if filtered_menu:
return "Our menu includes: " + ", ".join(filtered_menu.keys())
else:
return "No items match your preferences."
# Add to order
elif "order" in command or "add" in command:
for item in filtered_menu:
if item in command:
orders.append(item)
return f"{item} has been added to your order. Anything else you'd like to add?"
return "I'm sorry, I couldn't recognize the dish. Please try again."
# Remove from order
elif "remove" in command:
for item in orders:
if item in command:
orders.remove(item)
return f"{item} has been removed from your order. Anything else you'd like to modify?"
return "I'm sorry, I couldn't recognize the dish to remove. Please try again."
# Show order
elif "show order" in command or "what's my order" in command:
if orders:
return f"Your current order includes: {', '.join(orders)}."
else:
return "You haven't ordered anything yet."
# Thank you and exit
elif "thank you" in command or "bye" in command:
if orders:
return f"Thank you for your order! You have ordered: {', '.join(orders)}. Your food will arrive shortly. Have a great day!"
else:
return "Thank you! Your food will arrive shortly. Have a great day!"
else:
return "I'm sorry, I don't understand. Could you please repeat?"
if __name__ == "__main__":
app.run(debug=True, port=5000)
|