High-Quality Voice Cloning TTS for 600+ Languages
Python
Add CI workflows (PyPI publish, pre-commit) and format codebase with ruff
Han Zhu9c3ab463713d
diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.ymlindex 3c5887b..07d3b99 100644--- a/.github/ISSUE_TEMPLATE/bug_report.yml+++ b/.github/ISSUE_TEMPLATE/bug_report.yml@@ -47,4 +47,4 @@ body:label: ❌ Actual Behaviorplaceholder: Describe in detail what actually happened.validations:- required: false\ No newline at end of file+ required: falsediff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.ymlindex 2809a71..c761d10 100644--- a/.github/ISSUE_TEMPLATE/feature_request.yml+++ b/.github/ISSUE_TEMPLATE/feature_request.yml@@ -31,7 +31,7 @@ body:attributes:label: 2. What is your suggested solution?description: |- Provide a clear description of the feature or enhancement you'd like to propose.+ Provide a clear description of the feature or enhancement you'd like to propose.How would this feature solve your issue or improve the project?placeholder: Describe your idea or proposed solution here.validations:@@ -41,7 +41,7 @@ body:attributes:label: 3. Additional context or commentsdescription: |- Any other relevant information, links, documents, or screenshots that provide clarity.+ Any other relevant information, links, documents, or screenshots that provide clarity.Use this section for anything not covered above.placeholder: Add any extra details here.validations:@@ -59,4 +59,4 @@ body:- type: markdownattributes:value: |- **Note:** Please submit only one request per issue to keep discussions focused and manageable.\ No newline at end of file+ **Note:** Please submit only one request per issue to keep discussions focused and manageable.diff --git a/.github/ISSUE_TEMPLATE/help_wanted.yml b/.github/ISSUE_TEMPLATE/help_wanted.ymlindex 4efe94a..911642a 100644--- a/.github/ISSUE_TEMPLATE/help_wanted.yml+++ b/.github/ISSUE_TEMPLATE/help_wanted.yml@@ -49,4 +49,4 @@ body:label: ❌ Actual Behaviorplaceholder: Describe what actually happened in detail, failure messages, etc.validations:- required: false\ No newline at end of file+ required: falsediff --git a/.github/workflows/pre-commit.yaml b/.github/workflows/pre-commit.yamlnew file mode 100644index 0000000..c1978f8--- /dev/null+++ b/.github/workflows/pre-commit.yaml@@ -0,0 +1,14 @@+name: pre-commit++on:+ pull_request:+ push:+ branches: [master]++jobs:+ pre-commit:+ runs-on: ubuntu-latest+ steps:+ - uses: actions/checkout@v4+ - uses: actions/setup-python@v5+ - uses: pre-commit/[email protected]diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.ymlnew file mode 100644index 0000000..4e09eb6--- /dev/null+++ b/.github/workflows/publish.yml@@ -0,0 +1,44 @@+name: Publish to PyPI++on:+ release:+ types: [published]+ workflow_dispatch:++jobs:+ build:+ runs-on: ubuntu-latest+ steps:+ - uses: actions/checkout@v4++ - uses: actions/setup-python@v5+ with:+ python-version: "3.x"++ - name: Install build dependencies+ run: pip install hatchling build twine++ - name: Build package+ run: python -m build++ - name: Validate distribution metadata+ run: twine check dist/*++ - uses: actions/upload-artifact@v4+ with:+ name: dist+ path: dist/++ publish:+ needs: build+ runs-on: ubuntu-latest+ environment: pypi+ permissions:+ id-token: write+ steps:+ - uses: actions/download-artifact@v4+ with:+ name: dist+ path: dist/++ - uses: pypa/gh-action-pypi-publish@release/v1diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yamlnew file mode 100644index 0000000..381074b--- /dev/null+++ b/.pre-commit-config.yaml@@ -0,0 +1,17 @@+repos:+ - repo: https://github.com/astral-sh/ruff-pre-commit+ rev: v0.11.13+ hooks:+ - id: ruff+ args: ["--fix"]+ exclude: ^(docs|examples)/+ - id: ruff-format+ exclude: ^(docs|examples)/++ - repo: https://github.com/pre-commit/pre-commit-hooks+ rev: v5.0.0+ hooks:+ - id: check-executables-have-shebangs+ - id: end-of-file-fixer+ - id: mixed-line-ending+ - id: trailing-whitespacediff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdnew file mode 100644index 0000000..0d845dc--- /dev/null+++ b/CONTRIBUTING.md@@ -0,0 +1,25 @@+# Contributing to OmniVoice++Thank you for your interest in contributing to OmniVoice! We use pre-commit hooks to ensure code quality and consistency. Before contributing, please follow these guidelines to enable and use the pre-commit hooks.++## Setup++```bash+pip install pre-commit+pre-commit install+```++This enables automatic code style checks (linting, formatting, trailing whitespace, etc.) on every `git commit`.++Before committing, run:++```bash+pre-commit run --all-files+```++This will auto-fix any style issues. Then stage and commit as usual:++```bash+git add .+git commit -m "your message"+```diff --git a/README.md b/README.mdindex 1f47371..f8c9689 100644--- a/README.md+++ b/README.md@@ -314,6 +314,12 @@ See [examples/](examples/) for the complete pipeline — from data preparation t---+## Contributing++We welcome contributions! See [CONTRIBUTING.md](CONTRIBUTING.md) for how to get started.++---+## Discussion & CommunicationYou can directly discuss on [GitHub Issues](https://github.com/k2-fsa/OmniVoice/issues).diff --git a/docs/OmniVoice.ipynb b/docs/OmniVoice.ipynbindex b440f31..3c9f7c0 100644--- a/docs/OmniVoice.ipynb+++ b/docs/OmniVoice.ipynb@@ -141,4 +141,4 @@},"nbformat": 4,"nbformat_minor": 0-}\ No newline at end of file+}diff --git a/docs/data_preparation.md b/docs/data_preparation.mdindex 3ee972b..f63f5c9 100644--- a/docs/data_preparation.md+++ b/docs/data_preparation.md@@ -179,4 +179,4 @@ After creating WebDataset shards, write a data config JSON that references them:See [examples/config/](../examples/config/) for ready-to-use data config files.-> See [docs/data_preparation_advanced.md](../docs/data_preparation_advanced.md) for denoising and noise augmentation.\ No newline at end of file+> See [docs/data_preparation_advanced.md](../docs/data_preparation_advanced.md) for denoising and noise augmentation.diff --git a/docs/data_preparation_advanced.md b/docs/data_preparation_advanced.mdindex e7cc3ca..8d8403b 100644--- a/docs/data_preparation_advanced.md+++ b/docs/data_preparation_advanced.md@@ -18,7 +18,7 @@ Step 2: Tokenize (with optional noise augmentation)```-## Denoise+## DenoiseUse the [Sidon](https://github.com/sarulab-speech/Sidon) speech enhancement model to remove background noise from raw audio.diff --git a/docs/evaluation.md b/docs/evaluation.mdindex 71902b2..cddbb8f 100644--- a/docs/evaluation.md+++ b/docs/evaluation.md@@ -45,4 +45,4 @@ Measures how intelligible the generated speech is by transcribing it with an ASRCosine similarity between speaker embeddings (ECAPA-TDNN + WavLM) of the reference and generated audio. Higher is better.### UTMOS (Predicted MOS)-Neural network that predicts Mean Opinion Score from audio. Higher is better.\ No newline at end of file+Neural network that predicts Mean Opinion Score from audio. Higher is better.diff --git a/docs/tips.md b/docs/tips.mdindex 2fca43e..90a49fa 100644--- a/docs/tips.md+++ b/docs/tips.md@@ -1,10 +1,10 @@# Tips & Notes-- **Combination of `ref_audio` and `instruct`**:+- **Combination of `ref_audio` and `instruct`**:When both `ref_audio` and `instruct` are provided and they **conflict**, the model will most likely follow the style of the reference audio. When the two are **consistent**, `instruct` can improve cloning stability for the attributes it describes. A typical example is **Chinese dialect cloning**: provide both dialect reference audio and a matching dialect instruct (e.g., `ref_audio="sichuan.wav", instruct="四川话"`) for more stable dialect output.- **Short Audio Generation**:The model may not reliably generate short audio clips (e.g., 1–2 seconds) without reference audio. If you need to generate short clips, provide reference audio to the model.- **Min Nan Chinese (Hokkien) Input Format**:- Min Nan Chinese (闽南语, also known as Hokkien) can only be synthesized using [Tai-lo romanization](https://en.wikipedia.org/wiki/T%C3%A2i-l%C3%B4) as input; Chinese characters are not supported for Min Nan Chinese in the current model version.\ No newline at end of file+ Min Nan Chinese (闽南语, also known as Hokkien) can only be synthesized using [Tai-lo romanization](https://en.wikipedia.org/wiki/T%C3%A2i-l%C3%B4) as input; Chinese characters are not supported for Min Nan Chinese in the current model version.diff --git a/docs/training.md b/docs/training.mdindex 417d1a3..9339e51 100644--- a/docs/training.md+++ b/docs/training.md@@ -2,7 +2,7 @@## Training Config-All training is controlled by a JSON training config file and a JSON data config file.+All training is controlled by a JSON training config file and a JSON data config file.See [examples/config/](../examples/config/) for ready-to-use configs.diff --git a/examples/README.md b/examples/README.mdindex 0ec793f..00f6485 100644--- a/examples/README.md+++ b/examples/README.md@@ -117,4 +117,3 @@ bash examples/run_eval.sh```> See [docs/evaluation.md](../docs/evaluation.md) for metrics details, test set preparation, and running individual metrics.-diff --git a/examples/config/data_config_emilia.json b/examples/config/data_config_emilia.jsonindex 665dd76..3af0a02 100644--- a/examples/config/data_config_emilia.json+++ b/examples/config/data_config_emilia.json@@ -1,5 +1,5 @@{- "train":+ "train":[{"language_id": "en",diff --git a/examples/run_emilia.sh b/examples/run_emilia.shindex 40b869d..79faabd 100755--- a/examples/run_emilia.sh+++ b/examples/run_emilia.sh@@ -112,4 +112,4 @@ if [ $stage -le 2 ] && [ $stop_stage -ge 2 ]; then--train_config ${TRAIN_CONFIG} \--data_config ${data_config} \--output_dir ${OUTPUT_DIR}-fi\ No newline at end of file+fidiff --git a/examples/run_eval.sh b/examples/run_eval.shindex 23a0fdf..4f8df45 100755--- a/examples/run_eval.sh+++ b/examples/run_eval.sh@@ -11,7 +11,7 @@set -euo pipefail-# Specify the stages to run by setting the `stage` and `stop_stage` variables.+# Specify the stages to run by setting the `stage` and `stop_stage` variables.stage=1stop_stage=6diff --git a/omnivoice/cli/demo.py b/omnivoice/cli/demo.pyindex 8dd3f2c..6f79800 100644--- a/omnivoice/cli/demo.py+++ b/omnivoice/cli/demo.py@@ -154,7 +154,6 @@ def build_demo(checkpoint: str,generate_fn=None,) -> gr.Blocks:-sampling_rate = model.sampling_rate# -- shared generation core --@@ -257,8 +256,7 @@ def build_demo(value=None,label="Duration (seconds)",info=(- "Leave empty to use speed."- " Set a fixed duration to override speed."+ "Leave empty to use speed. Set a fixed duration to override speed."),)ns = gr.Slider(@@ -333,7 +331,7 @@ by Xiaomi AI Lab Next-gen Kaldi team."</span>")vc_ref_text = gr.Textbox(- label=("Reference Text (optional)" " / 参考音频文本(可选)"),+ label=("Reference Text (optional) / 参考音频文本(可选)"),lines=2,placeholder="Transcript of the reference audio. Leave empty"" to auto-transcribe via ASR models.",diff --git a/omnivoice/cli/infer_batch.py b/omnivoice/cli/infer_batch.pyindex b1d19d6..94a0d82 100644--- a/omnivoice/cli/infer_batch.py+++ b/omnivoice/cli/infer_batch.py@@ -377,7 +377,9 @@ def run_inference_batch(audios = worker_model.generate(text=texts,language=langs,- ref_audio=ref_audio_paths if any(p is not None for p in ref_audio_paths) else None,+ ref_audio=ref_audio_paths+ if any(p is not None for p in ref_audio_paths)+ else None,ref_text=ref_texts if any(t is not None for t in ref_texts) else None,duration=durations if any(d is not None for d in durations) else None,speed=speeds if any(s is not None for s in speeds) else None,diff --git a/omnivoice/data/batching.py b/omnivoice/data/batching.pyindex 6f78cbf..60a4586 100644--- a/omnivoice/data/batching.py+++ b/omnivoice/data/batching.py@@ -84,7 +84,6 @@ class StreamLengthGroupDataset(WrappedIterableDataset):self.dataset.set_epoch(epoch)def _get_bucket_id(self, length: float) -> int:-return bisect.bisect_left(self.boundaries, length)def __iter__(self) -> Iterator[List[Dict[str, Any]]]:diff --git a/omnivoice/data/collator.py b/omnivoice/data/collator.pyindex c1cac27..174abeb 100644--- a/omnivoice/data/collator.py+++ b/omnivoice/data/collator.py@@ -82,20 +82,22 @@ class PaddingDataCollator:valid[i, :length] = True# Stack into [B, C, max_len] / [B, max_len]- input_ids = torch.stack(padded_input_ids, dim=0) # [B, C, max_len]- labels = torch.stack(padded_labels, dim=0) # [B, C, max_len]- audio_mask = torch.stack(padded_audio_mask, dim=0) # [B, max_len]- position_ids = torch.stack(padded_position_ids, dim=0) # [B, max_len]+ input_ids = torch.stack(padded_input_ids, dim=0) # [B, C, max_len]+ labels = torch.stack(padded_labels, dim=0) # [B, C, max_len]+ audio_mask = torch.stack(padded_audio_mask, dim=0) # [B, max_len]+ position_ids = torch.stack(padded_position_ids, dim=0) # [B, max_len]# 4D bidirectional attention mask: mask[b, 0, i, j] = valid[b, j]# All query positions attend to all non-padding key positions.- attention_mask = valid[:, None, None, :].expand(B, 1, max_len, max_len).contiguous()+ attention_mask = (+ valid[:, None, None, :].expand(B, 1, max_len, max_len).contiguous()+ )return {- "input_ids": input_ids, # [B, C, max_len]- "labels": labels, # [B, C, max_len]- "audio_mask": audio_mask, # [B, max_len]- "position_ids": position_ids, # [B, max_len]+ "input_ids": input_ids, # [B, C, max_len]+ "labels": labels, # [B, C, max_len]+ "audio_mask": audio_mask, # [B, max_len]+ "position_ids": position_ids, # [B, max_len]"attention_mask": attention_mask, # [B, 1, max_len, max_len]}@@ -106,7 +108,6 @@ class PackingDataCollator:self.processor = processordef __call__(self, processed_samples: List[Dict[str, Any]]) -> Dict[str, Any]:-target_length = self.batch_tokensinput_ids = torch.cat(diff --git a/omnivoice/data/dataset.py b/omnivoice/data/dataset.pyindex f3811e9..e510e2b 100644--- a/omnivoice/data/dataset.py+++ b/omnivoice/data/dataset.py@@ -339,7 +339,6 @@ class WebDatasetReader(IterableDataReader):random.Random(epoch).shuffle(self.urls)def __iter__(self) -> Iterator[Dict[str, Any]]:-dataset = wds.WebDataset(self.urls,shardshuffle=False,@@ -430,9 +429,7 @@ class JsonlDatasetReader(IterableDataReader):)continuetry:- waveform = torch.from_numpy(- load_audio(audio_path, self.sample_rate)- )+ waveform = torch.from_numpy(load_audio(audio_path, self.sample_rate))if self.normalize_audio:waveform = (waveform / (waveform.abs().max() + 1e-7)) * 0.9meta["audio_duration"] = waveform.shape[1] / self.sample_rate@@ -495,9 +492,9 @@ class LazyIteratorMultiplexer:self.stop_early = stop_earlyself.seed = seed- assert (- len(self.iterators) > 1- ), "There have to be at least two iterables to multiplex."+ assert len(self.iterators) > 1, (+ "There have to be at least two iterables to multiplex."+ )if weights is None:if all(hasattr(it, "__len__") for it in self.iterators):@@ -512,7 +509,6 @@ class LazyIteratorMultiplexer:assert len(self.iterators) == len(self.weights)def __iter__(self):-rng = random.Random(self.seed)iters = [iter(it) for it in self.iterators]exhausted = [False for _ in range(len(iters))]diff --git a/omnivoice/data/processor.py b/omnivoice/data/processor.pyindex 7e3ec1b..64704cd 100644--- a/omnivoice/data/processor.py+++ b/omnivoice/data/processor.py@@ -64,7 +64,6 @@ class OmniVoiceSampleProcessor:self.only_instruct_ratio = only_instruct_ratiodef __call__(self, sample: Dict[str, Any]) -> Dict[str, Any]:-# clean_start_token_idx is only used for prompt denoising training,# where the prompt region is augmented with noises and the model# needs to learn to recover the clean prompt.diff --git a/omnivoice/eval/models/ecapa_tdnn_wavlm.py b/omnivoice/eval/models/ecapa_tdnn_wavlm.pyindex 1219fbc..63609d4 100644--- a/omnivoice/eval/models/ecapa_tdnn_wavlm.py+++ b/omnivoice/eval/models/ecapa_tdnn_wavlm.py@@ -354,7 +354,6 @@ class AttentiveStatsPool(nn.Module):) # equals V and k in the paperdef forward(self, x):-if self.global_context_att:context_mean = torch.mean(x, dim=-1, keepdim=True).expand_as(x)context_std = torch.sqrt(diff --git a/omnivoice/eval/models/utmos.py b/omnivoice/eval/models/utmos.pyindex dca1d4e..44313fb 100644--- a/omnivoice/eval/models/utmos.py+++ b/omnivoice/eval/models/utmos.py@@ -206,7 +206,6 @@ class TransformerEncoder(nn.Module):self.layers = nn.ModuleList([self.build_encoder_layer(feat) for _ in range(12)])def forward(self, x: Tensor) -> Tensor:-x_conv = self.pos_conv(x.transpose(1, 2)).transpose(1, 2)x = x + x_convdiff --git a/omnivoice/eval/mos/utmos.py b/omnivoice/eval/mos/utmos.pyindex e69d30f..5567c39 100755--- a/omnivoice/eval/mos/utmos.py+++ b/omnivoice/eval/mos/utmos.py@@ -18,6 +18,7 @@"""Calculate UTMOS score with automatic Mean Opinion Score (MOS) prediction system"""+import argparseimport loggingimport multiprocessing as mp@@ -137,7 +138,13 @@ def run_utmos_worker(file_idx, wav_path, language_name):"""Worker function to process a single audio file."""try:if not os.path.exists(wav_path):- return file_idx, wav_path, language_name, f"File not found: {wav_path}", "error"+ return (+ file_idx,+ wav_path,+ language_name,+ f"File not found: {wav_path}",+ "error",+ )# Load and preprocess waveformspeech = load_eval_waveform(wav_path, worker_sr, device=worker_device)diff --git a/omnivoice/eval/speaker_similarity/sim.py b/omnivoice/eval/speaker_similarity/sim.pyindex 429b128..ff9b81e 100755--- a/omnivoice/eval/speaker_similarity/sim.py+++ b/omnivoice/eval/speaker_similarity/sim.py@@ -19,6 +19,7 @@Computes speaker similarity (SIM-o) using a WavLM-basedECAPA-TDNN speaker verification model."""+import argparseimport loggingimport multiprocessing as mp@@ -144,7 +145,9 @@ def worker_init(@torch.no_grad()def get_embedding(wav_path: str) -> torch.Tensor:"""Extract embedding for a single file."""- speech = load_eval_waveform(wav_path, worker_sr, device=worker_device, max_seconds=120)+ speech = load_eval_waveform(+ wav_path, worker_sr, device=worker_device, max_seconds=120+ )return worker_model([speech])@@ -212,7 +215,7 @@ def main():total_procs = num_gpus * args.nj_per_gpulogging.info(- f"Starting evaluation with {total_procs} processes " f"on {num_gpus} GPUs."+ f"Starting evaluation with {total_procs} processes on {num_gpus} GPUs.")manager = mp.Manager()@@ -277,7 +280,7 @@ def main():except (Exception, KeyboardInterrupt) as e:logging.critical(- f"An unrecoverable error occurred: {e}. " f"Terminating all processes."+ f"An unrecoverable error occurred: {e}. Terminating all processes.")detailed_error_info = traceback.format_exc()logging.error(f"--- DETAILED TRACEBACK ---\n{detailed_error_info}")diff --git a/omnivoice/eval/wer/common.py b/omnivoice/eval/wer/common.pyindex c081fbd..29bb378 100644--- a/omnivoice/eval/wer/common.py+++ b/omnivoice/eval/wer/common.py@@ -18,6 +18,7 @@"""Shared utilities for WER evaluation scripts."""+import loggingimport numpy as npdiff --git a/omnivoice/eval/wer/fleurs.py b/omnivoice/eval/wer/fleurs.pyindex b1899af..a3d6b7d 100755--- a/omnivoice/eval/wer/fleurs.py+++ b/omnivoice/eval/wer/fleurs.py@@ -28,6 +28,7 @@ Usage:--model-card omniASR_LLM_Unlimited_7B_v2 \\--chunk-size 100 --batch-size 50"""+import argparseimport loggingimport multiprocessing as mp@@ -189,7 +190,7 @@ def get_parser():"--lang",type=str,default=None,- help="""Language code to evaluate (e.g., 'en' for English, 'zh' for Chinese).+ help="""Language code to evaluate (e.g., 'en' for English, 'zh' for Chinese).If not provided, the script will evaluate all languages found in the test list.If specified, only samples of the given language will be evaluated.""",@@ -404,7 +405,6 @@ def main():initializer=process_init,initargs=(rank_queue, args.model_card),) as executor:-futures = []for task in tasks:futures.append(diff --git a/omnivoice/eval/wer/hubert.py b/omnivoice/eval/wer/hubert.pyindex 48706bb..e66ed9f 100755--- a/omnivoice/eval/wer/hubert.py+++ b/omnivoice/eval/wer/hubert.py@@ -18,6 +18,7 @@"""Computes word error rate (WER) with Hubert models for LibriSpeech test sets."""+import argparseimport loggingimport multiprocessing as mp@@ -250,7 +251,6 @@ def main():initializer=process_init,initargs=(rank_queue, args.model_dir),) as executor:-futures = []for chunk in tasks:futures.append(executor.submit(run_eval_worker, chunk, args.batch_size))@@ -288,9 +288,7 @@ def main():)wer_weighted = (- round(- (np.sum(subses) + np.sum(deles) + np.sum(inses)) / word_nums * 100, 2- )+ round((np.sum(subses) + np.sum(deles) + np.sum(inses)) / word_nums * 100, 2)if word_nums > 0else float("nan"))diff --git a/omnivoice/eval/wer/minimax.py b/omnivoice/eval/wer/minimax.pyindex 1479304..7d194d8 100755--- a/omnivoice/eval/wer/minimax.py+++ b/omnivoice/eval/wer/minimax.py@@ -19,6 +19,7 @@Computes word error rate (WER) with Whisper-large-v3 for English andParaformer for Chinese. Intended to evaluate WERs on Seed-TTS test sets."""+import argparseimport loggingimport multiprocessing as mp@@ -108,7 +109,7 @@ def get_parser():"--lang",type=str,default=None,- help="""Language code to evaluate (e.g., 'en' for English, 'zh' for Chinese).+ help="""Language code to evaluate (e.g., 'en' for English, 'zh' for Chinese).If not provided, the script will evaluate all languages found in the test list.If specified, only samples of the given language will be evaluated.""",@@ -239,7 +240,6 @@ def post_process(text: str, lang: str) -> str:str: The cleaned and normalized text."""if lang != "unknown":-iso_639_3_code = mixed_id_to_iso_639_3_id[lang]text = text_normalize(text,@@ -275,7 +275,9 @@ class SpeechEvalDataset(torch.utils.data.Dataset):def __getitem__(self, index):item = self.data_list[index]- waveform = load_eval_waveform(item["wav_path"], sample_rate=16000, return_numpy=True)+ waveform = load_eval_waveform(+ item["wav_path"], sample_rate=16000, return_numpy=True+ )return {"array": waveform,"sampling_rate": 16000,@@ -460,7 +462,6 @@ def main():initializer=process_init,initargs=(whisper_rank_queue, args.model_dir),) as executor:-futures = []for task in whisper_tasks:futures.append(@@ -494,7 +495,6 @@ def main():initializer=process_init_paraformer,initargs=(para_rank_queue, args.model_dir),) as executor:-futures = []for chunk in paraformer_tasks:futures.append(diff --git a/omnivoice/eval/wer/seedtts.py b/omnivoice/eval/wer/seedtts.pyindex 7d1ba98..9ee5a12 100755--- a/omnivoice/eval/wer/seedtts.py+++ b/omnivoice/eval/wer/seedtts.py@@ -19,6 +19,7 @@Computes word error rate (WER) with Whisper-large-v3 for English andParaformer for Chinese. Intended to evaluate WERs on Seed-TTS test sets."""+import argparseimport loggingimport multiprocessing as mp@@ -336,7 +337,6 @@ def main():initializer=process_init,initargs=(rank_queue, args.model_dir, args.lang),) as executor:-futures = []for chunk in tasks:futures.append(@@ -381,9 +381,7 @@ def main():wer_avg = round(np.mean(wers) * 100, 2) if wers else float("nan")wer_weighted = (- round(- (np.sum(subses) + np.sum(deles) + np.sum(inses)) / word_nums * 100, 2- )+ round((np.sum(subses) + np.sum(deles) + np.sum(inses)) / word_nums * 100, 2)if word_nums > 0else float("nan"))diff --git a/omnivoice/eval/wer/sensevoice.py b/omnivoice/eval/wer/sensevoice.pyindex 8490c22..7e2a2a1 100644--- a/omnivoice/eval/wer/sensevoice.py+++ b/omnivoice/eval/wer/sensevoice.py@@ -289,7 +289,6 @@ def main():initializer=process_init_sensevoice,initargs=(rank_queue, args.model_dir),) as executor:-futures = []for chunk in tasks:futures.append(diff --git a/omnivoice/eval/wer/text_norm_omni.py b/omnivoice/eval/wer/text_norm_omni.pyindex fc435e8..f3d3a42 100644--- a/omnivoice/eval/wer/text_norm_omni.py+++ b/omnivoice/eval/wer/text_norm_omni.py@@ -6,7 +6,7 @@# LICENSE file in the root directory of this source tree."""-This module contains the text normalization function for WER evaluation.+This module contains the text normalization function for WER evaluation.Copied from https://github.com/facebookresearch/omnilingual-asr/blob/81f51e224ce9e74b02cc2a3eaf21b2d91d743455/workflows/dataprep/text_tools.py"""@@ -87,7 +87,6 @@ def text_normalize(# The lookaround enables overlapping pattern matches to be replacedif remove_numbers:-digits_pattern = "[" + config["digit_set"]digits_pattern += "]+"diff --git a/omnivoice/models/omnivoice.py b/omnivoice/models/omnivoice.pyindex d36dec0..48786e0 100644--- a/omnivoice/models/omnivoice.py+++ b/omnivoice/models/omnivoice.py@@ -175,7 +175,6 @@ class OmniVoiceConfig(PretrainedConfig):llm_config: Optional[Union[dict, PretrainedConfig]] = None,**kwargs,):-if isinstance(llm_config, dict):llm_config = CONFIG_MAPPING[llm_config["model_type"]](**llm_config)@@ -307,7 +306,9 @@ class OmniVoice(PreTrainedModel):logger.info("Loading ASR model %s ...", model_name)asr_dtype = (- torch.float16 if str(self.device).startswith(("cuda", "xpu")) else torch.float32+ torch.float16+ if str(self.device).startswith(("cuda", "xpu"))+ else torch.float32)model_name = _resolve_model_path(model_name)@@ -390,7 +391,6 @@ class OmniVoice(PreTrainedModel):document_ids: Optional[torch.Tensor] = None,position_ids: Optional[torch.LongTensor] = None,):-inputs_embeds = self._prepare_embed_inputs(input_ids, audio_mask)if attention_mask is None and document_ids is not None:@@ -434,7 +434,6 @@ class OmniVoice(PreTrainedModel):).permute(0, 2, 1, 3)if labels is not None:-# audio_logits.permute(0, 3, 1, 2):# [Batch, Layer, Seq, Vocab] -> [Batch, Vocab, Layer, Seq]# per_token_loss shape: [Batch, Layer, Seq],ignore -100@@ -600,7 +599,9 @@ class OmniVoice(PreTrainedModel):assert results[i] is not None, f"Result {i} was not generated"generated_audios.append(self._decode_and_post_process(- results[i], full_task.ref_rms[i], gen_config # type: ignore[arg-type]+ results[i],+ full_task.ref_rms[i],+ gen_config, # type: ignore[arg-type]))@@ -700,9 +701,7 @@ class OmniVoice(PreTrainedModel):ref_wav_tensor = torch.from_numpy(ref_wav).to(self.audio_tokenizer.device)ref_audio_tokens = self.audio_tokenizer.encode(ref_wav_tensor.unsqueeze(0),- ).audio_codes.squeeze(- 0- ) # (C, T)+ ).audio_codes.squeeze(0) # (C, T)if preprocess_prompt:ref_text = add_punctuation(ref_text)@@ -923,13 +922,12 @@ class OmniVoice(PreTrainedModel):speed: Union[float, list[Optional[float]], None] = None,duration: Union[float, list[Optional[float]], None] = None,) -> GenerationTask:-if isinstance(text, str):text_list = [text]else:- assert isinstance(- text, list- ), "text should be a string or a list of strings"+ assert isinstance(text, list), (+ "text should be a string or a list of strings"+ )text_list = textbatch_size = len(text_list)@@ -1105,9 +1103,7 @@ class OmniVoice(PreTrainedModel):self.text_tokenizer(style_text, return_tensors="pt").input_ids.repeat(self.config.num_audio_codebook, 1).unsqueeze(0)- ).to(- self.device- ) # [1, C, N1]+ ).to(self.device) # [1, C, N1]# Build text tokensfull_text = _combine_text(ref_text=ref_text, text=text)@@ -1116,9 +1112,7 @@ class OmniVoice(PreTrainedModel):_tokenize_with_nonverbal_tags(wrapped_text, self.text_tokenizer).repeat(self.config.num_audio_codebook, 1).unsqueeze(0)- ).to(- self.device- ) # [1, C, N2]+ ).to(self.device) # [1, C, N2]# Target: all MASKtarget_audio_tokens = torch.full(@@ -1574,7 +1568,6 @@ def _tokenize_with_nonverbal_tags(text: str, tokenizer) -> torch.Tensor:def _combine_text(text, ref_text: Optional[str] = None) -> str:-# combine with reference text if not Noneif ref_text:full_text = ref_text.strip() + " " + text.strip()diff --git a/omnivoice/scripts/denoise_audio.py b/omnivoice/scripts/denoise_audio.pyindex 27fce91..d46f987 100644--- a/omnivoice/scripts/denoise_audio.py+++ b/omnivoice/scripts/denoise_audio.py@@ -93,7 +93,7 @@ def build_parser() -> argparse.ArgumentParser:parser.add_argument("--input_jsonl",default=None,- help="Raw JSONL file. Each line: " '{"id": "...", "audio_path": "...", ...}',+ help='Raw JSONL file. Each line: {"id": "...", "audio_path": "...", ...}',)# ── Output ──@@ -752,14 +752,14 @@ def main() -> None:# Validate input argumentsassert args.tar_output_pattern is not None, "--tar_output_pattern is required."assert args.jsonl_output_pattern is not None, "--jsonl_output_pattern is required."- assert bool(args.input_manifest) != bool(- args.input_jsonl- ), "Exactly one of --input_manifest or --input_jsonl must be provided."+ assert bool(args.input_manifest) != bool(args.input_jsonl), (+ "Exactly one of --input_manifest or --input_jsonl must be provided."+ )if args.num_machines > 1:- assert (- 0 <= args.machine_index < args.num_machines- ), f"machine_index {args.machine_index} must be in [0, {args.num_machines})"+ assert 0 <= args.machine_index < args.num_machines, (+ f"machine_index {args.machine_index} must be in [0, {args.num_machines})"+ )# ── Build base dataset and count total samples ──if args.input_jsonl:@@ -793,9 +793,9 @@ def main() -> None:)assert os.path.exists(tar_path), f"File {tar_path} does not exist."assert os.path.exists(jsonl_path), f"File {jsonl_path} does not exist."- assert jsonl_path.endswith(- ".jsonl"- ), f"File {jsonl_path} is not a .jsonl file."+ assert jsonl_path.endswith(".jsonl"), (+ f"File {jsonl_path} is not a .jsonl file."+ )if (args.num_machines > 1and line_id % args.num_machines != args.machine_indexdiff --git a/omnivoice/scripts/extract_audio_tokens.py b/omnivoice/scripts/extract_audio_tokens.pyindex 2f03a4f..4791ae2 100644--- a/omnivoice/scripts/extract_audio_tokens.py+++ b/omnivoice/scripts/extract_audio_tokens.py@@ -327,14 +327,14 @@ def main() -> None:mp.set_start_method("spawn", force=True)# Validate input arguments- assert bool(args.input_manifest) != bool(- args.input_jsonl- ), "Exactly one of --input_manifest or --input_jsonl must be provided."+ assert bool(args.input_manifest) != bool(args.input_jsonl), (+ "Exactly one of --input_manifest or --input_jsonl must be provided."+ )if args.num_machines > 1:- assert (- 0 <= args.machine_index < args.num_machines- ), f"machine_index {args.machine_index} must be in [0, {args.num_machines})"+ assert 0 <= args.machine_index < args.num_machines, (+ f"machine_index {args.machine_index} must be in [0, {args.num_machines})"+ )# Build base dataset and count total samples based on input modeif args.input_jsonl:@@ -368,9 +368,9 @@ def main() -> None:)assert os.path.exists(tar_path), f"File {tar_path} does not exist."assert os.path.exists(jsonl_path), f"File {jsonl_path} does not exist."- assert jsonl_path.endswith(- ".jsonl"- ), f"File {jsonl_path} is not a .jsonl file."+ assert jsonl_path.endswith(".jsonl"), (+ f"File {jsonl_path} is not a .jsonl file."+ )if (args.num_machines > 1and line_id % args.num_machines != args.machine_indexdiff --git a/omnivoice/scripts/extract_audio_tokens_add_noise.py b/omnivoice/scripts/extract_audio_tokens_add_noise.pyindex 37b72ac..08b8a5c 100644--- a/omnivoice/scripts/extract_audio_tokens_add_noise.py+++ b/omnivoice/scripts/extract_audio_tokens_add_noise.py@@ -291,7 +291,11 @@ def process_init(rank_queue, tokenizer_path, noise_manifest=None, rir_manifest=NInitialization function for each worker process.Assigns a specific GPU to the process and loads the tokenizer."""- global worker_tokenizer, worker_feature_extractor, worker_noise_sampler, worker_rir_sampler+ global \+ worker_tokenizer, \+ worker_feature_extractor, \+ worker_noise_sampler, \+ worker_rir_sampler# Configure worker process loggingformatter = (@@ -511,14 +515,14 @@ def main() -> None:mp.set_start_method("spawn", force=True)# Validate input arguments- assert bool(args.input_manifest) != bool(- args.input_jsonl- ), "Exactly one of --input_manifest or --input_jsonl must be provided."+ assert bool(args.input_manifest) != bool(args.input_jsonl), (+ "Exactly one of --input_manifest or --input_jsonl must be provided."+ )if args.num_machines > 1:- assert (- 0 <= args.machine_index < args.num_machines- ), f"machine_index {args.machine_index} must be in [0, {args.num_machines})"+ assert 0 <= args.machine_index < args.num_machines, (+ f"machine_index {args.machine_index} must be in [0, {args.num_machines})"+ )# Build base dataset and count total samples based on input modeif args.input_jsonl:@@ -552,9 +556,9 @@ def main() -> None:)assert os.path.exists(tar_path), f"File {tar_path} does not exist."assert os.path.exists(jsonl_path), f"File {jsonl_path} does not exist."- assert jsonl_path.endswith(- ".jsonl"- ), f"File {jsonl_path} is not a .jsonl file."+ assert jsonl_path.endswith(".jsonl"), (+ f"File {jsonl_path} is not a .jsonl file."+ )if (args.num_machines > 1and line_id % args.num_machines != args.machine_indexdiff --git a/omnivoice/scripts/jsonl_to_webdataset.py b/omnivoice/scripts/jsonl_to_webdataset.pyindex 81442b4..9391d92 100644--- a/omnivoice/scripts/jsonl_to_webdataset.py+++ b/omnivoice/scripts/jsonl_to_webdataset.py@@ -212,10 +212,10 @@ def process_single_shard(total_duration = 0.0errors = []- with wds.TarWriter(tar_fname) as sink, open(- jsonl_fname, "w", encoding="utf-8"- ) as jsonl_f:-+ with (+ wds.TarWriter(tar_fname) as sink,+ open(jsonl_fname, "w", encoding="utf-8") as jsonl_f,+ ):with ThreadPoolExecutor(max_workers=num_threads) as thread_pool:futures = []@@ -331,7 +331,6 @@ def pack_dataset(print(f"Total samples: {total_lines}, Estimated shards: {total_shards_est}")with ProcessPoolExecutor(max_workers=num_workers) as executor:-futures = set()shard_idx = 0diff --git a/omnivoice/training/builder.py b/omnivoice/training/builder.pyindex 4af2fc7..6a33431 100644--- a/omnivoice/training/builder.py+++ b/omnivoice/training/builder.py@@ -189,9 +189,7 @@ def build_dataloaders(seed_worker,num_workers=config.num_workers,rank=(- torch.distributed.get_rank()- if torch.distributed.is_initialized()- else 0+ torch.distributed.get_rank() if torch.distributed.is_initialized() else 0),)@@ -207,9 +205,7 @@ def build_dataloaders(eval_loader = Noneif dev_manifests:- raw_dev_ds = WebDatasetReader(- manifests=dev_manifests, evaluation=True- )+ raw_dev_ds = WebDatasetReader(manifests=dev_manifests, evaluation=True)if use_packing:dev_dataset = PackingIterableDataset(raw_dev_ds, processor, config.batch_tokensdiff --git a/omnivoice/training/trainer.py b/omnivoice/training/trainer.pyindex 081955e..ec015be 100644--- a/omnivoice/training/trainer.py+++ b/omnivoice/training/trainer.py@@ -87,7 +87,11 @@ class OmniTrainer:] = 1# 4. Prepare with Accelerator- (self.model, self.optimizer, self.lr_scheduler,) = self.accelerator.prepare(+ (+ self.model,+ self.optimizer,+ self.lr_scheduler,+ ) = self.accelerator.prepare(self.model,self.optimizer,self.lr_scheduler,@@ -293,9 +297,7 @@ class OmniTrainer:grad_norm = self.accelerator.clip_grad_norm_(self.model.parameters(), self.config.max_grad_norm)- grad_norm = (- grad_norm.item() if grad_norm is not None else 0.0- )+ grad_norm = grad_norm.item() if grad_norm is not None else 0.0self.optimizer.step()self.lr_scheduler.step()diff --git a/omnivoice/utils/duration.py b/omnivoice/utils/duration.pyindex f3bb9d7..ab3fcfd 100644--- a/omnivoice/utils/duration.py+++ b/omnivoice/utils/duration.py@@ -170,7 +170,7 @@ class RuleDurationEstimator:return self.weights["latin"]if code == 32:return self.weights["space"]-+# Ignore arabic Tatweelif code == 0x0640:return self.weights["mark"]diff --git a/omnivoice/utils/text.py b/omnivoice/utils/text.pyindex 6294ea0..0ea9c90 100644--- a/omnivoice/utils/text.py+++ b/omnivoice/utils/text.py@@ -27,7 +27,7 @@ from typing import List, OptionalSPLIT_PUNCTUATION = set(".,;:!?。,;:!?")-CLOSING_MARKS = set("\"'""')]》》>」】")+CLOSING_MARKS = set("\"'“”‘’)]》>」】")END_PUNCTUATION = {";",@@ -42,8 +42,10 @@ END_PUNCTUATION = {"}",'"',"'",- '"',- "'",+ "“",+ "”",+ "‘",+ "’",";",":",",",@@ -54,8 +56,6 @@ END_PUNCTUATION = {"……",")","】",- '"',- "'",}@@ -216,4 +216,4 @@ def add_punctuation(text: str):text += "。" if is_chinese else "."- return text\ No newline at end of file+ return textdiff --git a/omnivoice/utils/voice_design.py b/omnivoice/utils/voice_design.pyindex 802321d..b369b77 100644--- a/omnivoice/utils/voice_design.py+++ b/omnivoice/utils/voice_design.py@@ -24,25 +24,55 @@ translation/validation utilities between English and Chinese. Used byimport re-_ZH_RE = re.compile(r'[\u4e00-\u9fff]')+_ZH_RE = re.compile(r"[\u4e00-\u9fff]")# Category = set of {english: chinese, ...} items that are mutually exclusive.# Accent (EN-only) and dialect (ZH-only) are stored as flat sets below._INSTRUCT_CATEGORIES = [{"male": "男", "female": "女"},- {"child": "儿童", "teenager": "少年", "young adult": "青年",- "middle-aged": "中年", "elderly": "老年"},- {"very low pitch": "极低音调", "low pitch": "低音调",- "moderate pitch": "中音调", "high pitch": "高音调",- "very high pitch": "极高音调"},+ {+ "child": "儿童",+ "teenager": "少年",+ "young adult": "青年",+ "middle-aged": "中年",+ "elderly": "老年",+ },+ {+ "very low pitch": "极低音调",+ "low pitch": "低音调",+ "moderate pitch": "中音调",+ "high pitch": "高音调",+ "very high pitch": "极高音调",+ },{"whisper": "耳语"},# Accent (English-only, no Chinese counterpart)- {"american accent", "british accent", "australian accent",- "chinese accent", "canadian accent", "indian accent",- "korean accent", "portuguese accent", "russian accent", "japanese accent"},+ {+ "american accent",+ "british accent",+ "australian accent",+ "chinese accent",+ "canadian accent",+ "indian accent",+ "korean accent",+ "portuguese accent",+ "russian accent",+ "japanese accent",+ },# Dialect (Chinese-only, no English counterpart)- {"河南话", "陕西话", "四川话", "贵州话", "云南话", "桂林话",- "济南话", "石家庄话", "甘肃话", "宁夏话", "青岛话", "东北话"},+ {+ "河南话",+ "陕西话",+ "四川话",+ "贵州话",+ "云南话",+ "桂林话",+ "济南话",+ "石家庄话",+ "甘肃话",+ "宁夏话",+ "青岛话",+ "东北话",+ },]_INSTRUCT_EN_TO_ZH = {}@@ -57,7 +87,8 @@ for _cat in _INSTRUCT_CATEGORIES:_INSTRUCT_MUTUALLY_EXCLUSIVE.append(set(_cat))_INSTRUCT_ALL_VALID = (- set(_INSTRUCT_EN_TO_ZH) | set(_INSTRUCT_ZH_TO_EN)+ set(_INSTRUCT_EN_TO_ZH)+ | set(_INSTRUCT_ZH_TO_EN)| _INSTRUCT_MUTUALLY_EXCLUSIVE[-2] # accents| _INSTRUCT_MUTUALLY_EXCLUSIVE[-1] # dialects)diff --git a/pyproject.toml b/pyproject.tomlindex d5f497f..59988c6 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -89,6 +89,9 @@ constraint-dependencies = ["torchaudio==2.8.0",]+[tool.ruff.lint]+ignore = ["F401", "E402", "F403", "F841", "E741"]+[tool.hatch.build.targets.sdist]include = ["omnivoice"]