Update app.py
Browse files
app.py
CHANGED
@@ -13,7 +13,7 @@ from simple_salesforce import Salesforce
|
|
13 |
import requests # Import requests for exception handling
|
14 |
|
15 |
app = Flask(__name__)
|
16 |
-
app.secret_key = 'your_secret_key'
|
17 |
|
18 |
# Use whisper-small for faster processing and better speed
|
19 |
device = "cuda" if torch.cuda.is_available() else "cpu"
|
@@ -22,30 +22,23 @@ device = "cuda" if torch.cuda.is_available() else "cpu"
|
|
22 |
config = AutoConfig.from_pretrained("openai/whisper-small")
|
23 |
config.update({"timeout": 60}) # Set timeout to 60 seconds
|
24 |
|
25 |
-
# Salesforce
|
26 |
try:
|
27 |
print("Attempting to connect to Salesforce...")
|
28 |
sf = Salesforce(username='[email protected]', password='Sati@1020', security_token='sSSjyhInIsUohKpG8sHzty2q')
|
29 |
print("Connected to Salesforce successfully!")
|
30 |
-
print("User Info:", sf.UserInfo) # Log the user info to verify the connection
|
31 |
except Exception as e:
|
32 |
print(f"Failed to connect to Salesforce: {str(e)}")
|
33 |
|
34 |
-
# Global cart variable to store cart items
|
35 |
-
cart = []
|
36 |
-
|
37 |
# Function for Salesforce operations
|
38 |
def create_salesforce_record(name, email, phone_number):
|
39 |
try:
|
40 |
-
# Create a new record in Salesforce's Customer_Login__c object
|
41 |
customer_login = sf.Customer_Login__c.create({
|
42 |
'Name': name,
|
43 |
'Email__c': email,
|
44 |
'Phone_Number__c': phone_number
|
45 |
})
|
46 |
return customer_login
|
47 |
-
except SalesforceResourceNotFound as e:
|
48 |
-
raise Exception(f"Salesforce resource not found: {str(e)}")
|
49 |
except Exception as e:
|
50 |
raise Exception(f"Failed to create record: {str(e)}")
|
51 |
|
@@ -54,6 +47,17 @@ def get_menu_items():
|
|
54 |
result = sf.query(query)
|
55 |
return result['records']
|
56 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
57 |
# Voice-related functions
|
58 |
def generate_audio_prompt(text, filename):
|
59 |
try:
|
@@ -82,149 +86,112 @@ def is_silent_audio(audio_path):
|
|
82 |
return len(nonsilent_parts) == 0 # If no speech detected
|
83 |
|
84 |
# Routes and Views
|
85 |
-
@app.route("/
|
86 |
-
def
|
87 |
-
|
88 |
-
menu_data = [{"name": item['Name'], "price": item['Price__c'], "ingredients": item['Ingredients__c'], "category": item['Category__c']} for item in menu_items]
|
89 |
-
return render_template("menu_page.html", menu_items=menu_data)
|
90 |
-
|
91 |
-
@app.route("/add_to_cart", methods=["POST"])
|
92 |
-
def add_to_cart():
|
93 |
-
item_name = request.json.get('item_name')
|
94 |
-
quantity = request.json.get('quantity')
|
95 |
-
|
96 |
-
# Find item price
|
97 |
-
for category, items in MENU.items():
|
98 |
-
if item_name in items:
|
99 |
-
price = items[item_name]
|
100 |
-
cart_item = {
|
101 |
-
'name': item_name,
|
102 |
-
'price': price,
|
103 |
-
'quantity': quantity
|
104 |
-
}
|
105 |
-
cart.append(cart_item)
|
106 |
-
return jsonify({"message": f"Added {quantity} x {item_name} to the cart."})
|
107 |
-
|
108 |
-
return jsonify({"message": "Item not found in menu."}), 404
|
109 |
-
|
110 |
-
# Route for handling order
|
111 |
-
@app.route("/order", methods=["POST"])
|
112 |
-
def place_order():
|
113 |
-
item_name = request.json.get('item_name')
|
114 |
-
quantity = request.json.get('quantity')
|
115 |
-
order_data = {"Item__c": item_name, "Quantity__c": quantity}
|
116 |
-
sf.Order__c.create(order_data)
|
117 |
-
return jsonify({"success": True, "message": f"Order for {item_name} placed successfully."})
|
118 |
-
|
119 |
-
# Route to handle the cart
|
120 |
-
@app.route("/cart", methods=["GET"])
|
121 |
-
def cart():
|
122 |
-
cart_items = [] # Placeholder for cart items
|
123 |
-
return render_template("cart_page.html", cart_items=cart_items)
|
124 |
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
order_details = [] # Placeholder for order details
|
129 |
-
return render_template("order_summary.html", order_details=order_details)
|
130 |
|
131 |
@app.route('/submit', methods=['POST'])
|
132 |
def submit():
|
133 |
try:
|
134 |
-
# Ensure JSON is being received
|
135 |
data = request.get_json()
|
136 |
print("Received Data:", data) # Debugging line
|
137 |
|
138 |
if not data:
|
139 |
return jsonify({"success": False, "message": "Invalid or empty JSON received"}), 400
|
140 |
|
141 |
-
# Get the values from the JSON data
|
142 |
name = data.get("name")
|
143 |
email = data.get("email")
|
144 |
phone = data.get("phone")
|
145 |
|
146 |
-
# Validate if all fields are present
|
147 |
if not name or not email or not phone:
|
148 |
return jsonify({"success": False, "message": "Missing required fields"}), 400
|
149 |
|
150 |
-
# Prepare data for Salesforce submission
|
151 |
salesforce_data = {
|
152 |
"Name": name,
|
153 |
"Email__c": email, # Ensure this is the correct field API name in Salesforce
|
154 |
"Phone_Number__c": phone # Ensure this is the correct field API name in Salesforce
|
155 |
}
|
156 |
|
157 |
-
# Insert data into Salesforce using simple_salesforce
|
158 |
try:
|
159 |
result = sf.Customer_Login__c.create(salesforce_data) # Replace `Customer_Login__c` with your Salesforce object API name
|
160 |
print(f"Salesforce Response: {result}") # Debugging line
|
161 |
-
|
162 |
return jsonify({"success": True, "message": "Data submitted successfully"})
|
163 |
-
|
164 |
except Exception as e:
|
165 |
if "STORAGE_LIMIT_EXCEEDED" in str(e):
|
166 |
return jsonify({"success": False, "message": "Salesforce storage limit exceeded. Please clean up or contact support."}), 500
|
167 |
else:
|
168 |
print(f"Salesforce Insertion Error: {str(e)}") # Log Salesforce errors
|
169 |
return jsonify({"success": False, "message": "Salesforce submission failed", "error": str(e)}), 500
|
170 |
-
|
171 |
except Exception as e:
|
172 |
print(f"Server Error: {str(e)}") # Log general errors
|
173 |
return jsonify({"success": False, "message": "Internal server error", "error": str(e)}), 500
|
174 |
|
175 |
-
|
176 |
@app.route('/validate-login', methods=['POST'])
|
177 |
def validate_login():
|
178 |
try:
|
179 |
-
# Ensure JSON is being received
|
180 |
data = request.get_json()
|
181 |
login_email = data.get("email")
|
182 |
login_mobile = data.get("mobile")
|
183 |
|
184 |
-
# Validate if email and mobile are present
|
185 |
if not login_email or not login_mobile:
|
186 |
return jsonify({"success": False, "message": "Missing email or mobile number"}), 400
|
187 |
|
188 |
-
# Query Salesforce to check if the record exists
|
189 |
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}'"
|
190 |
result = sf.query(query)
|
191 |
|
192 |
if result['records']:
|
193 |
-
|
194 |
-
user_name = result['records'][0]['Name'] # Assuming the 'Name' field is present in the Salesforce object
|
195 |
return jsonify({"success": True, "message": "Login successful", "name": user_name})
|
196 |
else:
|
197 |
-
# If no matching record is found
|
198 |
return jsonify({"success": False, "message": "Invalid email or mobile number"}), 401
|
199 |
-
|
200 |
except Exception as e:
|
201 |
print(f"Error validating login: {str(e)}")
|
202 |
return jsonify({"success": False, "message": "Internal server error", "error": str(e)}), 500
|
203 |
|
204 |
-
|
205 |
@app.route("/menu", methods=["GET"])
|
206 |
def menu_page():
|
207 |
menu_items = get_menu_items()
|
208 |
menu_data = [{"name": item['Name'], "price": item['Price__c'], "ingredients": item['Ingredients__c'], "category": item['Category__c']} for item in menu_items]
|
209 |
return render_template("menu_page.html", menu_items=menu_data)
|
210 |
|
211 |
-
|
212 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
213 |
def place_order():
|
214 |
-
cart_items =
|
215 |
-
total_price = sum([item['
|
216 |
customer_id = session.get('customer_id')
|
217 |
|
218 |
if not customer_id:
|
219 |
return jsonify({"message": "User not logged in"}), 400
|
220 |
|
221 |
try:
|
222 |
-
|
223 |
-
order =
|
|
|
224 |
return jsonify({"message": "Order placed successfully!", "order": order})
|
225 |
|
226 |
except Exception as e:
|
227 |
return jsonify({"message": f"Failed to create order: {str(e)}"}), 500
|
228 |
|
|
|
229 |
if __name__ == "__main__":
|
230 |
app.run(debug=True)
|
|
|
13 |
import requests # Import requests for exception handling
|
14 |
|
15 |
app = Flask(__name__)
|
16 |
+
app.secret_key = 'your_secret_key' # Use a secure secret key for sessions
|
17 |
|
18 |
# Use whisper-small for faster processing and better speed
|
19 |
device = "cuda" if torch.cuda.is_available() else "cpu"
|
|
|
22 |
config = AutoConfig.from_pretrained("openai/whisper-small")
|
23 |
config.update({"timeout": 60}) # Set timeout to 60 seconds
|
24 |
|
25 |
+
# Salesforce connection setup
|
26 |
try:
|
27 |
print("Attempting to connect to Salesforce...")
|
28 |
sf = Salesforce(username='[email protected]', password='Sati@1020', security_token='sSSjyhInIsUohKpG8sHzty2q')
|
29 |
print("Connected to Salesforce successfully!")
|
|
|
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 |
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 |
|
|
|
47 |
result = sf.query(query)
|
48 |
return result['records']
|
49 |
|
50 |
+
def create_salesforce_order(cart_items, total_price, customer_id):
|
51 |
+
try:
|
52 |
+
order = sf.Order__c.create({
|
53 |
+
'Total_Price__c': total_price,
|
54 |
+
'Cart_Items__c': json.dumps(cart_items), # Storing cart items as JSON
|
55 |
+
'Customer__c': customer_id # Linking to the customer record
|
56 |
+
})
|
57 |
+
return order
|
58 |
+
except Exception as e:
|
59 |
+
raise Exception(f"Failed to create order: {str(e)}")
|
60 |
+
|
61 |
# Voice-related functions
|
62 |
def generate_audio_prompt(text, filename):
|
63 |
try:
|
|
|
86 |
return len(nonsilent_parts) == 0 # If no speech detected
|
87 |
|
88 |
# Routes and Views
|
89 |
+
@app.route("/")
|
90 |
+
def index():
|
91 |
+
return render_template("index.html")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
92 |
|
93 |
+
@app.route("/dashboard", methods=["GET"])
|
94 |
+
def dashboard():
|
95 |
+
return render_template("dashboard.html") # Render the dashboard template
|
|
|
|
|
96 |
|
97 |
@app.route('/submit', methods=['POST'])
|
98 |
def submit():
|
99 |
try:
|
|
|
100 |
data = request.get_json()
|
101 |
print("Received Data:", data) # Debugging line
|
102 |
|
103 |
if not data:
|
104 |
return jsonify({"success": False, "message": "Invalid or empty JSON received"}), 400
|
105 |
|
|
|
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({"success": False, "message": "Missing required fields"}), 400
|
112 |
|
|
|
113 |
salesforce_data = {
|
114 |
"Name": name,
|
115 |
"Email__c": email, # Ensure this is the correct field API name in Salesforce
|
116 |
"Phone_Number__c": phone # Ensure this is the correct field API name in Salesforce
|
117 |
}
|
118 |
|
|
|
119 |
try:
|
120 |
result = sf.Customer_Login__c.create(salesforce_data) # Replace `Customer_Login__c` with your Salesforce object API name
|
121 |
print(f"Salesforce Response: {result}") # Debugging line
|
|
|
122 |
return jsonify({"success": True, "message": "Data submitted successfully"})
|
|
|
123 |
except Exception as e:
|
124 |
if "STORAGE_LIMIT_EXCEEDED" in str(e):
|
125 |
return jsonify({"success": False, "message": "Salesforce storage limit exceeded. Please clean up or contact support."}), 500
|
126 |
else:
|
127 |
print(f"Salesforce Insertion Error: {str(e)}") # Log Salesforce errors
|
128 |
return jsonify({"success": False, "message": "Salesforce submission failed", "error": str(e)}), 500
|
|
|
129 |
except Exception as e:
|
130 |
print(f"Server Error: {str(e)}") # Log general errors
|
131 |
return jsonify({"success": False, "message": "Internal server error", "error": str(e)}), 500
|
132 |
|
|
|
133 |
@app.route('/validate-login', methods=['POST'])
|
134 |
def validate_login():
|
135 |
try:
|
|
|
136 |
data = request.get_json()
|
137 |
login_email = data.get("email")
|
138 |
login_mobile = data.get("mobile")
|
139 |
|
|
|
140 |
if not login_email or not login_mobile:
|
141 |
return jsonify({"success": False, "message": "Missing email or mobile number"}), 400
|
142 |
|
|
|
143 |
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}'"
|
144 |
result = sf.query(query)
|
145 |
|
146 |
if result['records']:
|
147 |
+
user_name = result['records'][0]['Name']
|
|
|
148 |
return jsonify({"success": True, "message": "Login successful", "name": user_name})
|
149 |
else:
|
|
|
150 |
return jsonify({"success": False, "message": "Invalid email or mobile number"}), 401
|
|
|
151 |
except Exception as e:
|
152 |
print(f"Error validating login: {str(e)}")
|
153 |
return jsonify({"success": False, "message": "Internal server error", "error": str(e)}), 500
|
154 |
|
|
|
155 |
@app.route("/menu", methods=["GET"])
|
156 |
def menu_page():
|
157 |
menu_items = get_menu_items()
|
158 |
menu_data = [{"name": item['Name'], "price": item['Price__c'], "ingredients": item['Ingredients__c'], "category": item['Category__c']} for item in menu_items]
|
159 |
return render_template("menu_page.html", menu_items=menu_data)
|
160 |
|
161 |
+
@app.route("/add_to_cart", methods=["POST"])
|
162 |
+
def add_to_cart():
|
163 |
+
cart_items = session.get('cart_items', [])
|
164 |
+
item_name = request.json.get('item_name')
|
165 |
+
quantity = request.json.get('quantity')
|
166 |
+
|
167 |
+
cart_items.append({"name": item_name, "quantity": quantity})
|
168 |
+
session['cart_items'] = cart_items # Update session with new cart items
|
169 |
+
|
170 |
+
return jsonify({"success": True, "message": f"Added {item_name} to your cart."})
|
171 |
+
|
172 |
+
@app.route("/view_cart", methods=["GET"])
|
173 |
+
def view_cart():
|
174 |
+
cart_items = session.get('cart_items', [])
|
175 |
+
return render_template("cart_page.html", cart_items=cart_items)
|
176 |
+
|
177 |
+
@app.route("/place_order", methods=["POST"])
|
178 |
def place_order():
|
179 |
+
cart_items = session.get('cart_items', [])
|
180 |
+
total_price = sum([item['quantity'] * 100 for item in cart_items]) # Placeholder price calculation
|
181 |
customer_id = session.get('customer_id')
|
182 |
|
183 |
if not customer_id:
|
184 |
return jsonify({"message": "User not logged in"}), 400
|
185 |
|
186 |
try:
|
187 |
+
order_data = {"Total_Price__c": total_price, "Cart_Items__c": json.dumps(cart_items), "Customer__c": customer_id}
|
188 |
+
order = sf.Order__c.create(order_data)
|
189 |
+
session.pop('cart_items', None) # Clear the cart after placing the order
|
190 |
return jsonify({"message": "Order placed successfully!", "order": order})
|
191 |
|
192 |
except Exception as e:
|
193 |
return jsonify({"message": f"Failed to create order: {str(e)}"}), 500
|
194 |
|
195 |
+
# Run the app
|
196 |
if __name__ == "__main__":
|
197 |
app.run(debug=True)
|