Spaces:
Build error
Build error
v0.5.0
Browse filesFiles changed (33)
- .gitignoreAdded+214
- LICENSEAdded+201
- SoniTranslate_Colab.ipynbAdded+124
- app.pyAdded+2
- app_rvc.pyAdded
- assets/logo.jpegAdded
- docs/windows_install.mdAdded+150
- lib/audio.pyAdded+21
- lib/infer_pack/attentions.pyAdded+417
- lib/infer_pack/commons.pyAdded+166
- lib/infer_pack/models.pyAdded+1142
- lib/infer_pack/modules.pyAdded+522
- lib/infer_pack/transforms.pyAdded+209
- lib/rmvpe.pyAdded+422
- mdx_models/data.jsonAdded+354
- packages.txtAdded+3
- pre-requirements.txtAdded+15
- requirements.txtAdded+19
- requirements_xtts.txtAdded+58
- soni_translate/audio_segments.pyAdded+141
- soni_translate/language_configuration.pyAdded+551
- soni_translate/languages_gui.pyAdded
- soni_translate/logging_setup.pyAdded+68
- soni_translate/mdx_net.pyAdded+582
- soni_translate/postprocessor.pyAdded+229
- soni_translate/preprocessor.pyAdded+308
- soni_translate/speech_segmentation.pyAdded+499
- soni_translate/text_multiformat_processor.pyAdded+987
- soni_translate/text_to_speech.pyAdded+1574
- soni_translate/translate_segments.pyAdded+457
- soni_translate/utils.pyAdded+487
- vci_pipeline.pyAdded+454
- voice_main.pyAdded+732
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214# Byte-compiled / optimized / DLL files__pycache__/*.py[cod]*$py.class
# C extensions*.so
# Distribution / packaging.Pythonbuild/develop-eggs/dist/downloads/eggs/.eggs/lib64/parts/sdist/var/wheels/share/python-wheels/*.egg-info/.installed.cfg*.eggMANIFEST
# PyInstaller# Usually these files are written by a python script from a template# before PyInstaller builds the exe, so as to inject date/other infos into it.*.manifest*.spec
# Installer logspip-log.txtpip-delete-this-directory.txt
# Unit test / coverage reportshtmlcov/.tox/.nox/.coverage.coverage.*.cachenosetests.xmlcoverage.xml*.cover*.py,cover.hypothesis/.pytest_cache/cover/
# Translations*.mo*.pot
# Django stuff:*.loglocal_settings.pydb.sqlite3db.sqlite3-journal
# Flask stuff:instance/.webassets-cache
# Scrapy stuff:.scrapy
# Sphinx documentationdocs/_build/
# PyBuilder.pybuilder/target/
# Jupyter Notebook.ipynb_checkpoints
# IPythonprofile_default/ipython_config.py
# pyenv# For a library or package, you might want to ignore these files since the code is# intended to run in multiple environments; otherwise, check them in:# .python-version
# pipenv# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.# However, in case of collaboration, if having platform-specific dependencies or dependencies# having no cross-platform support, pipenv may install dependencies that don't work, or not# install all needed dependencies.#Pipfile.lock
# poetry# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.# This is especially recommended for binary packages to ensure reproducibility, and is more# commonly ignored for libraries.# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control#poetry.lock
# pdm# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.#pdm.lock# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it# in version control.# https://pdm.fming.dev/#use-with-ide.pdm.toml
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm__pypackages__/
# Celery stuffcelerybeat-schedulecelerybeat.pid
# SageMath parsed files*.sage.py
# Environments.env.venvenv/venv/ENV/env.bak/venv.bak/
# Spyder project settings.spyderproject.spyproject
# Rope project settings.ropeproject
# mkdocs documentation/site
# mypy.mypy_cache/.dmypy.jsondmypy.json
# Pyre type checker.pyre/
# pytype static type analyzer.pytype/
# Cython debug symbolscython_debug/
# PyCharm# JetBrains specific template is maintained in a separate JetBrains.gitignore that can# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore# and can be added to the global gitignore or merged into this file. For a more nuclear# option (not recommended) you can uncomment the following to ignore the entire idea folder.#.idea/
# Ignoresub_tra.*sub_ori.*SPEAKER_00.*SPEAKER_01.*SPEAKER_02.*SPEAKER_03.*SPEAKER_04.*SPEAKER_05.*SPEAKER_06.*SPEAKER_07.*SPEAKER_08.*SPEAKER_09.*SPEAKER_10.*SPEAKER_11.*task_subtitle.**.mp3*.mp4*.ogg*.wav*.mkv*.webm*.avi*.mpg*.mov*.ogv*.wmvtest.pylist.txttext_preprocessor.txttext_translation.txt*.srt*.vtt*.tsv*.aud*.ass*.pt.vscode/mdx_models/*.onnx_XTTS_/downloads/logs/weights/clean_song_output/audio2/audio/outputs/processed/OPENVOICE_MODELS/PIPER_MODELS/WHISPER_MODELS/whisper_api_audio_parts/uroman/pdf_images/123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124{ "nbformat": 4, "nbformat_minor": 0, "metadata": { "colab": { "provenance": [], "gpuType": "T4", "include_colab_link": true }, "kernelspec": { "name": "python3", "display_name": "Python 3" }, "language_info": { "name": "python" }, "accelerator": "GPU" }, "cells": [ { "cell_type": "markdown", "metadata": { "id": "view-in-github", "colab_type": "text" }, "source": [ "<a href=\"https://colab.research.google.com/github/R3gm/SoniTranslate/blob/main/SoniTranslate_Colab.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>" ] }, { "cell_type": "markdown", "source": [ "# SoniTranslate\n", "\n", "| Description | Link |\n", "| ----------- | ---- |\n", "| 🎉 Repository | [](https://github.com/R3gm/SoniTranslate/) |\n", "| 🚀 Online Demo in HF | [](https://huggingface.co/spaces/r3gm/SoniTranslate_translate_audio_of_a_video_content) |\n", "\n", "\n" ], "metadata": { "id": "8lw0EgLex-YZ" } }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "LUgwm0rfx0_J", "cellView": "form" }, "outputs": [], "source": [ "# @title Install requirements for SoniTranslate\n", "!git clone https://github.com/r3gm/SoniTranslate.git\n", "%cd SoniTranslate\n", "\n", "!apt install git-lfs\n", "!git lfs install\n", "\n", "!sed -i 's|git+https://github.com/R3gm/whisperX.git@cuda_11_8|git+https://github.com/R3gm/whisperX.git@cuda_12_x|' requirements_base.txt\n", "!pip install -q -r requirements_base.txt\n", "!pip install -q -r requirements_extra.txt\n", "!pip install -q ort-nightly-gpu --index-url=https://aiinfra.pkgs.visualstudio.com/PublicPackages/_packaging/ort-cuda-12-nightly/pypi/simple/\n", "\n", "Install_PIPER_TTS = True # @param {type:\"boolean\"}\n", "\n", "if Install_PIPER_TTS:\n", " !pip install -q piper-tts==1.2.0\n", "\n", "Install_Coqui_XTTS = True # @param {type:\"boolean\"}\n", "\n", "if Install_Coqui_XTTS:\n", " !pip install -q -r requirements_xtts.txt\n", " !pip install -q TTS==0.21.1 --no-deps" ] }, { "cell_type": "markdown", "source": [ "One important step is to accept the license agreement for using Pyannote. You need to have an account on Hugging Face and `accept the license to use the models`: https://huggingface.co/pyannote/speaker-diarization and https://huggingface.co/pyannote/segmentation\n", "\n", "\n", "\n", "\n", "Get your KEY TOKEN here: https://hf.co/settings/tokens" ], "metadata": { "id": "LTaTstXPXNg2" } }, { "cell_type": "code", "source": [ "#@markdown # `RUN THE WEB APP`\n", "YOUR_HF_TOKEN = \"\" #@param {type:'string'}\n", "%env YOUR_HF_TOKEN={YOUR_HF_TOKEN}\n", "theme = \"Taithrah/Minimal\" # @param [\"Taithrah/Minimal\", \"aliabid94/new-theme\", \"gstaff/xkcd\", \"ParityError/LimeFace\", \"abidlabs/pakistan\", \"rottenlittlecreature/Moon_Goblin\", \"ysharma/llamas\", \"gradio/dracula_revamped\"]\n", "interface_language = \"english\" # @param ['arabic', 'azerbaijani', 'chinese_zh_cn', 'english', 'french', 'german', 'hindi', 'indonesian', 'italian', 'japanese', 'korean', 'marathi', 'polish', 'portuguese', 'russian', 'spanish', 'swedish', 'turkish', 'ukrainian', 'vietnamese']\n", "verbosity_level = \"info\" # @param [\"debug\", \"info\", \"warning\", \"error\", \"critical\"]\n", "\n", "\n", "%cd /content/SoniTranslate\n", "!python app_rvc.py --theme {theme} --verbosity_level {verbosity_level} --language {interface_language} --public_url" ], "metadata": { "id": "XkhXfaFw4R4J", "cellView": "form" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "Open the `public URL` when it appears" ], "metadata": { "id": "KJW3KrhZJh0u" } } ]}12import osos.system("python app_rvc.py --language french --theme aliabid94/new-theme")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150## Install Locally Windows
### Before You Start
Before you start installing and using SoniTranslate, there are a few things you need to do:
1. Install Microsoft Visual C++ Build Tools, MSVC and Windows 10 SDK:
* Go to the [Visual Studio downloads page](https://visualstudio.microsoft.com/visual-cpp-build-tools/); Or maybe you already have **Visual Studio Installer**? Open it. If you have it already click modify.
* Download and install the "Build Tools for Visual Studio" if you don't have it.
* During installation, under "Workloads", select "C++ build tools" and ensure the latest versions of "MSVCv142 - VS 2019 C++ x64/x86 build tools" and "Windows 10 SDK" are selected ("Windows 11 SDK" if you are using Windows 11); OR go to individual components and find those two listed.
* Complete the installation.
2. Verify the NVIDIA driver on Windows using the command line:
* **Open Command Prompt:** Press `Win + R`, type `cmd`, then press `Enter`.
* **Type the command:** `nvidia-smi` and press `Enter`.
* **Look for "CUDA Version"** in the output.
```
+-----------------------------------------------------------------------------+
| NVIDIA-SMI 522.25 Driver Version: 522.25 CUDA Version: 11.8 |
|-------------------------------+----------------------+----------------------+
```
3. If you see that your CUDA version is less than 11.8, you should update your NVIDIA driver. Visit the NVIDIA website's driver download page (https://www.nvidia.com/Download/index.aspx) and enter your graphics card information.
4. Accept the license agreement for using Pyannote. You need to have an account on Hugging Face and `accept the license to use the models`: https://huggingface.co/pyannote/speaker-diarization and https://huggingface.co/pyannote/segmentation
5. Create a [huggingface token](https://huggingface.co/settings/tokens). Hugging Face is a natural language processing platform that provides access to state-of-the-art models and tools. You will need to create a token in order to use some of the automatic model download features in SoniTranslate. Follow the instructions on the Hugging Face website to create a token.
6. Install [Anaconda](https://www.anaconda.com/) or [Miniconda](https://docs.anaconda.com/free/miniconda/miniconda-install/). Anaconda is a free and open-source distribution of Python and R. It includes a package manager called conda that makes it easy to install and manage Python environments and packages. Follow the instructions on the Anaconda website to download and install Anaconda on your system.
7. Install Git for your system. Git is a version control system that helps you track changes to your code and collaborate with other developers. You can install Git with Anaconda by running `conda install -c anaconda git -y` in your terminal (Do this after step 1 in the following section.). If you have trouble installing Git via Anaconda, you can use the following link instead:
- [Git for Windows](https://git-scm.com/download/win)
Once you have completed these steps, you will be ready to install SoniTranslate.
### Getting Started
To install SoniTranslate, follow these steps:
1. Create a suitable anaconda environment for SoniTranslate and activate it:
```
conda create -n sonitr python=3.10 -y
conda activate sonitr
```
2. Clone this github repository and navigate to it:
```
git clone https://github.com/r3gm/SoniTranslate.git
cd SoniTranslate
```
3. Install CUDA Toolkit 11.8.0
```
conda install -c "nvidia/label/cuda-11.8.0" cuda-toolkit -y
```
4. Install PyTorch using conda
```
conda install pytorch torchvision torchaudio pytorch-cuda=11.8 -c pytorch -c nvidia -y
```
5. Install required packages:
```
pip install -r requirements_base.txt -v
pip install -r requirements_extra.txt -v
pip install onnxruntime-gpu
```
6. Install [ffmpeg](https://ffmpeg.org/download.html). FFmpeg is a free software project that produces libraries and programs for handling multimedia data. You will need it to process audio and video files. You can install ffmpeg with Anaconda by running `conda install -y ffmpeg` in your terminal (recommended). If you have trouble installing ffmpeg via Anaconda, you can use the following link instead: (https://ffmpeg.org/ffmpeg.html). Once it is installed, make sure it is in your PATH by running `ffmpeg -h` in your terminal. If you don't get an error message, you're good to go.
7. Optional install:
After installing FFmpeg, you can install these optional packages.
[Coqui XTTS](https://github.com/coqui-ai/TTS) is a text-to-speech (TTS) model that lets you generate realistic voices in different languages. It can clone voices with just a short audio clip, even speak in a different language! It's like having a personal voice mimic for any text you need spoken.
```
pip install -q -r requirements_xtts.txt
pip install -q TTS==0.21.1 --no-deps
```
[Piper TTS](https://github.com/rhasspy/piper) is a fast, local neural text to speech system that sounds great and is optimized for the Raspberry Pi 4. Piper is used in a variety of projects. Voices are trained with VITS and exported to the onnxruntime.
🚧 For Windows users, it's important to note that the Python module piper-tts is not fully supported on this operating system. While it works smoothly on Linux, Windows compatibility is currently experimental. If you still wish to install it on Windows, you can follow this experimental method:
```
pip install https://github.com/R3gm/piper-phonemize/releases/download/1.2.0/piper_phonemize-1.2.0-cp310-cp310-win_amd64.whl
pip install sherpa-onnx==1.9.12
pip install piper-tts==1.2.0 --no-deps
```
8. Setting your [Hugging Face token](https://huggingface.co/settings/tokens) as an environment variable in quotes:
```
conda env config vars set YOUR_HF_TOKEN="YOUR_HUGGING_FACE_TOKEN_HERE"
conda deactivate
```
### Running SoniTranslate
To run SoniTranslate locally, make sure the `sonitr` conda environment is active:
```
conda activate sonitr
```
Then navigate to the `SoniTranslate` folder and run either the `app_rvc.py`
```
python app_rvc.py
```
When the `local URL` `http://127.0.0.1:7860` is displayed in the terminal, simply open this URL in your web browser to access the SoniTranslate interface.
### Stop and close SoniTranslate.
In most environments, you can stop the execution by pressing Ctrl+C in the terminal where you launched the script `app_rvc.py`. This will interrupt the program and stop the Gradio app.
To deactivate the Conda environment, you can use the following command:
```
conda deactivate
```
This will deactivate the currently active Conda environment sonitr, and you'll return to the base environment or the global Python environment.
### Starting Over
If you need to start over from scratch, you can delete the `SoniTranslate` folder and remove the `sonitr` conda environment with the following set of commands:
```
conda deactivate
conda env remove -n sonitr
```
With the `sonitr` environment removed, you can start over with a fresh installation.
### Notes
- To use OpenAI's GPT API for translation, set up your OpenAI API key as an environment variable in quotes:
```
conda activate sonitr
conda env config vars set OPENAI_API_KEY="your-api-key-here"
conda deactivate
```
- Alternatively, you can install the CUDA Toolkit 11.8.0 directly on your system [CUDA Toolkit 11.8.0](https://developer.nvidia.com/cuda-11-8-0-download-archive).123456789101112131415161718192021import ffmpeg
import numpy as np
def load_audio(file, sr):
try:
# https://github.com/openai/whisper/blob/main/whisper/audio.py#L26
# This launches a subprocess to decode audio while down-mixing and resampling as necessary.
# Requires the ffmpeg CLI and `ffmpeg-python` package to be installed.
file = (
file.strip(" ").strip('"').strip("\n").strip('"').strip(" ")
) # To prevent beginners from copying paths with leading or trailing spaces, quotation marks, and line breaks.
out, _ = (
ffmpeg.input(file, threads=0)
.output("-", format="f32le", acodec="pcm_f32le", ac=1, ar=sr)
.run(cmd=["ffmpeg", "-nostdin"], capture_stdout=True, capture_stderr=True)
)
except Exception as e:
raise RuntimeError(f"Failed to load audio: {e}")
return np.frombuffer(out, np.float32).flatten()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417import copy
import math
import numpy as np
import torch
from torch import nn
from torch.nn import functional as F
from lib.infer_pack import commons
from lib.infer_pack import modules
from lib.infer_pack.modules import LayerNorm
class Encoder(nn.Module):
def __init__(
self,
hidden_channels,
filter_channels,
n_heads,
n_layers,
kernel_size=1,
p_dropout=0.0,
window_size=10,
**kwargs
):
super().__init__()
self.hidden_channels = hidden_channels
self.filter_channels = filter_channels
self.n_heads = n_heads
self.n_layers = n_layers
self.kernel_size = kernel_size
self.p_dropout = p_dropout
self.window_size = window_size
self.drop = nn.Dropout(p_dropout)
self.attn_layers = nn.ModuleList()
self.norm_layers_1 = nn.ModuleList()
self.ffn_layers = nn.ModuleList()
self.norm_layers_2 = nn.ModuleList()
for i in range(self.n_layers):
self.attn_layers.append(
MultiHeadAttention(
hidden_channels,
hidden_channels,
n_heads,
p_dropout=p_dropout,
window_size=window_size,
)
)
self.norm_layers_1.append(LayerNorm(hidden_channels))
self.ffn_layers.append(
FFN(
hidden_channels,
hidden_channels,
filter_channels,
kernel_size,
p_dropout=p_dropout,
)
)
self.norm_layers_2.append(LayerNorm(hidden_channels))
def forward(self, x, x_mask):
attn_mask = x_mask.unsqueeze(2) * x_mask.unsqueeze(-1)
x = x * x_mask
for i in range(self.n_layers):
y = self.attn_layers[i](x, x, attn_mask)
y = self.drop(y)
x = self.norm_layers_1[i](x + y)
y = self.ffn_layers[i](x, x_mask)
y = self.drop(y)
x = self.norm_layers_2[i](x + y)
x = x * x_mask
return x
class Decoder(nn.Module):
def __init__(
self,
hidden_channels,
filter_channels,
n_heads,
n_layers,
kernel_size=1,
p_dropout=0.0,
proximal_bias=False,
proximal_init=True,
**kwargs
):
super().__init__()
self.hidden_channels = hidden_channels
self.filter_channels = filter_channels
self.n_heads = n_heads
self.n_layers = n_layers
self.kernel_size = kernel_size
self.p_dropout = p_dropout
self.proximal_bias = proximal_bias
self.proximal_init = proximal_init
self.drop = nn.Dropout(p_dropout)
self.self_attn_layers = nn.ModuleList()
self.norm_layers_0 = nn.ModuleList()
self.encdec_attn_layers = nn.ModuleList()
self.norm_layers_1 = nn.ModuleList()
self.ffn_layers = nn.ModuleList()
self.norm_layers_2 = nn.ModuleList()
for i in range(self.n_layers):
self.self_attn_layers.append(
MultiHeadAttention(
hidden_channels,
hidden_channels,
n_heads,
p_dropout=p_dropout,
proximal_bias=proximal_bias,
proximal_init=proximal_init,
)
)
self.norm_layers_0.append(LayerNorm(hidden_channels))
self.encdec_attn_layers.append(
MultiHeadAttention(
hidden_channels, hidden_channels, n_heads, p_dropout=p_dropout
)
)
self.norm_layers_1.append(LayerNorm(hidden_channels))
self.ffn_layers.append(
FFN(
hidden_channels,
hidden_channels,
filter_channels,
kernel_size,
p_dropout=p_dropout,
causal=True,
)
)
self.norm_layers_2.append(LayerNorm(hidden_channels))
def forward(self, x, x_mask, h, h_mask):
"""
x: decoder input
h: encoder output
"""
self_attn_mask = commons.subsequent_mask(x_mask.size(2)).to(
device=x.device, dtype=x.dtype
)
encdec_attn_mask = h_mask.unsqueeze(2) * x_mask.unsqueeze(-1)
x = x * x_mask
for i in range(self.n_layers):
y = self.self_attn_layers[i](x, x, self_attn_mask)
y = self.drop(y)
x = self.norm_layers_0[i](x + y)
y = self.encdec_attn_layers[i](x, h, encdec_attn_mask)
y = self.drop(y)
x = self.norm_layers_1[i](x + y)
y = self.ffn_layers[i](x, x_mask)
y = self.drop(y)
x = self.norm_layers_2[i](x + y)
x = x * x_mask
return x
class MultiHeadAttention(nn.Module):
def __init__(
self,
channels,
out_channels,
n_heads,
p_dropout=0.0,
window_size=None,
heads_share=True,
block_length=None,
proximal_bias=False,
proximal_init=False,
):
super().__init__()
assert channels % n_heads == 0
self.channels = channels
self.out_channels = out_channels
self.n_heads = n_heads
self.p_dropout = p_dropout
self.window_size = window_size
self.heads_share = heads_share
self.block_length = block_length
self.proximal_bias = proximal_bias
self.proximal_init = proximal_init
self.attn = None
self.k_channels = channels // n_heads
self.conv_q = nn.Conv1d(channels, channels, 1)
self.conv_k = nn.Conv1d(channels, channels, 1)
self.conv_v = nn.Conv1d(channels, channels, 1)
self.conv_o = nn.Conv1d(channels, out_channels, 1)
self.drop = nn.Dropout(p_dropout)
if window_size is not None:
n_heads_rel = 1 if heads_share else n_heads
rel_stddev = self.k_channels**-0.5
self.emb_rel_k = nn.Parameter(
torch.randn(n_heads_rel, window_size * 2 + 1, self.k_channels)
* rel_stddev
)
self.emb_rel_v = nn.Parameter(
torch.randn(n_heads_rel, window_size * 2 + 1, self.k_channels)
* rel_stddev
)
nn.init.xavier_uniform_(self.conv_q.weight)
nn.init.xavier_uniform_(self.conv_k.weight)
nn.init.xavier_uniform_(self.conv_v.weight)
if proximal_init:
with torch.no_grad():
self.conv_k.weight.copy_(self.conv_q.weight)
self.conv_k.bias.copy_(self.conv_q.bias)
def forward(self, x, c, attn_mask=None):
q = self.conv_q(x)
k = self.conv_k(c)
v = self.conv_v(c)
x, self.attn = self.attention(q, k, v, mask=attn_mask)
x = self.conv_o(x)
return x
def attention(self, query, key, value, mask=None):
# reshape [b, d, t] -> [b, n_h, t, d_k]
b, d, t_s, t_t = (*key.size(), query.size(2))
query = query.view(b, self.n_heads, self.k_channels, t_t).transpose(2, 3)
key = key.view(b, self.n_heads, self.k_channels, t_s).transpose(2, 3)
value = value.view(b, self.n_heads, self.k_channels, t_s).transpose(2, 3)
scores = torch.matmul(query / math.sqrt(self.k_channels), key.transpose(-2, -1))
if self.window_size is not None:
assert (
t_s == t_t
), "Relative attention is only available for self-attention."
key_relative_embeddings = self._get_relative_embeddings(self.emb_rel_k, t_s)
rel_logits = self._matmul_with_relative_keys(
query / math.sqrt(self.k_channels), key_relative_embeddings
)
scores_local = self._relative_position_to_absolute_position(rel_logits)
scores = scores + scores_local
if self.proximal_bias:
assert t_s == t_t, "Proximal bias is only available for self-attention."
scores = scores + self._attention_bias_proximal(t_s).to(
device=scores.device, dtype=scores.dtype
)
if mask is not None:
scores = scores.masked_fill(mask == 0, -1e4)
if self.block_length is not None:
assert (
t_s == t_t
), "Local attention is only available for self-attention."
block_mask = (
torch.ones_like(scores)
.triu(-self.block_length)
.tril(self.block_length)
)
scores = scores.masked_fill(block_mask == 0, -1e4)
p_attn = F.softmax(scores, dim=-1) # [b, n_h, t_t, t_s]
p_attn = self.drop(p_attn)
output = torch.matmul(p_attn, value)
if self.window_size is not None:
relative_weights = self._absolute_position_to_relative_position(p_attn)
value_relative_embeddings = self._get_relative_embeddings(
self.emb_rel_v, t_s
)
output = output + self._matmul_with_relative_values(
relative_weights, value_relative_embeddings
)
output = (
output.transpose(2, 3).contiguous().view(b, d, t_t)
) # [b, n_h, t_t, d_k] -> [b, d, t_t]
return output, p_attn
def _matmul_with_relative_values(self, x, y):
"""
x: [b, h, l, m]
y: [h or 1, m, d]
ret: [b, h, l, d]
"""
ret = torch.matmul(x, y.unsqueeze(0))
return ret
def _matmul_with_relative_keys(self, x, y):
"""
x: [b, h, l, d]
y: [h or 1, m, d]
ret: [b, h, l, m]
"""
ret = torch.matmul(x, y.unsqueeze(0).transpose(-2, -1))
return ret
def _get_relative_embeddings(self, relative_embeddings, length):
max_relative_position = 2 * self.window_size + 1
# Pad first before slice to avoid using cond ops.
pad_length = max(length - (self.window_size + 1), 0)
slice_start_position = max((self.window_size + 1) - length, 0)
slice_end_position = slice_start_position + 2 * length - 1
if pad_length > 0:
padded_relative_embeddings = F.pad(
relative_embeddings,
commons.convert_pad_shape([[0, 0], [pad_length, pad_length], [0, 0]]),
)
else:
padded_relative_embeddings = relative_embeddings
used_relative_embeddings = padded_relative_embeddings[
:, slice_start_position:slice_end_position
]
return used_relative_embeddings
def _relative_position_to_absolute_position(self, x):
"""
x: [b, h, l, 2*l-1]
ret: [b, h, l, l]
"""
batch, heads, length, _ = x.size()
# Concat columns of pad to shift from relative to absolute indexing.
x = F.pad(x, commons.convert_pad_shape([[0, 0], [0, 0], [0, 0], [0, 1]]))
# Concat extra elements so to add up to shape (len+1, 2*len-1).
x_flat = x.view([batch, heads, length * 2 * length])
x_flat = F.pad(
x_flat, commons.convert_pad_shape([[0, 0], [0, 0], [0, length - 1]])
)
# Reshape and slice out the padded elements.
x_final = x_flat.view([batch, heads, length + 1, 2 * length - 1])[
:, :, :length, length - 1 :
]
return x_final
def _absolute_position_to_relative_position(self, x):
"""
x: [b, h, l, l]
ret: [b, h, l, 2*l-1]
"""
batch, heads, length, _ = x.size()
# padd along column
x = F.pad(
x, commons.convert_pad_shape([[0, 0], [0, 0], [0, 0], [0, length - 1]])
)
x_flat = x.view([batch, heads, length**2 + length * (length - 1)])
# add 0's in the beginning that will skew the elements after reshape
x_flat = F.pad(x_flat, commons.convert_pad_shape([[0, 0], [0, 0], [length, 0]]))
x_final = x_flat.view([batch, heads, length, 2 * length])[:, :, :, 1:]
return x_final
def _attention_bias_proximal(self, length):
"""Bias for self-attention to encourage attention to close positions.
Args:
length: an integer scalar.
Returns:
a Tensor with shape [1, 1, length, length]
"""
r = torch.arange(length, dtype=torch.float32)
diff = torch.unsqueeze(r, 0) - torch.unsqueeze(r, 1)
return torch.unsqueeze(torch.unsqueeze(-torch.log1p(torch.abs(diff)), 0), 0)
class FFN(nn.Module):
def __init__(
self,
in_channels,
out_channels,
filter_channels,
kernel_size,
p_dropout=0.0,
activation=None,
causal=False,
):
super().__init__()
self.in_channels = in_channels
self.out_channels = out_channels
self.filter_channels = filter_channels
self.kernel_size = kernel_size
self.p_dropout = p_dropout
self.activation = activation
self.causal = causal
if causal:
self.padding = self._causal_padding
else:
self.padding = self._same_padding
self.conv_1 = nn.Conv1d(in_channels, filter_channels, kernel_size)
self.conv_2 = nn.Conv1d(filter_channels, out_channels, kernel_size)
self.drop = nn.Dropout(p_dropout)
def forward(self, x, x_mask):
x = self.conv_1(self.padding(x * x_mask))
if self.activation == "gelu":
x = x * torch.sigmoid(1.702 * x)
else:
x = torch.relu(x)
x = self.drop(x)
x = self.conv_2(self.padding(x * x_mask))
return x * x_mask
def _causal_padding(self, x):
if self.kernel_size == 1:
return x
pad_l = self.kernel_size - 1
pad_r = 0
padding = [[0, 0], [0, 0], [pad_l, pad_r]]
x = F.pad(x, commons.convert_pad_shape(padding))
return x
def _same_padding(self, x):
if self.kernel_size == 1:
return x
pad_l = (self.kernel_size - 1) // 2
pad_r = self.kernel_size // 2
padding = [[0, 0], [0, 0], [pad_l, pad_r]]
x = F.pad(x, commons.convert_pad_shape(padding))
return x123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166import math
import numpy as np
import torch
from torch import nn
from torch.nn import functional as F
def init_weights(m, mean=0.0, std=0.01):
classname = m.__class__.__name__
if classname.find("Conv") != -1:
m.weight.data.normal_(mean, std)
def get_padding(kernel_size, dilation=1):
return int((kernel_size * dilation - dilation) / 2)
def convert_pad_shape(pad_shape):
l = pad_shape[::-1]
pad_shape = [item for sublist in l for item in sublist]
return pad_shape
def kl_divergence(m_p, logs_p, m_q, logs_q):
"""KL(P||Q)"""
kl = (logs_q - logs_p) - 0.5
kl += (
0.5 * (torch.exp(2.0 * logs_p) + ((m_p - m_q) ** 2)) * torch.exp(-2.0 * logs_q)
)
return kl
def rand_gumbel(shape):
"""Sample from the Gumbel distribution, protect from overflows."""
uniform_samples = torch.rand(shape) * 0.99998 + 0.00001
return -torch.log(-torch.log(uniform_samples))
def rand_gumbel_like(x):
g = rand_gumbel(x.size()).to(dtype=x.dtype, device=x.device)
return g
def slice_segments(x, ids_str, segment_size=4):
ret = torch.zeros_like(x[:, :, :segment_size])
for i in range(x.size(0)):
idx_str = ids_str[i]
idx_end = idx_str + segment_size
ret[i] = x[i, :, idx_str:idx_end]
return ret
def slice_segments2(x, ids_str, segment_size=4):
ret = torch.zeros_like(x[:, :segment_size])
for i in range(x.size(0)):
idx_str = ids_str[i]
idx_end = idx_str + segment_size
ret[i] = x[i, idx_str:idx_end]
return ret
def rand_slice_segments(x, x_lengths=None, segment_size=4):
b, d, t = x.size()
if x_lengths is None:
x_lengths = t
ids_str_max = x_lengths - segment_size + 1
ids_str = (torch.rand([b]).to(device=x.device) * ids_str_max).to(dtype=torch.long)
ret = slice_segments(x, ids_str, segment_size)
return ret, ids_str
def get_timing_signal_1d(length, channels, min_timescale=1.0, max_timescale=1.0e4):
position = torch.arange(length, dtype=torch.float)
num_timescales = channels // 2
log_timescale_increment = math.log(float(max_timescale) / float(min_timescale)) / (
num_timescales - 1
)
inv_timescales = min_timescale * torch.exp(
torch.arange(num_timescales, dtype=torch.float) * -log_timescale_increment
)
scaled_time = position.unsqueeze(0) * inv_timescales.unsqueeze(1)
signal = torch.cat([torch.sin(scaled_time), torch.cos(scaled_time)], 0)
signal = F.pad(signal, [0, 0, 0, channels % 2])
signal = signal.view(1, channels, length)
return signal
def add_timing_signal_1d(x, min_timescale=1.0, max_timescale=1.0e4):
b, channels, length = x.size()
signal = get_timing_signal_1d(length, channels, min_timescale, max_timescale)
return x + signal.to(dtype=x.dtype, device=x.device)
def cat_timing_signal_1d(x, min_timescale=1.0, max_timescale=1.0e4, axis=1):
b, channels, length = x.size()
signal = get_timing_signal_1d(length, channels, min_timescale, max_timescale)
return torch.cat([x, signal.to(dtype=x.dtype, device=x.device)], axis)
def subsequent_mask(length):
mask = torch.tril(torch.ones(length, length)).unsqueeze(0).unsqueeze(0)
return mask
@torch.jit.script
def fused_add_tanh_sigmoid_multiply(input_a, input_b, n_channels):
n_channels_int = n_channels[0]
in_act = input_a + input_b
t_act = torch.tanh(in_act[:, :n_channels_int, :])
s_act = torch.sigmoid(in_act[:, n_channels_int:, :])
acts = t_act * s_act
return acts
def convert_pad_shape(pad_shape):
l = pad_shape[::-1]
pad_shape = [item for sublist in l for item in sublist]
return pad_shape
def shift_1d(x):
x = F.pad(x, convert_pad_shape([[0, 0], [0, 0], [1, 0]]))[:, :, :-1]
return x
def sequence_mask(length, max_length=None):
if max_length is None:
max_length = length.max()
x = torch.arange(max_length, dtype=length.dtype, device=length.device)
return x.unsqueeze(0) < length.unsqueeze(1)
def generate_path(duration, mask):
"""
duration: [b, 1, t_x]
mask: [b, 1, t_y, t_x]
"""
device = duration.device
b, _, t_y, t_x = mask.shape
cum_duration = torch.cumsum(duration, -1)
cum_duration_flat = cum_duration.view(b * t_x)
path = sequence_mask(cum_duration_flat, t_y).to(mask.dtype)
path = path.view(b, t_x, t_y)
path = path - F.pad(path, convert_pad_shape([[0, 0], [1, 0], [0, 0]]))[:, :-1]
path = path.unsqueeze(1).transpose(2, 3) * mask
return path
def clip_grad_value_(parameters, clip_value, norm_type=2):
if isinstance(parameters, torch.Tensor):
parameters = [parameters]
parameters = list(filter(lambda p: p.grad is not None, parameters))
norm_type = float(norm_type)
if clip_value is not None:
clip_value = float(clip_value)
total_norm = 0
for p in parameters:
param_norm = p.grad.data.norm(norm_type)
total_norm += param_norm.item() ** norm_type
if clip_value is not None:
p.grad.data.clamp_(min=-clip_value, max=clip_value)
total_norm = total_norm ** (1.0 / norm_type)
return total_norm12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142import math, pdb, os
from time import time as ttime
import torch
from torch import nn
from torch.nn import functional as F
from lib.infer_pack import modules
from lib.infer_pack import attentions
from lib.infer_pack import commons
from lib.infer_pack.commons import init_weights, get_padding
from torch.nn import Conv1d, ConvTranspose1d, AvgPool1d, Conv2d
from torch.nn.utils import weight_norm, remove_weight_norm, spectral_norm
from lib.infer_pack.commons import init_weights
import numpy as np
from lib.infer_pack import commons
class TextEncoder256(nn.Module):
def __init__(
self,
out_channels,
hidden_channels,
filter_channels,
n_heads,
n_layers,
kernel_size,
p_dropout,
f0=True,
):
super().__init__()
self.out_channels = out_channels
self.hidden_channels = hidden_channels
self.filter_channels = filter_channels
self.n_heads = n_heads
self.n_layers = n_layers
self.kernel_size = kernel_size
self.p_dropout = p_dropout
self.emb_phone = nn.Linear(256, hidden_channels)
self.lrelu = nn.LeakyReLU(0.1, inplace=True)
if f0 == True:
self.emb_pitch = nn.Embedding(256, hidden_channels) # pitch 256
self.encoder = attentions.Encoder(
hidden_channels, filter_channels, n_heads, n_layers, kernel_size, p_dropout
)
self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1)
def forward(self, phone, pitch, lengths):
if pitch == None:
x = self.emb_phone(phone)
else:
x = self.emb_phone(phone) + self.emb_pitch(pitch)
x = x * math.sqrt(self.hidden_channels) # [b, t, h]
x = self.lrelu(x)
x = torch.transpose(x, 1, -1) # [b, h, t]
x_mask = torch.unsqueeze(commons.sequence_mask(lengths, x.size(2)), 1).to(
x.dtype
)
x = self.encoder(x * x_mask, x_mask)
stats = self.proj(x) * x_mask
m, logs = torch.split(stats, self.out_channels, dim=1)
return m, logs, x_mask
class TextEncoder768(nn.Module):
def __init__(
self,
out_channels,
hidden_channels,
filter_channels,
n_heads,
n_layers,
kernel_size,
p_dropout,
f0=True,
):
super().__init__()
self.out_channels = out_channels
self.hidden_channels = hidden_channels
self.filter_channels = filter_channels
self.n_heads = n_heads
self.n_layers = n_layers
self.kernel_size = kernel_size
self.p_dropout = p_dropout
self.emb_phone = nn.Linear(768, hidden_channels)
self.lrelu = nn.LeakyReLU(0.1, inplace=True)
if f0 == True:
self.emb_pitch = nn.Embedding(256, hidden_channels) # pitch 256
self.encoder = attentions.Encoder(
hidden_channels, filter_channels, n_heads, n_layers, kernel_size, p_dropout
)
self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1)
def forward(self, phone, pitch, lengths):
if pitch == None:
x = self.emb_phone(phone)
else:
x = self.emb_phone(phone) + self.emb_pitch(pitch)
x = x * math.sqrt(self.hidden_channels) # [b, t, h]
x = self.lrelu(x)
x = torch.transpose(x, 1, -1) # [b, h, t]
x_mask = torch.unsqueeze(commons.sequence_mask(lengths, x.size(2)), 1).to(
x.dtype
)
x = self.encoder(x * x_mask, x_mask)
stats = self.proj(x) * x_mask
m, logs = torch.split(stats, self.out_channels, dim=1)
return m, logs, x_mask
class ResidualCouplingBlock(nn.Module):
def __init__(
self,
channels,
hidden_channels,
kernel_size,
dilation_rate,
n_layers,
n_flows=4,
gin_channels=0,
):
super().__init__()
self.channels = channels
self.hidden_channels = hidden_channels
self.kernel_size = kernel_size
self.dilation_rate = dilation_rate
self.n_layers = n_layers
self.n_flows = n_flows
self.gin_channels = gin_channels
self.flows = nn.ModuleList()
for i in range(n_flows):
self.flows.append(
modules.ResidualCouplingLayer(
channels,
hidden_channels,
kernel_size,
dilation_rate,
n_layers,
gin_channels=gin_channels,
mean_only=True,
)
)
self.flows.append(modules.Flip())
def forward(self, x, x_mask, g=None, reverse=False):
if not reverse:
for flow in self.flows:
x, _ = flow(x, x_mask, g=g, reverse=reverse)
else:
for flow in reversed(self.flows):
x = flow(x, x_mask, g=g, reverse=reverse)
return x
def remove_weight_norm(self):
for i in range(self.n_flows):
self.flows[i * 2].remove_weight_norm()
class PosteriorEncoder(nn.Module):
def __init__(
self,
in_channels,
out_channels,
hidden_channels,
kernel_size,
dilation_rate,
n_layers,
gin_channels=0,
):
super().__init__()
self.in_channels = in_channels
self.out_channels = out_channels
self.hidden_channels = hidden_channels
self.kernel_size = kernel_size
self.dilation_rate = dilation_rate
self.n_layers = n_layers
self.gin_channels = gin_channels
self.pre = nn.Conv1d(in_channels, hidden_channels, 1)
self.enc = modules.WN(
hidden_channels,
kernel_size,
dilation_rate,
n_layers,
gin_channels=gin_channels,
)
self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1)
def forward(self, x, x_lengths, g=None):
x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(2)), 1).to(
x.dtype
)
x = self.pre(x) * x_mask
x = self.enc(x, x_mask, g=g)
stats = self.proj(x) * x_mask
m, logs = torch.split(stats, self.out_channels, dim=1)
z = (m + torch.randn_like(m) * torch.exp(logs)) * x_mask
return z, m, logs, x_mask
def remove_weight_norm(self):
self.enc.remove_weight_norm()
class Generator(torch.nn.Module):
def __init__(
self,
initial_channel,
resblock,
resblock_kernel_sizes,
resblock_dilation_sizes,
upsample_rates,
upsample_initial_channel,
upsample_kernel_sizes,
gin_channels=0,
):
super(Generator, self).__init__()
self.num_kernels = len(resblock_kernel_sizes)
self.num_upsamples = len(upsample_rates)
self.conv_pre = Conv1d(
initial_channel, upsample_initial_channel, 7, 1, padding=3
)
resblock = modules.ResBlock1 if resblock == "1" else modules.ResBlock2
self.ups = nn.ModuleList()
for i, (u, k) in enumerate(zip(upsample_rates, upsample_kernel_sizes)):
self.ups.append(
weight_norm(
ConvTranspose1d(
upsample_initial_channel // (2**i),
upsample_initial_channel // (2 ** (i + 1)),
k,
u,
padding=(k - u) // 2,
)
)
)
self.resblocks = nn.ModuleList()
for i in range(len(self.ups)):
ch = upsample_initial_channel // (2 ** (i + 1))
for j, (k, d) in enumerate(
zip(resblock_kernel_sizes, resblock_dilation_sizes)
):
self.resblocks.append(resblock(ch, k, d))
self.conv_post = Conv1d(ch, 1, 7, 1, padding=3, bias=False)
self.ups.apply(init_weights)
if gin_channels != 0:
self.cond = nn.Conv1d(gin_channels, upsample_initial_channel, 1)
def forward(self, x, g=None):
x = self.conv_pre(x)
if g is not None:
x = x + self.cond(g)
for i in range(self.num_upsamples):
x = F.leaky_relu(x, modules.LRELU_SLOPE)
x = self.ups[i](x)
xs = None
for j in range(self.num_kernels):
if xs is None:
xs = self.resblocks[i * self.num_kernels + j](x)
else:
xs += self.resblocks[i * self.num_kernels + j](x)
x = xs / self.num_kernels
x = F.leaky_relu(x)
x = self.conv_post(x)
x = torch.tanh(x)
return x
def remove_weight_norm(self):
for l in self.ups:
remove_weight_norm(l)
for l in self.resblocks:
l.remove_weight_norm()
class SineGen(torch.nn.Module):
"""Definition of sine generator
SineGen(samp_rate, harmonic_num = 0,
sine_amp = 0.1, noise_std = 0.003,
voiced_threshold = 0,
flag_for_pulse=False)
samp_rate: sampling rate in Hz
harmonic_num: number of harmonic overtones (default 0)
sine_amp: amplitude of sine-wavefrom (default 0.1)
noise_std: std of Gaussian noise (default 0.003)
voiced_thoreshold: F0 threshold for U/V classification (default 0)
flag_for_pulse: this SinGen is used inside PulseGen (default False)
Note: when flag_for_pulse is True, the first time step of a voiced
segment is always sin(np.pi) or cos(0)
"""
def __init__(
self,
samp_rate,
harmonic_num=0,
sine_amp=0.1,
noise_std=0.003,
voiced_threshold=0,
flag_for_pulse=False,
):
super(SineGen, self).__init__()
self.sine_amp = sine_amp
self.noise_std = noise_std
self.harmonic_num = harmonic_num
self.dim = self.harmonic_num + 1
self.sampling_rate = samp_rate
self.voiced_threshold = voiced_threshold
def _f02uv(self, f0):
# generate uv signal
uv = torch.ones_like(f0)
uv = uv * (f0 > self.voiced_threshold)
return uv
def forward(self, f0, upp):
"""sine_tensor, uv = forward(f0)
input F0: tensor(batchsize=1, length, dim=1)
f0 for unvoiced steps should be 0
output sine_tensor: tensor(batchsize=1, length, dim)
output uv: tensor(batchsize=1, length, 1)
"""
with torch.no_grad():
f0 = f0[:, None].transpose(1, 2)
f0_buf = torch.zeros(f0.shape[0], f0.shape[1], self.dim, device=f0.device)
# fundamental component
f0_buf[:, :, 0] = f0[:, :, 0]
for idx in np.arange(self.harmonic_num):
f0_buf[:, :, idx + 1] = f0_buf[:, :, 0] * (
idx + 2
) # idx + 2: the (idx+1)-th overtone, (idx+2)-th harmonic
rad_values = (f0_buf / self.sampling_rate) % 1 ###%1 means that the product of n_har cannot be post-processed and optimized
rand_ini = torch.rand(
f0_buf.shape[0], f0_buf.shape[2], device=f0_buf.device
)
rand_ini[:, 0] = 0
rad_values[:, 0, :] = rad_values[:, 0, :] + rand_ini
tmp_over_one = torch.cumsum(rad_values, 1) # % 1 #####%1 means that the following cumsum can no longer be optimized
tmp_over_one *= upp
tmp_over_one = F.interpolate(
tmp_over_one.transpose(2, 1),
scale_factor=upp,
mode="linear",
align_corners=True,
).transpose(2, 1)
rad_values = F.interpolate(
rad_values.transpose(2, 1), scale_factor=upp, mode="nearest"
).transpose(
2, 1
) #######
tmp_over_one %= 1
tmp_over_one_idx = (tmp_over_one[:, 1:, :] - tmp_over_one[:, :-1, :]) < 0
cumsum_shift = torch.zeros_like(rad_values)
cumsum_shift[:, 1:, :] = tmp_over_one_idx * -1.0
sine_waves = torch.sin(
torch.cumsum(rad_values + cumsum_shift, dim=1) * 2 * np.pi
)
sine_waves = sine_waves * self.sine_amp
uv = self._f02uv(f0)
uv = F.interpolate(
uv.transpose(2, 1), scale_factor=upp, mode="nearest"
).transpose(2, 1)
noise_amp = uv * self.noise_std + (1 - uv) * self.sine_amp / 3
noise = noise_amp * torch.randn_like(sine_waves)
sine_waves = sine_waves * uv + noise
return sine_waves, uv, noise
class SourceModuleHnNSF(torch.nn.Module):
"""SourceModule for hn-nsf
SourceModule(sampling_rate, harmonic_num=0, sine_amp=0.1,
add_noise_std=0.003, voiced_threshod=0)
sampling_rate: sampling_rate in Hz
harmonic_num: number of harmonic above F0 (default: 0)
sine_amp: amplitude of sine source signal (default: 0.1)
add_noise_std: std of additive Gaussian noise (default: 0.003)
note that amplitude of noise in unvoiced is decided
by sine_amp
voiced_threshold: threhold to set U/V given F0 (default: 0)
Sine_source, noise_source = SourceModuleHnNSF(F0_sampled)
F0_sampled (batchsize, length, 1)
Sine_source (batchsize, length, 1)
noise_source (batchsize, length 1)
uv (batchsize, length, 1)
"""
def __init__(
self,
sampling_rate,
harmonic_num=0,
sine_amp=0.1,
add_noise_std=0.003,
voiced_threshod=0,
is_half=True,
):
super(SourceModuleHnNSF, self).__init__()
self.sine_amp = sine_amp
self.noise_std = add_noise_std
self.is_half = is_half
# to produce sine waveforms
self.l_sin_gen = SineGen(
sampling_rate, harmonic_num, sine_amp, add_noise_std, voiced_threshod
)
# to merge source harmonics into a single excitation
self.l_linear = torch.nn.Linear(harmonic_num + 1, 1)
self.l_tanh = torch.nn.Tanh()
def forward(self, x, upp=None):
sine_wavs, uv, _ = self.l_sin_gen(x, upp)
if self.is_half:
sine_wavs = sine_wavs.half()
sine_merge = self.l_tanh(self.l_linear(sine_wavs))
return sine_merge, None, None # noise, uv
class GeneratorNSF(torch.nn.Module):
def __init__(
self,
initial_channel,
resblock,
resblock_kernel_sizes,
resblock_dilation_sizes,
upsample_rates,
upsample_initial_channel,
upsample_kernel_sizes,
gin_channels,
sr,
is_half=False,
):
super(GeneratorNSF, self).__init__()
self.num_kernels = len(resblock_kernel_sizes)
self.num_upsamples = len(upsample_rates)
self.f0_upsamp = torch.nn.Upsample(scale_factor=np.prod(upsample_rates))
self.m_source = SourceModuleHnNSF(
sampling_rate=sr, harmonic_num=0, is_half=is_half
)
self.noise_convs = nn.ModuleList()
self.conv_pre = Conv1d(
initial_channel, upsample_initial_channel, 7, 1, padding=3
)
resblock = modules.ResBlock1 if resblock == "1" else modules.ResBlock2
self.ups = nn.ModuleList()
for i, (u, k) in enumerate(zip(upsample_rates, upsample_kernel_sizes)):
c_cur = upsample_initial_channel // (2 ** (i + 1))
self.ups.append(
weight_norm(
ConvTranspose1d(
upsample_initial_channel // (2**i),
upsample_initial_channel // (2 ** (i + 1)),
k,
u,
padding=(k - u) // 2,
)
)
)
if i + 1 < len(upsample_rates):
stride_f0 = np.prod(upsample_rates[i + 1 :])
self.noise_convs.append(
Conv1d(
1,
c_cur,
kernel_size=stride_f0 * 2,
stride=stride_f0,
padding=stride_f0 // 2,
)
)
else:
self.noise_convs.append(Conv1d(1, c_cur, kernel_size=1))
self.resblocks = nn.ModuleList()
for i in range(len(self.ups)):
ch = upsample_initial_channel // (2 ** (i + 1))
for j, (k, d) in enumerate(
zip(resblock_kernel_sizes, resblock_dilation_sizes)
):
self.resblocks.append(resblock(ch, k, d))
self.conv_post = Conv1d(ch, 1, 7, 1, padding=3, bias=False)
self.ups.apply(init_weights)
if gin_channels != 0:
self.cond = nn.Conv1d(gin_channels, upsample_initial_channel, 1)
self.upp = np.prod(upsample_rates)
def forward(self, x, f0, g=None):
har_source, noi_source, uv = self.m_source(f0, self.upp)
har_source = har_source.transpose(1, 2)
x = self.conv_pre(x)
if g is not None:
x = x + self.cond(g)
for i in range(self.num_upsamples):
x = F.leaky_relu(x, modules.LRELU_SLOPE)
x = self.ups[i](x)
x_source = self.noise_convs[i](har_source)
x = x + x_source
xs = None
for j in range(self.num_kernels):
if xs is None:
xs = self.resblocks[i * self.num_kernels + j](x)
else:
xs += self.resblocks[i * self.num_kernels + j](x)
x = xs / self.num_kernels
x = F.leaky_relu(x)
x = self.conv_post(x)
x = torch.tanh(x)
return x
def remove_weight_norm(self):
for l in self.ups:
remove_weight_norm(l)
for l in self.resblocks:
l.remove_weight_norm()
sr2sr = {
"32k": 32000,
"40k": 40000,
"48k": 48000,
}
class SynthesizerTrnMs256NSFsid(nn.Module):
def __init__(
self,
spec_channels,
segment_size,
inter_channels,
hidden_channels,
filter_channels,
n_heads,
n_layers,
kernel_size,
p_dropout,
resblock,
resblock_kernel_sizes,
resblock_dilation_sizes,
upsample_rates,
upsample_initial_channel,
upsample_kernel_sizes,
spk_embed_dim,
gin_channels,
sr,
**kwargs
):
super().__init__()
if type(sr) == type("strr"):
sr = sr2sr[sr]
self.spec_channels = spec_channels
self.inter_channels = inter_channels
self.hidden_channels = hidden_channels
self.filter_channels = filter_channels
self.n_heads = n_heads
self.n_layers = n_layers
self.kernel_size = kernel_size
self.p_dropout = p_dropout
self.resblock = resblock
self.resblock_kernel_sizes = resblock_kernel_sizes
self.resblock_dilation_sizes = resblock_dilation_sizes
self.upsample_rates = upsample_rates
self.upsample_initial_channel = upsample_initial_channel
self.upsample_kernel_sizes = upsample_kernel_sizes
self.segment_size = segment_size
self.gin_channels = gin_channels
# self.hop_length = hop_length#
self.spk_embed_dim = spk_embed_dim
self.enc_p = TextEncoder256(
inter_channels,
hidden_channels,
filter_channels,
n_heads,
n_layers,
kernel_size,
p_dropout,
)
self.dec = GeneratorNSF(
inter_channels,
resblock,
resblock_kernel_sizes,
resblock_dilation_sizes,
upsample_rates,
upsample_initial_channel,
upsample_kernel_sizes,
gin_channels=gin_channels,
sr=sr,
is_half=kwargs["is_half"],
)
self.enc_q = PosteriorEncoder(
spec_channels,
inter_channels,
hidden_channels,
5,
1,
16,
gin_channels=gin_channels,
)
self.flow = ResidualCouplingBlock(
inter_channels, hidden_channels, 5, 1, 3, gin_channels=gin_channels
)
self.emb_g = nn.Embedding(self.spk_embed_dim, gin_channels)
print("gin_channels:", gin_channels, "self.spk_embed_dim:", self.spk_embed_dim)
def remove_weight_norm(self):
self.dec.remove_weight_norm()
self.flow.remove_weight_norm()
self.enc_q.remove_weight_norm()
def forward(
self, phone, phone_lengths, pitch, pitchf, y, y_lengths, ds
): # Here ds is id, [bs,1]
# print(1,pitch.shape)#[bs,t]
g = self.emb_g(ds).unsqueeze(-1) # [b, 256, 1]##1 is t, broadcast
m_p, logs_p, x_mask = self.enc_p(phone, pitch, phone_lengths)
z, m_q, logs_q, y_mask = self.enc_q(y, y_lengths, g=g)
z_p = self.flow(z, y_mask, g=g)
z_slice, ids_slice = commons.rand_slice_segments(
z, y_lengths, self.segment_size
)
# print(-1,pitchf.shape,ids_slice,self.segment_size,self.hop_length,self.segment_size//self.hop_length)
pitchf = commons.slice_segments2(pitchf, ids_slice, self.segment_size)
# print(-2,pitchf.shape,z_slice.shape)
o = self.dec(z_slice, pitchf, g=g)
return o, ids_slice, x_mask, y_mask, (z, z_p, m_p, logs_p, m_q, logs_q)
def infer(self, phone, phone_lengths, pitch, nsff0, sid, rate=None):
g = self.emb_g(sid).unsqueeze(-1)
m_p, logs_p, x_mask = self.enc_p(phone, pitch, phone_lengths)
z_p = (m_p + torch.exp(logs_p) * torch.randn_like(m_p) * 0.66666) * x_mask
if rate:
head = int(z_p.shape[2] * rate)
z_p = z_p[:, :, -head:]
x_mask = x_mask[:, :, -head:]
nsff0 = nsff0[:, -head:]
z = self.flow(z_p, x_mask, g=g, reverse=True)
o = self.dec(z * x_mask, nsff0, g=g)
return o, x_mask, (z, z_p, m_p, logs_p)
class SynthesizerTrnMs768NSFsid(nn.Module):
def __init__(
self,
spec_channels,
segment_size,
inter_channels,
hidden_channels,
filter_channels,
n_heads,
n_layers,
kernel_size,
p_dropout,
resblock,
resblock_kernel_sizes,
resblock_dilation_sizes,
upsample_rates,
upsample_initial_channel,
upsample_kernel_sizes,
spk_embed_dim,
gin_channels,
sr,
**kwargs
):
super().__init__()
if type(sr) == type("strr"):
sr = sr2sr[sr]
self.spec_channels = spec_channels
self.inter_channels = inter_channels
self.hidden_channels = hidden_channels
self.filter_channels = filter_channels
self.n_heads = n_heads
self.n_layers = n_layers
self.kernel_size = kernel_size
self.p_dropout = p_dropout
self.resblock = resblock
self.resblock_kernel_sizes = resblock_kernel_sizes
self.resblock_dilation_sizes = resblock_dilation_sizes
self.upsample_rates = upsample_rates
self.upsample_initial_channel = upsample_initial_channel
self.upsample_kernel_sizes = upsample_kernel_sizes
self.segment_size = segment_size
self.gin_channels = gin_channels
# self.hop_length = hop_length#
self.spk_embed_dim = spk_embed_dim
self.enc_p = TextEncoder768(
inter_channels,
hidden_channels,
filter_channels,
n_heads,
n_layers,
kernel_size,
p_dropout,
)
self.dec = GeneratorNSF(
inter_channels,
resblock,
resblock_kernel_sizes,
resblock_dilation_sizes,
upsample_rates,
upsample_initial_channel,
upsample_kernel_sizes,
gin_channels=gin_channels,
sr=sr,
is_half=kwargs["is_half"],
)
self.enc_q = PosteriorEncoder(
spec_channels,
inter_channels,
hidden_channels,
5,
1,
16,
gin_channels=gin_channels,
)
self.flow = ResidualCouplingBlock(
inter_channels, hidden_channels, 5, 1, 3, gin_channels=gin_channels
)
self.emb_g = nn.Embedding(self.spk_embed_dim, gin_channels)
print("gin_channels:", gin_channels, "self.spk_embed_dim:", self.spk_embed_dim)
def remove_weight_norm(self):
self.dec.remove_weight_norm()
self.flow.remove_weight_norm()
self.enc_q.remove_weight_norm()
def forward(
self, phone, phone_lengths, pitch, pitchf, y, y_lengths, ds
): # Here ds is id,[bs,1]
# print(1,pitch.shape)#[bs,t]
g = self.emb_g(ds).unsqueeze(-1) # [b, 256, 1]##1 is t, broadcast
m_p, logs_p, x_mask = self.enc_p(phone, pitch, phone_lengths)
z, m_q, logs_q, y_mask = self.enc_q(y, y_lengths, g=g)
z_p = self.flow(z, y_mask, g=g)
z_slice, ids_slice = commons.rand_slice_segments(
z, y_lengths, self.segment_size
)
# print(-1,pitchf.shape,ids_slice,self.segment_size,self.hop_length,self.segment_size//self.hop_length)
pitchf = commons.slice_segments2(pitchf, ids_slice, self.segment_size)
# print(-2,pitchf.shape,z_slice.shape)
o = self.dec(z_slice, pitchf, g=g)
return o, ids_slice, x_mask, y_mask, (z, z_p, m_p, logs_p, m_q, logs_q)
def infer(self, phone, phone_lengths, pitch, nsff0, sid, rate=None):
g = self.emb_g(sid).unsqueeze(-1)
m_p, logs_p, x_mask = self.enc_p(phone, pitch, phone_lengths)
z_p = (m_p + torch.exp(logs_p) * torch.randn_like(m_p) * 0.66666) * x_mask
if rate:
head = int(z_p.shape[2] * rate)
z_p = z_p[:, :, -head:]
x_mask = x_mask[:, :, -head:]
nsff0 = nsff0[:, -head:]
z = self.flow(z_p, x_mask, g=g, reverse=True)
o = self.dec(z * x_mask, nsff0, g=g)
return o, x_mask, (z, z_p, m_p, logs_p)
class SynthesizerTrnMs256NSFsid_nono(nn.Module):
def __init__(
self,
spec_channels,
segment_size,
inter_channels,
hidden_channels,
filter_channels,
n_heads,
n_layers,
kernel_size,
p_dropout,
resblock,
resblock_kernel_sizes,
resblock_dilation_sizes,
upsample_rates,
upsample_initial_channel,
upsample_kernel_sizes,
spk_embed_dim,
gin_channels,
sr=None,
**kwargs
):
super().__init__()
self.spec_channels = spec_channels
self.inter_channels = inter_channels
self.hidden_channels = hidden_channels
self.filter_channels = filter_channels
self.n_heads = n_heads
self.n_layers = n_layers
self.kernel_size = kernel_size
self.p_dropout = p_dropout
self.resblock = resblock
self.resblock_kernel_sizes = resblock_kernel_sizes
self.resblock_dilation_sizes = resblock_dilation_sizes
self.upsample_rates = upsample_rates
self.upsample_initial_channel = upsample_initial_channel
self.upsample_kernel_sizes = upsample_kernel_sizes
self.segment_size = segment_size
self.gin_channels = gin_channels
# self.hop_length = hop_length#
self.spk_embed_dim = spk_embed_dim
self.enc_p = TextEncoder256(
inter_channels,
hidden_channels,
filter_channels,
n_heads,
n_layers,
kernel_size,
p_dropout,
f0=False,
)
self.dec = Generator(
inter_channels,
resblock,
resblock_kernel_sizes,
resblock_dilation_sizes,
upsample_rates,
upsample_initial_channel,
upsample_kernel_sizes,
gin_channels=gin_channels,
)
self.enc_q = PosteriorEncoder(
spec_channels,
inter_channels,
hidden_channels,
5,
1,
16,
gin_channels=gin_channels,
)
self.flow = ResidualCouplingBlock(
inter_channels, hidden_channels, 5, 1, 3, gin_channels=gin_channels
)
self.emb_g = nn.Embedding(self.spk_embed_dim, gin_channels)
print("gin_channels:", gin_channels, "self.spk_embed_dim:", self.spk_embed_dim)
def remove_weight_norm(self):
self.dec.remove_weight_norm()
self.flow.remove_weight_norm()
self.enc_q.remove_weight_norm()
def forward(self, phone, phone_lengths, y, y_lengths, ds): # Here ds is id,[bs,1]
g = self.emb_g(ds).unsqueeze(-1) # [b, 256, 1]##1 is t, broadcast
m_p, logs_p, x_mask = self.enc_p(phone, None, phone_lengths)
z, m_q, logs_q, y_mask = self.enc_q(y, y_lengths, g=g)
z_p = self.flow(z, y_mask, g=g)
z_slice, ids_slice = commons.rand_slice_segments(
z, y_lengths, self.segment_size
)
o = self.dec(z_slice, g=g)
return o, ids_slice, x_mask, y_mask, (z, z_p, m_p, logs_p, m_q, logs_q)
def infer(self, phone, phone_lengths, sid, rate=None):
g = self.emb_g(sid).unsqueeze(-1)
m_p, logs_p, x_mask = self.enc_p(phone, None, phone_lengths)
z_p = (m_p + torch.exp(logs_p) * torch.randn_like(m_p) * 0.66666) * x_mask
if rate:
head = int(z_p.shape[2] * rate)
z_p = z_p[:, :, -head:]
x_mask = x_mask[:, :, -head:]
z = self.flow(z_p, x_mask, g=g, reverse=True)
o = self.dec(z * x_mask, g=g)
return o, x_mask, (z, z_p, m_p, logs_p)
class SynthesizerTrnMs768NSFsid_nono(nn.Module):
def __init__(
self,
spec_channels,
segment_size,
inter_channels,
hidden_channels,
filter_channels,
n_heads,
n_layers,
kernel_size,
p_dropout,
resblock,
resblock_kernel_sizes,
resblock_dilation_sizes,
upsample_rates,
upsample_initial_channel,
upsample_kernel_sizes,
spk_embed_dim,
gin_channels,
sr=None,
**kwargs
):
super().__init__()
self.spec_channels = spec_channels
self.inter_channels = inter_channels
self.hidden_channels = hidden_channels
self.filter_channels = filter_channels
self.n_heads = n_heads
self.n_layers = n_layers
self.kernel_size = kernel_size
self.p_dropout = p_dropout
self.resblock = resblock
self.resblock_kernel_sizes = resblock_kernel_sizes
self.resblock_dilation_sizes = resblock_dilation_sizes
self.upsample_rates = upsample_rates
self.upsample_initial_channel = upsample_initial_channel
self.upsample_kernel_sizes = upsample_kernel_sizes
self.segment_size = segment_size
self.gin_channels = gin_channels
# self.hop_length = hop_length#
self.spk_embed_dim = spk_embed_dim
self.enc_p = TextEncoder768(
inter_channels,
hidden_channels,
filter_channels,
n_heads,
n_layers,
kernel_size,
p_dropout,
f0=False,
)
self.dec = Generator(
inter_channels,
resblock,
resblock_kernel_sizes,
resblock_dilation_sizes,
upsample_rates,
upsample_initial_channel,
upsample_kernel_sizes,
gin_channels=gin_channels,
)
self.enc_q = PosteriorEncoder(
spec_channels,
inter_channels,
hidden_channels,
5,
1,
16,
gin_channels=gin_channels,
)
self.flow = ResidualCouplingBlock(
inter_channels, hidden_channels, 5, 1, 3, gin_channels=gin_channels
)
self.emb_g = nn.Embedding(self.spk_embed_dim, gin_channels)
print("gin_channels:", gin_channels, "self.spk_embed_dim:", self.spk_embed_dim)
def remove_weight_norm(self):
self.dec.remove_weight_norm()
self.flow.remove_weight_norm()
self.enc_q.remove_weight_norm()
def forward(self, phone, phone_lengths, y, y_lengths, ds): # Here ds is id,[bs,1]
g = self.emb_g(ds).unsqueeze(-1) # [b, 256, 1]##1 is t, broadcast
m_p, logs_p, x_mask = self.enc_p(phone, None, phone_lengths)
z, m_q, logs_q, y_mask = self.enc_q(y, y_lengths, g=g)
z_p = self.flow(z, y_mask, g=g)
z_slice, ids_slice = commons.rand_slice_segments(
z, y_lengths, self.segment_size
)
o = self.dec(z_slice, g=g)
return o, ids_slice, x_mask, y_mask, (z, z_p, m_p, logs_p, m_q, logs_q)
def infer(self, phone, phone_lengths, sid, rate=None):
g = self.emb_g(sid).unsqueeze(-1)
m_p, logs_p, x_mask = self.enc_p(phone, None, phone_lengths)
z_p = (m_p + torch.exp(logs_p) * torch.randn_like(m_p) * 0.66666) * x_mask
if rate:
head = int(z_p.shape[2] * rate)
z_p = z_p[:, :, -head:]
x_mask = x_mask[:, :, -head:]
z = self.flow(z_p, x_mask, g=g, reverse=True)
o = self.dec(z * x_mask, g=g)
return o, x_mask, (z, z_p, m_p, logs_p)
class MultiPeriodDiscriminator(torch.nn.Module):
def __init__(self, use_spectral_norm=False):
super(MultiPeriodDiscriminator, self).__init__()
periods = [2, 3, 5, 7, 11, 17]
# periods = [3, 5, 7, 11, 17, 23, 37]
discs = [DiscriminatorS(use_spectral_norm=use_spectral_norm)]
discs = discs + [
DiscriminatorP(i, use_spectral_norm=use_spectral_norm) for i in periods
]
self.discriminators = nn.ModuleList(discs)
def forward(self, y, y_hat):
y_d_rs = [] #
y_d_gs = []
fmap_rs = []
fmap_gs = []
for i, d in enumerate(self.discriminators):
y_d_r, fmap_r = d(y)
y_d_g, fmap_g = d(y_hat)
# for j in range(len(fmap_r)):
# print(i,j,y.shape,y_hat.shape,fmap_r[j].shape,fmap_g[j].shape)
y_d_rs.append(y_d_r)
y_d_gs.append(y_d_g)
fmap_rs.append(fmap_r)
fmap_gs.append(fmap_g)
return y_d_rs, y_d_gs, fmap_rs, fmap_gs
class MultiPeriodDiscriminatorV2(torch.nn.Module):
def __init__(self, use_spectral_norm=False):
super(MultiPeriodDiscriminatorV2, self).__init__()
# periods = [2, 3, 5, 7, 11, 17]
periods = [2, 3, 5, 7, 11, 17, 23, 37]
discs = [DiscriminatorS(use_spectral_norm=use_spectral_norm)]
discs = discs + [
DiscriminatorP(i, use_spectral_norm=use_spectral_norm) for i in periods
]
self.discriminators = nn.ModuleList(discs)
def forward(self, y, y_hat):
y_d_rs = [] #
y_d_gs = []
fmap_rs = []
fmap_gs = []
for i, d in enumerate(self.discriminators):
y_d_r, fmap_r = d(y)
y_d_g, fmap_g = d(y_hat)
# for j in range(len(fmap_r)):
# print(i,j,y.shape,y_hat.shape,fmap_r[j].shape,fmap_g[j].shape)
y_d_rs.append(y_d_r)
y_d_gs.append(y_d_g)
fmap_rs.append(fmap_r)
fmap_gs.append(fmap_g)
return y_d_rs, y_d_gs, fmap_rs, fmap_gs
class DiscriminatorS(torch.nn.Module):
def __init__(self, use_spectral_norm=False):
super(DiscriminatorS, self).__init__()
norm_f = weight_norm if use_spectral_norm == False else spectral_norm
self.convs = nn.ModuleList(
[
norm_f(Conv1d(1, 16, 15, 1, padding=7)),
norm_f(Conv1d(16, 64, 41, 4, groups=4, padding=20)),
norm_f(Conv1d(64, 256, 41, 4, groups=16, padding=20)),
norm_f(Conv1d(256, 1024, 41, 4, groups=64, padding=20)),
norm_f(Conv1d(1024, 1024, 41, 4, groups=256, padding=20)),
norm_f(Conv1d(1024, 1024, 5, 1, padding=2)),
]
)
self.conv_post = norm_f(Conv1d(1024, 1, 3, 1, padding=1))
def forward(self, x):
fmap = []
for l in self.convs:
x = l(x)
x = F.leaky_relu(x, modules.LRELU_SLOPE)
fmap.append(x)
x = self.conv_post(x)
fmap.append(x)
x = torch.flatten(x, 1, -1)
return x, fmap
class DiscriminatorP(torch.nn.Module):
def __init__(self, period, kernel_size=5, stride=3, use_spectral_norm=False):
super(DiscriminatorP, self).__init__()
self.period = period
self.use_spectral_norm = use_spectral_norm
norm_f = weight_norm if use_spectral_norm == False else spectral_norm
self.convs = nn.ModuleList(
[
norm_f(
Conv2d(
1,
32,
(kernel_size, 1),
(stride, 1),
padding=(get_padding(kernel_size, 1), 0),
)
),
norm_f(
Conv2d(
32,
128,
(kernel_size, 1),
(stride, 1),
padding=(get_padding(kernel_size, 1), 0),
)
),
norm_f(
Conv2d(
128,
512,
(kernel_size, 1),
(stride, 1),
padding=(get_padding(kernel_size, 1), 0),
)
),
norm_f(
Conv2d(
512,
1024,
(kernel_size, 1),
(stride, 1),
padding=(get_padding(kernel_size, 1), 0),
)
),
norm_f(
Conv2d(
1024,
1024,
(kernel_size, 1),
1,
padding=(get_padding(kernel_size, 1), 0),
)
),
]
)
self.conv_post = norm_f(Conv2d(1024, 1, (3, 1), 1, padding=(1, 0)))
def forward(self, x):
fmap = []
# 1d to 2d
b, c, t = x.shape
if t % self.period != 0: # pad first
n_pad = self.period - (t % self.period)
x = F.pad(x, (0, n_pad), "reflect")
t = t + n_pad
x = x.view(b, c, t // self.period, self.period)
for l in self.convs:
x = l(x)
x = F.leaky_relu(x, modules.LRELU_SLOPE)
fmap.append(x)
x = self.conv_post(x)
fmap.append(x)
x = torch.flatten(x, 1, -1)
return x, fmap123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522import copy
import math
import numpy as np
import scipy
import torch
from torch import nn
from torch.nn import functional as F
from torch.nn import Conv1d, ConvTranspose1d, AvgPool1d, Conv2d
from torch.nn.utils import weight_norm, remove_weight_norm
from lib.infer_pack import commons
from lib.infer_pack.commons import init_weights, get_padding
from lib.infer_pack.transforms import piecewise_rational_quadratic_transform
LRELU_SLOPE = 0.1
class LayerNorm(nn.Module):
def __init__(self, channels, eps=1e-5):
super().__init__()
self.channels = channels
self.eps = eps
self.gamma = nn.Parameter(torch.ones(channels))
self.beta = nn.Parameter(torch.zeros(channels))
def forward(self, x):
x = x.transpose(1, -1)
x = F.layer_norm(x, (self.channels,), self.gamma, self.beta, self.eps)
return x.transpose(1, -1)
class ConvReluNorm(nn.Module):
def __init__(
self,
in_channels,
hidden_channels,
out_channels,
kernel_size,
n_layers,
p_dropout,
):
super().__init__()
self.in_channels = in_channels
self.hidden_channels = hidden_channels
self.out_channels = out_channels
self.kernel_size = kernel_size
self.n_layers = n_layers
self.p_dropout = p_dropout
assert n_layers > 1, "Number of layers should be larger than 0."
self.conv_layers = nn.ModuleList()
self.norm_layers = nn.ModuleList()
self.conv_layers.append(
nn.Conv1d(
in_channels, hidden_channels, kernel_size, padding=kernel_size // 2
)
)
self.norm_layers.append(LayerNorm(hidden_channels))
self.relu_drop = nn.Sequential(nn.ReLU(), nn.Dropout(p_dropout))
for _ in range(n_layers - 1):
self.conv_layers.append(
nn.Conv1d(
hidden_channels,
hidden_channels,
kernel_size,
padding=kernel_size // 2,
)
)
self.norm_layers.append(LayerNorm(hidden_channels))
self.proj = nn.Conv1d(hidden_channels, out_channels, 1)
self.proj.weight.data.zero_()
self.proj.bias.data.zero_()
def forward(self, x, x_mask):
x_org = x
for i in range(self.n_layers):
x = self.conv_layers[i](x * x_mask)
x = self.norm_layers[i](x)
x = self.relu_drop(x)
x = x_org + self.proj(x)
return x * x_mask
class DDSConv(nn.Module):
"""
Dialted and Depth-Separable Convolution
"""
def __init__(self, channels, kernel_size, n_layers, p_dropout=0.0):
super().__init__()
self.channels = channels
self.kernel_size = kernel_size
self.n_layers = n_layers
self.p_dropout = p_dropout
self.drop = nn.Dropout(p_dropout)
self.convs_sep = nn.ModuleList()
self.convs_1x1 = nn.ModuleList()
self.norms_1 = nn.ModuleList()
self.norms_2 = nn.ModuleList()
for i in range(n_layers):
dilation = kernel_size**i
padding = (kernel_size * dilation - dilation) // 2
self.convs_sep.append(
nn.Conv1d(
channels,
channels,
kernel_size,
groups=channels,
dilation=dilation,
padding=padding,
)
)
self.convs_1x1.append(nn.Conv1d(channels, channels, 1))
self.norms_1.append(LayerNorm(channels))
self.norms_2.append(LayerNorm(channels))
def forward(self, x, x_mask, g=None):
if g is not None:
x = x + g
for i in range(self.n_layers):
y = self.convs_sep[i](x * x_mask)
y = self.norms_1[i](y)
y = F.gelu(y)
y = self.convs_1x1[i](y)
y = self.norms_2[i](y)
y = F.gelu(y)
y = self.drop(y)
x = x + y
return x * x_mask
class WN(torch.nn.Module):
def __init__(
self,
hidden_channels,
kernel_size,
dilation_rate,
n_layers,
gin_channels=0,
p_dropout=0,
):
super(WN, self).__init__()
assert kernel_size % 2 == 1
self.hidden_channels = hidden_channels
self.kernel_size = (kernel_size,)
self.dilation_rate = dilation_rate
self.n_layers = n_layers
self.gin_channels = gin_channels
self.p_dropout = p_dropout
self.in_layers = torch.nn.ModuleList()
self.res_skip_layers = torch.nn.ModuleList()
self.drop = nn.Dropout(p_dropout)
if gin_channels != 0:
cond_layer = torch.nn.Conv1d(
gin_channels, 2 * hidden_channels * n_layers, 1
)
self.cond_layer = torch.nn.utils.weight_norm(cond_layer, name="weight")
for i in range(n_layers):
dilation = dilation_rate**i
padding = int((kernel_size * dilation - dilation) / 2)
in_layer = torch.nn.Conv1d(
hidden_channels,
2 * hidden_channels,
kernel_size,
dilation=dilation,
padding=padding,
)
in_layer = torch.nn.utils.weight_norm(in_layer, name="weight")
self.in_layers.append(in_layer)
# last one is not necessary
if i < n_layers - 1:
res_skip_channels = 2 * hidden_channels
else:
res_skip_channels = hidden_channels
res_skip_layer = torch.nn.Conv1d(hidden_channels, res_skip_channels, 1)
res_skip_layer = torch.nn.utils.weight_norm(res_skip_layer, name="weight")
self.res_skip_layers.append(res_skip_layer)
def forward(self, x, x_mask, g=None, **kwargs):
output = torch.zeros_like(x)
n_channels_tensor = torch.IntTensor([self.hidden_channels])
if g is not None:
g = self.cond_layer(g)
for i in range(self.n_layers):
x_in = self.in_layers[i](x)
if g is not None:
cond_offset = i * 2 * self.hidden_channels
g_l = g[:, cond_offset : cond_offset + 2 * self.hidden_channels, :]
else:
g_l = torch.zeros_like(x_in)
acts = commons.fused_add_tanh_sigmoid_multiply(x_in, g_l, n_channels_tensor)
acts = self.drop(acts)
res_skip_acts = self.res_skip_layers[i](acts)
if i < self.n_layers - 1:
res_acts = res_skip_acts[:, : self.hidden_channels, :]
x = (x + res_acts) * x_mask
output = output + res_skip_acts[:, self.hidden_channels :, :]
else:
output = output + res_skip_acts
return output * x_mask
def remove_weight_norm(self):
if self.gin_channels != 0:
torch.nn.utils.remove_weight_norm(self.cond_layer)
for l in self.in_layers:
torch.nn.utils.remove_weight_norm(l)
for l in self.res_skip_layers:
torch.nn.utils.remove_weight_norm(l)
class ResBlock1(torch.nn.Module):
def __init__(self, channels, kernel_size=3, dilation=(1, 3, 5)):
super(ResBlock1, self).__init__()
self.convs1 = nn.ModuleList(
[
weight_norm(
Conv1d(
channels,
channels,
kernel_size,
1,
dilation=dilation[0],
padding=get_padding(kernel_size, dilation[0]),
)
),
weight_norm(
Conv1d(
channels,
channels,
kernel_size,
1,
dilation=dilation[1],
padding=get_padding(kernel_size, dilation[1]),
)
),
weight_norm(
Conv1d(
channels,
channels,
kernel_size,
1,
dilation=dilation[2],
padding=get_padding(kernel_size, dilation[2]),
)
),
]
)
self.convs1.apply(init_weights)
self.convs2 = nn.ModuleList(
[
weight_norm(
Conv1d(
channels,
channels,
kernel_size,
1,
dilation=1,
padding=get_padding(kernel_size, 1),
)
),
weight_norm(
Conv1d(
channels,
channels,
kernel_size,
1,
dilation=1,
padding=get_padding(kernel_size, 1),
)
),
weight_norm(
Conv1d(
channels,
channels,
kernel_size,
1,
dilation=1,
padding=get_padding(kernel_size, 1),
)
),
]
)
self.convs2.apply(init_weights)
def forward(self, x, x_mask=None):
for c1, c2 in zip(self.convs1, self.convs2):
xt = F.leaky_relu(x, LRELU_SLOPE)
if x_mask is not None:
xt = xt * x_mask
xt = c1(xt)
xt = F.leaky_relu(xt, LRELU_SLOPE)
if x_mask is not None:
xt = xt * x_mask
xt = c2(xt)
x = xt + x
if x_mask is not None:
x = x * x_mask
return x
def remove_weight_norm(self):
for l in self.convs1:
remove_weight_norm(l)
for l in self.convs2:
remove_weight_norm(l)
class ResBlock2(torch.nn.Module):
def __init__(self, channels, kernel_size=3, dilation=(1, 3)):
super(ResBlock2, self).__init__()
self.convs = nn.ModuleList(
[
weight_norm(
Conv1d(
channels,
channels,
kernel_size,
1,
dilation=dilation[0],
padding=get_padding(kernel_size, dilation[0]),
)
),
weight_norm(
Conv1d(
channels,
channels,
kernel_size,
1,
dilation=dilation[1],
padding=get_padding(kernel_size, dilation[1]),
)
),
]
)
self.convs.apply(init_weights)
def forward(self, x, x_mask=None):
for c in self.convs:
xt = F.leaky_relu(x, LRELU_SLOPE)
if x_mask is not None:
xt = xt * x_mask
xt = c(xt)
x = xt + x
if x_mask is not None:
x = x * x_mask
return x
def remove_weight_norm(self):
for l in self.convs:
remove_weight_norm(l)
class Log(nn.Module):
def forward(self, x, x_mask, reverse=False, **kwargs):
if not reverse:
y = torch.log(torch.clamp_min(x, 1e-5)) * x_mask
logdet = torch.sum(-y, [1, 2])
return y, logdet
else:
x = torch.exp(x) * x_mask
return x
class Flip(nn.Module):
def forward(self, x, *args, reverse=False, **kwargs):
x = torch.flip(x, [1])
if not reverse:
logdet = torch.zeros(x.size(0)).to(dtype=x.dtype, device=x.device)
return x, logdet
else:
return x
class ElementwiseAffine(nn.Module):
def __init__(self, channels):
super().__init__()
self.channels = channels
self.m = nn.Parameter(torch.zeros(channels, 1))
self.logs = nn.Parameter(torch.zeros(channels, 1))
def forward(self, x, x_mask, reverse=False, **kwargs):
if not reverse:
y = self.m + torch.exp(self.logs) * x
y = y * x_mask
logdet = torch.sum(self.logs * x_mask, [1, 2])
return y, logdet
else:
x = (x - self.m) * torch.exp(-self.logs) * x_mask
return x
class ResidualCouplingLayer(nn.Module):
def __init__(
self,
channels,
hidden_channels,
kernel_size,
dilation_rate,
n_layers,
p_dropout=0,
gin_channels=0,
mean_only=False,
):
assert channels % 2 == 0, "channels should be divisible by 2"
super().__init__()
self.channels = channels
self.hidden_channels = hidden_channels
self.kernel_size = kernel_size
self.dilation_rate = dilation_rate
self.n_layers = n_layers
self.half_channels = channels // 2
self.mean_only = mean_only
self.pre = nn.Conv1d(self.half_channels, hidden_channels, 1)
self.enc = WN(
hidden_channels,
kernel_size,
dilation_rate,
n_layers,
p_dropout=p_dropout,
gin_channels=gin_channels,
)
self.post = nn.Conv1d(hidden_channels, self.half_channels * (2 - mean_only), 1)
self.post.weight.data.zero_()
self.post.bias.data.zero_()
def forward(self, x, x_mask, g=None, reverse=False):
x0, x1 = torch.split(x, [self.half_channels] * 2, 1)
h = self.pre(x0) * x_mask
h = self.enc(h, x_mask, g=g)
stats = self.post(h) * x_mask
if not self.mean_only:
m, logs = torch.split(stats, [self.half_channels] * 2, 1)
else:
m = stats
logs = torch.zeros_like(m)
if not reverse:
x1 = m + x1 * torch.exp(logs) * x_mask
x = torch.cat([x0, x1], 1)
logdet = torch.sum(logs, [1, 2])
return x, logdet
else:
x1 = (x1 - m) * torch.exp(-logs) * x_mask
x = torch.cat([x0, x1], 1)
return x
def remove_weight_norm(self):
self.enc.remove_weight_norm()
class ConvFlow(nn.Module):
def __init__(
self,
in_channels,
filter_channels,
kernel_size,
n_layers,
num_bins=10,
tail_bound=5.0,
):
super().__init__()
self.in_channels = in_channels
self.filter_channels = filter_channels
self.kernel_size = kernel_size
self.n_layers = n_layers
self.num_bins = num_bins
self.tail_bound = tail_bound
self.half_channels = in_channels // 2
self.pre = nn.Conv1d(self.half_channels, filter_channels, 1)
self.convs = DDSConv(filter_channels, kernel_size, n_layers, p_dropout=0.0)
self.proj = nn.Conv1d(
filter_channels, self.half_channels * (num_bins * 3 - 1), 1
)
self.proj.weight.data.zero_()
self.proj.bias.data.zero_()
def forward(self, x, x_mask, g=None, reverse=False):
x0, x1 = torch.split(x, [self.half_channels] * 2, 1)
h = self.pre(x0)
h = self.convs(h, x_mask, g=g)
h = self.proj(h) * x_mask
b, c, t = x0.shape
h = h.reshape(b, c, -1, t).permute(0, 1, 3, 2) # [b, cx?, t] -> [b, c, t, ?]
unnormalized_widths = h[..., : self.num_bins] / math.sqrt(self.filter_channels)
unnormalized_heights = h[..., self.num_bins : 2 * self.num_bins] / math.sqrt(
self.filter_channels
)
unnormalized_derivatives = h[..., 2 * self.num_bins :]
x1, logabsdet = piecewise_rational_quadratic_transform(
x1,
unnormalized_widths,
unnormalized_heights,
unnormalized_derivatives,
inverse=reverse,
tails="linear",
tail_bound=self.tail_bound,
)
x = torch.cat([x0, x1], 1) * x_mask
logdet = torch.sum(logabsdet * x_mask, [1, 2])
if not reverse:
return x, logdet
else:
return x123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209import torch
from torch.nn import functional as F
import numpy as np
DEFAULT_MIN_BIN_WIDTH = 1e-3
DEFAULT_MIN_BIN_HEIGHT = 1e-3
DEFAULT_MIN_DERIVATIVE = 1e-3
def piecewise_rational_quadratic_transform(
inputs,
unnormalized_widths,
unnormalized_heights,
unnormalized_derivatives,
inverse=False,
tails=None,
tail_bound=1.0,
min_bin_width=DEFAULT_MIN_BIN_WIDTH,
min_bin_height=DEFAULT_MIN_BIN_HEIGHT,
min_derivative=DEFAULT_MIN_DERIVATIVE,
):
if tails is None:
spline_fn = rational_quadratic_spline
spline_kwargs = {}
else:
spline_fn = unconstrained_rational_quadratic_spline
spline_kwargs = {"tails": tails, "tail_bound": tail_bound}
outputs, logabsdet = spline_fn(
inputs=inputs,
unnormalized_widths=unnormalized_widths,
unnormalized_heights=unnormalized_heights,
unnormalized_derivatives=unnormalized_derivatives,
inverse=inverse,
min_bin_width=min_bin_width,
min_bin_height=min_bin_height,
min_derivative=min_derivative,
**spline_kwargs
)
return outputs, logabsdet
def searchsorted(bin_locations, inputs, eps=1e-6):
bin_locations[..., -1] += eps
return torch.sum(inputs[..., None] >= bin_locations, dim=-1) - 1
def unconstrained_rational_quadratic_spline(
inputs,
unnormalized_widths,
unnormalized_heights,
unnormalized_derivatives,
inverse=False,
tails="linear",
tail_bound=1.0,
min_bin_width=DEFAULT_MIN_BIN_WIDTH,
min_bin_height=DEFAULT_MIN_BIN_HEIGHT,
min_derivative=DEFAULT_MIN_DERIVATIVE,
):
inside_interval_mask = (inputs >= -tail_bound) & (inputs <= tail_bound)
outside_interval_mask = ~inside_interval_mask
outputs = torch.zeros_like(inputs)
logabsdet = torch.zeros_like(inputs)
if tails == "linear":
unnormalized_derivatives = F.pad(unnormalized_derivatives, pad=(1, 1))
constant = np.log(np.exp(1 - min_derivative) - 1)
unnormalized_derivatives[..., 0] = constant
unnormalized_derivatives[..., -1] = constant
outputs[outside_interval_mask] = inputs[outside_interval_mask]
logabsdet[outside_interval_mask] = 0
else:
raise RuntimeError("{} tails are not implemented.".format(tails))
(
outputs[inside_interval_mask],
logabsdet[inside_interval_mask],
) = rational_quadratic_spline(
inputs=inputs[inside_interval_mask],
unnormalized_widths=unnormalized_widths[inside_interval_mask, :],
unnormalized_heights=unnormalized_heights[inside_interval_mask, :],
unnormalized_derivatives=unnormalized_derivatives[inside_interval_mask, :],
inverse=inverse,
left=-tail_bound,
right=tail_bound,
bottom=-tail_bound,
top=tail_bound,
min_bin_width=min_bin_width,
min_bin_height=min_bin_height,
min_derivative=min_derivative,
)
return outputs, logabsdet
def rational_quadratic_spline(
inputs,
unnormalized_widths,
unnormalized_heights,
unnormalized_derivatives,
inverse=False,
left=0.0,
right=1.0,
bottom=0.0,
top=1.0,
min_bin_width=DEFAULT_MIN_BIN_WIDTH,
min_bin_height=DEFAULT_MIN_BIN_HEIGHT,
min_derivative=DEFAULT_MIN_DERIVATIVE,
):
if torch.min(inputs) < left or torch.max(inputs) > right:
raise ValueError("Input to a transform is not within its domain")
num_bins = unnormalized_widths.shape[-1]
if min_bin_width * num_bins > 1.0:
raise ValueError("Minimal bin width too large for the number of bins")
if min_bin_height * num_bins > 1.0:
raise ValueError("Minimal bin height too large for the number of bins")
widths = F.softmax(unnormalized_widths, dim=-1)
widths = min_bin_width + (1 - min_bin_width * num_bins) * widths
cumwidths = torch.cumsum(widths, dim=-1)
cumwidths = F.pad(cumwidths, pad=(1, 0), mode="constant", value=0.0)
cumwidths = (right - left) * cumwidths + left
cumwidths[..., 0] = left
cumwidths[..., -1] = right
widths = cumwidths[..., 1:] - cumwidths[..., :-1]
derivatives = min_derivative + F.softplus(unnormalized_derivatives)
heights = F.softmax(unnormalized_heights, dim=-1)
heights = min_bin_height + (1 - min_bin_height * num_bins) * heights
cumheights = torch.cumsum(heights, dim=-1)
cumheights = F.pad(cumheights, pad=(1, 0), mode="constant", value=0.0)
cumheights = (top - bottom) * cumheights + bottom
cumheights[..., 0] = bottom
cumheights[..., -1] = top
heights = cumheights[..., 1:] - cumheights[..., :-1]
if inverse:
bin_idx = searchsorted(cumheights, inputs)[..., None]
else:
bin_idx = searchsorted(cumwidths, inputs)[..., None]
input_cumwidths = cumwidths.gather(-1, bin_idx)[..., 0]
input_bin_widths = widths.gather(-1, bin_idx)[..., 0]
input_cumheights = cumheights.gather(-1, bin_idx)[..., 0]
delta = heights / widths
input_delta = delta.gather(-1, bin_idx)[..., 0]
input_derivatives = derivatives.gather(-1, bin_idx)[..., 0]
input_derivatives_plus_one = derivatives[..., 1:].gather(-1, bin_idx)[..., 0]
input_heights = heights.gather(-1, bin_idx)[..., 0]
if inverse:
a = (inputs - input_cumheights) * (
input_derivatives + input_derivatives_plus_one - 2 * input_delta
) + input_heights * (input_delta - input_derivatives)
b = input_heights * input_derivatives - (inputs - input_cumheights) * (
input_derivatives + input_derivatives_plus_one - 2 * input_delta
)
c = -input_delta * (inputs - input_cumheights)
discriminant = b.pow(2) - 4 * a * c
assert (discriminant >= 0).all()
root = (2 * c) / (-b - torch.sqrt(discriminant))
outputs = root * input_bin_widths + input_cumwidths
theta_one_minus_theta = root * (1 - root)
denominator = input_delta + (
(input_derivatives + input_derivatives_plus_one - 2 * input_delta)
* theta_one_minus_theta
)
derivative_numerator = input_delta.pow(2) * (
input_derivatives_plus_one * root.pow(2)
+ 2 * input_delta * theta_one_minus_theta
+ input_derivatives * (1 - root).pow(2)
)
logabsdet = torch.log(derivative_numerator) - 2 * torch.log(denominator)
return outputs, -logabsdet
else:
theta = (inputs - input_cumwidths) / input_bin_widths
theta_one_minus_theta = theta * (1 - theta)
numerator = input_heights * (
input_delta * theta.pow(2) + input_derivatives * theta_one_minus_theta
)
denominator = input_delta + (
(input_derivatives + input_derivatives_plus_one - 2 * input_delta)
* theta_one_minus_theta
)
outputs = input_cumheights + numerator / denominator
derivative_numerator = input_delta.pow(2) * (
input_derivatives_plus_one * theta.pow(2)
+ 2 * input_delta * theta_one_minus_theta
+ input_derivatives * (1 - theta).pow(2)
)
logabsdet = torch.log(derivative_numerator) - 2 * torch.log(denominator)
return outputs, logabsdet123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422import torch, numpy as np
import torch.nn as nn
import torch.nn.functional as F
class BiGRU(nn.Module):
def __init__(self, input_features, hidden_features, num_layers):
super(BiGRU, self).__init__()
self.gru = nn.GRU(
input_features,
hidden_features,
num_layers=num_layers,
batch_first=True,
bidirectional=True,
)
def forward(self, x):
return self.gru(x)[0]
class ConvBlockRes(nn.Module):
def __init__(self, in_channels, out_channels, momentum=0.01):
super(ConvBlockRes, self).__init__()
self.conv = nn.Sequential(
nn.Conv2d(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=(3, 3),
stride=(1, 1),
padding=(1, 1),
bias=False,
),
nn.BatchNorm2d(out_channels, momentum=momentum),
nn.ReLU(),
nn.Conv2d(
in_channels=out_channels,
out_channels=out_channels,
kernel_size=(3, 3),
stride=(1, 1),
padding=(1, 1),
bias=False,
),
nn.BatchNorm2d(out_channels, momentum=momentum),
nn.ReLU(),
)
if in_channels != out_channels:
self.shortcut = nn.Conv2d(in_channels, out_channels, (1, 1))
self.is_shortcut = True
else:
self.is_shortcut = False
def forward(self, x):
if self.is_shortcut:
return self.conv(x) + self.shortcut(x)
else:
return self.conv(x) + x
class Encoder(nn.Module):
def __init__(
self,
in_channels,
in_size,
n_encoders,
kernel_size,
n_blocks,
out_channels=16,
momentum=0.01,
):
super(Encoder, self).__init__()
self.n_encoders = n_encoders
self.bn = nn.BatchNorm2d(in_channels, momentum=momentum)
self.layers = nn.ModuleList()
self.latent_channels = []
for i in range(self.n_encoders):
self.layers.append(
ResEncoderBlock(
in_channels, out_channels, kernel_size, n_blocks, momentum=momentum
)
)
self.latent_channels.append([out_channels, in_size])
in_channels = out_channels
out_channels *= 2
in_size //= 2
self.out_size = in_size
self.out_channel = out_channels
def forward(self, x):
concat_tensors = []
x = self.bn(x)
for i in range(self.n_encoders):
_, x = self.layers[i](x)
concat_tensors.append(_)
return x, concat_tensors
class ResEncoderBlock(nn.Module):
def __init__(
self, in_channels, out_channels, kernel_size, n_blocks=1, momentum=0.01
):
super(ResEncoderBlock, self).__init__()
self.n_blocks = n_blocks
self.conv = nn.ModuleList()
self.conv.append(ConvBlockRes(in_channels, out_channels, momentum))
for i in range(n_blocks - 1):
self.conv.append(ConvBlockRes(out_channels, out_channels, momentum))
self.kernel_size = kernel_size
if self.kernel_size is not None:
self.pool = nn.AvgPool2d(kernel_size=kernel_size)
def forward(self, x):
for i in range(self.n_blocks):
x = self.conv[i](x)
if self.kernel_size is not None:
return x, self.pool(x)
else:
return x
class Intermediate(nn.Module): #
def __init__(self, in_channels, out_channels, n_inters, n_blocks, momentum=0.01):
super(Intermediate, self).__init__()
self.n_inters = n_inters
self.layers = nn.ModuleList()
self.layers.append(
ResEncoderBlock(in_channels, out_channels, None, n_blocks, momentum)
)
for i in range(self.n_inters - 1):
self.layers.append(
ResEncoderBlock(out_channels, out_channels, None, n_blocks, momentum)
)
def forward(self, x):
for i in range(self.n_inters):
x = self.layers[i](x)
return x
class ResDecoderBlock(nn.Module):
def __init__(self, in_channels, out_channels, stride, n_blocks=1, momentum=0.01):
super(ResDecoderBlock, self).__init__()
out_padding = (0, 1) if stride == (1, 2) else (1, 1)
self.n_blocks = n_blocks
self.conv1 = nn.Sequential(
nn.ConvTranspose2d(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=(3, 3),
stride=stride,
padding=(1, 1),
output_padding=out_padding,
bias=False,
),
nn.BatchNorm2d(out_channels, momentum=momentum),
nn.ReLU(),
)
self.conv2 = nn.ModuleList()
self.conv2.append(ConvBlockRes(out_channels * 2, out_channels, momentum))
for i in range(n_blocks - 1):
self.conv2.append(ConvBlockRes(out_channels, out_channels, momentum))
def forward(self, x, concat_tensor):
x = self.conv1(x)
x = torch.cat((x, concat_tensor), dim=1)
for i in range(self.n_blocks):
x = self.conv2[i](x)
return x
class Decoder(nn.Module):
def __init__(self, in_channels, n_decoders, stride, n_blocks, momentum=0.01):
super(Decoder, self).__init__()
self.layers = nn.ModuleList()
self.n_decoders = n_decoders
for i in range(self.n_decoders):
out_channels = in_channels // 2
self.layers.append(
ResDecoderBlock(in_channels, out_channels, stride, n_blocks, momentum)
)
in_channels = out_channels
def forward(self, x, concat_tensors):
for i in range(self.n_decoders):
x = self.layers[i](x, concat_tensors[-1 - i])
return x
class DeepUnet(nn.Module):
def __init__(
self,
kernel_size,
n_blocks,
en_de_layers=5,
inter_layers=4,
in_channels=1,
en_out_channels=16,
):
super(DeepUnet, self).__init__()
self.encoder = Encoder(
in_channels, 128, en_de_layers, kernel_size, n_blocks, en_out_channels
)
self.intermediate = Intermediate(
self.encoder.out_channel // 2,
self.encoder.out_channel,
inter_layers,
n_blocks,
)
self.decoder = Decoder(
self.encoder.out_channel, en_de_layers, kernel_size, n_blocks
)
def forward(self, x):
x, concat_tensors = self.encoder(x)
x = self.intermediate(x)
x = self.decoder(x, concat_tensors)
return x
class E2E(nn.Module):
def __init__(
self,
n_blocks,
n_gru,
kernel_size,
en_de_layers=5,
inter_layers=4,
in_channels=1,
en_out_channels=16,
):
super(E2E, self).__init__()
self.unet = DeepUnet(
kernel_size,
n_blocks,
en_de_layers,
inter_layers,
in_channels,
en_out_channels,
)
self.cnn = nn.Conv2d(en_out_channels, 3, (3, 3), padding=(1, 1))
if n_gru:
self.fc = nn.Sequential(
BiGRU(3 * 128, 256, n_gru),
nn.Linear(512, 360),
nn.Dropout(0.25),
nn.Sigmoid(),
)
else:
self.fc = nn.Sequential(
nn.Linear(3 * nn.N_MELS, nn.N_CLASS), nn.Dropout(0.25), nn.Sigmoid()
)
def forward(self, mel):
mel = mel.transpose(-1, -2).unsqueeze(1)
x = self.cnn(self.unet(mel)).transpose(1, 2).flatten(-2)
x = self.fc(x)
return x
from librosa.filters import mel
class MelSpectrogram(torch.nn.Module):
def __init__(
self,
is_half,
n_mel_channels,
sampling_rate,
win_length,
hop_length,
n_fft=None,
mel_fmin=0,
mel_fmax=None,
clamp=1e-5,
):
super().__init__()
n_fft = win_length if n_fft is None else n_fft
self.hann_window = {}
mel_basis = mel(
sr=sampling_rate,
n_fft=n_fft,
n_mels=n_mel_channels,
fmin=mel_fmin,
fmax=mel_fmax,
htk=True,
)
mel_basis = torch.from_numpy(mel_basis).float()
self.register_buffer("mel_basis", mel_basis)
self.n_fft = win_length if n_fft is None else n_fft
self.hop_length = hop_length
self.win_length = win_length
self.sampling_rate = sampling_rate
self.n_mel_channels = n_mel_channels
self.clamp = clamp
self.is_half = is_half
def forward(self, audio, keyshift=0, speed=1, center=True):
factor = 2 ** (keyshift / 12)
n_fft_new = int(np.round(self.n_fft * factor))
win_length_new = int(np.round(self.win_length * factor))
hop_length_new = int(np.round(self.hop_length * speed))
keyshift_key = str(keyshift) + "_" + str(audio.device)
if keyshift_key not in self.hann_window:
self.hann_window[keyshift_key] = torch.hann_window(win_length_new).to(
audio.device
)
fft = torch.stft(
audio,
n_fft=n_fft_new,
hop_length=hop_length_new,
win_length=win_length_new,
window=self.hann_window[keyshift_key],
center=center,
return_complex=True,
)
magnitude = torch.sqrt(fft.real.pow(2) + fft.imag.pow(2))
if keyshift != 0:
size = self.n_fft // 2 + 1
resize = magnitude.size(1)
if resize < size:
magnitude = F.pad(magnitude, (0, 0, 0, size - resize))
magnitude = magnitude[:, :size, :] * self.win_length / win_length_new
mel_output = torch.matmul(self.mel_basis, magnitude)
if self.is_half == True:
mel_output = mel_output.half()
log_mel_spec = torch.log(torch.clamp(mel_output, min=self.clamp))
return log_mel_spec
class RMVPE:
def __init__(self, model_path, is_half, device=None):
self.resample_kernel = {}
model = E2E(4, 1, (2, 2))
ckpt = torch.load(model_path, map_location="cpu")
model.load_state_dict(ckpt)
model.eval()
if is_half == True:
model = model.half()
self.model = model
self.resample_kernel = {}
self.is_half = is_half
if device is None:
device = "cuda" if torch.cuda.is_available() else "cpu"
self.device = device
self.mel_extractor = MelSpectrogram(
is_half, 128, 16000, 1024, 160, None, 30, 8000
).to(device)
self.model = self.model.to(device)
cents_mapping = 20 * np.arange(360) + 1997.3794084376191
self.cents_mapping = np.pad(cents_mapping, (4, 4)) # 368
def mel2hidden(self, mel):
with torch.no_grad():
n_frames = mel.shape[-1]
mel = F.pad(
mel, (0, 32 * ((n_frames - 1) // 32 + 1) - n_frames), mode="reflect"
)
hidden = self.model(mel)
return hidden[:, :n_frames]
def decode(self, hidden, thred=0.03):
cents_pred = self.to_local_average_cents(hidden, thred=thred)
f0 = 10 * (2 ** (cents_pred / 1200))
f0[f0 == 10] = 0
# f0 = np.array([10 * (2 ** (cent_pred / 1200)) if cent_pred else 0 for cent_pred in cents_pred])
return f0
def infer_from_audio(self, audio, thred=0.03):
audio = torch.from_numpy(audio).float().to(self.device).unsqueeze(0)
# torch.cuda.synchronize()
# t0=ttime()
mel = self.mel_extractor(audio, center=True)
# torch.cuda.synchronize()
# t1=ttime()
hidden = self.mel2hidden(mel)
# torch.cuda.synchronize()
# t2=ttime()
hidden = hidden.squeeze(0).cpu().numpy()
if self.is_half == True:
hidden = hidden.astype("float32")
f0 = self.decode(hidden, thred=thred)
# torch.cuda.synchronize()
# t3=ttime()
# print("hmvpe:%s\t%s\t%s\t%s"%(t1-t0,t2-t1,t3-t2,t3-t0))
return f0
def pitch_based_audio_inference(self, audio, thred=0.03, f0_min=50, f0_max=1100):
audio = torch.from_numpy(audio).float().to(self.device).unsqueeze(0)
mel = self.mel_extractor(audio, center=True)
hidden = self.mel2hidden(mel)
hidden = hidden.squeeze(0).cpu().numpy()
if self.is_half == True:
hidden = hidden.astype("float32")
f0 = self.decode(hidden, thred=thred)
f0[(f0 < f0_min) | (f0 > f0_max)] = 0
return f0
def to_local_average_cents(self, salience, thred=0.05):
# t0 = ttime()
center = np.argmax(salience, axis=1) # frame length#index
salience = np.pad(salience, ((0, 0), (4, 4))) # frame length,368
# t1 = ttime()
center += 4
todo_salience = []
todo_cents_mapping = []
starts = center - 4
ends = center + 5
for idx in range(salience.shape[0]):
todo_salience.append(salience[:, starts[idx] : ends[idx]][idx])
todo_cents_mapping.append(self.cents_mapping[starts[idx] : ends[idx]])
# t2 = ttime()
todo_salience = np.array(todo_salience) # frame length,9
todo_cents_mapping = np.array(todo_cents_mapping) # frame length,9
product_sum = np.sum(todo_salience * todo_cents_mapping, 1)
weight_sum = np.sum(todo_salience, 1) # frame length
devided = product_sum / weight_sum # frame length
# t3 = ttime()
maxx = np.max(salience, axis=1) # frame length
devided[maxx <= thred] = 0
# t4 = ttime()
# print("decode:%s\t%s\t%s\t%s" % (t1 - t0, t2 - t1, t3 - t2, t4 - t3))
return devided123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354{ "0ddfc0eb5792638ad5dc27850236c246": { "compensate": 1.035, "mdx_dim_f_set": 2048, "mdx_dim_t_set": 8, "mdx_n_fft_scale_set": 6144, "primary_stem": "Vocals" }, "26d308f91f3423a67dc69a6d12a8793d": { "compensate": 1.035, "mdx_dim_f_set": 2048, "mdx_dim_t_set": 9, "mdx_n_fft_scale_set": 8192, "primary_stem": "Other" }, "2cdd429caac38f0194b133884160f2c6": { "compensate": 1.045, "mdx_dim_f_set": 3072, "mdx_dim_t_set": 8, "mdx_n_fft_scale_set": 7680, "primary_stem": "Instrumental" }, "2f5501189a2f6db6349916fabe8c90de": { "compensate": 1.035, "mdx_dim_f_set": 2048, "mdx_dim_t_set": 8, "mdx_n_fft_scale_set": 6144, "primary_stem": "Vocals" }, "398580b6d5d973af3120df54cee6759d": { "compensate": 1.75, "mdx_dim_f_set": 3072, "mdx_dim_t_set": 8, "mdx_n_fft_scale_set": 7680, "primary_stem": "Vocals" }, "488b3e6f8bd3717d9d7c428476be2d75": { "compensate": 1.035, "mdx_dim_f_set": 3072, "mdx_dim_t_set": 8, "mdx_n_fft_scale_set": 7680, "primary_stem": "Instrumental" }, "4910e7827f335048bdac11fa967772f9": { "compensate": 1.035, "mdx_dim_f_set": 2048, "mdx_dim_t_set": 7, "mdx_n_fft_scale_set": 4096, "primary_stem": "Drums" }, "53c4baf4d12c3e6c3831bb8f5b532b93": { "compensate": 1.043, "mdx_dim_f_set": 3072, "mdx_dim_t_set": 8, "mdx_n_fft_scale_set": 7680, "primary_stem": "Vocals" }, "5d343409ef0df48c7d78cce9f0106781": { "compensate": 1.075, "mdx_dim_f_set": 3072, "mdx_dim_t_set": 8, "mdx_n_fft_scale_set": 7680, "primary_stem": "Vocals" }, "5f6483271e1efb9bfb59e4a3e6d4d098": { "compensate": 1.035, "mdx_dim_f_set": 2048, "mdx_dim_t_set": 9, "mdx_n_fft_scale_set": 6144, "primary_stem": "Vocals" }, "65ab5919372a128e4167f5e01a8fda85": { "compensate": 1.035, "mdx_dim_f_set": 2048, "mdx_dim_t_set": 8, "mdx_n_fft_scale_set": 8192, "primary_stem": "Other" }, "6703e39f36f18aa7855ee1047765621d": { "compensate": 1.035, "mdx_dim_f_set": 2048, "mdx_dim_t_set": 9, "mdx_n_fft_scale_set": 16384, "primary_stem": "Bass" }, "6b31de20e84392859a3d09d43f089515": { "compensate": 1.035, "mdx_dim_f_set": 2048, "mdx_dim_t_set": 8, "mdx_n_fft_scale_set": 6144, "primary_stem": "Vocals" }, "867595e9de46f6ab699008295df62798": { "compensate": 1.03, "mdx_dim_f_set": 3072, "mdx_dim_t_set": 8, "mdx_n_fft_scale_set": 7680, "primary_stem": "Vocals" }, "a3cd63058945e777505c01d2507daf37": { "compensate": 1.03, "mdx_dim_f_set": 2048, "mdx_dim_t_set": 8, "mdx_n_fft_scale_set": 6144, "primary_stem": "Vocals" }, "b33d9b3950b6cbf5fe90a32608924700": { "compensate": 1.03, "mdx_dim_f_set": 3072, "mdx_dim_t_set": 8, "mdx_n_fft_scale_set": 7680, "primary_stem": "Vocals" }, "c3b29bdce8c4fa17ec609e16220330ab": { "compensate": 1.035, "mdx_dim_f_set": 2048, "mdx_dim_t_set": 8, "mdx_n_fft_scale_set": 16384, "primary_stem": "Bass" }, "ceed671467c1f64ebdfac8a2490d0d52": { "compensate": 1.035, "mdx_dim_f_set": 3072, "mdx_dim_t_set": 8, "mdx_n_fft_scale_set": 7680, "primary_stem": "Instrumental" }, "d2a1376f310e4f7fa37fb9b5774eb701": { "compensate": 1.035, "mdx_dim_f_set": 3072, "mdx_dim_t_set": 8, "mdx_n_fft_scale_set": 7680, "primary_stem": "Instrumental" }, "d7bff498db9324db933d913388cba6be": { "compensate": 1.035, "mdx_dim_f_set": 2048, "mdx_dim_t_set": 8, "mdx_n_fft_scale_set": 6144, "primary_stem": "Vocals" }, "d94058f8c7f1fae4164868ae8ae66b20": { "compensate": 1.035, "mdx_dim_f_set": 2048, "mdx_dim_t_set": 8, "mdx_n_fft_scale_set": 6144, "primary_stem": "Vocals" }, "dc41ede5961d50f277eb846db17f5319": { "compensate": 1.035, "mdx_dim_f_set": 2048, "mdx_dim_t_set": 9, "mdx_n_fft_scale_set": 4096, "primary_stem": "Drums" }, "e5572e58abf111f80d8241d2e44e7fa4": { "compensate": 1.028, "mdx_dim_f_set": 3072, "mdx_dim_t_set": 8, "mdx_n_fft_scale_set": 7680, "primary_stem": "Instrumental" }, "e7324c873b1f615c35c1967f912db92a": { "compensate": 1.03, "mdx_dim_f_set": 3072, "mdx_dim_t_set": 8, "mdx_n_fft_scale_set": 7680, "primary_stem": "Vocals" }, "1c56ec0224f1d559c42fd6fd2a67b154": { "compensate": 1.025, "mdx_dim_f_set": 2048, "mdx_dim_t_set": 8, "mdx_n_fft_scale_set": 5120, "primary_stem": "Instrumental" }, "f2df6d6863d8f435436d8b561594ff49": { "compensate": 1.035, "mdx_dim_f_set": 3072, "mdx_dim_t_set": 8, "mdx_n_fft_scale_set": 7680, "primary_stem": "Instrumental" }, "b06327a00d5e5fbc7d96e1781bbdb596": { "compensate": 1.035, "mdx_dim_f_set": 3072, "mdx_dim_t_set": 8, "mdx_n_fft_scale_set": 6144, "primary_stem": "Instrumental" }, "94ff780b977d3ca07c7a343dab2e25dd": { "compensate": 1.039, "mdx_dim_f_set": 3072, "mdx_dim_t_set": 8, "mdx_n_fft_scale_set": 6144, "primary_stem": "Instrumental" }, "73492b58195c3b52d34590d5474452f6": { "compensate": 1.043, "mdx_dim_f_set": 3072, "mdx_dim_t_set": 8, "mdx_n_fft_scale_set": 7680, "primary_stem": "Vocals" }, "970b3f9492014d18fefeedfe4773cb42": { "compensate": 1.009, "mdx_dim_f_set": 3072, "mdx_dim_t_set": 8, "mdx_n_fft_scale_set": 7680, "primary_stem": "Vocals" }, "1d64a6d2c30f709b8c9b4ce1366d96ee": { "compensate": 1.035, "mdx_dim_f_set": 2048, "mdx_dim_t_set": 8, "mdx_n_fft_scale_set": 5120, "primary_stem": "Instrumental" }, "203f2a3955221b64df85a41af87cf8f0": { "compensate": 1.035, "mdx_dim_f_set": 3072, "mdx_dim_t_set": 8, "mdx_n_fft_scale_set": 6144, "primary_stem": "Instrumental" }, "291c2049608edb52648b96e27eb80e95": { "compensate": 1.035, "mdx_dim_f_set": 3072, "mdx_dim_t_set": 8, "mdx_n_fft_scale_set": 6144, "primary_stem": "Instrumental" }, "ead8d05dab12ec571d67549b3aab03fc": { "compensate": 1.035, "mdx_dim_f_set": 3072, "mdx_dim_t_set": 8, "mdx_n_fft_scale_set": 6144, "primary_stem": "Instrumental" }, "cc63408db3d80b4d85b0287d1d7c9632": { "compensate": 1.033, "mdx_dim_f_set": 3072, "mdx_dim_t_set": 8, "mdx_n_fft_scale_set": 6144, "primary_stem": "Instrumental" }, "cd5b2989ad863f116c855db1dfe24e39": { "compensate": 1.035, "mdx_dim_f_set": 3072, "mdx_dim_t_set": 9, "mdx_n_fft_scale_set": 6144, "primary_stem": "Other" }, "55657dd70583b0fedfba5f67df11d711": { "compensate": 1.022, "mdx_dim_f_set": 3072, "mdx_dim_t_set": 8, "mdx_n_fft_scale_set": 6144, "primary_stem": "Instrumental" }, "b6bccda408a436db8500083ef3491e8b": { "compensate": 1.02, "mdx_dim_f_set": 3072, "mdx_dim_t_set": 8, "mdx_n_fft_scale_set": 7680, "primary_stem": "Instrumental" }, "8a88db95c7fb5dbe6a095ff2ffb428b1": { "compensate": 1.026, "mdx_dim_f_set": 2048, "mdx_dim_t_set": 8, "mdx_n_fft_scale_set": 5120, "primary_stem": "Instrumental" }, "b78da4afc6512f98e4756f5977f5c6b9": { "compensate": 1.021, "mdx_dim_f_set": 3072, "mdx_dim_t_set": 8, "mdx_n_fft_scale_set": 7680, "primary_stem": "Instrumental" }, "77d07b2667ddf05b9e3175941b4454a0": { "compensate": 1.021, "mdx_dim_f_set": 3072, "mdx_dim_t_set": 8, "mdx_n_fft_scale_set": 7680, "primary_stem": "Vocals" }, "0f2a6bc5b49d87d64728ee40e23bceb1": { "compensate": 1.019, "mdx_dim_f_set": 2560, "mdx_dim_t_set": 8, "mdx_n_fft_scale_set": 5120, "primary_stem": "Instrumental" }, "b02be2d198d4968a121030cf8950b492": { "compensate": 1.020, "mdx_dim_f_set": 2560, "mdx_dim_t_set": 8, "mdx_n_fft_scale_set": 5120, "primary_stem": "No Crowd" }, "2154254ee89b2945b97a7efed6e88820": { "config_yaml": "model_2_stem_061321.yaml" }, "063aadd735d58150722926dcbf5852a9": { "config_yaml": "model_2_stem_061321.yaml" }, "fe96801369f6a148df2720f5ced88c19": { "config_yaml": "model3.yaml" }, "02e8b226f85fb566e5db894b9931c640": { "config_yaml": "model2.yaml" }, "e3de6d861635ab9c1d766149edd680d6": { "config_yaml": "model1.yaml" }, "3f2936c554ab73ce2e396d54636bd373": { "config_yaml": "modelB.yaml" }, "890d0f6f82d7574bca741a9e8bcb8168": { "config_yaml": "modelB.yaml" }, "63a3cb8c37c474681049be4ad1ba8815": { "config_yaml": "modelB.yaml" }, "a7fc5d719743c7fd6b61bd2b4d48b9f0": { "config_yaml": "modelA.yaml" }, "3567f3dee6e77bf366fcb1c7b8bc3745": { "config_yaml": "modelA.yaml" }, "a28f4d717bd0d34cd2ff7a3b0a3d065e": { "config_yaml": "modelA.yaml" }, "c9971a18da20911822593dc81caa8be9": { "config_yaml": "sndfx.yaml" }, "57d94d5ed705460d21c75a5ac829a605": { "config_yaml": "sndfx.yaml" }, "e7a25f8764f25a52c1b96c4946e66ba2": { "config_yaml": "sndfx.yaml" }, "104081d24e37217086ce5fde09147ee1": { "config_yaml": "model_2_stem_061321.yaml" }, "1e6165b601539f38d0a9330f3facffeb": { "config_yaml": "model_2_stem_061321.yaml" }, "fe0108464ce0d8271be5ab810891bd7c": { "config_yaml": "model_2_stem_full_band.yaml" }}123git-lfsaria2 -yffmpeg123456789101112131415--extra-index-url https://download.pytorch.org/whl/cu118torch>=2.1.0+cu118torchvision>=0.16.0+cu118torchaudio>=2.1.0+cu118yt-dlpgradio==4.19.2pydub==0.25.1edge_tts==6.1.7deep_translator==1.11.4git+https://github.com/R3gm/pyannote-audio.git@3.1.1git+https://github.com/R3gm/whisperX.git@cuda_11_8nest_asynciogTTSgradio_client==0.10.1IPython12345678910111213141516171819praat-parselmouth>=0.4.3pyworld==0.3.2faiss-cpu==1.7.3torchcrepe==0.0.20ffmpeg-python>=0.2.0fairseq==0.12.2 gdownrarfiletransformersaccelerateoptimumsentencepiecesrtgit+https://github.com/R3gm/openvoice_package.git@liteopenai==1.14.3tiktoken==0.6.0# Documentspypdf==4.2.0python-docx12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758# core depsnumpy==1.23.5cython>=0.29.30scipy>=1.11.2torchtorchaudiosoundfilelibrosascikit-learnnumbainflect>=5.6.0tqdm>=4.64.1anyascii>=0.3.0pyyaml>=6.0fsspec>=2023.6.0 # <= 2023.9.1 makes aux tests failaiohttp>=3.8.1packaging>=23.1# deps for examplesflask>=2.0.1# deps for inferencepysbd>=0.3.4# deps for notebooksumap-learn>=0.5.1pandas# deps for trainingmatplotlib# coqui stacktrainer>=0.0.32# config managementcoqpit>=0.0.16# chinese g2p depsjiebapypinyin# koreanhangul_romanize# gruut+supported langsgruut[de,es,fr]==2.2.3# deps for koreanjamonltkg2pkk>=0.1.1# deps for banglabanglabnnumerizerbnunicodenormalizer#deps for tortoiseeinops>=0.6.0transformers#deps for barkencodec>=0.1.1# deps for XTTSunidecode>=1.3.2num2wordsspacy[ja]>=3
# after this # pip install -r requirements_xtts.txt# pip install TTS==0.21.1 --no-deps123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141from pydub import AudioSegmentfrom tqdm import tqdmfrom .utils import run_commandfrom .logging_setup import loggerimport numpy as np
class Mixer: def __init__(self): self.parts = []
def __len__(self): parts = self._sync() seg = parts[0][1] frame_count = max(offset + seg.frame_count() for offset, seg in parts) return int(1000.0 * frame_count / seg.frame_rate)
def overlay(self, sound, position=0): self.parts.append((position, sound)) return self
def _sync(self): positions, segs = zip(*self.parts)
frame_rate = segs[0].frame_rate array_type = segs[0].array_type # noqa
offsets = [int(frame_rate * pos / 1000.0) for pos in positions] segs = AudioSegment.empty()._sync(*segs) return list(zip(offsets, segs))
def append(self, sound): self.overlay(sound, position=len(self))
def to_audio_segment(self): parts = self._sync() seg = parts[0][1] channels = seg.channels
frame_count = max(offset + seg.frame_count() for offset, seg in parts) sample_count = int(frame_count * seg.channels)
output = np.zeros(sample_count, dtype="int32") for offset, seg in parts: sample_offset = offset * channels samples = np.frombuffer(seg.get_array_of_samples(), dtype="int32") samples = np.int16(samples/np.max(np.abs(samples)) * 32767) start = sample_offset end = start + len(samples) output[start:end] += samples
return seg._spawn( output, overrides={"sample_width": 4}).normalize(headroom=0.0)
def create_translated_audio( result_diarize, audio_files, final_file, concat=False, avoid_overlap=False,): total_duration = result_diarize["segments"][-1]["end"] # in seconds
if concat: """ file .\audio\1.ogg file .\audio\2.ogg file .\audio\3.ogg file .\audio\4.ogg ... """
# Write the file paths to list.txt with open("list.txt", "w") as file: for i, audio_file in enumerate(audio_files): if i == len(audio_files) - 1: # Check if it's the last item file.write(f"file {audio_file}") else: file.write(f"file {audio_file}\n")
# command = f"ffmpeg -f concat -safe 0 -i list.txt {final_file}" command = ( f"ffmpeg -f concat -safe 0 -i list.txt -c:a pcm_s16le {final_file}" ) run_command(command)
else: # silent audio with total_duration base_audio = AudioSegment.silent( duration=int(total_duration * 1000), frame_rate=41000 ) combined_audio = Mixer() combined_audio.overlay(base_audio)
logger.debug( f"Audio duration: {total_duration // 60} " f"minutes and {int(total_duration % 60)} seconds" )
last_end_time = 0 previous_speaker = "" for line, audio_file in tqdm( zip(result_diarize["segments"], audio_files) ): start = float(line["start"])
# Overlay each audio at the corresponding time try: audio = AudioSegment.from_file(audio_file) # audio_a = audio.speedup(playback_speed=1.5)
if avoid_overlap: speaker = line["speaker"] if (last_end_time - 0.500) > start: overlap_time = last_end_time - start if previous_speaker and previous_speaker != speaker: start = (last_end_time - 0.500) else: start = (last_end_time - 0.200) if overlap_time > 2.5: start = start - 0.3 logger.info( f"Avoid overlap for {str(audio_file)} " f"with {str(start)}" )
previous_speaker = speaker
duration_tts_seconds = len(audio) / 1000.0 # to sec last_end_time = (start + duration_tts_seconds)
start_time = start * 1000 # to ms combined_audio = combined_audio.overlay( audio, position=start_time ) except Exception as error: logger.debug(str(error)) logger.error(f"Error audio file {audio_file}")
# combined audio as a file combined_audio_data = combined_audio.to_audio_segment() combined_audio_data.export( final_file, format="wav" ) # best than ogg, change if the audio is anomalous123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551from .logging_setup import logger
LANGUAGES_UNIDIRECTIONAL = { "Aymara (ay)": "ay", "Bambara (bm)": "bm", "Cebuano (ceb)": "ceb", "Chichewa (ny)": "ny", "Divehi (dv)": "dv", "Dogri (doi)": "doi", "Ewe (ee)": "ee", "Guarani (gn)": "gn", "Iloko (ilo)": "ilo", "Kinyarwanda (rw)": "rw", "Krio (kri)": "kri", "Kurdish (ku)": "ku", "Kirghiz (ky)": "ky", "Ganda (lg)": "lg", "Maithili (mai)": "mai", "Oriya (or)": "or", "Oromo (om)": "om", "Quechua (qu)": "qu", "Samoan (sm)": "sm", "Tigrinya (ti)": "ti", "Tsonga (ts)": "ts", "Akan (ak)": "ak", "Uighur (ug)": "ug"}
UNIDIRECTIONAL_L_LIST = LANGUAGES_UNIDIRECTIONAL.keys()
LANGUAGES = { "Automatic detection": "Automatic detection", "Arabic (ar)": "ar", "Chinese - Simplified (zh-CN)": "zh", "Czech (cs)": "cs", "Danish (da)": "da", "Dutch (nl)": "nl", "English (en)": "en", "Finnish (fi)": "fi", "French (fr)": "fr", "German (de)": "de", "Greek (el)": "el", "Hebrew (he)": "he", "Hungarian (hu)": "hu", "Italian (it)": "it", "Japanese (ja)": "ja", "Korean (ko)": "ko", "Persian (fa)": "fa", # no aux gTTS "Polish (pl)": "pl", "Portuguese (pt)": "pt", "Russian (ru)": "ru", "Spanish (es)": "es", "Turkish (tr)": "tr", "Ukrainian (uk)": "uk", "Urdu (ur)": "ur", "Vietnamese (vi)": "vi", "Hindi (hi)": "hi", "Indonesian (id)": "id", "Bengali (bn)": "bn", "Telugu (te)": "te", "Marathi (mr)": "mr", "Tamil (ta)": "ta", "Javanese (jw|jv)": "jw", "Catalan (ca)": "ca", "Nepali (ne)": "ne", "Thai (th)": "th", "Swedish (sv)": "sv", "Amharic (am)": "am", "Welsh (cy)": "cy", # no aux gTTS "Estonian (et)": "et", "Croatian (hr)": "hr", "Icelandic (is)": "is", "Georgian (ka)": "ka", # no aux gTTS "Khmer (km)": "km", "Slovak (sk)": "sk", "Albanian (sq)": "sq", "Serbian (sr)": "sr", "Azerbaijani (az)": "az", # no aux gTTS "Bulgarian (bg)": "bg", "Galician (gl)": "gl", # no aux gTTS "Gujarati (gu)": "gu", "Kazakh (kk)": "kk", # no aux gTTS "Kannada (kn)": "kn", "Lithuanian (lt)": "lt", # no aux gTTS "Latvian (lv)": "lv", "Macedonian (mk)": "mk", # no aux gTTS # error get align model "Malayalam (ml)": "ml", "Malay (ms)": "ms", # error get align model "Romanian (ro)": "ro", "Sinhala (si)": "si", "Sundanese (su)": "su", "Swahili (sw)": "sw", # error aling "Afrikaans (af)": "af", "Bosnian (bs)": "bs", "Latin (la)": "la", "Myanmar Burmese (my)": "my", "Norwegian (no|nb)": "no", "Chinese - Traditional (zh-TW)": "zh-TW", "Assamese (as)": "as", "Basque (eu)": "eu", "Hausa (ha)": "ha", "Haitian Creole (ht)": "ht", "Armenian (hy)": "hy", "Lao (lo)": "lo", "Malagasy (mg)": "mg", "Mongolian (mn)": "mn", "Maltese (mt)": "mt", "Punjabi (pa)": "pa", "Pashto (ps)": "ps", "Slovenian (sl)": "sl", "Shona (sn)": "sn", "Somali (so)": "so", "Tajik (tg)": "tg", "Turkmen (tk)": "tk", "Tatar (tt)": "tt", "Uzbek (uz)": "uz", "Yoruba (yo)": "yo", **LANGUAGES_UNIDIRECTIONAL}
BASE_L_LIST = LANGUAGES.keys()LANGUAGES_LIST = [list(BASE_L_LIST)[0]] + sorted(list(BASE_L_LIST)[1:])INVERTED_LANGUAGES = {value: key for key, value in LANGUAGES.items()}
EXTRA_ALIGN = { "id": "indonesian-nlp/wav2vec2-large-xlsr-indonesian", "bn": "arijitx/wav2vec2-large-xlsr-bengali", "mr": "sumedh/wav2vec2-large-xlsr-marathi", "ta": "Amrrs/wav2vec2-large-xlsr-53-tamil", "jw": "cahya/wav2vec2-large-xlsr-javanese", "ne": "shniranjan/wav2vec2-large-xlsr-300m-nepali", "th": "sakares/wav2vec2-large-xlsr-thai-demo", "sv": "KBLab/wav2vec2-large-voxrex-swedish", "am": "agkphysics/wav2vec2-large-xlsr-53-amharic", "cy": "Srulikbdd/Wav2Vec2-large-xlsr-welsh", "et": "anton-l/wav2vec2-large-xlsr-53-estonian", "hr": "classla/wav2vec2-xls-r-parlaspeech-hr", "is": "carlosdanielhernandezmena/wav2vec2-large-xlsr-53-icelandic-ep10-1000h", "ka": "MehdiHosseiniMoghadam/wav2vec2-large-xlsr-53-Georgian", "km": "vitouphy/wav2vec2-xls-r-300m-khmer", "sk": "infinitejoy/wav2vec2-large-xls-r-300m-slovak", "sq": "Alimzhan/wav2vec2-large-xls-r-300m-albanian-colab", "sr": "dnikolic/wav2vec2-xlsr-530-serbian-colab", "az": "nijatzeynalov/wav2vec2-large-mms-1b-azerbaijani-common_voice15.0", "bg": "infinitejoy/wav2vec2-large-xls-r-300m-bulgarian", "gl": "ifrz/wav2vec2-large-xlsr-galician", "gu": "Harveenchadha/vakyansh-wav2vec2-gujarati-gnm-100", "kk": "aismlv/wav2vec2-large-xlsr-kazakh", "kn": "Harveenchadha/vakyansh-wav2vec2-kannada-knm-560", "lt": "DeividasM/wav2vec2-large-xlsr-53-lithuanian", "lv": "anton-l/wav2vec2-large-xlsr-53-latvian", "mk": "", # Konstantin-Bogdanoski/wav2vec2-macedonian-base "ml": "gvs/wav2vec2-large-xlsr-malayalam", "ms": "", # Duy/wav2vec2_malay "ro": "anton-l/wav2vec2-large-xlsr-53-romanian", "si": "IAmNotAnanth/wav2vec2-large-xls-r-300m-sinhala", "su": "cahya/wav2vec2-large-xlsr-sundanese", "sw": "", # Lians/fine-tune-wav2vec2-large-swahili "af": "", # ylacombe/wav2vec2-common_voice-af-demo "bs": "", "la": "", "my": "", "no": "NbAiLab/wav2vec2-xlsr-300m-norwegian", "zh-TW": "jonatasgrosman/wav2vec2-large-xlsr-53-chinese-zh-cn", "as": "", "eu": "", # cahya/wav2vec2-large-xlsr-basque # verify "ha": "infinitejoy/wav2vec2-large-xls-r-300m-hausa", "ht": "", "hy": "infinitejoy/wav2vec2-large-xls-r-300m-armenian", # no (.) "lo": "", "mg": "", "mn": "tugstugi/wav2vec2-large-xlsr-53-mongolian", "mt": "carlosdanielhernandezmena/wav2vec2-large-xlsr-53-maltese-64h", "pa": "kingabzpro/wav2vec2-large-xlsr-53-punjabi", "ps": "aamirhs/wav2vec2-large-xls-r-300m-pashto-colab", "sl": "anton-l/wav2vec2-large-xlsr-53-slovenian", "sn": "", "so": "", "tg": "", "tk": "", # Ragav/wav2vec2-tk "tt": "anton-l/wav2vec2-large-xlsr-53-tatar", "uz": "", # Mekhriddin/wav2vec2-large-xls-r-300m-uzbek-colab "yo": "ogbi/wav2vec2-large-mms-1b-yoruba-test",}
def fix_code_language(translate_to, syntax="google"): if syntax == "google": # google-translator, gTTS replace_lang_code = {"zh": "zh-CN", "he": "iw", "zh-cn": "zh-CN"} elif syntax == "coqui": # coqui-xtts replace_lang_code = {"zh": "zh-cn", "zh-CN": "zh-cn", "zh-TW": "zh-cn"}
new_code_lang = replace_lang_code.get(translate_to, translate_to) logger.debug(f"Fix code {translate_to} -> {new_code_lang}") return new_code_lang
BARK_VOICES_LIST = { "de_speaker_0-Male BARK": "v2/de_speaker_0", "de_speaker_1-Male BARK": "v2/de_speaker_1", "de_speaker_2-Male BARK": "v2/de_speaker_2", "de_speaker_3-Female BARK": "v2/de_speaker_3", "de_speaker_4-Male BARK": "v2/de_speaker_4", "de_speaker_5-Male BARK": "v2/de_speaker_5", "de_speaker_6-Male BARK": "v2/de_speaker_6", "de_speaker_7-Male BARK": "v2/de_speaker_7", "de_speaker_8-Female BARK": "v2/de_speaker_8", "de_speaker_9-Male BARK": "v2/de_speaker_9", "en_speaker_0-Male BARK": "v2/en_speaker_0", "en_speaker_1-Male BARK": "v2/en_speaker_1", "en_speaker_2-Male BARK": "v2/en_speaker_2", "en_speaker_3-Male BARK": "v2/en_speaker_3", "en_speaker_4-Male BARK": "v2/en_speaker_4", "en_speaker_5-Male BARK": "v2/en_speaker_5", "en_speaker_6-Male BARK": "v2/en_speaker_6", "en_speaker_7-Male BARK": "v2/en_speaker_7", "en_speaker_8-Male BARK": "v2/en_speaker_8", "en_speaker_9-Female BARK": "v2/en_speaker_9", "es_speaker_0-Male BARK": "v2/es_speaker_0", "es_speaker_1-Male BARK": "v2/es_speaker_1", "es_speaker_2-Male BARK": "v2/es_speaker_2", "es_speaker_3-Male BARK": "v2/es_speaker_3", "es_speaker_4-Male BARK": "v2/es_speaker_4", "es_speaker_5-Male BARK": "v2/es_speaker_5", "es_speaker_6-Male BARK": "v2/es_speaker_6", "es_speaker_7-Male BARK": "v2/es_speaker_7", "es_speaker_8-Female BARK": "v2/es_speaker_8", "es_speaker_9-Female BARK": "v2/es_speaker_9", "fr_speaker_0-Male BARK": "v2/fr_speaker_0", "fr_speaker_1-Female BARK": "v2/fr_speaker_1", "fr_speaker_2-Female BARK": "v2/fr_speaker_2", "fr_speaker_3-Male BARK": "v2/fr_speaker_3", "fr_speaker_4-Male BARK": "v2/fr_speaker_4", "fr_speaker_5-Female BARK": "v2/fr_speaker_5", "fr_speaker_6-Male BARK": "v2/fr_speaker_6", "fr_speaker_7-Male BARK": "v2/fr_speaker_7", "fr_speaker_8-Male BARK": "v2/fr_speaker_8", "fr_speaker_9-Male BARK": "v2/fr_speaker_9", "hi_speaker_0-Female BARK": "v2/hi_speaker_0", "hi_speaker_1-Female BARK": "v2/hi_speaker_1", "hi_speaker_2-Male BARK": "v2/hi_speaker_2", "hi_speaker_3-Female BARK": "v2/hi_speaker_3", "hi_speaker_4-Female BARK": "v2/hi_speaker_4", "hi_speaker_5-Male BARK": "v2/hi_speaker_5", "hi_speaker_6-Male BARK": "v2/hi_speaker_6", "hi_speaker_7-Male BARK": "v2/hi_speaker_7", "hi_speaker_8-Male BARK": "v2/hi_speaker_8", "hi_speaker_9-Female BARK": "v2/hi_speaker_9", "it_speaker_0-Male BARK": "v2/it_speaker_0", "it_speaker_1-Male BARK": "v2/it_speaker_1", "it_speaker_2-Female BARK": "v2/it_speaker_2", "it_speaker_3-Male BARK": "v2/it_speaker_3", "it_speaker_4-Male BARK": "v2/it_speaker_4", "it_speaker_5-Male BARK": "v2/it_speaker_5", "it_speaker_6-Male BARK": "v2/it_speaker_6", "it_speaker_7-Female BARK": "v2/it_speaker_7", "it_speaker_8-Male BARK": "v2/it_speaker_8", "it_speaker_9-Female BARK": "v2/it_speaker_9", "ja_speaker_0-Female BARK": "v2/ja_speaker_0", "ja_speaker_1-Female BARK": "v2/ja_speaker_1", "ja_speaker_2-Male BARK": "v2/ja_speaker_2", "ja_speaker_3-Female BARK": "v2/ja_speaker_3", "ja_speaker_4-Female BARK": "v2/ja_speaker_4", "ja_speaker_5-Female BARK": "v2/ja_speaker_5", "ja_speaker_6-Male BARK": "v2/ja_speaker_6", "ja_speaker_7-Female BARK": "v2/ja_speaker_7", "ja_speaker_8-Female BARK": "v2/ja_speaker_8", "ja_speaker_9-Female BARK": "v2/ja_speaker_9", "ko_speaker_0-Female BARK": "v2/ko_speaker_0", "ko_speaker_1-Male BARK": "v2/ko_speaker_1", "ko_speaker_2-Male BARK": "v2/ko_speaker_2", "ko_speaker_3-Male BARK": "v2/ko_speaker_3", "ko_speaker_4-Male BARK": "v2/ko_speaker_4", "ko_speaker_5-Male BARK": "v2/ko_speaker_5", "ko_speaker_6-Male BARK": "v2/ko_speaker_6", "ko_speaker_7-Male BARK": "v2/ko_speaker_7", "ko_speaker_8-Male BARK": "v2/ko_speaker_8", "ko_speaker_9-Male BARK": "v2/ko_speaker_9", "pl_speaker_0-Male BARK": "v2/pl_speaker_0", "pl_speaker_1-Male BARK": "v2/pl_speaker_1", "pl_speaker_2-Male BARK": "v2/pl_speaker_2", "pl_speaker_3-Male BARK": "v2/pl_speaker_3", "pl_speaker_4-Female BARK": "v2/pl_speaker_4", "pl_speaker_5-Male BARK": "v2/pl_speaker_5", "pl_speaker_6-Female BARK": "v2/pl_speaker_6", "pl_speaker_7-Male BARK": "v2/pl_speaker_7", "pl_speaker_8-Male BARK": "v2/pl_speaker_8", "pl_speaker_9-Female BARK": "v2/pl_speaker_9", "pt_speaker_0-Male BARK": "v2/pt_speaker_0", "pt_speaker_1-Male BARK": "v2/pt_speaker_1", "pt_speaker_2-Male BARK": "v2/pt_speaker_2", "pt_speaker_3-Male BARK": "v2/pt_speaker_3", "pt_speaker_4-Male BARK": "v2/pt_speaker_4", "pt_speaker_5-Male BARK": "v2/pt_speaker_5", "pt_speaker_6-Male BARK": "v2/pt_speaker_6", "pt_speaker_7-Male BARK": "v2/pt_speaker_7", "pt_speaker_8-Male BARK": "v2/pt_speaker_8", "pt_speaker_9-Male BARK": "v2/pt_speaker_9", "ru_speaker_0-Male BARK": "v2/ru_speaker_0", "ru_speaker_1-Male BARK": "v2/ru_speaker_1", "ru_speaker_2-Male BARK": "v2/ru_speaker_2", "ru_speaker_3-Male BARK": "v2/ru_speaker_3", "ru_speaker_4-Male BARK": "v2/ru_speaker_4", "ru_speaker_5-Female BARK": "v2/ru_speaker_5", "ru_speaker_6-Female BARK": "v2/ru_speaker_6", "ru_speaker_7-Male BARK": "v2/ru_speaker_7", "ru_speaker_8-Male BARK": "v2/ru_speaker_8", "ru_speaker_9-Female BARK": "v2/ru_speaker_9", "tr_speaker_0-Male BARK": "v2/tr_speaker_0", "tr_speaker_1-Male BARK": "v2/tr_speaker_1", "tr_speaker_2-Male BARK": "v2/tr_speaker_2", "tr_speaker_3-Male BARK": "v2/tr_speaker_3", "tr_speaker_4-Female BARK": "v2/tr_speaker_4", "tr_speaker_5-Female BARK": "v2/tr_speaker_5", "tr_speaker_6-Male BARK": "v2/tr_speaker_6", "tr_speaker_7-Male BARK": "v2/tr_speaker_7", "tr_speaker_8-Male BARK": "v2/tr_speaker_8", "tr_speaker_9-Male BARK": "v2/tr_speaker_9", "zh_speaker_0-Male BARK": "v2/zh_speaker_0", "zh_speaker_1-Male BARK": "v2/zh_speaker_1", "zh_speaker_2-Male BARK": "v2/zh_speaker_2", "zh_speaker_3-Male BARK": "v2/zh_speaker_3", "zh_speaker_4-Female BARK": "v2/zh_speaker_4", "zh_speaker_5-Male BARK": "v2/zh_speaker_5", "zh_speaker_6-Female BARK": "v2/zh_speaker_6", "zh_speaker_7-Female BARK": "v2/zh_speaker_7", "zh_speaker_8-Male BARK": "v2/zh_speaker_8", "zh_speaker_9-Female BARK": "v2/zh_speaker_9",}
VITS_VOICES_LIST = { "ar-facebook-mms VITS": "facebook/mms-tts-ara", # 'zh-facebook-mms VITS': 'facebook/mms-tts-cmn', "zh_Hakka-facebook-mms VITS": "facebook/mms-tts-hak", "zh_MinNan-facebook-mms VITS": "facebook/mms-tts-nan", # 'cs-facebook-mms VITS': 'facebook/mms-tts-ces', # 'da-facebook-mms VITS': 'facebook/mms-tts-dan', "nl-facebook-mms VITS": "facebook/mms-tts-nld", "en-facebook-mms VITS": "facebook/mms-tts-eng", "fi-facebook-mms VITS": "facebook/mms-tts-fin", "fr-facebook-mms VITS": "facebook/mms-tts-fra", "de-facebook-mms VITS": "facebook/mms-tts-deu", "el-facebook-mms VITS": "facebook/mms-tts-ell", "el_Ancient-facebook-mms VITS": "facebook/mms-tts-grc", "he-facebook-mms VITS": "facebook/mms-tts-heb", "hu-facebook-mms VITS": "facebook/mms-tts-hun", # 'it-facebook-mms VITS': 'facebook/mms-tts-ita', # 'ja-facebook-mms VITS': 'facebook/mms-tts-jpn', "ko-facebook-mms VITS": "facebook/mms-tts-kor", "fa-facebook-mms VITS": "facebook/mms-tts-fas", "pl-facebook-mms VITS": "facebook/mms-tts-pol", "pt-facebook-mms VITS": "facebook/mms-tts-por", "ru-facebook-mms VITS": "facebook/mms-tts-rus", "es-facebook-mms VITS": "facebook/mms-tts-spa", "tr-facebook-mms VITS": "facebook/mms-tts-tur", "uk-facebook-mms VITS": "facebook/mms-tts-ukr", "ur_arabic-facebook-mms VITS": "facebook/mms-tts-urd-script_arabic", "ur_devanagari-facebook-mms VITS": "facebook/mms-tts-urd-script_devanagari", "ur_latin-facebook-mms VITS": "facebook/mms-tts-urd-script_latin", "vi-facebook-mms VITS": "facebook/mms-tts-vie", "hi-facebook-mms VITS": "facebook/mms-tts-hin", "hi_Fiji-facebook-mms VITS": "facebook/mms-tts-hif", "id-facebook-mms VITS": "facebook/mms-tts-ind", "bn-facebook-mms VITS": "facebook/mms-tts-ben", "te-facebook-mms VITS": "facebook/mms-tts-tel", "mr-facebook-mms VITS": "facebook/mms-tts-mar", "ta-facebook-mms VITS": "facebook/mms-tts-tam", "jw-facebook-mms VITS": "facebook/mms-tts-jav", "jw_Suriname-facebook-mms VITS": "facebook/mms-tts-jvn", "ca-facebook-mms VITS": "facebook/mms-tts-cat", "ne-facebook-mms VITS": "facebook/mms-tts-nep", "th-facebook-mms VITS": "facebook/mms-tts-tha", "th_Northern-facebook-mms VITS": "facebook/mms-tts-nod", "sv-facebook-mms VITS": "facebook/mms-tts-swe", "am-facebook-mms VITS": "facebook/mms-tts-amh", "cy-facebook-mms VITS": "facebook/mms-tts-cym", # "et-facebook-mms VITS": "facebook/mms-tts-est", # "ht-facebook-mms VITS": "facebook/mms-tts-hrv", "is-facebook-mms VITS": "facebook/mms-tts-isl", "km-facebook-mms VITS": "facebook/mms-tts-khm", "km_Northern-facebook-mms VITS": "facebook/mms-tts-kxm", # "sk-facebook-mms VITS": "facebook/mms-tts-slk", "sq_Northern-facebook-mms VITS": "facebook/mms-tts-sqi", "az_South-facebook-mms VITS": "facebook/mms-tts-azb", "az_North_script_cyrillic-facebook-mms VITS": "facebook/mms-tts-azj-script_cyrillic", "az_North_script_latin-facebook-mms VITS": "facebook/mms-tts-azj-script_latin", "bg-facebook-mms VITS": "facebook/mms-tts-bul", # "gl-facebook-mms VITS": "facebook/mms-tts-glg", "gu-facebook-mms VITS": "facebook/mms-tts-guj", "kk-facebook-mms VITS": "facebook/mms-tts-kaz", "kn-facebook-mms VITS": "facebook/mms-tts-kan", # "lt-facebook-mms VITS": "facebook/mms-tts-lit", "lv-facebook-mms VITS": "facebook/mms-tts-lav", # "mk-facebook-mms VITS": "facebook/mms-tts-mkd", "ml-facebook-mms VITS": "facebook/mms-tts-mal", "ms-facebook-mms VITS": "facebook/mms-tts-zlm", "ms_Central-facebook-mms VITS": "facebook/mms-tts-pse", "ms_Manado-facebook-mms VITS": "facebook/mms-tts-xmm", "ro-facebook-mms VITS": "facebook/mms-tts-ron", # "si-facebook-mms VITS": "facebook/mms-tts-sin", "sw-facebook-mms VITS": "facebook/mms-tts-swh", # "af-facebook-mms VITS": "facebook/mms-tts-afr", # "bs-facebook-mms VITS": "facebook/mms-tts-bos", "la-facebook-mms VITS": "facebook/mms-tts-lat", "my-facebook-mms VITS": "facebook/mms-tts-mya", # "no_Bokmål-facebook-mms VITS": "thomasht86/mms-tts-nob", # verify "as-facebook-mms VITS": "facebook/mms-tts-asm", "as_Nagamese-facebook-mms VITS": "facebook/mms-tts-nag", "eu-facebook-mms VITS": "facebook/mms-tts-eus", "ha-facebook-mms VITS": "facebook/mms-tts-hau", "ht-facebook-mms VITS": "facebook/mms-tts-hat", "hy_Western-facebook-mms VITS": "facebook/mms-tts-hyw", "lo-facebook-mms VITS": "facebook/mms-tts-lao", "mg-facebook-mms VITS": "facebook/mms-tts-mlg", "mn-facebook-mms VITS": "facebook/mms-tts-mon", # "mt-facebook-mms VITS": "facebook/mms-tts-mlt", "pa_Eastern-facebook-mms VITS": "facebook/mms-tts-pan", # "pa_Western-facebook-mms VITS": "facebook/mms-tts-pnb", # "ps-facebook-mms VITS": "facebook/mms-tts-pus", # "sl-facebook-mms VITS": "facebook/mms-tts-slv", "sn-facebook-mms VITS": "facebook/mms-tts-sna", "so-facebook-mms VITS": "facebook/mms-tts-son", "tg-facebook-mms VITS": "facebook/mms-tts-tgk", "tk_script_arabic-facebook-mms VITS": "facebook/mms-tts-tuk-script_arabic", "tk_script_latin-facebook-mms VITS": "facebook/mms-tts-tuk-script_latin", "tt-facebook-mms VITS": "facebook/mms-tts-tat", "tt_Crimean-facebook-mms VITS": "facebook/mms-tts-crh", "uz_script_cyrillic-facebook-mms VITS": "facebook/mms-tts-uzb-script_cyrillic", "yo-facebook-mms VITS": "facebook/mms-tts-yor", "ay-facebook-mms VITS": "facebook/mms-tts-ayr", "bm-facebook-mms VITS": "facebook/mms-tts-bam", "ceb-facebook-mms VITS": "facebook/mms-tts-ceb", "ny-facebook-mms VITS": "facebook/mms-tts-nya", "dv-facebook-mms VITS": "facebook/mms-tts-div", "doi-facebook-mms VITS": "facebook/mms-tts-dgo", "ee-facebook-mms VITS": "facebook/mms-tts-ewe", "gn-facebook-mms VITS": "facebook/mms-tts-grn", "ilo-facebook-mms VITS": "facebook/mms-tts-ilo", "rw-facebook-mms VITS": "facebook/mms-tts-kin", "kri-facebook-mms VITS": "facebook/mms-tts-kri", "ku_script_arabic-facebook-mms VITS": "facebook/mms-tts-kmr-script_arabic", "ku_script_cyrillic-facebook-mms VITS": "facebook/mms-tts-kmr-script_cyrillic", "ku_script_latin-facebook-mms VITS": "facebook/mms-tts-kmr-script_latin", "ckb-facebook-mms VITS": "razhan/mms-tts-ckb", # Verify w "ky-facebook-mms VITS": "facebook/mms-tts-kir", "lg-facebook-mms VITS": "facebook/mms-tts-lug", "mai-facebook-mms VITS": "facebook/mms-tts-mai", "or-facebook-mms VITS": "facebook/mms-tts-ory", "om-facebook-mms VITS": "facebook/mms-tts-orm", "qu_Huallaga-facebook-mms VITS": "facebook/mms-tts-qub", "qu_Lambayeque-facebook-mms VITS": "facebook/mms-tts-quf", "qu_South_Bolivian-facebook-mms VITS": "facebook/mms-tts-quh", "qu_North_Bolivian-facebook-mms VITS": "facebook/mms-tts-qul", "qu_Tena_Lowland-facebook-mms VITS": "facebook/mms-tts-quw", "qu_Ayacucho-facebook-mms VITS": "facebook/mms-tts-quy", "qu_Cusco-facebook-mms VITS": "facebook/mms-tts-quz", "qu_Cajamarca-facebook-mms VITS": "facebook/mms-tts-qvc", "qu_Eastern_Apurímac-facebook-mms VITS": "facebook/mms-tts-qve", "qu_Huamalíes_Dos_de_Mayo_Huánuco-facebook-mms VITS": "facebook/mms-tts-qvh", "qu_Margos_Yarowilca_Lauricocha-facebook-mms VITS": "facebook/mms-tts-qvm", "qu_North_Junín-facebook-mms VITS": "facebook/mms-tts-qvn", "qu_Napo-facebook-mms VITS": "facebook/mms-tts-qvo", "qu_San_Martín-facebook-mms VITS": "facebook/mms-tts-qvs", "qu_Huaylla_Wanca-facebook-mms VITS": "facebook/mms-tts-qvw", "qu_Northern_Pastaza-facebook-mms VITS": "facebook/mms-tts-qvz", "qu_Huaylas_Ancash-facebook-mms VITS": "facebook/mms-tts-qwh", "qu_Panao-facebook-mms VITS": "facebook/mms-tts-qxh", "qu_Salasaca_Highland-facebook-mms VITS": "facebook/mms-tts-qxl", "qu_Northern_Conchucos_Ancash-facebook-mms VITS": "facebook/mms-tts-qxn", "qu_Southern_Conchucos-facebook-mms VITS": "facebook/mms-tts-qxo", "qu_Cañar_Highland-facebook-mms VITS": "facebook/mms-tts-qxr", "sm-facebook-mms VITS": "facebook/mms-tts-smo", "ti-facebook-mms VITS": "facebook/mms-tts-tir", "ts-facebook-mms VITS": "facebook/mms-tts-tso", "ak-facebook-mms VITS": "facebook/mms-tts-aka", "ug_script_arabic-facebook-mms VITS": "facebook/mms-tts-uig-script_arabic", "ug_script_cyrillic-facebook-mms VITS": "facebook/mms-tts-uig-script_cyrillic",}
OPENAI_TTS_CODES = [ "af", "ar", "hy", "az", "be", "bs", "bg", "ca", "zh", "hr", "cs", "da", "nl", "en", "et", "fi", "fr", "gl", "de", "el", "he", "hi", "hu", "is", "id", "it", "ja", "kn", "kk", "ko", "lv", "lt", "mk", "ms", "mr", "mi", "ne", "no", "fa", "pl", "pt", "ro", "ru", "sr", "sk", "sl", "es", "sw", "sv", "tl", "ta", "th", "tr", "uk", "ur", "vi", "cy", "zh-TW"]
OPENAI_TTS_MODELS = [ ">alloy OpenAI-TTS", ">echo OpenAI-TTS", ">fable OpenAI-TTS", ">onyx OpenAI-TTS", ">nova OpenAI-TTS", ">shimmer OpenAI-TTS", ">alloy HD OpenAI-TTS", ">echo HD OpenAI-TTS", ">fable HD OpenAI-TTS", ">onyx HD OpenAI-TTS", ">nova HD OpenAI-TTS", ">shimmer HD OpenAI-TTS"]
LANGUAGE_CODE_IN_THREE_LETTERS = { "Automatic detection": "aut", "ar": "ara", "zh": "chi", "cs": "cze", "da": "dan", "nl": "dut", "en": "eng", "fi": "fin", "fr": "fre", "de": "ger", "el": "gre", "he": "heb", "hu": "hun", "it": "ita", "ja": "jpn", "ko": "kor", "fa": "per", "pl": "pol", "pt": "por", "ru": "rus", "es": "spa", "tr": "tur", "uk": "ukr", "ur": "urd", "vi": "vie", "hi": "hin", "id": "ind", "bn": "ben", "te": "tel", "mr": "mar", "ta": "tam", "jw": "jav", "ca": "cat", "ne": "nep", "th": "tha", "sv": "swe", "am": "amh", "cy": "cym", "et": "est", "hr": "hrv", "is": "isl", "km": "khm", "sk": "slk", "sq": "sqi", "sr": "srp",}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768import loggingimport sysimport warningsimport os
def configure_logging_libs(debug=False): warnings.filterwarnings( action="ignore", category=UserWarning, module="pyannote" ) modules = [ "numba", "httpx", "markdown_it", "speechbrain", "fairseq", "pyannote", "faiss", "pytorch_lightning.utilities.migration.utils", "pytorch_lightning.utilities.migration", "pytorch_lightning", "lightning", "lightning.pytorch.utilities.migration.utils", ] try: for module in modules: logging.getLogger(module).setLevel(logging.WARNING) os.environ['TF_CPP_MIN_LOG_LEVEL'] = "3" if not debug else "1"
# fix verbose pyannote audio def fix_verbose_pyannote(*args, what=""): pass import pyannote.audio.core.model # noqa pyannote.audio.core.model.check_version = fix_verbose_pyannote except Exception as error: logger.error(str(error))
def setup_logger(name_log): logger = logging.getLogger(name_log) logger.setLevel(logging.INFO)
_default_handler = logging.StreamHandler() # Set sys.stderr as stream. _default_handler.flush = sys.stderr.flush logger.addHandler(_default_handler)
logger.propagate = False
handlers = logger.handlers
for handler in handlers: formatter = logging.Formatter("[%(levelname)s] >> %(message)s") handler.setFormatter(formatter)
# logger.handlers
return logger
logger = setup_logger("sonitranslate")logger.setLevel(logging.INFO)
def set_logging_level(verbosity_level): logging_level_mapping = { "debug": logging.DEBUG, "info": logging.INFO, "warning": logging.WARNING, "error": logging.ERROR, "critical": logging.CRITICAL, }
logger.setLevel(logging_level_mapping.get(verbosity_level, logging.INFO))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582import gcimport hashlibimport osimport queueimport threadingimport jsonimport shleximport sysimport subprocessimport librosaimport numpy as npimport soundfile as sfimport torchfrom tqdm import tqdm
try: from .utils import ( remove_directory_contents, create_directories, )except: # noqa from utils import ( remove_directory_contents, create_directories, )from .logging_setup import logger
try: import onnxruntime as ortexcept Exception as error: logger.error(str(error))# import warnings# warnings.filterwarnings("ignore")
stem_naming = { "Vocals": "Instrumental", "Other": "Instruments", "Instrumental": "Vocals", "Drums": "Drumless", "Bass": "Bassless",}
class MDXModel: def __init__( self, device, dim_f, dim_t, n_fft, hop=1024, stem_name=None, compensation=1.000, ): self.dim_f = dim_f self.dim_t = dim_t self.dim_c = 4 self.n_fft = n_fft self.hop = hop self.stem_name = stem_name self.compensation = compensation
self.n_bins = self.n_fft // 2 + 1 self.chunk_size = hop * (self.dim_t - 1) self.window = torch.hann_window( window_length=self.n_fft, periodic=True ).to(device)
out_c = self.dim_c
self.freq_pad = torch.zeros( [1, out_c, self.n_bins - self.dim_f, self.dim_t] ).to(device)
def stft(self, x): x = x.reshape([-1, self.chunk_size]) x = torch.stft( x, n_fft=self.n_fft, hop_length=self.hop, window=self.window, center=True, return_complex=True, ) x = torch.view_as_real(x) x = x.permute([0, 3, 1, 2]) x = x.reshape([-1, 2, 2, self.n_bins, self.dim_t]).reshape( [-1, 4, self.n_bins, self.dim_t] ) return x[:, :, : self.dim_f]
def istft(self, x, freq_pad=None): freq_pad = ( self.freq_pad.repeat([x.shape[0], 1, 1, 1]) if freq_pad is None else freq_pad ) x = torch.cat([x, freq_pad], -2) # c = 4*2 if self.target_name=='*' else 2 x = x.reshape([-1, 2, 2, self.n_bins, self.dim_t]).reshape( [-1, 2, self.n_bins, self.dim_t] ) x = x.permute([0, 2, 3, 1]) x = x.contiguous() x = torch.view_as_complex(x) x = torch.istft( x, n_fft=self.n_fft, hop_length=self.hop, window=self.window, center=True, ) return x.reshape([-1, 2, self.chunk_size])
class MDX: DEFAULT_SR = 44100 # Unit: seconds DEFAULT_CHUNK_SIZE = 0 * DEFAULT_SR DEFAULT_MARGIN_SIZE = 1 * DEFAULT_SR
def __init__( self, model_path: str, params: MDXModel, processor=0 ): # Set the device and the provider (CPU or CUDA) self.device = ( torch.device(f"cuda:{processor}") if processor >= 0 else torch.device("cpu") ) self.provider = ( ["CUDAExecutionProvider"] if processor >= 0 else ["CPUExecutionProvider"] )
self.model = params
# Load the ONNX model using ONNX Runtime self.ort = ort.InferenceSession(model_path, providers=self.provider) # Preload the model for faster performance self.ort.run( None, {"input": torch.rand(1, 4, params.dim_f, params.dim_t).numpy()}, ) self.process = lambda spec: self.ort.run( None, {"input": spec.cpu().numpy()} )[0]
self.prog = None
@staticmethod def get_hash(model_path): try: with open(model_path, "rb") as f: f.seek(-10000 * 1024, 2) model_hash = hashlib.md5(f.read()).hexdigest() except: # noqa model_hash = hashlib.md5(open(model_path, "rb").read()).hexdigest()
return model_hash
@staticmethod def segment( wave, combine=True, chunk_size=DEFAULT_CHUNK_SIZE, margin_size=DEFAULT_MARGIN_SIZE, ): """ Segment or join segmented wave array
Args: wave: (np.array) Wave array to be segmented or joined combine: (bool) If True, combines segmented wave array. If False, segments wave array. chunk_size: (int) Size of each segment (in samples) margin_size: (int) Size of margin between segments (in samples)
Returns: numpy array: Segmented or joined wave array """
if combine: # Initializing as None instead of [] for later numpy array concatenation processed_wave = None for segment_count, segment in enumerate(wave): start = 0 if segment_count == 0 else margin_size end = None if segment_count == len(wave) - 1 else -margin_size if margin_size == 0: end = None if processed_wave is None: # Create array for first segment processed_wave = segment[:, start:end] else: # Concatenate to existing array for subsequent segments processed_wave = np.concatenate( (processed_wave, segment[:, start:end]), axis=-1 )
else: processed_wave = [] sample_count = wave.shape[-1]
if chunk_size <= 0 or chunk_size > sample_count: chunk_size = sample_count
if margin_size > chunk_size: margin_size = chunk_size
for segment_count, skip in enumerate( range(0, sample_count, chunk_size) ): margin = 0 if segment_count == 0 else margin_size end = min(skip + chunk_size + margin_size, sample_count) start = skip - margin
cut = wave[:, start:end].copy() processed_wave.append(cut)
if end == sample_count: break
return processed_wave
def pad_wave(self, wave): """ Pad the wave array to match the required chunk size
Args: wave: (np.array) Wave array to be padded
Returns: tuple: (padded_wave, pad, trim) - padded_wave: Padded wave array - pad: Number of samples that were padded - trim: Number of samples that were trimmed """ n_sample = wave.shape[1] trim = self.model.n_fft // 2 gen_size = self.model.chunk_size - 2 * trim pad = gen_size - n_sample % gen_size
# Padded wave wave_p = np.concatenate( ( np.zeros((2, trim)), wave, np.zeros((2, pad)), np.zeros((2, trim)), ), 1, )
mix_waves = [] for i in range(0, n_sample + pad, gen_size): waves = np.array(wave_p[:, i:i + self.model.chunk_size]) mix_waves.append(waves)
mix_waves = torch.tensor(mix_waves, dtype=torch.float32).to( self.device )
return mix_waves, pad, trim
def _process_wave(self, mix_waves, trim, pad, q: queue.Queue, _id: int): """ Process each wave segment in a multi-threaded environment
Args: mix_waves: (torch.Tensor) Wave segments to be processed trim: (int) Number of samples trimmed during padding pad: (int) Number of samples padded during padding q: (queue.Queue) Queue to hold the processed wave segments _id: (int) Identifier of the processed wave segment
Returns: numpy array: Processed wave segment """ mix_waves = mix_waves.split(1) with torch.no_grad(): pw = [] for mix_wave in mix_waves: self.prog.update() spec = self.model.stft(mix_wave) processed_spec = torch.tensor(self.process(spec)) processed_wav = self.model.istft( processed_spec.to(self.device) ) processed_wav = ( processed_wav[:, :, trim:-trim] .transpose(0, 1) .reshape(2, -1) .cpu() .numpy() ) pw.append(processed_wav) processed_signal = np.concatenate(pw, axis=-1)[:, :-pad] q.put({_id: processed_signal}) return processed_signal
def process_wave(self, wave: np.array, mt_threads=1): """ Process the wave array in a multi-threaded environment
Args: wave: (np.array) Wave array to be processed mt_threads: (int) Number of threads to be used for processing
Returns: numpy array: Processed wave array """ self.prog = tqdm(total=0) chunk = wave.shape[-1] // mt_threads waves = self.segment(wave, False, chunk)
# Create a queue to hold the processed wave segments q = queue.Queue() threads = [] for c, batch in enumerate(waves): mix_waves, pad, trim = self.pad_wave(batch) self.prog.total = len(mix_waves) * mt_threads thread = threading.Thread( target=self._process_wave, args=(mix_waves, trim, pad, q, c) ) thread.start() threads.append(thread) for thread in threads: thread.join() self.prog.close()
processed_batches = [] while not q.empty(): processed_batches.append(q.get()) processed_batches = [ list(wave.values())[0] for wave in sorted( processed_batches, key=lambda d: list(d.keys())[0] ) ] assert len(processed_batches) == len( waves ), "Incomplete processed batches, please reduce batch size!" return self.segment(processed_batches, True, chunk)
def run_mdx( model_params, output_dir, model_path, filename, exclude_main=False, exclude_inversion=False, suffix=None, invert_suffix=None, denoise=False, keep_orig=True, m_threads=2, device_base="cuda",): if device_base == "cuda": device = torch.device("cuda:0") processor_num = 0 device_properties = torch.cuda.get_device_properties(device) vram_gb = device_properties.total_memory / 1024**3 m_threads = 1 if vram_gb < 8 else 2 else: device = torch.device("cpu") processor_num = -1 m_threads = 1
model_hash = MDX.get_hash(model_path) mp = model_params.get(model_hash) model = MDXModel( device, dim_f=mp["mdx_dim_f_set"], dim_t=2 ** mp["mdx_dim_t_set"], n_fft=mp["mdx_n_fft_scale_set"], stem_name=mp["primary_stem"], compensation=mp["compensate"], )
mdx_sess = MDX(model_path, model, processor=processor_num) wave, sr = librosa.load(filename, mono=False, sr=44100) # normalizing input wave gives better output peak = max(np.max(wave), abs(np.min(wave))) wave /= peak if denoise: wave_processed = -(mdx_sess.process_wave(-wave, m_threads)) + ( mdx_sess.process_wave(wave, m_threads) ) wave_processed *= 0.5 else: wave_processed = mdx_sess.process_wave(wave, m_threads) # return to previous peak wave_processed *= peak stem_name = model.stem_name if suffix is None else suffix
main_filepath = None if not exclude_main: main_filepath = os.path.join( output_dir, f"{os.path.basename(os.path.splitext(filename)[0])}_{stem_name}.wav", ) sf.write(main_filepath, wave_processed.T, sr)
invert_filepath = None if not exclude_inversion: diff_stem_name = ( stem_naming.get(stem_name) if invert_suffix is None else invert_suffix ) stem_name = ( f"{stem_name}_diff" if diff_stem_name is None else diff_stem_name ) invert_filepath = os.path.join( output_dir, f"{os.path.basename(os.path.splitext(filename)[0])}_{stem_name}.wav", ) sf.write( invert_filepath, (-wave_processed.T * model.compensation) + wave.T, sr, )
if not keep_orig: os.remove(filename)
del mdx_sess, wave_processed, wave gc.collect() torch.cuda.empty_cache() return main_filepath, invert_filepath
MDX_DOWNLOAD_LINK = "https://github.com/TRvlvr/model_repo/releases/download/all_public_uvr_models/"UVR_MODELS = [ "UVR-MDX-NET-Voc_FT.onnx", "UVR_MDXNET_KARA_2.onnx", "Reverb_HQ_By_FoxJoy.onnx", "UVR-MDX-NET-Inst_HQ_4.onnx",]BASE_DIR = "." # os.path.dirname(os.path.dirname(os.path.abspath(__file__)))mdxnet_models_dir = os.path.join(BASE_DIR, "mdx_models")output_dir = os.path.join(BASE_DIR, "clean_song_output")
def convert_to_stereo_and_wav(audio_path): wave, sr = librosa.load(audio_path, mono=False, sr=44100)
# check if mono if type(wave[0]) != np.ndarray or audio_path[-4:].lower() != ".wav": # noqa stereo_path = f"{os.path.splitext(audio_path)[0]}_stereo.wav" stereo_path = os.path.join(output_dir, stereo_path)
command = shlex.split( f'ffmpeg -y -loglevel error -i "{audio_path}" -ac 2 -f wav "{stereo_path}"' ) sub_params = { "stdout": subprocess.PIPE, "stderr": subprocess.PIPE, "creationflags": subprocess.CREATE_NO_WINDOW if sys.platform == "win32" else 0, } process_wav = subprocess.Popen(command, **sub_params) output, errors = process_wav.communicate() if process_wav.returncode != 0 or not os.path.exists(stereo_path): raise Exception("Error processing audio to stereo wav")
return stereo_path else: return audio_path
def process_uvr_task( orig_song_path: str = "aud_test.mp3", main_vocals: bool = False, dereverb: bool = True, song_id: str = "mdx", # folder output name only_voiceless: bool = False, remove_files_output_dir: bool = False,): if os.environ.get("SONITR_DEVICE") == "cpu": device_base = "cpu" else: device_base = "cuda" if torch.cuda.is_available() else "cpu"
if remove_files_output_dir: remove_directory_contents(output_dir)
with open(os.path.join(mdxnet_models_dir, "data.json")) as infile: mdx_model_params = json.load(infile)
song_output_dir = os.path.join(output_dir, song_id) create_directories(song_output_dir) orig_song_path = convert_to_stereo_and_wav(orig_song_path)
logger.debug(f"onnxruntime device >> {ort.get_device()}")
if only_voiceless: logger.info("Voiceless Track Separation...") return run_mdx( mdx_model_params, song_output_dir, os.path.join(mdxnet_models_dir, "UVR-MDX-NET-Inst_HQ_4.onnx"), orig_song_path, suffix="Voiceless", denoise=False, keep_orig=True, exclude_inversion=True, device_base=device_base, )
logger.info("Vocal Track Isolation and Voiceless Track Separation...") vocals_path, instrumentals_path = run_mdx( mdx_model_params, song_output_dir, os.path.join(mdxnet_models_dir, "UVR-MDX-NET-Voc_FT.onnx"), orig_song_path, denoise=True, keep_orig=True, device_base=device_base, )
if main_vocals: logger.info("Main Voice Separation from Supporting Vocals...") backup_vocals_path, main_vocals_path = run_mdx( mdx_model_params, song_output_dir, os.path.join(mdxnet_models_dir, "UVR_MDXNET_KARA_2.onnx"), vocals_path, suffix="Backup", invert_suffix="Main", denoise=True, device_base=device_base, ) else: backup_vocals_path, main_vocals_path = None, vocals_path
if dereverb: logger.info("Vocal Clarity Enhancement through De-Reverberation...") _, vocals_dereverb_path = run_mdx( mdx_model_params, song_output_dir, os.path.join(mdxnet_models_dir, "Reverb_HQ_By_FoxJoy.onnx"), main_vocals_path, invert_suffix="DeReverb", exclude_main=True, denoise=True, device_base=device_base, ) else: vocals_dereverb_path = main_vocals_path
return ( vocals_path, instrumentals_path, backup_vocals_path, main_vocals_path, vocals_dereverb_path, )
if __name__ == "__main__": from utils import download_manager
for id_model in UVR_MODELS: download_manager( os.path.join(MDX_DOWNLOAD_LINK, id_model), mdxnet_models_dir ) ( vocals_path_, instrumentals_path_, backup_vocals_path_, main_vocals_path_, vocals_dereverb_path_, ) = process_uvr_task( orig_song_path="aud.mp3", main_vocals=True, dereverb=True, song_id="mdx", remove_files_output_dir=True, )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229from .utils import remove_files, run_commandfrom .text_multiformat_processor import get_subtitlefrom .logging_setup import loggerimport unicodedataimport shutilimport copyimport osimport re
OUTPUT_TYPE_OPTIONS = [ "video (mp4)", "video (mkv)", "audio (mp3)", "audio (ogg)", "audio (wav)", "subtitle", "subtitle [by speaker]", "video [subtitled] (mp4)", "video [subtitled] (mkv)", "audio [original vocal sound]", "audio [original background sound]", "audio [original vocal and background sound]", "audio [original vocal-dereverb sound]", "audio [original vocal-dereverb and background sound]", "raw media",]
DOCS_OUTPUT_TYPE_OPTIONS = [ "videobook (mp4)", "videobook (mkv)", "audiobook (wav)", "audiobook (mp3)", "audiobook (ogg)", "book (txt)",] # Add DOCX and etc.
def get_no_ext_filename(file_path): file_name_with_extension = os.path.basename(rf"{file_path}") filename_without_extension, _ = os.path.splitext(file_name_with_extension) return filename_without_extension
def get_video_info(link): aux_name = f"video_url_{link}" params_dlp = {"quiet": True, "no_warnings": True, "noplaylist": True} try: from yt_dlp import YoutubeDL
with YoutubeDL(params_dlp) as ydl: if link.startswith(("www.youtube.com/", "m.youtube.com/")): link = "https://" + link info_dict = ydl.extract_info(link, download=False, process=False) video_id = info_dict.get("id", aux_name) video_title = info_dict.get("title", video_id) if "youtube.com" in link and "&list=" in link: video_title = ydl.extract_info( "https://m.youtube.com/watch?v="+video_id, download=False, process=False ).get("title", video_title) except Exception as error: logger.error(str(error)) video_title, video_id = aux_name, "NO_ID" return video_title, video_id
def sanitize_file_name(file_name): # Normalize the string to NFKD form to separate combined # characters into base characters and diacritics normalized_name = unicodedata.normalize("NFKD", file_name) # Replace any non-ASCII characters or special symbols with an underscore sanitized_name = re.sub(r"[^\w\s.-]", "_", normalized_name) return sanitized_name
def get_output_file( original_file, new_file_name, soft_subtitles, output_directory="",): directory_base = "." # default directory
if output_directory and os.path.isdir(output_directory): new_file_path = os.path.join(output_directory, new_file_name) else: new_file_path = os.path.join(directory_base, "outputs", new_file_name) remove_files(new_file_path)
cm = None if soft_subtitles and original_file.endswith(".mp4"): if new_file_path.endswith(".mp4"): cm = f'ffmpeg -y -i "{original_file}" -i sub_tra.srt -i sub_ori.srt -map 0:v -map 0:a -map 1 -map 2 -c:v copy -c:a copy -c:s mov_text "{new_file_path}"' else: cm = f'ffmpeg -y -i "{original_file}" -i sub_tra.srt -i sub_ori.srt -map 0:v -map 0:a -map 1 -map 2 -c:v copy -c:a copy -c:s srt -movflags use_metadata_tags -map_metadata 0 "{new_file_path}"' elif new_file_path.endswith(".mkv"): cm = f'ffmpeg -i "{original_file}" -c:v copy -c:a copy "{new_file_path}"' elif new_file_path.endswith(".wav") and not original_file.endswith(".wav"): cm = f'ffmpeg -y -i "{original_file}" -acodec pcm_s16le -ar 44100 -ac 2 "{new_file_path}"' elif new_file_path.endswith(".ogg"): cm = f'ffmpeg -i "{original_file}" -c:a libvorbis "{new_file_path}"' elif new_file_path.endswith(".mp3") and not original_file.endswith(".mp3"): cm = f'ffmpeg -y -i "{original_file}" -codec:a libmp3lame -qscale:a 2 "{new_file_path}"'
if cm: try: run_command(cm) except Exception as error: logger.error(str(error)) remove_files(new_file_path) shutil.copy2(original_file, new_file_path) else: shutil.copy2(original_file, new_file_path)
return os.path.abspath(new_file_path)
def media_out( media_file, lang_code, media_out_name="", extension="mp4", file_obj="video_dub.mp4", soft_subtitles=False, subtitle_files="disable",): if not media_out_name: if os.path.exists(media_file): base_name = get_no_ext_filename(media_file) else: base_name, _ = get_video_info(media_file)
media_out_name = f"{base_name}__{lang_code}"
f_name = f"{sanitize_file_name(media_out_name)}.{extension}"
if subtitle_files != "disable": final_media = [get_output_file(file_obj, f_name, soft_subtitles)] name_tra = f"{sanitize_file_name(media_out_name)}.{subtitle_files}" name_ori = f"{sanitize_file_name(base_name)}.{subtitle_files}" tgt_subs = f"sub_tra.{subtitle_files}" ori_subs = f"sub_ori.{subtitle_files}" final_subtitles = [ get_output_file(tgt_subs, name_tra, False), get_output_file(ori_subs, name_ori, False) ] return final_media + final_subtitles else: return get_output_file(file_obj, f_name, soft_subtitles)
def get_subtitle_speaker(media_file, result, language, extension, base_name):
segments_base = copy.deepcopy(result)
# Sub segments by speaker segments_by_speaker = {} for segment in segments_base["segments"]: if segment["speaker"] not in segments_by_speaker.keys(): segments_by_speaker[segment["speaker"]] = [segment] else: segments_by_speaker[segment["speaker"]].append(segment)
if not base_name: if os.path.exists(media_file): base_name = get_no_ext_filename(media_file) else: base_name, _ = get_video_info(media_file)
files_subs = [] for name_sk, segments in segments_by_speaker.items():
subtitle_speaker = get_subtitle( language, {"segments": segments}, extension, filename=name_sk, )
media_out_name = f"{base_name}_{language}_{name_sk}"
output = media_out( media_file, # no need language, media_out_name, extension, file_obj=subtitle_speaker, )
files_subs.append(output)
return files_subs
def sound_separate(media_file, task_uvr): from .mdx_net import process_uvr_task
outputs = []
if "vocal" in task_uvr: try: _, _, _, _, vocal_audio = process_uvr_task( orig_song_path=media_file, main_vocals=False, dereverb=True if "dereverb" in task_uvr else False, remove_files_output_dir=True, ) outputs.append(vocal_audio) except Exception as error: logger.error(str(error))
if "background" in task_uvr: try: background_audio, _ = process_uvr_task( orig_song_path=media_file, song_id="voiceless", only_voiceless=True, remove_files_output_dir=False if "vocal" in task_uvr else True, ) # copy_files(background_audio, ".") outputs.append(background_audio) except Exception as error: logger.error(str(error))
if not outputs: raise Exception("Error in uvr process")
return outputs123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308from .utils import remove_filesimport os, shutil, subprocess, time, shlex, sys # noqafrom .logging_setup import loggerimport json
ERROR_INCORRECT_CODEC_PARAMETERS = [ "prores", # mov "ffv1", # mkv "msmpeg4v3", # avi "wmv2", # wmv "theora", # ogv] # fix final merge
TESTED_CODECS = [ "h264", # mp4 "h265", # mp4 "vp9", # webm "mpeg4", # mp4 "mpeg2video", # mpg "mjpeg", # avi]
class OperationFailedError(Exception): def __init__(self, message="The operation did not complete successfully."): self.message = message super().__init__(self.message)
def get_video_codec(video_file): command_base = rf'ffprobe -v error -select_streams v:0 -show_entries stream=codec_name -of json "{video_file}"' command = shlex.split(command_base) try: process = subprocess.Popen( command, stdout=subprocess.PIPE, creationflags=subprocess.CREATE_NO_WINDOW if sys.platform == "win32" else 0, ) output, _ = process.communicate() codec_info = json.loads(output.decode('utf-8')) codec_name = codec_info['streams'][0]['codec_name'] return codec_name except Exception as error: logger.debug(str(error)) return None
def audio_preprocessor(preview, base_audio, audio_wav, use_cuda=False): base_audio = base_audio.strip() previous_files_to_remove = [audio_wav] remove_files(previous_files_to_remove)
if preview: logger.warning( "Creating a preview video of 10 seconds, to disable " "this option, go to advanced settings and turn off preview." ) wav_ = f'ffmpeg -y -i "{base_audio}" -ss 00:00:20 -t 00:00:10 -vn -acodec pcm_s16le -ar 44100 -ac 2 audio.wav' else: wav_ = f'ffmpeg -y -i "{base_audio}" -vn -acodec pcm_s16le -ar 44100 -ac 2 audio.wav'
# Run cmd process sub_params = { "stdout": subprocess.PIPE, "stderr": subprocess.PIPE, "creationflags": subprocess.CREATE_NO_WINDOW if sys.platform == "win32" else 0, } wav_ = shlex.split(wav_) result_convert_audio = subprocess.Popen(wav_, **sub_params) output, errors = result_convert_audio.communicate() time.sleep(1) if result_convert_audio.returncode in [1, 2] or not os.path.exists( audio_wav ): raise OperationFailedError(f"Error can't create the audio file:\n{errors.decode('utf-8')}")
def audio_video_preprocessor( preview, video, OutputFile, audio_wav, use_cuda=False): video = video.strip() previous_files_to_remove = [OutputFile, "audio.webm", audio_wav] remove_files(previous_files_to_remove)
if os.path.exists(video): if preview: logger.warning( "Creating a preview video of 10 seconds, " "to disable this option, go to advanced " "settings and turn off preview." ) mp4_ = f'ffmpeg -y -i "{video}" -ss 00:00:20 -t 00:00:10 -c:v libx264 -c:a aac -strict experimental Video.mp4' else: video_codec = get_video_codec(video) if not video_codec: logger.debug("No video codec found in video") else: logger.info(f"Video codec: {video_codec}")
# Check if the file ends with ".mp4" extension or is valid codec if video.endswith(".mp4") or video_codec in TESTED_CODECS: destination_path = os.path.join(os.getcwd(), "Video.mp4") shutil.copy(video, destination_path) time.sleep(0.5) if os.path.exists(OutputFile): mp4_ = "ffmpeg -h" else: mp4_ = f'ffmpeg -y -i "{video}" -c copy Video.mp4' else: logger.warning( "File does not have the '.mp4' extension or a " "supported codec. Converting video to mp4 (codec: h264)." ) mp4_ = f'ffmpeg -y -i "{video}" -c:v libx264 -c:a aac -strict experimental Video.mp4' else: if preview: logger.warning( "Creating a preview from the link, 10 seconds " "to disable this option, go to advanced " "settings and turn off preview." ) # https://github.com/yt-dlp/yt-dlp/issues/2220 mp4_ = f'yt-dlp -f "mp4" --downloader ffmpeg --downloader-args "ffmpeg_i: -ss 00:00:20 -t 00:00:10" --force-overwrites --max-downloads 1 --no-warnings --no-playlist --no-abort-on-error --ignore-no-formats-error --restrict-filenames -o {OutputFile} {video}' wav_ = "ffmpeg -y -i Video.mp4 -vn -acodec pcm_s16le -ar 44100 -ac 2 audio.wav" else: mp4_ = f'yt-dlp -f "mp4" --force-overwrites --max-downloads 1 --no-warnings --no-playlist --no-abort-on-error --ignore-no-formats-error --restrict-filenames -o {OutputFile} {video}' wav_ = f"python -m yt_dlp --output {audio_wav} --force-overwrites --max-downloads 1 --no-warnings --no-playlist --no-abort-on-error --ignore-no-formats-error --extract-audio --audio-format wav {video}"
# Run cmd process mp4_ = shlex.split(mp4_) sub_params = { "stdout": subprocess.PIPE, "stderr": subprocess.PIPE, "creationflags": subprocess.CREATE_NO_WINDOW if sys.platform == "win32" else 0, }
if os.path.exists(video): logger.info("Process video...") result_convert_video = subprocess.Popen(mp4_, **sub_params) # result_convert_video.wait() output, errors = result_convert_video.communicate() time.sleep(1) if result_convert_video.returncode in [1, 2] or not os.path.exists( OutputFile ): raise OperationFailedError(f"Error processing video:\n{errors.decode('utf-8')}") logger.info("Process audio...") wav_ = "ffmpeg -y -i Video.mp4 -vn -acodec pcm_s16le -ar 44100 -ac 2 audio.wav" wav_ = shlex.split(wav_) result_convert_audio = subprocess.Popen(wav_, **sub_params) output, errors = result_convert_audio.communicate() time.sleep(1) if result_convert_audio.returncode in [1, 2] or not os.path.exists( audio_wav ): raise OperationFailedError(f"Error can't create the audio file:\n{errors.decode('utf-8')}")
else: wav_ = shlex.split(wav_) if preview: result_convert_video = subprocess.Popen(mp4_, **sub_params) output, errors = result_convert_video.communicate() time.sleep(0.5) result_convert_audio = subprocess.Popen(wav_, **sub_params) output, errors = result_convert_audio.communicate() time.sleep(0.5) if result_convert_audio.returncode in [1, 2] or not os.path.exists( audio_wav ): raise OperationFailedError( f"Error can't create the preview file:\n{errors.decode('utf-8')}" ) else: logger.info("Process audio...") result_convert_audio = subprocess.Popen(wav_, **sub_params) output, errors = result_convert_audio.communicate() time.sleep(1) if result_convert_audio.returncode in [1, 2] or not os.path.exists( audio_wav ): raise OperationFailedError(f"Error can't download the audio:\n{errors.decode('utf-8')}") logger.info("Process video...") result_convert_video = subprocess.Popen(mp4_, **sub_params) output, errors = result_convert_video.communicate() time.sleep(1) if result_convert_video.returncode in [1, 2] or not os.path.exists( OutputFile ): raise OperationFailedError(f"Error can't download the video:\n{errors.decode('utf-8')}")
def old_audio_video_preprocessor(preview, video, OutputFile, audio_wav): previous_files_to_remove = [OutputFile, "audio.webm", audio_wav] remove_files(previous_files_to_remove)
if os.path.exists(video): if preview: logger.warning( "Creating a preview video of 10 seconds, " "to disable this option, go to advanced " "settings and turn off preview." ) command = f'ffmpeg -y -i "{video}" -ss 00:00:20 -t 00:00:10 -c:v libx264 -c:a aac -strict experimental Video.mp4' result_convert_video = subprocess.run( command, capture_output=True, text=True, shell=True ) else: # Check if the file ends with ".mp4" extension if video.endswith(".mp4"): destination_path = os.path.join(os.getcwd(), "Video.mp4") shutil.copy(video, destination_path) result_convert_video = {} result_convert_video = subprocess.run( "echo Video copied", capture_output=True, text=True, shell=True, ) else: logger.warning( "File does not have the '.mp4' extension. Converting video." ) command = f'ffmpeg -y -i "{video}" -c:v libx264 -c:a aac -strict experimental Video.mp4' result_convert_video = subprocess.run( command, capture_output=True, text=True, shell=True )
if result_convert_video.returncode in [1, 2]: raise OperationFailedError("Error can't convert the video")
for i in range(120): time.sleep(1) logger.info("Process video...") if os.path.exists(OutputFile): time.sleep(1) command = "ffmpeg -y -i Video.mp4 -vn -acodec pcm_s16le -ar 44100 -ac 2 audio.wav" result_convert_audio = subprocess.run( command, capture_output=True, text=True, shell=True ) time.sleep(1) break if i == 119: # if not os.path.exists(OutputFile): raise OperationFailedError("Error processing video")
if result_convert_audio.returncode in [1, 2]: raise OperationFailedError( f"Error can't create the audio file: {result_convert_audio.stderr}" )
for i in range(120): time.sleep(1) logger.info("Process audio...") if os.path.exists(audio_wav): break if i == 119: raise OperationFailedError("Error can't create the audio file")
else: video = video.strip() if preview: logger.warning( "Creating a preview from the link, 10 " "seconds to disable this option, go to " "advanced settings and turn off preview." ) # https://github.com/yt-dlp/yt-dlp/issues/2220 mp4_ = f'yt-dlp -f "mp4" --downloader ffmpeg --downloader-args "ffmpeg_i: -ss 00:00:20 -t 00:00:10" --force-overwrites --max-downloads 1 --no-warnings --no-abort-on-error --ignore-no-formats-error --restrict-filenames -o {OutputFile} {video}' wav_ = "ffmpeg -y -i Video.mp4 -vn -acodec pcm_s16le -ar 44100 -ac 2 audio.wav" result_convert_video = subprocess.run( mp4_, capture_output=True, text=True, shell=True ) result_convert_audio = subprocess.run( wav_, capture_output=True, text=True, shell=True ) if result_convert_audio.returncode in [1, 2]: raise OperationFailedError("Error can't download a preview") else: mp4_ = f'yt-dlp -f "mp4" --force-overwrites --max-downloads 1 --no-warnings --no-abort-on-error --ignore-no-formats-error --restrict-filenames -o {OutputFile} {video}' wav_ = f"python -m yt_dlp --output {audio_wav} --force-overwrites --max-downloads 1 --no-warnings --no-abort-on-error --ignore-no-formats-error --extract-audio --audio-format wav {video}"
result_convert_audio = subprocess.run( wav_, capture_output=True, text=True, shell=True )
if result_convert_audio.returncode in [1, 2]: raise OperationFailedError("Error can't download the audio")
for i in range(120): time.sleep(1) logger.info("Process audio...") if os.path.exists(audio_wav) and not os.path.exists( "audio.webm" ): time.sleep(1) result_convert_video = subprocess.run( mp4_, capture_output=True, text=True, shell=True ) break if i == 119: raise OperationFailedError("Error downloading the audio")
if result_convert_video.returncode in [1, 2]: raise OperationFailedError("Error can't download the video")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499from whisperx.alignment import ( DEFAULT_ALIGN_MODELS_TORCH as DAMT, DEFAULT_ALIGN_MODELS_HF as DAMHF,)from whisperx.utils import TO_LANGUAGE_CODEimport whisperximport torchimport gcimport osimport soundfile as sffrom IPython.utils import capture # noqafrom .language_configuration import EXTRA_ALIGN, INVERTED_LANGUAGESfrom .logging_setup import loggerfrom .postprocessor import sanitize_file_namefrom .utils import remove_directory_contents, run_command
# ZERO GPU CONFIGimport spacesimport copyimport randomimport time
def random_sleep(): if os.environ.get("ZERO_GPU") == "TRUE": print("Random sleep") sleep_time = round(random.uniform(7.2, 9.9), 1) time.sleep(sleep_time)
@spaces.GPU(duration=120)def load_and_transcribe_audio(asr_model, audio, compute_type, language, asr_options, batch_size, segment_duration_limit): # Load model model = whisperx.load_model( asr_model, os.environ.get("SONITR_DEVICE") if os.environ.get("ZERO_GPU") != "TRUE" else "cuda", compute_type=compute_type, language=language, asr_options=asr_options, )
# Transcribe audio result = model.transcribe( audio, batch_size=batch_size, chunk_size=segment_duration_limit, print_progress=True, )
del model gc.collect() torch.cuda.empty_cache() # noqa return result
def load_align_and_align_segments(result, audio, DAMHF):
# Load alignment model model_a, metadata = whisperx.load_align_model( language_code=result["language"], device=os.environ.get("SONITR_DEVICE") if os.environ.get("ZERO_GPU") != "TRUE" else "cuda", model_name=None if result["language"] in DAMHF.keys() else EXTRA_ALIGN[result["language"]], )
# Align segments alignment_result = whisperx.align( result["segments"], model_a, metadata, audio, os.environ.get("SONITR_DEVICE") if os.environ.get("ZERO_GPU") != "TRUE" else "cuda", return_char_alignments=True, print_progress=False, )
# Clean up del model_a gc.collect() torch.cuda.empty_cache() # noqa
return alignment_result
@spaces.GPU(duration=120)def diarize_audio(diarize_model, audio_wav, min_speakers, max_speakers):
if os.environ.get("ZERO_GPU") == "TRUE": diarize_model.model.to(torch.device("cuda")) diarize_segments = diarize_model( audio_wav, min_speakers=min_speakers, max_speakers=max_speakers ) return diarize_segments
# ZERO GPU CONFIG
ASR_MODEL_OPTIONS = [ "tiny", "base", "small", "medium", "large", "large-v1", "large-v2", "large-v3", "distil-large-v2", "Systran/faster-distil-whisper-large-v3", "tiny.en", "base.en", "small.en", "medium.en", "distil-small.en", "distil-medium.en", "OpenAI_API_Whisper",]
COMPUTE_TYPE_GPU = [ "default", "auto", "int8", "int8_float32", "int8_float16", "int8_bfloat16", "float16", "bfloat16", "float32"]
COMPUTE_TYPE_CPU = [ "default", "auto", "int8", "int8_float32", "int16", "float32",]
WHISPER_MODELS_PATH = './WHISPER_MODELS'
def openai_api_whisper( input_audio_file, source_lang=None, chunk_duration=1800):
info = sf.info(input_audio_file) duration = info.duration
output_directory = "./whisper_api_audio_parts" os.makedirs(output_directory, exist_ok=True) remove_directory_contents(output_directory)
if duration > chunk_duration: # Split the audio file into smaller chunks with 30-minute duration cm = f'ffmpeg -i "{input_audio_file}" -f segment -segment_time {chunk_duration} -c:a libvorbis "{output_directory}/output%03d.ogg"' run_command(cm) # Get list of generated chunk files chunk_files = sorted( [f"{output_directory}/{f}" for f in os.listdir(output_directory) if f.endswith('.ogg')] ) else: one_file = f"{output_directory}/output000.ogg" cm = f'ffmpeg -i "{input_audio_file}" -c:a libvorbis {one_file}' run_command(cm) chunk_files = [one_file]
# Transcript segments = [] language = source_lang if source_lang else None for i, chunk in enumerate(chunk_files): from openai import OpenAI client = OpenAI()
audio_file = open(chunk, "rb") transcription = client.audio.transcriptions.create( model="whisper-1", file=audio_file, language=language, response_format="verbose_json", timestamp_granularities=["segment"], )
try: transcript_dict = transcription.model_dump() except: # noqa transcript_dict = transcription.to_dict()
if language is None: logger.info(f'Language detected: {transcript_dict["language"]}') language = TO_LANGUAGE_CODE[transcript_dict["language"]]
chunk_time = chunk_duration * (i)
for seg in transcript_dict["segments"]:
if "start" in seg.keys(): segments.append( { "text": seg["text"], "start": seg["start"] + chunk_time, "end": seg["end"] + chunk_time, } )
audio = whisperx.load_audio(input_audio_file) result = {"segments": segments, "language": language}
return audio, result
def find_whisper_models(): path = WHISPER_MODELS_PATH folders = []
if os.path.exists(path): for folder in os.listdir(path): folder_path = os.path.join(path, folder) if ( os.path.isdir(folder_path) and 'model.bin' in os.listdir(folder_path) ): folders.append(folder) return folders
def transcribe_speech( audio_wav, asr_model, compute_type, batch_size, SOURCE_LANGUAGE, literalize_numbers=True, segment_duration_limit=15,): """ Transcribe speech using a whisper model.
Parameters: - audio_wav (str): Path to the audio file in WAV format. - asr_model (str): The whisper model to be loaded. - compute_type (str): Type of compute to be used (e.g., 'int8', 'float16'). - batch_size (int): Batch size for transcription. - SOURCE_LANGUAGE (str): Source language for transcription.
Returns: - Tuple containing: - audio: Loaded audio file. - result: Transcription result as a dictionary. """
if asr_model == "OpenAI_API_Whisper": if literalize_numbers: logger.info( "OpenAI's API Whisper does not support " "the literalization of numbers." ) return openai_api_whisper(audio_wav, SOURCE_LANGUAGE)
# https://github.com/openai/whisper/discussions/277 prompt = "以下是普通话的句子。" if SOURCE_LANGUAGE == "zh" else None SOURCE_LANGUAGE = ( SOURCE_LANGUAGE if SOURCE_LANGUAGE != "zh-TW" else "zh" ) asr_options = { "initial_prompt": prompt, "suppress_numerals": literalize_numbers }
if asr_model not in ASR_MODEL_OPTIONS:
base_dir = WHISPER_MODELS_PATH if not os.path.exists(base_dir): os.makedirs(base_dir) model_dir = os.path.join(base_dir, sanitize_file_name(asr_model))
if not os.path.exists(model_dir): from ctranslate2.converters import TransformersConverter
quantization = "float32" # Download new model try: converter = TransformersConverter( asr_model, low_cpu_mem_usage=True, copy_files=[ "tokenizer_config.json", "preprocessor_config.json" ] ) converter.convert( model_dir, quantization=quantization, force=False ) except Exception as error: if "File tokenizer_config.json does not exist" in str(error): converter._copy_files = [ "tokenizer.json", "preprocessor_config.json" ] converter.convert( model_dir, quantization=quantization, force=True ) else: raise error
asr_model = model_dir logger.info(f"ASR Model: {str(model_dir)}")
audio = whisperx.load_audio(audio_wav) result = load_and_transcribe_audio( asr_model, audio, compute_type, SOURCE_LANGUAGE, asr_options, batch_size, segment_duration_limit )
if result["language"] == "zh" and not prompt: result["language"] = "zh-TW" logger.info("Chinese - Traditional (zh-TW)")
return audio, result
def align_speech(audio, result): """ Aligns speech segments based on the provided audio and result metadata.
Parameters: - audio (array): The audio data in a suitable format for alignment. - result (dict): Metadata containing information about the segments and language.
Returns: - result (dict): Updated metadata after aligning the segments with the audio. This includes character-level alignments if 'return_char_alignments' is set to True.
Notes: - This function uses language-specific models to align speech segments. - It performs language compatibility checks and selects the appropriate alignment model. - Cleans up memory by releasing resources after alignment. """ DAMHF.update(DAMT) # lang align if ( not result["language"] in DAMHF.keys() and not result["language"] in EXTRA_ALIGN.keys() ): logger.warning( "Automatic detection: Source language not compatible with align" ) raise ValueError( f"Detected language {result['language']} incompatible, " "you can select the source language to avoid this error." ) if ( result["language"] in EXTRA_ALIGN.keys() and EXTRA_ALIGN[result["language"]] == "" ): lang_name = ( INVERTED_LANGUAGES[result["language"]] if result["language"] in INVERTED_LANGUAGES.keys() else result["language"] ) logger.warning( "No compatible wav2vec2 model found " f"for the language '{lang_name}', skipping alignment." ) return result
random_sleep() result = load_align_and_align_segments(result, audio, DAMHF)
return result
diarization_models = { "pyannote_3.1": "pyannote/speaker-diarization-3.1", "pyannote_2.1": "pyannote/speaker-diarization@2.1", "disable": "",}
def reencode_speakers(result):
if result["segments"][0]["speaker"] == "SPEAKER_00": return result
speaker_mapping = {} counter = 0
logger.debug("Reencode speakers")
for segment in result["segments"]: old_speaker = segment["speaker"] if old_speaker not in speaker_mapping: speaker_mapping[old_speaker] = f"SPEAKER_{counter:02d}" counter += 1 segment["speaker"] = speaker_mapping[old_speaker]
return result
def diarize_speech( audio_wav, result, min_speakers, max_speakers, YOUR_HF_TOKEN, model_name="pyannote/speaker-diarization@2.1",): """ Performs speaker diarization on speech segments.
Parameters: - audio_wav (array): Audio data in WAV format to perform speaker diarization. - result (dict): Metadata containing information about speech segments and alignments. - min_speakers (int): Minimum number of speakers expected in the audio. - max_speakers (int): Maximum number of speakers expected in the audio. - YOUR_HF_TOKEN (str): Your Hugging Face API token for model authentication. - model_name (str): Name of the speaker diarization model to be used (default: "pyannote/speaker-diarization@2.1").
Returns: - result_diarize (dict): Updated metadata after assigning speaker labels to segments.
Notes: - This function utilizes a speaker diarization model to label speaker segments in the audio. - It assigns speakers to word-level segments based on diarization results. - Cleans up memory by releasing resources after diarization. - If only one speaker is specified, each segment is automatically assigned as the first speaker, eliminating the need for diarization inference. """
if max(min_speakers, max_speakers) > 1 and model_name: try:
diarize_model = whisperx.DiarizationPipeline( model_name=model_name, use_auth_token=YOUR_HF_TOKEN, device=os.environ.get("SONITR_DEVICE"), )
except Exception as error: error_str = str(error) gc.collect() torch.cuda.empty_cache() # noqa if "'NoneType' object has no attribute 'to'" in error_str: if model_name == diarization_models["pyannote_2.1"]: raise ValueError( "Accept the license agreement for using Pyannote 2.1." " You need to have an account on Hugging Face and " "accept the license to use the models: " "https://huggingface.co/pyannote/speaker-diarization " "and https://huggingface.co/pyannote/segmentation " "Get your KEY TOKEN here: " "https://hf.co/settings/tokens " ) elif model_name == diarization_models["pyannote_3.1"]: raise ValueError( "New Licence Pyannote 3.1: You need to have an account" " on Hugging Face and accept the license to use the " "models: https://huggingface.co/pyannote/speaker-diarization-3.1 " # noqa "and https://huggingface.co/pyannote/segmentation-3.0 " ) else: raise error
random_sleep() diarize_segments = diarize_audio(diarize_model, audio_wav, min_speakers, max_speakers)
result_diarize = whisperx.assign_word_speakers( diarize_segments, result )
for segment in result_diarize["segments"]: if "speaker" not in segment: segment["speaker"] = "SPEAKER_00" logger.warning( f"No speaker detected in {segment['start']}. First TTS " f"will be used for the segment text: {segment['text']} " )
del diarize_model gc.collect() torch.cuda.empty_cache() # noqa else: result_diarize = result result_diarize["segments"] = [ {**item, "speaker": "SPEAKER_00"} for item in result_diarize["segments"] ] return reencode_speakers(result_diarize)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987from .logging_setup import loggerfrom whisperx.utils import get_writerfrom .utils import remove_files, run_command, remove_directory_contentsfrom typing import Listimport srtimport reimport osimport copyimport stringimport soundfile as sffrom PIL import Image, ImageOps, ImageDraw, ImageFont
punctuation_list = list( string.punctuation + "¡¿«»„”“”‚‘’「」『』《》()【】〈〉〔〕〖〗〘〙〚〛⸤⸥⸨⸩")symbol_list = punctuation_list + ["", "..", "..."]
def extract_from_srt(file_path): with open(file_path, "r", encoding="utf-8") as file: srt_content = file.read()
subtitle_generator = srt.parse(srt_content) srt_content_list = list(subtitle_generator)
return srt_content_list
def clean_text(text):
# Remove content within square brackets text = re.sub(r'\[.*?\]', '', text) # Add pattern to remove content within <comment> tags text = re.sub(r'<comment>.*?</comment>', '', text) # Remove HTML tags text = re.sub(r'<.*?>', '', text) # Remove "♫" and "♪" content text = re.sub(r'♫.*?♫', '', text) text = re.sub(r'♪.*?♪', '', text) # Replace newline characters with an empty string text = text.replace("\n", ". ") # Remove double quotation marks text = text.replace('"', '') # Collapse multiple spaces and replace with a single space text = re.sub(r"\s+", " ", text) # Normalize spaces around periods text = re.sub(r"[\s\.]+(?=\s)", ". ", text) # Check if there are ♫ or ♪ symbols present if '♫' in text or '♪' in text: return ""
text = text.strip()
# Valid text return text if text not in symbol_list else ""
def srt_file_to_segments(file_path, speaker=False): try: srt_content_list = extract_from_srt(file_path) except Exception as error: logger.error(str(error)) fixed_file = "fixed_sub.srt" remove_files(fixed_file) fix_sub = f'ffmpeg -i "{file_path}" "{fixed_file}" -y' run_command(fix_sub) srt_content_list = extract_from_srt(fixed_file)
segments = [] for segment in srt_content_list:
text = clean_text(str(segment.content))
if text: segments.append( { "text": text, "start": float(segment.start.total_seconds()), "end": float(segment.end.total_seconds()), } )
if not segments: raise Exception("No data found in srt subtitle file")
if speaker: segments = [{**seg, "speaker": "SPEAKER_00"} for seg in segments]
return {"segments": segments}
# documents
def dehyphenate(lines: List[str], line_no: int) -> List[str]: next_line = lines[line_no + 1] word_suffix = next_line.split(" ")[0]
lines[line_no] = lines[line_no][:-1] + word_suffix lines[line_no + 1] = lines[line_no + 1][len(word_suffix):] return lines
def remove_hyphens(text: str) -> str: """
This fails for: * Natural dashes: well-known, self-replication, use-cases, non-semantic, Post-processing, Window-wise, viewpoint-dependent * Trailing math operands: 2 - 4 * Names: Lopez-Ferreras, VGG-19, CIFAR-100 """ lines = [line.rstrip() for line in text.split("\n")]
# Find dashes line_numbers = [] for line_no, line in enumerate(lines[:-1]): if line.endswith("-"): line_numbers.append(line_no)
# Replace for line_no in line_numbers: lines = dehyphenate(lines, line_no)
return "\n".join(lines)
def pdf_to_txt(pdf_file, start_page, end_page): from pypdf import PdfReader
with open(pdf_file, "rb") as file: reader = PdfReader(file) logger.debug(f"Total pages: {reader.get_num_pages()}") text = ""
start_page_idx = max((start_page-1), 0) end_page_inx = min((end_page), (reader.get_num_pages())) document_pages = reader.pages[start_page_idx:end_page_inx] logger.info( f"Selected pages from {start_page_idx} to {end_page_inx}: " f"{len(document_pages)}" )
for page in document_pages: text += remove_hyphens(page.extract_text()) return text
def docx_to_txt(docx_file): # https://github.com/AlJohri/docx2pdf update from docx import Document
doc = Document(docx_file) text = "" for paragraph in doc.paragraphs: text += paragraph.text + "\n" return text
def replace_multiple_elements(text, replacements): pattern = re.compile("|".join(map(re.escape, replacements.keys()))) replaced_text = pattern.sub( lambda match: replacements[match.group(0)], text )
# Remove multiple spaces replaced_text = re.sub(r"\s+", " ", replaced_text)
return replaced_text
def document_preprocessor(file_path, is_string, start_page, end_page): if not is_string: file_ext = os.path.splitext(file_path)[1].lower()
if is_string: text = file_path elif file_ext == ".pdf": text = pdf_to_txt(file_path, start_page, end_page) elif file_ext == ".docx": text = docx_to_txt(file_path) elif file_ext == ".txt": with open( file_path, "r", encoding='utf-8', errors='replace' ) as file: text = file.read() else: raise Exception("Unsupported file format")
# Add space to break segments more easily later replacements = { "、": "、 ", "。": "。 ", # "\n": " ", } text = replace_multiple_elements(text, replacements)
# Save text to a .txt file # file_name = os.path.splitext(os.path.basename(file_path))[0] txt_file_path = "./text_preprocessor.txt"
with open( txt_file_path, "w", encoding='utf-8', errors='replace' ) as txt_file: txt_file.write(text)
return txt_file_path, text
def split_text_into_chunks(text, chunk_size): words = re.findall(r"\b\w+\b", text) chunks = [] current_chunk = "" for word in words: if ( len(current_chunk) + len(word) + 1 <= chunk_size ): # Adding 1 for the space between words if current_chunk: current_chunk += " " current_chunk += word else: chunks.append(current_chunk) current_chunk = word if current_chunk: chunks.append(current_chunk) return chunks
def determine_chunk_size(file_name): patterns = { re.compile(r".*-(Male|Female)$"): 1024, # by character re.compile(r".* BARK$"): 100, # t 64 256 re.compile(r".* VITS$"): 500, re.compile( r".+\.(wav|mp3|ogg|m4a)$" ): 150, # t 250 400 api automatic split re.compile(r".* VITS-onnx$"): 250, # automatic sentence split re.compile(r".* OpenAI-TTS$"): 1024 # max charaters 4096 }
for pattern, chunk_size in patterns.items(): if pattern.match(file_name): return chunk_size
# Default chunk size if the file doesn't match any pattern; max 1800 return 100
def plain_text_to_segments(result_text=None, chunk_size=None): if not chunk_size: chunk_size = 100 text_chunks = split_text_into_chunks(result_text, chunk_size)
segments_chunks = [] for num, chunk in enumerate(text_chunks): chunk_dict = { "text": chunk, "start": (1.0 + num), "end": (2.0 + num), "speaker": "SPEAKER_00", } segments_chunks.append(chunk_dict)
result_diarize = {"segments": segments_chunks}
return result_diarize
def segments_to_plain_text(result_diarize): complete_text = "" for seg in result_diarize["segments"]: complete_text += seg["text"] + " " # issue
# Save text to a .txt file # file_name = os.path.splitext(os.path.basename(file_path))[0] txt_file_path = "./text_translation.txt"
with open( txt_file_path, "w", encoding='utf-8', errors='replace' ) as txt_file: txt_file.write(complete_text)
return txt_file_path, complete_text
# doc to video
COLORS = { "black": (0, 0, 0), "white": (255, 255, 255), "red": (255, 0, 0), "green": (0, 255, 0), "blue": (0, 0, 255), "yellow": (255, 255, 0), "light_gray": (200, 200, 200), "light_blue": (173, 216, 230), "light_green": (144, 238, 144), "light_yellow": (255, 255, 224), "light_pink": (255, 182, 193), "lavender": (230, 230, 250), "peach": (255, 218, 185), "light_cyan": (224, 255, 255), "light_salmon": (255, 160, 122), "light_green_yellow": (173, 255, 47),}
BORDER_COLORS = ["dynamic"] + list(COLORS.keys())
def calculate_average_color(img): # Resize the image to a small size for faster processing img_small = img.resize((50, 50)) # Calculate the average color average_color = img_small.convert("RGB").resize((1, 1)).getpixel((0, 0)) return average_color
def add_border_to_image( image_path, target_width, target_height, border_color=None):
img = Image.open(image_path)
# Calculate the width and height for the new image with borders original_width, original_height = img.size original_aspect_ratio = original_width / original_height target_aspect_ratio = target_width / target_height
# Resize the image to fit the target resolution retaining aspect ratio if original_aspect_ratio > target_aspect_ratio: # Image is wider, calculate new height new_height = int(target_width / original_aspect_ratio) resized_img = img.resize((target_width, new_height)) else: # Image is taller, calculate new width new_width = int(target_height * original_aspect_ratio) resized_img = img.resize((new_width, target_height))
# Calculate padding for borders padding = (0, 0, 0, 0) if resized_img.size[0] != target_width or resized_img.size[1] != target_height: if original_aspect_ratio > target_aspect_ratio: # Add borders vertically padding = (0, (target_height - resized_img.size[1]) // 2, 0, (target_height - resized_img.size[1]) // 2) else: # Add borders horizontally padding = ((target_width - resized_img.size[0]) // 2, 0, (target_width - resized_img.size[0]) // 2, 0)
# Add borders with specified color if not border_color or border_color == "dynamic": border_color = calculate_average_color(resized_img) else: border_color = COLORS.get(border_color, (0, 0, 0))
bordered_img = ImageOps.expand(resized_img, padding, fill=border_color)
bordered_img.save(image_path)
return image_path
def resize_and_position_subimage( subimage, max_width, max_height, subimage_position, main_width, main_height): subimage_width, subimage_height = subimage.size
# Resize subimage if it exceeds maximum dimensions if subimage_width > max_width or subimage_height > max_height: # Calculate scaling factor width_scale = max_width / subimage_width height_scale = max_height / subimage_height scale = min(width_scale, height_scale)
# Resize subimage subimage = subimage.resize( (int(subimage_width * scale), int(subimage_height * scale)) )
# Calculate position to place the subimage if subimage_position == "top-left": subimage_x = 0 subimage_y = 0 elif subimage_position == "top-right": subimage_x = main_width - subimage.width subimage_y = 0 elif subimage_position == "bottom-left": subimage_x = 0 subimage_y = main_height - subimage.height elif subimage_position == "bottom-right": subimage_x = main_width - subimage.width subimage_y = main_height - subimage.height else: raise ValueError( "Invalid subimage_position. Choose from 'top-left', 'top-right'," " 'bottom-left', or 'bottom-right'." )
return subimage, subimage_x, subimage_y
def create_image_with_text_and_subimages( text, subimages, width, height, text_color, background_color, output_file): # Create an image with the specified resolution and background color image = Image.new('RGB', (width, height), color=background_color)
# Initialize ImageDraw object draw = ImageDraw.Draw(image)
# Load a font font = ImageFont.load_default() # You can specify your font file here
# Calculate text size and position text_bbox = draw.textbbox((0, 0), text, font=font) text_width = text_bbox[2] - text_bbox[0] text_height = text_bbox[3] - text_bbox[1] text_x = (width - text_width) / 2 text_y = (height - text_height) / 2
# Draw text on the image draw.text((text_x, text_y), text, fill=text_color, font=font)
# Paste subimages onto the main image for subimage_path, subimage_position in subimages: # Open the subimage subimage = Image.open(subimage_path)
# Convert subimage to RGBA mode if it doesn't have an alpha channel if subimage.mode != 'RGBA': subimage = subimage.convert('RGBA')
# Resize and position the subimage subimage, subimage_x, subimage_y = resize_and_position_subimage( subimage, width / 4, height / 4, subimage_position, width, height )
# Paste the subimage onto the main image image.paste(subimage, (int(subimage_x), int(subimage_y)), subimage)
image.save(output_file)
return output_file
def doc_to_txtximg_pages( document, width, height, start_page, end_page, bcolor): from pypdf import PdfReader
images_folder = "pdf_images/" os.makedirs(images_folder, exist_ok=True) remove_directory_contents(images_folder)
# First image text_image = os.path.basename(document)[:-4] subimages = [("./assets/logo.jpeg", "top-left")] text_color = (255, 255, 255) if bcolor == "black" else (0, 0, 0) # w|b background_color = COLORS.get(bcolor, (255, 255, 255)) # dynamic white first_image = "pdf_images/0000_00_aaa.png"
create_image_with_text_and_subimages( text_image, subimages, width, height, text_color, background_color, first_image )
reader = PdfReader(document) logger.debug(f"Total pages: {reader.get_num_pages()}")
start_page_idx = max((start_page-1), 0) end_page_inx = min((end_page), (reader.get_num_pages())) document_pages = reader.pages[start_page_idx:end_page_inx]
logger.info( f"Selected pages from {start_page_idx} to {end_page_inx}: " f"{len(document_pages)}" )
data_doc = {} for i, page in enumerate(document_pages):
count = 0 images = [] for image_file_object in page.images: img_name = f"{images_folder}{i:04d}_{count:02d}_{image_file_object.name}" images.append(img_name) with open(img_name, "wb") as fp: fp.write(image_file_object.data) count += 1 img_name = add_border_to_image(img_name, width, height, bcolor)
data_doc[i] = { "text": remove_hyphens(page.extract_text()), "images": images }
return data_doc
def page_data_to_segments(result_text=None, chunk_size=None):
if not chunk_size: chunk_size = 100
segments_chunks = [] time_global = 0 for page, result_data in result_text.items(): # result_image = result_data["images"] result_text = result_data["text"] text_chunks = split_text_into_chunks(result_text, chunk_size) if not text_chunks: text_chunks = [" "]
for chunk in text_chunks: chunk_dict = { "text": chunk, "start": (1.0 + time_global), "end": (2.0 + time_global), "speaker": "SPEAKER_00", "page": page, } segments_chunks.append(chunk_dict) time_global += 1
result_diarize = {"segments": segments_chunks}
return result_diarize
def update_page_data(result_diarize, doc_data): complete_text = "" current_page = result_diarize["segments"][0]["page"] text_page = ""
for seg in result_diarize["segments"]: text = seg["text"] + " " # issue complete_text += text
page = seg["page"]
if page == current_page: text_page += text else: doc_data[current_page]["text"] = text_page
# Next text_page = text current_page = page
if doc_data[current_page]["text"] != text_page: doc_data[current_page]["text"] = text_page
return doc_data
def fix_timestamps_docs(result_diarize, audio_files): current_start = 0.0
for seg, audio in zip(result_diarize["segments"], audio_files): duration = round(sf.info(audio).duration, 2)
seg["start"] = current_start current_start += duration seg["end"] = current_start
return result_diarize
def create_video_from_images( doc_data, result_diarize):
# First image path first_image = "pdf_images/0000_00_aaa.png"
# Time segments and images max_pages_idx = len(doc_data) - 1 current_page = result_diarize["segments"][0]["page"] duration_page = 0.0 last_image = None
for seg in result_diarize["segments"]: start = seg["start"] end = seg["end"] duration_seg = end - start
page = seg["page"]
if page == current_page: duration_page += duration_seg else:
images = doc_data[current_page]["images"]
if first_image: images = [first_image] + images first_image = None if not doc_data[min(max_pages_idx, (current_page+1))]["text"].strip(): images = images + doc_data[min(max_pages_idx, (current_page+1))]["images"] if not images and last_image: images = [last_image]
# Calculate images duration time_duration_per_image = round((duration_page / len(images)), 2) doc_data[current_page]["time_per_image"] = time_duration_per_image
# Next values doc_data[current_page]["images"] = images last_image = images[-1] duration_page = duration_seg current_page = page
if "time_per_image" not in doc_data[current_page].keys(): images = doc_data[current_page]["images"] if first_image: images = [first_image] + images if not images: images = [last_image] time_duration_per_image = round((duration_page / len(images)), 2) doc_data[current_page]["time_per_image"] = time_duration_per_image
# Timestamped image video. with open("list.txt", "w") as file:
for i, page in enumerate(doc_data.values()):
duration = page["time_per_image"] for img in page["images"]: if i == len(doc_data) - 1 and img == page["images"][-1]: # Check if it's the last item file.write(f"file {img}\n") file.write(f"outpoint {duration}") else: file.write(f"file {img}\n") file.write(f"outpoint {duration}\n")
out_video = "video_from_images.mp4" remove_files(out_video)
cm = f"ffmpeg -y -f concat -i list.txt -c:v libx264 -preset veryfast -crf 18 -pix_fmt yuv420p {out_video}" cm_alt = f"ffmpeg -f concat -i list.txt -c:v libx264 -r 30 -pix_fmt yuv420p -y {out_video}" try: run_command(cm) except Exception as error: logger.error(str(error)) remove_files(out_video) run_command(cm_alt)
return out_video
def merge_video_and_audio(video_doc, final_wav_file):
fixed_audio = "fixed_audio.mp3" remove_files(fixed_audio) cm = f"ffmpeg -i {final_wav_file} -c:a libmp3lame {fixed_audio}" run_command(cm)
vid_out = "video_book.mp4" remove_files(vid_out) cm = f"ffmpeg -i {video_doc} -i {fixed_audio} -c:v copy -c:a copy -map 0:v -map 1:a -shortest {vid_out}" run_command(cm)
return vid_out
# subtitles
def get_subtitle( language, segments_data, extension, filename=None, highlight_words=False,): if not filename: filename = "task_subtitle"
is_ass_extension = False if extension == "ass": is_ass_extension = True extension = "srt"
sub_file = filename + "." + extension support_name = filename + ".mp3" remove_files(sub_file)
writer = get_writer(extension, output_dir=".") word_options = { "highlight_words": highlight_words, "max_line_count": None, "max_line_width": None, }
# Get data subs subtitle_data = copy.deepcopy(segments_data) subtitle_data["language"] = ( "ja" if language in ["ja", "zh", "zh-TW"] else language )
# Clean if not highlight_words: subtitle_data.pop("word_segments", None) for segment in subtitle_data["segments"]: for key in ["speaker", "chars", "words"]: segment.pop(key, None)
writer( subtitle_data, support_name, word_options, )
if is_ass_extension: temp_name = filename + ".ass" remove_files(temp_name) convert_sub = f'ffmpeg -i "{sub_file}" "{temp_name}" -y' run_command(convert_sub) sub_file = temp_name
return sub_file
def process_subtitles( deep_copied_result, align_language, result_diarize, output_format_subtitle, TRANSLATE_AUDIO_TO,): name_ori = "sub_ori." name_tra = "sub_tra." remove_files( [name_ori + output_format_subtitle, name_tra + output_format_subtitle] )
writer = get_writer(output_format_subtitle, output_dir=".") word_options = { "highlight_words": False, "max_line_count": None, "max_line_width": None, }
# original lang subs_copy_result = copy.deepcopy(deep_copied_result) subs_copy_result["language"] = ( "zh" if align_language == "zh-TW" else align_language ) for segment in subs_copy_result["segments"]: segment.pop("speaker", None)
try: writer( subs_copy_result, name_ori[:-1] + ".mp3", word_options, ) except Exception as error: logger.error(str(error)) if str(error) == "list indices must be integers or slices, not str": logger.error( "Related to poor word segmentation" " in segments after alignment." ) subs_copy_result["segments"][0].pop("words") writer( subs_copy_result, name_ori[:-1] + ".mp3", word_options, )
# translated lang subs_tra_copy_result = copy.deepcopy(result_diarize) subs_tra_copy_result["language"] = ( "ja" if TRANSLATE_AUDIO_TO in ["ja", "zh", "zh-TW"] else align_language ) subs_tra_copy_result.pop("word_segments", None) for segment in subs_tra_copy_result["segments"]: for key in ["speaker", "chars", "words"]: segment.pop(key, None)
writer( subs_tra_copy_result, name_tra[:-1] + ".mp3", word_options, )
return name_tra + output_format_subtitle
def linguistic_level_segments( result_base, linguistic_unit="word", # word or char): linguistic_unit = linguistic_unit[:4] linguistic_unit_key = linguistic_unit + "s" result = copy.deepcopy(result_base)
if linguistic_unit_key not in result["segments"][0].keys(): raise ValueError("No alignment detected, can't process")
segments_by_unit = [] for segment in result["segments"]: segment_units = segment[linguistic_unit_key] # segment_speaker = segment.get("speaker", "SPEAKER_00")
for unit in segment_units:
text = unit[linguistic_unit]
if "start" in unit.keys(): segments_by_unit.append( { "start": unit["start"], "end": unit["end"], "text": text, # "speaker": segment_speaker, } ) elif not segments_by_unit: pass else: segments_by_unit[-1]["text"] += text
return {"segments": segments_by_unit}
def break_aling_segments( result: dict, break_characters: str = "", # ":|,|.|"): result_align = copy.deepcopy(result)
break_characters_list = break_characters.split("|") break_characters_list = [i for i in break_characters_list if i != '']
if not break_characters_list: logger.info("No valid break characters were specified.") return result
logger.info(f"Redivide text segments by: {str(break_characters_list)}")
# create new with filters normal = []
def process_chars(chars, letter_new_start, num, text): start_key, end_key = "start", "end" start_value = end_value = None
for char in chars: if start_key in char: start_value = char[start_key] break
for char in reversed(chars): if end_key in char: end_value = char[end_key] break
if not start_value or not end_value: raise Exception( f"Unable to obtain a valid timestamp for chars: {str(chars)}" )
return { "start": start_value, "end": end_value, "text": text, "words": chars, }
for i, segment in enumerate(result_align['segments']):
logger.debug(f"- Process segment: {i}, text: {segment['text']}") # start = segment['start'] letter_new_start = 0 for num, char in enumerate(segment['chars']):
if char["char"] is None: continue
# if "start" in char: # start = char["start"]
# if "end" in char: # end = char["end"]
# Break by character if char['char'] in break_characters_list:
text = segment['text'][letter_new_start:num+1]
logger.debug( f"Break in: {char['char']}, position: {num}, text: {text}" )
chars = segment['chars'][letter_new_start:num+1]
if not text: logger.debug("No text") continue
if num == 0 and not text.strip(): logger.debug("blank space in start") continue
if len(text) == 1: logger.debug(f"Short char append, num: {num}") normal[-1]["text"] += text normal[-1]["words"].append(chars) continue
# logger.debug(chars) normal_dict = process_chars(chars, letter_new_start, num, text)
letter_new_start = num+1
normal.append(normal_dict)
# If we reach the end of the segment, add the last part of chars. if num == len(segment["chars"]) - 1:
text = segment['text'][letter_new_start:num+1]
# If remain text len is not default len text if num not in [len(text)-1, len(text)] and text: logger.debug(f'Remaining text: {text}')
if not text: logger.debug("No remaining text.") continue
if len(text) == 1: logger.debug(f"Short char append, num: {num}") normal[-1]["text"] += text normal[-1]["words"].append(chars) continue
chars = segment['chars'][letter_new_start:num+1]
normal_dict = process_chars(chars, letter_new_start, num, text)
letter_new_start = num+1
normal.append(normal_dict)
# Rename char to word for item in normal: words_list = item['words'] for word_item in words_list: if 'char' in word_item: word_item['word'] = word_item.pop('char')
# Convert to dict default break_segments = {"segments": normal}
msg_count = ( f"Segment count before: {len(result['segments'])}, " f"after: {len(break_segments['segments'])}." ) logger.info(msg_count)
return break_segments12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574from gtts import gTTSimport edge_tts, asyncio, json, glob # noqafrom tqdm import tqdmimport librosa, os, re, torch, gc, subprocess # noqafrom .language_configuration import ( fix_code_language, BARK_VOICES_LIST, VITS_VOICES_LIST,)from .utils import ( download_manager, create_directories, copy_files, rename_file, remove_directory_contents, remove_files, run_command,)import numpy as npfrom typing import Any, Dictfrom pathlib import Pathimport soundfile as sfimport platformimport loggingimport tracebackfrom .logging_setup import logger
class TTS_OperationError(Exception): def __init__(self, message="The operation did not complete successfully."): self.message = message super().__init__(self.message)
def verify_saved_file_and_size(filename): if not os.path.exists(filename): raise TTS_OperationError(f"File '{filename}' was not saved.") if os.path.getsize(filename) == 0: raise TTS_OperationError( f"File '{filename}' has a zero size. " "Related to incorrect TTS for the target language" )
def error_handling_in_tts(error, segment, TRANSLATE_AUDIO_TO, filename): traceback.print_exc() logger.error(f"Error: {str(error)}") try: from tempfile import TemporaryFile
tts = gTTS(segment["text"], lang=fix_code_language(TRANSLATE_AUDIO_TO)) # tts.save(filename) f = TemporaryFile() tts.write_to_fp(f)
# Reset the file pointer to the beginning of the file f.seek(0)
# Read audio data from the TemporaryFile using soundfile audio_data, samplerate = sf.read(f) f.close() # Close the TemporaryFile sf.write( filename, audio_data, samplerate, format="ogg", subtype="vorbis" )
logger.warning( 'TTS auxiliary will be utilized ' f'rather than TTS: {segment["tts_name"]}' ) verify_saved_file_and_size(filename) except Exception as error: logger.critical(f"Error: {str(error)}") sample_rate_aux = 22050 duration = float(segment["end"]) - float(segment["start"]) data = np.zeros(int(sample_rate_aux * duration)).astype(np.float32) sf.write( filename, data, sample_rate_aux, format="ogg", subtype="vorbis" ) logger.error("Audio will be replaced -> [silent audio].") verify_saved_file_and_size(filename)
def pad_array(array, sr):
if isinstance(array, list): array = np.array(array)
if not array.shape[0]: raise ValueError("The generated audio does not contain any data")
valid_indices = np.where(np.abs(array) > 0.001)[0]
if len(valid_indices) == 0: logger.debug(f"No valid indices: {array}") return array
try: pad_indice = int(0.1 * sr) start_pad = max(0, valid_indices[0] - pad_indice) end_pad = min(len(array), valid_indices[-1] + 1 + pad_indice) padded_array = array[start_pad:end_pad] return padded_array except Exception as error: logger.error(str(error)) return array
# =====================================# EDGE TTS# =====================================
def edge_tts_voices_list(): try: completed_process = subprocess.run( ["edge-tts", "--list-voices"], capture_output=True, text=True ) lines = completed_process.stdout.strip().split("\n") except Exception as error: logger.debug(str(error)) lines = []
voices = [] for line in lines: if line.startswith("Name: "): voice_entry = {} voice_entry["Name"] = line.split(": ")[1] elif line.startswith("Gender: "): voice_entry["Gender"] = line.split(": ")[1] voices.append(voice_entry)
formatted_voices = [ f"{entry['Name']}-{entry['Gender']}" for entry in voices ]
if not formatted_voices: logger.warning( "The list of Edge TTS voices could not be obtained, " "switching to an alternative method" ) tts_voice_list = asyncio.new_event_loop().run_until_complete( edge_tts.list_voices() ) formatted_voices = sorted( [f"{v['ShortName']}-{v['Gender']}" for v in tts_voice_list] )
if not formatted_voices: logger.error("Can't get EDGE TTS - list voices")
return formatted_voices
def segments_egde_tts(filtered_edge_segments, TRANSLATE_AUDIO_TO, is_gui): for segment in tqdm(filtered_edge_segments["segments"]): speaker = segment["speaker"] # noqa text = segment["text"] start = segment["start"] tts_name = segment["tts_name"]
# make the tts audio filename = f"audio/{start}.ogg" temp_file = filename[:-3] + "mp3"
logger.info(f"{text} >> {filename}") try: if is_gui: asyncio.run( edge_tts.Communicate( text, "-".join(tts_name.split("-")[:-1]) ).save(temp_file) ) else: # nest_asyncio.apply() if not is_gui else None command = f'edge-tts -t "{text}" -v "{tts_name.replace("-Male", "").replace("-Female", "")}" --write-media "{temp_file}"' run_command(command) verify_saved_file_and_size(temp_file)
data, sample_rate = sf.read(temp_file) data = pad_array(data, sample_rate) # os.remove(temp_file)
# Save file sf.write( file=filename, samplerate=sample_rate, data=data, format="ogg", subtype="vorbis", ) verify_saved_file_and_size(filename)
except Exception as error: error_handling_in_tts(error, segment, TRANSLATE_AUDIO_TO, filename)
# =====================================# BARK TTS# =====================================
def segments_bark_tts( filtered_bark_segments, TRANSLATE_AUDIO_TO, model_id_bark="suno/bark-small"): from transformers import AutoProcessor, BarkModel from optimum.bettertransformer import BetterTransformer
device = os.environ.get("SONITR_DEVICE") torch_dtype_env = torch.float16 if device == "cuda" else torch.float32
# load model bark model = BarkModel.from_pretrained( model_id_bark, torch_dtype=torch_dtype_env ).to(device) model = model.to(device) processor = AutoProcessor.from_pretrained( model_id_bark, return_tensors="pt" ) # , padding=True if device == "cuda": # convert to bettertransformer model = BetterTransformer.transform(model, keep_original_model=False) # enable CPU offload # model.enable_cpu_offload() sampling_rate = model.generation_config.sample_rate
# filtered_segments = filtered_bark_segments['segments'] # Sorting the segments by 'tts_name' # sorted_segments = sorted(filtered_segments, key=lambda x: x['tts_name']) # logger.debug(sorted_segments)
for segment in tqdm(filtered_bark_segments["segments"]): speaker = segment["speaker"] # noqa text = segment["text"] start = segment["start"] tts_name = segment["tts_name"]
inputs = processor(text, voice_preset=BARK_VOICES_LIST[tts_name]).to( device )
# make the tts audio filename = f"audio/{start}.ogg" logger.info(f"{text} >> {filename}") try: # Infer with torch.inference_mode(): speech_output = model.generate( **inputs, do_sample=True, fine_temperature=0.4, coarse_temperature=0.8, pad_token_id=processor.tokenizer.pad_token_id, ) # Save file data_tts = pad_array( speech_output.cpu().numpy().squeeze().astype(np.float32), sampling_rate, ) sf.write( file=filename, samplerate=sampling_rate, data=data_tts, format="ogg", subtype="vorbis", ) verify_saved_file_and_size(filename) except Exception as error: error_handling_in_tts(error, segment, TRANSLATE_AUDIO_TO, filename) gc.collect() torch.cuda.empty_cache() try: del processor del model gc.collect() torch.cuda.empty_cache() except Exception as error: logger.error(str(error)) gc.collect() torch.cuda.empty_cache()
# =====================================# VITS TTS# =====================================
def uromanize(input_string): """Convert non-Roman strings to Roman using the `uroman` perl package.""" # script_path = os.path.join(uroman_path, "bin", "uroman.pl")
if not os.path.exists("./uroman"): logger.info( "Clonning repository uroman https://github.com/isi-nlp/uroman.git" " for romanize the text" ) process = subprocess.Popen( ["git", "clone", "https://github.com/isi-nlp/uroman.git"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) stdout, stderr = process.communicate() script_path = os.path.join("./uroman", "bin", "uroman.pl")
command = ["perl", script_path]
process = subprocess.Popen( command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) # Execute the perl command stdout, stderr = process.communicate(input=input_string.encode())
if process.returncode != 0: raise ValueError(f"Error {process.returncode}: {stderr.decode()}")
# Return the output as a string and skip the new-line character at the end return stdout.decode()[:-1]
def segments_vits_tts(filtered_vits_segments, TRANSLATE_AUDIO_TO): from transformers import VitsModel, AutoTokenizer
filtered_segments = filtered_vits_segments["segments"] # Sorting the segments by 'tts_name' sorted_segments = sorted(filtered_segments, key=lambda x: x["tts_name"]) logger.debug(sorted_segments)
model_name_key = None for segment in tqdm(sorted_segments): speaker = segment["speaker"] # noqa text = segment["text"] start = segment["start"] tts_name = segment["tts_name"]
if tts_name != model_name_key: model_name_key = tts_name model = VitsModel.from_pretrained(VITS_VOICES_LIST[tts_name]) tokenizer = AutoTokenizer.from_pretrained( VITS_VOICES_LIST[tts_name] ) sampling_rate = model.config.sampling_rate
if tokenizer.is_uroman: romanize_text = uromanize(text) logger.debug(f"Romanize text: {romanize_text}") inputs = tokenizer(romanize_text, return_tensors="pt") else: inputs = tokenizer(text, return_tensors="pt")
# make the tts audio filename = f"audio/{start}.ogg" logger.info(f"{text} >> {filename}") try: # Infer with torch.no_grad(): speech_output = model(**inputs).waveform
data_tts = pad_array( speech_output.cpu().numpy().squeeze().astype(np.float32), sampling_rate, ) # Save file sf.write( file=filename, samplerate=sampling_rate, data=data_tts, format="ogg", subtype="vorbis", ) verify_saved_file_and_size(filename) except Exception as error: error_handling_in_tts(error, segment, TRANSLATE_AUDIO_TO, filename) gc.collect() torch.cuda.empty_cache() try: del tokenizer del model gc.collect() torch.cuda.empty_cache() except Exception as error: logger.error(str(error)) gc.collect() torch.cuda.empty_cache()
# =====================================# Coqui XTTS# =====================================
def coqui_xtts_voices_list(): main_folder = "_XTTS_" pattern_coqui = re.compile(r".+\.(wav|mp3|ogg|m4a)$") pattern_automatic_speaker = re.compile(r"AUTOMATIC_SPEAKER_\d+\.wav$")
# List only files in the directory matching the pattern but not matching # AUTOMATIC_SPEAKER_00.wav, AUTOMATIC_SPEAKER_01.wav, etc. wav_voices = [ "_XTTS_/" + f for f in os.listdir(main_folder) if os.path.isfile(os.path.join(main_folder, f)) and pattern_coqui.match(f) and not pattern_automatic_speaker.match(f) ]
return ["_XTTS_/AUTOMATIC.wav"] + wav_voices
def seconds_to_hhmmss_ms(seconds): hours = seconds // 3600 minutes = (seconds % 3600) // 60 seconds = seconds % 60 milliseconds = int((seconds - int(seconds)) * 1000) return "%02d:%02d:%02d.%03d" % (hours, minutes, int(seconds), milliseconds)
def audio_trimming(audio_path, destination, start, end): if isinstance(start, (int, float)): start = seconds_to_hhmmss_ms(start) if isinstance(end, (int, float)): end = seconds_to_hhmmss_ms(end)
if destination: file_directory = destination else: file_directory = os.path.dirname(audio_path)
file_name = os.path.splitext(os.path.basename(audio_path))[0] file_ = f"{file_name}_trim.wav" # file_ = f'{os.path.splitext(audio_path)[0]}_trim.wav' output_path = os.path.join(file_directory, file_)
# -t (duration from -ss) | -to (time stop) | -af silenceremove=1:0:-50dB (remove silence) command = f'ffmpeg -y -loglevel error -i "{audio_path}" -ss {start} -to {end} -acodec pcm_s16le -f wav "{output_path}"' run_command(command)
return output_path
def convert_to_xtts_good_sample(audio_path: str = "", destination: str = ""): if destination: file_directory = destination else: file_directory = os.path.dirname(audio_path)
file_name = os.path.splitext(os.path.basename(audio_path))[0] file_ = f"{file_name}_good_sample.wav" # file_ = f'{os.path.splitext(audio_path)[0]}_good_sample.wav' mono_path = os.path.join(file_directory, file_) # get root
command = f'ffmpeg -y -loglevel error -i "{audio_path}" -ac 1 -ar 22050 -sample_fmt s16 -f wav "{mono_path}"' run_command(command)
return mono_path
def sanitize_file_name(file_name): import unicodedata
# Normalize the string to NFKD form to separate combined characters into # base characters and diacritics normalized_name = unicodedata.normalize("NFKD", file_name) # Replace any non-ASCII characters or special symbols with an underscore sanitized_name = re.sub(r"[^\w\s.-]", "_", normalized_name) return sanitized_name
def create_wav_file_vc( sample_name="", # name final file audio_wav="", # path start=None, # trim start end=None, # trim end output_final_path="_XTTS_", get_vocals_dereverb=True,): sample_name = sample_name if sample_name else "default_name" sample_name = sanitize_file_name(sample_name) audio_wav = audio_wav if isinstance(audio_wav, str) else audio_wav.name
BASE_DIR = ( "." # os.path.dirname(os.path.dirname(os.path.abspath(__file__))) )
output_dir = os.path.join(BASE_DIR, "clean_song_output") # remove content # remove_directory_contents(output_dir)
if start or end: # Cut file audio_segment = audio_trimming(audio_wav, output_dir, start, end) else: # Complete file audio_segment = audio_wav
from .mdx_net import process_uvr_task
try: _, _, _, _, audio_segment = process_uvr_task( orig_song_path=audio_segment, main_vocals=True, dereverb=get_vocals_dereverb, ) except Exception as error: logger.error(str(error))
sample = convert_to_xtts_good_sample(audio_segment)
sample_name = f"{sample_name}.wav" sample_rename = rename_file(sample, sample_name)
copy_files(sample_rename, output_final_path)
final_sample = os.path.join(output_final_path, sample_name) if os.path.exists(final_sample): logger.info(final_sample) return final_sample else: raise Exception(f"Error wav: {final_sample}")
def create_new_files_for_vc( speakers_coqui, segments_base, dereverb_automatic=True): # before function delete automatic delete_previous_automatic output_dir = os.path.join(".", "clean_song_output") # remove content remove_directory_contents(output_dir)
for speaker in speakers_coqui: filtered_speaker = [ segment for segment in segments_base if segment["speaker"] == speaker ] if len(filtered_speaker) > 4: filtered_speaker = filtered_speaker[1:] if filtered_speaker[0]["tts_name"] == "_XTTS_/AUTOMATIC.wav": name_automatic_wav = f"AUTOMATIC_{speaker}" if os.path.exists(f"_XTTS_/{name_automatic_wav}.wav"): logger.info(f"WAV automatic {speaker} exists") # path_wav = path_automatic_wav pass else: # create wav wav_ok = False for seg in filtered_speaker: duration = float(seg["end"]) - float(seg["start"]) if duration > 7.0 and duration < 12.0: logger.info( f'Processing segment: {seg["start"]}, {seg["end"]}, {seg["speaker"]}, {duration}, {seg["text"]}' ) create_wav_file_vc( sample_name=name_automatic_wav, audio_wav="audio.wav", start=(float(seg["start"]) + 1.0), end=(float(seg["end"]) - 1.0), get_vocals_dereverb=dereverb_automatic, ) wav_ok = True break
if not wav_ok: logger.info("Taking the first segment") seg = filtered_speaker[0] logger.info( f'Processing segment: {seg["start"]}, {seg["end"]}, {seg["speaker"]}, {seg["text"]}' ) max_duration = float(seg["end"]) - float(seg["start"]) max_duration = max(2.0, min(max_duration, 9.0))
create_wav_file_vc( sample_name=name_automatic_wav, audio_wav="audio.wav", start=(float(seg["start"])), end=(float(seg["start"]) + max_duration), get_vocals_dereverb=dereverb_automatic, )
def segments_coqui_tts( filtered_coqui_segments, TRANSLATE_AUDIO_TO, model_id_coqui="tts_models/multilingual/multi-dataset/xtts_v2", speakers_coqui=None, delete_previous_automatic=True, dereverb_automatic=True, emotion=None,): """XTTS Install: pip install -q TTS==0.21.1 pip install -q numpy==1.23.5
Notes: - tts_name is the wav|mp3|ogg|m4a file for VC """ from TTS.api import TTS
TRANSLATE_AUDIO_TO = fix_code_language(TRANSLATE_AUDIO_TO, syntax="coqui") supported_lang_coqui = [ "zh-cn", "en", "fr", "de", "it", "pt", "pl", "tr", "ru", "nl", "cs", "ar", "es", "hu", "ko", "ja", ] if TRANSLATE_AUDIO_TO not in supported_lang_coqui: raise TTS_OperationError( f"'{TRANSLATE_AUDIO_TO}' is not a supported language for Coqui XTTS" ) # Emotion and speed can only be used with Coqui Studio models. discontinued # emotions = ["Neutral", "Happy", "Sad", "Angry", "Dull"]
if delete_previous_automatic: for spk in speakers_coqui: remove_files(f"_XTTS_/AUTOMATIC_{spk}.wav")
directory_audios_vc = "_XTTS_" create_directories(directory_audios_vc) create_new_files_for_vc( speakers_coqui, filtered_coqui_segments["segments"], dereverb_automatic, )
# Init TTS device = os.environ.get("SONITR_DEVICE") model = TTS(model_id_coqui).to(device) sampling_rate = 24000
# filtered_segments = filtered_coqui_segments['segments'] # Sorting the segments by 'tts_name' # sorted_segments = sorted(filtered_segments, key=lambda x: x['tts_name']) # logger.debug(sorted_segments)
for segment in tqdm(filtered_coqui_segments["segments"]): speaker = segment["speaker"] text = segment["text"] start = segment["start"] tts_name = segment["tts_name"] if tts_name == "_XTTS_/AUTOMATIC.wav": tts_name = f"_XTTS_/AUTOMATIC_{speaker}.wav"
# make the tts audio filename = f"audio/{start}.ogg" logger.info(f"{text} >> {filename}") try: # Infer wav = model.tts( text=text, speaker_wav=tts_name, language=TRANSLATE_AUDIO_TO ) data_tts = pad_array( wav, sampling_rate, ) # Save file sf.write( file=filename, samplerate=sampling_rate, data=data_tts, format="ogg", subtype="vorbis", ) verify_saved_file_and_size(filename) except Exception as error: error_handling_in_tts(error, segment, TRANSLATE_AUDIO_TO, filename) gc.collect() torch.cuda.empty_cache() try: del model gc.collect() torch.cuda.empty_cache() except Exception as error: logger.error(str(error)) gc.collect() torch.cuda.empty_cache()
# =====================================# PIPER TTS# =====================================
def piper_tts_voices_list(): file_path = download_manager( url="https://huggingface.co/rhasspy/piper-voices/resolve/main/voices.json", path="./PIPER_MODELS", )
with open(file_path, "r", encoding="utf8") as file: data = json.load(file) piper_id_models = [key + " VITS-onnx" for key in data.keys()]
return piper_id_models
def replace_text_in_json(file_path, key_to_replace, new_text, condition=None): # Read the JSON file with open(file_path, "r", encoding="utf-8") as file: data = json.load(file)
# Modify the specified key's value with the new text if key_to_replace in data: if condition: value_condition = condition else: value_condition = data[key_to_replace]
if data[key_to_replace] == value_condition: data[key_to_replace] = new_text
# Write the modified content back to the JSON file with open(file_path, "w") as file: json.dump( data, file, indent=2 ) # Write the modified data back to the file with indentation for readability
def load_piper_model( model: str, data_dir: list, download_dir: str = "", update_voices: bool = False,): from piper import PiperVoice from piper.download import ensure_voice_exists, find_voice, get_voices
try: import onnxruntime as rt
if rt.get_device() == "GPU" and os.environ.get("SONITR_DEVICE") == "cuda": logger.debug("onnxruntime device > GPU") cuda = True else: logger.info( "onnxruntime device > CPU" ) # try pip install onnxruntime-gpu cuda = False except Exception as error: raise TTS_OperationError(f"onnxruntime error: {str(error)}")
# Disable CUDA in Windows if platform.system() == "Windows": logger.info("Employing CPU exclusivity with Piper TTS") cuda = False
if not download_dir: # Download to first data directory by default download_dir = data_dir[0] else: data_dir = [os.path.join(data_dir[0], download_dir)]
# Download voice if file doesn't exist model_path = Path(model) if not model_path.exists(): # Load voice info voices_info = get_voices(download_dir, update_voices=update_voices)
# Resolve aliases for backwards compatibility with old voice names aliases_info: Dict[str, Any] = {} for voice_info in voices_info.values(): for voice_alias in voice_info.get("aliases", []): aliases_info[voice_alias] = {"_is_alias": True, **voice_info}
voices_info.update(aliases_info) ensure_voice_exists(model, data_dir, download_dir, voices_info) model, config = find_voice(model, data_dir)
replace_text_in_json( config, "phoneme_type", "espeak", "PhonemeType.ESPEAK" )
# Load voice voice = PiperVoice.load(model, config_path=config, use_cuda=cuda)
return voice
def synthesize_text_to_audio_np_array(voice, text, synthesize_args): audio_stream = voice.synthesize_stream_raw(text, **synthesize_args)
# Collect the audio bytes into a single NumPy array audio_data = b"" for audio_bytes in audio_stream: audio_data += audio_bytes
# Ensure correct data type and convert audio bytes to NumPy array audio_np = np.frombuffer(audio_data, dtype=np.int16) return audio_np
def segments_vits_onnx_tts(filtered_onnx_vits_segments, TRANSLATE_AUDIO_TO): """ Install: pip install -q piper-tts==1.2.0 onnxruntime-gpu # for cuda118 """
data_dir = [ str(Path.cwd()) ] # "Data directory to check for downloaded models (default: current directory)" download_dir = "PIPER_MODELS" # model_name = "en_US-lessac-medium" tts_name in a dict like VITS update_voices = True # "Download latest voices.json during startup",
synthesize_args = { "speaker_id": None, "length_scale": 1.0, "noise_scale": 0.667, "noise_w": 0.8, "sentence_silence": 0.0, }
filtered_segments = filtered_onnx_vits_segments["segments"] # Sorting the segments by 'tts_name' sorted_segments = sorted(filtered_segments, key=lambda x: x["tts_name"]) logger.debug(sorted_segments)
model_name_key = None for segment in tqdm(sorted_segments): speaker = segment["speaker"] # noqa text = segment["text"] start = segment["start"] tts_name = segment["tts_name"].replace(" VITS-onnx", "")
if tts_name != model_name_key: model_name_key = tts_name model = load_piper_model( tts_name, data_dir, download_dir, update_voices ) sampling_rate = model.config.sample_rate
# make the tts audio filename = f"audio/{start}.ogg" logger.info(f"{text} >> {filename}") try: # Infer speech_output = synthesize_text_to_audio_np_array( model, text, synthesize_args ) data_tts = pad_array( speech_output, # .cpu().numpy().squeeze().astype(np.float32), sampling_rate, ) # Save file sf.write( file=filename, samplerate=sampling_rate, data=data_tts, format="ogg", subtype="vorbis", ) verify_saved_file_and_size(filename) except Exception as error: error_handling_in_tts(error, segment, TRANSLATE_AUDIO_TO, filename) gc.collect() torch.cuda.empty_cache() try: del model gc.collect() torch.cuda.empty_cache() except Exception as error: logger.error(str(error)) gc.collect() torch.cuda.empty_cache()
# =====================================# CLOSEAI TTS# =====================================
def segments_openai_tts( filtered_openai_tts_segments, TRANSLATE_AUDIO_TO): from openai import OpenAI
client = OpenAI() sampling_rate = 24000
# filtered_segments = filtered_openai_tts_segments['segments'] # Sorting the segments by 'tts_name' # sorted_segments = sorted(filtered_segments, key=lambda x: x['tts_name'])
for segment in tqdm(filtered_openai_tts_segments["segments"]): speaker = segment["speaker"] # noqa text = segment["text"].strip() start = segment["start"] tts_name = segment["tts_name"]
# make the tts audio filename = f"audio/{start}.ogg" logger.info(f"{text} >> {filename}")
try: # Request response = client.audio.speech.create( model="tts-1-hd" if "HD" in tts_name else "tts-1", voice=tts_name.split()[0][1:], response_format="wav", input=text )
audio_bytes = b'' for data in response.iter_bytes(chunk_size=4096): audio_bytes += data
speech_output = np.frombuffer(audio_bytes, dtype=np.int16)
# Save file data_tts = pad_array( speech_output[240:], sampling_rate, )
sf.write( file=filename, samplerate=sampling_rate, data=data_tts, format="ogg", subtype="vorbis", ) verify_saved_file_and_size(filename)
except Exception as error: error_handling_in_tts(error, segment, TRANSLATE_AUDIO_TO, filename)
# =====================================# Select task TTS# =====================================
def find_spkr(pattern, speaker_to_voice, segments): return [ speaker for speaker, voice in speaker_to_voice.items() if pattern.match(voice) and any( segment["speaker"] == speaker for segment in segments ) ]
def filter_by_speaker(speakers, segments): return { "segments": [ segment for segment in segments if segment["speaker"] in speakers ] }
def audio_segmentation_to_voice( result_diarize, TRANSLATE_AUDIO_TO, is_gui, tts_voice00, tts_voice01="", tts_voice02="", tts_voice03="", tts_voice04="", tts_voice05="", tts_voice06="", tts_voice07="", tts_voice08="", tts_voice09="", tts_voice10="", tts_voice11="", dereverb_automatic=True, model_id_bark="suno/bark-small", model_id_coqui="tts_models/multilingual/multi-dataset/xtts_v2", delete_previous_automatic=True,):
remove_directory_contents("audio")
# Mapping speakers to voice variables speaker_to_voice = { "SPEAKER_00": tts_voice00, "SPEAKER_01": tts_voice01, "SPEAKER_02": tts_voice02, "SPEAKER_03": tts_voice03, "SPEAKER_04": tts_voice04, "SPEAKER_05": tts_voice05, "SPEAKER_06": tts_voice06, "SPEAKER_07": tts_voice07, "SPEAKER_08": tts_voice08, "SPEAKER_09": tts_voice09, "SPEAKER_10": tts_voice10, "SPEAKER_11": tts_voice11, }
# Assign 'SPEAKER_00' to segments without a 'speaker' key for segment in result_diarize["segments"]: if "speaker" not in segment: segment["speaker"] = "SPEAKER_00" logger.warning( "NO SPEAKER DETECT IN SEGMENT: First TTS will be used in the" f" segment time {segment['start'], segment['text']}" ) # Assign the TTS name segment["tts_name"] = speaker_to_voice[segment["speaker"]]
# Find TTS method pattern_edge = re.compile(r".*-(Male|Female)$") pattern_bark = re.compile(r".* BARK$") pattern_vits = re.compile(r".* VITS$") pattern_coqui = re.compile(r".+\.(wav|mp3|ogg|m4a)$") pattern_vits_onnx = re.compile(r".* VITS-onnx$") pattern_openai_tts = re.compile(r".* OpenAI-TTS$")
all_segments = result_diarize["segments"]
speakers_edge = find_spkr(pattern_edge, speaker_to_voice, all_segments) speakers_bark = find_spkr(pattern_bark, speaker_to_voice, all_segments) speakers_vits = find_spkr(pattern_vits, speaker_to_voice, all_segments) speakers_coqui = find_spkr(pattern_coqui, speaker_to_voice, all_segments) speakers_vits_onnx = find_spkr( pattern_vits_onnx, speaker_to_voice, all_segments ) speakers_openai_tts = find_spkr( pattern_openai_tts, speaker_to_voice, all_segments )
# Filter method in segments filtered_edge = filter_by_speaker(speakers_edge, all_segments) filtered_bark = filter_by_speaker(speakers_bark, all_segments) filtered_vits = filter_by_speaker(speakers_vits, all_segments) filtered_coqui = filter_by_speaker(speakers_coqui, all_segments) filtered_vits_onnx = filter_by_speaker(speakers_vits_onnx, all_segments) filtered_openai_tts = filter_by_speaker(speakers_openai_tts, all_segments)
# Infer if filtered_edge["segments"]: logger.info(f"EDGE TTS: {speakers_edge}") segments_egde_tts(filtered_edge, TRANSLATE_AUDIO_TO, is_gui) # mp3 if filtered_bark["segments"]: logger.info(f"BARK TTS: {speakers_bark}") segments_bark_tts( filtered_bark, TRANSLATE_AUDIO_TO, model_id_bark ) # wav if filtered_vits["segments"]: logger.info(f"VITS TTS: {speakers_vits}") segments_vits_tts(filtered_vits, TRANSLATE_AUDIO_TO) # wav if filtered_coqui["segments"]: logger.info(f"Coqui TTS: {speakers_coqui}") segments_coqui_tts( filtered_coqui, TRANSLATE_AUDIO_TO, model_id_coqui, speakers_coqui, delete_previous_automatic, dereverb_automatic, ) # wav if filtered_vits_onnx["segments"]: logger.info(f"PIPER TTS: {speakers_vits_onnx}") segments_vits_onnx_tts(filtered_vits_onnx, TRANSLATE_AUDIO_TO) # wav if filtered_openai_tts["segments"]: logger.info(f"OpenAI TTS: {speakers_openai_tts}") segments_openai_tts(filtered_openai_tts, TRANSLATE_AUDIO_TO) # wav
[result.pop("tts_name", None) for result in result_diarize["segments"]] return [ speakers_edge, speakers_bark, speakers_vits, speakers_coqui, speakers_vits_onnx, speakers_openai_tts ]
def accelerate_segments( result_diarize, max_accelerate_audio, valid_speakers, acceleration_rate_regulation=False, folder_output="audio2",): logger.info("Apply acceleration")
( speakers_edge, speakers_bark, speakers_vits, speakers_coqui, speakers_vits_onnx, speakers_openai_tts ) = valid_speakers
create_directories(f"{folder_output}/audio/") remove_directory_contents(f"{folder_output}/audio/")
audio_files = [] speakers_list = []
max_count_segments_idx = len(result_diarize["segments"]) - 1
for i, segment in tqdm(enumerate(result_diarize["segments"])): text = segment["text"] # noqa start = segment["start"] end = segment["end"] speaker = segment["speaker"]
# find name audio # if speaker in speakers_edge: filename = f"audio/{start}.ogg" # elif speaker in speakers_bark + speakers_vits + speakers_coqui + speakers_vits_onnx: # filename = f"audio/{start}.wav" # wav
# duration duration_true = end - start duration_tts = librosa.get_duration(filename=filename)
# Accelerate percentage acc_percentage = duration_tts / duration_true
# Smoth if acceleration_rate_regulation and acc_percentage >= 1.3: try: next_segment = result_diarize["segments"][ min(max_count_segments_idx, i + 1) ] next_start = next_segment["start"] next_speaker = next_segment["speaker"] duration_with_next_start = next_start - start
if duration_with_next_start > duration_true: extra_time = duration_with_next_start - duration_true
if speaker == next_speaker: # half smoth_duration = duration_true + (extra_time * 0.5) else: # 7/10 smoth_duration = duration_true + (extra_time * 0.7) logger.debug( f"Base acc: {acc_percentage}, " f"smoth acc: {duration_tts / smoth_duration}" ) acc_percentage = max(1.2, (duration_tts / smoth_duration))
except Exception as error: logger.error(str(error))
if acc_percentage > max_accelerate_audio: acc_percentage = max_accelerate_audio elif acc_percentage <= 1.15 and acc_percentage >= 0.8: acc_percentage = 1.0 elif acc_percentage <= 0.79: acc_percentage = 0.8
# Round acc_percentage = round(acc_percentage + 0.0, 1)
# Format read if need if speaker in speakers_edge: info_enc = sf.info(filename).format else: info_enc = "OGG"
# Apply aceleration or opposite to the audio file in folder_output folder if acc_percentage == 1.0 and info_enc == "OGG": copy_files(filename, f"{folder_output}{os.sep}audio") else: os.system( f"ffmpeg -y -loglevel panic -i {filename} -filter:a atempo={acc_percentage} {folder_output}/{filename}" )
if logger.isEnabledFor(logging.DEBUG): duration_create = librosa.get_duration( filename=f"{folder_output}/{filename}" ) logger.debug( f"acc_percen is {acc_percentage}, tts duration " f"is {duration_tts}, new duration is {duration_create}" f", for {filename}" )
audio_files.append(f"{folder_output}/{filename}") speaker = "TTS Speaker {:02d}".format(int(speaker[-2:]) + 1) speakers_list.append(speaker)
return audio_files, speakers_list
# =====================================# Tone color converter# =====================================
def se_process_audio_segments( source_seg, tone_color_converter, device, remove_previous_processed=True): # list wav seg source_audio_segs = glob.glob(f"{source_seg}/*.wav") if not source_audio_segs: raise ValueError( f"No audio segments found in {str(source_audio_segs)}" )
source_se_path = os.path.join(source_seg, "se.pth")
# if exist not create wav if os.path.isfile(source_se_path): se = torch.load(source_se_path).to(device) logger.debug(f"Previous created {source_se_path}") else: se = tone_color_converter.extract_se(source_audio_segs, source_se_path)
return se
def create_wav_vc( valid_speakers, segments_base, audio_name, max_segments=10, target_dir="processed", get_vocals_dereverb=False,): # valid_speakers = list({item['speaker'] for item in segments_base})
# Before function delete automatic delete_previous_automatic output_dir = os.path.join(".", target_dir) # remove content # remove_directory_contents(output_dir)
path_source_segments = [] path_target_segments = [] for speaker in valid_speakers: filtered_speaker = [ segment for segment in segments_base if segment["speaker"] == speaker ] if len(filtered_speaker) > 4: filtered_speaker = filtered_speaker[1:]
dir_name_speaker = speaker + audio_name dir_name_speaker_tts = "tts" + speaker + audio_name dir_path_speaker = os.path.join(output_dir, dir_name_speaker) dir_path_speaker_tts = os.path.join(output_dir, dir_name_speaker_tts) create_directories([dir_path_speaker, dir_path_speaker_tts])
path_target_segments.append(dir_path_speaker) path_source_segments.append(dir_path_speaker_tts)
# create wav max_segments_count = 0 for seg in filtered_speaker: duration = float(seg["end"]) - float(seg["start"]) if duration > 3.0 and duration < 18.0: logger.info( f'Processing segment: {seg["start"]}, {seg["end"]}, {seg["speaker"]}, {duration}, {seg["text"]}' ) name_new_wav = str(seg["start"])
check_segment_audio_target_file = os.path.join( dir_path_speaker, f"{name_new_wav}.wav" )
if os.path.exists(check_segment_audio_target_file): logger.debug( "Segment vc source exists: " f"{check_segment_audio_target_file}" ) pass else: create_wav_file_vc( sample_name=name_new_wav, audio_wav="audio.wav", start=(float(seg["start"]) + 1.0), end=(float(seg["end"]) - 1.0), output_final_path=dir_path_speaker, get_vocals_dereverb=get_vocals_dereverb, )
file_name_tts = f"audio2/audio/{str(seg['start'])}.ogg" # copy_files(file_name_tts, os.path.join(output_dir, dir_name_speaker_tts) convert_to_xtts_good_sample( file_name_tts, dir_path_speaker_tts )
max_segments_count += 1 if max_segments_count == max_segments: break
if max_segments_count == 0: logger.info("Taking the first segment") seg = filtered_speaker[0] logger.info( f'Processing segment: {seg["start"]}, {seg["end"]}, {seg["speaker"]}, {seg["text"]}' ) max_duration = float(seg["end"]) - float(seg["start"]) max_duration = max(1.0, min(max_duration, 18.0))
name_new_wav = str(seg["start"]) create_wav_file_vc( sample_name=name_new_wav, audio_wav="audio.wav", start=(float(seg["start"])), end=(float(seg["start"]) + max_duration), output_final_path=dir_path_speaker, get_vocals_dereverb=get_vocals_dereverb, )
file_name_tts = f"audio2/audio/{str(seg['start'])}.ogg" # copy_files(file_name_tts, os.path.join(output_dir, dir_name_speaker_tts) convert_to_xtts_good_sample(file_name_tts, dir_path_speaker_tts)
logger.debug(f"Base: {str(path_source_segments)}") logger.debug(f"Target: {str(path_target_segments)}")
return path_source_segments, path_target_segments
def toneconverter_openvoice( result_diarize, preprocessor_max_segments, remove_previous_process=True, get_vocals_dereverb=False, model="openvoice",): audio_path = "audio.wav" # se_path = "se.pth" target_dir = "processed" create_directories(target_dir)
from openvoice import se_extractor from openvoice.api import ToneColorConverter
audio_name = f"{os.path.basename(audio_path).rsplit('.', 1)[0]}_{se_extractor.hash_numpy_array(audio_path)}" # se_path = os.path.join(target_dir, audio_name, 'se.pth')
# create wav seg original and target
valid_speakers = list( {item["speaker"] for item in result_diarize["segments"]} )
logger.info("Openvoice preprocessor...")
if remove_previous_process: remove_directory_contents(target_dir)
path_source_segments, path_target_segments = create_wav_vc( valid_speakers, result_diarize["segments"], audio_name, max_segments=preprocessor_max_segments, get_vocals_dereverb=get_vocals_dereverb, )
logger.info("Openvoice loading model...") model_path_openvoice = "./OPENVOICE_MODELS" url_model_openvoice = "https://huggingface.co/myshell-ai/OpenVoice/resolve/main/checkpoints/converter"
if "v2" in model: model_path = os.path.join(model_path_openvoice, "v2") url_model_openvoice = url_model_openvoice.replace( "OpenVoice", "OpenVoiceV2" ).replace("checkpoints/", "") else: model_path = os.path.join(model_path_openvoice, "v1") create_directories(model_path)
config_url = f"{url_model_openvoice}/config.json" checkpoint_url = f"{url_model_openvoice}/checkpoint.pth"
config_path = download_manager(url=config_url, path=model_path) checkpoint_path = download_manager( url=checkpoint_url, path=model_path )
device = os.environ.get("SONITR_DEVICE") tone_color_converter = ToneColorConverter(config_path, device=device) tone_color_converter.load_ckpt(checkpoint_path)
logger.info("Openvoice tone color converter:") global_progress_bar = tqdm(total=len(result_diarize["segments"]), desc="Progress")
for source_seg, target_seg, speaker in zip( path_source_segments, path_target_segments, valid_speakers ): # source_se_path = os.path.join(source_seg, 'se.pth') source_se = se_process_audio_segments(source_seg, tone_color_converter, device) # target_se_path = os.path.join(target_seg, 'se.pth') target_se = se_process_audio_segments(target_seg, tone_color_converter, device)
# Iterate throw segments encode_message = "@MyShell" filtered_speaker = [ segment for segment in result_diarize["segments"] if segment["speaker"] == speaker ] for seg in filtered_speaker: src_path = ( save_path ) = f"audio2/audio/{str(seg['start'])}.ogg" # overwrite logger.debug(f"{src_path}")
tone_color_converter.convert( audio_src_path=src_path, src_se=source_se, tgt_se=target_se, output_path=save_path, message=encode_message, )
global_progress_bar.update(1)
global_progress_bar.close()
try: del tone_color_converter gc.collect() torch.cuda.empty_cache() except Exception as error: logger.error(str(error)) gc.collect() torch.cuda.empty_cache()
def toneconverter_freevc( result_diarize, remove_previous_process=True, get_vocals_dereverb=False,): audio_path = "audio.wav" target_dir = "processed" create_directories(target_dir)
from openvoice import se_extractor
audio_name = f"{os.path.basename(audio_path).rsplit('.', 1)[0]}_{se_extractor.hash_numpy_array(audio_path)}"
# create wav seg; original is target and dubbing is source valid_speakers = list( {item["speaker"] for item in result_diarize["segments"]} )
logger.info("FreeVC preprocessor...")
if remove_previous_process: remove_directory_contents(target_dir)
path_source_segments, path_target_segments = create_wav_vc( valid_speakers, result_diarize["segments"], audio_name, max_segments=1, get_vocals_dereverb=get_vocals_dereverb, )
logger.info("FreeVC loading model...") device_id = os.environ.get("SONITR_DEVICE") device = None if device_id == "cpu" else device_id try: from TTS.api import TTS tts = TTS( model_name="voice_conversion_models/multilingual/vctk/freevc24", progress_bar=False ).to(device) except Exception as error: logger.error(str(error)) logger.error("Error loading the FreeVC model.") return
logger.info("FreeVC process:") global_progress_bar = tqdm(total=len(result_diarize["segments"]), desc="Progress")
for source_seg, target_seg, speaker in zip( path_source_segments, path_target_segments, valid_speakers ):
filtered_speaker = [ segment for segment in result_diarize["segments"] if segment["speaker"] == speaker ]
files_and_directories = os.listdir(target_seg) wav_files = [file for file in files_and_directories if file.endswith(".wav")] original_wav_audio_segment = os.path.join(target_seg, wav_files[0])
for seg in filtered_speaker:
src_path = ( save_path ) = f"audio2/audio/{str(seg['start'])}.ogg" # overwrite logger.debug(f"{src_path} - {original_wav_audio_segment}")
wav = tts.voice_conversion( source_wav=src_path, target_wav=original_wav_audio_segment, )
sf.write( file=save_path, samplerate=tts.voice_converter.vc_config.audio.output_sample_rate, data=wav, format="ogg", subtype="vorbis", )
global_progress_bar.update(1)
global_progress_bar.close()
try: del tts gc.collect() torch.cuda.empty_cache() except Exception as error: logger.error(str(error)) gc.collect() torch.cuda.empty_cache()
def toneconverter( result_diarize, preprocessor_max_segments, remove_previous_process=True, get_vocals_dereverb=False, method_vc="freevc"):
if method_vc == "freevc": if preprocessor_max_segments > 1: logger.info("FreeVC only uses one segment.") return toneconverter_freevc( result_diarize, remove_previous_process=remove_previous_process, get_vocals_dereverb=get_vocals_dereverb, ) elif "openvoice" in method_vc: return toneconverter_openvoice( result_diarize, preprocessor_max_segments, remove_previous_process=remove_previous_process, get_vocals_dereverb=get_vocals_dereverb, model=method_vc, )
if __name__ == "__main__": from segments import result_diarize
audio_segmentation_to_voice( result_diarize, TRANSLATE_AUDIO_TO="en", max_accelerate_audio=2.1, is_gui=True, tts_voice00="en-facebook-mms VITS", tts_voice01="en-CA-ClaraNeural-Female", tts_voice02="en-GB-ThomasNeural-Male", tts_voice03="en-GB-SoniaNeural-Female", tts_voice04="en-NZ-MitchellNeural-Male", tts_voice05="en-GB-MaisieNeural-Female", )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457from tqdm import tqdmfrom deep_translator import GoogleTranslatorfrom itertools import chainimport copyfrom .language_configuration import fix_code_language, INVERTED_LANGUAGESfrom .logging_setup import loggerimport reimport jsonimport time
TRANSLATION_PROCESS_OPTIONS = [ "google_translator_batch", "google_translator", "gpt-3.5-turbo-0125_batch", "gpt-3.5-turbo-0125", "gpt-4-turbo-preview_batch", "gpt-4-turbo-preview", "disable_translation",]DOCS_TRANSLATION_PROCESS_OPTIONS = [ "google_translator", "gpt-3.5-turbo-0125", "gpt-4-turbo-preview", "disable_translation",]
def translate_iterative(segments, target, source=None): """ Translate text segments individually to the specified language.
Parameters: - segments (list): A list of dictionaries with 'text' as a key for segment text. - target (str): Target language code. - source (str, optional): Source language code. Defaults to None.
Returns: - list: Translated text segments in the target language.
Notes: - Translates each segment using Google Translate.
Example: segments = [{'text': 'first segment.'}, {'text': 'second segment.'}] translated_segments = translate_iterative(segments, 'es') """
segments_ = copy.deepcopy(segments)
if ( not source ): logger.debug("No source language") source = "auto"
translator = GoogleTranslator(source=source, target=target)
for line in tqdm(range(len(segments_))): text = segments_[line]["text"] translated_line = translator.translate(text.strip()) segments_[line]["text"] = translated_line
return segments_
def verify_translate( segments, segments_copy, translated_lines, target, source): """ Verify integrity and translate segments if lengths match, otherwise switch to iterative translation. """ if len(segments) == len(translated_lines): for line in range(len(segments_copy)): logger.debug( f"{segments_copy[line]['text']} >> " f"{translated_lines[line].strip()}" ) segments_copy[line]["text"] = translated_lines[ line].replace("\t", "").replace("\n", "").strip() return segments_copy else: logger.error( "The translation failed, switching to google_translate iterative. " f"{len(segments), len(translated_lines)}" ) return translate_iterative(segments, target, source)
def translate_batch(segments, target, chunk_size=2000, source=None): """ Translate a batch of text segments into the specified language in chunks, respecting the character limit.
Parameters: - segments (list): List of dictionaries with 'text' as a key for segment text. - target (str): Target language code. - chunk_size (int, optional): Maximum character limit for each translation chunk (default is 2000; max 5000). - source (str, optional): Source language code. Defaults to None.
Returns: - list: Translated text segments in the target language.
Notes: - Splits input segments into chunks respecting the character limit for translation. - Translates the chunks using Google Translate. - If chunked translation fails, switches to iterative translation using `translate_iterative()`.
Example: segments = [{'text': 'first segment.'}, {'text': 'second segment.'}] translated = translate_batch(segments, 'es', chunk_size=4000, source='en') """
segments_copy = copy.deepcopy(segments)
if ( not source ): logger.debug("No source language") source = "auto"
# Get text text_lines = [] for line in range(len(segments_copy)): text = segments_copy[line]["text"].strip() text_lines.append(text)
# chunk limit text_merge = [] actual_chunk = "" global_text_list = [] actual_text_list = [] for one_line in text_lines: one_line = " " if not one_line else one_line if (len(actual_chunk) + len(one_line)) <= chunk_size: if actual_chunk: actual_chunk += " ||||| " actual_chunk += one_line actual_text_list.append(one_line) else: text_merge.append(actual_chunk) actual_chunk = one_line global_text_list.append(actual_text_list) actual_text_list = [one_line] if actual_chunk: text_merge.append(actual_chunk) global_text_list.append(actual_text_list)
# translate chunks progress_bar = tqdm(total=len(segments), desc="Translating") translator = GoogleTranslator(source=source, target=target) split_list = [] try: for text, text_iterable in zip(text_merge, global_text_list): translated_line = translator.translate(text.strip()) split_text = translated_line.split("|||||") if len(split_text) == len(text_iterable): progress_bar.update(len(split_text)) else: logger.debug( "Chunk fixing iteratively. Len chunk: " f"{len(split_text)}, expected: {len(text_iterable)}" ) split_text = [] for txt_iter in text_iterable: translated_txt = translator.translate(txt_iter.strip()) split_text.append(translated_txt) progress_bar.update(1) split_list.append(split_text) progress_bar.close() except Exception as error: progress_bar.close() logger.error(str(error)) logger.warning( "The translation in chunks failed, switching to iterative." " Related: too many request" ) # use proxy or less chunk size return translate_iterative(segments, target, source)
# un chunk translated_lines = list(chain.from_iterable(split_list))
return verify_translate( segments, segments_copy, translated_lines, target, source )
def call_gpt_translate( client, model, system_prompt, user_prompt, original_text=None, batch_lines=None,):
# https://platform.openai.com/docs/guides/text-generation/json-mode response = client.chat.completions.create( model=model, response_format={"type": "json_object"}, messages=[ {"role": "system", "content": system_prompt}, {"role": "user", "content": user_prompt} ] ) result = response.choices[0].message.content logger.debug(f"Result: {str(result)}")
try: translation = json.loads(result) except Exception as error: match_result = re.search(r'\{.*?\}', result) if match_result: logger.error(str(error)) json_str = match_result.group(0) translation = json.loads(json_str) else: raise error
# Get valid data if batch_lines: for conversation in translation.values(): if isinstance(conversation, dict): conversation = list(conversation.values())[0] if ( list( original_text["conversation"][0].values() )[0].strip() == list(conversation[0].values())[0].strip() ): continue if len(conversation) == batch_lines: break
fix_conversation_length = [] for line in conversation: for speaker_code, text_tr in line.items(): fix_conversation_length.append({speaker_code: text_tr})
logger.debug(f"Data batch: {str(fix_conversation_length)}") logger.debug( f"Lines Received: {len(fix_conversation_length)}," f" expected: {batch_lines}" )
return fix_conversation_length
else: if isinstance(translation, dict): translation = list(translation.values())[0] if isinstance(translation, list): translation = translation[0] if isinstance(translation, set): translation = list(translation)[0] if not isinstance(translation, str): raise ValueError(f"No valid response received: {str(translation)}")
return translation
def gpt_sequential(segments, model, target, source=None): from openai import OpenAI
translated_segments = copy.deepcopy(segments)
client = OpenAI() progress_bar = tqdm(total=len(segments), desc="Translating")
lang_tg = re.sub(r'\([^)]*\)', '', INVERTED_LANGUAGES[target]).strip() lang_sc = "" if source: lang_sc = re.sub(r'\([^)]*\)', '', INVERTED_LANGUAGES[source]).strip()
fixed_target = fix_code_language(target) fixed_source = fix_code_language(source) if source else "auto"
system_prompt = "Machine translation designed to output the translated_text JSON."
for i, line in enumerate(translated_segments): text = line["text"].strip() start = line["start"] user_prompt = f"Translate the following {lang_sc} text into {lang_tg}, write the fully translated text and nothing more:\n{text}"
time.sleep(0.5)
try: translated_text = call_gpt_translate( client, model, system_prompt, user_prompt, )
except Exception as error: logger.error( f"{str(error)} >> The text of segment {start} " "is being corrected with Google Translate" ) translator = GoogleTranslator( source=fixed_source, target=fixed_target ) translated_text = translator.translate(text.strip())
translated_segments[i]["text"] = translated_text.strip() progress_bar.update(1)
progress_bar.close()
return translated_segments
def gpt_batch(segments, model, target, token_batch_limit=900, source=None): from openai import OpenAI import tiktoken
token_batch_limit = max(100, (token_batch_limit - 40) // 2) progress_bar = tqdm(total=len(segments), desc="Translating") segments_copy = copy.deepcopy(segments) encoding = tiktoken.get_encoding("cl100k_base") client = OpenAI()
lang_tg = re.sub(r'\([^)]*\)', '', INVERTED_LANGUAGES[target]).strip() lang_sc = "" if source: lang_sc = re.sub(r'\([^)]*\)', '', INVERTED_LANGUAGES[source]).strip()
fixed_target = fix_code_language(target) fixed_source = fix_code_language(source) if source else "auto"
name_speaker = "ABCDEFGHIJKL"
translated_lines = [] text_data_dict = [] num_tokens = 0 count_sk = {char: 0 for char in "ABCDEFGHIJKL"}
for i, line in enumerate(segments_copy): text = line["text"] speaker = line["speaker"] last_start = line["start"] # text_data_dict.append({str(int(speaker[-1])+1): text}) index_sk = int(speaker[-2:]) character_sk = name_speaker[index_sk] count_sk[character_sk] += 1 code_sk = character_sk+str(count_sk[character_sk]) text_data_dict.append({code_sk: text}) num_tokens += len(encoding.encode(text)) + 7 if num_tokens >= token_batch_limit or i == len(segments_copy)-1: try: batch_lines = len(text_data_dict) batch_conversation = {"conversation": copy.deepcopy(text_data_dict)} # Reset vars num_tokens = 0 text_data_dict = [] count_sk = {char: 0 for char in "ABCDEFGHIJKL"} # Process translation # https://arxiv.org/pdf/2309.03409.pdf system_prompt = f"Machine translation designed to output the translated_conversation key JSON containing a list of {batch_lines} items." user_prompt = f"Translate each of the following text values in conversation{' from' if lang_sc else ''} {lang_sc} to {lang_tg}:\n{batch_conversation}" logger.debug(f"Prompt: {str(user_prompt)}")
conversation = call_gpt_translate( client, model, system_prompt, user_prompt, original_text=batch_conversation, batch_lines=batch_lines, )
if len(conversation) < batch_lines: raise ValueError( "Incomplete result received. Batch lines: " f"{len(conversation)}, expected: {batch_lines}" )
for i, translated_text in enumerate(conversation): if i+1 > batch_lines: break translated_lines.append(list(translated_text.values())[0])
progress_bar.update(batch_lines)
except Exception as error: logger.error(str(error))
first_start = segments_copy[max(0, i-(batch_lines-1))]["start"] logger.warning( f"The batch from {first_start} to {last_start} " "failed, is being corrected with Google Translate" )
translator = GoogleTranslator( source=fixed_source, target=fixed_target )
for txt_source in batch_conversation["conversation"]: translated_txt = translator.translate( list(txt_source.values())[0].strip() ) translated_lines.append(translated_txt.strip()) progress_bar.update(1)
progress_bar.close()
return verify_translate( segments, segments_copy, translated_lines, fixed_target, fixed_source )
def translate_text( segments, target, translation_process="google_translator_batch", chunk_size=4500, source=None, token_batch_limit=1000,): """Translates text segments using a specified process.""" match translation_process: case "google_translator_batch": return translate_batch( segments, fix_code_language(target), chunk_size, fix_code_language(source) ) case "google_translator": return translate_iterative( segments, fix_code_language(target), fix_code_language(source) ) case model if model in ["gpt-3.5-turbo-0125", "gpt-4-turbo-preview"]: return gpt_sequential(segments, model, target, source) case model if model in ["gpt-3.5-turbo-0125_batch", "gpt-4-turbo-preview_batch",]: return gpt_batch( segments, translation_process.replace("_batch", ""), target, token_batch_limit, source ) case "disable_translation": return segments case _: raise ValueError("No valid translation process")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487import os, zipfile, rarfile, shutil, subprocess, shlex, sys # noqafrom .logging_setup import loggerfrom urllib.parse import urlparsefrom IPython.utils import captureimport re
VIDEO_EXTENSIONS = [ ".mp4", ".avi", ".mov", ".mkv", ".wmv", ".flv", ".webm", ".m4v", ".mpeg", ".mpg", ".3gp"]
AUDIO_EXTENSIONS = [ ".mp3", ".wav", ".aiff", ".aif", ".flac", ".aac", ".ogg", ".wma", ".m4a", ".alac", ".pcm", ".opus", ".ape", ".amr", ".ac3", ".vox", ".caf"]
SUBTITLE_EXTENSIONS = [ ".srt", ".vtt", ".ass"]
def run_command(command): logger.debug(command) if isinstance(command, str): command = shlex.split(command)
sub_params = { "stdout": subprocess.PIPE, "stderr": subprocess.PIPE, "creationflags": subprocess.CREATE_NO_WINDOW if sys.platform == "win32" else 0, } process_command = subprocess.Popen(command, **sub_params) output, errors = process_command.communicate() if ( process_command.returncode != 0 ): # or not os.path.exists(mono_path) or os.path.getsize(mono_path) == 0: logger.error("Error comnand") raise Exception(errors.decode())
def print_tree_directory(root_dir, indent=""): if not os.path.exists(root_dir): logger.error(f"{indent} Invalid directory or file: {root_dir}") return
items = os.listdir(root_dir)
for index, item in enumerate(sorted(items)): item_path = os.path.join(root_dir, item) is_last_item = index == len(items) - 1
if os.path.isfile(item_path) and item_path.endswith(".zip"): with zipfile.ZipFile(item_path, "r") as zip_file: print( f"{indent}{'└──' if is_last_item else '├──'} {item} (zip file)" ) zip_contents = zip_file.namelist() for zip_item in sorted(zip_contents): print( f"{indent}{' ' if is_last_item else '│ '}{zip_item}" ) else: print(f"{indent}{'└──' if is_last_item else '├──'} {item}")
if os.path.isdir(item_path): new_indent = indent + (" " if is_last_item else "│ ") print_tree_directory(item_path, new_indent)
def upload_model_list(): weight_root = "weights" models = [] for name in os.listdir(weight_root): if name.endswith(".pth"): models.append("weights/" + name) if models: logger.debug(models)
index_root = "logs" index_paths = [None] for name in os.listdir(index_root): if name.endswith(".index"): index_paths.append("logs/" + name) if index_paths: logger.debug(index_paths)
return models, index_paths
def manual_download(url, dst): if "drive.google" in url: logger.info("Drive url") if "folders" in url: logger.info("folder") os.system(f'gdown --folder "{url}" -O {dst} --fuzzy -c') else: logger.info("single") os.system(f'gdown "{url}" -O {dst} --fuzzy -c') elif "huggingface" in url: logger.info("HuggingFace url") if "/blob/" in url or "/resolve/" in url: if "/blob/" in url: url = url.replace("/blob/", "/resolve/") download_manager(url=url, path=dst, overwrite=True, progress=True) else: os.system(f"git clone {url} {dst+'repo/'}") elif "http" in url: logger.info("URL") download_manager(url=url, path=dst, overwrite=True, progress=True) elif os.path.exists(url): logger.info("Path") copy_files(url, dst) else: logger.error(f"No valid URL: {url}")
def download_list(text_downloads):
if os.environ.get("ZERO_GPU") == "TRUE": raise RuntimeError("This option is disabled in this demo.") try: urls = [elem.strip() for elem in text_downloads.split(",")] except Exception as error: raise ValueError(f"No valid URL. {str(error)}")
create_directories(["downloads", "logs", "weights"])
path_download = "downloads/" for url in urls: manual_download(url, path_download)
# Tree print("####################################") print_tree_directory("downloads", indent="") print("####################################")
# Place files select_zip_and_rar_files("downloads/")
models, _ = upload_model_list()
# hf space models files delete remove_directory_contents("downloads/repo")
return f"Downloaded = {models}"
def select_zip_and_rar_files(directory_path="downloads/"): # filter zip_files = [] rar_files = []
for file_name in os.listdir(directory_path): if file_name.endswith(".zip"): zip_files.append(file_name) elif file_name.endswith(".rar"): rar_files.append(file_name)
# extract for file_name in zip_files: file_path = os.path.join(directory_path, file_name) with zipfile.ZipFile(file_path, "r") as zip_ref: zip_ref.extractall(directory_path)
for file_name in rar_files: file_path = os.path.join(directory_path, file_name) with rarfile.RarFile(file_path, "r") as rar_ref: rar_ref.extractall(directory_path)
# set in path def move_files_with_extension(src_dir, extension, destination_dir): for root, _, files in os.walk(src_dir): for file_name in files: if file_name.endswith(extension): source_file = os.path.join(root, file_name) destination = os.path.join(destination_dir, file_name) shutil.move(source_file, destination)
move_files_with_extension(directory_path, ".index", "logs/") move_files_with_extension(directory_path, ".pth", "weights/")
return "Download complete"
def is_file_with_extensions(string_path, extensions): return any(string_path.lower().endswith(ext) for ext in extensions)
def is_video_file(string_path): return is_file_with_extensions(string_path, VIDEO_EXTENSIONS)
def is_audio_file(string_path): return is_file_with_extensions(string_path, AUDIO_EXTENSIONS)
def is_subtitle_file(string_path): return is_file_with_extensions(string_path, SUBTITLE_EXTENSIONS)
def get_directory_files(directory): audio_files = [] video_files = [] sub_files = []
for item in os.listdir(directory): item_path = os.path.join(directory, item)
if os.path.isfile(item_path):
if is_audio_file(item_path): audio_files.append(item_path)
elif is_video_file(item_path): video_files.append(item_path)
elif is_subtitle_file(item_path): sub_files.append(item_path)
logger.info( f"Files in path ({directory}): " f"{str(audio_files + video_files + sub_files)}" )
return audio_files, video_files, sub_files
def get_valid_files(paths): valid_paths = [] for path in paths: if os.path.isdir(path): audio_files, video_files, sub_files = get_directory_files(path) valid_paths.extend(audio_files) valid_paths.extend(video_files) valid_paths.extend(sub_files) else: valid_paths.append(path)
return valid_paths
def extract_video_links(link):
params_dlp = {"quiet": False, "no_warnings": True, "noplaylist": False}
try: from yt_dlp import YoutubeDL with capture.capture_output() as cap: with YoutubeDL(params_dlp) as ydl: info_dict = ydl.extract_info( # noqa link, download=False, process=True )
urls = re.findall(r'\[youtube\] Extracting URL: (.*?)\n', cap.stdout) logger.info(f"List of videos in ({link}): {str(urls)}") del cap except Exception as error: logger.error(f"{link} >> {str(error)}") urls = [link]
return urls
def get_link_list(urls): valid_links = [] for url_video in urls: if "youtube.com" in url_video and "/watch?v=" not in url_video: url_links = extract_video_links(url_video) valid_links.extend(url_links) else: valid_links.append(url_video) return valid_links
# =====================================# Download Manager# =====================================
def load_file_from_url( url: str, model_dir: str, file_name: str | None = None, overwrite: bool = False, progress: bool = True,) -> str: """Download a file from `url` into `model_dir`, using the file present if possible.
Returns the path to the downloaded file. """ os.makedirs(model_dir, exist_ok=True) if not file_name: parts = urlparse(url) file_name = os.path.basename(parts.path) cached_file = os.path.abspath(os.path.join(model_dir, file_name))
# Overwrite if os.path.exists(cached_file): if overwrite or os.path.getsize(cached_file) == 0: remove_files(cached_file)
# Download if not os.path.exists(cached_file): logger.info(f'Downloading: "{url}" to {cached_file}\n') from torch.hub import download_url_to_file
download_url_to_file(url, cached_file, progress=progress) else: logger.debug(cached_file)
return cached_file
def friendly_name(file: str): if file.startswith("http"): file = urlparse(file).path
file = os.path.basename(file) model_name, extension = os.path.splitext(file) return model_name, extension
def download_manager( url: str, path: str, extension: str = "", overwrite: bool = False, progress: bool = True,): url = url.strip()
name, ext = friendly_name(url) name += ext if not extension else f".{extension}"
if url.startswith("http"): filename = load_file_from_url( url=url, model_dir=path, file_name=name, overwrite=overwrite, progress=progress, ) else: filename = path
return filename
# =====================================# File management# =====================================
# only remove filesdef remove_files(file_list): if isinstance(file_list, str): file_list = [file_list]
for file in file_list: if os.path.exists(file): os.remove(file)
def remove_directory_contents(directory_path): """ Removes all files and subdirectories within a directory.
Parameters: directory_path (str): Path to the directory whose contents need to be removed. """ if os.path.exists(directory_path): for filename in os.listdir(directory_path): file_path = os.path.join(directory_path, filename) try: if os.path.isfile(file_path): os.remove(file_path) elif os.path.isdir(file_path): shutil.rmtree(file_path) except Exception as e: logger.error(f"Failed to delete {file_path}. Reason: {e}") logger.info(f"Content in '{directory_path}' removed.") else: logger.error(f"Directory '{directory_path}' does not exist.")
# Create directory if not existsdef create_directories(directory_path): if isinstance(directory_path, str): directory_path = [directory_path] for one_dir_path in directory_path: if not os.path.exists(one_dir_path): os.makedirs(one_dir_path) logger.debug(f"Directory '{one_dir_path}' created.")
def move_files(source_dir, destination_dir, extension=""): """ Moves file(s) from the source path to the destination path.
Parameters: source_dir (str): Path to the source directory. destination_dir (str): Path to the destination directory. extension (str): Only move files with this extension. """ create_directories(destination_dir)
for filename in os.listdir(source_dir): source_path = os.path.join(source_dir, filename) destination_path = os.path.join(destination_dir, filename) if extension and not filename.endswith(extension): continue os.replace(source_path, destination_path)
def copy_files(source_path, destination_path): """ Copies a file or multiple files from a source path to a destination path.
Parameters: source_path (str or list): Path or list of paths to the source file(s) or directory. destination_path (str): Path to the destination directory. """ create_directories(destination_path)
if isinstance(source_path, str): source_path = [source_path]
if os.path.isdir(source_path[0]): # Copy all files from the source directory to the destination directory base_path = source_path[0] source_path = os.listdir(source_path[0]) source_path = [ os.path.join(base_path, file_name) for file_name in source_path ]
for one_source_path in source_path: if os.path.exists(one_source_path): shutil.copy2(one_source_path, destination_path) logger.debug( f"File '{one_source_path}' copied to '{destination_path}'." ) else: logger.error(f"File '{one_source_path}' does not exist.")
def rename_file(current_name, new_name): file_directory = os.path.dirname(current_name)
if os.path.exists(current_name): dir_new_name_file = os.path.join(file_directory, new_name) os.rename(current_name, dir_new_name_file) logger.debug(f"File '{current_name}' renamed to '{new_name}'.") return dir_new_name_file else: logger.error(f"File '{current_name}' does not exist.") return None123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454import numpy as np, parselmouth, torch, pdb, sys
from time import time as ttime
import torch.nn.functional as F
import scipy.signal as signal
import pyworld, os, traceback, faiss, librosa, torchcrepe
from scipy import signal
from functools import lru_cache
from soni_translate.logging_setup import logger
now_dir = os.getcwd()
sys.path.append(now_dir)
bh, ah = signal.butter(N=5, Wn=48, btype="high", fs=16000)
input_audio_path2wav = {}
@lru_cache
def cache_harvest_f0(input_audio_path, fs, f0max, f0min, frame_period):
audio = input_audio_path2wav[input_audio_path]
f0, t = pyworld.harvest(
audio,
fs=fs,
f0_ceil=f0max,
f0_floor=f0min,
frame_period=frame_period,
)
f0 = pyworld.stonemask(audio, f0, t, fs)
return f0
def change_rms(data1, sr1, data2, sr2, rate): # 1 is the input audio, 2 is the output audio, rate is the proportion of 2
# print(data1.max(),data2.max())
rms1 = librosa.feature.rms(
y=data1, frame_length=sr1 // 2 * 2, hop_length=sr1 // 2
) # one dot every half second
rms2 = librosa.feature.rms(y=data2, frame_length=sr2 // 2 * 2, hop_length=sr2 // 2)
rms1 = torch.from_numpy(rms1)
rms1 = F.interpolate(
rms1.unsqueeze(0), size=data2.shape[0], mode="linear"
).squeeze()
rms2 = torch.from_numpy(rms2)
rms2 = F.interpolate(
rms2.unsqueeze(0), size=data2.shape[0], mode="linear"
).squeeze()
rms2 = torch.max(rms2, torch.zeros_like(rms2) + 1e-6)
data2 *= (
torch.pow(rms1, torch.tensor(1 - rate))
* torch.pow(rms2, torch.tensor(rate - 1))
).numpy()
return data2
class VC(object):
def __init__(self, tgt_sr, config):
self.x_pad, self.x_query, self.x_center, self.x_max, self.is_half = (
config.x_pad,
config.x_query,
config.x_center,
config.x_max,
config.is_half,
)
self.sr = 16000 # hubert input sampling rate
self.window = 160 # points per frame
self.t_pad = self.sr * self.x_pad # Pad time before and after each bar
self.t_pad_tgt = tgt_sr * self.x_pad
self.t_pad2 = self.t_pad * 2
self.t_query = self.sr * self.x_query # Query time before and after the cut point
self.t_center = self.sr * self.x_center # Query point cut position
self.t_max = self.sr * self.x_max # Query-free duration threshold
self.device = config.device
def get_f0(
self,
input_audio_path,
x,
p_len,
f0_up_key,
f0_method,
filter_radius,
inp_f0=None,
):
global input_audio_path2wav
time_step = self.window / self.sr * 1000
f0_min = 50
f0_max = 1100
f0_mel_min = 1127 * np.log(1 + f0_min / 700)
f0_mel_max = 1127 * np.log(1 + f0_max / 700)
if f0_method == "pm":
f0 = (
parselmouth.Sound(x, self.sr)
.to_pitch_ac(
time_step=time_step / 1000,
voicing_threshold=0.6,
pitch_floor=f0_min,
pitch_ceiling=f0_max,
)
.selected_array["frequency"]
)
pad_size = (p_len - len(f0) + 1) // 2
if pad_size > 0 or p_len - len(f0) - pad_size > 0:
f0 = np.pad(
f0, [[pad_size, p_len - len(f0) - pad_size]], mode="constant"
)
elif f0_method == "harvest":
input_audio_path2wav[input_audio_path] = x.astype(np.double)
f0 = cache_harvest_f0(input_audio_path, self.sr, f0_max, f0_min, 10)
if filter_radius > 2:
f0 = signal.medfilt(f0, 3)
elif f0_method == "crepe":
model = "full"
# Pick a batch size that doesn't cause memory errors on your gpu
batch_size = 512
# Compute pitch using first gpu
audio = torch.tensor(np.copy(x))[None].float()
f0, pd = torchcrepe.predict(
audio,
self.sr,
self.window,
f0_min,
f0_max,
model,
batch_size=batch_size,
device=self.device,
return_periodicity=True,
)
pd = torchcrepe.filter.median(pd, 3)
f0 = torchcrepe.filter.mean(f0, 3)
f0[pd < 0.1] = 0
f0 = f0[0].cpu().numpy()
elif "rmvpe" in f0_method:
if hasattr(self, "model_rmvpe") == False:
from lib.rmvpe import RMVPE
logger.info("Loading vocal pitch estimator model")
self.model_rmvpe = RMVPE(
"rmvpe.pt", is_half=self.is_half, device=self.device
)
thred = 0.03
if "+" in f0_method:
f0 = self.model_rmvpe.pitch_based_audio_inference(x, thred, f0_min, f0_max)
else:
f0 = self.model_rmvpe.infer_from_audio(x, thred)
f0 *= pow(2, f0_up_key / 12)
# with open("test.txt","w")as f:f.write("\n".join([str(i)for i in f0.tolist()]))
tf0 = self.sr // self.window # f0 points per second
if inp_f0 is not None:
delta_t = np.round(
(inp_f0[:, 0].max() - inp_f0[:, 0].min()) * tf0 + 1
).astype("int16")
replace_f0 = np.interp(
list(range(delta_t)), inp_f0[:, 0] * 100, inp_f0[:, 1]
)
shape = f0[self.x_pad * tf0 : self.x_pad * tf0 + len(replace_f0)].shape[0]
f0[self.x_pad * tf0 : self.x_pad * tf0 + len(replace_f0)] = replace_f0[
:shape
]
# with open("test_opt.txt","w")as f:f.write("\n".join([str(i)for i in f0.tolist()]))
f0bak = f0.copy()
f0_mel = 1127 * np.log(1 + f0 / 700)
f0_mel[f0_mel > 0] = (f0_mel[f0_mel > 0] - f0_mel_min) * 254 / (
f0_mel_max - f0_mel_min
) + 1
f0_mel[f0_mel <= 1] = 1
f0_mel[f0_mel > 255] = 255
try:
f0_coarse = np.rint(f0_mel).astype(np.int)
except: # noqa
f0_coarse = np.rint(f0_mel).astype(int)
return f0_coarse, f0bak # 1-0
def vc(
self,
model,
net_g,
sid,
audio0,
pitch,
pitchf,
times,
index,
big_npy,
index_rate,
version,
protect,
): # ,file_index,file_big_npy
feats = torch.from_numpy(audio0)
if self.is_half:
feats = feats.half()
else:
feats = feats.float()
if feats.dim() == 2: # double channels
feats = feats.mean(-1)
assert feats.dim() == 1, feats.dim()
feats = feats.view(1, -1)
padding_mask = torch.BoolTensor(feats.shape).to(self.device).fill_(False)
inputs = {
"source": feats.to(self.device),
"padding_mask": padding_mask,
"output_layer": 9 if version == "v1" else 12,
}
t0 = ttime()
with torch.no_grad():
logits = model.extract_features(**inputs)
feats = model.final_proj(logits[0]) if version == "v1" else logits[0]
if protect < 0.5 and pitch != None and pitchf != None:
feats0 = feats.clone()
if (
isinstance(index, type(None)) == False
and isinstance(big_npy, type(None)) == False
and index_rate != 0
):
npy = feats[0].cpu().numpy()
if self.is_half:
npy = npy.astype("float32")
# _, I = index.search(npy, 1)
# npy = big_npy[I.squeeze()]
score, ix = index.search(npy, k=8)
weight = np.square(1 / score)
weight /= weight.sum(axis=1, keepdims=True)
npy = np.sum(big_npy[ix] * np.expand_dims(weight, axis=2), axis=1)
if self.is_half:
npy = npy.astype("float16")
feats = (
torch.from_numpy(npy).unsqueeze(0).to(self.device) * index_rate
+ (1 - index_rate) * feats
)
feats = F.interpolate(feats.permute(0, 2, 1), scale_factor=2).permute(0, 2, 1)
if protect < 0.5 and pitch != None and pitchf != None:
feats0 = F.interpolate(feats0.permute(0, 2, 1), scale_factor=2).permute(
0, 2, 1
)
t1 = ttime()
p_len = audio0.shape[0] // self.window
if feats.shape[1] < p_len:
p_len = feats.shape[1]
if pitch != None and pitchf != None:
pitch = pitch[:, :p_len]
pitchf = pitchf[:, :p_len]
if protect < 0.5 and pitch != None and pitchf != None:
pitchff = pitchf.clone()
pitchff[pitchf > 0] = 1
pitchff[pitchf < 1] = protect
pitchff = pitchff.unsqueeze(-1)
feats = feats * pitchff + feats0 * (1 - pitchff)
feats = feats.to(feats0.dtype)
p_len = torch.tensor([p_len], device=self.device).long()
with torch.no_grad():
if pitch != None and pitchf != None:
audio1 = (
(net_g.infer(feats, p_len, pitch, pitchf, sid)[0][0, 0])
.data.cpu()
.float()
.numpy()
)
else:
audio1 = (
(net_g.infer(feats, p_len, sid)[0][0, 0]).data.cpu().float().numpy()
)
del feats, p_len, padding_mask
if torch.cuda.is_available():
torch.cuda.empty_cache()
t2 = ttime()
times[0] += t1 - t0
times[2] += t2 - t1
return audio1
def pipeline(
self,
model,
net_g,
sid,
audio,
input_audio_path,
times,
f0_up_key,
f0_method,
file_index,
# file_big_npy,
index_rate,
if_f0,
filter_radius,
tgt_sr,
resample_sr,
rms_mix_rate,
version,
protect,
f0_file=None,
):
if (
file_index != ""
# and file_big_npy != ""
# and os.path.exists(file_big_npy) == True
and os.path.exists(file_index) == True
and index_rate != 0
):
try:
index = faiss.read_index(file_index)
# big_npy = np.load(file_big_npy)
big_npy = index.reconstruct_n(0, index.ntotal)
except:
traceback.print_exc()
index = big_npy = None
else:
index = big_npy = None
logger.warning("File index Not found, set None")
audio = signal.filtfilt(bh, ah, audio)
audio_pad = np.pad(audio, (self.window // 2, self.window // 2), mode="reflect")
opt_ts = []
if audio_pad.shape[0] > self.t_max:
audio_sum = np.zeros_like(audio)
for i in range(self.window):
audio_sum += audio_pad[i : i - self.window]
for t in range(self.t_center, audio.shape[0], self.t_center):
opt_ts.append(
t
- self.t_query
+ np.where(
np.abs(audio_sum[t - self.t_query : t + self.t_query])
== np.abs(audio_sum[t - self.t_query : t + self.t_query]).min()
)[0][0]
)
s = 0
audio_opt = []
t = None
t1 = ttime()
audio_pad = np.pad(audio, (self.t_pad, self.t_pad), mode="reflect")
p_len = audio_pad.shape[0] // self.window
inp_f0 = None
if hasattr(f0_file, "name") == True:
try:
with open(f0_file.name, "r") as f:
lines = f.read().strip("\n").split("\n")
inp_f0 = []
for line in lines:
inp_f0.append([float(i) for i in line.split(",")])
inp_f0 = np.array(inp_f0, dtype="float32")
except:
traceback.print_exc()
sid = torch.tensor(sid, device=self.device).unsqueeze(0).long()
pitch, pitchf = None, None
if if_f0 == 1:
pitch, pitchf = self.get_f0(
input_audio_path,
audio_pad,
p_len,
f0_up_key,
f0_method,
filter_radius,
inp_f0,
)
pitch = pitch[:p_len]
pitchf = pitchf[:p_len]
if self.device == "mps":
pitchf = pitchf.astype(np.float32)
pitch = torch.tensor(pitch, device=self.device).unsqueeze(0).long()
pitchf = torch.tensor(pitchf, device=self.device).unsqueeze(0).float()
t2 = ttime()
times[1] += t2 - t1
for t in opt_ts:
t = t // self.window * self.window
if if_f0 == 1:
audio_opt.append(
self.vc(
model,
net_g,
sid,
audio_pad[s : t + self.t_pad2 + self.window],
pitch[:, s // self.window : (t + self.t_pad2) // self.window],
pitchf[:, s // self.window : (t + self.t_pad2) // self.window],
times,
index,
big_npy,
index_rate,
version,
protect,
)[self.t_pad_tgt : -self.t_pad_tgt]
)
else:
audio_opt.append(
self.vc(
model,
net_g,
sid,
audio_pad[s : t + self.t_pad2 + self.window],
None,
None,
times,
index,
big_npy,
index_rate,
version,
protect,
)[self.t_pad_tgt : -self.t_pad_tgt]
)
s = t
if if_f0 == 1:
audio_opt.append(
self.vc(
model,
net_g,
sid,
audio_pad[t:],
pitch[:, t // self.window :] if t is not None else pitch,
pitchf[:, t // self.window :] if t is not None else pitchf,
times,
index,
big_npy,
index_rate,
version,
protect,
)[self.t_pad_tgt : -self.t_pad_tgt]
)
else:
audio_opt.append(
self.vc(
model,
net_g,
sid,
audio_pad[t:],
None,
None,
times,
index,
big_npy,
index_rate,
version,
protect,
)[self.t_pad_tgt : -self.t_pad_tgt]
)
audio_opt = np.concatenate(audio_opt)
if rms_mix_rate != 1:
audio_opt = change_rms(audio, 16000, audio_opt, tgt_sr, rms_mix_rate)
if resample_sr >= 16000 and tgt_sr != resample_sr:
audio_opt = librosa.resample(
audio_opt, orig_sr=tgt_sr, target_sr=resample_sr
)
audio_max = np.abs(audio_opt).max() / 0.99
max_int16 = 32768
if audio_max > 1:
max_int16 /= audio_max
audio_opt = (audio_opt * max_int16).astype(np.int16)
del pitch, pitchf, sid
if torch.cuda.is_available():
torch.cuda.empty_cache()
return audio_opt123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732from soni_translate.logging_setup import loggerimport torchimport gcimport numpy as npimport osimport shutilimport warningsimport threadingfrom tqdm import tqdmfrom lib.infer_pack.models import ( SynthesizerTrnMs256NSFsid, SynthesizerTrnMs256NSFsid_nono, SynthesizerTrnMs768NSFsid, SynthesizerTrnMs768NSFsid_nono,)from lib.audio import load_audioimport soundfile as sfimport edge_ttsimport asynciofrom soni_translate.utils import remove_directory_contents, create_directoriesfrom scipy import signalfrom time import time as ttimeimport faissfrom vci_pipeline import VC, change_rms, bh, ahimport librosa
warnings.filterwarnings("ignore")
class Config: def __init__(self, only_cpu=False): self.device = "cuda:0" self.is_half = True self.n_cpu = 0 self.gpu_name = None self.gpu_mem = None ( self.x_pad, self.x_query, self.x_center, self.x_max ) = self.device_config(only_cpu)
def device_config(self, only_cpu) -> tuple: if torch.cuda.is_available() and not only_cpu: i_device = int(self.device.split(":")[-1]) self.gpu_name = torch.cuda.get_device_name(i_device) if ( ("16" in self.gpu_name and "V100" not in self.gpu_name.upper()) or "P40" in self.gpu_name.upper() or "1060" in self.gpu_name or "1070" in self.gpu_name or "1080" in self.gpu_name ): logger.info( "16/10 Series GPUs and P40 excel " "in single-precision tasks." ) self.is_half = False else: self.gpu_name = None self.gpu_mem = int( torch.cuda.get_device_properties(i_device).total_memory / 1024 / 1024 / 1024 + 0.4 ) elif torch.backends.mps.is_available() and not only_cpu: logger.info("Supported N-card not found, using MPS for inference") self.device = "mps" else: logger.info("No supported N-card found, using CPU for inference") self.device = "cpu" self.is_half = False
if self.n_cpu == 0: self.n_cpu = os.cpu_count()
if self.is_half: # 6GB VRAM configuration x_pad = 3 x_query = 10 x_center = 60 x_max = 65 else: # 5GB VRAM configuration x_pad = 1 x_query = 6 x_center = 38 x_max = 41
if self.gpu_mem is not None and self.gpu_mem <= 4: x_pad = 1 x_query = 5 x_center = 30 x_max = 32
logger.info( f"Config: Device is {self.device}, " f"half precision is {self.is_half}" )
return x_pad, x_query, x_center, x_max
BASE_DOWNLOAD_LINK = "https://huggingface.co/r3gm/sonitranslate_voice_models/resolve/main/"BASE_MODELS = [ "hubert_base.pt", "rmvpe.pt"]BASE_DIR = "."
def load_hu_bert(config): from fairseq import checkpoint_utils from soni_translate.utils import download_manager
for id_model in BASE_MODELS: download_manager( os.path.join(BASE_DOWNLOAD_LINK, id_model), BASE_DIR )
models, _, _ = checkpoint_utils.load_model_ensemble_and_task( ["hubert_base.pt"], suffix="", ) hubert_model = models[0] hubert_model = hubert_model.to(config.device) if config.is_half: hubert_model = hubert_model.half() else: hubert_model = hubert_model.float() hubert_model.eval()
return hubert_model
def load_trained_model(model_path, config):
if not model_path: raise ValueError("No model found")
logger.info("Loading %s" % model_path) cpt = torch.load(model_path, map_location="cpu") tgt_sr = cpt["config"][-1] cpt["config"][-3] = cpt["weight"]["emb_g.weight"].shape[0] # n_spk if_f0 = cpt.get("f0", 1) if if_f0 == 0: # protect to 0.5 need? pass
version = cpt.get("version", "v1") if version == "v1": if if_f0 == 1: net_g = SynthesizerTrnMs256NSFsid( *cpt["config"], is_half=config.is_half ) else: net_g = SynthesizerTrnMs256NSFsid_nono(*cpt["config"]) elif version == "v2": if if_f0 == 1: net_g = SynthesizerTrnMs768NSFsid( *cpt["config"], is_half=config.is_half ) else: net_g = SynthesizerTrnMs768NSFsid_nono(*cpt["config"]) del net_g.enc_q
net_g.load_state_dict(cpt["weight"], strict=False) net_g.eval().to(config.device)
if config.is_half: net_g = net_g.half() else: net_g = net_g.float()
vc = VC(tgt_sr, config) n_spk = cpt["config"][-3]
return n_spk, tgt_sr, net_g, vc, cpt, version
class ClassVoices: def __init__(self, only_cpu=False): self.model_config = {} self.config = None self.only_cpu = only_cpu
def apply_conf( self, tag="base_model", file_model="", pitch_algo="pm", pitch_lvl=0, file_index="", index_influence=0.66, respiration_median_filtering=3, envelope_ratio=0.25, consonant_breath_protection=0.33, resample_sr=0, file_pitch_algo="", ):
if not file_model: raise ValueError("Model not found")
if file_index is None: file_index = ""
if file_pitch_algo is None: file_pitch_algo = ""
if not self.config: self.config = Config(self.only_cpu) self.hu_bert_model = None self.model_pitch_estimator = None
self.model_config[tag] = { "file_model": file_model, "pitch_algo": pitch_algo, "pitch_lvl": pitch_lvl, # no decimal "file_index": file_index, "index_influence": index_influence, "respiration_median_filtering": respiration_median_filtering, "envelope_ratio": envelope_ratio, "consonant_breath_protection": consonant_breath_protection, "resample_sr": resample_sr, "file_pitch_algo": file_pitch_algo, } return f"CONFIGURATION APPLIED FOR {tag}: {file_model}"
def infer( self, task_id, params, # load model n_spk, tgt_sr, net_g, pipe, cpt, version, if_f0, # load index index_rate, index, big_npy, # load f0 file inp_f0, # audio file input_audio_path, overwrite, ):
f0_method = params["pitch_algo"] f0_up_key = params["pitch_lvl"] filter_radius = params["respiration_median_filtering"] resample_sr = params["resample_sr"] rms_mix_rate = params["envelope_ratio"] protect = params["consonant_breath_protection"]
if not os.path.exists(input_audio_path): raise ValueError( "The audio file was not found or is not " f"a valid file: {input_audio_path}" )
f0_up_key = int(f0_up_key)
audio = load_audio(input_audio_path, 16000)
# Normalize audio audio_max = np.abs(audio).max() / 0.95 if audio_max > 1: audio /= audio_max
times = [0, 0, 0]
# filters audio signal, pads it, computes sliding window sums, # and extracts optimized time indices audio = signal.filtfilt(bh, ah, audio) audio_pad = np.pad( audio, (pipe.window // 2, pipe.window // 2), mode="reflect" ) opt_ts = [] if audio_pad.shape[0] > pipe.t_max: audio_sum = np.zeros_like(audio) for i in range(pipe.window): audio_sum += audio_pad[i:i - pipe.window] for t in range(pipe.t_center, audio.shape[0], pipe.t_center): opt_ts.append( t - pipe.t_query + np.where( np.abs(audio_sum[t - pipe.t_query: t + pipe.t_query]) == np.abs(audio_sum[t - pipe.t_query: t + pipe.t_query]).min() )[0][0] )
s = 0 audio_opt = [] t = None t1 = ttime()
sid_value = 0 sid = torch.tensor(sid_value, device=pipe.device).unsqueeze(0).long()
# Pads audio symmetrically, calculates length divided by window size. audio_pad = np.pad(audio, (pipe.t_pad, pipe.t_pad), mode="reflect") p_len = audio_pad.shape[0] // pipe.window
# Estimates pitch from audio signal pitch, pitchf = None, None if if_f0 == 1: pitch, pitchf = pipe.get_f0( input_audio_path, audio_pad, p_len, f0_up_key, f0_method, filter_radius, inp_f0, ) pitch = pitch[:p_len] pitchf = pitchf[:p_len] if pipe.device == "mps": pitchf = pitchf.astype(np.float32) pitch = torch.tensor( pitch, device=pipe.device ).unsqueeze(0).long() pitchf = torch.tensor( pitchf, device=pipe.device ).unsqueeze(0).float()
t2 = ttime() times[1] += t2 - t1 for t in opt_ts: t = t // pipe.window * pipe.window if if_f0 == 1: pitch_slice = pitch[ :, s // pipe.window: (t + pipe.t_pad2) // pipe.window ] pitchf_slice = pitchf[ :, s // pipe.window: (t + pipe.t_pad2) // pipe.window ] else: pitch_slice = None pitchf_slice = None
audio_slice = audio_pad[s:t + pipe.t_pad2 + pipe.window] audio_opt.append( pipe.vc( self.hu_bert_model, net_g, sid, audio_slice, pitch_slice, pitchf_slice, times, index, big_npy, index_rate, version, protect, )[pipe.t_pad_tgt:-pipe.t_pad_tgt] ) s = t
pitch_end_slice = pitch[ :, t // pipe.window: ] if t is not None else pitch pitchf_end_slice = pitchf[ :, t // pipe.window: ] if t is not None else pitchf
audio_opt.append( pipe.vc( self.hu_bert_model, net_g, sid, audio_pad[t:], pitch_end_slice, pitchf_end_slice, times, index, big_npy, index_rate, version, protect, )[pipe.t_pad_tgt:-pipe.t_pad_tgt] )
audio_opt = np.concatenate(audio_opt) if rms_mix_rate != 1: audio_opt = change_rms( audio, 16000, audio_opt, tgt_sr, rms_mix_rate ) if resample_sr >= 16000 and tgt_sr != resample_sr: audio_opt = librosa.resample( audio_opt, orig_sr=tgt_sr, target_sr=resample_sr ) audio_max = np.abs(audio_opt).max() / 0.99 max_int16 = 32768 if audio_max > 1: max_int16 /= audio_max audio_opt = (audio_opt * max_int16).astype(np.int16) del pitch, pitchf, sid if torch.cuda.is_available(): torch.cuda.empty_cache()
if tgt_sr != resample_sr >= 16000: final_sr = resample_sr else: final_sr = tgt_sr
""" "Success.\n %s\nTime:\n npy:%ss, f0:%ss, infer:%ss" % ( times[0], times[1], times[2], ), (final_sr, audio_opt)
"""
if overwrite: output_audio_path = input_audio_path # Overwrite else: basename = os.path.basename(input_audio_path) dirname = os.path.dirname(input_audio_path)
new_basename = basename.split( '.')[0] + "_edited." + basename.split('.')[-1] new_path = os.path.join(dirname, new_basename) logger.info(str(new_path))
output_audio_path = new_path
# Save file sf.write( file=output_audio_path, samplerate=final_sr, data=audio_opt )
self.model_config[task_id]["result"].append(output_audio_path) self.output_list.append(output_audio_path)
def make_test( self, tts_text, tts_voice, model_path, index_path, transpose, f0_method, ):
folder_test = "test" tag = "test_edge" tts_file = "test/test.wav" tts_edited = "test/test_edited.wav"
create_directories(folder_test) remove_directory_contents(folder_test)
if "SET_LIMIT" == os.getenv("DEMO"): if len(tts_text) > 60: tts_text = tts_text[:60] logger.warning("DEMO; limit to 60 characters")
try: asyncio.run(edge_tts.Communicate( tts_text, "-".join(tts_voice.split('-')[:-1]) ).save(tts_file)) except Exception as e: raise ValueError( "No audio was received. Please change the " f"tts voice for {tts_voice}. Error: {str(e)}" )
shutil.copy(tts_file, tts_edited)
self.apply_conf( tag=tag, file_model=model_path, pitch_algo=f0_method, pitch_lvl=transpose, file_index=index_path, index_influence=0.66, respiration_median_filtering=3, envelope_ratio=0.25, consonant_breath_protection=0.33, )
self( audio_files=tts_edited, tag_list=tag, overwrite=True )
return tts_edited, tts_file
def run_threads(self, threads): # Start threads for thread in threads: thread.start()
# Wait for all threads to finish for thread in threads: thread.join()
gc.collect() torch.cuda.empty_cache()
def unload_models(self): self.hu_bert_model = None self.model_pitch_estimator = None gc.collect() torch.cuda.empty_cache()
def __call__( self, audio_files=[], tag_list=[], overwrite=False, parallel_workers=1, ): logger.info(f"Parallel workers: {str(parallel_workers)}")
self.output_list = []
if not self.model_config: raise ValueError("No model has been configured for inference")
if isinstance(audio_files, str): audio_files = [audio_files] if isinstance(tag_list, str): tag_list = [tag_list]
if not audio_files: raise ValueError("No audio found to convert") if not tag_list: tag_list = [list(self.model_config.keys())[-1]] * len(audio_files)
if len(audio_files) > len(tag_list): logger.info("Extend tag list to match audio files") extend_number = len(audio_files) - len(tag_list) tag_list.extend([tag_list[0]] * extend_number)
if len(audio_files) < len(tag_list): logger.info("Cut list tags") tag_list = tag_list[:len(audio_files)]
tag_file_pairs = list(zip(tag_list, audio_files)) sorted_tag_file = sorted(tag_file_pairs, key=lambda x: x[0])
# Base params if not self.hu_bert_model: self.hu_bert_model = load_hu_bert(self.config)
cache_params = None threads = [] progress_bar = tqdm(total=len(tag_list), desc="Progress") for i, (id_tag, input_audio_path) in enumerate(sorted_tag_file):
if id_tag not in self.model_config.keys(): logger.info( f"No configured model for {id_tag} with {input_audio_path}" ) continue
if ( len(threads) >= parallel_workers or cache_params != id_tag and cache_params is not None ):
self.run_threads(threads) progress_bar.update(len(threads))
threads = []
if cache_params != id_tag:
self.model_config[id_tag]["result"] = []
# Unload previous ( n_spk, tgt_sr, net_g, pipe, cpt, version, if_f0, index_rate, index, big_npy, inp_f0, ) = [None] * 11 gc.collect() torch.cuda.empty_cache()
# Model params params = self.model_config[id_tag]
model_path = params["file_model"] f0_method = params["pitch_algo"] file_index = params["file_index"] index_rate = params["index_influence"] f0_file = params["file_pitch_algo"]
# Load model ( n_spk, tgt_sr, net_g, pipe, cpt, version ) = load_trained_model(model_path, self.config) if_f0 = cpt.get("f0", 1) # pitch data
# Load index if os.path.exists(file_index) and index_rate != 0: try: index = faiss.read_index(file_index) big_npy = index.reconstruct_n(0, index.ntotal) except Exception as error: logger.error(f"Index: {str(error)}") index_rate = 0 index = big_npy = None else: logger.warning("File index not found") index_rate = 0 index = big_npy = None
# Load f0 file inp_f0 = None if os.path.exists(f0_file): try: with open(f0_file, "r") as f: lines = f.read().strip("\n").split("\n") inp_f0 = [] for line in lines: inp_f0.append([float(i) for i in line.split(",")]) inp_f0 = np.array(inp_f0, dtype="float32") except Exception as error: logger.error(f"f0 file: {str(error)}")
if "rmvpe" in f0_method: if not self.model_pitch_estimator: from lib.rmvpe import RMVPE
logger.info("Loading vocal pitch estimator model") self.model_pitch_estimator = RMVPE( "rmvpe.pt", is_half=self.config.is_half, device=self.config.device )
pipe.model_rmvpe = self.model_pitch_estimator
cache_params = id_tag
# self.infer( # id_tag, # params, # # load model # n_spk, # tgt_sr, # net_g, # pipe, # cpt, # version, # if_f0, # # load index # index_rate, # index, # big_npy, # # load f0 file # inp_f0, # # output file # input_audio_path, # overwrite, # )
thread = threading.Thread( target=self.infer, args=( id_tag, params, # loaded model n_spk, tgt_sr, net_g, pipe, cpt, version, if_f0, # loaded index index_rate, index, big_npy, # loaded f0 file inp_f0, # audio file input_audio_path, overwrite, ) )
threads.append(thread)
# Run last if threads: self.run_threads(threads)
progress_bar.update(len(threads)) progress_bar.close()
final_result = [] valid_tags = set(tag_list) for tag in valid_tags: if ( tag in self.model_config.keys() and "result" in self.model_config[tag].keys() ): final_result.extend(self.model_config[tag]["result"])
return final_result.gitignoreAdded+214
LICENSEAdded+201
SoniTranslate_Colab.ipynbAdded+124
app.pyAdded+2
app_rvc.pyAdded
assets/logo.jpegAdded

docs/windows_install.mdAdded+150
lib/audio.pyAdded+21
lib/infer_pack/attentions.pyAdded+417
lib/infer_pack/commons.pyAdded+166
lib/infer_pack/models.pyAdded+1142
lib/infer_pack/modules.pyAdded+522
lib/infer_pack/transforms.pyAdded+209
lib/rmvpe.pyAdded+422
mdx_models/data.jsonAdded+354
packages.txtAdded+3
pre-requirements.txtAdded+15
requirements.txtAdded+19
requirements_xtts.txtAdded+58
soni_translate/audio_segments.pyAdded+141
soni_translate/language_configuration.pyAdded+551
soni_translate/languages_gui.pyAdded
soni_translate/logging_setup.pyAdded+68
soni_translate/mdx_net.pyAdded+582
soni_translate/postprocessor.pyAdded+229
soni_translate/preprocessor.pyAdded+308
soni_translate/speech_segmentation.pyAdded+499
soni_translate/text_multiformat_processor.pyAdded+987
soni_translate/text_to_speech.pyAdded+1574
soni_translate/translate_segments.pyAdded+457
soni_translate/utils.pyAdded+487
vci_pipeline.pyAdded+454
voice_main.pyAdded+732