lokesh341 commited on
Commit
ca0b532
·
verified ·
1 Parent(s): bddcee1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +11 -158
app.py CHANGED
@@ -14,23 +14,16 @@ 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"
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 connection details
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
- # Functions for Salesforce operations
34
  def create_salesforce_record(sf, name, email, phone_number):
35
  try:
36
  customer_login = sf.Customer_Login__c.create({
@@ -47,46 +40,17 @@ def get_menu_items(sf):
47
  result = sf.query(query)
48
  return result['records']
49
 
50
- # Voice-related functions
51
- def generate_audio_prompt(text, filename):
52
- try:
53
- tts = gTTS(text)
54
- tts.save(os.path.join("static", filename))
55
- except gtts.tts.gTTSError as e:
56
- print(f"Error: {e}")
57
- print("Retrying after 5 seconds...")
58
- time.sleep(5) # Wait for 5 seconds before retrying
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) # Convert to 16kHz, mono
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) # Reduced silence duration
74
- print(f"Detected nonsilent parts: {nonsilent_parts}")
75
- return len(nonsilent_parts) == 0 # If no speech detected
76
-
77
- # Routes and Views
78
  @app.route("/")
79
  def index():
80
  return render_template("index.html")
81
 
82
  @app.route("/dashboard", methods=["GET"])
83
  def dashboard():
84
- return render_template("dashboard.html") # Render the dashboard template
85
 
86
  @app.route('/login', methods=['POST'])
87
  def login():
88
- # Get data from voice bot (name, email, phone number)
89
- data = request.json # Assuming voice bot sends JSON data
90
  name = data.get('name')
91
  email = data.get('email')
92
  phone_number = data.get('phone_number')
@@ -95,139 +59,28 @@ def login():
95
  return jsonify({'error': 'Missing required fields'}), 400
96
 
97
  try:
98
- customer_login = create_salesforce_record(sf, name, email, phone_number)
99
- return redirect("/menu") # Redirect to the menu page after successful login
100
  except Exception as e:
101
  return jsonify({'error': f'Failed to create record in Salesforce: {str(e)}'}), 500
102
 
103
- @app.route("/submit", methods=["POST"])
104
- def submit():
105
- data = request.json
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({'error': 'Missing data'}), 400
112
-
113
- try:
114
- # Create Salesforce record
115
- customer_login = sf.Customer_Login__c.create({
116
- 'Name': name,
117
- 'Email__c': email,
118
- 'Phone_Number__c': phone
119
- })
120
-
121
- if customer_login.get('id'):
122
- print(f"Success: Customer record created with ID: {customer_login['id']}")
123
- return jsonify({'success': True})
124
- else:
125
- print("Failed: No ID returned after creating the record.")
126
- return jsonify({'error': 'Failed to create record'}), 500
127
-
128
- except Exception as e:
129
- print(f"Error: {str(e)}") # Print error message if an exception occurs
130
- return jsonify({'error': str(e)}), 500
131
-
132
-
133
  @app.route("/menu", methods=["GET"])
134
  def menu_page():
135
- menu_items = get_menu_items(sf) # Fetch menu items from Salesforce
136
  menu_data = [{"name": item['Name'], "price": item['Price__c'], "ingredients": item['Ingredients__c'], "category": item['Category__c']} for item in menu_items]
137
  return render_template("menu_page.html", menu_items=menu_data)
138
 
139
- # Route for handling order
140
- @app.route("/order", methods=["POST"])
141
- def place_order():
142
- item_name = request.json.get('item_name')
143
- quantity = request.json.get('quantity')
144
- order_data = {"Item__c": item_name, "Quantity__c": quantity}
145
- sf.Order__c.create(order_data)
146
- return jsonify({"success": True, "message": f"Order for {item_name} placed successfully."})
147
-
148
- # Route to handle the cart
149
  @app.route("/cart", methods=["GET"])
150
  def cart():
151
- cart_items = [] # Placeholder for cart items
152
- return render_template("cart_page.html", cart_items=cart_items)
153
 
154
- # Route for the order summary page
155
  @app.route("/order-summary", methods=["GET"])
156
  def order_summary():
157
- order_details = [] # Placeholder for order details
158
- return render_template("order_summary.html", order_details=order_details)
159
-
160
- @app.route("/transcribe", methods=["POST"])
161
- def transcribe():
162
- if "audio" not in request.files:
163
- print("No audio file provided")
164
- return jsonify({"error": "No audio file provided"}), 400
165
-
166
- audio_file = request.files["audio"]
167
- input_audio_path = os.path.join("static", "temp_input.wav")
168
- output_audio_path = os.path.join("static", "temp.wav")
169
- audio_file.save(input_audio_path)
170
 
