Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -6,23 +6,65 @@ 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 |
-
import datetime
|
15 |
|
16 |
app = Flask(__name__, template_folder="templates")
|
17 |
app.secret_key = os.urandom(24)
|
18 |
|
19 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
20 |
try:
|
21 |
print("Attempting to connect to Salesforce...")
|
22 |
sf = Salesforce(username='[email protected]', password='Sati@1020', security_token='sSSjyhInIsUohKpG8sHzty2q')
|
23 |
-
print("
|
24 |
except Exception as e:
|
25 |
-
print(f"
|
26 |
|
27 |
# ✅ HOME ROUTE (Loads `index.html`)
|
28 |
@app.route("/", methods=["GET"])
|
@@ -34,25 +76,10 @@ def index():
|
|
34 |
def dashboard():
|
35 |
return render_template("dashboard.html")
|
36 |
|
37 |
-
# ✅ MENU PAGE ROUTE
|
38 |
@app.route("/menu_page", methods=["GET"])
|
39 |
def menu_page():
|
40 |
-
|
41 |
-
query = "SELECT Name, Price__c, Ingredients__c, Category__c FROM Menu_Item__c"
|
42 |
-
result = sf.query(query)
|
43 |
-
|
44 |
-
menu_items = []
|
45 |
-
for item in result["records"]:
|
46 |
-
menu_items.append({
|
47 |
-
"name": item["Name"],
|
48 |
-
"price": item["Price__c"],
|
49 |
-
"ingredients": item["Ingredients__c"],
|
50 |
-
"category": item["Category__c"]
|
51 |
-
})
|
52 |
-
|
53 |
-
return render_template("menu_page.html", menu=menu_items)
|
54 |
-
except Exception as e:
|
55 |
-
return jsonify({"error": f"Failed to fetch menu: {str(e)}"}), 500
|
56 |
|
57 |
# ✅ LOGIN API
|
58 |
@app.route('/login', methods=['POST'])
|
@@ -96,42 +123,65 @@ def submit():
|
|
96 |
except Exception as e:
|
97 |
return jsonify({'error': str(e)}), 500
|
98 |
|
99 |
-
# ✅
|
100 |
-
@app.route("/
|
101 |
-
def
|
102 |
-
|
103 |
-
|
104 |
-
total_price = data.get('total_price') # Total price of the order
|
105 |
-
customer_name = data.get('customer_name') # Customer details
|
106 |
-
customer_email = data.get('customer_email')
|
107 |
|
108 |
-
|
109 |
-
|
|
|
|
|
110 |
|
111 |
-
# Creating order record in Salesforce
|
112 |
try:
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
120 |
})
|
121 |
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
130 |
})
|
131 |
|
132 |
-
return jsonify({
|
133 |
except Exception as e:
|
134 |
-
return jsonify({
|
135 |
|
136 |
# ✅ START PRODUCTION SERVER
|
137 |
if __name__ == "__main__":
|
|
|
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__, template_folder="templates")
|
16 |
app.secret_key = os.urandom(24)
|
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 |
+
# Function to generate audio prompts
|
26 |
+
def generate_audio_prompt(text, filename):
|
27 |
+
try:
|
28 |
+
tts = gTTS(text)
|
29 |
+
tts.save(os.path.join("static", filename))
|
30 |
+
except Exception as e:
|
31 |
+
print(f"Error: {e}")
|
32 |
+
time.sleep(5) # Wait 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 |
+
# Function to convert audio to WAV format
|
47 |
+
def convert_to_wav(input_path, output_path):
|
48 |
+
try:
|
49 |
+
audio = AudioSegment.from_file(input_path)
|
50 |
+
audio = audio.set_frame_rate(16000).set_channels(1) # Convert to 16kHz, mono
|
51 |
+
audio.export(output_path, format="wav")
|
52 |
+
except Exception as e:
|
53 |
+
raise Exception(f"Audio conversion failed: {str(e)}")
|
54 |
+
|
55 |
+
# Function to check if audio contains actual speech
|
56 |
+
def is_silent_audio(audio_path):
|
57 |
+
audio = AudioSegment.from_wav(audio_path)
|
58 |
+
nonsilent_parts = detect_nonsilent(audio, min_silence_len=500, silence_thresh=audio.dBFS-16)
|
59 |
+
return len(nonsilent_parts) == 0
|
60 |
+
|
61 |
+
# Salesforce connection details
|
62 |
try:
|
63 |
print("Attempting to connect to Salesforce...")
|
64 |
sf = Salesforce(username='[email protected]', password='Sati@1020', security_token='sSSjyhInIsUohKpG8sHzty2q')
|
65 |
+
print("Connected to Salesforce successfully!")
|
66 |
except Exception as e:
|
67 |
+
print(f"Failed to connect to Salesforce: {str(e)}")
|
68 |
|
69 |
# ✅ HOME ROUTE (Loads `index.html`)
|
70 |
@app.route("/", methods=["GET"])
|
|
|
76 |
def dashboard():
|
77 |
return render_template("dashboard.html")
|
78 |
|
79 |
+
# ✅ MENU PAGE ROUTE
|
80 |
@app.route("/menu_page", methods=["GET"])
|
81 |
def menu_page():
|
82 |
+
return render_template("menu_page.html")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
83 |
|
84 |
# ✅ LOGIN API
|
85 |
@app.route('/login', methods=['POST'])
|
|
|
123 |
except Exception as e:
|
124 |
return jsonify({'error': str(e)}), 500
|
125 |
|
126 |
+
# ✅ TRANSCRIBE AUDIO API
|
127 |
+
@app.route("/transcribe", methods=["POST"])
|
128 |
+
def transcribe():
|
129 |
+
if "audio" not in request.files:
|
130 |
+
return jsonify({"error": "No audio file provided"}), 400
|
|
|
|
|
|
|
131 |
|
132 |
+
audio_file = request.files["audio"]
|
133 |
+
input_audio_path = os.path.join("static", "temp_input.wav")
|
134 |
+
output_audio_path = os.path.join("static", "temp.wav")
|
135 |
+
audio_file.save(input_audio_path)
|
136 |
|
|
|
137 |
try:
|
138 |
+
convert_to_wav(input_audio_path, output_audio_path)
|
139 |
+
if is_silent_audio(output_audio_path):
|
140 |
+
return jsonify({"error": "No speech detected. Please try again."}), 400
|
141 |
+
|
142 |
+
asr_pipeline = pipeline("automatic-speech-recognition", model="openai/whisper-small", device=0 if torch.cuda.is_available() else -1, config=config)
|
143 |
+
result = asr_pipeline(output_audio_path)
|
144 |
+
|
145 |
+
transcribed_text = result["text"].strip().capitalize()
|
146 |
+
|
147 |
+
parts = transcribed_text.split()
|
148 |
+
name = parts[0] if len(parts) > 0 else "Unknown Name"
|
149 |
+
email = parts[1] if '@' in parts[1] else "[email protected]"
|
150 |
+
phone_number = parts[2] if len(parts) > 2 else "0000000000"
|
151 |
+
|
152 |
+
confirmation = f"Is this correct? Name: {name}, Email: {email}, Phone: {phone_number}"
|
153 |
+
generate_audio_prompt(confirmation, "confirmation.mp3")
|
154 |
+
|
155 |
+
salesforce_response = sf.Customer_Login__c.create({
|
156 |
+
'Name': name,
|
157 |
+
'Email__c': email,
|
158 |
+
'Phone_Number__c': phone_number
|
159 |
})
|
160 |
|
161 |
+
return jsonify({"text": transcribed_text, "salesforce_record": salesforce_response})
|
162 |
+
|
163 |
+
except Exception as e:
|
164 |
+
return jsonify({"error": f"Speech recognition error: {str(e)}"}), 500
|
165 |
+
|
166 |
+
# ✅ MENU API
|
167 |
+
@app.route("/menu", methods=["GET"])
|
168 |
+
def get_menu():
|
169 |
+
try:
|
170 |
+
query = "SELECT Name, Price__c, Ingredients__c, Category__c FROM Menu_Item__c"
|
171 |
+
result = sf.query(query)
|
172 |
+
|
173 |
+
menu_items = []
|
174 |
+
for item in result["records"]:
|
175 |
+
menu_items.append({
|
176 |
+
"name": item["Name"],
|
177 |
+
"price": item["Price__c"],
|
178 |
+
"ingredients": item["Ingredients__c"],
|
179 |
+
"category": item["Category__c"]
|
180 |
})
|
181 |
|
182 |
+
return jsonify({"success": True, "menu": menu_items})
|
183 |
except Exception as e:
|
184 |
+
return jsonify({"error": f"Failed to fetch menu: {str(e)}"}), 500
|
185 |
|
186 |
# ✅ START PRODUCTION SERVER
|
187 |
if __name__ == "__main__":
|