Update app.py
Browse files
app.py
CHANGED
@@ -16,19 +16,11 @@ import requests
|
|
16 |
app = Flask(__name__)
|
17 |
app.secret_key = os.urandom(24) # For session handling
|
18 |
|
19 |
-
# Use whisper-small for faster processing and better speed
|
20 |
-
device = "cuda" if torch.cuda.is_available() else "cpu"
|
21 |
-
|
22 |
-
# Create config object to set timeout and other parameters
|
23 |
-
config = AutoConfig.from_pretrained("openai/whisper-small")
|
24 |
-
config.update({"timeout": 60}) # Set timeout to 60 seconds
|
25 |
-
|
26 |
# Salesforce connection details
|
27 |
try:
|
28 |
print("Attempting to connect to Salesforce...")
|
29 |
-
sf = Salesforce(username='
|
30 |
print("Connected to Salesforce successfully!")
|
31 |
-
print("User Info:", sf.UserInfo) # Log the user info to verify the connection
|
32 |
except Exception as e:
|
33 |
print(f"Failed to connect to Salesforce: {str(e)}")
|
34 |
|
@@ -44,6 +36,16 @@ def create_salesforce_record(sf, name, email, phone_number):
|
|
44 |
except Exception as e:
|
45 |
raise Exception(f"Failed to create record: {str(e)}")
|
46 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
47 |
def get_menu_items(sf):
|
48 |
query = "SELECT Name, Price__c, Ingredients__c, Category__c FROM Menu_Item__c"
|
49 |
result = sf.query(query)
|
@@ -77,27 +79,9 @@ def is_silent_audio(audio_path):
|
|
77 |
return len(nonsilent_parts) == 0 # If no speech detected
|
78 |
|
79 |
# Routes and Views
|
80 |
-
@app.route("/
|
81 |
-
def
|
82 |
-
return render_template("
|
83 |
-
|
84 |
-
@app.route('/login', methods=['POST'])
|
85 |
-
def login():
|
86 |
-
# Get data from voice bot (name, email, phone number)
|
87 |
-
data = request.json # Assuming voice bot sends JSON data
|
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 = create_salesforce_record(sf, name, email, phone_number)
|
97 |
-
session['customer_id'] = customer_login['id'] # Store customer ID in session
|
98 |
-
return redirect("/menu") # Redirect to the menu page after successful login
|
99 |
-
except Exception as e:
|
100 |
-
return jsonify({'error': f'Failed to create record in Salesforce: {str(e)}'}), 500
|
101 |
|
102 |
@app.route("/menu", methods=["GET"])
|
103 |
def menu_page():
|
@@ -105,141 +89,40 @@ def menu_page():
|
|
105 |
menu_data = [{"name": item['Name'], "price": item['Price__c'], "ingredients": item['Ingredients__c'], "category": item['Category__c']} for item in menu_items]
|
106 |
return render_template("menu_page.html", menu_items=menu_data)
|
107 |
|
108 |
-
@app.route("/add_to_cart", methods=["POST"])
|
109 |
-
def add_to_cart():
|
110 |
-
item_name = request.json.get('item_name')
|
111 |
-
quantity = request.json.get('quantity')
|
112 |
-
|
113 |
-
# Retrieve the current cart items from session or initialize an empty list
|
114 |
-
cart_items = session.get('cart_items', [])
|
115 |
-
cart_items.append({"name": item_name, "quantity": quantity, "price": 10}) # Assuming a fixed price for now
|
116 |
-
session['cart_items'] = cart_items # Save the updated cart items in session
|
117 |
-
|
118 |
-
return jsonify({"success": True, "message": f"Added {item_name} to cart."})
|
119 |
-
|
120 |
@app.route("/cart", methods=["GET"])
|
121 |
def cart():
|
122 |
-
# Retrieve cart items from session
|
123 |
cart_items = session.get('cart_items', [])
|
124 |
return render_template("cart_page.html", cart_items=cart_items)
|
125 |
|
126 |
@app.route("/order-summary", methods=["GET"])
|
127 |
def order_summary():
|
128 |
-
# Retrieve order details from session
|
129 |
order_details = session.get('cart_items', [])
|
130 |
total_price = sum(item['price'] * item['quantity'] for item in order_details)
|
131 |
return render_template("order_summary.html", order_details=order_details, total_price=total_price)
|
132 |
|
133 |
@app.route("/final_order", methods=["GET"])
|
134 |
def final_order():
|
135 |
-
# Clear cart items from the session after confirming the order
|
136 |
-
session.pop('cart_items', None)
|
137 |
-
return render_template("final_order.html")
|
138 |
-
|
139 |
-
@app.route("/place_order", methods=["POST"])
|
140 |
-
def place_order():
|
141 |
-
# Retrieve cart items from session
|
142 |
cart_items = session.get('cart_items', [])
|
143 |
-
|
144 |
-
return jsonify({"error": "Cart is empty, please add items."}), 400
|
145 |
|
146 |
-
# Create an Order record in Salesforce
|
147 |
try:
|
148 |
-
|
149 |
-
|
150 |
-
|
151 |
-
|
152 |
-
}
|
153 |
-
order = sf.Order.create(order_data)
|
154 |
-
order_id = order['id']
|
155 |
-
|
156 |
-
# Add items to the OrderLineItem related to the created Order
|
157 |
-
for cart_item in cart_items:
|
158 |
-
order_line_item_data = {
|
159 |
-
'OrderId': order_id,
|
160 |
-
'Quantity': cart_item['quantity'],
|
161 |
-
'UnitPrice': cart_item['price'],
|
162 |
-
'Product2Id': 'a0A2F00000o6K7GQ' # Example Product ID, replace with actual Product2Id
|
163 |
-
}
|
164 |
-
sf.OrderLineItem.create(order_line_item_data)
|
165 |
-
|
166 |
-
# Clear the cart after placing the order
|
167 |
-
session.pop('cart_items', None)
|
168 |
-
return jsonify({"success": True, "message": "Order placed successfully!"})
|
169 |
-
except Exception as e:
|
170 |
-
return jsonify({"error": f"Failed to place order: {str(e)}"}), 500
|
171 |
-
|
172 |
-
@app.route("/transcribe", methods=["POST"])
|
173 |
-
def transcribe():
|
174 |
-
if "audio" not in request.files:
|
175 |
-
print("No audio file provided")
|
176 |
-
return jsonify({"error": "No audio file provided"}), 400
|
177 |
-
|
178 |
-
audio_file = request.files["audio"]
|
179 |
-
input_audio_path = os.path.join("static", "temp_input.wav")
|
180 |
-
output_audio_path = os.path.join("static", "temp.wav")
|
181 |
-
audio_file.save(input_audio_path)
|
182 |
-
|
183 |
-
try:
|
184 |
-
# Convert to WAV
|
185 |
-
convert_to_wav(input_audio_path, output_audio_path)
|
186 |
-
|
187 |
-
# Check for silence
|
188 |
-
if is_silent_audio(output_audio_path):
|
189 |
-
return jsonify({"error": "No speech detected. Please try again."}), 400
|
190 |
-
else:
|
191 |
-
print("Audio contains speech, proceeding with transcription.")
|
192 |
-
|
193 |
-
# Use Whisper ASR model for transcription
|
194 |
-
result = None
|
195 |
-
retry_attempts = 3
|
196 |
-
for attempt in range(retry_attempts):
|
197 |
-
try:
|
198 |
-
result = pipeline("automatic-speech-recognition", model="openai/whisper-small", device=0 if torch.cuda.is_available() else -1, config=config)
|
199 |
-
print(f"Transcribed text: {result['text']}")
|
200 |
-
break
|
201 |
-
except requests.exceptions.ReadTimeout:
|
202 |
-
print(f"Timeout occurred, retrying attempt {attempt + 1}/{retry_attempts}...")
|
203 |
-
time.sleep(5)
|
204 |
-
|
205 |
-
if result is None:
|
206 |
-
return jsonify({"error": "Unable to transcribe audio after retries."}), 500
|
207 |
-
|
208 |
-
transcribed_text = result["text"].strip().capitalize()
|
209 |
-
print(f"Transcribed text: {transcribed_text}")
|
210 |
-
|
211 |
-
# Extract name, email, and phone number from the transcribed text
|
212 |
-
parts = transcribed_text.split()
|
213 |
-
name = parts[0] if len(parts) > 0 else "Unknown Name"
|
214 |
-
email = parts[1] if '@' in parts[1] else "[email protected]"
|
215 |
-
phone_number = parts[2] if len(parts) > 2 else "0000000000"
|
216 |
-
print(f"Parsed data - Name: {name}, Email: {email}, Phone Number: {phone_number}")
|
217 |
-
|
218 |
-
# Confirm details before submission
|
219 |
-
confirmation = f"Is this correct? Name: {name}, Email: {email}, Phone: {phone_number}"
|
220 |
-
generate_audio_prompt(confirmation, "confirmation.mp3")
|
221 |
-
|
222 |
-
# Simulate confirmation via user action
|
223 |
-
user_confirms = True # Assuming the user confirms, you can replace this with actual user input logic
|
224 |
-
|
225 |
-
if user_confirms:
|
226 |
-
# Create record in Salesforce
|
227 |
-
salesforce_response = create_salesforce_record(name, email, phone_number)
|
228 |
-
|
229 |
-
# Log the Salesforce response
|
230 |
-
print(f"Salesforce record creation response: {salesforce_response}")
|
231 |
-
|
232 |
-
# Check if the response contains an error
|
233 |
-
if "error" in salesforce_response:
|
234 |
-
print(f"Error creating record in Salesforce: {salesforce_response['error']}")
|
235 |
-
return jsonify(salesforce_response), 500
|
236 |
-
|
237 |
-
return jsonify({"text": transcribed_text, "salesforce_record": salesforce_response})
|
238 |
-
|
239 |
except Exception as e:
|
240 |
-
|
241 |
-
return jsonify({"error": f"Speech recognition error: {str(e)}"}), 500
|
242 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
243 |
|
244 |
# Start Production Server
|
245 |
if __name__ == "__main__":
|
|
|
16 |
app = Flask(__name__)
|
17 |
app.secret_key = os.urandom(24) # For session handling
|
18 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
19 |
# Salesforce connection details
|
20 |
try:
|
21 |
print("Attempting to connect to Salesforce...")
|
22 |
+
sf = Salesforce(username='your_salesforce_username', password='your_salesforce_password', security_token='your_salesforce_token')
|
23 |
print("Connected to Salesforce successfully!")
|
|
|
24 |
except Exception as e:
|
25 |
print(f"Failed to connect to Salesforce: {str(e)}")
|
26 |
|
|
|
36 |
except Exception as e:
|
37 |
raise Exception(f"Failed to create record: {str(e)}")
|
38 |
|
39 |
+
def create_salesforce_order(sf, cart_items, total_price):
|
40 |
+
try:
|
41 |
+
order = sf.Order__c.create({
|
42 |
+
'Total_Price__c': total_price,
|
43 |
+
'Cart_Items__c': json.dumps(cart_items) # Storing cart items as JSON (you can refine this as needed)
|
44 |
+
})
|
45 |
+
return order
|
46 |
+
except Exception as e:
|
47 |
+
raise Exception(f"Failed to create order: {str(e)}")
|
48 |
+
|
49 |
def get_menu_items(sf):
|
50 |
query = "SELECT Name, Price__c, Ingredients__c, Category__c FROM Menu_Item__c"
|
51 |
result = sf.query(query)
|
|
|
79 |
return len(nonsilent_parts) == 0 # If no speech detected
|
80 |
|
81 |
# Routes and Views
|
82 |
+
@app.route("/")
|
83 |
+
def index():
|
84 |
+
return render_template("index.html")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
85 |
|
86 |
@app.route("/menu", methods=["GET"])
|
87 |
def menu_page():
|
|
|
89 |
menu_data = [{"name": item['Name'], "price": item['Price__c'], "ingredients": item['Ingredients__c'], "category": item['Category__c']} for item in menu_items]
|
90 |
return render_template("menu_page.html", menu_items=menu_data)
|
91 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
92 |
@app.route("/cart", methods=["GET"])
|
93 |
def cart():
|
|
|
94 |
cart_items = session.get('cart_items', [])
|
95 |
return render_template("cart_page.html", cart_items=cart_items)
|
96 |
|
97 |
@app.route("/order-summary", methods=["GET"])
|
98 |
def order_summary():
|
|
|
99 |
order_details = session.get('cart_items', [])
|
100 |
total_price = sum(item['price'] * item['quantity'] for item in order_details)
|
101 |
return render_template("order_summary.html", order_details=order_details, total_price=total_price)
|
102 |
|
103 |
@app.route("/final_order", methods=["GET"])
|
104 |
def final_order():
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
105 |
cart_items = session.get('cart_items', [])
|
106 |
+
total_price = sum(item['price'] * item['quantity'] for item in cart_items)
|
|
|
107 |
|
|
|
108 |
try:
|
109 |
+
# Create order in Salesforce
|
110 |
+
order = create_salesforce_order(sf, cart_items, total_price)
|
111 |
+
session.pop('cart_items', None) # Clear cart after finalizing the order
|
112 |
+
return render_template("final_order.html", order_details=cart_items, total_price=total_price)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
113 |
except Exception as e:
|
114 |
+
return jsonify({'error': f'Failed to create order in Salesforce: {str(e)}'}), 500
|
|
|
115 |
|
116 |
+
@app.route("/add_to_cart", methods=["POST"])
|
117 |
+
def add_to_cart():
|
118 |
+
item_name = request.json.get('item_name')
|
119 |
+
quantity = request.json.get('quantity')
|
120 |
+
|
121 |
+
cart_items = session.get('cart_items', [])
|
122 |
+
cart_items.append({"name": item_name, "quantity": quantity, "price": 10}) # Assuming a fixed price for now
|
123 |
+
session['cart_items'] = cart_items
|
124 |
+
|
125 |
+
return jsonify({"success": True, "message": f"Added {item_name} to cart."})
|
126 |
|
127 |
# Start Production Server
|
128 |
if __name__ == "__main__":
|