lokesh341 commited on
Commit
027fc0b
·
verified ·
1 Parent(s): 97eee54

Update templates/index.html

Browse files
Files changed (1) hide show
  1. templates/index.html +209 -317
templates/index.html CHANGED
@@ -1,318 +1,210 @@
1
 
2
- <!DOCTYPE html>
3
- <html lang="en">
4
- <head>
5
- <meta charset="UTF-8">
6
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
7
- <title>Biryani Hub Login & Registration</title>
8
- <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;500&display=swap" rel="stylesheet">
9
- <link rel="stylesheet" href="{{ url_for('static', filename='styles.css') }}">
10
- <style>
11
- body {
12
- font-family: 'Roboto', sans-serif;
13
- background: linear-gradient(135deg, #f4c542, #ff8f6a);
14
- margin: 0;
15
- display: flex;
16
- justify-content: center;
17
- align-items: center;
18
- height: 100vh;
19
- text-align: center;
20
- }
21
- .container {
22
- background-color: #fff; /* White background for contrast */
23
- padding: 40px 50px;
24
- border-radius: 10px;
25
- width: 450px;
26
- box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
27
- margin-right: 20px;
28
- }
29
- h1 {
30
- font-size: 30px;
31
- font-weight: bold;
32
- color: #ff6a00;
33
- }
34
- label {
35
- font-size: 16px;
36
- margin-top: 20px;
37
- display: block;
38
- text-align: left;
39
- font-weight: bold;
40
- color: #333;
41
- }
42
- input[type="text"] {
43
- width: 100%;
44
- padding: 12px;
45
- font-size: 16px;
46
- border: 2px solid #ccc;
47
- border-radius: 8px;
48
- margin-top: 8px;
49
- box-sizing: border-box;
50
- background-color: #f9f9f9;
51
- }
52
- input[type="text"]:focus {
53
- border-color: #ff6a00;
54
- outline: none;
55
- }
56
- .info {
57
- margin-top: 20px;
58
- font-size: 16px;
59
- color: #ff6a00;
60
- font-weight: bold;
61
- }
62
- .status {
63
- font-size: 14px;
64
- color: gray;
65
- margin-top: 20px;
66
- }
67
- .form-container {
68
- display: flex;
69
- justify-content: space-between;
70
- gap: 30px;
71
- }
72
- .form-container > div {
73
- width: 48%;
74
- }
75
- .form-section {
76
- padding: 20px;
77
- background-color: #f9f9f9;
78
- border-radius: 10px;
79
- }
80
- .header {
81
- font-size: 24px;
82
- font-weight: bold;
83
- color: #ff6a00;
84
- }
85
- </style>
86
- </head>
87
- <body>
88
- <div class="container">
89
- <h1>Welcome to Biryani Hub 🍽 🍗</h1>
90
-
91
- <!-- Form Section -->
92
- <div class="form-container">
93
- <!-- Registration Form -->
94
- <div class="form-section" id="registrationForm" style="display: block;">
95
- <h2 class="header">Register</h2>
96
- <label for="name">Your Name</label>
97
- <input type="text" id="name" placeholder="Your name will appear here..." readonly>
98
-
99
- <label for="email">Your Email</label>
100
- <input type="text" id="email" placeholder="Your email will appear here..." readonly>
101
-
102
- <label for="mobile">Your Mobile Number</label>
103
- <input type="text" id="mobile" placeholder="Your mobile number will appear here..." readonly>
104
-
105
- <p class="info" id="infoMessage">Listening 🗣🎙️...</p>
106
- <p class="status" id="status">🔊...</p>
107
- </div>
108
-
109
- <!-- Login Form -->
110
- <div class="form-section" id="loginForm" style="display: none;">
111
- <h2 class="header">Login</h2>
112
- <label for="loginEmail">Your Email</label>
113
- <input type="text" id="loginEmail" placeholder="Your email will appear here..." readonly>
114
-
115
- <label for="loginMobile">Your Mobile Number</label>
116
- <input type="text" id="loginMobile" placeholder="Your mobile number will appear here..." readonly>
117
-
118
- <p class="info" id="infoMessageLogin">Listening 🗣🎙️...</p>
119
- <p class="status" id="statusLogin">🔊...</p>
120
- </div>
121
- </div>
122
- </div>
123
-
124
- <script>
125
- let recognition;
126
- let nameCaptured = "";
127
- let emailCaptured = "";
128
- let mobileCaptured = "";
129
-
130
- if ('webkitSpeechRecognition' in window) {
131
- recognition = new webkitSpeechRecognition();
132
- recognition.continuous = false;
133
- recognition.interimResults = false;
134
- recognition.lang = 'en-US';
135
- } else {
136
- alert("Speech Recognition API is not supported in this browser.");
137
- }
138
-
139
- function speak(text, callback) {
140
- const speech = new SpeechSynthesisUtterance(text);
141
- speech.onend = callback;
142
- window.speechSynthesis.speak(speech);
143
- }
144
-
145
- // Start by asking if the user is a new or existing customer
146
- function askLoginOrRegister() {
147
- speak("Are you a new customer or an existing customer? Say 'new' for registration or 'existing' for login.", function() {
148
- recognition.start();
149
- recognition.onresult = function(event) {
150
- let response = event.results[0][0].transcript.trim().toLowerCase();
151
- recognition.stop();
152
- if (response.includes("new")) {
153
- showRegistrationForm();
154
- } else if (response.includes("existing")) {
155
- showLoginForm();
156
- } else {
157
- speak("Sorry, I didn't understand. Please say 'new' for registration or 'existing' for login.", askLoginOrRegister);
158
- }
159
- };
160
- });
161
- }
162
-
163
- function showRegistrationForm() {
164
- document.getElementById('registrationForm').style.display = 'block';
165
- document.getElementById('loginForm').style.display = 'none';
166
- speak("Please tell me your name to begin the registration.", startListeningForName);
167
- }
168
-
169
- function showLoginForm() {
170
- document.getElementById('loginForm').style.display = 'block';
171
- document.getElementById('registrationForm').style.display = 'none';
172
- speak("Please tell me your email to begin the login process.", startListeningForLoginEmail);
173
- }
174
-
175
- // Capture the name for registration
176
- function startListeningForName() {
177
- recognition.start();
178
- recognition.onresult = function(event) {
179
- nameCaptured = event.results[0][0].transcript.trim();
180
- document.getElementById('name').value = nameCaptured;
181
- recognition.stop();
182
- speak("You said " + nameCaptured + ". Is it correct?", confirmName);
183
- };
184
- }
185
-
186
- function confirmName() {
187
- recognition.start();
188
- recognition.onresult = function(event) {
189
- let confirmation = event.results[0][0].transcript.trim().toLowerCase();
190
- recognition.stop();
191
- if (confirmation.includes("ok")) {
192
- speak("Great! Now, tell me your email.", startListeningForEmail);
193
- } else {
194
- speak("Let's try again. Tell me your name.", startListeningForName);
195
- }
196
- };
197
- }
198
-
199
- // Capture email for registration
200
- function startListeningForEmail() {
201
- recognition.start();
202
- recognition.onresult = function(event) {
203
- emailCaptured = event.results[0][0].transcript.trim().replace(/\bat\b/g, '@').replace(/\s+/g, '');
204
- document.getElementById('email').value = emailCaptured;
205
- recognition.stop();
206
- speak("You said " + emailCaptured + ". Is it correct?", confirmEmail);
207
- };
208
- }
209
-
210
- function confirmEmail() {
211
- recognition.start();
212
- recognition.onresult = function(event) {
213
- let confirmation = event.results[0][0].transcript.trim().toLowerCase();
214
- recognition.stop();
215
- if (confirmation.includes("ok")) {
216
- speak("Great! Now, tell me your mobile number.", startListeningForMobile);
217
- } else {
218
- speak("Let's try again. Tell me your email.", startListeningForEmail);
219
- }
220
- };
221
- }
222
-
223
- // Capture mobile number for registration
224
- function startListeningForMobile() {
225
- recognition.start();
226
- recognition.onresult = function(event) {
227
- mobileCaptured = event.results[0][0].transcript.trim().replace(/\s+/g, '');
228
- document.getElementById('mobile').value = mobileCaptured;
229
- recognition.stop();
230
- speak("You said " + mobileCaptured + ". Is it correct?", confirmMobile);
231
- };
232
- }
233
-
234
- function confirmMobile() {
235
- recognition.start();
236
- recognition.onresult = function(event) {
237
- let confirmation = event.results[0][0].transcript.trim().toLowerCase();
238
- recognition.stop();
239
- if (confirmation.includes("ok")) {
240
- submitRegistration();
241
- } else {
242
- speak("Let's try again. Tell me your mobile number.", startListeningForMobile);
243
- }
244
- };
245
- }
246
-
247
- // Start login process (similar to registration process but only email and phone)
248
- function startListeningForLoginEmail() {
249
- recognition.start();
250
- recognition.onresult = function(event) {
251
- emailCaptured = event.results[0][0].transcript.trim().replace(/\bat\b/g, '@').replace(/\s+/g, '');
252
- document.getElementById('loginEmail').value = emailCaptured;
253
- recognition.stop();
254
- speak("You said " + emailCaptured + ". Is it correct?", confirmLoginEmail);
255
- };
256
- }
257
-
258
- function confirmLoginEmail() {
259
- recognition.start();
260
- recognition.onresult = function(event) {
261
- let confirmation = event.results[0][0].transcript.trim().toLowerCase();
262
- recognition.stop();
263
- if (confirmation.includes("ok")) {
264
- speak("Great! Now, tell me your mobile number.", startListeningForLoginMobile);
265
- } else {
266
- speak("Let's try again. Tell me your email.", startListeningForLoginEmail);
267
- }
268
- };
269
- }
270
-
271
- function startListeningForLoginMobile() {
272
- recognition.start();
273
- recognition.onresult = function(event) {
274
- mobileCaptured = event.results[0][0].transcript.trim().replace(/\s+/g, '');
275
- document.getElementById('loginMobile').value = mobileCaptured;
276
- recognition.stop();
277
- speak("You said " + mobileCaptured + ". Is it correct?", confirmLoginMobile);
278
- };
279
- }
280
-
281
- function confirmLoginMobile() {
282
- recognition.start();
283
- recognition.onresult = function(event) {
284
- let confirmation = event.results[0][0].transcript.trim().toLowerCase();
285
- recognition.stop();
286
- if (confirmation.includes("ok")) {
287
- submitLogin();
288
- } else {
289
- speak("Let's try again. Tell me your mobile number.", startListeningForLoginMobile);
290
- }
291
- };
292
- }
293
-
294
- // Submit login details to backend
295
- function submitLogin() {
296
- let email = document.getElementById('loginEmail').value;
297
- let mobile = document.getElementById('loginMobile').value;
298
- fetch('/submit_login', {
299
- method: 'POST',
300
- headers: { 'Content-Type': 'application/json' },
301
- body: JSON.stringify({ email: email, mobile: mobile })
302
- })
303
- .then(response => response.json())
304
- .then(data => {
305
- speak("Login successful. Welcome back!");
306
- // Redirect or perform other actions
307
- })
308
- .catch(error => {
309
- speak("There was an error with your login. Please try again.");
310
- });
311
- }
312
-
313
- window.onload = function () {
314
- askLoginOrRegister();
315
- };
316
- </script>
317
- </body>
318
- </html>
 
1
 
2
+ import torch
3
+ from flask import Flask, render_template, request, jsonify
4
+ import json
5
+ import os
6
+ from transformers import pipeline
7
+ from gtts import gTTS
8
+ from pydub import AudioSegment
9
+ from pydub.silence import detect_nonsilent
10
+ from transformers import AutoConfig # Import AutoConfig for the config object
11
+ import time
12
+ from waitress import serve
13
+ from simple_salesforce import Salesforce
14
+ import requests # Import requests for exception handling
15
+
16
+ app = Flask(__name__)
17
+
18
+ # Use whisper-small for faster processing and better speed
19
+ device = "cuda" if torch.cuda.is_available() else "cpu"
20
+
21
+ # Create config object to set timeout and other parameters
22
+ config = AutoConfig.from_pretrained("openai/whisper-small")
23
+ config.update({"timeout": 60}) # Set timeout to 60 seconds
24
+
25
+ # Your function where you generate and save the audio
26
+ def generate_audio_prompt(text, filename):
27
+ try:
28
+ tts = gTTS(text)
29
+ tts.save(os.path.join("static", filename))
30
+ except gtts.tts.gTTSError as e:
31
+ print(f"Error: {e}")
32
+ print("Retrying after 5 seconds...")
33
+ time.sleep(5) # Wait for 5 seconds before retrying
34
+ generate_audio_prompt(text, filename)
35
+
36
+ # Generate required voice prompts
37
+ prompts = {
38
+ "welcome": "Welcome to Biryani Hub.",
39
+ "ask_name": "Tell me your name.",
40
+ "ask_email": "Please provide your email address.",
41
+ "thank_you": "Thank you for registration."
42
+ }
43
+
44
+ for key, text in prompts.items():
45
+ generate_audio_prompt(text, f"{key}.mp3")
46
+
47
+ # Symbol mapping for proper recognition
48
+ SYMBOL_MAPPING = {
49
+ "at the rate": "@",
50
+ "at": "@",
51
+ "dot": ".",
52
+ "underscore": "_",
53
+ "hash": "#",
54
+ "plus": "+",
55
+ "dash": "-",
56
+ "comma": ",",
57
+ "space": " "
58
+ }
59
+
60
+ # Function to convert audio to WAV format
61
+ def convert_to_wav(input_path, output_path):
62
+ try:
63
+ audio = AudioSegment.from_file(input_path)
64
+ audio = audio.set_frame_rate(16000).set_channels(1) # Convert to 16kHz, mono
65
+ audio.export(output_path, format="wav")
66
+ except Exception as e:
67
+ print(f"Error: {str(e)}")
68
+ raise Exception(f"Audio conversion failed: {str(e)}")
69
+
70
+ # Function to check if audio contains actual speech
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) # Reduced silence duration
74
+ print(f"Detected nonsilent parts: {nonsilent_parts}")
75
+ return len(nonsilent_parts) == 0 # If no speech detected
76
+
77
+ # Salesforce connection details
78
+ try:
79
+ print("Attempting to connect to Salesforce...")
80
+ sf = Salesforce(username='diggavalli98@gmail.com', password='Sati@1020', security_token='sSSjyhInIsUohKpG8sHzty2q')
81
+ print("Connected to Salesforce successfully!")
82
+ print("User Info:", sf.UserInfo) # Log the user info to verify the connection
83
+ except Exception as e:
84
+ print(f"Failed to connect to Salesforce: {str(e)}")
85
+
86
+ # Function to create Salesforce record
87
+ # API endpoint to receive data from voice bot
88
+ @app.route('/login', methods=['POST'])
89
+ def login():
90
+ # Get data from voice bot (name, email, phone number)
91
+ data = request.json # Assuming voice bot sends JSON data
92
+
93
+ name = data.get('name')
94
+ email = data.get('email')
95
+ phone_number = data.get('phone_number')
96
+
97
+ if not name or not email or not phone_number:
98
+ return jsonify({'error': 'Missing required fields'}), 400
99
+
100
+ # Create a record in Salesforce
101
+ try:
102
+ customer_login = sf.Customer_Login__c.create({
103
+ 'Name': name,
104
+ 'Email__c': email,
105
+ 'Phone_Number__c': phone_number
106
+ })
107
+ return jsonify({'success': True, 'id': customer_login['id']}), 200
108
+ except Exception as e:
109
+ print(f"Error creating Salesforce record: {str(e)}")
110
+ return jsonify({'error': f'Failed to create record in Salesforce: {str(e)}'}), 500
111
+
112
+ @app.route("/submit", methods=["POST"])
113
+ def submit():
114
+ data = request.json
115
+ name = data.get('name')
116
+ email = data.get('email')
117
+ phone = data.get('phone')
118
+
119
+ if not name or not email or not phone:
120
+ return jsonify({'error': 'Missing data'}), 400
121
+
122
+ try:
123
+ # Create Salesforce record
124
+ customer_login = sf.Customer_Login__c.create({
125
+ 'Name': name,
126
+ 'Email__c': email,
127
+ 'Phone_Number__c': phone
128
+ })
129
+
130
+ if customer_login.get('id'):
131
+ return jsonify({'success': True, 'id': customer_login['id']})
132
+ else:
133
+ return jsonify({'error': 'Failed to create record'}), 500
134
+
135
+ except Exception as e:
136
+ print(f"Error during Salesforce record creation: {str(e)}")
137
+ return jsonify({'error': str(e)}), 500
138
+
139
+
140
+ @app.route("/")
141
+ def index():
142
+ return render_template("index.html")
143
+
144
+ @app.route("/transcribe", methods=["POST"])
145
+ def transcribe():
146
+ if "audio" not in request.files:
147
+ print("No audio file provided")
148
+ return jsonify({"error": "No audio file provided"}), 400
149
+
150
+ audio_file = request.files["audio"]
151
+ input_audio_path = os.path.join("static", "temp_input.wav")
152
+ output_audio_path = os.path.join("static", "temp.wav")
153
+ audio_file.save(input_audio_path)
154
+
155
+ try:
156
+ # Convert to WAV
157
+ convert_to_wav(input_audio_path, output_audio_path)
158
+
159
+ # Check for silence
160
+ if is_silent_audio(output_audio_path):
161
+ return jsonify({"error": "No speech detected. Please try again."}), 400
162
+ else:
163
+ print("Audio contains speech, proceeding with transcription.")
164
+
165
+ # Use Whisper ASR model for transcription
166
+ result = None
167
+ retry_attempts = 3
168
+ for attempt in range(retry_attempts):
169
+ try:
170
+ result = pipeline("automatic-speech-recognition", model="openai/whisper-small", device=0 if torch.cuda.is_available() else -1, config=config)
171
+ print(f"Transcribed text: {result['text']}")
172
+ break
173
+ except requests.exceptions.ReadTimeout:
174
+ print(f"Timeout occurred, retrying attempt {attempt + 1}/{retry_attempts}...")
175
+ time.sleep(5)
176
+
177
+ if result is None:
178
+ return jsonify({"error": "Unable to transcribe audio after retries."}), 500
179
+
180
+ transcribed_text = result["text"].strip().capitalize()
181
+ print(f"Transcribed text: {transcribed_text}")
182
+
183
+ # Extract name, email, and phone number from the transcribed text
184
+ parts = transcribed_text.split()
185
+ name = parts[0] if len(parts) > 0 else "Unknown Name"
186
+ email = parts[1] if '@' in parts[1] else "[email protected]"
187
+ phone_number = parts[2] if len(parts) > 2 else "0000000000"
188
+ print(f"Parsed data - Name: {name}, Email: {email}, Phone Number: {phone_number}")
189
+
190
+ # Create record in Salesforce
191
+ salesforce_response = create_salesforce_record(name, email, phone_number)
192
+
193
+ # Log the Salesforce response
194
+ print(f"Salesforce record creation response: {salesforce_response}")
195
+
196
+ # Check if the response contains an error
197
+ if "error" in salesforce_response:
198
+ print(f"Error creating record in Salesforce: {salesforce_response['error']}")
199
+ return jsonify(salesforce_response), 500
200
+
201
+ # If creation was successful, return the details
202
+ return jsonify({"text": transcribed_text, "salesforce_record": salesforce_response})
203
+
204
+ except Exception as e:
205
+ print(f"Error in transcribing or processing: {str(e)}")
206
+ return jsonify({"error": f"Speech recognition error: {str(e)}"}), 500
207
+
208
+ # Start Production Server
209
+ if __name__ == "__main__":
210
+ serve(app, host="0.0.0.0", port=7860)