Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,138 +1,194 @@
|
|
1 |
-
import
|
2 |
-
from
|
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 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
-
#
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
'Phone_Number__c': phone_number
|
39 |
-
})
|
40 |
-
return customer_login
|
41 |
-
except Exception as e:
|
42 |
-
raise Exception(f"Failed to create record: {str(e)}")
|
43 |
-
|
44 |
-
def get_menu_items():
|
45 |
-
query = "SELECT Name, Price__c, Ingredients__c, Category__c FROM Menu_Item__c"
|
46 |
-
result = sf.query(query)
|
47 |
-
return result['records']
|
48 |
-
|
49 |
-
# Login validation function
|
50 |
-
def validate_user(email, phone):
|
51 |
-
query = f"SELECT Id, Name, Email__c, Phone_Number__c FROM Customer_Login__c WHERE Email__c = '{email}' AND Phone_Number__c = '{phone}'"
|
52 |
-
result = sf.query(query)
|
53 |
-
if result['records']:
|
54 |
-
return result['records'][0] # Return user record if found
|
55 |
-
return None # Return None if user not found
|
56 |
-
|
57 |
-
# Routes and Views
|
58 |
@app.route("/")
|
59 |
def index():
|
60 |
return render_template("index.html")
|
61 |
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
67 |
|
68 |
-
|
69 |
-
|
70 |
|
71 |
-
|
72 |
-
user = validate_user(email, phone)
|
73 |
-
if user:
|
74 |
-
# User found, redirect to menu or dashboard
|
75 |
-
return redirect(url_for("menu_page")) # Assuming login redirects to the menu
|
76 |
-
else:
|
77 |
-
return jsonify({"success": False, "message": "Invalid credentials. Please try again."}), 401
|
78 |
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
|
|
|
84 |
|
|
|
85 |
@app.route("/order", methods=["POST"])
|
86 |
def place_order():
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
|
|
|
|
|
|
92 |
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
return render_template("cart_page.html", cart_items=cart_items)
|
97 |
|
98 |
-
|
99 |
-
def
|
100 |
-
|
101 |
-
|
|
|
102 |
|
103 |
-
|
104 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
105 |
try:
|
106 |
data = request.get_json()
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
# Get the values from the JSON data
|
111 |
-
name = data.get("name")
|
112 |
-
email = data.get("email")
|
113 |
-
phone = data.get("phone")
|
114 |
|
115 |
-
# Validate if all fields are present
|
116 |
if not name or not email or not phone:
|
117 |
-
return jsonify({"success": False, "message": "
|
118 |
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
|
|
|
|
|
|
|
124 |
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
131 |
|
132 |
except Exception as e:
|
133 |
-
print(f"
|
134 |
return jsonify({"success": False, "message": "Internal server error", "error": str(e)}), 500
|
135 |
|
136 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
137 |
if __name__ == "__main__":
|
138 |
serve(app, host="0.0.0.0", port=7860)
|
|
|
1 |
+
from flask import Flask, render_template, request, jsonify, session
|
2 |
+
from simple_salesforce import Salesforce
|
3 |
import json
|
4 |
import os
|
5 |
+
import time
|
6 |
from transformers import pipeline
|
7 |
+
import torch
|
8 |
from gtts import gTTS
|
9 |
from pydub import AudioSegment
|
10 |
from pydub.silence import detect_nonsilent
|
11 |
+
from transformers import AutoConfig # Import AutoConfig for the config object
|
|
|
12 |
from waitress import serve
|
|
|
|
|
13 |
|
14 |
app = Flask(__name__)
|
15 |
+
app.secret_key = 'your_secret_key_here' # Secret key for session management
|
16 |
+
|
17 |
+
# Sample menu data
|
18 |
+
menu_data = {
|
19 |
+
"Main Course": [
|
20 |
+
{"name": "Chicken Biryani", "price": 250},
|
21 |
+
{"name": "Veg Biryani", "price": 200},
|
22 |
+
{"name": "Mutton Biryani", "price": 300},
|
23 |
+
],
|
24 |
+
"Appetizers": [
|
25 |
+
{"name": "Paneer Tikka", "price": 180},
|
26 |
+
{"name": "Chicken Wings", "price": 220},
|
27 |
+
]
|
28 |
+
}
|
29 |
|
30 |
# Salesforce credentials (Replace with actual values)
|
31 |
try:
|
32 |
print("Attempting to connect to Salesforce...")
|
33 |
sf = Salesforce(username='[email protected]', password='Sati@1020', security_token='sSSjyhInIsUohKpG8sHzty2q')
|
34 |
print("Connected to Salesforce successfully!")
|
35 |
+
print("User Info:", sf.UserInfo) # Log the user info to verify the connection
|
36 |
except Exception as e:
|
37 |
print(f"Failed to connect to Salesforce: {str(e)}")
|
38 |
|
39 |
+
# Setup Whisper ASR model and Salesforce credentials
|
40 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
41 |
+
config = AutoConfig.from_pretrained("openai/whisper-small")
|
42 |
+
config.update({"timeout": 60})
|
43 |
+
|
44 |
+
# Route for the Welcome Page (Page 1)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
45 |
@app.route("/")
|
46 |
def index():
|
47 |
return render_template("index.html")
|
48 |
|
49 |
+
# Route for the Menu Pages (Page 2)
|
50 |
+
@app.route("/menu", methods=["GET"])
|
51 |
+
def menu_page():
|
52 |
+
category = request.args.get('category', 'Main Course')
|
53 |
+
if category not in menu_data:
|
54 |
+
return jsonify({"error": "Category not found"}), 404
|
55 |
+
return render_template("menu_page.html", menu_items=menu_data[category])
|
56 |
+
|
57 |
+
# Route to add items to the cart
|
58 |
+
@app.route("/add-to-cart", methods=["POST"])
|
59 |
+
def add_to_cart():
|
60 |
+
item_data = request.get_json()
|
61 |
+
item_name = item_data.get('name')
|
62 |
+
item_price = item_data.get('price')
|
63 |
+
|
64 |
+
# If cart is not in session, initialize it
|
65 |
+
if 'cart' not in session:
|
66 |
+
session['cart'] = []
|
67 |
|
68 |
+
# Add item to the cart
|
69 |
+
session['cart'].append({"name": item_name, "price": item_price})
|
70 |
|
71 |
+
return jsonify({"message": f"{item_name} added to cart!"}), 200
|
|
|
|
|
|
|
|
|
|
|
|
|
72 |
|
73 |
+
# Route for Cart Page (Page 3)
|
74 |
+
@app.route("/cart", methods=["GET"])
|
75 |
+
def cart_page():
|
76 |
+
if 'cart' not in session or len(session['cart']) == 0:
|
77 |
+
return jsonify({"message": "Your cart is empty"}), 200
|
78 |
+
return render_template("cart_page.html", cart_items=session['cart'])
|
79 |
|
80 |
+
# Route to place an order (API integration for placing order)
|
81 |
@app.route("/order", methods=["POST"])
|
82 |
def place_order():
|
83 |
+
if 'cart' not in session or len(session['cart']) == 0:
|
84 |
+
return jsonify({"message": "Cart is empty, cannot place order."}), 400
|
85 |
+
|
86 |
+
order_data = session['cart']
|
87 |
+
|
88 |
+
# Here you can integrate with your API or Salesforce
|
89 |
+
# Example: Call Salesforce API to store the order
|
90 |
+
salesforce_response = send_to_salesforce(order_data)
|
91 |
|
92 |
+
# Simulate order processing with a success message
|
93 |
+
session['cart'] = [] # Clear the cart after order
|
94 |
+
return jsonify({"message": "Order placed successfully!", "order_data": order_data, "salesforce_response": salesforce_response}), 200
|
|
|
95 |
|
96 |
+
# Salesforce integration function
|
97 |
+
def send_to_salesforce(order_data):
|
98 |
+
try:
|
99 |
+
# Salesforce authentication
|
100 |
+
sf = Salesforce(username='[email protected]', password='Sati@1020', security_token='sSSjyhInIsUohKpG8sHzty2q')
|
101 |
|
102 |
+
# Example: Create an Order record in Salesforce
|
103 |
+
order = sf.Order__c.create({
|
104 |
+
'Name': 'New Order',
|
105 |
+
'Items__c': str(order_data) # Example field for items (this could be a custom Salesforce field)
|
106 |
+
})
|
107 |
+
return order
|
108 |
+
except Exception as e:
|
109 |
+
print(f"Error: {e}")
|
110 |
+
return None
|
111 |
+
|
112 |
+
# Route to register a new user
|
113 |
+
@app.route('/register', methods=['POST'])
|
114 |
+
def register():
|
115 |
try:
|
116 |
data = request.get_json()
|
117 |
+
name = data.get('name')
|
118 |
+
email = data.get('email')
|
119 |
+
phone = data.get('phone')
|
|
|
|
|
|
|
|
|
120 |
|
|
|
121 |
if not name or not email or not phone:
|
122 |
+
return jsonify({"success": False, "message": "All fields are required."}), 400
|
123 |
|
124 |
+
# Create a new record in Salesforce's Customer_Login__c object
|
125 |
+
customer_login = sf.Customer_Login__c.create({
|
126 |
+
'Name': name,
|
127 |
+
'Email__c': email,
|
128 |
+
'Phone_Number__c': phone
|
129 |
+
})
|
130 |
+
|
131 |
+
return jsonify({"success": True, "message": "Registration successful!", "salesforce_response": customer_login}), 201
|
132 |
|
133 |
+
except Exception as e:
|
134 |
+
print(f"Error: {str(e)}")
|
135 |
+
return jsonify({"success": False, "message": f"Registration failed: {str(e)}"}), 500
|
136 |
+
|
137 |
+
# Route to validate login credentials
|
138 |
+
@app.route('/validate-login', methods=['POST'])
|
139 |
+
def validate_login():
|
140 |
+
try:
|
141 |
+
data = request.get_json()
|
142 |
+
login_email = data.get("email")
|
143 |
+
login_mobile = data.get("mobile")
|
144 |
+
|
145 |
+
if not login_email or not login_mobile:
|
146 |
+
return jsonify({"success": False, "message": "Missing email or mobile number"}), 400
|
147 |
+
|
148 |
+
# Query Salesforce to check if the record exists
|
149 |
+
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}'"
|
150 |
+
result = sf.query(query)
|
151 |
+
|
152 |
+
if result['records']:
|
153 |
+
# If a matching record is found, return success and the name
|
154 |
+
user_name = result['records'][0]['Name']
|
155 |
+
return jsonify({"success": True, "message": "Login successful", "name": user_name})
|
156 |
+
else:
|
157 |
+
return jsonify({"success": False, "message": "Invalid email or mobile number"}), 401
|
158 |
|
159 |
except Exception as e:
|
160 |
+
print(f"Error validating login: {str(e)}")
|
161 |
return jsonify({"success": False, "message": "Internal server error", "error": str(e)}), 500
|
162 |
|
163 |
+
|
164 |
+
# Voice-related functions
|
165 |
+
def generate_audio_prompt(text, filename):
|
166 |
+
try:
|
167 |
+
tts = gTTS(text)
|
168 |
+
tts.save(os.path.join("static", filename))
|
169 |
+
except gtts.tts.gTTSError as e:
|
170 |
+
print(f"Error: {e}")
|
171 |
+
print("Retrying after 5 seconds...")
|
172 |
+
time.sleep(5) # Wait for 5 seconds before retrying
|
173 |
+
generate_audio_prompt(text, filename)
|
174 |
+
|
175 |
+
# Utility functions
|
176 |
+
def convert_to_wav(input_path, output_path):
|
177 |
+
try:
|
178 |
+
audio = AudioSegment.from_file(input_path)
|
179 |
+
audio = audio.set_frame_rate(16000).set_channels(1) # Convert to 16kHz, mono
|
180 |
+
audio.export(output_path, format="wav")
|
181 |
+
except Exception as e:
|
182 |
+
print(f"Error: {str(e)}")
|
183 |
+
raise Exception(f"Audio conversion failed: {str(e)}")
|
184 |
+
|
185 |
+
def is_silent_audio(audio_path):
|
186 |
+
audio = AudioSegment.from_wav(audio_path)
|
187 |
+
nonsilent_parts = detect_nonsilent(audio, min_silence_len=500, silence_thresh=audio.dBFS-16) # Reduced silence duration
|
188 |
+
print(f"Detected nonsilent parts: {nonsilent_parts}")
|
189 |
+
return len(nonsilent_parts) == 0 # If no speech detected
|
190 |
+
|
191 |
+
|
192 |
+
# Start Production Server
|
193 |
if __name__ == "__main__":
|
194 |
serve(app, host="0.0.0.0", port=7860)
|