Metadata-Version: 2.4
Name: disfluency-restoration
Version: 0.1.1
Summary: Word-level forced alignment for RSML transcripts using wav2vec2 / MMS CTC models.
Author-email: radheshyam.scsvmv@gmail.com
License-Expression: MIT
Project-URL: Source, https://github.com/OpenBhasha/forced-aligment
Project-URL: Issues, https://github.com/OpenBhasha/forced-aligment/issues
Keywords: forced alignment,speech,ASR,RSML,wav2vec2,CTC,disfluency,transcription
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Science/Research
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
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: Natural Language :: English
Classifier: Natural Language :: Hindi
Classifier: Natural Language :: Telugu
Classifier: Topic :: Multimedia :: Sound/Audio :: Speech
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: numpy
Requires-Dist: torch
Requires-Dist: transformers
Provides-Extra: num2words
Requires-Dist: num2words; extra == "num2words"
Provides-Extra: uroman
Requires-Dist: uroman; extra == "uroman"
Dynamic: license-file

# disfluency-restoration

**Word-level forced alignment for RSML transcripts.**

Give it an audio file and an RSML transcript with segment-level timestamps. It returns a new RSML file in which every
segment is followed by its words, each with its own start and end time and quality metadata. Spoken fillers
(`@uhh`), pauses and disfluency spans (`@repetition-start`) are kept and timed as well.

```
In this lecture, we will start a new topic ...
	00:00:14,820 --> 00:00:14,937
	confidence=1.000|weakest_letter_confidence=1.000|voiced_fraction=1.00|pause_after_milliseconds=0|...|flagged=0
	In
```

## Features

- Word-level start/end timestamps for every segment of an RSML file.
- Per-word quality metadata: model confidence, weakest-letter confidence, voiced fraction, pause length, flag.
- Disfluency aware: hesitations (`@uhh`, `@umm`) are aligned acoustically; breaths, silences, repetitions and false starts are
  placed between the surrounding words.
- Multilingual: English (wav2vec2) and Indian languages (Meta MMS aligner) through Harvard-Kyoto transliteration. Supports
  Devanagari, Bengali/Assamese, Gurmukhi, Gujarati, Odia, Tamil, Telugu, Kannada and Malayalam, plus code-mixed text.
- Handles RSML annotations such as `#NUM[two](2)`, `[cameya](camera)` and `!en[...](...)`.
- Command line tool (`forced-align`) and Python function (`align`).
- Runs on CPU or GPU (CUDA / MPS).

## Installation

```bash
pip install disfluency-restoration
```

`ffmpeg` must be on your `PATH` (it decodes the audio):

```bash
sudo apt install ffmpeg      # Debian / Ubuntu
brew install ffmpeg          # macOS
```

Optional extras: `pip install num2words uroman` (spelling out digits in non-English text; Urdu, Ol Chiki and Meetei Mayek).

The acoustic model is downloaded from the Hugging Face Hub on first use and cached afterwards (about 360 MB for English).

## Quick start

**Python**

```python
from disfluency_restoration import align

out = align("lecture.wav", "lecture.rsml")   # writes lecture.aligned.rsml
print(out)
```

**Command line**

```bash
forced-align lecture.wav lecture.rsml
```

Both write `lecture.aligned.rsml` next to the input and report progress on stderr.

## Usage

### Input: the RSML file

A blank-line-separated file of segment blocks followed by configuration blocks:

```
1
00:00:14,456 --> 00:00:18,685
primary=1|verified=1|flagged=0|note=
In this lecture, we will start a new topic that is on stereo geometry.

2
00:00:18,864 --> 00:00:22,867
primary=1|verified=1|flagged=0|note=
So, let us consider @uhh what is meant by a stereo setup.

[speakers]
1 = male, en

[tags]
hesitations = @umm, @uhh, @hmm, @ugh, @huh, @tsk, @uh-huh, @ehh
```

A segment is an id, a `start --> end` line, an optional metadata line (`key=value|key=value`, where `primary=N` names the
speaker) and the transcript. Blocks that are not segments (the `[sections]`) are copied to the output unchanged and are read
for configuration:

