Spaces:
Running on CPU Upgrade
Running on CPU Upgrade
updating backend for larger corpus
Browse files- .DS_Store +0 -0
- .dockerignore +8 -0
- .gitignore +10 -1
- Dockerfile +28 -0
- README.md +2 -3
- app.py → app.py_old +0 -0
- app_gradio.py → app_gradio.py_old +0 -0
- backend/.env.example +5 -0
- backend/astroparse_api/__init__.py +0 -0
- backend/astroparse_api/bootstrap.py +28 -0
- backend/astroparse_api/jobs.py +28 -0
- backend/astroparse_api/main.py +141 -0
- backend/astroparse_api/retrieve.py +123 -0
- backend/astroparse_api/schemas.py +22 -0
- backend/astroparse_api/search.py +106 -0
- backend/pyproject.toml +22 -0
- backend/uv.lock +0 -0
- frontend/index.html +16 -0
- frontend/package.json +9 -0
- frontend/src/App.jsx +334 -0
- frontend/src/api.js +27 -0
- frontend/src/main.jsx +6 -0
- frontend/src/theme.js +52 -0
- frontend/vite.config.js +8 -0
.DS_Store
CHANGED
|
Binary files a/.DS_Store and b/.DS_Store differ
|
|
|
.dockerignore
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# .dockerignore
|
| 2 |
+
backend/.venv
|
| 3 |
+
backend/data
|
| 4 |
+
frontend/node_modules
|
| 5 |
+
frontend/dist
|
| 6 |
+
.git
|
| 7 |
+
.gitignore
|
| 8 |
+
*.md
|
.gitignore
CHANGED
|
@@ -1,2 +1,11 @@
|
|
| 1 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
.DS_Store
|
|
|
|
| 1 |
+
# .gitignore
|
| 2 |
+
backend/.venv/
|
| 3 |
+
backend/data/
|
| 4 |
+
backend/__pycache__/
|
| 5 |
+
backend/**/__pycache__/
|
| 6 |
+
backend/annotations_cache.sqlite
|
| 7 |
+
frontend/node_modules/
|
| 8 |
+
frontend/dist/
|
| 9 |
+
.env
|
| 10 |
+
*.pyc
|
| 11 |
.DS_Store
|
Dockerfile
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM node:20-slim AS fe
|
| 2 |
+
WORKDIR /fe
|
| 3 |
+
COPY frontend/package*.json ./
|
| 4 |
+
RUN npm ci
|
| 5 |
+
COPY frontend/ ./
|
| 6 |
+
RUN npm run build
|
| 7 |
+
|
| 8 |
+
FROM python:3.11-slim
|
| 9 |
+
COPY --from=ghcr.io/astral-sh/uv:latest /uv /uvx /bin/
|
| 10 |
+
WORKDIR /app
|
| 11 |
+
|
| 12 |
+
COPY backend/pyproject.toml backend/uv.lock* ./backend/
|
| 13 |
+
WORKDIR /app/backend
|
| 14 |
+
RUN uv sync --no-dev || uv sync --no-dev --no-install-project
|
| 15 |
+
RUN uv run python -m spacy download en_core_web_sm
|
| 16 |
+
|
| 17 |
+
COPY backend/ /app/backend/
|
| 18 |
+
COPY --from=fe /fe/dist /app/frontend/dist
|
| 19 |
+
|
| 20 |
+
ENV PATHFINDER_STATIC_DIR=/app/frontend/dist \
|
| 21 |
+
ASTROPARSE_CORPUS_DIR=/data/corpus \
|
| 22 |
+
ASTROPARSE_FAISS_PATH=/data/astroparse_fp16.faiss \
|
| 23 |
+
HF_HOME=/data/hf_cache
|
| 24 |
+
|
| 25 |
+
RUN mkdir -p /data && chmod 777 /data
|
| 26 |
+
|
| 27 |
+
EXPOSE 7860
|
| 28 |
+
CMD ["uv", "run", "--no-sync", "uvicorn", "astroparse_api.main:app", "--host", "0.0.0.0", "--port", "7860"]
|
README.md
CHANGED
|
@@ -3,9 +3,8 @@ title: Pathfinder
|
|
| 3 |
emoji: 🔎
|
| 4 |
colorFrom: yellow
|
| 5 |
colorTo: blue
|
| 6 |
-
sdk:
|
| 7 |
-
|
| 8 |
-
app_file: app_gradio.py
|
| 9 |
pinned: true
|
| 10 |
license: mit
|
| 11 |
---
|
|
|
|
| 3 |
emoji: 🔎
|
| 4 |
colorFrom: yellow
|
| 5 |
colorTo: blue
|
| 6 |
+
sdk: docker
|
| 7 |
+
app_port: 7860
|
|
|
|
| 8 |
pinned: true
|
| 9 |
license: mit
|
| 10 |
---
|
app.py → app.py_old
RENAMED
|
File without changes
|
app_gradio.py → app_gradio.py_old
RENAMED
|
File without changes
|
backend/.env.example
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# backend/.env.example
|
| 2 |
+
OPENAI_API_KEY=sk-...
|
| 3 |
+
GITHUB_TOKEN=ghp_...
|
| 4 |
+
GIST_ID=...
|
| 5 |
+
PATHFINDER_CORPUS_REPO=kiyer/beacon_corpus
|
backend/astroparse_api/__init__.py
ADDED
|
File without changes
|
backend/astroparse_api/bootstrap.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# backend/astroparse_api/bootstrap.py — unchanged from Beacon, corpus pull is identical
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import shutil
|
| 5 |
+
import tempfile
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
|
| 8 |
+
from huggingface_hub import snapshot_download # noqa: F401 — re-exported so tests can patch
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def ensure_corpus(corpus_dir: Path, faiss_path: Path, repo_id: str) -> None:
|
| 12 |
+
if corpus_dir.is_dir() and faiss_path.is_file():
|
| 13 |
+
return
|
| 14 |
+
|
| 15 |
+
import astroparse_api.bootstrap as _self
|
| 16 |
+
_snapshot_download = _self.snapshot_download
|
| 17 |
+
|
| 18 |
+
with tempfile.TemporaryDirectory() as staging:
|
| 19 |
+
staging_path = Path(staging)
|
| 20 |
+
_snapshot_download(repo_id=repo_id, repo_type="dataset", local_dir=staging_path)
|
| 21 |
+
|
| 22 |
+
src_faiss = staging_path / "astroparse_fp16.faiss"
|
| 23 |
+
faiss_path.parent.mkdir(parents=True, exist_ok=True)
|
| 24 |
+
shutil.move(str(src_faiss), str(faiss_path))
|
| 25 |
+
|
| 26 |
+
src_corpus = staging_path / "corpus"
|
| 27 |
+
corpus_dir.parent.mkdir(parents=True, exist_ok=True)
|
| 28 |
+
shutil.move(str(src_corpus), str(corpus_dir))
|
backend/astroparse_api/jobs.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# backend/astroparse_api/jobs.py
|
| 2 |
+
import asyncio
|
| 3 |
+
import uuid
|
| 4 |
+
from dataclasses import dataclass, field
|
| 5 |
+
|
| 6 |
+
@dataclass
|
| 7 |
+
class Job:
|
| 8 |
+
id: str = field(default_factory=lambda: uuid.uuid4().hex)
|
| 9 |
+
queue: asyncio.Queue = field(default_factory=asyncio.Queue)
|
| 10 |
+
done: bool = False
|
| 11 |
+
|
| 12 |
+
class JobRegistry:
|
| 13 |
+
def __init__(self):
|
| 14 |
+
self._jobs: dict[str, Job] = {}
|
| 15 |
+
|
| 16 |
+
def create(self) -> Job:
|
| 17 |
+
job = Job()
|
| 18 |
+
self._jobs[job.id] = job
|
| 19 |
+
return job
|
| 20 |
+
|
| 21 |
+
def get(self, job_id: str) -> Job | None:
|
| 22 |
+
return self._jobs.get(job_id)
|
| 23 |
+
|
| 24 |
+
async def emit(job: Job, event: str, data: dict):
|
| 25 |
+
await job.queue.put({"event": event, "data": data})
|
| 26 |
+
if event in ("result", "error", "blocked"):
|
| 27 |
+
job.done = True
|
| 28 |
+
await job.queue.put(None)
|
backend/astroparse_api/main.py
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# backend/astroparse_api/main.py
|
| 2 |
+
import asyncio
|
| 3 |
+
import json
|
| 4 |
+
import os
|
| 5 |
+
from contextlib import asynccontextmanager
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
|
| 8 |
+
from dotenv import load_dotenv
|
| 9 |
+
from fastapi import FastAPI, HTTPException
|
| 10 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 11 |
+
from fastapi.staticfiles import StaticFiles
|
| 12 |
+
from pydantic import BaseModel
|
| 13 |
+
from sse_starlette.sse import EventSourceResponse
|
| 14 |
+
|
| 15 |
+
from .bootstrap import ensure_corpus
|
| 16 |
+
from .jobs import Job, JobRegistry, emit
|
| 17 |
+
from .retrieve import Corpus
|
| 18 |
+
from .search import check_moderation, log_query_to_gist, search_corpus, synthesize_answer, score_consensus
|
| 19 |
+
|
| 20 |
+
load_dotenv(Path(__file__).resolve().parent.parent / ".env")
|
| 21 |
+
|
| 22 |
+
_DEFAULT_DATA_DIR = Path(__file__).resolve().parent.parent / "data"
|
| 23 |
+
_REPO_ROOT = Path(__file__).resolve().parent.parent.parent
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
@asynccontextmanager
|
| 27 |
+
async def lifespan(app: FastAPI):
|
| 28 |
+
if os.environ.get("ASTROPARSE_SKIP_CORPUS") != "1":
|
| 29 |
+
corpus_dir = Path(os.environ.get("ASTROPARSE_CORPUS_DIR", str(_DEFAULT_DATA_DIR / "corpus")))
|
| 30 |
+
faiss_path = Path(os.environ.get("ASTROPARSE_FAISS_PATH", str(_DEFAULT_DATA_DIR / "astroparse_fp16.faiss")))
|
| 31 |
+
corpus_repo = os.environ.get("PATHFINDER_CORPUS_REPO", "kiyer/beacon_corpus")
|
| 32 |
+
await asyncio.to_thread(ensure_corpus, corpus_dir, faiss_path, corpus_repo)
|
| 33 |
+
await asyncio.to_thread(get_corpus)
|
| 34 |
+
yield
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
app = FastAPI(lifespan=lifespan)
|
| 38 |
+
app.add_middleware(
|
| 39 |
+
CORSMiddleware,
|
| 40 |
+
allow_origins=[os.environ.get("PATHFINDER_DEV_ORIGIN", "http://localhost:5173")],
|
| 41 |
+
allow_methods=["*"],
|
| 42 |
+
allow_headers=["*"],
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
registry = JobRegistry()
|
| 46 |
+
_corpus: Corpus | None = None
|
| 47 |
+
_umap_cache: list | None = None
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def get_corpus() -> Corpus:
|
| 51 |
+
global _corpus
|
| 52 |
+
if _corpus is None:
|
| 53 |
+
_corpus = Corpus.load()
|
| 54 |
+
return _corpus
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
class SearchRequest(BaseModel):
|
| 58 |
+
query: str
|
| 59 |
+
top_k: int = 10
|
| 60 |
+
pool: int = 1000
|
| 61 |
+
answer_style: str = "Multi-paper"
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
async def run_search_pipeline(job: Job, req: SearchRequest):
|
| 65 |
+
try:
|
| 66 |
+
async def stage(name, status, log=None):
|
| 67 |
+
await emit(job, "stage", {"name": name, "status": status, "log": log})
|
| 68 |
+
|
| 69 |
+
key = os.environ.get("OPENAI_API_KEY", "")
|
| 70 |
+
|
| 71 |
+
flagged = await asyncio.to_thread(check_moderation, req.query, key)
|
| 72 |
+
asyncio.create_task(log_query_to_gist(req.query, flagged))
|
| 73 |
+
if flagged:
|
| 74 |
+
await emit(job, "blocked", {
|
| 75 |
+
"message": "This query was flagged by content moderation. Try rephrasing your question."
|
| 76 |
+
})
|
| 77 |
+
return
|
| 78 |
+
|
| 79 |
+
await stage("intent", "active")
|
| 80 |
+
await stage("intent", "done", f"{req.answer_style.lower()} synthesis")
|
| 81 |
+
|
| 82 |
+
await stage("search", "active")
|
| 83 |
+
corpus = await asyncio.to_thread(get_corpus)
|
| 84 |
+
papers, abstracts = await asyncio.to_thread(
|
| 85 |
+
search_corpus, corpus, req.query, req.top_k, req.pool, key
|
| 86 |
+
)
|
| 87 |
+
await emit(job, "papers", {"papers": [p.model_dump() for p in papers]})
|
| 88 |
+
await stage("search", "done", f"{len(papers)} papers retrieved")
|
| 89 |
+
|
| 90 |
+
await stage("consensus", "active")
|
| 91 |
+
consensus = await score_consensus(req.query, abstracts, key)
|
| 92 |
+
await emit(job, "consensus", consensus)
|
| 93 |
+
await stage("consensus", "done", f"{len(abstracts)} abstracts \u2192 {consensus['label'].lower()}")
|
| 94 |
+
|
| 95 |
+
await stage("compose", "active")
|
| 96 |
+
async for chunk in synthesize_answer(req.query, papers, abstracts, req.answer_style, key):
|
| 97 |
+
await emit(job, "answer_token", {"text": chunk})
|
| 98 |
+
await stage("compose", "done", "gpt-4o-mini")
|
| 99 |
+
|
| 100 |
+
await emit(job, "result", {"done": True})
|
| 101 |
+
except Exception as e: # noqa: BLE001 — job boundary
|
| 102 |
+
await emit(job, "error", {"message": str(e)[:300]})
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
@app.post("/api/search", status_code=202)
|
| 106 |
+
async def search_endpoint(req: SearchRequest):
|
| 107 |
+
job = registry.create()
|
| 108 |
+
asyncio.create_task(run_search_pipeline(job, req))
|
| 109 |
+
return {"jobId": job.id}
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
@app.get("/api/jobs/{job_id}/events")
|
| 113 |
+
async def job_events(job_id: str):
|
| 114 |
+
job = registry.get(job_id)
|
| 115 |
+
if job is None:
|
| 116 |
+
raise HTTPException(404, "unknown job")
|
| 117 |
+
|
| 118 |
+
async def gen():
|
| 119 |
+
while True:
|
| 120 |
+
item = await job.queue.get()
|
| 121 |
+
if item is None:
|
| 122 |
+
break
|
| 123 |
+
yield {"event": item["event"], "data": json.dumps(item["data"])}
|
| 124 |
+
|
| 125 |
+
return EventSourceResponse(gen())
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
@app.get("/api/umap-sample")
|
| 129 |
+
async def umap_sample(n: int = 4000):
|
| 130 |
+
"""Background scatter for the embedding map. Cached in-process after the
|
| 131 |
+
first call since the corpus doesn't change at runtime."""
|
| 132 |
+
global _umap_cache
|
| 133 |
+
if _umap_cache is None:
|
| 134 |
+
corpus = await asyncio.to_thread(get_corpus)
|
| 135 |
+
_umap_cache = await asyncio.to_thread(corpus.umap_sample, n)
|
| 136 |
+
return {"points": _umap_cache}
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
_static_dir = Path(os.environ.get("PATHFINDER_STATIC_DIR", str(_REPO_ROOT / "frontend" / "dist")))
|
| 140 |
+
if _static_dir.is_dir():
|
| 141 |
+
app.mount("/", StaticFiles(directory=str(_static_dir), html=True), name="spa")
|
backend/astroparse_api/retrieve.py
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# backend/astroparse_api/retrieve.py
|
| 2 |
+
import os
|
| 3 |
+
import re
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
|
| 6 |
+
import numpy as np
|
| 7 |
+
|
| 8 |
+
_POS_TAGS = {"PROPN", "ADJ", "NOUN"}
|
| 9 |
+
_nlp = None
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def _get_nlp():
|
| 13 |
+
global _nlp
|
| 14 |
+
if _nlp is None:
|
| 15 |
+
import spacy
|
| 16 |
+
_nlp = spacy.load("en_core_web_sm")
|
| 17 |
+
return _nlp
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def get_keywords(text: str) -> list[str]:
|
| 21 |
+
doc = _get_nlp()(text.lower())
|
| 22 |
+
return [t.text for t in doc if t.pos_ in _POS_TAGS and not t.is_stop and not t.is_punct]
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def keyword_weights(query_kws: list[str], candidate_kws: list[list[str]]) -> np.ndarray:
|
| 26 |
+
w = np.full(len(candidate_kws), 0.1)
|
| 27 |
+
for qk in query_kws:
|
| 28 |
+
qk = qk.lower()
|
| 29 |
+
for i, kws in enumerate(candidate_kws):
|
| 30 |
+
for k in kws:
|
| 31 |
+
if qk in k.lower():
|
| 32 |
+
w[i] += 0.1
|
| 33 |
+
return w / w.max()
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
from .schemas import LitPaper, Scores # noqa: E402
|
| 37 |
+
|
| 38 |
+
EMBED_MODEL = "text-embedding-3-small"
|
| 39 |
+
_ARXIV_ID = re.compile(r"^\d{4}\.\d{4,5}$")
|
| 40 |
+
_DEFAULT_DATA_DIR = Path(__file__).resolve().parent.parent / "data"
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class Corpus:
|
| 44 |
+
def __init__(self, dataset, index):
|
| 45 |
+
self.ds = dataset
|
| 46 |
+
self.index = index
|
| 47 |
+
|
| 48 |
+
@property
|
| 49 |
+
def arxiv_ids(self) -> set[str]:
|
| 50 |
+
if not hasattr(self, "_arxiv_ids"):
|
| 51 |
+
col = self.ds["arxiv_id"] if "arxiv_id" in self.ds.column_names else []
|
| 52 |
+
self._arxiv_ids = {x for x in col if x}
|
| 53 |
+
return self._arxiv_ids
|
| 54 |
+
|
| 55 |
+
@property
|
| 56 |
+
def bibcodes(self) -> set[str]:
|
| 57 |
+
if not hasattr(self, "_bibcodes"):
|
| 58 |
+
col = self.ds["bibcode"] if "bibcode" in self.ds.column_names else []
|
| 59 |
+
self._bibcodes = {x for x in col if x}
|
| 60 |
+
return self._bibcodes
|
| 61 |
+
|
| 62 |
+
@classmethod
|
| 63 |
+
def load(cls) -> "Corpus":
|
| 64 |
+
import faiss
|
| 65 |
+
from datasets import load_dataset
|
| 66 |
+
|
| 67 |
+
corpus_dir = Path(os.environ.get("ASTROPARSE_CORPUS_DIR", _DEFAULT_DATA_DIR / "corpus"))
|
| 68 |
+
faiss_path = Path(os.environ.get("ASTROPARSE_FAISS_PATH", _DEFAULT_DATA_DIR / "astroparse_fp16.faiss"))
|
| 69 |
+
if not corpus_dir.is_dir() or not faiss_path.is_file():
|
| 70 |
+
raise RuntimeError(f"compact corpus not found ({corpus_dir}, {faiss_path})")
|
| 71 |
+
ds = load_dataset("parquet", data_files=str(corpus_dir / "*.parquet"), split="train")
|
| 72 |
+
index = faiss.read_index(str(faiss_path), faiss.IO_FLAG_MMAP)
|
| 73 |
+
return cls(ds, index)
|
| 74 |
+
|
| 75 |
+
def search(self, query_embedding: np.ndarray, k: int = 1000):
|
| 76 |
+
q = np.asarray(query_embedding, dtype=np.float32).reshape(1, -1)
|
| 77 |
+
distances, indices = self.index.search(q, k)
|
| 78 |
+
sims = 1.0 / (np.asarray(distances[0]) + 1e-10)
|
| 79 |
+
return [int(i) for i in indices[0]], sims
|
| 80 |
+
|
| 81 |
+
def umap_sample(self, n: int = 4000) -> list[list[float]]:
|
| 82 |
+
"""Random sample of (ux, uy) across the whole corpus, for the
|
| 83 |
+
embedding-map background scatter. Cached by the caller — this does
|
| 84 |
+
a fresh random draw each call."""
|
| 85 |
+
total = self.ds.num_rows
|
| 86 |
+
n = min(n, total)
|
| 87 |
+
rng = np.random.default_rng()
|
| 88 |
+
idx = rng.choice(total, size=n, replace=False)
|
| 89 |
+
rows = self.ds[idx.tolist()]
|
| 90 |
+
return [[float(x), float(y)] for x, y in zip(rows["umap_x"], rows["umap_y"])]
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def embed_batch(texts: list[str], api_key: str) -> list[np.ndarray]:
|
| 94 |
+
from openai import OpenAI
|
| 95 |
+
|
| 96 |
+
client = OpenAI(api_key=api_key)
|
| 97 |
+
out: list[np.ndarray] = []
|
| 98 |
+
for i in range(0, len(texts), 100):
|
| 99 |
+
data = client.embeddings.create(input=texts[i : i + 100], model=EMBED_MODEL).data
|
| 100 |
+
out += [np.array(d.embedding, dtype=np.float32) for d in data]
|
| 101 |
+
return out
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def _short_name(authors, year: int) -> str:
|
| 105 |
+
first = authors[0] if isinstance(authors, list) else str(authors).split(";")[0].split(" and ")[0]
|
| 106 |
+
last = first.split(",")[0].strip().split()[-1]
|
| 107 |
+
return f"{last}{str(year)[2:]}"
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def _lit_from_row(row: dict, embed_score: float, kw_score: float, rank: int) -> LitPaper:
|
| 111 |
+
date = row["date"]
|
| 112 |
+
year = date.year if hasattr(date, "year") else int(str(date)[:4])
|
| 113 |
+
authors = ", ".join(row["authors"]) if isinstance(row["authors"], list) else str(row["authors"])
|
| 114 |
+
arxiv_id = str(row.get("arxiv_id", ""))
|
| 115 |
+
arxiv = arxiv_id if _ARXIV_ID.match(arxiv_id) else ""
|
| 116 |
+
return LitPaper(
|
| 117 |
+
id=row["bibcode"], short=_short_name(row["authors"], year), title=row["title"],
|
| 118 |
+
authors=authors, year=year, journal="", bibcode=row["bibcode"], arxiv=arxiv,
|
| 119 |
+
cites=int(row.get("cites", 0) or 0),
|
| 120 |
+
ux=float(row.get("umap_x", 0.0) or 0.0), uy=float(row.get("umap_y", 0.0) or 0.0),
|
| 121 |
+
abstract=row["abstract"],
|
| 122 |
+
scores=Scores(embed=round(float(embed_score), 4), keywords=round(float(kw_score), 4), rank=rank),
|
| 123 |
+
)
|
backend/astroparse_api/schemas.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# backend/astroparse_api/schemas.py
|
| 2 |
+
from pydantic import BaseModel
|
| 3 |
+
|
| 4 |
+
class Scores(BaseModel):
|
| 5 |
+
embed: float
|
| 6 |
+
keywords: float
|
| 7 |
+
rank: int
|
| 8 |
+
|
| 9 |
+
class LitPaper(BaseModel):
|
| 10 |
+
id: str
|
| 11 |
+
short: str
|
| 12 |
+
title: str
|
| 13 |
+
authors: str
|
| 14 |
+
year: int
|
| 15 |
+
journal: str
|
| 16 |
+
bibcode: str
|
| 17 |
+
arxiv: str
|
| 18 |
+
cites: int
|
| 19 |
+
ux: float
|
| 20 |
+
uy: float
|
| 21 |
+
abstract: str
|
| 22 |
+
scores: Scores
|
backend/astroparse_api/search.py
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# backend/astroparse_api/search.py
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import json
|
| 5 |
+
import os
|
| 6 |
+
from datetime import datetime, timezone
|
| 7 |
+
|
| 8 |
+
import httpx
|
| 9 |
+
import numpy as np
|
| 10 |
+
from openai import AsyncOpenAI, OpenAI
|
| 11 |
+
|
| 12 |
+
from .retrieve import Corpus, get_keywords, keyword_weights, _lit_from_row
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def check_moderation(text: str, api_key: str) -> bool:
|
| 16 |
+
client = OpenAI(api_key=api_key)
|
| 17 |
+
result = client.moderations.create(input=text)
|
| 18 |
+
return result.results[0].flagged
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
async def log_query_to_gist(query: str, flagged: bool) -> None:
|
| 22 |
+
token = os.environ.get("GITHUB_TOKEN")
|
| 23 |
+
gist_id = os.environ.get("GIST_ID")
|
| 24 |
+
if not (token and gist_id):
|
| 25 |
+
return
|
| 26 |
+
timestamp = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S")
|
| 27 |
+
line = f"\n{timestamp}: [mod flag: {flagged}] {query}\n"
|
| 28 |
+
headers = {"Authorization": f"token {token}", "Accept": "application/vnd.github.v3+json"}
|
| 29 |
+
try:
|
| 30 |
+
async with httpx.AsyncClient(timeout=5.0) as client:
|
| 31 |
+
resp = await client.get(f"https://api.github.com/gists/{gist_id}", headers=headers)
|
| 32 |
+
existing = resp.json()["files"]["log.txt"]["content"] if resp.status_code == 200 else ""
|
| 33 |
+
await client.patch(
|
| 34 |
+
f"https://api.github.com/gists/{gist_id}", headers=headers,
|
| 35 |
+
json={"description": "Logged Strings", "public": False,
|
| 36 |
+
"files": {"log.txt": {"content": existing + line}}},
|
| 37 |
+
)
|
| 38 |
+
except Exception:
|
| 39 |
+
pass
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def search_corpus(corpus: Corpus, query: str, top_k: int, pool: int, api_key: str):
|
| 43 |
+
client = OpenAI(api_key=api_key)
|
| 44 |
+
emb = np.array(
|
| 45 |
+
client.embeddings.create(input=[query], model="text-embedding-3-small").data[0].embedding,
|
| 46 |
+
dtype=np.float32,
|
| 47 |
+
)
|
| 48 |
+
indices, sims = corpus.search(emb, k=pool)
|
| 49 |
+
rows = corpus.ds[indices]
|
| 50 |
+
kw = keyword_weights(get_keywords(query), rows["keywords"])
|
| 51 |
+
embed_norm = sims / sims.max()
|
| 52 |
+
combined = embed_norm * kw
|
| 53 |
+
order = np.argsort(combined)[::-1][:top_k]
|
| 54 |
+
papers = [
|
| 55 |
+
_lit_from_row({k: rows[k][j] for k in rows}, float(embed_norm[j]), float(kw[j]), rank)
|
| 56 |
+
for rank, j in enumerate(order, start=1)
|
| 57 |
+
]
|
| 58 |
+
return papers, [p.abstract for p in papers]
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
STYLE_PROMPTS = {
|
| 62 |
+
"Concise": "Answer in 1-2 sentences, citing papers inline as [Author+Year]. Be direct.",
|
| 63 |
+
"Multi-paper": "Answer in 2-3 short paragraphs synthesizing across papers, citing inline as [Author+Year].",
|
| 64 |
+
"Deep Research": (
|
| 65 |
+
"Break the question into 2-4 sub-questions. For each, write a short heading and a "
|
| 66 |
+
"grounded paragraph citing [Author+Year]. End with a 'Summary' paragraph noting where "
|
| 67 |
+
"the literature agrees and where it's still debated."
|
| 68 |
+
),
|
| 69 |
+
}
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
async def synthesize_answer(query: str, papers, abstracts: list[str], style: str, api_key: str):
|
| 73 |
+
client = AsyncOpenAI(api_key=api_key)
|
| 74 |
+
context = "\n\n".join(f"[{p.short}] {p.title}\n{a}" for p, a in zip(papers, abstracts))
|
| 75 |
+
stream = await client.chat.completions.create(
|
| 76 |
+
model="gpt-4o-mini", stream=True,
|
| 77 |
+
messages=[
|
| 78 |
+
{"role": "system", "content": "You are an astronomy research assistant. Use only "
|
| 79 |
+
f"the provided abstracts. {STYLE_PROMPTS[style]}"},
|
| 80 |
+
{"role": "user", "content": f"Question: {query}\n\nAbstracts:\n{context}"},
|
| 81 |
+
],
|
| 82 |
+
)
|
| 83 |
+
async for chunk in stream:
|
| 84 |
+
delta = chunk.choices[0].delta.content
|
| 85 |
+
if delta:
|
| 86 |
+
yield delta
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
async def score_consensus(query: str, abstracts: list[str], api_key: str) -> dict:
|
| 90 |
+
client = AsyncOpenAI(api_key=api_key)
|
| 91 |
+
resp = await client.chat.completions.create(
|
| 92 |
+
model="gpt-4o-mini",
|
| 93 |
+
response_format={"type": "json_schema", "json_schema": {"name": "consensus", "schema": {
|
| 94 |
+
"type": "object",
|
| 95 |
+
"properties": {"label": {"type": "string"}, "explanation": {"type": "string"},
|
| 96 |
+
"relevance_score": {"type": "number"}},
|
| 97 |
+
"required": ["label", "explanation", "relevance_score"],
|
| 98 |
+
}}},
|
| 99 |
+
messages=[
|
| 100 |
+
{"role": "system", "content": "Rate consensus between the query and abstracts. "
|
| 101 |
+
"label must be one of: Strong Agreement, Moderate Agreement, Weak Agreement, "
|
| 102 |
+
"No Clear Agreement, Weak Disagreement, Moderate Disagreement, Strong Disagreement."},
|
| 103 |
+
{"role": "user", "content": f"Query: {query}\n\n" + "\n\n".join(abstracts)},
|
| 104 |
+
],
|
| 105 |
+
)
|
| 106 |
+
return json.loads(resp.choices[0].message.content)
|
backend/pyproject.toml
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# backend/pyproject.toml
|
| 2 |
+
[project]
|
| 3 |
+
name = "astroparse-api"
|
| 4 |
+
version = "0.1.0"
|
| 5 |
+
requires-python = ">=3.11"
|
| 6 |
+
dependencies = [
|
| 7 |
+
"fastapi>=0.115",
|
| 8 |
+
"uvicorn[standard]>=0.30",
|
| 9 |
+
"sse-starlette>=2.1",
|
| 10 |
+
"openai>=1.40",
|
| 11 |
+
"httpx>=0.27",
|
| 12 |
+
"faiss-cpu>=1.8",
|
| 13 |
+
"datasets>=2.20",
|
| 14 |
+
"pyarrow>=17.0",
|
| 15 |
+
"numpy>=1.26",
|
| 16 |
+
"spacy>=3.7",
|
| 17 |
+
"huggingface_hub>=0.24",
|
| 18 |
+
"python-dotenv>=1.0",
|
| 19 |
+
]
|
| 20 |
+
|
| 21 |
+
[tool.uv]
|
| 22 |
+
package = false
|
backend/uv.lock
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
frontend/index.html
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!-- frontend/index.html -->
|
| 2 |
+
<!DOCTYPE html>
|
| 3 |
+
<html>
|
| 4 |
+
<head>
|
| 5 |
+
<meta charset="utf-8" />
|
| 6 |
+
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
| 7 |
+
<link rel="preconnect" href="https://fonts.googleapis.com">
|
| 8 |
+
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
| 9 |
+
<link href="https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@400;500;600;700&family=IBM+Plex+Sans:wght@400;500;600&family=IBM+Plex+Mono:wght@400;500&display=swap" rel="stylesheet">
|
| 10 |
+
<title>Pathfinder</title>
|
| 11 |
+
</head>
|
| 12 |
+
<body>
|
| 13 |
+
<div id="root"></div>
|
| 14 |
+
<script type="module" src="/src/main.jsx"></script>
|
| 15 |
+
</body>
|
| 16 |
+
</html>
|
frontend/package.json
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// frontend/package.json
|
| 2 |
+
{
|
| 3 |
+
"name": "pathfinder-frontend",
|
| 4 |
+
"private": true,
|
| 5 |
+
"type": "module",
|
| 6 |
+
"scripts": { "dev": "vite", "build": "vite build" },
|
| 7 |
+
"dependencies": { "react": "^18.3.0", "react-dom": "^18.3.0" },
|
| 8 |
+
"devDependencies": { "@vitejs/plugin-react": "^4.3.0", "vite": "^5.4.0" }
|
| 9 |
+
}
|
frontend/src/App.jsx
ADDED
|
@@ -0,0 +1,334 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// frontend/src/App.jsx
|
| 2 |
+
import React, { useState, useRef, useEffect, useCallback, useMemo } from 'react';
|
| 3 |
+
import { LIGHT, DARK, PIPELINE, EXAMPLES } from './theme.js';
|
| 4 |
+
import { runSearch, fetchUmapSample } from './api.js';
|
| 5 |
+
|
| 6 |
+
function fmtAuthors(a) {
|
| 7 |
+
const list = a.split(', ');
|
| 8 |
+
return list.length > 3 ? `${list.slice(0, 3).join(', ')}, +${list.length - 3}` : a;
|
| 9 |
+
}
|
| 10 |
+
|
| 11 |
+
function linkifyAnswer(text, papers) {
|
| 12 |
+
const byShort = {};
|
| 13 |
+
papers.forEach((p) => { byShort[p.short] = p; });
|
| 14 |
+
return text.replace(/\[([^\]]+)\]/g, (m, short) => {
|
| 15 |
+
const p = byShort[short];
|
| 16 |
+
if (!p) return m;
|
| 17 |
+
return `<a href="https://arxiv.org/abs/${p.arxiv}" target="_blank" style="color:var(--goldtext); border-bottom:1px solid var(--goldborder);">(${short})</a>`;
|
| 18 |
+
});
|
| 19 |
+
}
|
| 20 |
+
|
| 21 |
+
export default function App() {
|
| 22 |
+
const [view, setView] = useState('home');
|
| 23 |
+
const [query, setQuery] = useState('');
|
| 24 |
+
const [theme, setTheme] = useState('light');
|
| 25 |
+
const [topK, setTopK] = useState(10);
|
| 26 |
+
const [answerStyle, setAnswerStyle] = useState('Multi-paper');
|
| 27 |
+
const [sort, setSort] = useState('relevance');
|
| 28 |
+
const [weights, setWeights] = useState({ keywords: true, recency: false, citations: false });
|
| 29 |
+
const [years, setYears] = useState({});
|
| 30 |
+
const [expanded, setExpanded] = useState({});
|
| 31 |
+
const [reasoningOpen, setReasoningOpen] = useState(false);
|
| 32 |
+
const [settingsOpen, setSettingsOpen] = useState(false);
|
| 33 |
+
|
| 34 |
+
const [phaseKeys, setPhaseKeys] = useState([]);
|
| 35 |
+
const [papers, setPapers] = useState([]);
|
| 36 |
+
const [answerHtml, setAnswerHtml] = useState('');
|
| 37 |
+
const [answerRaw, setAnswerRaw] = useState('');
|
| 38 |
+
const [consensus, setConsensus] = useState(null);
|
| 39 |
+
const [blockedMsg, setBlockedMsg] = useState('');
|
| 40 |
+
const [done, setDone] = useState(false);
|
| 41 |
+
const [umapBg, setUmapBg] = useState([]);
|
| 42 |
+
|
| 43 |
+
const mapCanvasRef = useRef(null);
|
| 44 |
+
const esRef = useRef(null);
|
| 45 |
+
|
| 46 |
+
useEffect(() => { fetchUmapSample().then(setUmapBg).catch(() => {}); }, []);
|
| 47 |
+
|
| 48 |
+
const V = theme === 'dark' ? DARK : LIGHT;
|
| 49 |
+
const themeVars = useMemo(
|
| 50 |
+
() => Object.fromEntries(Object.entries(V).map(([k, v]) => [k, v])),
|
| 51 |
+
[V]
|
| 52 |
+
);
|
| 53 |
+
|
| 54 |
+
const scored = useCallback(() => {
|
| 55 |
+
const recencyFactor = (y) => 0.55 + 0.45 * Math.min(1, Math.max(0, (y - 2013) / 10));
|
| 56 |
+
const citeFactor = (c) => 0.55 + 0.45 * Math.min(1, Math.log10(c + 1) / Math.log10(2000));
|
| 57 |
+
return papers.map((p) => {
|
| 58 |
+
let sc = p.scores.embed;
|
| 59 |
+
if (weights.keywords) sc *= (0.45 + 0.55 * p.scores.keywords);
|
| 60 |
+
if (weights.recency) sc *= recencyFactor(p.year);
|
| 61 |
+
if (weights.citations) sc *= citeFactor(p.cites);
|
| 62 |
+
return { ...p, score: sc };
|
| 63 |
+
});
|
| 64 |
+
}, [papers, weights]);
|
| 65 |
+
|
| 66 |
+
const displayed = useCallback(() => {
|
| 67 |
+
const anyYr = Object.values(years).some(Boolean);
|
| 68 |
+
let list = scored().filter((p) => !anyYr || years[p.year]);
|
| 69 |
+
list.sort((a, b) => sort === 'year' ? b.year - a.year : sort === 'cites' ? b.cites - a.cites : b.score - a.score);
|
| 70 |
+
const maxSc = Math.max(...list.map((p) => p.score), 0.0001);
|
| 71 |
+
list = list.slice(0, topK);
|
| 72 |
+
return list.map((p, i) => ({ ...p, rank: i + 1, rel: p.score / maxSc }));
|
| 73 |
+
}, [scored, years, sort, topK]);
|
| 74 |
+
|
| 75 |
+
const drawMap = useCallback(() => {
|
| 76 |
+
const cv = mapCanvasRef.current;
|
| 77 |
+
if (!cv) return;
|
| 78 |
+
const dark = theme === 'dark';
|
| 79 |
+
const ctx = cv.getContext('2d');
|
| 80 |
+
const W = cv.width, H = cv.height, pad = 14;
|
| 81 |
+
const allX = umapBg.map((p) => p[0]).concat(papers.map((p) => p.ux));
|
| 82 |
+
const allY = umapBg.map((p) => p[1]).concat(papers.map((p) => p.uy));
|
| 83 |
+
const minX = Math.min(...allX, 0), maxX = Math.max(...allX, 1);
|
| 84 |
+
const minY = Math.min(...allY, 0), maxY = Math.max(...allY, 1);
|
| 85 |
+
const px = (x) => pad + ((x - minX) / (maxX - minX || 1)) * (W - 2 * pad);
|
| 86 |
+
const py = (y) => pad + ((y - minY) / (maxY - minY || 1)) * (H - 2 * pad);
|
| 87 |
+
|
| 88 |
+
ctx.clearRect(0, 0, W, H);
|
| 89 |
+
ctx.fillStyle = dark ? 'rgba(233,236,247,0.055)' : 'rgba(20,22,30,0.09)';
|
| 90 |
+
umapBg.forEach(([x, y]) => { ctx.beginPath(); ctx.arc(px(x), py(y), 1.15, 0, 6.29); ctx.fill(); });
|
| 91 |
+
|
| 92 |
+
displayed().forEach((p) => {
|
| 93 |
+
const x = px(p.ux), y = py(p.uy);
|
| 94 |
+
ctx.beginPath(); ctx.arc(x, y, 8, 0, 6.29);
|
| 95 |
+
ctx.fillStyle = dark ? 'rgba(255,255,255,0.9)' : 'rgba(12,13,17,0.10)';
|
| 96 |
+
ctx.fill();
|
| 97 |
+
ctx.shadowColor = dark ? 'rgba(244,183,64,0.9)' : 'rgba(227,154,30,0.75)';
|
| 98 |
+
ctx.shadowBlur = 11;
|
| 99 |
+
ctx.beginPath(); ctx.arc(x, y, 3.6, 0, 6.29);
|
| 100 |
+
ctx.fillStyle = dark ? '#F4B740' : '#E39A1E';
|
| 101 |
+
ctx.fill(); ctx.shadowBlur = 0;
|
| 102 |
+
});
|
| 103 |
+
}, [umapBg, papers, displayed, theme]);
|
| 104 |
+
|
| 105 |
+
useEffect(() => { drawMap(); }, [drawMap]);
|
| 106 |
+
|
| 107 |
+
const onSubmit = async () => {
|
| 108 |
+
const q = query.trim() || EXAMPLES[0];
|
| 109 |
+
setQuery(q); setView('run'); setPhaseKeys([]); setPapers([]);
|
| 110 |
+
setAnswerHtml(''); setAnswerRaw(''); setConsensus(null); setBlockedMsg(''); setDone(false);
|
| 111 |
+
|
| 112 |
+
esRef.current = await runSearch(q, topK, answerStyle, {
|
| 113 |
+
onStage: (d) => { if (d.status === 'done') setPhaseKeys((prev) => [...prev, d.name]); },
|
| 114 |
+
onPapers: (ps) => setPapers(ps),
|
| 115 |
+
onAnswerToken: (t) => setAnswerRaw((prev) => prev + t),
|
| 116 |
+
onConsensus: (c) => setConsensus(c),
|
| 117 |
+
onBlocked: (d) => { setBlockedMsg(d.message); setView('home'); },
|
| 118 |
+
onDone: () => setDone(true),
|
| 119 |
+
onError: (d) => { setBlockedMsg(d.message || 'Something went wrong.'); setDone(true); },
|
| 120 |
+
});
|
| 121 |
+
};
|
| 122 |
+
|
| 123 |
+
useEffect(() => {
|
| 124 |
+
return () => esRef.current?.close();
|
| 125 |
+
}, []);
|
| 126 |
+
|
| 127 |
+
const phase = PIPELINE.findIndex((s) => !phaseKeys.includes(s.k));
|
| 128 |
+
const running = view === 'run' && !done && phase !== -1;
|
| 129 |
+
const showResults = view === 'run' && (done || papers.length > 0);
|
| 130 |
+
const shownPapers = displayed();
|
| 131 |
+
|
| 132 |
+
const yearCounts = {};
|
| 133 |
+
scored().forEach((p) => { yearCounts[p.year] = (yearCounts[p.year] || 0) + 1; });
|
| 134 |
+
|
| 135 |
+
return (
|
| 136 |
+
<div style={{ display: 'flex', minHeight: '100vh', color: 'var(--text)', background: 'var(--bg)', fontFamily: "'IBM Plex Sans', sans-serif", ...themeVars }}>
|
| 137 |
+
<div style={{ width: 66, flex: '0 0 66px', borderRight: '1px solid var(--line)', display: 'flex', flexDirection: 'column', alignItems: 'center', padding: '18px 0', gap: 20 }}>
|
| 138 |
+
<button onClick={() => setView('home')} title="Pathfinder home" style={{ width: 38, height: 38, background: 'none', border: 'none', cursor: 'pointer' }}>
|
| 139 |
+
<svg viewBox="0 0 24 24" width="26" height="26"><path d="M12 1 L13.7 9.6 L22.4 12 L13.7 14.4 L12 23 L10.3 14.4 L1.6 12 L10.3 9.6 Z" style={{ fill: 'var(--gold)' }} /></svg>
|
| 140 |
+
</button>
|
| 141 |
+
</div>
|
| 142 |
+
|
| 143 |
+
<div style={{ flex: 1, minWidth: 0, display: 'flex', flexDirection: 'column' }}>
|
| 144 |
+
<div style={{ height: 60, borderBottom: '1px solid var(--line)', display: 'flex', alignItems: 'center', gap: 14, padding: '0 26px' }}>
|
| 145 |
+
<span style={{ fontFamily: "'Space Grotesk', sans-serif", fontWeight: 600, fontSize: 18, color: 'var(--head)' }}>Pathfinder</span>
|
| 146 |
+
<div style={{ marginLeft: 'auto' }}>
|
| 147 |
+
<button onClick={() => setTheme((t) => t === 'light' ? 'dark' : 'light')} style={{ fontSize: 13 }}>
|
| 148 |
+
{theme === 'light' ? 'Dark mode' : 'Light mode'}
|
| 149 |
+
</button>
|
| 150 |
+
</div>
|
| 151 |
+
</div>
|
| 152 |
+
|
| 153 |
+
{view === 'home' && (
|
| 154 |
+
<div style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', padding: '0 26px' }}>
|
| 155 |
+
<div style={{ width: '100%', maxWidth: 780, marginTop: '11vh' }}>
|
| 156 |
+
<h1 style={{ fontFamily: "'Space Grotesk', sans-serif", fontWeight: 700, fontSize: 48, lineHeight: 1.05, letterSpacing: '-1.6px', color: 'var(--head)' }}>
|
| 157 |
+
A beacon through the<br />astronomy literature.
|
| 158 |
+
</h1>
|
| 159 |
+
<p style={{ fontSize: 17, color: 'var(--muted)', maxWidth: 600 }}>
|
| 160 |
+
Ask a research question in plain language. Pathfinder embeds it, searches the corpus, weighs the results, and answers with the papers that ground it.
|
| 161 |
+
</p>
|
| 162 |
+
|
| 163 |
+
{blockedMsg && (
|
| 164 |
+
<div style={{ border: '1px solid var(--goldborder)', background: 'var(--goldsoft)', color: 'var(--goldtext)', borderRadius: 10, padding: '10px 14px', marginBottom: 16, fontSize: 14 }}>
|
| 165 |
+
{blockedMsg}
|
| 166 |
+
</div>
|
| 167 |
+
)}
|
| 168 |
+
|
| 169 |
+
<div style={{ border: '1px solid var(--line2)', borderRadius: 16, background: 'var(--surface)', overflow: 'hidden' }}>
|
| 170 |
+
<textarea
|
| 171 |
+
rows={2}
|
| 172 |
+
value={query}
|
| 173 |
+
onChange={(e) => setQuery(e.target.value)}
|
| 174 |
+
onKeyDown={(e) => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); onSubmit(); } }}
|
| 175 |
+
placeholder="How does stellar feedback regulate star formation in dwarf galaxies?"
|
| 176 |
+
style={{ width: '100%', border: 'none', outline: 'none', resize: 'none', background: 'transparent', color: 'var(--text)', fontSize: 17, padding: '20px 20px 8px' }}
|
| 177 |
+
/>
|
| 178 |
+
<div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '10px 12px 12px', borderTop: '1px solid var(--linesoft)' }}>
|
| 179 |
+
<span style={{ fontSize: '12.5px', color: 'var(--muted2)' }}>top-k {topK}</span>
|
| 180 |
+
<button onClick={() => setTopK((k) => Math.max(3, k - 1))}>−</button>
|
| 181 |
+
<button onClick={() => setTopK((k) => Math.min(20, k + 1))}>+</button>
|
| 182 |
+
<select value={answerStyle} onChange={(e) => setAnswerStyle(e.target.value)} style={{ marginLeft: 8 }}>
|
| 183 |
+
<option>Concise</option>
|
| 184 |
+
<option>Multi-paper</option>
|
| 185 |
+
<option>Deep Research</option>
|
| 186 |
+
</select>
|
| 187 |
+
<button onClick={onSubmit} style={{ marginLeft: 'auto', background: 'var(--gold)', color: 'var(--ongold)', border: 'none', padding: '10px 18px', borderRadius: 10, fontWeight: 600, cursor: 'pointer' }}>
|
| 188 |
+
Run Pathfinder →
|
| 189 |
+
</button>
|
| 190 |
+
</div>
|
| 191 |
+
</div>
|
| 192 |
+
|
| 193 |
+
<div style={{ display: 'flex', flexWrap: 'wrap', gap: 9, marginTop: 22 }}>
|
| 194 |
+
{EXAMPLES.map((q) => (
|
| 195 |
+
<button key={q} onClick={() => { setQuery(q); }} style={{ textAlign: 'left', border: '1px solid var(--line)', background: 'var(--example)', color: 'var(--abstract)', padding: '9px 13px', borderRadius: 10, fontSize: 13, cursor: 'pointer' }}>
|
| 196 |
+
{q}
|
| 197 |
+
</button>
|
| 198 |
+
))}
|
| 199 |
+
</div>
|
| 200 |
+
</div>
|
| 201 |
+
</div>
|
| 202 |
+
)}
|
| 203 |
+
|
| 204 |
+
{view === 'run' && running && (
|
| 205 |
+
<div style={{ maxWidth: 720, margin: '0 auto', padding: '48px 26px' }}>
|
| 206 |
+
<div style={{ fontSize: 18, color: 'var(--head)', marginBottom: 26 }}>{query}</div>
|
| 207 |
+
<div style={{ border: '1px solid var(--line)', borderRadius: 16, background: 'var(--card)', padding: '8px 6px' }}>
|
| 208 |
+
{PIPELINE.map((s, i) => (
|
| 209 |
+
<div key={s.k} style={{ display: 'flex', alignItems: 'center', gap: 13, padding: '12px 16px' }}>
|
| 210 |
+
<span style={{ width: 20, textAlign: 'center' }}>
|
| 211 |
+
{phaseKeys.includes(s.k) ? '✓' : i === phase ? '…' : '○'}
|
| 212 |
+
</span>
|
| 213 |
+
<span style={{ fontSize: '14.5px', color: i > phase ? 'var(--faint)' : 'var(--text)' }}>{s.label}</span>
|
| 214 |
+
</div>
|
| 215 |
+
))}
|
| 216 |
+
</div>
|
| 217 |
+
</div>
|
| 218 |
+
)}
|
| 219 |
+
|
| 220 |
+
{showResults && (
|
| 221 |
+
<div style={{ display: 'flex', gap: 28, maxWidth: 1320, margin: '0 auto', padding: '26px 26px 80px' }}>
|
| 222 |
+
<div style={{ flex: 1, minWidth: 0 }}>
|
| 223 |
+
<div style={{ fontFamily: "'Space Grotesk', sans-serif", fontSize: 21, color: 'var(--head)', marginBottom: 18 }}>{query}</div>
|
| 224 |
+
|
| 225 |
+
<button onClick={() => setReasoningOpen((o) => !o)} style={{ marginBottom: 22, fontSize: '12.5px' }}>
|
| 226 |
+
Retrieved {shownPapers.length} papers · {PIPELINE.length} steps {reasoningOpen ? '▲' : '▼'}
|
| 227 |
+
</button>
|
| 228 |
+
|
| 229 |
+
<div style={{ border: '1px solid var(--answercardborder)', borderRadius: 16, background: 'var(--answercardbg)', padding: '24px 26px', marginBottom: 16 }}>
|
| 230 |
+
<div style={{ fontFamily: "'Space Grotesk', sans-serif", fontWeight: 600, fontSize: 15, color: 'var(--head)', marginBottom: 14 }}>
|
| 231 |
+
Synthesized answer <span style={{ fontSize: 11, color: 'var(--muted2)', border: '1px solid var(--line2)', borderRadius: 999, padding: '2px 8px', marginLeft: 6 }}>{answerStyle}</span>
|
| 232 |
+
</div>
|
| 233 |
+
<div
|
| 234 |
+
style={{ fontSize: '15.5px', lineHeight: 1.72, color: 'var(--answer)' }}
|
| 235 |
+
dangerouslySetInnerHTML={{ __html: linkifyAnswer(answerRaw, papers) }}
|
| 236 |
+
/>
|
| 237 |
+
</div>
|
| 238 |
+
|
| 239 |
+
{consensus && (
|
| 240 |
+
<div style={{ border: '1px solid var(--line)', borderRadius: 14, background: 'var(--card)', padding: '18px 20px', marginBottom: 14 }}>
|
| 241 |
+
<div style={{ display: 'flex', gap: 10, marginBottom: 8 }}>
|
| 242 |
+
<span style={{ fontSize: 12, color: 'var(--muted2)' }}>LITERATURE CONSENSUS</span>
|
| 243 |
+
<span style={{ fontSize: '12.5px', fontWeight: 600, color: 'var(--green)', background: 'var(--greensoft)', padding: '3px 10px', borderRadius: 999 }}>{consensus.label}</span>
|
| 244 |
+
</div>
|
| 245 |
+
<div style={{ fontSize: '13.5px', color: 'var(--muted)' }}>{consensus.explanation}</div>
|
| 246 |
+
</div>
|
| 247 |
+
)}
|
| 248 |
+
|
| 249 |
+
<div style={{ display: 'flex', alignItems: 'baseline', gap: 10, margin: '26px 0 14px' }}>
|
| 250 |
+
<h2 style={{ fontFamily: "'Space Grotesk', sans-serif", fontSize: 16, color: 'var(--head)' }}>Retrieved papers</h2>
|
| 251 |
+
<span style={{ fontSize: '12.5px', color: 'var(--muted2)' }}>showing {shownPapers.length}</span>
|
| 252 |
+
</div>
|
| 253 |
+
|
| 254 |
+
{shownPapers.map((p) => {
|
| 255 |
+
const exp = !!expanded[p.bibcode];
|
| 256 |
+
const highly = p.rel > 0.94;
|
| 257 |
+
return (
|
| 258 |
+
<div key={p.bibcode} style={{ border: '1px solid var(--line)', borderRadius: 14, background: 'var(--card)', padding: '18px 20px', marginBottom: 12 }}>
|
| 259 |
+
<div style={{ display: 'flex', gap: 14 }}>
|
| 260 |
+
<div style={{ fontSize: 12, color: 'var(--faint2)', minWidth: 20 }}>{String(p.rank).padStart(2, '0')}</div>
|
| 261 |
+
<div style={{ flex: 1, minWidth: 0 }}>
|
| 262 |
+
<div style={{ display: 'flex', gap: 10, marginBottom: 5 }}>
|
| 263 |
+
<span style={{ fontSize: '11.5px', color: 'var(--goldtext)', background: 'var(--goldchip)', padding: '2px 8px', borderRadius: 6 }}>{p.short}</span>
|
| 264 |
+
<span style={{ fontSize: '11.5px', fontWeight: 600, color: highly ? 'var(--green)' : 'var(--cyan)', background: highly ? 'var(--greensoft)' : 'var(--relevantbg)', padding: '2px 9px', borderRadius: 999 }}>
|
| 265 |
+
{highly ? 'Highly relevant' : p.rel > 0.85 ? 'Relevant' : 'Related'}
|
| 266 |
+
</span>
|
| 267 |
+
</div>
|
| 268 |
+
<a href={`https://arxiv.org/abs/${p.arxiv}`} target="_blank" rel="noreferrer" style={{ fontFamily: "'Space Grotesk', sans-serif", fontSize: '16.5px', color: 'var(--head)', display: 'block', marginBottom: 6 }}>
|
| 269 |
+
{p.title}
|
| 270 |
+
</a>
|
| 271 |
+
<div style={{ fontSize: 13, color: 'var(--muted)' }}>{fmtAuthors(p.authors)}</div>
|
| 272 |
+
<div style={{ fontSize: '12.5px', color: 'var(--faint)', marginBottom: 12 }}>
|
| 273 |
+
{p.year} · {p.cites.toLocaleString()} citations
|
| 274 |
+
</div>
|
| 275 |
+
{exp && (
|
| 276 |
+
<div style={{ fontSize: '13.5px', lineHeight: 1.62, color: 'var(--abstract)', borderLeft: '2px solid var(--goldborder)', paddingLeft: 14, marginBottom: 14 }}>
|
| 277 |
+
{p.abstract}
|
| 278 |
+
</div>
|
| 279 |
+
)}
|
| 280 |
+
<div style={{ display: 'flex', gap: 18 }}>
|
| 281 |
+
<button onClick={() => setExpanded((e) => ({ ...e, [p.bibcode]: !exp }))} style={{ fontSize: 12 }}>
|
| 282 |
+
{exp ? 'Hide abstract' : 'Show abstract'}
|
| 283 |
+
</button>
|
| 284 |
+
<a href={`https://ui.adsabs.harvard.edu/abs/${p.bibcode}`} target="_blank" rel="noreferrer" style={{ fontSize: 12, color: 'var(--cyan)' }}>ADS ↗</a>
|
| 285 |
+
<a href={`https://arxiv.org/abs/${p.arxiv}`} target="_blank" rel="noreferrer" style={{ fontSize: 12, color: 'var(--cyan)' }}>arXiv ↗</a>
|
| 286 |
+
</div>
|
| 287 |
+
</div>
|
| 288 |
+
</div>
|
| 289 |
+
</div>
|
| 290 |
+
);
|
| 291 |
+
})}
|
| 292 |
+
</div>
|
| 293 |
+
|
| 294 |
+
<div style={{ width: 284, flexShrink: 0 }}>
|
| 295 |
+
<div style={{ border: '1px solid var(--line)', borderRadius: 14, background: 'var(--card2)', padding: 14, marginBottom: 16 }}>
|
| 296 |
+
<div style={{ fontSize: 13, fontWeight: 600, color: 'var(--head)', marginBottom: 10 }}>Embedding map</div>
|
| 297 |
+
<canvas ref={mapCanvasRef} width={512} height={440} style={{ width: '100%', height: 'auto', borderRadius: 8, background: 'var(--mapbg)' }} />
|
| 298 |
+
</div>
|
| 299 |
+
|
| 300 |
+
<div style={{ border: '1px solid var(--line)', borderRadius: 14, background: 'var(--card2)', padding: '15px 16px', marginBottom: 16 }}>
|
| 301 |
+
<div style={{ fontSize: 11, color: 'var(--muted2)', marginBottom: 11 }}>SORT BY</div>
|
| 302 |
+
{['relevance', 'year', 'cites'].map((k) => (
|
| 303 |
+
<label key={k} style={{ display: 'flex', gap: 10, padding: '6px 0', cursor: 'pointer', fontSize: '13.5px', color: sort === k ? 'var(--head)' : 'var(--muted)' }}>
|
| 304 |
+
<input type="radio" checked={sort === k} onChange={() => setSort(k)} /> {k}
|
| 305 |
+
</label>
|
| 306 |
+
))}
|
| 307 |
+
</div>
|
| 308 |
+
|
| 309 |
+
<div style={{ border: '1px solid var(--line)', borderRadius: 14, background: 'var(--card2)', padding: '15px 16px', marginBottom: 16 }}>
|
| 310 |
+
<div style={{ fontSize: 11, color: 'var(--muted2)', marginBottom: 6 }}>WEIGHT RANKING BY</div>
|
| 311 |
+
{[['keywords', 'Keywords'], ['recency', 'Recency'], ['citations', 'Citations']].map(([k, label]) => (
|
| 312 |
+
<label key={k} style={{ display: 'flex', justifyContent: 'space-between', padding: '7px 0', cursor: 'pointer', fontSize: '13.5px' }}>
|
| 313 |
+
{label}
|
| 314 |
+
<input type="checkbox" checked={weights[k]} onChange={() => setWeights((w) => ({ ...w, [k]: !w[k] }))} />
|
| 315 |
+
</label>
|
| 316 |
+
))}
|
| 317 |
+
</div>
|
| 318 |
+
|
| 319 |
+
<div style={{ border: '1px solid var(--line)', borderRadius: 14, background: 'var(--card2)', padding: '15px 16px' }}>
|
| 320 |
+
<div style={{ fontSize: 11, color: 'var(--muted2)', marginBottom: 11 }}>YEAR</div>
|
| 321 |
+
{Object.keys(yearCounts).sort((a, b) => b - a).map((y) => (
|
| 322 |
+
<label key={y} style={{ display: 'flex', gap: 10, padding: '5px 0', cursor: 'pointer', fontSize: '13.5px' }}>
|
| 323 |
+
<input type="checkbox" checked={!!years[y]} onChange={() => setYears((yr) => ({ ...yr, [y]: !yr[y] }))} />
|
| 324 |
+
{y} <span style={{ marginLeft: 'auto', color: 'var(--faint2)' }}>{yearCounts[y]}</span>
|
| 325 |
+
</label>
|
| 326 |
+
))}
|
| 327 |
+
</div>
|
| 328 |
+
</div>
|
| 329 |
+
</div>
|
| 330 |
+
)}
|
| 331 |
+
</div>
|
| 332 |
+
</div>
|
| 333 |
+
);
|
| 334 |
+
}
|
frontend/src/api.js
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// frontend/src/api.js
|
| 2 |
+
export async function runSearch(query, topK, answerStyle, handlers) {
|
| 3 |
+
const res = await fetch('/api/search', {
|
| 4 |
+
method: 'POST',
|
| 5 |
+
headers: { 'Content-Type': 'application/json' },
|
| 6 |
+
body: JSON.stringify({ query, top_k: topK, answer_style: answerStyle }),
|
| 7 |
+
});
|
| 8 |
+
const { jobId } = await res.json();
|
| 9 |
+
const es = new EventSource(`/api/jobs/${jobId}/events`);
|
| 10 |
+
|
| 11 |
+
es.addEventListener('stage', (e) => handlers.onStage?.(JSON.parse(e.data)));
|
| 12 |
+
es.addEventListener('papers', (e) => handlers.onPapers?.(JSON.parse(e.data).papers));
|
| 13 |
+
es.addEventListener('answer_token', (e) => handlers.onAnswerToken?.(JSON.parse(e.data).text));
|
| 14 |
+
es.addEventListener('consensus', (e) => handlers.onConsensus?.(JSON.parse(e.data)));
|
| 15 |
+
es.addEventListener('blocked', (e) => { handlers.onBlocked?.(JSON.parse(e.data)); es.close(); });
|
| 16 |
+
es.addEventListener('result', () => { handlers.onDone?.(); es.close(); });
|
| 17 |
+
es.addEventListener('error', (e) => {
|
| 18 |
+
try { handlers.onError?.(JSON.parse(e.data)); } catch { handlers.onError?.({ message: 'connection lost' }); }
|
| 19 |
+
es.close();
|
| 20 |
+
});
|
| 21 |
+
return es;
|
| 22 |
+
}
|
| 23 |
+
|
| 24 |
+
export async function fetchUmapSample() {
|
| 25 |
+
const res = await fetch('/api/umap-sample');
|
| 26 |
+
return (await res.json()).points;
|
| 27 |
+
}
|
frontend/src/main.jsx
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// frontend/src/main.jsx
|
| 2 |
+
import React from 'react';
|
| 3 |
+
import { createRoot } from 'react-dom/client';
|
| 4 |
+
import App from './App.jsx';
|
| 5 |
+
|
| 6 |
+
createRoot(document.getElementById('root')).render(<App />);
|
frontend/src/theme.js
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// frontend/src/theme.js — ported verbatim from the design doc
|
| 2 |
+
export const LIGHT = {
|
| 3 |
+
'--bg': '#FBFBF8', '--grad1': 'rgba(227,154,30,0.07)', '--grad2': 'rgba(12,122,134,0.05)',
|
| 4 |
+
'--text': '#1C1E25', '--head': '#0B0C0F', '--muted': '#565A68', '--muted2': '#565A68',
|
| 5 |
+
'--faint': '#868B99', '--faint2': '#A6AAB5', '--ver': '#B4B8C2',
|
| 6 |
+
'--abstract': '#3A3F4C', '--answer': '#26292F',
|
| 7 |
+
'--line': '#EAEAE3', '--line2': '#E0DFD6', '--line3': '#D8D8CE', '--linesoft': '#EFEEE8',
|
| 8 |
+
'--card': '#FFFFFF', '--card2': '#FFFFFF', '--surface': '#FFFFFF', '--popover': '#FFFFFF',
|
| 9 |
+
'--inset': '#F4F3EE', '--avatar': '#EFEEE8', '--track': '#E4E3DB',
|
| 10 |
+
'--example': '#FFFFFF', '--reasonbg': '#F4F3EE',
|
| 11 |
+
'--gold': '#E39A1E', '--goldhover': '#f2ab34', '--goldtext': '#A9640A', '--goldsoft': 'rgba(227,154,30,0.14)',
|
| 12 |
+
'--goldchip': 'rgba(227,154,30,0.12)', '--goldborder': 'rgba(227,154,30,0.5)', '--goldbtnborder': 'rgba(227,154,30,0.6)',
|
| 13 |
+
'--goldfaint': 'rgba(227,154,30,0.3)', '--goldglow': 'rgba(227,154,30,0.6)', '--ongold': '#241800',
|
| 14 |
+
'--answercardborder': 'rgba(227,154,30,0.35)', '--answercardbg': 'linear-gradient(180deg, rgba(227,154,30,0.06), rgba(227,154,30,0.015))',
|
| 15 |
+
'--cyan': '#0C7A86', '--cyanhover': '#0A5C66', '--green': '#1C8A4E', '--greensoft': 'rgba(28,138,78,0.1)',
|
| 16 |
+
'--greenring': 'rgba(28,138,78,0.4)', '--relevantbg': 'rgba(12,122,134,0.1)', '--relatedbg': 'rgba(0,0,0,0.05)',
|
| 17 |
+
'--ringoff': '#CFCEC5', '--knoboff': '#B0B0A8', '--topbar': 'rgba(251,251,248,0.86)',
|
| 18 |
+
'--slash': '#C4C3BA', '--mapbg': '#FCFCFA', '--corpusdot': '#C7C6BD',
|
| 19 |
+
};
|
| 20 |
+
|
| 21 |
+
export const DARK = {
|
| 22 |
+
'--bg': '#0A0D17', '--grad1': 'rgba(244,183,64,0.06)', '--grad2': 'rgba(111,214,230,0.05)',
|
| 23 |
+
'--text': '#E9ECF7', '--head': '#F3F5FC', '--muted': '#9aa1bd', '--muted2': '#8991ae',
|
| 24 |
+
'--faint': '#626a88', '--faint2': '#4f587a', '--ver': '#3f4763',
|
| 25 |
+
'--abstract': '#b6bcd4', '--answer': '#dfe3f2',
|
| 26 |
+
'--line': 'rgba(233,236,247,0.08)', '--line2': 'rgba(233,236,247,0.14)', '--line3': 'rgba(233,236,247,0.16)', '--linesoft': 'rgba(233,236,247,0.06)',
|
| 27 |
+
'--card': '#0f1423', '--card2': '#0d1220', '--surface': '#101524', '--popover': '#12162a',
|
| 28 |
+
'--inset': '#0c1120', '--avatar': '#1a2135', '--track': '#1a2135',
|
| 29 |
+
'--example': '#0e1320', '--reasonbg': '#0d1220',
|
| 30 |
+
'--gold': '#F4B740', '--goldhover': '#ffca5e', '--goldtext': '#F4B740', '--goldsoft': 'rgba(244,183,64,0.16)',
|
| 31 |
+
'--goldchip': 'rgba(244,183,64,0.1)', '--goldborder': 'rgba(244,183,64,0.5)', '--goldbtnborder': 'rgba(244,183,64,0.55)',
|
| 32 |
+
'--goldfaint': 'rgba(244,183,64,0.25)', '--goldglow': '#F4B740', '--ongold': '#161200',
|
| 33 |
+
'--answercardborder': 'rgba(244,183,64,0.22)', '--answercardbg': 'linear-gradient(180deg, rgba(244,183,64,0.05), rgba(244,183,64,0.01))',
|
| 34 |
+
'--cyan': '#6fd6e6', '--cyanhover': '#9ee6f2', '--green': '#63cf87', '--greensoft': 'rgba(99,207,135,0.12)',
|
| 35 |
+
'--greenring': 'rgba(99,207,135,0.35)', '--relevantbg': 'rgba(111,214,230,0.1)', '--relatedbg': 'rgba(233,236,247,0.06)',
|
| 36 |
+
'--ringoff': 'rgba(233,236,247,0.2)', '--knoboff': '#5b6486', '--topbar': 'rgba(10,13,23,0.82)',
|
| 37 |
+
'--slash': '#3a4260', '--mapbg': '#0A0D17', '--corpusdot': '#39415f',
|
| 38 |
+
};
|
| 39 |
+
|
| 40 |
+
export const PIPELINE = [
|
| 41 |
+
{ k: 'intent', label: 'Analyzing query intent' },
|
| 42 |
+
{ k: 'search', label: 'Searching the corpus' },
|
| 43 |
+
{ k: 'consensus', label: 'Evaluating consensus' },
|
| 44 |
+
{ k: 'compose', label: 'Composing grounded answer' },
|
| 45 |
+
];
|
| 46 |
+
|
| 47 |
+
export const EXAMPLES = [
|
| 48 |
+
'How does stellar feedback regulate star formation in dwarf galaxies?',
|
| 49 |
+
'Evidence for and against primordial non-Gaussianity from galaxy surveys',
|
| 50 |
+
'Can strong-lensing time delays resolve the Hubble tension?',
|
| 51 |
+
'JWST detections of quenched galaxies at z > 4',
|
| 52 |
+
];
|
frontend/vite.config.js
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// frontend/vite.config.js
|
| 2 |
+
import { defineConfig } from 'vite';
|
| 3 |
+
import react from '@vitejs/plugin-react';
|
| 4 |
+
|
| 5 |
+
export default defineConfig({
|
| 6 |
+
plugins: [react()],
|
| 7 |
+
server: { proxy: { '/api': 'http://localhost:7860' } },
|
| 8 |
+
});
|