Metadata-Version: 2.4
Name: ingush-text
Version: 0.1.0
Summary: Text normalization, palochka repair, tokenization, alphabet utilities, transliteration, and vigesimal numerals for Ingush (inh)
Author: Yunus Akhilgov
License-Expression: MIT
Project-URL: Homepage, https://paydadosh.ru
Project-URL: Repository, https://github.com/paydadosh/ingush-text
Project-URL: Issues, https://github.com/paydadosh/ingush-text/issues
Project-URL: Documentation, https://github.com/paydadosh/ingush-text#readme
Project-URL: Changelog, https://github.com/paydadosh/ingush-text/blob/main/CHANGELOG.md
Project-URL: Author ORCID, https://orcid.org/0009-0008-3127-094X
Keywords: ingush,inh,nakh,caucasian-languages,low-resource-languages,palochka,normalization,transliteration,nlp
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Text Processing :: Linguistic
Classifier: Typing :: Typed
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Provides-Extra: dev
Requires-Dist: pytest>=7.0; extra == "dev"
Dynamic: license-file

# ingush-text

Zero-dependency Python library for **Ingush** (ГӀалгӀай мотт, ISO 639-3 `inh`) text processing,
extracted from [PaydaDosh](https://paydadosh.ru).

Built for NLP/MT pipelines, search indexing, OCR post-processing, and linguistics tools working
with Ingush. Other North Caucasian Cyrillic orthographies share the palochka `Ӏ` and the
Latin-homoglyph problems, so parts of it may be useful there too (not tested on them).

- **Pure Python >= 3.11**, zero runtime dependencies, PEP 561 typed (`py.typed`).
- **Palochka-aware**: `tokenize` does not split words on uppercase `Ӏ` (U+04C0) or lowercase
  `ӏ` (U+04CF); the display helpers (`normalize_palochka_display`, `fix_palochka`, `clean_text`)
  repair `I / l / 1 / i / І / і` next to Cyrillic (Latin `L` only inside all-caps Cyrillic,
  `ГLАЛГLАЙ`) and leave numbers (`1941 шу`), Latin text (`Jack London 1941`), Roman numerals
  written in Latin letters and glued to a heading (`VIIIКХАЙКАНЗА`, `Корта IIНИКЪ`) and
  dictionary markers (`||`) alone. `clean_for_display` repairs the palochka the same way but is
  meant for plain display text: it removes `||` and folds dashes to `-`.
- **Diacritic-safe**: strips dictionary stress/length/brevity marks (`да́ха`, `ха̌р`, `мӑрха`)
  without decomposing Cyrillic `й` or `ё`.
- **Checked against PaydaDosh**: the search/index keys gave the same output as the site code on
  the approved headwords and definitions and the corpus sentences of the 28.11.2026 database
  (a check run outside CI; see [Parity with PaydaDosh](https://github.com/paydadosh/ingush-text#parity-with-paydadosh)).

## Install

```bash
pip install ingush-text
```

From source:

```bash
git clone https://github.com/paydadosh/ingush-text.git
cd ingush-text
pip install -e ".[dev]"
pytest
```

## Quickstart

```python
import ingush_text as it

# 1. Palochka normalization (display text — keeps numbers, Latin and Roman numerals intact)
it.normalize_palochka_display("1941 шу, г1алг1ай мотт, шоллагIа, Jack London, Корта IIНИКЪ")
# -> '1941 шу, гӀалгӀай мотт, шоллагӀа, Jack London, Корта IIНИКЪ'

# 2. OCR palochka repair (with optional wordlist for word-final positions)
text, fixes = it.fix_palochka("гIалгIай т1ехьаг1", known={"тӀехьагӀ"})
# text -> 'гӀалгӀай тӀехьагӀ'

# 3. Stress stripping & search/index normalization (preserves й and ё)
it.strip_stress("да́ха, гӀалгӀай, актёр")  # -> 'даха, гӀалгӀай, актёр'
it.normalize_for_index("ГIалгIай")         # -> 'гӏалгӏай'
it.normalize_for_search("Да́ха (идти)")    # -> 'даха идти'

# 4. Palochka- and diacritic-safe tokenization
it.tokenize("ЦӀи, да́ха а гӀалгӀай мотт")
# -> ['ЦӀи', 'даха', 'а', 'гӀалгӀай', 'мотт']
it.length_marks("да́ха")                   # -> frozenset({1})

# 5. 46-letter Ingush alphabet, collation, syllables, and pattern masks
it.letters("аьшкхьакха")
# -> ['аь', 'ш', 'к', 'хь', 'а', 'кх', 'а']
it.syllables("лоам")                       # -> 1
sorted(["аьхка", "аят", "бер", "аз"], key=it.sort_key)
# -> ['аз', 'аят', 'аьхка', 'бер']   (аь is a letter after а; plain sorted() puts аьхка before аят)
m = it.compile_mask("гӀ<м")                # < = vowel, > = consonant
m.match_word("гӀум")                       # -> True

# 6. Cyrillic -> Latin transliteration (1934 historical & Nichols ASCII)
it.transliterate("Аьттув хилба шун!", "1934")   # -> 'Ättuv xilba šun!'
it.transliterate("Аьттув хилба шун!", "ascii")  # -> 'Eattuv xilba shun!'

# 7. Historical 1929-1938 Ingush Latin -> Cyrillic
it.latin1930_to_cyrillic("Ghalghaj mott, čhoagha")
# -> 'ГӀалгӀай мотт, чӀоагӀа'

# 8. Vigesimal Ingush numerals (up to 10^21 - 1)
it.cardinal(44)                            # -> 'шовзткъе диъ'
it.ordinal(2)                              # -> 'шоллагӀа'
it.class_forms(14, "в")                    # -> {'collective': 'вийтте'}
```

## Modules & API

Everything listed here is exported from the top-level package (`import ingush_text as it`).
Names not listed are internal and may change without notice.

| Module | Exports | Purpose |
|---|---|---|
| `ingush_text.palochka` | `PALOCHKA` (`Ӏ` U+04C0), `PALOCHKA_LOWER` (`ӏ` U+04CF), `normalize_palochka_display`, `normalize_palochka_index`, `fix_palochka`, `fix_palochka_text`, `wordlist_key`, `load_wordlist` | Display/index palochka canonicalization and deterministic OCR palochka repair |
| `ingush_text.normalize` | `norm_space`, `strip_stress`, `strip_accents_latin_only`, `fold_latin_homoglyphs`, `fold_ocr_lookalikes`, `normalize_for_search`, `normalize_for_index`, `normalize_definition_safe`, `clean_for_display`, `clean_text`, `is_latin_heavy` | Search/index keys (PaydaDosh rules), homoglyph cleanup, stress removal, display/dataset cleanup |
| `ingush_text.tokenizer` | `WORD_MARKS`, `tokenize`, `length_marks`, `length_signature` | Word tokenization without splitting on `Ӏ` or vowel-length marks |
| `ingush_text.alphabet` | `LETTERS_RULE`, `ALPHABET`, `DIGRAPHS`, `VOWELS`, `CONSONANTS`, `SIGNS`, `fold`, `letters`, `encode`, `decode`, `strip_length`, `n_letters`, `syllables`, `last_letter_class`, `sort_key`, `rev_key`, `Mask`, `MaskError`, `compile_mask` | 46-letter Ingush alphabet (12 digraphs, `кхь` = `к`+`хь`), PUA collation, linguistic masks |
| `ingush_text.translit` | `SCHEMES`, `DEFAULT_SCHEME`, `RULES`, `clean_for_translit`, `transliterate`, `transliterate_all`, `palochka_unsure` (submodule also: `data`, `tokenize_letters`) | Cyrillic-to-Latin transliteration (`1934` and Nichols-based `ascii`) |
| `ingush_text.latin1930` | `latin1930_to_cyrillic` (submodule also: `UNITS`, `convert_word`, `iter_tokens`) | 1929–1938 Ingush Latin to modern Cyrillic conversion |
| `ingush_text.numbers` | `MAX_NUMBER`, `CLASS_LETTERS`, `cardinal`, `ordinal`, `class_forms`, `class_variable`, `class_note`, `number_to_words` | Base-20 (vigesimal) Ingush numerals up to `10^21 - 1` |

## Conventions & known notes

- **Input contract:** every text function takes `str` or `None`. `None` behaves like `""` and gives
  the empty result of the function (`""`, `[]`, `frozenset()`, `0`, `False`); `bytes` and other
  types raise `TypeError` — decode first. `compile_mask(None)` raises `MaskError` (empty mask).
  Numeral functions take an `int` and do not raise: `cardinal`/`ordinal` return `None` for
  anything that is not an `int` in range (`bool` included: `cardinal(True)` is `None`, the site
  gives `цаӏ`); `class_forms` returns `{}`, `class_variable` `[]` and `class_note` the
  "does not vary by class" text for such input; `number_to_words` also takes a digit string,
  treats `None` as `""` (`"error": "digits_only"`) and raises `TypeError` only on `bytes`.
- **Palochka code points:** display-facing functions (`normalize_palochka_display`, `fix_palochka`,
  `clean_for_display`, `clean_text`, `cardinal`, `ordinal`) return `Ӏ` (U+04C0, `PALOCHKA`) and
  preserve numbers and Latin text. Search/index functions (`normalize_for_index`,
  `normalize_for_search`, `normalize_palochka_index`, `wordlist_key`) use `ӏ` (U+04CF,
  `PALOCHKA_LOWER`) with a string-wide Cyrillic gate, so in index keys `"1941 шу"` becomes `"ӏ94ӏ шу"`.
  `cardinal()` / `ordinal()` default to `palochka="Ӏ"`; the PaydaDosh site writes `ӏ`, pass
  `palochka="ӏ"` to get its strings.
- **Roman numerals:** a run of two or more lookalikes *before* Cyrillic is left alone
  (`Корта IIНИКЪ`, `Глава IIВОЖАТЫЙ`); a run *after* Cyrillic becomes a double palochka, which is
  a real Ingush spelling (`теIIа` -> `теӀӀа`, `тӀӀийрг`). Not caught: a single `I` glued to a
  heading (`Глава IВОЖАТЫЙ` -> `Глава ӀВОЖАТЫЙ`) and a numeral typed with Cyrillic `Х`
  (`ХХХII` -> `ХХХӀӀ`): they cannot be told apart from a word.
- **`fix_palochka` is heuristic.** `|` and `!` are repaired only between two Cyrillic letters
  (`ц!и` -> `цӀи`) and are kept between a lowercase and an uppercase letter (verse breaks
  `вахар|ДӀадаьккхар`, missing spaces `Дика!Хьо`) and at the start of a token (`ер |сога`, `!хьо`);
  word-final positions are repaired only when `known` confirms the word. Check the returned `fixes`.
  For a big word list pass the result of `load_wordlist()` (used as is), a `frozenset` (normalized
  once and cached) or a predicate; a `set` or `list` is normalized again on every call.
- **`clean_for_display` differs from the PaydaDosh function of the same name**: this one returns
  the display palochka `Ӏ` and repairs it like `normalize_palochka_display` (next to Cyrillic only).
  The site one returns `ӏ` and uses the string-wide index gate, so in a string with Cyrillic it
  also turns digits and Latin letters into `ӏ` (`сантиметр 100` -> `сантиметр ӏ00`,
  `Maple клён` -> `Mapӏe клён`); here they stay.
- **Pattern masks:** a mask with `**` is matched against a phrase in O(len(mask) x len(key));
  `compile_mask` does not limit the mask length, so a service that takes masks from users should
  (PaydaDosh accepts at most 40 characters).
- **`cardinal(0)`** returns the PaydaDosh site string for zero for compatibility; it is not
  confirmed by a printed source.
- **No bundled dictionary data:** the wheel, the sdist and the repository contain only
  MIT-licensed code, small linguistic tables (`ingush_latin.json`) and short test strings. The
  reference pairs used to check parity with the site (fragments of dictionary definitions and
  corpus texts) are not distributed. `load_wordlist()` without a path returns `None`; word-final
  palochka repair in `fix_palochka()` accepts any user-supplied wordlist or callable `known`.
- **Transliteration schemes:** `1934` and `ascii` follow PaydaDosh's published draft (`draft-2026-10-31`).
  Letters absent from the 1934 alphabet (`ё`, `щ`, `ы`, `ь`, `яь`) carry tentative mappings marked in
  `ingush_text.translit.data()`.

## Parity with PaydaDosh

The functions below were run on the approved headwords and definitions and the corpus sentences
of the PaydaDosh database of 28.11.2026 next to the site code. The reference pairs are private
(the texts have no open license), so `tests/test_parity.py` is skipped in public CI and in the
sdist.

| Function | PaydaDosh code | Differences on the 28.11.2026 database, and in behaviour |
|---|---|---|
| `normalize_for_index`, `normalize_for_search` (with and without `drop_pipes`) | `app/normalize.py` | none |
| `normalize_palochka_display` | `app/normalize.py` | a run of two or more lookalikes after Cyrillic becomes `ӀӀ` here, `ӀI` on the site (`теIIа` -> `теӀӀа`, site `теӀIа`); Latin `L` between uppercase Cyrillic is repaired here, never on the site. On the database: 2 sentences (Roman numerals typed with Cyrillic `Х`) |
| `clean_text` | `tools/ml_ingush/textnorm.py` `clean` | the same, plus the circumflex is stripped: the combining `U+0302` (`Ва̂ха` -> `Ваха`) and precomposed Latin letters with it (`êtes` -> `etes`, `Ô` -> `O`); on the database: 15 strings |
| `fix_palochka` | `app/services/text_ocr.py` | a run of two or more letter lookalikes between Cyrillic letters becomes a double palochka here and is left as is on the site (`теIIа` -> `теӀӀа`, `тIIийрг` -> `тӀӀийрг`; site `теIIа`, `тIIийрг`); a Ukrainian `і` / `І` right after a repaired lookalike is repaired too (`а1і` -> `аӀӀ`, site `аӀі`); `\|` / `!` between a lowercase and an uppercase letter is kept (verse breaks); Latin `L` as above; on the database: 80 sentences |
| `tokenize` | `query_tokens` | a token made only of `\|` (`\|`, `\|\|`, `\|\|\|`) is dropped here (`мотт \|\| лоам` -> `['мотт', 'лоам']`), kept as a token on the site |
| `clean_for_display` | `app/normalize.py` | a different function by design: see *Conventions* above |
| `strip_stress`, `strip_accents_latin_only` | `app/normalize.py` | the input is composed (NFC) first, so a decomposed accent after a Latin letter is removed (`X` + `U+0301` -> `X`, the site keeps it) and a decomposed `а` + `U+0306` is treated like `ӑ` by `strip_stress` (-> `а`, the site keeps it) |

Other functions (alphabet, transliteration, numerals) are tested against the fixtures shared with
the site (`tests/fixtures/`), not against the whole database.

## License

**MIT** — see [LICENSE](https://github.com/paydadosh/ingush-text/blob/main/LICENSE). Copyright (c) 2026 Yunus Akhilgov.

## How to cite

See [CITATION.cff](https://github.com/paydadosh/ingush-text/blob/main/CITATION.cff), or:

> Akhilgov, Y. (2026). *ingush-text: text normalization, palochka repair, alphabet utilities,
> transliteration, and numerals for Ingush* (version 0.1.0). https://github.com/paydadosh/ingush-text

## Contact & related projects

- Website: <https://paydadosh.ru> · Telegram: [@paydadosh](https://t.me/paydadosh)
- [paydadosh-mcp](https://github.com/paydadosh/paydadosh-mcp) — open MCP server for the Ingush dictionary
- [ingush-frequency](https://github.com/paydadosh/ingush-frequency) — Ingush lemma frequency dictionary (27,774 words, CC BY 4.0)

---

## Кратко по-русски

`ingush-text` — открытая библиотека Python 3.11+ без внешних зависимостей (лицензия MIT) для работы с
ингушским текстом, вынесенная из проекта [PaydaDosh](https://paydadosh.ru):

- нормализация и починка палочки `Ӏ` (`U+04C0` / `U+04CF`) без порчи чисел (`1941 шу`), латиницы,
  римских цифр (`Корта IIНИКЪ`) и `||`;
- снятие ударений и пометок краткости с сохранением `й` и `ё`, свёртка латинских двойников;
- токенизация без разрыва слов на прописной палочке `Ӏ` и знаке долготы;
- 46-буквенный ингушский алфавит (12 диграфов, разбор `кхь = к + хь`), алфавитная сортировка, подсчёт слогов и поиск по маскам;
- транслитерация кириллицы в латиницу (`1934` и `ascii` по Николс) и обратное переложение латиницы 1929–1938 гг. в кириллицу;
- двадцатеричные ингушские числительные прописью до `10^21 - 1` (количественные, порядковые и классные формы).

Ключи поиска и индекса совпали с кодом сайта на базе от 28.11.2026 (проверка вне CI: эталонные пары
из текстов словарей и корпуса не распространяются); где и почему отличаются функции показа и починки
палочки — в разделе «Parity with PaydaDosh».
