chatbot2 / app.py
nagasurendra's picture
Update app.py
e255a05 verified
from flask import Flask, render_template, send_from_directory, request, jsonify
from simple_salesforce import Salesforce
from dotenv import load_dotenv
import os
import openai
openai.api_key = "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"
# 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()
@app.route('/')
def index():
return render_template('index.html')
@app.route('/static/<path:filename>')
def serve_static(filename):
return send_from_directory('static', filename)
@app.route('/get_ingredients', methods=['POST'])
def get_ingredients():
dietary_preference = request.json.get('dietary_preference', '').strip().lower()
# Debugging: print the received dietary preference
print(f"Received dietary preference: {dietary_preference}")
if dietary_preference == 'veg':
print("Fetching ingredients for Vegetarian...") # Debug when fetching vegetarian ingredients
soql = "SELECT Name, Image_URL__c FROM Sector_Detail__c WHERE Category__c IN ('Veg') LIMIT 200"
elif dietary_preference == 'non-vegetarian':
print("Fetching ingredients for Non-Vegetarian...") # Debug when fetching non-vegetarian ingredients
soql = "SELECT Name, Image_URL__c FROM Sector_Detail__c WHERE Category__c IN ('Non-Veg') LIMIT 200"
else:
print("Invalid dietary preference received.") # Debug for invalid dietary preference
return jsonify({"error": "Invalid dietary preference."}), 400
try:
result = sf.query(soql)
ingredients = [
{"name": record['Name'], "image_url": record.get('Image_URL__c', '')}
for record in result['records'] if 'Name' in record
]
print(f"Fetched {len(ingredients)} ingredients.") # Debug: print how many ingredients were fetched
return jsonify({"ingredients": ingredients})
except Exception as e:
print(f"Error while fetching ingredients: {str(e)}") # Debug error
return jsonify({"error": f"Failed to fetch ingredients: {str(e)}"}), 500
@app.route('/submit_ingredients', methods=['POST'])
def submit_ingredients():
data = request.json
ingredients = data.get('ingredients', [])
if not ingredients:
return jsonify({'error': 'No ingredients selected'}), 400
# You can now process the selected ingredients, store them in a database, etc.
print(f"Ingredients submitted: {ingredients}")
return jsonify({'success': True})
import logging
# Add this to the beginning of your Flask app file
logging.basicConfig(level=logging.DEBUG) # Enable debug-level logging
@app.route('/get_dish_suggestions', methods=['POST'])
def get_dish_suggestions():
selected_ingredients = request.json.get('ingredients', [])
if not selected_ingredients:
return jsonify({'error': 'No ingredients selected'}), 400
ingredients_text = ', '.join([ingredient['name'] for ingredient in selected_ingredients])
prompt = f"Suggest a recipe based on the following ingredients: {ingredients_text}"
try:
# Use the correct API structure for openai>=1.0.0
response = openai.Completion.create(
model="gpt-3.5-turbo",
prompt=prompt,
max_tokens=150,
temperature=0.7
)
dish_suggestions = response['choices'][0]['text'].strip()
return jsonify({"suggestions": dish_suggestions})
except Exception as e:
logging.error(f"Error in /get_dish_suggestions: {e}")
return jsonify({"error": f"Unexpected error: {str(e)}"}), 500
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0', port=7860)