SuhasGholkar commited on
Commit
e91c7ca
·
verified ·
1 Parent(s): a54e347

Update src/chat.py

Browse files
Files changed (1) hide show
  1. src/chat.py +97 -76
src/chat.py CHANGED
@@ -624,41 +624,70 @@ def _render_turn(h):
624
  # CHAT UI
625
  # =========================
626
  def render_chat_tab(conn):
627
- import streamlit as st
628
- from datetime import datetime
629
  import time
630
- # ... keep your imports and INTENTS etc.
 
 
 
631
 
 
632
  ss = st.session_state
633
- # --- session state init ---
634
- if "history" not in ss:
635
- ss.history = []
636
- if "user_input" not in ss:
637
- ss.user_input = ""
638
- if "show_history" not in ss:
639
- ss.show_history = False
640
-
641
- # ---------- HEADER ----------
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
642
  st.title("💬 Ecomm Chatbot")
643
 
644
- # ---------- CONTROLS ----------
645
- # IMPORTANT: checkbox OUTSIDE the form so it toggles immediately
646
  st.checkbox(
647
  "Show conversation history (this session)",
648
  key="show_history",
649
- help="Toggle to instantly show/hide the messages below.",
650
  )
651
 
652
- # ---------- INPUT FORM ----------
653
  with st.form("chat_form", clear_on_submit=True):
654
  user_text = st.text_input("You:", key="user_input")
655
  submitted = st.form_submit_button("Submit", type="primary")
656
 
657
- # ---------- ON SUBMIT ----------
658
  if submitted and user_text.strip():
659
- start_time = time.time()
660
- current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
661
-
662
  #Translate to English if needed (Hindi input)
663
  try:
664
  text_en = ensure_english(user_text)
@@ -669,8 +698,8 @@ def render_chat_tab(conn):
669
  except Exception as e:
670
  logging.warning("Exception in detect_lang: fallback to original due to: %s", e)
671
  logger.info(f"Translated Text ={text_en} Source Language = {src_lang}")
672
-
673
- # 1) intent + sentiment (your existing functions)
674
  cls = gpt_classify_intent(text_en)
675
  intent = cls.get("intent", "UNMAPPED")
676
  confidence = cls.get("confidence", 0.0)
@@ -679,7 +708,7 @@ def render_chat_tab(conn):
679
 
680
  sentiment = gpt_classify_sentiment(text_en)
681
 
682
- # keyword guardrail
683
  if intent != "UNMAPPED" and not _has_overlap(intent, text_en):
684
  intent = "UNMAPPED"
685
 
@@ -687,23 +716,26 @@ def render_chat_tab(conn):
687
  table_cols, table_rows = None, None
688
 
689
  if intent == "UNMAPPED":
690
- meta = gpt_label_unmapped(text_en)
691
- intent = meta # store meta label
692
- bot_reply = gpt_fallback_response(text_en)
693
  resolution = "Responded"
694
  else:
695
- # 2) extract + process params
696
  params = gpt_extract_params(intent, text_en)
697
  params = process_params(intent, params)
698
 
699
- # 3) required params check
700
  required = INTENTS[intent]["required"]
701
  missing = [p for p in required if not params.get(p)]
702
-
703
  if missing:
704
- bot_reply = f"Could you please provide the following information: {', '.join(missing)}"
 
 
 
705
  resolution = "Unresolved"
706
  else:
 
707
  rows, col_names, sql_query, sql_params = run_intent(conn, intent, params)
708
  if rows:
709
  table_cols, table_rows = col_names, rows
@@ -713,7 +745,7 @@ def render_chat_tab(conn):
713
  bot_reply = "No data found."
714
  resolution = "Unresolved"
715
 
716
- ftr_ms = round((time.time() - start_time) * 1000, 2)
717
 
718
  # Apply Hindi translation if input language was Hindi
719
  display_reply = bot_reply
@@ -723,6 +755,7 @@ def render_chat_tab(conn):
723
  logger.exception("Failed to detect langauge: %s", e)
724
  src_lang == ENG
725
 
 
726
  if src_lang == HINDI:
727
  try:
728
  display_reply = en_to_lang(bot_reply)
@@ -731,10 +764,9 @@ def render_chat_tab(conn):
731
  logging.warning("Exception in en_to_lang due to: %s", e)
732
  display_reply = bot_reply
733
 
734
-
735
- # 4) show + save (append to session history)
736
- entry = {
737
- "timestamp": current_time,
738
  "user": user_text,
739
  "intent": intent,
740
  "sentiment": sentiment,
@@ -744,57 +776,46 @@ def render_chat_tab(conn):
744
  "table_cols": table_cols,
745
  "table_rows": table_rows,
746
  }
