Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,362 +1,207 @@
|
|
1 |
-
|
2 |
-
|
3 |
-
|
4 |
-
|
5 |
-
|
6 |
-
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
.
|
29 |
-
|
30 |
-
}
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
.
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
|
132 |
-
|
133 |
-
|
134 |
-
|
135 |
-
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
|
145 |
-
|
146 |
-
|
147 |
-
|
148 |
-
|
149 |
-
|
150 |
-
|
151 |
-
|
152 |
-
|
153 |
-
|
154 |
-
|
155 |
-
|
156 |
-
|
157 |
-
|
158 |
-
|
159 |
-
|
160 |
-
|
161 |
-
|
162 |
-
|
163 |
-
|
164 |
-
|
165 |
-
|
166 |
-
|
167 |
-
|
168 |
-
|
169 |
-
|
170 |
-
|
171 |
-
|
172 |
-
|
173 |
-
|
174 |
-
|
175 |
-
|
176 |
-
|
177 |
-
|
178 |
-
|
179 |
-
|
180 |
-
|
181 |
-
|
182 |
-
|
183 |
-
|
184 |
-
|
185 |
-
|
186 |
-
|
187 |
-
|
188 |
-
|
189 |
-
|
190 |
-
|
191 |
-
|
192 |
-
|
193 |
-
|
194 |
-
|
195 |
-
|
196 |
-
|
197 |
-
|
198 |
-
|
199 |
-
|
200 |
-
|
201 |
-
|
202 |
-
|
203 |
-
|
204 |
-
|
205 |
-
|
206 |
-
|
207 |
-
|
208 |
-
}
|
209 |
-
function confirmName() {
|
210 |
-
recognition.start();
|
211 |
-
recognition.onresult = function(event) {
|
212 |
-
let confirmation = event.results[0][0].transcript.trim().toLowerCase();
|
213 |
-
recognition.stop();
|
214 |
-
if (confirmation.includes("ok")) {
|
215 |
-
speak("Great! Now, tell me your email.", startListeningForEmail);
|
216 |
-
} else {
|
217 |
-
speak("Let's try again. Tell me your name.", startListeningForName);
|
218 |
-
}
|
219 |
-
};
|
220 |
-
}
|
221 |
-
// Capture email for registration
|
222 |
-
function startListeningForEmail() {
|
223 |
-
recognition.start();
|
224 |
-
recognition.onresult = function(event) {
|
225 |
-
emailCaptured = event.results[0][0].transcript.trim().replace(/\bat\b/g, '@').replace(/\s+/g, '');
|
226 |
-
document.getElementById('email').value = emailCaptured;
|
227 |
-
recognition.stop();
|
228 |
-
speak("You said " + emailCaptured + ". Is it correct?", confirmEmail);
|
229 |
-
};
|
230 |
-
}
|
231 |
-
function confirmEmail() {
|
232 |
-
recognition.start();
|
233 |
-
recognition.onresult = function(event) {
|
234 |
-
let confirmation = event.results[0][0].transcript.trim().toLowerCase();
|
235 |
-
recognition.stop();
|
236 |
-
if (confirmation.includes("ok")) {
|
237 |
-
speak("Great! Now, tell me your mobile number.", startListeningForMobile);
|
238 |
-
} else {
|
239 |
-
speak("Let's try again. Tell me your email.", startListeningForEmail);
|
240 |
-
}
|
241 |
-
};
|
242 |
-
}
|
243 |
-
// Capture mobile number for registration
|
244 |
-
function startListeningForMobile() {
|
245 |
-
recognition.start();
|
246 |
-
recognition.onresult = function(event) {
|
247 |
-
mobileCaptured = event.results[0][0].transcript.trim().replace(/\s+/g, '');
|
248 |
-
document.getElementById('mobile').value = mobileCaptured;
|
249 |
-
recognition.stop();
|
250 |
-
speak("You said " + mobileCaptured + ". Is it correct?", confirmMobile);
|
251 |
-
};
|
252 |
-
}
|
253 |
-
function confirmMobile() {
|
254 |
-
recognition.start();
|
255 |
-
recognition.onresult = function(event) {
|
256 |
-
let confirmation = event.results[0][0].transcript.trim().toLowerCase();
|
257 |
-
recognition.stop();
|
258 |
-
if (confirmation.includes("ok")) {
|
259 |
-
autoConfirm();
|
260 |
-
} else {
|
261 |
-
speak("Let's try again. Tell me your mobile number.", startListeningForMobile);
|
262 |
-
}
|
263 |
-
};
|
264 |
-
}
|
265 |
-
// Confirm details and submit automatically
|
266 |
-
function autoConfirm() {
|
267 |
-
document.getElementById('confirmName').textContent = document.getElementById('name').value;
|
268 |
-
document.getElementById('confirmEmail').textContent = document.getElementById('email').value;
|
269 |
-
document.getElementById('confirmPhone').textContent = document.getElementById('mobile').value;
|
270 |
-
document.getElementById('confirmation').style.display = 'block';
|
271 |
-
setTimeout(autoSubmit, 3000);
|
272 |
-
}
|
273 |
-
// Submit details to backend
|
274 |
-
function autoSubmit() {
|
275 |
-
var name = document.getElementById('name').value;
|
276 |
-
var email = document.getElementById('email').value;
|
277 |
-
var phone = document.getElementById('mobile').value;
|
278 |
-
fetch('/submit', {
|
279 |
-
method: 'POST',
|
280 |
-
headers: { 'Content-Type': 'application/json' },
|
281 |
-
body: JSON.stringify({ name: name, email: email, phone: phone })
|
282 |
-
})
|
283 |
-
.then(response => response.json())
|
284 |
-
.then(data => {
|
285 |
-
if (data.success) {
|
286 |
-
document.getElementById('status').textContent = 'Your details were submitted successfully!';
|
287 |
-
document.getElementById('confirmation').style.display = 'none';
|
288 |
-
speak("Your registration is complete. Thank you for registering.");
|
289 |
-
setTimeout(() => location.reload(), 5000);
|
290 |
-
} else {
|
291 |
-
document.getElementById('status').textContent = 'There was an error submitting your details.';
|
292 |
-
speak("There was an error submitting your details. Please try again.");
|
293 |
-
}
|
294 |
-
});
|
295 |
-
}
|
296 |
-
// Start login process
|
297 |
-
function startListeningForLoginEmail() {
|
298 |
-
recognition.start();
|
299 |
-
recognition.onresult = function(event) {
|
300 |
-
emailCaptured = event.results[0][0].transcript.trim().replace(/\bat\b/g, '@').replace(/\s+/g, '');
|
301 |
-
document.getElementById('loginEmail').value = emailCaptured;
|
302 |
-
recognition.stop();
|
303 |
-
speak("You said " + emailCaptured + ". Is it correct?", confirmLoginEmail);
|
304 |
-
};
|
305 |
-
}
|
306 |
-
function confirmLoginEmail() {
|
307 |
-
recognition.start();
|
308 |
-
recognition.onresult = function(event) {
|
309 |
-
let confirmation = event.results[0][0].transcript.trim().toLowerCase();
|
310 |
-
recognition.stop();
|
311 |
-
if (confirmation.includes("ok")) {
|
312 |
-
speak("Great! Now, tell me your mobile number.", startListeningForLoginMobile);
|
313 |
-
} else {
|
314 |
-
speak("Let's try again. Tell me your email.", startListeningForLoginEmail);
|
315 |
-
}
|
316 |
-
};
|
317 |
-
}
|
318 |
-
function startListeningForLoginMobile() {
|
319 |
-
recognition.start();
|
320 |
-
recognition.onresult = function(event) {
|
321 |
-
mobileCaptured = event.results[0][0].transcript.trim().replace(/\s+/g, '');
|
322 |
-
document.getElementById('loginMobile').value = mobileCaptured;
|
323 |
-
recognition.stop();
|
324 |
-
speak("You said " + mobileCaptured + ". Is it correct?", confirmLoginMobile);
|
325 |
-
};
|
326 |
-
}
|
327 |
-
function confirmLoginMobile() {
|
328 |
-
recognition.start();
|
329 |
-
recognition.onresult = function(event) {
|
330 |
-
let confirmation = event.results[0][0].transcript.trim().toLowerCase();
|
331 |
-
recognition.stop();
|
332 |
-
if (confirmation.includes("ok")) {
|
333 |
-
submitLogin();
|
334 |
-
} else {
|
335 |
-
speak("Let's try again. Tell me your mobile number.", startListeningForLoginMobile);
|
336 |
-
}
|
337 |
-
};
|
338 |
-
}
|
339 |
-
// Submit login details to backend
|
340 |
-
function submitLogin() {
|
341 |
-
let email = document.getElementById('loginEmail').value;
|
342 |
-
let mobile = document.getElementById('loginMobile').value;
|
343 |
-
fetch('/submit_login', {
|
344 |
-
method: 'POST',
|
345 |
-
headers: { 'Content-Type': 'application/json' },
|
346 |
-
body: JSON.stringify({ email: email, mobile: mobile })
|
347 |
-
})
|
348 |
-
.then(response => response.json())
|
349 |
-
.then(data => {
|
350 |
-
speak("Login successful. Welcome back!");
|
351 |
-
// Redirect or perform other actions
|
352 |
-
})
|
353 |
-
.catch(error => {
|
354 |
-
speak("There was an error with your login. Please try again.");
|
355 |
-
});
|
356 |
-
}
|
357 |
-
window.onload = function () {
|
358 |
-
askLoginOrRegister();
|
359 |
-
};
|
360 |
-
</script>
|
361 |
-
</body>
|
362 |
-
</html>
|
|
|
1 |
+
import torch
|
2 |
+
from flask import Flask, render_template, request, jsonify
|
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 # Import AutoConfig for the config object
|
10 |
+
import time
|
11 |
+
from waitress import serve
|
12 |
+
from simple_salesforce import Salesforce
|
13 |
+
import requests # Import requests for exception handling
|
14 |
+
|
15 |
+
app = Flask(__name__)
|
16 |
+
|
17 |
+
# Use whisper-small for faster processing and better speed
|
18 |
+
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}) # Set timeout to 60 seconds
|
23 |
+
|
24 |
+
# Your function where you generate and save the audio
|
25 |
+
def generate_audio_prompt(text, filename):
|
26 |
+
try:
|
27 |
+
tts = gTTS(text)
|
28 |
+
tts.save(os.path.join("static", filename))
|
29 |
+
except gtts.tts.gTTSError as e:
|
30 |
+
print(f"Error: {e}")
|
31 |
+
print("Retrying after 5 seconds...")
|
32 |
+
time.sleep(5) # Wait for 5 seconds before retrying
|
33 |
+
generate_audio_prompt(text, filename)
|
34 |
+
|
35 |
+
# Generate required voice prompts
|
36 |
+
prompts = {
|
37 |
+
"welcome": "Welcome to Biryani Hub.",
|
38 |
+
"ask_name": "Tell me your name.",
|
39 |
+
"ask_email": "Please provide your email address.",
|
40 |
+
"thank_you": "Thank you for registration."
|
41 |
+
}
|
42 |
+
|
43 |
+
for key, text in prompts.items():
|
44 |
+
generate_audio_prompt(text, f"{key}.mp3")
|
45 |
+
|
46 |
+
# Symbol mapping for proper recognition
|
47 |
+
SYMBOL_MAPPING = {
|
48 |
+
"at the rate": "@",
|
49 |
+
"at": "@",
|
50 |
+
"dot": ".",
|
51 |
+
"underscore": "_",
|
52 |
+
"hash": "#",
|
53 |
+
"plus": "+",
|
54 |
+
"dash": "-",
|
55 |
+
"comma": ",",
|
56 |
+
"space": " "
|
57 |
+
}
|
58 |
+
|
59 |
+
# Function to convert audio to WAV format
|
60 |
+
def convert_to_wav(input_path, output_path):
|
61 |
+
try:
|
62 |
+
audio = AudioSegment.from_file(input_path)
|
63 |
+
audio = audio.set_frame_rate(16000).set_channels(1) # Convert to 16kHz, mono
|
64 |
+
audio.export(output_path, format="wav")
|
65 |
+
except Exception as e:
|
66 |
+
print(f"Error: {str(e)}")
|
67 |
+
raise Exception(f"Audio conversion failed: {str(e)}")
|
68 |
+
|
69 |
+
# Function to check if audio contains actual speech
|
70 |
+
def is_silent_audio(audio_path):
|
71 |
+
audio = AudioSegment.from_wav(audio_path)
|
72 |
+
nonsilent_parts = detect_nonsilent(audio, min_silence_len=500, silence_thresh=audio.dBFS-16) # Reduced silence duration
|
73 |
+
print(f"Detected nonsilent parts: {nonsilent_parts}")
|
74 |
+
return len(nonsilent_parts) == 0 # If no speech detected
|
75 |
+
|
76 |
+
# Salesforce connection details
|
77 |
+
try:
|
78 |
+
print("Attempting to connect to Salesforce...")
|
79 |
+
sf = Salesforce(username='[email protected]', password='Sati@1020', security_token='sSSjyhInIsUohKpG8sHzty2q')
|
80 |
+
print("Connected to Salesforce successfully!")
|
81 |
+
print("User Info:", sf.UserInfo) # Log the user info to verify the connection
|
82 |
+
except Exception as e:
|
83 |
+
print(f"Failed to connect to Salesforce: {str(e)}")
|
84 |
+
|
85 |
+
# Function to create Salesforce record
|
86 |
+
# API endpoint to receive data from voice bot
|
87 |
+
@app.route('/login', methods=['POST'])
|
88 |
+
def login():
|
89 |
+
# Get data from voice bot (name, email, phone number)
|
90 |
+
data = request.json # Assuming voice bot sends JSON data
|
91 |
+
|
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 |
+
# Create a record in Salesforce
|
100 |
+
try:
|
101 |
+
customer_login = sf.Customer_Login__c.create({
|
102 |
+
'Name': name,
|
103 |
+
'Email__c': email,
|
104 |
+
'Phone_Number__c': phone_number
|
105 |
+
})
|
106 |
+
return jsonify({'success': True, 'id': customer_login['id']}), 200
|
107 |
+
except Exception as e:
|
108 |
+
return jsonify({'error': f'Failed to create record in Salesforce: {str(e)}'}), 500
|
109 |
+
|
110 |
+
@app.route("/submit", methods=["POST"])
|
111 |
+
def submit():
|
112 |
+
data = request.json
|
113 |
+
name = data.get('name')
|
114 |
+
email = data.get('email')
|
115 |
+
phone = data.get('phone')
|
116 |
+
|
117 |
+
if not name or not email or not phone:
|
118 |
+
return jsonify({'error': 'Missing data'}), 400
|
119 |
+
|
120 |
+
try:
|
121 |
+
# Create Salesforce record
|
122 |
+
customer_login = sf.Customer_Login__c.create({
|
123 |
+
'Name': name,
|
124 |
+
'Email__c': email,
|
125 |
+
'Phone_Number__c': phone
|
126 |
+
})
|
127 |
+
|
128 |
+
if customer_login.get('id'):
|
129 |
+
return jsonify({'success': True})
|
130 |
+
else:
|
131 |
+
return jsonify({'error': 'Failed to create record'}), 500
|
132 |
+
|
133 |
+
except Exception as e:
|
134 |
+
return jsonify({'error': str(e)}), 500
|
135 |
+
|
136 |
+
|
137 |
+
@app.route("/")
|
138 |
+
def index():
|
139 |
+
return render_template("index.html")
|
140 |
+
|
141 |
+
@app.route("/transcribe", methods=["POST"])
|
142 |
+
def transcribe():
|
143 |
+
if "audio" not in request.files:
|
144 |
+
print("No audio file provided")
|
145 |
+
return jsonify({"error": "No audio file provided"}), 400
|
146 |
+
|
147 |
+
audio_file = request.files["audio"]
|
148 |
+
input_audio_path = os.path.join("static", "temp_input.wav")
|
149 |
+
output_audio_path = os.path.join("static", "temp.wav")
|
150 |
+
audio_file.save(input_audio_path)
|
151 |
+
|
152 |
+
try:
|
153 |
+
# Convert to WAV
|
154 |
+
convert_to_wav(input_audio_path, output_audio_path)
|
155 |
+
|
156 |
+
# Check for silence
|
157 |
+
if is_silent_audio(output_audio_path):
|
158 |
+
return jsonify({"error": "No speech detected. Please try again."}), 400
|
159 |
+
else:
|
160 |
+
print("Audio contains speech, proceeding with transcription.")
|
161 |
+
|
162 |
+
# Use Whisper ASR model for transcription
|
163 |
+
result = None
|
164 |
+
retry_attempts = 3
|
165 |
+
for attempt in range(retry_attempts):
|
166 |
+
try:
|
167 |
+
result = pipeline("automatic-speech-recognition", model="openai/whisper-small", device=0 if torch.cuda.is_available() else -1, config=config)
|
168 |
+
print(f"Transcribed text: {result['text']}")
|
169 |
+
break
|
170 |
+
except requests.exceptions.ReadTimeout:
|
171 |
+
print(f"Timeout occurred, retrying attempt {attempt + 1}/{retry_attempts}...")
|
172 |
+
time.sleep(5)
|
173 |
+
|
174 |
+
if result is None:
|
175 |
+
return jsonify({"error": "Unable to transcribe audio after retries."}), 500
|
176 |
+
|
177 |
+
transcribed_text = result["text"].strip().capitalize()
|
178 |
+
print(f"Transcribed text: {transcribed_text}")
|
179 |
+
|
180 |
+
# Extract name, email, and phone number from the transcribed text
|
181 |
+
parts = transcribed_text.split()
|
182 |
+
name = parts[0] if len(parts) > 0 else "Unknown Name"
|
183 |
+
email = parts[1] if '@' in parts[1] else "[email protected]"
|
184 |
+
phone_number = parts[2] if len(parts) > 2 else "0000000000"
|
185 |
+
print(f"Parsed data - Name: {name}, Email: {email}, Phone Number: {phone_number}")
|
186 |
+
|
187 |
+
# Create record in Salesforce
|
188 |
+
salesforce_response = create_salesforce_record(name, email, phone_number)
|
189 |
+
|
190 |
+
# Log the Salesforce response
|
191 |
+
print(f"Salesforce record creation response: {salesforce_response}")
|
192 |
+
|
193 |
+
# Check if the response contains an error
|
194 |
+
if "error" in salesforce_response:
|
195 |
+
print(f"Error creating record in Salesforce: {salesforce_response['error']}")
|
196 |
+
return jsonify(salesforce_response), 500
|
197 |
+
|
198 |
+
# If creation was successful, return the details
|
199 |
+
return jsonify({"text": transcribed_text, "salesforce_record": salesforce_response})
|
200 |
+
|
201 |
+
except Exception as e:
|
202 |
+
print(f"Error in transcribing or processing: {str(e)}")
|
203 |
+
return jsonify({"error": f"Speech recognition error: {str(e)}"}), 500
|
204 |
+
|
205 |
+
# Start Production Server
|
206 |
+
if __name__ == "__main__":
|
207 |
+
serve(app, host="0.0.0.0", port=7860)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|