lokesh341 commited on
Commit
c32f608
·
verified ·
1 Parent(s): 19a22f4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +99 -110
app.py CHANGED
@@ -1,6 +1,6 @@
1
 
2
  import torch
3
- from flask import Flask, render_template, request, jsonify, redirect, session
4
  import json
5
  import os
6
  from transformers import pipeline
@@ -13,143 +13,132 @@ from waitress import serve
13
  from simple_salesforce import Salesforce
14
  import requests
15
 
16
- # Initialize Flask app
17
  app = Flask(__name__)
18
- app.secret_key = os.urandom(24) # For session handling
19
 
20
- # Salesforce connection details
21
- try:
22
- print("Attempting to connect to Salesforce...")
23
- sf = Salesforce(username='[email protected]', password='Sati@1020', security_token='sSSjyhInIsUohKpG8sHzty2q')
24
- print("Connected to Salesforce successfully!")
25
- except Exception as e:
26
- print(f"Failed to connect to Salesforce: {str(e)}")
27
-
28
- # Functions for Salesforce operations
29
- def create_salesforce_record(sf, name, email, phone_number):
30
- try:
31
- customer_login = sf.Customer_Login__c.create({
32
- 'Name': name,
33
- 'Email__c': email,
34
- 'Phone_Number__c': phone_number
35
- })
36
- return customer_login
37
- except Exception as e:
38
- raise Exception(f"Failed to create record: {str(e)}")
39
-
40
- def get_menu_items(sf):
41
- query = "SELECT Name, Price__c, Ingredients__c, Category__c FROM Menu_Item__c"
42
- result = sf.query(query)
43
- return result['records']
44
 
45
- def create_salesforce_order(sf, cart_items, total_price, customer_id):
46
- try:
47
- order = sf.Order__c.create({
48
- 'Total_Price__c': total_price,
49
- 'Cart_Items__c': json.dumps(cart_items), # Storing cart items as JSON
50
- 'Customer__c': customer_id # Linking to the customer record
51
- })
52
- return order
53
- except Exception as e:
54
- raise Exception(f"Failed to create order: {str(e)}")
55
-
56
- # Voice-related functions
57
  def generate_audio_prompt(text, filename):
58
  try:
59
  tts = gTTS(text)
60
  tts.save(os.path.join("static", filename))
61
  except gtts.tts.gTTSError as e:
62
  print(f"Error: {e}")
63
- print("Retrying after 5 seconds...")
64
- time.sleep(5) # Wait for 5 seconds before retrying
65
  generate_audio_prompt(text, filename)
66
 
67
- # Utility functions
68
- def convert_to_wav(input_path, output_path):
69
- try:
70
- audio = AudioSegment.from_file(input_path)
71
- audio = audio.set_frame_rate(16000).set_channels(1) # Convert to 16kHz, mono
72
- audio.export(output_path, format="wav")
73
- except Exception as e:
74
- print(f"Error: {str(e)}")
75
- raise Exception(f"Audio conversion failed: {str(e)}")
76
 
77
- def is_silent_audio(audio_path):
78
- audio = AudioSegment.from_wav(audio_path)
79
- nonsilent_parts = detect_nonsilent(audio, min_silence_len=500, silence_thresh=audio.dBFS-16)
80
- print(f"Detected nonsilent parts: {nonsilent_parts}")
81
- return len(nonsilent_parts) == 0 # If no speech detected
 
82
 
83
- # Routes and Views
84
  @app.route("/")
85
  def index():
86
  return render_template("index.html")
87
 
88
- @app.route("/dashboard", methods=["GET"])
89
  def dashboard():
90
- return render_template("dashboard.html") # Render the dashboard template
91
 
92
- @app.route("/menu", methods=["GET"])
93
- def menu_page():
94
- # Fetch the menu items from Salesforce
95
- menu_items = get_menu_items(sf) # Fetch menu items from Salesforce
96
- menu_data = [{"name": item['Name'], "price": item['Price__c'], "ingredients": item['Ingredients__c'], "category": item['Category__c']} for item in menu_items]
97
- return render_template("menu_page.html", menu_items=menu_data)
98
 
