Skip to content

Commit f853628

Browse files
chore: document the semantic library map
1 parent 6727a27 commit f853628

2 files changed

Lines changed: 21 additions & 2 deletions

File tree

‎ARCHITECTURE.md‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -64,13 +64,14 @@ The backend is a standard FastAPI application. Three directories mirror the laye
6464
- `note_service.py` — CRUD for the per-item note filesystem, plus AI note generation (OpenAI JSON mode producing a structured tree of files/folders). Supports papers, websites, GitHub repos, and library-level notes.
6565
- `chat_service.py` — AI copilot: OpenAI chat with tool calling that can suggest diffs to notes. Works across papers, websites, and GitHub repos.
6666
- `search_service.py` — Unified search across papers, websites, and GitHub repos. Supports two modes: **lexical** (weighted keyword scoring per field, no API key needed) and **semantic** (OpenAI `text-embedding-3-small` cosine similarity, falls back to lexical when the API key is absent). Embeddings are cached in `backend/data/embeddings.json`.
67+
- `map_service.py` — UMAP 2D projection of cached item embeddings for the library map visualisation. Fetches all items in a library, filters to those with a cached embedding, and runs UMAP (`cosine` metric, `n_neighbors=min(15,n−1)`, `random_state=42`) inside a thread-pool executor so the async event loop is never blocked. The projection is cached in `backend/data/map_cache.json` keyed by a SHA-256 signature over the sorted set of embedding cache keys; the cache is invalidated automatically when the item set changes. `invalidate_map_cache()` can also be called explicitly after indexing new items.
6768
- `related_paper_service.py` — OpenAlex-powered related paper discovery for a seed paper. Combines semantic similarity links, citation references, and cited-by lookups from OpenAlex; falls back to title-neighbor search when direct links are sparse. Results are ranked by reason type and citation count and annotated with duplicate detection against the user's library.
6869
- `author_service.py` / `author_match_service.py` — Author CRUD and fuzzy name-matching across papers.
6970
- `github_repo_service.py` — GitHub repository import and metadata sync.
7071

7172
**`backend/routers/`** — One FastAPI router per resource. Thin handlers only. All routes are prefixed `/api`, and all responses are camelCase JSON via `model.model_dump(by_alias=True)`. Notable routers:
7273

73-
- `search.py` — `GET /api/search` with `?q=&mode=lexical|semantic&library_id=&types=` query parameters.
74+
- `search.py` — `GET /api/search` with `?q=&mode=lexical|semantic&library_id=&types=` query parameters. Also `GET /api/search/map?library_id=` which delegates to `map_service.build_map()` and returns the UMAP projection as a JSON array.
7475
- `settings.py` — `GET/PATCH /api/settings/models` for runtime LLM model selection.
7576

