Metadata-Version: 2.5
Name: ce-tagger
Version: 0.1.0
Summary: Find the words of a Chechen text that are not Chechen: Russian speech and loans the dictionaries do not attest
Project-URL: Homepage, https://github.com/chechen-language/ce-tagger
Project-URL: Repository, https://github.com/chechen-language/ce-tagger
Project-URL: Issues, https://github.com/chechen-language/ce-tagger/issues
Author-email: Chechen Language <chechen-language@proton.me>
License-Expression: MIT
License-File: LICENSE
Keywords: Chechen,code-switching,corpus cleaning,language identification
Classifier: Development Status :: 4 - Beta
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Topic :: Text Processing :: Linguistic
Requires-Python: >=3.10
Provides-Extra: ai
Requires-Dist: google-genai<4,>=2.29; extra == 'ai'
Requires-Dist: httpx<1,>=0.28.1; extra == 'ai'
Requires-Dist: pydantic<3,>=2; extra == 'ai'
Description-Content-Type: text/markdown

# ce-tagger

`ce-tagger` finds the words of a Chechen text that are not Chechen: Russian speech, and loans that no dictionary
attests. It is meant for cleaning a corpus before words are counted. It runs locally on the standard library, with
the model inside the package. An optional check asks a Gemini endpoint about the words the model has never met.

| Text | Marked |
| --- | --- |
| Машенаш некъа йистехьо гӏоьртина севцира. | nothing: `машен` is a loan the dictionaries list |
| Шайн эшарца, шайн гӏовгӏанца дӏакхечира уьш райцентре. | `райцентре` (ru) |
| Валлахӏ, ва биллахӏ, Васал, хӏокху тӏаьххьарчу деношкахь... | `валлахӏ`, `биллахӏ` (other) |
| Цо элира: «Товарищ начальник, я не знаю, что с ним делать». | all nine Russian words (ru) |

Requires Python 3.10 or later. Beta: the figures below are agreement with the labels of a large model, not accuracy
against a native-speaker gold standard.

## The rule

A word is marked as not Chechen when it is

- **Russian speech**: a reply, a quotation, a title, a Russian word dropped into a Chechen phrase. This is decided
  for each place in the text, so `и`, `а` or `да` can be Chechen in one sentence and Russian in the next;
- **a loan that no dictionary attests**, whatever its ending: `урканаш`, `райцентре`, `сборник`. A Chechen formation
  on a Russian root counts too (`бригадхо`, `гитлерхойн`) unless the word itself is listed.

A marked word carries a kind: `ru` (Russian speech, or came from or through Russian) or `other` (came from another
language: `биллахӏ`, `яраббий`).

Not marked: native words; loans the dictionaries list, in any of their forms (`машен`, `школехь`, `районерчу`);
Chechen formations on a root from another language (`ӏеламчаш`). Names are neither protected nor hunted.

The dictionaries are 12 titles, one of them a ten-volume dictionary of which one volume exists so far. A valid loan
that these dictionaries happen to miss is marked. This is deliberate: marking a legitimate loan is the cheaper
error, passing a foreign word as Chechen is the costly one.

## Installation

```bash
pip install ce-tagger            # or: uv add ce-tagger
pip install 'ce-tagger[ai]'      # with the optional origin check
```

## Quick start

```bash
ce-tagger text.txt -o cleaned.txt --marked marked.tsv --review review.tsv --unknown unknown.tsv
```

`text.txt` is the input. The other four are output files, each optional:

- `cleaned.txt` (`-o`): the text without the marked words.
- `marked.tsv` (`--marked`): the words that were marked, to see what was removed.
- `review.tsv` (`--review`): words that were kept, but the model was unsure about. A short list for a native
  speaker.
- `unknown.tsv` (`--unknown`): words found in neither the dictionaries nor the training data. This is what `--ai`
  would ask about.

Without them the command saves nothing and only prints a summary: how many words it marked and the most frequent
ones.

- `marked.tsv` and `review.tsv` are tab-separated, one row per place in the text: `doc`, `offset`, `word`,
  `p_not_chechen`, `kind` (`ru` or `other`, marked words only), `decided_by` (`model` or `ai`),
  `in_dictionaries_0_1_2` (2: the word is in the dictionaries, 1: it is a form of a dictionary word, 0: neither)
  and `context`.