| Section / key | Used for |
|---|---|
| `[speakers]`, e.g. `1 = male, te` | spoken language of speaker `primary=1` |
| `[settings] default_language` | language when a speaker has none |
| `[settings] default_code_mixing_language` | language for all-Latin segments under a non-English speaker (e.g. `en`) |
| `[tags] hesitations` | which `@tags` are real sounds to align |

Markup understood in the transcript:

| Markup | Meaning | Handling |
|---|---|---|
| `@uhh`, `@umm`, ... | hesitation sound | aligned acoustically, gets a real duration |
| `@breathe`, `@laughter`, `@short-pause`, `@silence`, ... | sound or silence without letters | takes the gap between neighbouring words |
| `@repetition-start` / `-end`, `@false-start-...` | marks a stretch of words | zero duration at the word boundary |
| `#NUM[two](2)`, `[cameya](camera)`, `!en[...](...)` | `[spoken form](written form)` | the spoken form is aligned |
| digits such as `2` | number | spelled out (`two`) |

The language of each segment comes from `lang` if given, otherwise from its speaker's entry in `[speakers]`, then
`default_language`, then it is guessed from the script.

### Output

`<rsml>.aligned.rsml` (or the path you pass). Every segment is kept as written and followed by three tab-indented lines per
word: the timestamps, a metadata line, and the word as written in the transcript. Running it again on an aligned file is safe,
because old word lines are dropped and regenerated.

| Metadata field | Meaning |
|---|---|
| `confidence` | mean model probability of the word's letters on the alignment path (0-1). Low means the audio does not match the word. Empty for tags and hesitations |
| `weakest_letter_confidence` | the same for the single weakest letter |
| `voiced_fraction` | fraction of the word's time span that contains speech energy |
| `pause_after_milliseconds` | time until the next spoken word |
| `pause_voiced_fraction` | fraction of that pause that contains speech, i.e. audio no word accounts for (a missing word, a breath) |
| `kind` | `word`, `hesitation`, `isolated`, `span`, `written`, `punctuation` or `untransliterated` |
| `script` | script of the spoken letters (`latin`, `telugu`, ...) |
| `flagged` | `1` if `confidence` is below `flag_confidence`, otherwise `0` |

### How it works

1. The RSML is parsed and the audio is decoded to 16 kHz mono with ffmpeg.
2. For each segment the transcript is turned into the letters the model knows (non-English text is transliterated).
3. A wav2vec2 / MMS CTC model scores the segment's audio, padded by `pad` seconds on each side.
4. A CTC Viterbi pass aligns the letters to the audio, giving every word a start, an end and a confidence.
5. Word edges are stretched over the neighbouring voiced audio (CTC peaks sit inside a sound, which would otherwise shorten
   hesitations and long words). `no_refine=True` turns this off.
6. Tags and punctuation are placed between the timed words, and the new RSML is written.

If a segment's audio window is too short for its text (under 0.1 s), its words are spread evenly by length and a warning is printed.

## Configuration and parameters

### Python: `align(audio, rsml, output=None, **options)`

Returns the output `pathlib.Path`.

