geethareddy commited on
Commit
2208db2
·
verified ·
1 Parent(s): 6dcad94

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +55 -104
app.py CHANGED
@@ -6,62 +6,20 @@ import ffmpeg
6
  import logging
7
  from werkzeug.exceptions import BadRequest
8
 
9
- # Initialize Flask App
10
  app = Flask(__name__)
11
-
12
- # Set up logging
13
  logging.basicConfig(level=logging.INFO)
14
 
15
- # Menu details
 
 
 
16
  MENU = {
17
- "Appetizer": {
18
- "Veg Samosas": 3,
19
- "Pakodas Onion": 9,
20
- "Pakodas Spinach": 9,
21
- "Pakodas Mixed Vegetable": 9,
22
- },
23
- "Manchurian": {
24
- "Vegetable": 12,
25
- "Gobi (Cauliflower florets)": 12,
26
- "Paneer (Cottage Cheese)": 13,
27
- "Chicken": 14,
28
- "Fish": 15,
29
- "Jhinga (Shrimp)": 17,
30
- },
31
- "Main Course Veg Section": {
32
- "Dal Fry": 11,
33
- "Dal Makhani": 12,
34
- "Channa Masala": 12,
35
- "Aloo Gobi Masala": 12,
36
- "Saag Paneer": 12,
37
- "Kadai Paneer": 12,
38
- "Paneer Butter Masala": 12,
39
- "Paneer Tikka Masala": 12,
40
- "Dum Ka Paneer": 12,
41
- },
42
- "Main Course Non-Veg Section": {
43
- "Chicken Saag": 15,
44
- "Gosht (Goat) Saag": 16,
45
- "Chicken Curry": 15,
46
- "Gosht (Goat) Curry": 16,
47
- "Butter Chicken": 15,
48
- "Tikka Masala Chicken": 15,
49
- },
50
- "Biryani": {
51
- "Vegetable": 12,
52
- "Egg": 12,
53
- "Paneer": 14,
54
- "Chicken Dum (Bone In)": 14,
55
- "Special Chicken (Boneless)": 15,
56
- "Shrimp": 17,
57
- "Kheema (Goat)": 17,
58
- },
59
  }
60
 
61
- # Cart for storing orders
62
- cart = []
63
-
64
- # HTML Template for Frontend
65
  html_code = """
66
  <!DOCTYPE html>
67
  <html lang="en">
@@ -72,13 +30,8 @@ html_code = """
72
  <style>
73
  body {
74
  font-family: Arial, sans-serif;
 
75
  background-color: #f4f4f9;
76
- display: flex;
77
- flex-direction: column;
78
- align-items: center;
79
- justify-content: center;
80
- height: 100vh;
81
- margin: 0;
82
  }
83
  h1 {
84
  color: #333;
@@ -91,37 +44,17 @@ html_code = """
91
  color: white;
92
  font-size: 24px;
93
  border: none;
94
- display: flex;
95
- align-items: center;
96
- justify-content: center;
97
  cursor: pointer;
98
- box-shadow: 0px 4px 6px rgba(0, 0, 0, 0.1);
99
- transition: background-color 0.3s;
100
- }
101
- .mic-button:hover {
102
- background-color: #0056b3;
103
  }
104
- .status {
105
  margin-top: 20px;
106
- font-size: 18px;
107
- color: #666;
108
- }
109
- .response {
110
- margin-top: 20px;
111
- padding: 10px;
112
- background-color: #fff;
113
- border: 1px solid #ddd;
114
- border-radius: 5px;
115
- box-shadow: 0px 4px 6px rgba(0, 0, 0, 0.1);
116
- width: 300px;
117
- text-align: center;
118
  }
119
  </style>
120
  </head>
121
  <body>
122
- <h1>BIRYANI HUB</h1>
123
  <button class="mic-button" id="mic-button">🎤</button>
124
- <div class="status" id="status">Press the mic button to start the conversation...</div>
125
  <div class="response" id="response" style="display: none;">Response will appear here...</div>
126
  <script>
127
  const micButton = document.getElementById('mic-button');
@@ -137,8 +70,12 @@ html_code = """
137
  });
