Spaces:
Sleeping
Sleeping
Update src/admin_export.py
Browse files- src/admin_export.py +254 -257
src/admin_export.py
CHANGED
|
@@ -1,288 +1,285 @@
|
|
| 1 |
# src/admin_export.py
|
| 2 |
-
|
| 3 |
import io
|
| 4 |
-
import os
|
| 5 |
-
import tempfile
|
| 6 |
from datetime import datetime, timedelta
|
|
|
|
| 7 |
|
| 8 |
-
import pandas as pd
|
| 9 |
import streamlit as st
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
#
|
| 28 |
-
#
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
|
|
|
|
|
|
| 33 |
SELECT id, username, email
|
| 34 |
FROM users
|
| 35 |
-
WHERE
|
| 36 |
-
ORDER BY
|
| 37 |
-
LIMIT
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
|
|
|
| 41 |
return [dict(r) for r in rows]
|
| 42 |
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
SELECT id, timestamp, user_message, bot_reply, intent, sentiment, resolution, ftr_ms
|
| 48 |
FROM chat_history
|
| 49 |
WHERE user_id = ?
|
| 50 |
-
AND
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
).fetchall()
|
| 55 |
return [dict(r) for r in rows]
|
| 56 |
|
| 57 |
-
# =========================
|
| 58 |
-
# TXT / CSV exports
|
| 59 |
-
# =========================
|
| 60 |
-
def export_txt(conn, ids):
|
| 61 |
-
if not ids:
|
| 62 |
-
st.warning("Select at least one record."); return
|
| 63 |
-
cur = conn.execute(
|
| 64 |
-
f"""
|
| 65 |
-
SELECT timestamp, user_message, bot_reply
|
| 66 |
-
FROM chat_history
|
| 67 |
-
WHERE id IN ({','.join('?' * len(ids))})
|
| 68 |
-
ORDER BY timestamp
|
| 69 |
-
""",
|
| 70 |
-
ids,
|
| 71 |
-
)
|
| 72 |
-
lines = []
|
| 73 |
-
for ts, u, b in cur.fetchall():
|
| 74 |
-
lines.append(f"[{ts}] USER: {u}\nBOT: {b}\n")
|
| 75 |
-
st.download_button("⬇️ Download TXT", "\n".join(lines), file_name="chats.txt")
|
| 76 |
-
|
| 77 |
-
def export_csv(conn, ids):
|
| 78 |
-
if not ids:
|
| 79 |
-
st.warning("Select at least one record."); return
|
| 80 |
-
cur = conn.execute(
|
| 81 |
-
f"""
|
| 82 |
-
SELECT timestamp, user_message, bot_reply, intent, sentiment, resolution, ftr_ms
|
| 83 |
-
FROM chat_history
|
| 84 |
-
WHERE id IN ({','.join('?' * len(ids))})
|
| 85 |
-
ORDER BY timestamp
|
| 86 |
-
""",
|
| 87 |
-
ids,
|
| 88 |
-
)
|
| 89 |
-
out = io.StringIO()
|
| 90 |
-
# header
|
| 91 |
-
cols = [d[0] for d in cur.description]
|
| 92 |
-
out.write(",".join(cols) + "\n")
|
| 93 |
-
# rows
|
| 94 |
-
for row in cur.fetchall():
|
| 95 |
-
# naive CSV (since fields are typically short); adapt to csv.writer if needed
|
| 96 |
-
out.write(",".join([str(x).replace("\n", " ").replace(",", " ") for x in row]) + "\n")
|
| 97 |
-
st.download_button("⬇️ Download CSV", out.getvalue(), file_name="chats.csv")
|
| 98 |
-
|
| 99 |
-
# =========================
|
| 100 |
-
# Video export fallback (PIL + gTTS + MoviePy)
|
| 101 |
-
# =========================
|
| 102 |
-
def _fallback_export_video(conn, ids):
|
| 103 |
-
"""Local implementation if your project doesn’t expose src.video_export.export_video."""
|
| 104 |
-
if not ids:
|
| 105 |
-
st.warning("Select at least one record."); return
|
| 106 |
-
|
| 107 |
-
# Lazy import heavy deps
|
| 108 |
-
try:
|
| 109 |
-
from gtts import gTTS
|
| 110 |
-
from moviepy.editor import ImageSequenceClip, AudioFileClip
|
| 111 |
-
except Exception as e: # pragma: no cover
|
| 112 |
-
st.error(f"Video deps missing: {e}")
|
| 113 |
-
return
|
| 114 |
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
# Build simple slides
|
| 130 |
-
frames = []
|
| 131 |
-
# Try nicer font if available, else default
|
| 132 |
-
try:
|
| 133 |
-
font = ImageFont.truetype("DejaVuSans.ttf", 22)
|
| 134 |
-
except Exception:
|
| 135 |
-
font = ImageFont.load_default()
|
| 136 |
-
|
| 137 |
-
for ts, user_msg, bot_msg in chats:
|
| 138 |
-
img = Image.new("RGB", (1024, 576), color=(255, 255, 255))
|
| 139 |
-
d = ImageDraw.Draw(img)
|
| 140 |
-
y = 30
|
| 141 |
-
d.text((40, y), f"Time: {ts}", fill=(0, 0, 0), font=font); y += 40
|
| 142 |
-
d.text((40, y), "User:", fill=(20, 20, 20), font=font); y += 30
|
| 143 |
-
_draw_wrapped_text(d, user_msg, (70, y), font, width=900); y += 120
|
| 144 |
-
d.text((40, y), "Bot:", fill=(20, 20, 20), font=font); y += 30
|
| 145 |
-
_draw_wrapped_text(d, bot_msg, (70, y), font, width=900)
|
| 146 |
-
frames.append(img)
|
| 147 |
-
|
| 148 |
-
tmpdir = tempfile.mkdtemp()
|
| 149 |
-
frame_files = []
|
| 150 |
-
for i, frame in enumerate(frames):
|
| 151 |
-
fpath = os.path.join(tmpdir, f"frame_{i:04d}.png")
|
| 152 |
-
frame.save(fpath)
|
| 153 |
-
frame_files.append(fpath)
|
| 154 |
-
|
| 155 |
-
# TTS voiceover (one narration)
|
| 156 |
-
narration = "\n".join([f"User said: {u}. Bot replied: {b}." for _, u, b in chats])
|
| 157 |
-
audio_path = os.path.join(tmpdir, "voice.mp3")
|
| 158 |
-
try:
|
| 159 |
-
gTTS(narration).save(audio_path)
|
| 160 |
-
except Exception as e: # pragma: no cover
|
| 161 |
-
st.error(f"Failed to synthesize voice: {e}")
|
| 162 |
-
return
|
| 163 |
|
| 164 |
-
# Compose video
|
| 165 |
-
try:
|
| 166 |
-
clip = ImageSequenceClip(frame_files, fps=1) # 1 slide / sec
|
| 167 |
-
audio = AudioFileClip(audio_path)
|
| 168 |
-
clip = clip.set_audio(audio)
|
| 169 |
-
video_path = os.path.join(tmpdir, "chats.mp4")
|
| 170 |
-
clip.write_videofile(video_path, codec="libx264", audio_codec="aac", verbose=False, logger=None)
|
| 171 |
-
except Exception as e: # pragma: no cover
|
| 172 |
-
st.error(f"Video composition failed: {e}")
|
| 173 |
-
return
|
| 174 |
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
def _draw_wrapped_text(draw: ImageDraw.ImageDraw, text: str, xy, font, width: int, fill=(0, 0, 0), leading: int = 6):
|
| 179 |
-
"""Basic word-wrapping for PIL text to fit a given width."""
|
| 180 |
-
x, y = xy
|
| 181 |
-
words = (text or "").split()
|
| 182 |
-
line = []
|
| 183 |
-
for w in words:
|
| 184 |
-
test = " ".join(line + [w])
|
| 185 |
-
w_px, _ = draw.textsize(test, font=font)
|
| 186 |
-
if w_px <= width:
|
| 187 |
-
line.append(w)
|
| 188 |
-
else:
|
| 189 |
-
draw.text((x, y), " ".join(line), font=font, fill=fill)
|
| 190 |
-
y += font.size + leading
|
| 191 |
-
line = [w]
|
| 192 |
-
if line:
|
| 193 |
-
draw.text((x, y), " ".join(line), font=font, fill=fill)
|
| 194 |
|
| 195 |
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
ensure_video_deps()
|
| 203 |
|
| 204 |
-
st.subheader("📥 Export Records")
|
| 205 |
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
with col2:
|
| 212 |
-
to_date = st.date_input("To Date", value=datetime.now().date())
|
| 213 |
|
| 214 |
-
prefix = st.text_input("Type first 3+ letters of email")
|
| 215 |
-
users = []
|
| 216 |
-
if prefix and len(prefix) >= 3:
|
| 217 |
-
users = search_users(conn, prefix)
|
| 218 |
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 224 |
|
| 225 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 226 |
|
| 227 |
-
|
| 228 |
-
|
| 229 |
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
|
|
|
| 233 |
return
|
| 234 |
|
| 235 |
-
# ---
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 239 |
|
| 240 |
-
page = st.number_input("Page", min_value=1, max_value=total_pages, step=1, value=1)
|
| 241 |
-
start_idx = (page - 1) * page_size
|
| 242 |
-
end_idx = start_idx + page_size
|
| 243 |
-
df_page = df.iloc[start_idx:end_idx].copy()
|
| 244 |
|
| 245 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 246 |
|
| 247 |
-
# --- Select all / multiselect for current page only ---
|
| 248 |
-
page_ids = df_page["id"].tolist()
|
| 249 |
-
select_all = st.checkbox("Select all rows on this page")
|
| 250 |
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
# --- Export actions with limits ---
|
| 262 |
-
st.markdown("### Export Options")
|
| 263 |
-
|
| 264 |
-
colA, colB, colC = st.columns(3)
|
| 265 |
-
with colA:
|
| 266 |
-
if st.button("⬇️ Export TXT"):
|
| 267 |
-
if len(selected_ids) > 100:
|
| 268 |
-
st.error("TXT export limited to 100 records.")
|
| 269 |
-
else:
|
| 270 |
-
export_txt(conn, selected_ids)
|
| 271 |
-
|
| 272 |
-
with colB:
|
| 273 |
-
if st.button("⬇️ Export CSV"):
|
| 274 |
-
if len(selected_ids) > 100:
|
| 275 |
-
st.error("CSV export limited to 100 records.")
|
| 276 |
-
else:
|
| 277 |
-
export_csv(conn, selected_ids)
|
| 278 |
-
|
| 279 |
-
with colC:
|
| 280 |
-
if st.button("🎬 Export Video"):
|
| 281 |
-
if len(selected_ids) > 20:
|
| 282 |
-
st.error("Video export limited to 20 records.")
|
| 283 |
-
else:
|
| 284 |
-
if project_export_video:
|
| 285 |
-
# Use project’s implementation if available
|
| 286 |
-
project_export_video(conn, selected_ids)
|
| 287 |
-
else:
|
| 288 |
-
_fallback_export_video(conn, selected_ids)
|
|
|
|
| 1 |
# src/admin_export.py
|
| 2 |
+
from __future__ import annotations
|
| 3 |
import io
|
|
|
|
|
|
|
| 4 |
from datetime import datetime, timedelta
|
| 5 |
+
from typing import List, Dict, Any, Tuple
|
| 6 |
|
|
|
|
| 7 |
import streamlit as st
|
| 8 |
+
|
| 9 |
+
from src.utils import get_connection
|
| 10 |
+
from src.video_export import ensure_video_deps, export_records_to_video
|
| 11 |
+
|
| 12 |
+
# ---- constants
|
| 13 |
+
TXT_CSV_LIMIT = 100
|
| 14 |
+
VIDEO_LIMIT = 20
|
| 15 |
+
PAGE_SIZE = 10
|
| 16 |
+
|
| 17 |
+
# ---- session keys (namespaced)
|
| 18 |
+
SS_SEL = "admin_export_selected_ids"
|
| 19 |
+
SS_PAGE = "admin_export_page"
|
| 20 |
+
SS_SELALL = "admin_export_select_all"
|
| 21 |
+
SS_USER_MATCHES = "admin_export_user_matches"
|
| 22 |
+
SS_PICKED_USER = "admin_export_picked_user"
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
# ---------------------------
|
| 26 |
+
# helpers: db queries
|
| 27 |
+
# ---------------------------
|
| 28 |
+
def _query_users_like(prefix: str) -> List[Dict[str, Any]]:
|
| 29 |
+
"""Return users whose username or email starts-with prefix (case-insensitive)."""
|
| 30 |
+
if not prefix:
|
| 31 |
+
return []
|
| 32 |
+
q = """
|
| 33 |
SELECT id, username, email
|
| 34 |
FROM users
|
| 35 |
+
WHERE (LOWER(username) LIKE ? OR LOWER(email) LIKE ?)
|
| 36 |
+
ORDER BY username
|
| 37 |
+
LIMIT 30
|
| 38 |
+
"""
|
| 39 |
+
like = f"{prefix.lower()}%"
|
| 40 |
+
with get_connection() as conn:
|
| 41 |
+
rows = conn.execute(q, (like, like)).fetchall()
|
| 42 |
return [dict(r) for r in rows]
|
| 43 |
|
| 44 |
+
|
| 45 |
+
def _query_chats(conn, user_id: int, start_iso: str, end_iso: str) -> List[Dict[str, Any]]:
|
| 46 |
+
q = """
|
| 47 |
+
SELECT id, timestamp, user_message, bot_reply, intent, sentiment, resolution, ftr_ms, user_id
|
|
|
|
| 48 |
FROM chat_history
|
| 49 |
WHERE user_id = ?
|
| 50 |
+
AND timestamp >= ?
|
| 51 |
+
AND timestamp < ?
|
| 52 |
+
ORDER BY timestamp ASC
|
| 53 |
+
"""
|
| 54 |
+
rows = conn.execute(q, (user_id, start_iso, end_iso)).fetchall()
|
| 55 |
return [dict(r) for r in rows]
|
| 56 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 57 |
|
| 58 |
+
# ---------------------------
|
| 59 |
+
# ui helpers
|
| 60 |
+
# ---------------------------
|
| 61 |
+
def _ensure_state():
|
| 62 |
+
if SS_SEL not in st.session_state:
|
| 63 |
+
st.session_state[SS_SEL] = set() # store selected chat ids
|
| 64 |
+
if SS_PAGE not in st.session_state:
|
| 65 |
+
st.session_state[SS_PAGE] = 1
|
| 66 |
+
if SS_SELALL not in st.session_state:
|
| 67 |
+
st.session_state[SS_SELALL] = False
|
| 68 |
+
if SS_USER_MATCHES not in st.session_state:
|
| 69 |
+
st.session_state[SS_USER_MATCHES] = []
|
| 70 |
+
if SS_PICKED_USER not in st.session_state:
|
| 71 |
+
st.session_state[SS_PICKED_USER] = None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 72 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 73 |
|
| 74 |
+
def _dt_to_iso(d: datetime) -> str:
|
| 75 |
+
return d.isoformat(timespec="seconds")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 76 |
|
| 77 |
|
| 78 |
+
def _page_slice(rows: List[Dict[str, Any]], page: int, page_size: int) -> Tuple[int, List[Dict[str, Any]]]:
|
| 79 |
+
total_pages = max(1, (len(rows) + page_size - 1) // page_size)
|
| 80 |
+
page = min(max(1, page), total_pages)
|
| 81 |
+
i0 = (page - 1) * page_size
|
| 82 |
+
i1 = min(len(rows), i0 + page_size)
|
| 83 |
+
return total_pages, rows[i0:i1]
|
|
|
|
| 84 |
|
|
|
|
| 85 |
|
| 86 |
+
def _tag(text: str, color: str) -> str:
|
| 87 |
+
return f"""<span style="
|
| 88 |
+
background:{color};color:#0f172a;border-radius:999px;
|
| 89 |
+
padding:2px 8px;font-size:12px;border:1px solid rgba(15,23,42,.08)
|
| 90 |
+
">{text}</span>"""
|
|
|
|
|
|
|
| 91 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
|
| 93 |
+
# ---------------------------
|
| 94 |
+
# main render
|
| 95 |
+
# ---------------------------
|
| 96 |
+
def render_admin_export_tab(conn):
|
| 97 |
+
"""
|
| 98 |
+
Admin export tab with:
|
| 99 |
+
- date range + typeahead user picker
|
| 100 |
+
- paginated grid
|
| 101 |
+
- per-row checkboxes + Select-all-on-page
|
| 102 |
+
- export TXT / CSV / Video with limits
|
| 103 |
+
"""
|
| 104 |
+
_ensure_state()
|
| 105 |
+
ensure_video_deps()
|
| 106 |
|
| 107 |
+
st.subheader("Admin: Export Chat History")
|
| 108 |
+
|
| 109 |
+
# --- filters row
|
| 110 |
+
c1, c2 = st.columns([1, 1])
|
| 111 |
+
with c1:
|
| 112 |
+
start = st.date_input("From date", value=(datetime.utcnow() - timedelta(days=7)).date())
|
| 113 |
+
with c2:
|
| 114 |
+
end = st.date_input("To date", value=datetime.utcnow().date())
|
| 115 |
+
|
| 116 |
+
# time clamp
|
| 117 |
+
start_dt = datetime.combine(start, datetime.min.time())
|
| 118 |
+
end_dt = datetime.combine(end, datetime.max.time())
|
| 119 |
+
start_iso, end_iso = _dt_to_iso(start_dt), _dt_to_iso(end_dt)
|
| 120 |
+
|
| 121 |
+
st.markdown("##### Pick User")
|
| 122 |
+
cc1, cc2 = st.columns([1, 1])
|
| 123 |
+
with cc1:
|
| 124 |
+
prefix = st.text_input("Type at least 3 letters (username/email)", placeholder="e.g. use… or adm…")
|
| 125 |
+
if len(prefix.strip()) >= 3:
|
| 126 |
+
st.session_state[SS_USER_MATCHES] = _query_users_like(prefix.strip())
|
| 127 |
+
else:
|
| 128 |
+
st.session_state[SS_USER_MATCHES] = []
|
| 129 |
+
with cc2:
|
| 130 |
+
matches = st.session_state[SS_USER_MATCHES]
|
| 131 |
+
if matches:
|
| 132 |
+
options = [f"{m['username']} <{m['email']}>" for m in matches]
|
| 133 |
+
picked_label = st.selectbox("Matches", options, index=0 if options else None)
|
| 134 |
+
picked = matches[options.index(picked_label)] if options else None
|
| 135 |
+
else:
|
| 136 |
+
picked_label, picked = st.selectbox("Matches", ["(no matches)"]), None
|
| 137 |
|
| 138 |
+
# store picked user id
|
| 139 |
+
st.session_state[SS_PICKED_USER] = picked["id"] if picked else None
|
| 140 |
|
| 141 |
+
if not picked:
|
| 142 |
+
st.info("Search a user (≥3 chars), pick one, then data will appear here.")
|
| 143 |
+
# show zeroed table structure for consistency
|
| 144 |
+
_draw_empty_grid_hint()
|
| 145 |
return
|
| 146 |
|
| 147 |
+
# --- fetch
|
| 148 |
+
rows = _query_chats(conn, picked["id"], start_iso, end_iso)
|
| 149 |
+
total_pages, page_rows = _page_slice(rows, st.session_state[SS_PAGE], PAGE_SIZE)
|
| 150 |
+
|
| 151 |
+
# --- page select
|
| 152 |
+
left, right = st.columns([1, 5])
|
| 153 |
+
with left:
|
| 154 |
+
page = st.number_input("Page", min_value=1, max_value=total_pages, value=st.session_state[SS_PAGE], step=1)
|
| 155 |
+
if page != st.session_state[SS_PAGE]:
|
| 156 |
+
st.session_state[SS_PAGE] = page
|
| 157 |
+
# reset select-all for new page
|
| 158 |
+
st.session_state[SS_SELALL] = False
|
| 159 |
+
st.rerun()
|
| 160 |
+
|
| 161 |
+
# --- grid header
|
| 162 |
+
_draw_grid_header()
|
| 163 |
+
|
| 164 |
+
# --- select-all on page
|
| 165 |
+
st.checkbox(
|
| 166 |
+
"Select all rows on this page",
|
| 167 |
+
key=SS_SELALL,
|
| 168 |
+
value=st.session_state[SS_SELALL],
|
| 169 |
+
on_change=_toggle_select_all_for_page,
|
| 170 |
+
args=(page_rows,),
|
| 171 |
+
)
|
| 172 |
+
|
| 173 |
+
# --- rows with checkboxes
|
| 174 |
+
sel_ids = st.session_state[SS_SEL]
|
| 175 |
+
for r in page_rows:
|
| 176 |
+
rid = r["id"]
|
| 177 |
+
checked = rid in sel_ids
|
| 178 |
+
cols = st.columns([0.6, 1, 1, 2, 1, 1, 1, 0.8]) # [chk,id,timestamp,user_message,bot_reply,intent,sentiment,resolution,ftr]
|
| 179 |
+
with cols[0]:
|
| 180 |
+
# unique key per row checkbox
|
| 181 |
+
cur = st.checkbox("", value=checked, key=f"sel_{rid}")
|
| 182 |
+
if cur and not checked:
|
| 183 |
+
sel_ids.add(rid)
|
| 184 |
+
elif (not cur) and checked:
|
| 185 |
+
sel_ids.discard(rid)
|
| 186 |
+
cols[1].markdown(f"`{r['id']}`")
|
| 187 |
+
cols[2].markdown(f"{r['timestamp']}")
|
| 188 |
+
cols[3].markdown(f"{(r['user_message'] or '')[:30]}")
|
| 189 |
+
cols[4].markdown(f"{(r['bot_reply'] or '')[:40]}")
|
| 190 |
+
cols[5].markdown(_tag(r.get("intent") or "-", "#E0F2FE"), unsafe_allow_html=True)
|
| 191 |
+
cols[6].markdown(_tag(r.get("sentiment") or "-", "#FDE68A"), unsafe_allow_html=True)
|
| 192 |
+
cols[7].markdown(_tag(r.get("resolution") or "-", "#DCFCE7"), unsafe_allow_html=True)
|
| 193 |
+
|
| 194 |
+
st.caption(f"Selected {len(sel_ids)} records (Page {st.session_state[SS_PAGE]}/{total_pages})")
|
| 195 |
+
|
| 196 |
+
# --- single-user enforcement: naturally satisfied (grid filters by chosen user)
|
| 197 |
+
# but we also cleanup any selected IDs that are not in 'rows' for this user/time window:
|
| 198 |
+
valid_ids = {r["id"] for r in rows}
|
| 199 |
+
stale = set(sel_ids) - valid_ids
|
| 200 |
+
if stale:
|
| 201 |
+
for x in stale:
|
| 202 |
+
sel_ids.discard(x)
|
| 203 |
+
|
| 204 |
+
# --- export controls
|
| 205 |
+
st.subheader("Export Options")
|
| 206 |
+
c_txt, c_csv, c_vid = st.columns(3)
|
| 207 |
+
|
| 208 |
+
with c_txt:
|
| 209 |
+
if st.button("⬇��� Export TXT", use_container_width=True, disabled=len(sel_ids) == 0):
|
| 210 |
+
ids = list(sel_ids)[:TXT_CSV_LIMIT]
|
| 211 |
+
buf = io.StringIO()
|
| 212 |
+
for r in rows:
|
| 213 |
+
if r["id"] in ids:
|
| 214 |
+
buf.write(f"[{r['timestamp']}] USER: {r['user_message']}\n")
|
| 215 |
+
buf.write(f"[{r['timestamp']}] BOT: {r['bot_reply']}\n")
|
| 216 |
+
buf.write("-" * 60 + "\n")
|
| 217 |
+
st.download_button("Download TXT", buf.getvalue(), file_name="chat_export.txt", mime="text/plain", use_container_width=True)
|
| 218 |
+
|
| 219 |
+
with c_csv:
|
| 220 |
+
if st.button("⬇️ Export CSV", use_container_width=True, disabled=len(sel_ids) == 0):
|
| 221 |
+
import csv
|
| 222 |
+
ids = list(sel_ids)[:TXT_CSV_LIMIT]
|
| 223 |
+
out = io.StringIO()
|
| 224 |
+
w = csv.writer(out)
|
| 225 |
+
w.writerow(["id", "timestamp", "user_message", "bot_reply", "intent", "sentiment", "resolution", "ftr_ms"])
|
| 226 |
+
for r in rows:
|
| 227 |
+
if r["id"] in ids:
|
| 228 |
+
w.writerow([r["id"], r["timestamp"], r["user_message"], r["bot_reply"], r["intent"], r["sentiment"], r["resolution"], r["ftr_ms"]])
|
| 229 |
+
st.download_button("Download CSV", out.getvalue(), file_name="chat_export.csv", mime="text/csv", use_container_width=True)
|
| 230 |
+
|
| 231 |
+
with c_vid:
|
| 232 |
+
disable_video = len(sel_ids) == 0 or len(sel_ids) > VIDEO_LIMIT
|
| 233 |
+
note = "" if len(sel_ids) <= VIDEO_LIMIT else f"(limit {VIDEO_LIMIT})"
|
| 234 |
+
if st.button(f"🎬 Export Video {note}", use_container_width=True, disabled=disable_video):
|
| 235 |
+
ids = sorted(list(sel_ids))[:VIDEO_LIMIT]
|
| 236 |
+
chosen = [r for r in rows if r["id"] in ids]
|
| 237 |
+
try:
|
| 238 |
+
video_path = export_records_to_video(chosen)
|
| 239 |
+
st.success("Video ready.")
|
| 240 |
+
st.download_button("Download MP4", open(video_path, "rb"), file_name="chat_export.mp4", mime="video/mp4", use_container_width=True)
|
| 241 |
+
except Exception as e:
|
| 242 |
+
st.error(f"Video export failed: {e}")
|
| 243 |
+
|
| 244 |
+
st.divider()
|
| 245 |
+
st.caption("Tip: switch pages; selections persist. Use the ‘Select all rows on this page’ checkbox to bulk select.")
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
def _toggle_select_all_for_page(page_rows: List[Dict[str, Any]]):
|
| 249 |
+
sel = st.session_state[SS_SEL]
|
| 250 |
+
if st.session_state[SS_SELALL]:
|
| 251 |
+
for r in page_rows:
|
| 252 |
+
sel.add(r["id"])
|
| 253 |
+
else:
|
| 254 |
+
for r in page_rows:
|
| 255 |
+
sel.discard(r["id"])
|
| 256 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 257 |
|
| 258 |
+
def _draw_grid_header():
|
| 259 |
+
st.markdown(
|
| 260 |
+
"""
|
| 261 |
+
<div style="display:grid;grid-template-columns:40px 80px 200px 1fr 1.2fr 120px 120px 120px;gap:8px;
|
| 262 |
+
padding:8px 12px;border:1px solid #e5e7eb;border-radius:8px;background:#F8FAFC;">
|
| 263 |
+
<div></div>
|
| 264 |
+
<div style="font-weight:600">id</div>
|
| 265 |
+
<div style="font-weight:600">timestamp</div>
|
| 266 |
+
<div style="font-weight:600">user_message</div>
|
| 267 |
+
<div style="font-weight:600">bot_reply</div>
|
| 268 |
+
<div style="font-weight:600">intent</div>
|
| 269 |
+
<div style="font-weight:600">sentiment</div>
|
| 270 |
+
<div style="font-weight:600">resolution</div>
|
| 271 |
+
</div>
|
| 272 |
+
""",
|
| 273 |
+
unsafe_allow_html=True,
|
| 274 |
+
)
|
| 275 |
|
|
|
|
|
|
|
|
|
|
| 276 |
|
| 277 |
+
def _draw_empty_grid_hint():
|
| 278 |
+
st.markdown(
|
| 279 |
+
"""
|
| 280 |
+
<div style="margin-top:8px;border:1px dashed #e5e7eb;border-radius:8px;padding:16px;background:#F8FAFC;">
|
| 281 |
+
<em>No data yet.</em> Pick a user to view chats. You can then select rows with checkboxes and export.
|
| 282 |
+
</div>
|
| 283 |
+
""",
|
| 284 |
+
unsafe_allow_html=True,
|
| 285 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|