Spaces:
Sleeping
Sleeping
Add SciHigh 2026 extractive highlight model and Gradio test UI
Browse files- README.md +88 -1
- SciHigh_2026_CPU_Hybrid.ipynb +1121 -0
- app.py +164 -0
- clf_ExtraTrees.part00.joblib +3 -0
- clf_ExtraTrees.part01.joblib +3 -0
- clf_LinearSVC.joblib +3 -0
- clf_LogReg.joblib +3 -0
- clf_MLP.joblib +3 -0
- clf_Ridge.joblib +3 -0
- config.json +114 -0
- proto.npy +3 -0
- requirements.txt +7 -0
- scihigh_model.py +360 -0
- svd.joblib +3 -0
- tfidf.joblib +3 -0
- train_centroids.part00.npy +3 -0
- train_centroids.part01.npy +3 -0
- train_export.py +227 -0
- train_highlight_emb.part00.npy +3 -0
- train_highlight_emb.part01.npy +3 -0
README.md
CHANGED
|
@@ -9,6 +9,93 @@ python_version: '3.12'
|
|
| 9 |
app_file: app.py
|
| 10 |
pinned: false
|
| 11 |
license: mit
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
---
|
| 13 |
|
| 14 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
app_file: app.py
|
| 10 |
pinned: false
|
| 11 |
license: mit
|
| 12 |
+
short_description: Extractive highlight generator for FIRE 2026 SciHigh
|
| 13 |
+
suggested_hardware: cpu-basic
|
| 14 |
+
models:
|
| 15 |
+
- sentence-transformers/all-MiniLM-L6-v2
|
| 16 |
+
tags:
|
| 17 |
+
- summarization
|
| 18 |
+
- extractive-summarization
|
| 19 |
+
- scientific-highlights
|
| 20 |
+
- fire-2026
|
| 21 |
+
- scikit-learn
|
| 22 |
---
|
| 23 |
|
| 24 |
+
# SciHigh 2026: Supervised Extractive Research-Highlight Generator
|
| 25 |
+
|
| 26 |
+
Submission to **FIRE 2026 SciHigh, Subtask 1** (research highlight generation from MixSub abstracts).
|
| 27 |
+
The system runs entirely on CPU. Open the **App** tab to try it on your own abstract or on a CSV file.
|
| 28 |
+
|
| 29 |
+
## Method
|
| 30 |
+
|
| 31 |
+
The task is treated as sentence ranking, not text generation.
|
| 32 |
+
|
| 33 |
+
| Stage | What happens |
|
| 34 |
+
|---|---|
|
| 35 |
+
| 1. Pre-processing | Clean the abstract and split it into sentences (splitter written for MixSub's spaced periods) |
|
| 36 |
+
| 2. Hand-built features (31) | Position, length, lexical density, discourse cue counts, TF-IDF centrality, TextRank |
|
| 37 |
+
| 3. Embedding features (36) | `all-MiniLM-L6-v2`: similarity to the abstract centroid, to a highlight-style prototype, to other sentences, a retrieval feature from the 10 nearest training abstracts, and a 32-dim SVD projection |
|
| 38 |
+
| 4. Scoring | Five classifiers: LinearSVC, Ridge, LogReg, MLP, ExtraTrees |
|
| 39 |
+
| 5. Fusion | Reciprocal Rank Fusion of the five rankings within each abstract (k = 60) |
|
| 40 |
+
| 6. Decoding | Top sentences under a 110-word budget, at most 3 sentences, MMR redundancy threshold 0.85; original order restored; reporting frames ("In this study, we found that ...") removed |
|
| 41 |
+
|
| 42 |
+
Training labels come from a greedy ROUGE-1+2 F1 oracle over the 10,000 training abstracts (61,775 sentences).
|
| 43 |
+
|
| 44 |
+
## Results (MixSub-SciHigh validation set, 1,985 abstracts)
|
| 45 |
+
|
| 46 |
+
| System | ROUGE-1 | ROUGE-2 | ROUGE-L |
|
| 47 |
+
|---|---|---|---|
|
| 48 |
+
| This model (5-model fusion) | 38.12 | 14.13 | 24.76 |
|
| 49 |
+
| FIRE 2025 winner (Pegasus), reported | - | - | 23.45 |
|
| 50 |
+
|
| 51 |
+
Single members (decoded with budget 110, 3 sentences, MMR 0.55; fast stemmed ROUGE-L):
|
| 52 |
+
|
| 53 |
+
| Model | ROUGE-L |
|
| 54 |
+
|---|---|
|
| 55 |
+
| LinearSVC | 23.47 |
|
| 56 |
+
| Ridge | 23.47 |
|
| 57 |
+
| LogReg | 23.45 |
|
| 58 |
+
| MLP | 23.40 |
|
| 59 |
+
| ExtraTrees | 23.25 |
|
| 60 |
+
|
| 61 |
+
Every output word is copied from the source abstract, so the system cannot hallucinate facts or numbers.
|
| 62 |
+
The trade-off is that it cannot paraphrase the way authors often do in their own highlights.
|
| 63 |
+
|
| 64 |
+
## Use it from Python
|
| 65 |
+
|
| 66 |
+
```python
|
| 67 |
+
# pip install scikit-learn==1.8.0 "numpy>=2" pandas sentence-transformers huggingface_hub
|
| 68 |
+
from huggingface_hub import snapshot_download
|
| 69 |
+
import sys
|
| 70 |
+
path = snapshot_download("Akash212/Highlight_Generator", repo_type="space")
|
| 71 |
+
sys.path.insert(0, path)
|
| 72 |
+
from scihigh_model import SciHighExtractor
|
| 73 |
+
|
| 74 |
+
model = SciHighExtractor.from_pretrained(path)
|
| 75 |
+
print(model.predict(["<paste an abstract here>"])[0])
|
| 76 |
+
print(model.predict(["<abstract>"], budget=90, maxs=4)) # optional decoder overrides
|
| 77 |
+
```
|
| 78 |
+
|
| 79 |
+
## Files
|
| 80 |
+
|
| 81 |
+
| File | Content |
|
| 82 |
+
|---|---|
|
| 83 |
+
| `app.py` | Gradio test UI (single abstract, batch CSV, per-sentence score table) |
|
| 84 |
+
| `scihigh_model.py` | Pre-processing, features, decoder and the `SciHighExtractor` class |
|
| 85 |
+
| `config.json` | Ensemble members, decoder settings, feature order, validation scores, library versions |
|
| 86 |
+
| `clf_*.joblib` | The five fitted scikit-learn models |
|
| 87 |
+
| `tfidf.joblib`, `svd.joblib` | TF-IDF vectoriser and 32-dim SVD fitted on training sentences |
|
| 88 |
+
| `proto.npy`, `train_centroids*.npy`, `train_highlight_emb*.npy` | Embedding prototype and the retrieval index (training abstracts and their gold highlights) |
|
| 89 |
+
| `train_export.py` | Re-trains the model and writes these files |
|
| 90 |
+
| `SciHigh_2026_CPU_Hybrid.ipynb` | Full experiment notebook (16 models, ensemble selection, decoder tuning, error analysis) |
|
| 91 |
+
|
| 92 |
+
Files larger than 9.5 MB are stored as byte chunks (`name.part00.ext`, `name.part01.ext`, ...);
|
| 93 |
+
`scihigh_model.py` joins them automatically when loading.
|
| 94 |
+
|
| 95 |
+
## Reproducibility
|
| 96 |
+
|
| 97 |
+
Trained with Python 3.11.15, scikit-learn 1.8.0, numpy 2.4.4, pandas 3.0.2.
|
| 98 |
+
The `.joblib` files must be loaded with **scikit-learn 1.8.0**. They are pickle files, so Hugging Face
|
| 99 |
+
shows a security notice for them; load them only from a source you trust.
|
| 100 |
+
|
| 101 |
+
The training data (MixSub-SciHigh, provided by the FIRE 2026 organisers) is not included in this repository.
|
SciHigh_2026_CPU_Hybrid.ipynb
ADDED
|
@@ -0,0 +1,1121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "markdown",
|
| 5 |
+
"metadata": {},
|
| 6 |
+
"source": [
|
| 7 |
+
"# SciHigh 2026 - Research Highlight Generation (CPU-only)\n",
|
| 8 |
+
"\n",
|
| 9 |
+
"**Track:** FIRE 2026 SciHigh, Subtask 1 - Research Highlight Generation from MixSub abstracts.\n",
|
| 10 |
+
"\n",
|
| 11 |
+
"**Constraint:** no GPU, no VRAM. Everything below runs on CPU and system RAM.\n",
|
| 12 |
+
"\n",
|
| 13 |
+
"## Method: Supervised Extractive Ranking with Rank-Fusion and Rule-Based Restyling\n",
|
| 14 |
+
"\n",
|
| 15 |
+
"The task is reframed from *sequence generation* to *per-sentence ranking*, which is what makes a\n",
|
| 16 |
+
"CPU-only solution viable and lets classical models participate meaningfully.\n",
|
| 17 |
+
"\n",
|
| 18 |
+
"| Stage | What happens |\n",
|
| 19 |
+
"|---|---|\n",
|
| 20 |
+
"| 1 | Clean text, segment each abstract into sentences |\n",
|
| 21 |
+
"| 2 | **Greedy ROUGE oracle** labels the sentence subset that best reproduces the gold highlights |\n",
|
| 22 |
+
"| 3 | Build 31 features per sentence: position, length, lexical density, cue phrases, TF-IDF centrality, TextRank |\n",
|
| 23 |
+
"| 4 | *(Optional)* MiniLM sentence embeddings + a retrieval layer over nearest training abstracts |\n",
|
| 24 |
+
"| 5 | Train 16 models to predict sentence-worthiness; compare on F1 / AP / decoded ROUGE-L |\n",
|
| 25 |
+
"| 6 | Fuse the best 3 by **Reciprocal Rank Fusion**, deduplicate with MMR, enforce a word budget |\n",
|
| 26 |
+
"| 7 | Rewrite selected sentences into highlight register with mined surface rules |\n",
|
| 27 |
+
"| 8 | Tune the decoder by coordinate descent on validation ROUGE-L, then export test predictions |\n",
|
| 28 |
+
"\n",
|
| 29 |
+
"## Measured results (full 1,985-row validation set, CPU only)\n",
|
| 30 |
+
"\n",
|
| 31 |
+
"| System | ROUGE-1 | ROUGE-2 | ROUGE-L |\n",
|
| 32 |
+
"|---|---|---|---|\n",
|
| 33 |
+
"| Full abstract copied verbatim | 32.28 | 13.10 | 21.25 |\n",
|
| 34 |
+
"| Last 4 sentences (heuristic) | 36.48 | 13.55 | 23.07 |\n",
|
| 35 |
+
"| Fine-tuned Pegasus (FIRE 2025 winner) | - | - | 23.45 |\n",
|
| 36 |
+
"| **This pipeline** | **37.96** | **14.01** | **24.63** |\n",
|
| 37 |
+
"| Extractive oracle (upper bound) | 38.46 | 15.20 | 28.81 |\n",
|
| 38 |
+
"\n",
|
| 39 |
+
"Total runtime is roughly 3-6 minutes on a Kaggle CPU session.\n",
|
| 40 |
+
"\n",
|
| 41 |
+
"## A note on the \"90% accuracy\" target\n",
|
| 42 |
+
"\n",
|
| 43 |
+
"Accuracy is undefined for generation, and 90% is not reachable on this task under any metric that\n",
|
| 44 |
+
"the organisers rank on. The 28.81 oracle row above is the hard ceiling for *any* purely extractive\n",
|
| 45 |
+
"system: even picking the perfect sentences with hindsight tops out there. Published MixSub results\n",
|
| 46 |
+
"sit in the low 20s, and the 2025 winner took first place with 23.45.\n",
|
| 47 |
+
"\n",
|
| 48 |
+
"BERTScore F1 is the one metric that lands in the high-80s range, because it measures embedding\n",
|
| 49 |
+
"similarity rather than exact overlap. It is reported in Section 13. Treat that as the honest version\n",
|
| 50 |
+
"of the number you were aiming for, and treat ROUGE-L as the number that decides the ranking."
|
| 51 |
+
]
|
| 52 |
+
},
|
| 53 |
+
{
|
| 54 |
+
"cell_type": "markdown",
|
| 55 |
+
"metadata": {},
|
| 56 |
+
"source": [
|
| 57 |
+
"## 1. Configuration and imports"
|
| 58 |
+
]
|
| 59 |
+
},
|
| 60 |
+
{
|
| 61 |
+
"cell_type": "code",
|
| 62 |
+
"execution_count": null,
|
| 63 |
+
"metadata": {},
|
| 64 |
+
"outputs": [],
|
| 65 |
+
"source": [
|
| 66 |
+
"import os, re, sys, time, bisect, warnings, collections\n",
|
| 67 |
+
"import numpy as np, pandas as pd\n",
|
| 68 |
+
"warnings.filterwarnings(\"ignore\")\n",
|
| 69 |
+
"np.random.seed(42)\n",
|
| 70 |
+
"\n",
|
| 71 |
+
"# ---- paths: edit INPUT_DIR if your Kaggle dataset slug differs ----\n",
|
| 72 |
+
"CANDIDATES = [\n",
|
| 73 |
+
" \"/kaggle/input/mixsub-scihigh\",\n",
|
| 74 |
+
" \"/kaggle/input/scihigh-2026\",\n",
|
| 75 |
+
" \"/kaggle/input\",\n",
|
| 76 |
+
" \".\",\n",
|
| 77 |
+
"]\n",
|
| 78 |
+
"TRAIN_NAME = \"MixSub-SciHigh_train_FIRE.csv\"\n",
|
| 79 |
+
"VAL_NAME = \"MixSub-SciHigh_val_FIRE.csv\"\n",
|
| 80 |
+
"TEST_NAME = \"MixSub-SciHigh_test_FIRE(Masked).csv\"\n",
|
| 81 |
+
"\n",
|
| 82 |
+
"def find_dir():\n",
|
| 83 |
+
" for root in CANDIDATES:\n",
|
| 84 |
+
" if not os.path.isdir(root):\n",
|
| 85 |
+
" continue\n",
|
| 86 |
+
" for dirpath, _, files in os.walk(root):\n",
|
| 87 |
+
" if TRAIN_NAME in files:\n",
|
| 88 |
+
" return dirpath\n",
|
| 89 |
+
" raise FileNotFoundError(\"Could not locate \" + TRAIN_NAME + \". Set INPUT_DIR manually.\")\n",
|
| 90 |
+
"\n",
|
| 91 |
+
"INPUT_DIR = find_dir()\n",
|
| 92 |
+
"OUT_DIR = \"/kaggle/working\" if os.path.isdir(\"/kaggle/working\") else \".\"\n",
|
| 93 |
+
"print(\"input :\", INPUT_DIR)\n",
|
| 94 |
+
"print(\"output:\", OUT_DIR)\n",
|
| 95 |
+
"\n",
|
| 96 |
+
"# ---- switches ----\n",
|
| 97 |
+
"USE_EMB = True # MiniLM embeddings + retrieval layer. Needs internet ON in Kaggle settings.\n",
|
| 98 |
+
" # Falls back automatically if the model cannot be downloaded.\n",
|
| 99 |
+
"N_TRAIN = None # None = all 10,000 training rows. Set e.g. 2000 for a fast smoke test.\n",
|
| 100 |
+
"RANDOM = 42\n",
|
| 101 |
+
"\n",
|
| 102 |
+
"t0 = time.time()\n",
|
| 103 |
+
"def log(*a): print(f\"[{time.time()-t0:6.1f}s]\", *a, flush=True)"
|
| 104 |
+
]
|
| 105 |
+
},
|
| 106 |
+
{
|
| 107 |
+
"cell_type": "markdown",
|
| 108 |
+
"metadata": {},
|
| 109 |
+
"source": [
|
| 110 |
+
"### 1b. Optional packages for the extra metrics\n",
|
| 111 |
+
"\n",
|
| 112 |
+
"ROUGE runs on `rouge_score`, which Kaggle ships by default. METEOR and BERTScore need two more\n",
|
| 113 |
+
"packages. If this cell fails because internet is off, Sections 4-16 still run - only the METEOR and\n",
|
| 114 |
+
"BERTScore lines in Section 14 will be skipped."
|
| 115 |
+
]
|
| 116 |
+
},
|
| 117 |
+
{
|
| 118 |
+
"cell_type": "code",
|
| 119 |
+
"execution_count": null,
|
| 120 |
+
"metadata": {},
|
| 121 |
+
"outputs": [],
|
| 122 |
+
"source": [
|
| 123 |
+
"try:\n",
|
| 124 |
+
" import evaluate, bert_score # noqa\n",
|
| 125 |
+
" print(\"evaluate and bert_score already present\")\n",
|
| 126 |
+
"except ImportError:\n",
|
| 127 |
+
" import subprocess\n",
|
| 128 |
+
" subprocess.run([sys.executable, \"-m\", \"pip\", \"install\", \"-q\",\n",
|
| 129 |
+
" \"evaluate\", \"bert_score\", \"rouge_score\", \"nltk\"], check=False)\n",
|
| 130 |
+
" print(\"install attempted\")\n",
|
| 131 |
+
"\n",
|
| 132 |
+
"import nltk\n",
|
| 133 |
+
"for pkg in [\"punkt\", \"wordnet\", \"omw-1.4\", \"punkt_tab\"]:\n",
|
| 134 |
+
" try: nltk.download(pkg, quiet=True)\n",
|
| 135 |
+
" except Exception: pass"
|
| 136 |
+
]
|
| 137 |
+
},
|
| 138 |
+
{
|
| 139 |
+
"cell_type": "markdown",
|
| 140 |
+
"metadata": {},
|
| 141 |
+
"source": [
|
| 142 |
+
"## 2. Load data"
|
| 143 |
+
]
|
| 144 |
+
},
|
| 145 |
+
{
|
| 146 |
+
"cell_type": "code",
|
| 147 |
+
"execution_count": null,
|
| 148 |
+
"metadata": {},
|
| 149 |
+
"outputs": [],
|
| 150 |
+
"source": [
|
| 151 |
+
"train = pd.read_csv(os.path.join(INPUT_DIR, TRAIN_NAME))\n",
|
| 152 |
+
"val = pd.read_csv(os.path.join(INPUT_DIR, VAL_NAME))\n",
|
| 153 |
+
"test = pd.read_csv(os.path.join(INPUT_DIR, TEST_NAME))\n",
|
| 154 |
+
"if N_TRAIN: train = train.head(N_TRAIN)\n",
|
| 155 |
+
"\n",
|
| 156 |
+
"print(\"train\", train.shape, \"| val\", val.shape, \"| test\", test.shape)\n",
|
| 157 |
+
"print(\"columns:\", train.columns.tolist(), \"/\", test.columns.tolist())\n",
|
| 158 |
+
"train.head(2)"
|
| 159 |
+
]
|
| 160 |
+
},
|
| 161 |
+
{
|
| 162 |
+
"cell_type": "markdown",
|
| 163 |
+
"metadata": {},
|
| 164 |
+
"source": [
|
| 165 |
+
"## 3. Cleaning and sentence segmentation\n",
|
| 166 |
+
"\n",
|
| 167 |
+
"MixSub abstracts have spaces around sentence-final periods (`... crashes . Therefore ...`) and carry a\n",
|
| 168 |
+
"`None` placeholder artifact where units were stripped. Both are handled here. The segmenter is written\n",
|
| 169 |
+
"for this specific punctuation convention rather than using a generic NLTK splitter, which mis-splits\n",
|
| 170 |
+
"on the spaced periods."
|
| 171 |
+
]
|
| 172 |
+
},
|
| 173 |
+
{
|
| 174 |
+
"cell_type": "code",
|
| 175 |
+
"execution_count": null,
|
| 176 |
+
"metadata": {},
|
| 177 |
+
"outputs": [],
|
| 178 |
+
"source": [
|
| 179 |
+
"def clean(t):\n",
|
| 180 |
+
" t = str(t)\n",
|
| 181 |
+
" t = re.sub(r\"\\.\\s*None\\.\\s*\", \" \", t) # \"value . None . unit\" artifact\n",
|
| 182 |
+
" t = re.sub(r\"\\bNone\\b\", \" \", t)\n",
|
| 183 |
+
" t = re.sub(r\"\\s*\\.\\s*\\.\", \".\", t) # collapse double periods left behind\n",
|
| 184 |
+
" return re.sub(r\"\\s+\", \" \", t).strip()\n",
|
| 185 |
+
"\n",
|
| 186 |
+
"for df in (train, val, test):\n",
|
| 187 |
+
" df[\"A\"] = df[\"Abstract\"].map(clean)\n",
|
| 188 |
+
"for df in (train, val):\n",
|
| 189 |
+
" df[\"H\"] = df[\"Highlights\"].map(clean)\n",
|
| 190 |
+
"\n",
|
| 191 |
+
"def sent_split(t):\n",
|
| 192 |
+
" # split on \" . \" (MixSub style) or on \". \" followed by a capital\n",
|
| 193 |
+
" parts = re.split(r\"(?<=[A-Za-z0-9\\)\\]\\%])\\s+\\.\\s+|(?<=[a-z0-9\\)\\]\\%])\\.\\s+(?=[A-Z])\", str(t).strip())\n",
|
| 194 |
+
" out = []\n",
|
| 195 |
+
" for p in parts:\n",
|
| 196 |
+
" if not p: continue\n",
|
| 197 |
+
" p = p.strip().rstrip(\".\").strip()\n",
|
| 198 |
+
" if len(p.split()) >= 3:\n",
|
| 199 |
+
" out.append(p)\n",
|
| 200 |
+
" elif out:\n",
|
| 201 |
+
" out[-1] += \" \" + p # glue fragments onto the previous sentence\n",
|
| 202 |
+
" return out or [str(t).rstrip(\".\").strip()]\n",
|
| 203 |
+
"\n",
|
| 204 |
+
"STOP = set('''a about above after again against all also am among an and any are as at be because been before\n",
|
| 205 |
+
"being below between both but by can cannot could did do does doing during each few for from further had has\n",
|
| 206 |
+
"have having he her here hers herself him himself his how i if in into is it its itself me more most my myself\n",
|
| 207 |
+
"no nor not now of off on once only or other others our ours out over own same she should so some such than\n",
|
| 208 |
+
"that the their theirs them themselves then there these they this those through to too under until up very\n",
|
| 209 |
+
"was we were what when where which while who whom why will with would you your yours'''.split())\n",
|
| 210 |
+
"\n",
|
| 211 |
+
"TOK = re.compile(r\"[a-z0-9]+\")\n",
|
| 212 |
+
"def toks(t): return TOK.findall(str(t).lower())\n",
|
| 213 |
+
"def content(t): return [w for w in toks(t) if w not in STOP and len(w) > 2]\n",
|
| 214 |
+
"\n",
|
| 215 |
+
"ex = sent_split(train.A.iloc[1])\n",
|
| 216 |
+
"print(f\"{len(ex)} sentences from abstract #1:\")\n",
|
| 217 |
+
"for i, s in enumerate(ex): print(f\" [{i}] {s[:110]}\")"
|
| 218 |
+
]
|
| 219 |
+
},
|
| 220 |
+
{
|
| 221 |
+
"cell_type": "markdown",
|
| 222 |
+
"metadata": {},
|
| 223 |
+
"source": [
|
| 224 |
+
"## 4. Fast ROUGE utilities\n",
|
| 225 |
+
"\n",
|
| 226 |
+
"`rouge_score` is used for all reported numbers, but it is far too slow to sit inside a greedy oracle\n",
|
| 227 |
+
"loop (hundreds of thousands of calls) or a hyperparameter search. So two fast equivalents are defined:\n",
|
| 228 |
+
"\n",
|
| 229 |
+
"- `r_gain` - ROUGE-1 + ROUGE-2 F1 from `Counter` intersections, for the oracle.\n",
|
| 230 |
+
"- `fast_rl` - stemmed ROUGE-L F1 via Hunt-Szymanski LCS, for the decoder search.\n",
|
| 231 |
+
"\n",
|
| 232 |
+
"Using **F1** rather than recall in the oracle matters: recall rises monotonically as you add\n",
|
| 233 |
+
"sentences, so a recall-greedy oracle labels ~63% of all sentences positive and teaches the model\n",
|
| 234 |
+
"nothing. F1 stops on its own, giving a 38% positive rate."
|
| 235 |
+
]
|
| 236 |
+
},
|
| 237 |
+
{
|
| 238 |
+
"cell_type": "code",
|
| 239 |
+
"execution_count": null,
|
| 240 |
+
"metadata": {},
|
| 241 |
+
"outputs": [],
|
| 242 |
+
"source": [
|
| 243 |
+
"from functools import lru_cache\n",
|
| 244 |
+
"from nltk.stem.porter import PorterStemmer\n",
|
| 245 |
+
"_PS = PorterStemmer()\n",
|
| 246 |
+
"\n",
|
| 247 |
+
"@lru_cache(maxsize=500_000)\n",
|
| 248 |
+
"def _stem(w): return _PS.stem(w) if len(w) > 3 else w\n",
|
| 249 |
+
"def stoks(t): return [_stem(w) for w in TOK.findall(str(t).lower())]\n",
|
| 250 |
+
"\n",
|
| 251 |
+
"def ngrams(ws, n):\n",
|
| 252 |
+
" return collections.Counter(zip(*[ws[i:] for i in range(n)])) if len(ws) >= n else collections.Counter()\n",
|
| 253 |
+
"\n",
|
| 254 |
+
"def _f(t, nc, nr):\n",
|
| 255 |
+
" if not t: return 0.0\n",
|
| 256 |
+
" p, r = t / max(nc, 1), t / max(nr, 1)\n",
|
| 257 |
+
" return 2 * p * r / (p + r)\n",
|
| 258 |
+
"\n",
|
| 259 |
+
"def r_gain(cand_ws, ref1, ref2):\n",
|
| 260 |
+
" # ROUGE-1 F1 + ROUGE-2 F1 of a candidate token list vs precomputed reference counters\n",
|
| 261 |
+
" c1, c2 = ngrams(cand_ws, 1), ngrams(cand_ws, 2)\n",
|
| 262 |
+
" t1 = sum(min(v, c1[k]) for k, v in ref1.items())\n",
|
| 263 |
+
" t2 = sum(min(v, c2[k]) for k, v in ref2.items())\n",
|
| 264 |
+
" return _f(t1, sum(c1.values()), sum(ref1.values())) + _f(t2, sum(c2.values()), sum(ref2.values()))\n",
|
| 265 |
+
"\n",
|
| 266 |
+
"def r12f(ws, ref_ws):\n",
|
| 267 |
+
" return r_gain(ws, ngrams(ref_ws, 1), ngrams(ref_ws, 2)) / 2\n",
|
| 268 |
+
"\n",
|
| 269 |
+
"def lcs_len(a, b):\n",
|
| 270 |
+
" # Longest common subsequence length, Hunt-Szymanski. Much faster than the O(nm) DP table.\n",
|
| 271 |
+
" pos = collections.defaultdict(list)\n",
|
| 272 |
+
" for j, x in enumerate(b): pos[x].append(j)\n",
|
| 273 |
+
" tails = []\n",
|
| 274 |
+
" for x in a:\n",
|
| 275 |
+
" for j in reversed(pos.get(x, ())):\n",
|
| 276 |
+
" k = bisect.bisect_left(tails, j)\n",
|
| 277 |
+
" if k == len(tails): tails.append(j)\n",
|
| 278 |
+
" else: tails[k] = j\n",
|
| 279 |
+
" return len(tails)\n",
|
| 280 |
+
"\n",
|
| 281 |
+
"def fast_rl(pred, ref_stems):\n",
|
| 282 |
+
" p = stoks(pred)\n",
|
| 283 |
+
" if not p or not ref_stems: return 0.0\n",
|
| 284 |
+
" l = lcs_len(p, ref_stems)\n",
|
| 285 |
+
" if not l: return 0.0\n",
|
| 286 |
+
" pr, rc = l / len(p), l / len(ref_stems)\n",
|
| 287 |
+
" return 2 * pr * rc / (pr + rc)\n",
|
| 288 |
+
"\n",
|
| 289 |
+
"# sanity check that fast_rl tracks the official scorer\n",
|
| 290 |
+
"from rouge_score import rouge_scorer\n",
|
| 291 |
+
"_RS = rouge_scorer.RougeScorer([\"rouge1\", \"rouge2\", \"rougeL\"], use_stemmer=True)\n",
|
| 292 |
+
"_a, _b = val.A.iloc[0], val.H.iloc[0]\n",
|
| 293 |
+
"print(\"fast_rl %.4f\" % fast_rl(_a, stoks(_b)))\n",
|
| 294 |
+
"print(\"official %.4f\" % _RS.score(_b, _a)[\"rougeL\"].fmeasure)"
|
| 295 |
+
]
|
| 296 |
+
},
|
| 297 |
+
{
|
| 298 |
+
"cell_type": "markdown",
|
| 299 |
+
"metadata": {},
|
| 300 |
+
"source": [
|
| 301 |
+
"## 5. Greedy ROUGE oracle labelling\n",
|
| 302 |
+
"\n",
|
| 303 |
+
"For each training abstract, greedily add the sentence that most increases ROUGE-1+2 F1 against the\n",
|
| 304 |
+
"gold highlights, stopping when nothing improves. Two targets come out of this:\n",
|
| 305 |
+
"\n",
|
| 306 |
+
"- `y` - binary, is this sentence in the oracle subset (classification target)\n",
|
| 307 |
+
"- `soft` - this sentence's own ROUGE-1+2 F1 against the gold highlights (regression / ranking target)\n",
|
| 308 |
+
"\n",
|
| 309 |
+
"Documents are stored as plain Python dicts, not a DataFrame. The decoder is called thousands of times\n",
|
| 310 |
+
"during tuning, and pandas `groupby` in that inner loop was the single largest bottleneck when this was\n",
|
| 311 |
+
"first built."
|
| 312 |
+
]
|
| 313 |
+
},
|
| 314 |
+
{
|
| 315 |
+
"cell_type": "code",
|
| 316 |
+
"execution_count": null,
|
| 317 |
+
"metadata": {},
|
| 318 |
+
"outputs": [],
|
| 319 |
+
"source": [
|
| 320 |
+
"def make_docs(df, labelled, maxsel=6):\n",
|
| 321 |
+
" docs = []\n",
|
| 322 |
+
" for rec in df.itertuples():\n",
|
| 323 |
+
" S = sent_split(rec.A); n = len(S)\n",
|
| 324 |
+
" d = dict(S=S, n=n, tk=[toks(s) for s in S], cw=[set(content(s)) for s in S])\n",
|
| 325 |
+
" if labelled:\n",
|
| 326 |
+
" rw = toks(rec.H); r1, r2 = ngrams(rw, 1), ngrams(rw, 2)\n",
|
| 327 |
+
" chosen, cur, best = [], [], 0.0\n",
|
| 328 |
+
" for _ in range(min(maxsel, n)):\n",
|
| 329 |
+
" cand, cbest = None, best\n",
|
| 330 |
+
" for i in range(n):\n",
|
| 331 |
+
" if i in chosen: continue\n",
|
| 332 |
+
" sc = r_gain(cur + d[\"tk\"][i], r1, r2)\n",
|
| 333 |
+
" if sc > cbest + 1e-9: cbest, cand = sc, i\n",
|
| 334 |
+
" if cand is None: break # F1 stopped improving -> stop\n",
|
| 335 |
+
" chosen.append(cand); cur += d[\"tk\"][cand]; best = cbest\n",
|
| 336 |
+
" ch = set(chosen)\n",
|
| 337 |
+
" d[\"y\"] = [int(i in ch) for i in range(n)]\n",
|
| 338 |
+
" d[\"soft\"] = [r12f(d[\"tk\"][i], rw) for i in range(n)]\n",
|
| 339 |
+
" d[\"ref\"] = rec.H\n",
|
| 340 |
+
" d[\"refs\"] = stoks(rec.H)\n",
|
| 341 |
+
" docs.append(d)\n",
|
| 342 |
+
" return docs\n",
|
| 343 |
+
"\n",
|
| 344 |
+
"log(\"labelling (this is the slowest preprocessing step) ...\")\n",
|
| 345 |
+
"Dtr = make_docs(train, True)\n",
|
| 346 |
+
"Dva = make_docs(val, True)\n",
|
| 347 |
+
"Dte = make_docs(test, False)\n",
|
| 348 |
+
"flat = lambda ds, k: np.concatenate([d[k] for d in ds])\n",
|
| 349 |
+
"log(\"train sentences:\", sum(d[\"n\"] for d in Dtr),\n",
|
| 350 |
+
" \"| positive rate: %.3f\" % flat(Dtr, \"y\").mean(),\n",
|
| 351 |
+
" \"| mean oracle size: %.2f\" % np.mean([sum(d[\"y\"]) for d in Dtr]))"
|
| 352 |
+
]
|
| 353 |
+
},
|
| 354 |
+
{
|
| 355 |
+
"cell_type": "markdown",
|
| 356 |
+
"metadata": {},
|
| 357 |
+
"source": [
|
| 358 |
+
"## 6. Baselines\n",
|
| 359 |
+
"\n",
|
| 360 |
+
"Worth computing before modelling, so there is something to beat. Copying the whole abstract already\n",
|
| 361 |
+
"scores 21.25 ROUGE-L, and taking the last four sentences scores 23.07 - within a point of the 2025\n",
|
| 362 |
+
"winning system. Any model that cannot clear 23.07 is not earning its keep."
|
| 363 |
+
]
|
| 364 |
+
},
|
| 365 |
+
{
|
| 366 |
+
"cell_type": "code",
|
| 367 |
+
"execution_count": null,
|
| 368 |
+
"metadata": {},
|
| 369 |
+
"outputs": [],
|
| 370 |
+
"source": [
|
| 371 |
+
"def eval_all(preds, refs):\n",
|
| 372 |
+
" o = {k: [] for k in [\"rouge1\", \"rouge2\", \"rougeL\"]}\n",
|
| 373 |
+
" for p, r in zip(preds, refs):\n",
|
| 374 |
+
" s = _RS.score(r, p)\n",
|
| 375 |
+
" for k in o: o[k].append(s[k].fmeasure)\n",
|
| 376 |
+
" return {k: round(100 * float(np.mean(v)), 2) for k, v in o.items()}\n",
|
| 377 |
+
"\n",
|
| 378 |
+
"REFS = [d[\"ref\"] for d in Dva]\n",
|
| 379 |
+
"REFST = [d[\"refs\"] for d in Dva]\n",
|
| 380 |
+
"def qrl(preds): # fast stemmed ROUGE-L, used for all searching\n",
|
| 381 |
+
" return 100 * float(np.mean([fast_rl(p, r) for p, r in zip(preds, REFST)]))\n",
|
| 382 |
+
"\n",
|
| 383 |
+
"base = {\n",
|
| 384 |
+
" \"full abstract\": eval_all(val.A.tolist(), REFS),\n",
|
| 385 |
+
" \"lead-4\": eval_all([\". \".join(d[\"S\"][:4]) + \".\" for d in Dva], REFS),\n",
|
| 386 |
+
" \"last-4\": eval_all([\". \".join(d[\"S\"][-4:]) + \".\" for d in Dva], REFS),\n",
|
| 387 |
+
" \"textrank-free\": None,\n",
|
| 388 |
+
"}\n",
|
| 389 |
+
"del base[\"textrank-free\"]\n",
|
| 390 |
+
"BASE = pd.DataFrame(base).T\n",
|
| 391 |
+
"print(BASE.to_string())\n",
|
| 392 |
+
"log(\"target to beat: 23.45 (Pegasus, FIRE 2025 winner)\")"
|
| 393 |
+
]
|
| 394 |
+
},
|
| 395 |
+
{
|
| 396 |
+
"cell_type": "markdown",
|
| 397 |
+
"metadata": {},
|
| 398 |
+
"source": [
|
| 399 |
+
"## 7. Feature engineering\n",
|
| 400 |
+
"\n",
|
| 401 |
+
"31 features per sentence, in five groups.\n",
|
| 402 |
+
"\n",
|
| 403 |
+
"| Group | Features |\n",
|
| 404 |
+
"|---|---|\n",
|
| 405 |
+
"| Position | `sid`, `rel_pos`, `rel_end`, `is_first`, `is_last`, `is_last2`, `is_first2`, `nsent` |\n",
|
| 406 |
+
"| Length | `nw`, `nchar`, `rel_len`, `awlen` |\n",
|
| 407 |
+
"| Lexical | `stop_ratio`, `n_content`, `content_dens`, `n_digit`, `n_acro`, `has_pct` |\n",
|
| 408 |
+
"| Discourse | `lead` (opens with a discourse marker), `redund` (max Jaccard with earlier sentences), 6 `cue_*` counts |\n",
|
| 409 |
+
"| Graph | `tf_cent`, `tf_deg`, `textrank`, `tf_sum`, `tf_maxsim` |\n",
|
| 410 |
+
"\n",
|
| 411 |
+
"The `cue_*` families were read off the training data: `bkg` (background) is a negative indicator,\n",
|
| 412 |
+
"while `res` (results) and `conc` (conclusions) mark the sentences authors actually promote to highlights."
|
| 413 |
+
]
|
| 414 |
+
},
|
| 415 |
+
{
|
| 416 |
+
"cell_type": "code",
|
| 417 |
+
"execution_count": null,
|
| 418 |
+
"metadata": {},
|
| 419 |
+
"outputs": [],
|
| 420 |
+
"source": [
|
| 421 |
+
"CUES = {\n",
|
| 422 |
+
" \"res\": r\"\\b(result|show|showed|shown|found|find|reveal|demonstrat|indicat|observ|obtain|achiev|improv|outperform|increas|decreas|significant)\",\n",
|
| 423 |
+
" \"meth\": r\"\\b(propos|present|develop|design|introduc|novel|new |method|approach|model|framework|algorithm|technique|scheme|system|strateg)\",\n",
|
| 424 |
+
" \"purp\": r\"\\b(aim|objective|purpose|goal|investigat|examin|explor|evaluat|assess|analys|analyz)\",\n",
|
| 425 |
+
" \"bkg\": r\"\\b(previous|literature|recently|recent years|has been|have been|widely|however|although|despite|remains|little is known|few studies)\",\n",
|
| 426 |
+
" \"conc\": r\"\\b(conclu|suggest|impl|therefore|thus|hence|overall|consequently|potential|promis|can be used|may be)\",\n",
|
| 427 |
+
" \"quant\": r\"(\\d+\\.?\\d*\\s?%|p\\s?[<=]|\\bn\\s?=|\\bmean\\b|\\bmedian\\b|\\bratio\\b|\\brate\\b|fold)\",\n",
|
| 428 |
+
"}\n",
|
| 429 |
+
"LEAD_RE = (r\"^(in this (study|paper|work|article|research)|in the present|the (aim|purpose|objective|goal) of\"\n",
|
| 430 |
+
" r\"|here we|in addition|moreover|furthermore|therefore|thus|however|finally|overall|first|second\"\n",
|
| 431 |
+
" r\"|third|also|based on)\")\n",
|
| 432 |
+
"\n",
|
| 433 |
+
"from sklearn.feature_extraction.text import TfidfVectorizer\n",
|
| 434 |
+
"from sklearn.preprocessing import normalize, StandardScaler, MinMaxScaler\n",
|
| 435 |
+
"\n",
|
| 436 |
+
"def featurize(docs, tv):\n",
|
| 437 |
+
" rows = []\n",
|
| 438 |
+
" for d in docs:\n",
|
| 439 |
+
" S, n, TKs, CWs = d[\"S\"], d[\"n\"], d[\"tk\"], d[\"cw\"]\n",
|
| 440 |
+
" tw = max(sum(len(t) for t in TKs), 1)\n",
|
| 441 |
+
" X = normalize(tv.transform(S))\n",
|
| 442 |
+
" cen = (X @ normalize(np.asarray(X.mean(0))).T).ravel() # cosine to abstract centroid\n",
|
| 443 |
+
" M = (X @ X.T).toarray(); np.fill_diagonal(M, 0); deg = M.sum(1)\n",
|
| 444 |
+
" P = M / np.maximum(deg[:, None], 1e-9); pr = np.ones(n) / n\n",
|
| 445 |
+
" for _ in range(20): pr = 0.15 / n + 0.85 * (P.T @ pr) # TextRank power iteration\n",
|
| 446 |
+
" tsum = np.asarray(X.sum(1)).ravel()\n",
|
| 447 |
+
" mx = M.max(1) if n > 1 else np.zeros(n)\n",
|
| 448 |
+
" for i, s in enumerate(S):\n",
|
| 449 |
+
" sw, cw, low = TKs[i], CWs[i], s.lower()\n",
|
| 450 |
+
" nov = max((len(cw & CWs[j]) / max(len(cw | CWs[j]), 1) for j in range(i)), default=0.0)\n",
|
| 451 |
+
" f = {\"sid\": i, \"rel_pos\": i / max(n-1, 1), \"rel_end\": (n-1-i) / max(n-1, 1),\n",
|
| 452 |
+
" \"is_first\": int(i == 0), \"is_last\": int(i == n-1), \"is_last2\": int(i >= n-2),\n",
|
| 453 |
+
" \"is_first2\": int(i <= 1), \"nsent\": n, \"nw\": len(sw), \"nchar\": len(s),\n",
|
| 454 |
+
" \"rel_len\": len(sw) / tw,\n",
|
| 455 |
+
" \"awlen\": float(np.mean([len(w) for w in sw])) if sw else 0.0,\n",
|
| 456 |
+
" \"stop_ratio\": sum(1 for w in sw if w in STOP) / max(len(sw), 1),\n",
|
| 457 |
+
" \"n_content\": len(cw), \"content_dens\": len(cw) / max(len(sw), 1),\n",
|
| 458 |
+
" \"n_digit\": sum(c.isdigit() for c in s),\n",
|
| 459 |
+
" \"n_acro\": len(re.findall(r\"\\b[A-Z]{2,}\\b\", s)), \"has_pct\": int(\"%\" in s),\n",
|
| 460 |
+
" \"lead\": int(bool(re.match(LEAD_RE, low))), \"redund\": nov,\n",
|
| 461 |
+
" \"tf_cent\": cen[i], \"tf_deg\": deg[i], \"textrank\": pr[i],\n",
|
| 462 |
+
" \"tf_sum\": tsum[i], \"tf_maxsim\": mx[i]}\n",
|
| 463 |
+
" for k, pat in CUES.items():\n",
|
| 464 |
+
" f[\"cue_\" + k] = len(re.findall(pat, low))\n",
|
| 465 |
+
" rows.append(f)\n",
|
| 466 |
+
" return pd.DataFrame(rows)\n",
|
| 467 |
+
"\n",
|
| 468 |
+
"log(\"fitting TF-IDF and extracting features ...\")\n",
|
| 469 |
+
"allsent = [s for d in Dtr for s in d[\"S\"]]\n",
|
| 470 |
+
"tv = TfidfVectorizer(sublinear_tf=True, stop_words=\"english\", min_df=2).fit(allsent)\n",
|
| 471 |
+
"Ftr, Fva, Fte = featurize(Dtr, tv), featurize(Dva, tv), featurize(Dte, tv)\n",
|
| 472 |
+
"log(\"feature block:\", Ftr.shape)\n",
|
| 473 |
+
"Ftr.head(3)"
|
| 474 |
+
]
|
| 475 |
+
},
|
| 476 |
+
{
|
| 477 |
+
"cell_type": "markdown",
|
| 478 |
+
"metadata": {},
|
| 479 |
+
"source": [
|
| 480 |
+
"## 8. Optional: MiniLM embeddings and the retrieval layer\n",
|
| 481 |
+
"\n",
|
| 482 |
+
"`all-MiniLM-L6-v2` is 22M parameters and encodes about 1-2k sentences/second on CPU, so it is\n",
|
| 483 |
+
"affordable here. It contributes four features plus a 32-dimension SVD projection:\n",
|
| 484 |
+
"\n",
|
| 485 |
+
"- `e_cent` - cosine to the abstract's own embedding centroid\n",
|
| 486 |
+
"- `e_proto` - cosine to a global **highlight-style prototype** (mean embedding of training highlight sentences)\n",
|
| 487 |
+
"- `e_maxsim` - max cosine to any other sentence in the same abstract (redundancy)\n",
|
| 488 |
+
"- `e_rag` - **retrieval-augmented signal**: cosine to the mean gold-highlight embedding of the 10 nearest\n",
|
| 489 |
+
" training abstracts. This is where the k-nearest-neighbour idea earns its place - retrieving what\n",
|
| 490 |
+
" authors of *similar papers* chose to highlight.\n",
|
| 491 |
+
"\n",
|
| 492 |
+
"If Kaggle internet is off and the model cannot download, this cell degrades gracefully and the\n",
|
| 493 |
+
"pipeline continues without embeddings. The 24.63 ROUGE-L figure quoted at the top was measured\n",
|
| 494 |
+
"**without** embeddings, so treat this section as upside rather than a dependency."
|
| 495 |
+
]
|
| 496 |
+
},
|
| 497 |
+
{
|
| 498 |
+
"cell_type": "code",
|
| 499 |
+
"execution_count": null,
|
| 500 |
+
"metadata": {},
|
| 501 |
+
"outputs": [],
|
| 502 |
+
"source": [
|
| 503 |
+
"Etr = Eva = Ete = None\n",
|
| 504 |
+
"if USE_EMB:\n",
|
| 505 |
+
" try:\n",
|
| 506 |
+
" from sentence_transformers import SentenceTransformer\n",
|
| 507 |
+
" from sklearn.decomposition import TruncatedSVD\n",
|
| 508 |
+
" enc = SentenceTransformer(\"sentence-transformers/all-MiniLM-L6-v2\", device=\"cpu\")\n",
|
| 509 |
+
" emb = lambda ts: enc.encode(list(ts), batch_size=256, convert_to_numpy=True,\n",
|
| 510 |
+
" normalize_embeddings=True, show_progress_bar=False)\n",
|
| 511 |
+
" log(\"encoding sentences on CPU ...\")\n",
|
| 512 |
+
" Etr = emb(allsent)\n",
|
| 513 |
+
" Eva = emb([s for d in Dva for s in d[\"S\"]])\n",
|
| 514 |
+
" Ete = emb([s for d in Dte for s in d[\"S\"]])\n",
|
| 515 |
+
"\n",
|
| 516 |
+
" hl = [x for h in train.H for x in re.split(r\"(?<=[a-z0-9\\)\\%])\\.\\s+\", h) if len(x.split()) > 3]\n",
|
| 517 |
+
" proto = normalize(emb(hl[:4000]).mean(0).reshape(1, -1)) # highlight-style prototype\n",
|
| 518 |
+
" Hemb = emb(train.H.tolist()) # gold highlights, per train doc\n",
|
| 519 |
+
"\n",
|
| 520 |
+
" def offsets(docs):\n",
|
| 521 |
+
" o, c = [], 0\n",
|
| 522 |
+
" for d in docs: o.append((c, c + d[\"n\"])); c += d[\"n\"]\n",
|
| 523 |
+
" return o\n",
|
| 524 |
+
" Otr, Ova, Ote = offsets(Dtr), offsets(Dva), offsets(Dte)\n",
|
| 525 |
+
" cent = lambda E, O: np.vstack([normalize(E[a:b].mean(0).reshape(1, -1)) for a, b in O])\n",
|
| 526 |
+
" Ctr = cent(Etr, Otr)\n",
|
| 527 |
+
"\n",
|
| 528 |
+
" def emb_feats(E, O, is_train, k=10):\n",
|
| 529 |
+
" out = np.zeros((len(E), 4), np.float32)\n",
|
| 530 |
+
" sim = cent(E, O) @ Ctr.T\n",
|
| 531 |
+
" if is_train: np.fill_diagonal(sim, -1) # never retrieve yourself\n",
|
| 532 |
+
" nn = np.argsort(-sim, 1)[:, :k]\n",
|
| 533 |
+
" for q, (a, b) in enumerate(O):\n",
|
| 534 |
+
" X = E[a:b]\n",
|
| 535 |
+
" out[a:b, 0] = (X @ normalize(X.mean(0).reshape(1, -1)).T).ravel()\n",
|
| 536 |
+
" out[a:b, 1] = (X @ proto.T).ravel()\n",
|
| 537 |
+
" M = X @ X.T; np.fill_diagonal(M, 0)\n",
|
| 538 |
+
" out[a:b, 2] = M.max(1) if b - a > 1 else 0\n",
|
| 539 |
+
" out[a:b, 3] = (X @ normalize(Hemb[nn[q]].mean(0).reshape(1, -1)).T).ravel()\n",
|
| 540 |
+
" return pd.DataFrame(out, columns=[\"e_cent\", \"e_proto\", \"e_maxsim\", \"e_rag\"])\n",
|
| 541 |
+
"\n",
|
| 542 |
+
" svd = TruncatedSVD(32, random_state=RANDOM).fit(Etr)\n",
|
| 543 |
+
" proj = lambda M: pd.DataFrame(svd.transform(M), columns=[f\"sv{i}\" for i in range(32)])\n",
|
| 544 |
+
" Ftr = pd.concat([Ftr, emb_feats(Etr, Otr, True), proj(Etr)], axis=1)\n",
|
| 545 |
+
" Fva = pd.concat([Fva, emb_feats(Eva, Ova, False), proj(Eva)], axis=1)\n",
|
| 546 |
+
" Fte = pd.concat([Fte, emb_feats(Ete, Ote, False), proj(Ete)], axis=1)\n",
|
| 547 |
+
" log(\"embeddings added ->\", Ftr.shape)\n",
|
| 548 |
+
" except Exception as e:\n",
|
| 549 |
+
" print(\"Embeddings unavailable, continuing without them:\", type(e).__name__, e)\n",
|
| 550 |
+
" USE_EMB = False\n",
|
| 551 |
+
" Etr = Eva = Ete = None\n",
|
| 552 |
+
"\n",
|
| 553 |
+
"Xtr, Xva, Xte = [f.astype(np.float32).fillna(0) for f in (Ftr, Fva, Fte)]\n",
|
| 554 |
+
"ytr, yva = flat(Dtr, \"y\"), flat(Dva, \"y\")\n",
|
| 555 |
+
"soft = flat(Dtr, \"soft\")\n",
|
| 556 |
+
"log(\"final design matrix:\", Xtr.shape)"
|
| 557 |
+
]
|
| 558 |
+
},
|
| 559 |
+
{
|
| 560 |
+
"cell_type": "markdown",
|
| 561 |
+
"metadata": {},
|
| 562 |
+
"source": [
|
| 563 |
+
"## 9. Decoder: budget, MMR, and surface restyling\n",
|
| 564 |
+
"\n",
|
| 565 |
+
"Given a score per sentence, the decoder:\n",
|
| 566 |
+
"\n",
|
| 567 |
+
"1. takes sentences in score order, subject to a **word budget** and a cap on count;\n",
|
| 568 |
+
"2. skips any sentence whose overlap with an already-picked one exceeds `mmr` (redundancy control);\n",
|
| 569 |
+
"3. restores original document order, so the output reads coherently;\n",
|
| 570 |
+
"4. rewrites each sentence into highlight register.\n",
|
| 571 |
+
"\n",
|
| 572 |
+
"The rewrite rules were mined from the training highlights. Author-written highlights almost never\n",
|
| 573 |
+
"open with a discourse marker - they begin with `The` (2254 occurrences), `A` (755), `We` (420) - and\n",
|
| 574 |
+
"they drop hedged reporting frames. So `In this study, we found that X` becomes `X`. Measured\n",
|
| 575 |
+
"contribution of this step: **+0.24 ROUGE-L**.\n",
|
| 576 |
+
"\n",
|
| 577 |
+
"One counter-intuitive finding worth reporting in the paper: a *loose* word budget beats a tight one.\n",
|
| 578 |
+
"Gold highlights average 51 words, but constraining output to 51 words scores 20.31 ROUGE-L while\n",
|
| 579 |
+
"allowing ~110 scores 24.63. ROUGE-L F1 rewards the recall gain more than it punishes the length\n",
|
| 580 |
+
"penalty. Optimising for the metric and optimising for human-like brevity diverge here."
|
| 581 |
+
]
|
| 582 |
+
},
|
| 583 |
+
{
|
| 584 |
+
"cell_type": "code",
|
| 585 |
+
"execution_count": null,
|
| 586 |
+
"metadata": {},
|
| 587 |
+
"outputs": [],
|
| 588 |
+
"source": [
|
| 589 |
+
"DROP = re.compile(\n",
|
| 590 |
+
" r\"^(in this (study|paper|work|article|research|comment|letter|note|review|report|contribution)\"\n",
|
| 591 |
+
" r\"|in the (present|current) (study|work|paper|article|research)|in the following\"\n",
|
| 592 |
+
" r\"|the (aim|aims|purpose|objective|objectives|goal|goals) of (this|the present|the current) \"\n",
|
| 593 |
+
" r\"(study|paper|work|research|article) (was|were|is|are) to\"\n",
|
| 594 |
+
" r\"|the (present|current) (study|work|paper) (aims?|aimed|sought|seeks?)( to)?\"\n",
|
| 595 |
+
" r\"|here (we|the authors)|in addition|additionally|moreover|furthermore|therefore|thus|hence|however\"\n",
|
| 596 |
+
" r\"|nevertheless|nonetheless|meanwhile|finally|overall|consequently|accordingly|notably|importantly\"\n",
|
| 597 |
+
" r\"|first(ly)?|second(ly)?|third(ly)?|also|in conclusion|in summary|to summari[sz]e|taken together\"\n",
|
| 598 |
+
" r\"|it (was|is|has been|had been) (found|shown|observed|concluded|demonstrated|reported|noted|revealed)( that)?\"\n",
|
| 599 |
+
" r\"|we (found|find|show|showed|observe|observed|conclude|concluded|report|reported|note|noted\"\n",
|
| 600 |
+
" r\"|demonstrate|demonstrated|argue|suggest|propose)( that| with| in)?\"\n",
|
| 601 |
+
" r\"|(the|our|these|this) (results?|findings?|data|analysis|study|work) (show|shows|showed|indicate\"\n",
|
| 602 |
+
" r\"|indicated|suggest|suggests|suggested|reveal|revealed|demonstrate|demonstrated|confirm|confirmed)( that)?\"\n",
|
| 603 |
+
" r\"|(this|these) (results?|findings?) (suggest|suggests|indicate|indicates|impl(y|ies))( that)?\"\n",
|
| 604 |
+
" r\"|as (a|an) (result|consequence)|on the (other hand|contrary)|in contrast|by contrast\"\n",
|
| 605 |
+
" r\"|based on (this|these|the)( results?| findings?)?\"\n",
|
| 606 |
+
" r\"|the (results?|findings?) (of (this|the present) (study )?)?(show|showed|indicate|indicated\"\n",
|
| 607 |
+
" r\"|suggest|suggested|revealed)( that)?)\\s*[,:]?\\s*\", re.I)\n",
|
| 608 |
+
"\n",
|
| 609 |
+
"CONN = re.compile(r\"\\s+(?:and|but|whereas|while|although|though|because|since|which|that)\\s+\")\n",
|
| 610 |
+
"\n",
|
| 611 |
+
"def restyle(s, trim=0):\n",
|
| 612 |
+
" prev = None\n",
|
| 613 |
+
" while prev != s: # rules can cascade: \"However, we found that X\" -> \"X\"\n",
|
| 614 |
+
" prev = s; s = DROP.sub(\"\", s).strip()\n",
|
| 615 |
+
" s = re.sub(r\"^(and|but|that|which|to|of|in|for|with|as)\\s+\", \"\", s, flags=re.I).strip()\n",
|
| 616 |
+
" if trim and len(s.split()) > trim: # optional clause-level truncation\n",
|
| 617 |
+
" parts = CONN.split(s)\n",
|
| 618 |
+
" if len(parts) > 1:\n",
|
| 619 |
+
" acc, keep = 0, []\n",
|
| 620 |
+
" for p in parts:\n",
|
| 621 |
+
" if keep and acc + len(p.split()) > trim: break\n",
|
| 622 |
+
" keep.append(p); acc += len(p.split())\n",
|
| 623 |
+
" if keep: s = \" and \".join(keep)\n",
|
| 624 |
+
" s = re.sub(r\"\\s+\", \" \", s).strip()\n",
|
| 625 |
+
" return (s[0].upper() + s[1:]) if s else s\n",
|
| 626 |
+
"\n",
|
| 627 |
+
"def decode(docs, sc, budget=110, maxs=3, mmr=0.55, trim=0, E=None):\n",
|
| 628 |
+
" out, c = [], 0\n",
|
| 629 |
+
" for d in docs:\n",
|
| 630 |
+
" n = d[\"n\"]; s = sc[c:c+n]; base = c; c += n\n",
|
| 631 |
+
" order = list(np.argsort(-s)); pick, wc = [], 0\n",
|
| 632 |
+
" for i in order:\n",
|
| 633 |
+
" if len(pick) >= maxs: break\n",
|
| 634 |
+
" w = len(d[\"tk\"][i])\n",
|
| 635 |
+
" if wc + w > budget and pick: continue\n",
|
| 636 |
+
" if mmr < 1.0 and pick:\n",
|
| 637 |
+
" if E is not None:\n",
|
| 638 |
+
" sim = max(float(E[base+i] @ E[base+j]) for j in pick)\n",
|
| 639 |
+
" else:\n",
|
| 640 |
+
" a = d[\"cw\"][i]\n",
|
| 641 |
+
" sim = max(len(a & d[\"cw\"][j]) / max(len(a | d[\"cw\"][j]), 1) for j in pick)\n",
|
| 642 |
+
" if sim > mmr: continue\n",
|
| 643 |
+
" pick.append(i); wc += w\n",
|
| 644 |
+
" if not pick: pick = [order[0]]\n",
|
| 645 |
+
" pick.sort() # restore reading order\n",
|
| 646 |
+
" segs = [x for x in (restyle(d[\"S\"][i], trim) for i in pick) if len(x.split()) >= 3]\n",
|
| 647 |
+
" out.append((\". \".join(segs) + \".\") if segs else d[\"S\"][pick[0]] + \".\")\n",
|
| 648 |
+
" return out\n",
|
| 649 |
+
"\n",
|
| 650 |
+
"demo = \"In this study, we found that the proposed method reduces error by 12%\"\n",
|
| 651 |
+
"print(\"before:\", demo)\n",
|
| 652 |
+
"print(\"after :\", restyle(demo))"
|
| 653 |
+
]
|
| 654 |
+
},
|
| 655 |
+
{
|
| 656 |
+
"cell_type": "markdown",
|
| 657 |
+
"metadata": {},
|
| 658 |
+
"source": [
|
| 659 |
+
"## 10. Train the model bank\n",
|
| 660 |
+
"\n",
|
| 661 |
+
"Sixteen learners across four families, all CPU. Note what each family is actually doing here - none of\n",
|
| 662 |
+
"them generate text; they all score sentences.\n",
|
| 663 |
+
"\n",
|
| 664 |
+
"| Family | Members |\n",
|
| 665 |
+
"|---|---|\n",
|
| 666 |
+
"| Linear | LogReg, RidgeClassifier, LinearSVC, Ridge regression |\n",
|
| 667 |
+
"| Bayes / instance | GaussianNB, ComplementNB, KNN |\n",
|
| 668 |
+
"| Tree / ensemble | DecisionTree, RandomForest, ExtraTrees, AdaBoost, HistGBM, LightGBM |\n",
|
| 669 |
+
"| Neural / ranking | MLP, LightGBM regressor, LightGBM LambdaRank |\n",
|
| 670 |
+
"\n",
|
| 671 |
+
"KNN is fitted on a 20,000-row subsample. Brute-force neighbour search over all ~62,000 sentences\n",
|
| 672 |
+
"materialises a distance matrix larger than available RAM - this was an actual out-of-memory crash\n",
|
| 673 |
+
"during development, not a hypothetical."
|
| 674 |
+
]
|
| 675 |
+
},
|
| 676 |
+
{
|
| 677 |
+
"cell_type": "code",
|
| 678 |
+
"execution_count": null,
|
| 679 |
+
"metadata": {},
|
| 680 |
+
"outputs": [],
|
| 681 |
+
"source": [
|
| 682 |
+
"from sklearn.linear_model import LogisticRegression, RidgeClassifier, Ridge as RidgeReg\n",
|
| 683 |
+
"from sklearn.svm import LinearSVC\n",
|
| 684 |
+
"from sklearn.naive_bayes import GaussianNB, ComplementNB\n",
|
| 685 |
+
"from sklearn.neighbors import KNeighborsClassifier\n",
|
| 686 |
+
"from sklearn.tree import DecisionTreeClassifier\n",
|
| 687 |
+
"from sklearn.ensemble import (RandomForestClassifier, ExtraTreesClassifier,\n",
|
| 688 |
+
" HistGradientBoostingClassifier, AdaBoostClassifier)\n",
|
| 689 |
+
"from sklearn.neural_network import MLPClassifier\n",
|
| 690 |
+
"from sklearn.pipeline import make_pipeline\n",
|
| 691 |
+
"from sklearn.metrics import f1_score, average_precision_score\n",
|
| 692 |
+
"import lightgbm as lgb\n",
|
| 693 |
+
"\n",
|
| 694 |
+
"SC = lambda m: make_pipeline(StandardScaler(), m)\n",
|
| 695 |
+
"\n",
|
| 696 |
+
"class SubKNN:\n",
|
| 697 |
+
" # KNN on a subsample - full brute-force search over 62k sentences would exhaust RAM\n",
|
| 698 |
+
" def __init__(self, k=25, n=20000): self.k, self.n = k, n\n",
|
| 699 |
+
" def fit(self, X, y):\n",
|
| 700 |
+
" i = np.random.RandomState(RANDOM).choice(len(X), min(self.n, len(X)), replace=False)\n",
|
| 701 |
+
" self.m = SC(KNeighborsClassifier(self.k, n_jobs=1)).fit(np.asarray(X)[i], np.asarray(y)[i])\n",
|
| 702 |
+
" return self\n",
|
| 703 |
+
" def predict_proba(self, X): return self.m.predict_proba(X)\n",
|
| 704 |
+
"\n",
|
| 705 |
+
"MODELS = {\n",
|
| 706 |
+
" \"LogReg\": SC(LogisticRegression(max_iter=1000)),\n",
|
| 707 |
+
" \"Ridge\": SC(RidgeClassifier()),\n",
|
| 708 |
+
" \"LinearSVC\": SC(LinearSVC(C=0.1, max_iter=3000)),\n",
|
| 709 |
+
" \"GaussianNB\": SC(GaussianNB()),\n",
|
| 710 |
+
" \"ComplementNB\": make_pipeline(MinMaxScaler(), ComplementNB()),\n",
|
| 711 |
+
" \"KNN\": SubKNN(),\n",
|
| 712 |
+
" \"DecTree\": DecisionTreeClassifier(max_depth=8, random_state=RANDOM),\n",
|
| 713 |
+
" \"RandomForest\": RandomForestClassifier(150, min_samples_leaf=20, max_features=0.5, n_jobs=-1, random_state=RANDOM),\n",
|
| 714 |
+
" \"ExtraTrees\": ExtraTreesClassifier(150, min_samples_leaf=20, max_features=0.5, n_jobs=-1, random_state=RANDOM),\n",
|
| 715 |
+
" \"AdaBoost\": AdaBoostClassifier(n_estimators=80, random_state=RANDOM),\n",
|
| 716 |
+
" \"HistGBM\": HistGradientBoostingClassifier(max_iter=250, learning_rate=0.08, random_state=RANDOM),\n",
|
| 717 |
+
" \"MLP\": SC(MLPClassifier((96, 48), max_iter=25, early_stopping=True, random_state=RANDOM)),\n",
|
| 718 |
+
" \"LightGBM\": lgb.LGBMClassifier(n_estimators=400, learning_rate=0.06, num_leaves=63,\n",
|
| 719 |
+
" n_jobs=-1, random_state=RANDOM, verbose=-1),\n",
|
| 720 |
+
"}\n",
|
| 721 |
+
"prob = lambda m, X: (m.predict_proba(X)[:, 1] if hasattr(m, \"predict_proba\")\n",
|
| 722 |
+
" else 1 / (1 + np.exp(-m.decision_function(X))))\n",
|
| 723 |
+
"\n",
|
| 724 |
+
"res, SV, ST = {}, {}, {}\n",
|
| 725 |
+
"for name, m in MODELS.items():\n",
|
| 726 |
+
" t = time.time(); m.fit(Xtr, ytr)\n",
|
| 727 |
+
" SV[name], ST[name] = prob(m, Xva), prob(m, Xte)\n",
|
| 728 |
+
" res[name] = dict(f1=f1_score(yva, (SV[name] > .5).astype(int), zero_division=0),\n",
|
| 729 |
+
" ap=average_precision_score(yva, SV[name]), sec=round(time.time()-t, 1))\n",
|
| 730 |
+
" log(f\" {name:13s} F1={res[name]['f1']:.3f} AP={res[name]['ap']:.3f} ({res[name]['sec']}s)\")"
|
| 731 |
+
]
|
| 732 |
+
},
|
| 733 |
+
{
|
| 734 |
+
"cell_type": "markdown",
|
| 735 |
+
"metadata": {},
|
| 736 |
+
"source": [
|
| 737 |
+
"### 10b. Continuous-target and listwise heads\n",
|
| 738 |
+
"\n",
|
| 739 |
+
"Binary classification throws away information: a sentence with 0.4 ROUGE overlap and one with 0.05\n",
|
| 740 |
+
"both get label 0. These three heads use the continuous `soft` target instead, and the LambdaRank head\n",
|
| 741 |
+
"optimises the *ordering within each abstract*, which is what the decoder actually consumes."
|
| 742 |
+
]
|
| 743 |
+
},
|
| 744 |
+
{
|
| 745 |
+
"cell_type": "code",
|
| 746 |
+
"execution_count": null,
|
| 747 |
+
"metadata": {},
|
| 748 |
+
"outputs": [],
|
| 749 |
+
"source": [
|
| 750 |
+
"for name, m in {\n",
|
| 751 |
+
" \"LGBM-Reg\": lgb.LGBMRegressor(n_estimators=400, learning_rate=0.06, num_leaves=63,\n",
|
| 752 |
+
" n_jobs=-1, random_state=RANDOM, verbose=-1),\n",
|
| 753 |
+
" \"Ridge-Reg\": SC(RidgeReg()),\n",
|
| 754 |
+
"}.items():\n",
|
| 755 |
+
" t = time.time(); m.fit(Xtr, soft)\n",
|
| 756 |
+
" SV[name], ST[name] = m.predict(Xva), m.predict(Xte)\n",
|
| 757 |
+
" thr = np.quantile(SV[name], .65)\n",
|
| 758 |
+
" res[name] = dict(f1=f1_score(yva, (SV[name] > thr).astype(int), zero_division=0),\n",
|
| 759 |
+
" ap=average_precision_score(yva, SV[name]), sec=round(time.time()-t, 1))\n",
|
| 760 |
+
" log(f\" {name:13s} F1={res[name]['f1']:.3f} AP={res[name]['ap']:.3f}\")\n",
|
| 761 |
+
"\n",
|
| 762 |
+
"t = time.time()\n",
|
| 763 |
+
"rk = lgb.LGBMRanker(objective=\"lambdarank\", n_estimators=400, learning_rate=0.06, num_leaves=63,\n",
|
| 764 |
+
" n_jobs=-1, random_state=RANDOM, verbose=-1)\n",
|
| 765 |
+
"rk.fit(Xtr, np.clip((soft / max(soft.max(), 1e-9) * 4).round().astype(int), 0, 4),\n",
|
| 766 |
+
" group=[d[\"n\"] for d in Dtr])\n",
|
| 767 |
+
"SV[\"LGBM-Rank\"], ST[\"LGBM-Rank\"] = rk.predict(Xva), rk.predict(Xte)\n",
|
| 768 |
+
"thr = np.quantile(SV[\"LGBM-Rank\"], .65)\n",
|
| 769 |
+
"res[\"LGBM-Rank\"] = dict(f1=f1_score(yva, (SV[\"LGBM-Rank\"] > thr).astype(int), zero_division=0),\n",
|
| 770 |
+
" ap=average_precision_score(yva, SV[\"LGBM-Rank\"]), sec=round(time.time()-t, 1))\n",
|
| 771 |
+
"log(f\" LGBM-Rank F1={res['LGBM-Rank']['f1']:.3f} AP={res['LGBM-Rank']['ap']:.3f}\")"
|
| 772 |
+
]
|
| 773 |
+
},
|
| 774 |
+
{
|
| 775 |
+
"cell_type": "markdown",
|
| 776 |
+
"metadata": {},
|
| 777 |
+
"source": [
|
| 778 |
+
"## 11. Model comparison\n",
|
| 779 |
+
"\n",
|
| 780 |
+
"Three metrics per model. `f1` and `ap` measure sentence selection; `rougeL` runs each model's scores\n",
|
| 781 |
+
"through the decoder and measures the actual deliverable.\n",
|
| 782 |
+
"\n",
|
| 783 |
+
"Read the gap between the columns carefully - it is a result in its own right. GaussianNB has the\n",
|
| 784 |
+
"highest sentence-level F1 of any model but sits near the bottom on ROUGE-L, because F1 at a fixed 0.5\n",
|
| 785 |
+
"threshold rewards calling many sentences positive, whereas the decoder only cares about *which\n",
|
| 786 |
+
"sentence ranks first*. Selecting models on classification F1 would pick the wrong model. This is why\n",
|
| 787 |
+
"the ranking below uses decoded ROUGE-L."
|
| 788 |
+
]
|
| 789 |
+
},
|
| 790 |
+
{
|
| 791 |
+
"cell_type": "code",
|
| 792 |
+
"execution_count": null,
|
| 793 |
+
"metadata": {},
|
| 794 |
+
"outputs": [],
|
| 795 |
+
"source": [
|
| 796 |
+
"R = pd.DataFrame(res).T\n",
|
| 797 |
+
"R[\"rougeL\"] = pd.Series({n: qrl(decode(Dva, SV[n], 110, 3, .55, 0, Eva)) for n in SV})\n",
|
| 798 |
+
"R = R.sort_values(\"rougeL\", ascending=False)\n",
|
| 799 |
+
"display(R.round(3))\n",
|
| 800 |
+
"\n",
|
| 801 |
+
"import matplotlib.pyplot as plt\n",
|
| 802 |
+
"fig, ax = plt.subplots(1, 2, figsize=(15, 5.5))\n",
|
| 803 |
+
"r = R.sort_values(\"rougeL\")\n",
|
| 804 |
+
"ax[0].barh(r.index, r.rougeL, color=\"#4a6fa5\")\n",
|
| 805 |
+
"ax[0].axvline(23.45, color=\"crimson\", ls=\"--\", lw=1.5, label=\"Pegasus 2025 winner (23.45)\")\n",
|
| 806 |
+
"ax[0].axvline(BASE.loc[\"last-4\", \"rougeL\"], color=\"grey\", ls=\":\", lw=1.5,\n",
|
| 807 |
+
" label=f\"last-4 baseline ({BASE.loc['last-4','rougeL']})\")\n",
|
| 808 |
+
"ax[0].set_xlim(min(r.rougeL) - 0.6, max(r.rougeL) + 0.4)\n",
|
| 809 |
+
"ax[0].set_xlabel(\"ROUGE-L F1 (%) on validation\"); ax[0].set_title(\"Decoded ROUGE-L by model\")\n",
|
| 810 |
+
"ax[0].legend(loc=\"lower right\", fontsize=9)\n",
|
| 811 |
+
"\n",
|
| 812 |
+
"ax[1].scatter(R.f1, R.rougeL, s=55, color=\"#4a6fa5\")\n",
|
| 813 |
+
"for n in R.index:\n",
|
| 814 |
+
" ax[1].annotate(n, (R.f1[n], R.rougeL[n]), fontsize=8,\n",
|
| 815 |
+
" xytext=(4, 3), textcoords=\"offset points\")\n",
|
| 816 |
+
"ax[1].set_xlabel(\"sentence-selection F1\"); ax[1].set_ylabel(\"ROUGE-L F1 (%)\")\n",
|
| 817 |
+
"ax[1].set_title(\"Selection F1 does not predict ROUGE-L\")\n",
|
| 818 |
+
"plt.tight_layout(); plt.show()\n",
|
| 819 |
+
"\n",
|
| 820 |
+
"print(\"Pearson correlation between selection F1 and ROUGE-L: %.3f\" % R.f1.corr(R.rougeL))"
|
| 821 |
+
]
|
| 822 |
+
},
|
| 823 |
+
{
|
| 824 |
+
"cell_type": "markdown",
|
| 825 |
+
"metadata": {},
|
| 826 |
+
"source": [
|
| 827 |
+
"## 12. Reciprocal Rank Fusion\n",
|
| 828 |
+
"\n",
|
| 829 |
+
"Scores from different models are not on a comparable scale, so they are combined by **rank**, not by\n",
|
| 830 |
+
"value. Within each abstract, a sentence ranked `r` by model `m` contributes `1 / (60 + r + 1)`.\n",
|
| 831 |
+
"\n",
|
| 832 |
+
"Four candidate ensembles are compared: the top 3 overall, the top 3 with one model forced from each\n",
|
| 833 |
+
"family (diversity), the top 5, and all sixteen. Whichever wins on validation is kept."
|
| 834 |
+
]
|
| 835 |
+
},
|
| 836 |
+
{
|
| 837 |
+
"cell_type": "code",
|
| 838 |
+
"execution_count": null,
|
| 839 |
+
"metadata": {},
|
| 840 |
+
"outputs": [],
|
| 841 |
+
"source": [
|
| 842 |
+
"def fuse(docs, D, names, k=60):\n",
|
| 843 |
+
" z = np.zeros(sum(d[\"n\"] for d in docs))\n",
|
| 844 |
+
" for n in names:\n",
|
| 845 |
+
" s = D[n]; c = 0\n",
|
| 846 |
+
" for d in docs:\n",
|
| 847 |
+
" m = d[\"n\"]\n",
|
| 848 |
+
" o = np.argsort(-s[c:c+m]); rr = np.empty(m, int); rr[o] = np.arange(m)\n",
|
| 849 |
+
" z[c:c+m] += 1.0 / (k + rr + 1); c += m\n",
|
| 850 |
+
" return z\n",
|
| 851 |
+
"\n",
|
| 852 |
+
"FAM = {\n",
|
| 853 |
+
" \"linear\": [\"Ridge\", \"LogReg\", \"LinearSVC\", \"Ridge-Reg\"],\n",
|
| 854 |
+
" \"tree\": [\"RandomForest\", \"ExtraTrees\", \"DecTree\", \"AdaBoost\", \"HistGBM\", \"LightGBM\",\n",
|
| 855 |
+
" \"LGBM-Reg\", \"LGBM-Rank\"],\n",
|
| 856 |
+
" \"other\": [\"GaussianNB\", \"ComplementNB\", \"KNN\", \"MLP\"],\n",
|
| 857 |
+
"}\n",
|
| 858 |
+
"cands = {\n",
|
| 859 |
+
" \"top3-overall\": R.index[:3].tolist(),\n",
|
| 860 |
+
" \"top3-diverse\": [next(n for n in R.index if n in v) for v in FAM.values()],\n",
|
| 861 |
+
" \"top5-overall\": R.index[:5].tolist(),\n",
|
| 862 |
+
" \"all-models\": list(SV),\n",
|
| 863 |
+
"}\n",
|
| 864 |
+
"fs = {}\n",
|
| 865 |
+
"for k, v in cands.items():\n",
|
| 866 |
+
" fs[k] = qrl(decode(Dva, fuse(Dva, SV, v), 110, 3, .55, 0, Eva))\n",
|
| 867 |
+
" log(f\" {k:13s} {fs[k]:.2f} {v}\")\n",
|
| 868 |
+
"\n",
|
| 869 |
+
"SEL = cands[max(fs, key=fs.get)]\n",
|
| 870 |
+
"FZ_va = fuse(Dva, SV, SEL)\n",
|
| 871 |
+
"FZ_te = fuse(Dte, ST, SEL)\n",
|
| 872 |
+
"log(\"selected ensemble:\", max(fs, key=fs.get), \"->\", SEL)"
|
| 873 |
+
]
|
| 874 |
+
},
|
| 875 |
+
{
|
| 876 |
+
"cell_type": "markdown",
|
| 877 |
+
"metadata": {},
|
| 878 |
+
"source": [
|
| 879 |
+
"## 13. Decoder tuning by coordinate descent\n",
|
| 880 |
+
"\n",
|
| 881 |
+
"Four hyperparameters: word `budget`, max sentence count `maxs`, redundancy threshold `mmr`, and clause\n",
|
| 882 |
+
"`trim`. A full grid is 875 combinations; each requires decoding and scoring all 1,985 validation\n",
|
| 883 |
+
"documents. Coordinate descent - sweep one axis at a time, three passes - finds the same optimum in\n",
|
| 884 |
+
"roughly 3% of the evaluations."
|
| 885 |
+
]
|
| 886 |
+
},
|
| 887 |
+
{
|
| 888 |
+
"cell_type": "code",
|
| 889 |
+
"execution_count": null,
|
| 890 |
+
"metadata": {},
|
| 891 |
+
"outputs": [],
|
| 892 |
+
"source": [
|
| 893 |
+
"cfg = dict(budget=110, maxs=3, mmr=0.55, trim=0)\n",
|
| 894 |
+
"GRID = dict(budget=[70, 90, 110, 130, 150, 180, 250],\n",
|
| 895 |
+
" maxs=[3, 4, 5, 6, 7],\n",
|
| 896 |
+
" mmr=[0.55, 0.65, 0.75, 0.85, 1.0],\n",
|
| 897 |
+
" trim=[0, 18, 24, 30, 40])\n",
|
| 898 |
+
"best = qrl(decode(Dva, FZ_va, **cfg, E=Eva))\n",
|
| 899 |
+
"log(\"start %.3f\" % best, cfg)\n",
|
| 900 |
+
"for sweep in range(3):\n",
|
| 901 |
+
" for k, vals in GRID.items():\n",
|
| 902 |
+
" for v in vals:\n",
|
| 903 |
+
" c2 = dict(cfg); c2[k] = v\n",
|
| 904 |
+
" s = qrl(decode(Dva, FZ_va, **c2, E=Eva))\n",
|
| 905 |
+
" if s > best + 1e-6: best, cfg = s, c2\n",
|
| 906 |
+
" log(f\" after sweep {sweep+1}: %.3f\" % best, cfg)\n",
|
| 907 |
+
"log(\"tuned config:\", cfg)"
|
| 908 |
+
]
|
| 909 |
+
},
|
| 910 |
+
{
|
| 911 |
+
"cell_type": "markdown",
|
| 912 |
+
"metadata": {},
|
| 913 |
+
"source": [
|
| 914 |
+
"## 14. Full evaluation on validation\n",
|
| 915 |
+
"\n",
|
| 916 |
+
"All five metrics the organisers named. METEOR and BERTScore are wrapped in `try` blocks so a missing\n",
|
| 917 |
+
"package cannot cost you the ROUGE numbers.\n",
|
| 918 |
+
"\n",
|
| 919 |
+
"BERTScore is the metric that reaches the high-80s. It is computed against `roberta-large` by default,\n",
|
| 920 |
+
"which is slow on CPU - `distilbert-base-uncased` is used here instead and is honest to report as long\n",
|
| 921 |
+
"as the model is named in the paper."
|
| 922 |
+
]
|
| 923 |
+
},
|
| 924 |
+
{
|
| 925 |
+
"cell_type": "code",
|
| 926 |
+
"execution_count": null,
|
| 927 |
+
"metadata": {},
|
| 928 |
+
"outputs": [],
|
| 929 |
+
"source": [
|
| 930 |
+
"pred_va = decode(Dva, FZ_va, **cfg, E=Eva)\n",
|
| 931 |
+
"\n",
|
| 932 |
+
"final = {\n",
|
| 933 |
+
" \"full abstract\": eval_all(val.A.tolist(), REFS),\n",
|
| 934 |
+
" \"last-4\": eval_all([\". \".join(d[\"S\"][-4:]) + \".\" for d in Dva], REFS),\n",
|
| 935 |
+
" f\"best single ({R.index[0]})\": eval_all(decode(Dva, SV[R.index[0]], **cfg, E=Eva), REFS),\n",
|
| 936 |
+
" \"FUSED (submitted)\": eval_all(pred_va, REFS),\n",
|
| 937 |
+
"}\n",
|
| 938 |
+
"T = pd.DataFrame(final).T\n",
|
| 939 |
+
"T.loc[\"Pegasus 2025 winner\"] = [np.nan, np.nan, 23.45]\n",
|
| 940 |
+
"print(T.to_string()); print()\n",
|
| 941 |
+
"\n",
|
| 942 |
+
"try:\n",
|
| 943 |
+
" import evaluate\n",
|
| 944 |
+
" met = evaluate.load(\"meteor\")\n",
|
| 945 |
+
" print(\"METEOR : %.2f\" % (100 * met.compute(predictions=pred_va, references=REFS)[\"meteor\"]))\n",
|
| 946 |
+
"except Exception as e:\n",
|
| 947 |
+
" print(\"METEOR skipped:\", type(e).__name__, e)\n",
|
| 948 |
+
"\n",
|
| 949 |
+
"try:\n",
|
| 950 |
+
" from bert_score import score as bscore\n",
|
| 951 |
+
" P, Rc, F = bscore(pred_va, REFS, model_type=\"distilbert-base-uncased\",\n",
|
| 952 |
+
" lang=\"en\", device=\"cpu\", batch_size=32, verbose=False)\n",
|
| 953 |
+
" print(\"BERTScore F1: %.2f (distilbert-base-uncased, CPU)\" % (100 * F.mean().item()))\n",
|
| 954 |
+
"except Exception as e:\n",
|
| 955 |
+
" print(\"BERTScore skipped:\", type(e).__name__, e)\n",
|
| 956 |
+
"\n",
|
| 957 |
+
"print(\"\\nlength: predicted %.1f words | gold %.1f words\"\n",
|
| 958 |
+
" % (np.mean([len(p.split()) for p in pred_va]), np.mean([len(r.split()) for r in REFS])))"
|
| 959 |
+
]
|
| 960 |
+
},
|
| 961 |
+
{
|
| 962 |
+
"cell_type": "markdown",
|
| 963 |
+
"metadata": {},
|
| 964 |
+
"source": [
|
| 965 |
+
"## 15. Error analysis: hallucination and factual consistency\n",
|
| 966 |
+
"\n",
|
| 967 |
+
"The task description asks participants to analyse hallucination and factual inconsistency. This\n",
|
| 968 |
+
"architecture has a structural answer, and it is the strongest argument in its favour for the paper.\n",
|
| 969 |
+
"\n",
|
| 970 |
+
"Because every output token is copied from the source abstract, **novel-token hallucination is zero by\n",
|
| 971 |
+
"construction**. An abstractive model such as Pegasus cannot make that guarantee - it invents numbers,\n",
|
| 972 |
+
"swaps entities, and reverses polarity, and each of those failures needs manual auditing.\n",
|
| 973 |
+
"\n",
|
| 974 |
+
"The trade-off is measurable and should be stated plainly: 38.7% of gold highlight unigrams and 76.5%\n",
|
| 975 |
+
"of gold bigrams do not appear in the source abstract. Authors genuinely paraphrase. So extraction\n",
|
| 976 |
+
"buys perfect factual grounding at the cost of never reaching the oracle ceiling of 28.81. The cells\n",
|
| 977 |
+
"below quantify both sides."
|
| 978 |
+
]
|
| 979 |
+
},
|
| 980 |
+
{
|
| 981 |
+
"cell_type": "code",
|
| 982 |
+
"execution_count": null,
|
| 983 |
+
"metadata": {},
|
| 984 |
+
"outputs": [],
|
| 985 |
+
"source": [
|
| 986 |
+
"def novel_rate(preds, srcs, n=1):\n",
|
| 987 |
+
" out = []\n",
|
| 988 |
+
" for p, s in zip(preds, srcs):\n",
|
| 989 |
+
" pg, sg = ngrams(toks(p), n), set(ngrams(toks(s), n))\n",
|
| 990 |
+
" if sum(pg.values()) == 0: continue\n",
|
| 991 |
+
" out.append(sum(v for k, v in pg.items() if k not in sg) / sum(pg.values()))\n",
|
| 992 |
+
" return 100 * float(np.mean(out))\n",
|
| 993 |
+
"\n",
|
| 994 |
+
"srcs = val.A.tolist()\n",
|
| 995 |
+
"print(\"HALLUCINATION AUDIT (novel n-grams not present in the source abstract)\")\n",
|
| 996 |
+
"print(\" unigram bigram\")\n",
|
| 997 |
+
"print(\" our predictions %6.2f%% %6.2f%%\" % (novel_rate(pred_va, srcs, 1), novel_rate(pred_va, srcs, 2)))\n",
|
| 998 |
+
"print(\" gold highlights %6.2f%% %6.2f%%\" % (novel_rate(REFS, srcs, 1), novel_rate(REFS, srcs, 2)))\n",
|
| 999 |
+
"print()\n",
|
| 1000 |
+
"print(\" Non-zero unigram novelty in our output comes only from the restyling rules\")\n",
|
| 1001 |
+
"print(\" (capitalisation and clause joining), never from invented content.\")\n",
|
| 1002 |
+
"\n",
|
| 1003 |
+
"num = re.compile(r\"\\d+(?:\\.\\d+)?\") # do not swallow a sentence-final period\n",
|
| 1004 |
+
"# substring containment, not set equality: the segmenter can split \"12.5\" across two sentences,\n",
|
| 1005 |
+
"# which a set-based test would wrongly flag as a fabricated number\n",
|
| 1006 |
+
"bad = [i for i, (p_, s_) in enumerate(zip(pred_va, srcs))\n",
|
| 1007 |
+
" if not all(v in s_ for v in num.findall(p_))]\n",
|
| 1008 |
+
"print(\"\\n numeric values in output not traceable to the source: %d / %d documents\" % (len(bad), len(pred_va)))\n",
|
| 1009 |
+
"if bad:\n",
|
| 1010 |
+
" print(\" (inspect these - expected to be 0 for a purely extractive system)\")\n",
|
| 1011 |
+
"\n",
|
| 1012 |
+
"print(\"\\n\" + \"=\"*100)\n",
|
| 1013 |
+
"print(\"WORST 3 PREDICTIONS BY ROUGE-L (inspect these before writing the error-analysis section)\")\n",
|
| 1014 |
+
"print(\"=\"*100)\n",
|
| 1015 |
+
"sc_each = np.array([fast_rl(p, r) for p, r in zip(pred_va, REFST)])\n",
|
| 1016 |
+
"for i in np.argsort(sc_each)[:3]:\n",
|
| 1017 |
+
" print(f\"\\n--- doc {i} ROUGE-L {100*sc_each[i]:.1f} ---\")\n",
|
| 1018 |
+
" print(\"PRED:\", pred_va[i][:340])\n",
|
| 1019 |
+
" print(\"GOLD:\", REFS[i][:340])"
|
| 1020 |
+
]
|
| 1021 |
+
},
|
| 1022 |
+
{
|
| 1023 |
+
"cell_type": "markdown",
|
| 1024 |
+
"metadata": {},
|
| 1025 |
+
"source": [
|
| 1026 |
+
"## 16. Generate test predictions and write the submission file"
|
| 1027 |
+
]
|
| 1028 |
+
},
|
| 1029 |
+
{
|
| 1030 |
+
"cell_type": "code",
|
| 1031 |
+
"execution_count": null,
|
| 1032 |
+
"metadata": {},
|
| 1033 |
+
"outputs": [],
|
| 1034 |
+
"source": [
|
| 1035 |
+
"pred_te = decode(Dte, FZ_te, **cfg, E=Ete)\n",
|
| 1036 |
+
"\n",
|
| 1037 |
+
"sub = pd.DataFrame({\"Filename\": test[\"Filename\"].values, \"Highlights\": pred_te})\n",
|
| 1038 |
+
"assert len(sub) == len(test), \"row count mismatch\"\n",
|
| 1039 |
+
"assert sub.Highlights.astype(str).str.len().min() > 0, \"empty prediction found\"\n",
|
| 1040 |
+
"\n",
|
| 1041 |
+
"path = os.path.join(OUT_DIR, \"submission.csv\")\n",
|
| 1042 |
+
"sub.to_csv(path, index=False)\n",
|
| 1043 |
+
"log(\"wrote\", path, sub.shape)\n",
|
| 1044 |
+
"\n",
|
| 1045 |
+
"print(\"\\nsentences per highlight: %.2f | words per highlight: %.1f\"\n",
|
| 1046 |
+
" % (sub.Highlights.str.count(r\"\\.\").mean(), sub.Highlights.str.split().str.len().mean()))\n",
|
| 1047 |
+
"display(sub.head(3))\n",
|
| 1048 |
+
"print(\"\\nEXAMPLE\\n\" + \"-\"*90)\n",
|
| 1049 |
+
"print(\"ABSTRACT:\", test.A.iloc[0][:420], \"...\")\n",
|
| 1050 |
+
"print(\"\\nGENERATED HIGHLIGHTS:\", pred_te[0])"
|
| 1051 |
+
]
|
| 1052 |
+
},
|
| 1053 |
+
{
|
| 1054 |
+
"cell_type": "markdown",
|
| 1055 |
+
"metadata": {},
|
| 1056 |
+
"source": [
|
| 1057 |
+
"## 17. Reproducibility record"
|
| 1058 |
+
]
|
| 1059 |
+
},
|
| 1060 |
+
{
|
| 1061 |
+
"cell_type": "code",
|
| 1062 |
+
"execution_count": null,
|
| 1063 |
+
"metadata": {},
|
| 1064 |
+
"outputs": [],
|
| 1065 |
+
"source": [
|
| 1066 |
+
"summary = pd.DataFrame({\n",
|
| 1067 |
+
" \"setting\": [\"train rows\", \"train sentences\", \"features\", \"embeddings used\",\n",
|
| 1068 |
+
" \"ensemble members\", \"budget\", \"max sentences\", \"mmr threshold\", \"clause trim\",\n",
|
| 1069 |
+
" \"val ROUGE-1\", \"val ROUGE-2\", \"val ROUGE-L\", \"target to beat\", \"runtime (s)\"],\n",
|
| 1070 |
+
" \"value\": [len(train), sum(d[\"n\"] for d in Dtr), Xtr.shape[1], USE_EMB,\n",
|
| 1071 |
+
" \", \".join(SEL), cfg[\"budget\"], cfg[\"maxs\"], cfg[\"mmr\"], cfg[\"trim\"],\n",
|
| 1072 |
+
" final[\"FUSED (submitted)\"][\"rouge1\"], final[\"FUSED (submitted)\"][\"rouge2\"],\n",
|
| 1073 |
+
" final[\"FUSED (submitted)\"][\"rougeL\"], 23.45, round(time.time()-t0, 1)],\n",
|
| 1074 |
+
"})\n",
|
| 1075 |
+
"display(summary)\n",
|
| 1076 |
+
"summary.to_csv(os.path.join(OUT_DIR, \"run_summary.csv\"), index=False)\n",
|
| 1077 |
+
"R.round(4).to_csv(os.path.join(OUT_DIR, \"model_comparison.csv\"))\n",
|
| 1078 |
+
"print(\"saved run_summary.csv and model_comparison.csv\")"
|
| 1079 |
+
]
|
| 1080 |
+
},
|
| 1081 |
+
{
|
| 1082 |
+
"cell_type": "markdown",
|
| 1083 |
+
"metadata": {},
|
| 1084 |
+
"source": [
|
| 1085 |
+
"## 18. Where to go next\n",
|
| 1086 |
+
"\n",
|
| 1087 |
+
"Ranked by expected gain per unit of effort, all still CPU-only.\n",
|
| 1088 |
+
"\n",
|
| 1089 |
+
"| Idea | Rationale | Expected |\n",
|
| 1090 |
+
"|---|---|---|\n",
|
| 1091 |
+
"| Clause-level candidates instead of sentences | Oracle ceiling rises from 28.81 to 30.00, and the precision penalty on long sentences drops | +0.3 to +0.8 |\n",
|
| 1092 |
+
"| Sentence-pair cross-encoder reranker on the top 5 | A small MiniLM cross-encoder reranks candidates with full context rather than isolated features | +0.5 to +1.0 |\n",
|
| 1093 |
+
"| Per-document adaptive `maxs` | Predict the highlight count from abstract length instead of fixing it at 3 | +0.2 to +0.5 |\n",
|
| 1094 |
+
"| Learn the restyling rules | Mine abstract-to-highlight edit pairs from training data rather than hand-writing the regex | +0.3 to +0.6 |\n",
|
| 1095 |
+
"| T5-small rewriter over selected sentences | Genuine abstraction; closes part of the 38.7% novel-unigram gap. Costs 3-5 hours CPU training and may score *lower* than extraction, so keep it as a separate track | uncertain |\n",
|
| 1096 |
+
"\n",
|
| 1097 |
+
"For the paper, three findings are worth foregrounding beyond the score itself:\n",
|
| 1098 |
+
"\n",
|
| 1099 |
+
"1. **Sentence-selection F1 does not predict ROUGE-L** (correlation printed in Section 11). Selecting\n",
|
| 1100 |
+
" models by classification metrics picks the wrong model.\n",
|
| 1101 |
+
"2. **Loose word budgets beat faithful ones.** Matching the gold 51-word length costs nearly 4 ROUGE-L\n",
|
| 1102 |
+
" points versus a 110-word budget. The ranking metric and human brevity pull in opposite directions.\n",
|
| 1103 |
+
"3. **Zero-hallucination is structural here, not incidental** - and the 38.7% novel-unigram figure\n",
|
| 1104 |
+
" quantifies exactly what that guarantee costs you."
|
| 1105 |
+
]
|
| 1106 |
+
}
|
| 1107 |
+
],
|
| 1108 |
+
"metadata": {
|
| 1109 |
+
"kernelspec": {
|
| 1110 |
+
"display_name": "Python 3",
|
| 1111 |
+
"language": "python",
|
| 1112 |
+
"name": "python3"
|
| 1113 |
+
},
|
| 1114 |
+
"language_info": {
|
| 1115 |
+
"name": "python",
|
| 1116 |
+
"version": "3.10.12"
|
| 1117 |
+
}
|
| 1118 |
+
},
|
| 1119 |
+
"nbformat": 4,
|
| 1120 |
+
"nbformat_minor": 5
|
| 1121 |
+
}
|
app.py
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Gradio test UI for the SciHigh 2026 extractive highlight generator.
|
| 3 |
+
Runs on CPU. On ZeroGPU hardware the handlers are wrapped with @spaces.GPU (required by ZeroGPU),
|
| 4 |
+
but the model itself still runs on CPU.
|
| 5 |
+
"""
|
| 6 |
+
import os, tempfile
|
| 7 |
+
import numpy as np, pandas as pd
|
| 8 |
+
import gradio as gr
|
| 9 |
+
from scihigh_model import SciHighExtractor, clean
|
| 10 |
+
|
| 11 |
+
try:
|
| 12 |
+
import spaces
|
| 13 |
+
GPU_SHORT, GPU_LONG = spaces.GPU(duration=30), spaces.GPU(duration=120)
|
| 14 |
+
except Exception:
|
| 15 |
+
GPU_SHORT = GPU_LONG = (lambda f: f)
|
| 16 |
+
|
| 17 |
+
HERE = os.path.dirname(os.path.abspath(__file__))
|
| 18 |
+
MODEL = SciHighExtractor.from_pretrained(HERE, encoder=os.environ.get("SCIHIGH_ENCODER")) # optional local encoder path
|
| 19 |
+
MODEL.predict(["This warm-up sentence loads the encoder once. It keeps the first request fast. It has no other use."])
|
| 20 |
+
CFG, VAL = MODEL.config["decoder"], MODEL.config["validation_scores"]
|
| 21 |
+
MAX_ROWS = 1000
|
| 22 |
+
|
| 23 |
+
try:
|
| 24 |
+
from rouge_score import rouge_scorer
|
| 25 |
+
RS = rouge_scorer.RougeScorer(["rouge1", "rouge2", "rougeL"], use_stemmer=True)
|
| 26 |
+
except Exception:
|
| 27 |
+
RS = None
|
| 28 |
+
|
| 29 |
+
EXAMPLES = [
|
| 30 |
+
"Urban heat islands raise night-time temperatures in dense cities and increase heat-related illness . "
|
| 31 |
+
"Previous studies have mostly relied on satellite land surface temperature , which does not capture air temperature at street level . "
|
| 32 |
+
"In this study , we deployed 120 low-cost sensors across three neighbourhoods of Chennai for twelve months . "
|
| 33 |
+
"A gradient boosting model was trained to predict street-level air temperature from land cover , building height and sky view factor . "
|
| 34 |
+
"The model achieved a mean absolute error of 0.42 degrees Celsius on held-out sensors . "
|
| 35 |
+
"Tree canopy cover above 30 % reduced peak night-time temperature by up to 1.8 degrees Celsius . "
|
| 36 |
+
"These results suggest that targeted street planting can lower heat exposure more than rooftop albedo changes .",
|
| 37 |
+
|
| 38 |
+
"Lithium-ion battery degradation limits the service life of electric vehicles . "
|
| 39 |
+
"Accurate estimation of remaining useful life remains difficult because degradation depends on temperature , load and charging habits . "
|
| 40 |
+
"We propose a hybrid framework that couples an equivalent circuit model with a temporal convolutional network . "
|
| 41 |
+
"The physical model supplies interpretable health indicators , while the network learns the residual degradation trend . "
|
| 42 |
+
"Experiments on 124 commercial cells show that the framework reduces prediction error by 27 % compared with purely data-driven baselines . "
|
| 43 |
+
"The method also requires only the first 100 cycles of data to reach stable predictions . "
|
| 44 |
+
"The proposed approach can support early warranty decisions and second-life battery grading .",
|
| 45 |
+
|
| 46 |
+
"Early detection of diabetic retinopathy can prevent vision loss , but specialist screening is scarce in rural clinics . "
|
| 47 |
+
"The aim of this study was to evaluate a lightweight deep learning model that runs on a smartphone . "
|
| 48 |
+
"A total of 8,412 fundus images from four hospitals were used for training and external validation . "
|
| 49 |
+
"The model detected referable retinopathy with a sensitivity of 93.1 % and a specificity of 90.4 % . "
|
| 50 |
+
"Inference took less than one second per image on a mid-range phone without internet access . "
|
| 51 |
+
"Performance was consistent across camera types and patient age groups . "
|
| 52 |
+
"Smartphone-based screening may therefore extend retinopathy screening to underserved populations .",
|
| 53 |
+
]
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def bullets(text):
|
| 57 |
+
parts = [p.strip().rstrip(".") for p in text.split(". ") if p.strip()]
|
| 58 |
+
return "\n".join(f"- {p}." for p in parts)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
@GPU_SHORT
|
| 62 |
+
def run_single(abstract, budget, maxs, mmr):
|
| 63 |
+
if not abstract or len(abstract.split()) < 10:
|
| 64 |
+
raise gr.Error("Please paste an abstract of at least a few sentences.")
|
| 65 |
+
text, table = MODEL.explain(abstract, budget=int(budget), maxs=int(maxs), mmr=float(mmr))
|
| 66 |
+
n = len(table)
|
| 67 |
+
info = (f"{n} sentences found, {int((table['picked'] == 'yes').sum())} selected. "
|
| 68 |
+
f"Output length: {len(text.split())} words.")
|
| 69 |
+
return bullets(text), text, info, table
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
@GPU_LONG
|
| 73 |
+
def run_batch(file, budget, maxs, mmr):
|
| 74 |
+
if file is None:
|
| 75 |
+
raise gr.Error("Upload a CSV file first.")
|
| 76 |
+
path = file if isinstance(file, str) else file.name
|
| 77 |
+
df = pd.read_csv(path)
|
| 78 |
+
col = next((c for c in df.columns if c.lower() == "abstract"), None)
|
| 79 |
+
if col is None:
|
| 80 |
+
raise gr.Error(f"No 'Abstract' column found. Columns in the file: {list(df.columns)}")
|
| 81 |
+
note = ""
|
| 82 |
+
if len(df) > MAX_ROWS:
|
| 83 |
+
note = f"Only the first {MAX_ROWS} of {len(df)} rows were processed. "
|
| 84 |
+
df = df.head(MAX_ROWS)
|
| 85 |
+
preds = MODEL.predict(df[col].astype(str).tolist(), budget=int(budget), maxs=int(maxs), mmr=float(mmr))
|
| 86 |
+
out = pd.DataFrame({"Filename": df["Filename"] if "Filename" in df.columns else np.arange(len(df)),
|
| 87 |
+
"Highlights": preds})
|
| 88 |
+
gold = next((c for c in df.columns if c.lower() == "highlights"), None)
|
| 89 |
+
if gold is not None and RS is not None:
|
| 90 |
+
sc = {k: [] for k in ["rouge1", "rouge2", "rougeL"]}
|
| 91 |
+
for p, r in zip(preds, df[gold].astype(str).map(clean)):
|
| 92 |
+
s = RS.score(r, p)
|
| 93 |
+
for k in sc: sc[k].append(s[k].fmeasure)
|
| 94 |
+
note += ("ROUGE against the file's Highlights column: " +
|
| 95 |
+
", ".join(f"{k.upper()} {100 * np.mean(v):.2f}" for k, v in sc.items()) + ".")
|
| 96 |
+
elif gold is not None:
|
| 97 |
+
note += "The file has a Highlights column, but rouge_score is not installed, so no scores were computed."
|
| 98 |
+
tmp = os.path.join(tempfile.mkdtemp(), "highlights.csv")
|
| 99 |
+
out.to_csv(tmp, index=False)
|
| 100 |
+
return out.head(50), tmp, note or f"Processed {len(df)} abstracts."
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
ABOUT = f"""
|
| 104 |
+
### How it works
|
| 105 |
+
1. The abstract is cleaned and split into sentences.
|
| 106 |
+
2. Each sentence gets 67 features: 31 hand-built (position, length, lexical density, discourse cues, TF-IDF centrality, TextRank)
|
| 107 |
+
and 36 from `all-MiniLM-L6-v2` embeddings, including a retrieval feature from the 10 most similar training abstracts.
|
| 108 |
+
3. Five classifiers ({", ".join(MODEL.config["ensemble"])}) score every sentence. Their rankings are merged with Reciprocal Rank Fusion (k = {MODEL.config["rrf_k"]}).
|
| 109 |
+
4. The decoder takes the top sentences under a word budget, skips near-duplicates (MMR), restores reading order,
|
| 110 |
+
and removes reporting phrases such as "In this study, we found that".
|
| 111 |
+
|
| 112 |
+
Because every word comes from the abstract, the system cannot invent facts or numbers.
|
| 113 |
+
|
| 114 |
+
### Validation scores (MixSub-SciHigh validation set, {MODEL.config.get("validation_docs", 1985)} abstracts)
|
| 115 |
+
ROUGE-1 {VAL["rouge1"]} | ROUGE-2 {VAL["rouge2"]} | ROUGE-L {VAL["rougeL"]}
|
| 116 |
+
|
| 117 |
+
Default decoder settings: budget {CFG["budget"]} words, at most {CFG["maxs"]} sentences, MMR threshold {CFG["mmr"]}.
|
| 118 |
+
"""
|
| 119 |
+
|
| 120 |
+
with gr.Blocks(title="SciHigh 2026 Highlight Generator") as demo:
|
| 121 |
+
gr.Markdown("# SciHigh 2026: Research Highlight Generator\n"
|
| 122 |
+
"FIRE 2026 SciHigh, Subtask 1. Paste a scientific abstract and the model extracts its research highlights. "
|
| 123 |
+
f"Validation ROUGE-L: **{VAL['rougeL']}**.")
|
| 124 |
+
with gr.Accordion("Decoder settings (defaults are the tuned values)", open=False):
|
| 125 |
+
with gr.Row():
|
| 126 |
+
budget = gr.Slider(40, 250, value=CFG["budget"], step=10, label="Word budget")
|
| 127 |
+
maxs = gr.Slider(1, 7, value=CFG["maxs"], step=1, label="Max sentences")
|
| 128 |
+
mmr = gr.Slider(0.5, 1.0, value=CFG["mmr"], step=0.05, label="Redundancy threshold (1.0 = off)")
|
| 129 |
+
|
| 130 |
+
with gr.Tab("Single abstract"):
|
| 131 |
+
with gr.Row():
|
| 132 |
+
with gr.Column():
|
| 133 |
+
abstract = gr.Textbox(label="Abstract", lines=12, placeholder="Paste an abstract here ...")
|
| 134 |
+
with gr.Row():
|
| 135 |
+
clear = gr.Button("Clear")
|
| 136 |
+
go = gr.Button("Generate highlights", variant="primary")
|
| 137 |
+
gr.Examples(EXAMPLES, inputs=abstract, label="Example abstracts (written for this demo)")
|
| 138 |
+
with gr.Column():
|
| 139 |
+
gr.Markdown("### Highlights")
|
| 140 |
+
out_md = gr.Markdown()
|
| 141 |
+
out_txt = gr.Textbox(label="Highlights as one string (submission format)", lines=4)
|
| 142 |
+
info = gr.Markdown()
|
| 143 |
+
table = gr.Dataframe(label="How each sentence was scored: rank = fused rank (1 is best); model columns are probabilities",
|
| 144 |
+
wrap=True, column_widths=["4%", "7%", "6%", "48%", "7%", "6%", "5%", "5%", "5%", "7%"])
|
| 145 |
+
go.click(run_single, [abstract, budget, maxs, mmr], [out_md, out_txt, info, table])
|
| 146 |
+
clear.click(lambda: ("", "", "", "", None), None, [abstract, out_md, out_txt, info, table])
|
| 147 |
+
|
| 148 |
+
with gr.Tab("Batch (CSV)"):
|
| 149 |
+
gr.Markdown(f"Upload a CSV with an `Abstract` column (for example the MixSub validation or test file). "
|
| 150 |
+
f"If it also has a `Highlights` column, ROUGE scores are computed. Up to {MAX_ROWS} rows.")
|
| 151 |
+
with gr.Row():
|
| 152 |
+
csv_in = gr.File(label="CSV file", file_types=[".csv"])
|
| 153 |
+
with gr.Column():
|
| 154 |
+
run_b = gr.Button("Run on file", variant="primary")
|
| 155 |
+
note = gr.Markdown()
|
| 156 |
+
csv_out = gr.File(label="Download highlights.csv")
|
| 157 |
+
preview = gr.Dataframe(label="First 50 predictions", wrap=True)
|
| 158 |
+
run_b.click(run_batch, [csv_in, budget, maxs, mmr], [preview, csv_out, note])
|
| 159 |
+
|
| 160 |
+
with gr.Tab("About"):
|
| 161 |
+
gr.Markdown(ABOUT)
|
| 162 |
+
|
| 163 |
+
if __name__ == "__main__":
|
| 164 |
+
demo.queue().launch()
|
clf_ExtraTrees.part00.joblib
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:b6ac9e131a3b3513a4d96b4d118e4db8e6d1faa29c493cf432a9e2244441d6e3
|
| 3 |
+
size 9500000
|
clf_ExtraTrees.part01.joblib
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:8b06ea3540b9ecdeb661ea454a630812574518f397d6426b64ebd97e4332aaed
|
| 3 |
+
size 6159104
|
clf_LinearSVC.joblib
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:41bf26bae12a1fa35f36d5120097791999b1c661def6657bb9e914883bd7e872
|
| 3 |
+
size 3250
|
clf_LogReg.joblib
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:c0b67d6343403f99189d8df2d2af9e4eb8978ee2be22649a41dc08263ffb3092
|
| 3 |
+
size 3292
|
clf_MLP.joblib
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:987e62eff99aaf6b6c877794ab993d7b676b2132f06bed1de72f65be2fa937d3
|
| 3 |
+
size 130950
|
clf_Ridge.joblib
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:7aa80a5ce14e44512e1e38ce269008b208a1f993a66bcd0873094af7bdc04741
|
| 3 |
+
size 3082
|
config.json
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"model_type": "scihigh-extractive-ranker",
|
| 3 |
+
"task": "FIRE 2026 SciHigh Subtask 1 - research highlight generation",
|
| 4 |
+
"ensemble": [
|
| 5 |
+
"LinearSVC",
|
| 6 |
+
"Ridge",
|
| 7 |
+
"LogReg",
|
| 8 |
+
"MLP",
|
| 9 |
+
"ExtraTrees"
|
| 10 |
+
],
|
| 11 |
+
"fusion": "reciprocal_rank_fusion",
|
| 12 |
+
"rrf_k": 60,
|
| 13 |
+
"decoder": {
|
| 14 |
+
"budget": 110,
|
| 15 |
+
"maxs": 3,
|
| 16 |
+
"mmr": 0.85,
|
| 17 |
+
"trim": 0
|
| 18 |
+
},
|
| 19 |
+
"embeddings_used": true,
|
| 20 |
+
"encoder": "sentence-transformers/all-MiniLM-L6-v2",
|
| 21 |
+
"retrieval_neighbours": 10,
|
| 22 |
+
"feature_columns": [
|
| 23 |
+
"sid",
|
| 24 |
+
"rel_pos",
|
| 25 |
+
"rel_end",
|
| 26 |
+
"is_first",
|
| 27 |
+
"is_last",
|
| 28 |
+
"is_last2",
|
| 29 |
+
"is_first2",
|
| 30 |
+
"nsent",
|
| 31 |
+
"nw",
|
| 32 |
+
"nchar",
|
| 33 |
+
"rel_len",
|
| 34 |
+
"awlen",
|
| 35 |
+
"stop_ratio",
|
| 36 |
+
"n_content",
|
| 37 |
+
"content_dens",
|
| 38 |
+
"n_digit",
|
| 39 |
+
"n_acro",
|
| 40 |
+
"has_pct",
|
| 41 |
+
"lead",
|
| 42 |
+
"redund",
|
| 43 |
+
"tf_cent",
|
| 44 |
+
"tf_deg",
|
| 45 |
+
"textrank",
|
| 46 |
+
"tf_sum",
|
| 47 |
+
"tf_maxsim",
|
| 48 |
+
"cue_res",
|
| 49 |
+
"cue_meth",
|
| 50 |
+
"cue_purp",
|
| 51 |
+
"cue_bkg",
|
| 52 |
+
"cue_conc",
|
| 53 |
+
"cue_quant",
|
| 54 |
+
"e_cent",
|
| 55 |
+
"e_proto",
|
| 56 |
+
"e_maxsim",
|
| 57 |
+
"e_rag",
|
| 58 |
+
"sv0",
|
| 59 |
+
"sv1",
|
| 60 |
+
"sv2",
|
| 61 |
+
"sv3",
|
| 62 |
+
"sv4",
|
| 63 |
+
"sv5",
|
| 64 |
+
"sv6",
|
| 65 |
+
"sv7",
|
| 66 |
+
"sv8",
|
| 67 |
+
"sv9",
|
| 68 |
+
"sv10",
|
| 69 |
+
"sv11",
|
| 70 |
+
"sv12",
|
| 71 |
+
"sv13",
|
| 72 |
+
"sv14",
|
| 73 |
+
"sv15",
|
| 74 |
+
"sv16",
|
| 75 |
+
"sv17",
|
| 76 |
+
"sv18",
|
| 77 |
+
"sv19",
|
| 78 |
+
"sv20",
|
| 79 |
+
"sv21",
|
| 80 |
+
"sv22",
|
| 81 |
+
"sv23",
|
| 82 |
+
"sv24",
|
| 83 |
+
"sv25",
|
| 84 |
+
"sv26",
|
| 85 |
+
"sv27",
|
| 86 |
+
"sv28",
|
| 87 |
+
"sv29",
|
| 88 |
+
"sv30",
|
| 89 |
+
"sv31"
|
| 90 |
+
],
|
| 91 |
+
"n_features": 67,
|
| 92 |
+
"train_rows": 10000,
|
| 93 |
+
"train_sentences": 61775,
|
| 94 |
+
"validation_scores": {
|
| 95 |
+
"rouge1": 38.12,
|
| 96 |
+
"rouge2": 14.13,
|
| 97 |
+
"rougeL": 24.76
|
| 98 |
+
},
|
| 99 |
+
"validation_single_model_rougeL": {
|
| 100 |
+
"LinearSVC": 23.4745,
|
| 101 |
+
"Ridge": 23.4669,
|
| 102 |
+
"LogReg": 23.4528,
|
| 103 |
+
"MLP": 23.4036,
|
| 104 |
+
"ExtraTrees": 23.2509
|
| 105 |
+
},
|
| 106 |
+
"library_versions": {
|
| 107 |
+
"python": "3.11.15",
|
| 108 |
+
"scikit-learn": "1.8.0",
|
| 109 |
+
"numpy": "2.4.4",
|
| 110 |
+
"pandas": "3.0.2",
|
| 111 |
+
"joblib": "1.5.3"
|
| 112 |
+
},
|
| 113 |
+
"validation_docs": 1985
|
| 114 |
+
}
|
proto.npy
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:a51951bbaa87c6d6571ce6015a2831bf4d9188add91edb0b34797b237550496f
|
| 3 |
+
size 1664
|
requirements.txt
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
scikit-learn==1.8.0
|
| 2 |
+
numpy>=2.0
|
| 3 |
+
pandas
|
| 4 |
+
joblib
|
| 5 |
+
sentence-transformers
|
| 6 |
+
huggingface_hub
|
| 7 |
+
rouge-score
|
scihigh_model.py
ADDED
|
@@ -0,0 +1,360 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
SciHigh 2026 - Supervised extractive research-highlight generator (CPU-only).
|
| 3 |
+
|
| 4 |
+
FIRE 2026 SciHigh, Subtask 1: research highlight generation from MixSub abstracts.
|
| 5 |
+
|
| 6 |
+
Pipeline for one abstract
|
| 7 |
+
1. clean the text and split it into sentences
|
| 8 |
+
2. 31 hand-built features per sentence (position, length, lexical, discourse cues, TF-IDF graph)
|
| 9 |
+
3. 36 embedding features from all-MiniLM-L6-v2 (4 similarity features + 32-dim SVD projection),
|
| 10 |
+
including a retrieval feature built from the 10 nearest training abstracts
|
| 11 |
+
4. five classifiers score every sentence; their rankings are merged by Reciprocal Rank Fusion
|
| 12 |
+
5. a decoder picks sentences under a word budget with an MMR redundancy filter, restores
|
| 13 |
+
reading order and rewrites each sentence into highlight style
|
| 14 |
+
|
| 15 |
+
Usage
|
| 16 |
+
from scihigh_model import SciHighExtractor
|
| 17 |
+
model = SciHighExtractor.from_pretrained(".") # local folder or a Hugging Face repo id
|
| 18 |
+
print(model.predict(["<abstract text>"])[0])
|
| 19 |
+
|
| 20 |
+
The text-processing functions below are copied unchanged from SciHigh_2026_CPU_Hybrid.ipynb, so
|
| 21 |
+
the saved models see exactly the features they were trained on.
|
| 22 |
+
"""
|
| 23 |
+
import os, re, io, json, glob, collections
|
| 24 |
+
import numpy as np, pandas as pd
|
| 25 |
+
from sklearn.preprocessing import normalize
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
# ---------------------------------------------------------------- file helpers
|
| 29 |
+
# Files larger than PART_LIMIT are stored as byte chunks named <stem>.part00<ext>, <stem>.part01<ext>, ...
|
| 30 |
+
# so every file stays under 10 MB (browser upload limit). The loader joins them back byte for byte.
|
| 31 |
+
PART_LIMIT = 9_500_000
|
| 32 |
+
|
| 33 |
+
def save_bytes(data, folder, name, limit=PART_LIMIT):
|
| 34 |
+
stem, ext = os.path.splitext(name)
|
| 35 |
+
for old in glob.glob(os.path.join(folder, f"{stem}.part*{ext}")): os.remove(old)
|
| 36 |
+
if len(data) <= limit:
|
| 37 |
+
open(os.path.join(folder, name), "wb").write(data); return [name]
|
| 38 |
+
names = []
|
| 39 |
+
for i in range(0, len(data), limit):
|
| 40 |
+
nm = f"{stem}.part{i // limit:02d}{ext}"
|
| 41 |
+
open(os.path.join(folder, nm), "wb").write(data[i:i + limit]); names.append(nm)
|
| 42 |
+
return names
|
| 43 |
+
|
| 44 |
+
def read_bytes(folder, name):
|
| 45 |
+
p = os.path.join(folder, name)
|
| 46 |
+
if os.path.exists(p): return open(p, "rb").read()
|
| 47 |
+
stem, ext = os.path.splitext(name)
|
| 48 |
+
parts = sorted(glob.glob(os.path.join(folder, f"{stem}.part*{ext}")))
|
| 49 |
+
if not parts: raise FileNotFoundError(p)
|
| 50 |
+
return b"".join(open(q, "rb").read() for q in parts)
|
| 51 |
+
|
| 52 |
+
def load_joblib(folder, name):
|
| 53 |
+
import joblib
|
| 54 |
+
return joblib.load(io.BytesIO(read_bytes(folder, name)))
|
| 55 |
+
|
| 56 |
+
def load_npy(folder, name):
|
| 57 |
+
return np.load(io.BytesIO(read_bytes(folder, name)))
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
# ---------------------------------------------------------------- cleaning and sentence splitting
|
| 61 |
+
def clean(t):
|
| 62 |
+
t = str(t)
|
| 63 |
+
t = re.sub(r"\.\s*None\.\s*", " ", t) # "value . None . unit" artifact
|
| 64 |
+
t = re.sub(r"\bNone\b", " ", t)
|
| 65 |
+
t = re.sub(r"\s*\.\s*\.", ".", t) # collapse double periods left behind
|
| 66 |
+
return re.sub(r"\s+", " ", t).strip()
|
| 67 |
+
|
| 68 |
+
def sent_split(t):
|
| 69 |
+
# split on " . " (MixSub style) or on ". " followed by a capital
|
| 70 |
+
parts = re.split(r"(?<=[A-Za-z0-9\)\]\%])\s+\.\s+|(?<=[a-z0-9\)\]\%])\.\s+(?=[A-Z])", str(t).strip())
|
| 71 |
+
out = []
|
| 72 |
+
for p in parts:
|
| 73 |
+
if not p: continue
|
| 74 |
+
p = p.strip().rstrip(".").strip()
|
| 75 |
+
if len(p.split()) >= 3:
|
| 76 |
+
out.append(p)
|
| 77 |
+
elif out:
|
| 78 |
+
out[-1] += " " + p # glue fragments onto the previous sentence
|
| 79 |
+
return out or [str(t).rstrip(".").strip()]
|
| 80 |
+
|
| 81 |
+
STOP = set('''a about above after again against all also am among an and any are as at be because been before
|
| 82 |
+
being below between both but by can cannot could did do does doing during each few for from further had has
|
| 83 |
+
have having he her here hers herself him himself his how i if in into is it its itself me more most my myself
|
| 84 |
+
no nor not now of off on once only or other others our ours out over own same she should so some such than
|
| 85 |
+
that the their theirs them themselves then there these they this those through to too under until up very
|
| 86 |
+
was we were what when where which while who whom why will with would you your yours'''.split())
|
| 87 |
+
|
| 88 |
+
TOK = re.compile(r"[a-z0-9]+")
|
| 89 |
+
def toks(t): return TOK.findall(str(t).lower())
|
| 90 |
+
def content(t): return [w for w in toks(t) if w not in STOP and len(w) > 2]
|
| 91 |
+
|
| 92 |
+
def make_doc(abstract):
|
| 93 |
+
"""One cleaned abstract -> the document dict used by featurize() and decode()."""
|
| 94 |
+
S = sent_split(clean(abstract)); n = len(S)
|
| 95 |
+
return dict(S=S, n=n, tk=[toks(s) for s in S], cw=[set(content(s)) for s in S])
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
# ---------------------------------------------------------------- hand-built sentence features
|
| 99 |
+
CUES = {
|
| 100 |
+
"res": r"\b(result|show|showed|shown|found|find|reveal|demonstrat|indicat|observ|obtain|achiev|improv|outperform|increas|decreas|significant)",
|
| 101 |
+
"meth": r"\b(propos|present|develop|design|introduc|novel|new |method|approach|model|framework|algorithm|technique|scheme|system|strateg)",
|
| 102 |
+
"purp": r"\b(aim|objective|purpose|goal|investigat|examin|explor|evaluat|assess|analys|analyz)",
|
| 103 |
+
"bkg": r"\b(previous|literature|recently|recent years|has been|have been|widely|however|although|despite|remains|little is known|few studies)",
|
| 104 |
+
"conc": r"\b(conclu|suggest|impl|therefore|thus|hence|overall|consequently|potential|promis|can be used|may be)",
|
| 105 |
+
"quant": r"(\d+\.?\d*\s?%|p\s?[<=]|\bn\s?=|\bmean\b|\bmedian\b|\bratio\b|\brate\b|fold)",
|
| 106 |
+
}
|
| 107 |
+
LEAD_RE = (r"^(in this (study|paper|work|article|research)|in the present|the (aim|purpose|objective|goal) of"
|
| 108 |
+
r"|here we|in addition|moreover|furthermore|therefore|thus|however|finally|overall|first|second"
|
| 109 |
+
r"|third|also|based on)")
|
| 110 |
+
|
| 111 |
+
def featurize(docs, tv):
|
| 112 |
+
rows = []
|
| 113 |
+
for d in docs:
|
| 114 |
+
S, n, TKs, CWs = d["S"], d["n"], d["tk"], d["cw"]
|
| 115 |
+
tw = max(sum(len(t) for t in TKs), 1)
|
| 116 |
+
X = normalize(tv.transform(S))
|
| 117 |
+
cen = (X @ normalize(np.asarray(X.mean(0))).T).ravel() # cosine to abstract centroid
|
| 118 |
+
M = (X @ X.T).toarray(); np.fill_diagonal(M, 0); deg = M.sum(1)
|
| 119 |
+
P = M / np.maximum(deg[:, None], 1e-9); pr = np.ones(n) / n
|
| 120 |
+
for _ in range(20): pr = 0.15 / n + 0.85 * (P.T @ pr) # TextRank power iteration
|
| 121 |
+
tsum = np.asarray(X.sum(1)).ravel()
|
| 122 |
+
mx = M.max(1) if n > 1 else np.zeros(n)
|
| 123 |
+
for i, s in enumerate(S):
|
| 124 |
+
sw, cw, low = TKs[i], CWs[i], s.lower()
|
| 125 |
+
nov = max((len(cw & CWs[j]) / max(len(cw | CWs[j]), 1) for j in range(i)), default=0.0)
|
| 126 |
+
f = {"sid": i, "rel_pos": i / max(n-1, 1), "rel_end": (n-1-i) / max(n-1, 1),
|
| 127 |
+
"is_first": int(i == 0), "is_last": int(i == n-1), "is_last2": int(i >= n-2),
|
| 128 |
+
"is_first2": int(i <= 1), "nsent": n, "nw": len(sw), "nchar": len(s),
|
| 129 |
+
"rel_len": len(sw) / tw,
|
| 130 |
+
"awlen": float(np.mean([len(w) for w in sw])) if sw else 0.0,
|
| 131 |
+
"stop_ratio": sum(1 for w in sw if w in STOP) / max(len(sw), 1),
|
| 132 |
+
"n_content": len(cw), "content_dens": len(cw) / max(len(sw), 1),
|
| 133 |
+
"n_digit": sum(c.isdigit() for c in s),
|
| 134 |
+
"n_acro": len(re.findall(r"\b[A-Z]{2,}\b", s)), "has_pct": int("%" in s),
|
| 135 |
+
"lead": int(bool(re.match(LEAD_RE, low))), "redund": nov,
|
| 136 |
+
"tf_cent": cen[i], "tf_deg": deg[i], "textrank": pr[i],
|
| 137 |
+
"tf_sum": tsum[i], "tf_maxsim": mx[i]}
|
| 138 |
+
for k, pat in CUES.items():
|
| 139 |
+
f["cue_" + k] = len(re.findall(pat, low))
|
| 140 |
+
rows.append(f)
|
| 141 |
+
return pd.DataFrame(rows)
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
# ---------------------------------------------------------------- embedding features
|
| 145 |
+
def offsets(docs):
|
| 146 |
+
o, c = [], 0
|
| 147 |
+
for d in docs: o.append((c, c + d["n"])); c += d["n"]
|
| 148 |
+
return o
|
| 149 |
+
|
| 150 |
+
def cent(E, O):
|
| 151 |
+
return np.vstack([normalize(E[a:b].mean(0).reshape(1, -1)) for a, b in O])
|
| 152 |
+
|
| 153 |
+
def emb_feats(E, O, Ctr, Hemb, proto, is_train=False, k=10):
|
| 154 |
+
out = np.zeros((len(E), 4), np.float32)
|
| 155 |
+
sim = cent(E, O) @ Ctr.T
|
| 156 |
+
if is_train: np.fill_diagonal(sim, -1) # never retrieve yourself
|
| 157 |
+
nn = np.argsort(-sim, 1)[:, :k]
|
| 158 |
+
for q, (a, b) in enumerate(O):
|
| 159 |
+
X = E[a:b]
|
| 160 |
+
out[a:b, 0] = (X @ normalize(X.mean(0).reshape(1, -1)).T).ravel()
|
| 161 |
+
out[a:b, 1] = (X @ proto.T).ravel()
|
| 162 |
+
M = X @ X.T; np.fill_diagonal(M, 0)
|
| 163 |
+
out[a:b, 2] = M.max(1) if b - a > 1 else 0
|
| 164 |
+
out[a:b, 3] = (X @ normalize(Hemb[nn[q]].mean(0).reshape(1, -1)).T).ravel()
|
| 165 |
+
return pd.DataFrame(out, columns=["e_cent", "e_proto", "e_maxsim", "e_rag"])
|
| 166 |
+
|
| 167 |
+
def load_encoder(name_or_path="sentence-transformers/all-MiniLM-L6-v2", device="cpu"):
|
| 168 |
+
"""all-MiniLM-L6-v2 as a SentenceTransformer: Transformer(max_seq_length=256) -> mean pooling -> L2 norm.
|
| 169 |
+
Accepts a Hugging Face id, a full sentence-transformers folder, or a folder that holds only
|
| 170 |
+
config.json + model.safetensors + tokenizer.json (the same three modules are then assembled here)."""
|
| 171 |
+
from sentence_transformers import SentenceTransformer, models
|
| 172 |
+
p = name_or_path
|
| 173 |
+
if os.path.isdir(p) and not os.path.exists(os.path.join(p, "modules.json")):
|
| 174 |
+
tr = models.Transformer(p, max_seq_length=256, do_lower_case=False)
|
| 175 |
+
dim = (tr.get_embedding_dimension() if hasattr(tr, "get_embedding_dimension")
|
| 176 |
+
else tr.get_word_embedding_dimension())
|
| 177 |
+
pool = models.Pooling(dim, pooling_mode="mean")
|
| 178 |
+
return SentenceTransformer(modules=[tr, pool, models.Normalize()], device=device)
|
| 179 |
+
return SentenceTransformer(p, device=device)
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
# ---------------------------------------------------------------- decoder and restyling
|
| 183 |
+
DROP = re.compile(
|
| 184 |
+
r"^(in this (study|paper|work|article|research|comment|letter|note|review|report|contribution)"
|
| 185 |
+
r"|in the (present|current) (study|work|paper|article|research)|in the following"
|
| 186 |
+
r"|the (aim|aims|purpose|objective|objectives|goal|goals) of (this|the present|the current) "
|
| 187 |
+
r"(study|paper|work|research|article) (was|were|is|are) to"
|
| 188 |
+
r"|the (present|current) (study|work|paper) (aims?|aimed|sought|seeks?)( to)?"
|
| 189 |
+
r"|here (we|the authors)|in addition|additionally|moreover|furthermore|therefore|thus|hence|however"
|
| 190 |
+
r"|nevertheless|nonetheless|meanwhile|finally|overall|consequently|accordingly|notably|importantly"
|
| 191 |
+
r"|first(ly)?|second(ly)?|third(ly)?|also|in conclusion|in summary|to summari[sz]e|taken together"
|
| 192 |
+
r"|it (was|is|has been|had been) (found|shown|observed|concluded|demonstrated|reported|noted|revealed)( that)?"
|
| 193 |
+
r"|we (found|find|show|showed|observe|observed|conclude|concluded|report|reported|note|noted"
|
| 194 |
+
r"|demonstrate|demonstrated|argue|suggest|propose)( that| with| in)?"
|
| 195 |
+
r"|(the|our|these|this) (results?|findings?|data|analysis|study|work) (show|shows|showed|indicate"
|
| 196 |
+
r"|indicated|suggest|suggests|suggested|reveal|revealed|demonstrate|demonstrated|confirm|confirmed)( that)?"
|
| 197 |
+
r"|(this|these) (results?|findings?) (suggest|suggests|indicate|indicates|impl(y|ies))( that)?"
|
| 198 |
+
r"|as (a|an) (result|consequence)|on the (other hand|contrary)|in contrast|by contrast"
|
| 199 |
+
r"|based on (this|these|the)( results?| findings?)?"
|
| 200 |
+
r"|the (results?|findings?) (of (this|the present) (study )?)?(show|showed|indicate|indicated"
|
| 201 |
+
r"|suggest|suggested|revealed)( that)?)\s*[,:]?\s*", re.I)
|
| 202 |
+
|
| 203 |
+
CONN = re.compile(r"\s+(?:and|but|whereas|while|although|though|because|since|which|that)\s+")
|
| 204 |
+
|
| 205 |
+
def restyle(s, trim=0):
|
| 206 |
+
prev = None
|
| 207 |
+
while prev != s: # rules can cascade: "However, we found that X" -> "X"
|
| 208 |
+
prev = s; s = DROP.sub("", s).strip()
|
| 209 |
+
s = re.sub(r"^(and|but|that|which|to|of|in|for|with|as)\s+", "", s, flags=re.I).strip()
|
| 210 |
+
if trim and len(s.split()) > trim: # optional clause-level truncation
|
| 211 |
+
parts = CONN.split(s)
|
| 212 |
+
if len(parts) > 1:
|
| 213 |
+
acc, keep = 0, []
|
| 214 |
+
for p in parts:
|
| 215 |
+
if keep and acc + len(p.split()) > trim: break
|
| 216 |
+
keep.append(p); acc += len(p.split())
|
| 217 |
+
if keep: s = " and ".join(keep)
|
| 218 |
+
s = re.sub(r"\s+", " ", s).strip()
|
| 219 |
+
return (s[0].upper() + s[1:]) if s else s
|
| 220 |
+
|
| 221 |
+
def decode(docs, sc, budget=110, maxs=3, mmr=0.55, trim=0, E=None):
|
| 222 |
+
out, c = [], 0
|
| 223 |
+
for d in docs:
|
| 224 |
+
n = d["n"]; s = sc[c:c+n]; base = c; c += n
|
| 225 |
+
order = list(np.argsort(-s)); pick, wc = [], 0
|
| 226 |
+
for i in order:
|
| 227 |
+
if len(pick) >= maxs: break
|
| 228 |
+
w = len(d["tk"][i])
|
| 229 |
+
if wc + w > budget and pick: continue
|
| 230 |
+
if mmr < 1.0 and pick:
|
| 231 |
+
if E is not None:
|
| 232 |
+
sim = max(float(E[base+i] @ E[base+j]) for j in pick)
|
| 233 |
+
else:
|
| 234 |
+
a = d["cw"][i]
|
| 235 |
+
sim = max(len(a & d["cw"][j]) / max(len(a | d["cw"][j]), 1) for j in pick)
|
| 236 |
+
if sim > mmr: continue
|
| 237 |
+
pick.append(i); wc += w
|
| 238 |
+
if not pick: pick = [order[0]]
|
| 239 |
+
pick.sort() # restore reading order
|
| 240 |
+
segs = [x for x in (restyle(d["S"][i], trim) for i in pick) if len(x.split()) >= 3]
|
| 241 |
+
out.append((". ".join(segs) + ".") if segs else d["S"][pick[0]] + ".")
|
| 242 |
+
return out
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
# ---------------------------------------------------------------- scoring and rank fusion
|
| 246 |
+
def prob(m, X):
|
| 247 |
+
return (m.predict_proba(X)[:, 1] if hasattr(m, "predict_proba")
|
| 248 |
+
else 1 / (1 + np.exp(-m.decision_function(X))))
|
| 249 |
+
|
| 250 |
+
def fuse(docs, D, names, k=60):
|
| 251 |
+
z = np.zeros(sum(d["n"] for d in docs))
|
| 252 |
+
for n in names:
|
| 253 |
+
s = D[n]; c = 0
|
| 254 |
+
for d in docs:
|
| 255 |
+
m = d["n"]
|
| 256 |
+
o = np.argsort(-s[c:c+m]); rr = np.empty(m, int); rr[o] = np.arange(m)
|
| 257 |
+
z[c:c+m] += 1.0 / (k + rr + 1); c += m
|
| 258 |
+
return z
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
# ---------------------------------------------------------------- the model
|
| 262 |
+
class SciHighExtractor:
|
| 263 |
+
"""Loads the saved artifacts and turns raw abstracts into highlights."""
|
| 264 |
+
|
| 265 |
+
def __init__(self, folder, encoder=None, device="cpu"):
|
| 266 |
+
self.folder = folder
|
| 267 |
+
self.config = json.load(open(os.path.join(folder, "config.json")))
|
| 268 |
+
self.tv = load_joblib(folder, "tfidf.joblib")
|
| 269 |
+
self.models = {n: load_joblib(folder, f"clf_{n}.joblib") for n in self.config["ensemble"]}
|
| 270 |
+
self.use_emb = self.config["embeddings_used"]
|
| 271 |
+
if self.use_emb:
|
| 272 |
+
self.svd = load_joblib(folder, "svd.joblib")
|
| 273 |
+
self.proto = load_npy(folder, "proto.npy")
|
| 274 |
+
self.Ctr = load_npy(folder, "train_centroids.npy")
|
| 275 |
+
self.Hemb = load_npy(folder, "train_highlight_emb.npy")
|
| 276 |
+
self._enc_src, self._enc, self._device = encoder or self.config["encoder"], None, device
|
| 277 |
+
|
| 278 |
+
@classmethod
|
| 279 |
+
def from_pretrained(cls, path_or_repo_id, encoder=None, device="cpu", **hub_kwargs):
|
| 280 |
+
"""path_or_repo_id: a local folder, or a Hugging Face repo id such as "user/scihigh2026-extractive-ranker".
|
| 281 |
+
encoder: optional local path to all-MiniLM-L6-v2 (default: downloaded from the Hub by name)."""
|
| 282 |
+
folder = path_or_repo_id
|
| 283 |
+
if not os.path.isdir(folder):
|
| 284 |
+
from huggingface_hub import snapshot_download
|
| 285 |
+
folder = snapshot_download(path_or_repo_id, **hub_kwargs)
|
| 286 |
+
return cls(folder, encoder=encoder, device=device)
|
| 287 |
+
|
| 288 |
+
def _embed(self, texts):
|
| 289 |
+
if self._enc is None:
|
| 290 |
+
self._enc = load_encoder(self._enc_src, self._device)
|
| 291 |
+
return self._enc.encode(list(texts), batch_size=256, convert_to_numpy=True,
|
| 292 |
+
normalize_embeddings=True, show_progress_bar=False)
|
| 293 |
+
|
| 294 |
+
def features(self, docs):
|
| 295 |
+
"""Design matrix (one row per sentence) and the sentence embeddings used by the MMR filter."""
|
| 296 |
+
F, E = featurize(docs, self.tv), None
|
| 297 |
+
if self.use_emb:
|
| 298 |
+
E = self._embed([s for d in docs for s in d["S"]])
|
| 299 |
+
proj = pd.DataFrame(self.svd.transform(E), columns=[f"sv{i}" for i in range(32)])
|
| 300 |
+
F = pd.concat([F, emb_feats(E, offsets(docs), self.Ctr, self.Hemb, self.proto), proj], axis=1)
|
| 301 |
+
X = F[self.config["feature_columns"]].astype(np.float32).fillna(0)
|
| 302 |
+
return X, E
|
| 303 |
+
|
| 304 |
+
def sentence_scores(self, docs):
|
| 305 |
+
X, E = self.features(docs)
|
| 306 |
+
S = {n: prob(m, X) for n, m in self.models.items()}
|
| 307 |
+
return fuse(docs, S, self.config["ensemble"], k=self.config["rrf_k"]), E
|
| 308 |
+
|
| 309 |
+
def _cfg(self, overrides):
|
| 310 |
+
cfg = dict(self.config["decoder"])
|
| 311 |
+
cfg.update({k: v for k, v in overrides.items() if v is not None})
|
| 312 |
+
return cfg
|
| 313 |
+
|
| 314 |
+
def predict(self, abstracts, **decoder):
|
| 315 |
+
"""list of abstract strings -> list of highlight strings.
|
| 316 |
+
Optional decoder overrides: budget (words), maxs (sentences), mmr (redundancy threshold), trim."""
|
| 317 |
+
if isinstance(abstracts, str): abstracts = [abstracts]
|
| 318 |
+
docs = [make_doc(a) for a in abstracts]
|
| 319 |
+
z, E = self.sentence_scores(docs)
|
| 320 |
+
return decode(docs, z, **self._cfg(decoder), E=E)
|
| 321 |
+
|
| 322 |
+
def explain(self, abstract, **decoder):
|
| 323 |
+
"""One abstract -> (highlights, per-sentence table with each model's score and the fused rank)."""
|
| 324 |
+
docs = [make_doc(abstract)]
|
| 325 |
+
X, E = self.features(docs)
|
| 326 |
+
S = {n: prob(m, X) for n, m in self.models.items()}
|
| 327 |
+
z = fuse(docs, S, self.config["ensemble"], k=self.config["rrf_k"])
|
| 328 |
+
cfg = self._cfg(decoder)
|
| 329 |
+
text = decode(docs, z, **cfg, E=E)[0]
|
| 330 |
+
picked = set(pick_indices(docs[0], z, E, **cfg))
|
| 331 |
+
order = np.argsort(-z); rank = np.empty(len(z), int); rank[order] = np.arange(1, len(z) + 1)
|
| 332 |
+
table = pd.DataFrame({"#": np.arange(1, len(z) + 1), "picked": ["yes" if i in picked else "" for i in range(len(z))],
|
| 333 |
+
"rank": rank, "sentence": docs[0]["S"], "RRF": np.round(z.astype(float), 4)})
|
| 334 |
+
for n in self.config["ensemble"]: table[n] = np.round(np.asarray(S[n], dtype=float), 3)
|
| 335 |
+
return text, table
|
| 336 |
+
|
| 337 |
+
|
| 338 |
+
def pick_indices(d, s, E=None, budget=110, maxs=3, mmr=0.55, trim=0):
|
| 339 |
+
"""The sentence-selection half of decode() for a single document, returning indices (for display)."""
|
| 340 |
+
order = list(np.argsort(-s)); pick, wc = [], 0
|
| 341 |
+
for i in order:
|
| 342 |
+
if len(pick) >= maxs: break
|
| 343 |
+
w = len(d["tk"][i])
|
| 344 |
+
if wc + w > budget and pick: continue
|
| 345 |
+
if mmr < 1.0 and pick:
|
| 346 |
+
if E is not None:
|
| 347 |
+
sim = max(float(E[i] @ E[j]) for j in pick)
|
| 348 |
+
else:
|
| 349 |
+
a = d["cw"][i]
|
| 350 |
+
sim = max(len(a & d["cw"][j]) / max(len(a | d["cw"][j]), 1) for j in pick)
|
| 351 |
+
if sim > mmr: continue
|
| 352 |
+
pick.append(i); wc += w
|
| 353 |
+
return sorted(pick) if pick else [order[0]]
|
| 354 |
+
|
| 355 |
+
|
| 356 |
+
if __name__ == "__main__":
|
| 357 |
+
import sys
|
| 358 |
+
m = SciHighExtractor.from_pretrained(os.path.dirname(os.path.abspath(__file__)))
|
| 359 |
+
text = " ".join(sys.argv[1:]) or sys.stdin.read()
|
| 360 |
+
print(m.predict([text])[0])
|
svd.joblib
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:4b5b000b4b702a4d5fed898be7b3df8e7a50bbbdc924de2f900ca4cda89b9d28
|
| 3 |
+
size 50279
|
tfidf.joblib
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:c6c9075a226d97c2ff9b8c71585e31c6c0f18d357cf05e6878dfc3c9847608b8
|
| 3 |
+
size 253590
|
train_centroids.part00.npy
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:c9571cc2517a22991013448bcda0b09eb129f79dc19a445b43c32258d5192f09
|
| 3 |
+
size 9500000
|
train_centroids.part01.npy
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:99426906e8e21c5420b12e9cb4e64e3f584ca43487ffcb0bac3a6ac8eeda3b04
|
| 3 |
+
size 5860128
|
train_export.py
ADDED
|
@@ -0,0 +1,227 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Re-trains the submitted SciHigh 2026 ensemble and exports it into this folder.
|
| 3 |
+
|
| 4 |
+
This is SciHigh_2026_CPU_Hybrid.ipynb with the model search removed: the ensemble members and the
|
| 5 |
+
decoder settings are fixed to the ones the notebook selected on validation (see run_summary.csv),
|
| 6 |
+
and the fitted objects are saved so they can be uploaded to the Hugging Face Hub.
|
| 7 |
+
|
| 8 |
+
python train_export.py --data <folder with the three MixSub CSVs> --encoder <all-MiniLM-L6-v2 path or id>
|
| 9 |
+
"""
|
| 10 |
+
import os, re, sys, time, json, bisect, argparse, collections, warnings
|
| 11 |
+
import numpy as np, pandas as pd, joblib
|
| 12 |
+
warnings.filterwarnings("ignore")
|
| 13 |
+
np.random.seed(42)
|
| 14 |
+
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
| 15 |
+
from scihigh_model import (clean, sent_split, toks, content, featurize, offsets, cent, emb_feats,
|
| 16 |
+
load_encoder, decode, prob, fuse)
|
| 17 |
+
|
| 18 |
+
ap = argparse.ArgumentParser()
|
| 19 |
+
ap.add_argument("--data", default=".")
|
| 20 |
+
ap.add_argument("--encoder", default="sentence-transformers/all-MiniLM-L6-v2")
|
| 21 |
+
ap.add_argument("--out", default=os.path.dirname(os.path.abspath(__file__)))
|
| 22 |
+
ap.add_argument("--cache", default=None, help="optional folder for intermediate results")
|
| 23 |
+
args = ap.parse_args()
|
| 24 |
+
|
| 25 |
+
RANDOM = 42
|
| 26 |
+
SEL = ["LinearSVC", "Ridge", "LogReg", "MLP", "ExtraTrees"] # "top5-overall", chosen in the notebook
|
| 27 |
+
CFG = dict(budget=110, maxs=3, mmr=0.85, trim=0) # tuned by coordinate descent in the notebook
|
| 28 |
+
|
| 29 |
+
t0 = time.time()
|
| 30 |
+
def log(*a): print(f"[{time.time()-t0:6.1f}s]", *a, flush=True)
|
| 31 |
+
def cached(name, fn):
|
| 32 |
+
if not args.cache: return fn()
|
| 33 |
+
p = os.path.join(args.cache, name + ".joblib")
|
| 34 |
+
if os.path.exists(p): return joblib.load(p)
|
| 35 |
+
os.makedirs(args.cache, exist_ok=True); v = fn(); joblib.dump(v, p); return v
|
| 36 |
+
|
| 37 |
+
# ---------------------------------------------------------------- data
|
| 38 |
+
train = pd.read_csv(os.path.join(args.data, "MixSub-SciHigh_train_FIRE.csv"))
|
| 39 |
+
val = pd.read_csv(os.path.join(args.data, "MixSub-SciHigh_val_FIRE.csv"))
|
| 40 |
+
test = pd.read_csv(os.path.join(args.data, "MixSub-SciHigh_test_FIRE(Masked).csv"))
|
| 41 |
+
for df in (train, val, test): df["A"] = df["Abstract"].map(clean)
|
| 42 |
+
for df in (train, val): df["H"] = df["Highlights"].map(clean)
|
| 43 |
+
log("train", train.shape, "| val", val.shape, "| test", test.shape)
|
| 44 |
+
|
| 45 |
+
# ---------------------------------------------------------------- oracle labels (notebook sections 4-5)
|
| 46 |
+
from functools import lru_cache
|
| 47 |
+
from nltk.stem.porter import PorterStemmer
|
| 48 |
+
_PS = PorterStemmer()
|
| 49 |
+
TOK = re.compile(r"[a-z0-9]+")
|
| 50 |
+
|
| 51 |
+
@lru_cache(maxsize=500_000)
|
| 52 |
+
def _stem(w): return _PS.stem(w) if len(w) > 3 else w
|
| 53 |
+
def stoks(t): return [_stem(w) for w in TOK.findall(str(t).lower())]
|
| 54 |
+
|
| 55 |
+
def ngrams(ws, n):
|
| 56 |
+
return collections.Counter(zip(*[ws[i:] for i in range(n)])) if len(ws) >= n else collections.Counter()
|
| 57 |
+
|
| 58 |
+
def _f(t, nc, nr):
|
| 59 |
+
if not t: return 0.0
|
| 60 |
+
p, r = t / max(nc, 1), t / max(nr, 1)
|
| 61 |
+
return 2 * p * r / (p + r)
|
| 62 |
+
|
| 63 |
+
def r_gain(cand_ws, ref1, ref2):
|
| 64 |
+
c1, c2 = ngrams(cand_ws, 1), ngrams(cand_ws, 2)
|
| 65 |
+
t1 = sum(min(v, c1[k]) for k, v in ref1.items())
|
| 66 |
+
t2 = sum(min(v, c2[k]) for k, v in ref2.items())
|
| 67 |
+
return _f(t1, sum(c1.values()), sum(ref1.values())) + _f(t2, sum(c2.values()), sum(ref2.values()))
|
| 68 |
+
|
| 69 |
+
def r12f(ws, ref_ws):
|
| 70 |
+
return r_gain(ws, ngrams(ref_ws, 1), ngrams(ref_ws, 2)) / 2
|
| 71 |
+
|
| 72 |
+
def lcs_len(a, b):
|
| 73 |
+
pos = collections.defaultdict(list)
|
| 74 |
+
for j, x in enumerate(b): pos[x].append(j)
|
| 75 |
+
tails = []
|
| 76 |
+
for x in a:
|
| 77 |
+
for j in reversed(pos.get(x, ())):
|
| 78 |
+
k = bisect.bisect_left(tails, j)
|
| 79 |
+
if k == len(tails): tails.append(j)
|
| 80 |
+
else: tails[k] = j
|
| 81 |
+
return len(tails)
|
| 82 |
+
|
| 83 |
+
def fast_rl(pred, ref_stems):
|
| 84 |
+
p = stoks(pred)
|
| 85 |
+
if not p or not ref_stems: return 0.0
|
| 86 |
+
l = lcs_len(p, ref_stems)
|
| 87 |
+
if not l: return 0.0
|
| 88 |
+
pr, rc = l / len(p), l / len(ref_stems)
|
| 89 |
+
return 2 * pr * rc / (pr + rc)
|
| 90 |
+
|
| 91 |
+
def make_docs(df, labelled, maxsel=6):
|
| 92 |
+
docs = []
|
| 93 |
+
for rec in df.itertuples():
|
| 94 |
+
S = sent_split(rec.A); n = len(S)
|
| 95 |
+
d = dict(S=S, n=n, tk=[toks(s) for s in S], cw=[set(content(s)) for s in S])
|
| 96 |
+
if labelled:
|
| 97 |
+
rw = toks(rec.H); r1, r2 = ngrams(rw, 1), ngrams(rw, 2)
|
| 98 |
+
chosen, cur, best = [], [], 0.0
|
| 99 |
+
for _ in range(min(maxsel, n)):
|
| 100 |
+
cand, cbest = None, best
|
| 101 |
+
for i in range(n):
|
| 102 |
+
if i in chosen: continue
|
| 103 |
+
sc = r_gain(cur + d["tk"][i], r1, r2)
|
| 104 |
+
if sc > cbest + 1e-9: cbest, cand = sc, i
|
| 105 |
+
if cand is None: break
|
| 106 |
+
chosen.append(cand); cur += d["tk"][cand]; best = cbest
|
| 107 |
+
ch = set(chosen)
|
| 108 |
+
d["y"] = [int(i in ch) for i in range(n)]
|
| 109 |
+
d["soft"] = [r12f(d["tk"][i], rw) for i in range(n)]
|
| 110 |
+
d["ref"] = rec.H
|
| 111 |
+
d["refs"] = stoks(rec.H)
|
| 112 |
+
docs.append(d)
|
| 113 |
+
return docs
|
| 114 |
+
|
| 115 |
+
log("labelling ...")
|
| 116 |
+
Dtr, Dva, Dte = cached("docs", lambda: (make_docs(train, True), make_docs(val, True), make_docs(test, False)))
|
| 117 |
+
flat = lambda ds, k: np.concatenate([d[k] for d in ds])
|
| 118 |
+
log("train sentences:", sum(d["n"] for d in Dtr), "| positive rate: %.3f" % flat(Dtr, "y").mean())
|
| 119 |
+
|
| 120 |
+
# ---------------------------------------------------------------- features (sections 7-8)
|
| 121 |
+
from sklearn.feature_extraction.text import TfidfVectorizer
|
| 122 |
+
from sklearn.decomposition import TruncatedSVD
|
| 123 |
+
from sklearn.preprocessing import normalize
|
| 124 |
+
allsent = [s for d in Dtr for s in d["S"]]
|
| 125 |
+
tv = TfidfVectorizer(sublinear_tf=True, stop_words="english", min_df=2).fit(allsent)
|
| 126 |
+
Ftr, Fva, Fte = cached("feats", lambda: (featurize(Dtr, tv), featurize(Dva, tv), featurize(Dte, tv)))
|
| 127 |
+
log("feature block:", Ftr.shape)
|
| 128 |
+
|
| 129 |
+
def encode_all():
|
| 130 |
+
enc = load_encoder(args.encoder, "cpu")
|
| 131 |
+
emb = lambda ts: enc.encode(list(ts), batch_size=256, convert_to_numpy=True,
|
| 132 |
+
normalize_embeddings=True, show_progress_bar=False)
|
| 133 |
+
log("encoding sentences on CPU ...")
|
| 134 |
+
Etr = emb(allsent); log(" train done")
|
| 135 |
+
Eva = emb([s for d in Dva for s in d["S"]])
|
| 136 |
+
Ete = emb([s for d in Dte for s in d["S"]])
|
| 137 |
+
hl = [x for h in train.H for x in re.split(r"(?<=[a-z0-9\)\%])\.\s+", h) if len(x.split()) > 3]
|
| 138 |
+
proto = normalize(emb(hl[:4000]).mean(0).reshape(1, -1))
|
| 139 |
+
Hemb = emb(train.H.tolist())
|
| 140 |
+
return Etr, Eva, Ete, proto, Hemb
|
| 141 |
+
Etr, Eva, Ete, proto, Hemb = cached("emb", encode_all)
|
| 142 |
+
Otr, Ova, Ote = offsets(Dtr), offsets(Dva), offsets(Dte)
|
| 143 |
+
Ctr = cent(Etr, Otr)
|
| 144 |
+
svd = TruncatedSVD(32, random_state=RANDOM).fit(Etr)
|
| 145 |
+
proj = lambda M: pd.DataFrame(svd.transform(M), columns=[f"sv{i}" for i in range(32)])
|
| 146 |
+
Ftr = pd.concat([Ftr, emb_feats(Etr, Otr, Ctr, Hemb, proto, True), proj(Etr)], axis=1)
|
| 147 |
+
Fva = pd.concat([Fva, emb_feats(Eva, Ova, Ctr, Hemb, proto, False), proj(Eva)], axis=1)
|
| 148 |
+
Fte = pd.concat([Fte, emb_feats(Ete, Ote, Ctr, Hemb, proto, False), proj(Ete)], axis=1)
|
| 149 |
+
Xtr, Xva, Xte = [f.astype(np.float32).fillna(0) for f in (Ftr, Fva, Fte)]
|
| 150 |
+
ytr, yva = flat(Dtr, "y"), flat(Dva, "y")
|
| 151 |
+
log("final design matrix:", Xtr.shape)
|
| 152 |
+
|
| 153 |
+
# ---------------------------------------------------------------- the five ensemble members (section 10)
|
| 154 |
+
from sklearn.linear_model import LogisticRegression, RidgeClassifier
|
| 155 |
+
from sklearn.svm import LinearSVC
|
| 156 |
+
from sklearn.ensemble import ExtraTreesClassifier
|
| 157 |
+
from sklearn.neural_network import MLPClassifier
|
| 158 |
+
from sklearn.pipeline import make_pipeline
|
| 159 |
+
from sklearn.preprocessing import StandardScaler
|
| 160 |
+
SC = lambda m: make_pipeline(StandardScaler(), m)
|
| 161 |
+
MODELS = {
|
| 162 |
+
"LogReg": SC(LogisticRegression(max_iter=1000)),
|
| 163 |
+
"Ridge": SC(RidgeClassifier()),
|
| 164 |
+
"LinearSVC": SC(LinearSVC(C=0.1, max_iter=3000)),
|
| 165 |
+
"ExtraTrees": ExtraTreesClassifier(150, min_samples_leaf=20, max_features=0.5, n_jobs=-1, random_state=RANDOM),
|
| 166 |
+
"MLP": SC(MLPClassifier((96, 48), max_iter=25, early_stopping=True, random_state=RANDOM)),
|
| 167 |
+
}
|
| 168 |
+
SV, ST = {}, {}
|
| 169 |
+
for name, m in MODELS.items():
|
| 170 |
+
t = time.time(); m.fit(Xtr, ytr)
|
| 171 |
+
SV[name], ST[name] = prob(m, Xva), prob(m, Xte)
|
| 172 |
+
log(f" {name:11s} fitted in {time.time()-t:.1f}s")
|
| 173 |
+
|
| 174 |
+
# ---------------------------------------------------------------- evaluation (sections 11, 14, 16)
|
| 175 |
+
from rouge_score import rouge_scorer
|
| 176 |
+
_RS = rouge_scorer.RougeScorer(["rouge1", "rouge2", "rougeL"], use_stemmer=True)
|
| 177 |
+
REFS, REFST = [d["ref"] for d in Dva], [d["refs"] for d in Dva]
|
| 178 |
+
def eval_all(preds, refs):
|
| 179 |
+
o = {k: [] for k in ["rouge1", "rouge2", "rougeL"]}
|
| 180 |
+
for p, r in zip(preds, refs):
|
| 181 |
+
s = _RS.score(r, p)
|
| 182 |
+
for k in o: o[k].append(s[k].fmeasure)
|
| 183 |
+
return {k: round(100 * float(np.mean(v)), 2) for k, v in o.items()}
|
| 184 |
+
qrl = lambda preds: 100 * float(np.mean([fast_rl(p, r) for p, r in zip(preds, REFST)]))
|
| 185 |
+
|
| 186 |
+
single = {n: round(qrl(decode(Dva, SV[n], 110, 3, .55, 0, Eva)), 4) for n in SEL}
|
| 187 |
+
log("single-model decoded ROUGE-L (notebook settings):", single)
|
| 188 |
+
FZ_va, FZ_te = fuse(Dva, SV, SEL), fuse(Dte, ST, SEL)
|
| 189 |
+
pred_va = decode(Dva, FZ_va, **CFG, E=Eva)
|
| 190 |
+
pred_te = decode(Dte, FZ_te, **CFG, E=Ete)
|
| 191 |
+
scores = eval_all(pred_va, REFS)
|
| 192 |
+
log("validation (fused):", scores)
|
| 193 |
+
|
| 194 |
+
# ---------------------------------------------------------------- export
|
| 195 |
+
import io, sklearn
|
| 196 |
+
from scihigh_model import save_bytes
|
| 197 |
+
out = args.out
|
| 198 |
+
os.makedirs(out, exist_ok=True)
|
| 199 |
+
def dump(obj, name, compress=3):
|
| 200 |
+
b = io.BytesIO(); joblib.dump(obj, b, compress=compress); save_bytes(b.getvalue(), out, name)
|
| 201 |
+
def npsave(arr, name):
|
| 202 |
+
b = io.BytesIO(); np.save(b, np.asarray(arr, np.float32)); save_bytes(b.getvalue(), out, name)
|
| 203 |
+
for n in SEL: dump(MODELS[n], f"clf_{n}.joblib")
|
| 204 |
+
dump(tv, "tfidf.joblib"); dump(svd, "svd.joblib")
|
| 205 |
+
npsave(proto, "proto.npy"); npsave(Ctr, "train_centroids.npy"); npsave(Hemb, "train_highlight_emb.npy")
|
| 206 |
+
config = {
|
| 207 |
+
"model_type": "scihigh-extractive-ranker",
|
| 208 |
+
"task": "FIRE 2026 SciHigh Subtask 1 - research highlight generation",
|
| 209 |
+
"ensemble": SEL, "fusion": "reciprocal_rank_fusion", "rrf_k": 60,
|
| 210 |
+
"decoder": CFG,
|
| 211 |
+
"embeddings_used": True,
|
| 212 |
+
"encoder": "sentence-transformers/all-MiniLM-L6-v2",
|
| 213 |
+
"retrieval_neighbours": 10,
|
| 214 |
+
"feature_columns": list(Xtr.columns),
|
| 215 |
+
"n_features": int(Xtr.shape[1]),
|
| 216 |
+
"train_rows": int(len(train)), "train_sentences": int(len(Xtr)), "validation_docs": int(len(val)),
|
| 217 |
+
"validation_scores": scores,
|
| 218 |
+
"validation_single_model_rougeL": single,
|
| 219 |
+
"library_versions": {"python": sys.version.split()[0], "scikit-learn": sklearn.__version__,
|
| 220 |
+
"numpy": np.__version__, "pandas": pd.__version__, "joblib": joblib.__version__},
|
| 221 |
+
}
|
| 222 |
+
json.dump(config, open(os.path.join(out, "config.json"), "w"), indent=2)
|
| 223 |
+
pd.DataFrame({"Filename": test["Filename"].values, "Highlights": pred_te}).to_csv(
|
| 224 |
+
os.path.join(out, "test_predictions.csv"), index=False)
|
| 225 |
+
pd.DataFrame({"Filename": val["Filename"].values, "Highlights": pred_va}).to_csv(
|
| 226 |
+
os.path.join(out, "val_predictions.csv"), index=False)
|
| 227 |
+
log("exported to", out)
|
train_highlight_emb.part00.npy
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:d742c8818f50340b5edee06d57ade6ba73ab02390adeb4b39d6b648afcd26deb
|
| 3 |
+
size 9500000
|
train_highlight_emb.part01.npy
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:9168d2336bea974a58102e481609832f1a3fd218d338072d30ed6b6dfaf00ed3
|
| 3 |
+
size 5860128
|