lokesh341 commited on
Commit
cd44447
·
verified ·
1 Parent(s): 7469ad2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +4 -135
app.py CHANGED
@@ -6,7 +6,6 @@ import logging
6
  import uuid
7
  from datetime import datetime
8
 
9
-
10
  # Load environment variables
11
  load_dotenv()
12
 
@@ -28,95 +27,12 @@ def get_salesforce_connection():
28
  logger.info("Successfully connected to Salesforce")
29
  return sf
30
  except Exception as e:
31
- logger.error(f"Error connecting to Salesforce: {e}")
32
  return None
33
 
34
  # Initialize Salesforce connection
35
  sf = get_salesforce_connection()
36
 
37
- # Initialize OpenAI client
38
- openai_api_key = os.getenv('OPENAI_API_KEY')
39
- if not openai_api_key:
40
- logger.error("OPENAI_API_KEY not found in .env. ChatGPT functionality disabled.")
41
- client = None
42
- else:
43
- try:
44
- client = OpenAI(api_key=openai_api_key)
45
- test_response = client.chat.completions.create(
46
- model="gpt-3.5-turbo",
47
- messages=[{"role": "user", "content": "Test API key"}]
48
- )
49
- logger.info("OpenAI API key validated successfully")
50
- except Exception as e:
51
- logger.error(f"Invalid OpenAI API key or connection issue: {e}")
52
- client = None
53
-
54
- # Conversation storage
55
- conversation_sessions = {}
56
-
57
- def is_restaurant_related(query):
58
- keywords = ['use', 'uses', 'dish', 'recipe', 'ingredient', 'food', 'menu', 'vegetarian', 'non-vegetarian',
59
- 'rice', 'chicken', 'pasta', 'veggie', 'mutton', 'lamb', 'beef', 'pork', 'fish', 'seafood',
60
- 'ingredients', 'nutrition', 'nutritional', 'info', 'message', 'messages']
61
- return bool(query.strip() and any(keyword in query.lower() for keyword in keywords)) or any(item in query.lower() for item in ['mutton', 'rice', 'chicken'])
62
-
63
- def get_chatgpt_response(prompt, session_id):
64
- if not client:
65
- logger.warning("No OpenAI client available, using mock ChatGPT response")
66
- if any(item in prompt.lower() for item in ['mutton', 'rice', 'chicken']):
67
- return f"{prompt.capitalize()} is great for curries or roasts in a restaurant!"
68
- return "I can help with food! Try 'uses of mutton' or 'ingredients for rice'."
69
-
70
- if session_id not in conversation_sessions:
71
- conversation_sessions[session_id] = [
72
- {"role": "system", "content": "You are a restaurant culinary assistant. Respond only to queries about ingredients, dishes, or recipes. Provide concise, friendly answers. For unclear queries, suggest: 'Try 'uses of mutton' or 'ingredients for rice'.'"}
73
- ]
74
-
75
- prompt = prompt.strip().lower()
76
- logger.info(f"Processing prompt: {prompt}")
77
- if not is_restaurant_related(prompt):
78
- logger.info(f"Off-topic or empty query: {prompt}")
79
- return "I can help with food! Try 'uses of mutton' or 'ingredients for rice'."
80
-
81
- intent = "uses"
82
- item = prompt
83
- if "what is the use of" in prompt or "uses of" in prompt:
84
- item = prompt.replace("what is the use of ", "").replace("uses of ", "").strip() or prompt
85
- prompt = f"Provide the culinary uses of '{item}' for a restaurant. Be concise and friendly. If unknown, say 'Great for many dishes!'"
86
- elif any(word in prompt for word in ['suggest', 'recipe', 'dish']):
87
- intent = "suggest"
88
- prompt = f"Suggest a restaurant dish based on: {prompt}. Include ingredients and be concise."
89
- elif any(word in prompt for word in ['ingredients', 'ingredient']):
90
- intent = "ingredients"
91
- item = prompt.replace("ingredients for ", "").replace("ingredient of ", "").strip() or prompt
92
- prompt = f"List common ingredients for a restaurant dish using '{item}'. Be concise and realistic."
93
- elif any(word in prompt for word in ['nutrition', 'nutritional', 'info']):
94
- intent = "nutrition"
95
- item = prompt.replace("nutrition of ", "").replace("nutritional info for ", "").strip() or prompt
96
- prompt = f"Provide a concise, approximate nutritional overview (calories, protein, fat, carbs) for a restaurant portion of '{item}'. Use general culinary knowledge and keep it friendly."
97
- elif any(item in prompt for item in ['mutton', 'rice', 'chicken', 'pasta', 'veggie', 'lamb', 'beef', 'pork', 'fish', 'seafood']):
98
- prompt = f"Provide the culinary uses of '{item}' for a restaurant. Be concise and friendly. If unknown, say 'Great for many dishes!'"
99
- else:
100
- logger.info(f"Unclear intent, defaulting to uses for: {prompt}")
101
- prompt = f"Provide the culinary uses of '{prompt}' for a restaurant. Be concise and friendly. If unknown, say 'Great for many dishes!'"
102
-
103
- conversation_sessions[session_id].append({"role": "user", "content": prompt})
104
-
105
- try:
106
- response = client.chat.completions.create(
107
- model="gpt-3.5-turbo",
108
- messages=conversation_sessions[session_id],
109
- max_tokens=150,
110
- timeout=10
111
- )
112
- reply = response.choices[0].message.content.strip()
113
- conversation_sessions[session_id].append({"role": "assistant", "content": reply})
114
- logger.info(f"ChatGPT response for '{prompt}': {reply}")
115
- return reply
116
- except Exception as e:
117
- logger.error(f"OpenAI API error: {e}")
118
- return f"Sorry, API failed. Mock response: {prompt.capitalize()} is great for curries or roasts!"
119
-
120
  @app.route('/')
