Spaces:
Sleeping
Sleeping
from flask import Flask, render_template, send_from_directory, request, jsonify | |
from simple_salesforce import Salesforce | |
from dotenv import load_dotenv | |
import os | |
from openai import OpenAI | |
# Load environment variables from .env file | |
load_dotenv() | |
app = Flask(__name__, template_folder='templates', static_folder='static') | |
# Function to get Salesforce connection | |
def get_salesforce_connection(): | |
try: | |
sf = Salesforce( | |
username=os.getenv('SFDC_USERNAME'), | |
password=os.getenv('SFDC_PASSWORD'), | |
security_token=os.getenv('SFDC_SECURITY_TOKEN'), | |
domain=os.getenv('SFDC_DOMAIN', 'login') | |
) | |
return sf | |
except Exception as e: | |
print(f"Error connecting to Salesforce: {e}") | |
return None | |
# Initialize Salesforce connection | |
sf = get_salesforce_connection() | |
# Initialize OpenAI client | |
openai_client = OpenAI(api_key=os.getenv('OPENAI_API_KEY')) | |
def index(): | |
return render_template('index.html') | |
def serve_static(filename): | |
return send_from_directory('static', filename) | |
def get_ingredients(): | |
global sf | |
if not sf: | |
sf = get_salesforce_connection() | |
if not sf: | |
return jsonify({"error": "Failed to connect to Salesforce"}), 500 | |
dietary_preference = request.json.get('dietary_preference', '').lower() | |
# SOQL query based on dietary preference with corrected field name 'Name' | |
if dietary_preference == 'veg': | |
soql = "SELECT Name FROM Sector_Detail__c WHERE Category__c IN ('Veg', 'Both') LIMIT 200" | |
elif dietary_preference == 'non-vegetarian': | |
soql = "SELECT Name FROM Sector_Detail__c WHERE Category__c IN ('Non-Veg', 'Both') LIMIT 200" | |
else: | |
soql = "SELECT Name FROM Sector_Detail__c LIMIT 200" | |
try: | |
result = sf.query(soql) | |
ingredients = [record['Name'] for record in result['records'] if 'Name' in record] | |
return jsonify({"ingredients": ingredients}) | |
except Exception as e: | |
return jsonify({"error": f"Failed to fetch ingredients: {str(e)}"}), 500 | |
def get_food_suggestions(): | |
selected_ingredients = request.json.get('ingredients', []) | |
if not selected_ingredients: | |
return jsonify({"error": "No ingredients selected"}), 400 | |
prompt = f"Suggest some food items using the following ingredients: {', '.join(selected_ingredients)}. Provide a list of 3-5 recipe ideas." | |
try: | |
response = openai_client.chat.completions.create( | |
model="gpt-3.5-turbo", # or "gpt-4" if you have access | |
messages=[ | |
{"role": "system", "content": "You are a helpful chef assistant."}, | |
{"role": "user", "content": prompt} | |
], | |
max_tokens=150 | |
) | |
suggestions = response.choices[0].message.content.strip().split('\n') | |
return jsonify({"suggestions": suggestions}) | |
except Exception as e: | |
return jsonify({"error": f"Failed to get food suggestions: {str(e)}"}), 500 | |
if __name__ == '__main__': | |
app.run(debug=True, host='0.0.0.0', port=7860) |