lokesh341 commited on
Commit
0ec8fd1
·
verified ·
1 Parent(s): 5d4cae7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +174 -103
app.py CHANGED
@@ -12,8 +12,7 @@ from waitress import serve
12
  from simple_salesforce import Salesforce
13
  import requests # Import requests for exception handling
14
 
15
- app = Flask(__name__, template_folder="templates")
16
- app.secret_key = os.urandom(24)
17
 
18
  # Use whisper-small for faster processing and better speed
19
  device = "cuda" if torch.cuda.is_available() else "cpu"
@@ -22,111 +21,176 @@ 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
- # Function to generate audio prompts
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26
  def generate_audio_prompt(text, filename):
27
  try:
28
  tts = gTTS(text)
29
  tts.save(os.path.join("static", filename))
30
- except Exception as e:
31
  print(f"Error: {e}")
32
- time.sleep(5) # Wait before retrying
 
33
  generate_audio_prompt(text, filename)
34
 
35
- # Generate required voice prompts
36
- prompts = {
37
- "welcome": "Welcome to Biryani Hub.",
38
- "ask_name": "Tell me your name.",
39
- "ask_email": "Please provide your email address.",
40
- "thank_you": "Thank you for registration."
41
- }
42
-
43
- for key, text in prompts.items():
44
- generate_audio_prompt(text, f"{key}.mp3")
45
-
46
- # Function to convert audio to WAV format
47
  def convert_to_wav(input_path, output_path):
48
  try:
49
  audio = AudioSegment.from_file(input_path)
50
  audio = audio.set_frame_rate(16000).set_channels(1) # Convert to 16kHz, mono
51
  audio.export(output_path, format="wav")
52
  except Exception as e:
 
53
  raise Exception(f"Audio conversion failed: {str(e)}")
54
 
55
- # Function to check if audio contains actual speech
56
  def is_silent_audio(audio_path):
57
  audio = AudioSegment.from_wav(audio_path)
58
- nonsilent_parts = detect_nonsilent(audio, min_silence_len=500, silence_thresh=audio.dBFS-16)
59
- return len(nonsilent_parts) == 0
 
60
 
61
- # Salesforce connection details
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
-
69
- # ✅ HOME ROUTE (Loads `index.html`)
70
- @app.route("/", methods=["GET"])
71
  def index():
72
  return render_template("index.html")
73
 
74
- # ✅ DASHBOARD ROUTE
75
  @app.route("/dashboard", methods=["GET"])
76
  def dashboard():
77
- return render_template("dashboard.html")
78
 
79
- # ✅ MENU PAGE ROUTE
80
- @app.route("/menu_page", methods=["GET"])
81
- def menu_page():
82
- return render_template("menu_page.html")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83
 
84
- # LOGIN API
85
- @app.route('/login', methods=['POST'])
86
- def login():
87
- data = request.json
88
- name = data.get('name')
89
- email = data.get('email')
90
- phone_number = data.get('phone_number')
91
 
92
- if not name or not email or not phone_number:
93
- return jsonify({'error': 'Missing required fields'}), 400
94
 
 
 
95
  try:
96
- customer_login = sf.Customer_Login__c.create({
97
- 'Name': name,
98
- 'Email__c': email,
99
- 'Phone_Number__c': phone_number
100
- })
101
- return jsonify({'success': True, 'id': customer_login['id']}), 200
102
- except Exception as e:
103
- return jsonify({'error': f'Failed to create record in Salesforce: {str(e)}'}), 500
104
 
105
- # REGISTER API
106
- @app.route("/submit", methods=["POST"])
107
- def submit():
108
- data = request.json
109
- name = data.get('name')
110
- email = data.get('email')
111
- phone = data.get('phone')
112
 
113
- if not name or not email or not phone:
114
- return jsonify({'error': 'Missing data'}), 400
 
 
 
 
 
 
 
 
 
115
 
116
- try:
117
- customer_login = sf.Customer_Login__c.create({
118
- 'Name': name,
119
- 'Email__c': email,
120
- 'Phone_Number__c': phone
121
- })
122
- return jsonify({'success': True}), 200
123
  except Exception as e:
124
- return jsonify({'error': str(e)}), 500
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
125
 
126
- # ✅ TRANSCRIBE AUDIO API
127
  @app.route("/transcribe", methods=["POST"])
128
  def transcribe():
129
  if "audio" not in request.files:
 
130
  return jsonify({"error": "No audio file provided"}), 400
131
 
132
  audio_file = request.files["audio"]
