geethareddy commited on
Commit
e696e76
·
verified ·
1 Parent(s): 4056770

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +181 -64
app.py CHANGED
@@ -1,76 +1,193 @@
1
- from flask import Flask, render_template, request, jsonify
2
- from simple_salesforce import Salesforce
3
- from dotenv import load_dotenv
4
- import os
5
- import logging
6
 
7
- # Load environment variables from .env file
8
- load_dotenv()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
 
10
- # Set up logging
11
- logging.basicConfig(level=logging.INFO)
12
- logger = logging.getLogger(__name__)
 
 
13
 
14
- app = Flask(__name__, template_folder='templates', static_folder='static')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
 
16
- # Function to get Salesforce connection
17
- def get_salesforce_connection():
18
- try:
19
- sf = Salesforce(
20
- username=os.getenv('SFDC_USERNAME'),
21
- password=os.getenv('SFDC_PASSWORD'),
22
- security_token=os.getenv('SFDC_SECURITY_TOKEN'),
23
- domain=os.getenv('SFDC_DOMAIN', 'login')
24
- )
25
- logger.info("Successfully connected to Salesforce")
26
- return sf
27
- except Exception as e:
28
- logger.error(f"Error connecting to Salesforce: {e}")
29
- return None
30
 
31
- # Initialize Salesforce connection
32
- sf = get_salesforce_connection()
 
 
 
 
 
 
33
 
34
- @app.route('/')
35
- def index():
36
- return render_template('index.html')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
 
38
- @app.route('/get_ingredients', methods=['POST'])
39
- def get_ingredients():
40
- global sf
41
- if not sf:
42
- sf = get_salesforce_connection()
43
- if not sf:
44
- return jsonify({"error": "Failed to connect to Salesforce"}), 500
45
 
46
- dietary_preference = request.json.get('dietary_preference', '').lower()
47
-
48
- # Map dietary preference to SOQL condition
49
- preference_map = {
50
- 'vegetarian': "Category__c = 'Veg'",
51
- 'non-vegetarian': "Category__c = 'Non-Veg'",
52
- 'both': None # No condition to fetch all records, including "Both" category
53
  }
54
- condition = preference_map.get(dietary_preference)
55
 
56
- try:
57
- # Construct the base query
58
- soql = "SELECT Name, Image_URL__c, Category__c FROM Sector_Detail__c" # Added Category__c for debugging
59
- if condition:
60
- soql += f" WHERE {condition}"
61
- soql += " LIMIT 200"
62
 
63
- logger.info(f"Executing SOQL query: {soql}")
64
- result = sf.query(soql)
65
- ingredients = [
66
- {"name": record['Name'], "image_url": record.get('Image_URL__c', ''), "category": record.get('Category__c', 'Unknown')}
67
- for record in result['records'] if 'Name' in record
68
- ]
69
- logger.info(f"Fetched {len(ingredients)} ingredients: {ingredients}")
70
- return jsonify({"ingredients": ingredients})
71
- except Exception as e:
72
- logger.error(f"Failed to fetch ingredients: {str(e)}")
73
- return jsonify({"error": f"Failed to fetch ingredients: {str(e)}"}), 500
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74
 
75
- if __name__ == '__main__':
76
- app.run(debug=True, host='0.0.0.0', port=7860)
 
1
+ let conversation = [
2
+ { role: 'bot', message: 'Hi there! I\'m Chef Bot! May I know your name?' }
3
+ ];
4
+ let selectedIngredients = [];
 
5
 
6
+ function addMessage(role, message) {
7
+ const chatMessages = document.getElementById('chatMessages');
8
+ if (!chatMessages) {
9
+ console.error('Chat messages container not found!');
10
+ return;
11
+ }
12
+ const messageDiv = document.createElement('div');
13
+ messageDiv.className = role === 'bot' ? 'bot-message' : 'user-message';
14
+ messageDiv.textContent = message;
15
+ chatMessages.appendChild(messageDiv);
16
+ chatMessages.scrollTop = chatMessages.scrollHeight;
17
+ console.log(`Added ${role} message: ${message}`);
18
+ }
19
+
20
+ function sendMessage() {
21
+ const userInput = document.getElementById('userInput');
22
+ if (!userInput) {
23
+ console.error('User input field not found!');
24
+ return;
25
+ }
26
+ const message = userInput.value.trim();
27
+ if (message) {
28
+ addMessage('user', message);
29
+ conversation.push({ role: 'user', message: message });
30
+ userInput.value = '';
31
+ setTimeout(() => handleResponse(message), 500);
32
+ } else {
33
+ console.warn('Empty message!');
34
+ }
35
+ }
36
+
37
+ function handleResponse(userInput) {
38
+ const lastMessage = conversation[conversation.length - 1].message.toLowerCase();
39
+ let botResponse = '';
40
+ let options = [];
41
+
42
+ if (conversation.length === 2) { // After name input
43
+ botResponse = `Nice to meet you, ${userInput}! 😊 Let's create your perfect meal! What type of food would you prefer?`;
44
+ options = [
45
+ { text: 'Vegetarian', class: 'green' },
46
+ { text: 'Non-Vegetarian', class: 'red' },
47
+ { text: 'Both', class: 'gray' }
48
+ ];
49
+ } else if (lastMessage.includes('vegetarian') || lastMessage.includes('non-vegetarian') || lastMessage.includes('both')) {
50
+ botResponse = `Great choice! 🍽️ These are the available ingredients for ${lastMessage} (including any "Both" category):`;
51
+ fetchIngredients(lastMessage.toLowerCase());
52
+ return;
53
+ }
54
 
55
+ addMessage('bot', botResponse);
56
+ if (options.length > 0) {
57
+ displayOptions(options);
58
+ }
59
+ }
60
 
