Metadata-Version: 2.4
Name: bg-text-normalizer
Version: 1.7.0
Summary: Bulgarian text normalization for TTS — converts numbers, dates, currency, abbreviations to spoken form
Author: Radi Totev
License-Expression: MIT
Project-URL: Homepage, https://github.com/raditotev/bg-text-normalizer
Project-URL: Repository, https://github.com/raditotev/bg-text-normalizer
Project-URL: Issues, https://github.com/raditotev/bg-text-normalizer/issues
Keywords: bulgarian,tts,text-normalization,nlp,speech-synthesis,bulgarian-language
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Multimedia :: Sound/Audio :: Speech
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Text Processing :: Linguistic
Classifier: Natural Language :: Bulgarian
Requires-Python: >=3.8
Description-Content-Type: text/markdown
License-File: LICENSE
Dynamic: license-file

# Bulgarian Text Normalizer for TTS

Converts written Bulgarian text into its spoken form, as a preprocessing step for Text-to-Speech (TTS). Numbers, dates, times, money, units, abbreviations, acronyms, Roman numerals and Latin names all come out as Cyrillic words, with no digits left.

## Features

| Category | Examples |
|----------|----------|
| **Numbers** | `1500` → `Хиляда и петстотин`, `2026` → `Две хиляди двадесет и шест`, `1.000.000` → `Един милион`, up to trillions |
| **Dates** | `15.02.2026 г.` → `Петнадесети февруари две хиляди двадесет и шеста година`, `на 4 V 2010 г.` → `на четвърти май две хиляди и десета година` |
| **Time** | `14:30 ч.` → `Четиринадесет часа и тридесет минути`, `Срещата е в 11:45.` → `Срещата е в единадесет часа и четиридесет и пет минути.`, `9:00 - 18:00` → `Девет часа до осемнадесет часа`, `2:03:59` → `Два часа три минути и петдесет и девет секунди` |
| **Currency** | `99.99 лв.` → `Деветдесет и девет лева и деветдесет и девет стотинки`, `12.50 €` → `Дванадесет евро и петдесет евроцента`, `$5` → `Пет долара`, `5 CHF` → `Пет швейцарски франка` (BGN, EUR, USD, GBP, CHF, JPY, CNY, RUB, TRY, RON, PLN, CZK) |
| **Scale words** | `1,5 млн.` → `Един и половина милиона`, `5 хил.` → `Пет хиляди` |
| **Units** | `1 км` → `Един километър`, `-5°C` → `Минус пет градуса Целзий`, `60 км/ч` → `Шестдесет километра в час`, `420 ppm` → `Четиристотин и двадесет части на милион`, `16 GB`, `3.2 GHz`, `5000 mAh`, `220 V`, `150 к.с.`, `1 ч.л.`, `800 евро/месец` → `Осемстотин евро на месец` |
| **Versions and hex** | `v1.29.0` → `версия едно точка двадесет и девет точка нула`, `Python 3.12` → `Python три точка дванадесет`, `т. 3.2` → `точка три точка две`, `0x53` → `Нула екс пет три` |
| **Digits in names** | `GP4` → `джи пи четири`, `ESP32 платка` → `и ес пи тридесет и две платка`, `V12` → `ви дванадесет` |
| **Fractions** | `3/4` → `Три четвърти`, `½ чаша` → `Половин чаша`, `1/2 година` → `Половин година`, `24/7` → `Двадесет и четири на седем`, `1/4 финал` → `четвъртфинал` |
| **Ranges** | `5-10 км` → `Пет до десет километра`, `2,0-3,5%` → `Два до три цяло и пет процента`, `2023-2024 г.` → `Две хиляди двадесет и трета до две хиляди двадесет и четвърта година`, `2025/2026 г.` → `Две хиляди двадесет и пета, двадесет и шеста година` |
| **Percentages** | `15.5%` → `Петнадесет цяло и пет процента`, `-15%` → `Минус петнадесет процента`, `1%` → `Един процент` |
| **Math and ratios** | `2 + 2 = 4` → `Две плюс две равно на четири`, `3:1` → `Три на едно`, `30x20 см` → `Тридесет на двадесет сантиметра`, `4x4` → `Четири по четири`, `±5`, `≈ 50`, `§ 5` |
| **Ordinals** | `21-ви` → `Двадесет и първи`, `5-ия` → `Петия`, `90-те` → `Деветдесетте`, `3-ма` → `Трима`, `2-те колеги` → `Двамата колеги`, `100-годишен` → `стогодишен`, `35-метров` → `Тридесет и пет метров`, `19 в.` → `Деветнадесети век` |
| **Scores and verses** | `Спечели с 8:13 т.` → `Спечели с осем на тринадесет точки.`, `Йоан 3:16` → `Йоан, глава три, стих шестнадесет`, `Товит 1:7` → `Товит първа глава, стих седем` |
| **Abbreviations** | `бул. Витоша, гр. София` → `булевард Витоша, град София`, `ЕС реши` → `Европейският съюз реши`, `на ЕС` → `на европейския съюз`, `мин. температура` → `минимална температура`, `пн.–пт.` → `от понеделник до петък`, `и др. гр.` → `и други градове` |
| **Acronyms** | Spelled with Bulgarian letter names: `БСП` → `Бе се пе`, `НСИ` → `Не се и`, `ДДС-то` → `Де де се-то`. Some have a fixed reading: `МВР` → `Ме ве ре`, `НДК` → `Ен де ка`. Acronyms said as a word stay a word: `НАТО реши.` → `Нато реши.`, `ГЕРБ` and `САЩ` stay as written |
| **Identifiers** | `ЕГН 8001011234`, IBANs, ISBNs and codes with a leading zero (`Код 0042` → `Код нула нула четири две`) digit by digit, `ivan@abv.bg` → `ivan кльомба а бе ве точка бе ге` |
| **Phone numbers** | `0888 123 456` → `Нула осем осем осем едно две три четири пет шест` |
| **Roman numerals** | `век XXI` → `век двадесет и първи`, `ХХ в.` (Cyrillic Х) → `двадесети век`, `Цар Симеон II` → `Цар Симеон втори`, `II световна война` → `Втората световна война` |
| **Symbols** | `№10` → `номер десет`, `No 15` → `номер петнадесет`, `t°` → `температура` |
| **Sentence starts** | A sentence that opens with a number opens with a capital: `100 години по-късно.` → `Сто години по-късно.`, `Тогава дойде. 21 евро струва.` → `Тогава дойде. Двадесет и едно евро струва.` |

