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 | |
| import requests | |
| # 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() | |
| 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 | |
| if dietary_preference == 'veg': | |
| soql = "SELECT Name, Image_URL__c FROM Sector_Detail__c WHERE Category__c = 'Veg' LIMIT 200" | |
| elif dietary_preference == 'non-vegetarian': | |
| soql = "SELECT Name, Image_URL__c FROM Sector_Detail__c WHERE Category__c = 'Non-Veg' LIMIT 200" | |
| else: | |
| soql = "SELECT Name, Image_URL__c FROM Sector_Detail__c LIMIT 200" | |
| 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 | |
| ] | |
| return jsonify({"ingredients": ingredients}) | |
| except Exception as e: | |
| return jsonify({"error": f"Failed to fetch ingredients: {str(e)}"}), 500 | |
| # Endpoint to generate South Indian recipes using OpenAI ChatGPT | |
| def generate_recipes(): | |
| data = request.json | |
| selected_ingredients = data.get('ingredients', []) | |
| if not selected_ingredients: | |
| return jsonify({"error": "No ingredients selected"}), 400 | |
| api_key = os.getenv('CHATGPT_API_KEY') | |
| if not api_key: | |
| return jsonify({"error": "CHATGPT_API_KEY not configured in .env"}), 500 | |
| headers = { | |
| 'Authorization': f'Bearer {api_key}', | |
| 'Content-Type': 'application/json' | |
| } | |
| ingredients_str = ', '.join(selected_ingredients) | |
| prompt = f"Generate 5 authentic South Indian recipes using {ingredients_str}. For each recipe, provide: name, image_url (use placeholder like https://via.placeholder.com/100?text={{name}}), description (a short engaging summary), details (an object with preparation steps and key ingredients as a list). Return the response as a JSON array of recipe objects." | |
| payload = { | |
| 'model': 'gpt-3.5-turbo', | |
| 'messages': [{'role': 'user', 'content': prompt}], | |
| 'max_tokens': 500 | |
| } | |
| try: | |
| response = requests.post('https://api.openai.com/v1/chat/completions', headers=headers, json=payload) | |
| response.raise_for_status() | |
| result = response.json() | |
| content = result['choices'][0]['message']['content'] | |
| # Parse the ChatGPT response (assuming it returns JSON-like string) | |
| import json | |
| recipes = json.loads(content) # Adjust parsing based on actual ChatGPT output format | |
| return jsonify({"recipes": recipes}) | |
| except requests.exceptions.RequestException as e: | |
| return jsonify({"error": f"Failed to connect to ChatGPT API: {str(e)}"}), 500 | |
| except json.JSONDecodeError as e: | |
| return jsonify({"error": f"Failed to parse ChatGPT response: {str(e)}. Raw response: {content}"}), 500 | |
| if __name__ == '__main__': | |
| app.run(debug=True, host='0.0.0.0', port=7860) |