voicemenu1433 / app.py
DSatishchandra's picture
Update app.py
e107b41 verified
raw
history blame
8.03 kB
import torch
from flask import Flask, render_template, request, jsonify
import os
from transformers import pipeline
from gtts import gTTS
from pydub import AudioSegment
from pydub.silence import detect_nonsilent
from transformers import AutoConfig # Import AutoConfig for the config object
import time
from waitress import serve
from simple_salesforce import Salesforce
import requests # Import requests for exception handling
app = Flask(__name__)
# Use whisper-small for faster processing and better speed
device = "cuda" if torch.cuda.is_available() else "cpu"
# Create config object to set timeout and other parameters
config = AutoConfig.from_pretrained("openai/whisper-small")
config.update({"timeout": 60}) # Set timeout to 60 seconds
# Your function where you generate and save the audio
def generate_audio_prompt(text, filename):
try:
tts = gTTS(text)
tts.save(os.path.join("static", filename))
except gtts.tts.gTTSError as e:
print(f"Error: {e}")
print("Retrying after 5 seconds...")
time.sleep(5) # Wait for 5 seconds before retrying
generate_audio_prompt(text, filename)
# Generate required voice prompts
prompts = {
"welcome": "Welcome to Biryani Hub.",
"ask_name": "Tell me your name.",
"ask_email": "Please provide your email address.",
"thank_you": "Thank you for registration."
}
for key, text in prompts.items():
generate_audio_prompt(text, f"{key}.mp3")
# Symbol mapping for proper recognition
SYMBOL_MAPPING = {
"at the rate": "@",
"at": "@",
"dot": ".",
"underscore": "_",
"hash": "#",
"plus": "+",
"dash": "-",
"comma": ",",
"space": " "
}
# Function to convert audio to WAV format
def convert_to_wav(input_path, output_path):
try:
audio = AudioSegment.from_file(input_path)
audio = audio.set_frame_rate(16000).set_channels(1) # Convert to 16kHz, mono
audio.export(output_path, format="wav")
except Exception as e:
print(f"Error: {str(e)}")
raise Exception(f"Audio conversion failed: {str(e)}")
# Function to check if audio contains actual speech
def is_silent_audio(audio_path):
audio = AudioSegment.from_wav(audio_path)
nonsilent_parts = detect_nonsilent(audio, min_silence_len=500, silence_thresh=audio.dBFS-16) # Reduced silence duration
print(f"Detected nonsilent parts: {nonsilent_parts}")
return len(nonsilent_parts) == 0 # If no speech detected
# Salesforce connection details
try:
print("Attempting to connect to Salesforce...")
sf = Salesforce(username='[email protected]', password='Sati@1020', security_token='sSSjyhInIsUohKpG8sHzty2q')
print("Connected to Salesforce successfully!")
print("User Info:", sf.UserInfo) # Log the user info to verify the connection
except Exception as e:
print(f"Failed to connect to Salesforce: {str(e)}")
# Function to create Salesforce record
def create_salesforce_record(name, email, phone_number):
try:
# Attempt to create a record in Salesforce with correct field API names
customer_login = sf.Customer_Login__c.create({
'Name': name, # Standard field (name)
'Email__c': email, # Custom email field
'Phone_Number__c': phone_number # Custom phone number field
})
# Log the full response from Salesforce
print(f"Salesforce response: {customer_login}")
# Check if the response contains an ID (successful creation)
if 'id' in customer_login:
print(f"Record created successfully with ID: {customer_login['id']}")
return customer_login
else:
# Log detailed information if the record creation failed
print(f"Record creation failed. Full response: {customer_login}")
# Log any errors if the response contains 'errors'
if 'errors' in customer_login:
print(f"Salesforce errors: {customer_login['errors']}")
return {"error": f"Record creation failed. Full response: {customer_login}"}
except Exception as e:
# Catch and log any exceptions during record creation
error_message = str(e)
print(f"Error creating Salesforce record: {error_message}")
return {"error": f"Failed to create record in Salesforce: {error_message}"}
# Correct the indentation here
@app.route("/submit", methods=["POST"])
def submit():
data = request.json
name = data.get('name')
email = data.get('email')
phone = data.get('phone')
if not name or not email or not phone:
return jsonify({'error': 'Missing data'}), 400
try:
# Create Salesforce record
customer_login = sf.Customer_Login__c.create({
'Name': name,
'Email__c': email,
'Phone_Number__c': phone
})
if customer_login.get('id'):
return jsonify({'success': True})
else:
return jsonify({'error': 'Failed to create record'}), 500
except Exception as e:
return jsonify({'error': str(e)}), 500
@app.route("/")
def index():
return render_template("index.html")
@app.route("/transcribe", methods=["POST"])
def transcribe():
if "audio" not in request.files:
print("No audio file provided")
return jsonify({"error": "No audio file provided"}), 400
audio_file = request.files["audio"]
input_audio_path = os.path.join("static", "temp_input.wav")
output_audio_path = os.path.join("static", "temp.wav")
audio_file.save(input_audio_path)
try:
# Convert to WAV
convert_to_wav(input_audio_path, output_audio_path)
# Check for silence
if is_silent_audio(output_audio_path):
return jsonify({"error": "No speech detected. Please try again."}), 400
else:
print("Audio contains speech, proceeding with transcription.")
# Use Whisper ASR model for transcription
result = None
retry_attempts = 3
for attempt in range(retry_attempts):
try:
result = pipeline("automatic-speech-recognition", model="openai/whisper-small", device=0 if torch.cuda.is_available() else -1, config=config)
print(f"Transcribed text: {result['text']}")
break
except requests.exceptions.ReadTimeout:
print(f"Timeout occurred, retrying attempt {attempt + 1}/{retry_attempts}...")
time.sleep(5)
if result is None:
return jsonify({"error": "Unable to transcribe audio after retries."}), 500
transcribed_text = result["text"].strip().capitalize()
print(f"Transcribed text: {transcribed_text}")
# Extract name, email, and phone number from the transcribed text
parts = transcribed_text.split()
name = parts[0] if len(parts) > 0 else "Unknown Name"
email = parts[1] if '@' in parts[1] else "[email protected]"
phone_number = parts[2] if len(parts) > 2 else "0000000000"
print(f"Parsed data - Name: {name}, Email: {email}, Phone Number: {phone_number}")
# Create record in Salesforce
salesforce_response = create_salesforce_record(name, email, phone_number)
# Log the Salesforce response
print(f"Salesforce record creation response: {salesforce_response}")
# Check if the response contains an error
if "error" in salesforce_response:
print(f"Error creating record in Salesforce: {salesforce_response['error']}")
return jsonify(salesforce_response), 500
# If creation was successful, return the details
return jsonify({"text": transcribed_text, "salesforce_record": salesforce_response})
except Exception as e:
print(f"Error in transcribing or processing: {str(e)}")
return jsonify({"error": f"Speech recognition error: {str(e)}"}), 500
# Start Production Server
if __name__ == "__main__":
serve(app, host="0.0.0.0", port=7860)