61
+ function fetchIngredients(dietaryPreference) {
62
+ fetch('/get_ingredients', {
63
+ method: 'POST',
64
+ headers: {
65
+ 'Content-Type': 'application/json',
66
+ },
67
+ body: JSON.stringify({ dietary_preference: dietaryPreference })
68
+ })
69
+ .then(response => response.json())
70
+ .then(data => {
71
+ if (data.error) {
72
+ addMessage('bot', `Sorry, there was an error fetching ingredients: ${data.error}`);
73
+ } else {
74
+ const ingredients = data.ingredients || [];
75
+ addMessage('bot', 'Great choice! These are available ingredients:');
76
+ displayIngredientsList(ingredients);
77
+ displaySelectedIngredients();
78
+ // Log ingredients to console for debugging
79
+ console.log(`Ingredients fetched for ${dietaryPreference}:`, ingredients);
80
+ }
81
+ })
82
+ .catch(error => {
83
+ addMessage('bot', `Error: Unable to connect to the ingredient database. ${error.message}`);
84
+ });
85
+ }
86
 
87
+ function displayIngredientsList(ingredients) {
88
+ const chatMessages = document.getElementById('chatMessages');
89
+ if (!chatMessages) {
90
+ console.error('Chat messages container not found for ingredients!');
91
+ return;
92
+ }
 
 
 
 
 
 
 
 
93
 
94
+ let ingredientsList = document.querySelector('.ingredients-list');
95
+ if (!ingredientsList) {
96
+ ingredientsList = document.createElement('div');
97
+ ingredientsList.className = 'ingredients-list';
98
+ chatMessages.appendChild(ingredientsList);
99
+ } else {
100
+ ingredientsList.innerHTML = '';
101
+ }
102
 
103
+ ingredients.forEach(ingredient => {
104
+ const item = document.createElement('div');
105
+ item.className = 'ingredient-item';
106
+ const img = document.createElement('img');
107
+ img.src = ingredient.image_url || 'https://via.placeholder.com/80';
108
+ img.alt = ingredient.name;
109
+ const name = document.createElement('div');
110
+ name.textContent = ingredient.name; // Removed category from display
111
+ name.style.textAlign = 'center';
112
+ name.style.marginTop = '5px';
113
+ name.style.fontSize = '12px';
114
+ const button = document.createElement('button');
115
+ button.textContent = 'Add';
116
+ button.onclick = () => {
117
+ if (!selectedIngredients.some(item => item.name === ingredient.name)) {
118
+ selectedIngredients.push(ingredient);
119
+ displaySelectedIngredients();
120
+ }
121
+ };
122
+ item.appendChild(img);
123
+ item.appendChild(name);
124
+ item.appendChild(button);
125
+ ingredientsList.appendChild(item);
126
+ });
127
+ }
128
 
129
+ function displaySelectedIngredients() {
130
+ const chatMessages = document.getElementById('chatMessages');
131
+ if (!chatMessages) {
132
+ console.error('Chat messages container not found for selected ingredients!');
133
+ return;
134
+ }
 
135
 
136
+ let selectedArea = document.querySelector('.selected-ingredients');
137
+ if (!selectedArea) {
138
+ selectedArea = document.createElement('div');
139
+ selectedArea.className = 'selected-ingredients';
140
+ chatMessages.appendChild(selectedArea);
141
+ } else {
142
+ selectedArea.innerHTML = '';
143
  }
 
144
 
145
+ selectedIngredients.forEach(ingredient => {
146
+ const div = document.createElement('div');
147
+ div.textContent = ingredient.name; // Removed category from display
148
+ selectedArea.appendChild(div);
149
+ });
150
+ }
151
 
152
+ function displayOptions(options) {
153
+ const chatMessages = document.getElementById('chatMessages');
154
+ if (!chatMessages) {
155
+ console.error('Chat messages container not found for options!');
156
+ return;
157
+ }
158
+ options.forEach(opt => {
159
+ const button = document.createElement('button');
160
+ button.textContent = opt.text;
161
+ button.className = `option-button ${opt.class}`;
162
+ button.onclick = () => {
163
+ addMessage('user', opt.text);
164
+ conversation.push({ role: 'user', message: opt.text });
165
+ chatMessages.innerHTML = ''; // Clear previous messages
166
+ conversation.forEach(msg => addMessage(msg.role, msg.message));
167
+ setTimeout(() => handleResponse(opt.text), 500);
168
+ };
169
+ chatMessages.appendChild(button);
170
+ });
171
+ chatMessages.appendChild(document.createElement('br'));
172
+ const backButton = document.createElement('button');
173
+ backButton.textContent = 'Go Back';
174
+ backButton.className = 'option-button';
175
+ backButton.onclick = () => {
176
+ conversation.pop(); // Remove last user input
177
+ selectedIngredients = []; // Clear selected ingredients
178
+ chatMessages.innerHTML = ''; // Clear previous messages
179
+ conversation.forEach(msg => addMessage(msg.role, msg.message));
180
+ setTimeout(() => handleResponse(conversation[conversation.length - 1].message), 500);
181
+ };
182
+ chatMessages.appendChild(backButton);
183
+ }
184
+
185
+ // Add event listener for Enter key
186
+ document.getElementById('userInput').addEventListener('keypress', function(e) {
187
+ if (e.key === 'Enter') {
188
+ sendMessage();
189
+ }
190
+ });
191
 
192
+ // Initial load check
193
+ console.log('Script loaded successfully');