Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -6,11 +6,11 @@ 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 |
|
@@ -19,14 +19,14 @@ 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='diggavalli98@gmail.com', 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 |
|
@@ -45,37 +45,19 @@ 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 |
-
result = sf.query(query)
|
51 |
-
return result['records']
|
52 |
-
|
53 |
-
# Voice-related functions
|
54 |
-
def generate_audio_prompt(text, filename):
|
55 |
-
try:
|
56 |
-
tts = gTTS(text)
|
57 |
-
tts.save(os.path.join("static", filename))
|
58 |
-
except gtts.tts.gTTSError as e:
|
59 |
-
print(f"Error: {e}")
|
60 |
-
print("Retrying after 5 seconds...")
|
61 |
-
time.sleep(5) # Wait for 5 seconds before retrying
|
62 |
-
generate_audio_prompt(text, filename)
|
63 |
-
|
64 |
-
# Utility functions
|
65 |
-
def convert_to_wav(input_path, output_path):
|
66 |
try:
|
67 |
-
|
68 |
-
|
69 |
-
|
|
|
|
|
|
|
|
|
|
|
70 |
except Exception as e:
|
71 |
-
|
72 |
-
raise Exception(f"Audio conversion failed: {str(e)}")
|
73 |
-
|
74 |
-
def is_silent_audio(audio_path):
|
75 |
-
audio = AudioSegment.from_wav(audio_path)
|
76 |
-
nonsilent_parts = detect_nonsilent(audio, min_silence_len=500, silence_thresh=audio.dBFS-16) # Reduced silence duration
|
77 |
-
print(f"Detected nonsilent parts: {nonsilent_parts}")
|
78 |
-
return len(nonsilent_parts) == 0 # If no speech detected
|
79 |
|
80 |
# Routes and Views
|
81 |
@app.route("/")
|
@@ -84,14 +66,12 @@ def index():
|
|
84 |
|
85 |
@app.route("/dashboard", methods=["GET"])
|
86 |
def dashboard():
|
87 |
-
return render_template("dashboard.html")
|
88 |
|
89 |
@app.route('/submit', methods=['POST'])
|
90 |
def submit():
|
91 |
try:
|
92 |
-
# Ensure JSON is being received
|
93 |
data = request.get_json()
|
94 |
-
print("Received Data:", data) # Debugging line
|
95 |
|
96 |
if not data:
|
97 |
return jsonify({"success": False, "message": "Invalid or empty JSON received"}), 400
|
@@ -101,162 +81,56 @@ def submit():
|
|
101 |
email = data.get("email")
|
102 |
phone = data.get("phone")
|
103 |
|
104 |
-
# Validate if all fields are present
|
105 |
if not name or not email or not phone:
|
106 |
return jsonify({"success": False, "message": "Missing required fields"}), 400
|
107 |
|
108 |
# Prepare data for Salesforce submission
|
109 |
salesforce_data = {
|
110 |
"Name": name,
|
111 |
-
"Email__c": email,
|
112 |
-
"Phone_Number__c": phone
|
113 |
}
|
114 |
|
115 |
-
# Insert data into Salesforce using simple_salesforce
|
116 |
try:
|
117 |
-
result = sf.Customer_Login__c.create(salesforce_data)
|
118 |
-
print(f"Salesforce Response: {result}")
|
119 |
-
|
120 |
return jsonify({"success": True, "message": "Data submitted successfully"})
|
121 |
-
|
122 |
-
except Exception as e:
|
123 |
-
if "STORAGE_LIMIT_EXCEEDED" in str(e):
|
124 |
-
return jsonify({"success": False, "message": "Salesforce storage limit exceeded. Please clean up or contact support."}), 500
|
125 |
-
else:
|
126 |
-
print(f"Salesforce Insertion Error: {str(e)}") # Log Salesforce errors
|
127 |
-
return jsonify({"success": False, "message": "Salesforce submission failed", "error": str(e)}), 500
|
128 |
-
|
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 |
-
|
134 |
-
@app.route('/validate-login', methods=['POST'])
|
135 |
-
def validate_login():
|
136 |
-
try:
|
137 |
-
# Ensure JSON is being received
|
138 |
-
data = request.get_json()
|
139 |
-
login_email = data.get("email")
|
140 |
-
login_mobile = data.get("mobile")
|
141 |
-
|
142 |
-
# Validate if email and mobile are present
|
143 |
-
if not login_email or not login_mobile:
|
144 |
-
return jsonify({"success": False, "message": "Missing email or mobile number"}), 400
|
145 |
-
|
146 |
-
# Query Salesforce to check if the record exists
|
147 |
-
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}'"
|
148 |
-
result = sf.query(query)
|
149 |
|
150 |
-
|
151 |
-
|
152 |
-
user_name = result['records'][0]['Name'] # Assuming the 'Name' field is present in the Salesforce object
|
153 |
-
return jsonify({"success": True, "message": "Login successful", "name": user_name})
|
154 |
-
else:
|
155 |
-
# If no matching record is found
|
156 |
-
return jsonify({"success": False, "message": "Invalid email or mobile number"}), 401
|
157 |
|
158 |
except Exception as e:
|
159 |
-
print(f"Error validating login: {str(e)}")
|
160 |
return jsonify({"success": False, "message": "Internal server error", "error": str(e)}), 500
|
161 |
|
162 |
-
|
163 |
-
@app.route("/menu", methods=["GET"])
|
164 |
-
def menu_page():
|
165 |
-
menu_items = get_menu_items()
|
166 |
-
menu_data = [{"name": item['Name'], "price": item['Price__c'], "ingredients": item['Ingredients__c'], "category": item['Category__c']} for item in menu_items]
|
167 |
-
return render_template("menu_page.html", menu_items=menu_data)
|
168 |
-
|
169 |
-
# Route for handling order
|
170 |
@app.route("/order", methods=["POST"])
|
171 |
def place_order():
|
172 |
-
item_name = request.json.get('item_name')
|
173 |
-
quantity = request.json.get('quantity')
|
174 |
-
order_data = {"Item__c": item_name, "Quantity__c": quantity}
|
175 |
-
sf.Order__c.create(order_data)
|
176 |
-
return jsonify({"success": True, "message": f"Order for {item_name} placed successfully."})
|
177 |
-
|
178 |
-
# Route to handle the cart
|
179 |
-
@app.route("/cart", methods=["GET"])
|
180 |
-
def cart():
|
181 |
-
cart_items = [] # Placeholder for cart items
|
182 |
-
return render_template("cart_page.html", cart_items=cart_items)
|
183 |
-
|
184 |
-
# Route for the order summary page
|
185 |
-
@app.route("/order-summary", methods=["GET"])
|
186 |
-
def order_summary():
|
187 |
-
order_details = [] # Placeholder for order details
|
188 |
-
return render_template("order_summary.html", order_details=order_details)
|
189 |
-
|
190 |
-
@app.route("/transcribe", methods=["POST"])
|
191 |
-
def transcribe():
|
192 |
-
if "audio" not in request.files:
|
193 |
-
print("No audio file provided")
|
194 |
-
return jsonify({"error": "No audio file provided"}), 400
|
195 |
-
|
196 |
-
audio_file = request.files["audio"]
|
197 |
-
input_audio_path = os.path.join("static", "temp_input.wav")
|
198 |
-
output_audio_path = os.path.join("static", "temp.wav")
|
199 |
-
audio_file.save(input_audio_path)
|
200 |
-
|
201 |
try:
|
202 |
-
|
203 |
-
convert_to_wav(input_audio_path, output_audio_path)
|
204 |
-
|
205 |
-
# Check for silence
|
206 |
-
if is_silent_audio(output_audio_path):
|
207 |
-
return jsonify({"error": "No speech detected. Please try again."}), 400
|
208 |
-
else:
|
209 |
-
print("Audio contains speech, proceeding with transcription.")
|
210 |
-
|
211 |
-
# Use Whisper ASR model for transcription
|
212 |
-
result = None
|
213 |
-
retry_attempts = 3
|
214 |
-
for attempt in range(retry_attempts):
|
215 |
-
try:
|
216 |
-
result = pipeline("automatic-speech-recognition", model="openai/whisper-small", device=0 if torch.cuda.is_available() else -1, config=config)
|
217 |
-
print(f"Transcribed text: {result['text']}")
|
218 |
-
break
|
219 |
-
except requests.exceptions.ReadTimeout:
|
220 |
-
print(f"Timeout occurred, retrying attempt {attempt + 1}/{retry_attempts}...")
|
221 |
-
time.sleep(5)
|
222 |
-
|
223 |
-
if result is None:
|
224 |
-
return jsonify({"error": "Unable to transcribe audio after retries."}), 500
|
225 |
-
|
226 |
-
transcribed_text = result["text"].strip().capitalize()
|
227 |
-
print(f"Transcribed text: {transcribed_text}")
|
228 |
|
229 |
-
|
230 |
-
|
231 |
-
|
232 |
-
email = parts[1] if '@' in parts[1] else "unknown@domain.com"
|
233 |
-
phone_number = parts[2] if len(parts) > 2 else "0000000000"
|
234 |
-
print(f"Parsed data - Name: {name}, Email: {email}, Phone Number: {phone_number}")
|
235 |
|
236 |
-
#
|
237 |
-
|
238 |
-
|
239 |
|
240 |
-
#
|
241 |
-
|
|
|
242 |
|
243 |
-
if
|
244 |
-
|
245 |
-
salesforce_response = create_salesforce_record(name, email, phone_number)
|
246 |
|
247 |
-
|
248 |
-
print(f"Salesforce record creation response: {salesforce_response}")
|
249 |
|
250 |
-
|
251 |
-
|
252 |
-
print(f"Error creating record in Salesforce: {salesforce_response['error']}")
|
253 |
-
return jsonify(salesforce_response), 500
|
254 |
|
255 |
-
|
256 |
|
257 |
except Exception as e:
|
258 |
-
|
259 |
-
return jsonify({"error": f"Speech recognition error: {str(e)}"}), 500
|
260 |
|
261 |
# Start Production Server
|
262 |
if __name__ == "__main__":
|
|
|
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 |
|
|
|
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='diggavalli98@gmail.com', 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 |
|
|
|
45 |
except Exception as e:
|
46 |
raise Exception(f"Failed to create record: {str(e)}")
|
47 |
|
48 |
+
# Function for order handling
|
49 |
+
def create_order_in_salesforce(item_name, quantity, customer_id):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
50 |
try:
|
51 |
+
# Create a new order in Salesforce's Order__c object
|
52 |
+
order_data = {
|
53 |
+
"Item__c": item_name, # Item__c is the field that stores the order item
|
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 |
+
raise Exception(f"Failed to create order: {str(e)}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
61 |
|
62 |
# Routes and Views
|
63 |
@app.route("/")
|
|
|
66 |
|
67 |
@app.route("/dashboard", methods=["GET"])
|
68 |
def dashboard():
|
69 |
+
return render_template("dashboard.html")
|
70 |
|
71 |
@app.route('/submit', methods=['POST'])
|
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
|
|
|
81 |
email = data.get("email")
|
82 |
phone = data.get("phone")
|
83 |
|
|
|
84 |
if not name or not email or not phone:
|
85 |
return jsonify({"success": False, "message": "Missing required fields"}), 400
|
86 |
|
87 |
# Prepare data for Salesforce submission
|
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 |
+
data = request.get_json()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
109 |
|
110 |
+
item_name = data.get('item_name')
|
111 |
+
quantity = data.get('quantity')
|
112 |
+
customer_email = data.get('customer_email') # Assuming the customer email is passed for lookup
|
|
|
|
|
|
|
113 |
|
114 |
+
# Validate input
|
115 |
+
if not item_name or not quantity or not customer_email:
|
116 |
+
return jsonify({"success": False, "message": "Missing required fields"}), 400
|
117 |
|
118 |
+
# Query Salesforce to get customer ID by email
|
119 |
+
query = f"SELECT Id FROM Customer_Login__c WHERE Email__c = '{customer_email}'"
|
120 |
+
result = sf.query(query)
|
121 |
|
122 |
+
if not result['records']:
|
123 |
+
return jsonify({"success": False, "message": "Customer not found"}), 404
|
|
|
124 |
|
125 |
+
customer_id = result['records'][0]['Id']
|
|
|
126 |
|
127 |
+
# Create the order in Salesforce
|
128 |
+
order = create_order_in_salesforce(item_name, quantity, customer_id)
|
|
|
|
|
129 |
|
130 |
+
return jsonify({"success": True, "message": f"Order for {item_name} placed successfully", "order_id": order['Id']})
|
131 |
|
132 |
except Exception as e:
|
133 |
+
return jsonify({"success": False, "message": f"Error placing order: {str(e)}"}), 500
|
|
|
134 |
|
135 |
# Start Production Server
|
136 |
if __name__ == "__main__":
|