138
 
139
  function startConversation() {
140
- status.textContent = 'Listening...';
141
- startListening();
 
 
 
 
142
  }
143
 
144
  function startListening() {
@@ -161,8 +98,8 @@ html_code = """
161
  const utterance = new SpeechSynthesisUtterance(data.response);
162
  speechSynthesis.speak(utterance);
163
  } catch (error) {
164
- response.textContent = 'Error occurred. Please try again.';
165
- status.textContent = 'Press the mic button to restart.';
166
  isConversationActive = false;
167
  }
168
  };
@@ -192,6 +129,9 @@ def process_audio():
192
  temp_file = NamedTemporaryFile(delete=False, suffix=".webm")
193
  audio_file.save(temp_file.name)
194
 
 
 
 
195
  converted_file = NamedTemporaryFile(delete=False, suffix=".wav")
196
  ffmpeg.input(temp_file.name).output(
197
  converted_file.name, acodec='pcm_s16le', ac=1, ar='16000'
@@ -200,37 +140,48 @@ def process_audio():
200
  recognizer = sr.Recognizer()
201
  with sr.AudioFile(converted_file.name) as source:
202
  audio_data = recognizer.record(source)
203
- command = recognizer.recognize_google(audio_data).lower()
204
- response = process_command(command)
 
 
 
205
 
206
  return jsonify({"response": response})
 
 
 
207
  except Exception as e:
208
- return jsonify({"response": f"Error: {str(e)}"})
209
  finally:
210
- if os.path.exists(temp_file.name):
211
- os.unlink(temp_file.name)
212
- if os.path.exists(converted_file.name):
213
- os.unlink(converted_file.name)
214
 
215
  def process_command(command):
216
  global cart
 
 
 
217
  if "menu" in command:
218
- menu_items = ". ".join(f"{category}: {', '.join(items.keys())}" for category, items in MENU.items())
219
- return f"Our menu includes: {menu_items}. What would you like to order?"
220
- elif "order" in command:
221
- for category, items in MENU.items():
222
- for item, price in items.items():
223
- if item.lower() in command:
224
- cart.append((item, price))
225
- return f"{item} has been added to your cart. Anything else?"
226
- elif "that's it" in command:
227
  if cart:
228
- total_price = sum(item[1] for item in cart)
229
- items = ", ".join(f"{item[0]} (${item[1]})" for item in cart)
230
- return f"Your cart includes: {items}. The total price is ${total_price}. Thank you for your order!"
 
231
  else:
232
- return "Your cart is empty. Thank you!"
233
- return "Sorry, I didn't understand. Please ask for the menu or place an order."
 
 
 
234
 
235
  if __name__ == "__main__":
236
  app.run(host="0.0.0.0", port=7860)
 
6
  import logging
7
  from werkzeug.exceptions import BadRequest
8
 
 
9
  app = Flask(__name__)
 
 
10
  logging.basicConfig(level=logging.INFO)
11
 
12
+ # Global cart to store items and their prices
13
+ cart = []
14
+
15
+ # Menu with items and their prices
16
  MENU = {
17
+ "biryani": {"chicken biryani": 150, "veg biryani": 120},
18
+ "starters": {"chicken wings": 180, "paneer tikka": 160},
19
+ "breads": {"butter naan": 40, "roti": 30},
20
+ "curries": {"butter chicken": 200, "dal fry": 150}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
  }
22
 
 
 
 
 
23
  html_code = """
24
  <!DOCTYPE html>
25
  <html lang="en">
 
30
  <style>
31
  body {
32
  font-family: Arial, sans-serif;
33
+ text-align: center;
34
  background-color: #f4f4f9;
 
 
 
 
 
 
35
  }
36
  h1 {
37
  color: #333;
 
44
  color: white;
45
  font-size: 24px;
46
  border: none;
 
 
 
47
  cursor: pointer;
 
 
 
 
 
48
  }
49
+ .status, .response {
50
  margin-top: 20px;
 
 
 
 
 
 
 
 
 
 
 
 
51
  }
52
  </style>
53
  </head>
54
  <body>
55
+ <h1>AI Dining Assistant</h1>
56
  <button class="mic-button" id="mic-button">🎤</button>
57
+ <div class="status" id="status">Press the mic button to start...</div>
58
  <div class="response" id="response" style="display: none;">Response will appear here...</div>
59
  <script>
60
  const micButton = document.getElementById('mic-button');
 
70
  });