| Parameter | Default | Description |
|---|---|---|
| `audio` | required | audio or video file, any format ffmpeg reads |
| `rsml` | required | input RSML transcript |
| `output` | `<rsml>.aligned.rsml` | output path |
| `lang` | `"auto"` | language code (`en`, `hi`, `te`, ...) used for every segment, overriding the RSML |
| `translit` | `"hk"` | `"hk"` (Harvard-Kyoto, spelled in the model's alphabet), `"hk-plain"` or `"uroman"` |
| `model` | per language | any Hugging Face CTC model with a Latin character vocabulary |
| `device` | `"auto"` | `"auto"` (CUDA if available), `"cpu"`, `"cuda"`, `"mps"` |
| `pad` | `0.2` | seconds of extra audio on each side of a segment while aligning |
| `max_gap` | `0.0` | absorb silences up to this many seconds into the neighbouring word, making spans contiguous (off by default) |
| `clamp` | `False` | force word times inside their segment |
| `no_refine` | `False` | keep raw CTC edges instead of stretching words over voiced audio |
| `word_meta` | all fields | comma-separated fields to write, or `"none"` for plain timestamp + word lines |
| `flag_confidence` | `0.3` | words with lower confidence get `flagged=1` |
| `drop_tags` | `False` | omit tag and punctuation tokens from the word lines |

An unknown option raises `TypeError`; an invalid `word_meta` raises `ValueError`. A missing ffmpeg, unreadable audio or an RSML
without segments raise `SystemExit` with a message.

### Command line: `forced-align AUDIO RSML [options]`

| Option | Python equivalent |
|---|---|
| `-o, --output PATH` | `output` |
| `--lang CODE` | `lang` |
| `--translit {hk,hk-plain,uroman}` | `translit` |
| `--model NAME` | `model` |
| `--device DEVICE` | `device` |
| `--pad SEC` | `pad` |
| `--max-gap SEC` | `max_gap` |
| `--clamp` | `clamp=True` |
| `--no-refine` | `no_refine=True` |
| `--word-meta LIST` | `word_meta` |
| `--flag-confidence X` | `flag_confidence` |
| `--drop-tags` | `drop_tags=True` |

Run `forced-align --help` for the full text.

## Examples

**Align on a GPU and keep only the fields you need**

```python
from disfluency_restoration import align

align("lecture.wav", "lecture.rsml", "out/lecture.aligned.rsml",
      device="cuda", word_meta="confidence,pause_after_milliseconds,flagged")
```

**Force a language** (for example a Hindi lecture whose RSML does not declare it)

```bash
forced-align class.wav class.rsml --lang hi
```

**Find words that probably do not match the audio**

```python
from pathlib import Path
from disfluency_restoration import align

out = align("lecture.wav", "lecture.rsml")
lines = Path(out).read_text(encoding="utf-8").split("\n")

for i, line in enumerate(lines):
    if line.startswith("\t") and "-->" in line:
        meta = dict(kv.split("=", 1) for kv in lines[i + 1].strip().split("|"))
        if meta.get("flagged") == "1":
            print(line.strip(), lines[i + 2].strip(), meta["confidence"])
```

**Find audio no word accounts for** (a missing word or noise between two words): look for a high `pause_voiced_fraction`
together with a long `pause_after_milliseconds`.

**Plain output without metadata**

```bash
forced-align lecture.wav lecture.rsml --word-meta none --drop-tags
```

**Align a short clip first** to check your files before running a long recording

```bash
ffmpeg -i lecture.wav -t 40 clip.wav     # keep only the matching segments in clip.rsml
forced-align clip.wav clip.rsml
```

## Requirements

- Python 3.9 or newer (tested on 3.10)
- [`numpy`](https://pypi.org/project/numpy/), [`torch`](https://pypi.org/project/torch/) and
  [`transformers`](https://pypi.org/project/transformers/) (installed automatically)
- `ffmpeg` on `PATH`
- Internet access on first use to download the model from the Hugging Face Hub
- Optional: `num2words`, `uroman`, a CUDA or MPS device

## Troubleshooting

| Symptom | Cause and fix |
|---|---|
| `error: ffmpeg not found on PATH` | install ffmpeg |
| `error: no segments found` | the file has no `id / start --> end / text` blocks |
| `warning: segment N: audio window too short ...` | segment shorter than about 0.1 s; its words were spread evenly |
| `warning: N word(s) contain letters the model has no sound for` | script not covered by Harvard-Kyoto; `pip install uroman` |
| many `flagged=1` words | the transcript differs from the audio, the language is wrong, or the audio is very noisy |
| slow on long recordings | use `device="cuda"`, or align a clip first |

## Notes and licences of the models

English alignment uses [`facebook/wav2vec2-base-960h`](https://huggingface.co/facebook/wav2vec2-base-960h). All other
languages use the MMS forced aligner (`MahmoudAshraf/mms-300m-1130-forced-aligner`), which is licensed
**CC-BY-NC-4.0 (non-commercial use only)**. Check the licence of any model you use before commercial use.

## Development

```bash
git clone https://github.com/OpenBhasha/forced-aligment
cd forced-aligment
pip install -e .
python -m build && twine check dist/*
```

## License

This package is released under the [MIT License](https://github.com/OpenBhasha/forced-aligment/blob/main/LICENSE). The models it
downloads have their own licences (see above).
