Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -1,101 +1,216 @@
|
|
|
|
|
|
|
|
1 |
import os
|
2 |
-
from
|
|
|
|
|
|
|
|
|
|
|
|
|
3 |
from simple_salesforce import Salesforce
|
|
|
4 |
|
|
|
5 |
app = Flask(__name__)
|
|
|
6 |
|
7 |
-
#
|
8 |
-
|
9 |
|
10 |
-
#
|
|
|
|
|
|
|
|
|
11 |
try:
|
12 |
print("Attempting to connect to Salesforce...")
|
13 |
sf = Salesforce(username='[email protected]', password='Sati@1020', security_token='sSSjyhInIsUohKpG8sHzty2q')
|
14 |
print("Connected to Salesforce successfully!")
|
|
|
15 |
except Exception as e:
|
16 |
print(f"Failed to connect to Salesforce: {str(e)}")
|
17 |
|
18 |
-
#
|
19 |
-
def create_salesforce_record(name, email,
|
20 |
try:
|
21 |
-
# Create record in Salesforce's Customer_Login__c object
|
22 |
customer_login = sf.Customer_Login__c.create({
|
23 |
'Name': name,
|
24 |
'Email__c': email,
|
25 |
-
'Phone_Number__c':
|
26 |
})
|
27 |
return customer_login
|
28 |
except Exception as e:
|
29 |
-
raise Exception(f"Failed to create record
|
30 |
-
|
31 |
-
# Route to handle registration form submission
|
32 |
-
@app.route("/register", methods=["POST", "GET"])
|
33 |
-
def register():
|
34 |
-
if request.method == "POST":
|
35 |
-
name = request.json.get('name')
|
36 |
-
email = request.json.get('email')
|
37 |
-
phone = request.json.get('phone')
|
38 |
|
39 |
-
|
40 |
-
|
|
|
|
|
41 |
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
47 |
|
48 |
-
|
49 |
-
|
|
|
|
|
|
|
50 |
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
|
56 |
-
|
|
|
|
|
57 |
|
58 |
-
|
59 |
-
@app.route("/login", methods=["POST"])
|
60 |
def login():
|
61 |
-
|
62 |
-
|
|
|
|
|
|
|
63 |
|
64 |
-
if not email or not
|
65 |
return jsonify({'error': 'Missing required fields'}), 400
|
66 |
|
67 |
try:
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
customer = result['records'][0]
|
72 |
-
session['customer_name'] = customer['Name']
|
73 |
-
session['customer_id'] = customer['Id']
|
74 |
-
|
75 |
-
# Return success message and redirect to menu
|
76 |
-
return jsonify({'success': True, 'message': f'Hi {customer["Name"]}, welcome back to Briyani Hub!'}), 200
|
77 |
-
else:
|
78 |
-
return jsonify({'error': 'Invalid email or phone number'}), 400
|
79 |
-
|
80 |
except Exception as e:
|
81 |
-
|
82 |
-
|
|
|
|
|
|
|
|
|
|
|
83 |
|
84 |
-
# Route for handling the cart (this could be updated later to handle actual cart data)
|
85 |
@app.route("/cart", methods=["GET"])
|
86 |
def cart():
|
87 |
-
|
|
|
|
|
88 |
|
89 |
-
# Route for the order summary page
|
90 |
@app.route("/order-summary", methods=["GET"])
|
91 |
def order_summary():
|
92 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
93 |
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
99 |
|
|
|
100 |
if __name__ == "__main__":
|
101 |
-
app.
|
|
|
1 |
+
import torch
|
2 |
+
from flask import Flask, render_template, request, jsonify, redirect, session
|
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 |
+
# Initialize Flask app
|
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='[email protected]', password='Sati@1020', security_token='sSSjyhInIsUohKpG8sHzty2q')
|
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 |
|
35 |
+
# Functions for Salesforce operations
|
36 |
+
def create_salesforce_record(sf, name, email, phone_number):
|
37 |
try:
|
|
|
38 |
customer_login = sf.Customer_Login__c.create({
|
39 |
'Name': name,
|
40 |
'Email__c': email,
|
41 |
+
'Phone_Number__c': phone_number
|
42 |
})
|
43 |
return customer_login
|
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)
|
50 |
+
return result['records']
|
51 |
|
52 |
+
# Voice-related functions
|
53 |
+
def generate_audio_prompt(text, filename):
|
54 |
+
try:
|
55 |
+
tts = gTTS(text)
|
56 |
+
tts.save(os.path.join("static", filename))
|
57 |
+
except gtts.tts.gTTSError as e:
|
58 |
+
print(f"Error: {e}")
|
59 |
+
print("Retrying after 5 seconds...")
|
60 |
+
time.sleep(5) # Wait for 5 seconds before retrying
|
61 |
+
generate_audio_prompt(text, filename)
|
62 |
+
|
63 |
+
# Utility functions
|
64 |
+
def convert_to_wav(input_path, output_path):
|
65 |
+
try:
|
66 |
+
audio = AudioSegment.from_file(input_path)
|
67 |
+
audio = audio.set_frame_rate(16000).set_channels(1) # Convert to 16kHz, mono
|
68 |
+
audio.export(output_path, format="wav")
|
69 |
+
except Exception as e:
|
70 |
+
print(f"Error: {str(e)}")
|
71 |
+
raise Exception(f"Audio conversion failed: {str(e)}")
|
72 |
|
73 |
+
def is_silent_audio(audio_path):
|
74 |
+
audio = AudioSegment.from_wav(audio_path)
|
75 |
+
nonsilent_parts = detect_nonsilent(audio, min_silence_len=500, silence_thresh=audio.dBFS-16) # Reduced silence duration
|
76 |
+
print(f"Detected nonsilent parts: {nonsilent_parts}")
|
77 |
+
return len(nonsilent_parts) == 0 # If no speech detected
|
78 |
|
79 |
+
# Routes and Views
|
80 |
+
@app.route("/")
|
81 |
+
def index():
|
82 |
+
return render_template("index.html")
|
83 |
|
84 |
+
@app.route("/dashboard", methods=["GET"])
|
85 |
+
def dashboard():
|
86 |
+
return render_template("dashboard.html") # Render the dashboard template
|
87 |
|
88 |
+
@app.route('/login', methods=['POST'])
|
|
|
89 |
def login():
|
90 |
+
# Get data from voice bot (name, email, phone number)
|
91 |
+
data = request.json # Assuming voice bot sends JSON data
|
92 |
+
name = data.get('name')
|
93 |
+
email = data.get('email')
|
94 |
+
phone_number = data.get('phone_number')
|
95 |
|
96 |
+
if not name or not email or not phone_number:
|
97 |
return jsonify({'error': 'Missing required fields'}), 400
|
98 |
|
99 |
try:
|
100 |
+
customer_login = create_salesforce_record(sf, name, email, phone_number)
|
101 |
+
session['customer_id'] = customer_login['id'] # Store customer ID in session
|
102 |
+
return redirect("/menu") # Redirect to the menu page after successful login
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
103 |
except Exception as e:
|
104 |
+
return jsonify({'error': f'Failed to create record in Salesforce: {str(e)}'}), 500
|
105 |
+
|
106 |
+
@app.route("/menu", methods=["GET"])
|
107 |
+
def menu_page():
|
108 |
+
menu_items = get_menu_items(sf) # Fetch menu items from Salesforce
|
109 |
+
menu_data = [{"name": item['Name'], "price": item['Price__c'], "ingredients": item['Ingredients__c'], "category": item['Category__c']} for item in menu_items]
|
110 |
+
return render_template("menu_page.html", menu_items=menu_data)
|
111 |
|
|
|
112 |
@app.route("/cart", methods=["GET"])
|
113 |
def cart():
|
114 |
+
# Retrieve cart items from session
|
115 |
+
cart_items = session.get('cart_items', [])
|
116 |
+
return render_template("cart_page.html", cart_items=cart_items)
|
117 |
|
|
|
118 |
@app.route("/order-summary", methods=["GET"])
|
119 |
def order_summary():
|
120 |
+
# Retrieve order details from session
|
121 |
+
order_details = session.get('cart_items', [])
|
122 |
+
total_price = sum(item['price'] * item['quantity'] for item in order_details)
|
123 |
+
return render_template("order_summary.html", order_details=order_details, total_price=total_price)
|
124 |
+
|
125 |
+
@app.route("/final_order", methods=["GET"])
|
126 |
+
def final_order():
|
127 |
+
# Clear cart items from the session after confirming the order
|
128 |
+
session.pop('cart_items', None)
|
129 |
+
return render_template("final_order.html")
|
130 |
+
|
131 |
+
@app.route("/add_to_cart", methods=["POST"])
|
132 |
+
def add_to_cart():
|
133 |
+
item_name = request.json.get('item_name')
|
134 |
+
quantity = request.json.get('quantity')
|
135 |
+
|
136 |
+
# Retrieve the current cart items from session or initialize an empty list
|
137 |
+
cart_items = session.get('cart_items', [])
|
138 |
+
cart_items.append({"name": item_name, "quantity": quantity, "price": 10}) # Assuming a fixed price for now
|
139 |
+
session['cart_items'] = cart_items # Save the updated cart items in session
|
140 |
+
|
141 |
+
return jsonify({"success": True, "message": f"Added {item_name} to cart."})
|
142 |
+
|
143 |
+
@app.route("/transcribe", methods=["POST"])
|
144 |
+
def transcribe():
|
145 |
+
if "audio" not in request.files:
|
146 |
+
print("No audio file provided")
|
147 |
+
return jsonify({"error": "No audio file provided"}), 400
|
148 |
+
|
149 |
+
audio_file = request.files["audio"]
|
150 |
+
input_audio_path = os.path.join("static", "temp_input.wav")
|
151 |
+
output_audio_path = os.path.join("static", "temp.wav")
|
152 |
+
audio_file.save(input_audio_path)
|
153 |
|
154 |
+
try:
|
155 |
+
# Convert to WAV
|
156 |
+
convert_to_wav(input_audio_path, output_audio_path)
|
157 |
+
|
158 |
+
# Check for silence
|
159 |
+
if is_silent_audio(output_audio_path):
|
160 |
+
return jsonify({"error": "No speech detected. Please try again."}), 400
|
161 |
+
else:
|
162 |
+
print("Audio contains speech, proceeding with transcription.")
|
163 |
+
|
164 |
+
# Use Whisper ASR model for transcription
|
165 |
+
result = None
|
166 |
+
retry_attempts = 3
|
167 |
+
for attempt in range(retry_attempts):
|
168 |
+
try:
|
169 |
+
result = pipeline("automatic-speech-recognition", model="openai/whisper-small", device=0 if torch.cuda.is_available() else -1, config=config)
|
170 |
+
print(f"Transcribed text: {result['text']}")
|
171 |
+
break
|
172 |
+
except requests.exceptions.ReadTimeout:
|
173 |
+
print(f"Timeout occurred, retrying attempt {attempt + 1}/{retry_attempts}...")
|
174 |
+
time.sleep(5)
|
175 |
+
|
176 |
+
if result is None:
|
177 |
+
return jsonify({"error": "Unable to transcribe audio after retries."}), 500
|
178 |
+
|
179 |
+
transcribed_text = result["text"].strip().capitalize()
|
180 |
+
print(f"Transcribed text: {transcribed_text}")
|
181 |
+
|
182 |
+
# Extract name, email, and phone number from the transcribed text
|
183 |
+
parts = transcribed_text.split()
|
184 |
+
name = parts[0] if len(parts) > 0 else "Unknown Name"
|
185 |
+
email = parts[1] if '@' in parts[1] else "[email protected]"
|
186 |
+
phone_number = parts[2] if len(parts) > 2 else "0000000000"
|
187 |
+
print(f"Parsed data - Name: {name}, Email: {email}, Phone Number: {phone_number}")
|
188 |
+
|
189 |
+
# Confirm details before submission
|
190 |
+
confirmation = f"Is this correct? Name: {name}, Email: {email}, Phone: {phone_number}"
|
191 |
+
generate_audio_prompt(confirmation, "confirmation.mp3")
|
192 |
+
|
193 |
+
# Simulate confirmation via user action
|
194 |
+
user_confirms = True # Assuming the user confirms, you can replace this with actual user input logic
|
195 |
+
|
196 |
+
if user_confirms:
|
197 |
+
# Create record in Salesforce
|
198 |
+
salesforce_response = create_salesforce_record(name, email, phone_number)
|
199 |
+
|
200 |
+
# Log the Salesforce response
|
201 |
+
print(f"Salesforce record creation response: {salesforce_response}")
|
202 |
+
|
203 |
+
# Check if the response contains an error
|
204 |
+
if "error" in salesforce_response:
|
205 |
+
print(f"Error creating record in Salesforce: {salesforce_response['error']}")
|
206 |
+
return jsonify(salesforce_response), 500
|
207 |
+
|
208 |
+
return jsonify({"text": transcribed_text, "salesforce_record": salesforce_response})
|
209 |
+
|
210 |
+
except Exception as e:
|
211 |
+
print(f"Error in transcribing or processing: {str(e)}")
|
212 |
+
return jsonify({"error": f"Speech recognition error: {str(e)}"}), 500
|
213 |
|
214 |
+
# Start Production Server
|
215 |
if __name__ == "__main__":
|
216 |
+
serve(app, host="0.0.0.0", port=7860)
|