Metadata-Version: 2.4
Name: TEAVE
Version: 0.1.0
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Rust
Classifier: Topic :: Text Processing :: Linguistic
Classifier: Typing :: Typed
Requires-Dist: langdetect>=1.0.9,<2
Requires-Dist: phonenumbers>=9,<10
Requires-Dist: torch>=2.6,<3 ; extra == 'ner'
Requires-Dist: transformers>=5.0,<6 ; extra == 'ner'
Requires-Dist: numpy>=1.26,<3 ; extra == 'ner'
Requires-Dist: huggingface-hub>=1,<3 ; extra == 'ner'
Requires-Dist: onnxruntime>=1.20,<2 ; extra == 'onnx'
Requires-Dist: tokenizers>=0.21,<1 ; extra == 'onnx'
Requires-Dist: numpy>=1.26,<3 ; extra == 'onnx'
Requires-Dist: pytest>=8,<10 ; extra == 'test'
Provides-Extra: ner
Provides-Extra: onnx
Provides-Extra: test
License-File: LICENSE
Summary: Local text indexing for Estonian, Finnish, Latvian and Russian
Keywords: text indexing,named entity recognition,PII,archives,multilingual
Author: Rahvusarhiiv (National Archives of Estonia)
License-Expression: GPL-3.0-only
Requires-Python: >=3.10
Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
Project-URL: Changelog, https://github.com/Rahvusarhiiv/TEAVE/blob/main/CHANGELOG.md
Project-URL: Issues, https://github.com/Rahvusarhiiv/TEAVE/issues
Project-URL: Repository, https://github.com/Rahvusarhiiv/TEAVE
Project-URL: TeXplorer, https://huggingface.co/spaces/Rahvusarhiiv/ArchXAI_TeXplorer_Demo

# TEAVE

Tools for Extraction, Analysis, Validation and Enrichment, from the National Archives
of Estonia. TEAVE is an offline-first Python library for indexing Estonian (`et`),
Finnish (`fi`), Latvian (`lv`) and Russian (`ru`) text. This is an alpha release.

```bash
python -m pip install TEAVE  # once the first release has been published
# or, from this checkout, with a Rust toolchain:
python -m pip install .
```

```python
from dataclasses import asdict
from teave import Analyzer, recognize_datetimes, recognize_pii, redact

text = "Koosolek toimus 24. juunil 1947. Kirjuta aadressil info@example.org."
result = Analyzer().analyze(text, language="et")
print(asdict(result)["dates"][0]["normalized"])  # 1947-06-24
print(redact(text, result.pii))

dates = recognize_datetimes("24.–26. VI-47.", "et")
pii = recognize_pii("Yhteys: test@example.org", "fi")
batch = Analyzer(workers=4).analyze_many([text, text], "et", tasks=("pii",))
```

Omit the language to use seeded `langdetect` independently for each document.
Uncertain/unsupported detections raise `LanguageError`; explicitly set the language
for short, OCR-damaged or mixed-language texts. Offsets are **half-open Unicode code
point indices** into the original string (`text[start:end]`), not UTF-8 bytes or
JavaScript UTF-16 indices. Results are immutable dataclasses. Nothing sends text to
a service.

### Named entities

```bash
python -m pip install 'TEAVE[ner]'
```

```python
from teave import Analyzer, recognize_entities

text = "Mari Saar külastas Tallinna."
print(recognize_entities(text, "et"))
print(Analyzer().analyze(text, "et", tasks=("ner", "datetime", "pii")))
```

TEAVE downloads the selected original checkpoint on the first NER call and
runs it locally in **FP32** with PyTorch on CPU. There is no quantised fallback.
Bare `Analyzer().analyze(...)` still selects only dates and PII. TEAVE uses
revision-pinned checkpoints from the original publishers, not the browser
demo's quantised artifacts:

