lokesh341 commited on
Commit
9b40d8d
·
verified ·
1 Parent(s): b47890c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +182 -82
app.py CHANGED
@@ -1,115 +1,215 @@
1
  import torch
2
- from flask import Flask, render_template, request, jsonify, redirect, session, url_for
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
10
  import time
11
  from waitress import serve
12
  from simple_salesforce import Salesforce
13
- import requests
14
 
15
- # Initialize Flask App
16
- app = Flask(__name__, template_folder="templates")
17
- app.secret_key = os.urandom(24)
18
 
19
- # Enable Debug Mode
20
- app.config["DEBUG"] = True
21
 
22
- # Salesforce Connection Setup
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
  try:
24
  print("Attempting to connect to Salesforce...")
25
- sf = Salesforce(username='[email protected]',
26
- password='Sati@1020',
27
- security_token='sSSjyhInIsUohKpG8sHzty2q')
28
- print("✅ Connected to Salesforce successfully!")
29
  except Exception as e:
30
- print(f"Failed to connect to Salesforce: {str(e)}")
31
 
32
- # HOME ROUTE (Loads `index.html`)
33
- @app.route("/", methods=["GET"])
34
- def home():
35
- return render_template("index.html")
36
-
37
- # RENDER DASHBOARD PAGE
38
- @app.route("/dashboard", methods=["GET"])
39
- def dashboard():
40
- return render_template("dashboard.html")
41
-
42
- # ✅ RENDER MENU PAGE
43
- @app.route("/menu_page", methods=["GET"])
44
- def menu_page():
45
- return render_template("menu_page.html")
46
 
47
- # REGISTER API: Create a new Customer in Salesforce
48
- @app.route("/register", methods=["POST"])
49
- def register():
50
- print("➡ Register API hit")
51
- data = request.json
52
- if not data or "name" not in data or "email" not in data or "phone" not in data:
53
- return jsonify({"error": "Missing required fields"}), 400
54
 
 
55
  try:
56
- new_customer = sf.Customer_Login__c.create({
57
- 'Name': data["name"],
58
- 'Email__c': data["email"],
59
- 'Phone_Number__c': data["phone"]
60
  })
61
- return jsonify({"success": True, "message": "Registration successful", "customer_id": new_customer["id"]})
62
  except Exception as e:
63
- return jsonify({"error": f"Registration failed: {str(e)}"}), 500)
64
 
65
- # ✅ LOGIN API: Validate User Credentials
66
- @app.route("/login", methods=["POST"])
67
- def login():
68
- print("➡ Login API hit")
69
  data = request.json
70
- if not data or "email" not in data or "phone" not in data:
71
- return jsonify({"error": "Missing email or phone"}), 400
 
 
 
 
72
 
73
  try:
74
- query = f"SELECT Id, Name FROM Customer_Login__c WHERE Email__c = '{data['email']}' AND Phone_Number__c = '{data['phone']}'"
75
- result = sf.query(query)
76
-
77
- if result["totalSize"] > 0:
78
- user = result["records"][0]
79
- session["customer_id"] = user["Id"] # Store in session
80
- return jsonify({
81
- "success": True,
82
- "message": "Login successful",
83
- "customer_id": user["Id"],
84
- "name": user["Name"]
85
- })
86
  else:
87
- return jsonify({"error": "Invalid login credentials"}), 401
 
88
  except Exception as e:
89
- return jsonify({"error": f"Login failed: {str(e)}"}), 500)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90
 
91
- # ✅ MENU API: Fetch Menu Items from Salesforce
92
- @app.route("/menu", methods=["GET"])
93
- def get_menu():
94
- print("➡ Menu API hit")
95
  try:
96
- query = "SELECT Name, Price__c, Ingredients__c, Category__c FROM Menu_Item__c"
97
- result = sf.query(query)
98
-
99
- menu_items = []
100
- for item in result["records"]:
101
- menu_items.append({
102
- "name": item["Name"],
103
- "price": item["Price__c"],
104
- "ingredients": item["Ingredients__c"],
105
- "category": item["Category__c"]
106
- })
107
-
108
- return jsonify({"success": True, "menu": menu_items})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
109
  except Exception as e:
110
- return jsonify({"error": f"Failed to fetch menu: {str(e)}"}), 500)
 
111
 
112
- # START PRODUCTION SERVER
113
  if __name__ == "__main__":
114
- print(" Starting Flask API Server on port 7860...")
115
- 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):
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
+ # Confirm details before submission
188
+ confirmation = f"Is this correct? Name: {name}, Email: {email}, Phone: {phone_number}"
189
+ generate_audio_prompt(confirmation, "confirmation.mp3")
190
+
191
+ # Simulate confirmation via user action, in real case this should be handled via front-end
192
+ user_confirms = True # Assuming the user confirms, you can replace this with actual user input logic
193
+
194
+ if user_confirms:
195
+ # Create record in Salesforce
196
+ salesforce_response = create_salesforce_record(name, email, phone_number)
197
+
198
+ # Log the Salesforce response
199
+ print(f"Salesforce record creation response: {salesforce_response}")
200
+
201
+ # Check if the response contains an error
202
+ if "error" in salesforce_response:
203
+ print(f"Error creating record in Salesforce: {salesforce_response['error']}")
204
+ return jsonify(salesforce_response), 500
205
+
206
+ # If creation was successful, return the details
207
+ return jsonify({"text": transcribed_text, "salesforce_record": salesforce_response})
208
+
209
  except Exception as e:
210
+ print(f"Error in transcribing or processing: {str(e)}")
211
+ return jsonify({"error": f"Speech recognition error: {str(e)}"}), 500
212
 
213
+ # Start Production Server
214
  if __name__ == "__main__":
215
+ serve(app, host="0.0.0.0", port=7860)