Swathi6 commited on
Commit
990ad0c
·
verified ·
1 Parent(s): 5b36b7c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +221 -50
app.py CHANGED
@@ -1,57 +1,228 @@
1
- from flask import Flask, request, jsonify
2
- from transformers import pipeline, set_seed
 
 
 
3
 
4
- app = Flask(__name__)
 
5
 
6
- # Initialize the Hugging Face text-generation pipeline (DialoGPT model)
7
- chatbot = pipeline("text-generation", model="microsoft/DialoGPT-medium")
8
- set_seed(42)
9
 
10
- # Example restaurant data
11
- menu = {
12
- 'vegan': ['Vegan Burger', 'Tofu Stir Fry', 'Veggie Pizza'],
13
- 'vegetarian': ['Cheese Pizza', 'Pasta Alfredo', 'Caprese Salad'],
14
- 'non_vegetarian': ['Chicken Curry', 'Grilled Salmon', 'Steak'],
15
- 'spicy': ['Spicy Tacos', 'Chili Chicken', 'Spicy Wings'],
16
- }
 
 
 
 
 
 
 
 
 
 
 
 
17
 
18
  @app.route('/')
19
- def home():
20
- return "Welcome to the Restaurant Chatbot API!"
21
-
22
- @app.route('/chat', methods=['POST'])
23
- def chat():
24
- # Get user input from the frontend
25
- user_input = request.json.get('user_input', '')
26
-
27
- # Add user input to the conversation history (we'll use a simple list to store history)
28
- conversation_history = user_input
29
-
30
- # Generate a response from the chatbot model using text generation
31
- response = chatbot(conversation_history, max_length=100, num_return_sequences=1, pad_token_id=50256)
32
-
33
- # Get the chatbot's response text
34
- chatbot_reply = response[0]['generated_text']
35
-
36
- # Match user preference to the menu (based on keywords in the input)
37
- user_preference = None
38
- if 'vegan' in user_input.lower():
39
- user_preference = 'vegan'
40
- elif 'vegetarian' in user_input.lower():
41
- user_preference = 'vegetarian'
42
- elif 'non-vegetarian' in user_input.lower():
43
- user_preference = 'non_vegetarian'
44
- elif 'spicy' in user_input.lower():
45
- user_preference = 'spicy'
46
-
47
- # Get menu suggestions based on user preference
48
- menu_suggestion = menu.get(user_preference, [])
49
-
50
- # Return the chatbot response and menu suggestion
51
- return jsonify({
52
- 'bot_response': chatbot_reply,
53
- 'menu_suggestion': menu_suggestion
54
- })
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55
 
56
  if __name__ == '__main__':
