version 1.8.16Xb - extended to include metric fields in SQLite cache, UI download & sorting/filtering
Browse files- src/kmai.py +178 -128
src/kmai.py
CHANGED
|
@@ -1,8 +1,5 @@
|
|
| 1 |
-
# version 1.8.16Xb -
|
| 2 |
-
#
|
| 3 |
-
# persist scores in session state, and display scores in Manage Q&A view).
|
| 4 |
-
#
|
| 5 |
-
# NOTE: This file preserves original behavior while adding the requested metric capture.
|
| 6 |
|
| 7 |
import os
|
| 8 |
import io
|
|
@@ -63,7 +60,7 @@ torch.cuda.empty_cache()
|
|
| 63 |
gc.collect()
|
| 64 |
|
| 65 |
# =============================================
|
| 66 |
-
# helper: derive subtopic from filename
|
| 67 |
# =============================================
|
| 68 |
def derive_subtopic_from_filename(filename: str) -> str:
|
| 69 |
if not filename:
|
|
@@ -84,13 +81,13 @@ def derive_subtopic_from_filename(filename: str) -> str:
|
|
| 84 |
return candidate if candidate else "general"
|
| 85 |
|
| 86 |
# =============================================
|
| 87 |
-
# SQLITE CACHE DB (modified to include
|
|
|
|
| 88 |
# =============================================
|
| 89 |
def init_cache_db(path: str = CACHE_DB_PATH):
|
| 90 |
conn = sqlite3.connect(path, check_same_thread=False)
|
| 91 |
cur = conn.cursor()
|
| 92 |
-
|
| 93 |
-
# Create base table if not exists (keeps original columns)
|
| 94 |
cur.execute("""
|
| 95 |
CREATE TABLE IF NOT EXISTS qa_cache (
|
| 96 |
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
@@ -102,26 +99,33 @@ def init_cache_db(path: str = CACHE_DB_PATH):
|
|
| 102 |
feedback_status TEXT CHECK(feedback_status IN ('Y','N')) DEFAULT NULL
|
| 103 |
);
|
| 104 |
""")
|
| 105 |
-
|
| 106 |
-
# Add new columns (idempotent) for metric storage
|
| 107 |
-
existing_cols = [row[1] for row in cur.execute("PRAGMA table_info('qa_cache');")]
|
| 108 |
-
if "cosine_score" not in existing_cols:
|
| 109 |
-
cur.execute("ALTER TABLE qa_cache ADD COLUMN cosine_score REAL;")
|
| 110 |
-
if "rouge2_score" not in existing_cols:
|
| 111 |
-
cur.execute("ALTER TABLE qa_cache ADD COLUMN rouge2_score REAL;")
|
| 112 |
-
if "rougeL_score" not in existing_cols:
|
| 113 |
-
cur.execute("ALTER TABLE qa_cache ADD COLUMN rougeL_score REAL;")
|
| 114 |
-
|
| 115 |
cur.execute("CREATE INDEX IF NOT EXISTS idx_topic ON qa_cache(topic);")
|
| 116 |
cur.execute("CREATE INDEX IF NOT EXISTS idx_sub_topic ON qa_cache(sub_topic);")
|
| 117 |
conn.commit()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 118 |
return conn
|
| 119 |
|
| 120 |
_cache_conn = init_cache_db()
|
| 121 |
|
| 122 |
def fetch_cache_by_topic(topic: str, only_helpful: bool = False):
|
| 123 |
"""
|
| 124 |
-
Returns rows
|
| 125 |
id, question, answer, created_at, feedback_status, sub_topic, cosine_score, rouge2_score, rougeL_score
|
| 126 |
"""
|
| 127 |
cur = _cache_conn.cursor()
|
|
@@ -140,9 +144,9 @@ def fetch_cache_by_topic(topic: str, only_helpful: bool = False):
|
|
| 140 |
|
| 141 |
def get_best_fuzzy_match(topic: str, question: str, threshold: float = 0.75):
|
| 142 |
"""
|
| 143 |
-
Return (id, stored_question, stored_answer, created_at, feedback_status, score)
|
| 144 |
or None if no match above threshold.
|
| 145 |
-
|
| 146 |
"""
|
| 147 |
rows = fetch_cache_by_topic(topic, only_helpful=True)
|
| 148 |
if not rows:
|
|
@@ -152,52 +156,34 @@ def get_best_fuzzy_match(topic: str, question: str, threshold: float = 0.75):
|
|
| 152 |
best = None
|
| 153 |
best_score = 0.0
|
| 154 |
for row in rows:
|
| 155 |
-
# row
|
| 156 |
-
rid = row
|
| 157 |
-
stored_q = row[1]
|
| 158 |
-
stored_a = row[2]
|
| 159 |
-
created_at = row[3]
|
| 160 |
-
fb = row[4]
|
| 161 |
-
# sub_topic = row[5] # available if needed
|
| 162 |
score = SequenceMatcher(None, q_lower, (stored_q or "").lower().strip()).ratio()
|
| 163 |
if score > best_score:
|
| 164 |
best_score = score
|
| 165 |
-
best = (rid, stored_q, stored_a, created_at, fb,
|
| 166 |
|
| 167 |
-
if best and best[
|
| 168 |
return best
|
| 169 |
return None
|
| 170 |
|
| 171 |
-
def insert_cache(topic: str,
|
| 172 |
-
|
| 173 |
-
answer: str,
|
| 174 |
-
feedback_status: str = None,
|
| 175 |
-
sub_topic: str = "all",
|
| 176 |
-
cosine_score: float = None,
|
| 177 |
-
rouge2_score: float = None,
|
| 178 |
-
rougeL_score: float = None):
|
| 179 |
now = datetime.now(timezone.utc).isoformat()
|
| 180 |
cur = _cache_conn.cursor()
|
| 181 |
cur.execute("""
|
| 182 |
-
INSERT INTO qa_cache
|
| 183 |
-
(topic, sub_topic, question, answer, created_at, feedback_status, cosine_score, rouge2_score, rougeL_score)
|
| 184 |
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
| 185 |
""", (topic, sub_topic, question, answer, now, feedback_status, cosine_score, rouge2_score, rougeL_score))
|
| 186 |
_cache_conn.commit()
|
| 187 |
return cur.lastrowid
|
| 188 |
|
| 189 |
|
| 190 |
-
def upsert_cache(topic: str,
|
| 191 |
-
|
| 192 |
-
answer: str,
|
| 193 |
-
feedback_status: str = None,
|
| 194 |
-
sub_topic: str = "all",
|
| 195 |
-
cosine_score: float = None,
|
| 196 |
-
rouge2_score: float = None,
|
| 197 |
-
rougeL_score: float = None):
|
| 198 |
"""
|
| 199 |
Upsert identified by topic, question, AND sub_topic (so same question in different sub-topics are distinct).
|
| 200 |
-
Updates metric
|
| 201 |
"""
|
| 202 |
now = datetime.now(timezone.utc).isoformat()
|
| 203 |
cur = _cache_conn.cursor()
|
|
@@ -205,12 +191,8 @@ def upsert_cache(topic: str,
|
|
| 205 |
row = cur.fetchone()
|
| 206 |
if row:
|
| 207 |
cur.execute(
|
| 208 |
-
""
|
| 209 |
-
|
| 210 |
-
SET answer = ?, created_at = ?, feedback_status = ?, cosine_score = ?, rouge2_score = ?, rougeL_score = ?
|
| 211 |
-
WHERE id = ?
|
| 212 |
-
""",
|
| 213 |
-
(answer, now, feedback_status, cosine_score, rouge2_score, rougeL_score, row[0])
|
| 214 |
)
|
| 215 |
_cache_conn.commit()
|
| 216 |
return row[0]
|
|
@@ -278,7 +260,7 @@ def embed_texts(texts: List[str]):
|
|
| 278 |
chroma_client = PersistentClient(path=CHROMA_DIR)
|
| 279 |
|
| 280 |
# =============================================
|
| 281 |
-
# VECTOR DB HELPERS
|
| 282 |
# =============================================
|
| 283 |
def get_or_create_collection(topic_name: str):
|
| 284 |
try:
|
|
@@ -292,7 +274,7 @@ def add_document_to_topic(topic_name: str, pdf_path: str, pdf_filename: str, ful
|
|
| 292 |
st.write("πΉ Starting document ingestion...")
|
| 293 |
# Derive sub-topic from filename
|
| 294 |
sub_topic = derive_subtopic_from_filename(pdf_filename)
|
| 295 |
-
st.info(f"Detected sub-topic: **{sub_topic}**")
|
| 296 |
|
| 297 |
col = get_or_create_collection(topic_name)
|
| 298 |
|
|
@@ -371,7 +353,7 @@ def query_collection(topic: str, query: str, top_k=3, relevance_threshold=0.35,
|
|
| 371 |
return sorted(relevant, key=lambda x: x["distance"])
|
| 372 |
|
| 373 |
# =============================================
|
| 374 |
-
# PDF / OCR / TABLE extraction functions
|
| 375 |
# =============================================
|
| 376 |
def extract_text_from_pdf_bytes(pdf_bytes: bytes) -> str:
|
| 377 |
text = ""
|
|
@@ -404,7 +386,7 @@ def extract_tables_as_text(pdf_path: str) -> str:
|
|
| 404 |
return "\n\n".join(table_texts)
|
| 405 |
|
| 406 |
# =============================================
|
| 407 |
-
# chunking & summarization (
|
| 408 |
# =============================================
|
| 409 |
def chunk_text(text: str, chunk_size=1000, overlap=200) -> List[str]:
|
| 410 |
if not text:
|
|
@@ -480,7 +462,11 @@ def chunked_summarize(
|
|
| 480 |
overlap: int = 200,
|
| 481 |
top_k: int = 4,
|
| 482 |
support_threshold: float = 0.60,
|
| 483 |
-
) -> str:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 484 |
if top_k > 10:
|
| 485 |
support_threshold = 0.55
|
| 486 |
elif top_k > 6:
|
|
@@ -495,11 +481,7 @@ def chunked_summarize(
|
|
| 495 |
total_chunks = len(chunks)
|
| 496 |
|
| 497 |
if total_chunks == 0:
|
| 498 |
-
|
| 499 |
-
st.session_state["cosine_score"] = None
|
| 500 |
-
st.session_state["rouge2_score"] = None
|
| 501 |
-
st.session_state["rougeL_score"] = None
|
| 502 |
-
return "[No chunks to summarize.]"
|
| 503 |
|
| 504 |
st.info(f"π Total combined chunks **{total_chunks}** (parallelizing up to {min(top_k, total_chunks)} workers).")
|
| 505 |
num_workers = max(1, min(top_k, total_chunks))
|
|
@@ -540,10 +522,7 @@ def chunked_summarize(
|
|
| 540 |
)
|
| 541 |
|
| 542 |
if not combined_summary_text:
|
| 543 |
-
|
| 544 |
-
st.session_state["rouge2_score"] = None
|
| 545 |
-
st.session_state["rougeL_score"] = None
|
| 546 |
-
return "[All chunk summarizations failed.]"
|
| 547 |
|
| 548 |
if question:
|
| 549 |
final_prompt = f"""
|
|
@@ -679,7 +658,6 @@ Complete, factual answer (do not invent):
|
|
| 679 |
|
| 680 |
final_summary = filtered_summary
|
| 681 |
|
| 682 |
-
# Compute metrics (cosine and ROUGE)
|
| 683 |
cosine_score = None
|
| 684 |
try:
|
| 685 |
emb_model = get_embed_model()
|
|
@@ -700,11 +678,6 @@ Complete, factual answer (do not invent):
|
|
| 700 |
except Exception as e:
|
| 701 |
st.warning(f"ROUGE scoring skipped: {e}")
|
| 702 |
|
| 703 |
-
# Persist metrics to session so Ask Questions can insert them into SQLite cache
|
| 704 |
-
st.session_state["cosine_score"] = cosine_score
|
| 705 |
-
st.session_state["rouge2_score"] = rouge2_score
|
| 706 |
-
st.session_state["rougeL_score"] = rougeL_score
|
| 707 |
-
|
| 708 |
def rating_label(score, high_thr, med_thr):
|
| 709 |
if score is None:
|
| 710 |
return ("-", "-", "-")
|
|
@@ -792,7 +765,7 @@ Complete, factual answer (do not invent):
|
|
| 792 |
else:
|
| 793 |
st.success(f"β
Summarization completed in **{total_time:.2f} seconds**.")
|
| 794 |
|
| 795 |
-
return final_summary
|
| 796 |
|
| 797 |
# =============================================
|
| 798 |
# UI: Tabs (Upload / Ask / Manage)
|
|
@@ -800,7 +773,7 @@ Complete, factual answer (do not invent):
|
|
| 800 |
tab1, tab2, tab3 = st.tabs(["Upload PDFs", "Ask Questions", "Manage Topics"])
|
| 801 |
|
| 802 |
# -----------------------
|
| 803 |
-
# Upload tab
|
| 804 |
# -----------------------
|
| 805 |
with tab1:
|
| 806 |
st.session_state["active_tab"] = "Upload PDFs"
|
|
@@ -879,7 +852,7 @@ with tab1:
|
|
| 879 |
st.warning(f"Could not fetch sample chunks: {e}")
|
| 880 |
|
| 881 |
# -----------------------
|
| 882 |
-
# Ask Questions tab
|
| 883 |
# -----------------------
|
| 884 |
with tab2:
|
| 885 |
st.session_state["active_tab"] = "Ask Questions"
|
|
@@ -912,13 +885,11 @@ with tab2:
|
|
| 912 |
try:
|
| 913 |
data_meta = col_for_topic.get(include=["metadatas"])
|
| 914 |
metas_all = data_meta.get("metadatas", [])
|
| 915 |
-
# metas_all is list of metadata dicts
|
| 916 |
sth = set()
|
| 917 |
for m in metas_all:
|
| 918 |
if isinstance(m, dict):
|
| 919 |
stv = m.get("sub_topic") or "general"
|
| 920 |
sth.add(stv)
|
| 921 |
-
# put sorted values after 'All'
|
| 922 |
subtopic_options = ["All"] + sorted([s for s in sth if s and s.lower() != "all"])
|
| 923 |
except Exception:
|
| 924 |
subtopic_options = ["All"]
|
|
@@ -947,16 +918,16 @@ with tab2:
|
|
| 947 |
try:
|
| 948 |
topic_norm = topic_q.strip()
|
| 949 |
cache_start = time.time()
|
| 950 |
-
#
|
| 951 |
best = get_best_fuzzy_match(topic_norm, query_text.strip(), threshold=fuzzy_threshold)
|
| 952 |
cache_elapsed = time.time() - cache_start
|
| 953 |
|
| 954 |
if best:
|
| 955 |
-
# best
|
| 956 |
-
rid, stored_q, stored_a, created_at, fb, score = best
|
| 957 |
st.session_state["last_query"] = {
|
| 958 |
"topic": topic_norm,
|
| 959 |
-
"sub_topic": "all",
|
| 960 |
"question": query_text.strip(),
|
| 961 |
"cached": True,
|
| 962 |
"entry_id": rid,
|
|
@@ -966,6 +937,9 @@ with tab2:
|
|
| 966 |
"score": score,
|
| 967 |
"created_at": created_at,
|
| 968 |
"cache_time": cache_elapsed,
|
|
|
|
|
|
|
|
|
|
| 969 |
},
|
| 970 |
}
|
| 971 |
else:
|
|
@@ -993,26 +967,16 @@ with tab2:
|
|
| 993 |
|
| 994 |
sum_start = time.time()
|
| 995 |
with st.spinner("Summarizing..."):
|
| 996 |
-
|
| 997 |
-
summary = chunked_summarize(combined_text, question=query_text.strip(), top_k=top_k)
|
| 998 |
sum_elapsed = time.time() - sum_start
|
| 999 |
|
| 1000 |
# store sub_topic used for query into cache record
|
| 1001 |
cache_subtopic_value = subtopic_filter if subtopic_filter else "all"
|
| 1002 |
-
|
| 1003 |
-
# fetch metric values from session (may be None if computation failed)
|
| 1004 |
-
cs = st.session_state.get("cosine_score")
|
| 1005 |
-
r2 = st.session_state.get("rouge2_score")
|
| 1006 |
-
rL = st.session_state.get("rougeL_score")
|
| 1007 |
-
|
| 1008 |
-
inserted_id = insert_cache(topic_norm,
|
| 1009 |
-
query_text.strip(),
|
| 1010 |
-
summary,
|
| 1011 |
-
feedback_status=None,
|
| 1012 |
sub_topic=cache_subtopic_value,
|
| 1013 |
-
cosine_score=
|
| 1014 |
-
rouge2_score=
|
| 1015 |
-
rougeL_score=
|
| 1016 |
|
| 1017 |
st.session_state["last_query"] = {
|
| 1018 |
"topic": topic_norm,
|
|
@@ -1025,9 +989,9 @@ with tab2:
|
|
| 1025 |
"meta": {
|
| 1026 |
"vec_time": vec_elapsed,
|
| 1027 |
"sum_time": sum_elapsed,
|
| 1028 |
-
"cosine_score":
|
| 1029 |
-
"rouge2_score":
|
| 1030 |
-
"rougeL_score":
|
| 1031 |
},
|
| 1032 |
}
|
| 1033 |
|
|
@@ -1044,16 +1008,22 @@ with tab2:
|
|
| 1044 |
st.subheader(f"Answer for: {last['question']} β *(Topic: {last['topic']}, Sub-topic: {last.get('sub_topic','all')})*")
|
| 1045 |
st.write(last["answer"])
|
| 1046 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1047 |
if last["cached"]:
|
| 1048 |
st.caption(f"β‘ Retrieved from cache (score={last['meta']['score']:.3f}, cached at {last['meta']['created_at']})")
|
| 1049 |
else:
|
| 1050 |
st.caption(f"Vector fetch took: **{last['meta']['vec_time']:.2f}s**, Summarization took: **{last['meta']['sum_time']:.2f}s**")
|
| 1051 |
-
# If metrics exist, show them
|
| 1052 |
-
if "cosine_score" in last["meta"] or st.session_state.get("cosine_score") is not None:
|
| 1053 |
-
cs_val = last["meta"].get("cosine_score", st.session_state.get("cosine_score"))
|
| 1054 |
-
r2_val = last["meta"].get("rouge2_score", st.session_state.get("rouge2_score"))
|
| 1055 |
-
rL_val = last["meta"].get("rougeL_score", st.session_state.get("rougeL_score"))
|
| 1056 |
-
st.markdown(f"**Metrics:** Cosine: `{cs_val}`, ROUGE-2: `{r2_val}`, ROUGE-L: `{rL_val}`")
|
| 1057 |
|
| 1058 |
def show_feedback_controls_and_apply(entry_id: int):
|
| 1059 |
col_yes, col_no = st.columns(2)
|
|
@@ -1098,7 +1068,7 @@ with tab2:
|
|
| 1098 |
st.button("π¬ Ask another question", on_click=reset_query)
|
| 1099 |
|
| 1100 |
# -----------------------
|
| 1101 |
-
# Manage Topics tab
|
| 1102 |
# -----------------------
|
| 1103 |
with tab3:
|
| 1104 |
st.session_state["active_tab"] = "Manage Topics"
|
|
@@ -1115,7 +1085,7 @@ with tab3:
|
|
| 1115 |
else:
|
| 1116 |
topic_to_manage = st.selectbox("Select a topic to manage/delete:", all_topics, key="manage_topic_select")
|
| 1117 |
|
| 1118 |
-
# Display sub-topics under this topic
|
| 1119 |
try:
|
| 1120 |
col = get_or_create_collection(topic_to_manage)
|
| 1121 |
metas_all = col.get(include=["metadatas"]).get("metadatas", [])
|
|
@@ -1129,7 +1099,7 @@ with tab3:
|
|
| 1129 |
|
| 1130 |
st.write("Sub-topics under this topic:", ", ".join(sublist_unique) if sublist_unique else "β none found β")
|
| 1131 |
|
| 1132 |
-
# Two radio button options for delete behavior
|
| 1133 |
delete_option = st.radio("Delete options:", ["Delete entire topic", "Delete select sub-topic(s)"], key="delete_option_radio")
|
| 1134 |
|
| 1135 |
# Initialize session state values for confirmations
|
|
@@ -1143,7 +1113,6 @@ with tab3:
|
|
| 1143 |
st.session_state.total_before_sub = 0
|
| 1144 |
|
| 1145 |
if delete_option == "Delete entire topic":
|
| 1146 |
-
# Option 1: delete entire topic (existing behavior with updated messages)
|
| 1147 |
st.write("This will delete the entire Chroma collection and all its records.")
|
| 1148 |
if st.button("Prepare to delete entire topic"):
|
| 1149 |
try:
|
|
@@ -1234,7 +1203,7 @@ with tab3:
|
|
| 1234 |
# count before
|
| 1235 |
data_before = col.get(include=["metadatas"], where={"sub_topic": ss})
|
| 1236 |
ids_before = data_before.get("ids", []) # ids are returned automatically in chromaDB
|
| 1237 |
-
before_ct = len(ids_before)
|
| 1238 |
# delete where sub_topic == ss
|
| 1239 |
try:
|
| 1240 |
col.delete(where={"sub_topic": ss})
|
|
@@ -1268,7 +1237,7 @@ with tab3:
|
|
| 1268 |
st.info("Deletion cancelled. Selections cleared.")
|
| 1269 |
|
| 1270 |
st.markdown("---")
|
| 1271 |
-
# B) Manage cache DB entries per topic β shows
|
| 1272 |
st.subheader("View / Delete cached Q&A entries (SQLite cache DB)")
|
| 1273 |
|
| 1274 |
try:
|
|
@@ -1295,21 +1264,102 @@ with tab3:
|
|
| 1295 |
if not rows:
|
| 1296 |
st.info("No cached Q&A for this topic.")
|
| 1297 |
else:
|
|
|
|
|
|
|
| 1298 |
for row in rows:
|
| 1299 |
-
# row
|
| 1300 |
-
|
| 1301 |
-
|
| 1302 |
-
|
| 1303 |
-
|
| 1304 |
-
|
| 1305 |
-
|
| 1306 |
-
|
| 1307 |
-
|
| 1308 |
-
|
| 1309 |
-
|
| 1310 |
-
|
| 1311 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1312 |
st.write(a_text)
|
|
|
|
| 1313 |
col1, col2, col3 = st.columns([1,1,4])
|
| 1314 |
with col1:
|
| 1315 |
if st.button(f"Delete id {rid}", key=f"del_{rid}"):
|
|
|
|
| 1 |
+
# version 1.8.16Xb - extended to include metric fields in SQLite cache, UI download & sorting/filtering
|
| 2 |
+
# Based on user's uploaded file kmai-v1.8.16Xa.py with requested features added.
|
|
|
|
|
|
|
|
|
|
| 3 |
|
| 4 |
import os
|
| 5 |
import io
|
|
|
|
| 60 |
gc.collect()
|
| 61 |
|
| 62 |
# =============================================
|
| 63 |
+
# helper: derive subtopic from filename
|
| 64 |
# =============================================
|
| 65 |
def derive_subtopic_from_filename(filename: str) -> str:
|
| 66 |
if not filename:
|
|
|
|
| 81 |
return candidate if candidate else "general"
|
| 82 |
|
| 83 |
# =============================================
|
| 84 |
+
# SQLITE CACHE DB (modified to include metric columns)
|
| 85 |
+
# - safe migration: add columns if missing
|
| 86 |
# =============================================
|
| 87 |
def init_cache_db(path: str = CACHE_DB_PATH):
|
| 88 |
conn = sqlite3.connect(path, check_same_thread=False)
|
| 89 |
cur = conn.cursor()
|
| 90 |
+
# Create base table if not exists (without metric columns yet)
|
|
|
|
| 91 |
cur.execute("""
|
| 92 |
CREATE TABLE IF NOT EXISTS qa_cache (
|
| 93 |
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
|
|
| 99 |
feedback_status TEXT CHECK(feedback_status IN ('Y','N')) DEFAULT NULL
|
| 100 |
);
|
| 101 |
""")
|
| 102 |
+
# ensure indices
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 103 |
cur.execute("CREATE INDEX IF NOT EXISTS idx_topic ON qa_cache(topic);")
|
| 104 |
cur.execute("CREATE INDEX IF NOT EXISTS idx_sub_topic ON qa_cache(sub_topic);")
|
| 105 |
conn.commit()
|
| 106 |
+
|
| 107 |
+
# Safe migration: ensure metric columns exist. Add them if missing.
|
| 108 |
+
cur.execute("PRAGMA table_info(qa_cache);")
|
| 109 |
+
existing_cols = [r[1] for r in cur.fetchall()] # second field is name
|
| 110 |
+
metric_cols = {
|
| 111 |
+
"cosine_score": "REAL",
|
| 112 |
+
"rouge2_score": "REAL",
|
| 113 |
+
"rougeL_score": "REAL"
|
| 114 |
+
}
|
| 115 |
+
for col, col_type in metric_cols.items():
|
| 116 |
+
if col not in existing_cols:
|
| 117 |
+
try:
|
| 118 |
+
cur.execute(f"ALTER TABLE qa_cache ADD COLUMN {col} {col_type};")
|
| 119 |
+
conn.commit()
|
| 120 |
+
except Exception as e:
|
| 121 |
+
st.warning(f"Could not add column {col}: {e}")
|
| 122 |
return conn
|
| 123 |
|
| 124 |
_cache_conn = init_cache_db()
|
| 125 |
|
| 126 |
def fetch_cache_by_topic(topic: str, only_helpful: bool = False):
|
| 127 |
"""
|
| 128 |
+
Returns rows with columns:
|
| 129 |
id, question, answer, created_at, feedback_status, sub_topic, cosine_score, rouge2_score, rougeL_score
|
| 130 |
"""
|
| 131 |
cur = _cache_conn.cursor()
|
|
|
|
| 144 |
|
| 145 |
def get_best_fuzzy_match(topic: str, question: str, threshold: float = 0.75):
|
| 146 |
"""
|
| 147 |
+
Return (id, stored_question, stored_answer, created_at, feedback_status, sub_topic, cosine_score, rouge2_score, rougeL_score, score)
|
| 148 |
or None if no match above threshold.
|
| 149 |
+
IMPORTANT: Only consider rows with feedback_status='Y' (helpful).
|
| 150 |
"""
|
| 151 |
rows = fetch_cache_by_topic(topic, only_helpful=True)
|
| 152 |
if not rows:
|
|
|
|
| 156 |
best = None
|
| 157 |
best_score = 0.0
|
| 158 |
for row in rows:
|
| 159 |
+
# row structure: id, question, answer, created_at, feedback_status, sub_topic, cosine_score, rouge2_score, rougeL_score
|
| 160 |
+
rid, stored_q, stored_a, created_at, fb, sub_topic, cos_m, r2_m, rL_m = row
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 161 |
score = SequenceMatcher(None, q_lower, (stored_q or "").lower().strip()).ratio()
|
| 162 |
if score > best_score:
|
| 163 |
best_score = score
|
| 164 |
+
best = (rid, stored_q, stored_a, created_at, fb, sub_topic, cos_m, r2_m, rL_m, score)
|
| 165 |
|
| 166 |
+
if best and best[9] >= threshold:
|
| 167 |
return best
|
| 168 |
return None
|
| 169 |
|
| 170 |
+
def insert_cache(topic: str, question: str, answer: str, feedback_status: str = None, sub_topic: str = "all",
|
| 171 |
+
cosine_score: float = None, rouge2_score: float = None, rougeL_score: float = None):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 172 |
now = datetime.now(timezone.utc).isoformat()
|
| 173 |
cur = _cache_conn.cursor()
|
| 174 |
cur.execute("""
|
| 175 |
+
INSERT INTO qa_cache (topic, sub_topic, question, answer, created_at, feedback_status, cosine_score, rouge2_score, rougeL_score)
|
|
|
|
| 176 |
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
| 177 |
""", (topic, sub_topic, question, answer, now, feedback_status, cosine_score, rouge2_score, rougeL_score))
|
| 178 |
_cache_conn.commit()
|
| 179 |
return cur.lastrowid
|
| 180 |
|
| 181 |
|
| 182 |
+
def upsert_cache(topic: str, question: str, answer: str, feedback_status: str = None, sub_topic: str = "all",
|
| 183 |
+
cosine_score: float = None, rouge2_score: float = None, rougeL_score: float = None):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 184 |
"""
|
| 185 |
Upsert identified by topic, question, AND sub_topic (so same question in different sub-topics are distinct).
|
| 186 |
+
Updates metric fields on update as well.
|
| 187 |
"""
|
| 188 |
now = datetime.now(timezone.utc).isoformat()
|
| 189 |
cur = _cache_conn.cursor()
|
|
|
|
| 191 |
row = cur.fetchone()
|
| 192 |
if row:
|
| 193 |
cur.execute(
|
| 194 |
+
"UPDATE qa_cache SET answer = ?, created_at = ?, feedback_status = ?, sub_topic = ?, cosine_score = ?, rouge2_score = ?, rougeL_score = ? WHERE id = ?",
|
| 195 |
+
(answer, now, feedback_status, sub_topic, cosine_score, rouge2_score, rougeL_score, row[0])
|
|
|
|
|
|
|
|
|
|
|
|
|
| 196 |
)
|
| 197 |
_cache_conn.commit()
|
| 198 |
return row[0]
|
|
|
|
| 260 |
chroma_client = PersistentClient(path=CHROMA_DIR)
|
| 261 |
|
| 262 |
# =============================================
|
| 263 |
+
# VECTOR DB HELPERS
|
| 264 |
# =============================================
|
| 265 |
def get_or_create_collection(topic_name: str):
|
| 266 |
try:
|
|
|
|
| 274 |
st.write("πΉ Starting document ingestion...")
|
| 275 |
# Derive sub-topic from filename
|
| 276 |
sub_topic = derive_subtopic_from_filename(pdf_filename)
|
| 277 |
+
st.info(f"Detected sub-topic: **{sub_topic}**")
|
| 278 |
|
| 279 |
col = get_or_create_collection(topic_name)
|
| 280 |
|
|
|
|
| 353 |
return sorted(relevant, key=lambda x: x["distance"])
|
| 354 |
|
| 355 |
# =============================================
|
| 356 |
+
# PDF / OCR / TABLE extraction functions
|
| 357 |
# =============================================
|
| 358 |
def extract_text_from_pdf_bytes(pdf_bytes: bytes) -> str:
|
| 359 |
text = ""
|
|
|
|
| 386 |
return "\n\n".join(table_texts)
|
| 387 |
|
| 388 |
# =============================================
|
| 389 |
+
# chunking & summarization (modified to return metrics)
|
| 390 |
# =============================================
|
| 391 |
def chunk_text(text: str, chunk_size=1000, overlap=200) -> List[str]:
|
| 392 |
if not text:
|
|
|
|
| 462 |
overlap: int = 200,
|
| 463 |
top_k: int = 4,
|
| 464 |
support_threshold: float = 0.60,
|
| 465 |
+
) -> (str, float, float, float):
|
| 466 |
+
"""
|
| 467 |
+
Returns:
|
| 468 |
+
final_summary (str), cosine_score (float or None), rouge2_score (float or None), rougeL_score (float or None)
|
| 469 |
+
"""
|
| 470 |
if top_k > 10:
|
| 471 |
support_threshold = 0.55
|
| 472 |
elif top_k > 6:
|
|
|
|
| 481 |
total_chunks = len(chunks)
|
| 482 |
|
| 483 |
if total_chunks == 0:
|
| 484 |
+
return "[No chunks to summarize.]", None, None, None
|
|
|
|
|
|
|
|
|
|
|
|
|
| 485 |
|
| 486 |
st.info(f"π Total combined chunks **{total_chunks}** (parallelizing up to {min(top_k, total_chunks)} workers).")
|
| 487 |
num_workers = max(1, min(top_k, total_chunks))
|
|
|
|
| 522 |
)
|
| 523 |
|
| 524 |
if not combined_summary_text:
|
| 525 |
+
return "[All chunk summarizations failed.]", None, None, None
|
|
|
|
|
|
|
|
|
|
| 526 |
|
| 527 |
if question:
|
| 528 |
final_prompt = f"""
|
|
|
|
| 658 |
|
| 659 |
final_summary = filtered_summary
|
| 660 |
|
|
|
|
| 661 |
cosine_score = None
|
| 662 |
try:
|
| 663 |
emb_model = get_embed_model()
|
|
|
|
| 678 |
except Exception as e:
|
| 679 |
st.warning(f"ROUGE scoring skipped: {e}")
|
| 680 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 681 |
def rating_label(score, high_thr, med_thr):
|
| 682 |
if score is None:
|
| 683 |
return ("-", "-", "-")
|
|
|
|
| 765 |
else:
|
| 766 |
st.success(f"β
Summarization completed in **{total_time:.2f} seconds**.")
|
| 767 |
|
| 768 |
+
return final_summary, cosine_score, rouge2_score, rougeL_score
|
| 769 |
|
| 770 |
# =============================================
|
| 771 |
# UI: Tabs (Upload / Ask / Manage)
|
|
|
|
| 773 |
tab1, tab2, tab3 = st.tabs(["Upload PDFs", "Ask Questions", "Manage Topics"])
|
| 774 |
|
| 775 |
# -----------------------
|
| 776 |
+
# Upload tab
|
| 777 |
# -----------------------
|
| 778 |
with tab1:
|
| 779 |
st.session_state["active_tab"] = "Upload PDFs"
|
|
|
|
| 852 |
st.warning(f"Could not fetch sample chunks: {e}")
|
| 853 |
|
| 854 |
# -----------------------
|
| 855 |
+
# Ask Questions tab
|
| 856 |
# -----------------------
|
| 857 |
with tab2:
|
| 858 |
st.session_state["active_tab"] = "Ask Questions"
|
|
|
|
| 885 |
try:
|
| 886 |
data_meta = col_for_topic.get(include=["metadatas"])
|
| 887 |
metas_all = data_meta.get("metadatas", [])
|
|
|
|
| 888 |
sth = set()
|
| 889 |
for m in metas_all:
|
| 890 |
if isinstance(m, dict):
|
| 891 |
stv = m.get("sub_topic") or "general"
|
| 892 |
sth.add(stv)
|
|
|
|
| 893 |
subtopic_options = ["All"] + sorted([s for s in sth if s and s.lower() != "all"])
|
| 894 |
except Exception:
|
| 895 |
subtopic_options = ["All"]
|
|
|
|
| 918 |
try:
|
| 919 |
topic_norm = topic_q.strip()
|
| 920 |
cache_start = time.time()
|
| 921 |
+
# Check cache (helpful entries only)
|
| 922 |
best = get_best_fuzzy_match(topic_norm, query_text.strip(), threshold=fuzzy_threshold)
|
| 923 |
cache_elapsed = time.time() - cache_start
|
| 924 |
|
| 925 |
if best:
|
| 926 |
+
# best = (rid, stored_q, stored_a, created_at, fb, sub_topic, cos_m, r2_m, rL_m, score)
|
| 927 |
+
rid, stored_q, stored_a, created_at, fb, sub_topic, cos_m, r2_m, rL_m, score = best
|
| 928 |
st.session_state["last_query"] = {
|
| 929 |
"topic": topic_norm,
|
| 930 |
+
"sub_topic": sub_topic or "all",
|
| 931 |
"question": query_text.strip(),
|
| 932 |
"cached": True,
|
| 933 |
"entry_id": rid,
|
|
|
|
| 937 |
"score": score,
|
| 938 |
"created_at": created_at,
|
| 939 |
"cache_time": cache_elapsed,
|
| 940 |
+
"cosine_score": cos_m,
|
| 941 |
+
"rouge2_score": r2_m,
|
| 942 |
+
"rougeL_score": rL_m
|
| 943 |
},
|
| 944 |
}
|
| 945 |
else:
|
|
|
|
| 967 |
|
| 968 |
sum_start = time.time()
|
| 969 |
with st.spinner("Summarizing..."):
|
| 970 |
+
summary, cosine_score, rouge2_score, rougeL_score = chunked_summarize(combined_text, question=query_text.strip(), top_k=top_k)
|
|
|
|
| 971 |
sum_elapsed = time.time() - sum_start
|
| 972 |
|
| 973 |
# store sub_topic used for query into cache record
|
| 974 |
cache_subtopic_value = subtopic_filter if subtopic_filter else "all"
|
| 975 |
+
inserted_id = insert_cache(topic_norm, query_text.strip(), summary, feedback_status=None,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 976 |
sub_topic=cache_subtopic_value,
|
| 977 |
+
cosine_score=cosine_score,
|
| 978 |
+
rouge2_score=rouge2_score,
|
| 979 |
+
rougeL_score=rougeL_score)
|
| 980 |
|
| 981 |
st.session_state["last_query"] = {
|
| 982 |
"topic": topic_norm,
|
|
|
|
| 989 |
"meta": {
|
| 990 |
"vec_time": vec_elapsed,
|
| 991 |
"sum_time": sum_elapsed,
|
| 992 |
+
"cosine_score": cosine_score,
|
| 993 |
+
"rouge2_score": rouge2_score,
|
| 994 |
+
"rougeL_score": rougeL_score
|
| 995 |
},
|
| 996 |
}
|
| 997 |
|
|
|
|
| 1008 |
st.subheader(f"Answer for: {last['question']} β *(Topic: {last['topic']}, Sub-topic: {last.get('sub_topic','all')})*")
|
| 1009 |
st.write(last["answer"])
|
| 1010 |
|
| 1011 |
+
# Show metrics if present
|
| 1012 |
+
meta_metrics = last.get("meta", {})
|
| 1013 |
+
if any(k in meta_metrics for k in ["cosine_score", "rouge2_score", "rougeL_score"]):
|
| 1014 |
+
metrics_html = f"""
|
| 1015 |
+
<div style="display:flex; gap:12px; align-items:center;">
|
| 1016 |
+
<div><b>Cosine:</b> {meta_metrics.get('cosine_score', '-')}</div>
|
| 1017 |
+
<div><b>ROUGE-2:</b> {meta_metrics.get('rouge2_score', '-')}</div>
|
| 1018 |
+
<div><b>ROUGE-L:</b> {meta_metrics.get('rougeL_score', '-')}</div>
|
| 1019 |
+
</div>
|
| 1020 |
+
"""
|
| 1021 |
+
st.markdown(metrics_html, unsafe_allow_html=True)
|
| 1022 |
+
|
| 1023 |
if last["cached"]:
|
| 1024 |
st.caption(f"β‘ Retrieved from cache (score={last['meta']['score']:.3f}, cached at {last['meta']['created_at']})")
|
| 1025 |
else:
|
| 1026 |
st.caption(f"Vector fetch took: **{last['meta']['vec_time']:.2f}s**, Summarization took: **{last['meta']['sum_time']:.2f}s**")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1027 |
|
| 1028 |
def show_feedback_controls_and_apply(entry_id: int):
|
| 1029 |
col_yes, col_no = st.columns(2)
|
|
|
|
| 1068 |
st.button("π¬ Ask another question", on_click=reset_query)
|
| 1069 |
|
| 1070 |
# -----------------------
|
| 1071 |
+
# Manage Topics tab
|
| 1072 |
# -----------------------
|
| 1073 |
with tab3:
|
| 1074 |
st.session_state["active_tab"] = "Manage Topics"
|
|
|
|
| 1085 |
else:
|
| 1086 |
topic_to_manage = st.selectbox("Select a topic to manage/delete:", all_topics, key="manage_topic_select")
|
| 1087 |
|
| 1088 |
+
# Display sub-topics under this topic
|
| 1089 |
try:
|
| 1090 |
col = get_or_create_collection(topic_to_manage)
|
| 1091 |
metas_all = col.get(include=["metadatas"]).get("metadatas", [])
|
|
|
|
| 1099 |
|
| 1100 |
st.write("Sub-topics under this topic:", ", ".join(sublist_unique) if sublist_unique else "β none found β")
|
| 1101 |
|
| 1102 |
+
# Two radio button options for delete behavior
|
| 1103 |
delete_option = st.radio("Delete options:", ["Delete entire topic", "Delete select sub-topic(s)"], key="delete_option_radio")
|
| 1104 |
|
| 1105 |
# Initialize session state values for confirmations
|
|
|
|
| 1113 |
st.session_state.total_before_sub = 0
|
| 1114 |
|
| 1115 |
if delete_option == "Delete entire topic":
|
|
|
|
| 1116 |
st.write("This will delete the entire Chroma collection and all its records.")
|
| 1117 |
if st.button("Prepare to delete entire topic"):
|
| 1118 |
try:
|
|
|
|
| 1203 |
# count before
|
| 1204 |
data_before = col.get(include=["metadatas"], where={"sub_topic": ss})
|
| 1205 |
ids_before = data_before.get("ids", []) # ids are returned automatically in chromaDB
|
| 1206 |
+
before_ct = len(ids_before)
|
| 1207 |
# delete where sub_topic == ss
|
| 1208 |
try:
|
| 1209 |
col.delete(where={"sub_topic": ss})
|
|
|
|
| 1237 |
st.info("Deletion cancelled. Selections cleared.")
|
| 1238 |
|
| 1239 |
st.markdown("---")
|
| 1240 |
+
# B) Manage cache DB entries per topic β shows metrics in Q&A expander
|
| 1241 |
st.subheader("View / Delete cached Q&A entries (SQLite cache DB)")
|
| 1242 |
|
| 1243 |
try:
|
|
|
|
| 1264 |
if not rows:
|
| 1265 |
st.info("No cached Q&A for this topic.")
|
| 1266 |
else:
|
| 1267 |
+
# Build DataFrame for full cached Q&A for this topic (with metric columns)
|
| 1268 |
+
df_rows = []
|
| 1269 |
for row in rows:
|
| 1270 |
+
# row: id, question, answer, created_at, feedback_status, sub_topic, cosine_score, rouge2_score, rougeL_score
|
| 1271 |
+
rid, q_text, a_text, created_at, fb, sub_topic, cos_m, r2_m, rL_m = row
|
| 1272 |
+
df_rows.append({
|
| 1273 |
+
"id": rid,
|
| 1274 |
+
"question": q_text,
|
| 1275 |
+
"answer": a_text,
|
| 1276 |
+
"created_at": created_at,
|
| 1277 |
+
"feedback_status": fb or "",
|
| 1278 |
+
"sub_topic": sub_topic or "all",
|
| 1279 |
+
"cosine_score": cos_m,
|
| 1280 |
+
"rouge2_score": r2_m,
|
| 1281 |
+
"rougeL_score": rL_m
|
| 1282 |
+
})
|
| 1283 |
+
df_cache = pd.DataFrame(df_rows)
|
| 1284 |
+
|
| 1285 |
+
# --- Filtering controls for metrics (Feature: sorting/filtering)
|
| 1286 |
+
st.markdown("**Filter & Sort cached Q&A by metric values**")
|
| 1287 |
+
filter_cols = st.columns(4)
|
| 1288 |
+
# provide checkboxes to enable filtering by each metric
|
| 1289 |
+
enable_cos = filter_cols[0].checkbox("Filter Cosine", value=False, key=f"f_cos_{t}")
|
| 1290 |
+
enable_r2 = filter_cols[1].checkbox("Filter ROUGE-2", value=False, key=f"f_r2_{t}")
|
| 1291 |
+
enable_rL = filter_cols[2].checkbox("Filter ROUGE-L", value=False, key=f"f_rL_{t}")
|
| 1292 |
+
|
| 1293 |
+
# prepare safe min,max ranges: metrics are between 0 and 1 typically; use 0..1 sliders
|
| 1294 |
+
def metric_slider(col_name, enabled, default_min=0.0, default_max=1.0):
|
| 1295 |
+
if enabled:
|
| 1296 |
+
min_v, max_v = st.slider(f"{col_name} range", min_value=0.0, max_value=1.0, value=(0.0, 1.0), step=0.01, key=f"sl_{t}_{col_name}")
|
| 1297 |
+
return min_v, max_v
|
| 1298 |
+
else:
|
| 1299 |
+
return None
|
| 1300 |
+
|
| 1301 |
+
cos_range = metric_slider("cosine_score", enable_cos)
|
| 1302 |
+
r2_range = metric_slider("rouge2_score", enable_r2)
|
| 1303 |
+
rL_range = metric_slider("rougeL_score", enable_rL)
|
| 1304 |
+
|
| 1305 |
+
# Sorting controls
|
| 1306 |
+
sort_col = st.selectbox("Sort by column:", options=["created_at", "cosine_score", "rouge2_score", "rougeL_score", "feedback_status"], index=0, key=f"sort_{t}")
|
| 1307 |
+
sort_dir = st.selectbox("Sort direction:", options=["descending", "ascending"], index=0, key=f"sortdir_{t}")
|
| 1308 |
+
|
| 1309 |
+
# Apply filters
|
| 1310 |
+
df_shown = df_cache.copy()
|
| 1311 |
+
# convert metric columns to numeric (they may be None)
|
| 1312 |
+
for mc in ["cosine_score", "rouge2_score", "rougeL_score"]:
|
| 1313 |
+
df_shown[mc] = pd.to_numeric(df_shown[mc], errors="coerce")
|
| 1314 |
+
|
| 1315 |
+
if cos_range:
|
| 1316 |
+
df_shown = df_shown[(df_shown["cosine_score"].fillna(-1) >= cos_range[0]) & (df_shown["cosine_score"].fillna(-1) <= cos_range[1])]
|
| 1317 |
+
if r2_range:
|
| 1318 |
+
df_shown = df_shown[(df_shown["rouge2_score"].fillna(-1) >= r2_range[0]) & (df_shown["rouge2_score"].fillna(-1) <= r2_range[1])]
|
| 1319 |
+
if rL_range:
|
| 1320 |
+
df_shown = df_shown[(df_shown["rougeL_score"].fillna(-1) >= rL_range[0]) & (df_shown["rougeL_score"].fillna(-1) <= rL_range[1])]
|
| 1321 |
+
|
| 1322 |
+
# Sort
|
| 1323 |
+
ascending = True if sort_dir == "ascending" else False
|
| 1324 |
+
if sort_col in df_shown.columns:
|
| 1325 |
+
# Some columns may be strings (created_at): handle numeric vs datetime
|
| 1326 |
+
if sort_col in ["cosine_score", "rouge2_score", "rougeL_score"]:
|
| 1327 |
+
df_shown = df_shown.sort_values(by=sort_col, ascending=ascending, na_position='last')
|
| 1328 |
+
else:
|
| 1329 |
+
df_shown = df_shown.sort_values(by=sort_col, ascending=ascending)
|
| 1330 |
+
|
| 1331 |
+
# Small UI for CSV export (professional compact control)
|
| 1332 |
+
st.markdown("**Download / Export**")
|
| 1333 |
+
export_cols = ["id", "topic", "sub_topic", "created_at", "feedback_status", "question", "answer", "cosine_score", "rouge2_score", "rougeL_score"]
|
| 1334 |
+
# Ensure 'topic' column present for context
|
| 1335 |
+
df_shown["topic"] = t
|
| 1336 |
+
csv_buffer = df_shown[["id", "topic", "sub_topic", "created_at", "feedback_status", "question", "answer", "cosine_score", "rouge2_score", "rougeL_score"]].to_csv(index=False)
|
| 1337 |
+
st.download_button(label="π₯ Download filtered cached Q&A as CSV", data=csv_buffer, file_name=f"cached_qna_{t}.csv", mime="text/csv", key=f"dl_{t}")
|
| 1338 |
+
|
| 1339 |
+
# Display the filtered & sorted table (compact)
|
| 1340 |
+
st.markdown("**Cached Q&A (filtered view)**")
|
| 1341 |
+
# shorten answer column for table display to keep UI tidy
|
| 1342 |
+
df_display = df_shown.copy()
|
| 1343 |
+
df_display["answer_excerpt"] = df_display["answer"].str.slice(0, 500).str.replace("\n", " ")
|
| 1344 |
+
display_cols = ["id", "created_at", "sub_topic", "feedback_status", "cosine_score", "rouge2_score", "rougeL_score", "question", "answer_excerpt"]
|
| 1345 |
+
st.dataframe(df_display[display_cols].reset_index(drop=True), use_container_width=True, height=300)
|
| 1346 |
+
|
| 1347 |
+
# Individual expanders for each entry (with delete / feedback actions)
|
| 1348 |
+
st.markdown("**Individual entries**")
|
| 1349 |
+
for _, r in df_shown.sort_values(by="created_at", ascending=False).iterrows():
|
| 1350 |
+
rid = int(r["id"])
|
| 1351 |
+
q_text = r["question"]
|
| 1352 |
+
a_text = r["answer"]
|
| 1353 |
+
created_at = r["created_at"]
|
| 1354 |
+
fb = r["feedback_status"]
|
| 1355 |
+
sub_topic = r["sub_topic"]
|
| 1356 |
+
cos_m = r["cosine_score"]
|
| 1357 |
+
r2_m = r["rouge2_score"]
|
| 1358 |
+
rL_m = r["rougeL_score"]
|
| 1359 |
+
header = f"Q: {q_text} (id: {rid}, created: {created_at}, sub_topic: {sub_topic}, feedback: {fb})"
|
| 1360 |
+
with st.expander(header):
|
| 1361 |
st.write(a_text)
|
| 1362 |
+
st.markdown(f"**Metrics:** Cosine={cos_m}, ROUGE-2={r2_m}, ROUGE-L={rL_m}")
|
| 1363 |
col1, col2, col3 = st.columns([1,1,4])
|
| 1364 |
with col1:
|
| 1365 |
if st.button(f"Delete id {rid}", key=f"del_{rid}"):
|