lokesh341 commited on
Commit
d2f9efb
·
verified ·
1 Parent(s): 15e9641

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +107 -41
app.py CHANGED
@@ -1,5 +1,5 @@
1
  import torch
2
- from flask import Flask, render_template, request, jsonify, session
3
  import json
4
  import os
5
  from transformers import pipeline
@@ -13,7 +13,6 @@ from simple_salesforce import Salesforce
13
  import requests # Import requests for exception handling
14
 
15
  app = Flask(__name__)
16
- app.secret_key = 'your_secret_key' # Use a secure secret key for sessions
17
 
18
  # Use whisper-small for faster processing and better speed
19
  device = "cuda" if torch.cuda.is_available() else "cpu"
@@ -22,23 +21,27 @@ device = "cuda" if torch.cuda.is_available() else "cpu"
22
  config = AutoConfig.from_pretrained("openai/whisper-small")
23
  config.update({"timeout": 60}) # Set timeout to 60 seconds
24
 
25
- # Salesforce connection setup
26
  try:
27
  print("Attempting to connect to Salesforce...")
28
  sf = Salesforce(username='[email protected]', password='Sati@1020', security_token='sSSjyhInIsUohKpG8sHzty2q')
29
  print("Connected to Salesforce successfully!")
 
30
  except Exception as e:
31
  print(f"Failed to connect to Salesforce: {str(e)}")
32
 
33
  # Function for Salesforce operations
34
  def create_salesforce_record(name, email, phone_number):
35
  try:
 
36
  customer_login = sf.Customer_Login__c.create({
37
  'Name': name,
38
  'Email__c': email,
39
  'Phone_Number__c': phone_number
40
  })
41
  return customer_login
 
 
42
  except Exception as e:
43
  raise Exception(f"Failed to create record: {str(e)}")
44
 
@@ -47,17 +50,6 @@ def get_menu_items():
47
  result = sf.query(query)
48
  return result['records']
49
 
50
- def create_salesforce_order(cart_items, total_price, customer_id):
51
- try:
52
- order = sf.Order__c.create({
53
- 'Total_Price__c': total_price,
54
- 'Cart_Items__c': json.dumps(cart_items), # Storing cart items as JSON
55
- 'Customer__c': customer_id # Linking to the customer record
56
- })
57
- return order
58
- except Exception as e:
59
- raise Exception(f"Failed to create order: {str(e)}")
60
-
61
  # Voice-related functions
62
  def generate_audio_prompt(text, filename):
63
  try:
@@ -97,101 +89,175 @@ def dashboard():
97
  @app.route('/submit', methods=['POST'])
98
  def submit():
99
  try:
 
100
  data = request.get_json()
101
  print("Received Data:", data) # Debugging line
102
 
103
  if not data:
104
  return jsonify({"success": False, "message": "Invalid or empty JSON received"}), 400
105
 
 
106
  name = data.get("name")
107
  email = data.get("email")
108
  phone = data.get("phone")
109
 
 
110
  if not name or not email or not phone:
111
  return jsonify({"success": False, "message": "Missing required fields"}), 400
112
 
 
113
  salesforce_data = {
114
  "Name": name,
115
  "Email__c": email, # Ensure this is the correct field API name in Salesforce
116
  "Phone_Number__c": phone # Ensure this is the correct field API name in Salesforce
117
  }
118
 
 
119
  try:
120
  result = sf.Customer_Login__c.create(salesforce_data) # Replace `Customer_Login__c` with your Salesforce object API name
121
  print(f"Salesforce Response: {result}") # Debugging line
 
122
  return jsonify({"success": True, "message": "Data submitted successfully"})
 
123
  except Exception as e:
124
  if "STORAGE_LIMIT_EXCEEDED" in str(e):
125
  return jsonify({"success": False, "message": "Salesforce storage limit exceeded. Please clean up or contact support."}), 500
126
  else:
127
  print(f"Salesforce Insertion Error: {str(e)}") # Log Salesforce errors
128
  return jsonify({"success": False, "message": "Salesforce submission failed", "error": str(e)}), 500
 
129
  except Exception as e:
130
  print(f"Server Error: {str(e)}") # Log general errors
131
  return jsonify({"success": False, "message": "Internal server error", "error": str(e)}), 500
132
 
 
133
  @app.route('/validate-login', methods=['POST'])
