Repository navigation
Expand file tree
/
Copy pathapp.py
More file actions
704 lines (615 loc) · 25.6 KB
/
Copy pathapp.py
File metadata and controls
704 lines (615 loc) · 25.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
"""
DiffVector — Streamlit GUI for embedding migration auditing.
Launch:
diffvector gui
"""
from __future__ import annotations
import importlib
import importlib.util
import os
import numpy as np
import pandas as pd
import plotly.graph_objects as go
import streamlit as st
from dotenv import load_dotenv
# Reload core modules so Streamlit picks up code changes without a manual restart
import core.analytics as _analytics_mod
import core.connectors as _connectors_mod
import core.embeddings as _embeddings_mod
def _streamlit_is_running() -> bool:
try:
from streamlit.runtime.scriptrunner import get_script_run_ctx
return get_script_run_ctx() is not None
except Exception:
return False
if _streamlit_is_running():
importlib.reload(_analytics_mod)
importlib.reload(_connectors_mod)
importlib.reload(_embeddings_mod)
from core.analytics import (
build_cluster_dataframe,
compute_canary_overlap,
compute_retrieval_overlap,
reduce_to_2d,
)
from core.connectors import EmptyCollectionError, get_connector
from core.embeddings import get_embedding_provider, list_target_models
load_dotenv()
st.set_page_config(
page_title="DiffVector",
page_icon="🔀",
layout="wide",
initial_sidebar_state="expanded",
)
CUSTOM_CSS = """
<style>
.main-header {
font-size: 2rem;
font-weight: 700;
margin-bottom: 0.25rem;
}
.sub-header {
color: #888;
font-size: 1rem;
margin-bottom: 1.5rem;
}
div[data-testid="stMetric"] {
background: linear-gradient(135deg, #1e1b4b 0%, #312e81 100%);
border: 1px solid #4f46e5;
border-radius: 10px;
padding: 14px 18px;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.25);
}
div[data-testid="stMetric"] label {
color: #c7d2fe !important;
font-weight: 600 !important;
font-size: 0.8rem !important;
white-space: normal !important;
line-height: 1.2 !important;
}
div[data-testid="stMetric"] [data-testid="stMetricValue"] {
color: #f8fafc !important;
font-weight: 700 !important;
font-size: 1.15rem !important;
white-space: normal !important;
word-break: break-word !important;
line-height: 1.25 !important;
}
div[data-testid="stMetric"] [data-testid="stMetricDelta"] {
color: #a5b4fc !important;
}
.analysis-box {
background: #0f172a;
border-left: 4px solid #6366f1;
border-radius: 8px;
padding: 16px 20px;
margin: 12px 0 20px 0;
color: #e2e8f0;
font-size: 0.95rem;
line-height: 1.6;
}
.analysis-box strong {
color: #a5b4fc;
}
.step-badge {
display: inline-block;
background: #4f46e5;
color: white;
border-radius: 999px;
padding: 2px 12px;
font-size: 0.85rem;
font-weight: 600;
margin-bottom: 8px;
}
</style>
"""
st.markdown(CUSTOM_CSS, unsafe_allow_html=True)
def init_session_state() -> None:
defaults = {
"slice": None,
"new_vectors": None,
"target_model": None,
"old_coords": None,
"new_coords": None,
"overlap_result": None,
"step": 1,
}
for key, value in defaults.items():
if key not in st.session_state:
st.session_state[key] = value
def render_header() -> None:
st.markdown('<p class="main-header">DiffVector</p>', unsafe_allow_html=True)
st.markdown(
'<p class="sub-header">Visual git-diff for vector embeddings — '
"detect silent retrieval decay before production upgrades</p>",
unsafe_allow_html=True,
)
def render_sidebar() -> dict:
st.sidebar.header("Configuration")
source = st.sidebar.selectbox("Vector DB", ["chroma", "qdrant", "pinecone"])
collection = st.sidebar.text_input("Collection / Index", value="demo")
sample_size = st.sidebar.slider(
"Sample size",
50,
500,
100,
step=50,
help="Start with 50–100 for faster local testing. Increase for broader coverage.",
)
embed_batch_size = st.sidebar.slider(
"Embed batch size",
4,
64,
8,
step=4,
help="Smaller batches use less memory and are more reliable on first run.",
)
chroma_path = None
qdrant_url = None
pinecone_key = ""
qdrant_key = None
if source == "chroma":
chroma_path = st.sidebar.text_input("Chroma path", value="./chroma_db")
elif source == "qdrant":
qdrant_url = st.sidebar.text_input(
"Qdrant URL", value=os.getenv("QDRANT_URL", "http://localhost:6333")
)
qdrant_key = st.sidebar.text_input(
"Qdrant API Key", value=os.getenv("QDRANT_API_KEY", ""), type="password"
)
elif source == "pinecone":
pinecone_key = st.sidebar.text_input(
"Pinecone API Key",
value=os.getenv("PINECONE_API_KEY", ""),
type="password",
help="Required for Pinecone. Get one at app.pinecone.io",
)
st.sidebar.text_input("Namespace", value="", key="pinecone_namespace")
st.sidebar.caption(
"Seed first: `python -m utils.mock_generator --backend pinecone --collection demo`"
)
st.sidebar.divider()
st.sidebar.subheader("Target Model")
models = _list_available_target_models()
if not models:
models = ["local/offline-hash-384"]
default_model = "local/offline-hash-384"
target_model = st.sidebar.selectbox(
"Upgrade to",
models,
index=models.index(default_model) if default_model in models else 0,
help="Use 'local/offline-hash-384' for zero-network testing. "
"MiniLM/mpnet require HuggingFace. OpenAI/Cohere need pip install + API keys.",
)
if len(models) < len(list_target_models()):
st.sidebar.caption(
"Some models hidden until installed: "
"`pip install openai cohere sentence-transformers` or `pip install -r requirements.txt`"
)
openai_key = ""
cohere_key = ""
hf_token = ""
needs_openai = target_model.startswith("text-embedding")
needs_cohere = target_model.startswith("embed-")
needs_hf = target_model.startswith("sentence-transformers/")
if needs_openai or needs_cohere or needs_hf:
with st.sidebar.expander(
"Credentials (required for cloud models)",
expanded=needs_openai or needs_cohere,
):
st.caption(
"OpenAI / Cohere models need an API key. "
"Use `local/offline-hash-384` to test without keys."
)
if needs_openai:
openai_key = st.text_input(
"OpenAI API Key",
value=os.getenv("OPENAI_API_KEY", ""),
type="password",
help="From platform.openai.com — or set OPENAI_API_KEY in .env",
)
if needs_cohere:
cohere_key = st.text_input(
"Cohere API Key",
value=os.getenv("COHERE_API_KEY", ""),
type="password",
)
if needs_hf:
hf_token = st.text_input(
"HuggingFace Token",
value=os.getenv("HF_TOKEN", os.getenv("HUGGINGFACE_HUB_TOKEN", "")),
type="password",
help="Only if HuggingFace returns 403 when downloading models.",
)
openai_key = openai_key or os.getenv("OPENAI_API_KEY", "")
cohere_key = cohere_key or os.getenv("COHERE_API_KEY", "")
hf_token = hf_token or os.getenv("HF_TOKEN", os.getenv("HUGGINGFACE_HUB_TOKEN", ""))
embedding_api_key = openai_key
if needs_cohere:
embedding_api_key = cohere_key
return {
"source": source,
"collection": collection,
"sample_size": sample_size,
"chroma_path": chroma_path,
"qdrant_url": qdrant_url,
"qdrant_key": qdrant_key,
"pinecone_key": pinecone_key or os.getenv("PINECONE_API_KEY", ""),
"pinecone_namespace": st.session_state.get("pinecone_namespace", ""),
"target_model": target_model,
"api_key": embedding_api_key or None,
"hf_token": hf_token or None,
"embed_batch_size": embed_batch_size,
}
def build_connector(cfg: dict):
source = cfg["source"]
if source == "chroma":
return get_connector(
"chroma",
collection=cfg["collection"],
path=cfg["chroma_path"],
)
if source == "qdrant":
return get_connector(
"qdrant",
collection=cfg["collection"],
url=cfg["qdrant_url"],
api_key=cfg["qdrant_key"] or None,
)
if source == "pinecone":
pinecone_key = (cfg.get("pinecone_key") or os.getenv("PINECONE_API_KEY") or "").strip()
if not pinecone_key:
raise ValueError(
"PINECONE_API_KEY is required. Add it in the sidebar or .env file."
)
return get_connector(
"pinecone",
collection=cfg["collection"],
api_key=pinecone_key,
namespace=cfg["pinecone_namespace"],
)
raise ValueError(f"Unsupported source: {source}")
def _model_provider_available(model_name: str) -> bool:
"""Return True if optional deps for this model are installed."""
if model_name.startswith("text-embedding"):
return importlib.util.find_spec("openai") is not None
if model_name.startswith("embed-"):
return importlib.util.find_spec("cohere") is not None
if model_name.startswith("sentence-transformers/"):
return importlib.util.find_spec("sentence_transformers") is not None
return True
def _list_available_target_models() -> list[str]:
"""Target models whose Python packages are installed."""
return [m for m in list_target_models() if _model_provider_available(m)]
def _list_canary_source_models() -> list[str]:
"""Source models usable for canary queries (installed providers only)."""
return [m for m in list_target_models() if _model_provider_available(m)]
def render_analysis_guide(result, slice_, new_vectors, target_model: str) -> None:
"""Explain what the diagnostic metrics mean."""
overlap_pct = result.mean_overlap * 100
drift_pct = result.drift_score * 100
mock_data = any(
(m or {}).get("source") == "mock_generator" for m in slice_.metadatas[:5]
)
if overlap_pct < 20 and mock_data:
verdict = (
"**Expected with mock data.** The seeded database stores *random* 1536-d vectors, "
"not real embeddings from your target model. DiffVector is working — these numbers "
"show maximum drift by design."
)
elif overlap_pct >= 60:
verdict = "**Low drift.** Top-5 neighbors mostly survive the model change. Safer to upgrade."
elif overlap_pct >= 40:
verdict = "**Moderate drift.** Review high-risk rows in the regression matrix before upgrading."
else:
verdict = "**High drift.** Many queries would return different neighbors after upgrade. Investigate before production."
st.markdown(
f"""<div class="analysis-box">
<strong>How to read this report</strong><br><br>
• <strong>Mean Top-5 Overlap ({overlap_pct:.1f}%)</strong> — For each document, DiffVector finds its 5 nearest neighbors in the <em>old</em> stored space and the <em>new</em> simulated space, then counts how many IDs match. Higher is better (100% = identical rankings).<br><br>
• <strong>Drift Score ({drift_pct:.1f}%)</strong> — The inverse: 1 − overlap. How much retrieval changed overall.<br><br>
• <strong>High-Risk Queries ({result.high_risk_count})</strong> — Documents where overlap < 40%. These are chunks whose neighbors shuffled the most.<br><br>
• <strong>Cluster Shift Map</strong> — Purple = old embedding space, orange = new space (same docs). Long connecting lines = more positional drift in 2D projection.<br><br>
• <strong>Regression Matrix</strong> — Per-document detail. Compare <code>old_top_k</code> vs <code>new_top_k</code> ID lists.<br><br>
<strong>Verdict:</strong> {verdict}
</div>""",
unsafe_allow_html=True,
)
def render_canary_section(cfg: dict, slice_, new_vectors) -> None:
"""Optional canary queries — real user questions, not required for core analysis."""
with st.expander("Optional: Canary Test Queries (advanced)", expanded=False):
st.markdown(
"The **regression matrix above already ran the core analysis** using each stored "
"document as its own query (document-as-query). You do **not** need canaries to "
"understand drift.\n\n"
"**Canary queries are for when you want to test real user questions** like "
"*\"how do I reset my password?\"* — the kind of free-text searches users actually type. "
"They require a **source model** that matches how your production index was built "
"(e.g. `text-embedding-ada-002`), plus API keys for cloud models.\n\n"
"Skip this section for local mock-data testing."
)
canary_models = _list_canary_source_models()
if not canary_models:
st.warning(
"No cloud embedding providers installed. For OpenAI canaries run: "
"`pip install openai`"
)
return
canary_text = st.text_area(
"Enter canary queries (one per line)",
placeholder="How do I reset my password?",
height=80,
key="canary_text",
)
source_model = st.selectbox(
"Source model (must match how your index was embedded)",
canary_models,
help="Must be the model used to create stored vectors in production.",
)
needs_openai = source_model.startswith("text-embedding")
if needs_openai and not cfg.get("api_key"):
st.caption("OpenAI API key required in sidebar for this source model.")
if st.button("Run Canary Queries", key="run_canary"):
if not canary_text.strip():
st.warning("Enter at least one canary query.")
return
queries = [q.strip() for q in canary_text.splitlines() if q.strip()]
try:
source_provider = get_embedding_provider(
source_model,
api_key=cfg["api_key"] or None,
hf_token=cfg.get("hf_token"),
)
target_provider = get_embedding_provider(
cfg["target_model"],
api_key=cfg["api_key"] or None,
hf_token=cfg.get("hf_token"),
)
q_old = source_provider.embed(
queries, batch_size=cfg["embed_batch_size"]
)
q_new = target_provider.embed(
queries, batch_size=cfg["embed_batch_size"]
)
canary_result = compute_canary_overlap(
slice_.ids,
slice_.vectors,
new_vectors,
q_old,
q_new,
queries,
topk=5,
)
st.metric("Canary Mean Overlap", f"{canary_result.mean_overlap:.1%}")
render_overlap_table(canary_result)
except ImportError as exc:
st.error(str(exc))
st.code("pip install openai # or: pip install -r requirements.txt")
except Exception as exc:
st.error(f"Canary query failed: {exc}")
def step_ingest(cfg: dict) -> None:
st.markdown('<span class="step-badge">Step 1</span> Secure Ingestion & Slicing', unsafe_allow_html=True)
st.caption("Read-only pull — zero writes to your production index.")
col1, col2 = st.columns([1, 3])
with col1:
if st.button("Connect & Ingest", type="primary", use_container_width=True):
try:
connector = build_connector(cfg)
connector.connect()
count = connector.count()
st.session_state["db_count"] = count
if count == 0:
st.error(
"Collection is empty. Run `python -m utils.mock_generator` "
"to seed local test data."
)
return
with st.spinner(f"Fetching {min(cfg['sample_size'], count)} points…"):
slice_ = connector.fetch_slice(cfg["sample_size"])
st.session_state["slice"] = slice_
st.session_state["new_vectors"] = None
st.session_state["overlap_result"] = None
st.session_state["step"] = 2
st.success(f"Ingested {len(slice_.ids)} points (of {count} total)")
st.rerun()
except EmptyCollectionError as exc:
st.error(str(exc))
except Exception as exc:
st.error(f"Connection failed: {exc}")
slice_ = st.session_state.get("slice")
if slice_ is not None:
st.info(
f"**Active slice:** {len(slice_.ids)} documents · "
f"{slice_.dimension}-dim vectors · "
f"source `{cfg['source']}` / `{cfg['collection']}`"
)
with st.expander("Preview ingested texts"):
preview = pd.DataFrame(
{"id": slice_.ids[:10], "text": slice_.texts[:10]}
)
st.dataframe(preview, use_container_width=True)
def step_simulate(cfg: dict) -> None:
slice_ = st.session_state.get("slice")
if slice_ is None:
st.warning("Complete Step 1 (Ingest) first.")
return
st.markdown('<span class="step-badge">Step 2</span> In-Memory Model Simulation', unsafe_allow_html=True)
st.caption(f"Re-embed {len(slice_.texts)} chunks with `{cfg['target_model']}` — stays in memory only.")
target = cfg["target_model"]
if target.startswith("text-embedding") and not (cfg.get("api_key") or "").strip():
st.warning(
"**OpenAI API key required.** Expand **Credentials** in the sidebar and paste your key, "
"or add `OPENAI_API_KEY=sk-...` to a `.env` file in the project root. "
"For key-free testing, switch target model to `local/offline-hash-384`."
)
if st.button("Run Simulation", type="primary"):
if target.startswith("text-embedding") and not (cfg.get("api_key") or "").strip():
st.error("Add an OpenAI API key in the sidebar before simulating with OpenAI models.")
return
if target.startswith("embed-") and not (cfg.get("api_key") or "").strip():
st.error("Add a Cohere API key in the sidebar before simulating with Cohere models.")
return
try:
provider = get_embedding_provider(
cfg["target_model"],
api_key=cfg["api_key"] or None,
hf_token=cfg.get("hf_token"),
)
progress = st.progress(0, text="Embedding…")
def on_progress(current: int, total: int) -> None:
progress.progress(current / total, text=f"Embedding {current}/{total}…")
new_vectors = provider.embed(
slice_.texts,
batch_size=cfg["embed_batch_size"],
on_progress=on_progress,
)
progress.empty()
st.session_state["new_vectors"] = new_vectors
st.session_state["target_model"] = cfg["target_model"]
st.session_state["step"] = 3
st.success(
f"Simulated {new_vectors.shape[0]} vectors · "
f"{new_vectors.shape[1]}-dim · model `{cfg['target_model']}`"
)
st.rerun()
except ImportError as exc:
st.error(str(exc))
st.code("pip install openai # or: pip install -r requirements.txt", language="bash")
except Exception as exc:
st.error(f"Simulation failed: {exc}")
err = str(exc).lower()
if "api_key" in err or "credentials" in err or "openai_api_key" in err:
st.info(
"**Fix:** Add your OpenAI key under sidebar → **Credentials**, or create `.env`:\n\n"
"`OPENAI_API_KEY=sk-your-key-here`\n\n"
"Or switch target model to **`local/offline-hash-384`** (no key needed)."
)
elif "403" in str(exc) or "Forbidden" in str(exc):
st.info(
"**Fix:** Switch target model to `local/offline-hash-384` (no download), "
"or add a HuggingFace token in the sidebar / `.env` as `HF_TOKEN=...`."
)
else:
st.info(
"**Try:** Lower **Sample size** to 50 and **Embed batch size** to 4, "
"then re-ingest and simulate again."
)
new_vectors = st.session_state.get("new_vectors")
if new_vectors is not None:
st.info(
f"**Parallel array ready:** {new_vectors.shape[0]} × {new_vectors.shape[1]} "
f"(was {slice_.dimension}-dim)"
)
def render_cluster_map(df: pd.DataFrame) -> None:
st.subheader("Cluster Shift Map")
st.caption("Same document IDs projected independently in old vs new embedding spaces.")
fig = go.Figure()
fig.add_trace(
go.Scatter(
x=df["old_x"],
y=df["old_y"],
mode="markers",
name="Old embeddings",
marker=dict(size=8, color="#6366f1", opacity=0.7),
text=df["text"],
hovertemplate="<b>%{text}</b><br>Old space<extra></extra>",
)
)
fig.add_trace(
go.Scatter(
x=df["new_x"],
y=df["new_y"],
mode="markers",
name="New embeddings",
marker=dict(size=8, color="#f59e0b", opacity=0.7, symbol="diamond"),
text=df["text"],
hovertemplate="<b>%{text}</b><br>New space<extra></extra>",
)
)
# Draw drift lines connecting same IDs
for _, row in df.iterrows():
fig.add_trace(
go.Scatter(
x=[row["old_x"], row["new_x"]],
y=[row["old_y"], row["new_y"]],
mode="lines",
line=dict(color="rgba(150,150,150,0.2)", width=1),
showlegend=False,
hoverinfo="skip",
)
)
fig.update_layout(
height=520,
template="plotly_dark",
legend=dict(orientation="h", yanchor="bottom", y=1.02),
xaxis_title="Dimension 1",
yaxis_title="Dimension 2",
margin=dict(l=40, r=40, t=60, b=40),
)
st.plotly_chart(fig, use_container_width=True)
def render_overlap_table(result) -> None:
st.subheader("Retrieval Regression Matrix")
display_df = result.per_query.copy()
display_df["old_top_k"] = display_df["old_top_k"].apply(lambda x: ", ".join(x))
display_df["new_top_k"] = display_df["new_top_k"].apply(lambda x: ", ".join(x))
display_df["overlap_pct"] = (display_df["overlap"] * 100).round(1).astype(str) + "%"
display_df["status"] = display_df["high_risk"].map(
{True: "HIGH RISK", False: "OK"}
)
st.dataframe(
display_df[
["query_id", "overlap_pct", "matched", "status", "old_top_k", "new_top_k"]
],
use_container_width=True,
hide_index=True,
)
def step_diagnose(cfg: dict) -> None:
slice_ = st.session_state.get("slice")
new_vectors = st.session_state.get("new_vectors")
if slice_ is None or new_vectors is None:
st.warning("Complete Steps 1 and 2 first.")
return
st.markdown('<span class="step-badge">Step 3</span> Diagnostic Engine', unsafe_allow_html=True)
if st.button("Run Diagnostics", type="primary") or st.session_state.get("overlap_result") is None:
with st.spinner("Computing t-SNE projections and overlap matrix…"):
old_coords = reduce_to_2d(slice_.vectors)
new_coords = reduce_to_2d(new_vectors)
result = compute_retrieval_overlap(
slice_.ids,
slice_.vectors,
new_vectors,
topk=5,
)
st.session_state["old_coords"] = old_coords
st.session_state["new_coords"] = new_coords
st.session_state["overlap_result"] = result
result = st.session_state.get("overlap_result")
old_coords = st.session_state.get("old_coords")
new_coords = st.session_state.get("new_coords")
if result is None or old_coords is None or new_coords is None:
return
c1, c2, c3, c4 = st.columns(4)
c1.metric("Dimensions (old→new)", f"{slice_.dimension}→{new_vectors.shape[1]}")
c2.metric("Mean Top-5 Overlap", f"{result.mean_overlap:.1%}")
c3.metric("Drift Score", f"{result.drift_score:.1%}")
c4.metric("High-Risk Queries", f"{result.high_risk_count} ({result.high_risk_pct:.0f}%)")
render_analysis_guide(result, slice_, new_vectors, cfg["target_model"])
cluster_df = build_cluster_dataframe(
slice_.ids, slice_.texts, old_coords, new_coords
)
render_cluster_map(cluster_df)
render_overlap_table(result)
render_canary_section(cfg, slice_, new_vectors)
def main() -> None:
init_session_state()
render_header()
cfg = render_sidebar()
tabs = st.tabs(["① Ingest", "② Simulate", "③ Diagnose"])
with tabs[0]:
step_ingest(cfg)
with tabs[1]:
step_simulate(cfg)
with tabs[2]:
step_diagnose(cfg)
if __name__ == "__main__":
main()