171
- try:
172
- # Convert to WAV
173
- convert_to_wav(input_audio_path, output_audio_path)
174
-
175
- # Check for silence
176
- if is_silent_audio(output_audio_path):
177
- return jsonify({"error": "No speech detected. Please try again."}), 400
178
- else:
179
- print("Audio contains speech, proceeding with transcription.")
180
-
181
- # Use Whisper ASR model for transcription
182
- result = None
183
- retry_attempts = 3
184
- for attempt in range(retry_attempts):
185
- try:
186
- result = pipeline("automatic-speech-recognition", model="openai/whisper-small", device=0 if torch.cuda.is_available() else -1, config=config)
187
- print(f"Transcribed text: {result['text']}")
188
- break
189
- except requests.exceptions.ReadTimeout:
190
- print(f"Timeout occurred, retrying attempt {attempt + 1}/{retry_attempts}...")
191
- time.sleep(5)
192
-
193
- if result is None:
194
- return jsonify({"error": "Unable to transcribe audio after retries."}), 500
195
-
196
- transcribed_text = result["text"].strip().capitalize()
197
- print(f"Transcribed text: {transcribed_text}")
198
-
199
- # Extract name, email, and phone number from the transcribed text
200
- parts = transcribed_text.split()
201
- name = parts[0] if len(parts) > 0 else "Unknown Name"
202
- email = parts[1] if '@' in parts[1] else "[email protected]"
203
- phone_number = parts[2] if len(parts) > 2 else "0000000000"
204
- print(f"Parsed data - Name: {name}, Email: {email}, Phone Number: {phone_number}")
205
-
206
- # Confirm details before submission
207
- confirmation = f"Is this correct? Name: {name}, Email: {email}, Phone: {phone_number}"
208
- generate_audio_prompt(confirmation, "confirmation.mp3")
209
-
210
- # Simulate confirmation via user action
211
- user_confirms = True # Assuming the user confirms, you can replace this with actual user input logic
212
-
213
- if user_confirms:
214
- # Create record in Salesforce
215
- salesforce_response = create_salesforce_record(name, email, phone_number)
216
-
217
- # Log the Salesforce response
218
- print(f"Salesforce record creation response: {salesforce_response}")
219
-
220
- # Check if the response contains an error
221
- if "error" in salesforce_response:
222
- print(f"Error creating record in Salesforce: {salesforce_response['error']}")
223
- return jsonify(salesforce_response), 500
224
-
225
- return jsonify({"text": transcribed_text, "salesforce_record": salesforce_response})
226
-
227
- except Exception as e:
228
- print(f"Error in transcribing or processing: {str(e)}")
229
- return jsonify({"error": f"Speech recognition error: {str(e)}"}), 500
230
 
231
- # Start Production Server
232
  if __name__ == "__main__":
233
  serve(app, host="0.0.0.0", port=7860)
 
14
 
15
  app = Flask(__name__)
16
 
 
17
  device = "cuda" if torch.cuda.is_available() else "cpu"
18
 
 
19
  config = AutoConfig.from_pretrained("openai/whisper-small")
20
+ config.update({"timeout": 60})
21
 
 
22
  try:
 
23
  sf = Salesforce(username='[email protected]', password='Sati@1020', security_token='sSSjyhInIsUohKpG8sHzty2q')
 
 
24
  except Exception as e:
25
  print(f"Failed to connect to Salesforce: {str(e)}")
26
 
 
27
  def create_salesforce_record(sf, name, email, phone_number):
28
  try:
29
  customer_login = sf.Customer_Login__c.create({
 
40
  result = sf.query(query)
41
  return result['records']
42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
  @app.route("/")
44
  def index():
45
  return render_template("index.html")
46
 
47
  @app.route("/dashboard", methods=["GET"])
48
  def dashboard():
49
+ return render_template("dashboard.html")
50
 
51
  @app.route('/login', methods=['POST'])
52
  def login():
53
+ data = request.json
 
54
  name = data.get('name')
55
  email = data.get('email')
56
  phone_number = data.get('phone_number')
 
59
  return jsonify({'error': 'Missing required fields'}), 400
60
 
61
  try:
62
+ create_salesforce_record(sf, name, email, phone_number)
63
+ return redirect("/menu")
64
  except Exception as e:
65
  return jsonify({'error': f'Failed to create record in Salesforce: {str(e)}'}), 500
66
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67
  @app.route("/menu", methods=["GET"])
68
  def menu_page():
69
+ menu_items = get_menu_items(sf)
70
  menu_data = [{"name": item['Name'], "price": item['Price__c'], "ingredients": item['Ingredients__c'], "category": item['Category__c']} for item in menu_items]
71
  return render_template("menu_page.html", menu_items=menu_data)
72
 
 
 
 
 
 
 
 
 
 
 
73
  @app.route("/cart", methods=["GET"])
74
  def cart():
75
+ return render_template("cart_page.html")
 
76
 
 
77
  @app.route("/order-summary", methods=["GET"])
78
  def order_summary():
79
+ return render_template("order_summary.html")
 
 
 
 
 
 
 
 
 
 
 
 
80
 
81
+ @app.route("/final_order", methods=["GET"])
82
+ def final_order():
83
+ return render_template("final_order.html")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84
 
 
85
  if __name__ == "__main__":
86
  serve(app, host="0.0.0.0", port=7860)