Metadata-Version: 2.4
Name: DEMNE
Version: 1.3.0
Summary: Cascade NLP pipeline for oncological biomarker extraction — optimizing the Performance-Explainability-Frugality trilemma
Author-email: Clément Longeac <clement.longeac@gmail.com>
License: MIT
Project-URL: Homepage, https://github.com/longeacc/DEMNE-Determination-of-Extraction-Methode-for-Named-Entity
Project-URL: Repository, https://github.com/longeacc/DEMNE-Determination-of-Extraction-Methode-for-Named-Entity
Project-URL: Bug Tracker, https://github.com/longeacc/DEMNE-Determination-of-Extraction-Methode-for-Named-Entity/issues
Project-URL: Documentation, https://github.com/longeacc/DEMNE-Determination-of-Extraction-Methode-for-Named-Entity#readme
Keywords: NLP,NER,oncology,biomarkers,frugal-AI,cascade
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Science/Research
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Operating System :: OS Independent
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: numpy>=1.24
Requires-Dist: pandas<3.0,>=2.0
Requires-Dist: scikit-learn>=1.3
Requires-Dist: scipy>=1.11
Requires-Dist: Unidecode>=1.3
Provides-Extra: ner
Requires-Dist: torch>=2.0; extra == "ner"
Requires-Dist: transformers>=4.36; extra == "ner"
Requires-Dist: datasets>=2.16; extra == "ner"
Requires-Dist: seqeval>=1.2; extra == "ner"
Provides-Extra: rest
Requires-Dist: matplotlib>=3.7; extra == "rest"
Requires-Dist: plotly<6.0,>=5.18; extra == "rest"
Requires-Dist: seaborn>=0.13; extra == "rest"
Requires-Dist: spacy>=3.7; extra == "rest"
Requires-Dist: python-Levenshtein>=0.25; extra == "rest"
Requires-Dist: nltk>=3.8; extra == "rest"
Requires-Dist: inflect>=7.0; extra == "rest"
Requires-Dist: bqplot>=0.12; extra == "rest"
Requires-Dist: ipydatagrid>=1.2; extra == "rest"
Requires-Dist: ipywidgets>=8.0; extra == "rest"
Requires-Dist: ipyfilechooser>=0.6; extra == "rest"
Provides-Extra: viz
Requires-Dist: matplotlib>=3.7; extra == "viz"
Requires-Dist: plotly<6.0,>=5.18; extra == "viz"
Requires-Dist: seaborn>=0.13; extra == "viz"
Requires-Dist: networkx>=3.2; extra == "viz"
Provides-Extra: notebook
Requires-Dist: nbformat>=5.9; extra == "notebook"
Provides-Extra: reports
Requires-Dist: reportlab>=4.0; extra == "reports"
Provides-Extra: gui
Requires-Dist: pywebview>=5.0; extra == "gui"
Provides-Extra: dashboard
Requires-Dist: streamlit>=1.30; extra == "dashboard"
Provides-Extra: energy
Requires-Dist: eco2ai>=0.3; extra == "energy"
Provides-Extra: optimize
Requires-Dist: optuna>=3.0; extra == "optimize"
Provides-Extra: dev
Requires-Dist: matplotlib>=3.7; extra == "dev"
Requires-Dist: pytest>=8.0; extra == "dev"
Requires-Dist: pytest-cov>=4.1; extra == "dev"
Requires-Dist: black>=24.0; extra == "dev"
Requires-Dist: isort>=5.13; extra == "dev"
Requires-Dist: ruff>=0.2; extra == "dev"
Requires-Dist: pre-commit>=3.7; extra == "dev"
Provides-Extra: gpu
Requires-Dist: torch>=2.0; extra == "gpu"
Requires-Dist: transformers>=4.36; extra == "gpu"
Requires-Dist: nvidia-ml-py>=12.0; extra == "gpu"
Dynamic: license-file

<div align="center">
   
# DEMNE