99
- @app.route("/cart", methods=["GET"])
100
  def cart():
101
- cart_items = session.get('cart_items', [])
102
- return render_template("cart_page.html", cart_items=cart_items)
103
-
104
- @app.route("/order-summary", methods=["GET"])
105
- def order_summary():
106
- order_details = session.get('cart_items', [])
107
- total_price = sum(item['price'] * item['quantity'] for item in order_details)
108
- return render_template("order_summary.html", order_details=order_details, total_price=total_price)
109
-
110
- @app.route("/final_order", methods=["GET"])
111
- def final_order():
112
- cart_items = session.get('cart_items', [])
113
- total_price = sum(item['price'] * item['quantity'] for item in cart_items)
114
- customer_id = session.get('customer_id', None)
115
-
116
- if customer_id:
117
- try:
118
- order = create_salesforce_order(sf, cart_items, total_price, customer_id)
119
- session.pop('cart_items', None) # Clear cart after placing the order
120
- return render_template("final_order.html", order_details=cart_items, total_price=total_price)
121
- except Exception as e:
122
- return jsonify({'error': f'Failed to create order in Salesforce: {str(e)}'}), 500
123
- else:
124
- return jsonify({'error': 'Customer not logged in'}), 400
125
-
126
- @app.route("/add_to_cart", methods=["POST"])
127
- def add_to_cart():
128
- item_name = request.json.get('item_name')
129
- quantity = request.json.get('quantity')
130
-
131
- cart_items = session.get('cart_items', [])
132
- cart_items.append({"name": item_name, "quantity": quantity, "price": 10}) # Assuming a fixed price for now
133
- session['cart_items'] = cart_items
134
-
135
- return jsonify({"success": True, "message": f"Added {item_name} to cart."})
136
-
137
- @app.route("/register", methods=["POST"])
138
- def register():
139
- name = request.json.get('name')
140
- email = request.json.get('email')
141
- phone_number = request.json.get('phone_number')
142
 
143
  if not name or not email or not phone_number:
144
  return jsonify({'error': 'Missing required fields'}), 400
145
 
146
  try:
147
- customer_login = create_salesforce_record(sf, name, email, phone_number)
148
- session['customer_id'] = customer_login['id'] # Store customer ID in session
149
- return redirect("/menu") # Redirect to the menu page after successful registration
 
 
 
150
  except Exception as e:
151
  return jsonify({'error': f'Failed to create record in Salesforce: {str(e)}'}), 500
152
 
153
- # Start Production Server
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
154
  if __name__ == "__main__":
155
  serve(app, host="0.0.0.0", port=7860)
 
1
 
2
  import torch
3
+ from flask import Flask, render_template, request, jsonify
4
  import json
5
  import os
6
  from transformers import pipeline
 
13
  from simple_salesforce import Salesforce
14
  import requests
15
 
 
16
  app = Flask(__name__)
 
17
 
18
+ device = "cuda" if torch.cuda.is_available() else "cpu"
19
+ config = AutoConfig.from_pretrained("openai/whisper-small")
20
+ config.update({"timeout": 60})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
 
 
 
 
 
 
 
 
 
 
 
 
 
22
  def generate_audio_prompt(text, filename):
23
  try:
24
  tts = gTTS(text)
25
  tts.save(os.path.join("static", filename))
26
  except gtts.tts.gTTSError as e:
27
  print(f"Error: {e}")
28
+ time.sleep(5)
 
29
  generate_audio_prompt(text, filename)
30
 
31
+ prompts = {
32
+ "welcome": "Welcome to Biryani Hub.",
33
+ "ask_name": "Tell me your name.",
34
+ "ask_email": "Please provide your email address.",
35
+ "thank_you": "Thank you for registration."
36
+ }
37
+
38
+ for key, text in prompts.items():
39
+ generate_audio_prompt(text, f"{key}.mp3")
40
 
