samwjya Claude Opus 5.5 commited on
Commit ·
f3fed0c
1
Parent(s): d18fbe7
Switch web app from Streamlit to Gradio for Hugging Face Spaces
Browse filesDocker Spaces aren't available on the free tier, so the UI is rewritten in
Gradio (same features: coverage, gaps, year filter, summaries, caching, rate
limits). Requirements use CPU-only PyTorch; README targets a Gradio Space.
Dockerfile and .dockerignore are removed.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- .dockerignore +0 -21
- Dockerfile +0 -28
- README.md +24 -20
- app.py +369 -267
- requirements.txt +5 -3
.dockerignore
DELETED
|
@@ -1,21 +0,0 @@
|
|
| 1 |
-
# Secrets: keys are passed at runtime (Spaces secrets / --env-file), never baked in.
|
| 2 |
-
.env
|
| 3 |
-
.env.*
|
| 4 |
-
|
| 5 |
-
# Local environments and caches
|
| 6 |
-
.venv/
|
| 7 |
-
venv/
|
| 8 |
-
__pycache__/
|
| 9 |
-
*.pyc
|
| 10 |
-
.pytest_cache/
|
| 11 |
-
|
| 12 |
-
# Repo and editor metadata
|
| 13 |
-
.git/
|
| 14 |
-
.gitignore
|
| 15 |
-
.claude/
|
| 16 |
-
CLAUDE.md
|
| 17 |
-
.vscode/
|
| 18 |
-
.idea/
|
| 19 |
-
|
| 20 |
-
# Evaluation data (large, only used by evaluate.py offline)
|
| 21 |
-
eval/dataset.json
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Dockerfile
DELETED
|
@@ -1,28 +0,0 @@
|
|
| 1 |
-
# PaperRank on Hugging Face Spaces (Docker SDK, free CPU tier).
|
| 2 |
-
FROM python:3.13-slim
|
| 3 |
-
|
| 4 |
-
# Spaces runs the container as UID 1000, so build and run as that user too;
|
| 5 |
-
# otherwise the model cache and pip installs would be owned by root.
|
| 6 |
-
RUN useradd -m -u 1000 user
|
| 7 |
-
USER user
|
| 8 |
-
ENV HOME=/home/user \
|
| 9 |
-
PATH=/home/user/.local/bin:$PATH \
|
| 10 |
-
HF_HOME=/home/user/.cache/huggingface \
|
| 11 |
-
PYTHONUNBUFFERED=1 \
|
| 12 |
-
STREAMLIT_BROWSER_GATHER_USAGE_STATS=false
|
| 13 |
-
WORKDIR $HOME/app
|
| 14 |
-
|
| 15 |
-
# CPU-only torch first (~200 MB instead of ~2 GB of unused CUDA libraries);
|
| 16 |
-
# requirements.txt then sees torch==2.12.1 as already installed.
|
| 17 |
-
COPY --chown=user requirements.txt .
|
| 18 |
-
RUN pip install --no-cache-dir --user torch==2.12.1 --index-url https://download.pytorch.org/whl/cpu \
|
| 19 |
-
&& pip install --no-cache-dir --user -r requirements.txt
|
| 20 |
-
|
| 21 |
-
# Bake the default reranker into the image so the first search after a cold
|
| 22 |
-
# start doesn't wait on a download. The other two models download on first use.
|
| 23 |
-
RUN python -c "from sentence_transformers import CrossEncoder; CrossEncoder('cross-encoder/ms-marco-MiniLM-L-6-v2')"
|
| 24 |
-
|
| 25 |
-
COPY --chown=user . .
|
| 26 |
-
|
| 27 |
-
EXPOSE 7860
|
| 28 |
-
CMD ["streamlit", "run", "app.py", "--server.port=7860", "--server.address=0.0.0.0", "--server.headless=true"]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
README.md
CHANGED
|
@@ -3,8 +3,10 @@ title: PaperRank
|
|
| 3 |
emoji: 📄
|
| 4 |
colorFrom: blue
|
| 5 |
colorTo: indigo
|
| 6 |
-
sdk:
|
| 7 |
-
|
|
|
|
|
|
|
| 8 |
pinned: false
|
| 9 |
short_description: Find papers for a research question and spot gaps
|
| 10 |
---
|
|
@@ -54,16 +56,18 @@ not conclusions.
|
|
| 54 |
|
| 55 |
## What's in here
|
| 56 |
|
|
|
|
|
|
|
|
|
|
| 57 |
| File | What it does |
|
| 58 |
|---|---|
|
| 59 |
-
| `app.py` | The
|
| 60 |
| `retriever.py` | Talks to OpenAlex. Runs searches (several at once), rebuilds abstracts from OpenAlex's odd inverted-index format, and counts matching papers for the gap check. |
|
| 61 |
| `reranker.py` | Loads a CrossEncoder and reranks papers. Every model's scores get squashed to 0–1 so they're comparable. |
|
| 62 |
| `analyzer.py` | All the LLM parts: breaking down the question, checking coverage, finding gaps, writing summaries. |
|
| 63 |
| `main.py` | The same pipeline from the command line, if you don't want to open a browser. |
|
| 64 |
| `evaluate.py` | Offline evaluation (NDCG@10, MRR) comparing plain OpenAlex ranking against multi-query search and reranking. Questions live in `eval/queries.txt`. |
|
| 65 |
-
| `
|
| 66 |
-
| `requirements.txt` | Python dependencies, pinned to versions I've tested. |
|
| 67 |
|
| 68 |
## Reranker models
|
| 69 |
|
|
@@ -96,13 +100,17 @@ GROQ_API_KEY=your_groq_key
|
|
| 96 |
OPEN_ALEX_API=your_openalex_key # optional, but gives you your own daily budget
|
| 97 |
```
|
| 98 |
|
| 99 |
-
Then start the app:
|
| 100 |
|
| 101 |
```bash
|
| 102 |
-
|
| 103 |
```
|
| 104 |
|
| 105 |
-
It opens at http://
|
|
|
|
|
|
|
|
|
|
|
|
|
| 106 |
|
| 107 |
```bash
|
| 108 |
python main.py "CRISPR delivery methods for liver diseases in vivo" --top 5
|
|
@@ -117,25 +125,21 @@ These are all optional environment variables:
|
|
| 117 |
|
| 118 |
## Deploying to Hugging Face Spaces
|
| 119 |
|
| 120 |
-
1. Create a new Space at https://huggingface.co/new-space
|
| 121 |
-
**
|
| 122 |
2. In the Space's **Settings → Variables and secrets**, add `GROQ_API_KEY`
|
| 123 |
(and `OPEN_ALEX_API` if you have one) as **secrets**.
|
| 124 |
3. Push this repo to the Space:
|
| 125 |
```bash
|
| 126 |
git remote add space https://huggingface.co/spaces/<your-username>/PaperRank
|
| 127 |
-
git push space main
|
| 128 |
```
|
|
|
|
|
|
|
| 129 |
|
| 130 |
-
The block at the top of this README tells Spaces
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
To try the Docker image locally first:
|
| 134 |
-
|
| 135 |
-
```bash
|
| 136 |
-
docker build -t paperrank .
|
| 137 |
-
docker run --rm -p 7860:7860 --env-file .env paperrank
|
| 138 |
-
```
|
| 139 |
|
| 140 |
## Evaluation
|
| 141 |
|
|
|
|
| 3 |
emoji: 📄
|
| 4 |
colorFrom: blue
|
| 5 |
colorTo: indigo
|
| 6 |
+
sdk: gradio
|
| 7 |
+
sdk_version: 6.30.0
|
| 8 |
+
python_version: "3.12"
|
| 9 |
+
app_file: app.py
|
| 10 |
pinned: false
|
| 11 |
short_description: Find papers for a research question and spot gaps
|
| 12 |
---
|
|
|
|
| 56 |
|
| 57 |
## What's in here
|
| 58 |
|
| 59 |
+
There's no separate backend. `app.py` is the whole web app: Gradio serves the
|
| 60 |
+
page and runs the pipeline in the same Python process.
|
| 61 |
+
|
| 62 |
| File | What it does |
|
| 63 |
|---|---|
|
| 64 |
+
| `app.py` | The Gradio web app. Search box, results, coverage bars, year filter, per-paper summaries, plus caching and rate limiting so a public deploy doesn't burn through API budgets. |
|
| 65 |
| `retriever.py` | Talks to OpenAlex. Runs searches (several at once), rebuilds abstracts from OpenAlex's odd inverted-index format, and counts matching papers for the gap check. |
|
| 66 |
| `reranker.py` | Loads a CrossEncoder and reranks papers. Every model's scores get squashed to 0–1 so they're comparable. |
|
| 67 |
| `analyzer.py` | All the LLM parts: breaking down the question, checking coverage, finding gaps, writing summaries. |
|
| 68 |
| `main.py` | The same pipeline from the command line, if you don't want to open a browser. |
|
| 69 |
| `evaluate.py` | Offline evaluation (NDCG@10, MRR) comparing plain OpenAlex ranking against multi-query search and reranking. Questions live in `eval/queries.txt`. |
|
| 70 |
+
| `requirements.txt` | Python dependencies, pinned to versions I've tested. Pulls the CPU-only build of PyTorch to keep installs small. |
|
|
|
|
| 71 |
|
| 72 |
## Reranker models
|
| 73 |
|
|
|
|
| 100 |
OPEN_ALEX_API=your_openalex_key # optional, but gives you your own daily budget
|
| 101 |
```
|
| 102 |
|
| 103 |
+
Then start the app and keep the terminal open while you use it:
|
| 104 |
|
| 105 |
```bash
|
| 106 |
+
python app.py
|
| 107 |
```
|
| 108 |
|
| 109 |
+
It opens at http://127.0.0.1:7860. A new question takes anywhere from 20
|
| 110 |
+
seconds to a minute (most of that is OpenAlex and the reranker). Asking the
|
| 111 |
+
same thing again is instant because results are cached for a day.
|
| 112 |
+
|
| 113 |
+
Or skip the browser:
|
| 114 |
|
| 115 |
```bash
|
| 116 |
python main.py "CRISPR delivery methods for liver diseases in vivo" --top 5
|
|
|
|
| 125 |
|
| 126 |
## Deploying to Hugging Face Spaces
|
| 127 |
|
| 128 |
+
1. Create a new Space at https://huggingface.co/new-space, pick **Gradio**
|
| 129 |
+
as the SDK and **CPU basic (free)** as the hardware.
|
| 130 |
2. In the Space's **Settings → Variables and secrets**, add `GROQ_API_KEY`
|
| 131 |
(and `OPEN_ALEX_API` if you have one) as **secrets**.
|
| 132 |
3. Push this repo to the Space:
|
| 133 |
```bash
|
| 134 |
git remote add space https://huggingface.co/spaces/<your-username>/PaperRank
|
| 135 |
+
git push --force space main
|
| 136 |
```
|
| 137 |
+
When git asks for a password, use a Hugging Face access token with write
|
| 138 |
+
access, not your account password.
|
| 139 |
|
| 140 |
+
The block at the top of this README tells Spaces which Gradio and Python
|
| 141 |
+
versions to use and to run `app.py`. The first build takes a few minutes,
|
| 142 |
+
mostly installing PyTorch. After that, every push rebuilds the Space.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 143 |
|
| 144 |
## Evaluation
|
| 145 |
|
app.py
CHANGED
|
@@ -1,13 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import os
|
| 2 |
-
import re
|
| 3 |
import threading
|
| 4 |
import time
|
| 5 |
from datetime import date
|
|
|
|
| 6 |
|
| 7 |
from dotenv import load_dotenv
|
| 8 |
load_dotenv()
|
| 9 |
|
| 10 |
-
import
|
| 11 |
|
| 12 |
from analyzer import LLMError, assess_coverage, decompose, find_gaps, summarize_paper
|
| 13 |
from reranker import AVAILABLE_MODELS, DEFAULT_MODEL, load_model, rerank
|
|
@@ -16,6 +20,7 @@ from retriever import multi_search
|
|
| 16 |
|
| 17 |
MAX_QUESTION_CHARS = 500
|
| 18 |
CACHE_TTL = 24 * 3600
|
|
|
|
| 19 |
# OpenAlex bills ~$0.009 per search against a $1/day key budget, so cap the
|
| 20 |
# whole app; per-session caps stop one visitor from using it all.
|
| 21 |
DAILY_SEARCH_LIMIT = int(os.environ.get("DAILY_SEARCH_LIMIT", "100"))
|
|
@@ -29,23 +34,48 @@ MODEL_LABELS = {
|
|
| 29 |
}
|
| 30 |
STATUS_ICON = {"covered": "✅", "partial": "🟡", "missing": "❌"}
|
| 31 |
|
| 32 |
-
st.set_page_config(page_title="PaperRank", page_icon="📄", layout="wide")
|
| 33 |
-
|
| 34 |
|
| 35 |
class NoResults(Exception):
|
| 36 |
pass
|
| 37 |
|
| 38 |
|
| 39 |
-
# ──
|
| 40 |
-
#
|
| 41 |
-
# never cached
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
|
| 43 |
-
@st.cache_resource(show_spinner=False)
|
| 44 |
def get_model(name: str):
|
| 45 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 46 |
|
| 47 |
|
| 48 |
-
@
|
| 49 |
def cached_plan(question: str) -> dict:
|
| 50 |
plan = decompose(question)
|
| 51 |
if not plan["aspects"]:
|
|
@@ -53,306 +83,378 @@ def cached_plan(question: str) -> dict:
|
|
| 53 |
return plan
|
| 54 |
|
| 55 |
|
| 56 |
-
@
|
| 57 |
-
def cached_search(sub_queries:
|
| 58 |
-
papers = multi_search(
|
| 59 |
if not papers:
|
| 60 |
raise NoResults()
|
| 61 |
return papers
|
| 62 |
|
| 63 |
|
| 64 |
-
@
|
| 65 |
-
def cached_rerank(question: str, sub_queries:
|
| 66 |
return rerank(question, cached_search(sub_queries), get_model(model_name))
|
| 67 |
|
| 68 |
|
| 69 |
-
@
|
| 70 |
def cached_assess(question: str, aspects: list[dict], papers: list[dict]) -> list[dict]:
|
| 71 |
return assess_coverage(question, aspects, papers)
|
| 72 |
|
| 73 |
|
| 74 |
-
@
|
| 75 |
def cached_gaps(aspects: list[dict], assessments: list[dict]) -> dict:
|
| 76 |
return find_gaps(aspects, assessments)
|
| 77 |
|
| 78 |
|
| 79 |
-
@
|
| 80 |
def cached_summary(question: str, paper_id: str, title: str, abstract: str) -> str:
|
| 81 |
return summarize_paper(question, {"title": title, "abstract": abstract})
|
| 82 |
|
| 83 |
|
| 84 |
# ── Rate limiting ─────────────────────────────────────────────────────────────
|
| 85 |
|
| 86 |
-
|
| 87 |
-
def _daily_usage() -> dict:
|
| 88 |
-
# One shared counter for the whole server process (all visitors).
|
| 89 |
-
return {"lock": threading.Lock(), "day": "", "count": 0}
|
| 90 |
|
| 91 |
|
| 92 |
-
def
|
| 93 |
-
|
| 94 |
-
with usage["lock"]:
|
| 95 |
today = date.today().isoformat()
|
| 96 |
-
if
|
| 97 |
-
|
| 98 |
-
if
|
| 99 |
return False
|
| 100 |
-
|
| 101 |
return True
|
| 102 |
|
| 103 |
|
| 104 |
-
def
|
|
|
|
| 105 |
now = time.time()
|
| 106 |
-
stamps = [t for t in
|
| 107 |
allowed = len(stamps) < per_hour
|
| 108 |
if allowed:
|
| 109 |
stamps.append(now)
|
| 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 |
try:
|
| 135 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 136 |
except LLMError:
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
st.error("No papers with abstracts were found (or OpenAlex is unavailable). Try rephrasing.")
|
| 146 |
-
return None
|
| 147 |
-
|
| 148 |
-
assessments, gaps = None, None
|
| 149 |
-
if plan["aspects"]:
|
| 150 |
-
st.write(f"Checking how well the top {top_k} papers cover each aspect...")
|
| 151 |
-
try:
|
| 152 |
-
assessments = cached_assess(question, plan["aspects"], papers[:top_k])
|
| 153 |
-
st.write("Looking for possible gaps...")
|
| 154 |
-
gaps = cached_gaps(plan["aspects"], assessments)
|
| 155 |
-
except LLMError:
|
| 156 |
-
st.write("⚠️ Coverage analysis is unavailable right now; showing ranked papers only.")
|
| 157 |
-
|
| 158 |
-
status.update(label=f"Found {len(papers)} candidate papers", state="complete", expanded=False)
|
| 159 |
-
|
| 160 |
-
if assessments:
|
| 161 |
-
for paper, analysis in zip(papers, assessments):
|
| 162 |
-
paper["analysis"] = analysis
|
| 163 |
return {
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
|
|
|
|
|
|
|
|
|
| 169 |
}
|
| 170 |
|
| 171 |
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 179 |
)
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
shown = True
|
| 183 |
-
terms = ", ".join(f"*{md(a['keywords'])}*" for a in aspects)
|
| 184 |
-
st.markdown(f"**{gaps['full_count']:,}** papers mention all of {terms} in their title or abstract.")
|
| 185 |
-
for b in gaps["bottlenecks"]:
|
| 186 |
-
ratio = b["count_without"] / max(gaps["full_count"], 1)
|
| 187 |
-
st.markdown(f"- Without **{md(b['aspect'])}**: {b['count_without']:,} papers ({ratio:,.0f}× more)")
|
| 188 |
-
if gaps["full_count"] < 20:
|
| 189 |
-
st.info("Few papers combine all of these aspects — this combination may be understudied.")
|
| 190 |
-
if gaps.get("uncovered"):
|
| 191 |
-
shown = True
|
| 192 |
-
names = ", ".join(f"**{md(n)}**" for n in gaps["uncovered"])
|
| 193 |
-
st.markdown(f"None of the top papers fully covers: {names}")
|
| 194 |
-
if not shown:
|
| 195 |
-
st.write("No obvious gaps: the top papers cover every aspect.")
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
def render_paper(paper: dict, question: str, n_queries: int) -> None:
|
| 199 |
-
pid = paper["paperId"]
|
| 200 |
-
with st.container(border=True):
|
| 201 |
-
title = md(paper["title"])
|
| 202 |
-
url = paper.get("url")
|
| 203 |
-
st.markdown(f"**#{paper['ce_rank']}** · " + (f"[{title}]({safe_url(url)})" if url else title))
|
| 204 |
-
|
| 205 |
-
authors = [a["name"] for a in paper.get("authors", [])]
|
| 206 |
-
author_text = ", ".join(authors[:3]) + (" et al." if len(authors) > 3 else "")
|
| 207 |
-
meta = [
|
| 208 |
-
str(paper.get("year") or "n.d."),
|
| 209 |
-
f"{paper.get('citationCount') or 0:,} citations",
|
| 210 |
-
author_text,
|
| 211 |
-
f"found by {len(paper.get('matched_queries', []))}/{n_queries} searches",
|
| 212 |
-
f"match score {paper['ce_score']:.2f}",
|
| 213 |
-
]
|
| 214 |
-
st.caption(md(" · ".join(m for m in meta if m)))
|
| 215 |
-
|
| 216 |
-
analysis = paper.get("analysis")
|
| 217 |
-
if analysis and analysis.get("coverage") is not None:
|
| 218 |
-
st.progress(analysis["coverage"] / 100, text=f"Covers {analysis['coverage']}% of your question")
|
| 219 |
-
for a in analysis["aspects"]:
|
| 220 |
-
line = f"{STATUS_ICON[a['status']]} **{md(a['name'])}**"
|
| 221 |
-
if a["evidence"]:
|
| 222 |
-
line += f' — *"{md(a["evidence"])}"*'
|
| 223 |
-
st.markdown(line)
|
| 224 |
-
if analysis.get("note"):
|
| 225 |
-
st.caption(f"Not addressed: {md(analysis['note'])}")
|
| 226 |
-
|
| 227 |
-
with st.expander("Abstract"):
|
| 228 |
-
st.write(md(paper["abstract"]))
|
| 229 |
-
|
| 230 |
-
summarized = st.session_state.setdefault("summarized", set())
|
| 231 |
-
if pid in summarized:
|
| 232 |
-
try:
|
| 233 |
-
st.info(md(cached_summary(question, pid, paper["title"], paper["abstract"])))
|
| 234 |
-
except LLMError as e:
|
| 235 |
-
summarized.discard(pid)
|
| 236 |
-
st.error(f"Summary failed: {e}")
|
| 237 |
-
elif st.button("Summarize", key=f"sum_{pid}"):
|
| 238 |
-
if _take_session("summary_times", SESSION_SUMMARIES_PER_HOUR):
|
| 239 |
-
summarized.add(pid)
|
| 240 |
-
st.rerun()
|
| 241 |
-
else:
|
| 242 |
-
st.warning("Summary limit reached for this hour. Please try again later.")
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
# ── Sidebar ───────────────────────────────────────────────────────────────────
|
| 246 |
-
|
| 247 |
-
with st.sidebar:
|
| 248 |
-
st.title("📄 PaperRank")
|
| 249 |
-
st.caption("Find papers that answer your research question — and spot what's missing.")
|
| 250 |
-
st.divider()
|
| 251 |
-
model_name = st.selectbox(
|
| 252 |
-
"Reranker model",
|
| 253 |
-
AVAILABLE_MODELS,
|
| 254 |
-
index=AVAILABLE_MODELS.index(DEFAULT_MODEL),
|
| 255 |
-
format_func=lambda m: MODEL_LABELS.get(m, m),
|
| 256 |
-
)
|
| 257 |
-
top_k = st.slider("Papers to analyze in depth", 5, 20, 10,
|
| 258 |
-
help="Top papers checked for coverage of each aspect. More is slower.")
|
| 259 |
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
st.title("PaperRank")
|
| 264 |
-
with st.form("search"):
|
| 265 |
-
question = st.text_area(
|
| 266 |
-
"Your research question",
|
| 267 |
placeholder="e.g. effects of microplastics on gut microbiome in zebrafish larvae",
|
| 268 |
-
max_chars=MAX_QUESTION_CHARS,
|
| 269 |
-
height=90,
|
| 270 |
)
|
| 271 |
-
|
| 272 |
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
result = st.session_state.get("result")
|
| 288 |
-
if not result:
|
| 289 |
-
st.info(
|
| 290 |
-
"Ask a question in plain language. PaperRank breaks it into aspects, searches OpenAlex "
|
| 291 |
-
"several ways, reranks the results, and shows which papers cover which parts of your "
|
| 292 |
-
"question — with quotes as evidence."
|
| 293 |
-
)
|
| 294 |
-
st.stop()
|
| 295 |
-
|
| 296 |
-
plan, papers = result["plan"], result["papers"]
|
| 297 |
-
|
| 298 |
-
st.subheader(f'Results for: "{md(result["question"])}"')
|
| 299 |
-
if plan["aspects"]:
|
| 300 |
-
st.markdown("**Aspects:** " + " · ".join(f"`{a['name']}`" for a in plan["aspects"]))
|
| 301 |
-
with st.expander("Searches run"):
|
| 302 |
-
for q in plan["sub_queries"]:
|
| 303 |
-
st.markdown(f"- {md(q)}")
|
| 304 |
-
st.caption(f"Reranked with {MODEL_LABELS.get(result['model'], result['model'])}")
|
| 305 |
-
|
| 306 |
-
if result["gaps"]:
|
| 307 |
-
render_gaps(result["gaps"], plan["aspects"])
|
| 308 |
-
|
| 309 |
-
# Display-only controls: never re-run search or analysis.
|
| 310 |
-
col_sort, col_year = st.columns(2)
|
| 311 |
-
analyzed = [p for p in papers if p.get("analysis")]
|
| 312 |
-
with col_sort:
|
| 313 |
-
sort_by = st.radio(
|
| 314 |
-
"Sort analyzed papers by", ["Match score", "Coverage"],
|
| 315 |
-
horizontal=True, disabled=not analyzed,
|
| 316 |
)
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
top = analyzed if analyzed else rest[:top_k]
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
if not top and not rest:
|
| 338 |
-
|
| 339 |
-
for paper in top:
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 358 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""PaperRank web app (Gradio). Run locally with: python app.py"""
|
| 2 |
+
import copy
|
| 3 |
+
import html
|
| 4 |
+
import json
|
| 5 |
import os
|
|
|
|
| 6 |
import threading
|
| 7 |
import time
|
| 8 |
from datetime import date
|
| 9 |
+
from functools import partial
|
| 10 |
|
| 11 |
from dotenv import load_dotenv
|
| 12 |
load_dotenv()
|
| 13 |
|
| 14 |
+
import gradio as gr
|
| 15 |
|
| 16 |
from analyzer import LLMError, assess_coverage, decompose, find_gaps, summarize_paper
|
| 17 |
from reranker import AVAILABLE_MODELS, DEFAULT_MODEL, load_model, rerank
|
|
|
|
| 20 |
|
| 21 |
MAX_QUESTION_CHARS = 500
|
| 22 |
CACHE_TTL = 24 * 3600
|
| 23 |
+
CACHE_MAX_ENTRIES = 256
|
| 24 |
# OpenAlex bills ~$0.009 per search against a $1/day key budget, so cap the
|
| 25 |
# whole app; per-session caps stop one visitor from using it all.
|
| 26 |
DAILY_SEARCH_LIMIT = int(os.environ.get("DAILY_SEARCH_LIMIT", "100"))
|
|
|
|
| 34 |
}
|
| 35 |
STATUS_ICON = {"covered": "✅", "partial": "🟡", "missing": "❌"}
|
| 36 |
|
|
|
|
|
|
|
| 37 |
|
| 38 |
class NoResults(Exception):
|
| 39 |
pass
|
| 40 |
|
| 41 |
|
| 42 |
+
# ── Caching ───────────────────────────────────────────────────────────────────
|
| 43 |
+
# Same idea as Streamlit's st.cache_data: identical inputs within 24h reuse the
|
| 44 |
+
# result, exceptions are never cached, and callers get a copy they can modify.
|
| 45 |
+
|
| 46 |
+
def ttl_cache(fn):
|
| 47 |
+
store: dict[str, tuple[float, object]] = {}
|
| 48 |
+
lock = threading.Lock()
|
| 49 |
+
|
| 50 |
+
def wrapper(*args):
|
| 51 |
+
key = json.dumps(args, sort_keys=True, default=str)
|
| 52 |
+
with lock:
|
| 53 |
+
hit = store.get(key)
|
| 54 |
+
if hit and time.time() - hit[0] < CACHE_TTL:
|
| 55 |
+
return copy.deepcopy(hit[1])
|
| 56 |
+
value = fn(*args)
|
| 57 |
+
with lock:
|
| 58 |
+
if len(store) >= CACHE_MAX_ENTRIES:
|
| 59 |
+
store.pop(min(store, key=lambda k: store[k][0])) # drop the oldest
|
| 60 |
+
store[key] = (time.time(), value)
|
| 61 |
+
return copy.deepcopy(value)
|
| 62 |
+
|
| 63 |
+
return wrapper
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
_models: dict = {}
|
| 67 |
+
_models_lock = threading.Lock()
|
| 68 |
+
|
| 69 |
|
|
|
|
| 70 |
def get_model(name: str):
|
| 71 |
+
# Lock so two visitors picking the same model don't load it twice.
|
| 72 |
+
with _models_lock:
|
| 73 |
+
if name not in _models:
|
| 74 |
+
_models[name] = load_model(name)
|
| 75 |
+
return _models[name]
|
| 76 |
|
| 77 |
|
| 78 |
+
@ttl_cache
|
| 79 |
def cached_plan(question: str) -> dict:
|
| 80 |
plan = decompose(question)
|
| 81 |
if not plan["aspects"]:
|
|
|
|
| 83 |
return plan
|
| 84 |
|
| 85 |
|
| 86 |
+
@ttl_cache
|
| 87 |
+
def cached_search(sub_queries: list[str]) -> list[dict]:
|
| 88 |
+
papers = multi_search(sub_queries)
|
| 89 |
if not papers:
|
| 90 |
raise NoResults()
|
| 91 |
return papers
|
| 92 |
|
| 93 |
|
| 94 |
+
@ttl_cache
|
| 95 |
+
def cached_rerank(question: str, sub_queries: list[str], model_name: str) -> list[dict]:
|
| 96 |
return rerank(question, cached_search(sub_queries), get_model(model_name))
|
| 97 |
|
| 98 |
|
| 99 |
+
@ttl_cache
|
| 100 |
def cached_assess(question: str, aspects: list[dict], papers: list[dict]) -> list[dict]:
|
| 101 |
return assess_coverage(question, aspects, papers)
|
| 102 |
|
| 103 |
|
| 104 |
+
@ttl_cache
|
| 105 |
def cached_gaps(aspects: list[dict], assessments: list[dict]) -> dict:
|
| 106 |
return find_gaps(aspects, assessments)
|
| 107 |
|
| 108 |
|
| 109 |
+
@ttl_cache
|
| 110 |
def cached_summary(question: str, paper_id: str, title: str, abstract: str) -> str:
|
| 111 |
return summarize_paper(question, {"title": title, "abstract": abstract})
|
| 112 |
|
| 113 |
|
| 114 |
# ── Rate limiting ─────────────────────────────────────────────────────────────
|
| 115 |
|
| 116 |
+
_daily = {"lock": threading.Lock(), "day": "", "count": 0} # shared by all visitors
|
|
|
|
|
|
|
|
|
|
| 117 |
|
| 118 |
|
| 119 |
+
def take_daily_search() -> bool:
|
| 120 |
+
with _daily["lock"]:
|
|
|
|
| 121 |
today = date.today().isoformat()
|
| 122 |
+
if _daily["day"] != today:
|
| 123 |
+
_daily["day"], _daily["count"] = today, 0
|
| 124 |
+
if _daily["count"] >= DAILY_SEARCH_LIMIT:
|
| 125 |
return False
|
| 126 |
+
_daily["count"] += 1
|
| 127 |
return True
|
| 128 |
|
| 129 |
|
| 130 |
+
def take_session(limits: dict, kind: str, per_hour: int) -> tuple[bool, dict]:
|
| 131 |
+
"""Per-browser-session sliding window. Returns (allowed, updated limits)."""
|
| 132 |
now = time.time()
|
| 133 |
+
stamps = [t for t in limits.get(kind, []) if now - t < 3600]
|
| 134 |
allowed = len(stamps) < per_hour
|
| 135 |
if allowed:
|
| 136 |
stamps.append(now)
|
| 137 |
+
return allowed, {**limits, kind: stamps}
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
# ── HTML rendering ────────────────────────────────────────────────────────────
|
| 141 |
+
# Everything from OpenAlex or the LLM goes through esc(), so titles or abstracts
|
| 142 |
+
# containing <, & or quotes show up as text and can't inject markup.
|
| 143 |
+
|
| 144 |
+
def esc(text) -> str:
|
| 145 |
+
return html.escape(str(text or ""), quote=True)
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
def link(url: str, text: str) -> str:
|
| 149 |
+
if url and url.startswith(("https://", "http://")):
|
| 150 |
+
return f'<a href="{esc(url)}" target="_blank" rel="noopener noreferrer">{esc(text)}</a>'
|
| 151 |
+
return esc(text)
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
def paper_card(paper: dict, n_queries: int, summary: str | None) -> str:
|
| 155 |
+
authors = [a["name"] for a in paper.get("authors", [])]
|
| 156 |
+
author_text = ", ".join(authors[:3]) + (" et al." if len(authors) > 3 else "")
|
| 157 |
+
meta = [
|
| 158 |
+
str(paper.get("year") or "n.d."),
|
| 159 |
+
f"{paper.get('citationCount') or 0:,} citations",
|
| 160 |
+
author_text,
|
| 161 |
+
f"found by {len(paper.get('matched_queries', []))}/{n_queries} searches",
|
| 162 |
+
f"match score {paper['ce_score']:.2f}",
|
| 163 |
+
]
|
| 164 |
+
parts = [
|
| 165 |
+
'<div class="pr-card">',
|
| 166 |
+
f'<div class="pr-title"><span class="pr-rank">#{paper["ce_rank"]}</span> '
|
| 167 |
+
f'{link(paper.get("url"), paper["title"])}</div>',
|
| 168 |
+
f'<div class="pr-meta">{esc(" · ".join(m for m in meta if m))}</div>',
|
| 169 |
+
]
|
| 170 |
+
|
| 171 |
+
analysis = paper.get("analysis")
|
| 172 |
+
if analysis and analysis.get("coverage") is not None:
|
| 173 |
+
cov = analysis["coverage"]
|
| 174 |
+
parts.append(
|
| 175 |
+
f'<div class="pr-bar"><div style="width:{cov}%"></div></div>'
|
| 176 |
+
f'<div class="pr-cov">Covers {cov}% of your question</div><ul class="pr-aspects">'
|
| 177 |
+
)
|
| 178 |
+
for a in analysis["aspects"]:
|
| 179 |
+
line = f'{STATUS_ICON[a["status"]]} <b>{esc(a["name"])}</b>'
|
| 180 |
+
if a["evidence"]:
|
| 181 |
+
line += f' — <i>"{esc(a["evidence"])}"</i>'
|
| 182 |
+
parts.append(f"<li>{line}</li>")
|
| 183 |
+
parts.append("</ul>")
|
| 184 |
+
if analysis.get("note"):
|
| 185 |
+
parts.append(f'<div class="pr-note">Not addressed: {esc(analysis["note"])}</div>')
|
| 186 |
+
|
| 187 |
+
parts.append(f'<details><summary>Abstract</summary><p>{esc(paper["abstract"])}</p></details>')
|
| 188 |
+
if summary:
|
| 189 |
+
parts.append(f'<div class="pr-summary"><b>Summary:</b> {esc(summary)}</div>')
|
| 190 |
+
parts.append("</div>")
|
| 191 |
+
return "".join(parts)
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
def overview_html(result: dict, notes: list[str]) -> str:
|
| 195 |
+
plan, gaps = result["plan"], result["gaps"]
|
| 196 |
+
parts = [f'<h3 class="pr-h">Results for: "{esc(result["question"])}"</h3>']
|
| 197 |
+
for note in notes:
|
| 198 |
+
parts.append(f'<div class="pr-warn">⚠️ {esc(note)}</div>')
|
| 199 |
+
if plan["aspects"]:
|
| 200 |
+
chips = "".join(f'<span class="pr-chip">{esc(a["name"])}</span>' for a in plan["aspects"])
|
| 201 |
+
parts.append(f"<div><b>Aspects:</b> {chips}</div>")
|
| 202 |
+
searches = "".join(f"<li>{esc(q)}</li>" for q in plan["sub_queries"])
|
| 203 |
+
parts.append(
|
| 204 |
+
f"<details><summary>Searches run ({len(plan['sub_queries'])})</summary><ul>{searches}</ul>"
|
| 205 |
+
f'<div class="pr-meta">Reranked with {esc(MODEL_LABELS.get(result["model"], result["model"]))}'
|
| 206 |
+
f" · {len(result['papers'])} candidate papers</div></details>"
|
| 207 |
+
)
|
| 208 |
+
if gaps:
|
| 209 |
+
parts.append(gaps_html(gaps, plan["aspects"]))
|
| 210 |
+
return "".join(parts)
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
def gaps_html(gaps: dict, aspects: list[dict]) -> str:
|
| 214 |
+
parts = [
|
| 215 |
+
'<div class="pr-gaps"><b>🔍 Possible gaps</b>'
|
| 216 |
+
'<div class="pr-meta">Leads to verify, not proof: the topic may be studied under other '
|
| 217 |
+
"wording, in full texts, or in papers OpenAlex doesn't index.</div>"
|
| 218 |
+
]
|
| 219 |
+
shown = False
|
| 220 |
+
if gaps.get("full_count") is not None:
|
| 221 |
+
shown = True
|
| 222 |
+
terms = ", ".join(f"<i>{esc(a['keywords'])}</i>" for a in aspects)
|
| 223 |
+
parts.append(f"<p><b>{gaps['full_count']:,}</b> papers mention all of {terms} in their title or abstract.</p><ul>")
|
| 224 |
+
for b in gaps["bottlenecks"]:
|
| 225 |
+
ratio = b["count_without"] / max(gaps["full_count"], 1)
|
| 226 |
+
parts.append(f"<li>Without <b>{esc(b['aspect'])}</b>: {b['count_without']:,} papers ({ratio:,.0f}× more)</li>")
|
| 227 |
+
parts.append("</ul>")
|
| 228 |
+
if gaps["full_count"] < 20:
|
| 229 |
+
parts.append("<p>Few papers combine all of these aspects — this combination may be understudied.</p>")
|
| 230 |
+
if gaps.get("uncovered"):
|
| 231 |
+
shown = True
|
| 232 |
+
names = ", ".join(f"<b>{esc(n)}</b>" for n in gaps["uncovered"])
|
| 233 |
+
parts.append(f"<p>None of the top papers fully covers: {names}</p>")
|
| 234 |
+
if not shown:
|
| 235 |
+
parts.append("<p>No obvious gaps: the top papers cover every aspect.</p>")
|
| 236 |
+
parts.append("</div>")
|
| 237 |
+
return "".join(parts)
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
# ── Event handlers ────────────────────────────────────────────────────────────
|
| 241 |
+
|
| 242 |
+
def run_search(question, model_name, top_k, limits, progress=gr.Progress()):
|
| 243 |
+
"""Search button: run the whole pipeline and store the result in session state."""
|
| 244 |
+
question = (question or "").strip()
|
| 245 |
+
top_k = int(top_k)
|
| 246 |
+
if len(question) < 5:
|
| 247 |
+
gr.Warning("Please enter a longer question.")
|
| 248 |
+
return {limits_state: limits}
|
| 249 |
+
allowed, limits = take_session(limits, "search", SESSION_SEARCHES_PER_HOUR)
|
| 250 |
+
if not allowed:
|
| 251 |
+
gr.Warning("You've reached the search limit for this hour. Please try again later.")
|
| 252 |
+
return {limits_state: limits}
|
| 253 |
+
if not take_daily_search():
|
| 254 |
+
gr.Warning("PaperRank has reached its daily search limit. Please come back tomorrow.")
|
| 255 |
+
return {limits_state: limits}
|
| 256 |
+
|
| 257 |
+
notes = []
|
| 258 |
+
progress(0.05, desc="Breaking the question into aspects...")
|
| 259 |
+
try:
|
| 260 |
+
plan = cached_plan(question)
|
| 261 |
+
except LLMError:
|
| 262 |
+
plan = {"aspects": [], "sub_queries": [question]}
|
| 263 |
+
notes.append("Couldn't analyze the question; searched it as-is without coverage analysis.")
|
| 264 |
+
|
| 265 |
+
progress(0.25, desc=f"Searching OpenAlex with {len(plan['sub_queries'])} queries and reranking...")
|
| 266 |
+
try:
|
| 267 |
+
papers = cached_rerank(question, plan["sub_queries"], model_name)
|
| 268 |
+
except NoResults:
|
| 269 |
+
gr.Warning("No papers with abstracts were found (or OpenAlex is unavailable). Try rephrasing.")
|
| 270 |
+
return {limits_state: limits}
|
| 271 |
+
|
| 272 |
+
gaps = None
|
| 273 |
+
if plan["aspects"]:
|
| 274 |
+
progress(0.65, desc=f"Checking how well the top {top_k} papers cover each aspect...")
|
| 275 |
try:
|
| 276 |
+
assessments = cached_assess(question, plan["aspects"], papers[:top_k])
|
| 277 |
+
progress(0.9, desc="Looking for possible gaps...")
|
| 278 |
+
gaps = cached_gaps(plan["aspects"], assessments)
|
| 279 |
+
for paper, analysis in zip(papers, assessments):
|
| 280 |
+
paper["analysis"] = analysis
|
| 281 |
except LLMError:
|
| 282 |
+
notes.append("Coverage analysis is unavailable right now; showing ranked papers only.")
|
| 283 |
+
|
| 284 |
+
result = {"question": question, "model": model_name, "plan": plan,
|
| 285 |
+
"papers": papers, "gaps": gaps, "top_k": top_k}
|
| 286 |
+
years = sorted({p["year"] for p in papers if p.get("year")})
|
| 287 |
+
has_range = len(years) > 1
|
| 288 |
+
lo, hi = (years[0], years[-1]) if years else (0, 1)
|
| 289 |
+
analyzed = any(p.get("analysis") for p in papers)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 290 |
return {
|
| 291 |
+
result_state: result,
|
| 292 |
+
summaries_state: {},
|
| 293 |
+
limits_state: limits,
|
| 294 |
+
overview: gr.update(value=overview_html(result, notes)),
|
| 295 |
+
controls: gr.update(visible=True),
|
| 296 |
+
sort_by: gr.update(value="Match score", interactive=analyzed),
|
| 297 |
+
year_from: gr.update(minimum=lo, maximum=hi, value=lo, visible=has_range),
|
| 298 |
+
year_to: gr.update(minimum=lo, maximum=hi, value=hi, visible=has_range),
|
| 299 |
}
|
| 300 |
|
| 301 |
|
| 302 |
+
def run_summary(paper_id, result, summaries, limits):
|
| 303 |
+
"""Summarize one paper (button on a card, or the picker for other candidates)."""
|
| 304 |
+
if not result or not paper_id:
|
| 305 |
+
return summaries, limits
|
| 306 |
+
paper = next((p for p in result["papers"] if p["paperId"] == paper_id), None)
|
| 307 |
+
if paper is None or paper_id in summaries:
|
| 308 |
+
return summaries, limits
|
| 309 |
+
allowed, limits = take_session(limits, "summary", SESSION_SUMMARIES_PER_HOUR)
|
| 310 |
+
if not allowed:
|
| 311 |
+
gr.Warning("Summary limit reached for this hour. Please try again later.")
|
| 312 |
+
return summaries, limits
|
| 313 |
+
try:
|
| 314 |
+
text = cached_summary(result["question"], paper_id, paper["title"], paper["abstract"])
|
| 315 |
+
except LLMError as e:
|
| 316 |
+
gr.Warning(f"Summary failed: {e}")
|
| 317 |
+
return summaries, limits
|
| 318 |
+
return {**summaries, paper_id: text}, limits
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
# ── Layout ────────────────────────────────────────────────────────────────────
|
| 322 |
+
|
| 323 |
+
CSS = """
|
| 324 |
+
.pr-card { padding: 4px 2px; line-height: 1.5; }
|
| 325 |
+
.pr-title { font-weight: 600; font-size: 1.05em; }
|
| 326 |
+
.pr-rank { color: var(--body-text-color-subdued); margin-right: 4px; }
|
| 327 |
+
.pr-meta { color: var(--body-text-color-subdued); font-size: 0.88em; margin: 2px 0 6px; }
|
| 328 |
+
.pr-bar { height: 8px; border-radius: 4px; background: var(--background-fill-secondary);
|
| 329 |
+
border: 1px solid var(--border-color-primary); overflow: hidden; margin-top: 6px; }
|
| 330 |
+
.pr-bar > div { height: 100%; background: var(--color-accent); }
|
| 331 |
+
.pr-cov { font-size: 0.88em; margin: 2px 0 4px; }
|
| 332 |
+
.pr-aspects { margin: 4px 0; padding-left: 0; list-style: none; }
|
| 333 |
+
.pr-aspects li { margin: 2px 0; }
|
| 334 |
+
.pr-note { color: var(--body-text-color-subdued); font-size: 0.88em; }
|
| 335 |
+
.pr-summary { margin-top: 8px; padding: 8px 10px; border-radius: 6px;
|
| 336 |
+
background: var(--background-fill-secondary); }
|
| 337 |
+
.pr-chip { display: inline-block; padding: 1px 8px; margin: 2px 4px 2px 0; border-radius: 10px;
|
| 338 |
+
border: 1px solid var(--border-color-primary); font-size: 0.9em; }
|
| 339 |
+
.pr-gaps { margin-top: 10px; padding: 10px 12px; border-radius: 8px;
|
| 340 |
+
border: 1px solid var(--border-color-primary); }
|
| 341 |
+
.pr-warn { margin: 4px 0; }
|
| 342 |
+
.pr-h { margin: 0 0 6px; }
|
| 343 |
+
details summary { cursor: pointer; }
|
| 344 |
+
"""
|
| 345 |
+
|
| 346 |
+
INTRO = (
|
| 347 |
+
"Ask a question in plain language. PaperRank breaks it into aspects, searches OpenAlex "
|
| 348 |
+
"several ways, reranks the results, and shows which papers cover which parts of your "
|
| 349 |
+
"question — with quotes as evidence."
|
| 350 |
+
)
|
| 351 |
+
|
| 352 |
+
HOW_IT_WORKS = """
|
| 353 |
+
1. An LLM breaks your question into **aspects** and writes several **search queries**.
|
| 354 |
+
2. Each query runs as a semantic search on **OpenAlex** (200M+ papers); results are merged.
|
| 355 |
+
3. A **CrossEncoder** reads your question next to every paper and reranks them (*match score*).
|
| 356 |
+
4. The LLM checks each top paper against each aspect and must **quote the abstract** as
|
| 357 |
+
evidence; quotes not found in the abstract are discarded. *Coverage* = covered (1) +
|
| 358 |
+
partial (½), averaged over aspects.
|
| 359 |
+
5. **Possible gaps** come from keyword counts on OpenAlex: how many papers mention all
|
| 360 |
+
aspects together, and how many when each aspect is dropped.
|
| 361 |
+
|
| 362 |
+
Based on abstracts only. Always verify against the full paper.
|
| 363 |
+
"""
|
| 364 |
+
|
| 365 |
+
with gr.Blocks(title="PaperRank") as demo:
|
| 366 |
+
result_state = gr.State(None)
|
| 367 |
+
summaries_state = gr.State({})
|
| 368 |
+
limits_state = gr.State({})
|
| 369 |
+
|
| 370 |
+
with gr.Sidebar():
|
| 371 |
+
gr.Markdown("## 📄 PaperRank\nFind papers that answer your research question — and spot what's missing.")
|
| 372 |
+
model_dd = gr.Dropdown(
|
| 373 |
+
choices=[(MODEL_LABELS.get(m, m), m) for m in AVAILABLE_MODELS],
|
| 374 |
+
value=DEFAULT_MODEL, label="Reranker model",
|
| 375 |
)
|
| 376 |
+
top_k_slider = gr.Slider(5, 20, value=10, step=1, label="Papers to analyze in depth",
|
| 377 |
+
info="Top papers checked for coverage of each aspect. More is slower.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 378 |
|
| 379 |
+
gr.Markdown("# PaperRank")
|
| 380 |
+
question_box = gr.Textbox(
|
| 381 |
+
label="Your research question", lines=3, max_length=MAX_QUESTION_CHARS,
|
|
|
|
|
|
|
|
|
|
|
|
|
| 382 |
placeholder="e.g. effects of microplastics on gut microbiome in zebrafish larvae",
|
|
|
|
|
|
|
| 383 |
)
|
| 384 |
+
search_btn = gr.Button("Search", variant="primary")
|
| 385 |
|
| 386 |
+
overview = gr.HTML(f"<p>{esc(INTRO)}</p>")
|
| 387 |
+
|
| 388 |
+
# Display-only controls: they never re-run search or analysis.
|
| 389 |
+
with gr.Row(visible=False) as controls:
|
| 390 |
+
sort_by = gr.Radio(["Match score", "Coverage"], value="Match score",
|
| 391 |
+
label="Sort analyzed papers by")
|
| 392 |
+
year_from = gr.Slider(0, 1, step=1, label="From year", visible=False)
|
| 393 |
+
year_to = gr.Slider(0, 1, step=1, label="To year", visible=False)
|
| 394 |
+
|
| 395 |
+
@gr.render(
|
| 396 |
+
inputs=[result_state, summaries_state, sort_by, year_from, year_to],
|
| 397 |
+
triggers=[result_state.change, summaries_state.change, sort_by.change,
|
| 398 |
+
year_from.release, year_to.release],
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 399 |
)
|
| 400 |
+
def show_papers(result, summaries, sort_mode, y_from, y_to):
|
| 401 |
+
if not result:
|
| 402 |
+
return
|
| 403 |
+
papers = result["papers"]
|
| 404 |
+
lo, hi = sorted((int(y_from or 0), int(y_to or 9999)))
|
| 405 |
+
years = [p["year"] for p in papers if p.get("year")]
|
| 406 |
+
if not years or min(years) == max(years):
|
| 407 |
+
lo, hi = 0, 9999 # sliders hidden: no filtering
|
| 408 |
+
|
| 409 |
+
def in_years(p):
|
| 410 |
+
return p.get("year") is None or lo <= p["year"] <= hi
|
| 411 |
+
|
| 412 |
+
analyzed = [p for p in papers if p.get("analysis") and in_years(p)]
|
| 413 |
+
rest = [p for p in papers if not p.get("analysis") and in_years(p)]
|
| 414 |
+
if sort_mode == "Coverage":
|
| 415 |
+
analyzed.sort(key=lambda p: (-p["analysis"]["coverage"], p["ce_rank"]))
|
| 416 |
+
top_k = result["top_k"]
|
| 417 |
+
top, rest = (analyzed, rest) if analyzed else (rest[:top_k], rest[top_k:])
|
| 418 |
+
n_queries = len(result["plan"]["sub_queries"])
|
| 419 |
+
|
| 420 |
+
if not top and not rest:
|
| 421 |
+
gr.Markdown("No papers in the selected year range.")
|
| 422 |
+
for paper in top:
|
| 423 |
+
pid = paper["paperId"]
|
| 424 |
+
with gr.Group():
|
| 425 |
+
gr.HTML(paper_card(paper, n_queries, summaries.get(pid)), padding=True)
|
| 426 |
+
if pid not in summaries:
|
| 427 |
+
btn = gr.Button("Summarize", size="sm", key=f"sum-{pid}")
|
| 428 |
+
btn.click(partial(run_summary, pid),
|
| 429 |
+
inputs=[result_state, summaries_state, limits_state],
|
| 430 |
+
outputs=[summaries_state, limits_state])
|
| 431 |
+
|
| 432 |
+
if rest:
|
| 433 |
+
with gr.Accordion(f"More candidates ({len(rest)}, not analyzed)", open=False,
|
| 434 |
+
key="more", preserved_by_key=["open"]):
|
| 435 |
+
with gr.Row():
|
| 436 |
+
pick = gr.Dropdown(
|
| 437 |
+
choices=[(f"#{p['ce_rank']} {p['title'][:90]}", p["paperId"])
|
| 438 |
+
for p in rest if p["paperId"] not in summaries],
|
| 439 |
+
label="Summarize one of these", scale=4, key="pick",
|
| 440 |
+
)
|
| 441 |
+
pick_btn = gr.Button("Summarize", size="sm", scale=1)
|
| 442 |
+
pick_btn.click(run_summary, inputs=[pick, result_state, summaries_state, limits_state],
|
| 443 |
+
outputs=[summaries_state, limits_state])
|
| 444 |
+
gr.HTML("<hr>".join(paper_card(p, n_queries, summaries.get(p["paperId"])) for p in rest),
|
| 445 |
+
padding=True)
|
| 446 |
+
|
| 447 |
+
with gr.Accordion("How ranking works", open=False):
|
| 448 |
+
gr.Markdown(HOW_IT_WORKS)
|
| 449 |
+
|
| 450 |
+
search_btn.click(
|
| 451 |
+
run_search,
|
| 452 |
+
inputs=[question_box, model_dd, top_k_slider, limits_state],
|
| 453 |
+
outputs=[result_state, summaries_state, limits_state, overview, controls,
|
| 454 |
+
sort_by, year_from, year_to],
|
| 455 |
+
concurrency_limit=2, # reranking is CPU-heavy; queue the rest
|
| 456 |
)
|
| 457 |
+
|
| 458 |
+
|
| 459 |
+
if __name__ == "__main__":
|
| 460 |
+
demo.queue(max_size=20).launch(theme=gr.themes.Soft(), css=CSS)
|
requirements.txt
CHANGED
|
@@ -1,10 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
# Pinned to the versions the pipeline was tested with (Python 3.13).
|
| 2 |
-
# The Dockerfile installs a CPU-only torch build first; locally, pip uses
|
| 3 |
-
# the regular torch wheel.
|
| 4 |
requests==2.34.2
|
| 5 |
torch==2.12.1
|
| 6 |
transformers==5.12.1
|
| 7 |
sentence-transformers==5.6.0
|
| 8 |
groq==1.5.0
|
| 9 |
python-dotenv==1.2.2
|
| 10 |
-
|
|
|
|
| 1 |
+
# Use PyTorch's CPU-only builds (~200 MB) instead of the default Linux wheel,
|
| 2 |
+
# which drags in ~2 GB of CUDA libraries a CPU server can't use.
|
| 3 |
+
--extra-index-url https://download.pytorch.org/whl/cpu
|
| 4 |
+
|
| 5 |
# Pinned to the versions the pipeline was tested with (Python 3.13).
|
|
|
|
|
|
|
| 6 |
requests==2.34.2
|
| 7 |
torch==2.12.1
|
| 8 |
transformers==5.12.1
|
| 9 |
sentence-transformers==5.6.0
|
| 10 |
groq==1.5.0
|
| 11 |
python-dotenv==1.2.2
|
| 12 |
+
gradio==6.30.0
|