Spaces:
Running
Running
zhzluke96 commited on
Commit ·
f367757
1
Parent(s): bb4ceb3
update
Browse filesFiles changed (9)
1 unmodified line23456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687881 unmodified lineimport zhonfrom modules.utils.detect_lang import guess_langdef split_zhon_sentence(text):result = []pattern = re.compile(zhon.hanzi.sentence)start = 0for match in pattern.finditer(text):# 获取匹配的中文句子end = match.end()result.append(text[start:end])start = end# 最后一个中文句子后面的内容(如果有)也需要添加到结果中if start < len(text):result.append(text[start:])result = [t for t in result if t.strip()]return resultdef split_en_sentence(text):"""Split English text into sentences."""# Define a regex pattern for English sentence splittingpattern = re.compile(r"(?<!\w\.\w.)(?<![A-Z][a-z]\.)(?<=\.|\?|\!)\s")result = pattern.split(text)# Filter out any empty strings or strings that are just whitespaceresult = [sentence.strip() for sentence in result if sentence.strip()]return resultdef is_eng_sentence(text):return guess_lang(text) == "en"def split_zhon_paragraph(text):lines = text.split("\n")result = []for line in lines:if is_eng_sentence(line):result.extend(split_en_sentence(line))else:result.extend(split_zhon_sentence(line))return result# 解析文本 并根据停止符号分割成句子# 可以设置最大阈值,即如果分割片段小于这个阈值会与下一段合并class SentenceSplitter:def __init__(self, threshold=100):self.sentence_threshold = thresholddef parse(self, text):sentences = split_zhon_paragraph(text)# 合并小于最大阈值的片段merged_sentences = []temp_sentence = []for sentence in sentences:if len(sentence) < self.sentence_threshold:temp_sentence.extend(sentence)if len(temp_sentence) >= self.sentence_threshold:merged_sentences.append(temp_sentence)temp_sentence = []else:if temp_sentence:merged_sentences.append(temp_sentence)temp_sentence = []merged_sentences.append(sentence)if temp_sentence:merged_sentences.append(temp_sentence)joind_sentences = ["".join(sentence) for sentence in merged_sentences if sentence]return joind_sentencesif __name__ == "__main__":1 unmodified line234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495961 unmodified lineimport zhonfrom modules.models import get_tokenizerfrom modules.utils.detect_lang import guess_lang# 解析文本 并根据停止符号分割成句子# 可以设置最大阈值,即如果分割片段小于这个阈值会与下一段合并class SentenceSplitter:SEP_TOKEN = " "def __init__(self, threshold=100):assert (isinstance(threshold, int) and threshold > 0), "Threshold must be greater than 0."self.sentence_threshold = thresholdself.tokenizer = get_tokenizer()def count_tokens(self, text: str):return len(self.tokenizer.tokenize(text))def parse(self, text: str):sentences = self.split_paragraph(text)sentences = self.merge_text_by_threshold(sentences)return sentencesdef merge_text_by_threshold(self, setences: list[str]):"""Merge text by threshold.If the length of the text is less than the threshold, merge it with the next text."""merged_sentences: list[str] = []temp_sentence = ""for sentence in setences:if len(temp_sentence) + len(sentence) < self.sentence_threshold:temp_sentence += SentenceSplitter.SEP_TOKEN + sentenceelse:merged_sentences.append(temp_sentence)temp_sentence = sentenceif temp_sentence:merged_sentences.append(temp_sentence)return merged_sentencesdef split_paragraph(self, text: str):"""Split text into sentences."""lines = text.split("\n")sentences: list[str] = []for line in lines:if self.is_eng_sentence(line):sentences.extend(self.split_en_sentence(line))else:sentences.extend(self.split_zhon_sentence(line))return sentencesdef is_eng_sentence(self, text: str):return guess_lang(text) == "en"def split_en_sentence(self, text: str):"""Split English text into sentences."""pattern = re.compile(r"(?<!\w\.\w.)(?<![A-Z][a-z]\.)(?<=\.|\?|\!)\s")sentences = pattern.split(text)sentences = [sentence.strip() for sentence in sentences if sentence.strip()]return sentencesdef split_zhon_sentence(self, text: str):"""Split Chinese text into sentences."""sentences: list[str] = []pattern = re.compile(zhon.hanzi.sentence)start = 0for match in pattern.finditer(text):end = match.end()sentences.append(text[start:end])start = endif start < len(text):sentences.append(text[start:])sentences = [t for t in sentences if t.strip()]return sentencesif __name__ == "__main__":
2 unmodified lines34567867 unmodified lines7677782 unmodified linesimport threadingimport torchfrom modules import configfrom modules.ChatTTS import ChatTTS67 unmodified linesinstance = load_chat_tts()logger.info("ChatTTS models reloaded")return instance2 unmodified lines345678967 unmodified lines7778798081828384852 unmodified linesimport threadingimport torchfrom transformers import LlamaTokenizerfrom modules import configfrom modules.ChatTTS import ChatTTS67 unmodified linesinstance = load_chat_tts()logger.info("ChatTTS models reloaded")return instancedef get_tokenizer() -> LlamaTokenizer:chat_tts = load_chat_tts()tokenizer = chat_tts.pretrain_models["tokenizer"]return tokenizer
1 unmodified line23456789101 unmodified linefrom io import BytesIOimport numpy as npimport soundfile as sffrom pydub import AudioSegment, effectsimport pyrubberband as pyrbINT16_MAX = np.iinfo(np.int16).max1 unmodified line23456789101 unmodified linefrom io import BytesIOimport numpy as npimport pyrubberband as pyrbimport soundfile as sffrom pydub import AudioSegment, effectsINT16_MAX = np.iinfo(np.int16).max
12345613 unmodified lines20212223242526from html.parser import HTMLParserclass HTMLTagRemover(HTMLParser):def __init__(self):super().__init__()13 unmodified linesreturn parser.get_data()if __name__ == "__main__":input_text = "<h1>一个标题</h1> 这是一段包含<code>标签</code>的文本。"output_text = remove_html_tags(input_text)print(output_text) # 输出: 一个标题 这是一段包含标签的文本。1234567891013 unmodified lines24252627282930313233343536373839404142import htmlimport refrom html.parser import HTMLParser# NOTE: 现在没用这个,因为不好解决转义字符的问题# 除非分段处理,但是太麻烦了...class HTMLTagRemover(HTMLParser):def __init__(self):super().__init__()13 unmodified linesreturn parser.get_data()def remove_html_tags_re(text):text = html.unescape(text)html_tags_pattern = re.compile(r"</?([a-zA-Z1-9]+)[^>]*>")return re.sub(html_tags_pattern, " ", text)if __name__ == "__main__":input_text = """<h1>一个标题</h1> 这是一段包含<code>标签</code>的文本。 <code>&</code><设定>一些文本</设定>"""# input_text = "我&你"output_text = remove_html_tags_re(input_text)print(output_text) # 输出: 一个标题 这是一段包含标签的文本。
18 unmodified lines1920212223242526272829303110 unmodified lines4243444546477 unmodified lines555657585960616263646566677 unmodified lines7576777879808118 unmodified linesspk = row.get("speaker")style = row.get("style")ssml += f"{indent}<voice"if spk:ssml += f' spk="{spk}"'if style:ssml += f' style="{style}"'ssml += ">\n"ssml += f"{indent}{indent}{text_normalize(text)}\n"ssml += f"{indent}</voice>\n"# 原封不动输出回去是为了触发 loadding 效果return msg, spk, style, f"<speak version='0.1'>\n{ssml}</speak>"10 unmodified lineswith gr.Row():with gr.Column(scale=1):with gr.Group():spk_input_dropdown = gr.Dropdown(choices=get_spk_choices(),interactive=True,7 unmodified linesshow_label=False,value="*auto",)with gr.Group():msg = gr.Textbox(lines=5, label="Message", placeholder="Type speaker message here")add = gr.Button("Add")undo = gr.Button("Undo")clear = gr.Button("Clear")with gr.Column(scale=5):with gr.Group():gr.Markdown("📔Script")7 unmodified linescol_count=(4, "fixed"),)send_to_ssml_btn = gr.Button("📩Send to SSML", variant="primary")def add_message(msg, spk, style, sheet: pd.DataFrame):if not msg:18 unmodified lines19202122232425262728293031323334353610 unmodified lines474849505152537 unmodified lines616263646566676869707172737475767778797 unmodified lines8788899091929318 unmodified linesspk = row.get("speaker")style = row.get("style")text = text_normalize(text)if text.strip() == "":continuessml += f"{indent}<voice"if spk:ssml += f' spk="{spk}"'if style:ssml += f' style="{style}"'ssml += ">\n"ssml += f"{indent}{indent}{text}\n"ssml += f"{indent}</voice>\n"# 原封不动输出回去是为了触发 loadding 效果return msg, spk, style, f"<speak version='0.1'>\n{ssml}</speak>"10 unmodified lineswith gr.Row():with gr.Column(scale=1):with gr.Group():gr.Markdown("🗣️Speaker")spk_input_dropdown = gr.Dropdown(choices=get_spk_choices(),interactive=True,7 unmodified linesshow_label=False,value="*auto",)with gr.Group():gr.Markdown("📝Text Input")msg = gr.Textbox(lines=5,label="Message",show_label=False,placeholder="Type speaker message here",)add = gr.Button("Add")undo = gr.Button("Undo")clear = gr.Button("Clear")with gr.Column(scale=5):with gr.Group():gr.Markdown("📔Script")7 unmodified linescol_count=(4, "fixed"),)send_to_ssml_btn = gr.Button("📩Send to SSML", variant="primary")def add_message(msg, spk, style, sheet: pd.DataFrame):if not msg:
21 unmodified lines2223242526272 unmodified lines3031323334353636 unmodified lines73747576777879803 unmodified lines848586878889909192938 unmodified lines10210310410510610710810911011111211311411511611711811912011 unmodified lines13213313413513613713813921 unmodified linesindent = " " * 2for i, row in dataframe.iterrows():ssml += f"{indent}<voice"if spk:ssml += f' spk="{spk}"'2 unmodified linesif seed:ssml += f' seed="{seed}"'ssml += ">\n"ssml += f"{indent}{indent}{text_normalize(row.iloc[1])}\n"ssml += f"{indent}</voice>\n"# 原封不动输出回去是为了触发 loadding 效果return dataframe, spk, style, seed, f"<speak version='0.1'>\n{ssml}</speak>"36 unmodified linesshow_label=False,value="*auto",)with gr.Group():gr.Markdown("🗣️Seed")infer_seed_input = gr.Number(value=42,label="Inference Seed",3 unmodified lines)infer_seed_rand_button = gr.Button(value="🎲",variant="secondary",)send_btn = gr.Button("📩Send to SSML", variant="primary")with gr.Column(scale=3):with gr.Group():8 unmodified lines)long_text_split_button = gr.Button("🔪Split Text")with gr.Row():with gr.Column(scale=3):with gr.Group():gr.Markdown("🎨Output")long_text_output = gr.DataFrame(headers=["index", "text", "length"],datatype=["number", "str", "number"],elem_id="long-text-output",interactive=False,wrap=True,value=[],)spk_input_dropdown.change(fn=lambda x: x.startswith("*") and "-1" or x.split(":")[-1].strip(),inputs=[spk_input_dropdown],11 unmodified lines)long_text_split_button.click(split_long_text,inputs=[long_text_input],outputs=[long_text_output],)infer_seed_rand_button.click(21 unmodified lines2223242526272829303132332 unmodified lines3637383940414236 unmodified lines7980818283848586873 unmodified lines9192939495969798991001011021031041051061071081091101111121138 unmodified lines12212312412512612712812913013113213313413513613713813914014114211 unmodified lines15415515615715815916016116216316416516616721 unmodified linesindent = " " * 2for i, row in dataframe.iterrows():text = row.iloc[1]text = text_normalize(text)if text.strip() == "":continuessml += f"{indent}<voice"if spk:ssml += f' spk="{spk}"'2 unmodified linesif seed:ssml += f' seed="{seed}"'ssml += ">\n"ssml += f"{indent}{indent}{text}\n"ssml += f"{indent}</voice>\n"# 原封不动输出回去是为了触发 loadding 效果return dataframe, spk, style, seed, f"<speak version='0.1'>\n{ssml}</speak>"36 unmodified linesshow_label=False,value="*auto",)with gr.Group():gr.Markdown("💃Inference Seed")infer_seed_input = gr.Number(value=42,label="Inference Seed",3 unmodified lines)infer_seed_rand_button = gr.Button(value="🎲",# tooltip="Random Seed",variant="secondary",)with gr.Group():gr.Markdown("🎛️Spliter")eos_input = gr.Textbox(label="eos",value="[uv_break]",)spliter_thr_input = gr.Slider(label="Spliter Threshold",value=100,minimum=50,maximum=1000,step=1,)with gr.Column(scale=3):with gr.Group():8 unmodified lines)long_text_split_button = gr.Button("🔪Split Text")with gr.Group():gr.Markdown("🎨Output")long_text_output = gr.DataFrame(headers=["index", "text", "length"],datatype=["number", "str", "number"],elem_id="long-text-output",interactive=True,wrap=True,value=[],row_count=(0, "dynamic"),col_count=(3, "fixed"),)send_btn = gr.Button("📩Send to SSML", variant="primary")spk_input_dropdown.change(fn=lambda x: x.startswith("*") and "-1" or x.split(":")[-1].strip(),inputs=[spk_input_dropdown],11 unmodified lines)long_text_split_button.click(split_long_text,inputs=[long_text_input,spliter_thr_input,eos_input,],outputs=[long_text_output,],)infer_seed_rand_button.click(
275 unmodified lines276277278279280281282283284285286275 unmodified lines@torch.inference_mode()@spaces.GPU(duration=120)def split_long_text(long_text_input):spliter = SentenceSplitter(webui_config.spliter_threshold)sentences = spliter.parse(long_text_input)sentences = [text_normalize(s) for s in sentences]data = []for i, text in enumerate(sentences):data.append([i, text, len(text)])return data275 unmodified lines276277278279280281282283284285286287275 unmodified lines@torch.inference_mode()@spaces.GPU(duration=120)def split_long_text(long_text_input, spliter_threshold=100, eos=""):spliter = SentenceSplitter(threshold=spliter_threshold)sentences = spliter.parse(long_text_input)sentences = [text_normalize(s) + eos for s in sentences]data = []for i, text in enumerate(sentences):token_length = spliter.count_tokens(text)data.append([i, text, token_length])return data
25 unmodified lines2627282925 unmodified linespython-boxftfylibrosapyrubberband25 unmodified lines262728293025 unmodified linespython-boxftfylibrosapyrubberbandhttps://github.com/Dao-AILab/flash-attention/releases/download/v2.5.9.post1/flash_attn-2.5.9.post1+cu118torch1.12cxx11abiFALSE-cp310-cp310-linux_x86_64.whl
29 unmodified lines303132333435363738394041424329 unmodified linesdcls_patch()ignore_useless_warnings()import subprocesssubprocess.run("pip install flash-attn --no-build-isolation",env={"FLASH_ATTENTION_SKIP_CUDA_BUILD": "TRUE"},shell=True,)def setup_webui_args(parser: argparse.ArgumentParser):parser.add_argument("--server_name", type=str, help="server name")29 unmodified lines30313233343529 unmodified linesdcls_patch()ignore_useless_warnings()def setup_webui_args(parser: argparse.ArgumentParser):parser.add_argument("--server_name", type=str, help="server name")
modules/SentenceSplitter.py+75-67
modules/models.py+7
modules/utils/audio.py+1-1
modules/utils/html.py+18-2
modules/webui/ssml/podcast_tab.py+15-3
modules/webui/ssml/spliter_tab.py+36-8
modules/webui/webui_utils.py+5-4
requirements.txt+2-1
webui.py-8