aishot commited on
Commit
a8d70e0
·
verified ·
1 Parent(s): d589598

Publish Studio ASR, corrector and TTS variants

Browse files
README.md CHANGED
@@ -21,11 +21,12 @@ Amharic speech and text models developed for EthiopicAI Voice Studio. This repos
21
  | Amharic ASR | Audio → transcript and word timings | [Speech recognition](cards/asr.md) |
22
  | Amharic text corrector | Text → corrected or punctuated text | [Text correction](cards/corrector.md) |
23
  | Amharic Pocket TTS and OmniVoice | Text and optional reference voice → speech | [Speech synthesis and voice cloning](cards/tts.md) |
 
24
  | Higgs Audio v2 codec | Audio ↔ discrete audio codes | [Audio codec](cards/codec.md) |
25
 
26
  The ASR models are Amharic-specialized models trained by EthiopicAI using Meta Omnilingual ASR pretrained checkpoints and **over 2,000 hours of Amharic podcast and news audio**. Their model card documents the released checkpoint lineage, Amharic training and evaluation results.
27
 
28
- `manifest.json` records the 11 released variants, their exact file sizes and SHA-256 checksums, dependencies, and an immutable download revision. Keep variant folders side by side so OmniVoice can locate its shared codec.
29
 
30
  ## Licenses
31
 
@@ -36,5 +37,6 @@ The EthiopicAI fine-tuned model weights are for **non-commercial use only**. Com
36
  - **OmniVoice:** weights CC BY-NC; library code Apache-2.0.