7677
**`backend/migrations/`** — SQL files run in order in the Supabase SQL editor. These are the schema source of truth.
@@ -133,6 +134,7 @@ The frontend is a React SPA with React Router v6 and Tailwind CSS.
133134
- `Website.jsx` — Three-pane layout: live iframe + Notes IDE + AI Copilot + Details panel.
134135
- `GitHubRepo.jsx` — Two-pane layout: repo overview (metadata, topics, description/abstract, links) + tabbed panel with Details and Notes IDE + AI Copilot.
135136
- `LibraryNotes.jsx` — Library-level Notes IDE with a file tree covering all notes across the library, a full-featured tiptap editor, and an optional D3 `NoteGraphView` sidebar for visualizing wiki-link connections.
137+
- `LibraryMap.jsx` — Semantic library map at `/library/map`. Fetches UMAP coordinates from `GET /api/search/map`, renders a D3 scatter plot on a dark dot-grid canvas, and supports zoom/pan (**Explore** mode) and brush-select (**Select** mode). Brush selection correctly inverts the current zoom transform when mapping pixel coordinates back to data space. Clicking a point navigates to the item's detail page. Color-coding toggles between first-collection and item-type. A collapsible legend panel mirrors the active colour scheme. Brush-selected items can be saved as a new collection via a `WindowModal` form that bulk-patches all selected items' `collections` field.
136138
- `Dashboard.jsx` — Activity feed, run stats, papers-over-time chart (Recharts). Triage health stat cards (Inbox / To Read / Read) are clickable and navigate to the corresponding filtered library view.
137139
- `Agents.jsx` — Workflow catalog and active runs with live log viewer.
138140
- `Proposals.jsx` — Human-in-the-loop approve/reject with diff view.
@@ -178,6 +180,20 @@ All AI features use OpenAI and share a pattern: extract context (PDF text, metad
178180

179181
`search_service.py` provides a unified search entry point over all item types. **Lexical mode** uses weighted keyword scoring per field (title, authors, tags, abstract, venue) and works without an API key. **Semantic mode** generates `text-embedding-3-small` embeddings via OpenAI, computes cosine similarity against cached item embeddings, and automatically falls back to lexical when the API key is absent or the call fails. Embeddings are persisted in `backend/data/embeddings.json` and are generated lazily on first search or on item import (as a background task). Cache keys are prefixed by type (`ws:` for websites, `gh:` for GitHub repos, bare ID for papers) for global uniqueness.
180182

183+
### Library Map
184+
185+
`map_service.py` turns the same embedding cache into a spatial overview of the whole library. On a `GET /api/search/map?library_id=` request it:
186+
187+
1. Loads all items for the library from Supabase.
188+
2. Filters to items that already have a cached embedding in `data/embeddings.json` — no new OpenAI calls are made.
189+
3. Computes a **signature** (16-char SHA-256 prefix over the sorted embedding-key list) and checks `data/map_cache.json`. On a cache hit the stored `x`/`y` coordinates are returned immediately with freshly fetched metadata (title, collections may have changed).
190+
4. On a cache miss, runs `umap.UMAP(n_components=2, metric="cosine", random_state=42)` inside `asyncio.get_event_loop().run_in_executor(None, ...)` so the event loop stays unblocked. Points with fewer than five embeddings fall back to a circle layout (too few for a meaningful UMAP projection).
191+
5. Normalises coordinates to `[−1, 1]` on each axis, saves the result keyed by library ID, and returns the point list.
192+
193+
The cache is invalidated whenever the set of embedded items changes — the signature check naturally catches additions and removals. `invalidate_map_cache()` can also be called explicitly.
194+
195+
The frontend `LibraryMap.jsx` renders the points in a D3 scatter plot. The **Explore** mode attaches `d3.zoom()` to the SVG and stores the running `ZoomTransform` in a ref that survives chart rebuilds. The **Select** mode attaches `d3.brush()` to a separate overlay group and uses `currentTransform.invert()` to convert brush-pixel coordinates into scale-space coordinates before hit-testing against the circle positions — this keeps selection correct at any zoom level. Switching modes rebuilds the chart but restores the stored zoom transform, so the viewport does not jump.
196+
181197
### Related Paper Discovery
182198

183199
`related_paper_service.py` queries the OpenAlex API to surface related works for a seed paper. It resolves the seed to an OpenAlex work record via DOI, arXiv ID, or title, then collects three pools of candidates: OpenAlex semantic-similarity links (`related_works`), outbound references (`referenced_works`), and papers that cite the seed (`cited_by_api_url`). Results are ranked by reason type and citation count. When the graph links are sparse, the service falls back to a title-neighbor search. Each candidate is annotated with duplicate-detection results against the user's library so the frontend can indicate which papers are already imported.

‎README.md‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ An AI-powered research operating system that merges a Zotero-like reference mana
3434
- **Editable tags for websites and GitHub repos** — tag chip editor available on all item types in detail panels, matching the existing paper tag editing experience
3535
- **Collections picker for GitHub repos** — GitHub repo detail panels now include the same collections picker available for papers and websites
3636
- **Export BibTeX from sidebar collection context menu** — the collection right-click menu includes an "Export BibTeX" action, making citation export accessible without opening the Library
37+
- **Semantic library map** — a 2D scatter plot of all papers, websites, and GitHub repos positioned by semantic similarity (UMAP over cached embeddings). Color-coded by collection or item type; hover for title and collection membership; click to navigate; brush-select a region to create a new collection from items that cluster together. No new AI calls — runs entirely on the existing embedding cache
3738

3839
## Tech Stack
3940

@@ -42,7 +43,7 @@ An AI-powered research operating system that merges a Zotero-like reference mana
4243
- **AI:** OpenAI
4344
- **Frontend:** React 18, Vite, React Router v6, Tailwind CSS 3
4445
- **Editor:** tiptap v3 with KaTeX
45-
- **Graph:** D3.js (note graph view)
46+
- **Graph:** D3.js (note graph view, library map)
4647

4748
## Quick Start
4849

@@ -152,6 +153,7 @@ CI (`.github/workflows/tests.yml`) runs backend tests, frontend tests/build, and
152153
| `/dashboard` | Activity feed + run stats |
153154
| `/library` | Paper, website, and GitHub repo library with collections, filters, and detail panels |
154155
| `/library/notes` | Library-level Notes IDE with D3 wiki-link graph |
156+
| `/library/map` | Semantic library map — 2D UMAP scatter of all items by embedding similarity |
155157
| `/library/paper/:id` | PDF viewer + Notes IDE + AI Copilot |
156158
| `/library/website/:id` | Live iframe + Notes IDE + AI Copilot + Details |
157159
| `/library/github-repo/:id` | Repo overview + Notes IDE + AI Copilot |
@@ -211,6 +213,7 @@ All routes are prefixed `/api`. Responses are camelCase JSON. See the full API r
211213
| GET | `/api/authors` | List authors |
212214
| GET/PATCH/DELETE | `/api/authors/{id}` | Single author |
213215
| GET | `/api/search` | Search across all item types; `?q=&mode=lexical\|semantic&library_id=&types=` |
216+
| GET | `/api/search/map` | UMAP 2D layout for all embedded items in a library; `?library_id=` |
214217
| GET | `/api/workflows` | Workflow catalog (read-only) |
215218
| GET/POST | `/api/runs` | List / start a run |
216219
| GET | `/api/runs/{id}` | Run with logs, trace, and cost |

0 commit comments

Comments
 (0)