geethareddy commited on
Commit
1afcd15
·
verified ·
1 Parent(s): 6e4e01d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +133 -31
app.py CHANGED
@@ -6,47 +6,82 @@ 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
 
17
- # Use whisper-small for faster processing
18
  device = "cuda" if torch.cuda.is_available() else "cpu"
19
 
20
- # Create config object to set timeout
21
  config = AutoConfig.from_pretrained("openai/whisper-small")
22
- config.update({"timeout": 60})
23
 
24
- # Salesforce connection
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
  except Exception as e:
30
  print(f"Failed to connect to Salesforce: {str(e)}")
31
 
32
- # Function to fetch menu items from Salesforce
33
- def get_menu_items():
34
  try:
35
- query = "SELECT Name, Price__c, Ingredients__c, Category__c FROM Menu_Item__c"
36
- result = sf.query(query)
37
- return result['records']
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
  except Exception as e:
39
- print(f"Error fetching menu items: {str(e)}")
40
- return []
 
 
 
 
 
 
41
 
42
- # Route to serve menu page
43
  @app.route("/")
44
  def index():
45
  return render_template("index.html")
46
 
47
  @app.route("/dashboard", methods=["GET"])
48
  def dashboard():
49
- return render_template("dashboard.html")
50
 
51
  @app.route('/login', methods=['POST'])
52
  def login():
@@ -59,26 +94,18 @@ def login():
59
  return jsonify({'error': 'Missing required fields'}), 400
60
 
61
  try:
62
- customer_login = sf.Customer_Login__c.create({
63
- 'Name': name,
64
- 'Email__c': email,
65
- 'Phone_Number__c': phone_number
66
- })
67
  return jsonify({'success': True, 'message': 'Successfully logged in'}), 200
68
  except Exception as e:
69
  return jsonify({'error': f'Failed to create record in Salesforce: {str(e)}'}), 500
70
 
71
- # Route to fetch menu items dynamically
72
- @app.route("/get-menu", methods=["GET"])
73
- def get_menu():
74
- menu_items = get_menu_items()
75
- return jsonify(menu_items)
76
-
77
- # Route to render menu page
78
  @app.route("/menu", methods=["GET"])
79
  def menu_page():
80
- return render_template("menu_page.html")
 
 
81
 
 
82
  @app.route("/order", methods=["POST"])
83
  def place_order():
84
  item_name = request.json.get('item_name')
@@ -87,14 +114,89 @@ def place_order():
87
  sf.Order__c.create(order_data)
88
  return jsonify({"success": True, "message": f"Order for {item_name} placed successfully."})
89
 
 
90
  @app.route("/cart", methods=["GET"])
91
  def cart():
92
- return render_template("cart_page.html")
 
93
 
 
94
  @app.route("/order-summary", methods=["GET"])
95
  def order_summary():
96
- return render_template("order_summary.html")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97
 
98
  # Start Production Server
99
  if __name__ == "__main__":
100
- serve(app, host="0.0.0.0", port=7860)
 
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
+ # Salesforce connection details
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) # Log the user info to verify the connection
30
  except Exception as e:
31
  print(f"Failed to connect to Salesforce: {str(e)}")
32
 
33
+ # Functions for Salesforce operations
34
+ def create_salesforce_record(sf, name, email, phone_number):
35
  try:
36
+ customer_login = sf.Customer_Login__c.create({
37
+ 'Name': name,
38
+ 'Email__c': email,
39
+ 'Phone_Number__c': phone_number
40
+ })
41
+ return customer_login
42
+ except Exception as e:
43
+ raise Exception(f"Failed to create record: {str(e)}")
44
+
45
+ def get_menu_items(sf):
46
+ query = "SELECT Name, Price__c, Ingredients__c, Category__c FROM Menu_Item__c"
47
+ result = sf.query(query)
48
+ return result['records']
49
+
50
+ # Voice-related functions
51
+ def generate_audio_prompt(text, filename):
52
+ try:
53
+ tts = gTTS(text)
54
+ tts.save(os.path.join("static", filename))
55
+ except gtts.tts.gTTSError as e:
56
+ print(f"Error: {e}")
57
+ print("Retrying after 5 seconds...")
58
+ time.sleep(5) # Wait for 5 seconds before retrying
59
+ generate_audio_prompt(text, filename)
60
+
61
+ # Utility functions
62
+ def convert_to_wav(input_path, output_path):
63
+ try:
64
+ audio = AudioSegment.from_file(input_path)
65
+ audio = audio.set_frame_rate(16000).set_channels(1) # Convert to 16kHz, mono
66
+ audio.export(output_path, format="wav")
67
  except Exception as e:
68
+ print(f"Error: {str(e)}")
69
+ raise Exception(f"Audio conversion failed: {str(e)}")
70
+
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
+ # Routes and Views
78
  @app.route("/")
79
  def index():
80
  return render_template("index.html")
81
 
82
  @app.route("/dashboard", methods=["GET"])
83
  def dashboard():
84
+ return render_template("dashboard.html") # Render the dashboard template
85
 
86
  @app.route('/login', methods=['POST'])
