forked from Tera2Space/TeraTTS
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
0 parents
commit 3ba346d
Showing
12 changed files
with
378 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
__pycache__/ | ||
*.py[cod] | ||
*.pyc | ||
*.so | ||
*.wav | ||
|
||
build/ | ||
dist/ | ||
RUTTS.egg-info | ||
model/ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
Copyright 2023 TeraSpace | ||
|
||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: | ||
|
||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. | ||
|
||
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,11 @@ | ||
git: | ||
git add . | ||
git commit -m "update" | ||
git push -u -f origin main | ||
|
||
pypi: | ||
rm -r ./build | ||
rm -r ./dist | ||
rm -r RUTTS.egg-info | ||
python setup.py sdist bdist_wheel | ||
twine upload dist/* |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,52 @@ | ||
# Russian TTS inference | ||
# Установка | ||
Вы можете установить пакет с помощью pip: | ||
``` | ||
pip install TeraTTS | ||
``` | ||
Также вы можете установить используя Git: | ||
``` | ||
pip install -e git+https://github.com/Tera2Space/RUTTS#egg=TeraTTS | ||
``` | ||
# Ошибки | ||
1)Если на Windows у вас **ошибка при установке**,нужно просто **скачать Visual Studio [здесь](https://visualstudio.microsoft.com/ru/thank-you-downloading-visual-studio/?sku=Community&channel=Release&version=VS2022&source=VSLandingPage&cid=2030&passive=false)** и при установке выбрать галочку около **Разработка классических приложений на С++** | ||
|
||
2)Если **после установки не работает** что-то, **убедитесь что модуль скачан последней версии**(удалить и скачать) и **так же что названия моделей есть на** https://huggingface.co/TeraTTS | ||
|
||
3)Если ничего не помогло **обратитесь за помощью в https://t.me/teraspace_chat** | ||
# Использование | ||
|
||
```python | ||
text = "Привет, мир!" | ||
|
||
from TeraTTS import TTS | ||
|
||
# Опционально: Предобработка текста (улучшает качество) | ||
from ruaccent import RUAccent | ||
accentizer = RUAccent(workdir="./model") | ||
|
||
# Загрузка моделей акцентуации и словарей | ||
# Доступны две модели: 'medium' (рекомендуется) и 'small'. | ||
# Переменная 'dict_load_startup' управляет загрузкой словаря при запуске (больше памяти) или загрузкой его по мере необходимости во время выполнения (экономия памяти, но медленнее). | ||
# Переменная disable_accent_dict отключает использование словаря (все ударения расставляет нейросеть). Данная функция экономит ОЗУ, по скорости работы сопоставима со всем словарём в ОЗУ. | ||
accentizer.load(omograph_model_size='big_poetry', use_dictionary=True) | ||
|
||
# Обработка текста с учетом ударений и буквы ё | ||
text = accentizer.process_all(text) | ||
print(f"Текст с ударениями и ё: {text}") | ||
|
||
|
||
# Примечание: Вы можете найти все модели по адресу https://huggingface.co/TeraTTS, включая модель GLADOS | ||
tts = TTS("TeraTTS/natasha-g2p-vits", add_time_to_end=1.0, tokenizer_load_dict=True) # Вы можете настроить 'add_time_to_end' для продолжительности аудио, 'tokenizer_load_dict' можно отключить если используете RUAccent | ||
|
||
|
||
# 'length_scale' можно использовать для замедления аудио для лучшего звучания (по умолчанию 1.1, указано здесь для примера) | ||
audio = tts(text, lenght_scale=1.1) # Создать аудио. Можно добавить ударения, используя '+' | ||
tts.play_audio(audio) # Воспроизвести созданное аудио | ||
tts.save_wav(audio, "./test.wav") # Сохранить аудио в файл | ||
|
||
|
||
# Создать аудио и сразу его воспроизвести | ||
tts(text, play=True, lenght_scale=1.1) | ||
|
||
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
from .infer_onnx import TTS | ||
from .tokenizer import TokenizerG2P |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,92 @@ | ||
import scipy.io.wavfile | ||
import os | ||
import sounddevice as sd | ||
import onnxruntime | ||
import numpy as np | ||
from huggingface_hub import snapshot_download | ||
from num2words import num2words | ||
import re | ||
from transliterate import translit | ||
from .tokenizer import TokenizerG2P | ||
|
||
class TTS: | ||
def __init__(self, model_name: str, save_path: str = "./model", add_time_to_end: float = 1.0, preprocess_nums=True, preprocess_trans=True, tokenizer_load_dict=True) -> None: | ||
if not os.path.exists(save_path): | ||
os.mkdir(save_path) | ||
|
||
model_dir = os.path.join(save_path, model_name) | ||
|
||
if not os.path.exists(model_dir): | ||
snapshot_download(repo_id=model_name, | ||
allow_patterns=["*.txt", "*.onnx", "*.json"], | ||
local_dir=model_dir, | ||
local_dir_use_symlinks=False | ||
) | ||
|
||
self.model = onnxruntime.InferenceSession(os.path.join(model_dir, "exported/model.onnx"), providers=['CPUExecutionProvider']) | ||
self.preprocess_nums = preprocess_nums | ||
self.preprocess_trans = preprocess_trans | ||
|
||
self.tokenizer = TokenizerG2P(os.path.join(model_dir, "exported"), load_dict=tokenizer_load_dict) | ||
|
||
self.add_time_to_end = add_time_to_end | ||
|
||
|
||
def _add_silent(self, audio, silence_duration: float = 1.0, sample_rate: int = 22050): | ||
num_samples_silence = int(sample_rate * silence_duration) | ||
silence_array = np.zeros(num_samples_silence, dtype=np.float32) | ||
audio_with_silence = np.concatenate((audio, silence_array), axis=0) | ||
return audio_with_silence | ||
|
||
|
||
def save_wav(self, audio, path:str): | ||
'''save audio to wav''' | ||
scipy.io.wavfile.write(path, 22050, audio) | ||
|
||
|
||
def play_audio(self, audio): | ||
sd.play(audio, 22050, blocking=True) | ||
|
||
|
||
def _intersperse(self, lst, item): | ||
result = [item] * (len(lst) * 2 + 1) | ||
result[1::2] = lst | ||
return result | ||
|
||
|
||
def _get_seq(self, text): | ||
phoneme_ids = self.tokenizer._get_seq(text) | ||
phoneme_ids_inter = self._intersperse(phoneme_ids, 0) | ||
return phoneme_ids_inter | ||
|
||
def _num2wordsshor(self, match): | ||
match = match.group() | ||
ret = num2words(match, lang ='ru') | ||
return ret | ||
|
||
def __call__(self, text: str, play = False, lenght_scale=1.2): | ||
if self.preprocess_trans: | ||
text = translit(text, 'ru') | ||
|
||
if self.preprocess_nums: | ||
text = re.sub(r'\d+',self._num2wordsshor,text) | ||
phoneme_ids = self._get_seq(text) | ||
text = np.expand_dims(np.array(phoneme_ids, dtype=np.int64), 0) | ||
text_lengths = np.array([text.shape[1]], dtype=np.int64) | ||
scales = np.array( | ||
[0.667, lenght_scale, 0.8], | ||
dtype=np.float32, | ||
) | ||
audio = self.model.run( | ||
None, | ||
{ | ||
"input": text, | ||
"input_lengths": text_lengths, | ||
"scales": scales, | ||
"sid": None, | ||
}, | ||
)[0][0,0][0] | ||
audio = self._add_silent(audio, silence_duration = self.add_time_to_end) | ||
if play: | ||
self.play_audio(audio) | ||
return audio |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
from .g2p import Tokenizer as TokenizerG2P |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
from .tokenizer import Tokenizer |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,94 @@ | ||
|
||
softletters=set(u"яёюиье") | ||
startsyl=set(u"#ъьаяоёуюэеиы-") | ||
others = set(["#", "+", "-", u"ь", u"ъ"]) | ||
|
||
softhard_cons = { | ||
u"б" : u"b", | ||
u"в" : u"v", | ||
u"г" : u"g", | ||
u"Г" : u"g", | ||
u"д" : u"d", | ||
u"з" : u"z", | ||
u"к" : u"k", | ||
u"л" : u"l", | ||
u"м" : u"m", | ||
u"н" : u"n", | ||
u"п" : u"p", | ||
u"р" : u"r", | ||
u"с" : u"s", | ||
u"т" : u"t", | ||
u"ф" : u"f", | ||
u"х" : u"h" | ||
} | ||
|
||
other_cons = { | ||
u"ж" : u"zh", | ||
u"ц" : u"c", | ||
u"ч" : u"ch", | ||
u"ш" : u"sh", | ||
u"щ" : u"sch", | ||
u"й" : u"j" | ||
} | ||
|
||
vowels = { | ||
u"а" : u"a", | ||
u"я" : u"a", | ||
u"у" : u"u", | ||
u"ю" : u"u", | ||
u"о" : u"o", | ||
u"ё" : u"o", | ||
u"э" : u"e", | ||
u"е" : u"e", | ||
u"и" : u"i", | ||
u"ы" : u"y", | ||
} | ||
|
||
def pallatize(phones): | ||
for i, phone in enumerate(phones[:-1]): | ||
if phone[0] in softhard_cons: | ||
if phones[i+1][0] in softletters: | ||
phones[i] = (softhard_cons[phone[0]] + "j", 0) | ||
else: | ||
phones[i] = (softhard_cons[phone[0]], 0) | ||
if phone[0] in other_cons: | ||
phones[i] = (other_cons[phone[0]], 0) | ||
|
||
def convert_vowels(phones): | ||
new_phones = [] | ||
prev = "" | ||
for phone in phones: | ||
if prev in startsyl: | ||
if phone[0] in set(u"яюеё"): | ||
new_phones.append("j") | ||
if phone[0] in vowels: | ||
new_phones.append(vowels[phone[0]] + str(phone[1])) | ||
else: | ||
new_phones.append(phone[0]) | ||
prev = phone[0] | ||
|
||
return new_phones | ||
|
||
def convert(stressword): | ||
phones = ("#" + stressword + "#") | ||
|
||
|
||
# Assign stress marks | ||
stress_phones = [] | ||
stress = 0 | ||
for phone in phones: | ||
if phone == "+": | ||
stress = 1 | ||
else: | ||
stress_phones.append((phone, stress)) | ||
stress = 0 | ||
|
||
# Pallatize | ||
pallatize(stress_phones) | ||
|
||
# Assign stress | ||
phones = convert_vowels(stress_phones) | ||
|
||
# Filter | ||
phones = [x for x in phones if x not in others] | ||
return " ".join(phones) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,50 @@ | ||
import re | ||
from .g2p import * #noqa | ||
import json | ||
import os | ||
|
||
class Tokenizer(): | ||
def __init__(self, data_path: str, load_dict=True) -> None: | ||
'''data_path - path to data dir; load_dict - load dict, if you use accent model like ruaccent you dont need its''' | ||
self.dic = {} | ||
if load_dict: | ||
for line in open(os.path.join(data_path, "dictionary.txt")): #noqa | ||
items = line.split() | ||
self.dic[items[0]] = " ".join(items[1:]) | ||
|
||
self.config = json.load(open(os.path.join(data_path, "config.json"))) #noqa | ||
|
||
def g2p(self, text): | ||
text = re.sub("—", "-", text) | ||
text = re.sub("([!'(),-.:;?])", r' \1 ', text) | ||
|
||
phonemes = [] | ||
for word in text.split(): | ||
if re.match("[!'(),-.:;?]", word): | ||
phonemes.append(word) | ||
continue | ||
|
||
word = word.lower() | ||
if len(phonemes) > 0: | ||
phonemes.append(' ') | ||
|
||
if word in self.dic: | ||
phonemes.extend(self.dic[word].split()) | ||
else: | ||
phonemes.extend(convert(word).split()) #noqa | ||
|
||
phoneme_id_map = self.config["phoneme_id_map"] | ||
phoneme_ids = [] | ||
phoneme_ids.extend(phoneme_id_map["^"]) | ||
phoneme_ids.extend(phoneme_id_map["_"]) | ||
for p in phonemes: | ||
if p in phoneme_id_map: | ||
phoneme_ids.extend(phoneme_id_map[p]) | ||
phoneme_ids.extend(phoneme_id_map["_"]) | ||
phoneme_ids.extend(phoneme_id_map["$"]) | ||
|
||
return phoneme_ids, phonemes | ||
|
||
def _get_seq(self, text: str) -> list[int]: | ||
seq = self.g2p(text)[0] | ||
return seq |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,31 @@ | ||
text = "Привет, мир!" | ||
|
||
from TeraTTS import TTS | ||
|
||
# Опционально: Предобработка текста (улучшает качество) | ||
from ruaccent import RUAccent | ||
accentizer = RUAccent(workdir="./model") | ||
|
||
# Загрузка моделей акцентуации и словарей | ||
# Доступны две модели: 'medium' (рекомендуется) и 'small'. | ||
# Переменная 'dict_load_startup' управляет загрузкой словаря при запуске (больше памяти) или загрузкой его по мере необходимости во время выполнения (экономия памяти, но медленнее). | ||
# Переменная disable_accent_dict отключает использование словаря (все ударения расставляет нейросеть). Данная функция экономит ОЗУ, по скорости работы сопоставима со всем словарём в ОЗУ. | ||
accentizer.load(omograph_model_size='big_poetry', use_dictionary=True) | ||
|
||
# Обработка текста с учетом ударений и буквы ё | ||
text = accentizer.process_all(text) | ||
print(f"Текст с ударениями и ё: {text}") | ||
|
||
|
||
# Примечание: Вы можете найти все модели по адресу https://huggingface.co/TeraTTS, включая модель GLADOS | ||
tts = TTS("TeraTTS/natasha-g2p-vits", add_time_to_end=1.0, tokenizer_load_dict=True) # Вы можете настроить 'add_time_to_end' для продолжительности аудио, 'tokenizer_load_dict' можно отключить если используете RUAccent | ||
|
||
|
||
# 'length_scale' можно использовать для замедления аудио для лучшего звучания (по умолчанию 1.1, указано здесь для примера) | ||
audio = tts(text, lenght_scale=1.1) # Создать аудио. Можно добавить ударения, используя '+' | ||
tts.play_audio(audio) # Воспроизвести созданное аудио | ||
tts.save_wav(audio, "./test.wav") # Сохранить аудио в файл | ||
|
||
|
||
# Создать аудио и сразу его воспроизвести | ||
tts(text, play=True, lenght_scale=1.1) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
from setuptools import setup, find_packages | ||
|
||
classifiers = [ | ||
'Development Status :: 5 - Production/Stable', | ||
'Intended Audience :: Education', | ||
'Operating System :: Microsoft :: Windows', | ||
'Operating System :: Unix', | ||
'Operating System :: MacOS', | ||
'License :: OSI Approved :: MIT License', | ||
'Programming Language :: Python :: 3' | ||
] | ||
|
||
setup( | ||
name='TeraTTS', | ||
version='1.0', | ||
description='russian text to speech', | ||
long_description=open("./README.md").read(), | ||
long_description_content_type='text/markdown', | ||
url='https://github.com/Tera2Space/TeraTTS', | ||
author='Tera Space', | ||
author_email='[email protected]', | ||
license='MIT', | ||
classifiers=classifiers, | ||
keywords='tts', | ||
packages=find_packages(), | ||
install_requires=['scipy', 'sounddevice', 'onnxruntime', "tok", "transformers", "numpy", "sentencepiece", "ruaccent", "transliterate", "num2words"] | ||
) |