41
+ try:
42
+ print("Attempting to connect to Salesforce...")
43
+ sf = Salesforce(username='[email protected]', password='Sati@1020', security_token='sSSjyhInIsUohKpG8sHzty2q')
44
+ print("Connected to Salesforce successfully!")
45
+ except Exception as e:
46
+ print(f"Failed to connect to Salesforce: {str(e)}")
47
 
 
48
  @app.route("/")
49
  def index():
50
  return render_template("index.html")
51
 
52
+ @app.route("/dashboard")
53
  def dashboard():
54
+ return render_template("dashboard.html")
55
 
56
+ @app.route("/menu")
57
+ def menu():
58
+ return render_template("menu.html")
 
 
 
59
 
60
+ @app.route("/cart")
61
  def cart():
62
+ return render_template("cart.html")
63
+
64
+ @app.route("/order")
65
+ def order():
66
+ return render_template("order.html")
67
+
68
+ @app.route("/final")
69
+ def final():
70
+ return render_template("final.html")
71
+
72
+ @app.route("/submit", methods=["POST"])
73
+ def submit():
74
+ data = request.json
75
+ name = data.get('name')
76
+ email = data.get('email')
77
+ phone = data.get('phone')
78
+
79
+ if not name or not email or not phone:
80
+ return jsonify({'error': 'Missing data'}), 400
81
+
82
+ try:
83
+ customer_login = sf.Customer_Login__c.create({
84
+ 'Name': name,
85
+ 'Email__c': email,
86
+ 'Phone_Number__c': phone
87
+ })
88
+
89
+ if customer_login.get('id'):
90
+ return jsonify({'success': True})
91
+ else:
92
+ return jsonify({'error': 'Failed to create record'}), 500
93
+
94
+ except Exception as e:
95
+ return jsonify({'error': str(e)}), 500
96
+
97
+ @app.route("/login", methods=["POST"])
98
+ def login():
99
+ data = request.json
100
+ name = data.get('name')
101
+ email = data.get('email')
102
+ phone_number = data.get('phone_number')
103
 
104
  if not name or not email or not phone_number:
105
  return jsonify({'error': 'Missing required fields'}), 400
106
 
107
  try:
108
+ customer_login = sf.Customer_Login__c.create({
109
+ 'Name': name,
110
+ 'Email__c': email,
111
+ 'Phone_Number__c': phone_number
112
+ })
113
+ return jsonify({'success': True, 'id': customer_login['id']}), 200
114
  except Exception as e:
115
  return jsonify({'error': f'Failed to create record in Salesforce: {str(e)}'}), 500
116
 
117
+ @app.route("/transcribe", methods=["POST"])
118
+ def transcribe():
119
+ if "audio" not in request.files:
120
+ return jsonify({"error": "No audio file provided"}), 400
121
+
122
+ audio_file = request.files["audio"]
123
+ input_audio_path = os.path.join("static", "temp_input.wav")
124
+ output_audio_path = os.path.join("static", "temp.wav")
125
+ audio_file.save(input_audio_path)
126
+
127
+ try:
128
+ audio = AudioSegment.from_file(input_audio_path)
129
+ audio = audio.set_frame_rate(16000).set_channels(1)
130
+ audio.export(output_audio_path, format="wav")
131
+
132
+ nonsilent_parts = detect_nonsilent(audio, min_silence_len=500, silence_thresh=audio.dBFS-16)
133
+ if len(nonsilent_parts) == 0:
134
+ return jsonify({"error": "No speech detected. Please try again."}), 400
135
+
136
+ result = pipeline("automatic-speech-recognition", model="openai/whisper-small", device=0 if torch.cuda.is_available() else -1, config=config)
137
+ transcribed_text = result["text"].strip().capitalize()
138
+
139
+ return jsonify({"text": transcribed_text})
140
+ except Exception as e:
141
+ return jsonify({"error": f"Speech recognition error: {str(e)}"}), 500
142
+
143
  if __name__ == "__main__":
144
  serve(app, host="0.0.0.0", port=7860)