mirror of
https://github.com/index-tts/index-tts.git
synced 2025-11-28 10:20:24 +08:00
* fix: Configure "uv" build system to use CUDA on supported platforms
- Linux builds of PyTorch always have CUDA acceleration built-in, but Windows only has it if we request a CUDA build.
- The built-in CUDA on Linux uses old libraries and can be slow.
- We now request PyTorch built for the most modern CUDA Toolkit on Linux + Windows, to solve both problems.
- Mac uses PyTorch without CUDA support, since it doesn't exist on that platform.
- Other dependencies have received new releases and are included in this fix too:
* click was downgraded because the author revoked 8.2.2 due to a bug.
* wetext received a new release now.
* fix: Use PyPI as the hashing reference in "uv" lockfile
- PyPI is the most trustworthy source for package hashes. We need to remove the custom mirror from the config, otherwise that mirror always becomes the default lockfile/package source, which leads to user trust issues and package impersonation risks.
- Regional mirrors should be added by users during installation instead, via the `uv sync --default-index` flag. Documented with example for Chinese mirror.
- When users add `--default-index`, "uv" will try to discover the exact same packages via the mirror to improve download speeds, but automatically uses PyPI if the mirror didn't have the files or if the mirror's file hashes were incorrect. Thus ensuring that users always have the correct package files.
* docs: Improve README for IndexTTS2 release!
- "Abstract" separated into paragraphs for easier readability.
- Clearer document structure and many grammatical improvements.
- More emojis, to make it easier to find sections when scrolling through the page!
- Added missing instructions:
* Needing `git-lfs` to clone the code.
* Needing CUDA Toolkit to install the dependencies.
* How to install the `hf` or `modelscope` CLI tools to download the models.
- Made our web demo the first section within "quickstart", to give users a quick, fun demo to start experimenting with.
- Fixed a bug in the "PYTHONPATH" recommendation. It must be enclosed in quotes `""`, otherwise the new path would break on systems that had spaces in their original path.
- Improved all Python code-example descriptions to make them much easier to understand.
- Clearly marked the IndexTTS1 legacy section as "legacy" to avoid confusion.
- Removed outdated Windows "conda/pip" instruction which is no longer relevant since we use "uv" now.
* refactor(webui): Remove unused imports
The old IndexTTS1 module and ModelScope were being loaded even though we don't need them. They also have a lot of dependencies, which slowed down loading and could even cause some conflicts.
* feat!: Remove obsolete build system (setup.py)
BREAKING CHANGE: The `setup.py` file has been removed.
Users should now use the new `pyproject.toml` based "uv" build system for installing and developing the project.
* feat: Add support for installing IndexTTS as a CLI tool
- We now support installing as a CLI tool via "uv".
- Uses the modern "hatchling" as the package / CLI build system.
- The `cli.py` code is currently outdated (doesn't support IndexTTS2). Marking as a TODO.
* chore: Add authors and classifiers metadata to pyproject.toml
* feat: Faster installs by making WebUI dependencies optional
* refactor!: Rename "sentences" to "segments" for clarity
- When we are splitting text into generation chunks, we are *not* creating "sentences". We are creating "segments". Because a *sentence* must always end with punctuation (".!?" etc). A *segment* can be a small fragment of a sentence, without any punctuation, so it's not accurate (and was very misleading) to use the word "sentences".
- All variables, function calls and strings have been carefully analyzed and renamed.
- This change will be part of user-facing code via a new feature, which is why the change was applied to the entire codebase.
- This change also helps future code contributors understand the code.
- All affected features are fully tested and work correctly after this refactoring.
- The `is_fp16` parameter has also been renamed to `use_fp16` since the previous name could confuse people ("is" implies an automatic check, "use" implies a user decision to enable/disable FP16).
- `cli.py`'s "--fp16" default value has been set to False, exactly like the web UI.
- `webui.py`'s "--is_fp16" flag has been changed to "--fp16" for easier usage and consistency with the CLI program, and the help-description has been improved.
* feat(webui): Set "max tokens per generation segment" via CLI flag
- The "Max tokens per generation segment" is a critical setting, as it directly impacts VRAM usage. Since the optimal value varies significantly based on a user's GPU, it is a frequent point of adjustment to prevent out-of-memory issues.
- This change allows the default value to be set via a CLI flag. Users can now conveniently start the web UI with the correct setting for their system, eliminating the need to manually reconfigure the value on every restart.
- The `webui.py -h` help text has also been enhanced to automatically display the default values for all CLI settings.
* refactor(i18n): Improve clarity of all web UI translation strings
* feat(webui): Use main text as emotion guidance when description is empty
If the user selects "text-to-emotion" control, but leaves the emotion description empty, we now automatically use the main text prompt instead.
This ensures that web users can enjoy every feature of IndexTTS2, including the ability to automatically guess the emotion from the main text prompt.
* feat: Add PyTorch GPU acceleration diagnostic tool
* chore: Use NVIDIA CUDA Toolkit v12.8
Downgrade from CUDA 12.9 to 12.8 to simplify user installation, since version 12.8 is very popular.
* docs: Simplify "uv run" command examples
The "uv run" command can take a `.py` file as direct argument and automatically understands that it should run via python.
194 lines
No EOL
5.6 KiB
Python
194 lines
No EOL
5.6 KiB
Python
import re
|
||
import json
|
||
import numpy as np
|
||
|
||
|
||
def get_hparams_from_file(config_path):
|
||
with open(config_path, "r", encoding="utf-8") as f:
|
||
data = f.read()
|
||
config = json.loads(data)
|
||
|
||
hparams = HParams(**config)
|
||
return hparams
|
||
|
||
class HParams:
|
||
def __init__(self, **kwargs):
|
||
for k, v in kwargs.items():
|
||
if type(v) == dict:
|
||
v = HParams(**v)
|
||
self[k] = v
|
||
|
||
def keys(self):
|
||
return self.__dict__.keys()
|
||
|
||
def items(self):
|
||
return self.__dict__.items()
|
||
|
||
def values(self):
|
||
return self.__dict__.values()
|
||
|
||
def __len__(self):
|
||
return len(self.__dict__)
|
||
|
||
def __getitem__(self, key):
|
||
return getattr(self, key)
|
||
|
||
def __setitem__(self, key, value):
|
||
return setattr(self, key, value)
|
||
|
||
def __contains__(self, key):
|
||
return key in self.__dict__
|
||
|
||
def __repr__(self):
|
||
return self.__dict__.__repr__()
|
||
|
||
|
||
def string_to_bits(string, pad_len=8):
|
||
# Convert each character to its ASCII value
|
||
ascii_values = [ord(char) for char in string]
|
||
|
||
# Convert ASCII values to binary representation
|
||
binary_values = [bin(value)[2:].zfill(8) for value in ascii_values]
|
||
|
||
# Convert binary strings to integer arrays
|
||
bit_arrays = [[int(bit) for bit in binary] for binary in binary_values]
|
||
|
||
# Convert list of arrays to NumPy array
|
||
numpy_array = np.array(bit_arrays)
|
||
numpy_array_full = np.zeros((pad_len, 8), dtype=numpy_array.dtype)
|
||
numpy_array_full[:, 2] = 1
|
||
max_len = min(pad_len, len(numpy_array))
|
||
numpy_array_full[:max_len] = numpy_array[:max_len]
|
||
return numpy_array_full
|
||
|
||
|
||
def bits_to_string(bits_array):
|
||
# Convert each row of the array to a binary string
|
||
binary_values = [''.join(str(bit) for bit in row) for row in bits_array]
|
||
|
||
# Convert binary strings to ASCII values
|
||
ascii_values = [int(binary, 2) for binary in binary_values]
|
||
|
||
# Convert ASCII values to characters
|
||
output_string = ''.join(chr(value) for value in ascii_values)
|
||
|
||
return output_string
|
||
|
||
|
||
def split_segment(text, min_len=10, language_str='[EN]'):
|
||
if language_str in ['EN']:
|
||
segments = split_segments_latin(text, min_len=min_len)
|
||
else:
|
||
segments = split_segments_zh(text, min_len=min_len)
|
||
return segments
|
||
|
||
def split_segments_latin(text, min_len=10):
|
||
"""Split Long sentences into list of short segments.
|
||
|
||
Args:
|
||
str: Input sentences.
|
||
|
||
Returns:
|
||
List[str]: list of output segments.
|
||
"""
|
||
# deal with dirty text characters
|
||
text = re.sub('[。!?;]', '.', text)
|
||
text = re.sub('[,]', ',', text)
|
||
text = re.sub('[“”]', '"', text)
|
||
text = re.sub('[‘’]', "'", text)
|
||
text = re.sub(r"[\<\>\(\)\[\]\"\«\»]+", "", text)
|
||
text = re.sub('[\n\t ]+', ' ', text)
|
||
text = re.sub('([,.!?;])', r'\1 $#!', text)
|
||
# split
|
||
segments = [s.strip() for s in text.split('$#!')]
|
||
if len(segments[-1]) == 0: del segments[-1]
|
||
|
||
new_segments = []
|
||
new_sent = []
|
||
count_len = 0
|
||
for ind, sent in enumerate(segments):
|
||
# print(sent)
|
||
new_sent.append(sent)
|
||
count_len += len(sent.split(" "))
|
||
if count_len > min_len or ind == len(segments) - 1:
|
||
count_len = 0
|
||
new_segments.append(' '.join(new_sent))
|
||
new_sent = []
|
||
return merge_short_segments_latin(new_segments)
|
||
|
||
|
||
def merge_short_segments_latin(sens):
|
||
"""Avoid short segments by merging them with the following segment.
|
||
|
||
Args:
|
||
List[str]: list of input segments.
|
||
|
||
Returns:
|
||
List[str]: list of output segments.
|
||
"""
|
||
sens_out = []
|
||
for s in sens:
|
||
# If the previous segment is too short, merge them with
|
||
# the current segment.
|
||
if len(sens_out) > 0 and len(sens_out[-1].split(" ")) <= 2:
|
||
sens_out[-1] = sens_out[-1] + " " + s
|
||
else:
|
||
sens_out.append(s)
|
||
try:
|
||
if len(sens_out[-1].split(" ")) <= 2:
|
||
sens_out[-2] = sens_out[-2] + " " + sens_out[-1]
|
||
sens_out.pop(-1)
|
||
except:
|
||
pass
|
||
return sens_out
|
||
|
||
def split_segments_zh(text, min_len=10):
|
||
text = re.sub('[。!?;]', '.', text)
|
||
text = re.sub('[,]', ',', text)
|
||
# 将文本中的换行符、空格和制表符替换为空格
|
||
text = re.sub('[\n\t ]+', ' ', text)
|
||
# 在标点符号后添加一个空格
|
||
text = re.sub('([,.!?;])', r'\1 $#!', text)
|
||
# 分隔句子并去除前后空格
|
||
# segments = [s.strip() for s in re.split('(。|!|?|;)', text)]
|
||
segments = [s.strip() for s in text.split('$#!')]
|
||
if len(segments[-1]) == 0: del segments[-1]
|
||
|
||
new_segments = []
|
||
new_sent = []
|
||
count_len = 0
|
||
for ind, sent in enumerate(segments):
|
||
new_sent.append(sent)
|
||
count_len += len(sent)
|
||
if count_len > min_len or ind == len(segments) - 1:
|
||
count_len = 0
|
||
new_segments.append(' '.join(new_sent))
|
||
new_sent = []
|
||
return merge_short_segments_zh(new_segments)
|
||
|
||
|
||
def merge_short_segments_zh(sens):
|
||
# return sens
|
||
"""Avoid short segments by merging them with the following segment.
|
||
|
||
Args:
|
||
List[str]: list of input segments.
|
||
|
||
Returns:
|
||
List[str]: list of output segments.
|
||
"""
|
||
sens_out = []
|
||
for s in sens:
|
||
# If the previous sentense is too short, merge them with
|
||
# the current segment.
|
||
if len(sens_out) > 0 and len(sens_out[-1]) <= 2:
|
||
sens_out[-1] = sens_out[-1] + " " + s
|
||
else:
|
||
sens_out.append(s)
|
||
try:
|
||
if len(sens_out[-1]) <= 2:
|
||
sens_out[-2] = sens_out[-2] + " " + sens_out[-1]
|
||
sens_out.pop(-1)
|
||
except:
|
||
pass
|
||
return sens_out |