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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import re
|
| 3 |
+
import sqlite3
|
| 4 |
+
import logging
|
| 5 |
+
import json
|
| 6 |
+
import time
|
| 7 |
+
from datetime import datetime
|
| 8 |
+
import dateparser
|
| 9 |
+
import streamlit as st
|
| 10 |
+
import matplotlib.pyplot as plt
|
| 11 |
+
import pandas as pd
|
| 12 |
+
from openai import OpenAI
|
| 13 |
+
|
| 14 |
+
# ================= CONFIG =================
|
| 15 |
+
DB_PATH = "/content/olist.sqlite" # <-- your DB path
|
| 16 |
+
MAX_HISTORY = 10
|
| 17 |
+
LOG_FILE = "app.log"
|
| 18 |
+
|
| 19 |
+
# ================= LOGGING =================
|
| 20 |
+
logging.basicConfig(
|
| 21 |
+
level=logging.DEBUG,
|
| 22 |
+
format="%(asctime)s [%(levelname)s] %(message)s",
|
| 23 |
+
handlers=[logging.FileHandler(LOG_FILE), logging.StreamHandler()]
|
| 24 |
+
)
|
| 25 |
+
logger = logging.getLogger(__name__)
|
| 26 |
+
|
| 27 |
+
# ================= OPENAI CLIENT (v1) =================
|
| 28 |
+
API_KEY = "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"
|
| 29 |
+
if not API_KEY:
|
| 30 |
+
raise ValueError("OPENAI_API_KEY environment variable not set.")
|
| 31 |
+
client = OpenAI(api_key=API_KEY)
|
| 32 |
+
|
| 33 |
+
# ================= SQLITE HELPERS =================
|
| 34 |
+
def get_connection():
|
| 35 |
+
# Works with SQLite 3.8+; ensure your path has no quotes
|
| 36 |
+
uri = f"file:{DB_PATH}?mode=ro"
|
| 37 |
+
return sqlite3.connect(uri, uri=True, check_same_thread=False)
|
| 38 |
+
|
| 39 |
+
def init_chat_history_table():
|
| 40 |
+
with get_connection() as conn:
|
| 41 |
+
conn.execute("""
|
| 42 |
+
CREATE TABLE IF NOT EXISTS chat_history (
|
| 43 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 44 |
+
timestamp TEXT,
|
| 45 |
+
user_message TEXT,
|
| 46 |
+
intent TEXT,
|
| 47 |
+
sentiment TEXT,
|
| 48 |
+
resolution TEXT,
|
| 49 |
+
bot_reply TEXT,
|
| 50 |
+
ftr_ms REAL,
|
| 51 |
+
sql_query TEXT,
|
| 52 |
+
sql_params TEXT
|
| 53 |
+
)
|
| 54 |
+
""")
|
| 55 |
+
conn.commit()
|
| 56 |
+
|
| 57 |
+
def save_chat_to_db(user_message, intent, sentiment, resolution, bot_reply, ftr_ms, sql_query, sql_params):
|
| 58 |
+
with get_connection() as conn:
|
| 59 |
+
conn.execute("""
|
| 60 |
+
INSERT INTO chat_history (timestamp, user_message, intent, sentiment, resolution,
|
| 61 |
+
bot_reply, ftr_ms, sql_query, sql_params)
|
| 62 |
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
| 63 |
+
""", (
|
| 64 |
+
datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
|
| 65 |
+
user_message, intent, sentiment, resolution, bot_reply,
|
| 66 |
+
ftr_ms, sql_query, json.dumps(sql_params)
|
| 67 |
+
))
|
| 68 |
+
conn.commit()
|
| 69 |
+
|
| 70 |
+
# ================= FULL INTENTS (Olist tables) =================
|
| 71 |
+
INTENTS = {
|
| 72 |
+
# --- Orders ---
|
| 73 |
+
"order_status": {
|
| 74 |
+
"required": ["order_id"],
|
| 75 |
+
"optional": [],
|
| 76 |
+
"sql": """
|
| 77 |
+
SELECT o.order_id, o.order_status,
|
| 78 |
+
o.order_purchase_timestamp,
|
| 79 |
+
o.order_delivered_customer_date,
|
| 80 |
+
o.order_estimated_delivery_date
|
| 81 |
+
FROM olist_orders o
|
| 82 |
+
WHERE o.order_id = :order_id
|
| 83 |
+
LIMIT 1;
|
| 84 |
+
"""
|
| 85 |
+
},
|
| 86 |
+
"orders_by_city": {
|
| 87 |
+
"required": ["city"],
|
| 88 |
+
"optional": ["start_date","end_date"],
|
| 89 |
+
"sql": """
|
| 90 |
+
SELECT c.customer_city AS city, COUNT(*) AS orders_count
|
| 91 |
+
FROM olist_orders o
|
| 92 |
+
JOIN olist_customers c USING(customer_id)
|
| 93 |
+
WHERE LOWER(c.customer_city) = LOWER(:city)
|
| 94 |
+
AND (:start_date IS NULL OR o.order_purchase_timestamp >= :start_date)
|
| 95 |
+
AND (:end_date IS NULL OR o.order_purchase_timestamp < :end_date)
|
| 96 |
+
GROUP BY c.customer_city;
|
| 97 |
+
"""
|
| 98 |
+
},
|
| 99 |
+
"delivery_delay_metrics": {
|
| 100 |
+
"required": [],
|
| 101 |
+
"optional": ["start_date","end_date"],
|
| 102 |
+
"sql": """
|
| 103 |
+
SELECT ROUND(AVG(JULIANDAY(o.order_delivered_customer_date) -
|
| 104 |
+
JULIANDAY(o.order_estimated_delivery_date)), 2) AS avg_delay_days,
|
| 105 |
+
ROUND(SUM(CASE WHEN o.order_delivered_customer_date IS NOT NULL
|
| 106 |
+
AND o.order_estimated_delivery_date IS NOT NULL
|
| 107 |
+
AND JULIANDAY(o.order_delivered_customer_date) >
|
| 108 |
+
JULIANDAY(o.order_estimated_delivery_date)
|
| 109 |
+
THEN 1 ELSE 0 END)*1.0 /
|
| 110 |
+
SUM(CASE WHEN o.order_delivered_customer_date IS NOT NULL
|
| 111 |
+
AND o.order_estimated_delivery_date IS NOT NULL
|
| 112 |
+
THEN 1 ELSE 0 END), 3) AS late_ratio
|
| 113 |
+
FROM olist_orders o
|
| 114 |
+
WHERE o.order_delivered_customer_date IS NOT NULL
|
| 115 |
+
AND o.order_estimated_delivery_date IS NOT NULL
|
| 116 |
+
AND (:start_date IS NULL OR o.order_purchase_timestamp >= :start_date)
|
| 117 |
+
AND (:end_date IS NULL OR o.order_purchase_timestamp < :end_date);
|
| 118 |
+
"""
|
| 119 |
+
},
|
| 120 |
+
"late_orders_list": {
|
| 121 |
+
"required": [],
|
| 122 |
+
"optional": ["start_date","end_date","limit"],
|
| 123 |
+
"sql": """
|
| 124 |
+
SELECT o.order_id, o.order_purchase_timestamp,
|
| 125 |
+
o.order_delivered_customer_date, o.order_estimated_delivery_date,
|
| 126 |
+
ROUND(JULIANDAY(o.order_delivered_customer_date) -
|
| 127 |
+
JULIANDAY(o.order_estimated_delivery_date), 2) AS delay_days
|
| 128 |
+
FROM olist_orders o
|
| 129 |
+
WHERE o.order_delivered_customer_date IS NOT NULL
|
| 130 |
+
AND o.order_estimated_delivery_date IS NOT NULL
|
| 131 |
+
AND JULIANDAY(o.order_delivered_customer_date) >
|
| 132 |
+
JULIANDAY(o.order_estimated_delivery_date)
|
| 133 |
+
AND (:start_date IS NULL OR o.order_purchase_timestamp >= :start_date)
|
| 134 |
+
AND (:end_date IS NULL OR o.order_purchase_timestamp < :end_date)
|
| 135 |
+
ORDER BY delay_days DESC
|
| 136 |
+
LIMIT :limit;
|
| 137 |
+
"""
|
| 138 |
+
},
|
| 139 |
+
|
| 140 |
+
# --- Products ---
|
| 141 |
+
"top_products_revenue": {
|
| 142 |
+
"required": [],
|
| 143 |
+
"optional": ["start_date","end_date","k"],
|
| 144 |
+
"sql": """
|
| 145 |
+
SELECT i.product_id,
|
| 146 |
+
ROUND(SUM(i.price), 2) AS revenue,
|
| 147 |
+
COUNT(*) AS quantity_sold
|
| 148 |
+
FROM olist_order_items i
|
| 149 |
+
JOIN olist_orders o USING(order_id)
|
| 150 |
+
WHERE (:start_date IS NULL OR o.order_purchase_timestamp >= :start_date)
|
| 151 |
+
AND (:end_date IS NULL OR o.order_purchase_timestamp < :end_date)
|
| 152 |
+
GROUP BY i.product_id
|
| 153 |
+
ORDER BY revenue DESC
|
| 154 |
+
LIMIT :k;
|
| 155 |
+
"""
|
| 156 |
+
},
|
| 157 |
+
"top_products_quantity": {
|
| 158 |
+
"required": [],
|
| 159 |
+
"optional": ["start_date","end_date","k"],
|
| 160 |
+
"sql": """
|
| 161 |
+
SELECT i.product_id,
|
| 162 |
+
COUNT(*) AS quantity_sold,
|
| 163 |
+
ROUND(SUM(i.price), 2) AS revenue
|
| 164 |
+
FROM olist_order_items i
|
| 165 |
+
JOIN olist_orders o USING(order_id)
|
| 166 |
+
WHERE (:start_date IS NULL OR o.order_purchase_timestamp >= :start_date)
|
| 167 |
+
AND (:end_date IS NULL OR o.order_purchase_timestamp < :end_date)
|
| 168 |
+
GROUP BY i.product_id
|
| 169 |
+
ORDER BY quantity_sold DESC
|
| 170 |
+
LIMIT :k;
|
| 171 |
+
"""
|
| 172 |
+
},
|
| 173 |
+
"category_sales": {
|
| 174 |
+
"required": [],
|
| 175 |
+
"optional": ["category","start_date","end_date"],
|
| 176 |
+
"sql": """
|
| 177 |
+
SELECT p.product_category_name, p.product_category_name_english,
|
| 178 |
+
ROUND(SUM(i.price), 2) AS revenue,
|
| 179 |
+
COUNT(*) AS lines
|
| 180 |
+
FROM olist_order_items i
|
| 181 |
+
JOIN olist_orders o USING(order_id)
|
| 182 |
+
JOIN olist_products p USING(product_id)
|
| 183 |
+
WHERE (:category IS NULL
|
| 184 |
+
OR LOWER(p.product_category_name) = LOWER(:category)
|
| 185 |
+
OR LOWER(p.product_category_name_english) = LOWER(:category))
|
| 186 |
+
AND (:start_date IS NULL OR o.order_purchase_timestamp >= :start_date)
|
| 187 |
+
AND (:end_date IS NULL OR o.order_purchase_timestamp < :end_date)
|
| 188 |
+
GROUP BY p.product_category_name, p.product_category_name_english
|
| 189 |
+
ORDER BY revenue DESC;
|
| 190 |
+
"""
|
| 191 |
+
},
|
| 192 |
+
"seller_performance": {
|
| 193 |
+
"required": ["seller_id"],
|
| 194 |
+
"optional": ["start_date","end_date"],
|
| 195 |
+
"sql": """
|
| 196 |
+
SELECT i.seller_id,
|
| 197 |
+
ROUND(SUM(i.price),2) AS revenue,
|
| 198 |
+
COUNT(*) AS items_sold,
|
| 199 |
+
ROUND(AVG(i.freight_value),2) AS avg_freight
|
| 200 |
+
FROM olist_order_items i
|
| 201 |
+
JOIN olist_orders o USING(order_id)
|
| 202 |
+
WHERE i.seller_id = :seller_id
|
| 203 |
+
AND (:start_date IS NULL OR o.order_purchase_timestamp >= :start_date)
|
| 204 |
+
AND (:end_date IS NULL OR o.order_purchase_timestamp < :end_date)
|
| 205 |
+
GROUP BY i.seller_id;
|
| 206 |
+
"""
|
| 207 |
+
},
|
| 208 |
+
|
| 209 |
+
# --- Customers & Geo ---
|
| 210 |
+
"orders_by_state": {
|
| 211 |
+
"required": [],
|
| 212 |
+
"optional": ["start_date","end_date","k"],
|
| 213 |
+
"sql": """
|
| 214 |
+
SELECT c.customer_state, COUNT(*) AS orders_count
|
| 215 |
+
FROM olist_orders o
|
| 216 |
+
JOIN olist_customers c USING(customer_id)
|
| 217 |
+
WHERE (:start_date IS NULL OR o.order_purchase_timestamp >= :start_date)
|
| 218 |
+
AND (:end_date IS NULL OR o.order_purchase_timestamp < :end_date)
|
| 219 |
+
GROUP BY c.customer_state
|
| 220 |
+
ORDER BY orders_count DESC
|
| 221 |
+
LIMIT :k;
|
| 222 |
+
"""
|
| 223 |
+
},
|
| 224 |
+
"repeat_rate": {
|
| 225 |
+
"required": [],
|
| 226 |
+
"optional": ["start_date","end_date"],
|
| 227 |
+
"sql": """
|
| 228 |
+
WITH cust_orders AS (
|
| 229 |
+
SELECT c.customer_unique_id AS cuid, COUNT(*) AS n
|
| 230 |
+
FROM olist_orders o
|
| 231 |
+
JOIN olist_customers c USING(customer_id)
|
| 232 |
+
WHERE (:start_date IS NULL OR o.order_purchase_timestamp >= :start_date)
|
| 233 |
+
AND (:end_date IS NULL OR o.order_purchase_timestamp < :end_date)
|
| 234 |
+
GROUP BY c.customer_unique_id
|
| 235 |
+
)
|
| 236 |
+
SELECT ROUND(SUM(CASE WHEN n>=2 THEN 1 ELSE 0 END)*1.0 / COUNT(*), 3) AS repeat_customer_ratio
|
| 237 |
+
FROM cust_orders;
|
| 238 |
+
"""
|
| 239 |
+
},
|
| 240 |
+
|
| 241 |
+
# --- Payments ---
|
| 242 |
+
"payments_breakdown": {
|
| 243 |
+
"required": [],
|
| 244 |
+
"optional": ["start_date","end_date"],
|
| 245 |
+
"sql": """
|
| 246 |
+
SELECT p.payment_type,
|
| 247 |
+
COUNT(*) AS payments_count,
|
| 248 |
+
ROUND(SUM(p.payment_value),2) AS total_value,
|
| 249 |
+
ROUND(AVG(p.payment_installments),2) AS avg_installments
|
| 250 |
+
FROM olist_order_payments p
|
| 251 |
+
JOIN olist_orders o USING(order_id)
|
| 252 |
+
WHERE (:start_date IS NULL OR o.order_purchase_timestamp >= :start_date)
|
| 253 |
+
AND (:end_date IS NULL OR o.order_purchase_timestamp < :end_date)
|
| 254 |
+
GROUP BY p.payment_type
|
| 255 |
+
ORDER BY total_value DESC;
|
| 256 |
+
"""
|
| 257 |
+
},
|
| 258 |
+
|
| 259 |
+
# --- AOV Trend ---
|
| 260 |
+
"aov_trend_monthly": {
|
| 261 |
+
"required": [],
|
| 262 |
+
"optional": ["start_date","end_date"],
|
| 263 |
+
"sql": """
|
| 264 |
+
WITH order_value AS (
|
| 265 |
+
SELECT o.order_id,
|
| 266 |
+
DATE(o.order_purchase_timestamp, 'start of month') AS month,
|
| 267 |
+
SUM(i.price) AS order_value
|
| 268 |
+
FROM olist_orders o
|
| 269 |
+
JOIN olist_order_items i USING(order_id)
|
| 270 |
+
WHERE (:start_date IS NULL OR o.order_purchase_timestamp >= :start_date)
|
| 271 |
+
AND (:end_date IS NULL OR o.order_purchase_timestamp < :end_date)
|
| 272 |
+
GROUP BY o.order_id, month
|
| 273 |
+
)
|
| 274 |
+
SELECT month, ROUND(AVG(order_value), 2) AS avg_order_value
|
| 275 |
+
FROM order_value
|
| 276 |
+
GROUP BY month
|
| 277 |
+
ORDER BY month;
|
| 278 |
+
"""
|
| 279 |
+
},
|
| 280 |
+
|
| 281 |
+
# --- Reviews ---
|
| 282 |
+
"latest_reviews": {
|
| 283 |
+
"required": [],
|
| 284 |
+
"optional": ["product_id","category","limit"],
|
| 285 |
+
"sql": """
|
| 286 |
+
SELECT r.order_id, r.review_score, r.review_creation_date, r.review_comment_message
|
| 287 |
+
FROM olist_order_reviews r
|
| 288 |
+
WHERE (:product_id IS NULL OR EXISTS (
|
| 289 |
+
SELECT 1 FROM olist_order_items i
|
| 290 |
+
WHERE i.order_id = r.order_id AND i.product_id = :product_id))
|
| 291 |
+
AND (:category IS NULL OR EXISTS (
|
| 292 |
+
SELECT 1 FROM olist_order_items i
|
| 293 |
+
JOIN olist_products p USING(product_id)
|
| 294 |
+
WHERE i.order_id = r.order_id
|
| 295 |
+
AND (LOWER(p.product_category_name) = LOWER(:category)
|
| 296 |
+
OR LOWER(p.product_category_name_english) = LOWER(:category))
|
| 297 |
+
))
|
| 298 |
+
ORDER BY r.review_creation_date DESC
|
| 299 |
+
LIMIT :limit;
|
| 300 |
+
"""
|
| 301 |
+
},
|
| 302 |
+
"rating_summary": {
|
| 303 |
+
"required": [],
|
| 304 |
+
"optional": ["product_id","category","start_date","end_date"],
|
| 305 |
+
"sql": """
|
| 306 |
+
SELECT ROUND(AVG(r.review_score),2) AS avg_rating,
|
| 307 |
+
COUNT(*) AS n_reviews
|
| 308 |
+
FROM olist_order_reviews r
|
| 309 |
+
JOIN olist_orders o ON o.order_id = r.order_id
|
| 310 |
+
WHERE (:start_date IS NULL OR r.review_creation_date >= :start_date)
|
| 311 |
+
AND (:end_date IS NULL OR r.review_creation_date < :end_date)
|
| 312 |
+
AND (:product_id IS NULL OR EXISTS (
|
| 313 |
+
SELECT 1 FROM olist_order_items i
|
| 314 |
+
WHERE i.order_id = r.order_id AND i.product_id = :product_id))
|
| 315 |
+
AND (:category IS NULL OR EXISTS (
|
| 316 |
+
SELECT 1 FROM olist_order_items i
|
| 317 |
+
JOIN olist_products p USING(product_id)
|
| 318 |
+
WHERE i.order_id = r.order_id AND
|
| 319 |
+
(LOWER(p.product_category_name) = LOWER(:category) OR
|
| 320 |
+
LOWER(p.product_category_name_english) = LOWER(:category))
|
| 321 |
+
));
|
| 322 |
+
"""
|
| 323 |
+
},
|
| 324 |
+
}
|
| 325 |
+
|
| 326 |
+
# Intent keywords to validate mapping (helps reject garbage)
|
| 327 |
+
INTENT_KEYWORDS = {
|
| 328 |
+
"order_status": ["order", "status", "track", "tracking", "delivered", "delivery", "estimate", "order id"],
|
| 329 |
+
"orders_by_city": ["city", "town", "municipality"],
|
| 330 |
+
"delivery_delay_metrics": ["delay", "late", "delivery time", "estimated", "sla"],
|
| 331 |
+
"late_orders_list": ["late", "delayed", "overdue"],
|
| 332 |
+
"top_products_revenue": ["top", "revenue", "sales", "gross", "gmv"],
|
| 333 |
+
"top_products_quantity": ["top", "quantity", "units", "sold", "bestseller"],
|
| 334 |
+
"category_sales": ["category", "department", "sales by category"],
|
| 335 |
+
"seller_performance": ["seller", "merchant", "vendor", "performance"],
|
| 336 |
+
"orders_by_state": ["state", "region", "province"],
|
| 337 |
+
"repeat_rate": ["repeat", "retention", "returning"],
|
| 338 |
+
"payments_breakdown": ["payment", "installments", "card", "boleto", "pix", "method"],
|
| 339 |
+
"aov_trend_monthly": ["aov", "average order value", "trend", "monthly"],
|
| 340 |
+
"latest_reviews": ["review", "comment", "feedback", "opinion", "rating"],
|
| 341 |
+
"rating_summary": ["rating", "score", "stars", "nps", "csat"],
|
| 342 |
+
}
|
| 343 |
+
|
| 344 |
+
def _has_overlap(intent: str, text: str) -> bool:
|
| 345 |
+
kws = INTENT_KEYWORDS.get(intent, [])
|
| 346 |
+
if not kws:
|
| 347 |
+
return True
|
| 348 |
+
t = text.lower()
|
| 349 |
+
return any(re.search(r"\b" + re.escape(kw.lower()) + r"\b", t) for kw in kws)
|
| 350 |
+
|
| 351 |
+
# ================= GPT HELPERS (v1 client) =================
|
| 352 |
+
def gpt_classify_intent(user_text: str) -> dict:
|
| 353 |
+
"""
|
| 354 |
+
Returns: {"intent": <key|UNMAPPED>, "confidence": float, "reason": str}
|
| 355 |
+
"""
|
| 356 |
+
options = list(INTENTS.keys())
|
| 357 |
+
system = (
|
| 358 |
+
"You are an intent classifier for an e-commerce analytics chatbot. "
|
| 359 |
+
"You MUST return strict JSON. If none of the intents clearly applies, return UNMAPPED."
|
| 360 |
+
)
|
| 361 |
+
user = (
|
| 362 |
+
"Available intents (keys): " + ", ".join(options) + "\n"
|
| 363 |
+
"Task: Choose the single BEST matching intent key OR 'UNMAPPED' if none clearly fits.\n"
|
| 364 |
+
"Output STRICT JSON with fields: intent (string), confidence (0.0-1.0), reason (short string).\n"
|
| 365 |
+
"Do NOT guess. If the message is unrelated, return UNMAPPED.\n\n"
|
| 366 |
+
f"Message: {user_text}"
|
| 367 |
+
)
|
| 368 |
+
resp = client.chat.completions.create(
|
| 369 |
+
model="gpt-3.5-turbo",
|
| 370 |
+
messages=[{"role":"system","content": system},
|
| 371 |
+
{"role":"user","content": user}],
|
| 372 |
+
temperature=0
|
| 373 |
+
)
|
| 374 |
+
txt = resp.choices[0].message.content.strip()
|
| 375 |
+
try:
|
| 376 |
+
data = json.loads(txt)
|
| 377 |
+
raw_intent = str(data.get("intent","")).strip().lower()
|
| 378 |
+
if raw_intent == "" or raw_intent in ("none","n/a","unknown"):
|
| 379 |
+
data["intent"] = "UNMAPPED"
|
| 380 |
+
else:
|
| 381 |
+
if raw_intent not in [k.lower() for k in INTENTS.keys()] and raw_intent != "unmapped":
|
| 382 |
+
data["intent"] = "UNMAPPED"
|
| 383 |
+
else:
|
| 384 |
+
for k in INTENTS.keys():
|
| 385 |
+
if k.lower() == raw_intent:
|
| 386 |
+
data["intent"] = k
|
| 387 |
+
break
|
| 388 |
+
try:
|
| 389 |
+
c = float(data.get("confidence", 0))
|
| 390 |
+
data["confidence"] = max(0.0, min(1.0, c))
|
| 391 |
+
except Exception:
|
| 392 |
+
data["confidence"] = 0.0
|
| 393 |
+
data["reason"] = str(data.get("reason","")).strip()
|
| 394 |
+
return data
|
| 395 |
+
except Exception:
|
| 396 |
+
return {"intent":"UNMAPPED","confidence":0.0,"reason":"parse_error"}
|
| 397 |
+
|
| 398 |
+
def gpt_classify_sentiment(user_text: str) -> str:
|
| 399 |
+
prompt = "Classify sentiment as Positive, Negative, or Neutral.\n\nMessage: " + user_text
|
| 400 |
+
resp = client.chat.completions.create(
|
| 401 |
+
model="gpt-3.5-turbo",
|
| 402 |
+
messages=[
|
| 403 |
+
{"role":"system","content":"You are a sentiment classifier."},
|
| 404 |
+
{"role":"user","content": prompt}
|
| 405 |
+
],
|
| 406 |
+
temperature=0
|
| 407 |
+
)
|
| 408 |
+
return resp.choices[0].message.content.strip()
|
| 409 |
+
|
| 410 |
+
def gpt_extract_params(intent_key: str, user_text: str) -> dict:
|
| 411 |
+
if intent_key not in INTENTS:
|
| 412 |
+
return {}
|
| 413 |
+
cfg = INTENTS[intent_key]
|
| 414 |
+
param_list = cfg["required"] + cfg["optional"]
|
| 415 |
+
prompt = (
|
| 416 |
+
"Extract the following parameters from the user's query and return STRICT JSON only.\n"
|
| 417 |
+
f"Keys: {param_list}. If a parameter is missing set it to null. "
|
| 418 |
+
"Dates may be natural language; return them as-is.\n\n"
|
| 419 |
+
f"User query: {user_text}"
|
| 420 |
+
)
|
| 421 |
+
resp = client.chat.completions.create(
|
| 422 |
+
model="gpt-3.5-turbo",
|
| 423 |
+
messages=[
|
| 424 |
+
{"role":"system","content":"You extract parameters and ONLY output valid JSON."},
|
| 425 |
+
{"role":"user","content": prompt}
|
| 426 |
+
],
|
| 427 |
+
temperature=0
|
| 428 |
+
)
|
| 429 |
+
txt = resp.choices[0].message.content.strip()
|
| 430 |
+
try:
|
| 431 |
+
params = json.loads(txt)
|
| 432 |
+
except Exception:
|
| 433 |
+
params = {p: None for p in param_list}
|
| 434 |
+
return params
|
| 435 |
+
|
| 436 |
+
def gpt_fallback_response(user_text: str) -> str:
|
| 437 |
+
"""
|
| 438 |
+
Generate a helpful reply when no intent matches.
|
| 439 |
+
"""
|
| 440 |
+
options = list(INTENTS.keys())
|
| 441 |
+
system = (
|
| 442 |
+
"You are a helpful support agent for an e-commerce analytics chatbot. "
|
| 443 |
+
"The app could not map the user's request to any known intent/SQL template. "
|
| 444 |
+
"Be helpful: either answer conversationally, gather missing details with specific "
|
| 445 |
+
"questions, or suggest the closest capability."
|
| 446 |
+
)
|
| 447 |
+
user = (
|
| 448 |
+
"No matching intent was found for the following message.\n"
|
| 449 |
+
f"Known intents are: {options}\n\n"
|
| 450 |
+
f"User message: {user_text}\n\n"
|
| 451 |
+
"Please provide a concise, helpful response. If appropriate, suggest the nearest "
|
| 452 |
+
"matching capability from the list above or ask one or two targeted follow-up questions."
|
| 453 |
+
)
|
| 454 |
+
resp = client.chat.completions.create(
|
| 455 |
+
model="gpt-3.5-turbo",
|
| 456 |
+
messages=[{"role":"system","content": system},
|
| 457 |
+
{"role":"user","content": user}],
|
| 458 |
+
temperature=0.3
|
| 459 |
+
)
|
| 460 |
+
return resp.choices[0].message.content.strip()
|
| 461 |
+
|
| 462 |
+
def gpt_label_unmapped(user_text: str) -> str:
|
| 463 |
+
"""
|
| 464 |
+
Classify unmapped messages into a small taxonomy.
|
| 465 |
+
Return one of: greeting, clarification, thanks, complaint, small_talk, farewell, other
|
| 466 |
+
"""
|
| 467 |
+
system = (
|
| 468 |
+
"You label short messages into one category: "
|
| 469 |
+
"greeting | clarification | thanks | complaint | small_talk | farewell | other. "
|
| 470 |
+
"Return ONLY the label, nothing else."
|
| 471 |
+
)
|
| 472 |
+
user = f"Message: {user_text}"
|
| 473 |
+
resp = client.chat.completions.create(
|
| 474 |
+
model="gpt-3.5-turbo",
|
| 475 |
+
messages=[{"role":"system","content": system},
|
| 476 |
+
{"role":"user","content": user}],
|
| 477 |
+
temperature=0
|
| 478 |
+
)
|
| 479 |
+
label = resp.choices[0].message.content.strip().lower()
|
| 480 |
+
allowed = {"greeting","clarification","thanks","complaint","small_talk","farewell","other"}
|
| 481 |
+
return label if label in allowed else "other"
|
| 482 |
+
|
| 483 |
+
|
| 484 |
+
# ================= PARAM PROCESSING (strict & safe) =================
|
| 485 |
+
def process_params(intent_key: str, params: dict) -> dict:
|
| 486 |
+
if params is None:
|
| 487 |
+
params = {}
|
| 488 |
+
cfg = INTENTS[intent_key]
|
| 489 |
+
required = cfg.get("required", [])
|
| 490 |
+
optional = cfg.get("optional", [])
|
| 491 |
+
allowed_keys = set(required + optional)
|
| 492 |
+
|
| 493 |
+
# Keep only allowed keys
|
| 494 |
+
clean = {k: params.get(k) for k in allowed_keys}
|
| 495 |
+
|
| 496 |
+
# Defaults for numeric limits
|
| 497 |
+
if "k" in allowed_keys:
|
| 498 |
+
v = clean.get("k")
|
| 499 |
+
try:
|
| 500 |
+
clean["k"] = int(str(v).strip()) if v not in (None, "", "null", "None") else 10
|
| 501 |
+
except Exception:
|
| 502 |
+
clean["k"] = 10
|
| 503 |
+
if "limit" in allowed_keys:
|
| 504 |
+
v = clean.get("limit")
|
| 505 |
+
try:
|
| 506 |
+
clean["limit"] = int(str(v).strip()) if v not in (None, "", "null", "None") else 50
|
| 507 |
+
except Exception:
|
| 508 |
+
clean["limit"] = 50
|
| 509 |
+
|
| 510 |
+
# Common optional fields
|
| 511 |
+
for k in ("start_date", "end_date", "category", "product_id", "city", "seller_id", "order_id"):
|
| 512 |
+
if k in allowed_keys and k not in clean:
|
| 513 |
+
clean[k] = None
|
| 514 |
+
|
| 515 |
+
# Parse NL dates
|
| 516 |
+
for k in ("start_date", "end_date"):
|
| 517 |
+
if k in clean:
|
| 518 |
+
v = clean.get(k)
|
| 519 |
+
if v and str(v).strip().lower() not in ("none", "null", ""):
|
| 520 |
+
parsed = dateparser.parse(str(v))
|
| 521 |
+
clean[k] = parsed.strftime("%Y-%m-%d") if parsed else None
|
| 522 |
+
else:
|
| 523 |
+
clean[k] = None
|
| 524 |
+
return clean
|
| 525 |
+
|
| 526 |
+
# ================= RUN INTENT (SQLite) =================
|
| 527 |
+
def run_intent(intent_key: str, params: dict):
|
| 528 |
+
cfg = INTENTS[intent_key]
|
| 529 |
+
sql = cfg["sql"]
|
| 530 |
+
required = cfg.get("required", [])
|
| 531 |
+
optional = cfg.get("optional", [])
|
| 532 |
+
allowed_keys = set(required + optional)
|
| 533 |
+
|
| 534 |
+
bound = {k: params.get(k) for k in allowed_keys}
|
| 535 |
+
|
| 536 |
+
# Ensure LIMIT ints
|
| 537 |
+
if "k" in allowed_keys:
|
| 538 |
+
try:
|
| 539 |
+
bound["k"] = int(bound.get("k", 10))
|
| 540 |
+
except Exception:
|
| 541 |
+
bound["k"] = 10
|
| 542 |
+
if "limit" in allowed_keys:
|
| 543 |
+
try:
|
| 544 |
+
bound["limit"] = int(bound.get("limit", 50))
|
| 545 |
+
except Exception:
|
| 546 |
+
bound["limit"] = 50
|
| 547 |
+
|
| 548 |
+
# Dates: ensure None or ISO string
|
| 549 |
+
for k in ("start_date","end_date"):
|
| 550 |
+
if k in bound:
|
| 551 |
+
v = bound[k]
|
| 552 |
+
if v is not None and not isinstance(v, str):
|
| 553 |
+
try:
|
| 554 |
+
bound[k] = v.strftime("%Y-%m-%d")
|
| 555 |
+
except Exception:
|
| 556 |
+
bound[k] = None
|
| 557 |
+
|
| 558 |
+
logging.info(f"SQL intent={intent_key} | params={ {k: (type(v).__name__, v) for k,v in bound.items()} }")
|
| 559 |
+
|
| 560 |
+
with get_connection() as conn:
|
| 561 |
+
cur = conn.cursor()
|
| 562 |
+
cur.execute(sql, bound)
|
| 563 |
+
rows = cur.fetchall()
|
| 564 |
+
col_names = [d[0] for d in cur.description]
|
| 565 |
+
return rows, col_names, sql
|
| 566 |
+
|
| 567 |
+
# ================= STREAMLIT APP =================
|
| 568 |
+
st.set_page_config(page_title="Olist Chatbot", layout="wide")
|
| 569 |
+
init_chat_history_table()
|
| 570 |
+
|
| 571 |
+
tab1, tab2, tab3 = st.tabs(["💬 Chat", "📊 MIS", "📥 Export"])
|
| 572 |
+
|
| 573 |
+
# ---------- TAB 1: Chat ----------
|
| 574 |
+
with tab1:
|
| 575 |
+
st.title("📦 Olist E-commerce Chatbot")
|
| 576 |
+
|
| 577 |
+
# session-state setup
|
| 578 |
+
if "history" not in st.session_state:
|
| 579 |
+
st.session_state.history = []
|
| 580 |
+
if "clear_input" not in st.session_state:
|
| 581 |
+
st.session_state.clear_input = False
|
| 582 |
+
if "user_input" not in st.session_state:
|
| 583 |
+
st.session_state.user_input = ""
|
| 584 |
+
|
| 585 |
+
# auto-clear (must occur BEFORE widget instantiation)
|
| 586 |
+
if st.session_state.clear_input:
|
| 587 |
+
st.session_state.user_input = ""
|
| 588 |
+
st.session_state.clear_input = False
|
| 589 |
+
|
| 590 |
+
user_input = st.text_input("You:", key="user_input")
|
| 591 |
+
show_hist = st.checkbox("Show conversation history (current session)")
|
| 592 |
+
|
| 593 |
+
# --- Submit handler ---
|
| 594 |
+
if st.button("Submit"):
|
| 595 |
+
if st.session_state.user_input.strip():
|
| 596 |
+
start_time = time.time()
|
| 597 |
+
current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
| 598 |
+
user_text = st.session_state.user_input
|
| 599 |
+
|
| 600 |
+
# 1) Intent (with UNMAPPED) & Sentiment
|
| 601 |
+
cls = gpt_classify_intent(user_text) # dict
|
| 602 |
+
intent = cls.get("intent", "UNMAPPED")
|
| 603 |
+
confidence = cls.get("confidence", 0.0)
|
| 604 |
+
reason = cls.get("reason", "")
|
| 605 |
+
logger.info(f"Intent -> '{intent}', conf={confidence}, reason='{reason}' | text='{user_text}'")
|
| 606 |
+
|
| 607 |
+
sentiment = gpt_classify_sentiment(user_text)
|
| 608 |
+
|
| 609 |
+
# Keyword validation: if no overlap, force UNMAPPED
|
| 610 |
+
if intent != "UNMAPPED" and not _has_overlap(intent, user_text):
|
| 611 |
+
logger.info(f"Keyword validation failed for intent='{intent}' → forcing UNMAPPED")
|
| 612 |
+
intent = "UNMAPPED"
|
| 613 |
+
|
| 614 |
+
sql_query = ""
|
| 615 |
+
table_cols, table_rows = None, None
|
| 616 |
+
|
| 617 |
+
if intent == "UNMAPPED":
|
| 618 |
+
# Meta label for better UX
|
| 619 |
+
meta = gpt_label_unmapped(user_text)
|
| 620 |
+
intent = f"{meta}" # <-- store combined string, no DB migration needed
|
| 621 |
+
bot_reply = gpt_fallback_response(user_text)
|
| 622 |
+
resolution = "Responded"
|
| 623 |
+
else:
|
| 624 |
+
# 2) Extract + process params
|
| 625 |
+
params = gpt_extract_params(intent, user_text)
|
| 626 |
+
params = process_params(intent, params)
|
| 627 |
+
|
| 628 |
+
# 3) Required params check
|
| 629 |
+
required = INTENTS[intent]["required"]
|
| 630 |
+
missing = [p for p in required if not params.get(p)]
|
| 631 |
+
|
| 632 |
+
if missing:
|
| 633 |
+
bot_reply = f"Could you please provide the following information: {', '.join(missing)}"
|
| 634 |
+
resolution = "Unresolved"
|
| 635 |
+
else:
|
| 636 |
+
rows, col_names, sql_query = run_intent(intent, params)
|
| 637 |
+
if rows:
|
| 638 |
+
table_cols, table_rows = col_names, rows
|
| 639 |
+
bot_reply = "Please see the table above for results."
|
| 640 |
+
resolution = "Resolved"
|
| 641 |
+
else:
|
| 642 |
+
bot_reply = "No data found."
|
| 643 |
+
resolution = "Unresolved"
|
| 644 |
+
|
| 645 |
+
ftr_ms = round((time.time() - start_time) * 1000, 2)
|
| 646 |
+
|
| 647 |
+
# 4) Session history + DB persistence
|
| 648 |
+
entry = {
|
| 649 |
+
"timestamp": current_time,
|
| 650 |
+
"user": user_text,
|
| 651 |
+
"intent": intent,
|
| 652 |
+
"sentiment": sentiment,
|
| 653 |
+
"resolution": resolution,
|
| 654 |
+
"reply": bot_reply,
|
| 655 |
+
"ftr_ms": ftr_ms,
|
| 656 |
+
"table_cols": table_cols, # session-only
|
| 657 |
+
"table_rows": table_rows, # session-only
|
| 658 |
+
}
|
| 659 |
+
st.session_state.history.append(entry)
|
| 660 |
+
if len(st.session_state.history) > MAX_HISTORY:
|
| 661 |
+
st.session_state.history.pop(0)
|
| 662 |
+
|
| 663 |
+
# Persist (store params only when intent mapped)
|
| 664 |
+
try:
|
| 665 |
+
save_chat_to_db(user_text, intent, sentiment, resolution, bot_reply, ftr_ms, sql_query,
|
| 666 |
+
params if intent != "UNMAPPED" else {})
|
| 667 |
+
except Exception:
|
| 668 |
+
logger.exception("Failed to save chat history to DB")
|
| 669 |
+
|
| 670 |
+
# request input clear on next render and rerun
|
| 671 |
+
st.session_state.clear_input = True
|
| 672 |
+
try:
|
| 673 |
+
st.rerun()
|
| 674 |
+
except Exception:
|
| 675 |
+
st.experimental_rerun()
|
| 676 |
+
|
| 677 |
+
# --- Renderer for one turn ---
|
| 678 |
+
def render_turn(turn):
|
| 679 |
+
ts = turn["timestamp"]
|
| 680 |
+
user_text = turn["user"]
|
| 681 |
+
intent_display = turn["intent"] if turn["intent"] else "UNMAPPED"
|
| 682 |
+
sentiment = turn["sentiment"]
|
| 683 |
+
resolution = turn["resolution"]
|
| 684 |
+
bot_reply = turn["reply"]
|
| 685 |
+
table_cols = turn.get("table_cols")
|
| 686 |
+
table_rows = turn.get("table_rows")
|
| 687 |
+
|
| 688 |
+
# Customer bubble
|
| 689 |
+
st.markdown(
|
| 690 |
+
f"""
|
| 691 |
+
<div style='background-color:#e6f2ff;padding:10px;border-radius:10px;max-width:80%;margin-bottom:5px;'>
|
| 692 |
+
<div style='font-size:0.8em;color:gray;'>{ts}</div>
|
| 693 |
+
<b>Customer:</b> {user_text}
|
| 694 |
+
</div>
|
| 695 |
+
""",
|
| 696 |
+
unsafe_allow_html=True
|
| 697 |
+
)
|
| 698 |
+
# Platform Analysis
|
| 699 |
+
st.markdown(
|
| 700 |
+
f"""
|
| 701 |
+
<div style='background-color:#ffffff;padding:10px;border-radius:10px;max-width:80%;margin-bottom:5px;'>
|
| 702 |
+
<b>Platform Analysis:</b><br>
|
| 703 |
+
<b>Intent Analysis:</b> {intent_display}<br>
|
| 704 |
+
<b>Sentiment Analysis:</b> {sentiment}<br>
|
| 705 |
+
<b>Resolution Status:</b> {resolution}
|
| 706 |
+
</div>
|
| 707 |
+
""",
|
| 708 |
+
unsafe_allow_html=True
|
| 709 |
+
)
|
| 710 |
+
# Table (if any)
|
| 711 |
+
if table_cols and table_rows:
|
| 712 |
+
df_result = pd.DataFrame(table_rows, columns=table_cols)
|
| 713 |
+
st.table(df_result)
|
| 714 |
+
# Agent bubble
|
| 715 |
+
st.markdown(
|
| 716 |
+
f"""
|
| 717 |
+
<div style='background-color:#e6ffe6;padding:10px;border-radius:10px;max-width:80%;margin-bottom:20px;margin-left:auto;'>
|
| 718 |
+
<div style='font-size:0.8em;color:gray;'>{ts}</div>
|
| 719 |
+
<b>Support Agent:</b> {bot_reply}
|
| 720 |
+
</div>
|
| 721 |
+
""",
|
| 722 |
+
unsafe_allow_html=True
|
| 723 |
+
)
|
| 724 |
+
|
| 725 |
+
# --- Always show the latest turn; optionally show full session history ---
|
| 726 |
+
if st.session_state.history:
|
| 727 |
+
st.subheader("Conversation")
|
| 728 |
+
if show_hist:
|
| 729 |
+
for turn in st.session_state.history[-MAX_HISTORY:]:
|
| 730 |
+
render_turn(turn)
|
| 731 |
+
else:
|
| 732 |
+
render_turn(st.session_state.history[-1])
|
| 733 |
+
|
| 734 |
+
# --- TAB 2: MIS ---
|
| 735 |
+
with tab2:
|
| 736 |
+
st.title("📊 Advanced MIS Dashboard")
|
| 737 |
+
|
| 738 |
+
with get_connection() as conn:
|
| 739 |
+
df_all = pd.read_sql_query("SELECT * FROM chat_history", conn)
|
| 740 |
+
|
| 741 |
+
if df_all.empty:
|
| 742 |
+
st.info("No chats logged yet.")
|
| 743 |
+
else:
|
| 744 |
+
# Prep
|
| 745 |
+
df_all["timestamp"] = pd.to_datetime(df_all["timestamp"], errors="coerce")
|
| 746 |
+
df_all["date"] = df_all["timestamp"].dt.date
|
| 747 |
+
# Filters
|
| 748 |
+
min_d = df_all["date"].min()
|
| 749 |
+
max_d = df_all["date"].max()
|
| 750 |
+
c1, c2 = st.columns([2, 3])
|
| 751 |
+
with c1:
|
| 752 |
+
date_range = st.date_input("Date range", value=[min_d, max_d], min_value=min_d, max_value=max_d)
|
| 753 |
+
with c2:
|
| 754 |
+
all_intents = sorted([x for x in df_all["intent"].dropna().unique().tolist()])
|
| 755 |
+
intent_filter = st.multiselect("Filter by intent(s)", options=all_intents, default=all_intents)
|
| 756 |
+
|
| 757 |
+
# Apply filters
|
| 758 |
+
if isinstance(date_range, (list, tuple)) and len(date_range) == 2:
|
| 759 |
+
start_d, end_d = date_range
|
| 760 |
+
else:
|
| 761 |
+
start_d, end_d = min_d, max_d
|
| 762 |
+
|
| 763 |
+
mask = (df_all["date"] >= start_d) & (df_all["date"] <= end_d)
|
| 764 |
+
if intent_filter:
|
| 765 |
+
mask &= df_all["intent"].isin(intent_filter)
|
| 766 |
+
df = df_all.loc[mask].copy()
|
| 767 |
+
|
| 768 |
+
if df.empty:
|
| 769 |
+
st.warning("No data for the selected filters.")
|
| 770 |
+
st.stop()
|
| 771 |
+
|
| 772 |
+
# KPIs
|
| 773 |
+
total_chats = len(df)
|
| 774 |
+
resolved_pct = (df["resolution"] == "Resolved").mean() if total_chats else 0.0
|
| 775 |
+
avg_ftr = df["ftr_ms"].mean() if total_chats else 0.0
|
| 776 |
+
p95_ftr = df["ftr_ms"].quantile(0.95) if total_chats else 0.0
|
| 777 |
+
sla_ms = int(os.getenv("SLA_MS", "1500"))
|
| 778 |
+
sla_pct = (df["ftr_ms"] <= sla_ms).mean() if total_chats else 0.0
|
| 779 |
+
|
| 780 |
+
k1,k2,k3,k4,k5 = st.columns(5)
|
| 781 |
+
k1.metric("Total chats", f"{total_chats}")
|
| 782 |
+
k2.metric("Resolved %", f"{resolved_pct*100:.1f}%")
|
| 783 |
+
k3.metric("Avg FTR (ms)", f"{avg_ftr:.0f}")
|
| 784 |
+
k4.metric("P95 FTR (ms)", f"{p95_ftr:.0f}")
|
| 785 |
+
k5.metric(f"SLA ≤ {sla_ms} ms", f"{sla_pct*100:.1f}%")
|
| 786 |
+
|
| 787 |
+
st.markdown("---")
|
| 788 |
+
|
| 789 |
+
# Intent performance table
|
| 790 |
+
perf = (
|
| 791 |
+
df.groupby("intent")
|
| 792 |
+
.agg(
|
| 793 |
+
total=("intent","size"),
|
| 794 |
+
resolved_pct=("resolution", lambda s: (s == "Resolved").mean()),
|
| 795 |
+
avg_ftr_ms=("ftr_ms","mean")
|
| 796 |
+
)
|
| 797 |
+
.sort_values("total", ascending=False)
|
| 798 |
+
)
|
| 799 |
+
perf["resolved_pct"] = (perf["resolved_pct"]*100).round(1)
|
| 800 |
+
perf["avg_ftr_ms"] = perf["avg_ftr_ms"].round(0)
|
| 801 |
+
st.subheader("Intent performance")
|
| 802 |
+
st.dataframe(perf.reset_index())
|
| 803 |
+
|
| 804 |
+
st.markdown("---")
|
| 805 |
+
|
| 806 |
+
# Volume over time
|
| 807 |
+
st.subheader("Daily chat volume")
|
| 808 |
+
daily = df.groupby("date").size().reset_index(name="count")
|
| 809 |
+
fig_vol, ax_vol = plt.subplots()
|
| 810 |
+
ax_vol.plot(daily["date"], daily["count"])
|
| 811 |
+
ax_vol.set_xlabel("Date")
|
| 812 |
+
ax_vol.set_ylabel("Chats")
|
| 813 |
+
ax_vol.set_title("Chats per day")
|
| 814 |
+
st.pyplot(fig_vol)
|
| 815 |
+
|
| 816 |
+
# Sentiment trend (daily)
|
| 817 |
+
st.subheader("Sentiment trend (daily)")
|
| 818 |
+
sent_daily = (
|
| 819 |
+
df.pivot_table(index="date", columns="sentiment", values="id", aggfunc="count")
|
| 820 |
+
.fillna(0)
|
| 821 |
+
.sort_index()
|
| 822 |
+
)
|
| 823 |
+
fig_sent, ax_sent = plt.subplots()
|
| 824 |
+
for col in sent_daily.columns:
|
| 825 |
+
ax_sent.plot(sent_daily.index, sent_daily[col], label=str(col))
|
| 826 |
+
ax_sent.set_xlabel("Date")
|
| 827 |
+
ax_sent.set_ylabel("Count")
|
| 828 |
+
ax_sent.set_title("Daily sentiment counts")
|
| 829 |
+
ax_sent.legend()
|
| 830 |
+
st.pyplot(fig_sent)
|
| 831 |
+
|
| 832 |
+
# Top intents (bar)
|
| 833 |
+
st.subheader("Top intents")
|
| 834 |
+
top_intents = df["intent"].value_counts().head(10)
|
| 835 |
+
fig_int, ax_int = plt.subplots()
|
| 836 |
+
ax_int.bar(top_intents.index.astype(str), top_intents.values)
|
| 837 |
+
ax_int.set_ylabel("Count")
|
| 838 |
+
ax_int.set_title("Top 10 intents")
|
| 839 |
+
plt.setp(ax_int.get_xticklabels(), rotation=30, ha="right")
|
| 840 |
+
st.pyplot(fig_int)
|
| 841 |
+
|
| 842 |
+
# FTR distribution (hist)
|
| 843 |
+
st.subheader("FTR distribution")
|
| 844 |
+
fig_ftr, ax_ftr = plt.subplots()
|
| 845 |
+
ax_ftr.hist(df["ftr_ms"].dropna(), bins=20)
|
| 846 |
+
ax_ftr.set_xlabel("FTR (ms)")
|
| 847 |
+
ax_ftr.set_ylabel("Frequency")
|
| 848 |
+
ax_ftr.set_title("FTR histogram")
|
| 849 |
+
st.pyplot(fig_ftr)
|
| 850 |
+
|
| 851 |
+
st.markdown("---")
|
| 852 |
+
|
| 853 |
+
# Recent interactions (last 50)
|
| 854 |
+
st.subheader("Recent interactions")
|
| 855 |
+
cols = ["timestamp","user_message","intent","sentiment","resolution","ftr_ms","sql_query","sql_params","bot_reply"]
|
| 856 |
+
show_cols = [c for c in cols if c in df.columns]
|
| 857 |
+
st.dataframe(df.sort_values("timestamp", ascending=False).head(50)[show_cols])
|
| 858 |
+
|
| 859 |
+
# ---------- TAB 3: Export ----------
|
| 860 |
+
with tab3:
|
| 861 |
+
st.title("📥 Export Chat History")
|
| 862 |
+
scope = st.radio("Select scope to export:", ["Session only", "Full history"])
|
| 863 |
+
|
| 864 |
+
if scope == "Session only":
|
| 865 |
+
export_df = pd.DataFrame(st.session_state.history)
|
| 866 |
+
if not export_df.empty:
|
| 867 |
+
export_df = export_df.rename(columns={"user":"user_message","reply":"bot_reply"})
|
| 868 |
+
# normalize columns to match DB export
|
| 869 |
+
for col in ["timestamp","user_message","intent","sentiment","resolution","bot_reply","ftr_ms","sql_query","sql_params"]:
|
| 870 |
+
if col not in export_df.columns:
|
| 871 |
+
export_df[col] = None
|
| 872 |
+
export_df = export_df[["timestamp","user_message","intent","sentiment","resolution","bot_reply","ftr_ms","sql_query","sql_params"]]
|
| 873 |
+
else:
|
| 874 |
+
with get_connection() as conn:
|
| 875 |
+
export_df = pd.read_sql_query("SELECT * FROM chat_history", conn)
|
| 876 |
+
|
| 877 |
+
if export_df is not None and not export_df.empty:
|
| 878 |
+
# CSV
|
| 879 |
+
csv_bytes = export_df.to_csv(index=False).encode("utf-8")
|
| 880 |
+
st.download_button(
|
| 881 |
+
"Download as CSV",
|
| 882 |
+
data=csv_bytes,
|
| 883 |
+
file_name=f"chat_export_{datetime.now().strftime('%Y%m%d_%H%M%S')}.csv",
|
| 884 |
+
mime="text/csv"
|
| 885 |
+
)
|
| 886 |
+
# TXT
|
| 887 |
+
txt_lines = []
|
| 888 |
+
for _, row in export_df.iterrows():
|
| 889 |
+
ts = row.get("timestamp", "")
|
| 890 |
+
user_msg = row.get("user_message", "")
|
| 891 |
+
intent = row.get("intent", "")
|
| 892 |
+
sentiment = row.get("sentiment", "")
|
| 893 |
+
res = row.get("resolution", "")
|
| 894 |
+
bot = row.get("bot_reply", "")
|
| 895 |
+
txt_lines.append(f"[{ts}] Customer: {user_msg}")
|
| 896 |
+
txt_lines.append(f"Intent: {intent} | Sentiment: {sentiment} | Resolution: {res}")
|
| 897 |
+
txt_lines.append(f"Support Agent: {bot}")
|
| 898 |
+
txt_lines.append("---")
|
| 899 |
+
txt_bytes = "\n".join(txt_lines).encode("utf-8")
|
| 900 |
+
st.download_button(
|
| 901 |
+
"Download as TXT",
|
| 902 |
+
data=txt_bytes,
|
| 903 |
+
file_name=f"chat_export_{datetime.now().strftime('%Y%m%d_%H%M%S')}.txt",
|
| 904 |
+
mime="text/plain"
|
| 905 |
+
)
|
| 906 |
+
else:
|
| 907 |
+
st.info("No history to export.")
|