voicemenuspe / app.py
geethareddy's picture
Update app.py
2b2be90 verified
raw
history blame
4.92 kB
import torch
from flask import Flask, render_template, request, jsonify
import json
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 time
from waitress import serve
from simple_salesforce import Salesforce
import requests
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})
# Salesforce credentials (Replace with actual values)
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)
except Exception as e:
print(f"Failed to connect to Salesforce: {str(e)}")
# Function for Salesforce operations
def create_salesforce_record(name, email, phone_number):
try:
# Create a new record in Salesforce's Customer_Login__c object
customer_login = sf.Customer_Login__c.create({
'Name': name,
'Email__c': email,
'Phone_Number__c': phone_number
})
return customer_login
except SalesforceResourceNotFound as e:
raise Exception(f"Salesforce resource not found: {str(e)}")
except Exception as e:
raise Exception(f"Failed to create record: {str(e)}")
# Function for order handling
def create_order_in_salesforce(item_name, quantity, customer_id):
try:
# Create a new order in Salesforce's Order__c object
order_data = {
"Item__c": item_name, # Item__c is the field that stores the order item
"Quantity__c": quantity, # Quantity__c is the field that stores the order quantity
"Customer__c": customer_id # Customer__c is a lookup field that stores the related customer record ID
}
order = sf.Order__c.create(order_data)
return order
except Exception as e:
raise Exception(f"Failed to create order: {str(e)}")
# Routes and Views
@app.route("/")
def index():
return render_template("index.html")
@app.route("/dashboard", methods=["GET"])
def dashboard():
return render_template("dashboard.html")
@app.route('/submit', methods=['POST'])
def submit():
try:
data = request.get_json()
if not data:
return jsonify({"success": False, "message": "Invalid or empty JSON received"}), 400
# Get the values from the JSON data
name = data.get("name")
email = data.get("email")
phone = data.get("phone")
if not name or not email or not phone:
return jsonify({"success": False, "message": "Missing required fields"}), 400
# Prepare data for Salesforce submission
salesforce_data = {
"Name": name,
"Email__c": email,
"Phone_Number__c": phone
}
try:
result = sf.Customer_Login__c.create(salesforce_data)
print(f"Salesforce Response: {result}")
return jsonify({"success": True, "message": "Data submitted successfully"})
except Exception as e:
return jsonify({"success": False, "message": "Salesforce submission failed", "error": str(e)}), 500
except Exception as e:
return jsonify({"success": False, "message": "Internal server error", "error": str(e)}), 500
@app.route("/order", methods=["POST"])
def place_order():
try:
data = request.get_json()
item_name = data.get('item_name')
quantity = data.get('quantity')
customer_email = data.get('customer_email') # Assuming the customer email is passed for lookup
# Validate input
if not item_name or not quantity or not customer_email:
return jsonify({"success": False, "message": "Missing required fields"}), 400
# Query Salesforce to get customer ID by email
query = f"SELECT Id FROM Customer_Login__c WHERE Email__c = '{customer_email}'"
result = sf.query(query)
if not result['records']:
return jsonify({"success": False, "message": "Customer not found"}), 404
customer_id = result['records'][0]['Id']
# Create the order in Salesforce
order = create_order_in_salesforce(item_name, quantity, customer_id)
return jsonify({"success": True, "message": f"Order for {item_name} placed successfully", "order_id": order['Id']})
except Exception as e:
return jsonify({"success": False, "message": f"Error placing order: {str(e)}"}), 500
# Start Production Server
if __name__ == "__main__":
serve(app, host="0.0.0.0", port=7860)