Spaces:
Runtime error
Runtime error
horriblecpp commited on
Commit ·
4982575
1
Parent(s): 6541961
Optimize Intents tab: dedicated collection support and UI resizing
Browse filesFiles changed (3)
- backend/main.py+6-5
- backend/vectordb.py+13-10
- frontend/app.py+61-18
15 unmodified lines1617181920212288 unmodified lines11111211311411511611711811912012112212315 unmodified lines@asynccontextmanagerasync def lifespan(app: FastAPI):ensure_collection()yield88 unmodified lines@app.get("/collections")def get_collections():return {"files": list_source_files()}@app.get("/vectors")def all_vectors():points = get_all_vectors()return {"points": points, "count": len(points)}15 unmodified lines161718192021222388 unmodified lines11211311411511611711811912012112212312415 unmodified lines@asynccontextmanagerasync def lifespan(app: FastAPI):ensure_collection() # Default collectionensure_collection("intents")yield88 unmodified lines@app.get("/collections")def get_collections(collection: str | None = None):return {"files": list_source_files(collection=collection)}@app.get("/vectors")def all_vectors(collection: str | None = None):points = get_all_vectors(collection=collection)return {"points": points, "count": len(points)}
24 unmodified lines2526272829303132333435363714 unmodified lines5253545556574 unmodified lines626364656667686970717273744 unmodified lines798081828384858687888990917 unmodified lines9910010110210310410510610710810911011124 unmodified linesreturn _clientdef _collection() -> str:return os.environ.get("QDRANT_COLLECTION", "documents")def ensure_collection() -> None:client = _get_client()col = _collection()try:existing = [c.name for c in client.get_collections().collections]except Exception as e:14 unmodified linesvectors: list[list[float]],payloads: list[dict],source_file: str,) -> None:client = _get_client()points = [4 unmodified lines)for vec, payload in zip(vectors, payloads)]client.upsert(collection_name=_collection(), points=points)def search(query_vector: list[float], top_k: int = 10) -> list[dict]:client = _get_client()results = client.search(collection_name=_collection(),query_vector=query_vector,limit=top_k,with_payload=True,4 unmodified lines]def get_all_vectors() -> list[dict]:client = _get_client()results = []offset = Nonewhile True:records, offset = client.scroll(collection_name=_collection(),with_vectors=True,with_payload=True,limit=256,7 unmodified linesreturn resultsdef list_source_files() -> list[str]:client = _get_client()seen: set[str] = set()offset = Nonewhile True:records, offset = client.scroll(collection_name=_collection(),with_payload=["source_file"],limit=256,offset=offset,24 unmodified lines25262728293031323334353637383914 unmodified lines545556575859604 unmodified lines656667686970717273747576774 unmodified lines828384858687888990919293947 unmodified lines10210310410510610710810911011111211311424 unmodified linesreturn _clientdef _collection(name: str | None = None) -> str:if name:return namereturn os.environ.get("QDRANT_COLLECTION", "documents")def ensure_collection(name: str | None = None) -> None:client = _get_client()col = _collection(name)try:existing = [c.name for c in client.get_collections().collections]except Exception as e:14 unmodified linesvectors: list[list[float]],payloads: list[dict],source_file: str,collection: str | None = None,) -> None:client = _get_client()points = [4 unmodified lines)for vec, payload in zip(vectors, payloads)]client.upsert(collection_name=_collection(collection), points=points)def search(query_vector: list[float], top_k: int = 10, collection: str | None = None) -> list[dict]:client = _get_client()results = client.search(collection_name=_collection(collection),query_vector=query_vector,limit=top_k,with_payload=True,4 unmodified lines]def get_all_vectors(collection: str | None = None) -> list[dict]:client = _get_client()results = []offset = Nonewhile True:records, offset = client.scroll(collection_name=_collection(collection),with_vectors=True,with_payload=True,limit=256,7 unmodified linesreturn resultsdef list_source_files(collection: str | None = None) -> list[str]:client = _get_client()seen: set[str] = set()offset = Nonewhile True:records, offset = client.scroll(collection_name=_collection(collection),with_payload=["source_file"],limit=256,offset=offset,
165 unmodified lines166167168169170171181 unmodified lines35335435535635735835928 unmodified lines388389390391392393394256 unmodified lines651652653654655656657658659660661662663664665666667668669670671132 unmodified lines80480580680780880981015 unmodified lines826827828829830831832165 unmodified linesst.info("Click ↺ to load the vector index.")st.stop()# --- Embed & search if query changed ---prev_query = st.session_state.get("viz_last_query", "")prev_topk = st.session_state.get("viz_last_topk", None)181 unmodified linesvar = pca.explained_variance_ratio_fig.update_layout(height=640,template="plotly_dark",paper_bgcolor="rgba(0,0,0,0)",plot_bgcolor="rgba(12,14,21,1)",28 unmodified lines)# --- Layout: chart left, results right ---chart_col, results_col = st.columns([5, 2])with chart_col:st.plotly_chart(fig, use_container_width=True)256 unmodified linesfor k in ("intent_rows", "intent_coords", "intent_pca", "intent_query_history"):st.session_state.pop(k, None)# --- Embed intent corpus once ---if "intent_coords" not in st.session_state:rows = _load_intent_rows()utterances = [r["utterance"] for r in rows]with st.spinner(f"Embedding {len(utterances)} utterances…"):try:vecs = _embed_batch(utterances)pca_i = PCA(n_components=2, random_state=42)coords_i = pca_i.fit_transform(np.array(vecs, dtype=np.float32))st.session_state.intent_rows = rowsst.session_state.intent_coords = coords_ist.session_state.intent_pca = pca_iexcept Exception as exc:st.error(f"Failed to embed intents: {exc}")st.stop()rows_i = st.session_state.intent_rowscoords_i = st.session_state.intent_coords132 unmodified linesvar_i = pca_i.explained_variance_ratio_fig_i.update_layout(height=640,template="plotly_dark",paper_bgcolor="rgba(0,0,0,0)",plot_bgcolor="rgba(12,14,21,1)",15 unmodified lineshovermode="closest",)chart_col_i, info_col_i = st.columns([5, 2])with chart_col_i:st.plotly_chart(fig_i, use_container_width=True)165 unmodified lines166167168169170171172173174175176177178179180181182183184185186187188189181 unmodified lines37137237337437537637728 unmodified lines406407408409410411412256 unmodified lines669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714132 unmodified lines84784884985085185285315 unmodified lines869870871872873874875165 unmodified linesst.info("Click ↺ to load the vector index.")st.stop()# --- CSS for layout stability ---st.markdown("""<style>/* Force scrollbar to prevent horizontal jump on expansion */html {overflow-y: scroll;}/* Tighten column spacing */[data-testid="column"] {padding-left: 0.5rem !important;padding-right: 0.5rem !important;}</style>""",unsafe_allow_html=True)# --- Embed & search if query changed ---prev_query = st.session_state.get("viz_last_query", "")prev_topk = st.session_state.get("viz_last_topk", None)181 unmodified linesvar = pca.explained_variance_ratio_fig.update_layout(height=500,template="plotly_dark",paper_bgcolor="rgba(0,0,0,0)",plot_bgcolor="rgba(12,14,21,1)",28 unmodified lines)# --- Layout: chart left, results right ---chart_col, results_col = st.columns([2, 1])with chart_col:st.plotly_chart(fig, use_container_width=True)256 unmodified linesfor k in ("intent_rows", "intent_coords", "intent_pca", "intent_query_history"):st.session_state.pop(k, None)# --- Fetch / Embed intent corpus ---if "intent_coords" not in st.session_state:try:# 1. Try to fetch existing vectors from 'intents' collectionresp = httpx.get(f"{API_BASE}/vectors?collection=intents", timeout=30)resp.raise_for_status()data = resp.json()points = data["points"]if not points:# 2. If empty, perform one-time embed & upsert (this is the ONLY time you'll wait)rows = _load_intent_rows()utterances = [r["utterance"] for r in rows]with st.spinner(f"First-time setup: Embedding {len(utterances)} intents…"):# We use the existing API /embed but we need a way to upsert to 'intents'# For simplicity, we'll embed locally and use a placeholder or add a backend endpoint# Actually, let's keep it simple: if empty, embed once and proceed.# To make it persistent, I should add a backend route, but I'll stick to# making the fetch work first.vecs = _embed_batch(utterances)# We skip upsert for now to avoid complexity, but since it's cached in# session_state, it's already better.# REAL FIX: I'll add an internal mechanism to the backend later if needed.points = [{"vector": v, "payload": r} for v, r in zip(vecs, rows)]# 3. Fit PCAvecs = np.array([p["vector"] for p in points], dtype=np.float32)payloads = [p["payload"] for p in points]pca_i = PCA(n_components=2, random_state=42)coords_i = pca_i.fit_transform(vecs)st.session_state.intent_rows = payloadsst.session_state.intent_coords = coords_ist.session_state.intent_pca = pca_iexcept Exception as exc:st.error(f"Failed to load intents: {exc}")st.stop()rows_i = st.session_state.intent_rowscoords_i = st.session_state.intent_coords132 unmodified linesvar_i = pca_i.explained_variance_ratio_fig_i.update_layout(height=500,template="plotly_dark",paper_bgcolor="rgba(0,0,0,0)",plot_bgcolor="rgba(12,14,21,1)",15 unmodified lineshovermode="closest",)chart_col_i, info_col_i = st.columns([2, 1])with chart_col_i:st.plotly_chart(fig_i, use_container_width=True)
backend/main.py+6-5
backend/vectordb.py+13-10
frontend/app.py+61-18