- In the cleaned text a removed word becomes spaces, so offsets stay valid.
- The input can also be a `.json` / `.json.gz` corpus: a list of objects with a `text` field. The cleaned corpus
  keeps that structure.
- `--threshold P` marks words above this probability. The model's own threshold is 0.3.

```python
from ce_tagger import Tagger

tagger = Tagger()
result = tagger.tag("Шайн эшарца, шайн гӏовгӏанца дӏакхечира уьш райцентре.")
for token in result.marked:
    print(token.word, token.kind, round(token.p, 2), token.decided_by)   # райцентре ru 1.0 model
print(result.cleaned())

results = tagger.tag_many(texts)        # several texts as one job
```

Each `Token` has `start`, `end` (offsets in the text), `word` (normalised), `p` (probability that the word is not
Chechen), `marked`, `kind`, `decided_by` (`model` or `ai`) and `attested` (2 listed in the dictionaries, 1 a form
of a listed word, 0 no).

Speed: about 10 000 words per second on one core; the model loads in 1.5 s and takes about 340 MB of memory.

## Words the model does not know

The model knows a word when a dictionary attests it or the training corpus contains it. Any other word is judged by
its letters and neighbours. For a Russian word that mostly works. A loan from Arabic or a Turkic language looks
like a Chechen word and is mostly missed (see the table below).

The optional **origin check** sends exactly these words, each with up to three short examples from the text, to a
large model through a Gemini-protocol endpoint (Google's API, or a compatible gateway). Its verdict replaces the
local model's and the output records who decided.

```bash
export GEMINI_API_KEY=...
ce-tagger corpus.json.gz --ai --ai-model MODEL_NAME -o cleaned.json.gz --marked marked.tsv
```

The check is off by default. Answers are kept in a file, so a second run sends nothing and gives the same result,
and the file can be applied later without any network call. The check takes minutes instead of seconds, sends
parts of your text to the provider and spends the quota of your key: see [docs/origin-check.md](https://github.com/chechen-language/ce-tagger/blob/main/docs/origin-check.md).

## How well it works

Five-fold cross-validation by document on the training corpus; each document is tagged by a model that never saw
it. "New word" means the word occurs nowhere in the training folds, which is the situation on a new corpus.

| | Result at the model's threshold (0.3) |
| --- | --- |
| Russian speech found | 96.2% of 2 917 words |
| Loan from Russian found: word seen in training / new word | 98.9% / 72.4% |
| Loan from another language found: word seen in training / new word | 96.0% / 28.7% |
| Chechen word the dictionaries attest, marked by mistake | 110 of 593 663 |
| Native word the dictionaries do not attest, new word, marked by mistake | 2.1% |
| Kind right: `ru` / `other` | 97.3% / 83.4% |

Full tables, the test on a held-out part of a book and the weak spots are in [MODEL_CARD.md](https://github.com/chechen-language/ce-tagger/blob/main/MODEL_CARD.md).

## Limitations

- Agreement with a large model's labels is not accuracy. A native-speaker gold set does not exist yet.
- Trained on fiction, folklore and essays. News text has not been tested.
- Unknown loans from Arabic or Turkic languages are mostly missed without the origin check.
- Single Russian words far from other Russian (a title in quotes, an exclamation) are caught less often than
  Russian passages.
- Some everyday old loans are missing from the dictionaries and get marked as `other` (`къурӏан`, `хьаьким`).

## Development

```bash
uv run --extra ai --with pytest pytest
uv build
```

The offline tests cover the tagger, the answer file, the origin procedure, the command line and real SDK requests
to local HTTP servers. They need no key and no endpoint. `pytest tests/test_live_gemini.py --run-live` sends four
words to the endpoint set by `GEMINI_API_KEY`, `GEMINI_MODEL` and `GEMINI_BASE_URL`.

Report bugs or ask questions in [GitHub Issues](https://github.com/chechen-language/ce-tagger/issues).

## Data inside the model

The model file holds word counts from the training corpus, Russian word counts derived from the
[Leipzig Corpora Collection](https://wortschatz.uni-leipzig.de/en/download/Russian), word forms from 12 dictionary
titles, and about 85 000 weights. It holds no text. Sources and their terms are listed in
[MODEL_CARD.md](https://github.com/chechen-language/ce-tagger/blob/main/MODEL_CARD.md).
