AIVoiceLogin / app.py
DSatishchandra's picture
Update app.py
03d3dc9 verified
from flask import Flask, render_template, request, redirect, jsonify
import speech_recognition as sr
from gtts import gTTS
from simple_salesforce import Salesforce
import os
import logging
from io import BytesIO
# Initialize Flask app
app = Flask(__name__)
# Configure logging
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
# Salesforce connection setup with provided credentials
sf = Salesforce(username='diggavalli98@gmail.com', password='Sati@1020', security_token='sSSjyhInIsUohKpG8sHzty2q')
# Function to recognize speech and convert it to text
def recognize_speech():
recognizer = sr.Recognizer()
with sr.Microphone() as source:
try:
logging.info("Listening for input...")
audio = recognizer.listen(source)
recognized_text = recognizer.recognize_google(audio)
logging.info(f"Recognized Speech: {recognized_text}")
return recognized_text
except sr.UnknownValueError:
logging.error("Speech Recognition could not understand the audio.")
return "Sorry, I did not understand that."
except sr.RequestError as e:
logging.error(f"Could not request results from Google Speech Recognition service; {e}")
return "Sorry, there was an issue with the request."
# Function to speak text using gTTS
def speak(text):
try:
tts = gTTS(text=text, lang='en')
fp = BytesIO()
tts.save(fp)
fp.seek(0)
logging.info(f"Spoken Text: {text}")
return fp
except Exception as e:
logging.error(f"Error in TTS (Text-to-Speech): {str(e)}")
return None
@app.route('/', methods=['GET', 'POST'])
def start_interaction():
if request.method == 'POST':
# Log the form data
logging.debug(f"Form Submitted - Name: {request.form['name']}, Email: {request.form['email']}, Phone: {request.form['phone']}")
name = request.form['name']
email = request.form['email']
phone = request.form['phone']
# Save details to Salesforce using the Customer_Login__c object
try:
customer_login = sf.Customer_Login__c.create({
'Name': name,
'Email__c': email,
'Phone_Number__c': phone
})
logging.info("Successfully saved details to Salesforce.")
speak("Thank you! Your details have been saved successfully.")
return jsonify({"status": "success", "message": "Details saved successfully."})
except Exception as e:
logging.error(f"Error while saving to Salesforce: {str(e)}")
speak("Sorry, there was an error saving your details.")
return jsonify({"status": "error", "message": str(e)})
# If GET request, initiate voice interaction (TTS + Speech Recognition)
try:
speak("Hello, welcome to the restaurant! Please tell me your name.")
name = recognize_speech()
speak("Please tell me your email.")
email = recognize_speech()
speak("Please tell me your phone number.")
phone = recognize_speech()
# Log the recognized details
logging.debug(f"Captured Details - Name: {name}, Email: {email}, Phone: {phone}")
# Confirm details before saving
speak(f"Name: {name}. Email: {email}. Phone: {phone}. Is this correct?")
confirmation = recognize_speech()
if 'yes' in confirmation.lower():
# Save details to Salesforce using the Customer_Login__c object
try:
customer_login = sf.Customer_Login__c.create({
'Name': name,
'Email__c': email,
'Phone_Number__c': phone
})
logging.info("Successfully saved details to Salesforce.")
speak("Thank you! Your details have been saved successfully.")
return jsonify({"status": "success", "message": "Details saved successfully."})
except Exception as e:
logging.error(f"Error while saving to Salesforce: {str(e)}")
speak("Sorry, there was an error saving your details.")
return jsonify({"status": "error", "message": str(e)})
else:
speak("Please provide your details again.")
return redirect(url_for('start_interaction'))
except Exception as e:
logging.error(f"Error during the interaction: {str(e)}")
speak("Sorry, there was an issue with the interaction.")
return jsonify({"status": "error", "message": str(e)})
if __name__ == '__main__':
logging.info("Starting Flask App...")
app.run(host='0.0.0.0', port=5000, debug=True)