Wajahat698 commited on
Commit
894aa78
·
verified ·
1 Parent(s): 46699e2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +32 -54
app.py CHANGED
@@ -1207,34 +1207,33 @@ def display_save_confirmation(type_saved):
1207
  # Function to update the message counter in a static location
1208
  message_counter_placeholder = st.sidebar.empty()
1209
 
1210
- def initialize_message_limit(user_id):
1211
- user_data = db.child("users").child(user_id).get().val()
1212
- if user_data:
1213
- st.session_state["message_limit"] = user_data.get("message_limit", INITIAL_MESSAGE_LIMIT)
1214
- st.session_state["used_messages"] = user_data.get("used_messages", 0)
1215
- else:
1216
- # Set default limits for new users and store them in Firebase
1217
- st.session_state["message_limit"] = INITIAL_MESSAGE_LIMIT
1218
- st.session_state["used_messages"] = 0
1219
- db.child("users").child(user_id).update({
1220
- "message_limit": INITIAL_MESSAGE_LIMIT,
1221
- "used_messages": 0
1222
- })
1223
-
1224
- def update_message_usage(user_id):
1225
- st.session_state["used_messages"] += 1
1226
- db.child("users").child(user_id).update({
1227
- "used_messages": st.session_state["used_messages"]
1228
- })
1229
- update_message_counter()
1230
  def update_message_counter():
1231
  remaining_messages = st.session_state["message_limit"] - st.session_state["used_messages"]
1232
  message_counter_placeholder.markdown(f"**Messages Left**: {remaining_messages} / {st.session_state['message_limit']}")
1233
 
1234
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1235
  if st.session_state.get("wix_user_id") and st.session_state.get("email"):
1236
- initialize_message_limit(st.session_state["wix_user_id"])
1237
- retrieve_user_data(st.session_state["wix_user_id"])
1238
  display_saved_trustbuilders()
1239
 
1240
  user_name = extract_name(st.session_state["email"])
@@ -1242,11 +1241,11 @@ if st.session_state.get("wix_user_id") and st.session_state.get("email"):
1242
  welcome_placeholder.info(f"**Hello, {user_name}!**")
1243
  time.sleep(3)
1244
  welcome_placeholder.empty()
1245
-
1246
-
1247
- update_message_counter()
1248
 
1249
- # Input for AI interaction
 
 
 
1250
  prompt = st.chat_input("")
1251
  global combined_text
1252
  if st.session_state["used_messages"] < st.session_state["message_limit"]:
@@ -1254,18 +1253,15 @@ if st.session_state.get("wix_user_id") and st.session_state.get("email"):
1254
  st.session_state.chat_started = True
1255
  st.session_state.chat_history.append({"role": "user", "content": prompt})
1256
 
1257
- # Check if the prompt is a memory query
1258
  memory_response = handle_memory_queries(prompt)
1259
  if memory_response:
1260
  with st.chat_message("assistant"):
1261
  st.markdown(memory_response)
1262
-
1263
  else:
1264
- # Detect if the user wants to save content based on chatbox prompts
1265
  save_as_trustbuilder = re.search(r"\b(save|add|store)\s*(this)?\s*(as)?\s*(trust\s*builder|trustbuilder)\b", prompt, re.IGNORECASE)
1266
  save_as_tonality = re.search(r"\b(save|add|store)\s*(this)?\s*(as)?\s*(brand\s*tonality|tonality)\b", prompt, re.IGNORECASE)
1267
 
1268
-
1269
  if save_as_trustbuilder or save_as_tonality:
1270
  user_id = st.session_state["wix_user_id"]
1271
  if save_as_trustbuilder:
@@ -1274,9 +1270,8 @@ if st.session_state.get("wix_user_id") and st.session_state.get("email"):
1274
  elif save_as_tonality:
1275
  store_brand_tonality(user_id, prompt)
1276
  display_save_confirmation("Brand Tonality")
1277
-
1278
  else:
1279
- # Generate a response with AI for other types of queries
1280
  with st.chat_message("user"):
1281
  st.markdown(prompt)
1282
  response_placeholder = st.empty()
@@ -1285,16 +1280,12 @@ if st.session_state.get("wix_user_id") and st.session_state.get("email"):
1285
  add_dot_typing_animation()
1286
  display_typing_indicator()
1287
  cleaned_text = ""
1288
- # Specialized responses if keywords detected
1289
  try:
1290
- #if "trustbuilder" in prompt.lower() or "trust" in prompt.lower():
1291
  output = agent_executor.invoke({
1292
- "input": f"{prompt}Be in natural tone,doesn’t use flowery language and typical ai words .Sources should be accurate.Avoid AI jargons.",
1293
- "chat_history": st.session_state.chat_history
1294
  })
1295
  full_response = output["output"]
1296
- #full_response= replace_terms(full_response)
1297
-
1298
  cleaned_text = clean_text(full_response)
1299
  trust_tip, suggestion = get_trust_tip_and_suggestion()
1300
  combined_text = f"{cleaned_text}\n\n---\n\n**Trust Tip**: {trust_tip}\n\n**Suggestion**: {suggestion}"
@@ -1302,19 +1293,6 @@ if st.session_state.get("wix_user_id") and st.session_state.get("email"):
1302
  with st.chat_message("assistant"):
1303
  st.markdown(combined_text, unsafe_allow_html=True)
1304
 
1305
- #else:
1306
- # llm = ChatOpenAI(model="gpt-4o", temperature=0.8)
1307
- # output = llm.invoke(prompt)
1308
- # full_response = output["output"]
1309
- #full_response= replace_terms(full_response)
1310
-
1311
- # cleaned_text = clean_text(full_response)
1312
- # trust_tip, suggestion = get_trust_tip_and_suggestion()
1313
- # combined_text = f"{cleaned_text}\n\n---\n\n**Trust Tip**: {trust_tip}\n\n**Suggestion**: {suggestion}"
1314
- # with response_placeholder:
1315
- # with st.chat_message("assistant"):
1316
- # st.markdown(combined_text, unsafe_allow_html=True)
1317
-
1318
  update_message_usage(st.session_state["wix_user_id"])