71
 
72
  function startConversation() {
73
+ const utterance = new SpeechSynthesisUtterance('Please give your order.');
74
+ speechSynthesis.speak(utterance);
75
+ utterance.onend = () => {
76
+ status.textContent = 'Listening...';
77
+ startListening();
78
+ };
79
  }
80
 
81
  function startListening() {
 
98
  const utterance = new SpeechSynthesisUtterance(data.response);
99
  speechSynthesis.speak(utterance);
100
  } catch (error) {
101
+ response.textContent = 'Error processing your request. Please try again.';
102
+ status.textContent = 'Error occurred. Please press the mic button to restart.';
103
  isConversationActive = false;
104
  }
105
  };
 
129
  temp_file = NamedTemporaryFile(delete=False, suffix=".webm")
130
  audio_file.save(temp_file.name)
131
 
132
+ if os.path.getsize(temp_file.name) == 0:
133
+ raise BadRequest("Uploaded audio file is empty.")
134
+
135
  converted_file = NamedTemporaryFile(delete=False, suffix=".wav")
136
  ffmpeg.input(temp_file.name).output(
137
  converted_file.name, acodec='pcm_s16le', ac=1, ar='16000'
 
140
  recognizer = sr.Recognizer()
141
  with sr.AudioFile(converted_file.name) as source:
142
  audio_data = recognizer.record(source)
143
+ try:
144
+ command = recognizer.recognize_google(audio_data)
145
+ response = process_command(command)
146
+ except sr.UnknownValueError:
147
+ response = "Sorry, I could not understand. Please try again."
148
 
149
  return jsonify({"response": response})
150
+
151
+ except BadRequest as br:
152
+ return jsonify({"response": f"Bad Request: {str(br)}"}), 400
153
  except Exception as e:
154
+ return jsonify({"response": f"An error occurred: {str(e)}"}), 500
155
  finally:
156
+ os.unlink(temp_file.name)
157
+ os.unlink(converted_file.name)
 
 
158
 
159
  def process_command(command):
160
  global cart
161
+ command = command.lower()
162
+ all_items = {item: price for category in MENU.values() for item, price in category.items()}
163
+
164
  if "menu" in command:
165
+ menu = ", ".join([f"{category}: {', '.join(items.keys())}" for category, items in MENU.items()])
166
+ return f"Here is our menu: {menu}."
167
+ elif any(item in command for item in all_items.keys()):
168
+ item = next((item for item in all_items.keys() if item in command), None)
169
+ if item:
170
+ cart.append((item, all_items[item]))
171
+ total = sum(item[1] for item in cart)
172
+ return f"{item.capitalize()} added to your cart. Your current total is ₹{total}."
173
+ elif "final order" in command or "submit" in command:
174
  if cart:
175
+ items = ", ".join([f"{item[0]} (₹{item[1]})" for item in cart])
176
+ total = sum(item[1] for item in cart)
177
+ cart.clear() # Reset cart after final order
178
+ return f"Your final order is: {items}. The total price is ₹{total}. Thank you for ordering!"
179
  else:
180
+ return "Your cart is empty. Please add items first."
181
+ elif "no" in command or "nothing" in command or "goodbye" in command:
182
+ cart.clear()
183
+ return "Goodbye! Thank you for using AI Dining Assistant."
184
+ return "Sorry, I didn't understand that. Please try again."
185
 
186
  if __name__ == "__main__":
187
  app.run(host="0.0.0.0", port=7860)