lokesh341 commited on
Commit
66083bc
·
verified ·
1 Parent(s): fc05317

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +150 -68
app.py CHANGED
@@ -1,30 +1,60 @@
1
  import torch
2
- from flask import Flask, render_template, request, jsonify, redirect, url_for
 
3
  import os
4
- from transformers import pipeline, AutoConfig
 
5
  from pydub import AudioSegment
6
  from pydub.silence import detect_nonsilent
 
7
  import time
8
  from waitress import serve
9
  from simple_salesforce import Salesforce
10
- import requests
11
 
12
  app = Flask(__name__)
13
 
14
- # Use whisper-small for faster processing
15
  device = "cuda" if torch.cuda.is_available() else "cpu"
16
 
17
- # Whisper ASR Model Configuration
18
  config = AutoConfig.from_pretrained("openai/whisper-small")
19
  config.update({"timeout": 60}) # Set timeout to 60 seconds
20
 
21
- # Salesforce Connection
22
- try:
23
- print("Connecting to Salesforce...")
24
- sf = Salesforce(username='[email protected]', password='Sati@1020', security_token='sSSjyhInIsUohKpG8sHzty2q')
25
- print("Connected to Salesforce!")
26
- except Exception as e:
27
- print(f"Failed to connect to Salesforce: {str(e)}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
 
29
  # Function to convert audio to WAV format
30
  def convert_to_wav(input_path, output_path):
@@ -33,28 +63,50 @@ def convert_to_wav(input_path, output_path):
33
  audio = audio.set_frame_rate(16000).set_channels(1) # Convert to 16kHz, mono
34
  audio.export(output_path, format="wav")
35
  except Exception as e:
36
- print(f"Audio conversion failed: {str(e)}")
37
- raise
38
 
39
- # Check if audio contains speech
40
  def is_silent_audio(audio_path):
41
  audio = AudioSegment.from_wav(audio_path)
42
- nonsilent_parts = detect_nonsilent(audio, min_silence_len=500, silence_thresh=audio.dBFS-16)
 
43
  return len(nonsilent_parts) == 0 # If no speech detected
44
 
45
- # Create Salesforce Record
46
- def create_salesforce_record(name, email, phone_number):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47
  try:
48
- response = sf.Customer_Login__c.create({
49
  'Name': name,
50
  'Email__c': email,
51
  'Phone_Number__c': phone_number
52
  })
53
- return {'success': True, 'id': response.get('id')}
54
  except Exception as e:
55
- return {'error': f'Failed to create record: {str(e)}'}
56
 
57
- # Registration API
58
  @app.route("/submit", methods=["POST"])
59
  def submit():
60
  data = request.json
@@ -65,61 +117,91 @@ def submit():
65
  if not name or not email or not phone:
66
  return jsonify({'error': 'Missing data'}), 400
67
 
68
- response = create_salesforce_record(name, email, phone)
69
- return jsonify(response) if "error" not in response else (jsonify(response), 500)
70
-
71
- # Updated Login API (Only for Registered Users)
72
- @app.route('/login', methods=['POST'])
73
- def login():
74
- data = request.json
75
- email = data.get('email')
76
- phone_number = data.get('phone_number')
77
-
78
- if not email or not phone_number:
79
- return jsonify({'error': 'Email and phone number are required'}), 400
80
-
81
  try:
82
- # Print received login details for debugging
83
- print(f"🔍 Received login request for Email: {email}, Phone: {phone_number}")
84
-
85
- # Query Salesforce to check if the user exists
86
- query_result = sf.query(f"""
87
- SELECT Id, Name, Email__c, Phone_Number__c FROM Customer_Login__c
88
- WHERE LOWER(Email__c) = '{email.lower()}'
89
- AND Phone_Number__c = '{phone_number}'
90
- """)
91
-
92
- # Debugging: Print Salesforce Query Result
93
- print("🔍 Salesforce Query Result:", query_result)
94
-
95
- if query_result['totalSize'] > 0:
96
- print("✅ Login successful!")
97
- return jsonify({
98
- 'success': True,
99
- 'message': 'Login successful',
100
- 'user': query_result['records'][0],
101
- 'redirect': '/dashboard'
102
- }), 200
103
  else:
104
- print("❌ Invalid credentials! User not found in Salesforce.") # Debugging
105
- return jsonify({'error': 'Invalid credentials! Only registered users can log in.', 'refresh': True}), 401
106
  except Exception as e:
107
- print(f"⚠️ Salesforce Query Failed: {str(e)}") # Debugging
108
- return jsonify({'error': f'Salesforce query failed: {str(e)}', 'refresh': True}), 500
109
 
110
- # Serve Registration and Login Pages
111
  @app.route("/")
112
  def index():
113
  return render_template("index.html")
114
 
115
- @app.route("/login-page")
116
- def login_page():
117
- return render_template("login.html")
 
 
118
 
119
- @app.route("/dashboard")
120
- def dashboard():
121
- return "<h1>Welcome to the Dashboard</h1><p>You have successfully logged in.</p>"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
122
 
123
- # Start the Flask App
124
  if __name__ == "__main__":
125
  serve(app, host="0.0.0.0", port=7860)
 
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):
 
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
 
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)