57
- app.run(debug=True)
 
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
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
+ # Salesforce connection function
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
+ # Fetch items from Sector_Detail__c for dietary preferences
39
+ @app.route('/get_menu_items', methods=['POST'])
40
+ def get_menu_items():
41
+ global sf
42
+ if not sf:
43
+ sf = get_salesforce_connection()
44
+ if not sf:
45
+ logger.error("Salesforce connection failed after retry")
46
+ return jsonify({"error": "Unable to connect to Salesforce"}), 500
47
+
48
+ dietary_preference = request.json.get('dietary_preference', 'both').lower()
49
+ try:
50
+ soql = "SELECT Name, Image_URL__c, Category__c, Description__c FROM Sector_Detail__c"
51
+ if dietary_preference == 'vegetarian':
52
+ soql += " WHERE Category__c = 'Veg'"
53
+ elif dietary_preference == 'non-vegetarian':
54
+ soql += " WHERE Category__c = 'Non-Veg'"
55
+ soql += " LIMIT 200"
56
+
57
+ logger.info(f"Executing SOQL query: {soql}")
58
+ result = sf.query(soql)
59
+ items = [
60
+ {
61
+ "name": record['Name'],
62
+ "image_url": record.get('Image_URL__c', ''),
63
+ "category": record.get('Category__c', ''),
64
+ "description": record.get('Description__c', 'No description available')
65
+ }
66
+ for record in result['records'] if 'Name' in record
67
+ ]
68
+ logger.info(f"Fetched {len(items)} items from Sector_Detail__c for {dietary_preference}")
69
+ return jsonify({"menu_items": items})
70
+ except Exception as e:
71
+ logger.error(f"Failed to fetch items from Sector_Detail__c: {str(e)}")
72
+ return jsonify({"error": f"Failed to fetch items from Salesforce: {str(e)}"}), 500
73
+
74
+ # Fetch suggestions from Ingredient_Object__c
75
+ @app.route('/suggest_items', methods=['POST'])
76
+ def suggest_items():
77
+ global sf
78
+ if not sf:
79
+ sf = get_salesforce_connection()
80
+ if not sf:
81
+ return jsonify({"error": "Unable to connect to Salesforce"}), 500
82
+
83
+ search_term = request.json.get('search_term', '').strip()
84
+ if not search_term:
85
+ return jsonify({"error": "Search term is required"}), 400
86
+
87
+ try:
88
+ soql = f"SELECT Ingredient_Name__c, Image_URL__c FROM Ingredient_Object__c WHERE Ingredient_Name__c LIKE '%{search_term}%' LIMIT 10"
89
+ logger.info(f"Executing SOQL query: {soql}")
90
+ result = sf.query(soql)
91
+ suggestions = [
92
+ {"name": record['Ingredient_Name__c'], "image_url": record.get('Image_URL__c', '')}
93
+ for record in result['records'] if 'Ingredient_Name__c' in record
94
+ ]
95
+ logger.info(f"Fetched {len(suggestions)} suggestions for '{search_term}'")
96
+ return jsonify({"suggestions": suggestions})
97
+ except Exception as e:
98
+ logger.error(f"Failed to fetch suggestions: {str(e)}")
99
+ return jsonify({"error": "Failed to fetch suggestions from Salesforce"}), 500
100
+
101
+ # Fetch item details from Ingredient_Object__c
102
+ @app.route('/get_item_details', methods=['POST'])
103
+ def get_item_details():
104
+ global sf
105
+ if not sf:
106
+ sf = get_salesforce_connection()
107
+ if not sf:
108
+ return jsonify({"error": "Unable to connect to Salesforce"}), 500
109
+
110
+ item_name = request.json.get('item_name', '').strip()
111
+ if not item_name:
112
+ return jsonify({"error": "Item name is required"}), 400
113
+
114
+ try:
115
+ soql = f"SELECT Ingredient_Name__c, Image_URL__c FROM Ingredient_Object__c WHERE Ingredient_Name__c LIKE '%{item_name}%' LIMIT 1"
116
+ logger.info(f"Executing SOQL query: {soql}")
117
+ result = sf.query(soql)
118
+
119
+ if result['totalSize'] == 0:
120
+ return jsonify({"error": f"No item found matching '{item_name}' in Ingredient_Object__c"}), 404
121
+
122
+ record = result['records'][0]
123
+ item_details = {
124
+ "name": record.get('Ingredient_Name__c', ''),
125
+ "image_url": record.get('Image_URL__c', '')
126
+ }
127
+ logger.info(f"Fetched details for '{item_name}'")
128
+ return jsonify({"item_details": item_details})
129
+ except Exception as e:
130
+ logger.error(f"Failed to fetch item details: {str(e)}")
131
+ return jsonify({"error": "Failed to fetch item details from Salesforce"}), 500
132
+
133
+ # Fetch item details from Sector_Detail__c by name
134
+ @app.route('/get_item_details_by_name', methods=['POST'])
135
+ def get_item_details_by_name():
136
+ global sf
137
+ if not sf:
138
+ sf = get_salesforce_connection()
139
+ if not sf:
140
+ return jsonify({"error": "Unable to connect to Salesforce"}), 500
141
+
142
+ item_name = request.json.get('item_name', '').strip()
143
+ if not item_name:
144
+ return jsonify({"error": "Item name is required"}), 400
145
+
146
+ try:
147
+ soql = f"SELECT Name, Category__c, Description__c FROM Sector_Detail__c WHERE Name LIKE '%{item_name}%' LIMIT 1"
148
+ logger.info(f"Executing SOQL query: {soql}")
149
+ result = sf.query(soql)
150
+
151
+ if result['totalSize'] == 0:
152
+ return jsonify({"error": f"No item found matching '{item_name}' in Sector_Detail__c"}), 404
153
+
154
+ record = result['records'][0]
155
+ item_details = {
156
+ "name": record.get('Name', ''),
157
+ "category": record.get('Category__c', 'Unknown'),
158
+ "description": record.get('Description__c', 'No description available')
159
+ }
160
+ logger.info(f"Fetched details for '{item_name}' from Sector_Detail__c")
161
+ return jsonify({"item_details": item_details})
162
+ except Exception as e:
163
+ logger.error(f"Failed to fetch item details from Sector_Detail__c: {str(e)}")
164
+ return jsonify({"error": f"Failed to fetch item details from Salesforce: {str(e)}"}), 500
165
+
166
+ # Fetch item details (Name, Image_URL, Category, Description) from Sector_Detail__c by name
167
+ @app.route('/get_sector_item_details', methods=['POST'])
168
+ def get_sector_item_details():
169
+ global sf
170
+ if not sf:
171
+ sf = get_salesforce_connection()
172
+ if not sf:
173
+ return jsonify({"error": "Unable to connect to Salesforce"}), 500
174
+
175
+ item_name = request.json.get('item_name', '').strip()
176
+ if not item_name:
177
+ return jsonify({"error": "Item name is required"}), 400
178
+
179
+ try:
180
+ soql = f"SELECT Name, Image_URL__c, Category__c, Description__c FROM Sector_Detail__c WHERE Name LIKE '%{item_name}%' LIMIT 1"
181
+ logger.info(f"Executing SOQL query: {soql}")
182
+ result = sf.query(soql)
183
+
184
+ if result['totalSize'] == 0:
185
+ return jsonify({"error": f"No item found matching '{item_name}' in Sector_Detail__c"}), 404
186
+
187
+ record = result['records'][0]
188
+ item_details = {
189
+ "name": record.get('Name', ''),
190
+ "image_url": record.get('Image_URL__c', 'https://via.placeholder.com/30'),
191
+ "category": record.get('Category__c', 'Unknown'),
192
+ "description": record.get('Description__c', 'No description available')
193
+ }
194
+ logger.info(f"Fetched details for '{item_name}' from Sector_Detail__c")
195
+ return jsonify({"item_details": item_details})
196
+ except Exception as e:
197
+ logger.error(f"Failed to fetch item details from Sector_Detail__c: {str(e)}")
198
+ return jsonify({"error": f"Failed to fetch item details from Salesforce: {str(e)}"}), 500
199
+
200
+ # Submit selected items to Ingredient_Object__c
201
+ @app.route('/submit_items', methods=['POST'])
202
+ def submit_items():
203
+ global sf
204
+ if not sf:
205
+ sf = get_salesforce_connection()
206
+ if not sf:
207
+ return jsonify({"error": "Unable to connect to Salesforce"}), 500
208
+
209
+ items = request.json.get('items', [])
210
+ if not items:
211
+ return jsonify({"error": "No items to submit"}), 400
212
+
213
+ try:
214
+ for item in items:
215
+ logger.info(f"Submitting item: {item}")
216
+ sf.Ingredient_Object__c.create({
217
+ 'Ingredient_Name__c': item['name'],
218
+ 'Category__c': item.get('category', 'Unknown'), # Add Category__c
219
+ 'Description__c': item.get('description', 'No description available') # Ensure description is included
220
+ })
221
+ logger.info(f"Successfully submitted item to Ingredient_Object__c: {item['name']}")
222
+ return jsonify({"success": f"Successfully submitted {len(items)} items to Salesforce"})
223
+ except Exception as e:
224
+ logger.error(f"Failed to submit items: {str(e)}")
225
+ return jsonify({"error": f"Failed to submit items to Salesforce: {str(e)}"}), 500
226
 
227
  if __name__ == '__main__':
228
+ app.run(debug=True, host='0.0.0.0', port=7860)