├── onnx ├── models │ ├── 转换后的模型onnx文件夹放到这里.txt │ └── 转换后的模型json放在这里,不要放到文件夹内 ├── Bert │ ├── deberta-v3-large │ │ ├── model.onnx文件放到这里.txt │ │ ├── tokenizer_config.json │ │ ├── spm.model │ │ ├── generator_config.json │ │ ├── config.json │ │ ├── .gitattributes │ │ └── README.md │ ├── deberta-v2-large-japanese │ │ ├── model.onnx文件放到这里.txt │ │ ├── special_tokens_map.json │ │ ├── tokenizer_config.json │ │ ├── config.json │ │ └── README.md │ └── chinese-roberta-wwm-ext-large │ │ ├── model.onnx文件放到这里.txt │ │ ├── added_tokens.json │ │ ├── tokenizer_config.json │ │ ├── special_tokens_map.json │ │ ├── config.json │ │ └── README.md └── Text │ ├── cmudict_cache.pickle │ └── opencpop-strict.txt ├── icon.ico ├── image.png ├── image-1.png ├── image-2.png ├── image-3.png ├── image-4.png ├── image-5.png ├── image-6.png ├── image-7.png ├── image-8.png ├── speakers_map.json ├── requirements.txt ├── .editorconfig ├── config.json ├── log.py ├── api ├── utils.py ├── api.py ├── ui.py ├── split.py └── tts.py ├── config.py ├── README.md ├── launch.py ├── onnx_infer ├── text │ ├── tokenizer.py │ ├── cleaner.py │ ├── symbols.py │ ├── chinese.py │ ├── english.py │ ├── japanese.py │ └── chinese_tone_sandhi.py ├── onnx_bert.py └── onnx_infer.py ├── .gitignore └── LICENSE /onnx/models/转换后的模型onnx文件夹放到这里.txt: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /onnx/models/转换后的模型json放在这里,不要放到文件夹内: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /onnx/Bert/deberta-v3-large/model.onnx文件放到这里.txt: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /onnx/Bert/deberta-v2-large-japanese/model.onnx文件放到这里.txt: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /onnx/Bert/chinese-roberta-wwm-ext-large/model.onnx文件放到这里.txt: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /onnx/Bert/chinese-roberta-wwm-ext-large/added_tokens.json: -------------------------------------------------------------------------------- 1 | {} 2 | -------------------------------------------------------------------------------- /icon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/huahuahuage/Bert-VITS2-Speech/HEAD/icon.ico -------------------------------------------------------------------------------- /image.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/huahuahuage/Bert-VITS2-Speech/HEAD/image.png -------------------------------------------------------------------------------- /image-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/huahuahuage/Bert-VITS2-Speech/HEAD/image-1.png -------------------------------------------------------------------------------- /image-2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/huahuahuage/Bert-VITS2-Speech/HEAD/image-2.png -------------------------------------------------------------------------------- /image-3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/huahuahuage/Bert-VITS2-Speech/HEAD/image-3.png -------------------------------------------------------------------------------- /image-4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/huahuahuage/Bert-VITS2-Speech/HEAD/image-4.png -------------------------------------------------------------------------------- /image-5.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/huahuahuage/Bert-VITS2-Speech/HEAD/image-5.png -------------------------------------------------------------------------------- /image-6.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/huahuahuage/Bert-VITS2-Speech/HEAD/image-6.png -------------------------------------------------------------------------------- /image-7.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/huahuahuage/Bert-VITS2-Speech/HEAD/image-7.png -------------------------------------------------------------------------------- /image-8.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/huahuahuage/Bert-VITS2-Speech/HEAD/image-8.png -------------------------------------------------------------------------------- /onnx/Bert/chinese-roberta-wwm-ext-large/tokenizer_config.json: -------------------------------------------------------------------------------- 1 | {"init_inputs": []} 2 | -------------------------------------------------------------------------------- /onnx/Bert/deberta-v3-large/tokenizer_config.json: -------------------------------------------------------------------------------- 1 | { 2 | "do_lower_case": false, 3 | "vocab_type": "spm" 4 | } 5 | -------------------------------------------------------------------------------- /speakers_map.json: -------------------------------------------------------------------------------- 1 | { 2 | "刻晴": { 3 | "JP": "刻晴(原神-日语)", 4 | "EN": "Keqing(原神-英语)" 5 | } 6 | } -------------------------------------------------------------------------------- /onnx/Text/cmudict_cache.pickle: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/huahuahuage/Bert-VITS2-Speech/HEAD/onnx/Text/cmudict_cache.pickle -------------------------------------------------------------------------------- /onnx/Bert/chinese-roberta-wwm-ext-large/special_tokens_map.json: -------------------------------------------------------------------------------- 1 | {"unk_token": "[UNK]", "sep_token": "[SEP]", "pad_token": "[PAD]", "cls_token": "[CLS]", "mask_token": "[MASK]"} 2 | -------------------------------------------------------------------------------- /onnx/Bert/deberta-v3-large/spm.model: -------------------------------------------------------------------------------- 1 | version https://git-lfs.github.com/spec/v1 2 | oid sha256:c679fbf93643d19aab7ee10c0b99e460bdbc02fedf34b92b05af343b4af586fd 3 | size 2464616 4 | -------------------------------------------------------------------------------- /onnx/Bert/deberta-v2-large-japanese/special_tokens_map.json: -------------------------------------------------------------------------------- 1 | { 2 | "bos_token": "[CLS]", 3 | "cls_token": "[CLS]", 4 | "eos_token": "[SEP]", 5 | "mask_token": "[MASK]", 6 | "pad_token": "[PAD]", 7 | "sep_token": "[SEP]", 8 | "unk_token": "[UNK]" 9 | } 10 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | numpy 2 | scipy 3 | transformers 4 | cn2an 5 | jieba 6 | g2p_en 7 | num2words 8 | jaconv 9 | pypinyin 10 | colorlog 11 | chardet 12 | gradio 13 | fastapi 14 | uvicorn 15 | onnxruntime 16 | openjtalk 17 | sentencepiece 18 | pyperclip -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | # EditorConfig is awesome: https://EditorConfig.org 2 | 3 | # top-most EditorConfig file 4 | root = true 5 | 6 | [*] 7 | indent_style = space 8 | indent_size = 4 9 | end_of_line = crlf 10 | charset = utf-8 11 | trim_trailing_whitespace = false 12 | insert_final_newline = false -------------------------------------------------------------------------------- /onnx/Bert/deberta-v2-large-japanese/tokenizer_config.json: -------------------------------------------------------------------------------- 1 | { 2 | "bos_token": "[CLS]", 3 | "cls_token": "[CLS]", 4 | "do_lower_case": false, 5 | "eos_token": "[SEP]", 6 | "keep_accents": true, 7 | "mask_token": "[MASK]", 8 | "pad_token": "[PAD]", 9 | "sep_token": "[SEP]", 10 | "sp_model_kwargs": {}, 11 | "special_tokens_map_file": null, 12 | "split_by_punct": false, 13 | "tokenizer_class": "DebertaV2Tokenizer", 14 | "unk_token": "[UNK]" 15 | } 16 | -------------------------------------------------------------------------------- /config.json: -------------------------------------------------------------------------------- 1 | { 2 | "server_host": "127.0.0.1", 3 | "server_port": 7880, 4 | "webui_enable": true, 5 | "onnx_providers": "CPUExecutionProvider", 6 | "onnx_tts_models": "onnx/models/Genshin/", 7 | "onnx_tts_models_chinese_mark": "中文", 8 | "bert_enable": true, 9 | "bert_chinese": "onnx/Bert/chinese-roberta-wwm-ext-large/", 10 | "bert_japanese": "onnx/Bert/deberta-v2-large-japanese/", 11 | "bert_english": "onnx/Bert/deberta-v3-large/" 12 | } -------------------------------------------------------------------------------- /onnx/Bert/deberta-v3-large/generator_config.json: -------------------------------------------------------------------------------- 1 | { 2 | "model_type": "deberta-v2", 3 | "attention_probs_dropout_prob": 0.1, 4 | "hidden_act": "gelu", 5 | "hidden_dropout_prob": 0.1, 6 | "hidden_size": 1024, 7 | "initializer_range": 0.02, 8 | "intermediate_size": 4096, 9 | "max_position_embeddings": 512, 10 | "relative_attention": true, 11 | "position_buckets": 256, 12 | "norm_rel_ebd": "layer_norm", 13 | "share_att_key": true, 14 | "pos_att_type": "p2c|c2p", 15 | "layer_norm_eps": 1e-7, 16 | "max_relative_positions": -1, 17 | "position_biased_input": false, 18 | "num_attention_heads": 16, 19 | "num_hidden_layers": 12, 20 | "type_vocab_size": 0, 21 | "vocab_size": 128100 22 | } 23 | -------------------------------------------------------------------------------- /onnx/Bert/deberta-v3-large/config.json: -------------------------------------------------------------------------------- 1 | { 2 | "model_type": "deberta-v2", 3 | "attention_probs_dropout_prob": 0.1, 4 | "hidden_act": "gelu", 5 | "hidden_dropout_prob": 0.1, 6 | "hidden_size": 1024, 7 | "initializer_range": 0.02, 8 | "intermediate_size": 4096, 9 | "max_position_embeddings": 512, 10 | "relative_attention": true, 11 | "position_buckets": 256, 12 | "norm_rel_ebd": "layer_norm", 13 | "share_att_key": true, 14 | "pos_att_type": "p2c|c2p", 15 | "layer_norm_eps": 1e-7, 16 | "max_relative_positions": -1, 17 | "position_biased_input": false, 18 | "num_attention_heads": 16, 19 | "num_hidden_layers": 24, 20 | "type_vocab_size": 0, 21 | "vocab_size": 128100 22 | } 23 | -------------------------------------------------------------------------------- /onnx/Bert/chinese-roberta-wwm-ext-large/config.json: -------------------------------------------------------------------------------- 1 | { 2 | "architectures": [ 3 | "BertForMaskedLM" 4 | ], 5 | "attention_probs_dropout_prob": 0.1, 6 | "bos_token_id": 0, 7 | "directionality": "bidi", 8 | "eos_token_id": 2, 9 | "hidden_act": "gelu", 10 | "hidden_dropout_prob": 0.1, 11 | "hidden_size": 1024, 12 | "initializer_range": 0.02, 13 | "intermediate_size": 4096, 14 | "layer_norm_eps": 1e-12, 15 | "max_position_embeddings": 512, 16 | "model_type": "bert", 17 | "num_attention_heads": 16, 18 | "num_hidden_layers": 24, 19 | "output_past": true, 20 | "pad_token_id": 0, 21 | "pooler_fc_size": 768, 22 | "pooler_num_attention_heads": 12, 23 | "pooler_num_fc_layers": 3, 24 | "pooler_size_per_head": 128, 25 | "pooler_type": "first_token_transform", 26 | "type_vocab_size": 2, 27 | "vocab_size": 21128 28 | } 29 | -------------------------------------------------------------------------------- /log.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import colorlog 3 | import jieba 4 | 5 | # 调整jieba日志输出级别 6 | jieba.setLogLevel(jieba.logging.ERROR) 7 | 8 | 9 | # 禁止某些模块日志输出 10 | DISABLED_LOGGER = ["gradio.processing_utils", "gradio", "httpx"] 11 | 12 | for logger_name in DISABLED_LOGGER: 13 | logger_object = logging.getLogger(logger_name) 14 | logger_object.setLevel(logging.ERROR) 15 | 16 | # 创建新的logger 17 | log_instance = logging.getLogger() 18 | log_instance.setLevel(logging.INFO) 19 | 20 | console_handler = logging.StreamHandler() 21 | console_formatter = colorlog.ColoredFormatter( 22 | fmt="[%(levelname)s] - %(message)s", 23 | datefmt="%Y-%m-%d %H:%M:%S", 24 | log_colors={ 25 | "DEBUG": "white", 26 | "INFO": "green", 27 | "WARNING": "yellow", 28 | "ERROR": "red", 29 | "CRITICAL": "bold_red", 30 | }, 31 | ) 32 | console_handler.setFormatter(console_formatter) 33 | 34 | if not log_instance.handlers: 35 | log_instance.addHandler(console_handler) 36 | -------------------------------------------------------------------------------- /api/utils.py: -------------------------------------------------------------------------------- 1 | import os 2 | import platform 3 | import shutil 4 | import pyperclip 5 | from log import log_instance 6 | 7 | 8 | def rebuild_temp_dir(dir_path: str, tips: str = "正在清空API接口语音缓存..."): 9 | """ 10 | 清空重建缓存文件夹 11 | """ 12 | # 删除缓存 13 | try: 14 | shutil.rmtree(dir_path) 15 | log_instance.info(tips) 16 | except OSError as e: 17 | pass 18 | # 重新建立缓存文件夹 19 | os.makedirs(dir_path, exist_ok=True) 20 | 21 | 22 | def copy_to_clipboard(text: str): 23 | """ 24 | 复制字符串到剪切板 25 | """ 26 | pyperclip.copy(text) 27 | 28 | 29 | class OSType: 30 | def __init__(self) -> None: 31 | self.type = self.check_os() 32 | 33 | def check_os(): 34 | """ 35 | 检查操作系统类型 36 | """ 37 | system = platform.system() 38 | if system == "Windows": 39 | return "Windows" 40 | elif system == "Linux": 41 | return "Linux" 42 | else: 43 | return "MacOS" 44 | 45 | 46 | os_type_instance = OSType() -------------------------------------------------------------------------------- /config.py: -------------------------------------------------------------------------------- 1 | import json 2 | import chardet 3 | import logging 4 | 5 | CONFIG_PATH = "config.json" 6 | 7 | 8 | def read_config(config_path:str) -> dict: 9 | """ 10 | 取读配置文件 11 | """ 12 | f = open(config_path, "rb") 13 | try: 14 | raw_data:str = f.read() 15 | # 检测配置文件编码 16 | char_type = chardet.detect(raw_data)['encoding'] 17 | # 解码 18 | data = raw_data.decode(char_type) 19 | config_data = json.loads(data) 20 | except: 21 | config_data = {} 22 | logging.error(f"配置文件 {config_path} 不存在或者格式错误。") 23 | 24 | f.close() 25 | 26 | return config_data 27 | 28 | 29 | class ONNX_CONFIG: 30 | """ 31 | 配置文件 32 | """ 33 | 34 | def __init__(self) -> None: 35 | logging.info(f"正在加载配置文件...") 36 | self.config_data = read_config(CONFIG_PATH) 37 | 38 | def get(self, key, default=None): 39 | """ 40 | 获取配置信息 41 | """ 42 | return self.config_data.get(key, default) 43 | 44 | config_instance = ONNX_CONFIG() 45 | -------------------------------------------------------------------------------- /onnx/Bert/deberta-v2-large-japanese/config.json: -------------------------------------------------------------------------------- 1 | { 2 | "_name_or_path": "configs/deberta_v2_large.json", 3 | "architectures": [ 4 | "DebertaV2ForMaskedLM" 5 | ], 6 | "attention_head_size": 64, 7 | "attention_probs_dropout_prob": 0.1, 8 | "conv_act": "gelu", 9 | "conv_kernel_size": 3, 10 | "hidden_act": "gelu", 11 | "hidden_dropout_prob": 0.1, 12 | "hidden_size": 1024, 13 | "initializer_range": 0.02, 14 | "intermediate_size": 4096, 15 | "layer_norm_eps": 1e-07, 16 | "max_position_embeddings": 512, 17 | "max_relative_positions": -1, 18 | "model_type": "deberta-v2", 19 | "norm_rel_ebd": "layer_norm", 20 | "num_attention_heads": 16, 21 | "num_hidden_layers": 24, 22 | "pad_token_id": 0, 23 | "pooler_dropout": 0, 24 | "pooler_hidden_act": "gelu", 25 | "pooler_hidden_size": 1024, 26 | "pos_att_type": [ 27 | "p2c", 28 | "c2p" 29 | ], 30 | "position_biased_input": false, 31 | "position_buckets": 256, 32 | "relative_attention": true, 33 | "share_att_key": true, 34 | "torch_dtype": "float32", 35 | "transformers_version": "4.23.1", 36 | "type_vocab_size": 0, 37 | "vocab_size": 32000 38 | } 39 | -------------------------------------------------------------------------------- /onnx/Bert/deberta-v3-large/.gitattributes: -------------------------------------------------------------------------------- 1 | *.7z filter=lfs diff=lfs merge=lfs -text 2 | *.arrow filter=lfs diff=lfs merge=lfs -text 3 | *.bin filter=lfs diff=lfs merge=lfs -text 4 | *.bin.* filter=lfs diff=lfs merge=lfs -text 5 | *.bz2 filter=lfs diff=lfs merge=lfs -text 6 | *.ftz filter=lfs diff=lfs merge=lfs -text 7 | *.gz filter=lfs diff=lfs merge=lfs -text 8 | *.h5 filter=lfs diff=lfs merge=lfs -text 9 | *.joblib filter=lfs diff=lfs merge=lfs -text 10 | *.lfs.* filter=lfs diff=lfs merge=lfs -text 11 | *.model filter=lfs diff=lfs merge=lfs -text 12 | *.msgpack filter=lfs diff=lfs merge=lfs -text 13 | *.onnx filter=lfs diff=lfs merge=lfs -text 14 | *.ot filter=lfs diff=lfs merge=lfs -text 15 | *.parquet filter=lfs diff=lfs merge=lfs -text 16 | *.pb filter=lfs diff=lfs merge=lfs -text 17 | *.pt filter=lfs diff=lfs merge=lfs -text 18 | *.pth filter=lfs diff=lfs merge=lfs -text 19 | *.rar filter=lfs diff=lfs merge=lfs -text 20 | saved_model/**/* filter=lfs diff=lfs merge=lfs -text 21 | *.tar.* filter=lfs diff=lfs merge=lfs -text 22 | *.tflite filter=lfs diff=lfs merge=lfs -text 23 | *.tgz filter=lfs diff=lfs merge=lfs -text 24 | *.xz filter=lfs diff=lfs merge=lfs -text 25 | *.zip filter=lfs diff=lfs merge=lfs -text 26 | *.zstandard filter=lfs diff=lfs merge=lfs -text 27 | *tfevents* filter=lfs diff=lfs merge=lfs -text 28 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Bert-VITS2 Speech 2 | 3 | ## 声明 4 | + 严禁将此项目用于一切违反《中华人民共和国宪法》,《中华人民共和国刑法》,《中华人民共和国治安管理处罚法》和《中华人民共和国民法典》之用途。 5 | + 严禁用于任何政治相关用途。 6 | 7 | ## 项目说明 8 | + 基于开源项目[fishaudio/Bert-VITS2 2.1](https://github.com/fishaudio/Bert-VITS2/tree/2.1) 实现 9 | + 去除所有训练相关代码,仅保留onnx模型推理能力,重写调用推理代码 10 | + 重写WEBUI页面,剔除切分生成功能,生成时自动切分,支持多语言多段落混合输入 11 | + WEBUI支持一键获取TTS API地址 12 | 13 | ## 运行环境 14 | + python == 3.10 15 | 16 | ## 安装说明 17 | 18 | `pip install -r requirements.txt` 19 | 20 | ## 使用说明 21 | 22 | 下载中/日/英bert对应onnx模型,放入项目 onnx/Bert目录对应文件夹内 [下载链接](https://openi.pcl.ac.cn/Shirakana/Bert/modelmanage/show_model) 23 | 24 | ![Alt text](image.png) 25 | 26 | 转换[fishaudio/Bert-VITS2 2.1](https://github.com/fishaudio/Bert-VITS2/tree/2.1)版本(仅适用2.1版本)训练后的模型pth文件为onnx,然后将onnx模型文件夹连同json文件放到onnx/models文件夹下。模型转换方法看下方。 27 | 28 | ![Alt text](image-1.png) 29 | 30 | 修改配置文件 config.json,修改 onnx_tts_models_chinese_mark 字段为模型内角色名称的中文标志字符 31 | 32 | 如 角色名称:刻晴(原神-中文), 中文标志字符:"中文"、角色名称:刻晴_ZH, 中文标志字符:"ZH" 33 | 34 | ![Alt text](image-2.png) 35 | 36 | 修改角色多语言映射文件 speakers_map.json,如果不指定,则在进行多语言输出时,仅使用中文角色进行推理 37 | 38 | ![Alt text](image-3.png) 39 | 40 | 可选择是否开启bert推理(默认启用),修改 config.json 文件 bert-enable配置项即可 41 | 42 | ## 训练模型转ONNX说明 43 | 44 | (仅适用2.1版本) 45 | 46 | 运行 [fishaudio/Bert-VITS2 2.1](https://github.com/fishaudio/Bert-VITS2/tree/2.1) 项目根目录下的 export_onnx.py 进行导出。 47 | 48 | ## 界面截图 49 | 50 | ![Alt text](image-4.png) 51 | 52 | ![Alt text](image-8.png) 53 | 54 | ![Alt text](image-5.png) 55 | 56 | ![Alt text](image-6.png) 57 | 58 | ![Alt text](image-7.png) 59 | 60 | ## References 61 | + [fishaudio/Bert-VITS2 2.1](https://github.com/fishaudio/Bert-VITS2/tree/2.1) 62 | 63 | ### 最后,感谢Bert-VITS2项目组的努力与群里大佬们的答疑 -------------------------------------------------------------------------------- /launch.py: -------------------------------------------------------------------------------- 1 | from api.utils import os_type_instance 2 | 3 | if os_type_instance.type == "Windows": 4 | import ctypes 5 | 6 | ctypes.windll.kernel32.SetConsoleTitleW("花花 Bert-VITS2 原神/星铁语音合成API助手") 7 | 8 | # 全文忽略警告信息 9 | import warnings 10 | 11 | warnings.filterwarnings("ignore") 12 | import sys 13 | import imp 14 | 15 | imp.reload(sys) 16 | 17 | print( 18 | "【程序声明】基于开源项目 Bert-VITS2.1 (https://github.com/fishaudio/Bert-VITS2)。" 19 | ) 20 | print( 21 | "【模型来源】红血球AE3803@bilibili/纳鲁塞缪希娜卡纳@bilibili/原神4.2/星穹铁道1.5/chinese-roberta-wwm-ext-large/deberta-v2-large-japanese/deberta-v3-large。" 22 | ) 23 | 24 | print("【程序制作】花花花花花歌@bilibili。") 25 | 26 | print( 27 | "【郑重声明】严禁将此软件用于一切违反《中华人民共和国宪法》,《中华人民共和国刑法》,《中华人民共和国治安管理处罚法》和《中华人民共和国民法典》的用途,严禁将此软件用于任何政治相关用途。\n" 28 | ) 29 | 30 | from log import log_instance 31 | 32 | import gradio 33 | import uvicorn 34 | 35 | # 重载uvicorn日志输出格式 36 | log_config = uvicorn.config.LOGGING_CONFIG 37 | log_config["formatters"]["access"]["fmt"] = "[%(levelname)s] - %(message)s" 38 | log_config["formatters"]["default"]["fmt"] = "[%(levelname)s] - %(message)s" 39 | 40 | # 取读配置文件 41 | from config import config_instance 42 | 43 | HOST = config_instance.get("server_host", "127.0.0.1") 44 | PORT = config_instance.get("server_port", 7880) 45 | WEBUI_ENABLE = config_instance.get("webui_enable", True) 46 | 47 | log_instance.info("欢迎使用 花花 Bert-VITS2 原神/星铁语音合成API助手。") 48 | log_instance.info(f"程序资源正在载入中,请稍候...") 49 | 50 | 51 | from api.api import app as api_app 52 | 53 | if WEBUI_ENABLE: 54 | from api.ui import app as webui_app 55 | 56 | app = gradio.mount_gradio_app(app=api_app, blocks=webui_app, path="/gradio") 57 | else: 58 | app = api_app 59 | 60 | 61 | if __name__ == "__main__": 62 | try: 63 | uvicorn.run(app=app, host=HOST, port=PORT, log_level="critical") 64 | except Exception as e: 65 | log_instance.error("程序启动失败:", e) 66 | # 用户输入任意键来退出 67 | log_instance.info("按下任意键退出程序...") 68 | input() 69 | -------------------------------------------------------------------------------- /onnx_infer/text/tokenizer.py: -------------------------------------------------------------------------------- 1 | """ 2 | 这里实现Bert Tokenizer的加载 3 | """ 4 | 5 | from log import log_instance 6 | from dataclasses import dataclass 7 | from transformers import BertTokenizer, DebertaV2TokenizerFast 8 | from config import config_instance 9 | 10 | from api.utils import os_type_instance 11 | 12 | 13 | CHINESE_ONNX_LOCAL_DIR = config_instance.get("bert_chinese", "") 14 | JAPANESE_ONNX_LOCAL_DIR = config_instance.get("bert_japanese", "") 15 | ENGLISH_ONNX_LOCAL_DIR = config_instance.get("bert_english", "") 16 | 17 | if os_type_instance.type == "Windows": 18 | 19 | @dataclass 20 | class BertTokenizerDict: 21 | """ 22 | ONNX分析器对象字典 for windows 23 | """ 24 | 25 | ZH: BertTokenizer = ( 26 | BertTokenizer.from_pretrained(CHINESE_ONNX_LOCAL_DIR) 27 | if CHINESE_ONNX_LOCAL_DIR 28 | else None 29 | ) 30 | JP: DebertaV2TokenizerFast = ( 31 | DebertaV2TokenizerFast.from_pretrained(JAPANESE_ONNX_LOCAL_DIR) 32 | if JAPANESE_ONNX_LOCAL_DIR 33 | else None 34 | ) 35 | EN: DebertaV2TokenizerFast = ( 36 | DebertaV2TokenizerFast.from_pretrained(ENGLISH_ONNX_LOCAL_DIR) 37 | if ENGLISH_ONNX_LOCAL_DIR 38 | else None 39 | ) 40 | 41 | else: 42 | 43 | @dataclass 44 | class BertTokenizerDict: 45 | """ 46 | ONNX分析器对象字典 for linux 47 | """ 48 | 49 | ZH: BertTokenizer = ( 50 | BertTokenizer.from_pretrained(CHINESE_ONNX_LOCAL_DIR) 51 | if CHINESE_ONNX_LOCAL_DIR 52 | else None 53 | ) 54 | JP: BertTokenizer = ( 55 | BertTokenizer.from_pretrained(JAPANESE_ONNX_LOCAL_DIR) 56 | if JAPANESE_ONNX_LOCAL_DIR 57 | else None 58 | ) 59 | EN: DebertaV2TokenizerFast = ( 60 | DebertaV2TokenizerFast.from_pretrained(ENGLISH_ONNX_LOCAL_DIR) 61 | if ENGLISH_ONNX_LOCAL_DIR 62 | else None 63 | ) 64 | 65 | 66 | log_instance.info("正在加载BERT分析器...") 67 | tokenizer_instance = BertTokenizerDict() 68 | -------------------------------------------------------------------------------- /onnx/Bert/chinese-roberta-wwm-ext-large/README.md: -------------------------------------------------------------------------------- 1 | --- 2 | language: 3 | - zh 4 | tags: 5 | - bert 6 | license: "apache-2.0" 7 | --- 8 | 9 | # Please use 'Bert' related functions to load this model! 10 | 11 | ## Chinese BERT with Whole Word Masking 12 | For further accelerating Chinese natural language processing, we provide **Chinese pre-trained BERT with Whole Word Masking**. 13 | 14 | **[Pre-Training with Whole Word Masking for Chinese BERT](https://arxiv.org/abs/1906.08101)** 15 | Yiming Cui, Wanxiang Che, Ting Liu, Bing Qin, Ziqing Yang, Shijin Wang, Guoping Hu 16 | 17 | This repository is developed based on:https://github.com/google-research/bert 18 | 19 | You may also interested in, 20 | - Chinese BERT series: https://github.com/ymcui/Chinese-BERT-wwm 21 | - Chinese MacBERT: https://github.com/ymcui/MacBERT 22 | - Chinese ELECTRA: https://github.com/ymcui/Chinese-ELECTRA 23 | - Chinese XLNet: https://github.com/ymcui/Chinese-XLNet 24 | - Knowledge Distillation Toolkit - TextBrewer: https://github.com/airaria/TextBrewer 25 | 26 | More resources by HFL: https://github.com/ymcui/HFL-Anthology 27 | 28 | ## Citation 29 | If you find the technical report or resource is useful, please cite the following technical report in your paper. 30 | - Primary: https://arxiv.org/abs/2004.13922 31 | ``` 32 | @inproceedings{cui-etal-2020-revisiting, 33 | title = "Revisiting Pre-Trained Models for {C}hinese Natural Language Processing", 34 | author = "Cui, Yiming and 35 | Che, Wanxiang and 36 | Liu, Ting and 37 | Qin, Bing and 38 | Wang, Shijin and 39 | Hu, Guoping", 40 | booktitle = "Proceedings of the 2020 Conference on Empirical Methods in Natural Language Processing: Findings", 41 | month = nov, 42 | year = "2020", 43 | address = "Online", 44 | publisher = "Association for Computational Linguistics", 45 | url = "https://www.aclweb.org/anthology/2020.findings-emnlp.58", 46 | pages = "657--668", 47 | } 48 | ``` 49 | - Secondary: https://arxiv.org/abs/1906.08101 50 | ``` 51 | @article{chinese-bert-wwm, 52 | title={Pre-Training with Whole Word Masking for Chinese BERT}, 53 | author={Cui, Yiming and Che, Wanxiang and Liu, Ting and Qin, Bing and Yang, Ziqing and Wang, Shijin and Hu, Guoping}, 54 | journal={arXiv preprint arXiv:1906.08101}, 55 | year={2019} 56 | } 57 | ``` 58 | -------------------------------------------------------------------------------- /onnx_infer/text/cleaner.py: -------------------------------------------------------------------------------- 1 | from .symbols import symbol_to_id, language_tone_start_map, language_id_map 2 | 3 | from typing import Callable 4 | from dataclasses import dataclass 5 | 6 | from .chinese import text_normalize as zh_text_normalize 7 | from .japanese import text_normalize as jp_text_normalize 8 | from .english import text_normalize as en_text_normalize 9 | 10 | from .chinese import g2p as zh_g2p 11 | from .japanese import g2p as jp_g2p 12 | from .english import g2p as en_g2p 13 | 14 | 15 | # from text import cleaned_text_to_sequence 16 | @dataclass 17 | class TextNormalizeDict: 18 | """ 19 | 文本序列化 替换所有阿拉伯数字为对应语言,同时将符号替换为指定列表内的英文符号 20 | """ 21 | 22 | ZH: Callable = zh_text_normalize 23 | JP: Callable = jp_text_normalize 24 | EN: Callable = en_text_normalize 25 | 26 | 27 | @dataclass 28 | class G2PDict: 29 | """ 30 | 文本序列化 31 | """ 32 | 33 | ZH: Callable = zh_g2p 34 | JP: Callable = jp_g2p 35 | EN: Callable = en_g2p 36 | 37 | 38 | text_normalize_instance = TextNormalizeDict() 39 | g2p_instance = G2PDict() 40 | 41 | 42 | def clean_text(text: str, language: str): 43 | """ 44 | 处理标点符号,并将文本转化成对应语言音标? 45 | 46 | norm_text:处理标点后的文本 47 | 48 | phones:所有文本的音标列表 49 | 50 | tones:所有文本的音调 51 | 52 | word2ph:单个字的音标个数 53 | 54 | """ 55 | try: 56 | language_text_normalize = getattr(text_normalize_instance, language) 57 | except AttributeError: 58 | raise TypeError(f"语言类型输入错误:{language}。") 59 | # 替换所有阿拉伯数字为对应语言,同时将符号替换为指定列表内的英文符号 60 | norm_text = language_text_normalize(text) 61 | phones, tones, word2ph = getattr(g2p_instance, language)(norm_text) 62 | return norm_text, phones, tones, word2ph 63 | 64 | 65 | def cleaned_text_to_sequence(cleaned_text, tones, language): 66 | """Converts a string of text to a sequence of IDs corresponding to the symbols in the text. 67 | Args: 68 | text: string to convert to a sequence 69 | Returns: 70 | List of integers corresponding to the symbols in the text 71 | """ 72 | phones = [symbol_to_id[symbol] for symbol in cleaned_text] 73 | tone_start = language_tone_start_map[language] 74 | tones = [i + tone_start for i in tones] 75 | lang_ids = [language_id_map[language]] * len(phones) 76 | return phones, tones, lang_ids -------------------------------------------------------------------------------- /onnx_infer/text/symbols.py: -------------------------------------------------------------------------------- 1 | punctuation = ["!", "?", "…", ",", ".", "'", "-"] 2 | pu_symbols = punctuation + ["SP", "UNK"] 3 | pad = "_" 4 | 5 | # chinese 6 | zh_symbols = [ 7 | "E", 8 | "En", 9 | "a", 10 | "ai", 11 | "an", 12 | "ang", 13 | "ao", 14 | "b", 15 | "c", 16 | "ch", 17 | "d", 18 | "e", 19 | "ei", 20 | "en", 21 | "eng", 22 | "er", 23 | "f", 24 | "g", 25 | "h", 26 | "i", 27 | "i0", 28 | "ia", 29 | "ian", 30 | "iang", 31 | "iao", 32 | "ie", 33 | "in", 34 | "ing", 35 | "iong", 36 | "ir", 37 | "iu", 38 | "j", 39 | "k", 40 | "l", 41 | "m", 42 | "n", 43 | "o", 44 | "ong", 45 | "ou", 46 | "p", 47 | "q", 48 | "r", 49 | "s", 50 | "sh", 51 | "t", 52 | "u", 53 | "ua", 54 | "uai", 55 | "uan", 56 | "uang", 57 | "ui", 58 | "un", 59 | "uo", 60 | "v", 61 | "van", 62 | "ve", 63 | "vn", 64 | "w", 65 | "x", 66 | "y", 67 | "z", 68 | "zh", 69 | "AA", 70 | "EE", 71 | "OO", 72 | ] 73 | num_zh_tones = 6 74 | 75 | # japanese 76 | ja_symbols = [ 77 | "N", 78 | "a", 79 | "a:", 80 | "b", 81 | "by", 82 | "ch", 83 | "d", 84 | "dy", 85 | "e", 86 | "e:", 87 | "f", 88 | "g", 89 | "gy", 90 | "h", 91 | "hy", 92 | "i", 93 | "i:", 94 | "j", 95 | "k", 96 | "ky", 97 | "m", 98 | "my", 99 | "n", 100 | "ny", 101 | "o", 102 | "o:", 103 | "p", 104 | "py", 105 | "q", 106 | "r", 107 | "ry", 108 | "s", 109 | "sh", 110 | "t", 111 | "ts", 112 | "ty", 113 | "u", 114 | "u:", 115 | "w", 116 | "y", 117 | "z", 118 | "zy", 119 | ] 120 | num_ja_tones = 2 121 | 122 | # English 123 | en_symbols = [ 124 | "aa", 125 | "ae", 126 | "ah", 127 | "ao", 128 | "aw", 129 | "ay", 130 | "b", 131 | "ch", 132 | "d", 133 | "dh", 134 | "eh", 135 | "er", 136 | "ey", 137 | "f", 138 | "g", 139 | "hh", 140 | "ih", 141 | "iy", 142 | "jh", 143 | "k", 144 | "l", 145 | "m", 146 | "n", 147 | "ng", 148 | "ow", 149 | "oy", 150 | "p", 151 | "r", 152 | "s", 153 | "sh", 154 | "t", 155 | "th", 156 | "uh", 157 | "uw", 158 | "V", 159 | "w", 160 | "y", 161 | "z", 162 | "zh", 163 | ] 164 | num_en_tones = 4 165 | 166 | # combine all symbols 167 | normal_symbols = sorted(set(zh_symbols + ja_symbols + en_symbols)) 168 | symbols = [pad] + normal_symbols + pu_symbols 169 | sil_phonemes_ids = [symbols.index(i) for i in pu_symbols] 170 | 171 | # combine all tones 172 | num_tones = num_zh_tones + num_ja_tones + num_en_tones 173 | 174 | # language maps 175 | language_id_map = {"ZH": 0, "JP": 1, "EN": 2} 176 | num_languages = len(language_id_map.keys()) 177 | 178 | language_tone_start_map = { 179 | "ZH": 0, 180 | "JP": num_zh_tones, 181 | "EN": num_zh_tones + num_ja_tones, 182 | } 183 | 184 | symbol_to_id = {s: i for i, s in enumerate(symbols)} 185 | -------------------------------------------------------------------------------- /api/api.py: -------------------------------------------------------------------------------- 1 | import time 2 | 3 | time_for_launch_start = time.time() 4 | 5 | import os 6 | from typing import Optional 7 | from fastapi import FastAPI 8 | from fastapi.responses import FileResponse 9 | from contextlib import asynccontextmanager 10 | 11 | from .tts import tts_instance 12 | 13 | # 取读配置文件 14 | from log import log_instance 15 | from config import config_instance 16 | 17 | HOST = config_instance.get("server_host", "127.0.0.1") 18 | PORT = config_instance.get("server_port", 7880) 19 | WEBUI_ENABLE = config_instance.get("webui_enable", True) 20 | 21 | 22 | def handle_startup_event(): 23 | # 后台线程启动webui 24 | time_for_launch_end = time.time() 25 | log_instance.info( 26 | f"程序资源载入已完成,耗时:{str(time_for_launch_end - time_for_launch_start)}\n" 27 | ) 28 | api_string_zh = ( 29 | f"http://{HOST}:{PORT}/api/tts?speaker=珊瑚宫心海&text=" 30 | + "{text}" 31 | + "&format=wav&language=auto&length=1&sdp=0.4&noise=0.6&noisew=0.8&emotion=7&seed=114514" 32 | ) 33 | 34 | if WEBUI_ENABLE: 35 | log_instance.info(f"网页控制台 -> http://{HOST}:{PORT}/gradio\n") 36 | 37 | @asynccontextmanager 38 | async def lifespan(app: FastAPI): 39 | """ 40 | fastapi生命周期函数 41 | """ 42 | # 启动事件 43 | handle_startup_event() 44 | yield 45 | # 结束事件 46 | 47 | 48 | app = FastAPI(lifespan=lifespan) 49 | 50 | 51 | @app.get("/api/tts") 52 | def get_data( 53 | text: str, 54 | speaker: str, 55 | language: Optional[str] = "ZH", 56 | sdp: Optional[float] = 0.2, 57 | noise: Optional[float] = 0.6, 58 | noisew: Optional[float] = 0.8, 59 | length: Optional[float] = 1, 60 | emotion: Optional[int] = 7, 61 | seed: Optional[int] = 114514, 62 | ): 63 | log_string = f"收到文本转语音请求:{speaker} -> {text}" 64 | log_error_string = f"文本转语音推理失败:{speaker} -> {text}" 65 | 66 | try: 67 | start = time.time() 68 | file_path = tts_instance.gen_tts( 69 | text=text, 70 | speaker_name=speaker, 71 | language=language, 72 | sdp_ratio=sdp, 73 | noise_scale=noise, 74 | noise_scale_w=noisew, 75 | length_scale=length, 76 | emotion=emotion, 77 | seed=seed, 78 | ) 79 | stop = time.time() 80 | log_instance.info(f"{log_string} 耗时:{str(stop - start)}") 81 | except Exception as e: 82 | log_instance.error(f"{log_error_string} {str(e)}") 83 | return {"code": -1, "data": f"{str(e)}。"} 84 | 85 | if not file_path: 86 | log_instance.error(f"{log_error_string} 请检查请求参数是否正确。") 87 | return {"code": -1, "data": "语音生成失败,请检查请求参数是否正确。"} 88 | 89 | try: 90 | file_size = os.path.getsize(file_path) 91 | except FileNotFoundError: 92 | log_instance.error(f"{log_error_string} 语音文件读取失败。") 93 | return {"code": -2, "data": "数据读取失败,请重试。"} 94 | except: 95 | log_instance.error(f"{log_error_string} 请检查请求参数是否正确。") 96 | return {"code": -1, "data": "语音生成失败,请检查请求参数是否正确。"} 97 | 98 | return FileResponse( 99 | file_path, 100 | headers={"Accept-Ranges": "bytes", "Content-Length": str(file_size)}, 101 | media_type="audio/basic", 102 | filename=os.path.basename(file_path), 103 | ) 104 | -------------------------------------------------------------------------------- /onnx/Bert/deberta-v3-large/README.md: -------------------------------------------------------------------------------- 1 | --- 2 | language: en 3 | tags: 4 | - deberta 5 | - deberta-v3 6 | - fill-mask 7 | thumbnail: https://huggingface.co/front/thumbnails/microsoft.png 8 | license: mit 9 | --- 10 | 11 | ## DeBERTaV3: Improving DeBERTa using ELECTRA-Style Pre-Training with Gradient-Disentangled Embedding Sharing 12 | 13 | [DeBERTa](https://arxiv.org/abs/2006.03654) improves the BERT and RoBERTa models using disentangled attention and enhanced mask decoder. With those two improvements, DeBERTa out perform RoBERTa on a majority of NLU tasks with 80GB training data. 14 | 15 | In [DeBERTa V3](https://arxiv.org/abs/2111.09543), we further improved the efficiency of DeBERTa using ELECTRA-Style pre-training with Gradient Disentangled Embedding Sharing. Compared to DeBERTa, our V3 version significantly improves the model performance on downstream tasks. You can find more technique details about the new model from our [paper](https://arxiv.org/abs/2111.09543). 16 | 17 | Please check the [official repository](https://github.com/microsoft/DeBERTa) for more implementation details and updates. 18 | 19 | The DeBERTa V3 large model comes with 24 layers and a hidden size of 1024. It has 304M backbone parameters with a vocabulary containing 128K tokens which introduces 131M parameters in the Embedding layer. This model was trained using the 160GB data as DeBERTa V2. 20 | 21 | 22 | #### Fine-tuning on NLU tasks 23 | 24 | We present the dev results on SQuAD 2.0 and MNLI tasks. 25 | 26 | | Model |Vocabulary(K)|Backbone #Params(M)| SQuAD 2.0(F1/EM) | MNLI-m/mm(ACC)| 27 | |-------------------|----------|-------------------|-----------|----------| 28 | | RoBERTa-large |50 |304 | 89.4/86.5 | 90.2 | 29 | | XLNet-large |32 |- | 90.6/87.9 | 90.8 | 30 | | DeBERTa-large |50 |- | 90.7/88.0 | 91.3 | 31 | | **DeBERTa-v3-large**|128|304 | **91.5/89.0**| **91.8/91.9**| 32 | 33 | 34 | #### Fine-tuning with HF transformers 35 | 36 | ```bash 37 | #!/bin/bash 38 | 39 | cd transformers/examples/pytorch/text-classification/ 40 | 41 | pip install datasets 42 | export TASK_NAME=mnli 43 | 44 | output_dir="ds_results" 45 | 46 | num_gpus=8 47 | 48 | batch_size=8 49 | 50 | python -m torch.distributed.launch --nproc_per_node=${num_gpus} \ 51 | run_glue.py \ 52 | --model_name_or_path microsoft/deberta-v3-large \ 53 | --task_name $TASK_NAME \ 54 | --do_train \ 55 | --do_eval \ 56 | --evaluation_strategy steps \ 57 | --max_seq_length 256 \ 58 | --warmup_steps 50 \ 59 | --per_device_train_batch_size ${batch_size} \ 60 | --learning_rate 6e-6 \ 61 | --num_train_epochs 2 \ 62 | --output_dir $output_dir \ 63 | --overwrite_output_dir \ 64 | --logging_steps 1000 \ 65 | --logging_dir $output_dir 66 | 67 | ``` 68 | 69 | ### Citation 70 | 71 | If you find DeBERTa useful for your work, please cite the following papers: 72 | 73 | ``` latex 74 | @misc{he2021debertav3, 75 | title={DeBERTaV3: Improving DeBERTa using ELECTRA-Style Pre-Training with Gradient-Disentangled Embedding Sharing}, 76 | author={Pengcheng He and Jianfeng Gao and Weizhu Chen}, 77 | year={2021}, 78 | eprint={2111.09543}, 79 | archivePrefix={arXiv}, 80 | primaryClass={cs.CL} 81 | } 82 | ``` 83 | 84 | ``` latex 85 | @inproceedings{ 86 | he2021deberta, 87 | title={DEBERTA: DECODING-ENHANCED BERT WITH DISENTANGLED ATTENTION}, 88 | author={Pengcheng He and Xiaodong Liu and Jianfeng Gao and Weizhu Chen}, 89 | booktitle={International Conference on Learning Representations}, 90 | year={2021}, 91 | url={https://openreview.net/forum?id=XPZIaotutsD} 92 | } 93 | ``` 94 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | share/python-wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | MANIFEST 28 | 29 | # PyInstaller 30 | # Usually these files are written by a python script from a template 31 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 32 | *.manifest 33 | *.spec 34 | 35 | # Installer logs 36 | pip-log.txt 37 | pip-delete-this-directory.txt 38 | 39 | # Unit test / coverage reports 40 | htmlcov/ 41 | .tox/ 42 | .nox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *.cover 49 | *.py,cover 50 | .hypothesis/ 51 | .pytest_cache/ 52 | cover/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | .pybuilder/ 76 | target/ 77 | 78 | # Jupyter Notebook 79 | .ipynb_checkpoints 80 | 81 | # IPython 82 | profile_default/ 83 | ipython_config.py 84 | 85 | # pyenv 86 | # For a library or package, you might want to ignore these files since the code is 87 | # intended to run in multiple environments; otherwise, check them in: 88 | # .python-version 89 | 90 | # pipenv 91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 94 | # install all needed dependencies. 95 | #Pipfile.lock 96 | 97 | # poetry 98 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 99 | # This is especially recommended for binary packages to ensure reproducibility, and is more 100 | # commonly ignored for libraries. 101 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 102 | #poetry.lock 103 | 104 | # pdm 105 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. 106 | #pdm.lock 107 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it 108 | # in version control. 109 | # https://pdm.fming.dev/#use-with-ide 110 | .pdm.toml 111 | 112 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 113 | __pypackages__/ 114 | 115 | # Celery stuff 116 | celerybeat-schedule 117 | celerybeat.pid 118 | 119 | # SageMath parsed files 120 | *.sage.py 121 | 122 | # Environments 123 | .env 124 | .venv 125 | env/ 126 | venv/ 127 | ENV/ 128 | env.bak/ 129 | venv.bak/ 130 | 131 | # Spyder project settings 132 | .spyderproject 133 | .spyproject 134 | 135 | # Rope project settings 136 | .ropeproject 137 | 138 | # mkdocs documentation 139 | /site 140 | 141 | # mypy 142 | .mypy_cache/ 143 | .dmypy.json 144 | dmypy.json 145 | 146 | # Pyre type checker 147 | .pyre/ 148 | 149 | # pytype static type analyzer 150 | .pytype/ 151 | 152 | # Cython debug symbols 153 | cython_debug/ 154 | 155 | # PyCharm 156 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 157 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 158 | # and can be added to the global gitignore or merged into this file. For a more nuclear 159 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 160 | #.idea/ 161 | 162 | upx-4.0.2-win64/ 163 | temp/ 164 | onnx/Bert/chinese-roberta-wwm-ext-large/model.onnx 165 | onnx/Bert/deberta-v2-large-japanese/model.onnx 166 | onnx/Bert/deberta-v3-large/model.onnx 167 | onnx/models/Genshin/ 168 | onnx/models/Genshin.json 169 | build.txt 170 | test.py -------------------------------------------------------------------------------- /onnx/Bert/deberta-v2-large-japanese/README.md: -------------------------------------------------------------------------------- 1 | --- 2 | language: ja 3 | license: cc-by-sa-4.0 4 | library_name: transformers 5 | tags: 6 | - deberta 7 | - deberta-v2 8 | - fill-mask 9 | datasets: 10 | - wikipedia 11 | - cc100 12 | - oscar 13 | metrics: 14 | - accuracy 15 | mask_token: "[MASK]" 16 | widget: 17 | - text: "京都 大学 で 自然 言語 処理 を [MASK] する 。" 18 | --- 19 | 20 | # Model Card for Japanese DeBERTa V2 large 21 | 22 | ## Model description 23 | 24 | This is a Japanese DeBERTa V2 large model pre-trained on Japanese Wikipedia, the Japanese portion of CC-100, and the 25 | Japanese portion of OSCAR. 26 | 27 | ## How to use 28 | 29 | You can use this model for masked language modeling as follows: 30 | 31 | ```python 32 | from transformers import AutoTokenizer, AutoModelForMaskedLM 33 | 34 | tokenizer = AutoTokenizer.from_pretrained('ku-nlp/deberta-v2-large-japanese') 35 | model = AutoModelForMaskedLM.from_pretrained('ku-nlp/deberta-v2-large-japanese') 36 | 37 | sentence = '京都 大学 で 自然 言語 処理 を [MASK] する 。' # input should be segmented into words by Juman++ in advance 38 | encoding = tokenizer(sentence, return_tensors='pt') 39 | ... 40 | ``` 41 | 42 | You can also fine-tune this model on downstream tasks. 43 | 44 | ## Tokenization 45 | 46 | The input text should be segmented into words by [Juman++](https://github.com/ku-nlp/jumanpp) in 47 | advance. [Juman++ 2.0.0-rc3](https://github.com/ku-nlp/jumanpp/releases/tag/v2.0.0-rc3) was used for pre-training. Each 48 | word is tokenized into subwords by [sentencepiece](https://github.com/google/sentencepiece). 49 | 50 | ## Training data 51 | 52 | We used the following corpora for pre-training: 53 | 54 | - Japanese Wikipedia (as of 20221020, 3.2GB, 27M sentences, 1.3M documents) 55 | - Japanese portion of CC-100 (85GB, 619M sentences, 66M documents) 56 | - Japanese portion of OSCAR (54GB, 326M sentences, 25M documents) 57 | 58 | Note that we filtered out documents annotated with "header", "footer", or "noisy" tags in OSCAR. 59 | Also note that Japanese Wikipedia was duplicated 10 times to make the total size of the corpus comparable to that of 60 | CC-100 and OSCAR. As a result, the total size of the training data is 171GB. 61 | 62 | ## Training procedure 63 | 64 | We first segmented texts in the corpora into words using [Juman++](https://github.com/ku-nlp/jumanpp). 65 | Then, we built a sentencepiece model with 32000 tokens including words ([JumanDIC](https://github.com/ku-nlp/JumanDIC)) 66 | and subwords induced by the unigram language model of [sentencepiece](https://github.com/google/sentencepiece). 67 | 68 | We tokenized the segmented corpora into subwords using the sentencepiece model and trained the Japanese DeBERTa model 69 | using [transformers](https://github.com/huggingface/transformers) library. 70 | The training took 36 days using 8 NVIDIA A100-SXM4-40GB GPUs. 71 | 72 | The following hyperparameters were used during pre-training: 73 | 74 | - learning_rate: 1e-4 75 | - per_device_train_batch_size: 18 76 | - distributed_type: multi-GPU 77 | - num_devices: 8 78 | - gradient_accumulation_steps: 16 79 | - total_train_batch_size: 2,304 80 | - max_seq_length: 512 81 | - optimizer: Adam with betas=(0.9,0.999) and epsilon=1e-06 82 | - lr_scheduler_type: linear schedule with warmup 83 | - training_steps: 300,000 84 | - warmup_steps: 10,000 85 | 86 | The accuracy of the trained model on the masked language modeling task was 0.799. 87 | The evaluation set consists of 5,000 randomly sampled documents from each of the training corpora. 88 | 89 | ## Fine-tuning on NLU tasks 90 | 91 | We fine-tuned the following models and evaluated them on the dev set of JGLUE. 92 | We tuned learning rate and training epochs for each model and task 93 | following [the JGLUE paper](https://www.jstage.jst.go.jp/article/jnlp/30/1/30_63/_pdf/-char/ja). 94 | 95 | | Model | MARC-ja/acc | JSTS/pearson | JSTS/spearman | JNLI/acc | JSQuAD/EM | JSQuAD/F1 | JComQA/acc | 96 | |-------------------------------|-------------|--------------|---------------|----------|-----------|-----------|------------| 97 | | Waseda RoBERTa base | 0.965 | 0.913 | 0.876 | 0.905 | 0.853 | 0.916 | 0.853 | 98 | | Waseda RoBERTa large (seq512) | 0.969 | 0.925 | 0.890 | 0.928 | 0.910 | 0.955 | 0.900 | 99 | | LUKE Japanese base* | 0.965 | 0.916 | 0.877 | 0.912 | - | - | 0.842 | 100 | | LUKE Japanese large* | 0.965 | 0.932 | 0.902 | 0.927 | - | - | 0.893 | 101 | | DeBERTaV2 base | 0.970 | 0.922 | 0.886 | 0.922 | 0.899 | 0.951 | 0.873 | 102 | | DeBERTaV2 large | 0.968 | 0.925 | 0.892 | 0.924 | 0.912 | 0.959 | 0.890 | 103 | 104 | *The scores of LUKE are from [the official repository](https://github.com/studio-ousia/luke). 105 | 106 | ## Acknowledgments 107 | 108 | This work was supported by Joint Usage/Research Center for Interdisciplinary Large-scale Information Infrastructures ( 109 | JHPCN) through General Collaboration Project no. jh221004, "Developing a Platform for Constructing and Sharing of 110 | Large-Scale Japanese Language Models". 111 | For training models, we used the mdx: a platform for the data-driven future. 112 | -------------------------------------------------------------------------------- /onnx/Text/opencpop-strict.txt: -------------------------------------------------------------------------------- 1 | a AA a 2 | ai AA ai 3 | an AA an 4 | ang AA ang 5 | ao AA ao 6 | ba b a 7 | bai b ai 8 | ban b an 9 | bang b ang 10 | bao b ao 11 | bei b ei 12 | ben b en 13 | beng b eng 14 | bi b i 15 | bian b ian 16 | biao b iao 17 | bie b ie 18 | bin b in 19 | bing b ing 20 | bo b o 21 | bu b u 22 | ca c a 23 | cai c ai 24 | can c an 25 | cang c ang 26 | cao c ao 27 | ce c e 28 | cei c ei 29 | cen c en 30 | ceng c eng 31 | cha ch a 32 | chai ch ai 33 | chan ch an 34 | chang ch ang 35 | chao ch ao 36 | che ch e 37 | chen ch en 38 | cheng ch eng 39 | chi ch ir 40 | chong ch ong 41 | chou ch ou 42 | chu ch u 43 | chua ch ua 44 | chuai ch uai 45 | chuan ch uan 46 | chuang ch uang 47 | chui ch ui 48 | chun ch un 49 | chuo ch uo 50 | ci c i0 51 | cong c ong 52 | cou c ou 53 | cu c u 54 | cuan c uan 55 | cui c ui 56 | cun c un 57 | cuo c uo 58 | da d a 59 | dai d ai 60 | dan d an 61 | dang d ang 62 | dao d ao 63 | de d e 64 | dei d ei 65 | den d en 66 | deng d eng 67 | di d i 68 | dia d ia 69 | dian d ian 70 | diao d iao 71 | die d ie 72 | ding d ing 73 | diu d iu 74 | dong d ong 75 | dou d ou 76 | du d u 77 | duan d uan 78 | dui d ui 79 | dun d un 80 | duo d uo 81 | e EE e 82 | ei EE ei 83 | en EE en 84 | eng EE eng 85 | er EE er 86 | fa f a 87 | fan f an 88 | fang f ang 89 | fei f ei 90 | fen f en 91 | feng f eng 92 | fo f o 93 | fou f ou 94 | fu f u 95 | ga g a 96 | gai g ai 97 | gan g an 98 | gang g ang 99 | gao g ao 100 | ge g e 101 | gei g ei 102 | gen g en 103 | geng g eng 104 | gong g ong 105 | gou g ou 106 | gu g u 107 | gua g ua 108 | guai g uai 109 | guan g uan 110 | guang g uang 111 | gui g ui 112 | gun g un 113 | guo g uo 114 | ha h a 115 | hai h ai 116 | han h an 117 | hang h ang 118 | hao h ao 119 | he h e 120 | hei h ei 121 | hen h en 122 | heng h eng 123 | hong h ong 124 | hou h ou 125 | hu h u 126 | hua h ua 127 | huai h uai 128 | huan h uan 129 | huang h uang 130 | hui h ui 131 | hun h un 132 | huo h uo 133 | ji j i 134 | jia j ia 135 | jian j ian 136 | jiang j iang 137 | jiao j iao 138 | jie j ie 139 | jin j in 140 | jing j ing 141 | jiong j iong 142 | jiu j iu 143 | ju j v 144 | jv j v 145 | juan j van 146 | jvan j van 147 | jue j ve 148 | jve j ve 149 | jun j vn 150 | jvn j vn 151 | ka k a 152 | kai k ai 153 | kan k an 154 | kang k ang 155 | kao k ao 156 | ke k e 157 | kei k ei 158 | ken k en 159 | keng k eng 160 | kong k ong 161 | kou k ou 162 | ku k u 163 | kua k ua 164 | kuai k uai 165 | kuan k uan 166 | kuang k uang 167 | kui k ui 168 | kun k un 169 | kuo k uo 170 | la l a 171 | lai l ai 172 | lan l an 173 | lang l ang 174 | lao l ao 175 | le l e 176 | lei l ei 177 | leng l eng 178 | li l i 179 | lia l ia 180 | lian l ian 181 | liang l iang 182 | liao l iao 183 | lie l ie 184 | lin l in 185 | ling l ing 186 | liu l iu 187 | lo l o 188 | long l ong 189 | lou l ou 190 | lu l u 191 | luan l uan 192 | lun l un 193 | luo l uo 194 | lv l v 195 | lve l ve 196 | ma m a 197 | mai m ai 198 | man m an 199 | mang m ang 200 | mao m ao 201 | me m e 202 | mei m ei 203 | men m en 204 | meng m eng 205 | mi m i 206 | mian m ian 207 | miao m iao 208 | mie m ie 209 | min m in 210 | ming m ing 211 | miu m iu 212 | mo m o 213 | mou m ou 214 | mu m u 215 | na n a 216 | nai n ai 217 | nan n an 218 | nang n ang 219 | nao n ao 220 | ne n e 221 | nei n ei 222 | nen n en 223 | neng n eng 224 | ni n i 225 | nian n ian 226 | niang n iang 227 | niao n iao 228 | nie n ie 229 | nin n in 230 | ning n ing 231 | niu n iu 232 | nong n ong 233 | nou n ou 234 | nu n u 235 | nuan n uan 236 | nun n un 237 | nuo n uo 238 | nv n v 239 | nve n ve 240 | o OO o 241 | ou OO ou 242 | pa p a 243 | pai p ai 244 | pan p an 245 | pang p ang 246 | pao p ao 247 | pei p ei 248 | pen p en 249 | peng p eng 250 | pi p i 251 | pian p ian 252 | piao p iao 253 | pie p ie 254 | pin p in 255 | ping p ing 256 | po p o 257 | pou p ou 258 | pu p u 259 | qi q i 260 | qia q ia 261 | qian q ian 262 | qiang q iang 263 | qiao q iao 264 | qie q ie 265 | qin q in 266 | qing q ing 267 | qiong q iong 268 | qiu q iu 269 | qu q v 270 | qv q v 271 | quan q van 272 | qvan q van 273 | que q ve 274 | qve q ve 275 | qun q vn 276 | qvn q vn 277 | ran r an 278 | rang r ang 279 | rao r ao 280 | re r e 281 | ren r en 282 | reng r eng 283 | ri r ir 284 | rong r ong 285 | rou r ou 286 | ru r u 287 | rua r ua 288 | ruan r uan 289 | rui r ui 290 | run r un 291 | ruo r uo 292 | sa s a 293 | sai s ai 294 | san s an 295 | sang s ang 296 | sao s ao 297 | se s e 298 | sen s en 299 | seng s eng 300 | sha sh a 301 | shai sh ai 302 | shan sh an 303 | shang sh ang 304 | shao sh ao 305 | she sh e 306 | shei sh ei 307 | shen sh en 308 | sheng sh eng 309 | shi sh ir 310 | shou sh ou 311 | shu sh u 312 | shua sh ua 313 | shuai sh uai 314 | shuan sh uan 315 | shuang sh uang 316 | shui sh ui 317 | shun sh un 318 | shuo sh uo 319 | si s i0 320 | song s ong 321 | sou s ou 322 | su s u 323 | suan s uan 324 | sui s ui 325 | sun s un 326 | suo s uo 327 | ta t a 328 | tai t ai 329 | tan t an 330 | tang t ang 331 | tao t ao 332 | te t e 333 | tei t ei 334 | teng t eng 335 | ti t i 336 | tian t ian 337 | tiao t iao 338 | tie t ie 339 | ting t ing 340 | tong t ong 341 | tou t ou 342 | tu t u 343 | tuan t uan 344 | tui t ui 345 | tun t un 346 | tuo t uo 347 | wa w a 348 | wai w ai 349 | wan w an 350 | wang w ang 351 | wei w ei 352 | wen w en 353 | weng w eng 354 | wo w o 355 | wu w u 356 | xi x i 357 | xia x ia 358 | xian x ian 359 | xiang x iang 360 | xiao x iao 361 | xie x ie 362 | xin x in 363 | xing x ing 364 | xiong x iong 365 | xiu x iu 366 | xu x v 367 | xv x v 368 | xuan x van 369 | xvan x van 370 | xue x ve 371 | xve x ve 372 | xun x vn 373 | xvn x vn 374 | ya y a 375 | yan y En 376 | yang y ang 377 | yao y ao 378 | ye y E 379 | yi y i 380 | yin y in 381 | ying y ing 382 | yo y o 383 | yong y ong 384 | you y ou 385 | yu y v 386 | yv y v 387 | yuan y van 388 | yvan y van 389 | yue y ve 390 | yve y ve 391 | yun y vn 392 | yvn y vn 393 | za z a 394 | zai z ai 395 | zan z an 396 | zang z ang 397 | zao z ao 398 | ze z e 399 | zei z ei 400 | zen z en 401 | zeng z eng 402 | zha zh a 403 | zhai zh ai 404 | zhan zh an 405 | zhang zh ang 406 | zhao zh ao 407 | zhe zh e 408 | zhei zh ei 409 | zhen zh en 410 | zheng zh eng 411 | zhi zh ir 412 | zhong zh ong 413 | zhou zh ou 414 | zhu zh u 415 | zhua zh ua 416 | zhuai zh uai 417 | zhuan zh uan 418 | zhuang zh uang 419 | zhui zh ui 420 | zhun zh un 421 | zhuo zh uo 422 | zi z i0 423 | zong z ong 424 | zou z ou 425 | zu z u 426 | zuan z uan 427 | zui z ui 428 | zun z un 429 | zuo z uo 430 | -------------------------------------------------------------------------------- /onnx_infer/onnx_bert.py: -------------------------------------------------------------------------------- 1 | import os 2 | from log import log_instance 3 | import numpy as np 4 | import onnxruntime as ort 5 | from dataclasses import dataclass 6 | 7 | from config import config_instance 8 | 9 | from .text.japanese import text2sep_kata as japanese_text2sep_kata 10 | from .text.tokenizer import tokenizer_instance 11 | 12 | ONNX_PROVIDERS = [config_instance.get("onnx_providers", "CPUExecutionProvider")] 13 | CHINESE_ONNX_LOCAL_DIR = config_instance.get("bert_chinese", "") 14 | JAPANESE_ONNX_LOCAL_DIR = config_instance.get("bert_japanese", "") 15 | ENGLISH_ONNX_LOCAL_DIR = config_instance.get("bert_english", "") 16 | 17 | 18 | @dataclass 19 | class BertModelsDict: 20 | """ 21 | ONNX模型对象字典 22 | """ 23 | 24 | ZH: ort.InferenceSession = ( 25 | ort.InferenceSession( 26 | os.path.join(CHINESE_ONNX_LOCAL_DIR, "model.onnx"), 27 | providers=ONNX_PROVIDERS, 28 | ) 29 | if CHINESE_ONNX_LOCAL_DIR 30 | else None 31 | ) 32 | JP: ort.InferenceSession = ( 33 | ort.InferenceSession( 34 | os.path.join(JAPANESE_ONNX_LOCAL_DIR, "model.onnx"), 35 | providers=ONNX_PROVIDERS, 36 | ) 37 | if JAPANESE_ONNX_LOCAL_DIR 38 | else None 39 | ) 40 | EN: ort.InferenceSession = ( 41 | ort.InferenceSession( 42 | os.path.join(ENGLISH_ONNX_LOCAL_DIR, "model.onnx"), 43 | providers=ONNX_PROVIDERS, 44 | ) 45 | if ENGLISH_ONNX_LOCAL_DIR 46 | else None 47 | ) 48 | 49 | 50 | class BertOnnx: 51 | def __init__(self) -> None: 52 | log_instance.info("正在加载BERT分析器...") 53 | self.tokenizer_instance = tokenizer_instance 54 | 55 | log_instance.info("正在加载BERT语言模型...") 56 | self.models_dict: BertModelsDict = BertModelsDict() 57 | 58 | def __get_model_path(self, dir_path: str): 59 | """ 60 | 获取模型的完整路径 61 | """ 62 | return os.path.join(dir_path, "model.onnx") 63 | 64 | def __check_language(self, language_str: str): 65 | """ 66 | 检查语言类型参数是否合法 67 | """ 68 | if hasattr(self.models_dict, language_str): 69 | return language_str 70 | return False 71 | 72 | @staticmethod 73 | def __check_params_inputs(text: str, word2ph: list, language_str: str = "ZH"): 74 | # 检查输入参数的合法性 75 | log_instance.debug(f"{language_str}, {str(len(word2ph))} {str(len(text) + 2)}") 76 | if language_str in ["ZH"] and len(word2ph) != len(text) + 2: 77 | raise ValueError("输入参数错误,len(word2ph) != len(text) + 2。") 78 | else: 79 | pass 80 | 81 | @staticmethod 82 | def __check_onnx_outputs(res: np.float32, word2ph: list, language_str: str = "ZH"): 83 | """ 84 | 检查输出结果的合法性 85 | """ 86 | # 检查输出结果的合法性 87 | if language_str == "EN" and len(word2ph) != res.shape[0]: 88 | raise ValueError( 89 | f"Bert输出参数错误,len(word2ph) != res.shape[0] (len(word2ph):{len(word2ph)} res.shape[0]:{res.shape[0]})。 " 90 | ) 91 | else: 92 | pass 93 | # pass 94 | 95 | @staticmethod 96 | def __handle_text(text: str, language_str: str = "ZH"): 97 | """ 98 | 针对不同的语言,对文本进行处理 99 | """ 100 | log_instance.debug(f"文本处理 {language_str} {text}") 101 | if language_str == "JP": 102 | return "".join(japanese_text2sep_kata(text)[0]) 103 | return text 104 | 105 | def __structure_onnx_inputs(self, text: str, language_str: str = "ZH"): 106 | """ 107 | 构造分析器转换文本参数 108 | """ 109 | # 加载分析器转换文本参数 110 | tokenizer = getattr(self.tokenizer_instance, language_str) 111 | 112 | if not tokenizer: 113 | raise KeyError(f"BERT_{language_str}分析器尚未载入。") 114 | 115 | tokenized_tokens = tokenizer(text) 116 | 117 | # 构造模型 输入参数 118 | input_feed = { 119 | "input_ids": np.array([tokenized_tokens["input_ids"]], dtype=np.int64), 120 | "attention_mask": np.array( 121 | [tokenized_tokens["attention_mask"]], dtype=np.int64 122 | ), 123 | } 124 | # 目前只有ZH的bert模型需要 token_type_ids 参数 125 | if language_str == "ZH": 126 | input_feed["token_type_ids"] = np.array( 127 | [tokenized_tokens["token_type_ids"]], dtype=np.int64 128 | ) 129 | 130 | return input_feed 131 | 132 | def __get_phone_level_feature(self, res: np.float32, word2ph: list) -> np.float32: 133 | """ 134 | 获取最终bert结果 ???具体作用不清楚 135 | """ 136 | phone_level_feature = [] 137 | for i in range(len(word2ph)): 138 | if i >= res.shape[0]: 139 | repeat_feature = np.repeat([np.empty(res.shape[1])], word2ph[i], axis=0) 140 | else: 141 | repeat_feature = np.repeat([res[i]], word2ph[i], axis=0) 142 | phone_level_feature.append(repeat_feature) 143 | res = np.concatenate(phone_level_feature, axis=0) 144 | # 强制转化为float32 145 | res = res.astype(np.float32) 146 | return res 147 | 148 | def __run_onnx(self, inputs: dict, language_str: str = "ZH") -> np.float32: 149 | """ 150 | 输入并获取bert最后一层隐藏数据 151 | """ 152 | onnx_model: ort.InferenceSession = getattr(self.models_dict, language_str) 153 | 154 | if not onnx_model: 155 | raise KeyError(f"BERT_{language_str}模型尚未载入。") 156 | res = onnx_model.run( 157 | output_names=["last_hidden_state"], 158 | input_feed=inputs, 159 | )[0] 160 | onnx_model.disable_fallback() 161 | res = np.array(res, dtype=np.float32) 162 | return res 163 | 164 | def run(self, norm_text: str, word2ph: list, language_str: str) -> np.float32: 165 | """ 166 | 运行推理 167 | """ 168 | 169 | # 检查语言类型参数是否合法 170 | if not self.__check_language(language_str): 171 | raise TypeError(f"语言类型输入错误:{language_str}。") 172 | 173 | # 针对不同的语言,对文本进行处理 174 | norm_text = self.__handle_text(text=norm_text, language_str=language_str) 175 | log_instance.debug(f"结果处理 {language_str} {norm_text}") 176 | # 检查输入参数 177 | self.__check_params_inputs( 178 | text=norm_text, word2ph=word2ph, language_str=language_str 179 | ) 180 | 181 | # 构造模型输入参数 182 | input_feed = self.__structure_onnx_inputs( 183 | text=norm_text, language_str=language_str 184 | ) 185 | 186 | # 推理获取输出 187 | res = self.__run_onnx(inputs=input_feed, language_str=language_str) 188 | log_instance.debug(f"原始onnx输出 {language_str} {str(res.shape)}") 189 | # 检查输出结果的合法性 190 | self.__check_onnx_outputs(res=res, word2ph=word2ph, language_str=language_str) 191 | 192 | # 获取最终bert结果 ???具体作用不清楚 193 | phone_level_feature = self.__get_phone_level_feature(res=res, word2ph=word2ph) 194 | log_instance.debug(f"最终bert结果 {language_str} {str(phone_level_feature.dtype)}") 195 | return phone_level_feature 196 | 197 | bert_onnx_instance = BertOnnx() 198 | 199 | 200 | def get_bert(norm_text: str, word2ph: list, language: np.int64): 201 | """ 202 | bert模型推理 203 | """ 204 | return bert_onnx_instance.run(norm_text, word2ph, language) 205 | -------------------------------------------------------------------------------- /onnx_infer/text/chinese.py: -------------------------------------------------------------------------------- 1 | import os 2 | import re 3 | 4 | import cn2an 5 | import jieba.posseg as psg 6 | from typing import List, Dict 7 | from pypinyin import lazy_pinyin, Style 8 | 9 | from .symbols import punctuation 10 | from .chinese_tone_sandhi import ToneSandhi 11 | 12 | from log import log_instance 13 | 14 | REP_MAP = { 15 | ":": ",", 16 | ";": ",", 17 | ",": ",", 18 | "。": ".", 19 | "!": "!", 20 | "?": "?", 21 | "\n": ".", 22 | "·": ",", 23 | "、": ",", 24 | "...": "…", 25 | "$": ".", 26 | "“": "'", 27 | "”": "'", 28 | '"': "'", 29 | "‘": "'", 30 | "’": "'", 31 | "(": "'", 32 | ")": "'", 33 | "(": "'", 34 | ")": "'", 35 | "《": "'", 36 | "》": "'", 37 | "【": "'", 38 | "】": "'", 39 | "[": "'", 40 | "]": "'", 41 | "—": "-", 42 | "~": "-", 43 | "~": "-", 44 | "「": "'", 45 | "」": "'", 46 | } 47 | 48 | 49 | class ChineseG2P: 50 | def __init__(self) -> None: 51 | self.tone_modifier = ToneSandhi() 52 | self.pinyin_to_symbol_map: Dict[str, str] = {} 53 | self.__read_opencpop_symbol_map() 54 | 55 | def __read_opencpop_symbol_map(self): 56 | """ 57 | 取读opencpop数据 58 | """ 59 | f = open("onnx/Text/opencpop-strict.txt", "r") 60 | for line in f.readlines(): 61 | self.pinyin_to_symbol_map[line.split("\t")[0]] = line.strip().split("\t")[1] 62 | f.close() 63 | 64 | @staticmethod 65 | def __get_initials_finals(word): 66 | initials = [] 67 | finals = [] 68 | orig_initials = lazy_pinyin( 69 | word, neutral_tone_with_five=True, style=Style.INITIALS 70 | ) 71 | orig_finals = lazy_pinyin( 72 | word, neutral_tone_with_five=True, style=Style.FINALS_TONE3 73 | ) 74 | for c, v in zip(orig_initials, orig_finals): 75 | initials.append(c) 76 | finals.append(v) 77 | return initials, finals 78 | 79 | def g2p(self, segments_list: List[str]): 80 | phones_list = [] 81 | tones_list = [] 82 | word2ph = [] 83 | for seg in segments_list: 84 | seg_cut = psg.lcut(seg) 85 | initials = [] 86 | finals = [] 87 | seg_cut = self.tone_modifier.pre_merge_for_modify(seg_cut) 88 | for word, pos in seg_cut: 89 | if pos == "eng": 90 | continue 91 | sub_initials, sub_finals = self.__get_initials_finals(word) 92 | sub_finals = self.tone_modifier.modified_tone(word, pos, sub_finals) 93 | initials.append(sub_initials) 94 | finals.append(sub_finals) 95 | 96 | # assert len(sub_initials) == len(sub_finals) == len(word) 97 | initials = sum(initials, []) 98 | finals = sum(finals, []) 99 | # 100 | for c, v in zip(initials, finals): 101 | raw_pinyin = c + v 102 | # NOTE: post process for pypinyin outputs 103 | # we discriminate i, ii and iii 104 | if c == v: 105 | assert c in punctuation 106 | phone = [c] 107 | tone = "0" 108 | word2ph.append(1) 109 | else: 110 | v_without_tone = v[:-1] 111 | tone = v[-1] 112 | 113 | pinyin = c + v_without_tone 114 | assert tone in "12345" 115 | 116 | if c: 117 | # 多音节 118 | v_rep_map = { 119 | "uei": "ui", 120 | "iou": "iu", 121 | "uen": "un", 122 | } 123 | if v_without_tone in v_rep_map.keys(): 124 | pinyin = c + v_rep_map[v_without_tone] 125 | else: 126 | # 单音节 127 | pinyin_rep_map = { 128 | "ing": "ying", 129 | "i": "yi", 130 | "in": "yin", 131 | "u": "wu", 132 | } 133 | if pinyin in pinyin_rep_map.keys(): 134 | pinyin = pinyin_rep_map[pinyin] 135 | else: 136 | single_rep_map = { 137 | "v": "yu", 138 | "e": "e", 139 | "i": "y", 140 | "u": "w", 141 | } 142 | if pinyin[0] in single_rep_map.keys(): 143 | pinyin = single_rep_map[pinyin[0]] + pinyin[1:] 144 | 145 | assert pinyin in self.pinyin_to_symbol_map.keys(), ( 146 | pinyin, 147 | seg, 148 | raw_pinyin, 149 | ) 150 | phone = self.pinyin_to_symbol_map[pinyin].split(" ") 151 | word2ph.append(len(phone)) 152 | 153 | phones_list += phone 154 | tones_list += [int(tone)] * len(phone) 155 | return phones_list, tones_list, word2ph 156 | 157 | 158 | chinese_g2p_instance = ChineseG2P() 159 | 160 | 161 | def g2p(text: str): 162 | """ 163 | 将文本转换成音节 164 | """ 165 | # 将文本按照标点符号切分成列表 166 | pattern = r"(?<=[{0}])\s*".format("".join(punctuation)) 167 | sentences = [i for i in re.split(pattern, text) if i.strip() != ""] 168 | # 根据切分后的列表,返回文本对应发音列表 169 | # phone:拼音的声母、韵母 170 | # tone:声调 1 2 3 4 5 171 | # word2ph:如果只有韵母,返回1,如果有声母韵母,返回2 172 | phones_list, tones_list, word2ph_list = chinese_g2p_instance.g2p(sentences) 173 | if sum(word2ph_list) != len(phones_list): 174 | raise ValueError("中文转拼音失败:音节总数(sum(word2ph_list))与音节的个数(len(phones_list))不匹配。") 175 | if len(word2ph_list) != len(text): # Sometimes it will crash,you can add a try-catch. 176 | raise ValueError("中文转拼音失败:拼音结果个数(len(word2ph_list))与文本长度(len(text))不匹配。") 177 | 178 | phones_list = ["_"] + phones_list + ["_"] 179 | log_instance.debug(f"phones {str(phones_list)}") 180 | tones_list = [0] + tones_list + [0] 181 | log_instance.debug(f"tones {str(tones_list)}") 182 | word2ph_list = [1] + word2ph_list + [1] 183 | log_instance.debug(f"word2ph {str(word2ph_list)}") 184 | return phones_list, tones_list, word2ph_list 185 | 186 | 187 | def replace_punctuation(text: str): 188 | """ 189 | 替换所有中文标点符号为指定的英文符号: ["!", "?", "…", ",", ".", "'", "-"] 190 | """ 191 | # 替换某些同音字 192 | text = text.replace("嗯", "恩").replace("呣", "母") 193 | # 将所有标点符号替换成指定英文符号 194 | pattern = re.compile("|".join(re.escape(p) for p in REP_MAP.keys())) 195 | replaced_text = pattern.sub(lambda x: REP_MAP[x.group()], text) 196 | # 剔除非指定英文符号和中文的所有字符 197 | replaced_text = re.sub( 198 | r"[^\u4e00-\u9fa5" + "".join(punctuation) + r"]+", "", replaced_text 199 | ) 200 | return replaced_text 201 | 202 | 203 | def text_normalize(text: str): 204 | """ 205 | 替换所有阿拉伯数字为中文,同时将中文符号替换为英文符号 206 | """ 207 | # 提取文本中所有的阿拉伯数字 208 | numbers = re.findall(r"\d+(?:\.?\d+)?", text) 209 | for number in numbers: 210 | # 将阿拉伯数字转中文小写数字一百二十三 211 | text = text.replace(number, cn2an.an2cn(number), 1) 212 | # 替换所有中文标点符号为指定的英文符号: ["!", "?", "…", ",", ".", "'", "-"] 213 | text = replace_punctuation(text) 214 | return text 215 | -------------------------------------------------------------------------------- /api/ui.py: -------------------------------------------------------------------------------- 1 | import os 2 | import time 3 | from log import log_instance 4 | import gradio as gr 5 | 6 | from .tts import tts_instance 7 | from .utils import rebuild_temp_dir, copy_to_clipboard 8 | from .utils import os_type_instance 9 | 10 | from config import config_instance 11 | 12 | HOST = config_instance.get("server_host", "127.0.0.1") 13 | PORT = config_instance.get("server_port", 7880) 14 | 15 | SPEAKERS_LIST = tts_instance.get_speakers_list() 16 | LANGUAGES_LIST = ["自动识别", "仅中文", "仅英文", "仅日文"] 17 | LANGUAGES_DICT = {"自动识别": "auto", "仅中文": "ZH", "仅英文": "EN", "仅日文": "JP"} 18 | 19 | 20 | def __handle_speaker_name(speaker_name): 21 | """ 22 | 处理成接口可识别的发音人名字 23 | 该方法根据模型角色名不同,自行自定义 24 | """ 25 | split_mark = "[" 26 | if split_mark in speaker_name: 27 | return "".join(speaker_name.split(split_mark)[:-1]) 28 | return speaker_name 29 | 30 | 31 | def __copy_url( 32 | speaker: str, 33 | language: str = "ZH", 34 | sdp: float = 0.2, 35 | noise: float = 0.6, 36 | noisew: float = 0.8, 37 | length: float = 1, 38 | emotion: int = 7, 39 | seed: int = 114514, 40 | ): 41 | """ 42 | # 将接口地址发送到剪切板 43 | """ 44 | language = LANGUAGES_DICT[language] 45 | # 重命名角色名 46 | speaker = __handle_speaker_name(speaker) 47 | 48 | url = ( 49 | f"http://{HOST}:{PORT}/api/tts?speaker={speaker}&text=" 50 | + "{text}" 51 | + f"&format=wav&language={language}&length={str(length)}&sdp={str(sdp)}&noise={str(noise)}&noisew={str(noisew)}&emotion={str(emotion)}&seed={str(seed)}" 52 | ) 53 | 54 | copy_to_clipboard(url) 55 | 56 | gr.Info(f"接口地址已复制到剪切板。") 57 | gr.Info(f"文件类型:wav") 58 | gr.Info(f"请求方式:GET") 59 | gr.Info(f"接口地址:{url}") 60 | 61 | 62 | def __tts( 63 | text: str, 64 | speaker: str, 65 | language: str = "ZH", 66 | sdp: float = 0.2, 67 | noise: float = 0.6, 68 | noisew: float = 0.8, 69 | length: float = 1, 70 | emotion: int = 7, 71 | seed: int = 114514, 72 | within_interval:float = 0.5, 73 | sentence_interval: float = 1.0, 74 | paragraph_interval: float = 2.0, 75 | ): 76 | log_string = f"收到文本转语音请求:{speaker} -> {text}" 77 | log_error_string = f"文本转语音推理失败:{speaker} -> {text}" 78 | 79 | language = LANGUAGES_DICT[language] 80 | # 重命名角色名 81 | speaker = __handle_speaker_name(speaker) 82 | 83 | # try: 84 | start = time.time() 85 | file_path = tts_instance.gen_tts( 86 | text=text, 87 | speaker_name=speaker, 88 | language=language, 89 | sdp_ratio=sdp, 90 | noise_scale=noise, 91 | noise_scale_w=noisew, 92 | length_scale=length, 93 | emotion=emotion, 94 | seed=seed, 95 | within_interval=within_interval, 96 | sentence_interval=sentence_interval, 97 | paragraph_interval=paragraph_interval, 98 | ) 99 | stop = time.time() 100 | log_instance.info(f"{log_string} 耗时:{str(stop - start)}") 101 | # except Exception as e: 102 | # log_instance.error(f"{log_error_string} {str(e)}") 103 | # gr.Error(f"{log_error_string} {str(e)}") 104 | # return f"文本转换语音失败,{str(e)}", None 105 | return "文本转换语音成功", file_path 106 | 107 | 108 | def webui(): 109 | """ 110 | webui界面 111 | """ 112 | with gr.Blocks() as app: 113 | with gr.Row(): 114 | with gr.Column(): 115 | gr.Markdown("欢迎使用 花花 Bert-VITS2 原神/星铁语音合成API助手") 116 | input_text = gr.TextArea(label="文本内容", placeholder="请输入需要转换语音的文本内容。") 117 | with gr.Row(): 118 | select_speaker = gr.Dropdown(choices=SPEAKERS_LIST, value=0, label="发音人") 119 | select_language = gr.Dropdown(choices=LANGUAGES_LIST, value=0, label="语言") 120 | with gr.Column(): 121 | button_generate = gr.Button(value="生成", variant="primary") 122 | button_api = gr.Button(value="获取API地址", variant="primary") 123 | # 输出 124 | output_status = gr.Textbox(label="状态信息") 125 | output_audio = gr.Audio(label="输出音频") 126 | 127 | # 其他参数 128 | with gr.Accordion(label="更多参数配置", open=False): 129 | slider_emotion = gr.Slider( 130 | minimum=0, 131 | maximum=9, 132 | value=7, 133 | step=1, 134 | interactive=True, 135 | label="情感数值 Emotion", 136 | ) 137 | slider_sdp_ratio = gr.Slider( 138 | minimum=0.1, 139 | maximum=1, 140 | value=0.2, 141 | step=0.1, 142 | interactive=True, 143 | label="语音语调 SDP Ratio", 144 | ) 145 | slider_noise_scale_w = gr.Slider( 146 | minimum=0.1, 147 | maximum=2, 148 | value=0.8, 149 | step=0.1, 150 | interactive=True, 151 | label="语音速度 Noise_W", 152 | ) 153 | slider_noise_scale = gr.Slider( 154 | minimum=0.1, 155 | maximum=2, 156 | value=0.6, 157 | step=0.1, 158 | interactive=True, 159 | label="感情变化 Noise", 160 | ) 161 | slider_length_scale = gr.Slider( 162 | minimum=0.1, 163 | maximum=2, 164 | value=1.0, 165 | step=0.1, 166 | interactive=True, 167 | label="音节长度 Length", 168 | ) 169 | slider_seed = gr.Slider( 170 | minimum=0, 171 | maximum=1000000, 172 | value=114514, 173 | step=1000, 174 | interactive=True, 175 | randomize=True, 176 | label="随机种子 Seed", 177 | ) 178 | within_interval = gr.Slider( 179 | minimum=0, 180 | maximum=10.0, 181 | value=0.5, 182 | step=0.1, 183 | label="句内停顿(秒) ", 184 | ) 185 | sentence_interval = gr.Slider( 186 | minimum=0, 187 | maximum=10.0, 188 | value=1.0, 189 | step=0.1, 190 | label="句间停顿(秒) ", 191 | ) 192 | paragraph_interval = gr.Slider( 193 | minimum=0, 194 | maximum=10.0, 195 | value=2.0, 196 | step=0.1, 197 | label="段间停顿(秒) ", 198 | ) 199 | 200 | # 生成按钮事件 201 | button_generate.click( 202 | __tts, 203 | inputs=[ 204 | input_text, 205 | select_speaker, 206 | select_language, 207 | slider_sdp_ratio, 208 | slider_noise_scale, 209 | slider_noise_scale_w, 210 | slider_length_scale, 211 | slider_emotion, 212 | slider_seed, 213 | within_interval, 214 | sentence_interval, 215 | paragraph_interval, 216 | ], 217 | outputs=[output_status, output_audio], 218 | ) 219 | # API按钮事件 220 | button_api.click( 221 | __copy_url, 222 | inputs=[ 223 | select_speaker, 224 | select_language, 225 | slider_sdp_ratio, 226 | slider_noise_scale, 227 | slider_noise_scale_w, 228 | slider_length_scale, 229 | slider_emotion, 230 | slider_seed, 231 | ], 232 | ) 233 | 234 | # 重新建立缓存文件夹(for windows) 235 | if os_type_instance.type == "Windows": 236 | temp_path = os.path.join(os.path.dirname(os.getenv("APPDATA")), "Temp/gradio/") 237 | rebuild_temp_dir(temp_path, tips="正在清空Gradio组件语音缓存...") 238 | 239 | return app 240 | 241 | 242 | app = webui() 243 | -------------------------------------------------------------------------------- /api/split.py: -------------------------------------------------------------------------------- 1 | import re 2 | from typing import Tuple,List 3 | 4 | 5 | def __split_jp_text(text: str): 6 | """ 7 | 提取日语 8 | 文心一言说过: 9 | 在日语中,连续出现的中文字符的数量通常是受限于句子的长度和语境。在正常的日语表达中,连续出现的中文字符一般不会超过两个。 10 | 这是因为日语中的汉字通常只用于表示具有特定含义的词,而平假名和片假名则用于表示日语中的音节。因此,连续出现三个或更多的中文字符在日语中并不常见,也不是日语的常规用法。 11 | 当然,在一些特定的语境下,比如使用汉字表示某种特殊的含义或者是因为某种特定的文化背景,可能会出现连续出现三个或更多的中文字符的情况。但这种情况并不常见,也不是日语的常规用法。 12 | 13 | 所以这里匹配连续5个中文字符 14 | """ 15 | jp_segments = [] 16 | # 仅提取最多5个连续字符的中文字符 17 | zh_pattern = re.compile(r"[\u4e00-\u9fff]+") 18 | zh_char_dict = {} 19 | for match in zh_pattern.finditer(text): 20 | match_text = match.group().strip() 21 | if not match_text: 22 | continue 23 | # 仅提取最多5个连续字符 24 | if len(match_text) > 5: 25 | continue 26 | zh_char_dict[str(match.end())] = match_text 27 | 28 | # print(zh_char_dict) 29 | 30 | # 提取日文 31 | jp_pattern = re.compile( 32 | r"[\u3040-\u309F\u30A0-\u30FF\uFF65-\uFF9F々0-9\s]+" 33 | ) # 日文字符的Unicode范围 34 | 35 | jp_chars_list = [] 36 | for match in jp_pattern.finditer(text): 37 | match_text = match.group().strip() 38 | if not match_text: 39 | continue 40 | if match_text.isdigit(): 41 | continue 42 | char_start = match.start() 43 | char_end = match.end() 44 | # 是否有相邻中文字符,如果有,标记为日语 45 | zh_char = zh_char_dict.get(str(char_start), None) 46 | if zh_char: 47 | char_start = char_start - len(zh_char) 48 | match_text = zh_char + match_text 49 | jp_chars_list.append((char_start, char_end, match_text)) 50 | 51 | if len(jp_chars_list) == 0: 52 | return [] 53 | 54 | # 获取最后一个日语字符后面的中文 55 | last_jp_char_end = jp_chars_list[-1][1] 56 | for zh_char_end in zh_char_dict: 57 | zh_char_length = len(zh_char_dict[zh_char_end]) 58 | if last_jp_char_end != int(zh_char_end) - len(zh_char_dict[zh_char_end]): 59 | continue 60 | jp_chars_list.append( 61 | ( 62 | last_jp_char_end, 63 | last_jp_char_end + zh_char_length, 64 | zh_char_dict[zh_char_end], 65 | ) 66 | ) 67 | 68 | jp_segments = [] 69 | font_jp_chars_tuple = jp_chars_list[0] 70 | font_start = font_jp_chars_tuple[0] 71 | font_end = font_jp_chars_tuple[1] 72 | font_text = font_jp_chars_tuple[2] 73 | 74 | for index, jp_chars_tuple in enumerate(jp_chars_list): 75 | if index == 0: 76 | continue 77 | start, end, text = jp_chars_tuple 78 | 79 | if start == font_end: 80 | # 如果当前元素的起始位置与前一个元素的结束位置相同,则将文本拼接到前一个元素的文本后面 81 | font_end = end 82 | font_text = font_text + text 83 | else: 84 | # 将前一个加入列表 85 | jp_segments.append((font_start, font_end, font_text, "JP")) 86 | # 否则,将当前元素加入前一个 87 | font_start = start 88 | font_end = end 89 | font_text = text 90 | 91 | # 将最后一个加入列表 92 | jp_segments.append((font_start, font_end, font_text, "JP")) 93 | 94 | # 判断是否为纯数字 95 | if len(jp_segments) != 1: 96 | return jp_segments 97 | 98 | match_text: str = jp_segments[0][2] 99 | if match_text.isdigit(): 100 | return [] 101 | else: 102 | return jp_segments 103 | 104 | 105 | def __split_en_text(text: str): 106 | """ 107 | 提取英语 108 | """ 109 | en_segments = [] 110 | en_pattern = re.compile(r"[a-zA-Z0-9\s]+") 111 | # 提取包含连续英文数字空格的字符串 112 | en_pattern = re.compile(r"[a-zA-Z0-9\s]+") 113 | for match in en_pattern.finditer(text): 114 | match_text = match.group().strip() 115 | if not match_text: 116 | continue 117 | en_segments.append((match.start(), match.end(), match_text, "EN")) 118 | 119 | # 如果非全数字,直接返回 120 | for segment in en_segments: 121 | match_text: str = segment[2] 122 | if not match_text.isdigit(): 123 | return en_segments 124 | 125 | # 如果是全数据,返回空 126 | return [] 127 | 128 | 129 | def __split_jp_en_text(text: str): 130 | """ 131 | 切割混合语言文本(日、英) 132 | """ 133 | en_segments = __split_en_text(text) 134 | # 提取日语 135 | jp_segments = __split_jp_text(text) 136 | segments = en_segments + jp_segments 137 | 138 | return segments 139 | 140 | 141 | def __extract_chinese(text: str): 142 | """ 143 | 提取中文词和数字 144 | """ 145 | # 提取中文词 146 | pattern = re.compile(r"[\u4e00-\u9fff0-9]+") 147 | chinese_chars = re.findall(pattern, text) 148 | if len(chinese_chars) == 0: 149 | return None 150 | return ",".join(chinese_chars) 151 | 152 | 153 | def __divide_text(text: str, intervals: list): 154 | """ 155 | 三语言混合 156 | """ 157 | # 对输入的区间列表按照起始索引进行排序 158 | intervals.sort(key=lambda x: x[0]) 159 | # 判断输入的索引是否合法 160 | parts = [] 161 | if len(intervals) > 0: 162 | if intervals[0][0] < 0 or intervals[-1][1] > len(text): 163 | return [] 164 | 165 | # 划分出第一个区间前面的部分,并将其添加到列表头部 166 | first_start = intervals[0][0] 167 | 168 | if first_start > 0: 169 | first_part_text = __extract_chinese(text[:first_start]) 170 | if first_part_text: 171 | first_part_info = (0, first_start, first_part_text, "ZH") 172 | parts.insert(0, first_part_info) 173 | 174 | # 划分出各个区间之间的部分,并存储到列表中 175 | for i in range(len(intervals) - 1): 176 | parts.append(intervals[i]) 177 | start, end = intervals[i][1], intervals[i + 1][0] 178 | part_text = __extract_chinese(text[start:end]) 179 | if not part_text: 180 | continue 181 | part_info = (intervals[i][1], intervals[i + 1][0], part_text, "ZH") 182 | parts.append(part_info) 183 | 184 | # 划分出最后一个区间后面的部分,并将其添加到列表末尾 185 | parts.append(intervals[-1]) 186 | last_end = intervals[-1][1] 187 | # 如果text不是以最后的区间结尾 188 | if last_end < len(text) - 1: 189 | # 继续提取中文 190 | last_part_text = __extract_chinese(text[last_end:]) 191 | if last_part_text: 192 | last_part_info = (last_end, len(text) - 1, last_part_text, "ZH") 193 | parts.append(last_part_info) 194 | else: 195 | zh_text = __extract_chinese(text) 196 | if zh_text: 197 | parts = [(0, len(zh_text), zh_text, "ZH")] 198 | 199 | # 返回划分后的结果 200 | return parts 201 | 202 | 203 | def __correct_digst_to_zh(text_segments:List[Tuple[int,int,str,str]]): 204 | """ 205 | 修正混合句子中的数字为中文 206 | """ 207 | # 判断句子中是否存在中文混合 208 | is_zh_mix = False 209 | for segment in text_segments: 210 | if segment[3] != 'ZH': 211 | continue 212 | is_zh_mix = True 213 | break 214 | 215 | if not is_zh_mix: 216 | return text_segments 217 | 218 | # 修正混合句子中的数字为中文 219 | new_text_segments = [] 220 | for segment in iter(text_segments): 221 | if not segment[2].isdigit(): 222 | new_text_segments.append(segment) 223 | continue 224 | new_text_segments.append((segment[0],segment[1],segment[2],"ZH")) 225 | 226 | return new_text_segments 227 | 228 | def split_text(text: str) -> Tuple[list, list]: 229 | """ 230 | 自动切割混合文本 231 | """ 232 | print(text) 233 | other_text_segments = __split_jp_en_text(text) 234 | print(other_text_segments) 235 | # print(other_text_segments) 236 | text_segments = __divide_text(text, other_text_segments) 237 | print(text_segments) 238 | text_segments = __correct_digst_to_zh(text_segments) 239 | print(text_segments) 240 | 241 | if not text_segments: 242 | return None 243 | 244 | text_list = [] 245 | language_list = [] 246 | for text_segment in text_segments: 247 | text_list.append(text_segment[2]) 248 | language_list.append(text_segment[3]) 249 | print(text_list, language_list) 250 | return text_list, language_list 251 | 252 | 253 | def __split_by_paragraph(text: str): 254 | """ 255 | 将长文本按段落划分。 256 | """ 257 | text_list = text.split("\n") 258 | # 排除包含多个空格在内的空字符串 259 | text_list = [text.strip() for text in text_list if re.search(r"\S", text)] 260 | return text_list 261 | 262 | 263 | def __split_by_sentence(text: str): 264 | """ 265 | 将单段落文本按句子划分。 266 | """ 267 | text_list = re.split(r"[。\.\?\?\!\!]+", text) 268 | # 排除包含多个空格在内的空字符串 269 | text_list = [text.strip() for text in text_list if re.search(r"\S", text)] 270 | return text_list 271 | 272 | 273 | def __split_by_within_sentence(text: str): 274 | """ 275 | 句子内停顿 276 | """ 277 | text_list = re.split(r"[\;\;\、\,\,]+", text) 278 | text_list = [text.strip() for text in text_list if re.search(r"\S", text)] 279 | return text_list 280 | 281 | 282 | def text_split_to_sentence(text: str) -> list: 283 | """ 284 | 将长文本按段落、句子、句内分别划分,生成三级列表 285 | """ 286 | # 首先按段落划分 287 | text_paragraph_list = __split_by_paragraph(text=text) 288 | # print(text_paragraph_list) 289 | if len(text_paragraph_list) == 0: 290 | return [] 291 | third_list = [] 292 | for text_paragraph in text_paragraph_list: 293 | # 按句子划分 294 | secondary_list = [] 295 | text_sentence_list = __split_by_sentence(text_paragraph) 296 | for text_sentence in text_sentence_list: 297 | # print(__split_by_within_sentence(text_sentence)) 298 | secondary_list.append(__split_by_within_sentence(text_sentence)) 299 | third_list.append(secondary_list) 300 | return third_list 301 | -------------------------------------------------------------------------------- /api/tts.py: -------------------------------------------------------------------------------- 1 | import os 2 | import numpy as np 3 | from uuid import uuid4 4 | from log import log_instance 5 | from config import config_instance 6 | from scipy.io import wavfile 7 | from typing import Callable, List 8 | from dataclasses import dataclass 9 | from onnx_infer.onnx_infer import infor_onnx_instance 10 | 11 | from .split import split_text, text_split_to_sentence 12 | from .utils import rebuild_temp_dir 13 | 14 | EMOTION = 7 15 | SDP_RATIO = 0.2 16 | NOISE = 0.6 17 | NOISEW = 0.8 18 | LENGTH = 0.8 19 | LANGUAGE = "ZH" 20 | AUDIO_RATE = 44100 21 | 22 | TEMP_PATH = os.path.abspath("./temp") 23 | 24 | 25 | def change_to_wav( 26 | file_path: str, data: np.float32, sample_rate: int = AUDIO_RATE 27 | ) -> str: 28 | """ 29 | 将返回的numpy数据转换成音频 30 | """ 31 | scaled_data = np.int16(data * 32767) 32 | wavfile.write(file_path, sample_rate, scaled_data) 33 | return file_path 34 | 35 | 36 | def __generate_empty_float32(sample_rate: int = AUDIO_RATE) -> tuple: 37 | """ 38 | 生成空音频的numpy数据 39 | """ 40 | return tuple( 41 | sample_rate, 42 | np.concatenate([np.zeros(sample_rate // 2)]), 43 | ) 44 | 45 | 46 | def __generate_slient_audio( 47 | interval_time: float = 1.5, sample_rate: int = AUDIO_RATE 48 | ) -> np.float32: 49 | """ 50 | 生成指定秒数的空音频数据 51 | """ 52 | return np.zeros((int)(sample_rate * interval_time), dtype=np.float32).reshape( 53 | 1, 1, int(sample_rate * interval_time) 54 | ) 55 | 56 | 57 | def __generate_single_audio( 58 | text: str, 59 | speaker_name: str, 60 | language: str = "ZH", 61 | sdp_ratio: float = SDP_RATIO, 62 | noise_scale: float = NOISE, 63 | noise_scale_w: float = NOISEW, 64 | length_scale: float = LENGTH, 65 | emotion: float = EMOTION, 66 | seed: int = 114514, 67 | ) -> np.float32: 68 | """ 69 | 根据text生成单语言音频 70 | """ 71 | audio = infor_onnx_instance.infer( 72 | text=text, 73 | speaker_name=speaker_name, 74 | language=language, 75 | sdp_ratio=sdp_ratio, 76 | noise_scale=noise_scale, 77 | noise_scale_w=noise_scale_w, 78 | length_scale=length_scale, 79 | emotion=emotion, 80 | seed=seed, 81 | ) 82 | return audio 83 | 84 | 85 | def __generate_multilang_audio( 86 | text: str, 87 | speaker_name: str, 88 | sdp_ratio: float = SDP_RATIO, 89 | noise_scale: float = NOISE, 90 | noise_scale_w: float = NOISEW, 91 | length_scale: float = LENGTH, 92 | emotion: float = EMOTION, 93 | seed: int = 114514, 94 | ) -> np.float32: 95 | """ 96 | 根据text自动切分,生成多语言混合音频 97 | """ 98 | text_list, language_list = split_text(text) 99 | 100 | if not language_list: 101 | log_instance.warning("文本转语音推理失败:{speaker_name} -> {text} 文本内容不可为空。") 102 | return __generate_empty_float32() 103 | 104 | elif len(language_list) == 1: 105 | audio = infor_onnx_instance.infer( 106 | text=text_list[0], 107 | speaker_name=speaker_name, 108 | language=language_list[0], 109 | sdp_ratio=sdp_ratio, 110 | noise_scale=noise_scale, 111 | noise_scale_w=noise_scale_w, 112 | length_scale=length_scale, 113 | emotion=emotion, 114 | seed=seed, 115 | ) 116 | else: 117 | audio = infor_onnx_instance.infer_multilang( 118 | text_list=text_list, 119 | speaker_name=speaker_name, 120 | language_list=language_list, 121 | sdp_ratio=sdp_ratio, 122 | noise_scale=noise_scale, 123 | noise_scale_w=noise_scale_w, 124 | length_scale=length_scale, 125 | emotion=emotion, 126 | seed=seed, 127 | ) 128 | return audio 129 | 130 | 131 | def __generate_multi_within( 132 | text_list: List[str], 133 | speaker_name: str, 134 | language: str = "ZH", 135 | sdp_ratio: float = SDP_RATIO, 136 | noise_scale: float = NOISE, 137 | noise_scale_w: float = NOISEW, 138 | length_scale: float = LENGTH, 139 | emotion: float = EMOTION, 140 | seed: int = 114514, 141 | within_interval: float = 0.5, 142 | ) -> np.float32: 143 | """ 144 | 根据多个句内文字段生成语音 145 | """ 146 | # 获取局部变量 147 | params_dict: dict = locals() 148 | del params_dict["text_list"] 149 | del params_dict["within_interval"] 150 | 151 | within_audio_list = [] 152 | list_length = len(text_list) 153 | 154 | for index, text in enumerate(text_list): 155 | params_dict["text"] = text 156 | log_instance.info( 157 | f"正在推理({str(index+1)}/{str(list_length)}):{speaker_name} -> {text}" 158 | ) 159 | 160 | # 判断是否需要自动多语言切分 161 | if language.lower() == "auto": 162 | try: 163 | del params_dict["language"] 164 | except KeyError: 165 | pass 166 | audio = __generate_multilang_audio(**params_dict) 167 | else: 168 | params_dict["language"] = language 169 | audio = __generate_single_audio(**params_dict) 170 | 171 | # 将所有语音句子数据存入列表中 172 | within_audio_list.append(audio) 173 | # 插入静音数据 174 | slient_audio = __generate_slient_audio(interval_time=within_interval) 175 | within_audio_list.append(slient_audio) 176 | 177 | # 删除最后一个静音数据 178 | within_audio_list.pop() 179 | # 将列表中的语音数据合成 180 | audio_concat = np.concatenate(within_audio_list, axis=2) 181 | 182 | return audio_concat 183 | 184 | 185 | def __generate_multi_sentence( 186 | text_list: List[str], 187 | speaker_name: str, 188 | language: str = "ZH", 189 | sdp_ratio: float = SDP_RATIO, 190 | noise_scale: float = NOISE, 191 | noise_scale_w: float = NOISEW, 192 | length_scale: float = LENGTH, 193 | emotion: float = EMOTION, 194 | seed: int = 114514, 195 | within_interval: float = 0.5, 196 | sentence_interval: float = 1.0, 197 | ) -> np.float32: 198 | """ 199 | 根据多个句子生成语音 200 | """ 201 | # 获取局部变量 202 | params_dict: dict = locals() 203 | del params_dict["text_list"] 204 | del params_dict["sentence_interval"] 205 | 206 | sentence_audio_list = [] 207 | for whithin_text_list in text_list: 208 | # 句子列表数据合成一个段落音频数据 209 | params_dict["text_list"] = whithin_text_list 210 | sentence_audio = __generate_multi_within(**params_dict) 211 | sentence_audio_list.append(sentence_audio) 212 | # 插入静音数据 213 | slient_audio = __generate_slient_audio(interval_time=sentence_interval) 214 | sentence_audio_list.append(slient_audio) 215 | # 删除最后一个静音数据 216 | sentence_audio_list.pop() 217 | audio_concat = np.concatenate(sentence_audio_list, axis=2) 218 | return audio_concat 219 | 220 | 221 | def generate_tts_auto( 222 | text: str, 223 | speaker_name: str, 224 | language: str = "ZH", 225 | sdp_ratio: float = 0.2, 226 | noise_scale: float = 0.6, 227 | noise_scale_w: float = 0.8, 228 | length_scale: float = 1.0, 229 | emotion: int = 7, 230 | seed: int = 114514, 231 | within_interval: float = 0.5, 232 | sentence_interval: float = 1.0, 233 | paragraph_interval: float = 2.0, 234 | ) -> np.float32: 235 | """ 236 | 自动切分,生成语音 237 | """ 238 | # 获取局部变量 239 | params_dict: dict = locals() 240 | del params_dict["text"] 241 | del params_dict["paragraph_interval"] 242 | 243 | # 根据文本进行按句子切分成三级列表 244 | paragraph_sentences_text_list = text_split_to_sentence(text=text) 245 | log_instance.debug(f"自动切分结果 {str(paragraph_sentences_text_list)}") 246 | # 检测文本是否为空,为空直接返回空音频 247 | if len(paragraph_sentences_text_list) == 0: 248 | log_instance.warning("文本转语音推理失败:{speaker_name} -> {text} 文本内容不可为空。") 249 | return __generate_empty_float32() 250 | 251 | # 获取每一个段落所有句子的语音数据 252 | paragraph_audio_list = [] 253 | for sentences_text_list in paragraph_sentences_text_list: 254 | # 句子列表数据合成一个段落音频数据 255 | params_dict["text_list"] = sentences_text_list 256 | paragraph_audio = __generate_multi_sentence(**params_dict) 257 | paragraph_audio_list.append(paragraph_audio) 258 | # 插入静音数据 259 | slient_audio = __generate_slient_audio(interval_time=paragraph_interval) 260 | paragraph_audio_list.append(slient_audio) 261 | # 删除最后一个静音数据 262 | paragraph_audio_list.pop() 263 | audio_concat = np.concatenate(paragraph_audio_list, axis=2) 264 | return audio_concat 265 | 266 | 267 | @dataclass 268 | class InferHander: 269 | single: Callable = None 270 | auto: Callable = None 271 | 272 | 273 | class GenerateTTS: 274 | def __init__(self) -> None: 275 | # 重建语音缓存文件夹 276 | rebuild_temp_dir(TEMP_PATH) 277 | # 加载onnx推理实例 278 | self.onnx_infer = infor_onnx_instance 279 | 280 | def get_speakers_list(self, chinese_only: bool = True) -> list: 281 | """ 282 | 获取处理过后的角色列表 283 | """ 284 | 285 | if not chinese_only: 286 | return self.onnx_infer.speakers_list 287 | 288 | speakers_list = [] 289 | chinese_mark = config_instance.get("onnx_tts_models_chinese_mark", "中文") 290 | 291 | for speaker_name in self.onnx_infer.speakers_list: 292 | if chinese_mark not in speaker_name: 293 | continue 294 | speakers_list.append( 295 | speaker_name.replace(chinese_mark, "") 296 | .replace("-", "") 297 | .replace("_", "") 298 | .replace("(", "[") 299 | .replace(")", "]") 300 | ) 301 | return speakers_list 302 | 303 | def gen_tts( 304 | self, 305 | text: str, 306 | speaker_name: str, 307 | language: str = "ZH", 308 | sdp_ratio: float = 0.2, 309 | noise_scale: float = 0.6, 310 | noise_scale_w: float = 0.8, 311 | length_scale: float = 1.0, 312 | emotion: int = 7, 313 | seed: int = 114514, 314 | within_interval: float = 0.5, 315 | sentence_interval: float = 1.0, 316 | paragraph_interval: float = 2.0, 317 | ): 318 | """ 319 | tts生成 320 | """ 321 | # 获取传入参数 322 | params_dict: dict = locals() 323 | del params_dict["self"] 324 | 325 | audio = generate_tts_auto(**params_dict) 326 | 327 | file_path = os.path.join(TEMP_PATH, uuid4().hex + ".wav") 328 | file_path = change_to_wav(file_path, audio) 329 | return file_path 330 | 331 | 332 | tts_instance = GenerateTTS() 333 | -------------------------------------------------------------------------------- /onnx_infer/text/english.py: -------------------------------------------------------------------------------- 1 | import pickle 2 | import os 3 | import re 4 | from g2p_en import G2p 5 | 6 | from .symbols import symbols 7 | from .tokenizer import tokenizer_instance 8 | 9 | CMU_DICT_PATH = "onnx/Text/cmudict.rep" 10 | CACHE_PATH = "onnx/Text/cmudict_cache.pickle" 11 | 12 | tokenizer = tokenizer_instance.EN 13 | 14 | _g2p = G2p() 15 | 16 | arpa = { 17 | "AH0", 18 | "S", 19 | "AH1", 20 | "EY2", 21 | "AE2", 22 | "EH0", 23 | "OW2", 24 | "UH0", 25 | "NG", 26 | "B", 27 | "G", 28 | "AY0", 29 | "M", 30 | "AA0", 31 | "F", 32 | "AO0", 33 | "ER2", 34 | "UH1", 35 | "IY1", 36 | "AH2", 37 | "DH", 38 | "IY0", 39 | "EY1", 40 | "IH0", 41 | "K", 42 | "N", 43 | "W", 44 | "IY2", 45 | "T", 46 | "AA1", 47 | "ER1", 48 | "EH2", 49 | "OY0", 50 | "UH2", 51 | "UW1", 52 | "Z", 53 | "AW2", 54 | "AW1", 55 | "V", 56 | "UW2", 57 | "AA2", 58 | "ER", 59 | "AW0", 60 | "UW0", 61 | "R", 62 | "OW1", 63 | "EH1", 64 | "ZH", 65 | "AE0", 66 | "IH2", 67 | "IH", 68 | "Y", 69 | "JH", 70 | "P", 71 | "AY1", 72 | "EY0", 73 | "OY2", 74 | "TH", 75 | "HH", 76 | "D", 77 | "ER0", 78 | "CH", 79 | "AO1", 80 | "AE1", 81 | "AO2", 82 | "OY1", 83 | "AY2", 84 | "IH1", 85 | "OW0", 86 | "L", 87 | "SH", 88 | } 89 | 90 | 91 | def post_replace_ph(ph): 92 | rep_map = { 93 | ":": ",", 94 | ";": ",", 95 | ",": ",", 96 | "。": ".", 97 | "!": "!", 98 | "?": "?", 99 | "\n": ".", 100 | "·": ",", 101 | "、": ",", 102 | "…": "...", 103 | "···": "...", 104 | "・・・": "...", 105 | "v": "V", 106 | } 107 | if ph in rep_map.keys(): 108 | ph = rep_map[ph] 109 | if ph in symbols: 110 | return ph 111 | if ph not in symbols: 112 | ph = "UNK" 113 | return ph 114 | 115 | 116 | rep_map = { 117 | ":": ",", 118 | ";": ",", 119 | ",": ",", 120 | "。": ".", 121 | "!": "!", 122 | "?": "?", 123 | "\n": ".", 124 | ".": ".", 125 | "…": "...", 126 | "···": "...", 127 | "・・・": "...", 128 | "·": ",", 129 | "・": ",", 130 | "、": ",", 131 | "$": ".", 132 | "“": "'", 133 | "”": "'", 134 | '"': "'", 135 | "‘": "'", 136 | "’": "'", 137 | "(": "'", 138 | ")": "'", 139 | "(": "'", 140 | ")": "'", 141 | "《": "'", 142 | "》": "'", 143 | "【": "'", 144 | "】": "'", 145 | "[": "'", 146 | "]": "'", 147 | "—": "-", 148 | "−": "-", 149 | "~": "-", 150 | "~": "-", 151 | "「": "'", 152 | "」": "'", 153 | } 154 | 155 | 156 | def replace_punctuation(text): 157 | pattern = re.compile("|".join(re.escape(p) for p in rep_map.keys())) 158 | 159 | replaced_text = pattern.sub(lambda x: rep_map[x.group()], text) 160 | 161 | # replaced_text = re.sub( 162 | # r"[^\u3040-\u309F\u30A0-\u30FF\u4E00-\u9FFF\u3400-\u4DBF\u3005" 163 | # + "".join(punctuation) 164 | # + r"]+", 165 | # "", 166 | # replaced_text, 167 | # ) 168 | 169 | return replaced_text 170 | 171 | 172 | def read_dict(): 173 | g2p_dict = {} 174 | start_line = 49 175 | with open(CMU_DICT_PATH) as f: 176 | line = f.readline() 177 | line_index = 1 178 | while line: 179 | if line_index >= start_line: 180 | line = line.strip() 181 | word_split = line.split(" ") 182 | word = word_split[0] 183 | 184 | syllable_split = word_split[1].split(" - ") 185 | g2p_dict[word] = [] 186 | for syllable in syllable_split: 187 | phone_split = syllable.split(" ") 188 | g2p_dict[word].append(phone_split) 189 | 190 | line_index = line_index + 1 191 | line = f.readline() 192 | 193 | return g2p_dict 194 | 195 | 196 | def cache_dict(g2p_dict, file_path): 197 | with open(file_path, "wb") as pickle_file: 198 | pickle.dump(g2p_dict, pickle_file) 199 | 200 | 201 | def get_dict(): 202 | if os.path.exists(CACHE_PATH): 203 | with open(CACHE_PATH, "rb") as pickle_file: 204 | g2p_dict = pickle.load(pickle_file) 205 | else: 206 | g2p_dict = read_dict() 207 | cache_dict(g2p_dict, CACHE_PATH) 208 | 209 | return g2p_dict 210 | 211 | 212 | eng_dict = get_dict() 213 | 214 | 215 | def refine_ph(phn): 216 | tone = 0 217 | if re.search(r"\d$", phn): 218 | tone = int(phn[-1]) + 1 219 | phn = phn[:-1] 220 | return phn.lower(), tone 221 | 222 | 223 | def refine_syllables(syllables): 224 | tones = [] 225 | phonemes = [] 226 | for phn_list in syllables: 227 | for i in range(len(phn_list)): 228 | phn = phn_list[i] 229 | phn, tone = refine_ph(phn) 230 | phonemes.append(phn) 231 | tones.append(tone) 232 | return phonemes, tones 233 | 234 | 235 | import re 236 | import inflect 237 | 238 | _inflect = inflect.engine() 239 | _comma_number_re = re.compile(r"([0-9][0-9\,]+[0-9])") 240 | _decimal_number_re = re.compile(r"([0-9]+\.[0-9]+)") 241 | _pounds_re = re.compile(r"£([0-9\,]*[0-9]+)") 242 | _dollars_re = re.compile(r"\$([0-9\.\,]*[0-9]+)") 243 | _ordinal_re = re.compile(r"[0-9]+(st|nd|rd|th)") 244 | _number_re = re.compile(r"[0-9]+") 245 | 246 | # List of (regular expression, replacement) pairs for abbreviations: 247 | _abbreviations = [ 248 | (re.compile("\\b%s\\." % x[0], re.IGNORECASE), x[1]) 249 | for x in [ 250 | ("mrs", "misess"), 251 | ("mr", "mister"), 252 | ("dr", "doctor"), 253 | ("st", "saint"), 254 | ("co", "company"), 255 | ("jr", "junior"), 256 | ("maj", "major"), 257 | ("gen", "general"), 258 | ("drs", "doctors"), 259 | ("rev", "reverend"), 260 | ("lt", "lieutenant"), 261 | ("hon", "honorable"), 262 | ("sgt", "sergeant"), 263 | ("capt", "captain"), 264 | ("esq", "esquire"), 265 | ("ltd", "limited"), 266 | ("col", "colonel"), 267 | ("ft", "fort"), 268 | ] 269 | ] 270 | 271 | 272 | # List of (ipa, lazy ipa) pairs: 273 | _lazy_ipa = [ 274 | (re.compile("%s" % x[0]), x[1]) 275 | for x in [ 276 | ("r", "ɹ"), 277 | ("æ", "e"), 278 | ("ɑ", "a"), 279 | ("ɔ", "o"), 280 | ("ð", "z"), 281 | ("θ", "s"), 282 | ("ɛ", "e"), 283 | ("ɪ", "i"), 284 | ("ʊ", "u"), 285 | ("ʒ", "ʥ"), 286 | ("ʤ", "ʥ"), 287 | ("ˈ", "↓"), 288 | ] 289 | ] 290 | 291 | # List of (ipa, lazy ipa2) pairs: 292 | _lazy_ipa2 = [ 293 | (re.compile("%s" % x[0]), x[1]) 294 | for x in [ 295 | ("r", "ɹ"), 296 | ("ð", "z"), 297 | ("θ", "s"), 298 | ("ʒ", "ʑ"), 299 | ("ʤ", "dʑ"), 300 | ("ˈ", "↓"), 301 | ] 302 | ] 303 | 304 | # List of (ipa, ipa2) pairs 305 | _ipa_to_ipa2 = [ 306 | (re.compile("%s" % x[0]), x[1]) for x in [("r", "ɹ"), ("ʤ", "dʒ"), ("ʧ", "tʃ")] 307 | ] 308 | 309 | 310 | def _expand_dollars(m): 311 | match = m.group(1) 312 | parts = match.split(".") 313 | if len(parts) > 2: 314 | return match + " dollars" # Unexpected format 315 | dollars = int(parts[0]) if parts[0] else 0 316 | cents = int(parts[1]) if len(parts) > 1 and parts[1] else 0 317 | if dollars and cents: 318 | dollar_unit = "dollar" if dollars == 1 else "dollars" 319 | cent_unit = "cent" if cents == 1 else "cents" 320 | return "%s %s, %s %s" % (dollars, dollar_unit, cents, cent_unit) 321 | elif dollars: 322 | dollar_unit = "dollar" if dollars == 1 else "dollars" 323 | return "%s %s" % (dollars, dollar_unit) 324 | elif cents: 325 | cent_unit = "cent" if cents == 1 else "cents" 326 | return "%s %s" % (cents, cent_unit) 327 | else: 328 | return "zero dollars" 329 | 330 | 331 | def _remove_commas(m): 332 | return m.group(1).replace(",", "") 333 | 334 | 335 | def _expand_ordinal(m): 336 | return _inflect.number_to_words(m.group(0)) 337 | 338 | 339 | def _expand_number(m): 340 | num = int(m.group(0)) 341 | if num > 1000 and num < 3000: 342 | if num == 2000: 343 | return "two thousand" 344 | elif num > 2000 and num < 2010: 345 | return "two thousand " + _inflect.number_to_words(num % 100) 346 | elif num % 100 == 0: 347 | return _inflect.number_to_words(num // 100) + " hundred" 348 | else: 349 | return _inflect.number_to_words( 350 | num, andword="", zero="oh", group=2 351 | ).replace(", ", " ") 352 | else: 353 | return _inflect.number_to_words(num, andword="") 354 | 355 | 356 | def _expand_decimal_point(m): 357 | return m.group(1).replace(".", " point ") 358 | 359 | 360 | def normalize_numbers(text): 361 | text = re.sub(_comma_number_re, _remove_commas, text) 362 | text = re.sub(_pounds_re, r"\1 pounds", text) 363 | text = re.sub(_dollars_re, _expand_dollars, text) 364 | text = re.sub(_decimal_number_re, _expand_decimal_point, text) 365 | text = re.sub(_ordinal_re, _expand_ordinal, text) 366 | text = re.sub(_number_re, _expand_number, text) 367 | return text 368 | 369 | 370 | def text_normalize(text): 371 | text = normalize_numbers(text) 372 | text = replace_punctuation(text) 373 | text = re.sub(r"([,;.\?\!])([\w])", r"\1 \2", text) 374 | return text 375 | 376 | 377 | def distribute_phone(n_phone, n_word): 378 | phones_per_word = [0] * n_word 379 | for task in range(n_phone): 380 | min_tasks = min(phones_per_word) 381 | min_index = phones_per_word.index(min_tasks) 382 | phones_per_word[min_index] += 1 383 | return phones_per_word 384 | 385 | 386 | def sep_text(text): 387 | words = re.split(r"([,;.\?\!\s+])", text) 388 | words = [word for word in words if word.strip() != ""] 389 | return words 390 | 391 | 392 | def g2p(text): 393 | phones = [] 394 | tones = [] 395 | # word2ph = [] 396 | words = sep_text(text) 397 | # print(words) 398 | # tokens = [f"▁{i}" for i in words] 399 | tokens = [tokenizer.tokenize(i) for i in words] 400 | # print(tokens) 401 | for word in words: 402 | if word.upper() in eng_dict: 403 | phns, tns = refine_syllables(eng_dict[word.upper()]) 404 | phones.append([post_replace_ph(i) for i in phns]) 405 | tones.append(tns) 406 | # word2ph.append(len(phns)) 407 | else: 408 | phone_list = list(filter(lambda p: p != " ", _g2p(word))) 409 | phns = [] 410 | tns = [] 411 | for ph in phone_list: 412 | if ph in arpa: 413 | ph, tn = refine_ph(ph) 414 | phns.append(ph) 415 | tns.append(tn) 416 | else: 417 | phns.append(ph) 418 | tns.append(0) 419 | phones.append([post_replace_ph(i) for i in phns]) 420 | tones.append(tns) 421 | # word2ph.append(len(phns)) 422 | # phones = [post_replace_ph(i) for i in phones] 423 | 424 | word2ph = [] 425 | for token, phoneme in zip(tokens, phones): 426 | phone_len = len(phoneme) 427 | word_len = len(token) 428 | 429 | aaa = distribute_phone(phone_len, word_len) 430 | word2ph += aaa 431 | 432 | phones = ["_"] + [j for i in phones for j in i] + ["_"] 433 | tones = [0] + [j for i in tones for j in i] + [0] 434 | word2ph = [1] + word2ph + [1] 435 | assert len(phones) == len(tones), text 436 | assert len(phones) == sum(word2ph), text 437 | 438 | return phones, tones, word2ph -------------------------------------------------------------------------------- /onnx_infer/text/japanese.py: -------------------------------------------------------------------------------- 1 | # Convert Japanese text to phonemes which is 2 | # compatible with Julius https://github.com/julius-speech/segmentation-kit 3 | import re 4 | import unicodedata 5 | import pyopenjtalk 6 | import jaconv 7 | 8 | from num2words import num2words 9 | from .symbols import punctuation, symbols 10 | from .tokenizer import tokenizer_instance 11 | 12 | # 加载分析器 13 | tokenizer = tokenizer_instance.JP 14 | 15 | 16 | def kata2phoneme(text: str) -> str: 17 | """Convert katakana text to phonemes.""" 18 | text = text.strip() 19 | if text == "ー": 20 | return ["ー"] 21 | elif text.startswith("ー"): 22 | return ["ー"] + kata2phoneme(text[1:]) 23 | res = [] 24 | prev = None 25 | while text: 26 | if re.match(_MARKS, text): 27 | res.append(text) 28 | text = text[1:] 29 | continue 30 | if text.startswith("ー"): 31 | if prev: 32 | res.append(prev[-1]) 33 | text = text[1:] 34 | continue 35 | res += pyopenjtalk.g2p(text).lower().replace("cl", "q").split(" ") 36 | break 37 | # res = _COLON_RX.sub(":", res) 38 | return res 39 | 40 | 41 | def hira2kata(text: str) -> str: 42 | return jaconv.hira2kata(text) 43 | 44 | 45 | _SYMBOL_TOKENS = set(list("・、。?!")) 46 | _NO_YOMI_TOKENS = set(list("「」『』―()[][]")) 47 | _MARKS = re.compile( 48 | r"[^A-Za-z\d\u3005\u3040-\u30ff\u4e00-\u9fff\uff11-\uff19\uff21-\uff3a\uff41-\uff5a\uff66-\uff9d]" 49 | ) 50 | 51 | 52 | def text2kata(text: str) -> str: 53 | parsed = pyopenjtalk.run_frontend(text) 54 | 55 | res = [] 56 | for parts in parsed: 57 | word, yomi = replace_punctuation(parts["string"]), parts["pron"].replace( 58 | "’", "" 59 | ) 60 | if yomi: 61 | if re.match(_MARKS, yomi): 62 | if len(word) > 1: 63 | word = [replace_punctuation(i) for i in list(word)] 64 | yomi = word 65 | res += yomi 66 | sep += word 67 | continue 68 | elif word not in rep_map.keys() and word not in rep_map.values(): 69 | word = "," 70 | yomi = word 71 | res.append(yomi) 72 | else: 73 | if word in _SYMBOL_TOKENS: 74 | res.append(word) 75 | elif word in ("っ", "ッ"): 76 | res.append("ッ") 77 | elif word in _NO_YOMI_TOKENS: 78 | pass 79 | else: 80 | res.append(word) 81 | return hira2kata("".join(res)) 82 | 83 | 84 | def text2sep_kata(text: str) -> (list, list): 85 | parsed = pyopenjtalk.run_frontend(text) 86 | 87 | res = [] 88 | sep = [] 89 | for parts in parsed: 90 | word, yomi = replace_punctuation(parts["string"]), parts["pron"].replace( 91 | "’", "" 92 | ) 93 | if yomi: 94 | if re.match(_MARKS, yomi): 95 | if len(word) > 1: 96 | word = [replace_punctuation(i) for i in list(word)] 97 | yomi = word 98 | res += yomi 99 | sep += word 100 | continue 101 | elif word not in rep_map.keys() and word not in rep_map.values(): 102 | word = "," 103 | yomi = word 104 | res.append(yomi) 105 | else: 106 | if word in _SYMBOL_TOKENS: 107 | res.append(word) 108 | elif word in ("っ", "ッ"): 109 | res.append("ッ") 110 | elif word in _NO_YOMI_TOKENS: 111 | pass 112 | else: 113 | res.append(word) 114 | sep.append(word) 115 | return sep, [hira2kata(i) for i in res], get_accent(parsed) 116 | 117 | 118 | def get_accent(parsed): 119 | labels = pyopenjtalk.make_label(parsed) 120 | 121 | phonemes = [] 122 | accents = [] 123 | for n, label in enumerate(labels): 124 | phoneme = re.search(r"\-([^\+]*)\+", label).group(1) 125 | if phoneme not in ["sil", "pau"]: 126 | phonemes.append(phoneme.replace("cl", "q").lower()) 127 | else: 128 | continue 129 | a1 = int(re.search(r"/A:(\-?[0-9]+)\+", label).group(1)) 130 | a2 = int(re.search(r"\+(\d+)\+", label).group(1)) 131 | if re.search(r"\-([^\+]*)\+", labels[n + 1]).group(1) in ["sil", "pau"]: 132 | a2_next = -1 133 | else: 134 | a2_next = int(re.search(r"\+(\d+)\+", labels[n + 1]).group(1)) 135 | # Falling 136 | if a1 == 0 and a2_next == a2 + 1: 137 | accents.append(-1) 138 | # Rising 139 | elif a2 == 1 and a2_next == 2: 140 | accents.append(1) 141 | else: 142 | accents.append(0) 143 | return list(zip(phonemes, accents)) 144 | 145 | 146 | _ALPHASYMBOL_YOMI = { 147 | "#": "シャープ", 148 | "%": "パーセント", 149 | "&": "アンド", 150 | "+": "プラス", 151 | "-": "マイナス", 152 | ":": "コロン", 153 | ";": "セミコロン", 154 | "<": "小なり", 155 | "=": "イコール", 156 | ">": "大なり", 157 | "@": "アット", 158 | "a": "エー", 159 | "b": "ビー", 160 | "c": "シー", 161 | "d": "ディー", 162 | "e": "イー", 163 | "f": "エフ", 164 | "g": "ジー", 165 | "h": "エイチ", 166 | "i": "アイ", 167 | "j": "ジェー", 168 | "k": "ケー", 169 | "l": "エル", 170 | "m": "エム", 171 | "n": "エヌ", 172 | "o": "オー", 173 | "p": "ピー", 174 | "q": "キュー", 175 | "r": "アール", 176 | "s": "エス", 177 | "t": "ティー", 178 | "u": "ユー", 179 | "v": "ブイ", 180 | "w": "ダブリュー", 181 | "x": "エックス", 182 | "y": "ワイ", 183 | "z": "ゼット", 184 | "α": "アルファ", 185 | "β": "ベータ", 186 | "γ": "ガンマ", 187 | "δ": "デルタ", 188 | "ε": "イプシロン", 189 | "ζ": "ゼータ", 190 | "η": "イータ", 191 | "θ": "シータ", 192 | "ι": "イオタ", 193 | "κ": "カッパ", 194 | "λ": "ラムダ", 195 | "μ": "ミュー", 196 | "ν": "ニュー", 197 | "ξ": "クサイ", 198 | "ο": "オミクロン", 199 | "π": "パイ", 200 | "ρ": "ロー", 201 | "σ": "シグマ", 202 | "τ": "タウ", 203 | "υ": "ウプシロン", 204 | "φ": "ファイ", 205 | "χ": "カイ", 206 | "ψ": "プサイ", 207 | "ω": "オメガ", 208 | } 209 | 210 | 211 | _NUMBER_WITH_SEPARATOR_RX = re.compile("[0-9]{1,3}(,[0-9]{3})+") 212 | _CURRENCY_MAP = {"$": "ドル", "¥": "円", "£": "ポンド", "€": "ユーロ"} 213 | _CURRENCY_RX = re.compile(r"([$¥£€])([0-9.]*[0-9])") 214 | _NUMBER_RX = re.compile(r"[0-9]+(\.[0-9]+)?") 215 | 216 | 217 | def japanese_convert_numbers_to_words(text: str) -> str: 218 | res = _NUMBER_WITH_SEPARATOR_RX.sub(lambda m: m[0].replace(",", ""), text) 219 | res = _CURRENCY_RX.sub(lambda m: m[2] + _CURRENCY_MAP.get(m[1], m[1]), res) 220 | res = _NUMBER_RX.sub(lambda m: num2words(m[0], lang="ja"), res) 221 | return res 222 | 223 | 224 | def japanese_convert_alpha_symbols_to_words(text: str) -> str: 225 | return "".join([_ALPHASYMBOL_YOMI.get(ch, ch) for ch in text.lower()]) 226 | 227 | 228 | def japanese_text_to_phonemes(text: str) -> str: 229 | """Convert Japanese text to phonemes.""" 230 | res = unicodedata.normalize("NFKC", text) 231 | res = japanese_convert_numbers_to_words(res) 232 | # res = japanese_convert_alpha_symbols_to_words(res) 233 | res = text2kata(res) 234 | res = kata2phoneme(res) 235 | return res 236 | 237 | 238 | def is_japanese_character(char): 239 | # 定义日语文字系统的 Unicode 范围 240 | japanese_ranges = [ 241 | (0x3040, 0x309F), # 平假名 242 | (0x30A0, 0x30FF), # 片假名 243 | (0x4E00, 0x9FFF), # 汉字 (CJK Unified Ideographs) 244 | (0x3400, 0x4DBF), # 汉字扩展 A 245 | (0x20000, 0x2A6DF), # 汉字扩展 B 246 | # 可以根据需要添加其他汉字扩展范围 247 | ] 248 | 249 | # 将字符的 Unicode 编码转换为整数 250 | char_code = ord(char) 251 | 252 | # 检查字符是否在任何一个日语范围内 253 | for start, end in japanese_ranges: 254 | if start <= char_code <= end: 255 | return True 256 | 257 | return False 258 | 259 | 260 | rep_map = { 261 | ":": ",", 262 | ";": ",", 263 | ",": ",", 264 | "。": ".", 265 | "!": "!", 266 | "?": "?", 267 | "\n": ".", 268 | ".": ".", 269 | "…": "...", 270 | "···": "...", 271 | "・・・": "...", 272 | "·": ",", 273 | "・": ",", 274 | "、": ",", 275 | "$": ".", 276 | "“": "'", 277 | "”": "'", 278 | '"': "'", 279 | "‘": "'", 280 | "’": "'", 281 | "(": "'", 282 | ")": "'", 283 | "(": "'", 284 | ")": "'", 285 | "《": "'", 286 | "》": "'", 287 | "【": "'", 288 | "】": "'", 289 | "[": "'", 290 | "]": "'", 291 | "—": "-", 292 | "−": "-", 293 | "~": "-", 294 | "~": "-", 295 | "「": "'", 296 | "」": "'", 297 | } 298 | 299 | 300 | def replace_punctuation(text): 301 | pattern = re.compile("|".join(re.escape(p) for p in rep_map.keys())) 302 | 303 | replaced_text = pattern.sub(lambda x: rep_map[x.group()], text) 304 | 305 | replaced_text = re.sub( 306 | r"[^\u3040-\u309F\u30A0-\u30FF\u4E00-\u9FFF\u3400-\u4DBF\u3005" 307 | + "".join(punctuation) 308 | + r"]+", 309 | "", 310 | replaced_text, 311 | ) 312 | 313 | return replaced_text 314 | 315 | 316 | def text_normalize(text): 317 | res = unicodedata.normalize("NFKC", text) 318 | res = japanese_convert_numbers_to_words(res) 319 | # res = "".join([i for i in res if is_japanese_character(i)]) 320 | res = replace_punctuation(res) 321 | res = res.replace("゙", "") 322 | return res 323 | 324 | 325 | def distribute_phone(n_phone, n_word): 326 | phones_per_word = [0] * n_word 327 | for task in range(n_phone): 328 | min_tasks = min(phones_per_word) 329 | min_index = phones_per_word.index(min_tasks) 330 | phones_per_word[min_index] += 1 331 | return phones_per_word 332 | 333 | 334 | def handle_long(sep_phonemes): 335 | for i in range(len(sep_phonemes)): 336 | if sep_phonemes[i][0] == "ー": 337 | sep_phonemes[i][0] = sep_phonemes[i - 1][-1] 338 | if "ー" in sep_phonemes[i]: 339 | for j in range(len(sep_phonemes[i])): 340 | if sep_phonemes[i][j] == "ー": 341 | sep_phonemes[i][j] = sep_phonemes[i][j - 1][-1] 342 | return sep_phonemes 343 | 344 | 345 | def align_tones(phones, tones): 346 | res = [] 347 | for pho in phones: 348 | temp = [0] * len(pho) 349 | for idx, p in enumerate(pho): 350 | if len(tones) == 0: 351 | break 352 | if p == tones[0][0]: 353 | temp[idx] = tones[0][1] 354 | if idx > 0: 355 | temp[idx] += temp[idx - 1] 356 | tones.pop(0) 357 | temp = [0] + temp 358 | temp = temp[:-1] 359 | if -1 in temp: 360 | temp = [i + 1 for i in temp] 361 | res.append(temp) 362 | res = [i for j in res for i in j] 363 | assert not any([i < 0 for i in res]) and not any([i > 1 for i in res]) 364 | return res 365 | 366 | 367 | def rearrange_tones(tones, phones): 368 | res = [0] * len(tones) 369 | for i in range(len(tones)): 370 | if i == 0: 371 | if tones[i] not in punctuation: 372 | res[i] = 1 373 | elif tones[i] == prev: 374 | if phones[i] in punctuation: 375 | res[i] = 0 376 | else: 377 | res[i] = 1 378 | elif tones[i] > prev: 379 | res[i] = 2 380 | elif tones[i] < prev: 381 | res[i - 1] = 3 382 | res[i] = 1 383 | prev = tones[i] 384 | return res 385 | 386 | 387 | def g2p(norm_text): 388 | sep_text, sep_kata, acc = text2sep_kata(norm_text) 389 | sep_tokenized = [] 390 | for i in sep_text: 391 | if i not in punctuation: 392 | # print('aaaa',tokenizer.tokenize(i)) 393 | # sep_tokenized.append([f"▁{i}"]) 394 | sep_tokenized.append(tokenizer.tokenize(i)) 395 | else: 396 | sep_tokenized.append([i]) 397 | 398 | sep_phonemes = handle_long([kata2phoneme(i) for i in sep_kata]) 399 | # 异常处理,MeCab不认识的词的话会一路传到这里来,然后炸掉。目前来看只有那些超级稀有的生僻词会出现这种情况 400 | for i in sep_phonemes: 401 | for j in i: 402 | assert j in symbols, (sep_text, sep_kata, sep_phonemes) 403 | tones = align_tones(sep_phonemes, acc) 404 | 405 | word2ph = [] 406 | for token, phoneme in zip(sep_tokenized, sep_phonemes): 407 | phone_len = len(phoneme) 408 | word_len = len(token) 409 | 410 | aaa = distribute_phone(phone_len, word_len) 411 | word2ph += aaa 412 | phones = ["_"] + [j for i in sep_phonemes for j in i] + ["_"] 413 | # tones = [0] + rearrange_tones(tones, phones[1:-1]) + [0] 414 | tones = [0] + tones + [0] 415 | word2ph = [1] + word2ph + [1] 416 | assert len(phones) == len(tones) 417 | return phones, tones, word2ph 418 | -------------------------------------------------------------------------------- /onnx_infer/onnx_infer.py: -------------------------------------------------------------------------------- 1 | import os 2 | import numpy as np 3 | from copy import copy 4 | from typing import List 5 | from dataclasses import dataclass 6 | import onnxruntime as ort 7 | 8 | from log import log_instance 9 | from config import read_config 10 | from config import config_instance 11 | from .text.cleaner import clean_text, cleaned_text_to_sequence 12 | 13 | BERT_ENABLE = config_instance.get("bert_enable", True) 14 | 15 | if BERT_ENABLE: 16 | from .onnx_bert import get_bert 17 | 18 | 19 | # 获取模型中包含的中文角色标记 20 | CHINESE_CHARACTER_MARK = config_instance.get("onnx_tts_models_chinese_mark", "中文") 21 | 22 | ONNX_PROVIDERS = [config_instance.get("onnx_providers", "CPUExecutionProvider")] 23 | MODELS_PATH = os.path.abspath(config_instance.get("onnx_tts_models", "onnx/models")) 24 | MODELS_BASE_NAME = os.path.basename(MODELS_PATH) 25 | MODELS_PARENT_PATH = os.path.dirname(MODELS_PATH) 26 | MODELS_PREFIX = os.path.join(MODELS_PATH, os.path.basename(MODELS_PATH)) 27 | 28 | ONNX_MODELS_PATH = { 29 | "config": f"{MODELS_PARENT_PATH}/{MODELS_BASE_NAME}.json", 30 | "enc": f"{MODELS_PREFIX}_enc_p.onnx", 31 | "emb_g": f"{MODELS_PREFIX}_emb.onnx", 32 | "dp": f"{MODELS_PREFIX}_dp.onnx", 33 | "sdp": f"{MODELS_PREFIX}_sdp.onnx", 34 | "flow": f"{MODELS_PREFIX}_flow.onnx", 35 | "dec": f"{MODELS_PREFIX}_dec.onnx", 36 | } 37 | 38 | 39 | class SpeakerMap: 40 | """ 41 | 多语言关系表 42 | """ 43 | 44 | def __init__(self) -> None: 45 | log_instance.info("正在加载模型发音人多语言关系表...") 46 | self.map_data: dict = read_config("speakers_map.json") 47 | 48 | def get_jp_speaker_name(self, speaker_name: str): 49 | """ 50 | 获取对应日语发音人名称 51 | """ 52 | speaker_name_dict: dict = self.map_data.get(speaker_name, {}) 53 | return speaker_name_dict.get("JP", speaker_name) 54 | 55 | def get_en_speaker_name(self, speaker_name: str): 56 | """ 57 | 获取对应英语发音人名称 58 | """ 59 | speaker_name_dict: dict = self.map_data.get(speaker_name, {}) 60 | return speaker_name_dict.get("EN", speaker_name) 61 | 62 | 63 | @dataclass 64 | class ONNX_MODELS: 65 | enc: ort.InferenceSession = ort.InferenceSession( 66 | ONNX_MODELS_PATH["enc"], providers=ONNX_PROVIDERS 67 | ) 68 | emb_g: ort.InferenceSession = ort.InferenceSession( 69 | ONNX_MODELS_PATH["emb_g"], providers=ONNX_PROVIDERS 70 | ) 71 | dp: ort.InferenceSession = ort.InferenceSession( 72 | ONNX_MODELS_PATH["dp"], providers=ONNX_PROVIDERS 73 | ) 74 | sdp: ort.InferenceSession = ort.InferenceSession( 75 | ONNX_MODELS_PATH["sdp"], providers=ONNX_PROVIDERS 76 | ) 77 | flow: ort.InferenceSession = ort.InferenceSession( 78 | ONNX_MODELS_PATH["flow"], providers=ONNX_PROVIDERS 79 | ) 80 | dec: ort.InferenceSession = ort.InferenceSession( 81 | ONNX_MODELS_PATH["dec"], providers=ONNX_PROVIDERS 82 | ) 83 | 84 | 85 | class ONNX_RUNTINE: 86 | def __init__(self): 87 | log_instance.info("正在加载BERT-VITS语音模型...") 88 | self.config = read_config(ONNX_MODELS_PATH["config"]) 89 | self.models = ONNX_MODELS() 90 | 91 | def __call__( 92 | self, 93 | seq: np.int64, 94 | tone: np.int64, 95 | language_id: np.int64, 96 | bert_zh: np.float32, 97 | bert_jp: np.float32, 98 | bert_en: np.float32, 99 | speaker_id: int, 100 | seed: int = 114514, 101 | seq_noise_scale: float = 0.8, 102 | sdp_noise_scale: float = 0.6, 103 | length_scale: float = 1.0, 104 | sdp_ratio: float = 0.2, 105 | emotion: int = 0, 106 | ): 107 | speaker_id: np.int64 = np.array([speaker_id], dtype=np.int64) 108 | emotion: np.int64 = np.array([emotion], dtype=np.int64) 109 | 110 | # emb_g模型推理 111 | g = self.models.emb_g.run(None, {"sid": speaker_id})[0] 112 | g = np.expand_dims(g, -1) 113 | 114 | enc_rtn: List[np.float32] = self.models.enc.run( 115 | output_names=None, 116 | input_feed={ 117 | "x": seq, 118 | "t": tone, 119 | "language": language_id, 120 | "bert_0": bert_zh, 121 | "bert_1": bert_jp, 122 | "bert_2": bert_en, 123 | "g": g, 124 | "sid": speaker_id, 125 | "vqidx": emotion, 126 | }, 127 | ) 128 | 129 | x, m_p, logs_p, x_mask = enc_rtn[0], enc_rtn[1], enc_rtn[2], enc_rtn[3] 130 | # 设置随机种子 131 | np.random.seed(seed) 132 | zinput = np.random.randn(x.shape[0], 2, x.shape[2]) * sdp_noise_scale 133 | 134 | logw = self.models.sdp.run( 135 | None, {"x": x, "x_mask": x_mask, "zin": zinput.astype(np.float32), "g": g} 136 | )[0] * (sdp_ratio) + self.models.dp.run( 137 | None, {"x": x, "x_mask": x_mask, "g": g} 138 | )[ 139 | 0 140 | ] * ( 141 | 1 - sdp_ratio 142 | ) 143 | 144 | w = np.exp(logw) * x_mask * length_scale 145 | w_ceil = np.ceil(w) 146 | y_lengths = np.clip(np.sum(w_ceil, (1, 2)), a_min=1.0, a_max=100000).astype( 147 | np.int64 148 | ) 149 | y_mask = np.expand_dims(sequence_mask(y_lengths, None), 1) 150 | 151 | attn_mask = np.expand_dims(x_mask, 2) * np.expand_dims(y_mask, -1) 152 | attn = generate_path(w_ceil, attn_mask) 153 | 154 | m_p: np.float32 = np.matmul(attn.squeeze(1), m_p.transpose(0, 2, 1)) 155 | m_p = m_p.transpose(0, 2, 1) # [b, t', t], [b, t, d] -> [b, d, t'] 156 | 157 | logs_p: np.float32 = np.matmul(attn.squeeze(1), logs_p.transpose(0, 2, 1)) 158 | logs_p = logs_p.transpose(0, 2, 1) # [b, t', t], [b, t, d] -> [b, d, t'] 159 | 160 | z_p: np.float32 = ( 161 | m_p 162 | + np.random.randn(m_p.shape[0], m_p.shape[1], m_p.shape[2]) 163 | * np.exp(logs_p) 164 | * seq_noise_scale 165 | ) 166 | 167 | log_instance.debug( 168 | f"flow模型输入 {str(z_p.shape)} {str(y_mask.shape)} {str(g.shape)}" 169 | ) 170 | 171 | if z_p.shape[2] == 0 or y_mask.shape[2] == 0: 172 | raise MemoryError("flow模型输入参数错误,有可能是临时缓存空间不足。") 173 | 174 | z: np.float32 = self.models.flow.run( 175 | None, 176 | { 177 | "z_p": z_p.astype(np.float32), 178 | "y_mask": y_mask.astype(np.float32), 179 | "g": g, 180 | }, 181 | )[0] 182 | 183 | return self.models.dec.run(None, {"z_in": z, "g": g})[0] 184 | 185 | def get_config(self, key: str, default=None): 186 | """ 187 | 获取模型配置项 188 | """ 189 | return self.config.get(key, default) 190 | 191 | 192 | onnx_runtime_instance = ONNX_RUNTINE() 193 | 194 | 195 | def __add_blank(phone, tone, language, word2ph): 196 | """ 197 | ??添加空白间隔 198 | """ 199 | for i in range(len(word2ph)): 200 | word2ph[i] = word2ph[i] * 2 201 | word2ph[0] += 1 202 | 203 | return ( 204 | intersperse(phone, 0), 205 | intersperse(tone, 0), 206 | intersperse(language, 0), 207 | word2ph, 208 | ) 209 | 210 | 211 | def convert_pad_shape(pad_shape): 212 | layer = pad_shape[::-1] 213 | pad_shape = [item for sublist in layer for item in sublist] 214 | return pad_shape 215 | 216 | 217 | def sequence_mask(length, max_length=None): 218 | if max_length is None: 219 | max_length = length.max() 220 | x = np.arange(max_length, dtype=length.dtype) 221 | return np.expand_dims(x, 0) < np.expand_dims(length, 1) 222 | 223 | 224 | def generate_path(duration, mask): 225 | """ 226 | duration: [b, 1, t_x] 227 | mask: [b, 1, t_y, t_x] 228 | """ 229 | 230 | b, _, t_y, t_x = mask.shape 231 | cum_duration = np.cumsum(duration, -1) 232 | 233 | cum_duration_flat = cum_duration.reshape(b * t_x) 234 | path = sequence_mask(cum_duration_flat, t_y) 235 | path = path.reshape(b, t_x, t_y) 236 | path = path ^ np.pad(path, ((0, 0), (1, 0), (0, 0)))[:, :-1] 237 | path = np.expand_dims(path, 1).transpose(0, 1, 3, 2) 238 | return path 239 | 240 | 241 | def intersperse(lst, item): 242 | """ 243 | 在列表的每个元素之间插入一个分隔符元素 244 | 245 | 如: [1, '-', 2, '-', 3, '-', 4] 246 | """ 247 | result = [item] * (len(lst) * 2 + 1) 248 | result[1::2] = lst 249 | return result 250 | 251 | 252 | def get_text(text: str, language: str, add_blank: bool = True) -> tuple: 253 | """ 254 | 推理前文本预处理 255 | """ 256 | language_list = ["ZH", "JP", "EN"] 257 | try: 258 | language: str = language.upper() 259 | language_index = language_list.index(language) 260 | language_str = copy(language) 261 | except ValueError: 262 | raise TypeError(f"语言类型输入错误:{language}。") 263 | 264 | norm_text, phone, tone, word2ph = clean_text(text, language) 265 | # print(norm_text, phone, tone, word2ph) 266 | # 将phone, tone, language转化为对应id表示 267 | phone, tone, language = cleaned_text_to_sequence(phone, tone, language) 268 | 269 | # ??添加空白间隔 270 | if add_blank: 271 | phone, tone, language, word2ph = __add_blank(phone, tone, language, word2ph) 272 | # print(len(phone), sum(word2ph)) 273 | 274 | bert_list: list = [np.zeros([len(phone), 1024], dtype=np.float32)] * len( 275 | language_list 276 | ) 277 | 278 | if BERT_ENABLE: 279 | bert_ori: np.float32 = get_bert(norm_text, word2ph, language_str) 280 | if bert_ori.shape[0] != len(phone): 281 | raise KeyError("BERT推理结果与预期不符合。") 282 | 283 | bert_list[language_index] = bert_ori 284 | 285 | del word2ph 286 | 287 | res_tuple = tuple(bert_list) + ( 288 | np.expand_dims(np.array(phone, dtype=np.int64), 0), 289 | np.expand_dims(np.array(tone, dtype=np.int64), 0), 290 | np.expand_dims(np.array(language, dtype=np.int64), 0), 291 | ) 292 | return res_tuple 293 | 294 | 295 | class INFER_ONNX: 296 | """ 297 | 语音推理实现 298 | """ 299 | 300 | def __init__(self) -> None: 301 | self.onnx_runtime_instance: ONNX_RUNTINE = onnx_runtime_instance 302 | self.speakers_list = self.onnx_runtime_instance.get_config( 303 | "Characters", default=[] 304 | ) 305 | self.speaker_map = SpeakerMap() 306 | 307 | def get_speaker_id(self, speaker_name: str, chinese_only: bool = True) -> int: 308 | """ 309 | 获取发音人名字对应id,默认仅匹配名字带中文标志的模型,中文标志由 CHINESE_CHARACTER_MARK 决定 310 | """ 311 | for index, speaker in enumerate(self.speakers_list): 312 | if speaker_name not in speaker: 313 | continue 314 | if chinese_only and CHINESE_CHARACTER_MARK not in speaker: 315 | continue 316 | else: 317 | return index 318 | return -1 319 | 320 | def get_full_speaker_name(self, speaker_name: str, language_str: str = "ZH"): 321 | """ 322 | 获取发音人的完整名称,映射关系由 speakers_map.json 决定 323 | 如果无法找到,则返回原来的名称 324 | """ 325 | if language_str == "JP": 326 | return self.speaker_map.get_jp_speaker_name(speaker_name) 327 | 328 | if language_str == "EN": 329 | return self.speaker_map.get_en_speaker_name(speaker_name) 330 | 331 | return speaker_name 332 | 333 | @staticmethod 334 | def __clamp( 335 | value: int | float, min_value: int | float = 0, max_value: int | float = 9 336 | ): 337 | """ 338 | 限定数据在范围内,超出仅取边缘值 339 | """ 340 | return max(min_value, min(max_value, value)) 341 | 342 | @staticmethod 343 | def __skip_start(phones, tones, language_id, zh_bert, jp_bert, en_bert): 344 | """ 345 | ?跳过第一个一个元素 346 | """ 347 | phones = np.delete(phones, 0, axis=1) 348 | tones = np.delete(tones, 0, axis=1) 349 | language_id = np.delete(language_id, 0, axis=1) 350 | zh_bert = np.delete(zh_bert, 0, axis=0) 351 | jp_bert = np.delete(jp_bert, 0, axis=0) 352 | en_bert = np.delete(en_bert, 0, axis=0) 353 | return phones, tones, language_id, zh_bert, jp_bert, en_bert 354 | 355 | @staticmethod 356 | def __skip_end(phones, tones, language_id, zh_bert, jp_bert, en_bert): 357 | """ 358 | ?跳过最后一个元素 359 | """ 360 | phones = phones[:, :-1] 361 | tones = tones[:, :-1] 362 | language_id = language_id[:, :-1] 363 | zh_bert = zh_bert[:-1, :] 364 | jp_bert = jp_bert[:-1, :] 365 | en_bert = en_bert[:-1, :] 366 | return phones, tones, language_id, zh_bert, jp_bert, en_bert 367 | 368 | def __params_specification( 369 | self, 370 | sdp_ratio: float, 371 | noise_scale: float, 372 | noise_scale_w: float, 373 | length_scale: float, 374 | emotion: int, 375 | ): 376 | """ 377 | 规范化语音调整参数 378 | """ 379 | sdp_ratio = self.__clamp(sdp_ratio, min_value=0.0, max_value=1.0) 380 | noise_scale = self.__clamp(noise_scale, min_value=0.0, max_value=2.0) 381 | noise_scale_w = self.__clamp(noise_scale_w, min_value=0.1, max_value=2.0) 382 | length_scale = self.__clamp(length_scale, min_value=0.1, max_value=2.0) 383 | emotion = self.__clamp(emotion) 384 | return (sdp_ratio, noise_scale, noise_scale_w, length_scale, emotion) 385 | 386 | def __text_to_model_inputs( 387 | self, 388 | text: str, 389 | language: str = "ZH", 390 | skip_start: bool = False, 391 | skip_end: bool = False, 392 | add_blank: bool = True, 393 | ): 394 | """ 395 | 将文本转化为onnx模型所需numpy数据 396 | """ 397 | # 在此处实现当前版本的推理 398 | # 文本预处理 399 | zh_bert, jp_bert, en_bert, phones, tones, language_id = get_text( 400 | text=text, language=language, add_blank=add_blank 401 | ) 402 | 403 | if skip_start: 404 | # ?跳过第一个一个元素 405 | phones, tones, language_id, zh_bert, jp_bert, en_bert = self.__skip_start( 406 | phones, tones, language_id, zh_bert, jp_bert, en_bert 407 | ) 408 | 409 | if skip_end: 410 | # ?跳过最后一个元素 411 | phones, tones, language_id, zh_bert, jp_bert, en_bert = self.__skip_end( 412 | phones, tones, language_id, zh_bert, jp_bert, en_bert 413 | ) 414 | 415 | return phones, tones, language_id, zh_bert, jp_bert, en_bert 416 | 417 | def infer( 418 | self, 419 | text: str, 420 | speaker_name: str, 421 | language: str = "ZH", 422 | sdp_ratio: float = 0.2, 423 | noise_scale: float = 0.8, 424 | noise_scale_w: float = 0.6, 425 | length_scale: float = 1.0, 426 | emotion: int = 7, 427 | seed: int = 114514, 428 | skip_start: bool = False, 429 | skip_end: bool = False, 430 | add_blank: bool = True, 431 | ) -> np.float32: 432 | """ 433 | 语音推理 434 | """ 435 | # 参数规范化 436 | ( 437 | sdp_ratio, 438 | noise_scale, 439 | noise_scale_w, 440 | length_scale, 441 | emotion, 442 | ) = self.__params_specification( 443 | sdp_ratio, noise_scale, noise_scale_w, length_scale, emotion 444 | ) 445 | # 到 speakers_map.json 内查找是否存在对应关系,如果有,则返回对应发音人真实名称 446 | full_speaker_name = self.get_full_speaker_name( 447 | speaker_name=speaker_name, language_str=language 448 | ) 449 | log_instance.debug(f"获取发音人真实名称 {speaker_name} -> {full_speaker_name}") 450 | 451 | speaker_id = self.get_speaker_id( 452 | full_speaker_name, 453 | True if language == "ZH" else False, 454 | ) 455 | 456 | if speaker_id == -1: 457 | raise ValueError(f"无法在模型中找到发音人信息:{speaker_name}。") 458 | 459 | # 文本预处理 460 | # 将文本转化为onnx模型所需numpy数据 461 | ( 462 | phones, 463 | tones, 464 | language_id, 465 | zh_bert, 466 | jp_bert, 467 | en_bert, 468 | ) = self.__text_to_model_inputs( 469 | text=text, 470 | language=language, 471 | skip_start=skip_start, 472 | skip_end=skip_end, 473 | add_blank=add_blank, 474 | ) 475 | log_instance.debug(f"推理 {full_speaker_name} -> {text}") 476 | np_audio = self.onnx_runtime_instance( 477 | seq=phones, 478 | tone=tones, 479 | language_id=language_id, 480 | bert_zh=zh_bert, 481 | bert_jp=jp_bert, 482 | bert_en=en_bert, 483 | speaker_id=speaker_id, 484 | seed=seed, 485 | seq_noise_scale=noise_scale, 486 | sdp_noise_scale=noise_scale_w, 487 | length_scale=length_scale, 488 | sdp_ratio=sdp_ratio, 489 | emotion=emotion, 490 | ) 491 | 492 | del ( 493 | phones, 494 | tones, 495 | language_id, 496 | zh_bert, 497 | jp_bert, 498 | en_bert, 499 | noise_scale, 500 | noise_scale_w, 501 | length_scale, 502 | sdp_ratio, 503 | emotion, 504 | ) 505 | 506 | return np_audio 507 | 508 | def infer_multilang( 509 | self, 510 | text_list: list, 511 | speaker_name: str, 512 | language_list: list = ["ZH"], 513 | sdp_ratio: float = 0.2, 514 | noise_scale: float = 0.8, 515 | noise_scale_w: float = 0.6, 516 | length_scale: float = 1.0, 517 | emotion: int = 7, 518 | seed: int = 114514, 519 | skip_start: bool = False, 520 | skip_end: bool = False, 521 | add_blank: bool = True, 522 | ) -> np.float32: 523 | """ 524 | 语音混合推理 525 | """ 526 | # ( 527 | # zh_bert_list, 528 | # jp_bert_list, 529 | # en_bert_list, 530 | # phones_list, 531 | # tones_list, 532 | # language_id_list, 533 | # ) = ([], [], [], [], [], []) 534 | 535 | # # 将所有数据合成到列表中 536 | # for idx, (text, language) in enumerate(zip(text_list, language_list)): 537 | # # 计算skip_start、skip_end参数值 538 | # skip_start = (idx != 0) or (skip_start and idx == 0) 539 | # skip_end = (idx != len(text_list) - 1) or ( 540 | # skip_end and idx == len(text_list) - 1 541 | # ) 542 | 543 | # # 预处理 544 | # ( 545 | # temp_phones, 546 | # temp_tones, 547 | # temp_language_id, 548 | # temp_zh_bert, 549 | # temp_jp_bert, 550 | # temp_en_bert, 551 | # ) = self.__text_to_model_inputs( 552 | # text=text, language=language, add_blank=add_blank 553 | # ) 554 | 555 | # zh_bert_list.append(temp_zh_bert) 556 | # jp_bert_list.append(temp_jp_bert) 557 | # en_bert_list.append(temp_en_bert) 558 | # phones_list.append(temp_phones) 559 | # tones_list.append(temp_tones) 560 | # language_id_list.append(temp_language_id) 561 | 562 | # zh_bert = np.concatenate(zh_bert_list, axis=0) 563 | # jp_bert = np.concatenate(jp_bert_list, axis=0) 564 | # en_bert = np.concatenate(en_bert_list, axis=0) 565 | # phones = np.concatenate(phones_list, axis=1) 566 | # tones = np.concatenate(tones_list, axis=1) 567 | # language_id = np.concatenate(language_id_list, axis=1) 568 | 569 | # # 参数规范化 570 | # ( 571 | # sdp_ratio, 572 | # noise_scale, 573 | # noise_scale_w, 574 | # length_scale, 575 | # emotion, 576 | # ) = self.__params_specification( 577 | # sdp_ratio, noise_scale, noise_scale_w, length_scale, emotion 578 | # ) 579 | 580 | # full_speaker_name = self.get_full_speaker_name( 581 | # speaker_name=speaker_name, language_str=language, default=speaker_name 582 | # ) 583 | # log_instance.info(f"获取发音人真实名称 {speaker_name} -> {full_speaker_name}") 584 | 585 | # speaker_id = self.get_speaker_id( 586 | # full_speaker_name, 587 | # True if language == "ZH" else False, 588 | # ) 589 | # speaker_id = self.get_speaker_id(speaker_name=speaker_name) 590 | 591 | # np_audio = self.onnx_runtime_instance( 592 | # seq=phones, 593 | # tone=tones, 594 | # language_id=language_id, 595 | # bert_zh=zh_bert, 596 | # bert_jp=jp_bert, 597 | # bert_en=en_bert, 598 | # speaker_id=speaker_id, 599 | # seed=seed, 600 | # seq_noise_scale=noise_scale, 601 | # sdp_noise_scale=noise_scale_w, 602 | # length_scale=length_scale, 603 | # sdp_ratio=sdp_ratio, 604 | # emotion=emotion, 605 | # ) 606 | 607 | # del ( 608 | # phones, 609 | # tones, 610 | # language_id, 611 | # zh_bert, 612 | # jp_bert, 613 | # en_bert, 614 | # noise_scale, 615 | # noise_scale_w, 616 | # length_scale, 617 | # sdp_ratio, 618 | # emotion, 619 | # ) 620 | 621 | audil_list = [] 622 | 623 | for idx, (text, language) in enumerate(zip(text_list, language_list)): 624 | # 计算skip_start、skip_end参数值 625 | skip_start = (idx != 0) or (skip_start and idx == 0) 626 | skip_end = (idx != len(text_list) - 1) or ( 627 | skip_end and idx == len(text_list) - 1 628 | ) 629 | 630 | audio = self.infer( 631 | text=text, 632 | speaker_name=speaker_name, 633 | language=language, 634 | sdp_ratio=sdp_ratio, 635 | noise_scale=noise_scale, 636 | noise_scale_w=noise_scale_w, 637 | length_scale=length_scale, 638 | emotion=emotion, 639 | seed=seed, 640 | skip_start=skip_start, 641 | skip_end=skip_end, 642 | add_blank=add_blank, 643 | ) 644 | audil_list.append(audio) 645 | 646 | np_audio = np.concatenate(audil_list, axis=2) 647 | return np_audio 648 | 649 | 650 | infor_onnx_instance = INFER_ONNX() 651 | -------------------------------------------------------------------------------- /onnx_infer/text/chinese_tone_sandhi.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | from typing import List 15 | from typing import Tuple 16 | 17 | import jieba 18 | from pypinyin import lazy_pinyin 19 | from pypinyin import Style 20 | 21 | from log import log_instance 22 | 23 | 24 | class ToneSandhi: 25 | def __init__(self): 26 | self.must_neural_tone_words = { 27 | "麻烦", 28 | "麻利", 29 | "鸳鸯", 30 | "高粱", 31 | "骨头", 32 | "骆驼", 33 | "马虎", 34 | "首饰", 35 | "馒头", 36 | "馄饨", 37 | "风筝", 38 | "难为", 39 | "队伍", 40 | "阔气", 41 | "闺女", 42 | "门道", 43 | "锄头", 44 | "铺盖", 45 | "铃铛", 46 | "铁匠", 47 | "钥匙", 48 | "里脊", 49 | "里头", 50 | "部分", 51 | "那么", 52 | "道士", 53 | "造化", 54 | "迷糊", 55 | "连累", 56 | "这么", 57 | "这个", 58 | "运气", 59 | "过去", 60 | "软和", 61 | "转悠", 62 | "踏实", 63 | "跳蚤", 64 | "跟头", 65 | "趔趄", 66 | "财主", 67 | "豆腐", 68 | "讲究", 69 | "记性", 70 | "记号", 71 | "认识", 72 | "规矩", 73 | "见识", 74 | "裁缝", 75 | "补丁", 76 | "衣裳", 77 | "衣服", 78 | "衙门", 79 | "街坊", 80 | "行李", 81 | "行当", 82 | "蛤蟆", 83 | "蘑菇", 84 | "薄荷", 85 | "葫芦", 86 | "葡萄", 87 | "萝卜", 88 | "荸荠", 89 | "苗条", 90 | "苗头", 91 | "苍蝇", 92 | "芝麻", 93 | "舒服", 94 | "舒坦", 95 | "舌头", 96 | "自在", 97 | "膏药", 98 | "脾气", 99 | "脑袋", 100 | "脊梁", 101 | "能耐", 102 | "胳膊", 103 | "胭脂", 104 | "胡萝", 105 | "胡琴", 106 | "胡同", 107 | "聪明", 108 | "耽误", 109 | "耽搁", 110 | "耷拉", 111 | "耳朵", 112 | "老爷", 113 | "老实", 114 | "老婆", 115 | "老头", 116 | "老太", 117 | "翻腾", 118 | "罗嗦", 119 | "罐头", 120 | "编辑", 121 | "结实", 122 | "红火", 123 | "累赘", 124 | "糨糊", 125 | "糊涂", 126 | "精神", 127 | "粮食", 128 | "簸箕", 129 | "篱笆", 130 | "算计", 131 | "算盘", 132 | "答应", 133 | "笤帚", 134 | "笑语", 135 | "笑话", 136 | "窟窿", 137 | "窝囊", 138 | "窗户", 139 | "稳当", 140 | "稀罕", 141 | "称呼", 142 | "秧歌", 143 | "秀气", 144 | "秀才", 145 | "福气", 146 | "祖宗", 147 | "砚台", 148 | "码头", 149 | "石榴", 150 | "石头", 151 | "石匠", 152 | "知识", 153 | "眼睛", 154 | "眯缝", 155 | "眨巴", 156 | "眉毛", 157 | "相声", 158 | "盘算", 159 | "白净", 160 | "痢疾", 161 | "痛快", 162 | "疟疾", 163 | "疙瘩", 164 | "疏忽", 165 | "畜生", 166 | "生意", 167 | "甘蔗", 168 | "琵琶", 169 | "琢磨", 170 | "琉璃", 171 | "玻璃", 172 | "玫瑰", 173 | "玄乎", 174 | "狐狸", 175 | "状元", 176 | "特务", 177 | "牲口", 178 | "牙碜", 179 | "牌楼", 180 | "爽快", 181 | "爱人", 182 | "热闹", 183 | "烧饼", 184 | "烟筒", 185 | "烂糊", 186 | "点心", 187 | "炊帚", 188 | "灯笼", 189 | "火候", 190 | "漂亮", 191 | "滑溜", 192 | "溜达", 193 | "温和", 194 | "清楚", 195 | "消息", 196 | "浪头", 197 | "活泼", 198 | "比方", 199 | "正经", 200 | "欺负", 201 | "模糊", 202 | "槟榔", 203 | "棺材", 204 | "棒槌", 205 | "棉花", 206 | "核桃", 207 | "栅栏", 208 | "柴火", 209 | "架势", 210 | "枕头", 211 | "枇杷", 212 | "机灵", 213 | "本事", 214 | "木头", 215 | "木匠", 216 | "朋友", 217 | "月饼", 218 | "月亮", 219 | "暖和", 220 | "明白", 221 | "时候", 222 | "新鲜", 223 | "故事", 224 | "收拾", 225 | "收成", 226 | "提防", 227 | "挖苦", 228 | "挑剔", 229 | "指甲", 230 | "指头", 231 | "拾掇", 232 | "拳头", 233 | "拨弄", 234 | "招牌", 235 | "招呼", 236 | "抬举", 237 | "护士", 238 | "折腾", 239 | "扫帚", 240 | "打量", 241 | "打算", 242 | "打点", 243 | "打扮", 244 | "打听", 245 | "打发", 246 | "扎实", 247 | "扁担", 248 | "戒指", 249 | "懒得", 250 | "意识", 251 | "意思", 252 | "情形", 253 | "悟性", 254 | "怪物", 255 | "思量", 256 | "怎么", 257 | "念头", 258 | "念叨", 259 | "快活", 260 | "忙活", 261 | "志气", 262 | "心思", 263 | "得罪", 264 | "张罗", 265 | "弟兄", 266 | "开通", 267 | "应酬", 268 | "庄稼", 269 | "干事", 270 | "帮手", 271 | "帐篷", 272 | "希罕", 273 | "师父", 274 | "师傅", 275 | "巴结", 276 | "巴掌", 277 | "差事", 278 | "工夫", 279 | "岁数", 280 | "屁股", 281 | "尾巴", 282 | "少爷", 283 | "小气", 284 | "小伙", 285 | "将就", 286 | "对头", 287 | "对付", 288 | "寡妇", 289 | "家伙", 290 | "客气", 291 | "实在", 292 | "官司", 293 | "学问", 294 | "学生", 295 | "字号", 296 | "嫁妆", 297 | "媳妇", 298 | "媒人", 299 | "婆家", 300 | "娘家", 301 | "委屈", 302 | "姑娘", 303 | "姐夫", 304 | "妯娌", 305 | "妥当", 306 | "妖精", 307 | "奴才", 308 | "女婿", 309 | "头发", 310 | "太阳", 311 | "大爷", 312 | "大方", 313 | "大意", 314 | "大夫", 315 | "多少", 316 | "多么", 317 | "外甥", 318 | "壮实", 319 | "地道", 320 | "地方", 321 | "在乎", 322 | "困难", 323 | "嘴巴", 324 | "嘱咐", 325 | "嘟囔", 326 | "嘀咕", 327 | "喜欢", 328 | "喇嘛", 329 | "喇叭", 330 | "商量", 331 | "唾沫", 332 | "哑巴", 333 | "哈欠", 334 | "哆嗦", 335 | "咳嗽", 336 | "和尚", 337 | "告诉", 338 | "告示", 339 | "含糊", 340 | "吓唬", 341 | "后头", 342 | "名字", 343 | "名堂", 344 | "合同", 345 | "吆喝", 346 | "叫唤", 347 | "口袋", 348 | "厚道", 349 | "厉害", 350 | "千斤", 351 | "包袱", 352 | "包涵", 353 | "匀称", 354 | "勤快", 355 | "动静", 356 | "动弹", 357 | "功夫", 358 | "力气", 359 | "前头", 360 | "刺猬", 361 | "刺激", 362 | "别扭", 363 | "利落", 364 | "利索", 365 | "利害", 366 | "分析", 367 | "出息", 368 | "凑合", 369 | "凉快", 370 | "冷战", 371 | "冤枉", 372 | "冒失", 373 | "养活", 374 | "关系", 375 | "先生", 376 | "兄弟", 377 | "便宜", 378 | "使唤", 379 | "佩服", 380 | "作坊", 381 | "体面", 382 | "位置", 383 | "似的", 384 | "伙计", 385 | "休息", 386 | "什么", 387 | "人家", 388 | "亲戚", 389 | "亲家", 390 | "交情", 391 | "云彩", 392 | "事情", 393 | "买卖", 394 | "主意", 395 | "丫头", 396 | "丧气", 397 | "两口", 398 | "东西", 399 | "东家", 400 | "世故", 401 | "不由", 402 | "不在", 403 | "下水", 404 | "下巴", 405 | "上头", 406 | "上司", 407 | "丈夫", 408 | "丈人", 409 | "一辈", 410 | "那个", 411 | "菩萨", 412 | "父亲", 413 | "母亲", 414 | "咕噜", 415 | "邋遢", 416 | "费用", 417 | "冤家", 418 | "甜头", 419 | "介绍", 420 | "荒唐", 421 | "大人", 422 | "泥鳅", 423 | "幸福", 424 | "熟悉", 425 | "计划", 426 | "扑腾", 427 | "蜡烛", 428 | "姥爷", 429 | "照顾", 430 | "喉咙", 431 | "吉他", 432 | "弄堂", 433 | "蚂蚱", 434 | "凤凰", 435 | "拖沓", 436 | "寒碜", 437 | "糟蹋", 438 | "倒腾", 439 | "报复", 440 | "逻辑", 441 | "盘缠", 442 | "喽啰", 443 | "牢骚", 444 | "咖喱", 445 | "扫把", 446 | "惦记", 447 | } 448 | self.must_not_neural_tone_words = { 449 | "男子", 450 | "女子", 451 | "分子", 452 | "原子", 453 | "量子", 454 | "莲子", 455 | "石子", 456 | "瓜子", 457 | "电子", 458 | "人人", 459 | "虎虎", 460 | } 461 | self.punc = ":,;。?!“”‘’':,;.?!" 462 | 463 | # the meaning of jieba pos tag: https://blog.csdn.net/weixin_44174352/article/details/113731041 464 | # e.g. 465 | # word: "家里" 466 | # pos: "s" 467 | # finals: ['ia1', 'i3'] 468 | def _neural_sandhi(self, word: str, pos: str, finals: List[str]) -> List[str]: 469 | # reduplication words for n. and v. e.g. 奶奶, 试试, 旺旺 470 | for j, item in enumerate(word): 471 | if ( 472 | j - 1 >= 0 473 | and item == word[j - 1] 474 | and pos[0] in {"n", "v", "a"} 475 | and word not in self.must_not_neural_tone_words 476 | ): 477 | finals[j] = finals[j][:-1] + "5" 478 | ge_idx = word.find("个") 479 | if len(word) >= 1 and word[-1] in "吧呢啊呐噻嘛吖嗨呐哦哒额滴哩哟喽啰耶喔诶": 480 | finals[-1] = finals[-1][:-1] + "5" 481 | elif len(word) >= 1 and word[-1] in "的地得": 482 | finals[-1] = finals[-1][:-1] + "5" 483 | # e.g. 走了, 看着, 去过 484 | # elif len(word) == 1 and word in "了着过" and pos in {"ul", "uz", "ug"}: 485 | # finals[-1] = finals[-1][:-1] + "5" 486 | elif ( 487 | len(word) > 1 488 | and word[-1] in "们子" 489 | and pos in {"r", "n"} 490 | and word not in self.must_not_neural_tone_words 491 | ): 492 | finals[-1] = finals[-1][:-1] + "5" 493 | # e.g. 桌上, 地下, 家里 494 | elif len(word) > 1 and word[-1] in "上下里" and pos in {"s", "l", "f"}: 495 | finals[-1] = finals[-1][:-1] + "5" 496 | # e.g. 上来, 下去 497 | elif len(word) > 1 and word[-1] in "来去" and word[-2] in "上下进出回过起开": 498 | finals[-1] = finals[-1][:-1] + "5" 499 | # 个做量词 500 | elif ( 501 | ge_idx >= 1 502 | and (word[ge_idx - 1].isnumeric() or word[ge_idx - 1] in "几有两半多各整每做是") 503 | ) or word == "个": 504 | finals[ge_idx] = finals[ge_idx][:-1] + "5" 505 | else: 506 | if ( 507 | word in self.must_neural_tone_words 508 | or word[-2:] in self.must_neural_tone_words 509 | ): 510 | finals[-1] = finals[-1][:-1] + "5" 511 | 512 | word_list = self._split_word(word) 513 | finals_list = [finals[: len(word_list[0])], finals[len(word_list[0]) :]] 514 | for i, word in enumerate(word_list): 515 | # conventional neural in Chinese 516 | if ( 517 | word in self.must_neural_tone_words 518 | or word[-2:] in self.must_neural_tone_words 519 | ): 520 | finals_list[i][-1] = finals_list[i][-1][:-1] + "5" 521 | finals = sum(finals_list, []) 522 | return finals 523 | 524 | def _bu_sandhi(self, word: str, finals: List[str]) -> List[str]: 525 | # e.g. 看不懂 526 | if len(word) == 3 and word[1] == "不": 527 | finals[1] = finals[1][:-1] + "5" 528 | else: 529 | for i, char in enumerate(word): 530 | # "不" before tone4 should be bu2, e.g. 不怕 531 | if char == "不" and i + 1 < len(word) and finals[i + 1][-1] == "4": 532 | finals[i] = finals[i][:-1] + "2" 533 | return finals 534 | 535 | def _yi_sandhi(self, word: str, finals: List[str]) -> List[str]: 536 | # "一" in number sequences, e.g. 一零零, 二一零 537 | if word.find("一") != -1 and all( 538 | [item.isnumeric() for item in word if item != "一"] 539 | ): 540 | return finals 541 | # "一" between reduplication words should be yi5, e.g. 看一看 542 | elif len(word) == 3 and word[1] == "一" and word[0] == word[-1]: 543 | finals[1] = finals[1][:-1] + "5" 544 | # when "一" is ordinal word, it should be yi1 545 | elif word.startswith("第一"): 546 | finals[1] = finals[1][:-1] + "1" 547 | else: 548 | for i, char in enumerate(word): 549 | if char == "一" and i + 1 < len(word): 550 | # "一" before tone4 should be yi2, e.g. 一段 551 | if finals[i + 1][-1] == "4": 552 | finals[i] = finals[i][:-1] + "2" 553 | # "一" before non-tone4 should be yi4, e.g. 一天 554 | else: 555 | # "一" 后面如果是标点,还读一声 556 | if word[i + 1] not in self.punc: 557 | finals[i] = finals[i][:-1] + "4" 558 | return finals 559 | 560 | def _split_word(self, word: str) -> List[str]: 561 | word_list = jieba.cut_for_search(word) 562 | word_list = sorted(word_list, key=lambda i: len(i), reverse=False) 563 | first_subword = word_list[0] 564 | first_begin_idx = word.find(first_subword) 565 | if first_begin_idx == 0: 566 | second_subword = word[len(first_subword) :] 567 | new_word_list = [first_subword, second_subword] 568 | else: 569 | second_subword = word[: -len(first_subword)] 570 | new_word_list = [second_subword, first_subword] 571 | return new_word_list 572 | 573 | def _three_sandhi(self, word: str, finals: List[str]) -> List[str]: 574 | if len(word) == 2 and self._all_tone_three(finals): 575 | finals[0] = finals[0][:-1] + "2" 576 | elif len(word) == 3: 577 | word_list = self._split_word(word) 578 | if self._all_tone_three(finals): 579 | # disyllabic + monosyllabic, e.g. 蒙古/包 580 | if len(word_list[0]) == 2: 581 | finals[0] = finals[0][:-1] + "2" 582 | finals[1] = finals[1][:-1] + "2" 583 | # monosyllabic + disyllabic, e.g. 纸/老虎 584 | elif len(word_list[0]) == 1: 585 | finals[1] = finals[1][:-1] + "2" 586 | else: 587 | finals_list = [finals[: len(word_list[0])], finals[len(word_list[0]) :]] 588 | if len(finals_list) == 2: 589 | for i, sub in enumerate(finals_list): 590 | # e.g. 所有/人 591 | if self._all_tone_three(sub) and len(sub) == 2: 592 | finals_list[i][0] = finals_list[i][0][:-1] + "2" 593 | # e.g. 好/喜欢 594 | elif ( 595 | i == 1 596 | and not self._all_tone_three(sub) 597 | and finals_list[i][0][-1] == "3" 598 | and finals_list[0][-1][-1] == "3" 599 | ): 600 | finals_list[0][-1] = finals_list[0][-1][:-1] + "2" 601 | finals = sum(finals_list, []) 602 | # split idiom into two words who's length is 2 603 | elif len(word) == 4: 604 | finals_list = [finals[:2], finals[2:]] 605 | finals = [] 606 | for sub in finals_list: 607 | if self._all_tone_three(sub): 608 | sub[0] = sub[0][:-1] + "2" 609 | finals += sub 610 | 611 | return finals 612 | 613 | def _all_tone_three(self, finals: List[str]) -> bool: 614 | return all(x[-1] == "3" for x in finals) 615 | 616 | # merge "不" and the word behind it 617 | # if don't merge, "不" sometimes appears alone according to jieba, which may occur sandhi error 618 | def __merge_bu(self, seg_list: List[Tuple[str, str]]) -> List[Tuple[str, str]]: 619 | """ 620 | 合并'不'字,在jieba中'不'字单独出现可能会引起错误 621 | """ 622 | last_words = "" 623 | new_seg_list = [] 624 | # 在分词列表中查找单独出现的'不'字 625 | for words, speech_part in seg_list: 626 | if last_words == "不" and words != "不": 627 | words = last_words + words 628 | if words != "不": 629 | new_seg_list.append((words, speech_part)) 630 | last_words = words 631 | if last_words == "不": 632 | new_seg_list.append((last_words, "d")) 633 | return new_seg_list 634 | 635 | # function 1: merge "一" and reduplication words in it's left and right, e.g. "听","一","听" ->"听一听" 636 | # function 2: merge single "一" and the word behind it 637 | # if don't merge, "一" sometimes appears alone according to jieba, which may occur sandhi error 638 | # e.g. 639 | # input seg: [('听', 'v'), ('一', 'm'), ('听', 'v')] 640 | # output seg: [['听一听', 'v']] 641 | def __merge_yi(self, seg: List[Tuple[str, str]]) -> List[Tuple[str, str]]: 642 | """ 643 | 合并'一'字,在jieba中'不'字单独出现可能会引起错误 644 | """ 645 | new_seg = [] 646 | # function 1 647 | for i, (word, pos) in enumerate(seg): 648 | if ( 649 | i - 1 >= 0 650 | and word == "一" 651 | and i + 1 < len(seg) 652 | and seg[i - 1][0] == seg[i + 1][0] 653 | and seg[i - 1][1] == "v" 654 | ): 655 | new_seg[i - 1][0] = new_seg[i - 1][0] + "一" + new_seg[i - 1][0] 656 | else: 657 | if ( 658 | i - 2 >= 0 659 | and seg[i - 1][0] == "一" 660 | and seg[i - 2][0] == word 661 | and pos == "v" 662 | ): 663 | continue 664 | else: 665 | new_seg.append([word, pos]) 666 | seg = new_seg 667 | new_seg = [] 668 | # function 2 669 | for i, (word, pos) in enumerate(seg): 670 | if new_seg and new_seg[-1][0] == "一": 671 | new_seg[-1][0] = new_seg[-1][0] + word 672 | else: 673 | new_seg.append([word, pos]) 674 | return new_seg 675 | 676 | # the first and the second words are all_tone_three 677 | def __merge_continuous_three_tones( 678 | self, seg: List[Tuple[str, str]] 679 | ) -> List[Tuple[str, str]]: 680 | new_seg = [] 681 | sub_finals_list = [ 682 | lazy_pinyin(word, neutral_tone_with_five=True, style=Style.FINALS_TONE3) 683 | for (word, pos) in seg 684 | ] 685 | assert len(sub_finals_list) == len(seg) 686 | merge_last = [False] * len(seg) 687 | for i, (word, pos) in enumerate(seg): 688 | if ( 689 | i - 1 >= 0 690 | and self._all_tone_three(sub_finals_list[i - 1]) 691 | and self._all_tone_three(sub_finals_list[i]) 692 | and not merge_last[i - 1] 693 | ): 694 | # if the last word is reduplication, not merge, because reduplication need to be _neural_sandhi 695 | if ( 696 | not self._is_reduplication(seg[i - 1][0]) 697 | and len(seg[i - 1][0]) + len(seg[i][0]) <= 3 698 | ): 699 | new_seg[-1][0] = new_seg[-1][0] + seg[i][0] 700 | merge_last[i] = True 701 | else: 702 | new_seg.append([word, pos]) 703 | else: 704 | new_seg.append([word, pos]) 705 | 706 | return new_seg 707 | 708 | def _is_reduplication(self, word: str) -> bool: 709 | return len(word) == 2 and word[0] == word[1] 710 | 711 | # the last char of first word and the first char of second word is tone_three 712 | def __merge_continuous_three_tones_2( 713 | self, seg: List[Tuple[str, str]] 714 | ) -> List[Tuple[str, str]]: 715 | new_seg = [] 716 | sub_finals_list = [ 717 | lazy_pinyin(word, neutral_tone_with_five=True, style=Style.FINALS_TONE3) 718 | for (word, pos) in seg 719 | ] 720 | assert len(sub_finals_list) == len(seg) 721 | merge_last = [False] * len(seg) 722 | for i, (word, pos) in enumerate(seg): 723 | if ( 724 | i - 1 >= 0 725 | and sub_finals_list[i - 1][-1][-1] == "3" 726 | and sub_finals_list[i][0][-1] == "3" 727 | and not merge_last[i - 1] 728 | ): 729 | # if the last word is reduplication, not merge, because reduplication need to be _neural_sandhi 730 | if ( 731 | not self._is_reduplication(seg[i - 1][0]) 732 | and len(seg[i - 1][0]) + len(seg[i][0]) <= 3 733 | ): 734 | new_seg[-1][0] = new_seg[-1][0] + seg[i][0] 735 | merge_last[i] = True 736 | else: 737 | new_seg.append([word, pos]) 738 | else: 739 | new_seg.append([word, pos]) 740 | return new_seg 741 | 742 | def __merge_er(self, seg: List[Tuple[str, str]]) -> List[Tuple[str, str]]: 743 | """ 744 | 合并'儿'话 745 | """ 746 | new_seg = [] 747 | for i, (word, pos) in enumerate(seg): 748 | if i - 1 >= 0 and word == "儿" and seg[i - 1][0] != "#": 749 | new_seg[-1][0] = new_seg[-1][0] + seg[i][0] 750 | else: 751 | new_seg.append([word, pos]) 752 | return new_seg 753 | 754 | def __merge_reduplication( 755 | self, seg: List[Tuple[str, str]] 756 | ) -> List[Tuple[str, str]]: 757 | """ 758 | 合并单独的叠词 759 | """ 760 | new_seg = [] 761 | for i, (word, pos) in enumerate(seg): 762 | if new_seg and word == new_seg[-1][0]: 763 | new_seg[-1][0] = new_seg[-1][0] + seg[i][0] 764 | else: 765 | new_seg.append([word, pos]) 766 | return new_seg 767 | 768 | def pre_merge_for_modify(self, seg: List[Tuple[str, str]]) -> List[Tuple[str, str]]: 769 | """ 770 | 自定义jieba分词合并处理 771 | 772 | 输入: jieba分词结果列表 773 | """ 774 | seg = self.__merge_bu(seg) 775 | try: 776 | seg = self.__merge_yi(seg) 777 | except: 778 | log_instance.warning("jieba中文分词:合并'一'字失败") 779 | # print("jieba中文分词:合并'一'字失败") 780 | log_instance.debug("jieba中文分词:合并相同的字词") 781 | seg = self.__merge_reduplication(seg) 782 | log_instance.debug(seg) 783 | seg = self.__merge_continuous_three_tones(seg) 784 | seg = self.__merge_continuous_three_tones_2(seg) 785 | seg = self.__merge_er(seg) 786 | return seg 787 | 788 | def modified_tone(self, word: str, pos: str, finals: List[str]) -> List[str]: 789 | finals = self._bu_sandhi(word, finals) 790 | finals = self._yi_sandhi(word, finals) 791 | finals = self._neural_sandhi(word, pos, finals) 792 | finals = self._three_sandhi(word, finals) 793 | return finals 794 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------