Swathi6 commited on
Commit
08a8bb7
·
verified ·
1 Parent(s): 9e09d87

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +236 -0
app.py ADDED
@@ -0,0 +1,236 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
10
+ import time
11
+ from waitress import serve
12
+ from simple_salesforce import Salesforce
13
+ import requests
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"
19
+
20
+ # Create config object to set timeout and other parameters
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='diggavalli98@gmail.com', password='Sati@1020', security_token='sSSjyhInIsUohKpG8sHzty2q')
28
+ print("Connected to Salesforce successfully!")
29
+ except Exception as e:
30
+ print(f"Failed to connect to Salesforce: {str(e)}")
31
+
32
+ # Function for Salesforce operations
33
+ def create_salesforce_record(name, email, phone_number):
34
+ try:
35
+ customer_login = sf.Customer_Login__c.create({
36
+ 'Name': name,
37
+ 'Email__c': email,
38
+ 'Phone_Number__c': phone_number
39
+ })
40
+ return customer_login
41
+ except SalesforceResourceNotFound as e:
42
+ raise Exception(f"Salesforce resource not found: {str(e)}")
43
+ except Exception as e:
44
+ raise Exception(f"Failed to create record: {str(e)}")
45
+
46
+ def get_menu_items():
47
+ query = "SELECT Name, Price__c, Ingredients__c, Category__c FROM Menu_Item__c"
48
+ result = sf.query(query)
49
+ return result['records']
50
+
51
+ # Voice-related functions
52
+ def generate_audio_prompt(text, filename):
53
+ try:
54
+ tts = gTTS(text)
55
+ tts.save(os.path.join("static", filename))
56
+ except gtts.tts.gTTSError as e:
57
+ print(f"Error: {e}")
58
+ time.sleep(10) # Retry after 10 seconds
59
+ generate_audio_prompt(text, filename)
60
+
61
+ # Utility functions
62
+ def convert_to_wav(input_path, output_path):
63
+ try:
64
+ audio = AudioSegment.from_file(input_path)
65
+ audio = audio.set_frame_rate(16000).set_channels(1)
66
+ audio.export(output_path, format="wav")
67
+ except Exception as e:
68
+ print(f"Error: {str(e)}")
69
+ raise Exception(f"Audio conversion failed: {str(e)}")
70
+
71
+ def is_silent_audio(audio_path):
72
+ audio = AudioSegment.from_wav(audio_path)
73
+ nonsilent_parts = detect_nonsilent(audio, min_silence_len=500, silence_thresh=audio.dBFS-16)
74
+ return len(nonsilent_parts) == 0 # If no speech detected
75
+
76
+ # Routes and Views
77
+ @app.route("/")
78
+ def index():
79
+ return render_template("index.html")
80
+
81
+ @app.route("/dashboard", methods=["GET"])
82
+ def dashboard():
83
+ return render_template("dashboard.html")
84
+
85
+ @app.route('/submit', methods=['POST'])
86
+ def submit():
87
+ try:
88
+ data = request.get_json()
89
+ if not data:
90
+ return jsonify({"success": False, "message": "Invalid or empty JSON received"}), 400
91
+
92
+ name = data.get("name")
93
+ email = data.get("email")
94
+ phone = data.get("phone")
95
+
96
+ if not name or not email or not phone:
97
+ return jsonify({"success": False, "message": "Missing required fields"}), 400
98
+
99
+ # Insert data into Salesforce
100
+ salesforce_data = {"Name": name, "Email__c": email, "Phone_Number__c": phone}
101
+ try:
102
+ result = sf.Customer_Login__c.create(salesforce_data)
103
+ return jsonify({"success": True, "message": "Data submitted successfully"})
104
+ except Exception as e:
105
+ return jsonify({"success": False, "message": "Salesforce submission failed", "error": str(e)}), 500
106
+ except Exception as e:
107
+ return jsonify({"success": False, "message": "Internal server error", "error": str(e)}), 500
108
+
109
+ @app.route("/menu", methods=["GET"])
110
+ def menu_page():
111
+ menu_items = get_menu_items()
112
+ menu_data = [{"name": item['Name'], "price": item['Price__c'], "ingredients": item['Ingredients__c'], "category": item['Category__c']} for item in menu_items]
113
+ return render_template("menu_page.html", menu_items=menu_data)
114
+
115
+ @app.route("/validate-login", methods=["POST"])
116
+ def validate_login():
117
+ try:
118
+ # Ensure JSON is being received
119
+ data = request.get_json()
120
+ login_email = data.get("email")
121
+ login_mobile = data.get("mobile")
122
+
123
+ # Validate if email and mobile are present
124
+ if not login_email or not login_mobile:
125
+ return jsonify({"success": False, "message": "Missing email or mobile number"}), 400
126
+
127
+ # Query Salesforce to check if the record exists
128
+ 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}'"
129
+ result = sf.query(query)
130
+
131
+ if result['records']:
132
+ # If a matching record is found, return success and the name
133
+ user_name = result['records'][0]['Name']
134
+ return jsonify({"success": True, "message": "Login successful", "name": user_name})
135
+ else:
136
+ # If no matching record is found
137
+ return jsonify({"success": False, "message": "Invalid email or mobile number"}), 401
138
+
139
+ except Exception as e:
140
+ return jsonify({"success": False, "message": "Internal server error", "error": str(e)}), 500
141
+
142
+ @app.route("/order", methods=["POST"])
143
+ def place_order():
144
+ order_data = request.json
145
+
146
+ # Get order details from the request
147
+ customer_name = order_data.get("customerName")
148
+ customer_email = order_data.get("customerEmail")
149
+ customer_phone = order_data.get("customerPhone")
150
+ customer_address = order_data.get("customerAddress")
151
+ items = order_data.get("items")
152
+ total_amount = order_data.get("totalAmount")
153
+
154
+ # Ensure all required fields are present
155
+ if not customer_name or not customer_email or not customer_phone or not customer_address or not items or not total_amount:
156
+ return jsonify({"success": False, "message": "Missing required fields"}), 400
157
+
158
+ try:
159
+ # Create the order in Salesforce (custom object Order__c)
160
+ order = sf.Order__c.create({
161
+ "Customer_Name__c": customer_name,
162
+ "Customer_Email__c": customer_email,
163
+ "Customer_Phone__c": customer_phone,
164
+ "Customer_Address__c": customer_address,
165
+ "Total_Amount__c": total_amount
166
+ })
167
+
168
+ # Optionally create order items in a related object or as line items
169
+ for item in items:
170
+ sf.Order_Item__c.create({
171
+ "Order__c": order['id'], # Link to the parent order
172
+ "Item__c": item['name'],
173
+ "Quantity__c": item['quantity'],
174
+ "Price__c": item['price']
175
+ })
176
+
177
+ # Return success response
178
+ return jsonify({"success": True, "message": "Order placed successfully."})
179
+
180
+ except Exception as e:
181
+ # If an error occurs, return an error message
182
+ return jsonify({"success": False, "message": f"Error placing order: {str(e)}"}), 500
183
+
184
+ @app.route("/cart", methods=["GET"])
185
+ def cart():
186
+ cart_items = [] # Placeholder for cart items
187
+ return render_template("cart_page.html", cart_items=cart_items)
188
+
189
+ @app.route("/order-summary", methods=["GET"])
190
+ def order_summary():
191
+ order_details = [] # Placeholder for order details
192
+ return render_template("order_summary.html", order_details=order_details)
193
+
194
+ @app.route("/transcribe", methods=["POST"])
195
+ def transcribe():
196
+ if "audio" not in request.files:
197
+ return jsonify({"error": "No audio file provided"}), 400
198
+
199
+ audio_file = request.files["audio"]
200
+ input_audio_path = os.path.join("static", "temp_input.wav")
201
+ output_audio_path = os.path.join("static", "temp.wav")
202
+ audio_file.save(input_audio_path)
203
+
204
+ try:
205
+ convert_to_wav(input_audio_path, output_audio_path)
206
+
207
+ if is_silent_audio(output_audio_path):
208
+ return jsonify({"error": "No speech detected. Please try again."}), 400
209
+
210
+ result = pipeline("automatic-speech-recognition", model="openai/whisper-small", device=0 if torch.cuda.is_available() else -1, config=config)
211
+ transcribed_text = result["text"].strip().capitalize()
212
+
213
+ # Extract name, email, and phone number from the transcribed text
214
+ parts = transcribed_text.split()
215
+ name = parts[0] if len(parts) > 0 else "Unknown Name"
216
+ email = parts[1] if '@' in parts[1] else "unknown@domain.com"
217
+ phone_number = parts[2] if len(parts) > 2 else "0000000000"
218
+
219
+ confirmation = f"Is this correct? Name: {name}, Email: {email}, Phone: {phone_number}"
220
+ generate_audio_prompt(confirmation, "confirmation.mp3")
221
+
222
+ user_confirms = True # Assuming user confirms, replace with actual logic
223
+
224
+ if user_confirms:
225
+ salesforce_response = create_salesforce_record(name, email, phone_number)
226
+
227
+ if "error" in salesforce_response:
228
+ return jsonify(salesforce_response), 500
229
+
230
+ return jsonify({"text": transcribed_text, "salesforce_record": salesforce_response})
231
+
232
+ except Exception as e:
233
+ return jsonify({"error": f"Speech recognition error: {str(e)}"}), 500
234
+
235
+ if __name__ == "__main__":
236
+ serve(app, host="0.0.0.0", port=7860)