Full Code of daanzu/kaldi-active-grammar for AI

master 2e4aafae406b cached
54 files
470.6 KB
116.3k tokens
345 symbols
1 requests
Download .txt
Showing preview only (493K chars total). Download the full file or copy to clipboard to get everything.
Repository: daanzu/kaldi-active-grammar
Branch: master
Commit: 2e4aafae406b
Files: 54
Total size: 470.6 KB

Directory structure:
gitextract_2q213gax/

├── .github/
│   ├── FUNDING.yml
│   ├── RELEASING.md
│   ├── release_notes.md
│   └── workflows/
│       └── build.yml
├── .gitignore
├── AGENTS.md
├── CHANGELOG.md
├── CMakeLists.txt
├── Justfile
├── LICENSE.txt
├── README.md
├── building/
│   ├── build-wheel-dockcross.sh
│   ├── dockcross-manylinux2010-x64
│   └── kaldi-configure-wrapper.sh
├── docs/
│   └── models.md
├── examples/
│   ├── audio.py
│   ├── full_example.py
│   ├── mix_dictation.py
│   ├── plain_dictation.py
│   ├── requirements_audio.txt
│   └── util.py
├── kaldi_active_grammar/
│   ├── LICENSE.txt
│   ├── __init__.py
│   ├── __main__.py
│   ├── compiler.py
│   ├── defaults.py
│   ├── ffi.py
│   ├── kaldi/
│   │   ├── COPYING
│   │   ├── __init__.py
│   │   ├── augment_phones_txt.py
│   │   ├── augment_phones_txt_py2.py
│   │   ├── augment_words_txt.py
│   │   ├── augment_words_txt_py2.py
│   │   ├── make_lexicon_fst.py
│   │   └── make_lexicon_fst_py2.py
│   ├── model.py
│   ├── plain_dictation.py
│   ├── utils.py
│   ├── wfst.py
│   └── wrapper.py
├── pyproject.toml
├── requirements-build.txt
├── requirements-editable.txt
├── requirements-test.txt
├── setup.cfg
├── setup.py
└── tests/
    ├── conftest.py
    ├── generate_google_tts.py
    ├── generate_piper_tts.py
    ├── helpers.py
    ├── run_each_test_separately.py
    ├── test_grammar.py
    ├── test_package.py
    └── test_plain_dictation.py

================================================
FILE CONTENTS
================================================

================================================
FILE: .github/FUNDING.yml
================================================
github: daanzu
custom: "https://paypal.me/daanzu"


================================================
FILE: .github/RELEASING.md
================================================
# Release Process

## Quick Summary

1. **Prepare**: Update version in `__init__.py`, update `CHANGELOG.md`, run tests
2. **Tag Fork First**: Push all changes and tag `kag-vX.Y.Z` in kaldi-fork repo (MUST be done first!)
3. **Tag Main**: Create and push git tag `vX.Y.Z` in this repo to trigger builds
4. **Build**: Automated GitHub Actions builds wheels for all platforms
5. **Release**: Create GitHub release with changelog, upload wheel artifacts and models
6. **Publish**: Download wheels from artifacts, upload to PyPI with twine
7. **Finalize**: Bump to next dev version, announce release

---

## Detailed Release Process

### Overview

This is a **duorepo** (2 separate repos used together):
- Main repo: `daanzu/kaldi-active-grammar` (Python package)
- Native binaries repo: `daanzu/kaldi-fork-active-grammar` (Kaldi C++ fork)

**⚠️ IMPORTANT: The fork repo MUST always be pushed first before this repo for any changes!** The build process in this repo checks out code from the fork repo, so the fork must contain all necessary changes before triggering builds here.

### 1. Pre-Release Preparation

#### Update Version Number

Edit `kaldi_active_grammar/__init__.py`:
```python
__version__ = 'X.Y.Z'  # Change from previous version
```

Optionally update `REQUIRED_MODEL_VERSION` if model changes.

#### Update CHANGELOG.md

Add new version section following Keep a Changelog format:
```markdown
## [X.Y.Z](release-url) - YYYY-MM-DD - Changes: [KaldiAG](compare-url) [KaldiFork](compare-url)

### Added
- New features

### Changed
- Changes to existing functionality

### Fixed
- Bug fixes

### Removed
- Removed features
```

Include comparison links for both repos (KaldiAG and KaldiFork).

#### Run Tests

```bash
just test
```

#### Commit Changes

```bash
git add kaldi_active_grammar/__init__.py CHANGELOG.md
git commit -m "Release vX.Y.Z"
```

### 2. Create Git Tags

**⚠️ CRITICAL ORDER: Tag and push the fork repo FIRST, then this repo!**

#### Tag the Kaldi Fork Repo (DO THIS FIRST!)

In the `daanzu/kaldi-fork-active-grammar` repo:

1. Ensure all native code changes are committed and pushed
2. Create and push the tag:
   ```bash
   git tag kag-vX.Y.Z  # Note the 'kag-' prefix matching the version
   git push origin kag-vX.Y.Z
   ```

This is crucial because the build process in this repo will check out code from the fork using this tag.

#### Tag This Repo (DO THIS SECOND!)

Only after the fork repo tag is pushed:

```bash
git tag vX.Y.Z
git push origin vX.Y.Z
```

Pushing this tag will trigger the GitHub Actions build workflow, which will pull the native code from the fork repo using the `kag-vX.Y.Z` tag.

### 3. Automated Build Process (GitHub Actions)

When you push a tag, the CI automatically:

#### Detects the Tag

Sets `KALDI_BRANCH=kag-vX.Y.Z` for tagged commits, or uses current branch name for non-tagged commits.

#### Builds Native Binaries

**Linux** (`build-linux` job):
- Uses dockcross/manylinux2010 for compatibility
- Compiles Kaldi C++ code with CMake
- Runs auditwheel for wheel repair

**Windows** (`build-windows` job):
- Uses Visual Studio 2022/2025
- Installs Intel MKL
- Compiles OpenFST and Kaldi with MSBuild

**macOS ARM** (`build-macos-arm` job):
- For Apple Silicon (M1/M2/etc)
- Uses delocate for wheel repair

**macOS Intel** (`build-macos-intel` job):
- For x86_64 Macs
- Uses delocate for wheel repair

#### Caches Native Binaries

Caches compiled Kaldi binaries by commit hash to speed up rebuilds.

#### Creates Python Wheels

- Packages include all native binaries
- Platform-specific wheels: `py3-none-{platform}`
- Uses `setup.py` with scikit-build (or `KALDIAG_BUILD_SKIP_NATIVE=1` for packaging only)

#### Tests All Wheels

`test-wheels` job runs on multiple OS/Python version combinations.

#### Merges Wheel Artifacts

`merge-wheels` job combines all platform wheels into single artifact named `wheels`.

### 4. Manual Workflow Trigger (Optional)

You can also trigger builds manually:

```bash
# Using GitHub CLI
gh workflow run build.yml --ref master
# Or specific ref:
gh workflow run build.yml --ref vX.Y.Z

# Or via Justfile:
just trigger-build master
```

### 5. Create GitHub Release

1. **Navigate to GitHub Releases page**
   - https://github.com/daanzu/kaldi-active-grammar/releases

2. **Create new release**:
   - Tag: `vX.Y.Z` (select existing tag)
   - Title: `vX.Y.Z` or descriptive name
   - Description: Copy relevant section from `CHANGELOG.md` or use template from `.github/release_notes.md`

3. **Download wheel artifacts** from successful build workflow:
   - Go to Actions → Build workflow → successful run
   - Download artifact named `wheels` (merged) or individual `wheels-{platform}`

4. **Upload wheels to release**:
   - Upload all `.whl` files from the artifacts

5. **Upload additional assets** (if applicable):
   - Pre-trained Kaldi models (if updated)
   - WinPython distributions (if prepared):
     - `kaldi-dragonfly-winpython` (stable)
     - `kaldi-dragonfly-winpython-dev` (development)
     - `kaldi-caster-winpython-dev` (with Caster)

6. **Publish the release**

### 6. Publish to PyPI

The process is currently **manual** (not automated in workflow).

#### Download Wheel Artifacts

Download the `wheels` artifact from the successful GitHub Actions build.

#### Upload to PyPI

You'll need PyPI credentials (entered interactively or configured in `~/.pypirc` or via environment variables).

```bash
# Test PyPI first (recommended):
uvx twine upload --repository testpypi wheels/*
# Production PyPI:
uvx twine upload wheels/*
```

Or:

```bash
pip install twine
# Test PyPI first (recommended):
twine upload --repository testpypi wheels/*
# Production PyPI:
twine upload wheels/*
```

#### Verify on PyPI

- Check https://pypi.org/project/kaldi-active-grammar/
- Verify all platforms are present
- Test installation:
  ```bash
  pip install kaldi-active-grammar==X.Y.Z
  ```

### 7. Post-Release Tasks

#### Bump Version for Development

Update `__version__` in `kaldi_active_grammar/__init__.py` to next dev version:
```python
__version__ = 'X.Y.Z.dev0'  # or 'X.Y+1.0.dev0'
```

Commit the change:
```bash
git add kaldi_active_grammar/__init__.py
git commit -m "Bump version to X.Y.Z.dev0"
git push
```

#### Announce Release

- Update documentation/README if needed
- Update Dragonfly documentation if relevant
- Post on relevant forums/communities
    - Notify on Gitter:
        - https://app.gitter.im/#/room/#dragonfly2:matrix.org
        - https://gitter.im/kaldi-active-grammar/community

---

## Key Files in Release Process

| File | Purpose |
|------|---------|
| `kaldi_active_grammar/__init__.py:8` | Version source |
| `kaldi_active_grammar/__init__.py:10` | Required model version |
| `CHANGELOG.md` | Release notes and history |
| `.github/workflows/build.yml` | CI build configuration |
| `.github/workflows/tests.yml` | CI test configuration |
| `setup.py` | Package build configuration |
| `pyproject.toml` | Build system requirements |
| `Justfile` | Build and test tasks |
| `.github/release_notes.md` | Release notes template |

---

## Environment Variables

| Variable | Purpose |
|----------|---------|
| `KALDIAG_BUILD_SKIP_NATIVE=1` | Skip native compilation, just package |
| `KALDI_BRANCH` | Which Kaldi fork branch/tag to build from (auto-detected from git tag) |
| `MKL_URL` | Optional Intel MKL download URL (mostly disabled now) |

---

## Development vs Release Versions

- **Dev versions**: `setup.py` auto-appends timestamp to `X.Y.Z.dev0` versions
  - Example: `3.1.0.dev20251031123456`
- **Release versions**: Clean `X.Y.Z` semantic version
  - Example: `3.1.0`
- Build process differentiates based on git tags

---

## Troubleshooting

### Build fails on one platform

- Check the GitHub Actions logs for that specific job
- Native binaries are cached, so may need to invalidate cache if Kaldi fork changed
- Ensure the `kag-vX.Y.Z` tag exists in kaldi-fork-active-grammar repo

### Tests fail

- Run tests locally: `just test`
- Check if model needs to be updated
- Verify test data is downloaded: `just setup-tests`

### PyPI upload fails

- Verify credentials in `~/.pypirc`
- Check wheel filenames are correct
- Ensure version doesn't already exist on PyPI
- Try test PyPI first

### Wheels missing for a platform

- Check if that build job completed successfully
- Look for cache issues
- Verify platform is included in build matrix

### Version mismatch

- Ensure git tag matches `__version__` in `__init__.py`
- Check that both repos are tagged (main repo: `vX.Y.Z`, fork: `kag-vX.Y.Z`)
- Verify `CHANGELOG.md` has correct version


================================================
FILE: .github/release_notes.md
================================================
v0.5.0: User Lexicon! Compilation Optimizations! Better Model!

### Notes

* **User Lexicon**: you can add new words/pronunciations to the model's lexicon to be recognized & used in grammars, and the pronunciations can be either specified explicitly or inferred automatically.
* **Compilation Optimizations**: compilation while loading grammars uses the disk much less, and far fewer passes are made over the graphs, as separate modules have been customized & combined.
* **Better Model**: 50% more training data.

### Artifacts

* **`kaldi_model_zamia`**: [*new model version required!*] A compatible general English Kaldi nnet3 chain model.
* **`kaldi-dragonfly-winpython`**: A self-contained, portable, batteries-included (python & libraries & model) distribution of kaldi-active-grammar + dragonfly2. Just unzip and run!
* **`kaldi-dragonfly-winpython-dev`**: [*more recent development version*] A self-contained, portable, batteries-included (python & libraries & model) distribution of kaldi-active-grammar + dragonfly2. Just unzip and run!
* **`kaldi-caster-winpython-dev`**: [*more recent development version*] A self-contained, portable, batteries-included (python & libraries & model) distribution of kaldi-active-grammar + dragonfly2 + caster. Just unzip and run!

### **Donations are appreciated to encourage development.**

