Metadata-Version: 2.4
Name: JointRecAlign
Version: 0.1.5
Summary: Joint phone recognition and alignment with wav2vec2 (CTC + cross-attention aligner)
Author: ImenBA
License-Expression: MIT
Project-URL: Homepage, https://github.com/Imenbaa/Joint_fr_phoneme_recognition_alignment
Project-URL: Repository, https://github.com/Imenbaa/Joint_fr_phoneme_recognition_alignment
Project-URL: Documentation, https://github.com/Imenbaa/Joint_fr_phoneme_recognition_alignment/blob/main/GUIDE.md
Project-URL: Issues, https://github.com/Imenbaa/Joint_fr_phoneme_recognition_alignment/issues
Project-URL: Model release, https://github.com/Imenbaa/Joint_fr_phoneme_recognition_alignment/releases/tag/v0.1.0
Keywords: phone recognition,forced alignment,wav2vec2,CTC,speech,phonetics,French,Praat,TextGrid
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Science/Research
Classifier: Natural Language :: French
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
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
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: torch>=2.1
Requires-Dist: torchaudio>=2.1
Requires-Dist: transformers>=4.41
Requires-Dist: numpy
Requires-Dist: soundfile
Requires-Dist: soxr
Requires-Dist: Levenshtein
Requires-Dist: jiwer
Requires-Dist: silero-vad>=6.2
Provides-Extra: train
Requires-Dist: datasets; extra == "train"
Requires-Dist: accelerate; extra == "train"
Requires-Dist: editdistance; extra == "train"
Requires-Dist: tensorboard; extra == "train"
Provides-Extra: eval
Requires-Dist: librosa; extra == "eval"
Requires-Dist: pandas; extra == "eval"
Dynamic: license-file

# A joint French phoneme recognition and alignment model

