Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -19,21 +19,19 @@ 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})
|
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)
|
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,
|
@@ -45,19 +43,35 @@ def create_salesforce_record(name, email, phone_number):
|
|
45 |
except Exception as e:
|
46 |
raise Exception(f"Failed to create record: {str(e)}")
|
47 |
|
48 |
-
|
49 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
50 |
try:
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
"Quantity__c": quantity, # Quantity__c is the field that stores the order quantity
|
55 |
-
"Customer__c": customer_id # Customer__c is a lookup field that stores the related customer record ID
|
56 |
-
}
|
57 |
-
order = sf.Order__c.create(order_data)
|
58 |
-
return order
|
59 |
except Exception as e:
|
60 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
61 |
|
62 |
# Routes and Views
|
63 |
@app.route("/")
|
@@ -72,11 +86,9 @@ def dashboard():
|
|
72 |
def submit():
|
73 |
try:
|
74 |
data = request.get_json()
|
75 |
-
|
76 |
if not data:
|
77 |
return jsonify({"success": False, "message": "Invalid or empty JSON received"}), 400
|
78 |
|
79 |
-
# Get the values from the JSON data
|
80 |
name = data.get("name")
|
81 |
email = data.get("email")
|
82 |
phone = data.get("phone")
|
@@ -84,54 +96,141 @@ def submit():
|
|
84 |
if not name or not email or not phone:
|
85 |
return jsonify({"success": False, "message": "Missing required fields"}), 400
|
86 |
|
87 |
-
#
|
88 |
-
salesforce_data = {
|
89 |
-
"Name": name,
|
90 |
-
"Email__c": email,
|
91 |
-
"Phone_Number__c": phone
|
92 |
-
}
|
93 |
-
|
94 |
try:
|
95 |
result = sf.Customer_Login__c.create(salesforce_data)
|
96 |
-
print(f"Salesforce Response: {result}")
|
97 |
return jsonify({"success": True, "message": "Data submitted successfully"})
|
98 |
-
|
99 |
except Exception as e:
|
100 |
return jsonify({"success": False, "message": "Salesforce submission failed", "error": str(e)}), 500
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
101 |
|
102 |
except Exception as e:
|
103 |
return jsonify({"success": False, "message": "Internal server error", "error": str(e)}), 500
|
104 |
|
105 |
@app.route("/order", methods=["POST"])
|
106 |
def place_order():
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
107 |
try:
|
108 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
109 |
|
110 |
-
|
111 |
-
|
112 |
-
|
|
|
|
|
|
|
|
|
|
|
113 |
|
114 |
-
#
|
115 |
-
|
116 |
-
return jsonify({"success": False, "message": "Missing required fields"}), 400
|
117 |
|
118 |
-
|
119 |
-
|
120 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
121 |
|
122 |
-
|
123 |
-
|
|
|
|
|
124 |
|
125 |
-
|
|
|
|
|
|
|
126 |
|
127 |
-
|
128 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
129 |
|
130 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
131 |
|
132 |
except Exception as e:
|
133 |
-
return jsonify({"
|
134 |
|
135 |
-
# Start Production Server
|
136 |
if __name__ == "__main__":
|
137 |
serve(app, host="0.0.0.0", port=7860)
|
|
|
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 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 |
except Exception as e:
|
30 |
print(f"Failed to connect to Salesforce: {str(e)}")
|
31 |
|
32 |
# Function for Salesforce operations
|
33 |
def create_salesforce_record(name, email, phone_number):
|
34 |
try:
|
|
|
35 |
customer_login = sf.Customer_Login__c.create({
|
36 |
'Name': name,
|
37 |
'Email__c': email,
|
|
|
43 |
except Exception as e:
|
44 |
raise Exception(f"Failed to create record: {str(e)}")
|
45 |
|
46 |
+
def get_menu_items():
|
47 |
+
query = "SELECT Name, Price__c, Ingredients__c, Category__c FROM Menu_Item__c"
|
48 |
+
result = sf.query(query)
|
49 |
+
return result['records']
|
50 |
+
|
51 |
+
# Voice-related functions
|
52 |
+
def generate_audio_prompt(text, filename):
|
53 |
+
try:
|
54 |
+
tts = gTTS(text)
|
55 |
+
tts.save(os.path.join("static", filename))
|
56 |
+
except gtts.tts.gTTSError as e:
|
57 |
+
print(f"Error: {e}")
|
58 |
+
time.sleep(5) # Retry after 5 seconds
|
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)
|
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)
|
74 |
+
return len(nonsilent_parts) == 0 # If no speech detected
|
75 |
|
76 |
# Routes and Views
|
77 |
@app.route("/")
|
|
|
86 |
def submit():
|
87 |
try:
|
88 |
data = request.get_json()
|
|
|
89 |
if not data:
|
90 |
return jsonify({"success": False, "message": "Invalid or empty JSON received"}), 400
|
91 |
|
|
|
92 |
name = data.get("name")
|
93 |
email = data.get("email")
|
94 |
phone = data.get("phone")
|
|
|
96 |
if not name or not email or not phone:
|
97 |
return jsonify({"success": False, "message": "Missing required fields"}), 400
|
98 |
|
99 |
+
# Insert data into Salesforce
|
100 |
+
salesforce_data = {"Name": name, "Email__c": email, "Phone_Number__c": phone}
|
|
|
|
|
|
|
|
|
|
|
101 |
try:
|
102 |
result = sf.Customer_Login__c.create(salesforce_data)
|
|
|
103 |
return jsonify({"success": True, "message": "Data submitted successfully"})
|
|
|
104 |
except Exception as e:
|
105 |
return jsonify({"success": False, "message": "Salesforce submission failed", "error": str(e)}), 500
|
106 |
+
except Exception as e:
|
107 |
+
return jsonify({"success": False, "message": "Internal server error", "error": str(e)}), 500
|
108 |
+
|
109 |
+
@app.route("/menu", methods=["GET"])
|
110 |
+
def menu_page():
|
111 |
+
menu_items = get_menu_items()
|
112 |
+
menu_data = [{"name": item['Name'], "price": item['Price__c'], "ingredients": item['Ingredients__c'], "category": item['Category__c']} for item in menu_items]
|
113 |
+
return render_template("menu_page.html", menu_items=menu_data)
|
114 |
+
|
115 |
+
@app.route("/validate-login", methods=["POST"])
|
116 |
+
def validate_login():
|
117 |
+
try:
|
118 |
+
# Ensure JSON is being received
|
119 |
+
data = request.get_json()
|
120 |
+
login_email = data.get("email")
|
121 |
+
login_mobile = data.get("mobile")
|
122 |
+
|
123 |
+
# Validate if email and mobile are present
|
124 |
+
if not login_email or not login_mobile:
|
125 |
+
return jsonify({"success": False, "message": "Missing email or mobile number"}), 400
|
126 |
+
|
127 |
+
# Query Salesforce to check if the record exists
|
128 |
+
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}'"
|
129 |
+
result = sf.query(query)
|
130 |
+
|
131 |
+
if result['records']:
|
132 |
+
# If a matching record is found, return success and the name
|
133 |
+
user_name = result['records'][0]['Name']
|
134 |
+
return jsonify({"success": True, "message": "Login successful", "name": user_name})
|
135 |
+
else:
|
136 |
+
# If no matching record is found
|
137 |
+
return jsonify({"success": False, "message": "Invalid email or mobile number"}), 401
|
138 |
|
139 |
except Exception as e:
|
140 |
return jsonify({"success": False, "message": "Internal server error", "error": str(e)}), 500
|
141 |
|
142 |
@app.route("/order", methods=["POST"])
|
143 |
def place_order():
|
144 |
+
order_data = request.json
|
145 |
+
|
146 |
+
# Get order details from the request
|
147 |
+
customer_name = order_data.get("customerName")
|
148 |
+
customer_email = order_data.get("customerEmail")
|
149 |
+
customer_phone = order_data.get("customerPhone")
|
150 |
+
customer_address = order_data.get("customerAddress")
|
151 |
+
items = order_data.get("items")
|
152 |
+
total_amount = order_data.get("totalAmount")
|
153 |
+
|
154 |
+
# Ensure all required fields are present
|
155 |
+
if not customer_name or not customer_email or not customer_phone or not customer_address or not items or not total_amount:
|
156 |
+
return jsonify({"success": False, "message": "Missing required fields"}), 400
|
157 |
+
|
158 |
try:
|
159 |
+
# Create the order in Salesforce (custom object Order__c)
|
160 |
+
order = sf.Order__c.create({
|
161 |
+
"Customer_Name__c": customer_name,
|
162 |
+
"Customer_Email__c": customer_email,
|
163 |
+
"Customer_Phone__c": customer_phone,
|
164 |
+
"Customer_Address__c": customer_address,
|
165 |
+
"Total_Amount__c": total_amount
|
166 |
+
})
|
167 |
|
168 |
+
# Optionally create order items in a related object or as line items
|
169 |
+
for item in items:
|
170 |
+
sf.Order_Item__c.create({
|
171 |
+
"Order__c": order['id'], # Link to the parent order
|
172 |
+
"Item__c": item['name'],
|
173 |
+
"Quantity__c": item['quantity'],
|
174 |
+
"Price__c": item['price']
|
175 |
+
})
|
176 |
|
177 |
+
# Return success response
|
178 |
+
return jsonify({"success": True, "message": "Order placed successfully."})
|
|
|
179 |
|
180 |
+
except Exception as e:
|
181 |
+
# If an error occurs, return an error message
|
182 |
+
return jsonify({"success": False, "message": f"Error placing order: {str(e)}"}), 500
|
183 |
+
|
184 |
+
@app.route("/cart", methods=["GET"])
|
185 |
+
def cart():
|
186 |
+
cart_items = [] # Placeholder for cart items
|
187 |
+
return render_template("cart_page.html", cart_items=cart_items)
|
188 |
+
|
189 |
+
@app.route("/order-summary", methods=["GET"])
|
190 |
+
def order_summary():
|
191 |
+
order_details = [] # Placeholder for order details
|
192 |
+
return render_template("order_summary.html", order_details=order_details)
|
193 |
|
194 |
+
@app.route("/transcribe", methods=["POST"])
|
195 |
+
def transcribe():
|
196 |
+
if "audio" not in request.files:
|
197 |
+
return jsonify({"error": "No audio file provided"}), 400
|
198 |
|
199 |
+
audio_file = request.files["audio"]
|
200 |
+
input_audio_path = os.path.join("static", "temp_input.wav")
|
201 |
+
output_audio_path = os.path.join("static", "temp.wav")
|
202 |
+
audio_file.save(input_audio_path)
|
203 |
|
204 |
+
try:
|
205 |
+
convert_to_wav(input_audio_path, output_audio_path)
|
206 |
+
|
207 |
+
if is_silent_audio(output_audio_path):
|
208 |
+
return jsonify({"error": "No speech detected. Please try again."}), 400
|
209 |
+
|
210 |
+
result = pipeline("automatic-speech-recognition", model="openai/whisper-small", device=0 if torch.cuda.is_available() else -1, config=config)
|
211 |
+
transcribed_text = result["text"].strip().capitalize()
|
212 |
+
|
213 |
+
# Extract name, email, and phone number from the transcribed text
|
214 |
+
parts = transcribed_text.split()
|
215 |
+
name = parts[0] if len(parts) > 0 else "Unknown Name"
|
216 |
+
email = parts[1] if '@' in parts[1] else "[email protected]"
|
217 |
+
phone_number = parts[2] if len(parts) > 2 else "0000000000"
|
218 |
+
|
219 |
+
confirmation = f"Is this correct? Name: {name}, Email: {email}, Phone: {phone_number}"
|
220 |
+
generate_audio_prompt(confirmation, "confirmation.mp3")
|
221 |
|
222 |
+
user_confirms = True # Assuming user confirms, replace with actual logic
|
223 |
+
|
224 |
+
if user_confirms:
|
225 |
+
salesforce_response = create_salesforce_record(name, email, phone_number)
|
226 |
+
|
227 |
+
if "error" in salesforce_response:
|
228 |
+
return jsonify(salesforce_response), 500
|
229 |
+
|
230 |
+
return jsonify({"text": transcribed_text, "salesforce_record": salesforce_response})
|
231 |
|
232 |
except Exception as e:
|
233 |
+
return jsonify({"error": f"Speech recognition error: {str(e)}"}), 500
|
234 |
|
|
|
235 |
if __name__ == "__main__":
|
236 |
serve(app, host="0.0.0.0", port=7860)
|