747
- ss.history.append(entry)
 
 
 
 
 
748
  if len(ss.history) > 50:
749
  ss.history.pop(0)
750
 
751
- # persist with user_id
752
- uid = ss["user"]["id"]
753
  try:
754
- save_chat_to_db(
755
- conn,
756
- user_id=uid,
757
- user_message=user_text,
758
- bot_reply=display_reply,
759
- intent=intent,
760
- sentiment=sentiment,
761
- resolution=resolution,
762
- ftr_ms=ftr_ms,
763
- sql_query=sql_query,
764
- sql_params=sql_params if intent in INTENTS else {},
765
- )
 
 
766
  except Exception as e:
767
  logger.exception("Failed to save chat: %s", e)
768
 
769
- # optionally re-render tables/replies for the latest exchange here
770
- # (leave your existing display code)
 
 
771
 
772
- # ---------- RENDER HISTORY (independent of submit) ----------
773
  if ss.show_history and ss.history:
774
  st.markdown("### Conversation")
775
- # add spacing between messages for readability
776
- for h in ss.history:
777
- st.markdown(f"**{h['timestamp']}**")
778
- st.markdown(f"**Customer:** {h['user']}")
779
- st.markdown("**Platform Analysis**")
780
- c1, c2, c3, c4 = st.columns([1,1,1,1])
781
- with c1:
782
- st.write(f"**Intent:** {h['intent']}")
783
- with c2:
784
- st.write(f"**Sentiment:** {h['sentiment']}")
785
- with c3:
786
- st.write(f"**Resolution:** {h['resolution']}")
787
- with c4:
788
- st.write(f"**Latency:** {h['ftr_ms']} ms")
789
-
790
- if h["table_cols"] and h["table_rows"]:
791
- st.dataframe(
792
- pd.DataFrame(h["table_rows"], columns=h["table_cols"]),
793
- use_container_width=True,
794
- )
795
-
796
- st.markdown(f"**Support Agent:** {h['reply']}")
797
- st.markdown("---")
798
 
799
  def render_user_export_tab(conn, user_id: int):
800
  st.subheader("Export My Chats")
 
624
  # CHAT UI
625
  # =========================
626
  def render_chat_tab(conn):
 
 
627
  import time
628
+ from datetime import datetime
629
+ import pandas as pd
630
+ import streamlit as st
631
+ import logging
632
 
633
+ logger = logging.getLogger(__name__)
634
  ss = st.session_state
635
+
636
+ # ---------- Session state init ----------
637
+ ss.setdefault("history", []) # list of exchanges (dicts)
638
+ ss.setdefault("last_exchange", None) # last exchange dict
639
+ ss.setdefault("show_history", False) # toggle for history visibility
640
+ ss.setdefault("user_input", "") # input buffer
641
+
642
+ # ---------- Small helpers ----------
643
+ def _render_exchange(ex):
644
+ """One nicely formatted exchange (customer + platform analysis + table + agent)."""
645
+ st.markdown(f"**{ex['timestamp']}**")
646
+ st.markdown(f"**Customer:** {ex['user']}")
647
+ # Platform analysis strip
648
+ c1, c2, c3, c4 = st.columns([1, 1, 1, 1])
649
+ with c1:
650
+ st.write(f"**Intent:** {ex.get('intent', '-')}")
651
+ with c2:
652
+ st.write(f"**Sentiment:** {ex.get('sentiment', '-')}")
653
+ with c3:
654
+ st.write(f"**Resolution:** {ex.get('resolution', '-')}")
655
+ with c4:
656
+ st.write(f"**Latency:** {ex.get('ftr_ms', 0)} ms")
657
+
658
+ # Optional table
659
+ if ex.get("table_cols") and ex.get("table_rows"):
660
+ try:
661
+ df = pd.DataFrame(ex["table_rows"], columns=ex["table_cols"])
662
+ st.dataframe(df, use_container_width=True)
663
+ except Exception:
664
+ # If the shape doesn't match, just skip rendering the grid
665
+ pass
666
+
667
+ # Agent reply
668
+ st.markdown(f"**Support Agent:** {ex.get('reply', '')}")
669
+ st.markdown("---")
670
+
671
+ # ---------- Page UI ----------
672
  st.title("💬 Ecomm Chatbot")
673
 
674
+ # Checkbox OUTSIDE the form so it toggles instantly
 
675
  st.checkbox(
676
  "Show conversation history (this session)",
677
  key="show_history",
678
+ help="Toggle to instantly show/hide the full conversation below.",
679
  )
680
 
681
+ # Input form (Enter submits here)
682
  with st.form("chat_form", clear_on_submit=True):