134
  def validate_login():
135
  try:
 
136
  data = request.get_json()
137
  login_email = data.get("email")
138
  login_mobile = data.get("mobile")
139
 
 
140
  if not login_email or not login_mobile:
141
  return jsonify({"success": False, "message": "Missing email or mobile number"}), 400
142
 
 
143
  query = f"SELECT Id, Name, Email__c, Phone_Number__c FROM Customer_Login__c WHERE Email__c = '{login_email}' AND Phone_Number__c = '{login_mobile}'"
144
  result = sf.query(query)
145
 
146
  if result['records']:
147
- user_name = result['records'][0]['Name']
 
148
  return jsonify({"success": True, "message": "Login successful", "name": user_name})
149
  else:
 
150
  return jsonify({"success": False, "message": "Invalid email or mobile number"}), 401
 
151
  except Exception as e:
152
  print(f"Error validating login: {str(e)}")
153
  return jsonify({"success": False, "message": "Internal server error", "error": str(e)}), 500
154
 
 
155
  @app.route("/menu", methods=["GET"])
156
  def menu_page():
157
  menu_items = get_menu_items()
158
  menu_data = [{"name": item['Name'], "price": item['Price__c'], "ingredients": item['Ingredients__c'], "category": item['Category__c']} for item in menu_items]
159
  return render_template("menu_page.html", menu_items=menu_data)
160
 
161
- @app.route("/add_to_cart", methods=["POST"])
162
- def add_to_cart():
163
- cart_items = session.get('cart_items', [])
164
  item_name = request.json.get('item_name')
165
  quantity = request.json.get('quantity')
166
-
167
- cart_items.append({"name": item_name, "quantity": quantity})
168
- session['cart_items'] = cart_items # Update session with new cart items
169
-
170
- return jsonify({"success": True, "message": f"Added {item_name} to your cart."})
171
-
172
- @app.route("/view_cart", methods=["GET"])
173
- def view_cart():
174
- cart_items = session.get('cart_items', [])
175
  return render_template("cart_page.html", cart_items=cart_items)
176
 
177
- @app.route("/place_order", methods=["POST"])
178
- def place_order():
179
- cart_items = session.get('cart_items', [])
180
- total_price = sum([item['quantity'] * 100 for item in cart_items]) # Placeholder price calculation
181
- customer_id = session.get('customer_id')
 
 
 
 
 
 
182
 
183
- if not customer_id:
184
- return jsonify({"message": "User not logged in"}), 400
 
 
185
 
186
  try:
187
- order_data = {"Total_Price__c": total_price, "Cart_Items__c": json.dumps(cart_items), "Customer__c": customer_id}
188
- order = sf.Order__c.create(order_data)
189
- session.pop('cart_items', None) # Clear the cart after placing the order
190
- return jsonify({"message": "Order placed successfully!", "order": order})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
191
 
192
  except Exception as e:
193
- return jsonify({"message": f"Failed to create order: {str(e)}"}), 500
 
194
 
195
- # Run the app
196
  if __name__ == "__main__":
197
- app.run(debug=True)
 
1
  import torch
2
+ from flask import Flask, render_template, request, jsonify
3
  import json
4
  import os
5
  from transformers import pipeline
 
13
  import requests # Import requests for exception handling
14
 
15
  app = Flask(__name__)
 
16
 
17
  # Use whisper-small for faster processing and better speed
18
  device = "cuda" if torch.cuda.is_available() else "cpu"
 
21
  config = AutoConfig.from_pretrained("openai/whisper-small")
22
  config.update({"timeout": 60}) # Set timeout to 60 seconds
23
 
24
+ # Salesforce credentials (Replace with actual values)
25
  try:
26
  print("Attempting to connect to Salesforce...")
27
  sf = Salesforce(username='[email protected]', password='Sati@1020', security_token='sSSjyhInIsUohKpG8sHzty2q')
28
  print("Connected to Salesforce successfully!")
29
+ print("User Info:", sf.UserInfo) # Log the user info to verify the connection
30
  except Exception as e:
31
  print(f"Failed to connect to Salesforce: {str(e)}")
32
 
33
  # Function for Salesforce operations
34
  def create_salesforce_record(name, email, phone_number):
35
  try:
36
+ # Create a new record in Salesforce's Customer_Login__c object
37
  customer_login = sf.Customer_Login__c.create({
38
  'Name': name,
39
  'Email__c': email,
40
  'Phone_Number__c': phone_number
41
  })
42
  return customer_login
43
+ except SalesforceResourceNotFound as e:
44
+ raise Exception(f"Salesforce resource not found: {str(e)}")
45
  except Exception as e:
46
  raise Exception(f"Failed to create record: {str(e)}")
47
 
 
50
  result = sf.query(query)
51
  return result['records']
52
 
 
 
 
 
 
 
 
 
 
 
 
53
  # Voice-related functions
54
  def generate_audio_prompt(text, filename):
55
  try:
 
89
  @app.route('/submit', methods=['POST'])
90
  def submit():
91
  try:
92
+ # Ensure JSON is being received
93
  data = request.get_json()
94
  print("Received Data:", data) # Debugging line
95
 
96
  if not data:
97
  return jsonify({"success": False, "message": "Invalid or empty JSON received"}), 400
98
 
99
+ # Get the values from the JSON data
100
  name = data.get("name")
101
  email = data.get("email")
102
  phone = data.get("phone")
103
 
104
+ # Validate if all fields are present
105
  if not name or not email or not phone:
106
  return jsonify({"success": False, "message": "Missing required fields"}), 400
107
 
108
+ # Prepare data for Salesforce submission
109
  salesforce_data = {
110
  "Name": name,
111
  "Email__c": email, # Ensure this is the correct field API name in Salesforce
112
  "Phone_Number__c": phone # Ensure this is the correct field API name in Salesforce
113
  }
114
 
115
+ # Insert data into Salesforce using simple_salesforce
116
  try:
117
  result = sf.Customer_Login__c.create(salesforce_data) # Replace `Customer_Login__c` with your Salesforce object API name
118
  print(f"Salesforce Response: {result}") # Debugging line
119
+
120
  return jsonify({"success": True, "message": "Data submitted successfully"})
121
+
122
  except Exception as e:
123
  if "STORAGE_LIMIT_EXCEEDED" in str(e):
124
  return jsonify({"success": False, "message": "Salesforce storage limit exceeded. Please clean up or contact support."}), 500
125
  else:
126
  print(f"Salesforce Insertion Error: {str(e)}") # Log Salesforce errors
127
  return jsonify({"success": False, "message": "Salesforce submission failed", "error": str(e)}), 500
128
+
129
  except Exception as e:
130
  print(f"Server Error: {str(e)}") # Log general errors
131
  return jsonify({"success": False, "message": "Internal server error", "error": str(e)}), 500
132
 
133
+
134
  @app.route('/validate-login', methods=['POST'])
135
  def validate_login():
136
  try:
137
+ # Ensure JSON is being received
138
  data = request.get_json()
139
  login_email = data.get("email")
140
  login_mobile = data.get("mobile")
141
 
142
+ # Validate if email and mobile are present
143
  if not login_email or not login_mobile:
144
  return jsonify({"success": False, "message": "Missing email or mobile number"}), 400
145
 
146
+ # Query Salesforce to check if the record exists
147
  query = f"SELECT Id, Name, Email__c, Phone_Number__c FROM Customer_Login__c WHERE Email__c = '{login_email}' AND Phone_Number__c = '{login_mobile}'"
148
  result = sf.query(query)
149
 
150
  if result['records']:
151
+ # If a matching record is found, return success and the name
152
+ user_name = result['records'][0]['Name'] # Assuming the 'Name' field is present in the Salesforce object
153
  return jsonify({"success": True, "message": "Login successful", "name": user_name})
154
  else:
155
+ # If no matching record is found
156
  return jsonify({"success": False, "message": "Invalid email or mobile number"}), 401
157
+
158
  except Exception as e:
159
  print(f"Error validating login: {str(e)}")
160
  return jsonify({"success": False, "message": "Internal server error", "error": str(e)}), 500
161
 
162
+
163
  @app.route("/menu", methods=["GET"])
164
  def menu_page():
165
  menu_items = get_menu_items()
166
  menu_data = [{"name": item['Name'], "price": item['Price__c'], "ingredients": item['Ingredients__c'], "category": item['Category__c']} for item in menu_items]
167
  return render_template("menu_page.html", menu_items=menu_data)
168
 