| Languages | First download (approx.) | Model |
| --- | --- | --- |
| Estonian, Latvian (shared checkpoint) | 2.25 GB | [51la5/roberta-large-NER](https://huggingface.co/51la5/roberta-large-NER) |
| Finnish | 497 MB | [Kansallisarkisto/finbert-ner](https://huggingface.co/Kansallisarkisto/finbert-ner) |
| Russian | 713 MB | [bond005/rubert-multiconer](https://huggingface.co/bond005/rubert-multiconer) |

The Russian default is RuBERT MultiCoNER, rather than Rapido's custom model
architecture. Its corporation and group labels map to `ORGANIZATION`. This is a
different model, not an accuracy-equivalent conversion; Rapido remains an
option with a trusted local FP32 ONNX export.

The Hub cache holds one copy of each artifact. TEAVE verifies the checkpoint
against its pinned SHA-256 digest and checks metadata against its pinned Git
blob IDs. Requests retrieve public files without sending document text or a
Hugging Face token. TEAVE does not fetch or execute remote model code, and
loads legacy checkpoint files in PyTorch's weights-only mode. Weights are
not included in the wheel; upstream model and training-data terms still apply.

```python
from teave import TransformerNER, recognize_entities

TransformerNER().prepare_model("fi")  # Optional: prefetch in the Hub cache.
ner = TransformerNER(local_files_only=True)
print(recognize_entities("Ilse Hammar syntyi Helsingissä.", "fi", backend=ner))
```

Pass `cache_dir=` to override the Hugging Face Hub cache location. Allow extra
space for transient downloads and enough RAM for the FP32 model plus runtime
buffers. For CPU-only deployments, install PyTorch from its CPU wheel index
before installing `TEAVE[ner]` if available for your platform.

For managed/offline deployments, install `TEAVE[onnx]` and use
`OnnxNER(model_root=...)` to skip the Hub entirely. Point it to a trusted
uncompressed **FP32** TeXplorer model-export directory with
subfolders `xlm-roberta-ner`, `finbert-ner`, or `rapido-ner`. Each needs
`tokenizer.json`, `config.json` and `onnx/model.onnx` plus any external tensor
files; Rapido also needs `crf.json`. Applications can instead supply their own
`NERBackend`.
NER returns people, organisations and places; it does not link identities.

### Dates, privacy and performance

- **Datetime:** source-aware calendar rules from TeXplorer, including supported
  historical spellings, partial dates, ranges, and clocks attached to a date.
  The four languages share numeric year rules, wrap boundaries and explicit
  year-list/range handling; year words and conjunctions are language-specific.
  Not a general time-zone or standalone time parser.
- **PII:** email, explicit HTTP(S)/WWW URLs, IP candidates, phone numbers,
  checksummed Estonian and Finnish personal IDs, selected IBAN countries and
  Luhn-valid card candidates. This is detection, not identity verification.
  Names are a separate NER task. The masking helper preserves punctuation and
  offsets; it is **not a guarantee of effective anonymisation**. Review omissions
  and protect all exports.
- **Parallelism:** Rust scans independent documents on a bounded reusable
  Rayon pool while releasing Python's GIL. The inference backends batch
  sliding windows when the model allows it and run tensor operations in their
  native runtimes. Language detection, phone matching, and the historical
  Python date grammar are not Rayon tasks. Reuse the model backend across
  bounded batches; loaded models can be large.

On one local ARM64 machine, a synthetic 1,200-document batch (3.38 million
characters) took a median 232 ms on one Rust worker and 78 ms on four, across
five warmed runs. Outputs matched exactly. This measures the native scanner
and Python result conversion, not phone matching, date parsing or inference.

### Why Rust for the native scanner?

Rust is not inherently faster than C or C++. The relevant comparison would use
the same rules, data, thread budget and Python boundary; we have not benchmarked
a C or C++ implementation. We chose Rust for memory-safety guarantees in the
scanner and for the PyO3/Rayon/Cargo toolchain. Portability comes from building
and testing the native wheels on the target platforms, not from the source
language. The CPython stable ABI reduces the wheel count across Python versions
but does not make one wheel work across different operating systems or CPUs.

The repository is Python-heavy mainly because the historical date grammar
contains thousands of lines of language rules and was carried over intact to
preserve its tested behaviour. Python also handles the public API, language
detection, phone matching and inference orchestration. The heavy NER tensor
operations are already native PyTorch or ONNX Runtime code, not Python loops.
A future port should follow profiling of representative documents rather than
targeting a source-language percentage.

### Integration

Python servers and a future Python-backed Hugging Face Space can import TEAVE
directly. The existing browser-only TeXplorer cannot install native CPython wheels.
Its current Python date adapter and browser ONNX model transport can stay in
place. A future browser port can expose the Rust scanner through WebAssembly and
keep Transformers.js for inference; use the same Unicode span contract and shared
golden fixtures. This revision does not modify or redeploy the demo.

See [RELEASING.md](RELEASING.md) for builds, CI and Trusted Publishing. TEAVE is
licensed under GPL-3.0-only; see [LICENSE](LICENSE).