[![PyPI](https://img.shields.io/pypi/v/JointRecAlign)](https://pypi.org/project/JointRecAlign/)

Joint **phone recognition and phone alignment** for French speech, with one wav2vec2 model.
A CTC head transcribes the speech into phones. A cross-attention aligner, trained in the same
network, places each phone in time, with optional silences. The same model gives the phone
sequence and its segmentation, at 10 ms resolution.

This repository has the code to train the models from scratch and to transcribe recordings into
Praat TextGrids (phones, boundaries, pauses and the model's top-5 candidates for each phone),
with no transcript needed.

**Phoneticians: start with the [step-by-step guide](https://github.com/Imenbaa/Joint_fr_phoneme_recognition_alignment/blob/main/GUIDE.md)**: install with two commands, then
transcribe a corpus with one command (with an optional HTML report of the plots).

## Contents

- [Installation](#installation)
- [Transcribing recordings](#transcribing-recordings)

## Installation

Python ≥ 3.10. Runs on the CPU, or on an NVIDIA GPU when there is one.

**To transcribe recordings only**, see the [step-by-step guide](https://github.com/Imenbaa/Joint_fr_phoneme_recognition_alignment/blob/main/GUIDE.md) (no Python
knowledge needed), or, in a Python environment, run the commands for your computer:

macOS, or Windows without an NVIDIA GPU:

```bash
pip install JointRecAlign
```

Linux with an NVIDIA GPU:

```bash
pip install JointRecAlign
```

Linux without an NVIDIA GPU:

```bash
pip install torch torchaudio --index-url https://download.pytorch.org/whl/cpu
pip install JointRecAlign
```

Windows with an NVIDIA GPU:

```bash
pip install torch==2.9.0 torchaudio==2.9.0 --index-url https://download.pytorch.org/whl/cu128
pip install JointRecAlign
```

This installs the `JointRecAlign` command.

## Transcribing recordings

`JointRecAlign` (or `python transcribe.py` from the repository root) gives, for each
recording, the phones the model hears, their boundaries, the pauses, and the model's five best
candidates for each phone. It runs on GPU or CPU.

```bash
JointRecAlign validate recordings_folder/                 # check the audio files (no model)
JointRecAlign transcribe recordings_folder/ [-o out/]     # check, then transcribe
JointRecAlign transcribe recordings_folder/ --report      # + one HTML page per recording, index.html
JointRecAlign transcribe recordings_folder/ --reference textgrids/   # + comparison with reference TextGrids
JointRecAlign align recordings_folder/ --phones phones_folder/        # forced alignment of your phones
```

`transcribe` checks every file first (readable, not silent; warnings for a
sampling rate under 16 kHz, several channels, clipping, very low level, two recordings that
would write the same result files), skips the files that cannot be transcribed, goes on when
one fails, and ends with a summary, also written to `JointRecAlign.log`. The exit code is 1 when
a recording was not transcribed.
Recordings of any length are accepted: from about 0.1 s the model finds phones (below, there is
too little sound for one); `align` refuses audio under 25 ms, where the model has no frame.

Audio: WAV, FLAC, MP3, OGG or AIFF, any sampling rate, mono or stereo (resampled to 16 kHz and
downmixed). A folder means every audio file in it. A recording that cannot be read is reported
and the others are still transcribed.

For each recording, in a folder `JointRecAlign/` next to the recording (or in `-o`), and
`JointRecAlign.log`:

| file | content |
|---|---|
| `<name>.TextGrid` | Praat interval tiers, all covering the whole recording |
| `<name>.csv` | one row per phone: `start`, `end`, `phone`, then `top1`, `p1` ... `top5`, `p5` |
| `<name>.html` | with `--report`: waveform, spectrogram, phones and pauses, the aligner's attention with the alignment path, the CTC posteriors of every phone, the five candidates of each phone coloured by probability, on one time axis that scrolls and zooms; self-contained, no server (`index.html` lists the recordings) |

| tier | label of each interval |
|---|---|
| `phones` | the recognised phone (empty between phones) |
| `confidence` | probability of that phone |
| `top2` ... `top5` | the next candidates, as `symbol probability` (e.g. `p 0.050`) |
| `pauses` | `SIL` on every pause the model detected |

| option | meaning |
|---|---|
| `-o folder` | where the results go (default: `JointRecAlign/` next to each recording) |
| `--report` | also the HTML pages (about 3.5 MB per minute of audio) |
| `--copy_audio` | with `--report`: copy each recording into `<results>/audio/`, so the pages still play it after the results folder is moved or copied to another computer |
| `--model folder` | another model (default: the released one, downloaded the first time) |
| `--symbols ipa` (default) / `model` | `ipa` writes the nasal vowels and œ in IPA (`ɑ̃ ɛ̃ ɔ̃ œ`); `model` keeps the model's one-character codes (`@ 1 § 9`) |
| `--phone_map map.json` | your own labels, applied last, e.g. `{"ə": "ø"}` for a corpus that writes the schwa `ø` |
| `--max_chunk 10` | longest piece of audio the model sees at once, in seconds |
| `--vocab_path` | phone vocabulary (default: `vocab.json` in the checkpoint) |
| `--device cuda` / `cpu` | default: `cuda` when available |

**Forced alignment.** `align` takes the phones from `--phones folder`: `<name>.TextGrid` (a phone
tier, `--phones_tier`; its times are not used) or `<name>.txt` (phones separated by white space),
and aligns them in place of the CTC decode, with the same SIL-Viterbi decode (boundaries and
pauses) and the same outputs. Labels are read as IPA or model symbols, plus `g`, `r`, `ʀ`, `ɥ`
(-> `y`), `œ̃` (-> `ɛ̃`); `--phones_map map.json` maps the others; pause labels are dropped. The
candidate tiers remain the CTC posteriors inside each aligned phone, so they show where the model
hears something else. A recording longer than `--max_chunk` is decoded chunk by chunk first, and
each given phone goes to the chunk of the decoded phone it matches (edit-distance alignment).

**Comparison with a reference** (`--reference FOLDER`, `jointrecalign/reference.py`): for
`<name>.wav`, the phone tier of `FOLDER/<name>.TextGrid` (`--ref_tier`, default the tier named
`phones`/`phonemes`/..., else the first interval tier) is compared with the transcription with these
metrics:

| figure | meaning |
|---|---|
| PER | substitutions + deletions + insertions over the reference phones |
| F1 20 ms / 50 ms | boundary detection: every phone onset and offset; each reference boundary is matched one-to-one to the nearest recognised boundary within 20 / 50 ms |
| median error | median \|error\| of the starts and ends of the phones recognised with the reference label |
| pause P / R / F1 | reference pauses matched one-to-one by a recognised pause (time not covered by a phone) with intersection over union ≥ 0.5 |

Empty intervals and `--pause_labels` (default `SIL sil sp spn _ # <p:>` ...) are reference pauses,
`--skip_labels` (e.g. `noise,overlap`) are left out, and `--ref_map map.json` rewrites the other
labels into the model's phones (e.g. `{"ø": "ə"}` for a corpus that writes the schwa `ø`). The
summary lists the reference labels that are not phones of the model; they count as errors. Results:
`comparison.csv` (one row per recording and a `TOTAL` row; corpus figures pool the counts of all
recordings), the scores in the summary and, with `--report`, in the pages: reference lane under the
recognised phones (amber: substituted, red: inserted / deleted), reference boundaries and pauses
in red on the attention, reference phones as red boxes on the posteriors, on the top 5 a reference
strip with each recognised phone's candidates outlined in green (reference = 1st) or red
(reference among the others), and a "show reference" switch. A reference TextGrid is never overwritten (`-o` into the reference folder
is refused when the names collide).

**The model's phones.** The model writes 34 French phones (IPA, the default `--symbols ipa`):

| | |
|---|---|
| oral vowels | `i e ɛ a ɔ o u y ø œ ə` |
| nasal vowels | `ɑ̃ ɛ̃ ɔ̃` |
| semi-vowels | `j w` |
| consonants | `p b t d k ɡ f v s z ʃ ʒ m n ɲ ŋ l ʁ` |

It has no `ɥ` (it writes `y`), no `œ̃` (it writes `ɛ̃`) and no `r` or `ʀ` (it writes `ʁ`); its `ɡ`
is the IPA letter, not the keyboard `g`.

**When the reference phones are not written with these symbols, give a map file**
(`--ref_map map.json`, `{"reference label": "model phone"}`), e.g. `{"g": "ɡ", "ɥ": "y", "œ̃": "ɛ̃", "r": "ʁ", "a~": "ɑ̃", "E": "ɛ"}`. Without it,
every reference label that is not a model phone counts as an error (PER goes up, and the median error
leaves these phones out; boundary F1 and pause scores do not use the labels), and the summary, also in `JointRecAlign.log`, lists these
labels with their counts. Unlisted labels are kept as they are. With `--symbols model` or
`--phone_map`, the reference is compared with those output labels instead.

How it works (`jointrecalign/transcribe.py`):
1. The recording is cut into pieces of at most 10 s, back to back, so no audio is dropped.
   [Silero VAD](https://github.com/snakers4/silero-vad) finds the pauses; each cut goes in the
   middle of the latest pause within 10 s (or, with no pause, where speech is least likely).
2. For each piece: the CTC head gives the phones; a Viterbi pass over
   `[SIL] p1 [SIL] p2 ... [SIL]` on the aligner gives their boundaries and the pauses.
   A pause cut in two by a piece boundary is joined back into one.
3. The candidates of a phone are the CTC posteriors at the frame where that phone is most
   probable, over the phone symbols only, renormalised to sum to 1.

Read the probabilities with care: they are the model's own and are **not calibrated**. The top-1
is often given about 0.99 even when it is wrong, but the **order** of the candidates is
informative: when the top-1 is wrong, the right phone is 2nd in 29 to 57 % of the cases and in the
top 5 in 53 to 79 %, depending on the kind of speech (measured against reference transcriptions; see
GUIDE.md, "How far to trust the candidates").

The model cannot see the first and last ~10 ms of each piece, so a gap of 15 to 25 ms with no
label is left at each cut (about every 10 s) and at the start and end of the recording.

## Generative AI Use Disclosure

The code in this repository was refactored, organised and refined with the aid of
[Claude Code](https://claude.com/claude-code) (Anthropic).

## License

Code: MIT, see `LICENSE`. Released model weights: [CC BY-NC 4.0](https://creativecommons.org/licenses/by-nc/4.0/)
(non-commercial use, with attribution).