37
  - **Pocket TTS:** Kyutai base weights [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/) and [Kyutai acceptable-use terms](https://huggingface.co/kyutai/pocket-tts); library code MIT. EthiopicAI's Amharic fine-tune is non-commercial. [Attribution and terms](LICENSES/Pocket-TTS-terms.txt).
38
  - **Higgs Audio v2 codec:** [Boson agreement](LICENSES/Boson-Higgs-Audio-2.txt), incorporated [Meta Llama 3 agreement](LICENSES/Meta-Llama-3.txt) and [NOTICE](NOTICE).
 
39
 
40
  Built with Higgs Materials licensed from Boson AI USA, Inc., Copyright Boson AI USA, Inc., All Rights Reserved and Meta Llama 3 licensed under the Meta Llama 3 Community License, Copyright Meta Platforms, Inc., All Right Reserved.
 
21
  | Amharic ASR | Audio → transcript and word timings | [Speech recognition](cards/asr.md) |
22
  | Amharic text corrector | Text → corrected or punctuated text | [Text correction](cards/corrector.md) |
23
  | Amharic Pocket TTS and OmniVoice | Text and optional reference voice → speech | [Speech synthesis and voice cloning](cards/tts.md) |
24
+ | Voice editor | Recording and revised transcript → edited speech | [Voice editing](cards/editing.md) |
25
  | Higgs Audio v2 codec | Audio ↔ discrete audio codes | [Audio codec](cards/codec.md) |
26
 
27
  The ASR models are Amharic-specialized models trained by EthiopicAI using Meta Omnilingual ASR pretrained checkpoints and **over 2,000 hours of Amharic podcast and news audio**. Their model card documents the released checkpoint lineage, Amharic training and evaluation results.
28
 
29
+ `manifest.json` records the 12 released variants, their exact file sizes and SHA-256 checksums, dependencies, and an immutable download revision. Keep variant folders side by side so OmniVoice and the voice editor can locate shared components.
30
 
31
  ## Licenses
32
 
 
37
  - **OmniVoice:** weights CC BY-NC; library code Apache-2.0.
38
  - **Pocket TTS:** Kyutai base weights [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/) and [Kyutai acceptable-use terms](https://huggingface.co/kyutai/pocket-tts); library code MIT. EthiopicAI's Amharic fine-tune is non-commercial. [Attribution and terms](LICENSES/Pocket-TTS-terms.txt).
39
  - **Higgs Audio v2 codec:** [Boson agreement](LICENSES/Boson-Higgs-Audio-2.txt), incorporated [Meta Llama 3 agreement](LICENSES/Meta-Llama-3.txt) and [NOTICE](NOTICE).
40
+ - **Voice editor:** code Apache-2.0, with an MIT-derived alignment routine. Its OmniVoice and ASR dependencies make the feature non-commercial.
41
 
42
  Built with Higgs Materials licensed from Boson AI USA, Inc., Copyright Boson AI USA, Inc., All Rights Reserved and Meta Llama 3 licensed under the Meta Llama 3 Community License, Copyright Meta Platforms, Inc., All Right Reserved.
cards/editing.md ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ language:
3
+ - am
4
+ tags:
5
+ - voice-editing
6
+ - speech-infilling
7
+ - transcript-based-editing
8
+ license: other
9
+ license_name: ethiopic-voice-editing-component-terms
10
+ license_link: https://huggingface.co/ethiopic/ethiopic-studio-models/blob/main/README.md#licenses
11
+ ---
12
+
13
+ # EthiopicAI Voice Editing
14
+
15
+ `edit-omnivoice` is a code-only component for replacing, inserting or deleting words in Amharic recordings, using audio on both sides to preserve the speaker's voice and room sound. It has no model weights of its own.
16
+
17
+ ## Dependencies
18
+
19
+ - One OmniVoice variant: `tts-omnivoice-fp16`, `tts-omnivoice-fp32` or `tts-omnivoice-cpu-int8`, selected by the hardware bundle.
20
+ - `tts-codec-higgs`, always in FP32.
21
+ - `asr-ctc-1b-onnx-int8`, for transcription and word alignment on CPU.
22
+
23
+ The manifest declares required dependencies and alternative OmniVoice variants. Keep their folders beside `edit-omnivoice`. GPU bundles enable editing; CPU-high offers the INT8 backend as an explicit slow option. Other bundles leave editing off.
24
+
25
+ ## Interface
26
+
27
+ `SpeechEditor(tts_dir, codec_dir=None, aligner_dir=None, device=None, threads=None, num_step=None)` creates one reusable editor. Its `tts` object also provides ordinary synthesis, so applications can share one loaded voice model.
28
+
29
+ - `transcribe(audio, sr=None)` returns transcript text, word timings in seconds and the ASR model version.
30
+ - `align(audio, text, sr=None)` locates the supplied transcript in the audio. Punctuation-only tokens can have no timing.
31
+ - `edit(audio, orig_text, new_text, words=timings, seed=0, num_step=...)` returns a float32 24 kHz mono waveform, the revised transcript, changed spans and updated word timings.
32
+
33
+ Pass existing word timings to avoid a redundant alignment pass. Calls accept at most 30 seconds; applications handle longer recordings with contextual windows. Use at least 16 synthesis steps. Different seeds produce alternative takes.
34
+
35
+ ## Use and limitations
36
+
37
+ Fix transcript errors before changing the speech. Preview the result and listen around every edit, especially deletions, which may affect a neighboring word. Spell numbers out and write foreign words in Ethiopic script for better results. Performance depends on hardware; CPU editing is substantially slower than GPU editing.
38
+
39
+ Only edit recordings you have the right to change. Generated regions are synthetic and should remain identified in project history and exported edit logs. Edits must not misrepresent what someone said.
40
+
41
+ ## Terms
42
+
43
+ The feature is **non-commercial**: OmniVoice weights are CC BY-NC and the Amharic ASR aligner is non-commercial. Editor code is Apache-2.0; its alignment routine is adapted from MIT-licensed code. The [codec agreements](codec.md#terms) also apply.
edit-omnivoice/README.md ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # edit-omnivoice: word-level voice editing (code-only variant)
2
+
3
+ Change, insert or delete words in an Amharic recording. Only the changed words are regenerated, in the same voice and
4
+ room; the rest of the waveform is left untouched, sample for sample. No weights of its own. It uses:
5
+
6
+ | needs | why |
7
+ |---|---|
8
+ | one of `tts-omnivoice-fp16` / `tts-omnivoice-fp32` / `tts-omnivoice-cpu-int8` | the OmniVoice model that fills the masked span |
9
+ | `tts-codec-higgs` | audio tokens in and out (always fp32) |
10
+ | `asr-ctc-1b-onnx-int8` | transcription + forced word alignment (CPU, onnxruntime) |
11
+
12
+ Keep the folders side by side: `<models>/edit-omnivoice`, `<models>/tts-omnivoice-*`, `<models>/tts-codec-higgs`,
13
+ `<models>/asr-ctc-1b-onnx-int8`.
14
+
15
+ Python deps: those of the TTS variant (torch, torchaudio, transformers>=5.3, soundfile, omnivoice) plus onnxruntime
16
+ (for the aligner) and numpy; scipy optional (faster resampling). Tested in a fresh venv: torch 2.9.0+cu130,
17
+ transformers 5.14.1, onnxruntime 1.32.0, omnivoice 0.2.1, soundfile 0.14.0.
18
+
19
+ ## Use
20
+
21
+ ```python
22
+ from edit_omnivoice_infer import SpeechEditor, EditError
23
+ ed = SpeechEditor("<models>/tts-omnivoice-fp16") # codec/aligner found next to it; threads= for the CPU parts
24
+ t = ed.transcribe("clip.wav") # {"text", "words": [{"word","start","end"}], "model_version"}
25
+ r = ed.edit("clip.wav", t["text"], "<edited text>", words=t["words"], num_step=32)
26
+ r["audio"], r["sr"] # float32 numpy, 24000
27
+ r["edits"] # [{"span_in": [s, e], "span_out": [s, e], "orig_words": [...], "new_words": [...]}, ...]
28
+ r["words"] # word timings of the result -> pass them (with r["audio"], r["new_text"]) to chain the next edit
29
+ ```
30
+
31
+ - **Text in, text out:** `new_text` is the whole edited transcript. The word diff against `orig_text` finds the changes
32
+ (several at once are fine; changes at most one word apart are merged). Use the transcript the user edits as
33
+ `orig_text`; for a fresh recording, `transcribe()` gives it.
34
+ - **Pass `words`** when you have them (from `transcribe()`, `align()` or the previous `edit()`): that skips one full
35
+ ASR pass and halves GPU latency. Without `words`, the audio is transcribed and aligned, and `orig_text` must agree
36
+ with the transcript (CER <= 0.6), otherwise `EditError("text_mismatch")`; `force=True` overrides.
37
+ - **`num_step`:** use the tier's `tts_num_step` (32 on gpu-modern, 16 elsewhere). Below 16 is refused.
38
+ - **`span_duration`** (seconds) overrides the length of the new words (single-change edits only); `speed` scales it.
39
+ - **Limits:** clips up to 30 s (`EditError("too_long")`). For longer recordings, cut out the sentence (or a <= 30 s
40
+ window around the edit, at a pause), edit it and splice it back; chunking is not built in.
41
+ - **Undo** is the caller's job: keep the previous audio + text + words.
42
+ - `seed` (default 0) makes results repeatable; a different seed gives another take of the same edit.
43
+
44
+ Errors: `EditError(kind, message)`, a `ValueError` subclass, with `kind` in `empty_text`, `too_long`, `too_short`,
45
+ `bad_num_step`, `no_change`, `text_mismatch`, `alignment_failed`.
46
+
47
+ CLI:
48
+
49
+ ```bash
50
+ python edit_omnivoice_infer.py --tts <models>/tts-omnivoice-fp16 --audio in.wav # print transcript + words
51
+ python edit_omnivoice_infer.py --tts <models>/tts-omnivoice-fp16 --audio in.wav \
52
+ --new-text "<edited text>" [--orig-text "..."] [--num-step 32] [--span-duration 0.8] --out out.wav
53
+ ```
54
+
55
+ ## How it works
56
+
57
+ 1. Word timings: CTC Viterbi forced alignment with amharic-ctc v0.3 (ONNX int8; letter variants folded,
58
+ punctuation ignored).
59
+ 2. The changed words' audio is cut half-way into the neighbouring pauses (at most 0.3 s); an insertion goes in the
60
+ middle of the pause.
61
+ 3. New length = the context's speaking rate (OmniVoice's character weights, over up to 6 s each side) x the new words
62
+ + typical pauses.
63
+ 4. Tokens `[left context | MASK x N | right context]` with the edited transcript as text; OmniVoice fills the masked
64
+ frames by iterative unmasking, text guidance 2.0 (the unconditional branch keeps the audio context).
65
+ 5. Only the new span is decoded into the original waveform, with 20 ms crossfades inside the pauses. A deletion is a
66
+ cut plus a 0.32 s regeneration across the seam.
67
+ 6. Several changes are edited right to left; between them, the timings shift and the generated words are re-aligned
68
+ in a short window.
69
+
70
+ Background, training experiments and evaluation: research repo `amharic-speech-edit` (README.md, RESULTS.md). An
71
+ infill fine-tune was tried and gave no audible gain, so the stock Amharic OmniVoice weights are used.
72
+
73
+ ## Licenses
74
+
75
+ OmniVoice weights CC-BY-NC (non-commercial). amharic-ctc fine-tuned weights: non-commercial (training data includes
76
+ Amilia). This code: Apache-2.0 (the forced-alignment routine is adapted from pocket-tts, MIT). Edited audio is
77
+ synthetic: the app should make that clear and must not be used to misrepresent what someone said.
edit-omnivoice/amharic_text.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Amharic text normalisation for alignment and CER: a self-contained copy of the rules used to build and score
2
+ the edit model's data (TTS_small/scripts/ttstext.py + asr_finetune asr_metrics.FOLD).
3
+
4
+ fold(s) merge letter variants that sound the same (ሐ/ኀ/ሃ -> ሀ, ሠ -> ሰ, ዐ/ኣ -> አ, ፀ -> ጸ, ...)
5
+ strip_punct(s) remove punctuation (Ethiopic + ASCII + quotes/dashes), collapse whitespace
6
+ spoken_chars(s) letters and digits only, folded (used for forced alignment and CER)
7
+ cer(ref, hyp) character error rate on spoken_chars
8
+ """
9
+ import re
10
+
11
+ FOLD_MAP = {'ሃ': 'ሀ', 'ሐ': 'ሀ', 'ሑ': 'ሁ', 'ሒ': 'ሂ', 'ሓ': 'ሀ', 'ሔ': 'ሄ', 'ሕ': 'ህ', 'ሖ': 'ሆ', 'ሗ': 'ኋ', 'ሠ': 'ሰ', 'ሡ': 'ሱ', 'ሢ': 'ሲ', 'ሣ': 'ሳ', 'ሤ': 'ሴ', 'ሥ': 'ስ', 'ሦ': 'ሶ', 'ሧ': 'ሷ', 'ቍ': 'ቁ', 'ኀ': 'ሀ', 'ኁ': 'ሁ', 'ኂ': 'ሂ', 'ኃ': 'ሀ', 'ኄ': 'ሄ', 'ኅ': 'ህ', 'ኆ': 'ሆ', 'ኍ': 'ሁ', 'ኣ': 'አ', 'ኵ': 'ኩ', 'ዉ': 'ው', 'ዐ': 'አ', 'ዑ': 'ኡ', 'ዒ': 'ኢ', 'ዓ': 'አ', 'ዔ': 'ኤ', 'ዕ': 'እ', 'ዖ': 'ኦ', 'ጕ': 'ጉ', 'ፀ': 'ጸ', 'ፁ': 'ጹ', 'ፂ': 'ጺ', 'ፃ': 'ጻ', 'ፄ': 'ጼ', 'ፅ': 'ጽ', 'ፆ': 'ጾ', 'ፇ': 'ጿ'}
12
+ _FOLD = str.maketrans(FOLD_MAP)
13
+ PUNCT = '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~«»፠፡።፣፤፥፦፧፨–—‘’“”„…'
14
+ _PUNCT_RE = re.compile("[" + re.escape(PUNCT) + "]")
15
+
16
+
17
+ def fold(s):
18
+ return s.translate(_FOLD)
19
+
20
+
21
+ def strip_punct(s):
22
+ return " ".join(_PUNCT_RE.sub(" ", s).split())
23
+
24
+
25
+ def spoken_chars(s):
26
+ return "".join(c for c in fold(s) if c.isalnum())
27
+
28
+
29
+ def norm_word(w):
30
+ return spoken_chars(strip_punct(fold(w)))
31
+
32
+
33
+ def lev(a, b):
34
+ if len(a) < len(b):
35
+ a, b = b, a
36
+ prev = list(range(len(b) + 1))
37
+ for i, x in enumerate(a, 1):
38
+ cur = [i]
39
+ for j, y in enumerate(b, 1):
40
+ cur.append(min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (x != y)))
41
+ prev = cur
42
+ return prev[-1]
43
+
44
+
45
+ def cer(ref, hyp):
46
+ r, h = spoken_chars(ref), spoken_chars(hyp)
47
+ return lev(r, h) / max(1, len(r))
edit-omnivoice/edit_omnivoice_infer.py ADDED
@@ -0,0 +1,584 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Word-level speech editing ("change the words, keep the voice") for the Ethiopic Voice Studio.
2
+
3
+ Code-only variant: it reuses the weights of a sibling OmniVoice TTS variant, the shared Higgs codec and the ONNX
4
+ amharic-ctc aligner. Expected layout (as in manifest.json):
5
+
6
+ <models>/edit-omnivoice/ this folder
7
+ <models>/tts-omnivoice-fp16/ or tts-omnivoice-fp32 / tts-omnivoice-cpu-int8 (any one)
8
+ <models>/tts-codec-higgs/ found by the TTS variant at ../tts-codec-higgs
9
+ <models>/asr-ctc-1b-onnx-int8/ forced alignment + transcription (CPU, onnxruntime)
10
+
11
+ Python:
12
+ from edit_omnivoice_infer import SpeechEditor
13
+ ed = SpeechEditor("<models>/tts-omnivoice-fp16") # aligner_dir defaults to ../asr-ctc-1b-onnx-int8
14
+ r = ed.transcribe("clip.wav") # {"text", "words": [{"word","start","end"}]}
15
+ out = ed.edit("clip.wav", r["text"], "<edited text>") # {"audio" float32 24 kHz, "sr", "edits", "words", ...}
16
+
17
+ CLI:
18
+ python edit_omnivoice_infer.py --tts <models>/tts-omnivoice-fp16 --audio in.wav --new-text "..." --out out.wav
19
+ [--orig-text "..."] [--num-step 32] [--span-duration 0.8] [--force] [--threads 4]
20
+
21
+ Method (details: amharic-speech-edit README): the edited words' audio is cut at the neighbouring pauses, replaced by
22
+ N masked token frames (N from the local speaking rate), and filled by OmniVoice's iterative unmasking with the audio
23
+ on BOTH sides as context (masked-middle inference) and the new transcript as text; only the regenerated span is
24
+ decoded into the original waveform (20 ms crossfades). Deletions are a cut plus a 0.32 s regeneration around the
25
+ seam. Several changes are edited right to left. Needs: torch, torchaudio, transformers>=5.3, soundfile, omnivoice,
26
+ onnxruntime (aligner); numpy. scipy optional (faster resampling).
27
+ """
28
+ import argparse
29
+ import difflib
30
+ import importlib.util
31
+ import math
32
+ import os
33
+ import sys
34
+ import time
35
+
36
+ import numpy as np
37
+ import torch
38
+
39
+ HERE = os.path.dirname(os.path.abspath(__file__))
40
+ sys.path.insert(0, HERE)
41
+ from amharic_text import cer, fold, norm_word, spoken_chars, strip_punct # noqa: E402
42
+
43
+ SR = 24000
44
+ FPS = 25
45
+ HOP = SR // FPS
46
+ SR16 = 16000
47
+ MAX_SEC = 30.0
48
+ DEFAULT_ALIGNER = "asr-ctc-1b-onnx-int8"
49
+
50
+
51
+ class EditError(ValueError):
52
+ """Raised for requests the editor refuses. `kind` is one of: no_change, too_long, too_short, bad_num_step,
53
+ text_mismatch, alignment_failed, empty_text."""
54
+
55
+ def __init__(self, kind, msg):
56
+ super().__init__(msg)
57
+ self.kind = kind
58
+
59
+
60
+ def _load_module(path, name):
61
+ spec = importlib.util.spec_from_file_location(name, path)
62
+ mod = importlib.util.module_from_spec(spec)
63
+ spec.loader.exec_module(mod)
64
+ return mod
65
+
66
+
67
+ # ---------------------------------------------------------------------------- forced alignment (numpy)
68
+ def viterbi_word_spans(logp, tokens, word_of):
69
+ """CTC Viterbi forced alignment of one utterance. logp: (T, V) log-probs, tokens: target ids (no blanks),
70
+ word_of: word index per token (-1 for the space token). Returns [(first_frame, last_frame) | None] per word, or
71
+ None if the text cannot be aligned. Same algorithm as the research aligner (blank id 0)."""
72
+ T, N = logp.shape[0], len(tokens)
73
+ if N == 0 or T < N:
74
+ return None
75
+ tok = np.asarray(tokens)
76
+ blank = logp[:, 0]
77
+ tok_em = logp[:, tok] # (T, N)
78
+ neg = -np.inf
79
+ tr = np.full((T + 1, N + 1), neg, dtype=np.float32)
80
+ tr[0, 0] = 0.0
81
+ for t in range(T):
82
+ prev = tr[t]
83
+ stay = prev + blank[t]
84
+ move = np.concatenate([[neg], prev[:-1] + tok_em[t]])
85
+ tr[t + 1] = np.maximum(stay, move)
86
+ if not np.isfinite(tr[T, N]):
87
+ return None
88
+ frames = [0] * N
89
+ j = N
90
+ for t in range(T, 0, -1):
91
+ if j == 0:
92
+ break
93
+ stay = tr[t - 1, j] + blank[t - 1]
94
+ move = tr[t - 1, j - 1] + tok_em[t - 1, j - 1]
95
+ if move >= stay:
96
+ j -= 1
97
+ frames[j] = t - 1
98
+ spans = {}
99
+ for f, w in zip(frames, word_of):
100
+ if w < 0:
101
+ continue
102
+ s, e = spans.get(w, (f, f))
103
+ spans[w] = (min(s, f), max(e, f))
104
+ n_words = max(word_of, default=-1) + 1
105
+ return [spans.get(i) for i in range(n_words)]
106
+
107
+
108
+ class OnnxAligner:
109
+ """amharic-ctc v0.3 (ONNX, CPU) transcription + forced word alignment of a given transcript."""
110
+
111
+ def __init__(self, aligner_dir, threads=4):
112
+ mod = _load_module(os.path.join(aligner_dir, "asr_onnx_infer.py"), "_edit_asr_onnx_infer")
113
+ self.mod = mod
114
+ self.asr = mod.OnnxCTCTranscriber(aligner_dir, threads=threads)
115
+ self.char_id = {p: i for i, p in enumerate(self.asr.vocab) if len(p) == 1}
116
+ self.space_id, self.unk_id = mod.SPACE_ID, 3
117
+
118
+ def to16(self, wav24):
119
+ return self.mod.resample(np.asarray(wav24, np.float32), SR, SR16)
120
+
121
+ def logp(self, wav24):
122
+ """One ONNX pass -> (log-probs (T, V), seconds per frame). Audio must be <= 40 s (the editor caps at 30 s)."""
123
+ w16 = self.to16(wav24)
124
+ if len(w16) < 400:
125
+ return None, None
126
+ logits = self.asr.logits(np.ascontiguousarray(w16, np.float32)).astype(np.float32)
127
+ return logits - np.logaddexp.reduce(logits, axis=-1, keepdims=True), (len(w16) / SR16) / logits.shape[0]
128
+
129
+ def transcribe(self, wav24, lp=None):
130
+ """Greedy transcript + word times. Clips over 30 s go through the transcriber's own chunking."""
131
+ if lp is None and len(wav24) > 30 * SR:
132
+ r = self.asr.transcribe(self.to16(wav24), sr=SR16)
133
+ return {"text": r["text"], "words": r["words"], "model_version": r.get("model_version")}
134
+ lp = lp if lp is not None else self.logp(wav24)[0]
135
+ words = [] if lp is None else self.asr.words(lp.argmax(-1).tolist())
136
+ return {"text": " ".join(w["word"] for w in words), "words": words, "model_version": self.asr.version}
137
+
138
+ def align(self, wav24, text, lp=None, spf=None):
139
+ """Per raw whitespace token of `text`: (start_sec, end_sec) or None (no spoken characters). None if the text
140
+ cannot be aligned at all. Pass lp/spf from logp() to reuse one ONNX pass."""
141
+ if lp is None:
142
+ lp, spf = self.logp(wav24)
143
+ if lp is None:
144
+ return None
145
+ logp = lp
146
+ raw = text.split()
147
+ tk, wo, tok_word, k = [], [], [], 0
148
+ for ri, tok in enumerate(raw):
149
+ for part in strip_punct(fold(tok)).split():
150
+ ids = [self.char_id.get(c, self.unk_id) for c in spoken_chars(part)]
151
+ ids = [i for i in ids if i != self.unk_id]
152
+ if not ids:
153
+ continue
154
+ if tk:
155
+ tk.append(self.space_id); wo.append(-1)
156
+ tk += ids; wo += [k] * len(ids); tok_word.append(ri); k += 1
157
+ res = viterbi_word_spans(logp, tk, wo)
158
+ if res is None:
159
+ return None
160
+ out = [None] * len(raw)
161
+ for j, ri in enumerate(tok_word):
162
+ s = res[j]
163
+ if s is None:
164
+ continue
165
+ st, en = s[0] * spf, (s[1] + 1) * spf
166
+ out[ri] = (st, en) if out[ri] is None else (min(out[ri][0], st), max(out[ri][1], en))
167
+ return out
168
+
169
+
170
+ def fill_timings(timings):
171
+ """Untimed tokens (punctuation, Latin script) become zero-length at the previous word's end."""
172
+ out, last = [], 0.0
173
+ nxt, nv = [None] * len(timings), None
174
+ for i in range(len(timings) - 1, -1, -1):
175
+ if timings[i] is not None:
176
+ nv = timings[i][0]
177
+ nxt[i] = nv
178
+ for i, t in enumerate(timings):
179
+ if t is None:
180
+ t = (last, last) if i > 0 or nxt[i] is None else (nxt[i], nxt[i])
181
+ out.append((float(t[0]), float(t[1])))
182
+ last = t[1]
183
+ return out
184
+
185
+
186
+ # ---------------------------------------------------------------------------- editor
187
+ class SpeechEditor:
188
+ def __init__(self, tts_dir, codec_dir=None, aligner_dir=None, device=None, threads=None, num_step=None):
189
+ """tts_dir: a tts-omnivoice-{fp16,fp32,cpu-int8} folder. codec_dir default ../tts-codec-higgs, aligner_dir
190
+ default ../asr-ctc-1b-onnx-int8 (both next to tts_dir). device: torch device for the TTS variant (default
191
+ cuda if available; the cpu-int8 variant always runs on CPU). threads: CPU threads for the aligner (and the
192
+ cpu-int8 backbone). num_step: default decoding steps (default: the TTS variant's recommended value)."""
193
+ tts_dir = os.path.abspath(tts_dir)
194
+ parent = os.path.dirname(tts_dir)
195
+ aligner_dir = aligner_dir or os.path.join(parent, DEFAULT_ALIGNER)
196
+ tmod = _load_module(os.path.join(tts_dir, "tts_omnivoice_infer.py"), "_edit_tts_omnivoice_infer")
197
+ from omnivoice.models.omnivoice import OmniVoiceGenerationConfig, _get_time_steps, _gumbel_sample
198
+ self._gc_cls, self._time_steps, self._gumbel = OmniVoiceGenerationConfig, _get_time_steps, _gumbel_sample
199
+ self.tts = tmod.OmniVoiceTTS(tts_dir, codec_dir, device=device, threads=threads, num_step=num_step)
200
+ self.model, self.device = self.tts.model, self.tts.device
201
+ self.model.audio_tokenizer.float() # the codec must run in fp32 (fp16 decodes garbage)
202
+ self.num_step = self.tts.num_step
203
+ self.cfg = self.model.config
204
+ self.est = self.model.duration_estimator
205
+ self.aligner = OnnxAligner(aligner_dir, threads=threads or 4)
206
+ self.variant = self.tts.meta.get("id", os.path.basename(tts_dir))
207
+
208
+ # ------------------------------------------------------------------ audio io
209
+ def load(self, audio, sr=None):
210
+ """Path (wav/flac/ogg/mp3 via soundfile) or float array (pass sr) -> mono float32 at 24 kHz."""
211
+ if isinstance(audio, (str, os.PathLike)):
212
+ import soundfile as sf
213
+ x, sr = sf.read(str(audio), dtype="float32", always_2d=True)
214
+ x = x.mean(1)
215
+ else:
216
+ x = np.asarray(audio, np.float32)
217
+ if x.ndim == 2:
218
+ x = x.mean(1) if x.shape[1] <= 8 else x.mean(0)
219
+ if sr is None:
220
+ raise ValueError("pass sr= with a raw waveform")
221
+ return np.ascontiguousarray(self.aligner.mod.resample(x, sr, SR) if sr != SR else x, dtype=np.float32)
222
+
223
+ @torch.inference_mode()
224
+ def encode(self, wav):
225
+ fe = self.model.feature_extractor(raw_audio=wav, sampling_rate=SR, return_tensors="pt")
226
+ return self.model.audio_tokenizer.encode(fe["input_values"].to(self.device).float()).audio_codes.squeeze(0)
227
+
228
+ @torch.inference_mode()
229
+ def decode(self, tokens):
230
+ return self.model.audio_tokenizer.decode(tokens.to(self.device).unsqueeze(0)).audio_values[0, 0].float().cpu().numpy()
231
+
232
+ # ------------------------------------------------------------------ public: ASR / alignment
233
+ def transcribe(self, audio, sr=None):
234
+ """-> {"text", "words": [{"word","start","end"}], "model_version"} (greedy amharic-ctc v0.3)."""
235
+ return self.aligner.transcribe(self.load(audio, sr))
236
+
237
+ def align(self, audio, text, sr=None):
238
+ """Forced alignment of `text` -> [{"word","start","end"}] per whitespace token (start/end None for tokens
239
+ without Ethiopic/Latin letters or digits the model knows). Raises EditError("alignment_failed")."""
240
+ wav = self.load(audio, sr)
241
+ t = self.aligner.align(wav, text)
242
+ if t is None:
243
+ raise EditError("alignment_failed", "forced alignment failed: does the text match the audio?")
244
+ return [{"word": w, "start": None if s is None else round(s[0], 3), "end": None if s is None else round(s[1], 3)}
245
+ for w, s in zip(text.split(), t)]
246
+
247
+ # ------------------------------------------------------------------ public: edit
248
+ def edit(self, audio, orig_text, new_text, words=None, span_duration=None, num_step=None, seed=0, sr=None,
249
+ force=False, ctx_sec=6.0, guidance_scale=2.0, speed=1.0):
250
+ """Edit `audio` so it says `new_text` instead of `orig_text`, regenerating only the changed words.
251
+
252
+ audio: path or float array (+ sr). orig_text: transcript of the audio; None/"" -> transcribed with the
253
+ aligner's ASR (returned as "orig_text"). words: optional timings of orig_text, one per whitespace token
254
+ ([{"word","start","end"}] as returned by transcribe()/align()/edit(), or [(start, end) | None]); given, the
255
+ aligner pass and the orig_text-vs-ASR check are skipped (about half the latency of a GPU edit). Chain
256
+ edits by passing the previous result's audio, new_text and words. span_duration: seconds for the new span (single-change edits
257
+ only; default from the local speaking rate). num_step >= 16 (default: variant's recommendation).
258
+ force: skip the orig_text-vs-ASR check (CER > 0.6 refused otherwise).
259
+
260
+ Returns {"audio": float32 (n,), "sr": 24000, "orig_text", "orig_text_transcribed", "new_text",
261
+ "edits": [{"span_in": [s, e] (input seconds replaced), "span_out": [s, e] (output seconds),
262
+ "orig_words", "new_words"}] (left to right), "words": [{"word","start","end","aligned"}]
263
+ of the output (unchanged words: shifted input timings; new words: aligned in a short window;
264
+ aligned=False means an even split of the span because that window failed), "orig_text_cer_vs_asr",
265
+ "latency_sec" (whole call incl. alignment), "num_step"}.
266
+ Raises EditError (kind: empty_text, too_long, too_short, bad_num_step, no_change, text_mismatch,
267
+ alignment_failed)."""
268
+ num_step = int(num_step or self.num_step)
269
+ if num_step < 16:
270
+ raise EditError("bad_num_step", "num_step must be >= 16 (8 steps clearly degrades quality)")
271
+ new_text = " ".join((new_text or "").split())
272
+ if not new_text:
273
+ raise EditError("empty_text", "new_text is empty")
274
+ wav = self.load(audio, sr)
275
+ if len(wav) > MAX_SEC * SR:
276
+ raise EditError("too_long", f"audio is {len(wav) / SR:.1f} s; the limit is {MAX_SEC:.0f} s "
277
+ "(cut the recording into sentences and edit the one that changes)")
278
+ if len(wav) < 0.5 * SR:
279
+ raise EditError("too_short", "audio is shorter than 0.5 s")
280
+ t0 = time.perf_counter()
281
+ transcribed, orig_cer = False, None
282
+ if words is not None: # caller's timings (from transcribe()/align()/a previous edit()): no ASR pass, no check
283
+ orig_text = " ".join((orig_text or "").split())
284
+ if not orig_text:
285
+ raise EditError("empty_text", "orig_text is required when words are given")
286
+ if len(words) != len(orig_text.split()):
287
+ raise EditError("text_mismatch", f"{len(words)} word timings for {len(orig_text.split())} words")
288
+ tim = [None if w is None else ((w["start"], w["end"]) if isinstance(w, dict) else tuple(w)) for w in words]
289
+ tim = [None if t is None or t[0] is None else t for t in tim]
290
+ else:
291
+ lp, spf = self.aligner.logp(wav) # one ONNX pass for both the ASR check and the alignment
292
+ asr = self.aligner.transcribe(wav, lp)["text"]
293
+ transcribed = not (orig_text or "").strip()
294
+ orig_text = asr if transcribed else " ".join(orig_text.split())
295
+ if not orig_text:
296
+ raise EditError("empty_text", "no speech recognised in the audio")
297
+ orig_cer = round(cer(orig_text, asr), 3)
298
+ if orig_cer > 0.6 and not force:
299
+ raise EditError("text_mismatch", f"orig_text does not match the audio (CER {orig_cer} against the ASR "
300
+ f"transcript '{asr}'); fix it or pass force=True")
301
+ if [norm_word(w) for w in orig_text.split()] == [norm_word(w) for w in new_text.split()]:
302
+ raise EditError("no_change", "new_text has no word changes against orig_text")
303
+ if words is None:
304
+ tim = self.aligner.align(wav, orig_text, lp, spf)
305
+ if tim is None:
306
+ raise EditError("alignment_failed", "forced alignment of orig_text failed: does it match the audio?")
307
+ out, edits, out_tim, is_new = self._edit_groups(wav, orig_text, new_text, fill_timings(tim), span_duration,
308
+ num_step, seed, ctx_sec, guidance_scale, speed)
309
+ out = np.clip(out, -1.0, 1.0).astype(np.float32)
310
+ words = self._output_words(out, new_text.split(), out_tim, is_new)
311
+ latency = time.perf_counter() - t0
312
+ return {"audio": out, "sr": SR, "orig_text": orig_text, "orig_text_transcribed": transcribed,
313
+ "new_text": new_text, "edits": edits, "words": words,
314
+ "orig_text_cer_vs_asr": orig_cer, "latency_sec": round(latency, 3), "num_step": num_step}
315
+
316
+ def _output_words(self, out, words, tim, is_new):
317
+ """Word timings of the output: unchanged words keep their (shifted) input timings; the generated words are
318
+ force-aligned in a short window (the new words plus one neighbour each side, +-0.15 s), which costs a
319
+ fraction of a full aligner pass. Words whose window fails keep an even split of the generated span."""
320
+ tim = [list(t) for t in tim]
321
+ exact = [g < 0 for g in is_new]
322
+ for g in sorted(set(x for x in is_new if x >= 0)):
323
+ idx = [i for i, x in enumerate(is_new) if x == g]
324
+ lo, hi = max(0, idx[0] - 1), min(len(words), idx[-1] + 2)
325
+ a = max(0.0, tim[lo][0] - 0.15)
326
+ b = min(len(out) / SR, tim[hi - 1][1] + 0.15)
327
+ r = self.aligner.align(out[int(a * SR):int(b * SR)], " ".join(words[lo:hi]))
328
+ if r is None:
329
+ continue
330
+ for j, t in zip(range(lo, hi), r):
331
+ if t is not None:
332
+ tim[j] = [a + t[0], a + t[1]]
333
+ exact[j] = True
334
+ return [{"word": w, "start": round(t[0], 3), "end": round(t[1], 3), "aligned": ex}
335
+ for w, t, ex in zip(words, tim, exact)]
336
+
337
+ # ------------------------------------------------------------------ internals
338
+ def _edit_groups(self, wav, orig_text, new_text, tim, span_duration, num_step, seed, ctx_sec, gs, speed):
339
+ peak = float(np.abs(wav).max()) + 1e-7
340
+ gain = 0.9 / peak # same peak normalisation as the training tokens; undone at the end
341
+ cur = wav * gain
342
+ ow, nw = orig_text.split(), new_text.split()
343
+ sm = difflib.SequenceMatcher(a=[norm_word(w) for w in ow], b=[norm_word(w) for w in nw], autojunk=False)
344
+ groups = []
345
+ for op, i1, i2, j1, j2 in sm.get_opcodes():
346
+ if op == "equal":
347
+ continue
348
+ if groups and i1 - groups[-1][1] <= 1 and j1 - groups[-1][3] <= 1: # merge changes <= 1 word apart
349
+ g = groups[-1]
350
+ groups[-1] = (g[0], i2, g[2], j2)
351
+ else:
352
+ groups.append((i1, i2, j1, j2))
353
+ if span_duration is not None and len(groups) != 1:
354
+ span_duration = None # only meaningful for a single change
355
+ edits, cur_words, shifted = [], list(ow), None
356
+ is_new = [-1] * len(ow) # per current word: index of the edit group that generated it, -1 = original
357
+ # Right to left: the word indices of the groups still to do are unchanged. Between groups, words left of the
358
+ # last edit keep their times, words to its right shift by the length change, and its generated words are
359
+ # force-aligned in a short window (if that fails they share the generated span evenly).
360
+ for gi, (i1, i2, j1, j2) in enumerate(reversed(groups)):
361
+ if gi > 0: # refresh: shifted timings, generated words re-aligned in a short window
362
+ tim = [(w["start"], w["end"]) for w in self._output_words(cur, cur_words, shifted, is_new)]
363
+ new_w = nw[j1:j2]
364
+ before = len(cur)
365
+ cur, e = self._edit_one(cur, cur_words, tim, i1, i2, new_w, span_duration, num_step, seed, ctx_sec, gs,
366
+ speed)
367
+ delta = (len(cur) - before) / SR
368
+ for p in edits:
369
+ p["span_out"] = [round(p["span_out"][0] + delta, 3), round(p["span_out"][1] + delta, 3)]
370
+ s0, s1 = e["span_out"]
371
+ k = len(new_w)
372
+ shifted = (tim[:i1] + [(s0 + (s1 - s0) * q / max(k, 1), s0 + (s1 - s0) * (q + 1) / max(k, 1))
373
+ for q in range(k)] + [(a + delta, b + delta) for a, b in tim[i2:]])
374
+ e["orig_words"] = ow[i1:i2]
375
+ cur_words = cur_words[:i1] + new_w + cur_words[i2:]
376
+ is_new = is_new[:i1] + [len(groups) - 1 - gi] * k + is_new[i2:]
377
+ edits.append(e)
378
+ edits.reverse()
379
+ return cur / gain, edits, shifted, is_new
380
+
381
+ @torch.inference_mode()
382
+ def _generate(self, text, seq, gen_pos, num_step, gs, seed, t_shift=0.1, layer_penalty=5.0, pos_temp=5.0):
383
+ """Fill frames gen_pos of seq [8, T] by iterative unmasking; text CFG whose unconditional branch keeps the
384
+ audio context (no style/text)."""
385
+ torch.manual_seed(seed)
386
+ C, mask_id = self.cfg.num_audio_codebook, self.cfg.audio_mask_id
387
+ dev = self.device
388
+ seq = seq.clone().to(dev)
389
+ gen_pos = gen_pos.to(dev)
390
+ seq[:, gen_pos] = mask_id
391
+ tok = self.model.text_tokenizer
392
+ st = tok("<|lang_start|>am<|lang_end|><|instruct_start|>None<|instruct_end|>", return_tensors="pt").input_ids
393
+ tx = tok(f"<|text_start|>{text}<|text_end|>", return_tensors="pt").input_ids
394
+ pre = torch.cat([st, tx], 1).repeat(C, 1).to(dev)
395
+ P, T = pre.shape[1], seq.shape[1]
396
+ L = P + T
397
+ ids = torch.full((2, C, L), mask_id, dtype=torch.long, device=dev)
398
+ amask = torch.zeros(2, L, dtype=torch.bool, device=dev)
399
+ att = torch.zeros(2, 1, L, L, dtype=torch.bool, device=dev)
400
+ ids[0, :, :P] = pre
401
+ ids[0, :, P:] = seq
402
+ amask[0, P:] = True
403
+ att[0] = True
404
+ ids[1, :, :T] = seq
405
+ amask[1, :T] = True
406
+ att[1, :, :T, :T] = True
407
+ d = torch.arange(T, L, device=dev)
408
+ att[1, :, d, d] = True
409
+ c_idx, u_idx = P + gen_pos, gen_pos
410
+ n = len(gen_pos)
411
+ total = n * C
412
+ ts = self._time_steps(0.0, 1.0, num_step, t_shift).tolist()
413
+ sched, rem = [], total
414
+ for s in range(num_step):
415
+ k = rem if s == num_step - 1 else min(math.ceil(total * (ts[s + 1] - ts[s])), rem)
416
+ sched.append(int(k)); rem -= int(k)
417
+ layer_ids = torch.arange(C, device=dev).view(1, -1, 1)
418
+ cur = torch.full((1, C, n), mask_id, dtype=torch.long, device=dev)
419
+ gc = self._gc_cls(num_step=num_step, guidance_scale=gs, t_shift=t_shift, layer_penalty_factor=layer_penalty,
420
+ position_temperature=pos_temp)
421
+ for s in range(num_step):
422
+ k = sched[s]
423
+ if k <= 0:
424
+ continue
425
+ logits = self.model(input_ids=ids, audio_mask=amask, attention_mask=att).logits.to(torch.float32)
426
+ pred, scores = self.model._predict_tokens_with_scoring(logits[0:1, :, c_idx, :], logits[1:2, :, u_idx, :], gc)
427
+ scores = scores - layer_ids * layer_penalty
428
+ if pos_temp > 0:
429
+ scores = self._gumbel(scores, pos_temp)
430
+ scores.masked_fill_(cur != mask_id, -float("inf"))
431
+ _, top = torch.topk(scores.flatten(), k)
432
+ flat = cur.flatten()
433
+ flat[top] = pred.flatten()[top]
434
+ cur = flat.view_as(cur)
435
+ ids[0, :, c_idx] = cur[0]
436
+ ids[1, :, u_idx] = cur[0]
437
+ seq[:, gen_pos] = cur[0]
438
+ return seq
439
+
440
+ def _rate(self, words, tim, lo, hi, ctx_sec, a_t, b_t):
441
+ """(weight per frame over context words only, median context pause in frames) or None."""
442
+ ctx = [i for i in range(len(words)) if tim[i][1] > tim[i][0] and
443
+ ((i < lo and tim[i][1] >= a_t - ctx_sec) or (i >= hi and tim[i][0] <= b_t + ctx_sec))]
444
+ wt = sum(self.est.calculate_total_weight(words[i]) for i in ctx)
445
+ du = sum(tim[i][1] - tim[i][0] for i in ctx) * FPS
446
+ if not ctx or du <= 0.3 * FPS or wt <= 0:
447
+ return None
448
+ cs = set(ctx)
449
+ gaps = [tim[i][0] - tim[i - 1][1] for i in range(1, len(words)) if i in cs and i - 1 in cs]
450
+ mg = float(np.median([max(0.0, g) for g in gaps])) * FPS if gaps else 0.05 * FPS
451
+ return wt / du, mg
452
+
453
+ @staticmethod
454
+ def _crop(tim, lo, hi, cut_l, cut_r, ctx_sec, dur):
455
+ n = len(tim)
456
+
457
+ def gap_mid(i):
458
+ if i <= 0:
459
+ return 0.0
460
+ if i >= n:
461
+ return dur
462
+ return 0.5 * (tim[i - 1][1] + tim[i][0])
463
+
464
+ a = lo
465
+ while a > 0 and cut_l - gap_mid(a - 1) <= ctx_sec:
466
+ a -= 1
467
+ b = hi
468
+ while b < n and gap_mid(b + 1) - cut_r <= ctx_sec:
469
+ b += 1
470
+ return a, b, min(gap_mid(a), cut_l), max(gap_mid(b), cut_r)
471
+
472
+ def _edit_one(self, wav, words, tim, i1, i2, new_w, span_duration, num_step, seed, ctx_sec, gs, speed,
473
+ seam_window=0.32, crossfade=0.02):
474
+ dur = len(wav) / SR
475
+ n = len(words)
476
+ prev_end = tim[i1 - 1][1] if i1 > 0 else 0.0
477
+ next_start = tim[i2][0] if i2 < n else dur
478
+ if i2 > i1: # replace / delete: cut half-way into the neighbouring pauses (max 0.3 s)
479
+ w0, w1 = tim[i1][0], tim[i2 - 1][1]
480
+ cut_l = w0 - min(max(0.0, w0 - prev_end) / 2, 0.3)
481
+ cut_r = w1 + min(max(0.0, next_start - w1) / 2, 0.3)
482
+ pad = (w0 - cut_l) + (cut_r - w1)
483
+ else: # insert at the middle of the pause
484
+ if i1 == 0:
485
+ c = max(0.0, next_start - min(next_start / 2, 0.15))
486
+ elif i1 == n:
487
+ c = min(dur, prev_end + min((dur - prev_end) / 2, 0.15))
488
+ else:
489
+ c = 0.5 * (prev_end + next_start)
490
+ cut_l = cut_r = c
491
+ pad = None
492
+ cl, cr = int(round(cut_l * FPS)), int(round(cut_r * FPS))
493
+ if new_w:
494
+ if span_duration is not None:
495
+ N = max(2, int(round(span_duration * FPS)))
496
+ else:
497
+ r = self._rate(words, tim, i1, i2, ctx_sec, cut_l, cut_r) or self._rate(words, tim, 0, 0, 1e9, 0, 0)
498
+ rate, mg = r if r is not None else (1.5, 2.0)
499
+ wf = sum(self.est.calculate_total_weight(w) for w in new_w) / rate
500
+ gap_frames = (len(new_w) - 1) * mg + (mg if pad is None else pad * FPS)
501
+ N = max(3, int(round(wf / speed + gap_frames)))
502
+ else:
503
+ N = 0
504
+ a, b, crop_l, crop_r = self._crop(tim, i1, i2, cut_l, cut_r, ctx_sec, dur)
505
+ c0, c1 = int(round(crop_l * FPS)), int(round(crop_r * FPS))
506
+ m0, m1 = max(0, c0 - FPS), int(round(min(dur, crop_r + 1.0) * FPS))
507
+ tokens = self.encode(wav[m0 * HOP: m1 * HOP])
508
+ left, right = tokens[:, c0 - m0: cl - m0], tokens[:, cr - m0: c1 - m0]
509
+ text = " ".join(words[a:i1] + new_w + words[i2:b])
510
+ if N > 0:
511
+ seq = torch.cat([left, torch.full((tokens.shape[0], N), self.cfg.audio_mask_id, device=tokens.device,
512
+ dtype=tokens.dtype), right], 1)
513
+ gp = torch.arange(left.shape[1], left.shape[1] + N)
514
+ else: # delete: cut, then regenerate a short window centred on the seam
515
+ seq = torch.cat([left, right], 1)
516
+ gp = None
517
+ if left.shape[1] and right.shape[1]:
518
+ W = max(2, int(round(seam_window * FPS)))
519
+ g0 = max(0, left.shape[1] - W // 2)
520
+ gp = torch.arange(g0, min(seq.shape[1], g0 + W))
521
+ xf = int(crossfade * SR)
522
+ L0 = cl * HOP
523
+ if gp is None or not len(gp):
524
+ out = np.concatenate([wav[:L0], wav[cr * HOP:]])
525
+ span = (L0 / SR, L0 / SR)
526
+ else:
527
+ gen0, gen1 = int(gp[0]), int(gp[-1]) + 1
528
+ dec = self.decode(self._generate(text, seq, gp, num_step, gs, seed))
529
+ seg = dec[gen0 * HOP: gen1 * HOP]
530
+ if N == 0:
531
+ lk = wav[:(c0 + gen0) * HOP]
532
+ rk = wav[(cr + (gen1 - left.shape[1])) * HOP:]
533
+ else:
534
+ lk, rk = wav[:L0], wav[cr * HOP:]
535
+ d0, d1 = gen0 * HOP, gen1 * HOP
536
+ ramp = np.sin(np.linspace(0, np.pi / 2, xf)) ** 2 if xf > 0 else None
537
+ if xf > 0 and d0 >= xf and len(lk) >= xf:
538
+ lk = lk.copy(); lk[-xf:] = lk[-xf:] * (1 - ramp) + dec[d0 - xf:d0] * ramp
539
+ if xf > 0 and len(dec) >= d1 + xf and len(rk) >= xf:
540
+ rk = rk.copy(); rk[:xf] = dec[d1:d1 + xf] * (1 - ramp) + rk[:xf] * ramp
541
+ out = np.concatenate([lk, seg, rk])
542
+ span = (len(lk) / SR, (len(lk) + len(seg)) / SR)
543
+ return out.astype(np.float32), {"span_in": [round(cut_l, 3), round(cut_r, 3)],
544
+ "span_out": [round(span[0], 3), round(span[1], 3)], "new_words": new_w}
545
+
546
+
547
+ def main():
548
+ ap = argparse.ArgumentParser(description="Edit the words of an Amharic recording (OmniVoice masked-middle).")
549
+ ap.add_argument("--tts", required=True, help="tts-omnivoice-{fp16,fp32,cpu-int8} folder")
550
+ ap.add_argument("--audio", required=True)
551
+ ap.add_argument("--new-text", help="edited transcript (omit to only print the transcript)")
552
+ ap.add_argument("--orig-text", default=None, help="transcript of --audio (default: ASR)")
553
+ ap.add_argument("--out", default="edited.wav")
554
+ ap.add_argument("--codec", default=None)
555
+ ap.add_argument("--aligner", default=None)
556
+ ap.add_argument("--num-step", type=int, default=None)
557
+ ap.add_argument("--span-duration", type=float, default=None)
558
+ ap.add_argument("--threads", type=int, default=None)
559
+ ap.add_argument("--device", default=None)
560
+ ap.add_argument("--force", action="store_true")
561
+ ap.add_argument("--seed", type=int, default=0)
562
+ a = ap.parse_args()
563
+ import json
564
+ import soundfile as sf
565
+ t = time.perf_counter()
566
+ ed = SpeechEditor(a.tts, a.codec, a.aligner, device=a.device, threads=a.threads, num_step=a.num_step)
567
+ print(f"loaded {ed.variant} in {time.perf_counter() - t:.1f} s", file=sys.stderr)
568
+ if not a.new_text:
569
+ print(json.dumps(ed.transcribe(a.audio), ensure_ascii=False))
570
+ return
571
+ try:
572
+ r = ed.edit(a.audio, a.orig_text, a.new_text, span_duration=a.span_duration, num_step=a.num_step,
573
+ seed=a.seed, force=a.force)
574
+ except EditError as e:
575
+ print(f"refused ({e.kind}): {e}", file=sys.stderr)
576
+ sys.exit(2)
577
+ sf.write(a.out, r["audio"], r["sr"])
578
+ print(json.dumps({k: v for k, v in r.items() if k != "audio"}, ensure_ascii=False))
579
+ print(f"{a.out}: {len(r['audio']) / SR:.2f} s, edit {r['latency_sec']:.2f} s ({r['num_step']} steps)",
580
+ file=sys.stderr)
581
+
582
+
583
+ if __name__ == "__main__":
584
+ main()