[![Donate](https://img.shields.io/badge/donate-PayPal-green.svg)](https://paypal.me/daanzu)
[![Donate](https://img.shields.io/badge/donate-Patreon-orange.svg)](https://www.patreon.com/daanzu)


v0.6.0: Big Fixes And Optimizations To Get Caster Running

### Artifacts

* **`kaldi_model_zamia`**: A compatible general English Kaldi nnet3 chain model.
* **`kaldi-dragonfly-winpython`**: [*stable release version*] A self-contained, portable, batteries-included (python & libraries & model) distribution of kaldi-active-grammar + dragonfly2. Just unzip and run!
* **`kaldi-dragonfly-winpython-dev`**: [*more recent development version*] A self-contained, portable, batteries-included (python & libraries & model) distribution of kaldi-active-grammar + dragonfly2. Just unzip and run!
* **`kaldi-caster-winpython-dev`**: [*more recent development version*] A self-contained, portable, batteries-included (python & libraries & model) distribution of kaldi-active-grammar + dragonfly2 + caster. Just unzip and run!

If you have trouble downloading, try using `wget --continue`.

### **Donations are appreciated to encourage development.**

[![Donate](https://img.shields.io/badge/donate-PayPal-green.svg)](https://paypal.me/daanzu)
[![Donate](https://img.shields.io/badge/donate-Patreon-orange.svg)](https://www.patreon.com/daanzu)


v0.7.1: Partial Decoding, Parallel Compilation, & Various Optimizations for 15-50% Speedup

Support is now included in dragonfly2 v0.17.0! You can try a self-contained distribution available below, of either stable or development versions.

### Notes

* **Partial Decoding**: support for having **separate Voice Activity Detection timeout values** based on whether the current utterance is complex (dictation) or not.
* **Parallel Compilation**: when compiling grammars/rules that are not cached, multiple can be compiled at once (up to your core count).
    * Example: loading Caster without cache is ~40% faster (in addition to optimizations below).
* **Various Optimizations**: loading even while cached sped up 15%.
* Refactored temporary/cache file handling
* Various bug fixes

### Artifacts

* **`kaldi_model_zamia`**: A compatible general English Kaldi nnet3 chain model.
* **`kaldi-dragonfly-winpython`**: [*stable release version*] A self-contained, portable, batteries-included (python & libraries & model) distribution of kaldi-active-grammar + dragonfly2. Just unzip and run!
* **`kaldi-dragonfly-winpython-dev`**: [*more recent development version*] A self-contained, portable, batteries-included (python & libraries & model) distribution of kaldi-active-grammar + dragonfly2. Just unzip and run!
* **`kaldi-caster-winpython-dev`**: [*more recent development version*] A self-contained, portable, batteries-included (python & libraries & model) distribution of kaldi-active-grammar + dragonfly2 + caster. Just unzip and run!

If you have trouble downloading, try using `wget --continue`.

### **Donations are appreciated to encourage development.**

[![Donate](https://img.shields.io/badge/donate-PayPal-green.svg)](https://paypal.me/daanzu)
[![Donate](https://img.shields.io/badge/donate-Patreon-orange.svg)](https://www.patreon.com/daanzu)


v1.0.0: Faster Loading, Python3, Grammar/Rule Weights, and more

Support is now included in dragonfly2 v0.18.0! You can try a self-contained distribution available below, of either stable or development versions.

### Notes

* **Direct Parsing**: parse recognitions directly on the FST, removing the (slow) `pyparsing` dependency.
    * Caster example: Loading is now **~50%** faster when cached, and the Kaldi backend accounts for only ~15% of loading time.
* **Python3**: both python 2 and 3 should be fully supported now.
    * **Unicode**: this should also fix unicode issues in various places in both python2/3.
* **Grammar/Rule Weights**: can specify weight, where grammars/rules with higher weight value are more likely to be recognized, compared to their peers, for an ambiguous recognition.
* **Generalized Alternative Dictation**: the cloud dictation feature has been generalized to make it easier to add other alternatives in the future.
* Various bug fixes & optimizations

### Artifacts

* **`kaldi_model_zamia`**: A compatible general English Kaldi nnet3 chain model.
* **`kaldi-dragonfly-winpython`**: [*stable release version*] A self-contained, portable, batteries-included (python & libraries & model) distribution of kaldi-active-grammar + dragonfly2. Just unzip and run!
* **`kaldi-dragonfly-winpython-dev`**: [*more recent development version*] A self-contained, portable, batteries-included (python & libraries & model) distribution of kaldi-active-grammar + dragonfly2. Just unzip and run!
* **`kaldi-caster-winpython-dev`**: [*more recent development version*] A self-contained, portable, batteries-included (python & libraries & model) distribution of kaldi-active-grammar + dragonfly2 + caster. Just unzip and run!

If you have trouble downloading, try using `wget --continue`.

### Donations are appreciated to encourage development.

[![Donate](https://img.shields.io/badge/donate-GitHub-pink.svg)](https://github.com/sponsors/daanzu) [![Donate](https://img.shields.io/badge/donate-Patreon-orange.svg)](https://www.patreon.com/daanzu) [![Donate](https://img.shields.io/badge/donate-PayPal-green.svg)](https://paypal.me/daanzu) [![Donate](https://img.shields.io/badge/preferred-GitHub-black.svg)](https://github.com/sponsors/daanzu)
[**GitHub** is currently matching all my donations $-for-$.]




v1.2.0: Improved Recognition, Weights on Any Elements, Pluggable Alternative Dictation, Stand-alone Plain Dictation Interface, and More

Support is now included in dragonfly2 v0.20.0! You can try a self-contained distribution available below, of either stable or development versions.

### Notes

* **Improved Recognition**: better graph construction/compilation should give significantly better overall recognition.
* **Weights on Any Elements**: you can now easily add weights to any element (including compound elements in `MappingRule`s), in addition to any rule/grammar.
* **Pluggable Alternative Dictation**: you can optionally pass a `callable` as `alternative_dictation` to define your own, external dictation engine.
* **Stand-alone Plain Dictation Interface**: the library now provides a simple interface for recognizing plain dictation without fancy active grammar features.
* **NOTE**: the default model directory is now `kaldi_model`.
* Various bug fixes & optimizations

### Artifacts

* **`kaldi_model_daanzu`**: A better overall compatible general English Kaldi nnet3 chain model than below.
* **`kaldi_model_zamia_daanzu_mediumlm`**: A compatible general English Kaldi nnet3 chain model, with a larger/better dictation language model than below.
* **`kaldi_model_zamia`**: A compatible general English Kaldi nnet3 chain model.
* **`kaldi-dragonfly-winpython`**: [*stable release version*] A self-contained, portable, batteries-included (python & libraries & model) distribution of kaldi-active-grammar + dragonfly2. Just unzip and run!
* **`kaldi-dragonfly-winpython-dev`**: [*more recent development version*] A self-contained, portable, batteries-included (python & libraries & model) distribution of kaldi-active-grammar + dragonfly2. Just unzip and run!
* **`kaldi-caster-winpython-dev`**: [*more recent development version*] A self-contained, portable, batteries-included (python & libraries & model) distribution of kaldi-active-grammar + dragonfly2 + caster. Just unzip and run!

If you have trouble downloading, try using `wget --continue`.

### Donations are appreciated to encourage development.

[![Donate](https://img.shields.io/badge/donate-GitHub-pink.svg)](https://github.com/sponsors/daanzu) [![Donate](https://img.shields.io/badge/donate-Patreon-orange.svg)](https://www.patreon.com/daanzu) [![Donate](https://img.shields.io/badge/donate-PayPal-green.svg)](https://paypal.me/daanzu) [![Donate](https://img.shields.io/badge/preferred-GitHub-black.svg)](https://github.com/sponsors/daanzu)
[**GitHub** is currently matching all my donations $-for-$.]



v1.3.0: Preparation and Fixes for Next Generation of Models

This should be included the next dragonfly version, or you can try a self-contained distribution available below.

You can subscribe to announcements on Gitter: see [instructions](https://gitlab.com/gitlab-org/gitter/webapp/blob/master/docs/notifications.md#announcements). [![Gitter](https://badges.gitter.im/kaldi-active-grammar/community.svg)](https://gitter.im/kaldi-active-grammar/community)

### Notes

* **Next Generation of Models**: support for a new generation of models, trained on more data, and with hopefully better accuracy.
* **User Lexicon**: if there is a ``user_lexicon.txt`` file in the current working directory of your initial loader script, its contents will be automatically added to the ``user_lexicon.txt`` in the active model when it is loaded.
* Various bug fixes & optimizations

### Artifacts

* **`kaldi_model_daanzu*`**: A better acoustic model, and varying levels of language model for dictation (bigger is generally better).
* **`kaldi_model_zamia`**: A compatible general English Kaldi nnet3 chain model.
* **`kaldi-dragonfly-winpython`**: [*stable release version*] A self-contained, portable, batteries-included (python & libraries & model) distribution of kaldi-active-grammar + dragonfly2. Just unzip and run!
* **`kaldi-dragonfly-winpython-dev`**: [*more recent development version*] A self-contained, portable, batteries-included (python & libraries & model) distribution of kaldi-active-grammar + dragonfly2. Just unzip and run!
* **`kaldi-caster-winpython-dev`**: [*more recent development version*] A self-contained, portable, batteries-included (python & libraries & model) distribution of kaldi-active-grammar + dragonfly2 + caster. Just unzip and run!

If you have trouble downloading, try using `wget --continue`.

### Donations are appreciated to encourage development.

[![Donate](https://img.shields.io/badge/donate-GitHub-pink.svg)](https://github.com/sponsors/daanzu) [![Donate](https://img.shields.io/badge/donate-Patreon-orange.svg)](https://www.patreon.com/daanzu) [![Donate](https://img.shields.io/badge/donate-PayPal-green.svg)](https://paypal.me/daanzu) [![Donate](https://img.shields.io/badge/preferred-GitHub-black.svg)](https://github.com/sponsors/daanzu)
[**GitHub** is matching (only) my **GitHub Sponsors** donations.]





v1.4.0: MacOS Support, And Faster Graph Compilation

Support is now included in dragonfly2 v0.22.0! You can try a self-contained distribution available below.

You can subscribe to announcements on Gitter: see [instructions](https://gitlab.com/gitlab-org/gitter/webapp/blob/master/docs/notifications.md#announcements). [![Gitter](https://badges.gitter.im/kaldi-active-grammar/community.svg)](https://gitter.im/kaldi-active-grammar/community)

### Notes

* **MacOS Support**
* **Faster Graph Compilation**
* **Dictation**: the dictation model now does not recognize a zero-word sequence
* Various bug fixes & optimizations

### Artifacts

* **`kaldi_model_daanzu*`**: A better acoustic model, and varying levels of language model for dictation (bigger is generally better).
* **`kaldi_model_zamia`**: A compatible general English Kaldi nnet3 chain model.
* **`kaldi-dragonfly-winpython`**: [*stable release version*] A self-contained, portable, batteries-included (python & libraries & model) distribution of kaldi-active-grammar + dragonfly2. Just unzip and run!
* **`kaldi-caster-winpython-dev`**: [*more recent development version*] A self-contained, portable, batteries-included (python & libraries & model) distribution of kaldi-active-grammar + dragonfly2 + caster. Just unzip and run!

If you have trouble downloading, try using `wget --continue`.

### Donations are appreciated to encourage development.

[![Donate](https://img.shields.io/badge/donate-GitHub-pink.svg)](https://github.com/sponsors/daanzu) [![Donate](https://img.shields.io/badge/donate-Patreon-orange.svg)](https://www.patreon.com/daanzu) [![Donate](https://img.shields.io/badge/donate-PayPal-green.svg)](https://paypal.me/daanzu) [![Donate](https://img.shields.io/badge/preferred-GitHub-black.svg)](https://github.com/sponsors/daanzu)
[**GitHub** is matching (only) my **GitHub Sponsors** donations.]





v1.5.0: Improved Recognition Confidence Estimation

You can subscribe to announcements on Gitter: see [instructions](https://gitlab.com/gitlab-org/gitter/webapp/blob/master/docs/notifications.md#announcements). [![Gitter](https://badges.gitter.im/kaldi-active-grammar/community.svg)](https://gitter.im/kaldi-active-grammar/community)

### Notes

* **Improved Recognition Confidence Estimation**: two new, different measures:
    * `confidence`: basically the difference in how much "better" the returned recognition was, compared to the second best guess (`>0`)
    * `expected_error_rate`: an estimate of how often similar utterances are incorrect (roughly out of `1.0`, but can be greater)
* Refactoring in preparation for future improvements
* Various bug fixes & optimizations

### Artifacts

* **Models are available [here](https://github.com/daanzu/kaldi-active-grammar/blob/master/docs/models.md)**
* **`kaldi-dragonfly-winpython`**: [*stable release version*] A self-contained, portable, batteries-included (python & libraries & model) distribution of kaldi-active-grammar + dragonfly2. Just unzip and run!
* **`kaldi-caster-winpython-dev`**: [*more recent development version*] A self-contained, portable, batteries-included (python & libraries & model) distribution of kaldi-active-grammar + dragonfly2 + caster. Just unzip and run!

If you have trouble downloading, try using `wget --continue`.

### Donations are appreciated to encourage development.

[![Donate](https://img.shields.io/badge/donate-GitHub-pink.svg)](https://github.com/sponsors/daanzu) [![Donate](https://img.shields.io/badge/donate-Patreon-orange.svg)](https://www.patreon.com/daanzu) [![Donate](https://img.shields.io/badge/donate-PayPal-green.svg)](https://paypal.me/daanzu) [![Donate](https://img.shields.io/badge/preferred-GitHub-black.svg)](https://github.com/sponsors/daanzu)
[**GitHub** is matching (only) my **GitHub Sponsors** donations.]




v1.6.0: Easier Configuration; Public Automated Builds

You can subscribe to announcements on GitHub (see Watch panel above), or on Gitter (see [instructions](https://gitlab.com/gitlab-org/gitter/webapp/blob/master/docs/notifications.md#announcements) [![Gitter](https://badges.gitter.im/kaldi-active-grammar/community.svg)](https://gitter.im/kaldi-active-grammar/community))

### Added
* Can now pass configuration dict to `KaldiAgfNNet3Decoder`, `PlainDictationRecognizer` (without `HCLG.fst`).
* Continuous Integration builds run on GitHub Actions for Windows (x64), MacOS (x64), Linux (x64).

### Changed
* Refactor of passing configuration to initialization.
* `PlainDictationRecognizer.decode_utterance` can take `chunk_size` parameter.
* Smaller binaries: MacOS 11MB -> 7.6MB, Linux 21MB -> 18MB.

### Fixed
* Confidence measurement in the presence of multiple, redundant rules.
* Python3 int division bug for cloud dictation.

### Artifacts

* **Models are available [here](https://github.com/daanzu/kaldi-active-grammar/blob/master/docs/models.md)**
* **`kaldi-dragonfly-winpython`**: [*stable release version*] A self-contained, portable, batteries-included (python & libraries & model) distribution of kaldi-active-grammar + dragonfly2. Just unzip and run!
* **`kaldi-caster-winpython-dev`**: [*more recent development version*] A self-contained, portable, batteries-included (python & libraries & model) distribution of kaldi-active-grammar + dragonfly2 + caster. Just unzip and run!

If you have trouble downloading, try using `wget --continue`.

### Donations are appreciated to encourage development.

[![Donate](https://img.shields.io/badge/donate-GitHub-pink.svg)](https://github.com/sponsors/daanzu) [![Donate](https://img.shields.io/badge/donate-Patreon-orange.svg)](https://www.patreon.com/daanzu) [![Donate](https://img.shields.io/badge/donate-PayPal-green.svg)](https://paypal.me/daanzu) [![Donate](https://img.shields.io/badge/preferred-GitHub-black.svg)](https://github.com/sponsors/daanzu)
[**GitHub** is matching (only) my **GitHub Sponsors** donations.]



v2.0.0: Faster Grammar Compilation; Cleaner Codebase; Preparation For New Features


v2.1.0

Minor fix for OpenBLAS compilation for some architectures on linux/mac.

See [major changes introduced in v2.0.0 and associated downloads](https://github.com/daanzu/kaldi-active-grammar/releases/tag/v2.0.0).


v3.2.0

Functionality-wise, only one small bug-fix: to the broken alternative dictation interface. But extensive build and infrastructure changes lead me to make this a minor release rather than just a patch release, out of an abundance of caution.

Active development has resumed after a long break! (While development paused, the project was continuously maintained and actively used in production.) Look forward to more frequent releases in the hopefully-near future.



You can subscribe to announcements on GitHub (see Watch panel above), or on Gitter (see [instructions](https://gitlab.com/gitlab-org/gitter/webapp/blob/master/docs/notifications.md#announcements) [![Gitter](https://badges.gitter.im/kaldi-active-grammar/community.svg)](https://gitter.im/kaldi-active-grammar/community))

#### Donations are appreciated to encourage development.

[![Donate](https://img.shields.io/badge/donate-GitHub-EA4AAA.svg?logo=githubsponsors)](https://github.com/sponsors/daanzu) [![Donate](https://img.shields.io/badge/donate-PayPal-002991.svg?logo=paypal)](https://paypal.me/daanzu) [![Donate](https://img.shields.io/badge/donate-GitHub-EA4AAA.svg?logo=githubsponsors)](https://github.com/sponsors/daanzu)


### Artifacts

* **Models are available [here](https://github.com/daanzu/kaldi-active-grammar/blob/master/docs/models.md)** and below.
* **`kaldi-dragonfly-winpython`**: A self-contained, portable, batteries-included (python & libraries & model) distribution of kaldi-active-grammar + dragonfly2. Just unzip and run!
* **`kaldi-caster-winpython`**: A self-contained, portable, batteries-included (python & libraries & model) distribution of kaldi-active-grammar + dragonfly2 + caster. Just unzip and run!

If you have trouble downloading, try using `wget --continue`.




* **`kaldi-dragonfly-winpython`**: [*stable release version*] A self-contained, portable, batteries-included (python & libraries & model) distribution of kaldi-active-grammar + dragonfly2. Just unzip and run!
* **`kaldi-caster-winpython`**: [*more recent development version*] A self-contained, portable, batteries-included (python & libraries & model) distribution of kaldi-active-grammar + dragonfly2 + caster. Just unzip and run!

This should be included the next dragonfly version, or you can try a self-contained distribution available below.


================================================
FILE: .github/workflows/build.yml
================================================
name: Build

on:
  push:
  pull_request:
  workflow_dispatch:
    # gh api repos/:owner/:repo/actions/workflows/build.yml/dispatches -F ref=master
    # gh workflow run build.yml --ref develop
    # gh workflow run build.yml

jobs:

  build-linux:
    runs-on: ubuntu-latest
    if: true
    env:
      MKL_URL: ""
      # MKL_URL: "https://registrationcenter-download.intel.com/akdlm/irc_nas/tec/16917/l_mkl_2020.4.304.tgz"
    steps:
      - name: Checkout repository
        uses: actions/checkout@v5

      - name: Get KALDI_BRANCH (kag-$TAG tag if commit is tagged; current branch name if not)
        run: |
          # Fetch tags on the one fetched commit (shallow clone)
          git fetch --depth=1 origin "+refs/tags/*:refs/tags/*"
          export TAG=$(git tag --points-at HEAD)
          echo "TAG: $TAG"
          if [[ $TAG ]]; then
            echo "KALDI_BRANCH: kag-$TAG"
            echo "KALDI_BRANCH=kag-$TAG" >> $GITHUB_ENV
            echo "KALDI_BRANCH=kag-$TAG" >> $GITHUB_OUTPUT
          else
            echo "KALDI_BRANCH: ${GITHUB_REF/refs\/heads\//}"
            echo "KALDI_BRANCH=${GITHUB_REF/refs\/heads\//}" >> $GITHUB_ENV
            echo "KALDI_BRANCH=${GITHUB_REF/refs\/heads\//}" >> $GITHUB_OUTPUT
          fi

      - name: Get Kaldi commit hash
        id: get-kaldi-commit
        run: |
          KALDI_COMMIT=$(git ls-remote https://github.com/daanzu/kaldi-fork-active-grammar.git $KALDI_BRANCH | cut -f1)
          echo "KALDI_COMMIT: $KALDI_COMMIT"
          echo "KALDI_COMMIT=$KALDI_COMMIT" >> $GITHUB_OUTPUT

      - name: Restore cached native binaries
        id: cache-native-binaries-restore
        uses: actions/cache/restore@v4
        with:
          key: native-${{ runner.os }}-${{ steps.get-kaldi-commit.outputs.KALDI_COMMIT }}-${{ env.MKL_URL }}-v1
          path: |
            kaldi_active_grammar/exec/linux
            kaldi_active_grammar.libs

      - name: Install just
        uses: taiki-e/install-action@just

      - name: Build with dockcross (native binaries & python wheel)
        run: |
          shopt -s nullglob
          echo "KALDI_BRANCH: $KALDI_BRANCH"
          echo "MKL_URL: $MKL_URL"
          just build-dockcross ${{ steps.cache-native-binaries-restore.outputs.cache-hit == 'true' && '--skip-native' || '' }} $KALDI_BRANCH $MKL_URL
          ls -l wheelhouse/
          for whl in wheelhouse/*.whl; do
            unzip -l $whl
          done

      - name: Extract native binaries from wheel after auditwheel repair, to save to cache
        if: steps.cache-native-binaries-restore.outputs.cache-hit != 'true'
        # We do this rather than manually caching all of the various kaldi/openfst libraries in their build locations
        run: |
          shopt -s nullglob
          # Assert there is only one wheel
          WHEEL_COUNT=$(ls wheelhouse/*.whl | wc -l)
          if [ "$WHEEL_COUNT" -ne 1 ]; then
            echo "Error: Expected exactly 1 wheel, found $WHEEL_COUNT"
            ls -l wheelhouse/
            exit 1
          fi
          WHEEL_FILE=$(ls wheelhouse/*.whl)
          echo "Extracting from wheel: $WHEEL_FILE"
          unzip -o $WHEEL_FILE 'kaldi_active_grammar/exec/linux/*'
          unzip -o $WHEEL_FILE 'kaldi_active_grammar.libs/*'
          ls -l kaldi_active_grammar/exec/linux/ kaldi_active_grammar.libs/
          readelf -d kaldi_active_grammar/exec/linux/libkaldi-dragonfly.so | egrep 'NEEDED|RUNPATH|RPATH'

      - name: Save cached native binaries
        if: steps.cache-native-binaries-restore.outputs.cache-hit != 'true'
        uses: actions/cache/save@v4
        with:
          key: ${{ steps.cache-native-binaries-restore.outputs.cache-primary-key }}
          path: |
            kaldi_active_grammar/exec/linux
            kaldi_active_grammar.libs

      - name: Upload native binaries to artifacts
        uses: actions/upload-artifact@v4
        with:
          name: native-linux
          path: |
            kaldi_active_grammar/exec/linux
            kaldi_active_grammar.libs

      - name: Upload Linux wheels
        uses: actions/upload-artifact@v4
        with:
          name: wheels-linux
          path: wheelhouse/*

      - name: Examine results
        run: |
          shopt -s nullglob
          for whl in wheelhouse/*.whl; do
            echo "::notice title=Built wheel::$(basename $whl)"
            unzip -l $whl
          done

  build-windows:
    runs-on: windows-2025
    if: true
    env:
      VS_VERSION: vs2022
      PLATFORM_TOOLSET: v143
      WINDOWS_TARGET_PLATFORM_VERSION: 10.0
      MKL_VERSION: 2025.1.0
    defaults:
      run:
        shell: bash
    steps:

      - name: Checkout main repository
        uses: actions/checkout@v5
        with:
          path: main

      - name: Get KALDI_BRANCH (kag-$TAG tag if commit is tagged; current branch name if not)
        id: get-kaldi-branch
        working-directory: main
        run: |
          # Fetch tags on the one fetched commit (shallow clone)
          git fetch --depth=1 origin "+refs/tags/*:refs/tags/*"
          export TAG=$(git tag --points-at HEAD)
          echo "TAG: $TAG"
          if [[ $TAG ]]; then
            echo "KALDI_BRANCH: kag-$TAG"
            echo "KALDI_BRANCH=kag-$TAG" >> $GITHUB_ENV
            echo "KALDI_BRANCH=kag-$TAG" >> $GITHUB_OUTPUT
          else
            echo "KALDI_BRANCH: ${GITHUB_REF/refs\/heads\//}"
            echo "KALDI_BRANCH=${GITHUB_REF/refs\/heads\//}" >> $GITHUB_ENV
            echo "KALDI_BRANCH=${GITHUB_REF/refs\/heads\//}" >> $GITHUB_OUTPUT
          fi

      - name: Get Kaldi commit hash
        id: get-kaldi-commit
        run: |
          KALDI_COMMIT=$(git ls-remote https://github.com/daanzu/kaldi-fork-active-grammar.git $KALDI_BRANCH | cut -f1)
          echo "KALDI_COMMIT: $KALDI_COMMIT"
          echo "KALDI_COMMIT=$KALDI_COMMIT" >> $GITHUB_OUTPUT

      - name: Restore cached native binaries
        id: cache-native-binaries-restore
        uses: actions/cache/restore@v4
        with:
          key: native-${{ runner.os }}-${{ steps.get-kaldi-commit.outputs.KALDI_COMMIT }}-${{ env.VS_VERSION }}-${{ env.PLATFORM_TOOLSET }}-${{ env.WINDOWS_TARGET_PLATFORM_VERSION }}-${{ env.MKL_VERSION }}-v1
          path: main/kaldi_active_grammar/exec/windows

      - name: Checkout OpenFST repository
        if: steps.cache-native-binaries-restore.outputs.cache-hit != 'true'
        uses: actions/checkout@v5
        with:
          repository: daanzu/openfst
          path: openfst

      - name: Checkout Kaldi repository
        if: steps.cache-native-binaries-restore.outputs.cache-hit != 'true'
        uses: actions/checkout@v5
        with:
          repository: daanzu/kaldi-fork-active-grammar
          path: kaldi
          ref: ${{ steps.get-kaldi-branch.outputs.KALDI_BRANCH }}

      - name: Gather system information
        if: steps.cache-native-binaries-restore.outputs.cache-hit != 'true'
        run: |
          echo $GITHUB_WORKSPACE
          df -h
          echo "Windows SDK Versions:"
          ls -l '/c/Program Files (x86)/Windows Kits/10/Include/'
          echo "Visual Studio Redistributables:"
          # ls -l '/c/Program Files (x86)/Microsoft Visual Studio/2022/Enterprise/VC/Redist/MSVC/'
          # ls -l '/c/Program Files (x86)/Microsoft Visual Studio/2022/Enterprise/VC/Redist/MSVC/14.26.28720'
          # ls -l '/c/Program Files (x86)/Microsoft Visual Studio/2022/Enterprise/VC/Redist/MSVC/v142'
          # ls -l '/c/Program Files (x86)/Microsoft Visual Studio/2022/Enterprise/VC/Redist/MSVC/14.16.27012/x64/Microsoft.VC141.CRT'
          # ls -l '/c/Program Files (x86)/Microsoft Visual Studio/2022/Enterprise/VC/Redist/MSVC/'*/x64/Microsoft.*.CRT
          # ls -lR /c/Program\ Files\ \(x86\)/Microsoft Visual Studio/2022/Enterprise/VC/Redist/MSVC/
          # ls -lR '/c/Program Files (x86)/Microsoft Visual Studio/'2022/Enterprise/VC/Redist/MSVC/
          vswhere
          vswhere -find 'VC\Redist\**\VC_redist.x64.exe'

      - name: Setup Kaldi build configuration
        if: steps.cache-native-binaries-restore.outputs.cache-hit != 'true'
        run: |
          cd kaldi/windows
          cp kaldiwin_mkl.props kaldiwin.props
          cp variables.props.dev variables.props
          # Set openfst location
          perl -pi -e 's/<OPENFST>.*<\/OPENFST>/<OPENFST>$ENV{GITHUB_WORKSPACE}\\openfst<\/OPENFST>/g' variables.props
          perl -pi -e 's/<OPENFSTLIB>.*<\/OPENFSTLIB>/<OPENFSTLIB>$ENV{GITHUB_WORKSPACE}\\openfst\\build_output<\/OPENFSTLIB>/g' variables.props
          perl generate_solution.pl --vsver ${VS_VERSION} --enable-mkl --noportaudio
          # Add additional libfstscript library to dragonfly build file
          sed -i.bak '$i\
            <ItemDefinitionGroup>\
              <Link>\
                <AdditionalDependencies>libfstscript.lib;%(AdditionalDependencies)</AdditionalDependencies>\
              </Link>\
            </ItemDefinitionGroup>' ../kaldiwin_${VS_VERSION}_MKL/kaldiwin/kaldi-dragonfly/kaldi-dragonfly.vcxproj
          perl get_version.pl

      - name: Add msbuild to PATH
        if: steps.cache-native-binaries-restore.outputs.cache-hit != 'true'
        uses: microsoft/setup-msbuild@v2

      - name: Install MKL
        if: steps.cache-native-binaries-restore.outputs.cache-hit != 'true'
        run: winget install --id=Intel.oneMKL -v "${MKL_VERSION}" -e --accept-package-agreements --accept-source-agreements --disable-interactivity

      - name: Build OpenFST
        if: steps.cache-native-binaries-restore.outputs.cache-hit != 'true'
        shell: cmd
        run: msbuild -t:Build -p:Configuration=Release -p:Platform=x64 -p:PlatformToolset=%PLATFORM_TOOLSET% -maxCpuCount -verbosity:minimal openfst/openfst.sln

      - name: Build Kaldi
        if: steps.cache-native-binaries-restore.outputs.cache-hit != 'true'
        shell: cmd
        run: msbuild -t:Build -p:Configuration=Release -p:Platform=x64 -p:PlatformToolset=%PLATFORM_TOOLSET% -p:WindowsTargetPlatformVersion=%WINDOWS_TARGET_PLATFORM_VERSION% -maxCpuCount -verbosity:minimal kaldi/kaldiwin_%VS_VERSION%_MKL/kaldiwin/kaldi-dragonfly/kaldi-dragonfly.vcxproj

      - name: Copy native binaries
        if: steps.cache-native-binaries-restore.outputs.cache-hit != 'true'
        run: |
          mkdir -p main/kaldi_active_grammar/exec/windows
          cp kaldi/kaldiwin_${VS_VERSION}_MKL/kaldiwin/kaldi-dragonfly/x64/Release/kaldi-dragonfly.dll main/kaldi_active_grammar/exec/windows/

      - name: Save cached native binaries
        if: steps.cache-native-binaries-restore.outputs.cache-hit != 'true'
        uses: actions/cache/save@v4
        with:
          key: ${{ steps.cache-native-binaries-restore.outputs.cache-primary-key }}
          path: main/kaldi_active_grammar/exec/windows

      - name: Upload native binaries to artifacts
        uses: actions/upload-artifact@v4
        with:
          name: native-windows
          path: main/kaldi_active_grammar/exec/windows

      - name: Build Python wheel
        working-directory: main
        run: |
          python -m pip -V
          python -m pip install --upgrade setuptools wheel
          env KALDIAG_BUILD_SKIP_NATIVE=1 python setup.py bdist_wheel
          ls -l dist/

      - name: Upload Windows wheels
        uses: actions/upload-artifact@v4
        with:
          name: wheels-windows
          path: main/dist/*

      - name: Examine results
        run: |
          shopt -s nullglob
          for whl in main/dist/*.whl; do
            echo "::notice title=Built wheel::$(basename $whl)"
            unzip -l $whl
          done

      # - name: Copy Windows vc_redist
      #   run: |
      #     mkdir -p vc_redist
      #     cp '/c/Program Files (x86)/Microsoft Visual Studio/2022/Enterprise/VC/Redist/MSVC/14.26.28720'/vc_redist.x64.exe vc_redist/
      #     cp '/c/Program Files (x86)/Microsoft Visual Studio/2022/Enterprise/VC/Redist/MSVC/14.26.28720'/x64/Microsoft.*.CRT/* vc_redist/
      # - uses: actions/upload-artifact@v4
      #   with:
      #     name: windows_vc_redist
      #     path: vc_redist/*

  build-macos-arm:
    runs-on: macos-15
    if: true
    env:
      MACOSX_DEPLOYMENT_TARGET: "11.0"
      MKL_URL: ""
      # MKL_URL: https://registrationcenter-download.intel.com/akdlm/irc_nas/tec/17172/m_mkl_2020.4.301.dmg
    steps:
      - name: Checkout repository
        uses: actions/checkout@v5

      - name: Get KALDI_BRANCH (kag-$TAG tag if commit is tagged; current branch name if not)
        id: get-kaldi-branch
        run: |
          # Fetch tags on the one fetched commit (shallow clone)
          git fetch --depth=1 origin "+refs/tags/*:refs/tags/*"
          export TAG=$(git tag --points-at HEAD)
          echo "TAG: $TAG"
          if [[ $TAG ]]; then
            echo "KALDI_BRANCH: kag-$TAG"
            echo "KALDI_BRANCH=kag-$TAG" >> $GITHUB_ENV
            echo "KALDI_BRANCH=kag-$TAG" >> $GITHUB_OUTPUT
          else
            echo "KALDI_BRANCH: ${GITHUB_REF/refs\/heads\//}"
            echo "KALDI_BRANCH=${GITHUB_REF/refs\/heads\//}" >> $GITHUB_ENV
            echo "KALDI_BRANCH=${GITHUB_REF/refs\/heads\//}" >> $GITHUB_OUTPUT
          fi

      - name: Get Kaldi commit hash
        id: get-kaldi-commit
        run: |
          KALDI_COMMIT=$(git ls-remote https://github.com/daanzu/kaldi-fork-active-grammar.git $KALDI_BRANCH | cut -f1)
          echo "KALDI_COMMIT: $KALDI_COMMIT"
          echo "KALDI_COMMIT=$KALDI_COMMIT" >> $GITHUB_OUTPUT

      - name: Restore cached native binaries
        id: cache-native-binaries-restore
        uses: actions/cache/restore@v4
        with:
          key: native-${{ runner.os }}-arm-${{ steps.get-kaldi-commit.outputs.KALDI_COMMIT }}-${{ env.MACOSX_DEPLOYMENT_TARGET }}-${{ env.MKL_URL }}-v1
          path: kaldi_active_grammar/exec/macos

      - name: Install MKL (if enabled)
        if: ${{ env.MKL_URL != '' && steps.cache-native-binaries-restore.outputs.cache-hit != 'true' }}
        run: |
          echo "Installing MKL from: $MKL_URL"
          export MKL_FILE=${MKL_URL##*/}
          export MKL_FILE=${MKL_FILE%\.dmg}
          wget --no-verbose $MKL_URL
          hdiutil attach ${MKL_FILE}.dmg
          cp /Volumes/${MKL_FILE}/${MKL_FILE}.app/Contents/MacOS/silent.cfg .
          sed -i.bak -e 's/decline/accept/g' silent.cfg
          sudo /Volumes/${MKL_FILE}/${MKL_FILE}.app/Contents/MacOS/install.sh --silent silent.cfg

      - name: Install dependencies for native build
        if: steps.cache-native-binaries-restore.outputs.cache-hit != 'true'
        run: |
          python3 -m pip install --break-system-packages --user --upgrade scikit-build>=0.10.0 cmake ninja
          brew install automake sox libtool
          brew reinstall gfortran  # For openblas
          # brew install autoconf

      - name: Install dependencies for python build
        run: |
          python3 -m pip install --break-system-packages --user --upgrade setuptools wheel delocate

      - name: Build Python wheel
        run: |
          shopt -s nullglob
          echo "KALDI_BRANCH: $KALDI_BRANCH"
          echo "MKL_URL: $MKL_URL"
          ${{ steps.cache-native-binaries-restore.outputs.cache-hit == 'true' && 'KALDIAG_BUILD_SKIP_NATIVE=1' || '' }} python3 setup.py bdist_wheel
          ls -l dist/
          for whl in dist/*.whl; do
            unzip -l $whl
          done

      - name: Repair wheel with delocate
        run: |
          shopt -s nullglob
          for whl in dist/*.whl; do
            echo "Examining wheel before delocate: $whl"
            python3 -m delocate.cmd.delocate_listdeps -d $whl
            echo "Repairing wheel: $whl"
            python3 -m delocate.cmd.delocate_wheel -v -w wheelhouse -L exec/macos/libs --require-archs arm64 $whl
          done
          # NOTE: This also downgrades the required MacOS version to the minimum possible
          ls -l wheelhouse/
          for whl in wheelhouse/*.whl; do
            echo "Examining repaired wheel: $whl"
            python3 -m delocate.cmd.delocate_listdeps -d $whl
          done

      - name: Extract native binaries from wheel after delocate repair, to save to cache
        if: steps.cache-native-binaries-restore.outputs.cache-hit != 'true'
        # We do this rather than manually caching all of the various kaldi/openfst libraries in their build locations
        run: |
          shopt -s nullglob
          # Assert there is only one wheel
          WHEEL_COUNT=$(ls wheelhouse/*.whl | wc -l)
          if [ "$WHEEL_COUNT" -ne 1 ]; then
            echo "Error: Expected exactly 1 wheel, found $WHEEL_COUNT"
            ls -l wheelhouse/
            exit 1
          fi
          WHEEL_FILE=$(ls wheelhouse/*.whl)
          echo "Extracting from wheel: $WHEEL_FILE"
          unzip -o $WHEEL_FILE 'kaldi_active_grammar/exec/macos/*'
          ls -l kaldi_active_grammar/exec/macos/
          otool -l kaldi_active_grammar/exec/macos/libkaldi-dragonfly.dylib | egrep -A2 'LC_RPATH|cmd LC_LOAD_DYLIB'
          otool -L kaldi_active_grammar/exec/macos/libkaldi-dragonfly.dylib
          lipo -archs kaldi_active_grammar/exec/macos/libkaldi-dragonfly.dylib

      - name: Save cached native binaries
        if: steps.cache-native-binaries-restore.outputs.cache-hit != 'true'
        uses: actions/cache/save@v4
        with:
          key: ${{ steps.cache-native-binaries-restore.outputs.cache-primary-key }}
          path: kaldi_active_grammar/exec/macos

      - name: Upload native binaries to artifacts
        uses: actions/upload-artifact@v4
        with:
          name: native-macos-arm
          path: kaldi_active_grammar/exec/macos

      - name: Upload MacOS ARM wheels
        uses: actions/upload-artifact@v4
        with:
          name: wheels-macos-arm
          path: wheelhouse/*

      - name: Examine results
        run: |
          shopt -s nullglob
          for whl in wheelhouse/*.whl; do
            echo "::notice title=Built wheel::$(basename $whl)"
            unzip -l $whl
          done

  build-macos-intel:
    runs-on: macos-15-intel
    if: true
    env:
      MACOSX_DEPLOYMENT_TARGET: "10.9"
      MKL_URL: ""
      # MKL_URL: https://registrationcenter-download.intel.com/akdlm/irc_nas/tec/17172/m_mkl_2020.4.301.dmg
    steps:
      - name: Checkout repository
        uses: actions/checkout@v5

      - name: Get KALDI_BRANCH (kag-$TAG tag if commit is tagged; current branch name if not)
        id: get-kaldi-branch
        run: |
          # Fetch tags on the one fetched commit (shallow clone)
          git fetch --depth=1 origin "+refs/tags/*:refs/tags/*"
          export TAG=$(git tag --points-at HEAD)
          echo "TAG: $TAG"
          if [[ $TAG ]]; then
            echo "KALDI_BRANCH: kag-$TAG"
            echo "KALDI_BRANCH=kag-$TAG" >> $GITHUB_ENV
            echo "KALDI_BRANCH=kag-$TAG" >> $GITHUB_OUTPUT
          else
            echo "KALDI_BRANCH: ${GITHUB_REF/refs\/heads\//}"
            echo "KALDI_BRANCH=${GITHUB_REF/refs\/heads\//}" >> $GITHUB_ENV
            echo "KALDI_BRANCH=${GITHUB_REF/refs\/heads\//}" >> $GITHUB_OUTPUT
          fi

      - name: Get Kaldi commit hash
        id: get-kaldi-commit
        run: |
          KALDI_COMMIT=$(git ls-remote https://github.com/daanzu/kaldi-fork-active-grammar.git $KALDI_BRANCH | cut -f1)
          echo "KALDI_COMMIT: $KALDI_COMMIT"
          echo "KALDI_COMMIT=$KALDI_COMMIT" >> $GITHUB_OUTPUT

      - name: Restore cached native binaries
        id: cache-native-binaries-restore
        uses: actions/cache/restore@v4
        with:
          key: native-${{ runner.os }}-intel-${{ steps.get-kaldi-commit.outputs.KALDI_COMMIT }}-${{ env.MACOSX_DEPLOYMENT_TARGET }}-${{ env.MKL_URL }}-v1
          path: kaldi_active_grammar/exec/macos

      - name: Install MKL (if enabled)
        if: ${{ env.MKL_URL != '' && steps.cache-native-binaries-restore.outputs.cache-hit != 'true' }}
        run: |
          echo "Installing MKL from: $MKL_URL"
          export MKL_FILE=${MKL_URL##*/}
          export MKL_FILE=${MKL_FILE%\.dmg}
          wget --no-verbose $MKL_URL
          hdiutil attach ${MKL_FILE}.dmg
          cp /Volumes/${MKL_FILE}/${MKL_FILE}.app/Contents/MacOS/silent.cfg .
          sed -i.bak -e 's/decline/accept/g' silent.cfg
          sudo /Volumes/${MKL_FILE}/${MKL_FILE}.app/Contents/MacOS/install.sh --silent silent.cfg

      - name: Install dependencies for native build
        if: steps.cache-native-binaries-restore.outputs.cache-hit != 'true'
        run: |
          python3 -m pip install --break-system-packages --user --upgrade scikit-build>=0.10.0 cmake ninja
          brew install automake sox
          brew reinstall gfortran  # For openblas
          # brew install autoconf libtool

      - name: Install dependencies for python build
        run: |
          python3 -m pip install --break-system-packages --user --upgrade setuptools wheel delocate

      - name: Build Python wheel
        run: |
          shopt -s nullglob
          echo "KALDI_BRANCH: $KALDI_BRANCH"
          echo "MKL_URL: $MKL_URL"
          ${{ steps.cache-native-binaries-restore.outputs.cache-hit == 'true' && 'KALDIAG_BUILD_SKIP_NATIVE=1' || '' }} python3 setup.py bdist_wheel
          ls -l dist/
          for whl in dist/*.whl; do
            unzip -l $whl
          done

      - name: Repair wheel with delocate
        run: |
          shopt -s nullglob
          for whl in dist/*.whl; do
            echo "Examining wheel before delocate: $whl"
            python3 -m delocate.cmd.delocate_listdeps -d $whl
            echo "Repairing wheel: $whl"
            python3 -m delocate.cmd.delocate_wheel -v -w wheelhouse -L exec/macos/libs --require-archs x86_64 $whl
          done
          # NOTE: This also downgrades the required MacOS version to the minimum possible
          ls -l wheelhouse/
          for whl in wheelhouse/*.whl; do
            echo "Examining repaired wheel: $whl"
            python3 -m delocate.cmd.delocate_listdeps -d $whl
          done

      - name: Extract native binaries from wheel after delocate repair, to save to cache
        if: steps.cache-native-binaries-restore.outputs.cache-hit != 'true'
        # We do this rather than manually caching all of the various kaldi/openfst libraries in their build locations
        run: |
          shopt -s nullglob
          # Assert there is only one wheel
          WHEEL_COUNT=$(ls wheelhouse/*.whl | wc -l)
          if [ "$WHEEL_COUNT" -ne 1 ]; then
            echo "Error: Expected exactly 1 wheel, found $WHEEL_COUNT"
            ls -l wheelhouse/
            exit 1
          fi
          WHEEL_FILE=$(ls wheelhouse/*.whl)
          echo "Extracting from wheel: $WHEEL_FILE"
          unzip -o $WHEEL_FILE 'kaldi_active_grammar/exec/macos/*'
          ls -l kaldi_active_grammar/exec/macos/
          otool -l kaldi_active_grammar/exec/macos/libkaldi-dragonfly.dylib | egrep -A2 'LC_RPATH|cmd LC_LOAD_DYLIB'
          otool -L kaldi_active_grammar/exec/macos/libkaldi-dragonfly.dylib
          lipo -archs kaldi_active_grammar/exec/macos/libkaldi-dragonfly.dylib

      - name: Save cached native binaries
        if: steps.cache-native-binaries-restore.outputs.cache-hit != 'true'
        uses: actions/cache/save@v4
        with:
          key: ${{ steps.cache-native-binaries-restore.outputs.cache-primary-key }}
          path: kaldi_active_grammar/exec/macos

      - name: Upload native binaries to artifacts
        uses: actions/upload-artifact@v4
        with:
          name: native-macos-intel
          path: kaldi_active_grammar/exec/macos

      - name: Upload MacOS Intel wheels
        uses: actions/upload-artifact@v4
        with:
          name: wheels-macos-intel
          path: wheelhouse/*

      - name: Examine results
        run: |
          shopt -s nullglob
          for whl in wheelhouse/*.whl; do
            echo "::notice title=Built wheel::$(basename $whl)"
            unzip -l $whl
          done

  merge-wheels:
    runs-on: ubuntu-latest
    needs: [
      build-linux,
      build-windows,
      build-macos-arm,
      build-macos-intel,
    ]
    steps:
      - name: Merge all wheel artifacts
        uses: actions/upload-artifact/merge@v4
        with:
          name: wheels
          pattern: wheels-*
          delete-merged: false  # Optional: removes the individual artifacts

  setup-tests-cache:
    runs-on: ${{ matrix.os }}
    strategy:
      matrix:
        os: [ubuntu-latest, windows-latest]
    steps:
      - uses: actions/checkout@v5

      - name: Install just
        uses: taiki-e/install-action@just

      - name: Install uv
        uses: astral-sh/setup-uv@v6

      - name: Restore cached tests setup
        id: cache-tests-setup-restore
        uses: actions/cache/restore@v4
        with:
          key: tests-setup-${{ hashFiles('Justfile') }}-v1
          path: |
            tests/*.onnx
            tests/*.onnx.json
            tests/kaldi_model

      - name: Setup tests
        if: steps.cache-tests-setup-restore.outputs.cache-hit != 'true'
        run: |
          just setup-tests

      - name: Save cached tests setup
        if: steps.cache-tests-setup-restore.outputs.cache-hit != 'true'
        uses: actions/cache/save@v4
        with:
          key: ${{ steps.cache-tests-setup-restore.outputs.cache-primary-key }}
          path: |
            tests/*.onnx
            tests/*.onnx.json
            tests/kaldi_model

  test-wheels:
    runs-on: ${{ matrix.os }}
    needs:
      - build-linux
      - build-windows
      - build-macos-arm
      - build-macos-intel
      - setup-tests-cache
    if: ${{ always() && true }}  # Run even if some build jobs failed
    defaults:
      run:
        shell: bash
    strategy:
      fail-fast: false
      matrix:
        # https://docs.github.com/en/actions/reference/runners/github-hosted-runners#standard-github-hosted-runners-for-public-repositories
        # https://github.com/actions/runner-images
        os: [ubuntu-22.04, ubuntu-24.04, windows-2022, windows-2025, macos-14, macos-15, macos-15-intel, macos-26]
        # Status of Python versions (https://devguide.python.org/versions/)
        python-version: ["3.9", "3.10", "3.11", "3.12", "3.13"]  # 3.14 doesn't have piper-tts wheels yet
    steps:
      - uses: actions/checkout@v5

      - name: Install just
        uses: taiki-e/install-action@just

      - name: Install uv and set the python version
        uses: astral-sh/setup-uv@v6
        with:
          python-version: ${{ matrix.python-version }}

      - name: Set artifact name
        id: artifact-name
        run: |
          case "${{ matrix.os }}" in
            ubuntu-*) echo "name=wheels-linux" >> $GITHUB_OUTPUT ;;
            windows-*) echo "name=wheels-windows" >> $GITHUB_OUTPUT ;;
            macos-15-intel) echo "name=wheels-macos-intel" >> $GITHUB_OUTPUT ;;
            macos-*) echo "name=wheels-macos-arm" >> $GITHUB_OUTPUT ;;
            *) echo "Unexpected OS: ${{ matrix.os }}" 1>&2; exit 1 ;;
          esac

      - name: Download wheel artifacts
        uses: actions/download-artifact@v4
        with:
          name: ${{ steps.artifact-name.outputs.name }}
          path: wheels/
        continue-on-error: true  # Continue even if no artifact found

      - name: Check wheels presence
        id: wheels-presence
        run: |
          shopt -s nullglob
          files=(wheels/*.whl)
          if (( ${#files[@]} > 0 )); then
            echo "found=true" >> $GITHUB_OUTPUT
            ls -l wheels/
          else
            echo "found=false" >> $GITHUB_OUTPUT
            echo "No wheel artifacts found for ${{ matrix.os }}" 1>&2
          fi

      - name: Restore cached tests setup
        uses: actions/cache/restore@v4
        with:
          key: tests-setup-${{ hashFiles('Justfile') }}-v1
          path: |
            tests/*.onnx
            tests/*.onnx.json
            tests/kaldi_model
          fail-on-cache-miss: true

      - name: Run tests
        if: steps.wheels-presence.outputs.found == 'true'
        # Must ignore warnings for piper-tts on Github Actions Windows runners
        run: |
          # just test-package -v -W 'ignore:Unsupported Windows version (2022server). ONNX Runtime supports Windows 10 and above, only.:UserWarning' -W 'ignore:Unsupported Windows version (2025server). ONNX Runtime supports Windows 10 and above, only.:UserWarning'
          just test-package-separately -W 'ignore:Unsupported Windows version (2022server). ONNX Runtime supports Windows 10 and above, only.:UserWarning' -W 'ignore:Unsupported Windows version (2025server). ONNX Runtime supports Windows 10 and above, only.:UserWarning'


================================================
FILE: .gitignore
================================================
_cmake_test_compile/
kaldi_active_grammar/exec
examples/*.fst
portable/
tests/*.onnx
tests/*.onnx.json
tests/**/*.wav
tmp/
wheels
*/kaldi_model*/
*/kaldi_model*.zip

# general things to ignore
venv*/
build/
_skbuild/
dist/
wheelhouse/
wheels/
*.egg-info/
*.egg
*.py[cod]
__pycache__/
*.so
*~
.vscode/
pip-wheel-metadata/

# due to using tox and pytest
.tox
.cache
.coverage


================================================
FILE: AGENTS.md
================================================
# Kaldi Active Grammar - Agent Information

This document provides technical architectural information for AI coding agents (or humans!) working with the kaldi-active-grammar project.

WARNING: This file may be auto-generated and/or out of date!

## Project Overview

**Kaldi Active Grammar** is a Python package that enables context-based command and control using the Kaldi automatic speech recognition engine with dynamically manageable grammars.

### Key Technologies

- **Speech Recognition**: Kaldi ASR engine
- **Language**: Python 3.6+
- **Supported Platforms**: Windows, Linux, macOS (64-bit)
- **Primary Integration**: Dragonfly speech recognition framework
- **Model Architecture**: Kaldi nnet3 chain models

### Version Information

- **Current Version**: See [`kaldi_active_grammar/__init__.py:8`](kaldi_active_grammar/__init__.py:8)
- **Required Model Version**: See [`kaldi_active_grammar/__init__.py:10`](kaldi_active_grammar/__init__.py:10)
- **Version History**: See [`CHANGELOG.md`](CHANGELOG.md:1)

## Core Modules

### Compiler (`kaldi_active_grammar/compiler.py`)

The **Compiler** module is responsible for compiling grammar rules into FST (Finite State Transducer) format for use by the Kaldi decoder.

**Key Classes:**
- `Compiler`: Main compilation engine that manages grammar compilation and FST generation
- `KaldiRule`: Represents an individual grammar rule with associated FST representation

**Responsibilities:**
- Grammar-to-FST compilation
- Rule caching and management
- Dynamic grammar loading/unloading
- Lexicon handling and pronunciation generation

### Model (`kaldi_active_grammar/model.py`)

The **Model** module manages the Kaldi acoustic model and lexicon operations.

**Key Classes:**
- `Lexicon`: Manages phoneme sets and phoneme conversion (CMU to XSAMPA)
- `Model`: Orchestrates the acoustic model and lexicon

**Responsibilities:**
- Loading and validating Kaldi nnet3 chain models
- Lexicon management (CMU, XSAMPA phoneme sets)
- Word pronunciation generation (local via g2p_en or online)
- Model version verification

### Wrapper (`kaldi_active_grammar/wrapper.py`)

The **Wrapper** module provides the FFI (Foreign Function Interface) to native Kaldi binaries.

**Key Classes:**
- `KaldiAgfNNet3Decoder`: Main decoder for active grammar FSTs
- `KaldiLafNNet3Decoder`: Alternative LAF (Linear Alignment Filter) decoder
- `KaldiPlainNNet3Decoder`: Decoder for plain dictation

**Responsibilities:**
- Native library binding
- Audio decoding
- Hypothesis generation and lattice manipulation

### WFST (Weighted Finite State Transducer) (`kaldi_active_grammar/wfst.py`)

The **WFST** module handles FST representation and manipulation.

**Key Classes:**
- `WFST`: Python-based FST implementation
- `NativeWFST`: Native (C++-based) FST wrapper
- `SymbolTable`: Maps symbols to numeric IDs for FST operations

**Responsibilities:**
- FST construction and modification
- Symbol table management
- FST serialization and caching

### Plain Dictation (`kaldi_active_grammar/plain_dictation.py`)

The **PlainDictationRecognizer** module provides simple dictation recognition without grammar rules.

**Features:**
- Works with standard Kaldi HCLG.fst files
- Fallback option for dictation-only use cases
- Compatible with both pre-trained models and custom models

### Utilities (`kaldi_active_grammar/utils.py`)

Utility functions for:
- File discovery and path handling
- Symbol table loading
- External process management
- Cross-platform compatibility

## Architecture Overview

```
┌─────────────────────────────────────────┐
│     Dragonfly / User Application        │
└────────────────┬────────────────────────┘
                 │
┌─────────────────▼────────────────────────┐
│  Compiler (Grammar Rules → FSTs)         │
├──────────────────────────────────────────┤
│ • Grammar compilation                    │
│ • FST generation & caching               │
│ • Rule management                        │
└────────────────┬────────────────────────┘
                 │
┌─────────────────▼────────────────────────┐
│  Model (Acoustic Model + Lexicon)        │
├──────────────────────────────────────────┤
│ • Kaldi nnet3 chain model loading        │
│ • Pronunciation generation               │
│ • Lexicon management                     │
└────────────────┬────────────────────────┘
                 │
┌─────────────────▼────────────────────────┐
│  Wrapper (FFI to Native Kaldi)           │
├──────────────────────────────────────────┤
│ • KaldiAgfNNet3Decoder                   │
│ • KaldiLafNNet3Decoder                   │
│ • Audio decoding & lattice generation    │
└────────────────┬────────────────────────┘
                 │
┌─────────────────▼────────────────────────┐
│  Native Kaldi Binaries (C++)             │
├──────────────────────────────────────────┤
│ • Acoustic model decoding                │
│ • FST operations                         │
│ • Lattice operations                     │
└──────────────────────────────────────────┘
```

## Key Features & Capabilities

### Dynamic Grammar Management
- Grammars can be marked active/inactive on a per-utterance basis
- Enables context-aware command recognition
- Improves accuracy by reducing possible recognitions

### Grammar Compilation
- Multiple independent grammars with nonterminals
- Separate compilation and dynamic stitching at decode-time
- Shared dictation grammar between command grammars

### Performance & Accuracy
- Context-based activation reduces vocabulary scope
- Efficient FST-based representation
- Support for weighted grammar rules

### Dictation Support
- Integrated dictation grammar
- Plain dictation interface (HCLG.fst compatible)
- Pronunciation generation via g2p_en or online service

## Development Integration

### Testing
- Test suite in `tests/` directory
- Pytest configuration in `pyproject.toml`
- Coverage reporting can be enabled
- Integration tests for grammar compilation and decoding
- Run tests with `just test`
- To setup virtual environment for tests: `uv venv && uv pip install -r requirements-test.txt -r requirements-editable.txt`

### Examples
- `examples/plain_dictation.py`: Plain dictation usage
- `examples/mix_dictation.py`: Mixed command+dictation
- `examples/full_example.py`: Comprehensive example
- `examples/audio.py`: Audio handling utilities

### Build System
- CMake-based native compilation
- Scikit-build integration for wheel generation
- Multi-platform support (Windows/Linux/macOS)
- GitHub Actions CI/CD pipeline

## System Requirements

- **Python**: 3.6+, 64-bit
- **RAM**: 1GB+ (model + grammars)
- **Disk Space**: 1GB+ (model + temporary files)
- **Model Type**: Kaldi left-biphone nnet3 chain (specific modifications required)
- **Audio Input**: Microphone or audio file

## Workflow

1. **Model Initialization**: Load Kaldi nnet3 chain model
2. **Grammar Definition**: Define command/rule grammar
3. **Compilation**: Compiler converts grammar rules to FSTs
4. **Activation**: Set which grammars are active for current utterance
5. **Decoding**: Wrapper processes audio through Kaldi decoder
6. **Recognition**: Return recognized utterance and associated action


================================================
FILE: CHANGELOG.md
================================================
# Changelog

All notable changes to this project will be documented in this file.
Note that the project (and python wheel) is built from a duorepo (2 separate repos used together), so changes from both will be reflected here, but the commits are spread between both.

The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html) since v1.0.0.

<!-- ## [Unreleased] - Changes: [KaldiAG](https://github.com/daanzu/kaldi-active-grammar/compare/v3.2.0...master) [KaldiFork](https://github.com/daanzu/kaldi-fork-active-grammar/compare/kag-v3.2.0...master) -->

## [3.2.0](https://github.com/daanzu/kaldi-active-grammar/releases/tag/v3.2.0) - 2025-11-02 - Changes: [KaldiAG](https://github.com/daanzu/kaldi-active-grammar/compare/v3.1.0...v3.2.0) [KaldiFork](https://github.com/daanzu/kaldi-fork-active-grammar/compare/kag-v3.1.0...kag-v3.2.0)

### Added

* Comprehensive test suite with 80+ tests covering grammar compilation, plain dictation, and alternative dictation
* Test infrastructure using pytest with TTS-generated test audio (Piper)
* `AGENTS.md` documentation for AI coding agents with project architecture and development guidance
* Exposed `NativeWFST` at package top-level for easier importing
* Support for testing with multiple platforms and Python versions (3.9-3.13)

### Changed

* **CI/CD Improvements**:
  * Implemented comprehensive caching of native binaries by commit hash
  * Added caching of test setup data
  * Updated build workflow to run on all pushes and PRs
  * Modified macOS wheel builds to use delocate instead of ad-hoc manual library handling
  * Improved Linux wheel build with cleaner output and better caching
  * Updated CI to support latest GitHub Actions runners (Ubuntu 24.04, Windows 2025, macOS 13/15/26)
  * Moved tests into main build workflow for faster feedback
  * Added notices for built wheels in CI output
* Relaxed Python package requirements version specifiers for better compatibility
* Updated setup.py classifiers to include Python 3.11, 3.12, 3.13, 3.14
* Dropped Python 2 from wheel tag (py3 instead of py2.py3), as Python 2 is no longer supported
* Improved comments and cleanup in Justfile

### Fixed

* Updated CI workflows to properly handle latest runner environments
* Fixed Linux build configuration and wrapper script
* Cleaned up and standardized build processes across all platforms

### Development

* Refactored test structure for better organization and maintainability
* Added test generators for creating synthetic speech using Piper TTS and Google TTS
* Added helper utilities for test fixtures and audio generation
* Improved test coverage for edge cases (empty audio, garbage audio, very short/long audio)
* Added tests for complex grammar patterns (diamond, cascade, hub-and-spoke, etc.)
* Added comprehensive alternative dictation tests with mocking

## [3.1.0](https://github.com/daanzu/kaldi-active-grammar/releases/tag/v3.1.0) - 2021-11-24 - Changes: [KaldiAG](https://github.com/daanzu/kaldi-active-grammar/compare/v3.0.0...v3.1.0) [KaldiFork](https://github.com/daanzu/kaldi-fork-active-grammar/compare/kag-v3.0.0...kag-v3.1.0)

### Fixed

* Fix updating of SymbolTable multiple times for new words, so that there is only one instance for a single Model.

### Changed

* Only mark lexicon stale if it was successfully modified.
* Removed deprecated CLI binaries from Windows build, reducing wheel size by ~65%.

## [3.0.0](https://github.com/daanzu/kaldi-active-grammar/releases/tag/v3.0.0) - 2021-10-31 - Changes: [KaldiAG](https://github.com/daanzu/kaldi-active-grammar/compare/v2.1.0...v3.0.0) [KaldiFork](https://github.com/daanzu/kaldi-fork-active-grammar/compare/kag-v2.1.0...kag-v3.0.0)

### Changed

* Pronunciation generation for lexicon now better supports local mode (using the `g2p_en` package), which is now also the default mode. It is also preferred over the online mode (using CMU's web service), which is now disabled by default. See the Setup section of the README for details. The new models now include the data files for `g2p_en`.
* `PlainDictation` output now discards any silence words from transcript.
* `lattice_beam` default value reduced from `6.0` to `5.0`, to hopefully avoid occasional errors.
* Removed deprecated CLI binaries from build for linux/mac.

### Fixed

* Whitespace in the model path is once again handled properly (thanks [@matthewmcintire](https://github.com/matthewmcintire)).
* `NativeWFST.has_path()` now handles loops.
* Linux/Mac binaries are now more stripped.

## [2.1.0](https://github.com/daanzu/kaldi-active-grammar/releases/tag/v2.1.0) - 2021-04-04 - Changes: [KaldiAG](https://github.com/daanzu/kaldi-active-grammar/compare/v2.0.2...v2.1.0) [KaldiFork](https://github.com/daanzu/kaldi-fork-active-grammar/compare/kag-v2.0.2...kag-v2.1.0)

### Added

* NativeWFST support for checking for impossible graphs (no successful path), which can then fail to compile.
* Debugging info for NativeWFST.

### Changed

* `lattice_beam` default value reduced from `8.0` to `6.0`, to hopefully avoid occasional errors.

### Fixed

* Reloading grammars with NativeWFST.

## [2.0.2](https://github.com/daanzu/kaldi-active-grammar/releases/tag/v2.0.2) - 2021-03-30 - Changes: [KaldiAG](https://github.com/daanzu/kaldi-active-grammar/compare/v2.0.0...v2.0.2) [KaldiFork](https://github.com/daanzu/kaldi-fork-active-grammar/compare/kag-v2.0.0...kag-v2.0.2)

### Changed

* Minor fix for OpenBLAS compilation for some architectures on linux/mac

## [2.0.0](https://github.com/daanzu/kaldi-active-grammar/releases/tag/v2.0.0) - 2021-03-21 - Changes: [KaldiAG](https://github.com/daanzu/kaldi-active-grammar/compare/v1.8.0...v2.0.0) [KaldiFork](https://github.com/daanzu/kaldi-fork-active-grammar/compare/kag-v1.8.0...kag-v2.0.0)

### Added

* Native FST support, via direct wrapping of OpenFST, rather than Python text-format implementation
    * Eliminates grammar (G) FST compilation step
* Internalized many graph construction steps, via direct use of native Kaldi/OpenFST functions, rather than invoking separate CLI processes
    * Eliminates need for many temporary files (FSTs, `.conf`s, etc) and pipes
* Example usage for allowing mixing of free dictation with strict command phrases
* Experimental support for "look ahead" graphs, as an alternative to full HCLG compilation
* Experimental support for rescoring with CARPA LMs
* Experimental support for rescoring with RNN LMs
* Experimental support for "priming" RNNLM previous left context for each utterance

### Changed

* OpenBLAS is now the default linear algebra library (rather than Intel MKL) on Linux/MacOS
    * Because it is open source and provides good performance on all hardware (including AMD)
    * Windows is more difficult for this, and will be implemented soon in a later release
* Default `tmp_dir` is now set to `[model_dir]/cache.tmp`
* `tmp_dir` is now optional, and only needed if caching compiled FSTs (or for certain framework/option combinations)
* File cache is now stored at `[model_dir]/file_cache.json`
* Optimized adding many new words to the lexicon, in many different grammars, all in one loading session: only rebuild `L_disambig.fst` once at the end.
* External interfaces: `Compiler.__init__()`, decoding setup, etc.
* Internal interfaces: wrappers, etc.
* Major refactoring of C++ components, with a new inheritance hierarchy and configuration mechanism, making it easier to use and test features with and without "activity"
* Many build changes

### Removed

* Python 2.7 support: it may still work, but will not be a focus.
* Google cloud speech-to-text removed, as an unneeded dependency. Alternative dictation is still supported as an option, via a callback to an external provider.

### Deprecated

* Separate CLI Kaldi/OpenFST executables
* Indirect AGF graph compilation (framework==`agf-indirect`)
* Non-native FSTs
* parsing_framework==`text`

## [1.8.0](https://github.com/daanzu/kaldi-active-grammar/releases/tag/v1.8.0) - 2020-09-05 - Changes: [KaldiAG](https://github.com/daanzu/kaldi-active-grammar/compare/v1.7.0...v1.8.0) [KaldiFork](https://github.com/daanzu/kaldi-fork-active-grammar/compare/kag-v1.7.0...kag-v1.8.0)

### Added
* New speech models (should be better in general, and support new noise resistance)
* Make failed AGF graph compilation save and output stderr upon failure automatically
* Example of complete usage with a grammar and microphone audio
* Various documentation

### Changed
* Top FST now accepts various noise phones (if present in speech model), making it more resistant to noise
* Cleanup error handling in compiler, supporting Dragonfly backend automatically printing excerpt of the Rule that failed

### Fixed
* Mysterious windows newline bug in some environments

## [1.7.0](https://github.com/daanzu/kaldi-active-grammar/releases/tag/v1.7.0) - 2020-08-01 - Changes: [KaldiAG](https://github.com/daanzu/kaldi-active-grammar/compare/v1.6.2...v1.7.0) [KaldiFork](https://github.com/daanzu/kaldi-fork-active-grammar/compare/kag-v1.6.2...kag-v1.7.0)

### Added
* Add automatic saving of text FST & compiled FST files with log level 5

### Changed
* Miscellaneous naming

### Fixed
* Support compiling some complex grammars (Caster text manipulation), by simplifying during compilation (remove epsilons, and determinize)

## [1.6.2](https://github.com/daanzu/kaldi-active-grammar/releases/tag/v1.6.2) - 2020-07-20 - Changes: [KaldiAG](https://github.com/daanzu/kaldi-active-grammar/compare/v1.6.1...v1.6.2) [KaldiFork](https://github.com/daanzu/kaldi-fork-active-grammar/compare/kag-v1.6.1...kag-v1.6.2)

### Fixed
* Add missing rnnlm library file in MacOS build

## [1.6.1](https://github.com/daanzu/kaldi-active-grammar/releases/tag/v1.6.1) - 2020-07-19 - Changes: [KaldiAG](https://github.com/daanzu/kaldi-active-grammar/compare/v1.6.0...v1.6.1) [KaldiFork](https://github.com/daanzu/kaldi-fork-active-grammar/compare/kag-v1.6.0...kag-v1.6.1)

### Changed
* Windows wheels now only require the VS2017 (not VS2019) redistributables to be installed

## [1.6.0](https://github.com/daanzu/kaldi-active-grammar/releases/tag/v1.6.0) - 2020-07-11 - Changes: [KaldiAG](https://github.com/daanzu/kaldi-active-grammar/compare/v1.5.0...v1.6.0) [KaldiFork](https://github.com/daanzu/kaldi-fork-active-grammar/compare/kag-v1.5.0...kag-v1.6.0)

### Added
* Can now pass configuration dict to `KaldiAgfNNet3Decoder`, `PlainDictationRecognizer` (without `HCLG.fst`).
* Continuous Integration builds run on GitHub Actions for Windows (x64), MacOS (x64), Linux (x64).

### Changed
* Refactor of passing configuration to initialization.
* `PlainDictationRecognizer.decode_utterance` can take `chunk_size` parameter.
* Smaller binaries: MacOS 11MB -> 7.6MB, Linux 21MB -> 18MB.

### Fixed
* Confidence measurement in the presence of multiple, redundant rules.
* Python3 int division bug for cloud dictation.

## Earlier versions

See [GitHub releases notes](https://github.com/daanzu/kaldi-active-grammar/releases).


================================================
FILE: CMakeLists.txt
================================================
cmake_minimum_required(VERSION 3.13.0)
project(kaldi_binaries)

include(ExternalProject)
include(ProcessorCount)

ProcessorCount(NCPU)
if(NOT NCPU EQUAL 0)
  set(MAKE_FLAGS -j${NCPU})
endif()

set(DST ${PROJECT_SOURCE_DIR}/kaldi_active_grammar/exec)
if ("${CMAKE_HOST_SYSTEM_NAME}" STREQUAL "Darwin")
  set(DST ${DST}/macos/)
elseif("${CMAKE_HOST_SYSTEM_NAME}" STREQUAL "Linux")
  set(DST ${DST}/linux/)
else()
  set(DST ${DST}/windows/)
endif()

set(BINARIES
  )
set(LIBRARIES
  src/lib/libkaldi-dragonfly${CMAKE_SHARED_LIBRARY_SUFFIX}
  )

if("${CMAKE_HOST_SYSTEM_NAME}" STREQUAL "Windows")
  message(FATAL_ERROR "CMake build not supported on Windows")
  # FIXME: copy files?
  # https://cmake.org/cmake/help/latest/command/foreach.html
  # https://stackoverflow.com/questions/34799916/copy-file-from-source-directory-to-binary-directory-using-cmake
endif()

find_program(MAKE_EXE NAMES make gmake nmake)

if(DEFINED ENV{INTEL_MKL_DIR})
  # Default: INTEL_MKL_DIR=/opt/intel/mkl/
  message("Compiling with MKL in: $ENV{INTEL_MKL_DIR}")
  set(KALDI_CONFIG_FLAGS --shared --static-math --use-cuda=no --mathlib=MKL --mkl-root=$ENV{INTEL_MKL_DIR})
  set(MATHLIB_BUILD_COMMAND true)
else()
  if(NOT DEFINED OPENBLAS_REF)
    if("${CMAKE_HOST_SYSTEM_NAME}" STREQUAL "Darwin")
      # Need newer version to build on macOS
      set(OPENBLAS_REF "v0.3.30")
    else()
      set(OPENBLAS_REF "v0.3.13")
    endif()
  endif()
  message("Compiling with OpenBLAS git ref: ${OPENBLAS_REF}")
  set(KALDI_CONFIG_FLAGS --shared --static-math --use-cuda=no --mathlib=OPENBLAS)
  set(MATHLIB_BUILD_COMMAND cd tools
    && git clone -b ${OPENBLAS_REF} --single-branch https://github.com/OpenMathLib/OpenBLAS
    && ${MAKE_EXE} ${MAKE_FLAGS} -C OpenBLAS DYNAMIC_ARCH=1 TARGET=GENERIC USE_LOCKING=1 USE_THREAD=0 all
    && ${MAKE_EXE} ${MAKE_FLAGS} -C OpenBLAS PREFIX=install install
    && cd ..)
endif()

if(DEFINED ENV{KALDI_BRANCH})
  set(KALDI_BRANCH $ENV{KALDI_BRANCH})
else()
  message(FATAL_ERROR "KALDI_BRANCH not set! Use 'origin/master'?")
  # set(KALDI_BRANCH "origin/master")
endif()

message("MAKE_EXE                  = ${MAKE_EXE}")
message("PYTHON_EXECUTABLE         = ${PYTHON_EXECUTABLE}")
message("PYTHON_INCLUDE_DIR        = ${PYTHON_INCLUDE_DIR}")
message("PYTHON_LIBRARY            = ${PYTHON_LIBRARY}")
message("PYTHON_VERSION_STRING     = ${PYTHON_VERSION_STRING}")
message("SKBUILD                   = ${SKBUILD}")
message("KALDI_BRANCH              = ${KALDI_BRANCH}")
message("CMAKE_CURRENT_SOURCE_DIR  = ${CMAKE_CURRENT_SOURCE_DIR}")
message("CMAKE_CURRENT_BINARY_DIR  = ${CMAKE_CURRENT_BINARY_DIR}")

# CXXFLAGS are set and exported in kaldi-configure-wrapper.sh

if(NOT "${CMAKE_HOST_SYSTEM_NAME}" STREQUAL "Windows")
  set(STRIP_LIBS_COMMAND find src/lib tools/openfst/lib -name *${CMAKE_SHARED_LIBRARY_SUFFIX} | xargs strip)
  # set(STRIP_DST_COMMAND find ${DST} [[[other specifiers]]] | xargs strip)
  if("${CMAKE_HOST_SYSTEM_NAME}" STREQUAL "Darwin")
    list(APPEND STRIP_LIBS_COMMAND -x)
    # list(APPEND STRIP_DST_COMMAND -x)
  endif()
  # set(STRIP_LIBS_COMMAND true)
  set(STRIP_DST_COMMAND true)
  ExternalProject_Add(kaldi
    GIT_CONFIG        advice.detachedHead=false
    GIT_REPOSITORY    https://github.com/daanzu/kaldi-fork-active-grammar.git
    GIT_TAG           ${KALDI_BRANCH}
    GIT_SHALLOW       TRUE
    CONFIGURE_COMMAND sed -i.bak -e "s/status=0/exit 0/g" tools/extras/check_dependencies.sh && sed -i.bak -e "s/openfst_add_CXXFLAGS = -g -O2/openfst_add_CXXFLAGS = -g0 -O3/g" tools/Makefile && cp ${PROJECT_SOURCE_DIR}/building/kaldi-configure-wrapper.sh src/
    BUILD_IN_SOURCE   TRUE
    BUILD_COMMAND     ${MATHLIB_BUILD_COMMAND} && cd tools && ${MAKE_EXE} && cd openfst && autoreconf && cd ../../src && bash ./kaldi-configure-wrapper.sh ./configure ${KALDI_CONFIG_FLAGS} && ${MAKE_EXE} ${MAKE_FLAGS} depend && ${MAKE_EXE} ${MAKE_FLAGS} dragonfly
    LIST_SEPARATOR    " "
    INSTALL_COMMAND   ${STRIP_LIBS_COMMAND} && mkdir -p ${DST} && cp ${BINARIES} ${LIBRARIES} ${DST} && ${STRIP_DST_COMMAND}
    )
endif()

install(CODE "MESSAGE(\"Installed kaldi engine binaries.\")")


================================================
FILE: Justfile
================================================

set ignore-comments
set positional-arguments

docker_repo := 'daanzu/kaldi-fork-active-grammar-manylinux'
piper_voice := 'en_US-ryan-low'
kaldi_model_url := 'https://github.com/daanzu/kaldi-active-grammar/releases/download/v3.0.0/kaldi_model_daanzu_20211030-smalllm.zip'

_default:
	just --list
	just --summary

build-linux python='python3':
	mkdir -p _skbuild
	rm -rf kaldi_active_grammar/exec
	rm -rf _skbuild/*/cmake-build/ _skbuild/*/cmake-install/ _skbuild/*/setuptools/
	# {{python}} -m pip install -r requirements-build.txt
	# MKL with INTEL_MKL_DIR=/opt/intel/mkl/
	{{python}} setup.py bdist_wheel

build-dockcross *args='':
	building/dockcross-manylinux2010-x64 bash building/build-wheel-dockcross.sh manylinux2010_x86_64 {{args}}

setup-dockcross:
	docker run --rm dockcross/manylinux2010-x64:20210127-72b83fc > building/dockcross-manylinux2010-x64 && chmod +x building/dockcross-manylinux2010-x64
	@# [ ! -e building/dockcross-manylinux2010-x64 ] && docker run --rm dockcross/manylinux2010-x64 > building/dockcross-manylinux2010-x64 && chmod +x building/dockcross-manylinux2010-x64 || true

pip-install-develop:
	KALDIAG_BUILD_SKIP_NATIVE=1 pip3 install --user -e .

# Setup an editable development environment on linux
setup-linux-develop kaldi_root_dir:
	# Compile kaldi_root_dir with: env CXXFLAGS=-O2 ./configure --mkl-root=/home/daanzu/intel/mkl/ --shared --static-math
	mkdir -p kaldi_active_grammar/exec/linux/
	ln -sr {{kaldi_root_dir}}/tools/openfst/bin/fstarcsort kaldi_active_grammar/exec/linux/
	ln -sr {{kaldi_root_dir}}/tools/openfst/bin/fstcompile kaldi_active_grammar/exec/linux/
	ln -sr {{kaldi_root_dir}}/tools/openfst/bin/fstinfo kaldi_active_grammar/exec/linux/
	ln -sr {{kaldi_root_dir}}/src/fstbin/fstaddselfloops kaldi_active_grammar/exec/linux/
	ln -sr {{kaldi_root_dir}}/src/dragonfly/libkaldi-dragonfly.so kaldi_active_grammar/exec/linux/
	ln -sr {{kaldi_root_dir}}/src/dragonflybin/compile-graph-agf kaldi_active_grammar/exec/linux/

watch-windows-develop config='Release':
	bash -c "watchexec -v --no-ignore -w /mnt/c/Work/Speech/kaldi/kaldi-windows/kaldiwin_vs2019_MKL/x64/ cp /mnt/c/Work/Speech/kaldi/kaldi-windows/kaldiwin_vs2019_MKL/x64/{{config}}/kaldi-dragonfly.dll /mnt/c/Work/Speech/kaldi/kaldi-active-grammar/kaldi_active_grammar/exec/windows/"

test-model model_dir:
	cd {{invocation_directory()}} && rm -rf kaldi_model kaldi_model.tmp && cp -rp {{model_dir}} kaldi_model

trigger-build ref='master':
	gh workflow run build.yml --ref {{ref}}

setup-tests:
	uv run --no-project --with-requirements requirements-test.txt -m piper.download_voices --debug --download-dir tests/ '{{piper_voice}}'
	cd tests && [ ! -e kaldi_model ] && curl -L -C - -o kaldi_model.zip '{{kaldi_model_url}}' && unzip -o kaldi_model.zip || true

# Common args: --lf -k
test *args='':
    uv run --no-project --with-requirements requirements-test.txt --with-requirements requirements-editable.txt -m pytest "$@"

# Test package after building wheel into wheels/ directory. Runs tests from within tests/ directory to prevent importing kaldi_active_grammar from source tree
test-package *args='':
	uv run -v --no-project --isolated --with-requirements ../requirements-test.txt --with kaldi-active-grammar --find-links wheels/ --directory tests/ -m pytest "$@"

test-package-separately *args='':
	uv run -v --no-project --isolated --with-requirements ../requirements-test.txt --with kaldi-active-grammar --find-links wheels/ --directory tests/ run_each_test_separately.py "$@"


================================================
FILE: LICENSE.txt
================================================
                    GNU AFFERO GENERAL PUBLIC LICENSE
                       Version 3, 19 November 2007

 Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.

                            Preamble

  The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.

  The licenses for most software and other practical works are designed
to take away your freedom to share and change the works.  By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.

  When we speak of free software, we are referring to freedom, not
price.  Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.

  Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.

  A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate.  Many developers of free software are heartened and
encouraged by the resulting cooperation.  However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.

  The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community.  It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server.  Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.

  An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals.  This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.

  The precise terms and conditions for copying, distribution and
modification follow.

                       TERMS AND CONDITIONS

  0. Definitions.

  "This License" refers to version 3 of the GNU Affero General Public License.

  "Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.

  "The Program" refers to any copyrightable work licensed under this
License.  Each licensee is addressed as "you".  "Licensees" and
"recipients" may be individuals or organizations.

  To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy.  The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.

  A "covered work" means either the unmodified Program or a work based
on the Program.

  To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy.  Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.

  To "convey" a work means any kind of propagation that enables other
parties to make or receive copies.  Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.

  An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License.  If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.

  1. Source Code.

  The "source code" for a work means the preferred form of the work
for making modifications to it.  "Object code" means any non-source
form of a work.

  A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.

  The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form.  A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.

  The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities.  However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work.  For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.

  The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.

  The Corresponding Source for a work in source code form is that
same work.

  2. Basic Permissions.

  All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met.  This License explicitly affirms your unlimited
permission to run the unmodified Program.  The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work.  This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.

  You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force.  You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright.  Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.

  Conveying under any other circumstances is permitted solely under
the conditions stated below.  Sublicensing is not allowed; section 10
makes it unnecessary.

  3. Protecting Users' Legal Rights From Anti-Circumvention Law.

  No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.

  When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.

  4. Conveying Verbatim Copies.

  You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.

  You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.

  5. Conveying Modified Source Versions.

  You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:

    a) The work must carry prominent notices stating that you modified
    it, and giving a relevant date.

    b) The work must carry prominent notices stating that it is
    released under this License and any conditions added under section
    7.  This requirement modifies the requirement in section 4 to
    "keep intact all notices".

    c) You must license the entire work, as a whole, under this
    License to anyone who comes into possession of a copy.  This
    License will therefore apply, along with any applicable section 7
    additional terms, to the whole of the work, and all its parts,
    regardless of how they are packaged.  This License gives no
    permission to license the work in any other way, but it does not
    invalidate such permission if you have separately received it.

    d) If the work has interactive user interfaces, each must display
    Appropriate Legal Notices; however, if the Program has interactive
    interfaces that do not display Appropriate Legal Notices, your
    work need not make them do so.

  A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit.  Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.

  6. Conveying Non-Source Forms.

  You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:

    a) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by the
    Corresponding Source fixed on a durable physical medium
    customarily used for software interchange.

    b) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by a
    written offer, valid for at least three years and valid for as
    long as you offer spare parts or customer support for that product
    model, to give anyone who possesses the object code either (1) a
    copy of the Corresponding Source for all the software in the
    product that is covered by this License, on a durable physical
    medium customarily used for software interchange, for a price no
    more than your reasonable cost of physically performing this
    conveying of source, or (2) access to copy the
    Corresponding Source from a network server at no charge.

    c) Convey individual copies of the object code with a copy of the
    written offer to provide the Corresponding Source.  This
    alternative is allowed only occasionally and noncommercially, and
    only if you received the object code with such an offer, in accord
    with subsection 6b.

    d) Convey the object code by offering access from a designated
    place (gratis or for a charge), and offer equivalent access to the
    Corresponding Source in the same way through the same place at no
    further charge.  You need not require recipients to copy the
    Corresponding Source along with the object code.  If the place to
    copy the object code is a network server, the Corresponding Source
    may be on a different server (operated by you or a third party)
    that supports equivalent copying facilities, provided you maintain
    clear directions next to the object code saying where to find the
    Corresponding Source.  Regardless of what server hosts the
    Corresponding Source, you remain obligated to ensure that it is
    available for as long as needed to satisfy these requirements.

    e) Convey the object code using peer-to-peer transmission, provided
    you inform other peers where the object code and Corresponding
    Source of the work are being offered to the general public at no
    charge under subsection 6d.

  A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.

  A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling.  In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage.  For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product.  A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.

  "Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source.  The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.

  If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information.  But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).

  The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed.  Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.

  Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.

  7. Additional Terms.

  "Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law.  If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.

  When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it.  (Additional permissions may be written to require their own
removal in certain cases when you modify the work.)  You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.

  Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:

    a) Disclaiming warranty or limiting liability differently from the
    terms of sections 15 and 16 of this License; or

    b) Requiring preservation of specified reasonable legal notices or
    author attributions in that material or in the Appropriate Legal
    Notices displayed by works containing it; or

    c) Prohibiting misrepresentation of the origin of that material, or
    requiring that modified versions of such material be marked in
    reasonable ways as different from the original version; or

    d) Limiting the use for publicity purposes of names of licensors or
    authors of the material; or

    e) Declining to grant rights under trademark law for use of some
    trade names, trademarks, or service marks; or

    f) Requiring indemnification of licensors and authors of that
    material by anyone who conveys the material (or modified versions of
    it) with contractual assumptions of liability to the recipient, for
    any liability that these contractual assumptions directly impose on
    those licensors and authors.

  All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10.  If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term.  If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.

  If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.

  Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.

  8. Termination.

  You may not propagate or modify a covered work except as expressly
provided under this License.  Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).

  However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.

  Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.

  Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License.  If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.

  9. Acceptance Not Required for Having Copies.

  You are not required to accept this License in order to receive or
run a copy of the Program.  Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance.  However,
nothing other than this License grants you permission to propagate or
modify any covered work.  These actions infringe copyright if you do
not accept this License.  Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.

  10. Automatic Licensing of Downstream Recipients.

  Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License.  You are not responsible
for enforcing compliance by third parties with this License.

  An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations.  If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.

  You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License.  For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.

  11. Patents.

  A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based.  The
work thus licensed is called the contributor's "contributor version".

  A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version.  For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.

  Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.

  In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement).  To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.

  If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients.  "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.

  If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.

  A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License.  You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.

  Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.

  12. No Surrender of Others' Freedom.

  If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License.  If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all.  For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.

  13. Remote Network Interaction; Use with the GNU General Public License.

  Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software.  This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.

  Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work.  The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.

  14. Revised Versions of this License.

  The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time.  Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.

  Each version is given a distinguishing version number.  If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation.  If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.

  If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.

  Later license versions may give you additional or different
permissions.  However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.

  15. Disclaimer of Warranty.

  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.

  16. Limitation of Liability.

  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.

  17. Interpretation of Sections 15 and 16.

  If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.

                     END OF TERMS AND CONDITIONS

            How to Apply These Terms to Your New Programs

  If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.

  To do so, attach the following notices to the program.  It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.

    <one line to give the program's name and a brief idea of what it does.>
    Copyright (C) <year>  <name of author>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <https://www.gnu.org/licenses/>.

Also add information on how to contact you by electronic and paper mail.

  If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source.  For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code.  There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.

  You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.


================================================
FILE: README.md
================================================
# Kaldi Active Grammar

> **Python Kaldi speech recognition with grammars that can be set active/inactive dynamically at decode-time**

> Python package developed to enable context-based command & control of computer applications, as in the [Dragonfly](https://github.com/dictation-toolbox/dragonfly) speech recognition framework, using the [Kaldi](https://github.com/kaldi-asr/kaldi) automatic speech recognition engine.

[![PyPI - Version](https://img.shields.io/pypi/v/kaldi-active-grammar.svg)](https://pypi.python.org/pypi/kaldi-active-grammar/)
[![PyPI - Wheel](https://img.shields.io/pypi/wheel/kaldi-active-grammar.svg)](https://pypi.python.org/pypi/kaldi-active-grammar/)
[![PyPI - Python Version](https://img.shields.io/pypi/pyversions/kaldi-active-grammar.svg)](https://pypi.python.org/pypi/kaldi-active-grammar/)
[![PyPI - Downloads](https://img.shields.io/pypi/dm/kaldi-active-grammar.svg?logo=python)](https://pypi.python.org/pypi/kaldi-active-grammar/)
[![GitHub - Downloads](https://img.shields.io/github/downloads/daanzu/kaldi-active-grammar/total?logo=github)](https://github.com/daanzu/kaldi-active-grammar/releases)
<!-- [![GitHub - Downloads](https://img.shields.io/github/downloads/daanzu/kaldi-active-grammar/latest/total?logo=github)](https://github.com/daanzu/kaldi-active-grammar/releases/latest) -->

![Maintenance](https://img.shields.io/maintenance/yes/2026)
![PyPI - Status](https://img.shields.io/pypi/status/kaldi-active-grammar)
[![Build](https://github.com/daanzu/kaldi-active-grammar/actions/workflows/build.yml/badge.svg)](https://github.com/daanzu/kaldi-active-grammar/actions/workflows/build.yml)
[![PyPI - License](https://img.shields.io/pypi/l/kaldi-active-grammar)](https://github.com/daanzu/kaldi-active-grammar?tab=AGPL-3.0-1-ov-file#readme)
[![Gitter](https://img.shields.io/gitter/room/daanzu/kaldi-active-grammar)](https://app.gitter.im/#/room/#kaldi-active-grammar_community:gitter.im)
<!-- [![Gitter](https://badges.gitter.im/kaldi-active-grammar/community.svg)](https://app.gitter.im/#/room/#kaldi-active-grammar_community:gitter.im) -->
<!-- [![Gitter](https://badges.gitter.im/kaldi-active-grammar/community.svg)](https://app.gitter.im/#/room/#dragonfly2:matrix.org) -->
<!-- [![Batteries-Included](https://img.shields.io/badge/batteries-included-green.svg)](https://github.com/daanzu/kaldi-active-grammar/releases) -->
<!-- ![GitHub Sponsors](https://img.shields.io/github/sponsors/daanzu) -->

[![Donate](https://img.shields.io/badge/donate-GitHub-EA4AAA.svg?logo=githubsponsors)](https://github.com/sponsors/daanzu)
[![Donate](https://img.shields.io/badge/donate-PayPal-002991.svg?logo=paypal)](https://paypal.me/daanzu)
[![Donate](https://img.shields.io/badge/donate-GitHub-EA4AAA.svg?logo=githubsponsors)](https://github.com/sponsors/daanzu)

Normally, Kaldi decoding graphs are **monolithic**, require **expensive up-front off-line** compilation, and are **static during decoding**. Kaldi's new grammar framework allows **multiple independent** grammars with nonterminals, to be compiled separately and **stitched together dynamically** at decode-time, but all the grammars are **always active** and capable of being recognized.

This project extends that to allow each grammar/rule to be **independently marked** as active/inactive **dynamically** on a **per-utterance** basis (set at the beginning of each utterance). Dragonfly is then capable of activating **only the appropriate grammars for the current environment**, resulting in increased accuracy due to fewer possible recognitions. Furthermore, the dictation grammar can be **shared** between all the command grammars, which can be **compiled quickly** without needing to include large-vocabulary dictation directly.

See the [Changelog](CHANGELOG.md) for the latest updates.

### Features

* **Binaries:** The Python package **includes all necessary binaries** for decoding on **Windows/Linux/MacOS**. Available on [PyPI](https://pypi.org/project/kaldi-active-grammar/#files).
    * Binaries are generated from my [fork of Kaldi](https://github.com/daanzu/kaldi-fork-active-grammar), which is only intended to be used by kaldi-active-grammar directly, and not as a stand-alone library.
* **Pre-trained model:** A compatible **general English Kaldi nnet3 chain model** is trained on **~3000** hours of open audio. Available under [project releases](https://github.com/daanzu/kaldi-active-grammar/releases).
    * [**Model info and comparison**](docs/models.md)
    * Improved models are under development.
* **Plain dictation:** Do you just want to recognize plain dictation? Seems kind of boring, but okay! There is an [**interface for plain dictation** (see below)](#plain-dictation-interface), using either your specified `HCLG.fst` file, or KaldiAG's included pre-trained dictation model.
* **Dragonfly/Caster:** A compatible [**backend for Dragonfly**](https://github.com/daanzu/dragonfly/tree/kaldi/dragonfly/engines/backend_kaldi) is under development in the `kaldi` branch of my fork, and has been merged as of Dragonfly **v0.15.0**.
    * See its [documentation](https://dragonfly2.readthedocs.io/en/latest/kaldi_engine.html), try out a [demo](https://github.com/dictation-toolbox/dragonfly/blob/master/dragonfly/examples/kaldi_demo.py), or use the [loader](https://github.com/dictation-toolbox/dragonfly/blob/master/dragonfly/examples/kaldi_module_loader_plus.py) to run all normal dragonfly scripts.
    * You can try it out easily on Windows using a **simple no-install package**: see [Getting Started](#getting-started) below.
    * [Caster](https://github.com/dictation-toolbox/Caster) is supported as of KaldiAG **v0.6.0** and Dragonfly **v0.16.1**.
* **Bootstrapped** since v0.2: development of KaldiAG is done entirely using KaldiAG.

### Demo Video

<div align="center">

[![Demo Video](docs/demo_video.png)](https://youtu.be/Qk1mGbIJx3s)

</div>

### Donations are appreciated to encourage development.

[![Donate](https://img.shields.io/badge/donate-GitHub-EA4AAA.svg?logo=githubsponsors)](https://github.com/sponsors/daanzu)
[![Donate](https://img.shields.io/badge/donate-PayPal-002991.svg?logo=paypal)](https://paypal.me/daanzu)
[![Donate](https://img.shields.io/badge/donate-GitHub-EA4AAA.svg?logo=githubsponsors)](https://github.com/sponsors/daanzu)

### Related Repositories

* [daanzu/kaldi-grammar-simple](https://github.com/daanzu/kaldi-grammar-simple)
* [daanzu/speech-training-recorder](https://github.com/daanzu/speech-training-recorder)
* [daanzu/dragonfly_daanzu_tools](https://github.com/daanzu/dragonfly_daanzu_tools)
* [kmdouglass/caster-kaldi](https://github.com/kmdouglass/homelab/tree/master/speech-recognition/toolchains/caster-kaldi): Docker image to run KaldiAG + Dragonfly + Caster inside a container on Linux, using the host's microphone.

## Getting Started

Want to get started **quickly & easily on Windows**?
Available under [project releases](https://github.com/daanzu/kaldi-active-grammar/releases):

* **`kaldi-dragonfly-winpython`**: A self-contained, portable, batteries-included (python & libraries & model) distribution of kaldi-active-grammar + dragonfly2. Just unzip and run!
* **`kaldi-dragonfly-winpython-dev`**: [*more recent development version*] A self-contained, portable, batteries-included (python & libraries & model) distribution of kaldi-active-grammar + dragonfly2. Just unzip and run!
* **`kaldi-caster-winpython-dev`**: [*more recent development version*] A self-contained, portable, batteries-included (python & libraries & model) distribution of kaldi-active-grammar + dragonfly2 + caster. Just unzip and run!

Otherwise...

### Setup

**Requirements**:
* Python 3.6+; *64-bit required!*
* OS: Windows/Linux/MacOS all supported
* Only supports Kaldi left-biphone models, specifically *nnet3 chain* models, with specific modifications
* ~1GB+ disk space for model plus temporary storage and cache, depending on your grammar complexity
* ~1GB+ RAM for model and grammars, depending on your model and grammar complexity

**Installation**:
1. Download compatible generic English Kaldi nnet3 chain model from [project releases](https://github.com/daanzu/kaldi-active-grammar/releases). Unzip the model and pass the directory path to kaldi-active-grammar constructor.
    * Or use your own model. Standard Kaldi models must be converted to be usable. Conversion can be performed automatically, but this hasn't been fully implemented yet.
1. Install Python package, which includes necessary Kaldi binaries:
    * The easy way to use kaldi-active-grammar is as a backend to dragonfly, which makes it easy to define grammars and resultant actions.
        * For this, simply run `pip install 'dragonfly2[kaldi]'` to install all necessary packages. See the [dragonfly documentation for details on installation](https://dragonfly2.readthedocs.io/en/latest/kaldi_engine.html#setup), plus how to define grammars and actions.
    * Alternatively, if you only want to use it directly (via a more low level interface), you can just run `pip install kaldi-active-grammar`
1. To support automatic generation of pronunciations for unknown words (not in the lexicon), you have two choices:
    * Local generation: Install the `g2p_en` package with `pip install 'kaldi-active-grammar[g2p_en]'`
        * The necessary data files are now included in the latest speech models I released with `v3.0.0`.
    * Online/cloud generation: Install the `requests` package with `pip install 'kaldi-active-grammar[online]'` **AND** pass `allow_online_pronunciations=True` to `Compiler.add_word()` or `Model.add_word()`
    * If both are available, the former is preferentially used.

### Troubleshooting

* Errors installing
    * Make sure you're using a 64-bit Python.
    * You should install via `pip install kaldi-active-grammar` (directly or indirectly), *not* `python setup.py install`, in order to get the required binaries.
    * Update your `pip` (to at least `19.0+`) by executing `python -m pip install --upgrade pip`, to support the required python binary wheel package.
* Errors running
    * Windows: `The code execution cannot proceed because VCRUNTIME140.dll was not found.` (or similar)
        * You must install the VC2017+ redistributable from Microsoft: [download page](https://support.microsoft.com/en-us/help/2977003/the-latest-supported-visual-c-downloads), [direct link](https://aka.ms/vs/16/release/vc_redist.x64.exe). (This is usually already installed globally by other programs.)
    * Try deleting the Kaldi model `.tmp` directory, and re-running.
    * Try deleting the Kaldi model directory itself, re-downloading and/or re-extracting it, and re-running. (Note: You may want to make a copy of your `user_lexicon.txt` file before deleting, to put in the new model directory.)
* For reporting issues, try running with `import logging; logging.basicConfig(level=1)` at the top of your main/loader file to enable full debugging logging.

## Documentation

Formal documentation is somewhat lacking currently. To see example usage, examine:

* [**Plain dictation interface**](examples/plain_dictation.py): Set up recognizer for plain dictation; perform decoding on given `wav` file.
* [**Full example**](examples/full_example.py): Set up grammar compiler & decoder; set up a rule; perform decoding on live, real-time audio from microphone.
* [**Backend for Dragonfly**](https://github.com/daanzu/dragonfly/tree/kaldi/dragonfly/engines/backend_kaldi): Many advanced features and complex interactions.

The KaldiAG API is fairly low level, but basically: you define a set of grammar rules, then send in audio data, along with a bit mask of which rules are active at the beginning of each utterance, and receive back the recognized rule and text. The easy way is to go through Dragonfly, which makes it easy to define the rules, contexts, and actions.

### Building

* Recommendation: use the binary wheels distributed for all major platforms.
    * Significant work has gone into allowing you to avoid the many repo/dependency downloads, GBs of disk space, and vCPU-hours needed for building from scratch.
    * They are built in public by automated Continuous Integration run on GitHub Actions: [see manifest](.github/workflows/build.yml).
* Alternatively, to build for use locally:
    * Linux/MacOS:
        1. `python -m pip install -r requirements-build.txt`
        1. `python setup.py bdist_wheel` (see [`CMakeLists.txt`](CMakeLists.txt) for details)
    * Windows:
        * Less easily generally automated
        * You can follow the steps for Continuous Integration run on GitHub Actions: see the `build-windows` section of [the manifest](.github/workflows/build.yml).
* Note: the project (and python wheel) is built from a duorepo (2 separate repos used together):
    1. This repo, containing the external interface and higher-level logic, written in Python.
    1. [My fork of Kaldi](https://github.com/daanzu/kaldi-fork-active-grammar), containing the lower-level code, written in C++.

## Contributing

Issues, suggestions, and feature requests are welcome & encouraged. Pull requests are considered, but project structure is in flux.

Donations are appreciated to encourage development.

[![Donate](https://img.shields.io/badge/donate-GitHub-EA4AAA.svg?logo=githubsponsors)](https://github.com/sponsors/daanzu)
[![Donate](https://img.shields.io/badge/donate-PayPal-002991.svg?logo=paypal)](https://paypal.me/daanzu)
[![Donate](https://img.shields.io/badge/donate-GitHub-EA4AAA.svg?logo=githubsponsors)](https://github.com/sponsors/daanzu)

## Author

* David Zurow ([@daanzu](https://github.com/daanzu))

## License

This project is licensed under the GNU Affero General Public License v3 (AGPL-3.0-or-later). See the [LICENSE.txt file](LICENSE.txt) for details. If this license is problematic for you, please contact me.

## Acknowledgments

* Based on and including code from [Kaldi ASR](https://github.com/kaldi-asr/kaldi), under the Apache-2.0 license.
* Code from [OpenFST](http://www.openfst.org/) and [OpenFST port for Windows](https://github.com/kkm000/openfst), under the Apache-2.0 license.
* [Intel Math Kernel Library](https://software.intel.com/en-us/mkl), copyright (c) 2018 Intel Corporation, under the [Intel Simplified Software License](https://software.intel.com/en-us/license/intel-simplified-software-license), currently only used for Windows build.


================================================
FILE: building/build-wheel-dockcross.sh
================================================
#!/usr/bin/env bash

# This script builds a Python wheel for kaldi-active-grammar using dockcross,
# and is to be RUN WITHIN THE DOCKCROSS CONTAINER. It optionally installs Intel
# MKL if MKL_URL is provided, then builds the wheel and repairs it for the
# specified platform using auditwheel.
#
# Usage: ./build-wheel-dockcross.sh [--skip-native] <WHEEL_PLAT> <KALDI_BRANCH> [MKL_URL]
# - --skip-native: Skip the native build step
# - WHEEL_PLAT: The platform tag for the wheel (e.g., manylinux2014_x86_64)
# - KALDI_BRANCH: The Kaldi branch to use for building
# - MKL_URL: Optional URL to download and install Intel MKL

set -e -x

PYTHON_EXE=/opt/python/cp38-cp38/bin/python

# Parse optional arguments and filter them out
SKIP_NATIVE=false
ARGS=()
while [[ $# -gt 0 ]]; do
  case $1 in
    --skip-native)
      SKIP_NATIVE=true
      shift
      ;;
    *)
      ARGS+=("$1")
      shift
      ;;
  esac
done
# Set positional arguments from filtered array
set -- "${ARGS[@]}"

# Parse required arguments
WHEEL_PLAT=$1
KALDI_BRANCH=$2
MKL_URL=$3

if [ -z "$PYTHON_EXE" ] || [ -z "$WHEEL_PLAT" ] || [ -z "$KALDI_BRANCH" ]; then
    echo "ERROR: variable not set!"
    exit 1
fi

if [ -n "$MKL_URL" ]; then
    pushd _skbuild
    wget --no-verbose --no-clobber $MKL_URL
    mkdir -p /tmp/mkl
    MKL_FILE=$(basename $MKL_URL)
    tar zxf $MKL_FILE -C /tmp/mkl --strip-components=1
    sed -i.bak -e 's/ACCEPT_EULA=decline/ACCEPT_EULA=accept/g' -e 's/ARCH_SELECTED=ALL/ARCH_SELECTED=INTEL64/g' /tmp/mkl/silent.cfg
    sudo /tmp/mkl/install.sh --silent /tmp/mkl/silent.cfg
    rm -rf /tmp/mkl
    export INTEL_MKL_DIR="/opt/intel/mkl/"
    popd
fi

if [ "$SKIP_NATIVE" = true ]; then
    export KALDIAG_BUILD_SKIP_NATIVE=1
    # Patch the native binaries restored from cache to work with auditwheel repair below; final result should be idempotent
    patchelf --force-rpath --set-rpath "$(pwd)/kaldi_active_grammar.libs" kaldi_active_grammar/exec/linux/libkaldi-dragonfly.so
    readelf -d kaldi_active_grammar/exec/linux/libkaldi-dragonfly.so | egrep 'NEEDED|RUNPATH|RPATH'
    # ldd kaldi_active_grammar/exec/linux/libkaldi-dragonfly.so
    # LD_DEBUG=libs ldd kaldi_active_grammar/exec/linux/libkaldi-dragonfly.so
else
    # Clean in preparation for native build
    mkdir -p _skbuild
    rm -rf _skbuild/*/cmake-install/ _skbuild/*/setuptools/
    rm -rf kaldi_active_grammar/exec
fi

KALDI_BRANCH=$KALDI_BRANCH $PYTHON_EXE setup.py bdist_wheel

# ls -lR kaldi_active_grammar/exec/linux

mkdir -p wheelhouse
for whl in dist/*.whl; do
    unzip -l $whl
    auditwheel show $whl
    auditwheel repair $whl --plat $WHEEL_PLAT -w wheelhouse/
    # auditwheel -v repair $whl --plat $WHEEL_PLAT -w wheelhouse/
done


================================================
FILE: building/dockcross-manylinux2010-x64
================================================
#!/usr/bin/env bash

DEFAULT_DOCKCROSS_IMAGE=dockcross/manylinux2010-x64:latest

#------------------------------------------------------------------------------
# Helpers
#
err() {
    echo -e >&2 ERROR: $@\\n
}

die() {
    err $@
    exit 1
}

has() {
    # eg. has command update
    local kind=$1
    local name=$2

    type -t $kind:$name | grep -q function
}

#------------------------------------------------------------------------------
# Command handlers
#
command:update-image() {
    docker pull $FINAL_IMAGE
}

help:update-image() {
    echo Pull the latest $FINAL_IMAGE .
}

command:update-script() {
    if cmp -s <( docker run --rm $FINAL_IMAGE ) $0; then
        echo $0 is up to date
    else
        echo -n Updating $0 '... '
        docker run --rm $FINAL_IMAGE > $0 && echo ok
    fi
}

help:update-image() {
    echo Update $0 from $FINAL_IMAGE .
}

command:update() {
    command:update-image
    command:update-script
}

help:update() {
    echo Pull the latest $FINAL_IMAGE, and then update $0 from that.
}

command:help() {
    if [[ $# != 0 ]]; then
        if ! has command $1; then
            err \"$1\" is not an dockcross command
            command:help
        elif ! has help $1; then
            err No help found for \"$1\"
        else
            help:$1
        fi
    else
        cat >&2 <<ENDHELP
Usage: dockcross [options] [--] command [args]

By default, run the given *command* in an dockcross Docker container.

The *options* can be one of:

    --args|-a           Extra args to the *docker run* command
    --image|-i          Docker cross-compiler image to use
    --config|-c         Bash script to source before running this script


Additionally, there are special update commands:

    update-image
    update-script
    update

For update command help use: $0 help <command>
ENDHELP
        exit 1
    fi
}

#------------------------------------------------------------------------------
# Option processing
#
special_update_command=''
while [[ $# != 0 ]]; do
    case $1 in

        --)
            shift
            break
            ;;

        --args|-a)
            ARG_ARGS="$2"
            shift 2
            ;;

        --config|-c)
            ARG_CONFIG="$2"
            shift 2
            ;;

        --image|-i)
            ARG_IMAGE="$2"
            shift 2
            ;;
        update|update-image|update-script)
            special_update_command=$1
            break
            ;;
        -*)
            err Unknown option \"$1\"
            command:help
            exit
            ;;

        *)
            break
            ;;

    esac
done

# The precedence for options is:
# 1. command-line arguments
# 2. environment variables
# 3. defaults

# Source the config file if it exists
DEFAULT_DOCKCROSS_CONFIG=~/.dockcross
FINAL_CONFIG=${ARG_CONFIG-${DOCKCROSS_CONFIG-$DEFAULT_DOCKCROSS_CONFIG}}

[[ -f "$FINAL_CONFIG" ]] && source "$FINAL_CONFIG"

# Set the docker image
FINAL_IMAGE=${ARG_IMAGE-${DOCKCROSS_IMAGE-$DEFAULT_DOCKCROSS_IMAGE}}

# Handle special update command
if [ "$special_update_command" != "" ]; then
    case $special_update_command in

        update)
            command:update
            exit $?
            ;;

        update-image)
            command:update-image
            exit $?
            ;;

        update-script)
            command:update-script
            exit $?
            ;;

    esac
fi

# Set the docker run extra args (if any)
FINAL_ARGS=${ARG_ARGS-${DOCKCROSS_ARGS}}

# Bash on Ubuntu on Windows
UBUNTU_ON_WINDOWS=$([ -e /proc/version ] && grep -l Microsoft /proc/version || echo "")
# MSYS, Git Bash, etc.
MSYS=$([ -e /proc/version ] && grep -l MINGW /proc/version || echo "")

if [ -z "$UBUNTU_ON_WINDOWS" -a -z "$MSYS" ]; then
    USER_IDS=(-e BUILDER_UID="$( id -u )" -e BUILDER_GID="$( id -g )" -e BUILDER_USER="$( id -un )" -e BUILDER_GROUP="$( id -gn )")
fi

# Change the PWD when working in Docker on Windows
if [ -n "$UBUNTU_ON_WINDOWS" ]; then
    WSL_ROOT="/mnt/"
    CFG_FILE=/etc/wsl.conf
	if [ -f "$CFG_FILE" ]; then
		CFG_CONTENT=$(cat $CFG_FILE | sed -r '/[^=]+=[^=]+/!d' | sed -r 's/\s+=\s/=/g')
		eval "$CFG_CONTENT"
		if [ -n "$root" ]; then
			WSL_ROOT=$root
		fi
	fi
    HOST_PWD=`pwd -P`
    HOST_PWD=${HOST_PWD/$WSL_ROOT//}
elif [ -n "$MSYS" ]; then
    HOST_PWD=$PWD
    HOST_PWD=${HOST_PWD/\//}
    HOST_PWD=${HOST_PWD/\//:\/}
else
    HOST_PWD=$PWD
    [ -L $HOST_PWD ] && HOST_PWD=$(readlink $HOST_PWD)
fi

# Mount Additional Volumes
if [ -z "$SSH_DIR" ]; then
    SSH_DIR="$HOME/.ssh"
fi

HOST_VOLUMES=
if [ -e "$SSH_DIR" -a -z "$MSYS" ]; then
    HOST_VOLUMES+="-v $SSH_DIR:/home/$(id -un)/.ssh"
fi

#------------------------------------------------------------------------------
# Now, finally, run the command in a container
#
TTY_ARGS=
tty -s && [ -z "$MSYS" ] && TTY_ARGS=-ti
CONTAINER_NAME=dockcross_$RANDOM
docker run $TTY_ARGS --name $CONTAINER_NAME \
    -v "$HOST_PWD":/work \
    $HOST_VOLUMES \
    "${USER_IDS[@]}" \
    $FINAL_ARGS \
    $FINAL_IMAGE "$@"
run_exit_code=$?

# Attempt to delete container
rm_output=$(docker rm -f $CONTAINER_NAME 2>&1)
rm_exit_code=$?
if [[ $rm_exit_code != 0 ]]; then
  if [[ "$CIRCLECI" == "true" ]] && [[ $rm_output == *"Driver btrfs failed to remove"* ]]; then
    : # Ignore error because of https://circleci.com/docs/docker-btrfs-error/
  else
    echo "$rm_output"
    exit $rm_exit_code
  fi
fi

exit $run_exit_code

################################################################################
#
# This image is not intended to be run manually.
#
# To create a dockcross helper script for the
# dockcross/manylinux2010-x64:latest image, run:
#
# docker run --rm dockcross/manylinux2010-x64:latest > dockcross-manylinux2010-x64-latest
# chmod +x dockcross-manylinux2010-x64-latest
#
# You may then wish to move the dockcross script to your PATH.
#
################################################################################


================================================
FILE: building/kaldi-configure-wrapper.sh
================================================
#!/usr/bin/env bash

# We use this wrapper script to set CXXFLAGS in the environment before calling
# kaldi configure, to avoid issues with setting environment variables in
# commands called from cmake.

set -e -x

export CXXFLAGS="-O3 -g0 -ftree-vectorize"
# -g0: Request debugging information and also use level to specify how much information. The default level is 2.
#      Level 0 produces no debug information at all. Thus, -g0 negates -g.

# Execute all arguments
exec "$@"


================================================
FILE: docs/models.md
================================================
# Speech Recognition Models

[![Donate](https://img.shields.io/badge/donate-GitHub-pink.svg)](https://github.com/sponsors/daanzu)
[![Donate](https://img.shields.io/badge/donate-Patreon-orange.svg)](https://www.patreon.com/daanzu)
[![Donate](https://img.shields.io/badge/donate-PayPal-green.svg)](https://paypal.me/daanzu)
[![Donate](https://img.shields.io/badge/preferred-GitHub-black.svg)](https://github.com/sponsors/daanzu)

## Available Models

* For **kaldi-active-grammar**
    * [kaldi_model_daanzu_20211030-biglm](https://github.com/daanzu/kaldi-active-grammar/releases/download/v3.0.0/kaldi_model_daanzu_20211030-biglm.zip) (1.05 GB)
    * [kaldi_model_daanzu_20211030-mediumlm](https://github.com/daanzu/kaldi-active-grammar/releases/download/v3.0.0/kaldi_model_daanzu_20211030-mediumlm.zip) (651 MB)
    * [kaldi_model_daanzu_20211030-smalllm](https://github.com/daanzu/kaldi-active-grammar/releases/download/v3.0.0/kaldi_model_daanzu_20211030-smalllm.zip) (400 MB)
    * [kaldi_model_daanzu_20200905_1ep-biglm](https://github.com/daanzu/kaldi-active-grammar/releases/download/v1.8.0/kaldi_model_daanzu_20200905_1ep-biglm.zip) (1.05 GB)
    * [kaldi_model_daanzu_20200905_1ep-mediumlm](https://github.com/daanzu/kaldi-active-grammar/releases/download/v1.8.0/kaldi_model_daanzu_20200905_1ep-mediumlm.zip) (651 MB)
    * [kaldi_model_daanzu_20200905_1ep-smalllm](https://github.com/daanzu/kaldi-active-grammar/releases/download/v1.8.0/kaldi_model_daanzu_20200905_1ep-smalllm.zip) (400 MB)
    * [kaldi_model_daanzu_20200328_1ep-mediumlm](https://github.com/daanzu/kaldi-active-grammar/releases/download/v1.4.0/kaldi_model_daanzu_20200328_1ep-mediumlm.zip) (322 MB)
* For **generic kaldi**, or [**vosk**](https://github.com/alphacep/vosk-api)
    * [vosk-model-en-us-daanzu-20200328](https://github.com/daanzu/kaldi-active-grammar/releases/download/v1.4.0/vosk-model-en-us-daanzu-20200328.zip)
    * [vosk-model-en-us-daanzu-20200328-lgraph](https://github.com/daanzu/kaldi-active-grammar/releases/download/v1.4.0/vosk-model-en-us-daanzu-20200328-lgraph.zip)
* If you have trouble downloading, try using `wget --continue`

## Basic info for KaldiAG models

* **Latency**: I have yet to do formal latency testing, but for command grammars, the latency between the end of the utterance (as determined by the Voice Activity Detector) and receiving the final recognition results is in the range of 10-20ms.

## General Comparison

* Metric: [Word Error Rate (WER)](https://en.wikipedia.org/wiki/Word_error_rate)
* Data sets:
    * [LibriSpeech](http://www.openslr.org/12) Test Clean
    * [Mozilla Common Voice](https://voice.mozilla.org/en/datasets) English Test
    * [TED-LIUM Release 3](https://www.openslr.org/51/) Legacy Test
    * TestSet1: my test set combining multiple sources
    * Speech Comm: test set from [Google's Speech Commands Dataset](http://download.tensorflow.org/data/speech_commands_v0.02.tar.gz), consisting of short single-word commands

**Note**: The tests on commands are not necessarily fair, because they were performed using a full dictation grammar, rather than a reduced command-specific grammar. This is a worst case scenario for accuracy; in practice, speaking commands would perform much more accurately.

|                       Engine                       | LS Test Clean | CV4 Test  | Ted3 Test | TestSet1  | Speech Comm |
|:--------------------------------------------------:|:-------------:|:---------:|:---------:|:---------:|:-----------:|
|        KaldiAG dgesr2-f-1ep LibriSpeech LM         |     4.77      | **30.91** | **12.98** | **10.16** |  **11.67**  |
|        vosk-model-en-us-aspire-0.2 [carpa]         |     17.90     |   69.76   |           |           |    55.90    |
|             vosk-model-small-en-us-0.3             |     19.30     |           |           |           |    45.57    |
|                Zamia LibriSpeech LM                |   **4.56**    |   34.28   |           |   10.34   |    30.16    |
|             Amazon Transcribe **\*\***             |     8.21%     |           |           |           |             |
|         CMU PocketSphinx (0.1.15) **\*\***         |    31.82%     |           |           |           |             |
|           Google Speech-to-Text **\*\***           |    12.23%     |           |           |           |             |
|        Mozilla DeepSpeech (0.6.1) **\*\***         |     7.55%     |           |           |           |             |
|        Picovoice Cheetah (v1.2.0) **\*\***         |    10.49%     |           |           |           |             |
| Picovoice Cheetah LibriSpeech LM (v1.2.0) **\*\*** |     8.25%     |           |           |           |             |
|        Picovoice Leopard (v1.0.0) **\*\***         |     8.34%     |           |           |           |             |
| Picovoice Leopard LibriSpeech LM (v1.0.0) **\*\*** |     6.58%     |           |           |           |             |

**\*\***: not tested by me; from [Picovoice speech-to-text-benchmark](https://github.com/Picovoice/speech-to-text-benchmark#results)

## Fine tuning for individual speakers

Fine tuning a generic model for an individual speaker can greatly increase accuracy, at the small cost of recording some training data from the speaker themself. This training data can be recorded specifically for training purposes, or it can be retained from normal use while using another model (or even another engine).

### David

* Very difficult speech.

|                                 Model                                 | David Commands (test set) | David Dictation (test set) |
|:---------------------------------------------------------------------:|:-------------------------:|:--------------------------:|
|                      KaldiAG dgesr-f-1ep generic                      |           84.94           |           70.59            |
| KaldiAG dgesr-f-1ep fine tuned on ~34hr of mixed commands + dictation |           7.11            |           14.46            |
|   Custom model trained only on ~34hr of mixed commands + dictation    |           10.04           |           10.29            |

### Shervin

* Accented speech.
* Shervin Commands: ~1 hour, ~4000 utterances.
* Shervin Dictation: ~20 minutes, ~250 utterances.

|                              Model                              | Shervin Commands | Shervin Dictation |
|:---------------------------------------------------------------:|:----------------:|:-----------------:|
|                  KaldiAG dgesr2-f-1ep generic                   |      46.98       |       9.21        |
| KaldiAG dgesr2-f-1ep fine tuned on Shervin Commands + Dictation |       9.76       |       2.40        |







================================================
FILE: examples/audio.py
================================================
#
# This file is part of kaldi-active-grammar.
# (c) Copyright 2019 by David Zurow
# Licensed under the AGPL-3.0; see LICENSE.txt file.
#

from __future__ import division, print_function
import collections, itertools, logging, time, threading, wave

from six import binary_type, print_
from six.moves import queue
import sounddevice
import webrtcvad

_log = logging.getLogger("audio")


class MicAudio(object):
    """Streams raw audio from microphone. Data is received in a separate thread, and stored in a buffer, to be read from."""

    FORMAT = 'int16'
    SAMPLE_WIDTH = 2
    SAMPLE_RATE = 16000
    CHANNELS = 1
    BLOCKS_PER_SECOND = 100
    BLOCK_SIZE_SAMPLES = int(SAMPLE_RATE / float(BLOCKS_PER_SECOND))  # Block size in number of samples
    BLOCK_DURATION_MS = int(1000 * BLOCK_SIZE_SAMPLES // SAMPLE_RATE)  # Block duration in milliseconds

    def __init__(self, callback=None, buffer_s=0, flush_queue=True, start=True, input_device=None, self_threaded=None, reconnect_callback=None):
        self.callback = callback if callback is not None else lambda in_data: self.buffer_queue.put(in_data, block=False)
        self.flush_queue = bool(flush_queue)
        self.input_device = input_device
        self.self_threaded = bool(self_threaded)
        if reconnect_callback is not None and not callable(reconnect_callback):
            _log.error("Invalid reconnect_callback not callable: %r", reconnect_callback)
            reconnect_callback = None
        self.reconnect_callback = reconnect_callback

        self.buffer_queue = queue.Queue(maxsize=(buffer_s * 1000 // self.BLOCK_DURATION_MS))
        self.stream = None
        self.thread = None
        self.thread_cancelled = False
        self.device_info = None
        self._connect(start=start)

    def _connect(self, start=None):
        callback = self.callback
        def proxy_callback(in_data, frame_count, time_info, status):
            callback(bytes(in_data))  # Must copy data from temporary C buffer!

        self.stream = sounddevice.RawInputStream(
            samplerate=self.SAMPLE_RATE,
            channels=self.CHANNELS,
            dtype=self.FORMAT,
            blocksize=self.BLOCK_SIZE_SAMPLES,
            # latency=80,
            device=self.input_device,
            callback=proxy_callback if not self.self_threaded else None,
        )

        if self.self_threaded:
            self.thread_cancelled = False
            self.thread = threading.Thread(target=self._reader_thread, args=(callback,))
            self.thread.daemon = True
            self.thread.start()

        if start:
            self.start()

        device_info = sounddevice.query_devices(self.stream.device)
        hostapi_info = sounddevice.query_hostapis(device_info['hostapi'])
        _log.info("streaming audio from '%s' using %s: %i sample_rate, %i block_duration_ms, %i latency_ms",
            device_info['name'], hostapi_info['name'], self.stream.samplerate, self.BLOCK_DURATION_MS, int(self.stream.latency*1000))
        self.device_info = device_info

    def _reader_thread(self, callback):
        while not self.thread_cancelled and self.stream and not self.stream.closed:
            if self.stream.active and self.stream.read_available >= self.stream.blocksize:
                in_data, overflowed = self.stream.read(self.stream.blocksize)
                # print('_reader_thread', read_available, len(in_data), overflowed, self.stream.blocksize)
                if overflowed:
                    _log.warning("audio stream overflow")
                callback(bytes(in_data))  # Must copy data from temporary C buffer!
            else:
                time.sleep(0.001)

    def destroy(self):
        self.stream.close()

    def reconnect(self):
        # FIXME: flapping
        old_device_info = self.device_info
        self.thread_cancelled = True
        if self.thread:
            self.thread.join()
            self.thread = None
        self.stream.close()
        self._connect(start=True)
        if self.reconnect_callback is not None:
            self.reconnect_callback(self)
        if self.device_info != old_device_info:
            raise Exception("Audio reconnect could not reconnect to the same device")

    def start(self):
        self.stream.start()

    def stop(self):
        self.stream.stop()

    def read(self, nowait=False):
        """Return a block of audio data. If nowait==False, waits for a block if necessary; else, returns False immediately if no block is available."""
        if self.stream or (self.flush_queue and not self.buffer_queue.empty()):
            if nowait:
                try:
                    return self.buffer_queue.get_nowait()  # Return good block if available
                except queue.Empty as e:
                    return False  # Queue is empty for now
            else:
                return self.buffer_queue.get()  # Wait for a good block and return it
        else:
            return None  # We are done

    def read_loop(self, callback):
        """Block looping reading, repeatedly passing a block of audio data to callback."""
        for block in iter(self):
            callback(block)

    def iter(self, nowait=False):
        """Generator that yields all audio blocks from microphone."""
        while True:
            block = self.read(nowait=nowait)
            if block is None:
                break
            yield block

    def __iter__(self):
        """Generator that yields all audio blocks from microphone."""
        return self.iter()

    def get_wav_length_s(self, data):
        assert isinstance(data, binary_type)
        length_bytes = len(data)
        assert self.FORMAT == 'int16'
        length_samples = length_bytes / self.SAMPLE_WIDTH
        return (float(length_samples) / self.SAMPLE_RATE)

    def write_wav(self, filename, data):
        # _log.debug("write wav %s", filename)
        wf = wave.open(filename, 'wb')
        wf.setnchannels(self.CHANNELS)
        # wf.setsampwidth(self.pa.get_sample_size(FORMAT))
        assert self.FORMAT == 'int16'
        wf.setsampwidth(self.SAMPLE_WIDTH)
        wf.setframerate(self.SAMPLE_RATE)
        wf.writeframes(data)
        wf.close()

    @staticmethod
    def print_list():
        print_("")
        print_("LISTING ALL INPUT DEVICES SUPPORTED BY PORTAUDIO")
        print_("(any device numbers not shown are for output only)")
        print_("")
        devices = sounddevice.query_devices()
        print_(devices)

        # for i in range(0, pa.get_device_count()):
        #     info = pa.get_device_info_by_index(i)

        #     if info['maxInputChannels'] > 0:  # microphone? or just speakers
        #         print_("DEVICE #%d" % info['index'])
        #         print_("    %s" % info['name'])
        #         print_("    input channels = %d, output channels = %d, defaultSampleRate = %d" %
        #             (info['maxInputChannels'], info['maxOutputChannels'], info['defaultSampleRate']))
        #         # print_(info)
        #         try:
        #           supports16k = pa.is_format_supported(16000,  # sample rate
        #               input_device = info['index'],
        #               input_channels = info['maxInputChannels'],
        #               input_format = pyaudio.paInt16)
        #         except ValueError:
        #           print_("    NOTE: 16k sampling not supported, configure pulseaudio to use this device")

        print_("")


class VADAudio(MicAudio):
    """Filter & segment audio with voice activity detection."""

    def __init__(self, aggressiveness=3, **kwargs):
        super(VADAudio, self).__init__(**kwargs)
        self.vad = webrtcvad.Vad(aggressiveness)

    def vad_collector(self, start_window_ms=150, start_padding_ms=100,
        end_window_ms=150, end_padding_ms=None, complex_end_window_ms=None,
        ratio=0.8, blocks=None, nowait=False,
        ):
        """Generator/coroutine that yields series of consecutive audio blocks comprising each phrase, separated by yielding a single None.
            Determines voice activity by ratio of blocks in window_ms. Uses a buffer to include window_ms prior to being triggered.
            Example: (block, ..., block, None, block, ..., block, None, ...)
                      |----phrase-----|        |----phrase-----|
        """
        assert end_padding_ms == None, "end_padding_ms not supported yet"
        num_start_window_blocks = max(1, int(start_window_ms // self.BLOCK_DURATION_MS))
        num_start_padding_blocks = max(0, int((start_padding_ms or 0) // self.BLOCK_DURATION_MS))
        num_end_window_blocks = max(1, int(end_window_ms // self.BLOCK_DURATION_MS))
        num_complex_end_window_blocks = max(1, int((complex_end_window_ms or end_window_ms) // self.BLOCK_DURATION_MS))
        num_end_padding_blocks = max(0, int((end_padding_ms or 0) // self.BLOCK_DURATION_MS))
        _log.debug("%s: vad_collector: num_start_window_blocks=%s num_end_window_blocks=%s num_complex_end_window_blocks=%s",
            self, num_start_window_blocks, num_end_window_blocks, num_complex_end_window_blocks)
        audio_reconnect_threshold_blocks = 5
        audio_reconnect_threshold_time = 50 * self.BLOCK_DURATION_MS / 1000

        ring_buffer = collections.deque(maxlen=max(
            (num_start_window_blocks + num_start_padding_blocks),
            (num_end_window_blocks + num_end_padding_blocks),
            (num_complex_end_window_blocks + num_end_padding_blocks),
        ))
        ring_buffer_recent_slice = lambda num_blocks: itertools.islice(ring_buffer, max(0, (len(ring_buffer) - num_blocks)), None)

        triggered = False
        in_complex_phrase = False
        num_empty_blocks = 0
        last_good_block_time = time.time()

        if blocks is None: blocks = self.iter(nowait=nowait)
        for block in blocks:
            if block is False or block is None:
                # Bad/empty block
                num_empty_blocks += 1
                if (num_empty_blocks >= audio_reconnect_threshold_blocks) and (time.time() - last_good_block_time >= audio_reconnect_threshold_time):
                    _log.warning("%s: no good block received recently, so reconnecting audio", self)
                    self.reconnect()
                    num_empty_blocks = 0
                    last_good_block_time = time.time()
                in_complex_phrase = yield block

            else:
                # Good block
                num_empty_blocks = 0
                last_good_block_time = time.time()
                is_speech = self.vad.is_speech(block, self.SAMPLE_RATE)

                if not triggered:
                    # Between phrases
                    ring_buffer.append((block, is_speech))
                    num_voiced = len([1 for (_, speech) in ring_buffer_recent_slice(num_start_window_blocks) if speech])
                    if num_voiced >= (num_start_window_blocks * ratio):
                        # Start of phrase
                        triggered = True
                        for block, _ in ring_buffer_recent_slice(num_start_padding_blocks + num_start_window_blocks):
                            # print('|' if is_speech else '.', end='')
                            # print('|' if in_complex_phrase else '.', end='')
                            in_complex_phrase = yield block
                        # print('#', end='')
                        ring_buffer.clear()

                else:
                    # Ongoing phrase
                    in_complex_phrase = yield block
                    # print('|' if is_speech else '.', end='')
                    # print('|' if in_complex_phrase else '.', end='')
                    ring_buffer.append((block, is_speech))
                    num_unvoiced = len([1 for (_, speech) in ring_buffer_recent_slice(num_end_window_blocks) if not speech])
                    num_complex_unvoiced = len([1 for (_, speech) in ring_buffer_recent_slice(num_complex_end_window_blocks) if not speech])
                    if (not in_complex_phrase and num_unvoiced >= (num_end_window_blocks * ratio)) or \
                        (in_complex_phrase and num_complex_unvoiced >= (num_complex_end_window_blocks * ratio)):
                        # End of phrase
                        triggered = False
                        in_complex_phrase = yield None
                        # print('*')
                        ring_buffer.clear()

    def debug_print_simple(self):
        print("block_duration_ms=%s" % self.BLOCK_DURATION_MS)
        for block in self.iter(nowait=False):
            is_speech = self.vad.is_speech(block, self.SAMPLE_RATE)
            print('|' if is_speech else '.', end='')

    def debug_loop(self, *args, **kwargs):
        audio_iter = self.vad_collector(*args, **kwargs)
        next(audio_iter)
        while True:
            block = audio_iter.send(False)


================================================
FILE: examples/full_example.py
================================================
import logging, time
import kaldi_active_grammar

logging.basicConfig(level=20)
model_dir = None  # Default
tmp_dir = None  # Default

##### Set up grammar compiler & decoder

compiler = kaldi_active_grammar.Compiler(model_dir=model_dir, tmp_dir=tmp_dir)
# compiler.fst_cache.invalidate()
decoder = compiler.init_decoder()

##### Set up a rule

rule = kaldi_active_grammar.KaldiRule(compiler, 'TestRule')
fst = rule.fst

# Construct grammar in a FST
previous_state = fst.add_state(initial=True)
for word in "i will order the".split():
    state = fst.add_state()
    fst.add_arc(previous_state, state, word)
    if word == 'the':
        # 'the' is optional, so we also allow an epsilon (silent) arc
        fst.add_arc(previous_state, state, None)
    previous_state = state
final_state = fst.add_state(final=True)
for word in ['egg', 'bacon', 'sausage']: fst.add_arc(previous_state, final_state, word)
fst.add_arc(previous_state, final_state, 'spam', weight=8)  # 'spam' is much more likely
fst.add_arc(final_state, previous_state, None)  # Loop back, with an epsilon (silent) arc

rule.compile()
rule.load()

##### You could add many more rules...

##### Perform decoding on live, real-time audio from microphone

from audio import VADAudio
audio = VADAudio()
audio_iterator = audio.vad_collector(nowait=True)
print("Listening...")

in_phrase = False
for block in audio_iterator:

    if block is False:
        # No audio block available
        time.sleep(0.001)

    elif block is not None:
        if not in_phrase:
            # Start of phrase
            kaldi_rules_activity = [True]  # A bool for each rule
            in_phrase = True
        else:
            # Ongoing phrase
            kaldi_rules_activity = None  # Irrelevant

        decoder.decode(block, False, kaldi_rules_activity)
        output, info = decoder.get_output()
        print("Partial phrase: %r" % (output,))
        recognized_rule, words, words_are_dictation_mask, in_dictation = compiler.parse_partial_output(output)

    else:
        # End of phrase
        decoder.decode(b'', True)
        output, info = decoder.get_output()
        expected_error_rate = info.get('expected_error_rate', float('nan'))
        confidence = info.get('confidence', float('nan'))

        recognized_rule, words, words_are_dictation_mask = compiler.parse_output(output)
        is_acceptable_recognition = bool(recognized_rule)
        parsed_output = ' '.join(words)
        print("End of phrase: eer=%.2f conf=%.2f%s, rule %s, %r" %
            (expected_error_rate, confidence, (" [BAD]" if not is_acceptable_recognition else ""), recognized_rule, parsed_output))

        in_phrase = False


================================================
FILE: examples/mix_dictation.py
================================================
import kaldi_active_grammar

if __name__ == '__main__':
    import util
    compiler, decoder = util.initialize()

##### Set up a rule mixing strict commands with free dictation

rule = kaldi_active_grammar.KaldiRule(compiler, 'TestRule')
fst = rule.fst

dictation_nonterm = '#nonterm:dictation'
end_nonterm = '#nonterm:end'

# Optional preface
previous_state = fst.add_state(initial=True)
next_state = fst.add_state()
fst.add_arc(previous_state, next_state, 'cap')
fst.add_arc(previous_state, next_state, None)  # Optionally skip, with an epsilon (silent) arc

# Required free dictation
previous_state = next_state
extra_state = fst.add_state()
next_state = fst.add_state()
# These two arcs together (always use together) will recognize one or more words of free dictation (but not zero):
fst.add_arc(previous_state, extra_state, dictation_nonterm)
fst.add_arc(extra_state, next_state, None, end_nonterm)

# Loop repetition, alternating between a group of alternatives and more free dictation
previous_state = next_state
next_state = fst.add_state()
for word in ['period', 'comma', 'colon']:
    fst.add_arc(previous_state, next_state, word)
extra_state = fst.add_state()
next_state = fst.add_state()
fst.add_arc(next_state, extra_state, dictation_nonterm)
fst.add_arc(extra_state, next_state, None, end_nonterm)
fst.add_arc(next_state, previous_state, None)  # Loop back, with an epsilon (silent) arc
fst.add_arc(previous_state, next_state, None)  # Optionally skip, with an epsilon (silent) arc

# Finish up
final_state = fst.add_state(final=True)
fst.add_arc(next_state, final_state, None)

rule.compile()
rule.load()

# Decode
if __name__ == '__main__':
    util.do_recognition(compiler, decoder)


================================================
FILE: examples/plain_dictation.py
================================================
import logging, sys, wave
from kaldi_active_grammar import PlainDictationRecognizer

# logging.basicConfig(level=10)
recognizer = PlainDictationRecognizer()  # Or supply non-default model_dir, tmp_dir, or fst_file
filename = sys.argv[1] if len(sys.argv) > 1 else 'test.wav'
wave_file = wave.open(filename, 'rb')
data = wave_file.readframes(wave_file.getnframes())
output_str, info = recognizer.decode_utterance(data)
print(repr(output_str), info)  # -> 'it depends on the context'


================================================
FILE: examples/requirements_audio.txt
================================================
sounddevice==0.3.*
webrtcvad-wheels==2.0.*


================================================
FILE: examples/util.py
================================================
import time
import kaldi_active_grammar
from audio import VADAudio

def initialize(model_dir=None, tmp_dir=None, config={}):
    compiler = kaldi_active_grammar.Compiler(model_dir=model_dir, tmp_dir=tmp_dir)
    decoder = compiler.init_decoder(config=config)
    return (compiler, decoder)

def do_recognition(compiler, decoder, print_partial=True, cap_dictation=True):
    audio = VADAudio()
    audio_iterator = audio.vad_collector(nowait=True)
    print("Listening...")

    in_phrase = False
    for block in audio_iterator:

        if block is False:
            # No audio block available
            time.sleep(0.001)

        elif block is not None:
            if not in_phrase:
                # Start of phrase
                kaldi_rules_activity = [True]  # A bool for each rule
                in_phrase = True
            else:
                # Ongoing phrase
                kaldi_rules_activity = None  # Irrelevant

            decoder.decode(block, False, kaldi_rules_activity)
            output, info = decoder.get_output()
            if print_partial:
                print("Partial phrase: %r" % (output,))
            recognized_rule, words, words_are_dictation_mask, in_dictation = compiler.parse_partial_output(output)

        else:
            # End of phrase
            decoder.decode(b'', True)
            output, info = decoder.get_output()
            expected_error_rate = info.get('expected_error_rate', float('nan'))
            confidence = info.get('confidence', float('nan'))

            recognized_rule, words, words_are_dictation_mask = compiler.parse_output(output)
            is_acceptable_recognition = bool(recognized_rule)
            if cap_dictation:
                words = [(word.upper() if word_in_dictation else word) for (word, word_in_dictation) in zip(words, words_are_dictation_mask)]
            parsed_output = ' '.join(words)
            print("End of phrase: eer=%.2f conf=%.2f%s, rule %s, %r" %
                (expected_error_rate, confidence, (" [BAD]" if not is_acceptable_recognition else ""), recognized_rule, parsed_output))

            in_phrase = False


================================================
FILE: kaldi_active_grammar/LICENSE.txt
================================================
                    GNU AFFERO GENERAL PUBLIC LICENSE
                       Version 3, 19 November 2007

 Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.

                            Preamble

  The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.

  The licenses for most software and other practical works are designed
to take away your freedom to share and change the works.  By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.

  When we speak of free software, we are referring to freedom, not
price.  Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.

  Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.

  A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate.  Many developers of free software are heartened and
encouraged by the resulting cooperation.  However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.

  The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community.  It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server.  Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.

  An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals.  This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.

  The precise terms and conditions for copying, distribution and
modification follow.

                       TERMS AND CONDITIONS

  0. Definitions.

  "This License" refers to version 3 of the GNU Affero General Public License.

  "Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.

  "The Program" refers to any copyrightable work licensed under this
License.  Each licensee is addressed as "you".  "Licensees" and
"recipients" may be individuals or organizations.

  To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy.  The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.

  A "covered work" means either the unmodified Program or a work based
on the Program.

  To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy.  Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.

  To "convey" a work means any kind of propagation that enables other
parties to make or receive copies.  Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.

  An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License.  If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.

  1. Source Code.

  The "source code" for a work means the preferred form of the work
for making modifications to it.  "Object code" means any non-source
form of a work.

  A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.

  The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form.  A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.

  The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities.  However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work.  For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.

  The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.

  The Corresponding Source for a work in source code form is that
same work.

  2. Basic Permissions.

  All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met.  This License explicitly affirms your unlimited
permission to run the unmodified Program.  The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work.  This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.

  You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force.  You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright.  Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.

  Conveying under any other circumstances is permitted solely under
the conditions stated below.  Sublicensing is not allowed; section 10
makes it unnecessary.

  3. Protecting Users' Legal Rights From Anti-Circumvention Law.

  No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.

  When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.

  4. Conveying Verbatim Copies.

  You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.

  You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.

  5. Conveying Modified Source Versions.

  You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:

    a) The work must carry prominent notices stating that you modified
    it, and giving a relevant date.

    b) The work must carry prominent notices stating that it is
    released under this License and any conditions added under section
    7.  This requirement modifies the requirement in section 4 to
    "keep intact all notices".

    c) You must license the entire work, as a whole, under this
    License to anyone who comes into possession of a copy.  This
    License will therefore apply, along with any applicable section 7
    additional terms, to the whole of the work, and all its parts,
    regardless of how they are packaged.  This License gives no
    permission to license the work in any other way, but it does not
    invalidate such permission if you have separately received it.

    d) If the work has interactive user interfaces, each must display
    Appropriate Legal Notices; however, if the Program has interactive
    interfaces that do not display Appropriate Legal Notices, your
    work need not make them do so.

  A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit.  Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.

  6. Conveying Non-Source Forms.

  You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:

    a) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by the
    Corresponding Source fixed on a durable physical medium
    customarily used for software interchange.

    b) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by a
    written offer, valid for at least three years and valid for as
    long as you offer spare parts or customer support for that product
    model, to give anyone who possesses the object code either (1) a
    copy of the Corresponding Source for all the software in the
    product that is covered by this License, on a durable physical
    medium customarily used for software interchange, for a price no
    more than your reasonable cost of physically performing this
    conveying of source, or (2) access to copy the
    Corresponding Source from a network server at no charge.

    c) Convey individual copies of the object code with a copy of the
    written offer to provide the Corresponding Source.  This
    alternative is allowed only occasionally and noncommercially, and
    only if you received the object code with such an offer, in accord
    with subsection 6b.

    d) Convey the object code by offering access from a designated
    place (gratis or for a charge), and offer equivalent access to the
    Corresponding Source in the same way through the same place at no
    further charge.  You need not require recipients to copy the
    Corresponding Source along with the object code.  If the place to
    copy the object code is a network server, the Corresponding Source
    may be on a different server (operated by you or a third party)
    that supports equivalent copying facilities, provided you maintain
    clear directions next to the object code saying where to find the
    Corresponding Source.  Regardless of what server hosts the
    Corresponding Source, you remain obligated to ensure that it is
    available for as long as needed to satisfy these requirements.

    e) Convey the object code using peer-to-peer transmission, provided
    you inform other peers where the object code and Corresponding
    Source of the work are being offered to the general public at no
    charge under subsection 6d.

  A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.

  A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling.  In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage.  For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product.  A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.

  "Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source.  The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.

  If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information.  But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).

  The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed.  Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.

  Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.

  7. Additional Terms.

  "Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law.  If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.

  When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it.  (Additional permissions may be written to require their own
removal in certain cases when you modify the work.)  You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.

  Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:

    a) Disclaiming warranty or limiting liability differently from the
    terms of sections 15 and 16 of this License; or

    b) Requiring preservation of specified reasonable legal notices or
    author attributions in that material or in the Appropriate Legal
    Notices displayed by works containing it; or

    c) Prohibiting misrepresentation of the origin of that material, or
    requiring that modified versions of such material be marked in
    reasonable ways as different from the original version; or

    d) Limiting the use for publicity purposes of names of licensors or
    authors of the material; or

    e) Declining to grant rights under trademark law for use of some
    trade names, trademarks, or service marks; or

    f) Requiring indemnification of licensors and authors of that
    material by anyone who conveys the material (or modified versions of
    it) with contractual assumptions of liability to the recipient, for
    any liability that these contractual assumptions directly impose on
    those licensors and authors.

  All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10.  If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term.  If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.

  If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.

  Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.

  8. Termination.

  You may not propagate or modify a covered work except as expressly
provided under this License.  Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).

  However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.

  Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.

  Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License.  If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.

  9. Acceptance Not Required for Having Copies.

  You are not required to accept this License in order to receive or
run a copy of the Program.  Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance.  However,
nothing other than this License grants you permission to propagate or
modify any covered work.  These actions infringe copyright if you do
not accept this License.  Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.

  10. Automatic Licensing of Downstream Recipients.

  Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License.  You are not responsible
for enforcing compliance by third parties with this License.

  An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations.  If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.

  You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License.  For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.

  11. Patents.

  A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based.  The
work thus licensed is called the contributor's "contributor version".

  A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version.  For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.

  Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.

  In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement).  To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.

  If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients.  "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.

  If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.

  A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License.  You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.

  Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.

  12. No Surrender of Others' Freedom.

  If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License.  If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all.  For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.

  13. Remote Network Interaction; Use with the GNU General Public License.

  Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no 
Download .txt
gitextract_2q213gax/

├── .github/
│   ├── FUNDING.yml
│   ├── RELEASING.md
│   ├── release_notes.md
│   └── workflows/
│       └── build.yml
├── .gitignore
├── AGENTS.md
├── CHANGELOG.md
├── CMakeLists.txt
├── Justfile
├── LICENSE.txt
├── README.md
├── building/
│   ├── build-wheel-dockcross.sh
│   ├── dockcross-manylinux2010-x64
│   └── kaldi-configure-wrapper.sh
├── docs/
│   └── models.md
├── examples/
│   ├── audio.py
│   ├── full_example.py
│   ├── mix_dictation.py
│   ├── plain_dictation.py
│   ├── requirements_audio.txt
│   └── util.py
├── kaldi_active_grammar/
│   ├── LICENSE.txt
│   ├── __init__.py
│   ├── __main__.py
│   ├── compiler.py
│   ├── defaults.py
│   ├── ffi.py
│   ├── kaldi/
│   │   ├── COPYING
│   │   ├── __init__.py
│   │   ├── augment_phones_txt.py
│   │   ├── augment_phones_txt_py2.py
│   │   ├── augment_words_txt.py
│   │   ├── augment_words_txt_py2.py
│   │   ├── make_lexicon_fst.py
│   │   └── make_lexicon_fst_py2.py
│   ├── model.py
│   ├── plain_dictation.py
│   ├── utils.py
│   ├── wfst.py
│   └── wrapper.py
├── pyproject.toml
├── requirements-build.txt
├── requirements-editable.txt
├── requirements-test.txt
├── setup.cfg
├── setup.py
└── tests/
    ├── conftest.py
    ├── generate_google_tts.py
    ├── generate_piper_tts.py
    ├── helpers.py
    ├── run_each_test_separately.py
    ├── test_grammar.py
    ├── test_package.py
    └── test_plain_dictation.py
Download .txt
SYMBOL INDEX (345 symbols across 25 files)

FILE: examples/audio.py
  class MicAudio (line 18) | class MicAudio(object):
    method __init__ (line 29) | def __init__(self, callback=None, buffer_s=0, flush_queue=True, start=...
    method _connect (line 46) | def _connect(self, start=None):
    method _reader_thread (line 76) | def _reader_thread(self, callback):
    method destroy (line 87) | def destroy(self):
    method reconnect (line 90) | def reconnect(self):
    method start (line 104) | def start(self):
    method stop (line 107) | def stop(self):
    method read (line 110) | def read(self, nowait=False):
    method read_loop (line 123) | def read_loop(self, callback):
    method iter (line 128) | def iter(self, nowait=False):
    method __iter__ (line 136) | def __iter__(self):
    method get_wav_length_s (line 140) | def get_wav_length_s(self, data):
    method write_wav (line 147) | def write_wav(self, filename, data):
    method print_list (line 159) | def print_list():
  class VADAudio (line 187) | class VADAudio(MicAudio):
    method __init__ (line 190) | def __init__(self, aggressiveness=3, **kwargs):
    method vad_collector (line 194) | def vad_collector(self, start_window_ms=150, start_padding_ms=100,
    method debug_print_simple (line 274) | def debug_print_simple(self):
    method debug_loop (line 280) | def debug_loop(self, *args, **kwargs):

FILE: examples/util.py
  function initialize (line 5) | def initialize(model_dir=None, tmp_dir=None, config={}):
  function do_recognition (line 10) | def do_recognition(compiler, decoder, print_partial=True, cap_dictation=...

FILE: kaldi_active_grammar/__init__.py
  class KaldiError (line 17) | class KaldiError(Exception):

FILE: kaldi_active_grammar/__main__.py
  function main (line 16) | def main():

FILE: kaldi_active_grammar/compiler.py
  class KaldiRule (line 26) | class KaldiRule(object):
    method __init__ (line 30) | def __init__(self, compiler, name, nonterm=True, has_dictation=None, i...
    method __repr__ (line 60) | def __repr__(self):
    method filepath (line 73) | def filepath(self):
    method compile (line 78) | def compile(self, lazy=False, duplicate=None):
    method finish_compile (line 116) | def finish_compile(self):
    method load (line 151) | def load(self, lazy=False):
    method _do_reloading (line 173) | def _do_reloading(self):
    method reload (line 183) | def reload(self):
    method destroy (line 205) | def destroy(self):
  class Compiler (line 234) | class Compiler(object):
    method __init__ (line 236) | def __init__(self, model_dir=None, tmp_dir=None, alternative_dictation...
    method init_decoder (line 290) | def init_decoder(self, config=None, dictation_fst_file=None):
    method alloc_rule_id (line 319) | def alloc_rule_id(self):
    method free_rule_id (line 324) | def free_rule_id(self):
    method add_word (line 333) | def add_word(self, word, phones=None, lazy_compilation=False, allow_on...
    method prepare_for_compilation (line 338) | def prepare_for_compilation(self):
    method _compile_laf_graph (line 349) | def _compile_laf_graph(self, input_text=None, input_filename=None, out...
    method _init_agf_compiler (line 367) | def _init_agf_compiler(self):
    method _compile_agf_graph (line 379) | def _compile_agf_graph(self, compile=False, nonterm=False, simplify_lg...
    method compile_plain_dictation_fst (line 476) | def compile_plain_dictation_fst(self, g_filename=None, output_filename...
    method compile_agf_dictation_fst (line 487) | def compile_agf_dictation_fst(self, g_filename=None):
    method compile_top_fst (line 506) | def compile_top_fst(self):
    method compile_top_fst_dictation_only (line 509) | def compile_top_fst_dictation_only(self):
    method _build_top_fst (line 512) | def _build_top_fst(self, nonterms, noise_words):
    method _get_dictation_fst_filepath (line 534) | def _get_dictation_fst_filepath(self):
    method compile_universal_grammar (line 560) | def compile_universal_grammar(self, words=None):
    method process_compile_and_load_queues (line 574) | def process_compile_and_load_queues(self):
    method prepare_for_recognition (line 623) | def prepare_for_recognition(self):
    method parse_output_for_rule (line 637) | def parse_output_for_rule(self, kaldi_rule, output):
    method parse_output (line 651) | def parse_output(self, output, dictation_info_func=None):
    method parse_partial_output (line 722) | def parse_partial_output(self, output):
  function remove_words_in_words (line 751) | def remove_words_in_words(words, remove_words_func):
  function remove_words_in_text (line 754) | def remove_words_in_text(text, remove_words_func):
  function remove_nonterms_in_words (line 757) | def remove_nonterms_in_words(words):
  function remove_nonterms_in_text (line 760) | def remove_nonterms_in_text(text):
  function run_subprocess (line 763) | def run_subprocess(cmd, format_kwargs, description=None, format_kwargs_u...

FILE: kaldi_active_grammar/ffi.py
  function encode (line 21) | def encode(text):
  function decode (line 24) | def decode(binary):
  class FFIObject (line 28) | class FFIObject(object):
    method __init__ (line 30) | def __init__(self):
    method init_ffi (line 34) | def init_ffi(cls):
    method _init_ffi (line 38) | def _init_ffi(cls):

FILE: kaldi_active_grammar/kaldi/augment_phones_txt.py
  function get_args (line 9) | def get_args():
  function read_phones_txt (line 27) | def read_phones_txt(filename):
  function read_nonterminals (line 57) | def read_nonterminals(filename):
  function write_phones_txt (line 73) | def write_phones_txt(orig_lines, highest_numbered_symbol, nonterminals, ...
  function main (line 88) | def main():

FILE: kaldi_active_grammar/kaldi/augment_phones_txt_py2.py
  function get_args (line 10) | def get_args():
  function read_phones_txt (line 28) | def read_phones_txt(filename):
  function read_nonterminals (line 58) | def read_nonterminals(filename):
  function write_phones_txt (line 74) | def write_phones_txt(orig_lines, highest_numbered_symbol, nonterminals, ...
  function main (line 89) | def main():

FILE: kaldi_active_grammar/kaldi/augment_words_txt.py
  function get_args (line 9) | def get_args():
  function read_words_txt (line 28) | def read_words_txt(filename):
  function read_nonterminals (line 58) | def read_nonterminals(filename):
  function write_words_txt (line 74) | def write_words_txt(orig_lines, highest_numbered_symbol, nonterminals, f...
  function main (line 88) | def main():

FILE: kaldi_active_grammar/kaldi/augment_words_txt_py2.py
  function get_args (line 10) | def get_args():
  function read_words_txt (line 29) | def read_words_txt(filename):
  function read_nonterminals (line 59) | def read_nonterminals(filename):
  function write_words_txt (line 75) | def write_words_txt(orig_lines, highest_numbered_symbol, nonterminals, f...
  function main (line 89) | def main():

FILE: kaldi_active_grammar/kaldi/make_lexicon_fst.py
  function get_args (line 21) | def get_args():
  function read_lexiconp (line 60) | def read_lexiconp(filename):
  function write_nonterminal_arcs (line 119) | def write_nonterminal_arcs(start_state, loop_state, next_state,
  function write_fst_no_silence (line 173) | def write_fst_no_silence(lexicon, nonterminals=None, left_context_phones...
  function write_fst_with_silence (line 220) | def write_fst_with_silence(lexicon, sil_prob, sil_phone, sil_disambig,
  function write_words_txt (line 308) | def write_words_txt(orig_lines, highest_numbered_symbol, nonterminals, f...
  function read_nonterminals (line 322) | def read_nonterminals(filename):
  function read_left_context_phones (line 338) | def read_left_context_phones(filename):
  function is_token (line 354) | def is_token(s):
  function main (line 363) | def main(args=None):

FILE: kaldi_active_grammar/kaldi/make_lexicon_fst_py2.py
  function get_args (line 22) | def get_args():
  function read_lexiconp (line 61) | def read_lexiconp(filename):
  function write_nonterminal_arcs (line 120) | def write_nonterminal_arcs(start_state, loop_state, next_state,
  function write_fst_no_silence (line 174) | def write_fst_no_silence(lexicon, nonterminals=None, left_context_phones...
  function write_fst_with_silence (line 221) | def write_fst_with_silence(lexicon, sil_prob, sil_phone, sil_disambig,
  function write_words_txt (line 309) | def write_words_txt(orig_lines, highest_numbered_symbol, nonterminals, f...
  function read_nonterminals (line 323) | def read_nonterminals(filename):
  function read_left_context_phones (line 339) | def read_left_context_phones(filename):
  function is_token (line 355) | def is_token(s):
  function main (line 364) | def main(args=None):

FILE: kaldi_active_grammar/model.py
  class Lexicon (line 24) | class Lexicon(object):
    method __init__ (line 26) | def __init__(self, phones):
    method phones_cmu_to_xsampa_generic (line 78) | def phones_cmu_to_xsampa_generic(cls, phones, lexicon_phones=None):
    method phones_cmu_to_xsampa (line 101) | def phones_cmu_to_xsampa(self, phones):
    method make_position_dependent (line 105) | def make_position_dependent(cls, phones):
    method make_position_independent (line 111) | def make_position_independent(cls, phones):
    method generate_pronunciations_cmu_online (line 115) | def generate_pronunciations_cmu_online(cls, word):
    method attempt_load_g2p_en (line 144) | def attempt_load_g2p_en(cls, model_dir=None):
    method generate_pronunciations_g2p_en (line 158) | def generate_pronunciations_g2p_en(cls, word):
    method generate_pronunciations (line 168) | def generate_pronunciations(cls, word, model_dir=None, allow_online_pr...
  class Model (line 181) | class Model(object):
    method __init__ (line 182) | def __init__(self, model_dir=None, tmp_dir=None, tmp_dir_needed=False):
    method load_words (line 258) | def load_words(self, words_file=None):
    method read_user_lexicon (line 266) | def read_user_lexicon(self, filename=None):
    method write_user_lexicon (line 275) | def write_user_lexicon(self, entries, filename=None):
    method add_word (line 281) | def add_word(self, word, phones=None, lazy_compilation=False, allow_on...
    method create_missing_files (line 317) | def create_missing_files(self):
    method check_user_lexicon (line 329) | def check_user_lexicon(self):
    method generate_lexicon_files (line 343) | def generate_lexicon_files(self):
    method reset_user_lexicon (line 424) | def reset_user_lexicon(self):
    method generate_words_relabeled_file (line 429) | def generate_words_relabeled_file(words_filename, relabel_filename, wo...
  function convert_generic_model_to_agf (line 448) | def convert_generic_model_to_agf(src_dir, model_dir):
  function str_space_join (line 509) | def str_space_join(iterable):
  function base_filepath (line 512) | def base_filepath(filepath):
  function verify_files_exist (line 516) | def verify_files_exist(*filenames):

FILE: kaldi_active_grammar/plain_dictation.py
  class PlainDictationRecognizer (line 16) | class PlainDictationRecognizer(object):
    method __init__ (line 18) | def __init__(self, model_dir=None, tmp_dir=None, fst_file=None, config...
    method decode_utterance (line 47) | def decode_utterance(self, samples_data, chunk_size=None):

FILE: kaldi_active_grammar/utils.py
  function show_donation_message (line 29) | def show_donation_message():
  function disable_donation_message (line 34) | def disable_donation_message():
  class ThreadLocalData (line 43) | class ThreadLocalData(threading.local):
    method __init__ (line 44) | def __init__(self):
  function debug_timer (line 49) | def debug_timer(log, desc, enabled=True, independent=False):
  function clock (line 68) | def clock():
  function clock (line 71) | def clock():
  class ExternalProcess (line 86) | class ExternalProcess(object):
    method get_dict_formatter (line 101) | def get_dict_formatter(format_kwargs):
    method get_list_formatter (line 104) | def get_list_formatter(format_kwargs):
    method get_debug_stderr_kwargs (line 108) | def get_debug_stderr_kwargs(log):
    method execute_command_safely (line 112) | def execute_command_safely(commands, log):
  function lazy_readonly_property (line 127) | def lazy_readonly_property(func):
  class lazy_settable_property (line 140) | class lazy_settable_property(object):
    method __init__ (line 147) | def __init__(self, fget):
    method __get__ (line 152) | def __get__(self, obj, cls):
  function touch_file (line 162) | def touch_file(filename):
  function clear_file (line 166) | def clear_file(filename):
  function symbol_table_lookup (line 172) | def symbol_table_lookup(filename, input):
  function load_symbol_table (line 191) | def load_symbol_table(filename):
  function find_file (line 195) | def find_file(directory, filename, required=False, default=False):
  function is_file_up_to_date (line 212) | def is_file_up_to_date(filename, *parent_filenames):
  class FSTFileCache (line 222) | class FSTFileCache(object):
    method __init__ (line 224) | def __init__(self, cache_filename, tmp_dir=None, dependencies_dict=Non...
    method _load (line 271) | def _load(self):
    method save (line 279) | def save(self):
    method update_dependencies (line 285) | def update_dependencies(self):
    method invalidate (line 293) | def invalidate(self, filename=None):
    method hash_data (line 309) | def hash_data(self, data, mix_dependencies=False):
    method add_file (line 320) | def add_file(self, filepath, data=None):
    method contains (line 329) | def contains(self, filename, data):
    method file_is_current (line 332) | def file_is_current(self, filepath, data=None):
    method fst_is_current (line 344) | def fst_is_current(self, filepath, touch=True):

FILE: kaldi_active_grammar/wfst.py
  class WFST (line 15) | class WFST(object):
    method __init__ (line 29) | def __init__(self):
    method clear (line 32) | def clear(self):
    method iter_arcs (line 42) | def iter_arcs(self):
    method is_state_final (line 45) | def is_state_final(self, state):
    method add_state (line 48) | def add_state(self, weight=None, initial=False, final=False):
    method add_arc (line 62) | def add_arc(self, src_state, dst_state, label, olabel=None, weight=None):
    method get_fst_text (line 71) | def get_fst_text(self, fst_cache, eps2disambig=False):
    method label_is_silent (line 93) | def label_is_silent(self, label):
    method scale_weights (line 96) | def scale_weights(self, factor):
    method normalize_weights (line 103) | def normalize_weights(self, stochasticity=False):
    method has_eps_path (line 112) | def has_eps_path(self, path_src_state, path_dst_state, eps_like_labels...
    method does_match (line 128) | def does_match(self, target_words, wildcard_nonterms=(), include_silen...
  class NativeWFST (line 157) | class NativeWFST(FFIObject):
    method init_class (line 189) | def init_class(cls, isymbol_table, wildcard_nonterms, osymbol_table=No...
    method __init__ (line 209) | def __init__(self):
    method _construct (line 213) | def _construct(self):
    method __del__ (line 223) | def __del__(self):
    method destruct (line 226) | def destruct(self):
    method compiled_native_obj (line 236) | def compiled_native_obj(self, value):
    method compiled_native_obj (line 240) | def compiled_native_obj(self):
    method clear (line 247) | def clear(self):
    method add_state (line 251) | def add_state(self, weight=None, initial=False, final=False):
    method add_arc (line 267) | def add_arc(self, src_state, dst_state, label, olabel=None, weight=None):
    method compute_hash (line 281) | def compute_hash(self, dependencies_seed_hash_str='0'*32):
    method has_path (line 292) | def has_path(self):
    method has_eps_path (line 297) | def has_eps_path(self, path_src_state, path_dst_state, eps_like_labels...
    method does_match (line 303) | def does_match(self, target_words, wildcard_nonterms=(), include_silen...
    method write_file (line 321) | def write_file(self, fst_filename):
    method write_file_const (line 326) | def write_file_const(self, fst_filename):
    method print (line 331) | def print(self, fst_filename=None):
    method load_file (line 337) | def load_file(cls, fst_filename):
    method compile_text (line 346) | def compile_text(cls, fst_text, isymbols_filename, osymbols_filename):
  class SymbolTable (line 357) | class SymbolTable(object):
    method __init__ (line 359) | def __init__(self, filename=None):
    method load_text_file (line 366) | def load_text_file(self, filename):
    method add_word (line 375) | def add_word(self, word, id=None):
    method __contains__ (line 386) | def __contains__(self, word):

FILE: kaldi_active_grammar/wrapper.py
  class KaldiDecoderBase (line 29) | class KaldiDecoderBase(FFIObject):
    method __init__ (line 32) | def __init__(self):
    method _reset_decode_time (line 43) | def _reset_decode_time(self):
    method _start_decode_time (line 48) | def _start_decode_time(self, num_frames):
    method _stop_decode_time (line 52) | def _stop_decode_time(self, finalize=False):
    method kaldi_frame_num_to_audio_bytes (line 64) | def kaldi_frame_num_to_audio_bytes(self, kaldi_frame_num):
    method audio_bytes_to_s (line 69) | def audio_bytes_to_s(self, audio_bytes):
  class KaldiGmmDecoder (line 76) | class KaldiGmmDecoder(KaldiDecoderBase):
    method __init__ (line 86) | def __init__(self, graph_dir=None, words_file=None, graph_file=None, m...
    method decode (line 98) | def decode(self, frames, finalize, grammars_activity=None):
    method get_output (line 112) | def get_output(self, output_max_length=4*1024):
  class KaldiOtfGmmDecoder (line 125) | class KaldiOtfGmmDecoder(KaldiDecoderBase):
    method __init__ (line 138) | def __init__(self, graph_dir=None, words_file=None, model_conf_file=No...
    method add_grammar_fst (line 155) | def add_grammar_fst(self, grammar_fst_file):
    method decode (line 163) | def decode(self, frames, finalize, grammars_activity=None):
    method get_output (line 185) | def get_output(self, output_max_length=4*1024):
  class KaldiNNet3Decoder (line 198) | class KaldiNNet3Decoder(KaldiDecoderBase):
    method __init__ (line 212) | def __init__(self, model_dir, tmp_dir, words_file=None, word_align_lex...
    method _read_ie_conf_file (line 242) | def _read_ie_conf_file(self, model_dir, old_filename, search=True):
    method saving_adaptation_state (line 284) | def saving_adaptation_state(self, value): self._saving_adaptation_stat...
    method load_lexicon (line 286) | def load_lexicon(self, words_file=None, word_align_lexicon_file=None):
    method save_adaptation_state (line 294) | def save_adaptation_state(self):
    method reset_adaptation_state (line 299) | def reset_adaptation_state(self):
    method get_output (line 304) | def get_output(self, output_max_length=4*1024):
    method get_word_align (line 325) | def get_word_align(self, output):
    method set_lm_prime_text (line 338) | def set_lm_prime_text(self, prime_text):
  class KaldiPlainNNet3Decoder (line 347) | class KaldiPlainNNet3Decoder(KaldiNNet3Decoder):
    method __init__ (line 356) | def __init__(self, fst_file=None, config=None, **kwargs):
    method destroy (line 371) | def destroy(self):
    method decode (line 378) | def decode(self, frames, finalize):
  class KaldiAgfNNet3Decoder (line 396) | class KaldiAgfNNet3Decoder(KaldiNNet3Decoder):
    method __init__ (line 411) | def __init__(self, *, top_fst=None, dictation_fst_file=None, config=No...
    method destroy (line 441) | def destroy(self):
    method add_grammar_fst (line 448) | def add_grammar_fst(self, grammar_fst):
    method reload_grammar_fst (line 461) | def reload_grammar_fst(self, grammar_fst_index, grammar_fst):
    method remove_grammar_fst (line 471) | def remove_grammar_fst(self, grammar_fst_index):
    method decode (line 478) | def decode(self, frames, finalize, grammars_activity=None):
  class KaldiAgfCompiler (line 507) | class KaldiAgfCompiler(FFIObject):
    method __init__ (line 517) | def __init__(self, config):
    method destroy (line 522) | def destroy(self):
    method compile_graph (line 529) | def compile_graph(self, config, grammar_fst=None, grammar_fst_text=Non...
  class KaldiLafNNet3Decoder (line 548) | class KaldiLafNNet3Decoder(KaldiNNet3Decoder):
    method __init__ (line 562) | def __init__(self, dictation_fst_file=None, config=None, **kwargs):
    method destroy (line 579) | def destroy(self):
    method add_grammar_fst (line 586) | def add_grammar_fst(self, grammar_fst):
    method add_grammar_fst_text (line 595) | def add_grammar_fst_text(self, grammar_fst_text):
    method reload_grammar_fst (line 605) | def reload_grammar_fst(self, grammar_fst_index, grammar_fst):
    method remove_grammar_fst (line 611) | def remove_grammar_fst(self, grammar_fst_index):
    method decode (line 618) | def decode(self, frames, finalize, grammars_activity=None):
  class KaldiModelBuildUtils (line 647) | class KaldiModelBuildUtils(FFIObject):
    method build_L_disambig (line 654) | def build_L_disambig(cls, lexicon_fst_text_bytes, phones_file, words_f...
    method make_lexicon_fst (line 660) | def make_lexicon_fst(**kwargs):

FILE: setup.py
  class bdist_wheel_impure (line 31) | class bdist_wheel_impure(bdist_wheel):
    method finalize_options (line 33) | def finalize_options(self):
    method get_tag (line 38) | def get_tag(self):
  class install_platlib (line 49) | class install_platlib(install):
    method finalize_options (line 50) | def finalize_options(self):
  function read (line 58) | def read(*parts):
  function find_version (line 62) | def find_version(*file_paths):

FILE: tests/conftest.py
  function change_to_test_dir (line 10) | def change_to_test_dir(monkeypatch):
  function get_piper_model_path (line 13) | def get_piper_model_path():
  function piper_voice (line 24) | def piper_voice():
  function audio_generator (line 30) | def audio_generator(piper_voice):

FILE: tests/generate_google_tts.py
  function generate (line 19) | def generate(text, out=None, voice="en-US-Studio-Q", lang="en-US", forma...
  function list_voices (line 39) | def list_voices():

FILE: tests/helpers.py
  function assert_info_shape (line 10) | def assert_info_shape(info):
  function play_audio_on_windows (line 16) | def play_audio_on_windows(audio_bytes: bytes, sample_rate: int = 16000):

FILE: tests/run_each_test_separately.py
  function collect_nodeids (line 8) | def collect_nodeids(extra):
  function main (line 20) | def main():

FILE: tests/test_grammar.py
  class TestGrammar (line 10) | class TestGrammar:
    method setup (line 13) | def setup(self, change_to_test_dir, audio_generator):
    method make_rule (line 18) | def make_rule(self, name: str, build_func: Callable[[Union[NativeWFST,...
    method decode (line 29) | def decode(self, text_or_audio: Union[str, bytes], kaldi_rules_activit...
    method test_simple_rule (line 60) | def test_simple_rule(self):
    method test_epsilon_transition (line 68) | def test_epsilon_transition(self):
    method test_multiple_paths (line 79) | def test_multiple_paths(self):
    method test_multiple_paths_hi (line 92) | def test_multiple_paths_hi(self):
    method test_sequential_chain (line 103) | def test_sequential_chain(self):
    method test_diamond_pattern (line 118) | def test_diamond_pattern(self):
    method test_diamond_pattern_alt (line 140) | def test_diamond_pattern_alt(self):
    method test_self_loop (line 157) | def test_self_loop(self):
    method test_optional_path_with_epsilon (line 170) | def test_optional_path_with_epsilon(self):
    method test_complex_branching (line 186) | def test_complex_branching(self):
    method test_complex_branching_alt1 (line 211) | def test_complex_branching_alt1(self):
    method test_complex_branching_alt2 (line 231) | def test_complex_branching_alt2(self):
    method test_multiple_epsilon_transitions (line 251) | def test_multiple_epsilon_transitions(self):
    method test_weighted_alternatives (line 267) | def test_weighted_alternatives(self):
    method test_parallel_sequences (line 279) | def test_parallel_sequences(self):
    method test_parallel_sequences_alt (line 299) | def test_parallel_sequences_alt(self):
    method test_nested_loops (line 316) | def test_nested_loops(self):
    method test_multiple_entry_points (line 334) | def test_multiple_entry_points(self):
    method test_cascade_pattern (line 356) | def test_cascade_pattern(self):
    method test_backtracking_pattern (line 381) | def test_backtracking_pattern(self):
    method test_very_long_sequence (line 401) | def test_very_long_sequence(self):
    method test_hub_and_spoke (line 411) | def test_hub_and_spoke(self):
    method test_rule_with_dictation (line 441) | def test_rule_with_dictation(self, dictation_words, expected_mask):
    method test_no_rules (line 459) | def test_no_rules(self):
    method test_no_active_rules (line 463) | def test_no_active_rules(self):
    method test_garbage_audio (line 472) | def test_garbage_audio(self):
    method test_empty_audio (line 485) | def test_empty_audio(self):
    method test_very_short_audio (line 494) | def test_very_short_audio(self):
    method test_multiple_utterances_sequence (line 503) | def test_multiple_utterances_sequence(self):
  class TestAlternativeDictation (line 517) | class TestAlternativeDictation:
    method setup (line 521) | def setup(self, change_to_test_dir, audio_generator):
    method compiler_with_mock (line 526) | def compiler_with_mock(self):
    method create_mock_rule (line 533) | def create_mock_rule(self, compiler, has_dictation=True):
    method parse_with_dictation_info (line 537) | def parse_with_dictation_info(self, compiler, output_text, audio_data,...
    method test_alternative_dictation_callable_check (line 543) | def test_alternative_dictation_callable_check(self):
    method test_alternative_dictation_not_called_without_dictation (line 551) | def test_alternative_dictation_not_called_without_dictation(self, comp...
    method test_alternative_dictation_integration_full_decode (line 571) | def test_alternative_dictation_integration_full_decode(self, change_to...
    method test_alternative_dictation_not_called_without_cloud_nonterm (line 651) | def test_alternative_dictation_not_called_without_cloud_nonterm(self, ...
    method test_alternative_dictation_word_align_parsing (line 671) | def test_alternative_dictation_word_align_parsing(self, compiler_with_...
    method test_alternative_dictation_span_calculation (line 721) | def test_alternative_dictation_span_calculation(self, compiler_with_mo...
    method test_alternative_dictation_multiple_spans (line 731) | def test_alternative_dictation_multiple_spans(self):
    method test_alternative_dictation_fallback (line 765) | def test_alternative_dictation_fallback(self, alternative_func, expect...
    method test_alternative_dictation_exception_handling (line 785) | def test_alternative_dictation_exception_handling(self):
    method test_alternative_dictation_invalid_type_raises (line 806) | def test_alternative_dictation_invalid_type_raises(self):
    method test_alternative_dictation_audio_slice_accuracy (line 824) | def test_alternative_dictation_audio_slice_accuracy(self):

FILE: tests/test_package.py
  function test_import_and_version (line 4) | def test_import_and_version():

FILE: tests/test_plain_dictation.py
  function recognizer (line 12) | def recognizer(change_to_test_dir):
  function test_initialization (line 16) | def test_initialization(recognizer):
  function test_basic_dictation (line 30) | def test_basic_dictation(recognizer, audio_generator, test_text):
  function test_empty_audio (line 38) | def test_empty_audio(recognizer):
  function test_garbage_audio (line 45) | def test_garbage_audio(recognizer):
  function test_multiple_utterances (line 54) | def test_multiple_utterances(recognizer, audio_generator):
  class TestPlainDictationWithFST (line 68) | class TestPlainDictationWithFST:
    method setup (line 72) | def setup(self, change_to_test_dir):
    method test_initialization (line 80) | def test_initialization(self):
    method test_basic_dictation (line 87) | def test_basic_dictation(self, audio_generator):
  function test_chunked_decode (line 103) | def test_chunked_decode(recognizer, audio_generator, chunk_size, test_te...
  function test_custom_tmp_dir (line 111) | def test_custom_tmp_dir(change_to_test_dir, audio_generator, tmp_path):
  function test_custom_config (line 121) | def test_custom_config(change_to_test_dir, audio_generator):
  function test_very_short_audio (line 135) | def test_very_short_audio(recognizer, audio_generator):
  function test_very_long_audio (line 143) | def test_very_long_audio(recognizer, audio_generator):
  function test_repeated_words (line 156) | def test_repeated_words(recognizer, audio_generator):
  function test_sequential_empty_audio (line 164) | def test_sequential_empty_audio(recognizer):
  function test_alternating_empty_and_valid (line 172) | def test_alternating_empty_and_valid(recognizer, audio_generator):
  function test_info_structure (line 189) | def test_info_structure(recognizer, audio_generator):
  function test_info_consistency (line 200) | def test_info_consistency(change_to_test_dir, audio_generator):
Condensed preview — 54 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (500K chars).
[
  {
    "path": ".github/FUNDING.yml",
    "chars": 50,
    "preview": "github: daanzu\ncustom: \"https://paypal.me/daanzu\"\n"
  },
  {
    "path": ".github/RELEASING.md",
    "chars": 8599,
    "preview": "# Release Process\n\n## Quick Summary\n\n1. **Prepare**: Update version in `__init__.py`, update `CHANGELOG.md`, run tests\n2"
  },
  {
    "path": ".github/release_notes.md",
    "chars": 20308,
    "preview": "v0.5.0: User Lexicon! Compilation Optimizations! Better Model!\n\n### Notes\n\n* **User Lexicon**: you can add new words/pro"
  },
  {
    "path": ".github/workflows/build.yml",
    "chars": 28707,
    "preview": "name: Build\n\non:\n  push:\n  pull_request:\n  workflow_dispatch:\n    # gh api repos/:owner/:repo/actions/workflows/build.ym"
  },
  {
    "path": ".gitignore",
    "chars": 374,
    "preview": "_cmake_test_compile/\nkaldi_active_grammar/exec\nexamples/*.fst\nportable/\ntests/*.onnx\ntests/*.onnx.json\ntests/**/*.wav\ntm"
  },
  {
    "path": "AGENTS.md",
    "chars": 7147,
    "preview": "# Kaldi Active Grammar - Agent Information\n\nThis document provides technical architectural information for AI coding age"
  },
  {
    "path": "CHANGELOG.md",
    "chars": 11064,
    "preview": "# Changelog\n\nAll notable changes to this project will be documented in this file.\nNote that the project (and python whee"
  },
  {
    "path": "CMakeLists.txt",
    "chars": 4118,
    "preview": "cmake_minimum_required(VERSION 3.13.0)\nproject(kaldi_binaries)\n\ninclude(ExternalProject)\ninclude(ProcessorCount)\n\nProces"
  },
  {
    "path": "Justfile",
    "chars": 3497,
    "preview": "\nset ignore-comments\nset positional-arguments\n\ndocker_repo := 'daanzu/kaldi-fork-active-grammar-manylinux'\npiper_voice :"
  },
  {
    "path": "LICENSE.txt",
    "chars": 34523,
    "preview": "                    GNU AFFERO GENERAL PUBLIC LICENSE\n                       Version 3, 19 November 2007\n\n Copyright (C)"
  },
  {
    "path": "README.md",
    "chars": 14368,
    "preview": "# Kaldi Active Grammar\n\n> **Python Kaldi speech recognition with grammars that can be set active/inactive dynamically at"
  },
  {
    "path": "building/build-wheel-dockcross.sh",
    "chars": 2711,
    "preview": "#!/usr/bin/env bash\n\n# This script builds a Python wheel for kaldi-active-grammar using dockcross,\n# and is to be RUN WI"
  },
  {
    "path": "building/dockcross-manylinux2010-x64",
    "chars": 5943,
    "preview": "#!/usr/bin/env bash\n\nDEFAULT_DOCKCROSS_IMAGE=dockcross/manylinux2010-x64:latest\n\n#--------------------------------------"
  },
  {
    "path": "building/kaldi-configure-wrapper.sh",
    "chars": 481,
    "preview": "#!/usr/bin/env bash\n\n# We use this wrapper script to set CXXFLAGS in the environment before calling\n# kaldi configure, t"
  },
  {
    "path": "docs/models.md",
    "chars": 6696,
    "preview": "# Speech Recognition Models\n\n[![Donate](https://img.shields.io/badge/donate-GitHub-pink.svg)](https://github.com/sponsor"
  },
  {
    "path": "examples/audio.py",
    "chars": 12905,
    "preview": "#\n# This file is part of kaldi-active-grammar.\n# (c) Copyright 2019 by David Zurow\n# Licensed under the AGPL-3.0; see LI"
  },
  {
    "path": "examples/full_example.py",
    "chars": 2669,
    "preview": "import logging, time\nimport kaldi_active_grammar\n\nlogging.basicConfig(level=20)\nmodel_dir = None  # Default\ntmp_dir = No"
  },
  {
    "path": "examples/mix_dictation.py",
    "chars": 1702,
    "preview": "import kaldi_active_grammar\n\nif __name__ == '__main__':\n    import util\n    compiler, decoder = util.initialize()\n\n#####"
  },
  {
    "path": "examples/plain_dictation.py",
    "chars": 481,
    "preview": "import logging, sys, wave\nfrom kaldi_active_grammar import PlainDictationRecognizer\n\n# logging.basicConfig(level=10)\nrec"
  },
  {
    "path": "examples/requirements_audio.txt",
    "chars": 43,
    "preview": "sounddevice==0.3.*\nwebrtcvad-wheels==2.0.*\n"
  },
  {
    "path": "examples/util.py",
    "chars": 2129,
    "preview": "import time\nimport kaldi_active_grammar\nfrom audio import VADAudio\n\ndef initialize(model_dir=None, tmp_dir=None, config="
  },
  {
    "path": "kaldi_active_grammar/LICENSE.txt",
    "chars": 34523,
    "preview": "                    GNU AFFERO GENERAL PUBLIC LICENSE\n                       Version 3, 19 November 2007\n\n Copyright (C)"
  },
  {
    "path": "kaldi_active_grammar/__init__.py",
    "chars": 683,
    "preview": "#\n# This file is part of kaldi-active-grammar.\n# (c) Copyright 2019 by David Zurow\n# Licensed under the AGPL-3.0; see LI"
  },
  {
    "path": "kaldi_active_grammar/__main__.py",
    "chars": 2725,
    "preview": "#\n# This file is part of kaldi-active-grammar.\n# (c) Copyright 2019 by David Zurow\n# Licensed under the AGPL-3.0; see LI"
  },
  {
    "path": "kaldi_active_grammar/compiler.py",
    "chars": 41432,
    "preview": "#\n# This file is part of kaldi-active-grammar.\n# (c) Copyright 2019 by David Zurow\n# Licensed under the AGPL-3.0; see LI"
  },
  {
    "path": "kaldi_active_grammar/defaults.py",
    "chars": 357,
    "preview": "#\n# This file is part of kaldi-active-grammar.\n# (c) Copyright 2019 by David Zurow\n# Licensed under the AGPL-3.0; see LI"
  },
  {
    "path": "kaldi_active_grammar/ffi.py",
    "chars": 1155,
    "preview": "#\n# This file is part of kaldi-active-grammar.\n# (c) Copyright 2019 by David Zurow\n# Licensed under the AGPL-3.0; see LI"
  },
  {
    "path": "kaldi_active_grammar/kaldi/COPYING",
    "chars": 17264,
    "preview": "\n Update to legal notice, made Feb 2012, modified Sep 2013.  We would like to\n clarify that we are using a convention wh"
  },
  {
    "path": "kaldi_active_grammar/kaldi/__init__.py",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "kaldi_active_grammar/kaldi/augment_phones_txt.py",
    "chars": 4385,
    "preview": "#!/usr/bin/env python3\n\n\nimport argparse\nimport re\nimport os\nimport sys\n\ndef get_args():\n    parser = argparse.ArgumentP"
  },
  {
    "path": "kaldi_active_grammar/kaldi/augment_phones_txt_py2.py",
    "chars": 4364,
    "preview": "#!/usr/bin/env python3\n\n\nfrom __future__ import print_function\nimport argparse\nimport re\nimport os\nimport sys\n\ndef get_a"
  },
  {
    "path": "kaldi_active_grammar/kaldi/augment_words_txt.py",
    "chars": 4386,
    "preview": "#!/usr/bin/env python3\n\n\nimport argparse\nimport os\nimport sys\nimport re\n\ndef get_args():\n    parser = argparse.ArgumentP"
  },
  {
    "path": "kaldi_active_grammar/kaldi/augment_words_txt_py2.py",
    "chars": 4365,
    "preview": "#!/usr/bin/env python3\n\n\nfrom __future__ import print_function\nimport argparse\nimport os\nimport sys\nimport re\n\ndef get_a"
  },
  {
    "path": "kaldi_active_grammar/kaldi/make_lexicon_fst.py",
    "chars": 19186,
    "preview": "#!/usr/bin/env python3\n\n# Copyright   2018  Johns Hopkins University (author: Daniel Povey)\n# Apache 2.0.\n\n# see get_arg"
  },
  {
    "path": "kaldi_active_grammar/kaldi/make_lexicon_fst_py2.py",
    "chars": 19117,
    "preview": "#!/usr/bin/env python3\n\n# Copyright   2018  Johns Hopkins University (author: Daniel Povey)\n# Apache 2.0.\n\n# see get_arg"
  },
  {
    "path": "kaldi_active_grammar/model.py",
    "chars": 24361,
    "preview": "#\n# This file is part of kaldi-active-grammar.\n# (c) Copyright 2019 by David Zurow\n# Licensed under the AGPL-3.0; see LI"
  },
  {
    "path": "kaldi_active_grammar/plain_dictation.py",
    "chars": 2744,
    "preview": "#\n# This file is part of kaldi-active-grammar.\n# (c) Copyright 2019 by David Zurow\n# Licensed under the AGPL-3.0; see LI"
  },
  {
    "path": "kaldi_active_grammar/utils.py",
    "chars": 13880,
    "preview": "#\n# This file is part of kaldi-active-grammar.\n# (c) Copyright 2019 by David Zurow\n# Licensed under the AGPL-3.0; see LI"
  },
  {
    "path": "kaldi_active_grammar/wfst.py",
    "chars": 17858,
    "preview": "#\n# This file is part of kaldi-active-grammar.\n# (c) Copyright 2019 by David Zurow\n# Licensed under the AGPL-3.0; see LI"
  },
  {
    "path": "kaldi_active_grammar/wrapper.py",
    "chars": 35555,
    "preview": "#\n# This file is part of kaldi-active-grammar.\n# (c) Copyright 2019 by David Zurow\n# Licensed under the AGPL-3.0; see LI"
  },
  {
    "path": "pyproject.toml",
    "chars": 459,
    "preview": "[build-system]\nrequires = [\"setuptools\", \"wheel\", \"scikit-build\", \"cmake\", \"ninja\"]\n\n[tool.pytest.ini_options]\nminversio"
  },
  {
    "path": "requirements-build.txt",
    "chars": 50,
    "preview": "cmake\nninja\nscikit-build>=0.10.0\nsetuptools\nwheel\n"
  },
  {
    "path": "requirements-editable.txt",
    "chars": 5,
    "preview": "-e .\n"
  },
  {
    "path": "requirements-test.txt",
    "chars": 38,
    "preview": "piper-tts~=1.0\npytest>=8.0\npytest-cov\n"
  },
  {
    "path": "setup.cfg",
    "chars": 666,
    "preview": "[metadata]\n# This includes the license file(s) in the wheel.\n# https://wheel.readthedocs.io/en/stable/user_guide.html#in"
  },
  {
    "path": "setup.py",
    "chars": 12524,
    "preview": "\"\"\"A setuptools based setup module.\n\nSee:\nhttps://packaging.python.org/guides/distributing-packages-using-setuptools/\nht"
  },
  {
    "path": "tests/conftest.py",
    "chars": 1614,
    "preview": "\nimport os\nfrom pathlib import Path\n\nimport piper\nimport pytest\n\n\n@pytest.fixture\ndef change_to_test_dir(monkeypatch):\n "
  },
  {
    "path": "tests/generate_google_tts.py",
    "chars": 1676,
    "preview": "#!/usr/bin/env -S uv run --script\n# /// script\n# requires-python = \">=3.12\"\n# dependencies = [\n#     \"google-cloud-textt"
  },
  {
    "path": "tests/generate_piper_tts.py",
    "chars": 1876,
    "preview": "#!/usr/bin/env -S uv run --script\n# /// script\n# requires-python = \">=3.12\"\n# dependencies = [\n#     \"piper-tts\",\n#     "
  },
  {
    "path": "tests/helpers.py",
    "chars": 1001,
    "preview": "\nexpected_info_keys_and_types = {\n    'likelihood': float,\n    'am_score': float,\n    'lm_score': float,\n    'confidence"
  },
  {
    "path": "tests/run_each_test_separately.py",
    "chars": 1229,
    "preview": "\"\"\"\nRun each test in a separate process.\nThis is the only reasonable cross-platform way to do this with pytest.\n\"\"\"\n\nimp"
  },
  {
    "path": "tests/test_grammar.py",
    "chars": 36276,
    "preview": "\nfrom typing import Callable, Optional, Union\n\nimport pytest\n\nfrom kaldi_active_grammar import Compiler, KaldiRule, Nati"
  },
  {
    "path": "tests/test_package.py",
    "chars": 348,
    "preview": "\nimport re\n\ndef test_import_and_version():\n    import kaldi_active_grammar as kag\n    assert isinstance(kag.__version__,"
  },
  {
    "path": "tests/test_plain_dictation.py",
    "chars": 7295,
    "preview": "\nimport math\nimport random\n\nimport pytest\n\nfrom kaldi_active_grammar import PlainDictationRecognizer\nfrom tests.helpers "
  }
]

About this extraction

This page contains the full source code of the daanzu/kaldi-active-grammar GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 54 files (470.6 KB), approximately 116.3k tokens, and a symbol index with 345 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!