Update app.py
Browse files
app.py
CHANGED
@@ -1,76 +1,92 @@
|
|
1 |
import torch
|
2 |
from flask import Flask, render_template, request, jsonify, redirect
|
3 |
-
|
|
|
|
|
|
|
|
|
|
|
4 |
from transformers import AutoConfig
|
|
|
5 |
from waitress import serve
|
|
|
|
|
6 |
|
7 |
app = Flask(__name__)
|
8 |
|
9 |
-
#
|
10 |
device = "cuda" if torch.cuda.is_available() else "cpu"
|
11 |
|
12 |
-
#
|
13 |
config = AutoConfig.from_pretrained("openai/whisper-small")
|
14 |
-
config.update({"timeout": 60})
|
15 |
-
|
16 |
-
#
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
# Initialize Salesforce connection
|
28 |
-
sf = connect_to_salesforce()
|
29 |
-
|
30 |
-
# Function to create a record in Salesforce (Customer Login)
|
31 |
def create_salesforce_record(sf, name, email, phone_number):
|
32 |
-
if not sf:
|
33 |
-
raise Exception("Salesforce connection is not established.")
|
34 |
try:
|
35 |
-
# Creating the Customer_Login__c record in Salesforce
|
36 |
customer_login = sf.Customer_Login__c.create({
|
37 |
'Name': name,
|
38 |
'Email__c': email,
|
39 |
'Phone_Number__c': phone_number
|
40 |
})
|
41 |
-
print(f"Customer record created with ID: {customer_login['id']}")
|
42 |
return customer_login
|
43 |
except Exception as e:
|
44 |
-
|
45 |
-
raise Exception(f"Failed to create record in Salesforce: {str(e)}")
|
46 |
|
47 |
-
# Function to fetch menu items from Salesforce
|
48 |
def get_menu_items(sf):
|
49 |
-
|
50 |
-
|
|
|
|
|
|
|
|
|
51 |
try:
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
56 |
except Exception as e:
|
57 |
-
print(f"
|
58 |
-
raise Exception(f"
|
|
|
|
|
|
|
|
|
|
|
|
|
59 |
|
60 |
-
#
|
61 |
@app.route("/")
|
62 |
def index():
|
63 |
return render_template("index.html")
|
64 |
|
65 |
-
# Route to dashboard
|
66 |
@app.route("/dashboard", methods=["GET"])
|
67 |
def dashboard():
|
68 |
-
return render_template("dashboard.html")
|
69 |
|
70 |
-
# Route for login (registration) - creates a new customer record in Salesforce
|
71 |
@app.route('/login', methods=['POST'])
|
72 |
def login():
|
73 |
-
data
|
|
|
74 |
name = data.get('name')
|
75 |
email = data.get('email')
|
76 |
phone_number = data.get('phone_number')
|
@@ -79,42 +95,139 @@ def login():
|
|
79 |
return jsonify({'error': 'Missing required fields'}), 400
|
80 |
|
81 |
try:
|
82 |
-
|
83 |
-
|
84 |
-
return jsonify({'error': 'Salesforce connection failed, try again later.'}), 500
|
85 |
-
|
86 |
-
# Create the customer record in Salesforce
|
87 |
-
create_salesforce_record(sf, name, email, phone_number)
|
88 |
-
return redirect("/menu")
|
89 |
except Exception as e:
|
90 |
return jsonify({'error': f'Failed to create record in Salesforce: {str(e)}'}), 500
|
91 |
|
92 |
-
|
93 |
-
|
94 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
95 |
try:
|
96 |
-
#
|
97 |
-
|
98 |
-
|
99 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
100 |
except Exception as e:
|
101 |
-
|
|
|
102 |
|
103 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
104 |
@app.route("/cart", methods=["GET"])
|
105 |
def cart():
|
106 |
-
|
|
|
107 |
|
108 |
# Route for the order summary page
|
109 |
@app.route("/order-summary", methods=["GET"])
|
110 |
def order_summary():
|
111 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
112 |
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
117 |
|
118 |
-
#
|
119 |
if __name__ == "__main__":
|
120 |
serve(app, host="0.0.0.0", port=7860)
|
|
|
1 |
import torch
|
2 |
from flask import Flask, render_template, request, jsonify, redirect
|
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 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({
|
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 |
|
|
|
45 |
def get_menu_items(sf):
|
46 |
+
query = "SELECT Name, Price__c, Ingredients__c, Category__c FROM Menu_Item__c"
|
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 |
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)
|