683
  user_text = st.text_input("You:", key="user_input")
684
  submitted = st.form_submit_button("Submit", type="primary")
685
 
686
+ # ---------- On submit, run the pipeline and show latest immediately ----------
687
  if submitted and user_text.strip():
688
+ start = time.time()
689
+ now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
690
+
691
  #Translate to English if needed (Hindi input)
692
  try:
693
  text_en = ensure_english(user_text)
 
698
  except Exception as e:
699
  logging.warning("Exception in detect_lang: fallback to original due to: %s", e)
700
  logger.info(f"Translated Text ={text_en} Source Language = {src_lang}")
701
+
702
+ # 1) intent + sentiment
703
  cls = gpt_classify_intent(text_en)
704
  intent = cls.get("intent", "UNMAPPED")
705
  confidence = cls.get("confidence", 0.0)
 
708
 
709
  sentiment = gpt_classify_sentiment(text_en)
710
 
711
+ # Guardrail: if keyword overlap fails, demote to UNMAPPED
712
  if intent != "UNMAPPED" and not _has_overlap(intent, text_en):
713
  intent = "UNMAPPED"
714
 
 
716
  table_cols, table_rows = None, None
717
 
718
  if intent == "UNMAPPED":
719
+ meta = gpt_label_unmapped(text_en) # optional coarse label
720
+ intent = meta
721
+ bot_reply = gpt_fallback_response(user_text)
722
  resolution = "Responded"
723
  else:
724
+ # 2) extract + clean params
725
  params = gpt_extract_params(intent, text_en)
726
  params = process_params(intent, params)
727
 
728
+ # 3) check required params
729
  required = INTENTS[intent]["required"]
730
  missing = [p for p in required if not params.get(p)]
 
731
  if missing:
732
+ bot_reply = (
733
+ "Could you please provide the following information: "
734
+ + ", ".join(missing)
735
+ )
736
  resolution = "Unresolved"
737
  else:
738
+ # 4) run SQL / compute results
739
  rows, col_names, sql_query, sql_params = run_intent(conn, intent, params)
740
  if rows:
741
  table_cols, table_rows = col_names, rows
 
745
  bot_reply = "No data found."
746
  resolution = "Unresolved"
747
 
748
+ ftr_ms = round((time.time() - start) * 1000, 2)
749
 
750
  # Apply Hindi translation if input language was Hindi
751
  display_reply = bot_reply
 
755
  logger.exception("Failed to detect langauge: %s", e)
756
  src_lang == ENG
757
 
758
+
759
  if src_lang == HINDI:
760
  try:
761
  display_reply = en_to_lang(bot_reply)
 
764
  logging.warning("Exception in en_to_lang due to: %s", e)
765
  display_reply = bot_reply
766
 
767
+ # Build exchange object
768
+ ex = {
769
+ "timestamp": now,
 
770
  "user": user_text,
771
  "intent": intent,
772
  "sentiment": sentiment,
 
776
  "table_cols": table_cols,
777
  "table_rows": table_rows,
778
  }
779
+
780
+ # Save as the latest so it renders RIGHT NOW
781
+ ss.last_exchange = ex
782
+
783
+ # Append to rolling history (limit 50)
784
+ ss.history.append(ex)
785
  if len(ss.history) > 50:
786
  ss.history.pop(0)
787
 
788
+ # Persist to DB
 
789
  try:
790
+ uid = ss.get("user", {}).get("id")
791
+ if uid:
792
+ save_chat_to_db(
793
+ conn,
794
+ user_id=uid,
795
+ user_message=user_text,
796
+ bot_reply=display_reply,
797
+ intent=intent,
798
+ sentiment=sentiment,
799
+ resolution=resolution,
800
+ ftr_ms=ftr_ms,
801
+ sql_query=sql_query,
802
+ sql_params=sql_params if intent in INTENTS else {},
803
+ )
804
  except Exception as e:
805
  logger.exception("Failed to save chat: %s", e)
806
 
807
+ # ---------- Always show the latest exchange (if any), regardless of history toggle ----------
808
+ if ss.last_exchange:
809
+ st.markdown("### Latest")
810
+ _render_exchange(ss.last_exchange)
811
 
812
+ # ---------- Show full conversation only if the toggle is ON ----------
813
  if ss.show_history and ss.history:
814
  st.markdown("### Conversation")
815
+ # To avoid duplicate if latest already shown, skip the last item
816
+ upto = len(ss.history) - 1 if ss.last_exchange else len(ss.history)
817
+ for i in range(upto):
818
+ _render_exchange(ss.history[i])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
819
 
820
  def render_user_export_tab(conn, user_id: int):
821
  st.subheader("Export My Chats")