Spaces:
Sleeping
Sleeping
Download src/chat.py from SuhasGholkar/chatbot: direct link, hf CLI and curl.
- Browser
- Download file 40.9 kB
-
https://huggingface.co/spaces/SuhasGholkar/chatbot/resolve/main/src/chat.py
- Command line
-
hf download hf://spaces/SuhasGholkar/chatbot/src/chat.py
-
curl -L -o chat.py https://huggingface.co/spaces/SuhasGholkar/chatbot/resolve/main/src/chat.py
40.9 kB
# src/chat.py
import json
import re
import time
import logging
from datetime import datetime
import sqlite3
import io
import dateparser
import pandas as pd
import streamlit as st
from openai import OpenAI
from src.translate import ensure_english, en_to_lang, HINDI, ENG, detect_lang
from src.utils import get_connection
logger = logging.getLogger("chat")
if not logger.handlers:
logging.basicConfig(level=logging.INFO)
# OpenAI client (expects OPENAI_API_KEY in env)
_client = OpenAI()
# =========================
# INTENT TEMPLATES (SQL)
# =========================
INTENTS = {
# --- Orders ---
"order_status": {
"required": ["order_id"],
"optional": [],
"sql": """
SELECT o.order_id, o.order_status,
o.order_purchase_timestamp,
o.order_delivered_customer_date,
o.order_estimated_delivery_date
FROM olist_orders o
WHERE o.order_id = :order_id
LIMIT 1;
"""
},
"orders_by_city": {
"required": ["city"],
"optional": ["start_date","end_date"],
"sql": """
SELECT c.customer_city AS city, COUNT(*) AS orders_count
FROM olist_orders o
JOIN olist_customers c USING(customer_id)
WHERE LOWER(c.customer_city) = LOWER(:city)
AND (:start_date IS NULL OR o.order_purchase_timestamp >= :start_date)
AND (:end_date IS NULL OR o.order_purchase_timestamp < :end_date)
GROUP BY c.customer_city;
"""
},
"delivery_delay_metrics": {
"required": [],
"optional": ["start_date","end_date"],
"sql": """
SELECT ROUND(AVG(JULIANDAY(o.order_delivered_customer_date) -
JULIANDAY(o.order_estimated_delivery_date)), 2) AS avg_delay_days,
ROUND(SUM(CASE WHEN o.order_delivered_customer_date IS NOT NULL
AND o.order_estimated_delivery_date IS NOT NULL
AND JULIANDAY(o.order_delivered_customer_date) >
JULIANDAY(o.order_estimated_delivery_date)
THEN 1 ELSE 0 END)*1.0 /
SUM(CASE WHEN o.order_delivered_customer_date IS NOT NULL
AND o.order_estimated_delivery_date IS NOT NULL
THEN 1 ELSE 0 END), 3) AS late_ratio
FROM olist_orders o
WHERE o.order_delivered_customer_date IS NOT NULL
AND o.order_estimated_delivery_date IS NOT NULL
AND (:start_date IS NULL OR o.order_purchase_timestamp >= :start_date)
AND (:end_date IS NULL OR o.order_purchase_timestamp < :end_date);
"""
},
"late_orders_list": {
"required": [],
"optional": ["start_date","end_date","limit"],
"sql": """
SELECT o.order_id, o.order_purchase_timestamp,
o.order_delivered_customer_date, o.order_estimated_delivery_date,
ROUND(JULIANDAY(o.order_delivered_customer_date) -
JULIANDAY(o.order_estimated_delivery_date), 2) AS delay_days
FROM olist_orders o
WHERE o.order_delivered_customer_date IS NOT NULL
AND o.order_estimated_delivery_date IS NOT NULL
AND JULIANDAY(o.order_delivered_customer_date) >
JULIANDAY(o.order_estimated_delivery_date)
AND (:start_date IS NULL OR o.order_purchase_timestamp >= :start_date)
AND (:end_date IS NULL OR o.order_purchase_timestamp < :end_date)
ORDER BY delay_days DESC
LIMIT :limit;
"""
},
# --- Products ---
"top_products_revenue": {
"required": [],
"optional": ["start_date","end_date","k"],
"sql": """
SELECT i.product_id,
ROUND(SUM(i.price), 2) AS revenue,
COUNT(*) AS quantity_sold
FROM olist_order_items i
JOIN olist_orders o USING(order_id)
WHERE (:start_date IS NULL OR o.order_purchase_timestamp >= :start_date)
AND (:end_date IS NULL OR o.order_purchase_timestamp < :end_date)
GROUP BY i.product_id
ORDER BY revenue DESC
LIMIT :k;
"""
},
"top_products_quantity": {
"required": [],
"optional": ["start_date","end_date","k"],
"sql": """
SELECT i.product_id,
COUNT(*) AS quantity_sold,
ROUND(SUM(i.price), 2) AS revenue
FROM olist_order_items i
JOIN olist_orders o USING(order_id)
WHERE (:start_date IS NULL OR o.order_purchase_timestamp >= :start_date)
AND (:end_date IS NULL OR o.order_purchase_timestamp < :end_date)
GROUP BY i.product_id
ORDER BY quantity_sold DESC
LIMIT :k;
"""
},
"category_sales": {
"required": [],
"optional": ["category","start_date","end_date"],
"sql": """
SELECT p.product_category_name, p.product_category_name_english,
ROUND(SUM(i.price), 2) AS revenue,
COUNT(*) AS lines
FROM olist_order_items i
JOIN olist_orders o USING(order_id)
JOIN olist_products p USING(product_id)
WHERE (:category IS NULL
OR LOWER(p.product_category_name) = LOWER(:category)
OR LOWER(p.product_category_name_english) = LOWER(:category))
AND (:start_date IS NULL OR o.order_purchase_timestamp >= :start_date)
AND (:end_date IS NULL OR o.order_purchase_timestamp < :end_date)
GROUP BY p.product_category_name, p.product_category_name_english
ORDER BY revenue DESC;
"""
},
"seller_performance": {
"required": ["seller_id"],
"optional": ["start_date","end_date"],
"sql": """
SELECT i.seller_id,
ROUND(SUM(i.price),2) AS revenue,
COUNT(*) AS items_sold,
ROUND(AVG(i.freight_value),2) AS avg_freight
FROM olist_order_items i
JOIN olist_orders o USING(order_id)
WHERE i.seller_id = :seller_id
AND (:start_date IS NULL OR o.order_purchase_timestamp >= :start_date)
AND (:end_date IS NULL OR o.order_purchase_timestamp < :end_date)
GROUP BY i.seller_id;
"""
},
# --- Customers & Geo ---
"orders_by_state": {
"required": [],
"optional": ["start_date","end_date","k"],
"sql": """
SELECT c.customer_state, COUNT(*) AS orders_count
FROM olist_orders o
JOIN olist_customers c USING(customer_id)
WHERE (:start_date IS NULL OR o.order_purchase_timestamp >= :start_date)
AND (:end_date IS NULL OR o.order_purchase_timestamp < :end_date)
GROUP BY c.customer_state
ORDER BY orders_count DESC
LIMIT :k;
"""
},
"repeat_rate": {
"required": [],
"optional": ["start_date","end_date"],
"sql": """
WITH cust_orders AS (
SELECT c.customer_unique_id AS cuid, COUNT(*) AS n
FROM olist_orders o
JOIN olist_customers c USING(customer_id)
WHERE (:start_date IS NULL OR o.order_purchase_timestamp >= :start_date)
AND (:end_date IS NULL OR o.order_purchase_timestamp < :end_date)
GROUP BY c.customer_unique_id
)
SELECT ROUND(SUM(CASE WHEN n>=2 THEN 1 ELSE 0 END)*1.0 / COUNT(*), 3) AS repeat_customer_ratio
FROM cust_orders;
"""
},
# --- Payments ---
"payments_breakdown": {
"required": [],
"optional": ["start_date","end_date"],
"sql": """
SELECT p.payment_type,
COUNT(*) AS payments_count,
ROUND(SUM(p.payment_value),2) AS total_value,
ROUND(AVG(p.payment_installments),2) AS avg_installments
FROM olist_order_payments p
JOIN olist_orders o USING(order_id)
WHERE (:start_date IS NULL OR o.order_purchase_timestamp >= :start_date)
AND (:end_date IS NULL OR o.order_purchase_timestamp < :end_date)
GROUP BY p.payment_type
ORDER BY total_value DESC;
"""
},
# --- AOV Trend ---
"aov_trend_monthly": {
"required": [],
"optional": ["start_date","end_date"],
"sql": """
WITH order_value AS (
SELECT o.order_id,
DATE(o.order_purchase_timestamp, 'start of month') AS month,
SUM(i.price) AS order_value
FROM olist_orders o
JOIN olist_order_items i USING(order_id)
WHERE (:start_date IS NULL OR o.order_purchase_timestamp >= :start_date)
AND (:end_date IS NULL OR o.order_purchase_timestamp < :end_date)
GROUP BY o.order_id, month
)
SELECT month, ROUND(AVG(order_value), 2) AS avg_order_value
FROM order_value
GROUP BY month
ORDER BY month;
"""
},
# --- Reviews ---
"latest_reviews": {
"required": [],
"optional": ["product_id","category","limit"],
"sql": """
SELECT r.order_id, r.review_score, r.review_creation_date, r.review_comment_message
FROM olist_order_reviews r
WHERE (:product_id IS NULL OR EXISTS (
SELECT 1 FROM olist_order_items i
WHERE i.order_id = r.order_id AND i.product_id = :product_id))
AND (:category IS NULL OR EXISTS (
SELECT 1 FROM olist_order_items i
JOIN olist_products p USING(product_id)
WHERE i.order_id = r.order_id
AND (LOWER(p.product_category_name) = LOWER(:category)
OR LOWER(p.product_category_name_english) = LOWER(:category))
))
ORDER BY r.review_creation_date DESC
LIMIT :limit;
"""
},
"rating_summary": {
"required": [],
"optional": ["product_id","category","start_date","end_date"],
"sql": """
SELECT ROUND(AVG(r.review_score),2) AS avg_rating,
COUNT(*) AS n_reviews
FROM olist_order_reviews r
JOIN olist_orders o ON o.order_id = r.order_id
WHERE (:start_date IS NULL OR r.review_creation_date >= :start_date)
AND (:end_date IS NULL OR r.review_creation_date < :end_date)
AND (:product_id IS NULL OR EXISTS (
SELECT 1 FROM olist_order_items i
WHERE i.order_id = r.order_id AND i.product_id = :product_id))
AND (:category IS NULL OR EXISTS (
SELECT 1 FROM olist_order_items i
JOIN olist_products p USING(product_id)
WHERE i.order_id = r.order_id
AND (LOWER(p.product_category_name) = LOWER(:category)
OR LOWER(p.product_category_name_english) = LOWER(:category))
));
"""
},
}
INTENT_KEYWORDS = {
"order_status": ["order", "status", "track", "tracking", "delivered", "delivery", "estimate", "order id"],
"orders_by_city": ["city", "town", "municipality"],
"delivery_delay_metrics": ["delay", "late", "delivery time", "estimated", "sla"],
"late_orders_list": ["late", "delayed", "overdue"],
"top_products_revenue": ["top", "revenue", "sales", "gross", "gmv"],
"top_products_quantity": ["top", "quantity", "units", "sold", "bestseller"],
"category_sales": ["category", "department", "sales by category"],
"seller_performance": ["seller", "merchant", "vendor", "performance"],
"orders_by_state": ["state", "region", "province"],
"repeat_rate": ["repeat", "retention", "returning"],
"payments_breakdown": ["payment", "installments", "card", "boleto", "pix", "method"],
"aov_trend_monthly": ["aov", "average order value", "trend", "monthly"],
"latest_reviews": ["review", "comment", "feedback", "opinion", "rating"],
"rating_summary": ["rating", "score", "stars", "nps", "csat"],
}
def _inject_chat_css():
st.markdown("""
<style>
/* page background stays light */
.chat-wrap { background: transparent; }
/* message bubbles */
.msg-row { display: flex; gap: 10px; margin: 10px 0 16px 0; align-items: flex-start; }
.msg-avatar { flex: 0 0 32px; width: 32px; height: 32px; border-radius: 50%;
display:flex; align-items:center; justify-content:center;
background: #E8EEF9; color:#2557D6; font-weight:700; }
.msg-bubble { max-width: 900px; padding: 10px 14px; border-radius: 12px;
border: 1px solid rgba(0,0,0,0.06); }
.msg-user { background: #ffffff; }
.msg-bot { background: #F7FAFF; }
.msg-meta { font-size: 12px; color: #6B7280; margin-top: 6px; }
/* table card look */
.table-card { border: 1px solid rgba(0,0,0,0.08); border-radius: 12px; padding: 8px; background:#fff; }
/* small buttons like links */
[data-testid="stButton"] > button[kind="secondary"] {
background: none !important; border: none !important; box-shadow: none !important;
color: #266EF1 !important; padding: 0 !important; text-decoration: underline;
}
[data-testid="stButton"] > button[kind="secondary"]:hover { text-decoration: none; }
/* tighten header space a bit */
.block-container { padding-top: 1.25rem; }
/* --- Analysis chips per turn --- */
.analysis-row { display:flex; gap:8px; flex-wrap:wrap; margin:6px 0 10px 42px; }
.chip { font-size:12px; padding:4px 8px; border-radius:999px; border:1px solid rgba(0,0,0,0.08); background:#fff; color:#374151; }
.chip.intent { background:#EEF2FF; border-color:#E0E7FF; color:#3730A3; }
.chip.sentiment { background:#ECFEFF; border-color:#CFFAFE; color:#075985; }
.chip.resolved { background:#ECFDF5; border-color:#D1FAE5; color:#065F46; }
.chip.unresolved { background:#FEF3C7; border-color:#FDE68A; color:#92400E; }
.chip.latency { background:#F3F4F6; border-color:#E5E7EB; color:#374151; }
/* --- Keep the input bar visible near the bottom --- */
.sticky-input { position: sticky; bottom: 8px; z-index: 10; background: #F6F8FC; padding-top: 6px; }
</style>
""", unsafe_allow_html=True)
def _fmt_ts():
return datetime.now().strftime("%Y-%m-%d %H:%M:%S")
def _render_analysis_chips(turn: dict):
"""
Render a compact analysis row for one conversation turn.
Expected keys on 'turn': intent, sentiment, resolution, ftr_ms
"""
intent = turn.get("intent", "—")
sentiment = turn.get("sentiment", "—")
resolution = turn.get("resolution", "—")
ftr_ms = turn.get("ftr_ms", None)
res_cls = "resolved" if str(resolution).lower().startswith("resol") else "unresolved"
lat = f"{float(ftr_ms):.2f} ms" if ftr_ms is not None else "—"
st.markdown(
f"""
<div class="analysis-row">
<span class="chip intent">Intent: {intent}</span>
<span class="chip sentiment">Sentiment: {sentiment}</span>
<span class="chip {res_cls}">Resolution: {resolution}</span>
<span class="chip latency">Latency: {lat}</span>
</div>
""",
unsafe_allow_html=True,
)
def _bubble(role: str, msg: str, ts: str = None, analysis: dict | None = None):
"""
Render a chat bubble with optional analysis block.
role = "user" | "bot"
analysis: dict with keys like intent, sentiment, resolution, latency_ms
"""
if not msg:
return
avatar = "👤" if role == "user" else "🤖"
role_class = "bubble-user" if role == "user" else "bubble-bot"
st.markdown(
f"""
<div class="bubble {role_class}">
<div class="bubble-header">{avatar} {msg}</div>
<div class="bubble-timestamp">{ts or ""}</div>
</div>
""",
unsafe_allow_html=True,
)
# Only show analysis chips for the user's message, and only if provided
if role == "user" and analysis:
_render_analysis_chips(analysis)
def _export_history_csv(entries: list) -> bytes:
"""Turn in-session history into CSV bytes."""
if not entries:
return b""
rows = []
for e in entries:
rows.append({
"timestamp": e.get("timestamp"),
"user": e.get("user"),
"intent": e.get("intent"),
"sentiment": e.get("sentiment"),
"resolution": e.get("resolution"),
"reply": e.get("reply"),
"ftr_ms": e.get("ftr_ms"),
})
df = pd.DataFrame(rows)
with io.StringIO() as s:
df.to_csv(s, index=False)
return s.getvalue().encode("utf-8")
def _scroll_to_bottom():
# hacky but effective: scroll after render
st.markdown(
"<script>window.scrollTo(0, document.body.scrollHeight);</script>",
unsafe_allow_html=True
)
def _has_overlap(intent: str, text: str) -> bool:
kws = INTENT_KEYWORDS.get(intent, [])
if not kws:
return True
t = text.lower()
return any(re.search(r"\b" + re.escape(kw.lower()) + r"\b", t) for kw in kws)
# =========================
# GPT HELPERS
# =========================
def gpt_classify_intent(user_text: str) -> dict:
options = list(INTENTS.keys())
system = (
"You are an intent classifier for an e-commerce analytics chatbot. "
"You MUST return strict JSON. If none of the intents clearly applies, return UNMAPPED."
)
user = (
"Available intents (keys): " + ", ".join(options) + "\n"
"Task: Choose the single BEST matching intent key OR 'UNMAPPED' if none clearly fits.\n"
"Output STRICT JSON with fields: intent (string), confidence (0.0-1.0), reason (short string).\n"
"Do NOT guess. If the message is unrelated, return UNMAPPED.\n\n"
f"Message: {user_text}"
)
resp = _client.chat.completions.create(
model="gpt-3.5-turbo",
messages=[{"role":"system","content": system},
{"role":"user","content": user}],
temperature=0
)
txt = resp.choices[0].message.content.strip()
try:
data = json.loads(txt)
raw_intent = str(data.get("intent","")).strip().lower()
if raw_intent == "" or raw_intent in ("none","n/a","unknown"):
data["intent"] = "UNMAPPED"
else:
if raw_intent not in [k.lower() for k in INTENTS.keys()] and raw_intent != "unmapped":
data["intent"] = "UNMAPPED"
else:
for k in INTENTS.keys():
if k.lower() == raw_intent:
data["intent"] = k
break
try:
c = float(data.get("confidence", 0))
data["confidence"] = max(0.0, min(1.0, c))
except Exception:
data["confidence"] = 0.0
data["reason"] = str(data.get("reason","")).strip()
return data
except Exception:
return {"intent":"UNMAPPED","confidence":0.0,"reason":"parse_error"}
def gpt_classify_sentiment(user_text: str) -> str:
prompt = "Classify sentiment as Positive, Negative, or Neutral.\n\nMessage: " + user_text
resp = _client.chat.completions.create(
model="gpt-3.5-turbo",
messages=[
{"role":"system","content":"You are a sentiment classifier."},
{"role":"user","content": prompt}
],
temperature=0
)
return resp.choices[0].message.content.strip()
def gpt_extract_params(intent_key: str, user_text: str) -> dict:
if intent_key not in INTENTS:
return {}
cfg = INTENTS[intent_key]
param_list = cfg["required"] + cfg["optional"]
prompt = (
"Extract the following parameters from the user's query and return STRICT JSON only.\n"
f"Keys: {param_list}. If a parameter is missing set it to null. "
"Dates may be natural language; return them as-is.\n\n"
f"User query: {user_text}"
)
resp = _client.chat.completions.create(
model="gpt-3.5-turbo",
messages=[
{"role":"system","content":"You extract parameters and ONLY output valid JSON."},
{"role":"user","content": prompt}
],
temperature=0
)
txt = resp.choices[0].message.content.strip()
try:
params = json.loads(txt)
except Exception:
params = {p: None for p in param_list}
return params
def gpt_fallback_response(user_text: str) -> str:
options = list(INTENTS.keys())
system = (
"You are a helpful support agent for an e-commerce analytics chatbot. "
"The app could not map the user's request to any known intent/SQL template. "
"Be helpful: either answer conversationally, gather missing details with specific "
"questions, or suggest the closest capability."
)
user = (
"No matching intent was found for the following message.\n"
f"Known intents are: {options}\n\n"
f"User message: {user_text}\n\n"
"Provide a concise, helpful response. If appropriate, suggest the nearest "
"matching capability from the list or ask one or two targeted follow-up questions."
)
resp = _client.chat.completions.create(
model="gpt-3.5-turbo",
messages=[{"role":"system","content": system},
{"role":"user","content": user}],
temperature=0.3
)
return resp.choices[0].message.content.strip()
def gpt_label_unmapped(user_text: str) -> str:
system = (
"You label short messages into one category: "
"greeting | clarification | thanks | complaint | small_talk | farewell | other. "
"Return ONLY the label, nothing else."
)
user = f"Message: {user_text}"
resp = _client.chat.completions.create(
model="gpt-3.5-turbo",
messages=[{"role":"system","content": system},
{"role":"user","content": user}],
temperature=0
)
label = resp.choices[0].message.content.strip().lower()
allowed = {"greeting","clarification","thanks","complaint","small_talk","farewell","other"}
return label if label in allowed else "other"
# =========================
# PARAM PROCESSING
# =========================
def process_params(intent_key: str, params: dict) -> dict:
if params is None:
params = {}
cfg = INTENTS[intent_key]
required = cfg.get("required", [])
optional = cfg.get("optional", [])
allowed_keys = set(required + optional)
clean = {k: params.get(k) for k in allowed_keys}
# integer defaults
if "k" in allowed_keys:
v = clean.get("k")
try:
clean["k"] = int(str(v).strip()) if v not in (None, "", "null", "None") else 10
except Exception:
clean["k"] = 10
if "limit" in allowed_keys:
v = clean.get("limit")
try:
clean["limit"] = int(str(v).strip()) if v not in (None, "", "null", "None") else 50
except Exception:
clean["limit"] = 50
# defaults for common keys
for k in ("start_date", "end_date", "category", "product_id", "city", "seller_id", "order_id"):
if k in allowed_keys and k not in clean:
clean[k] = None
# parse natural language dates to YYYY-MM-DD
for k in ("start_date", "end_date"):
if k in clean:
v = clean.get(k)
if v and str(v).strip().lower() not in ("none", "null", ""):
parsed = dateparser.parse(str(v))
clean[k] = parsed.strftime("%Y-%m-%d") if parsed else None
else:
clean[k] = None
return clean
# =========================
# EXECUTE INTENT (SQLite)
# =========================
def run_intent(conn: sqlite3.Connection, intent_key: str, params: dict):
cfg = INTENTS[intent_key]
sql = cfg["sql"]
required = cfg.get("required", [])
optional = cfg.get("optional", [])
allowed_keys = set(required + optional)
bound = {k: params.get(k) for k in allowed_keys}
if "k" in allowed_keys:
try:
bound["k"] = int(bound.get("k", 10))
except Exception:
bound["k"] = 10
if "limit" in allowed_keys:
try:
bound["limit"] = int(bound.get("limit", 50))
except Exception:
bound["limit"] = 50
for k in ("start_date", "end_date"):
if k in bound:
v = bound[k]
if v is not None and not isinstance(v, str):
try:
bound[k] = v.strftime("%Y-%m-%d")
except Exception:
bound[k] = None
logger.info(f"SQL intent={intent_key} | params={bound}")
cur = conn.cursor()
cur.execute(sql, bound)
rows = cur.fetchall()
col_names = [d[0] for d in cur.description]
return rows, col_names, sql, bound
# =========================
# DB SAVE
# =========================
def ensure_chat_schema():
with get_connection() as conn:
conn.execute("""
CREATE TABLE IF NOT EXISTS chat_history (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
timestamp TEXT NOT NULL,
user_message TEXT,
bot_reply TEXT,
intent TEXT,
sentiment TEXT,
resolution TEXT,
ftr_ms REAL,
sql_query TEXT,
sql_params TEXT,
FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE CASCADE
)""")
conn.commit()
def save_chat_to_db(conn, user_id, user_message, bot_reply,
intent=None, sentiment=None, resolution=None,
ftr_ms=None, sql_query=None, sql_params=None):
conn.execute("""
INSERT INTO chat_history (user_id, timestamp, user_message, bot_reply,
intent, sentiment, resolution, ftr_ms, sql_query, sql_params)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""", (
user_id, datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
user_message, bot_reply, intent, sentiment, resolution, ftr_ms,
sql_query, json.dumps(sql_params or {})
))
conn.commit()
# =========================
# RENDER HELPERS
# =========================
def _render_analysis_block(h):
st.markdown(
f"""
<div class="analysis">
<span class="meta">{h['timestamp']}</span>
<div style="font-weight:800;margin-bottom:6px;">Platform Analysis</div>
<dl>
<dt>Intent</dt><dd><span class="badge intent">{h['intent']}</span></dd>
<dt>Sentiment</dt><dd><span class="badge neutral">{h['sentiment']}</span></dd>
<dt>Resolution</dt><dd><span class="badge ok">{h['resolution']}</span></dd>
<dt>Latency</dt><dd><span class="badge slow">{h['ftr_ms']:.2f} ms</span></dd>
</dl>
</div>
""",
unsafe_allow_html=True,
)
def _render_msg(role, text, ts):
cls = "user" if role == "user" else "bot"
st.markdown(
f"""
<div class="msg {cls}">
<span class="meta">{ts}</span>
<b>{"Customer" if cls=="user" else "Support Agent"}:</b> {text}
</div>
""",
unsafe_allow_html=True,
)
def render_order_status_compact(df: pd.DataFrame, title="Order Status"):
if df.empty:
st.info("No rows returned.")
return
row = df.iloc[0]
st.subheader(title)
# 1st line: compact pill chips
chip = """
<span style="
display:inline-block;padding:6px 10px;margin:4px 8px 10px 0;
background:#f4f6ff;border:1px solid #e3e7ff;color:#4a52b8;
border-radius:999px;font-size:13px;">{}</span>
"""
c1, c2, c3, c4 = st.columns(4)
c1.metric("Order ID", str(row.get("order_id", "—")))
c2.metric("Status", str(row.get("order_status", "—")))
c3.metric("Purchased", str(row.get("order_purchase_timestamp", "—")))
c4.metric("Delivered", str(row.get("order_delivered_customer_date", "—")))
def _render_turn(h):
# Customer bubble
st.markdown(
f"<div class='chat-bubble customer'>"
f"<div class='chat-meta'>{h['timestamp']}</div>"
f"<b>Customer:</b> {h['user']}"
f"</div>",
unsafe_allow_html=True,
)
# Optional results table
if h.get("table_cols") and h.get("table_rows"):
try:
df = pd.DataFrame(h["table_rows"], columns=h["table_cols"])
st.dataframe(df, height=240, width="stretch")
except Exception:
pass
# Analysis card
with st.container():
st.markdown(
"<div class='card soft'><div class='card-title'>Platform Analysis</div>",
unsafe_allow_html=True,
)
colA, colB, colC, colD = st.columns([1.2, 1.2, 1.2, 1.2])
with colA:
st.write(f"**Intent:** {h['intent']}")
with colB:
st.write(f"**Sentiment:** {h['sentiment']}")
with colC:
st.write(f"**Resolution:** {h['resolution']}")
with colD:
st.write(f"**Latency:** {h['ftr_ms']:.2f} ms")
st.markdown("</div>", unsafe_allow_html=True)
# Agent bubble
st.markdown(
f"<div class='chat-bubble agent'>"
f"<div class='chat-meta'>{h['timestamp']}</div>"
f"<b>Support Agent:</b> {h['reply']}"
f"</div>",
unsafe_allow_html=True,
)
# =========================
# CHAT UI
# =========================
def render_chat_tab(conn):
"""
UI-only upgraded chat tab.
Business logic (INTENTS, LLM calls, SQL, save_chat_to_db, etc.) remains unchanged.
"""
from datetime import datetime
_inject_chat_css()
st.markdown("## 💬 Ecomm Chatbot", help="Ask questions about orders, delivery, revenue, reviews, and more.")
ss = st.session_state
# ---- initialize UI/session state (non-business) ----
if "history" not in ss:
ss.history = [] # list of dict entries (same structure you already use)
if "show_history" not in ss:
ss.show_history = False
# ---- toolbar: show history toggle + export ----
t1, t2 = st.columns([1, 1])
with t1:
ss.show_history = st.checkbox("Show conversation history (this session)", value=ss.show_history, key="show_hist_toggle")
with t2:
# CSV export of session history
csv_bytes = _export_history_csv(ss.history)
ts = datetime.now().strftime("%Y%m%d_%H%M%S")
#st.download_button("Download CSV", csv_bytes, file_name=f"my_chats_{ts}.csv", mime="text/csv", use_container_width=True)
st.markdown('<div class="chat-wrap">', unsafe_allow_html=True)
# ---- show conversation history live (no submit needed) ----
if ss.show_history and ss.history:
st.markdown("#### Conversation")
for e in ss.history:
_bubble("user", e.get("user"), e.get("timestamp"), analysis=e)
# Render table (if any) right before the bot bubble for that turn
tbl_cols, tbl_rows = e.get("table_cols"), e.get("table_rows")
if tbl_cols and tbl_rows:
st.markdown('<div class="table-card">', unsafe_allow_html=True)
try:
df = pd.DataFrame(tbl_rows, columns=tbl_cols)
st.dataframe(df, height=240, use_container_width=True)
except Exception:
# fallback simple
st.write(tbl_rows)
st.markdown("</div>", unsafe_allow_html=True)
_bubble("bot", e.get("reply"), e.get("timestamp"))
st.markdown("---")
# ---- input box: Enter = send, Shift+Enter = newline (native) ----
prompt = st.chat_input("Type your question…")
if prompt is None:
# nothing submitted this frame
st.markdown("</div>", unsafe_allow_html=True)
return
# ---- handle a new user query (BUSINESS LOGIC PRESERVED) ----
# If you already do bilingual handling, keep your calls here:
# from src.translate import ensure_english, en_to_lang, HINDI
text_in = prompt.strip()
if not text_in:
st.stop()
# Optional bilingual layer (kept compatible with your integration).
# If you already have ensure_english()/detect_lang(), keep using it here.
src_lang = None
try:
from src.translate import ensure_english, en_to_lang, HINDI
original_src_lang = detect_lang(text_in) # keep this stable!
text_en = ensure_english(text_in) if original_src_lang != ENG else text_in
logger.info("render_chat_tab -> SRC=%s | IN=%s", original_src_lang, text_in[:100].replace("\n"," "))
logger.info("render_chat_tab -> EN =%s", text_en[:100].replace("\n"," "))
#text_en = ensure_english(text_in)
src_lang = getattr(st.session_state, "_last_src_lang", None) # if you store it there
logger.info("render_chat_tab -> src_lang is ", src_lang)
except Exception:
text_en = text_in # no-op if translate module not wired
import time
from datetime import datetime
start_time = time.time()
current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
# 1) intent + sentiment (unchanged)
try:
cls = gpt_classify_intent(text_en)
intent = cls.get("intent", "UNMAPPED")
confidence = cls.get("confidence", 0.0)
reason = cls.get("reason", "")
logger.info(f"render_chat_tab -> intent={intent} conf={confidence} reason={reason}")
except Exception as e:
logger.exception("Exception occured in gpt_classify_sentiment. Exception is : %s", e)
logger.info("render_chat_tab -> intent Classification Done")
try:
sentiment = gpt_classify_sentiment(text_en)
except Exception as e:
logger.exception("Exception occured in gpt_classify_sentiment. Exception is : %s", e)
logger.info("render_chat_tab -> Sentiment Classification Done")
# keyword guardrail (your existing helper)
if intent != "UNMAPPED" and not _has_overlap(intent, text_en):
intent = "UNMAPPED"
sql_query, sql_params = "", {}
table_cols, table_rows = None, None
if intent == "UNMAPPED":
meta = gpt_label_unmapped(text_en)
intent = meta # store meta label
bot_reply = gpt_fallback_response(text_en)
resolution = "Responded"
else:
# 2) extract + process params
try:
params = gpt_extract_params(intent, text_en)
except Exception as e:
logger.exception("Exception occured in gpt_extract_params. Exception is : %s", e)
try:
params = process_params(intent, params)
except Exception as e:
logger.exception("Exception occured in process_params. Exception is : %s", e)
logger.info("render_chat_tab -> Process Parameters Done")
# 3) required params check from your INTENTS
required = INTENTS[intent]["required"]
missing = [p for p in required if not params.get(p)]
if missing:
bot_reply = f"Could you please provide the following information: {', '.join(missing)}"
resolution = "Unresolved"
else:
rows, col_names, sql_query, sql_params = run_intent(conn, intent, params)
if rows:
table_cols, table_rows = col_names, rows
bot_reply = "Please see the table above for results."
resolution = "Resolved"
else:
bot_reply = "No data found."
resolution = "Unresolved"
ftr_ms = round((time.time() - start_time) * 1000, 2)
logger.info("render_chat_tab -> Going for LLM Call")
logger.info(f"render_chat_tab -> src_lang:{src_lang}")
# Bilingual display back to user (if you keep Hindi display)
display_reply = bot_reply
logger.info(f"render_chat_tab -> bot reply is:{bot_reply}, src_lang is: {src_lang} , original_src_lang is :{original_src_lang} ")
try:
if original_src_lang == HINDI:
try:
logger.info("Back-translate EN->HI …")
display_reply = en_to_lang(bot_reply)
logger.info(f"response from BOT is ={bot_reply} Source Language is = {src_lang} display_reply is = {display_reply}")
logger.info("LLM reply (HI): %s", display_reply[:120].replace("\n"," "))
except Exception:
logger.warning("Exception in en_to_lang due to: %s", e)
display_reply = bot_reply
except Exception:
pass
entry = {
"timestamp": current_time,
"user": text_in,
"reply": display_reply,
"intent": intent,
"intent_conf": confidence,
"sentiment": sentiment,
"resolution": resolution,
"ftr_ms": ftr_ms,
"table_cols": table_cols,
"table_rows": table_rows,
"sql_error": "",
"src_lang": src_lang,
}
# ss.history.append(entry)
# 4) show latest turn immediately even if history is hidden
# (We render the most recent pair inline so the user sees the response right away.)
_bubble("user", text_in, current_time, analysis = entry)
if intent == "order_status":
if table_cols and table_rows:
try:
df = pd.DataFrame(table_rows, columns=table_cols)
render_order_status_compact(df, title="Order Status")
except Exception as e:
st.error("Could not display the table. Please try again or contact support.")
logger.error(f"Error creating DataFrame: {e}") # Log the specific error for debugging
else:
if table_cols and table_rows:
st.markdown('<div class="table-card">', unsafe_allow_html=True)
try:
df = pd.DataFrame(table_rows, columns=table_cols)
st.dataframe(df, height=240, use_container_width=True)
except Exception:
st.write(table_rows)
st.markdown("</div>", unsafe_allow_html=True)
_bubble("bot", display_reply, current_time)
# 5) persist in session + DB
entry = {
"timestamp": current_time,
"user": text_in,
"intent": intent,
"sentiment": sentiment,
"resolution": resolution,
"reply": display_reply,
"ftr_ms": ftr_ms,
"table_cols": table_cols,
"table_rows": table_rows,
}
ss.history.append(entry)
if len(ss.history) > 50:
ss.history.pop(0)
# persist with user_id (unchanged)
uid = st.session_state["user"]["id"]
try:
save_chat_to_db(
conn,
user_id=uid,
user_message=text_in,
bot_reply=display_reply,
intent=intent,
sentiment=sentiment,
resolution=resolution,
ftr_ms=ftr_ms,
sql_query=sql_query,
sql_params=sql_params if intent in INTENTS else {}
)
except Exception as e:
logger.exception("Failed to save chat: %s", e)
st.markdown("</div>", unsafe_allow_html=True)
_scroll_to_bottom()
def render_user_export_tab(conn, user_id: int):
import datetime
st.subheader("Export My Chats")
df = pd.read_sql_query(
"SELECT timestamp, user_message, bot_reply, intent, sentiment, resolution, ftr_ms "
"FROM chat_history WHERE user_id=? ORDER BY timestamp DESC",
conn, params=(user_id,)
)
if df.empty:
st.info("No chats to export yet.")
return
csv_bytes = df.to_csv(index=False).encode("utf-8")
timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
# Create dynamic file name
file_name_csv = f"my_chats_{timestamp}.csv"
file_name_txt = f"my_chats_{timestamp}.txt"
st.download_button("Download CSV", csv_bytes, file_name=file_name_csv, mime="text/csv")
lines = []
for _, r in df.iterrows():
lines.append(f"[{r['timestamp']}] You: {r['user_message']}")
lines.append(f"Bot: {r['bot_reply']}")
lines.append("---")
txt_bytes = "\n".join(lines).encode("utf-8")
st.download_button("Download TXT", txt_bytes, file_name=file_name_txt, mime="text/plain")
# src/chat.py
import json
import re
import time
import logging
from datetime import datetime
import sqlite3
import io
import dateparser
import pandas as pd
import streamlit as st
from openai import OpenAI
from src.translate import ensure_english, en_to_lang, HINDI, ENG, detect_lang
from src.utils import get_connection
logger = logging.getLogger("chat")
if not logger.handlers:
logging.basicConfig(level=logging.INFO)
# OpenAI client (expects OPENAI_API_KEY in env)
_client = OpenAI()
# =========================
# INTENT TEMPLATES (SQL)
# =========================
INTENTS = {
# --- Orders ---
"order_status": {
"required": ["order_id"],
"optional": [],
"sql": """
SELECT o.order_id, o.order_status,
o.order_purchase_timestamp,
o.order_delivered_customer_date,
o.order_estimated_delivery_date
FROM olist_orders o
WHERE o.order_id = :order_id
LIMIT 1;
"""
},
"orders_by_city": {
"required": ["city"],
"optional": ["start_date","end_date"],
"sql": """
SELECT c.customer_city AS city, COUNT(*) AS orders_count
FROM olist_orders o
JOIN olist_customers c USING(customer_id)
WHERE LOWER(c.customer_city) = LOWER(:city)
AND (:start_date IS NULL OR o.order_purchase_timestamp >= :start_date)
AND (:end_date IS NULL OR o.order_purchase_timestamp < :end_date)
GROUP BY c.customer_city;
"""
},
"delivery_delay_metrics": {
"required": [],
"optional": ["start_date","end_date"],
"sql": """
SELECT ROUND(AVG(JULIANDAY(o.order_delivered_customer_date) -
JULIANDAY(o.order_estimated_delivery_date)), 2) AS avg_delay_days,
ROUND(SUM(CASE WHEN o.order_delivered_customer_date IS NOT NULL
AND o.order_estimated_delivery_date IS NOT NULL
AND JULIANDAY(o.order_delivered_customer_date) >
JULIANDAY(o.order_estimated_delivery_date)
THEN 1 ELSE 0 END)*1.0 /
SUM(CASE WHEN o.order_delivered_customer_date IS NOT NULL
AND o.order_estimated_delivery_date IS NOT NULL
THEN 1 ELSE 0 END), 3) AS late_ratio
FROM olist_orders o
WHERE o.order_delivered_customer_date IS NOT NULL
AND o.order_estimated_delivery_date IS NOT NULL
AND (:start_date IS NULL OR o.order_purchase_timestamp >= :start_date)
AND (:end_date IS NULL OR o.order_purchase_timestamp < :end_date);
"""
},
"late_orders_list": {
"required": [],
"optional": ["start_date","end_date","limit"],
"sql": """
SELECT o.order_id, o.order_purchase_timestamp,
o.order_delivered_customer_date, o.order_estimated_delivery_date,
ROUND(JULIANDAY(o.order_delivered_customer_date) -
JULIANDAY(o.order_estimated_delivery_date), 2) AS delay_days
FROM olist_orders o
WHERE o.order_delivered_customer_date IS NOT NULL
AND o.order_estimated_delivery_date IS NOT NULL
AND JULIANDAY(o.order_delivered_customer_date) >
JULIANDAY(o.order_estimated_delivery_date)
AND (:start_date IS NULL OR o.order_purchase_timestamp >= :start_date)
AND (:end_date IS NULL OR o.order_purchase_timestamp < :end_date)
ORDER BY delay_days DESC
LIMIT :limit;
"""
},
# --- Products ---
"top_products_revenue": {
"required": [],
"optional": ["start_date","end_date","k"],