Metadata-Version: 2.4
Name: cawn-etalon
Version: 0.1.4
Summary: Where every word and every letter of a known text begins and ends in its sound. No model, no training: numpy only.
License: Apache-2.0
Project-URL: Homepage, https://cawnai.com/blog/etalon
Keywords: forced alignment,speech,Serbian,Croatian,subtitles
Classifier: Programming Language :: Python :: 3
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Operating System :: OS Independent
Classifier: Topic :: Multimedia :: Sound/Audio :: Speech
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
License-File: NOTICE
Requires-Dist: numpy
Requires-Dist: num2words<0.6,>=0.5.14
Provides-Extra: hf
Requires-Dist: huggingface_hub; extra == "hf"
Requires-Dist: pyarrow; extra == "hf"
Provides-Extra: dev
Requires-Dist: pytest; extra == "dev"
Requires-Dist: black; extra == "dev"
Dynamic: license-file

<p align="center">
  <img src="https://raw.githubusercontent.com/DeanChugall/etalon/main/assets/etalon_banner.png?v=0.1.4" alt="Etalon: where every word and every letter of a known text begins and ends in its sound" width="100%">
</p>

<h4 align="center">
  <a href="https://cawnai.com/blog/etalon" target="_blank">How it works</a> |
  <a href="https://huggingface.co/spaces/datatab/etalon-demo" target="_blank">Live demo</a> |
  <a href="https://pypi.org/project/cawn-etalon/" target="_blank">PyPI</a>
</h4>

<p align="center">
  <a href="https://pypi.org/project/cawn-etalon/" target="_blank"><img src="https://img.shields.io/pypi/v/cawn-etalon.svg?style=flat-square&color=d3a64e" alt="PyPI version"></a>
  <a href="https://pypi.org/project/cawn-etalon/" target="_blank"><img src="https://img.shields.io/badge/python-3.9%2B-3c4552?style=flat-square" alt="Python 3.9 or newer"></a>
  <a href="https://github.com/DeanChugall/etalon/blob/main/LICENSE"><img src="https://img.shields.io/badge/code-Apache%202.0-3c4552?style=flat-square" alt="Code licence: Apache 2.0"></a>
  <a href="https://creativecommons.org/licenses/by-sa/4.0/" target="_blank"><img src="https://img.shields.io/badge/bank-CC%20BY--SA%204.0-3c4552?style=flat-square" alt="Bank licence: CC BY-SA 4.0"></a>
  <img src="https://img.shields.io/badge/languages-Serbian%20%7C%20Croatian-69b8a4?style=flat-square" alt="Languages: Serbian, Croatian">
  <img src="https://img.shields.io/badge/needs-numpy%20only-69b8a4?style=flat-square" alt="Needs numpy only">
  <a href="https://huggingface.co/spaces/datatab/etalon-demo" target="_blank"><img src="https://img.shields.io/badge/demo-Hugging%20Face-d3a64e?style=flat-square" alt="Demo on Hugging Face"></a>
</p>

Etalon finds where every word and every letter of a known text begins and ends in a recording of
it (forced alignment). It uses no neural model and needs no training and no graphics card: the
whole method is a few hundred lines of numpy and a small bank of sounds that ships with the
package.

- Serbian and Croatian, measured. Bosnian and Montenegrin work the same way and are not measured yet.
- Between half a minute and two minutes of work on a desktop processor for an hour of sound.
- A recording and its plain text are enough; no times, no subtitles and no cutting are needed.
- Works on one recording, or on a whole dataset read as a stream from Hugging Face.
- From the command line, from Python, or on a page in the browser.