87
  def login():
 
94
  return jsonify({'error': 'Missing required fields'}), 400
95
 
96
  try:
97
+ customer_login = create_salesforce_record(sf, name, email, phone_number)
 
 
 
 
98
  return jsonify({'success': True, 'message': 'Successfully logged in'}), 200
99
  except Exception as e:
100
  return jsonify({'error': f'Failed to create record in Salesforce: {str(e)}'}), 500
101
 
 
 
 
 
 
 
 
102
  @app.route("/menu", methods=["GET"])
103
  def menu_page():
104
+ menu_items = get_menu_items(sf)
105
+ menu_data = [{"name": item['Name'], "price": item['Price__c'], "ingredients": item['Ingredients__c'], "category": item['Category__c']} for item in menu_items]
106
+ return render_template("menu_page.html", menu_items=menu_data)
107
 
108
+ # Route for handling order
109
  @app.route("/order", methods=["POST"])
110
  def place_order():
111
  item_name = request.json.get('item_name')
 
114
  sf.Order__c.create(order_data)
115
  return jsonify({"success": True, "message": f"Order for {item_name} placed successfully."})
116
 
117
+ # Route to handle the cart
118
  @app.route("/cart", methods=["GET"])
119
  def cart():
120
+ cart_items = [] # Placeholder for cart items
121
+ return render_template("cart_page.html", cart_items=cart_items)
122
 
123
+ # Route for the order summary page
124
  @app.route("/order-summary", methods=["GET"])
125
  def order_summary():
126
+ order_details = [] # Placeholder for order details
127
+ return render_template("order_summary.html", order_details=order_details)
128
+
129
+ @app.route("/transcribe", methods=["POST"])
130
+ def transcribe():
131
+ if "audio" not in request.files:
132
+ print("No audio file provided")
133
+ return jsonify({"error": "No audio file provided"}), 400
134
+
135
+ audio_file = request.files["audio"]
136
+ input_audio_path = os.path.join("static", "temp_input.wav")
137
+ output_audio_path = os.path.join("static", "temp.wav")
138
+ audio_file.save(input_audio_path)
139
+
140
+ try:
141
+ # Convert to WAV
142
+ convert_to_wav(input_audio_path, output_audio_path)
143
+
144
+ # Check for silence
145
+ if is_silent_audio(output_audio_path):
146
+ return jsonify({"error": "No speech detected. Please try again."}), 400
147
+ else:
148
+ print("Audio contains speech, proceeding with transcription.")
149
+
150
+ # Use Whisper ASR model for transcription
151
+ result = None
152
+ retry_attempts = 3
153
+ for attempt in range(retry_attempts):
154
+ try:
155
+ result = pipeline("automatic-speech-recognition", model="openai/whisper-small", device=0 if torch.cuda.is_available() else -1, config=config)
156
+ print(f"Transcribed text: {result['text']}")
157
+ break
158
+ except requests.exceptions.ReadTimeout:
159
+ print(f"Timeout occurred, retrying attempt {attempt + 1}/{retry_attempts}...")
160
+ time.sleep(5)
161
+
162
+ if result is None:
163
+ return jsonify({"error": "Unable to transcribe audio after retries."}), 500
164
+
165
+ transcribed_text = result["text"].strip().capitalize()
166
+ print(f"Transcribed text: {transcribed_text}")
167
+
168
+ # Extract name, email, and phone number from the transcribed text
169
+ parts = transcribed_text.split()
170
+ name = parts[0] if len(parts) > 0 else "Unknown Name"
171
+ email = parts[1] if '@' in parts[1] else "unknown@domain.com"
172
+ phone_number = parts[2] if len(parts) > 2 else "0000000000"
173
+ print(f"Parsed data - Name: {name}, Email: {email}, Phone Number: {phone_number}")
174
+
175
+ # Confirm details before submission
176
+ confirmation = f"Is this correct? Name: {name}, Email: {email}, Phone: {phone_number}"
177
+ generate_audio_prompt(confirmation, "confirmation.mp3")
178
+
179
+ # Simulate confirmation via user action
180
+ user_confirms = True # Assuming the user confirms, you can replace this with actual user input logic
181
+
182
+ if user_confirms:
183
+ # Create record in Salesforce
184
+ salesforce_response = create_salesforce_record(name, email, phone_number)
185
+
186
+ # Log the Salesforce response
187
+ print(f"Salesforce record creation response: {salesforce_response}")
188
+
189
+ # Check if the response contains an error
190
+ if "error" in salesforce_response:
191
+ print(f"Error creating record in Salesforce: {salesforce_response['error']}")
192
+ return jsonify(salesforce_response), 500
193
+
194
+ return jsonify({"text": transcribed_text, "salesforce_record": salesforce_response})
195
+
196
+ except Exception as e:
197
+ print(f"Error in transcribing or processing: {str(e)}")
198
+ return jsonify({"error": f"Speech recognition error: {str(e)}"}), 500
199
 
200
  # Start Production Server
201
  if __name__ == "__main__":
202
+ serve(app, host="0.0.0.0", port=7860)