## Usage

### Quick usage
```python
from bg_text_normalizer import normalize_text

result = normalize_text("На 15.02.2026 г. в 14:30 ч. цената е 1500.50 лв.")
# "На петнадесети февруари две хиляди двадесет и шеста година в четиринадесет
#  часа и тридесет минути цената е хиляда и петстотин лева и петдесет стотинки."
```

### Class-based usage
```python
from bg_text_normalizer import BulgarianTextNormalizer

normalizer = BulgarianTextNormalizer(expand_abbrevs=True, verbose=False)
result = normalizer.normalize("бул. Витоша №10, гр. София")
# "булевард Витоша номер десет, град София"
```

### Options

All options are on by default except `verbose`.

| Option | On | Off |
|--------|----|-----|
| `expand_abbrevs` | `бул. Витоша` → `булевард Витоша` | `бул. Витоша` stays. Numbers, units and money are still read |
| `spell_latin` | `USB кабел` → `ю ес би кабел`, `Модел X` → `Модел екс` | Latin stays Latin (`USB`, `GP четири`, `Модел X`) for a TTS model that reads Latin letters itself |
| `roman_numerals` | `Карл V` → `Карл пети` | A lone `V` after a name is a letter: `Карл ви`, or `Карл V` with `spell_latin=False`. Longer numerals such as `Борис III` stay as written |
| `verbose` | prints each change | silent |

A Roman numeral made of I, V and X after a capitalized Cyrillic name is read as an ordinal: `Борис III управлява.` → `Борис трети управлява.` A lone `I`, `V` or `X` counts only after a ruler's name or a title (`Петър I` → `Петър първи`). Turn `roman_numerals` off where names carry product numbers.

### Individual modules
```python
from bg_text_normalizer.bg_numbers import number_to_words_cardinal, number_to_words_ordinal
from bg_text_normalizer.bg_dates import normalize_date
from bg_text_normalizer.bg_currency import normalize_currency

number_to_words_cardinal(2500, gender='m')    # "две хиляди и петстотин"
number_to_words_ordinal(15, gender='m')       # "петнадесети"
normalize_date(15, 2, 2026)                   # "петнадесети февруари две хиляди двадесет и шеста"
normalize_currency("99.99", "BGN")            # "деветдесет и девет лева и деветдесет и девет стотинки"
```

These functions read the value you give them and see no context. Most of the rules below need the words around a number, so use `normalize_text` on real text.

## How context changes the reading

The same token can be read several ways. The normalizer picks a reading from the words around it, so the examples below are the rules in practice. Every example is the library's current output.

### Years: "г.", "през" and bare numbers