The method is described in [Etalon](https://cawnai.com/blog/etalon).

## Install

```
pip install cawn-etalon              # one recording at a time
pip install "cawn-etalon[hf]"        # also whole datasets (adds huggingface_hub and pyarrow)
```

The command and the Python module are both called `etalon`.

Python 3.9 or newer. A plain 16 kHz mono `.wav` is read directly; any other sound needs `ffmpeg`
on the path.

## Use

### In the browser

```
etalon ui
```

A page opens on this computer (nothing is sent anywhere). Drop a recording, paste its text, and
hear the result with the word that sounds lit. The same page lays whole datasets and makes banks
for other languages, and shows the log of everything it works on.

### Command line

```
etalon recording.wav text.txt                       # -> recording.srt, recording.json
etalon recording.mp3 text.txt --format srt,vtt,json,tsv,textgrid,html --out folder/name
etalon recording.wav subtitles.srt                  # only the text of the subtitles is used
```

`--format html` writes a page to hear the result. On it, red words are the tenth of the words
that fit their sound worst and yellow the next 15 %. These marks are relative: a tenth of the
words is always red, in the best result too. They say where to listen first, not that a word is
wrong.

### Python

```python
import etalon

result = etalon.align("recording.wav", "text.txt", lang="sr")
for word in result["words"]:
    print(word["word"], word["start"], word["end"])     # seconds
etalon.save(result, "name", ("srt", "json"))
```

Every word also has its `letters` (letter, start, end), a `mark` (higher fits better) and a
`doubt` (0, 1 or 2). `result["fit"]` and `result["match"]` say whether the text belongs to the sound.

### A whole dataset

Every row a sound and its text. A Hugging Face repository is read as a stream, so nothing is
downloaded whole; a folder of parquet files on disk works too.

```
etalon dataset OWNER/NAME                                # shows the columns it has
etalon dataset OWNER/NAME --audio_column audio --text_column text --limit 100 --html 20
etalon dataset OWNER/NAME --audio_column audio --text_column text --speaker_column speaker --push OWNER/NEW
```

The rows are written out as parquet with new columns: `words`, `letters`, `etalon_slide`,
`etalon_mark`, `etalon_ok`. `--html 20` adds a page to hear the first 20 rows. `--push` sends the
result to a new repository, which is made private; its licence is yours to set.

## Languages

| `--lang` | language | bank of sounds | measured |
|---|---|---|---|
| `sr` | Serbian | its own (Serbian parliament) | yes |
| `hr` | Croatian | the Serbian one | yes |
| `bs`, `me` | Bosnian, Montenegrin | the Serbian one | not yet |
| any other code | a language said the way it is written | made by you, once ([below](#banks-of-sounds)) | no |

A language Etalon does not have yet needs a bank of sounds, made once (see
[Banks of sounds](#banks-of-sounds)). After that Etalon lays that language by itself:

```
etalon bank OWNER/NAME --lang sl --audio_column audio --letters_column letters --speaker_column speaker
etalon recording.wav text.txt --lang sl
```

Numbers written in digits are read out: by Etalon's own tables for the four languages above, by
the package `num2words` for the others it knows. Where neither can, write the numbers as words.

Languages written one way and said another (English, French) are beyond this method: they would
need a dictionary of pronunciations.

## Banks of sounds

Etalon lays a text over a sound by comparing the sound with a **bank**: the usual sound of every
half of every letter, next to each of its neighbours. A bank is made once, from speech whose
letter times are already known, and then used for any recording of that language.

One bank comes with Etalon, the *parliament's*, made from speech of the Serbian parliament. It
serves Serbian, Croatian, Bosnian and Montenegrin. You can make more: the bank of a new language,
or one more bank for a language that already has one (speech from the radio, from video, from a
telephone line sounds different from a parliament hall, and a bank made from it fits it better).

### The file: `NAME.etalon`

One file is one bank, with everything that belongs to it. It is a plain zip archive; any unzip
shows what is inside:

```
$ unzip -l youtube-v1.etalon
       25  mimetype              application/x-etalon-bank
      843  card.json             what the bank is (below)
     1168  mean.npy              the middle of all rows
    41728  projection.npy        the turn that pulls the sounds apart
    31168  alone.npy             every half of a letter on its own
  1474688  with_neighbour.npy    every half of a letter with its neighbour
```

`card.json` is the card of the bank:

| field | what |
|---|---|
| `name` | the name the bank is asked for by, e.g. `youtube-v1` |
| `language` | the language it is for (`sr` stands for sr, hr, bs and me together) |
| `made` | when it was made |
| `source`, `hours`, `rows`, `speakers` | what it was made from |
| `licence` | the licence of that speech, as you gave it with `--licence` |
| `beside` | for one more bank: the bank that found the voices while it was made |
| `check` | how it did on rows kept out of it (below) |
| `letters` | the letters it knows and their numbers |
| `format` | the number of this file format (now 1); a newer Etalon still reads older files |
| `sha256` | the fingerprint of its numbers and letters |

**There is no code in the file, and none is run when it is read.** The four tables are numpy
arrays read with pickling switched off; the card is JSON. A bank file from somebody else can be
opened safely. The fingerprint is checked every time a bank is read: a file whose numbers or
letters were changed after it was written is refused. (The words of the card - source, licence -
are not part of the fingerprint; they describe the bank, they are not the bank.)

Up to 0.1.3 Etalon kept banks as Python pickles. A pickle can run code when it is read, so those
files are read only from your own disk and are never sent or fetched. `etalon banks convert NAME`
writes one again as `NAME.etalon` and keeps the old file as `.bak`.

### The banks on your computer

```
etalon banks                 # every bank: what it is for, what it was made from, its check, its file
etalon banks remove NAME     # take a bank you made away (it asks first; --yes does not)
```

Your banks lie in `~/.etalon/` (or in `ETALON_DATA`), one file each. The bank that comes with
Etalon cannot be removed or replaced. The same list, with a Remove button, is on the page
`etalon ui` under "Banks of sounds", where a bank can also be made.

### Making a bank

From a dataset that has, for every row, its sound and a list of `{letter, start, end}` (seconds
from the start of the row) - the output of another aligner. Hugging Face (read as a stream) or a
folder of parquet files; this needs `pip install "cawn-etalon[hf]"`.

**The bank of a new language** is called by the code of the language:

```
etalon bank OWNER/NAME --lang sl --audio_column audio --letters_column letters --speaker_column speaker
etalon recording.wav text.txt --lang sl
```

With `--speaker_column` it is made in two rounds, every speaker moved to a standard voice first,
as the parliament's was; without it in one round, and it is blunter.

**One more bank for a language that has one** gets a name of its own:

```
etalon bank OWNER/NAME --lang sr --name youtube-v1 --audio_column audio --letters_column letters --licence "CC BY 4.0"
etalon recording.wav text.txt --bank youtube-v1
```

It is made in one round: the first bank of the language finds the voice of every speaker (or,
with no `--speaker_column`, of every row). Without `--bank`, Etalon tries every bank of the
language on the first minute and a half of a recording and lays with the one that fits best - so
a bank you add takes part from then on, also for recordings you laid before. Ask for a bank by
name when the result must not depend on which banks happen to be on the computer.

Making a bank cannot quietly go wrong:

- `sr`, `hr`, `bs`, `me` and `parliament` are taken. A bank simply called `sr` would never be
  used, so it is refused; `--lang sr --name youtube-v1` is how one more bank for them is made.
- A bank that is already there is not replaced unless you add `--overwrite`; the old one is then
  kept beside the new one as `NAME.etalon.bak`.
- Letter times that do not fit the sound (milliseconds instead of seconds, or counted from the
  start of the whole recording) stop the work on the first 50 rows.
- When the bank is made it is tried on rows that were kept out of it (one in 20), and you are
  told how many letter starts it finds within 50 ms of the dataset's own times. Below 50% the
  bank is called poor. This says whether the bank was made from sound data. It does not say how
  right the dataset's times are: Etalon can only be as good as the aligner it learned from.

### Versions

A name means one bank, for good. When you make a better bank - more speech, other speech - give
it a new name, `youtube-v2`, and keep `youtube-v1`: then the two can be compared on the same
recordings, a result can say which bank gave it (`result["bank"]`, and the line "taken: the bank
..."), and going back is one word. `--overwrite` exists, but a version that is written over can
no longer be told from the one before.

The banks of one language are used together, so they must number their letters the same way. A
bank made on this computer does: it takes the numbers of the banks that are there and gives new
letters the next ones. A bank brought from another computer, where other banks were there, may
not agree; `etalon banks` then lists it as *not used* and says why.

### A store of banks on Hugging Face

To keep your banks somewhere other than one computer, and to hand a bank to another computer of
yours - or to somebody you choose:

```
etalon banks push youtube-v1 --repo OWNER/NAME     # send a bank to the store
etalon banks --repo OWNER/NAME                     # what the store holds
etalon banks pull youtube-v1 --repo OWNER/NAME     # fetch one to this computer
```

`ETALON_BANKS_REPO` can name the store once, instead of `--repo` every time. The store is a model
repository. It needs `pip install "cawn-etalon[hf]"` and a login of this computer
(`huggingface-cli login`) that may write to it, or read it.

- **The store is private.** `push` makes the repository if it is not there, and makes it
  private. A bank is not sent to a repository that is public unless you add `--public`. Who may
  fetch is decided on Hugging Face, by who has access to the repository.
- **A name in the store is a version.** `push` does not write over a bank that is there; a bank
  that changed goes up under a new name. (`--overwrite` forces it.)
- **Only `.etalon` files travel**, and a fetched file is read in full and checked against its
  fingerprint before it is kept. A bank of that name already on the computer is not replaced
  unless you add `--overwrite` (it is then kept as `.bak`).
- In the store a bank is two files, `NAME.etalon` and `NAME.json` (a copy of its card, so that
  the store can be listed without fetching every bank).

A bank is made *from* speech, and the licence of that speech decides what may be done with the
bank. The parliament's bank comes from ParlaSpeech-RS 4.0 and is shared under the same licence,
CC BY-SA 4.0. For your own banks, write the licence of the speech into the card with `--licence`
while you still know it; before you give a bank to anybody, make sure that licence allows it.
Etalon does not check this and cannot.

### In Python

```python
import etalon

etalon.list_banks()                                # BankInfo: name, kind, language, path, made, info (the card), usable ...
etalon.align("recording.wav", "text.txt", bank="youtube-v1")
bank, letters, card = etalon.read_bank_file("youtube-v1.etalon")

from etalon.dataset import make_language_bank
make_language_bank("OWNER/NAME", "sr", "audio", "letters", name="youtube-v1", licence="CC BY 4.0")

etalon.push_bank("youtube-v1", "OWNER/NAME")       # the store is made private
etalon.pull_bank("youtube-v1", "OWNER/NAME")
etalon.remove_bank("youtube-v1")
```

## Accuracy

The share of word starts that lie within 50 ms of the times of another aligner. Those times are
not the truth, only the ruler that exists.

| speech | against | within 50 ms |
|---|---|---|
| Serbian parliament, short pieces | times published with ParlaSpeech-RS | 93.8 % (MFA on the same: 93.9 %) |
| Serbian videos, short pieces, one speaker (14 videos) | Montreal Forced Aligner | 88.5 % |
| Serbian video of 90 minutes, several speakers | Montreal Forced Aligner | 87.3 % |
| Serbian, a whole hour from its plain text | Montreal Forced Aligner | 85.4 % |
| Croatian parliament, one hour, Serbian bank | times published with ParlaSpeech-HR | 81.2 % (97.1 % within 100 ms) |

## Settings

Every setting is an argument of the command; some can also be set as a variable of the terminal.

| argument | variable | what it does |
|---|---|---|
| `--lang CODE` | `ETALON_LANG` | the language (default `sr`) |
| `--slide MODE` | `ETALON_SLIDE` | one voice or several. `auto` (default): Etalon decides. `video`: one voice, the fastest. `piece`: always several |
| `--fit 65` | `ETALON_FIT` | the text must explain at least so many percent of the start of the sound, or a warning is given and the command exits with 2 |
| `--bank NAME` | | which bank of sounds (default `auto`: every bank of the language is tried on the start, the best fit is taken) |
| `--repo OWNER/NAME` | `ETALON_BANKS_REPO` | the store of banks, for `etalon banks push` / `pull` |
| `--minutes N` | | only the first N minutes of the recording |
| | `ETALON_DATA` | a folder to keep the banks in, instead of `~/.etalon` |

## How it works

1. **Rows.** The sound becomes one row of 26 frequency bands every 10 ms. A *slide* moves the
   bands of a speaker towards a standard voice; there are 9 slides.
2. **Bank.** From speech whose letter times are known, the bank keeps the usual row of every
   half of a letter together with its neighbour.
3. **Path.** The text becomes a chain of letter halves and silences, and the chain is stretched
   over the rows of the sound so that the sum of the fits is the largest.
4. **Voices.** Pieces spread over the recording each pick the slide that fits them. If they
   agree it is one voice; if they do not, several people talk and every piece gets its own slide.

## Limits

- The text must be what is said. Abbreviations must be written the way they are spoken; numbers
  in digits are read in their basic form.
- The check "does the text belong to the sound" looks only at the first minute and a half, and
  works only where the recording is mostly speech. With street noise or music and little speech
  a wrong text can pass.
- Bosnian, Montenegrin and banks made for other languages are not measured.
- The times of word ends agree with other aligners less than the times of word starts.

## Development

```
pip install -e ".[dev]"
pytest            # needs no sound
black .           # line length 110
```

The code lies in folders by what it does:

| folder | modules | what |
|---|---|---|
| `etalon/` | `config.py`, `errors.py` | constants and file locations; the one error |
| `audio/` | `reading.py`, `features.py` | reading the sound; its rows of 26 bands, the 9 slides |
| `text/` | `words.py`, `numbers.py`, `languages.py` | words to the letters that are said, numbers, languages |
| `soundbank/` | `model.py`, `format.py`, `files.py`, `repo.py` | what a bank is; its file `NAME.etalon`; the banks on the disk; the store on Hugging Face |
| `laying/` | `path.py`, `slide.py`, `align.py` | a text stretched over its sound; the slide; `align` and `align_all` |
| `output/` | `subtitles.py`, `pages.py`, `save.py` | srt, vtt, tsv, TextGrid; pages to hear; writing the files |
| `dataset/` | `files.py`, `rows.py`, `language_bank.py`, `bank_check.py` | whole datasets; making and checking the bank of a language |
| `app/` | `cli.py`, `ui.py`, `ui.html`, `bank_words.py` | the command line and the page in the browser |

What is meant to be used from outside is on the package itself (`etalon.align`, `etalon.save`,
`etalon.list_banks` ...) and in `etalon.dataset` (`align_dataset`, `make_language_bank`).

## Licence

The code is under the Apache License 2.0 (see `LICENSE`).

The bank of sounds, `etalon/data/bank_parliament.etalon`, is derived from
[ParlaSpeech-RS 4.0](http://hdl.handle.net/11356/1885) (CLARIN.SI) and is shared under the same
licence, [CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/).