@@ -135,58 +199,65 @@ def transcribe():
135
  audio_file.save(input_audio_path)
136
 
137
  try:
 
138
  convert_to_wav(input_audio_path, output_audio_path)
 
 
139
  if is_silent_audio(output_audio_path):
140
  return jsonify({"error": "No speech detected. Please try again."}), 400
141
-
142
- asr_pipeline = pipeline("automatic-speech-recognition", model="openai/whisper-small", device=0 if torch.cuda.is_available() else -1, config=config)
143
- result = asr_pipeline(output_audio_path)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
144
 
145
  transcribed_text = result["text"].strip().capitalize()
 
146
 
 
147
  parts = transcribed_text.split()
148
  name = parts[0] if len(parts) > 0 else "Unknown Name"
149
  email = parts[1] if '@' in parts[1] else "[email protected]"
150
  phone_number = parts[2] if len(parts) > 2 else "0000000000"
 
151
 
 
152
  confirmation = f"Is this correct? Name: {name}, Email: {email}, Phone: {phone_number}"
153
  generate_audio_prompt(confirmation, "confirmation.mp3")
154
 
155
- salesforce_response = sf.Customer_Login__c.create({
156
- 'Name': name,
157
- 'Email__c': email,
158
- 'Phone_Number__c': phone_number
159
- })
160
 
161
- return jsonify({"text": transcribed_text, "salesforce_record": salesforce_response})
 
 
162
 
163
- except Exception as e:
164
- return jsonify({"error": f"Speech recognition error: {str(e)}"}), 500
165
 
166
- # MENU API
167
- @app.route("/menu", methods=["GET"])
168
- def get_menu():
169
- try:
170
- # Fetch menu items from Salesforce
171
- query = "SELECT Name, Price__c, Ingredients__c, Category__c FROM Menu_Item__c"
172
- result = sf.query(query)
173
-
174
- menu_items = []
175
- for item in result["records"]:
176
- menu_items.append({
177
- "name": item["Name"],
178
- "price": item["Price__c"],
179
- "ingredients": item["Ingredients__c"],
180
- "category": item["Category__c"]
181
- })
182
 
183
- # Pass the menu items to the template
184
- return render_template("menu_page.html", menu=menu_items)
185
 
186
  except Exception as e:
187
- return jsonify({"error": f"Failed to fetch menu: {str(e)}"}), 500
 
188
 
189
- # START PRODUCTION SERVER
190
  if __name__ == "__main__":
191
- print("✅ Starting Flask API Server on port 7860...")
192
  serve(app, host="0.0.0.0", port=7860)
 
12
  from simple_salesforce import Salesforce
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
+
48
+ def get_menu_items():
49
+ query = "SELECT Name, Price__c, Ingredients__c, Category__c FROM Menu_Item__c"
50
+ result = sf.query(query)
51
+ return result['records']
52
+
53
+ # Voice-related functions
54
  def generate_audio_prompt(text, filename):
55
  try:
56
  tts = gTTS(text)
57
  tts.save(os.path.join("static", filename))
58
+ except gtts.tts.gTTSError as e:
59
  print(f"Error: {e}")
60
+ print("Retrying after 5 seconds...")
61
+ time.sleep(5) # Wait for 5 seconds before retrying
62
  generate_audio_prompt(text, filename)
63
 
64
+ # Utility functions
 
 
 
 
 
 
 
 
 
 
 
65
  def convert_to_wav(input_path, output_path):
66
  try:
67
  audio = AudioSegment.from_file(input_path)
68
  audio = audio.set_frame_rate(16000).set_channels(1) # Convert to 16kHz, mono
69
  audio.export(output_path, format="wav")
70
  except Exception as e:
71
+ print(f"Error: {str(e)}")
72
  raise Exception(f"Audio conversion failed: {str(e)}")
73
 
 
74
  def is_silent_audio(audio_path):
75
  audio = AudioSegment.from_wav(audio_path)
76
+ nonsilent_parts = detect_nonsilent(audio, min_silence_len=500, silence_thresh=audio.dBFS-16) # Reduced silence duration
77
+ print(f"Detected nonsilent parts: {nonsilent_parts}")
78
+ return len(nonsilent_parts) == 0 # If no speech detected
79
 
80
+ # Routes and Views
81
+ @app.route("/")
 
 
 
 
 
 
 
 
82
  def index():
83
  return render_template("index.html")
84
 
 
85
  @app.route("/dashboard", methods=["GET"])
86
  def dashboard():
87
+ return render_template("dashboard.html") # Render the dashboard template
88
 
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"]
 
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)