169
+ # Route for handling order
170
+ @app.route("/order", methods=["POST"])
171
+ def place_order():
172
  item_name = request.json.get('item_name')
173
  quantity = request.json.get('quantity')
174
+ order_data = {"Item__c": item_name, "Quantity__c": quantity}
175
+ sf.Order__c.create(order_data)
176
+ return jsonify({"success": True, "message": f"Order for {item_name} placed successfully."})
177
+
178
+ # Route to handle the cart
179
+ @app.route("/cart", methods=["GET"])
180
+ def cart():
181
+ cart_items = [] # Placeholder for cart items
 
182
  return render_template("cart_page.html", cart_items=cart_items)
183
 
184
+ # Route for the order summary page
185
+ @app.route("/order-summary", methods=["GET"])
186
+ def order_summary():
187
+ order_details = [] # Placeholder for order details
188
+ return render_template("order_summary.html", order_details=order_details)
189
+
190
+ @app.route("/transcribe", methods=["POST"])
191
+ def transcribe():
192
+ if "audio" not in request.files:
193
+ print("No audio file provided")
194
+ return jsonify({"error": "No audio file provided"}), 400
195
 
196
+ audio_file = request.files["audio"]
197
+ input_audio_path = os.path.join("static", "temp_input.wav")
198
+ output_audio_path = os.path.join("static", "temp.wav")
199
+ audio_file.save(input_audio_path)
200
 
201
  try:
202
+ # Convert to WAV
203
+ convert_to_wav(input_audio_path, output_audio_path)
204
+
205
+ # Check for silence
206
+ if is_silent_audio(output_audio_path):
207
+ return jsonify({"error": "No speech detected. Please try again."}), 400
208
+ else:
209
+ print("Audio contains speech, proceeding with transcription.")
210
+
211
+ # Use Whisper ASR model for transcription
212
+ result = None
213
+ retry_attempts = 3
214
+ for attempt in range(retry_attempts):
215
+ try:
216
+ result = pipeline("automatic-speech-recognition", model="openai/whisper-small", device=0 if torch.cuda.is_available() else -1, config=config)
217
+ print(f"Transcribed text: {result['text']}")
218
+ break
219
+ except requests.exceptions.ReadTimeout:
220
+ print(f"Timeout occurred, retrying attempt {attempt + 1}/{retry_attempts}...")
221
+ time.sleep(5)
222
+
223
+ if result is None:
224
+ return jsonify({"error": "Unable to transcribe audio after retries."}), 500
225
+
226
+ transcribed_text = result["text"].strip().capitalize()
227
+ print(f"Transcribed text: {transcribed_text}")
228
+
229
+ # Extract name, email, and phone number from the transcribed text
230
+ parts = transcribed_text.split()
231
+ name = parts[0] if len(parts) > 0 else "Unknown Name"
232
+ email = parts[1] if '@' in parts[1] else "[email protected]"
233
+ phone_number = parts[2] if len(parts) > 2 else "0000000000"
234
+ print(f"Parsed data - Name: {name}, Email: {email}, Phone Number: {phone_number}")
235
+
236
+ # Confirm details before submission
237
+ confirmation = f"Is this correct? Name: {name}, Email: {email}, Phone: {phone_number}"
238
+ generate_audio_prompt(confirmation, "confirmation.mp3")
239
+
240
+ # Simulate confirmation via user action
241
+ user_confirms = True # Assuming the user confirms, you can replace this with actual user input logic
242
+
243
+ if user_confirms:
244
+ # Create record in Salesforce
245
+ salesforce_response = create_salesforce_record(name, email, phone_number)
246
+
247
+ # Log the Salesforce response
248
+ print(f"Salesforce record creation response: {salesforce_response}")
249
+
250
+ # Check if the response contains an error
251
+ if "error" in salesforce_response:
252
+ print(f"Error creating record in Salesforce: {salesforce_response['error']}")
253
+ return jsonify(salesforce_response), 500
254
+
255
+ return jsonify({"text": transcribed_text, "salesforce_record": salesforce_response})
256
 
257
  except Exception as e:
258
+ print(f"Error in transcribing or processing: {str(e)}")
259
+ return jsonify({"error": f"Speech recognition error: {str(e)}"}), 500
260
 
261
+ # Start Production Server
262
  if __name__ == "__main__":
263
+ serve(app, host="0.0.0.0", port=7860)