Metadata-Version: 2.4
Name: eliana-asr
Version: 1.0.0
Summary: Eliana-ASR: Vietnamese speech recognition, offline and live streaming with one set of weights
Author: Nguyen Nhat Hoang
License-Expression: CC-BY-NC-SA-4.0
Project-URL: Model, https://huggingface.co/nhathoangdev/Eliana-ASR-1.0-vi
Project-URL: Repository, https://github.com/nhathoang0110/eliana-asr
Project-URL: Benchmark, https://github.com/nhathoang0110/vi-asr-bench
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: torch>=2.6
Requires-Dist: transformers<6,>=5.18
Requires-Dist: huggingface_hub>=1.0
Requires-Dist: safetensors>=0.4
Requires-Dist: sentencepiece>=0.2
Requires-Dist: numpy>=1.26
Requires-Dist: scipy>=1.11
Requires-Dist: soundfile>=0.12
Provides-Extra: test
Requires-Dist: pytest>=8; extra == "test"
Dynamic: license-file

# eliana-asr

Gói Python cho [Eliana-ASR-1.0-vi](https://huggingface.co/nhathoangdev/Eliana-ASR-1.0-vi), mô hình nhận dạng
giọng nói tiếng Việt. Cùng một bộ trọng số dùng được cho cả nhận dạng file (offline) lẫn nhận dạng trực
tiếp từ micro (streaming), chạy trên CPU không cần GPU, và có **lỗi thấp nhất trên nhóm A trong hạng model mở
nhận dạng tiếng Việt streaming dưới 400 triệu tham số**, ở cả hai chế độ.
*English below.*

| WER % nhóm A (8 tập test công khai, càng thấp càng tốt) | Tham số | Streaming | Offline |
|---|---:|---:|---:|
| **Eliana-ASR-1.0-vi** (đoạn 0,48 s) | 353M | **5,43** | **4,70** |
| VietNote-Zipformer-78M-Streaming (đoạn 0,64 s) | 72M | 6,81 | 5,51 |
| Zipformer-30M-RNNT-Streaming (đoạn 0,64 s) | 25M | 5,97 | 6,59 |
| VieGem-ASR (đoạn 0,48 s) | 359M | 7,77 | 6,36 |

Nhóm B (3 đơn vị ngoài dữ liệu huấn luyện), bảng đầy đủ 28 hệ thống và cách đo nằm trên
[model card](https://huggingface.co/nhathoangdev/Eliana-ASR-1.0-vi), tái lập bằng
[vi-asr-bench](https://github.com/nhathoang0110/vi-asr-bench).

```bash
pip install eliana-asr
```

```python
from eliana_asr import ElianaASR

model = ElianaASR.from_pretrained("nhathoangdev/Eliana-ASR-1.0-vi")   # hoặc đường dẫn tới thư mục trên máy
text = model.transcribe("phong_van.wav")                              # các định dạng phổ biến, tự chuyển về mono 16 kHz

stream = model.stream()                                               # cùng bộ trọng số
for chunk in microphone(sample_rate=16000):                           # từng đoạn tín hiệu âm thanh float32 (hoặc int16), mono 16 kHz
    partial = stream.feed(chunk)                                      # kết quả tạm thời tính đến thời điểm hiện tại
print(stream.finish())                                                # kết quả cuối cùng
```

- `from_pretrained(..., device="cpu", dtype=None)`: mặc định chạy trên CPU với fp32. Với `device="cuda"`,
  mặc định dùng autocast bf16 (head CTC vẫn tính bằng fp32); truyền `dtype="float32"` hoặc
  `"bfloat16"` để chỉ định kiểu dữ liệu cụ thể.
- Trên CPU, gói dùng tối đa 2 luồng khi streaming và tối đa 8 luồng khi nhận dạng file, rồi trả lại cài
  đặt luồng cũ của torch sau mỗi lần gọi. Dùng nhiều luồng hơn làm streaming chậm đi rõ rệt, nhất là trên
  CPU có cả nhân hiệu năng lẫn nhân tiết kiệm điện. Chỉnh bằng `num_threads=` ở `from_pretrained` hoặc
  `stream`; `num_threads=0` giữ nguyên cài đặt của torch.
- Tốc độ trên CPU với cài đặt mặc định: streaming 25 giây audio mất 8,5 giây trên Apple M4 và 7,4 giây trên
  Intel Core Ultra 9 285H (đoạn 0,48 giây chậm nhất: 0,24 và 0,16 giây); nhận dạng file 60 giây mất 1,9 và
  2,8 giây.
- `transcribe` nhận đường dẫn file, mảng hoặc tensor chứa mẫu âm thanh (kèm `sample_rate=` nếu khác 16 kHz),
  hoặc danh sách các đầu vào tương ứng (khi đó trả về danh sách kết quả). WAV, FLAC, OGG, MP3 được đọc bằng
  libsndfile; các định dạng khác (M4A, WebM...) cần cài `ffmpeg`.
- Đầu ra toàn chữ thường, **không có dấu câu**.

### Streaming và audio dài

Model xử lý audio theo từng đoạn (chunk) 0,48 giây: văn bản của một đoạn hiện ra ngay khi nhận đủ audio
của đoạn đó (cộng thêm thời gian suy luận). Mỗi lần gọi `feed` chỉ xử lý phần audio mới nhờ KV-cache.

Model được huấn luyện trên các câu dài tối đa 30 giây, nên audio dài được chia thành các phân đoạn tối đa
28 giây, theo đúng cách `transcribe` chia file: cắt tại cửa sổ 0,2 giây yên lặng nhất trong khoảng giây thứ
20–28 của phân đoạn. Điểm cắt chỉ xác định được khi phân đoạn vượt quá 28 giây. Có hai chế độ:

- Mặc định `model.stream()`: **không phải chờ**. Sau giây thứ 20,1 của một phân đoạn, kết quả tạm thời được
  lấy từ một bản sao của bộ giải mã tiếp tục xử lý phân đoạn đó. Khi phân đoạn vượt quá 28 giây, điểm cắt
  được chọn: phần văn bản trước điểm cắt được chốt, phân đoạn mới bắt đầu từ điểm cắt và xử lý bù phần
  audio từ đó tới hiện tại (tối đa 7,9 giây, ngay trong lần gọi `feed` đó). Vài giây cuối của kết quả tạm
  thời có thể thay đổi vào lúc này.
- `model.stream(stable_partials=True)`: văn bản tạm thời chỉ nối dài thêm và không bao giờ bị sửa lại, nhưng
  sau giây thứ 20,1 của một phân đoạn sẽ tạm dừng cập nhật cho tới khi xác định được điểm cắt (trễ so với
  audio tối đa khoảng 8 giây).

Hai chế độ cho cùng kết quả cuối, trùng với `model.decode_waveforms(..., chunk_frames=12)` trên toàn bộ
audio. Với audio không quá 28 giây thì không cần cắt phân đoạn: kết quả tạm thời không bao giờ bị sửa lại, và
`finish()` chỉ bổ sung phần văn bản của đoạn cuối chưa đủ 0,48 giây.

#### Ngắt câu theo khoảng lặng (endpointing)

Với micro trực tiếp, `model.stream(endpoint=True)` tự ngắt câu khi người nói ngừng, theo cách của sherpa-onnx
và WeNet: khoảng lặng là số khung blank liên tiếp ở cuối đầu ra của model, xét ở cuối mỗi đoạn 0,48 giây.

```python
stream = model.stream(endpoint=True)
for chunk in microphone(sample_rate=16000):
    stream.feed(chunk)
    if stream.is_endpoint:               # vừa xong một câu
        print(stream.committed[-1])
    else:
        print(stream.partial, end="\r")  # câu đang nói
```

- Ngừng 1,2 giây sau khi đã có chữ: câu được chốt vào `stream.committed` (không bao giờ đổi nữa), `is_endpoint`
  bật lên, câu tiếp theo bắt đầu từ trạng thái mới (kèm 0,24 giây cuối của khoảng lặng). Vì xét theo đoạn 0,48
  giây, câu được chốt khoảng 1,2–1,7 giây sau từ cuối cùng.
- Khoảng lặng còn phải thật sự nhỏ: 0,48 giây cuối của nó nhỏ hơn mức giọng nói gần đây ít nhất 8 dB. Có lúc model
  không ra chữ hơn một giây trong khi người nói vẫn đang nói; bước kiểm này giữ cho câu không bị cắt ở đó.
- Im lặng 2,4 giây mà chưa có chữ nào: bỏ đoạn im lặng đó, không tạo câu rỗng.
- Nói liền quá 28 giây không nghỉ: cắt như trên.
- Các ngưỡng chỉnh được bằng `EndpointConfig` (đặt `None` để tắt một luật). `stream.reset()` bỏ hết audio và chữ
  mà không xử lý phần còn lại; `finish()` cũng xóa `committed`, nên hãy giữ lại kết quả nó trả về.

Mặc định `endpoint=False`: không ngắt câu, kết quả như mô tả ở trên. Khi bật, mỗi câu được giải mã riêng nên kết
quả không còn trùng `decode_waveforms`, nhưng vẫn giống nhau dù `feed` nhận audio theo gói lớn hay nhỏ.

### Tải model

`from_pretrained` tải `config.json`, `model.safetensors` và `units.model`. Nếu `model.safetensors` không kèm
sẵn encoder (`"bundled": false` trong config.json), thư viện sẽ tự tải thêm `model.safetensors` của
[google/embeddinggemma-2](https://huggingface.co/google/embeddinggemma-2) theo đúng revision đã cố định và
tách phần encoder âm thanh (audio tower) từ đó.

---

## English

Python package for [Eliana-ASR-1.0-vi](https://huggingface.co/nhathoangdev/Eliana-ASR-1.0-vi): Vietnamese
speech recognition, one set of weights for offline transcription and live microphone streaming, with the
**lowest Group A error rate among open Vietnamese streaming models under 400M parameters**, offline and
streaming, on a CPU with no GPU (table above: WER % on Group A, 8 public test sets; Group B and the full
28-system comparison are on the model card). The code above works as is.

- `from_pretrained(..., device="cpu", dtype=None)`: CPU fp32 by default. On `device="cuda"` the default is
  bf16 autocast (the CTC head stays fp32); pass `dtype="float32"` or `"bfloat16"` to choose.
- On CPU the package uses at most 2 torch threads while streaming and at most 8 for files, and restores
  torch's setting after each call. More threads make streaming much slower, above all on CPUs with both
  performance and efficiency cores. Set `num_threads=` on `from_pretrained` or `stream`; `num_threads=0`
  leaves torch's setting untouched.
- CPU speed with the defaults: streaming 25 s of audio takes 8.5 s on an Apple M4 and 7.4 s on an Intel
  Core Ultra 9 285H (slowest 0.48-second chunk: 0.24 s and 0.16 s); a 60-second file takes 1.9 s and 2.8 s.
- `transcribe` takes a file path, an array/tensor of samples (`sample_rate=` if not 16 kHz), or a list
  (returns a list). WAV, FLAC, OGG, MP3 are read with libsndfile; other formats (M4A, WebM...) need `ffmpeg`.
- Output is lower-case words **without punctuation or capitalization**.

### Streaming and long audio

The reader sees audio in 0.48-second chunks: the words of a chunk appear as soon as the chunk is complete
(plus compute time), and each `feed` only computes the new audio (KV-cache).

The model was trained on utterances of at most 30 seconds, so audio is decoded in segments of at most 28
seconds, cut exactly like `transcribe` cuts files: at the quietest 0.2-second window in seconds 20–28 of
the segment. The cut point is only known once the segment passes 28 seconds. Two modes:

- default `model.stream()`: **nothing waits**. Past second 20.1 of a segment, the partial text comes from a
  copy of the decoder that simply continues the segment. When the segment passes 28 seconds the cut is
  chosen: the part before the cut is finalised, a new segment starts at the cut and catches up on the
  audio since then (at most 7.9 seconds, computed within that one `feed` call). The last few seconds of
  the partial text may change at that moment.
- `model.stream(stable_partials=True)`: the partial text only grows and is never rewritten, but past
  second 20.1 of a segment it pauses until the cut is known (up to about 8 seconds behind the audio).

Both give the same final text, identical to `model.decode_waveforms(..., chunk_frames=12)` on the whole
audio. Up to 28 seconds of audio there is no cut: partial text is never revised and `finish()` only adds
the words of the last, incomplete chunk.

#### Sentences (endpointing)

For a live microphone, `model.stream(endpoint=True)` ends a sentence when the speaker pauses, as in
sherpa-onnx and WeNet: silence is the number of consecutive blank frames at the end of the model output,
checked at the end of every 0.48-second chunk.

```python
stream = model.stream(endpoint=True)
for chunk in microphone(sample_rate=16000):
    stream.feed(chunk)
    if stream.is_endpoint:               # a sentence just ended
        print(stream.committed[-1])
    else:
        print(stream.partial, end="\r")  # the sentence being spoken
```

- 1.2 seconds of silence after some words: the sentence goes to `stream.committed` (never changed again),
  `is_endpoint` is set and the next sentence starts from a fresh state (with the last 0.24 s of the silence).
  Decisions are taken per 0.48-second chunk, so a sentence ends 1.2 to 1.7 seconds after its last word.
- The silence must also be quiet: its last 0.48 s at least 8 dB below the recent speech level. The model
  sometimes outputs nothing for over a second while someone is still talking; this check keeps the
  sentence from being cut there.
- 2.4 seconds of silence with no words yet: that silence is dropped, no empty sentence is produced.
- Speech running past 28 seconds without a pause is cut as above.
- Thresholds are set with `EndpointConfig` (`None` disables a rule). `stream.reset()` drops all audio and text
  without decoding the rest; `finish()` also clears `committed`, so keep the text it returns.

The default `endpoint=False` never ends sentences and behaves as described above. With endpointing on,
sentences are decoded separately, so the result no longer equals `decode_waveforms`, but it does not
depend on how the audio is split across `feed` calls.

### Model files

`from_pretrained` downloads `config.json`, `model.safetensors` and `units.model`. If `model.safetensors`
does not bundle the encoder (`"bundled": false` in config.json), the package also downloads
`model.safetensors` of [google/embeddinggemma-2](https://huggingface.co/google/embeddinggemma-2) at a
pinned revision and takes the audio tower from it.

## Giấy phép / License

[CC BY-NC-SA 4.0](https://creativecommons.org/licenses/by-nc-sa/4.0/) (phi thương mại / non-commercial).
The audio encoder comes from [google/embeddinggemma-2](https://huggingface.co/google/embeddinggemma-2) and is
licensed under the [Apache License 2.0](https://ai.google.dev/gemma/docs/gemma_4_license) (Gemma 4 license).