- A number followed by `г.` or `година` is a year and reads as an ordinal: `Книгата излиза в 1980 г.` → `Книгата излиза в хиляда деветстотин и осемдесета година.`
- A number right after `през` is a year too, even without `г.`: `Роден е през 1980.` → `Роден е през хиляда деветстотин и осемдесета.`, `През 1980 започва войната.` → `През хиляда деветстотин и осемдесета започва войната.`
- After `през`, a counted noun turns it back into a count: `През 2000 години се промени.` → `През две хиляди години се промени.`
- After a day and month name it is a year: `През май 1980 се върна.` → `През май хиляда деветстотин и осемдесета се върна.`
- Anywhere else a bare four-digit number is a plain number, also when it looks like a year: `В 1980 се върна.` → `В хиляда деветстотин и осемдесет се върна.`, `Книгата (1909) е стара.` → `Книгата (хиляда деветстотин и девет) е стара.`, `София, 1909.` → `София, хиляда деветстотин и девет.`, `През лятото на 1980 се върна.` → `През лятото на хиляда деветстотин и осемдесет се върна.` Add `г.` when you want the ordinal.
- Round hundreds and thousands take the article: `През 2000 г. се роди.` → `През двехилядната година се роди.`, `През 1500 г. се роди.` → `През хиляда и петстотната година се роди.`
- A short year after an apostrophe is a plain number: `през '89` → `през осемдесет и девет`.
- A year before `модел` is an ordinal: `за 2024 модел` → `за две хиляди двадесет и четвърти модел`.
- A sports season or school year written with a slash reads both years: `сезон 2024/25` → `сезон две хиляди двадесет и четвърта, двадесет и пета`.
- A date written with dots reads its year as an ordinal with or without `г.`: `15.02.2026` → `Петнадесети февруари две хиляди двадесет и шеста`. With `г.` it adds `година`.
- A range of years with `г.` reads `до`: `1989 г. – 1991 г.` → `Хиляда деветстотин осемдесет и девета година до хиляда деветстотин деветдесет и първа година.`
- A number after `№` and a slash is a year: `№ 3/2021` → `номер три от две хиляди двадесет и първа година.`

### "г.": year, grams or years

- `г.` after a number is a year by default (see above).
- Before a food or material noun it is grams: `Купих 500 г. брашно.` → `Купих петстотин грама брашно.`, `1000 г. захар` → `Хиляда грама захар`.
- Before an era it counts years: `Отидох там 500 г. пр. н. е.` → `Отидох там петстотин години преди новата ера.`
- After an age range it counts years: `деца 6-12 г.` → `деца шест до дванадесет години.`
- Two amounts in grams joined by a dash still read the first as a year: `100 г. – 200 г. захар` gives `Стотната година – двеста грама захар`. Write `грама` in full: `Купих 100 грама захар.` → `Купих сто грама захар.`

### "т.", "ст.", "ч." and other short forms

- `т.` after a number is points in sports text and tons elsewhere: `Отборът има 5 т. след мача.` → `Отборът има пет точки след мача.`, `Превозиха 5 т. пясък.` → `Превозиха пет тона пясък.` Before a number it is a point or item: `Виж т. 3.` → `Виж точка три.`
- `ст.` after a Roman century is a century, after an order it is a class, before `монети` it means old: `в XXI ст.` → `в двадесет и първи век.`, `„За храброст“ II ст.` → `„За храброст“ втора степен.`, `120 ст. монети` → `Сто и двадесет стари монети`.
- `ч.` after a number is hours: `Започна в 5 ч.` → `Започна в пет часа.`
- Adjective abbreviations agree with their noun: `ген. директор` → `генерален директор`.
- An abbreviation keeps its period only where the sentence ends. A lowercase Cyrillic word after it continues the sentence: `5 лв. на човек` → `Пет лева на човек`, `Платих 5 лв. Утре пак.` → `Платих пет лева. Утре пак.`

### The colon: time, score, ratio or verse

- An hour under 24 and two digits under 60 make a clock time, in hours and minutes: `в 10:05` → `в десет часа и пет минути`. `:00` drops the minutes: `Срещата е в 11:00 ч.` → `Срещата е в единадесет часа.`
- Anything else is a ratio or score: `Резултатът е 3:1.` → `Резултатът е три на едно.`, `16:9` → `Шестнадесет на девет`, `мащаб 1:100` → `мащаб едно към сто`.
- A score that looks like a time reads as a time unless `т.` or `точки` follows: `Загубиха с 21:15.` → `Загубиха с двадесет и един часа и петнадесет минути.`, but `Загубиха с 21:15 т.` → `Загубиха с двадесет и едно на петнадесет точки.`
- After a book of the Bible it is chapter and verse: `Йоан 3:16` → `Йоан, глава три, стих шестнадесет`, `II Хр. 5,5` → `Втора Летописи, глава пет, стих пет`. Without a book name it stays a time.

