lokesh341 commited on
Commit
0613b1a
Β·
verified Β·
1 Parent(s): 00d34d4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +82 -45
app.py CHANGED
@@ -1,12 +1,12 @@
1
  import torch
2
- from flask import Flask, render_template, request, jsonify
3
  import json
4
  import os
5
  from transformers import pipeline
6
  from gtts import gTTS
7
  from pydub import AudioSegment
8
  from pydub.silence import detect_nonsilent
9
- from transformers import AutoConfig # Import AutoConfig for the config object
10
  import time
11
  from waitress import serve
12
  from simple_salesforce import Salesforce
@@ -62,7 +62,7 @@ def is_silent_audio(audio_path):
62
  try:
63
  print("Attempting to connect to Salesforce...")
64
  sf = Salesforce(username='[email protected]', password='Sati@1020', security_token='sSSjyhInIsUohKpG8sHzty2q')
65
- print("βœ… Connected to Salesforce successfully!")
66
  except Exception as e:
67
  print(f"Failed to connect to Salesforce: {str(e)}")
68
 
@@ -80,7 +80,7 @@ def dashboard():
80
  @app.route("/menu_page", methods=["GET"])
81
  def menu_page():
82
  try:
83
- query = "SELECT Name, Price__c, Ingredients__c, Category__c FROM Menu_Item__c"
84
  result = sf.query(query)
85
 
86
  menu_items = []
@@ -89,17 +89,60 @@ def menu_page():
89
  "name": item["Name"],
90
  "price": item["Price__c"],
91
  "ingredients": item["Ingredients__c"],
92
- "category": item["Category__c"]
 
93
  })
94
 
95
  return render_template("menu_page.html", menu=menu_items)
96
  except Exception as e:
97
  return jsonify({"error": f"Failed to fetch menu: {str(e)}"}), 500
98
 
99
- # βœ… CART PAGE ROUTE (NEWLY ADDED)
100
- @app.route("/cart_page", methods=["GET"])
101
- def cart_page():
102
- return render_template("cart_page.html")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
103
 
104
  # βœ… LOGIN API
105
  @app.route('/login', methods=['POST'])
@@ -122,51 +165,45 @@ def login():
122
  except Exception as e:
123
  return jsonify({'error': f'Failed to create record in Salesforce: {str(e)}'}), 500
124
 
125
- # βœ… REGISTER API
126
- @app.route("/submit", methods=["POST"])
127
- def submit():
128
- data = request.json
129
- name = data.get('name')
130
- email = data.get('email')
131
- phone = data.get('phone')
132
 
133
- if not name or not email or not phone:
134
- return jsonify({'error': 'Missing data'}), 400
 
 
135
 
136
  try:
137
- customer_login = sf.Customer_Login__c.create({
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
138
  'Name': name,
139
  'Email__c': email,
140
- 'Phone_Number__c': phone
141
  })
142
- return jsonify({'success': True}), 200
143
- except Exception as e:
144
- return jsonify({'error': str(e)}), 500
145
-
146
- # βœ… MENU API
147
- @app.route("/menu", methods=["GET"])
148
- def get_menu():
149
- try:
150
- query = "SELECT Name, Price__c, Ingredients__c, Category__c FROM Menu_Item__c"
151
- result = sf.query(query)
152
 
153
- menu_items = []
154
- for item in result["records"]:
155
- menu_items.append({
156
- "name": item["Name"],
157
- "price": item["Price__c"],
158
- "ingredients": item["Ingredients__c"],
159
- "category": item["Category__c"]
160
- })
161
 
162
- return jsonify({"success": True, "menu": menu_items})
163
  except Exception as e:
164
- return jsonify({"error": f"Failed to fetch menu: {str(e)}"}), 500
165
-
166
- # βœ… STATIC IMAGES ROUTE
167
- @app.route("/static/images/<path:filename>")
168
- def static_images(filename):
169
- return send_from_directory(os.path.join(app.root_path, 'static/images'), filename)
170
 
171
  # βœ… START PRODUCTION SERVER
172
  if __name__ == "__main__":
 
1
  import torch
2
+ from flask import Flask, render_template, request, jsonify, send_from_directory
3
  import json
4
  import os
5
  from transformers import pipeline
6
  from gtts import gTTS
7
  from pydub import AudioSegment
8
  from pydub.silence import detect_nonsilent
9
+ from transformers import AutoConfig
10
  import time
11
  from waitress import serve
12
  from simple_salesforce import Salesforce
 
62
  try:
63
  print("Attempting to connect to Salesforce...")
64
  sf = Salesforce(username='[email protected]', password='Sati@1020', security_token='sSSjyhInIsUohKpG8sHzty2q')
65
+ print("Connected to Salesforce successfully!")
66
  except Exception as e:
67
  print(f"Failed to connect to Salesforce: {str(e)}")
68
 
 
80
  @app.route("/menu_page", methods=["GET"])
81
  def menu_page():
82
  try:
83
+ query = "SELECT Name, Price__c, Ingredients__c, Category__c, Image_URL__c FROM Menu_Item__c"
84
  result = sf.query(query)
85
 
86
  menu_items = []
 
89
  "name": item["Name"],
90
  "price": item["Price__c"],
91
  "ingredients": item["Ingredients__c"],
92
+ "category": item["Category__c"],
93
+ "image_url": item.get("Image_URL__c", "default_image.jpg") # Fallback if no image is found
94
  })
95
 
96
  return render_template("menu_page.html", menu=menu_items)
97
  except Exception as e:
98
  return jsonify({"error": f"Failed to fetch menu: {str(e)}"}), 500
99
 
100
+ # βœ… MENU API (Returns menu items in JSON format)
101
+ @app.route("/menu", methods=["GET"])
102
+ def get_menu():
103
+ try:
104
+ query = "SELECT Name, Price__c, Ingredients__c, Category__c, Image_URL__c FROM Menu_Item__c"
105
+ result = sf.query(query)
106
+
107
+ menu_items = []
108
+ for item in result["records"]:
109
+ menu_items.append({
110
+ "name": item["Name"],
111
+ "price": item["Price__c"],
112
+ "ingredients": item["Ingredients__c"],
113
+ "category": item["Category__c"],
114
+ "image_url": item.get("Image_URL__c", "default_image.jpg") # Fallback if no image is found
115
+ })
116
+
117
+ return jsonify({"success": True, "menu": menu_items})
118
+ except Exception as e:
119
+ return jsonify({"error": f"Failed to fetch menu: {str(e)}"}), 500
120
+
121
+ # βœ… STATIC IMAGES ROUTE
122
+ @app.route("/static/images/<path:filename>")
123
+ def static_images(filename):
124
+ return send_from_directory(os.path.join(app.root_path, 'static/images'), filename)
125
+
126
+ # βœ… REGISTER API
127
+ @app.route("/submit", methods=["POST"])
128
+ def submit():
129
+ data = request.json
130
+ name = data.get('name')
131
+ email = data.get('email')
132
+ phone = data.get('phone')
133
+
134
+ if not name or not email or not phone:
135
+ return jsonify({'error': 'Missing data'}), 400
136
+
137
+ try:
138
+ customer_login = sf.Customer_Login__c.create({
139
+ 'Name': name,
140
+ 'Email__c': email,
141
+ 'Phone_Number__c': phone
142
+ })
143
+ return jsonify({'success': True}), 200
144
+ except Exception as e:
145
+ return jsonify({'error': str(e)}), 500
146
 
147
  # βœ… LOGIN API
148
  @app.route('/login', methods=['POST'])
 
165
  except Exception as e:
166
  return jsonify({'error': f'Failed to create record in Salesforce: {str(e)}'}), 500
167
 
168
+ # βœ… TRANSCRIBE AUDIO API
169
+ @app.route("/transcribe", methods=["POST"])
170
+ def transcribe():
171
+ if "audio" not in request.files:
172
+ return jsonify({"error": "No audio file provided"}), 400
 
 
173
 
174
+ audio_file = request.files["audio"]
175
+ input_audio_path = os.path.join("static", "temp_input.wav")
176
+ output_audio_path = os.path.join("static", "temp.wav")
177
+ audio_file.save(input_audio_path)
178
 
179
  try:
180
+ convert_to_wav(input_audio_path, output_audio_path)
181
+ if is_silent_audio(output_audio_path):
182
+ return jsonify({"error": "No speech detected. Please try again."}), 400
183
+
184
+ asr_pipeline = pipeline("automatic-speech-recognition", model="openai/whisper-small", device=0 if torch.cuda.is_available() else -1, config=config)
185
+ result = asr_pipeline(output_audio_path)
186
+
187
+ transcribed_text = result["text"].strip().capitalize()
188
+
189
+ parts = transcribed_text.split()
190
+ name = parts[0] if len(parts) > 0 else "Unknown Name"
191
+ email = parts[1] if '@' in parts[1] else "[email protected]"
192
+ phone_number = parts[2] if len(parts) > 2 else "0000000000"
193
+
194
+ confirmation = f"Is this correct? Name: {name}, Email: {email}, Phone: {phone_number}"
195
+ generate_audio_prompt(confirmation, "confirmation.mp3")
196
+
197
+ salesforce_response = sf.Customer_Login__c.create({
198
  'Name': name,
199
  'Email__c': email,
200
+ 'Phone_Number__c': phone_number
201
  })
 
 
 
 
 
 
 
 
 
 
202
 
203
+ return jsonify({"text": transcribed_text, "salesforce_record": salesforce_response})
 
 
 
 
 
 
 
204
 
 
205
  except Exception as e:
206
+ return jsonify({"error": f"Speech recognition error: {str(e)}"}), 500
 
 
 
 
 
207
 
208
  # βœ… START PRODUCTION SERVER
209
  if __name__ == "__main__":