Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,159 +1,125 @@
|
|
| 1 |
-
import os
|
| 2 |
-
import time
|
| 3 |
-
import logging
|
| 4 |
-
import json
|
| 5 |
-
import requests
|
| 6 |
import torch
|
| 7 |
-
from flask import Flask, render_template, request, jsonify,
|
| 8 |
-
|
| 9 |
-
from simple_salesforce import Salesforce
|
| 10 |
from transformers import pipeline, AutoConfig
|
| 11 |
-
from gtts import gTTS
|
| 12 |
from pydub import AudioSegment
|
| 13 |
from pydub.silence import detect_nonsilent
|
|
|
|
| 14 |
from waitress import serve
|
|
|
|
|
|
|
| 15 |
|
| 16 |
app = Flask(__name__)
|
| 17 |
|
| 18 |
-
#
|
| 19 |
-
|
| 20 |
-
app.config["SESSION_TYPE"] = "filesystem"
|
| 21 |
-
Session(app)
|
| 22 |
|
| 23 |
-
#
|
| 24 |
-
|
|
|
|
| 25 |
|
| 26 |
-
#
|
| 27 |
try:
|
|
|
|
| 28 |
sf = Salesforce(username='diggavalli98@gmail.com', password='Sati@1020', security_token='sSSjyhInIsUohKpG8sHzty2q')
|
| 29 |
-
print("
|
| 30 |
except Exception as e:
|
| 31 |
-
print(f"
|
| 32 |
-
|
| 33 |
-
# Whisper ASR Configuration
|
| 34 |
-
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 35 |
-
config = AutoConfig.from_pretrained("openai/whisper-small")
|
| 36 |
-
config.update({"timeout": 60})
|
| 37 |
-
|
| 38 |
-
# Voice prompts
|
| 39 |
-
prompts = {
|
| 40 |
-
"welcome": "Welcome to Biryani Hub.",
|
| 41 |
-
"ask_name": "Tell me your name.",
|
| 42 |
-
"ask_email": "Please provide your email address.",
|
| 43 |
-
"thank_you": "Thank you for registration."
|
| 44 |
-
}
|
| 45 |
-
|
| 46 |
-
# Function to generate voice prompts
|
| 47 |
-
def generate_audio_prompt(text, filename):
|
| 48 |
-
try:
|
| 49 |
-
tts = gTTS(text)
|
| 50 |
-
tts.save(os.path.join("static", filename))
|
| 51 |
-
except gtts.tts.gTTSError as e:
|
| 52 |
-
time.sleep(5)
|
| 53 |
-
generate_audio_prompt(text, filename)
|
| 54 |
-
|
| 55 |
-
for key, text in prompts.items():
|
| 56 |
-
generate_audio_prompt(text, f"{key}.mp3")
|
| 57 |
|
| 58 |
# Function to convert audio to WAV format
|
| 59 |
def convert_to_wav(input_path, output_path):
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 63 |
|
| 64 |
-
#
|
| 65 |
def is_silent_audio(audio_path):
|
| 66 |
audio = AudioSegment.from_wav(audio_path)
|
| 67 |
nonsilent_parts = detect_nonsilent(audio, min_silence_len=500, silence_thresh=audio.dBFS-16)
|
| 68 |
-
return len(nonsilent_parts) == 0
|
| 69 |
-
|
| 70 |
-
@app.route("/")
|
| 71 |
-
def index():
|
| 72 |
-
return render_template("index.html")
|
| 73 |
-
|
| 74 |
-
# ✅ LOGIN ENDPOINT
|
| 75 |
-
@app.route('/login', methods=['POST'])
|
| 76 |
-
def login():
|
| 77 |
-
data = request.json
|
| 78 |
-
email = data.get('email', '').strip().lower()
|
| 79 |
-
phone_number = data.get('phone_number', '').strip()
|
| 80 |
-
|
| 81 |
-
if not email or not phone_number:
|
| 82 |
-
return jsonify({'error': 'Missing email or phone number'}), 400
|
| 83 |
|
|
|
|
|
|
|
| 84 |
try:
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
user_data = result['records'][0]
|
| 92 |
-
session['user_id'] = user_data['Id']
|
| 93 |
-
session['name'] = user_data['Name']
|
| 94 |
-
|
| 95 |
-
return jsonify({'success': True, 'message': 'Login successful', 'user_id': user_data['Id'], 'name': user_data['Name']}), 200
|
| 96 |
-
|
| 97 |
except Exception as e:
|
| 98 |
-
return
|
| 99 |
|
| 100 |
-
#
|
| 101 |
-
@app.route("/
|
| 102 |
-
def
|
| 103 |
data = request.json
|
| 104 |
-
name = data.get('name'
|
| 105 |
-
email = data.get('email'
|
| 106 |
-
phone = data.get('phone'
|
| 107 |
|
| 108 |
if not name or not email or not phone:
|
| 109 |
return jsonify({'error': 'Missing data'}), 400
|
| 110 |
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
existing_user = sf.query(query)
|
| 114 |
|
| 115 |
-
|
| 116 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 117 |
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
'Email__c': email,
|
| 121 |
-
'Phone_Number__c': phone
|
| 122 |
-
})
|
| 123 |
|
| 124 |
-
|
| 125 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 126 |
else:
|
| 127 |
-
|
| 128 |
-
|
| 129 |
except Exception as e:
|
| 130 |
-
|
|
|
|
| 131 |
|
| 132 |
-
#
|
| 133 |
-
@app.route("/
|
| 134 |
-
def
|
| 135 |
-
|
| 136 |
-
return jsonify({"error": "No audio file provided"}), 400
|
| 137 |
-
|
| 138 |
-
audio_file = request.files["audio"]
|
| 139 |
-
input_audio_path = os.path.join("static", "temp_input.wav")
|
| 140 |
-
output_audio_path = os.path.join("static", "temp.wav")
|
| 141 |
-
audio_file.save(input_audio_path)
|
| 142 |
-
|
| 143 |
-
try:
|
| 144 |
-
convert_to_wav(input_audio_path, output_audio_path)
|
| 145 |
-
|
| 146 |
-
if is_silent_audio(output_audio_path):
|
| 147 |
-
return jsonify({"error": "No speech detected. Please try again."}), 400
|
| 148 |
-
|
| 149 |
-
result = pipeline("automatic-speech-recognition", model="openai/whisper-small", device=0 if torch.cuda.is_available() else -1, config=config)
|
| 150 |
-
transcribed_text = result(output_audio_path)["text"].strip().capitalize()
|
| 151 |
|
| 152 |
-
|
|
|
|
|
|
|
| 153 |
|
| 154 |
-
|
| 155 |
-
|
|
|
|
| 156 |
|
| 157 |
-
# Start
|
| 158 |
if __name__ == "__main__":
|
| 159 |
-
serve(app, host="0.0.0.0", port=7860)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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='diggavalli98@gmail.com', 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):
|
| 31 |
+
try:
|
| 32 |
+
audio = AudioSegment.from_file(input_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
|
| 61 |
+
name = data.get('name')
|
| 62 |
+
email = data.get('email')
|
| 63 |
+
phone = data.get('phone')
|
| 64 |
|
| 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)
|