### Dots and commas in numbers

- A comma is a decimal point: `3,14` → `Три цяло и четиринадесет`, `1,000` → `Едно`.
- A dot is a decimal point too, unless it groups exactly three digits in a number with two or more groups (`1.000.000` → `Един милион`) or stands before money (`1.500 лв.` → `Хиляда и петстотин лева.`). So `1.000` → `Едно` and `1.5 кг` → `Едно цяло и пет килограма`. Write thousands as `1000` or `1 000`: `1 000 000` → `Един милион`, `100 000 лв.` → `Сто хиляди лева.`
- A decimal before `милиона`, `часа` and similar reads in halves where it can: `2,5 милиона` → `Два и половина милиона`, `2,5 часа` → `Два часа и половина`. Elsewhere it reads `цяло`: `2,5 км` → `Две цяло и пет километра`.
- A leading zero means a code, read digit by digit: `Код 0042` → `Код нула нула четири две`. So do phone numbers and ЕГН.

### Dash, slash and "x"

- A dash between numbers is a range read `до`, with or without spaces: `5-10 км` → `Пет до десет километра`, `Бяха 5 - 10 души.` → `Бяха пет до десет души.` A dash right before a number with nothing in front is a minus: `-5 градуса` → `Минус пет градуса`.
- A slash with no spaces is a fraction or a pair: `3/4` → `Три четвърти`, `Windows 10/11` → `Windows десет и единадесет`. With spaces it is left alone: `10 / 2` → `Десет / две`. Inside an equation it is division: `10:2=5` → `Десет делено на две равно на пет`.
- `x` between numbers reads `на` for sizes and `по` for `4x4`: `30x20 см` → `Тридесет на двадесет сантиметра`, `4x4` → `Четири по четири`.

### Numerals agree with the noun

- One and two follow the noun's gender, past any adjectives: `2 стола` → `Два стола`, `2 палта` → `Две палта`, `2 ключови битки` → `Две ключови битки`, `1 евро` → `Едно евро`, `2 евро` → `Две евро`. Plural genders come from the hand lists in `bg_numbers.py` and corpus counts in `bg_noun_data.py`.
- 2 to 6 take the personal form only before a plural listed as people: `5 работници` → `Петима работници`, `2 граждани` → `Двама граждани`, but `5 учебници` → `Пет учебници`. A masculine count form keeps the plain numeral: `2 брата` → `Два брата`. A person noun missing from the lists reads with the plain numeral.
- `-ма` after a number is a count of people, not an ordinal: `3-ма мъже` → `Трима мъже`, `7-ма родители` → `Седем родители`.
- With no noun after it, or after a label noun, a number takes the counting form: `стая 2` → `стая две`, `Купих 2.` → `Купих две.`
- A range's first number agrees too: `2-3 книги` → `Две до три книги`.
- `в` and `с` become `във` and `със` before a number word that starts with `в` or `с`: `в 2-ри клас` → `във втори клас`, `с 7 души` → `със седем души`.
- A day before a month name is an ordinal: `на 1 май` → `на първи май`.

### Acronyms, Latin and Roman numerals

- Cyrillic acronyms are expanded only in capitals and as whole words, so spelled-out Latin stays: `ес де а` → `ес де а`.
- Institutions take the full article as a subject and the short one elsewhere: `ЕС реши.` → `Европейският съюз реши.`, `Виж ЕС.` → `Виж европейския съюз.`
- A suffix stays on a spelled acronym: `ДДС-то` → `Де де се-то`.
- Latin acronyms are read with English letter names in Cyrillic: `USB кабел` → `ю ес би кабел`. Those said as a word get that word: `RAM` → `рам`. Mixed-case names stay as written: `iPhone 15` → `iPhone петнадесет`.
- Inside an IBAN the letters keep English names (`би джи`); elsewhere `BG` is `бе ге`.
- A Roman numeral after a Latin name is a model number: `Pentium II` → `Pentium две`. After a Cyrillic name it is an ordinal: `Борис III` → `Борис трети`. A lone `X` after an ordinary word is a letter: `Модел X` → `Модел екс`.
- Latin look-alike letters inside a Cyrillic word become Cyrillic: `ВIRTУАЛНАТА` → `ВИРТУАЛНАТА`.
- `v` before a version is `версия`, `V` before an engine size is a letter: `v1.2` → `версия едно точка две`, `V12` → `ви дванадесет`.
- Initials before a surname are read as letter names: `П. К. Яворов` → `Пе Ка Яворов`. A capital letter after a label is left alone: `вход Б.` → `вход Б.`