121
  def index():
122
  return render_template('index.html')
@@ -156,11 +72,11 @@ def get_menu_items():
156
  for record in result_sector['records'] if 'Name' in record
157
  ]
158
  items.extend(sector_items)
159
-
160
  # Query Menu_Item__c
161
  soql_menu = "SELECT Name, Description__c, Image1__c, Ingredientsinfo__c, NutritionalInfo__c, Price__c, Sector__c, Spice_Levels__c, Veg_NonVeg__c, Category__c, Dynamic_Dish__c FROM Menu_Item__c"
162
  if search_term:
163
- soql_menu += f" WHERE Name LIKE '%{search_term}%' OR Ingredientsinfo__c LIKE '%{search_term}%'"
164
  elif dietary_preference == 'vegetarian':
165
  soql_menu += " WHERE Veg_NonVeg__c = 'Vegetarian'"
166
  elif dietary_preference == 'non-vegetarian':
@@ -236,7 +152,7 @@ def suggest_items():
236
  return jsonify({"error": "Unable to connect to Salesforce"}), 500
237
 
238
  search_term = request.json.get('search_term', '').strip()
239
- if not search_term:
240
  return jsonify({"error": "Search term is required"}), 400
241
 
242
  try:
@@ -318,52 +234,5 @@ def submit_items():
318
  logger.error(f"Failed to submit items: {str(e)}")
319
  return jsonify({"error": f"Failed to submit items: {str(e)}"}), 500
320
 
321
- @app.route('/get_item_info', methods=['POST'])
322
- def get_item_info():
323
- global sf, client
324
- item_name = request.json.get('item_name', '').strip()
325
- if not item_name or not client:
326
- return jsonify({"error": "Item name required or OpenAI unavailable"}), 400
327
-
328
- try:
329
- soql = f"SELECT Name, Description__c FROM Sector_Detail__c WHERE Name LIKE '%{item_name}%' LIMIT 1"
330
- result = sf.query(soql)
331
- if result['totalSize'] == 0:
332
- return jsonify({"error": f"No item found matching '{item_name}' in Sector_Detail__c"}), 404
333
-
334
- record = result['records'][0]
335
- base_info = record.get('Description__c', 'No description available')
336
-
337
- prompt = f"Based on general culinary knowledge, provide a concise list of common ingredients and an approximate nutritional overview (calories, protein, fat, carbs) for a restaurant portion of '{item_name}'. Use realistic values and keep it friendly."
338
- response = client.chat.completions.create(
339
- model="gpt-3.5-turbo",
340
- messages=[{"role": "user", "content": prompt}],
341
- max_tokens=150,
342
- timeout=10
343
- )
344
- ai_response = response.choices[0].message.content.strip()
345
-
346
- item_info = {
347
- "name": record['Name'],
348
- "description": base_info,
349
- "details": ai_response
350
- }
351
- logger.info(f"Generated info for '{item_name}'")
352
- return jsonify({"item_info": item_info})
353
- except Exception as e:
354
- logger.error(f"Failed to get item info: {str(e)}")
355
- return jsonify({"error": f"Failed to get item info: {str(e)}"}), 500
356
-
357
- @app.route('/chat', methods=['POST'])
358
- def chat():
359
- user_message = request.json.get('message', '').strip()
360
- session_id = request.json.get('session_id', 'default')
361
- if not user_message:
362
- return jsonify({"error": "No message provided"}), 400
363
-
364
- response = get_chatgpt_response(user_message, session_id)
365
- logger.info(f"Chat response sent: {response}")
366
- return jsonify({"response": response})
367
-
368
  if __name__ == '__main__':
369
  app.run(debug=True, host='0.0.0.0', port=7860)
 
6
  import uuid
7
  from datetime import datetime
8
 
 
9
  # Load environment variables
10
  load_dotenv()
11
 
 
27
  logger.info("Successfully connected to Salesforce")
28
  return sf
29
  except Exception as e:
30
+ logger.error(f"Error connecting to Salesforce: {str(e)}")
31
  return None
32
 
33
  # Initialize Salesforce connection
34
  sf = get_salesforce_connection()
35
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
  @app.route('/')
37
  def index():
38
  return render_template('index.html')
 
72
  for record in result_sector['records'] if 'Name' in record
73
  ]
74
  items.extend(sector_items)
75
+
76
  # Query Menu_Item__c
77
  soql_menu = "SELECT Name, Description__c, Image1__c, Ingredientsinfo__c, NutritionalInfo__c, Price__c, Sector__c, Spice_Levels__c, Veg_NonVeg__c, Category__c, Dynamic_Dish__c FROM Menu_Item__c"
78
  if search_term:
79
+ soql_menu += f" WHERE Name LIKE '%{search_term}%'"
80
  elif dietary_preference == 'vegetarian':
81
  soql_menu += " WHERE Veg_NonVeg__c = 'Vegetarian'"
82
  elif dietary_preference == 'non-vegetarian':
 
152
  return jsonify({"error": "Unable to connect to Salesforce"}), 500
153
 
154
  search_term = request.json.get('search_term', '').strip()
155
+ if not item_name:
156
  return jsonify({"error": "Search term is required"}), 400
157
 
158
  try:
 
234
  logger.error(f"Failed to submit items: {str(e)}")
235
  return jsonify({"error": f"Failed to submit items: {str(e)}"}), 500
236
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
237
  if __name__ == '__main__':
238
  app.run(debug=True, host='0.0.0.0', port=7860)