1319
 
1320
  except Exception as e:
@@ -1322,8 +1300,8 @@ if st.session_state.get("wix_user_id") and st.session_state.get("email"):
1322
  st.error("An error occurred while generating the response. Please try again.")
1323
 
1324
  st.session_state.chat_history.append({"role": "assistant", "content": cleaned_text})
1325
- copy_to_clipboard(cleaned_text)
1326
  else:
1327
  st.warning("You have reached your message limit. Please upgrade your plan to continue.")
1328
  else:
1329
- st.warning("Please log in to access the chatbot features.")
 
1207
  # Function to update the message counter in a static location
1208
  message_counter_placeholder = st.sidebar.empty()
1209
 
1210
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1211
  def update_message_counter():
1212
  remaining_messages = st.session_state["message_limit"] - st.session_state["used_messages"]
1213
  message_counter_placeholder.markdown(f"**Messages Left**: {remaining_messages} / {st.session_state['message_limit']}")
1214
 
1215
+ def initialize_user_data(wix_user_id):
1216
+ response = requests.get(f"{backend_url}/check-user/{wix_user_id}")
1217
+ if response.status_code == 200:
1218
+ data = response.json()
1219
+ st.session_state["message_limit"] = data.get("message_limit", 100) # Default limit is 100
1220
+ st.session_state["used_messages"] = data.get("used_messages", 0)
1221
+ update_message_counter()
1222
+ else:
1223
+ st.error("Error fetching user data.")
1224
+
1225
+ # Update message usage in Firebase after each interaction
1226
+ def update_message_usage(wix_user_id):
1227
+ response = requests.post(f"{backend_url}/update-message-usage/{wix_user_id}")
1228
+ if response.status_code == 200:
1229
+ st.session_state["used_messages"] += 1
1230
+ update_message_counter()
1231
+ else:
1232
+ st.error("Error updating message usage.")
1233
+
1234
+ # Main interface
1235
  if st.session_state.get("wix_user_id") and st.session_state.get("email"):
1236
+ retrieve_user_data(st.session_state["wix_user_id"]) # Fetch and display saved data for the user
 
1237
  display_saved_trustbuilders()
1238
 
1239
  user_name = extract_name(st.session_state["email"])
 
1241
  welcome_placeholder.info(f"**Hello, {user_name}!**")
1242
  time.sleep(3)
1243
  welcome_placeholder.empty()
 
 
 
1244
 
1245
+ # Initialize the user's message limit and usage from Firebase
1246
+ initialize_user_data(st.session_state["wix_user_id"])
1247
+
1248
+ # Input field for chatbot interaction
1249
  prompt = st.chat_input("")
1250
  global combined_text
1251
  if st.session_state["used_messages"] < st.session_state["message_limit"]:
 
1253
  st.session_state.chat_started = True
1254
  st.session_state.chat_history.append({"role": "user", "content": prompt})
1255
 
1256
+ # Handle save commands based on the user prompt
1257
  memory_response = handle_memory_queries(prompt)
1258
  if memory_response:
1259
  with st.chat_message("assistant"):
1260
  st.markdown(memory_response)
 
1261
  else:
 
1262
  save_as_trustbuilder = re.search(r"\b(save|add|store)\s*(this)?\s*(as)?\s*(trust\s*builder|trustbuilder)\b", prompt, re.IGNORECASE)
1263
  save_as_tonality = re.search(r"\b(save|add|store)\s*(this)?\s*(as)?\s*(brand\s*tonality|tonality)\b", prompt, re.IGNORECASE)
1264
 
 
1265
  if save_as_trustbuilder or save_as_tonality:
1266
  user_id = st.session_state["wix_user_id"]
1267
  if save_as_trustbuilder:
 
1270
  elif save_as_tonality:
1271
  store_brand_tonality(user_id, prompt)
1272
  display_save_confirmation("Brand Tonality")
 
1273
  else:
1274
+ # Generate a response with AI for general queries
1275
  with st.chat_message("user"):
1276
  st.markdown(prompt)
1277
  response_placeholder = st.empty()
 
1280
  add_dot_typing_animation()
1281
  display_typing_indicator()
1282
  cleaned_text = ""
 
1283
  try:
 
1284
  output = agent_executor.invoke({
1285
+ "input": f"{prompt} Be in natural tone, avoid AI jargon, and provide accurate sources.",
1286
+ "chat_history": st.session_state.chat_history
1287
  })
1288
  full_response = output["output"]
 
 
1289
  cleaned_text = clean_text(full_response)
1290
  trust_tip, suggestion = get_trust_tip_and_suggestion()
1291
  combined_text = f"{cleaned_text}\n\n---\n\n**Trust Tip**: {trust_tip}\n\n**Suggestion**: {suggestion}"
 
1293
  with st.chat_message("assistant"):
1294
  st.markdown(combined_text, unsafe_allow_html=True)
1295
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1296
  update_message_usage(st.session_state["wix_user_id"])
1297
 
1298
  except Exception as e:
 
1300
  st.error("An error occurred while generating the response. Please try again.")
1301
 
1302
  st.session_state.chat_history.append({"role": "assistant", "content": cleaned_text})
1303
+ copy_to_clipboard(cleaned_text)
1304
  else:
1305
  st.warning("You have reached your message limit. Please upgrade your plan to continue.")
1306
  else:
1307
+ st.warning("Please log in to access the chatbot features.")