### Capitals and sentence ends

- A text or sentence that opens with a number opens with a capital: `100 години минаха.` → `Сто години минаха.` A text that opens in lowercase stays lowercase: `това е 100 години.` → `това е сто години.` No capital after a dash, inside brackets, or after an abbreviation left as written.
- An expanded acronym that opens a sentence is capitalized, so sentence splitting still sees the boundary: `БСП` → `Бе се пе`.

## Tips for use

- Normalize whole sentences or paragraphs, not fragments. The words around a number decide its reading: `5 т.` is points only with sports words nearby, and `през` must sit next to the year.
- Normalize before you split into sentences. The normalizer drops an abbreviation's period inside a sentence, so a splitter that runs first cuts at `гр.` or `т.`.
- Running the output through again changes nothing, and the test suite checks this. You can normalize text that is partly normalized.
- The output has no digits. Every character the normalizer doesn't know passes through unchanged, so check your TTS vocabulary for stray symbols. The `|` of a `SPEAKER|text` script line passes through.
- If a reading depends on meaning the text doesn't show (a year or a count, grams or a year), write the unambiguous form: add `г.` to a year, write `грама`, write `1000` instead of `1.000`.

## Integration with TTS training

Use the normalizer as a preprocessing step when you prepare training data:

```python
import json
from bg_text_normalizer import normalize_text

with open('raw_data.jsonl', 'r') as f_in, open('normalized_data.jsonl', 'w') as f_out:
    for line in f_in:
        entry = json.loads(line)
        entry['text'] = normalize_text(entry['text'])
        f_out.write(json.dumps(entry, ensure_ascii=False) + '\n')
```

At inference, normalize before synthesis:

```python
from bg_text_normalizer import normalize_text

def synthesize(text: str):
    normalized = normalize_text(text)
    # ... pass normalized text to the TTS model
```

## File structure

```
bg-text-normalizer/
├── src/
│   └── bg_text_normalizer/
│       ├── __init__.py                # Package entry point
│       ├── bg_normalizer.py           # Main orchestrator and context rules
│       ├── bg_numbers.py              # Cardinals, ordinals, decimals, noun gender lists
│       ├── bg_noun_data.py            # Plural genders and person nouns from corpus counts (generated)
│       ├── bg_dates.py                # Dates and years
│       ├── bg_time.py                 # Clock times
│       ├── bg_currency.py             # Currencies
│       ├── bg_scales.py               # хил., млн., млрд.
│       ├── bg_units.py                # Measurement units with count forms
│       ├── bg_abbreviations.py        # Abbreviations, institutions, acronyms
│       ├── bg_known_abbreviations.py  # Abbreviations with their sources
│       ├── bg_latin.py                # Latin acronyms and letters in Cyrillic
│       ├── bg_punctuation.py          # Keeps an abbreviation's period only at sentence end
│       ├── bg_phone.py                # Phone numbers
│       ├── bg_roman.py                # Roman numerals
│       └── bg_re.py                   # `re` with a larger pattern cache
├── gold/                              # Gold set and scorer (gold/score.py)
├── test_normalizer.py                 # Test suite
├── KNOWN-ISSUES.md                    # Findings, checks and what is left as is
├── pyproject.toml
└── README.md
```

## Adding abbreviations and readings

- Abbreviations: add a row to `KNOWN_ABBREVIATIONS` in `bg_known_abbreviations.py` with its full form, its sources and a mode (`always`, `context` or `unknown`). Each row needs a source: a dictionary, a style guide or a native speaker's ruling (`user`). Don't add forms nobody has checked.
- Cyrillic acronyms with a fixed reading: `INSTITUTION_ABBREVS` in `bg_abbreviations.py`. Latin ones: `LATIN_WORD_ACRONYMS` in `bg_latin.py`.
- Noun genders and person nouns: the lists in `bg_numbers.py` (`FEMININE_PLURALS`, `NEUTER_PLURALS`, `MASCULINE_PLURALS`, `PERSON_PLURALS`). Don't edit `bg_noun_data.py` by hand; `docs/superpowers/check-scripts/noun_data.py` builds it.
- Add a test to `test_normalizer.py` for each new reading. Run it with `uv run python test_normalizer.py`.

## Dependencies

None. Pure Python.
