Spaces:
Sleeping
Sleeping
Update src/chat.py
Browse files- src/chat.py +125 -149
src/chat.py
CHANGED
|
@@ -544,7 +544,6 @@ def save_chat_to_db(conn, user_id, user_message, bot_reply,
|
|
| 544 |
# =========================
|
| 545 |
def render_chat_tab(conn):
|
| 546 |
"""Full Ecomm chatbot with intents + SQL, scoped to current user."""
|
| 547 |
-
import hashlib, json
|
| 548 |
import time
|
| 549 |
from datetime import datetime
|
| 550 |
import pandas as pd
|
|
@@ -552,163 +551,139 @@ def render_chat_tab(conn):
|
|
| 552 |
|
| 553 |
st.title("💬 Ecomm Chatbot")
|
| 554 |
|
| 555 |
-
# ---------- session state ----------
|
| 556 |
ss = st.session_state
|
| 557 |
ss.setdefault("history", [])
|
| 558 |
-
ss.setdefault("
|
| 559 |
-
ss.setdefault("user_input", "")
|
| 560 |
-
ss.setdefault("last_hash", None) # used to avoid duplicate appends
|
| 561 |
-
|
| 562 |
-
# clear text box after submit
|
| 563 |
-
if ss.clear_input:
|
| 564 |
-
ss.user_input = ""
|
| 565 |
-
ss.clear_input = False
|
| 566 |
-
|
| 567 |
-
# ---------- input + controls ----------
|
| 568 |
-
user_input = st.text_input("You:", key="user_input")
|
| 569 |
-
|
| 570 |
-
ctrl1, ctrl2 = st.columns([3, 1])
|
| 571 |
-
with ctrl1:
|
| 572 |
-
show_hist = st.checkbox(
|
| 573 |
-
"Show conversation history (this session)",
|
| 574 |
-
key="show_hist_checkbox",
|
| 575 |
-
value=False,
|
| 576 |
-
)
|
| 577 |
-
with ctrl2:
|
| 578 |
-
if st.button("Clear session history"):
|
| 579 |
-
ss.history = []
|
| 580 |
-
ss.last_hash = None
|
| 581 |
-
st.toast("History cleared")
|
| 582 |
-
|
| 583 |
-
# ---------- submit ----------
|
| 584 |
-
if st.button("Submit"):
|
| 585 |
-
if ss.user_input.strip():
|
| 586 |
-
user_text = ss.user_input
|
| 587 |
-
start_time = time.time()
|
| 588 |
-
current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
| 589 |
-
|
| 590 |
-
#Translate to English if needed (Hindi input)
|
| 591 |
-
try:
|
| 592 |
-
text_en = ensure_english(user_text)
|
| 593 |
-
except Exception as e:
|
| 594 |
-
logging.warning("Exception in ensure_english: fallback to original due to: %s", e)
|
| 595 |
-
try:
|
| 596 |
-
src_lang = detect_lang(user_text)
|
| 597 |
-
except Exception as e:
|
| 598 |
-
logging.warning("Exception in detect_lang: fallback to original due to: %s", e)
|
| 599 |
-
logger.info(f"Translated Text ={text_en} Source Language = {src_lang}")
|
| 600 |
-
|
| 601 |
-
# 1) intent + sentiment
|
| 602 |
-
cls = gpt_classify_intent(text_en)
|
| 603 |
-
intent = cls.get("intent", "UNMAPPED")
|
| 604 |
-
confidence = cls.get("confidence", 0.0)
|
| 605 |
-
reason = cls.get("reason", "")
|
| 606 |
-
logger.info(f"intent={intent} conf={confidence} reason={reason}")
|
| 607 |
-
|
| 608 |
-
sentiment = gpt_classify_sentiment(text_en)
|
| 609 |
-
|
| 610 |
-
# keyword guardrail
|
| 611 |
-
if intent != "UNMAPPED" and not _has_overlap(intent, text_en):
|
| 612 |
-
intent = "UNMAPPED"
|
| 613 |
-
|
| 614 |
-
sql_query, sql_params = "", {}
|
| 615 |
-
table_cols, table_rows = None, None
|
| 616 |
-
|
| 617 |
-
if intent == "UNMAPPED":
|
| 618 |
-
meta = gpt_label_unmapped(text_en)
|
| 619 |
-
intent = meta # store meta label
|
| 620 |
-
bot_reply = gpt_fallback_response(text_en)
|
| 621 |
-
resolution = "Responded"
|
| 622 |
-
else:
|
| 623 |
-
# 2) extract + process params
|
| 624 |
-
params = gpt_extract_params(intent, text_en)
|
| 625 |
-
params = process_params(intent, params)
|
| 626 |
|
| 627 |
-
|
| 628 |
-
|
| 629 |
-
|
|
|
|
|
|
|
|
|
|
| 630 |
|
| 631 |
-
|
| 632 |
-
|
| 633 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 634 |
else:
|
| 635 |
-
|
| 636 |
-
|
| 637 |
-
table_cols, table_rows = col_names, rows
|
| 638 |
-
bot_reply = "Please see the table above for results."
|
| 639 |
-
resolution = "Resolved"
|
| 640 |
-
else:
|
| 641 |
-
bot_reply = "No data found."
|
| 642 |
-
resolution = "Unresolved"
|
| 643 |
-
|
| 644 |
-
ftr_ms = round((time.time() - start_time) * 1000, 2)
|
| 645 |
-
|
| 646 |
-
# Apply Hindi translation if input language was Hindi
|
| 647 |
-
display_reply = bot_reply
|
| 648 |
-
try:
|
| 649 |
-
src_lang = detect_lang(user_text)
|
| 650 |
-
except Exception as e:
|
| 651 |
-
logger.exception("Failed to detect langauge: %s", e)
|
| 652 |
-
src_lang == ENG
|
| 653 |
-
|
| 654 |
-
if src_lang == HINDI:
|
| 655 |
-
try:
|
| 656 |
-
display_reply = en_to_lang(bot_reply)
|
| 657 |
-
logger.info(f"response from BOT is ={bot_reply} Source Language is = {src_lang} display_reply is = {display_reply}")
|
| 658 |
-
except Exception:
|
| 659 |
-
logging.warning("Exception in en_to_lang due to: %s", e)
|
| 660 |
-
display_reply = bot_reply
|
| 661 |
-
|
| 662 |
-
# 4) show + save (with a dedupe guard)
|
| 663 |
-
entry = {
|
| 664 |
-
"timestamp": current_time,
|
| 665 |
-
"user": user_text,
|
| 666 |
-
"intent": intent,
|
| 667 |
-
"sentiment": sentiment,
|
| 668 |
-
"resolution": resolution,
|
| 669 |
-
"reply": display_reply,
|
| 670 |
-
"ftr_ms": ftr_ms,
|
| 671 |
-
"table_cols": table_cols,
|
| 672 |
-
"table_rows": table_rows,
|
| 673 |
-
}
|
| 674 |
-
# hash of the entry => stops accidental double-append on reruns
|
| 675 |
-
h = hashlib.md5(json.dumps(entry, sort_keys=True, default=str).encode("utf-8")).hexdigest()
|
| 676 |
-
if ss.get("last_hash") != h:
|
| 677 |
-
ss.history.append(entry)
|
| 678 |
-
ss.last_hash = h
|
| 679 |
-
if len(ss.history) > 50:
|
| 680 |
-
ss.history.pop(0)
|
| 681 |
-
|
| 682 |
-
# persist with user_id
|
| 683 |
-
uid = ss["user"]["id"]
|
| 684 |
-
try:
|
| 685 |
-
save_chat_to_db(
|
| 686 |
-
conn,
|
| 687 |
-
user_id=uid,
|
| 688 |
-
user_message=user_text,
|
| 689 |
-
bot_reply=display_reply,
|
| 690 |
-
intent=intent,
|
| 691 |
-
sentiment=sentiment,
|
| 692 |
-
resolution=resolution,
|
| 693 |
-
ftr_ms=ftr_ms,
|
| 694 |
-
sql_query=sql_query,
|
| 695 |
-
sql_params=sql_params if intent in INTENTS else {},
|
| 696 |
-
)
|
| 697 |
-
except Exception as e:
|
| 698 |
-
logger.exception("Failed to save chat: %s", e)
|
| 699 |
|
| 700 |
-
|
| 701 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 702 |
try:
|
| 703 |
-
|
|
|
|
| 704 |
except Exception:
|
| 705 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 706 |
|
| 707 |
-
# ---
|
| 708 |
st.markdown("### Conversation")
|
| 709 |
|
| 710 |
-
# If history is
|
| 711 |
-
feed = ss.history if
|
| 712 |
|
| 713 |
for h in feed:
|
| 714 |
# Customer bubble
|
|
@@ -722,7 +697,7 @@ def render_chat_tab(conn):
|
|
| 722 |
unsafe_allow_html=True,
|
| 723 |
)
|
| 724 |
|
| 725 |
-
#
|
| 726 |
with st.container(border=True):
|
| 727 |
st.markdown(
|
| 728 |
f"""
|
|
@@ -737,7 +712,7 @@ def render_chat_tab(conn):
|
|
| 737 |
unsafe_allow_html=True,
|
| 738 |
)
|
| 739 |
|
| 740 |
-
# Optional table
|
| 741 |
if h.get("table_rows"):
|
| 742 |
try:
|
| 743 |
df = pd.DataFrame(h["table_rows"], columns=h["table_cols"])
|
|
@@ -756,6 +731,7 @@ def render_chat_tab(conn):
|
|
| 756 |
unsafe_allow_html=True,
|
| 757 |
)
|
| 758 |
|
|
|
|
| 759 |
# renderer
|
| 760 |
def _render_turn(turn):
|
| 761 |
ts = turn["timestamp"]
|
|
|
|
| 544 |
# =========================
|
| 545 |
def render_chat_tab(conn):
|
| 546 |
"""Full Ecomm chatbot with intents + SQL, scoped to current user."""
|
|
|
|
| 547 |
import time
|
| 548 |
from datetime import datetime
|
| 549 |
import pandas as pd
|
|
|
|
| 551 |
|
| 552 |
st.title("💬 Ecomm Chatbot")
|
| 553 |
|
|
|
|
| 554 |
ss = st.session_state
|
| 555 |
ss.setdefault("history", [])
|
| 556 |
+
ss.setdefault("show_history", False)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 557 |
|
| 558 |
+
# --- Show/Hide history lives OUTSIDE the form so it updates immediately ---
|
| 559 |
+
ss.show_history = st.checkbox(
|
| 560 |
+
"Show conversation history (this session)",
|
| 561 |
+
value=ss.get("show_history", False),
|
| 562 |
+
key="chat_show_hist",
|
| 563 |
+
)
|
| 564 |
|
| 565 |
+
# --- Input form (submit clears the box automatically) ---
|
| 566 |
+
with st.form("chat_form", clear_on_submit=True):
|
| 567 |
+
user_text = st.text_input("You:", key="chat_user_input")
|
| 568 |
+
submitted = st.form_submit_button("Submit")
|
| 569 |
+
|
| 570 |
+
# --- Handle submit ---
|
| 571 |
+
if submitted and user_text.strip():
|
| 572 |
+
start_time = time.time()
|
| 573 |
+
current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
| 574 |
+
|
| 575 |
+
#Translate to English if needed (Hindi input)
|
| 576 |
+
try:
|
| 577 |
+
text_en = ensure_english(user_text)
|
| 578 |
+
except Exception as e:
|
| 579 |
+
logging.warning("Exception in ensure_english: fallback to original due to: %s", e)
|
| 580 |
+
try:
|
| 581 |
+
src_lang = detect_lang(user_text)
|
| 582 |
+
except Exception as e:
|
| 583 |
+
logging.warning("Exception in detect_lang: fallback to original due to: %s", e)
|
| 584 |
+
logger.info(f"Translated Text ={text_en} Source Language = {src_lang}")
|
| 585 |
+
|
| 586 |
+
# 1) intent + sentiment
|
| 587 |
+
cls = gpt_classify_intent(text_en)
|
| 588 |
+
intent = cls.get("intent", "UNMAPPED")
|
| 589 |
+
confidence = cls.get("confidence", 0.0)
|
| 590 |
+
reason = cls.get("reason", "")
|
| 591 |
+
logger.info(f"intent={intent} conf={confidence} reason={reason}")
|
| 592 |
+
|
| 593 |
+
sentiment = gpt_classify_sentiment(text_en)
|
| 594 |
+
|
| 595 |
+
# keyword guardrail
|
| 596 |
+
if intent != "UNMAPPED" and not _has_overlap(intent, text_en):
|
| 597 |
+
intent = "UNMAPPED"
|
| 598 |
+
|
| 599 |
+
sql_query, sql_params = "", {}
|
| 600 |
+
table_cols, table_rows = None, None
|
| 601 |
+
|
| 602 |
+
if intent == "UNMAPPED":
|
| 603 |
+
meta = gpt_label_unmapped(text_en)
|
| 604 |
+
intent = meta # store meta label
|
| 605 |
+
bot_reply = gpt_fallback_response(text_en)
|
| 606 |
+
resolution = "Responded"
|
| 607 |
+
else:
|
| 608 |
+
# 2) extract + process params
|
| 609 |
+
params = gpt_extract_params(intent, text_en)
|
| 610 |
+
params = process_params(intent, params)
|
| 611 |
+
|
| 612 |
+
# 3) required params check
|
| 613 |
+
required = INTENTS[intent]["required"]
|
| 614 |
+
missing = [p for p in required if not params.get(p)]
|
| 615 |
+
|
| 616 |
+
if missing:
|
| 617 |
+
bot_reply = f"Could you please provide the following information: {', '.join(missing)}"
|
| 618 |
+
resolution = "Unresolved"
|
| 619 |
+
else:
|
| 620 |
+
rows, col_names, sql_query, sql_params = run_intent(conn, intent, params)
|
| 621 |
+
if rows:
|
| 622 |
+
table_cols, table_rows = col_names, rows
|
| 623 |
+
bot_reply = "Please see the table above for results."
|
| 624 |
+
resolution = "Resolved"
|
| 625 |
else:
|
| 626 |
+
bot_reply = "No data found."
|
| 627 |
+
resolution = "Unresolved"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 628 |
|
| 629 |
+
ftr_ms = round((time.time() - start_time) * 1000, 2)
|
| 630 |
+
|
| 631 |
+
# Apply Hindi translation if input language was Hindi
|
| 632 |
+
display_reply = bot_reply
|
| 633 |
+
try:
|
| 634 |
+
src_lang = detect_lang(user_text)
|
| 635 |
+
except Exception as e:
|
| 636 |
+
logger.exception("Failed to detect langauge: %s", e)
|
| 637 |
+
src_lang == ENG
|
| 638 |
+
|
| 639 |
+
|
| 640 |
+
if src_lang == HINDI:
|
| 641 |
try:
|
| 642 |
+
display_reply = en_to_lang(bot_reply)
|
| 643 |
+
logger.info(f"response from BOT is ={bot_reply} Source Language is = {src_lang} display_reply is = {display_reply}")
|
| 644 |
except Exception:
|
| 645 |
+
logging.warning("Exception in en_to_lang due to: %s", e)
|
| 646 |
+
display_reply = bot_reply
|
| 647 |
+
|
| 648 |
+
# 4) show + save
|
| 649 |
+
entry = {
|
| 650 |
+
"timestamp": current_time,
|
| 651 |
+
"user": user_text,
|
| 652 |
+
"intent": intent,
|
| 653 |
+
"sentiment": sentiment,
|
| 654 |
+
"resolution": resolution,
|
| 655 |
+
"reply": display_reply,
|
| 656 |
+
"ftr_ms": ftr_ms,
|
| 657 |
+
"table_cols": table_cols,
|
| 658 |
+
"table_rows": table_rows,
|
| 659 |
+
}
|
| 660 |
+
ss.history.append(entry)
|
| 661 |
+
if len(ss.history) > 200:
|
| 662 |
+
ss.history.pop(0)
|
| 663 |
+
|
| 664 |
+
# persist with user_id
|
| 665 |
+
uid = ss["user"]["id"]
|
| 666 |
+
try:
|
| 667 |
+
save_chat_to_db(
|
| 668 |
+
conn,
|
| 669 |
+
user_id=uid,
|
| 670 |
+
user_message=user_text,
|
| 671 |
+
bot_reply=display_reply,
|
| 672 |
+
intent=intent,
|
| 673 |
+
sentiment=sentiment,
|
| 674 |
+
resolution=resolution,
|
| 675 |
+
ftr_ms=ftr_ms,
|
| 676 |
+
sql_query=sql_query,
|
| 677 |
+
sql_params=sql_params if intent in INTENTS else {},
|
| 678 |
+
)
|
| 679 |
+
except Exception as e:
|
| 680 |
+
logger.exception("Failed to save chat: %s", e)
|
| 681 |
|
| 682 |
+
# --- Conversation feed (single source of truth) ---
|
| 683 |
st.markdown("### Conversation")
|
| 684 |
|
| 685 |
+
# If history is OFF, show only the most recent exchange; otherwise all
|
| 686 |
+
feed = ss.history if ss.show_history else (ss.history[-1:] if ss.history else [])
|
| 687 |
|
| 688 |
for h in feed:
|
| 689 |
# Customer bubble
|
|
|
|
| 697 |
unsafe_allow_html=True,
|
| 698 |
)
|
| 699 |
|
| 700 |
+
# Platform analysis card
|
| 701 |
with st.container(border=True):
|
| 702 |
st.markdown(
|
| 703 |
f"""
|
|
|
|
| 712 |
unsafe_allow_html=True,
|
| 713 |
)
|
| 714 |
|
| 715 |
+
# Optional table
|
| 716 |
if h.get("table_rows"):
|
| 717 |
try:
|
| 718 |
df = pd.DataFrame(h["table_rows"], columns=h["table_cols"])
|
|
|
|
| 731 |
unsafe_allow_html=True,
|
| 732 |
)
|
| 733 |
|
| 734 |
+
|
| 735 |
# renderer
|
| 736 |
def _render_turn(turn):
|
| 737 |
ts = turn["timestamp"]
|