**Adaptive selection of the named-entity extraction method for frugal clinical NLP in oncology**

[![CI](https://github.com/longeacc/DEMNE-Determination-of-Extraction-Methode-for-Named-Entity/actions/workflows/ci.yml/badge.svg)](https://github.com/longeacc/DEMNE-Determination-of-Extraction-Methode-for-Named-Entity/actions/workflows/ci.yml)
[![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE)
[![Python 3.10+](https://img.shields.io/badge/python-3.10+-blue.svg)](https://python.org)

[Paper (in preparation)](#citation) · [Quick start](#quick-start) · [How it works](#how-it-works) · [Results](#results)

</div>

Not every entity in a French clinical report needs a transformer or an LLM. DEMNE measures each entity type in an annotated corpus with five metrics, then routes it to the **least costly extraction tier predicted to be good enough**: deterministic **rules**, a **transformer-based model (TBM)**, or an **LLM** as a last resort. It addresses the performance, explainability and frugality trilemma by matching method complexity to measured extraction difficulty.

|  **99.5 %**  |  **0.941 vs 0.358**  |  **0.866**  |  **59 · 92**  |
|:---:|:---:|:---:|:---:|
| of mentions routed to rules on an unseen AP-HP cohort (411/413) | mean F1, rules vs fine-tuned DrBERT, same entities | routing concordance on an unseen corpus (leave-one-corpus-out) | oncology entity types · entity-corpus pairs |

## How it works

<p align="center">
  <img src="https://github.com/user-attachments/assets/ce820f8d-2f83-4e7c-8798-d144e0e4660f" width="60%" alt="DEMNE routing decision graph">
</p>

1. **Characterize.** Five metrics are computed per entity type from BRAT annotations: templateability, lexical homogeneity, TF-IDF extractability, contextual risk (negation, uncertainty, contradiction), and a derived NER feasibility score.
2. **Route.** A deterministic decision graph with four nodes and calibrated thresholds assigns a tier. Rules are chosen only on positive evidence and a safe context; otherwise the entity escalates to a transformer when enough labelled examples exist, and to an LLM as a last resort.
3. **Calibrate.** The 17 free parameters are optimized with Optuna (NSGA-II) on routing concordance and an asymmetric cost that penalizes under-escalation twice as much as over-escalation. The calibration was first run by Akram Redjal; the resulting values ship in `src/demne/data/demne_params.json`, with a frozen copy in `Results/demne_params_published.json`. You can recalibrate on your own corpora with `python main.py optimize_params` (see [Recalibration](#recalibration)).

Every decision traces back to explicit metric values and thresholds, which makes the routing auditable (EU AI Act, Art. 12 and 14).

## Results

| Setting | Concordance | Notes |
|---|---|---|
| In-domain, 59 oncology entities (Protocol B) | 0.954 | cost-score 0.947, pooled accuracy 0.915 (54/59), no over-escalation |
| Leave-one-corpus-out | 0.866 | expected performance on an unseen corpus of the same domain |
| Best fixed-tier baseline (always RULES) | 0.729 | always-LLM reaches 0.148 |
| Across domains (oncology, Quaero, MACCROBAT) | 0.45 to 0.73 | recalibrate for a new domain or language |

**External validation** on 300 AP-HP CT-scan reports (colorectal and head-and-neck cancers), frozen configuration, no retuning: 6 of 7 tumour-response entities routed to rules (F1 0.892 to 0.972, mean 0.941), 1 to the LLM tier. A fine-tuned DrBERT trained on five of these entities reaches a mean F1 of 0.358.

<p align="center">
   <img width="732" height="202" alt="RESULTS_CA_300" src="https://github.com/user-attachments/assets/f9f09cef-d591-45b5-b479-309d9f8682dd" />
</p>


**Limitations.** The reference standard is small (92 entity types, 59 in oncology), the LLM tier was not evaluated end to end on the external cohort, and the contextual-risk gate did not bind on the evaluated corpora.

## Quick start

```bash
git clone https://github.com/longeacc/DEMNE-Determination-of-Extraction-Methode-for-Named-Entity.git
cd DEMNE-Determination-of-Extraction-Methode-for-Named-Entity
python -m venv .venv && source .venv/bin/activate
pip install -e ".[dev,ner]"

# sanity check: environment + entities discovered
python main.py info

# run metrics + decision tree on a BRAT corpus (clinical data not distributed — supply your own)
python main.py evaluate --gs_dir <path-to-BRAT-corpus>
```

The REST annotation interface is available as a notebook via `python main.py notebook` (serves `src/demne/REST_interface/REST.ipynb`).

## Recalibration

To retune the thresholds and weights on your own annotated corpora, place them under `data/` in the working directory and run:

```bash
pip install -e ".[optimize]"
python main.py optimize_params --in_domain     # target-domain corpora only
python main.py optimize_params --all_corpora   # also include data/OFF_DOMAIN_CORPORA
```

`data/OPT_CORPORA/` and `data/TEST_CORPORA/` each hold one folder per corpus: BRAT `.ann`/`.txt` pairs plus a `*_routing.csv` with the expected tier (`RULES`/`TBM`/`LLM`) per entity type. The run reports concordance and cost-score before and after, then updates `demne_params.json`, which the CLI and the dashboard read. The previous file is backed up in `Results/`. To reproduce the published figures, restore `Results/demne_params_published.json`. Folder layout, CSV format and outputs: [docs/OPTIMIZE_PARAMS.md](docs/OPTIMIZE_PARAMS.md).

## Repository layout

| Path | Content |
|---|---|
| `src/demne/` | the package, see the module table below |
| `main.py` | command line (`metrics`, `evaluate`, `dashboard`, `optimize_params`, …) |
| `scripts/` | maintenance scripts (manifest PDF) |
| `dashboard/` | Streamlit dashboard |
| `tests/` | unit tests (run by CI) |
| `docs/` | documentation |

### Modules of `src/demne/`

| Module | Role |
|---|---|
| `templatability.py`, `homogeneity.py`, `frequency.py`, `risk_context.py`, `ner_feasibility.py` | the five per-entity scorers (Te, He, Freq, R, Feas), each a standalone class with `compute_all()` |
| `tfidf_coverage.py` | TF-IDF extractability: coverage-F1 of the top-X keywords of an entity |
| `routing.py` | the decision graph, implemented once (`route()`) and used by the CLI and the dashboard |
| `decision_tree_builder.py` | applies the graph to the metrics, writes `decision_config.json` and the report |
| `params.py` | thresholds and weights from `demne_params.json`, risk lexicons, derived presets |
| `optimize_params.py` | Optuna recalibration of `demne_params.json` on your corpora |
| `_brat.py` | the single BRAT `.ann` parser used everywhere |
| `_tracking.py` | optional energy tracking with eco2ai (`pip install "demne[energy]"`); a no-op without it |
| `_table.py`, `visualize_decision_tree.py` | terminal tables and the decision figure |

## Data and ethics

The AP-HP data used for external validation are pseudonymized, were processed under the applicable institutional framework (AP-HP Health Data Warehouse, CSE-EDS approval CSE-220024) and are **not distributed** in this repository.

## Citation

```bibtex
@misc{demne2026,
  title  = {DEMNE: Adaptive Selection of Named Entity Extraction Method for Frugal Clinical NLP in Oncology},
  author = {Longeac, Clément and others},
  year   = {2026},
  note   = {Manuscript in preparation},
  url    = {https://github.com/longeacc/DEMNE-Determination-of-Extraction-Methode-for-Named-Entity}
}
```

See also `CITATION.cff`. DEMNE builds on the REST tool (Rapid Entity Selection Tool) and on the DuraXELL project at the AP-HP Clinical Data Warehouse.

## Contributing and license

Issues and pull requests are welcome, see [CONTRIBUTING.md](CONTRIBUTING.md). Released under the [MIT license](LICENSE).
