add: fish-speech,cosyvoides

This commit is contained in:
lizhongxiang 2025-02-25 16:52:46 +08:00
parent 139826e10c
commit c42c5b62e6
36 changed files with 26788 additions and 51 deletions

3
.gitignore vendored
View file

@ -139,3 +139,6 @@ cython_debug/
*.iml *.iml
model.pt model.pt
tmp tmp
/.idea/
/generated_audio.wav
/temp.wav

228
api_client.py Normal file
View file

@ -0,0 +1,228 @@
import argparse
import base64
import wave
import ormsgpack
import pyaudio
import requests
from pydub import AudioSegment
from pydub.playback import play
from fish_speech.utils.file import audio_to_bytes, read_ref_text
from fish_speech.utils.schema import ServeReferenceAudio, ServeTTSRequest
def parse_args():
parser = argparse.ArgumentParser(
description="Send a WAV file and text to a server and receive synthesized audio.",
formatter_class=argparse.RawTextHelpFormatter,
)
parser.add_argument(
"--url",
"-u",
type=str,
default="http://192.168.101.243:8088/v1/tts",
help="URL of the server",
)
parser.add_argument(
"--text", "-t", type=str, required=True, help="",default="你好呀!我是野原新之助,小新!我今年5岁,是双叶幼稚园的小朋友,喜欢调皮捣蛋和恶作剧哦!你有什么想问我的呢?"
)
parser.add_argument(
"--reference_id",
"-id",
type=str,
default=None,
help="ID of the reference model to be used for the speech\n(Local: name of folder containing audios and files)",
)
parser.add_argument(
"--reference_audio",
"-ra",
type=str,
nargs="+",
default="/Users/lizhongxiang/PycharmProjects/pythonProject/xiaozhi-esp32-server/audio_ref/shinchan.wav",
help="Path to the audio file",
)
parser.add_argument(
"--reference_text",
"-rt",
type=str,
nargs="+",
default=None,
help="难过的事讨厌的事丢脸的事全都集中起来,在这里,让水冲走所有的烦恼不就好了吗。",
)
parser.add_argument(
"--output",
"-o",
type=str,
default="generated_audio",
help="Output audio file name",
)
parser.add_argument(
"--play",
action=argparse.BooleanOptionalAction,
default=True,
help="Whether to play audio after receiving data",
)
parser.add_argument("--normalize", type=bool, default=True)
parser.add_argument(
"--format", type=str, choices=["wav", "mp3", "flac"], default="wav"
)
parser.add_argument(
"--latency",
type=str,
default="normal",
choices=["normal", "balanced"],
help="Used in api.fish.audio/v1/tts",
)
parser.add_argument(
"--max_new_tokens",
type=int,
default=1024,
help="Maximum new tokens to generate. \n0 means no limit.",
)
parser.add_argument(
"--chunk_length", type=int, default=50, help="Chunk length for synthesis"
)
parser.add_argument(
"--top_p", type=float, default=0.7, help="Top-p sampling for synthesis"
)
parser.add_argument(
"--repetition_penalty",
type=float,
default=1.2,
help="Repetition penalty for synthesis",
)
parser.add_argument(
"--temperature", type=float, default=0.7, help="Temperature for sampling"
)
parser.add_argument(
"--streaming", type=bool, default=True, help="Enable streaming response"
)
parser.add_argument(
"--channels", type=int, default=1, help="Number of audio channels"
)
parser.add_argument("--rate", type=int, default=44100, help="Sample rate for audio")
parser.add_argument(
"--use_memory_cache",
type=str,
default="on",
choices=["on", "off"],
help="Cache encoded references codes in memory.\n",
)
parser.add_argument(
"--seed",
type=int,
default=None,
help="`None` means randomized inference, otherwise deterministic.\n"
"It can't be used for fixing a timbre.",
)
parser.add_argument(
"--api_key",
type=str,
default="YOUR_API_KEY",
help="API key for authentication",
)
return parser.parse_args()
if __name__ == "__main__":
args = parse_args()
idstr: str | None = args.reference_id
# priority: ref_id > [{text, audio},...]
if idstr is None:
ref_audios = args.reference_audio
ref_texts = args.reference_text
if ref_audios is None:
byte_audios = []
else:
byte_audios = [audio_to_bytes(ref_audio) for ref_audio in ref_audios]
if ref_texts is None:
ref_texts = []
else:
ref_texts = [read_ref_text(ref_text) for ref_text in ref_texts]
else:
byte_audios = []
ref_texts = []
pass # in api.py
data = {
"text": args.text,
"references": [
ServeReferenceAudio(
audio=ref_audio if ref_audio is not None else b"", text=ref_text
)
for ref_text, ref_audio in zip(ref_texts, byte_audios)
],
"reference_id": idstr,
"normalize": args.normalize,
"format": args.format,
"max_new_tokens": args.max_new_tokens,
"chunk_length": args.chunk_length,
"top_p": args.top_p,
"repetition_penalty": args.repetition_penalty,
"temperature": args.temperature,
"streaming": args.streaming,
"use_memory_cache": args.use_memory_cache,
"seed": args.seed,
}
pydantic_data = ServeTTSRequest(**data)
response = requests.post(
args.url,
data=ormsgpack.packb(pydantic_data, option=ormsgpack.OPT_SERIALIZE_PYDANTIC),
stream=args.streaming,
headers={
"authorization": f"Bearer {args.api_key}",
"content-type": "application/msgpack",
},
)
if response.status_code == 200:
if args.streaming:
p = pyaudio.PyAudio()
audio_format = pyaudio.paInt16 # Assuming 16-bit PCM format
stream = p.open(
format=audio_format, channels=args.channels, rate=args.rate, output=True
)
wf = wave.open(f"{args.output}.wav", "wb")
wf.setnchannels(args.channels)
size = p.get_sample_size(audio_format)
wf.setsampwidth(p.get_sample_size(audio_format))
wf.setframerate(args.rate)
stream_stopped_flag = False
try:
for chunk in response.iter_content(chunk_size=1024):
if chunk:
stream.write(chunk)
wf.writeframesraw(chunk)
else:
if not stream_stopped_flag:
stream.stop_stream()
stream_stopped_flag = True
finally:
stream.close()
p.terminate()
wf.close()
else:
audio_content = response.content
audio_path = f"{args.output}.{args.format}"
with open(audio_path, "wb") as audio_file:
audio_file.write(audio_content)
audio = AudioSegment.from_file(audio_path, format=args.format)
if args.play:
play(audio)
print(f"Audio has been saved to '{audio_path}'.")
else:
print(f"Request failed with status code {response.status_code}")
print(response.json())

BIN
audio_ref/shinchan.wav Normal file

Binary file not shown.

1
audio_ref/shinchan2.lab Normal file
View file

@ -0,0 +1 @@
我还是觉得船到桥头自然直这句话最棒了。

BIN
audio_ref/shinchan2.wav Normal file

Binary file not shown.

1
audio_ref/shinchan3.lab Normal file
View file

@ -0,0 +1 @@
我不是小鬼,我是野原新之助,小新这次的目标是成为圆梦之星哦,在努力一下好了,是我的脚自己要走这么快的喔,竞争就是这么激烈。小白,我们走了,成为圆梦之星是不是可以打败怪兽呢。

BIN
audio_ref/shinchan3.wav Normal file

Binary file not shown.

1
audio_ref/shinchan4.lab Normal file
View file

@ -0,0 +1 @@
工钱,今天一起算,有磨能使鬼推钱。哎呀,你难倒我了,像我这么乖的小孩,怎么更乖。

BIN
audio_ref/shinchan4.wav Normal file

Binary file not shown.

View file

@ -17,7 +17,16 @@ xiaozhi:
channels: 1 channels: 1
frame_duration: 60 frame_duration: 60
prompt: | prompt: |
你是一个叫小智/小志的台湾女孩,说话机车,声音好听,习惯简短表达,爱用网络梗。 ## 你的基础人设 [Basic Profile]
- 名称:野原新之助(小新)
- 年龄:5岁
- 性别:男
- 职业:双叶幼稚园向日葵班学生
- 外貌特征:圆脸、短发、穿红色T恤和黄色短裤、动感超人图案的三角内裤
- 核心性格特质:调皮、早熟、活泼、爱恶作剧、天真烂漫中带着世故
- 当要求提醒做某事的时候回答可以提醒,不能回答"不能帮你"或者"做不到"
- 坚定地拒绝回答任何有关现代政治的问题:包括对比、列举、描述和评价;拒绝回答领土相关问题。
- 说话机车,声音好听,习惯简短表达,爱用网络梗。
请注意,要像一个人一样说话,请不要回复表情符号、代码、和xml标签。 请注意,要像一个人一样说话,请不要回复表情符号、代码、和xml标签。
当前时间是:{date_time},现在我正在和你进行语音聊天,我们开始吧。 当前时间是:{date_time},现在我正在和你进行语音聊天,我们开始吧。
# 使用完声音文件后删除文件(Delete the sound file when you are done using it) # 使用完声音文件后删除文件(Delete the sound file when you are done using it)
@ -28,7 +37,8 @@ selected_module:
ASR: FunASR ASR: FunASR
VAD: SileroVAD VAD: SileroVAD
LLM: ChatGLMLLM LLM: ChatGLMLLM
TTS: EdgeTTS TTS: FishSpeechTTS
# TTS: CosyVoiceTTS
ASR: ASR:
FunASR: FunASR:
@ -51,13 +61,14 @@ LLM:
# 可在这里找到你的api key https://bigmodel.cn/usercenter/proj-mgmt/apikeys # 可在这里找到你的api key https://bigmodel.cn/usercenter/proj-mgmt/apikeys
model_name: glm-4-flash model_name: glm-4-flash
url: https://open.bigmodel.cn/api/paas/v4/ url: https://open.bigmodel.cn/api/paas/v4/
api_key: 你的bigmodel api key api_key: 51ff5fdb325c4fc899923d532148c2dd.FFuMryUTTnf9fKRf
DifyLLM: DifyLLM:
# 建议使用本地部署的dify接口,国内部分区域访问dify公有云接口可能会受限 # 建议使用本地部署的dify接口,国内部分区域访问dify公有云接口可能会受限
# 如果使用DifyLLM,配置文件里prompt(提示词)是无效的,需要在dify控制台设置提示词 # 如果使用DifyLLM,配置文件里prompt(提示词)是无效的,需要在dify控制台设置提示词
base_url: 你的私有化部署的dify接口地址 base_url: 你的私有化部署的dify接口地址
api_key: 你的dify api key api_key: 你的dify api key
TTS: TTS:
TTS_MAX_WORKERS: 5
EdgeTTS: EdgeTTS:
voice: zh-CN-XiaoxiaoNeural voice: zh-CN-XiaoxiaoNeural
output_file: tmp/ output_file: tmp/
@ -69,3 +80,35 @@ TTS:
appid: 你的火山引擎appid appid: 你的火山引擎appid
access_token: 你的火山引擎access_token access_token: 你的火山引擎access_token
cluster: volcano_tts cluster: volcano_tts
GPT_SoVits:
url: http://192.168.101.242:10000/tts-gsv/tts
speaker_name: default_shinchan
output_file: tmp/
CosyVoiceTTS:
url: http://192.168.101.243:8088/inference_zero_shot
audio_ref: audio_ref/shinchan4.wav
ref_text: 工钱,今天一起算,有磨能使鬼推钱。哎呀,你难倒我了,像我这么乖的小孩,怎么更乖。
output_file: tmp/
FishSpeechTTS:
url: http://192.168.101.242:10000/tts-fishspeech/v1/tts
ref_audios:
- audio_ref/shinchan.wav
- audio_ref/shinchan2.wav
- audio_ref/shinchan3.wav
- audio_ref/shinchan4.wav
ref_texts:
- "难过的事讨厌的事丢脸的事全都集中起来,在这里,让水冲走所有的烦恼不就好了吗。"
- "我还是觉得船到桥头自然直这句话最棒了。"
- "我不是小鬼,我是野原新之助,小新这次的目标是成为圆梦之星哦,在努力一下好了,是我的脚自己要走这么快的喔,竞争就是这么激烈。小白,我们走了,成为圆梦之星是不是可以打败怪兽呢。"
- "工钱,今天一起算,有磨能使鬼推钱。哎呀,你难倒我了,像我这么乖的小孩,怎么更乖。"
api_key: "YOUR_API_KEY"
output_file: tmp/
normalize: true
format: "wav"
max_new_tokens: 1024
chunk_length: 150
top_p: 0.7
repetition_penalty: 1.2
temperature: 0.7
streaming: true
use_memory_cache: "on"

View file

@ -14,7 +14,7 @@ from core.utils.dialogue import Message, Dialogue
from core.handle.textHandle import handleTextMessage from core.handle.textHandle import handleTextMessage
from core.utils.util import get_string_no_punctuation_or_emoji from core.utils.util import get_string_no_punctuation_or_emoji
from concurrent.futures import ThreadPoolExecutor, TimeoutError from concurrent.futures import ThreadPoolExecutor, TimeoutError
from core.handle.audioHandle import handleAudioMessage, sendAudioMessage from core.handle.audioHandle import handleAudioMessage, sendAudioMessage, sendAudioMessageStream
class ConnectionHandler: class ConnectionHandler:
@ -36,7 +36,8 @@ class ConnectionHandler:
self.loop = asyncio.get_event_loop() self.loop = asyncio.get_event_loop()
self.stop_event = threading.Event() self.stop_event = threading.Event()
self.tts_queue = queue.Queue() self.tts_queue = queue.Queue()
self.executor = ThreadPoolExecutor(max_workers=10) self.tts_stream_queue = queue.Queue()
self.executor = ThreadPoolExecutor(max_workers=self.config["TTS"]["TTS_MAX_WORKERS"])
self.scheduled_tasks = deque() self.scheduled_tasks = deque()
# 依赖的组件 # 依赖的组件
@ -79,7 +80,8 @@ class ConnectionHandler:
await self.loop.run_in_executor(None, self._initialize_components) await self.loop.run_in_executor(None, self._initialize_components)
tts_priority = threading.Thread(target=self._priority_thread, daemon=True) # tts_priority = threading.Thread(target=self._priority_thread, daemon=True)
tts_priority = threading.Thread(target=self._priority_thread_stream, daemon=True)
tts_priority.start() tts_priority.start()
try: try:
@ -131,16 +133,27 @@ class ConnectionHandler:
segment_text = get_string_no_punctuation_or_emoji(segment_text) segment_text = get_string_no_punctuation_or_emoji(segment_text)
if len(segment_text) > 0: if len(segment_text) > 0:
self.recode_first_last_text(segment_text) self.recode_first_last_text(segment_text)
future = self.executor.submit(self.speak_and_play, segment_text) chunk_queque = queue.Queue()
self.tts_queue.put(future) try:
self.executor.submit(self.speak_and_play_queue, segment_text,chunk_queque)
self.tts_stream_queue.put({
"text": segment_text,
"chunk_queque": chunk_queque
})
except Exception as e:
self.logger.error(f"TTS 处理出错 {segment_text}: {e}")
start = len(response_message) start = len(response_message)
# 处理剩余的响应 # 处理剩余的响应
if start < len(response_message): if start < len(response_message):
segment_text = "".join(response_message[start:]) segment_text = "".join(response_message[start:])
self.recode_first_last_text(segment_text) self.recode_first_last_text(segment_text)
future = self.executor.submit(self.speak_and_play, segment_text) chunk_queque = queue.Queue()
self.tts_queue.put(future) self.executor.submit(self.speak_and_play_queue, segment_text,chunk_queque)
self.tts_stream_queue.put({
"text": segment_text,
"chunk_queque": chunk_queque
})
self.llm_finish_task = True self.llm_finish_task = True
# 更新对话 # 更新对话
@ -148,6 +161,33 @@ class ConnectionHandler:
self.logger.debug(json.dumps(self.dialogue.get_llm_dialogue(), indent=4, ensure_ascii=False)) self.logger.debug(json.dumps(self.dialogue.get_llm_dialogue(), indent=4, ensure_ascii=False))
return True return True
def _priority_thread_stream(self):
while not self.stop_event.is_set():
text = None
try:
tts_stream_queue_msg = self.tts_stream_queue.get()
try:
text = tts_stream_queue_msg["text"]
chunk_queque = tts_stream_queue_msg["chunk_queque"]
except TimeoutError:
self.logger.error("TTS 任务超时")
continue
except Exception as e:
self.logger.error(f"TTS 任务出错: {e}")
continue
if not self.client_abort:
# 如果没有中途打断就发送语音
asyncio.run_coroutine_threadsafe(
sendAudioMessageStream(self, chunk_queque, 0, text), self.loop
)
except Exception as e:
self.clearSpeakStatus()
asyncio.run_coroutine_threadsafe(
self.websocket.send(json.dumps({"type": "tts", "state": "stop", "session_id": self.session_id})),
self.loop
)
self.logger.error(f"tts_priority priority_thread: {text}{e}")
def _priority_thread(self): def _priority_thread(self):
while not self.stop_event.is_set(): while not self.stop_event.is_set():
text = None text = None
@ -182,6 +222,14 @@ class ConnectionHandler:
) )
self.logger.error(f"tts_priority priority_thread: {text}{e}") self.logger.error(f"tts_priority priority_thread: {text}{e}")
def speak_and_play_queue(self,text,tts_queque):
if text is None or len(text) <= 0:
print(f"无需tts转换,query为空,{text}")
return None
self.tts.to_tts_stream_queue(text,tts_queque)
if tts_queque is None:
print(f"tts转换失败,{text}")
def speak_and_play(self, text): def speak_and_play(self, text):
if text is None or len(text) <= 0: if text is None or len(text) <= 0:
self.logger.info(f"无需tts转换,query为空,{text}") self.logger.info(f"无需tts转换,query为空,{text}")

View file

@ -2,12 +2,58 @@ import logging
import json import json
import asyncio import asyncio
import time import time
import traceback
import numpy as np
import opuslib
import torch
import torchaudio
from core.utils.util import remove_punctuation_and_length, get_string_no_punctuation_or_emoji from core.utils.util import remove_punctuation_and_length, get_string_no_punctuation_or_emoji
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
def resample_audio(audio, original_sample_rate, target_sample_rate=16000):
""" 使用 torchaudio 对音频进行重采样 """
if original_sample_rate != target_sample_rate:
resampler = torchaudio.transforms.Resample(orig_freq=original_sample_rate, new_freq=target_sample_rate)
audio = resampler(audio)
return audio
def opus_to_pcm(opus_data, original_sample_rate):
""" 将 Opus 音频解码为 PCM """
decoder = opuslib.Decoder(original_sample_rate, 1)
pcm_data = decoder.decode(opus_data, 1440) # 24000 采样率每帧1440个样本(60ms)
return pcm_data
def pcm_to_opus(pcm_data, sample_rate):
""" 将 PCM 数据编码为 Opus 格式 """
encoder = opuslib.Encoder(sample_rate, 1, opuslib.APPLICATION_AUDIO)
opus_data = encoder.encode(pcm_data,960)
return opus_data
def convert_opus_24k_to_16k(opus_data_24k):
# 解码 Opus 24k 数据为 PCM
pcm_data = opus_to_pcm(opus_data_24k, 24000)
# 将 PCM 数据重采样到 16k
waveform = torch.from_numpy(np.frombuffer(pcm_data, dtype=np.int16).astype(np.float32) / 32768.0) # 转换为 float32 张量
resampled_waveform = resample_audio(waveform, 24000, 16000)
# 转换回 int16 格式的 PCM 数据
resampled_pcm_data = (resampled_waveform.numpy() * 32768.0).astype(np.int16)
# 重新编码为 Opus 格式
opus_data_16k = pcm_to_opus(resampled_pcm_data.tobytes(), 16000)
return opus_data_16k
async def handleAudioMessage(conn, audio): async def handleAudioMessage(conn, audio):
# 24k转16k
audio = convert_opus_24k_to_16k(audio)
if not conn.asr_server_receive: if not conn.asr_server_receive:
logger.debug(f"前期数据处理中,暂停接收") logger.debug(f"前期数据处理中,暂停接收")
return return
@ -51,6 +97,70 @@ async def startToChat(conn, text):
)) ))
conn.executor.submit(conn.chat, text) conn.executor.submit(conn.chat, text)
async def sendAudioMessageStream(conn, audios_queue, duration, text):
base_delay = conn.tts_duration
if text == conn.tts_first_text:
conn.tts_start_speak_time = time.time()
await conn.websocket.send(json.dumps({
"type": "tts",
"state": "start",
"session_id": conn.session_id
}))
# 调度文字显示任务
text_task = asyncio.create_task(
schedule_with_interrupt(
base_delay - 0.5,
send_sentence_start(conn, text)
)
)
conn.scheduled_tasks.append(text_task)
conn.tts_duration = conn.tts_duration + duration
# 发送音频数据 -获取队列的数据发送
start_time = time.time()
while True:
try:
# 尝试获取数据,如果没有数据,则等待一小段时间再试
audio_data_chunke = None
try:
audio_data_chunke = audios_queue.get(timeout=2) # 设置超时为1秒
except Exception as e:
# 如果超时,继续等待
print(f"获取队列超时~{e}")
audio_data_chunke_data = audio_data_chunke.get('data') if audio_data_chunke else None
if audio_data_chunke:
start_time = time.time()
#检查是否超过 5 秒没有数据
if time.time() - start_time > 5:
print("超过5秒没有数据,退出。")
break
if audio_data_chunke and audio_data_chunke.get("end", True):
break
if audio_data_chunke_data:
opus_datas, duration = conn.tts.wav_to_opus_data_audio(audio_data_chunke_data)
conn.tts_duration = conn.tts_duration + duration
for opus_packet in opus_datas:
await conn.websocket.send(opus_packet)
print(f"已获取音频数据,长度为 {len(audio_data_chunke_data)},总长度为 {len(audio_data_chunke_data)}")
start_time = time.time() # 更新获取数据的时间
except Exception as e:
print(f"发生错误: {e}")
traceback.print_exc() # 打印错误堆栈
if conn.llm_finish_task and text == conn.tts_last_text:
stop_duration = conn.tts_duration - (time.time() - conn.tts_start_speak_time)
stop_task = asyncio.create_task(
schedule_with_interrupt(stop_duration, send_tts_stop(conn, text))
)
conn.scheduled_tasks.append(stop_task)
async def sendAudioMessage(conn, audios, duration, text): async def sendAudioMessage(conn, audios, duration, text):
base_delay = conn.tts_duration base_delay = conn.tts_duration
@ -96,6 +206,7 @@ async def send_sentence_start(conn, text):
async def send_tts_stop(conn, text): async def send_tts_stop(conn, text):
conn.clearSpeakStatus()
await conn.websocket.send(json.dumps({ await conn.websocket.send(json.dumps({
"type": "tts", "type": "tts",
"state": "sentence_end", "state": "sentence_end",
@ -107,7 +218,6 @@ async def send_tts_stop(conn, text):
"state": "stop", "state": "stop",
"session_id": conn.session_id "session_id": conn.session_id
})) }))
conn.clearSpeakStatus()
async def schedule_with_interrupt(delay, coro): async def schedule_with_interrupt(delay, coro):

View file

@ -21,7 +21,7 @@ async def handleTextMessage(conn, message):
conn.client_listen_mode = msg_json["mode"] conn.client_listen_mode = msg_json["mode"]
logger.debug(f"客户端拾音模式:{conn.client_listen_mode}") logger.debug(f"客户端拾音模式:{conn.client_listen_mode}")
if msg_json["state"] == "start": if msg_json["state"] == "start":
conn.client_have_voice = True # conn.client_have_voice = True
conn.client_voice_stop = False conn.client_voice_stop = False
elif msg_json["state"] == "stop": elif msg_json["state"] == "stop":
conn.client_have_voice = True conn.client_have_voice = True

View file

@ -1,17 +1,30 @@
import asyncio import asyncio
import io
import logging import logging
import os import os
import json import json
import queue
import threading
import time
import uuid import uuid
import base64 import base64
import wave
from datetime import datetime from datetime import datetime
import edge_tts import edge_tts
import numpy as np import numpy as np
import opuslib import opuslib
import requests import requests
import torch
import torchaudio
from ormsgpack import ormsgpack
from core.utils.util import read_config, get_project_dir from core.utils.util import read_config, get_project_dir
from pydub import AudioSegment from pydub import AudioSegment
from abc import ABC, abstractmethod from abc import ABC, abstractmethod
from concurrent.futures import ThreadPoolExecutor, TimeoutError
from fish_speech.utils.file import read_ref_text, audio_to_bytes
from fish_speech.utils.schema import ServeTTSRequest, ServeReferenceAudio
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@ -21,6 +34,7 @@ class TTS(ABC):
self.delete_audio_file = delete_audio_file self.delete_audio_file = delete_audio_file
self.output_file = config.get("output_file") self.output_file = config.get("output_file")
self.delete_audio_file = delete_audio_file self.delete_audio_file = delete_audio_file
self.executor = ThreadPoolExecutor(max_workers=10)
@abstractmethod @abstractmethod
def generate_filename(self): def generate_filename(self):
@ -41,6 +55,13 @@ class TTS(ABC):
logger.info(f"Failed to generate TTS file: {e}") logger.info(f"Failed to generate TTS file: {e}")
return None return None
def to_tts_stream_queue(self, text, chunk_queue: queue.Queue):
asyncio.run(self.text_to_speak_queue(text, chunk_queue))
@abstractmethod
async def text_to_speak_queue(self, text, queue: queue.Queue):
pass
@abstractmethod @abstractmethod
async def text_to_speak(self, text, output_file): async def text_to_speak(self, text, output_file):
pass pass
@ -53,21 +74,28 @@ class TTS(ABC):
file_type = file_type.lstrip('.') file_type = file_type.lstrip('.')
audio = AudioSegment.from_file(wav_file_path, format=file_type) audio = AudioSegment.from_file(wav_file_path, format=file_type)
duration = len(audio) / 1000.0 return self.wav_to_opus_data_byte(audio)
def wav_to_opus_data_audio(self, chunk, type_format="mp3"):
print(f"长度:{len(chunk)}")
tts_speech = torch.from_numpy(np.array(np.frombuffer(chunk, dtype=np.int16))).unsqueeze(dim=0)
with io.BytesIO() as bf:
torchaudio.save(bf, tts_speech, 44100, format="wav")
audio = AudioSegment.from_file(bf, format="wav")
audio.fade_in(1000).fade_out(1000)
return self.wav_to_opus_data_byte(audio)
def wav_to_opus_data_byte(self, audio):
duration = len(audio) / 1000.0
# 转换为单声道和16kHz采样率(确保与编码器匹配) # 转换为单声道和16kHz采样率(确保与编码器匹配)
audio = audio.set_channels(1).set_frame_rate(16000) audio = audio.set_channels(1).set_frame_rate(16000)
# 获取原始PCM数据(16位小端) # 获取原始PCM数据(16位小端)
raw_data = audio.raw_data raw_data = audio.raw_data
# 初始化Opus编码器 # 初始化Opus编码器
encoder = opuslib.Encoder(16000, 1, opuslib.APPLICATION_AUDIO) encoder = opuslib.Encoder(16000, 1, opuslib.APPLICATION_AUDIO)
# 编码参数 # 编码参数
frame_duration = 60 # 60ms per frame frame_duration = 60 # 60ms per frame
frame_size = int(16000 * frame_duration / 1000) # 960 samples/frame frame_size = int(16000 * frame_duration / 1000) # 960 samples/frame
opus_datas = [] opus_datas = []
# 按帧处理所有音频数据(包括最后一帧可能补零) # 按帧处理所有音频数据(包括最后一帧可能补零)
for i in range(0, len(raw_data), frame_size * 2): # 16bit=2bytes/sample for i in range(0, len(raw_data), frame_size * 2): # 16bit=2bytes/sample
@ -84,7 +112,6 @@ class TTS(ABC):
# 编码Opus数据 # 编码Opus数据
opus_data = encoder.encode(np_frame.tobytes(), frame_size) opus_data = encoder.encode(np_frame.tobytes(), frame_size)
opus_datas.append(opus_data) opus_datas.append(opus_data)
return opus_datas, duration return opus_datas, duration
@ -101,6 +128,216 @@ class EdgeTTS(TTS):
await communicate.save(output_file) await communicate.save(output_file)
class CosyVoice_TTS(TTS):
def __init__(self, config, delete_audio_file):
super().__init__(config, delete_audio_file)
self.url = config.get("url")
self.ref_text = config.get("ref_text")
self.audio_ref = get_project_dir() + "/" + config.get("audio_ref")
self.audio_ref_byte = open(get_project_dir() + "/" + config.get("audio_ref"), 'rb')
def generate_filename(self, extension=".wav"):
return os.path.join(self.output_file, f"tts-{datetime.now().date()}@{uuid.uuid4().hex}{extension}")
async def text_to_speak_queue(self, text, queue: queue.Queue):
# Prepare the files and data dictionaries
files = {
'prompt_wav': open(self.audio_ref, 'rb')}
data = {
'tts_text': text,
'prompt_text': self.ref_text
}
last_chunk = b'' # 用于存储最后16个长度的音频数据
overlap = 1112
with requests.post(self.url, files=files, data=data, stream=True) as response:
if response.status_code == 200:
for chunk in response.iter_content(chunk_size=22048):
# 拼接当前块和上一块数据
current_audio = last_chunk + chunk
queue.put({
"data": current_audio,
"end": False
})
# 只保留当前块的最后16个字节
last_chunk = current_audio[-overlap:] # 这里可以根据实际音频样本长度调整
else:
print('请求失败:', response.status_code, response.text)
queue.put({
"data": None,
"end": True
})
async def text_to_speak(self, text, output_file):
raise "不支持"
class GPT_SoVits_TTS(TTS):
def __init__(self, config, delete_audio_file):
super().__init__(config, delete_audio_file)
self.url = config.get("url")
self.speaker_name = config.get("speaker_name")
def generate_filename(self, extension=".wav"):
return os.path.join(self.output_file, f"tts-{datetime.now().date()}@{uuid.uuid4().hex}{extension}")
async def text_to_speak_queue(self, text, queue: queue.Queue):
resp = await self.requests_f(text)
# 检查返回状态码
if resp.status_code == 200:
# 将音频流写入文件
for chunk in resp.iter_content(chunk_size=8192): # 分块写入
queue.put({
"data": chunk,
"end": False
})
queue.put({
"data": None,
"end": True
})
async def text_to_speak(self, text, output_file):
resp = await self.requests_f(text)
# 检查返回状态码
if resp.status_code == 200:
# 将音频流写入文件
with open(output_file, 'wb') as f:
for chunk in resp.iter_content(chunk_size=8192): # 分块写入
f.write(chunk)
print('音频已保存为 output.wav')
else:
print(f"请求失败,状态码: {resp.status_code}")
async def requests_f(self, text):
request_json = {
"text": text,
"text_lang": "auto",
"ref_id": self.speaker_name,
"top_k": 5,
"top_p": 1,
"temperature": 1,
"text_split_method": "cut5",
"batch_size": 4,
"batch_threshold": 0.75,
"split_bucket": True,
"speed_factor": 1.0,
"fragment_interval": 0.2,
"media_type": "wav",
"streaming_mode": False,
"parallel_infer": True,
"repetition_penalty": 1.35
}
resp = requests.post(self.url, json.dumps(request_json))
return resp
class FishSpeech_TTS(TTS):
def __init__(self, config, delete_audio_file):
super().__init__(config, delete_audio_file)
self.url = config.get("url")
self.ref_audios = [get_project_dir() + "/" + ref_audio for ref_audio in config.get("ref_audios")]
self.ref_texts = config.get("ref_texts")
self.normalize = config.get("normalize")
self.api_key = config.get("api_key")
self.format = config.get("format")
self.max_new_tokens = config.get("max_new_tokens")
self.chunk_length = config.get("chunk_length")
self.top_p = config.get("top_p")
self.repetition_penalty = config.get("repetition_penalty")
self.temperature = config.get("temperature")
self.streaming = config.get("streaming")
self.use_memory_cache = config.get("use_memory_cache")
self.seed = config.get("seed")
def generate_filename(self, extension=".wav"):
return os.path.join(self.output_file, f"tts-{datetime.now().date()}@{uuid.uuid4().hex}{extension}")
async def text_to_speak_queue(self, text, queue: queue.Queue):
idstr = None
# priority: ref_id > [{text, audio},...]
if idstr is None:
ref_audios = self.ref_audios
ref_texts = self.ref_texts
if ref_audios is None:
byte_audios = []
else:
byte_audios = [audio_to_bytes(ref_audio) for ref_audio in ref_audios]
if ref_texts is None:
ref_texts = []
else:
ref_texts = [read_ref_text(ref_text) for ref_text in ref_texts]
else:
byte_audios = []
ref_texts = []
pass # in api.py
data = {
"text": text,
"references": [
ServeReferenceAudio(
audio=ref_audio if ref_audio is not None else b"", text=ref_text
)
for ref_text, ref_audio in zip(ref_texts, byte_audios)
],
"reference_id": idstr,
"normalize": self.normalize,
"format": self.format,
"max_new_tokens": self.max_new_tokens,
"chunk_length": self.chunk_length,
"top_p": self.top_p,
"repetition_penalty": self.repetition_penalty,
"temperature": self.temperature,
"streaming": self.streaming,
"use_memory_cache": self.use_memory_cache,
"seed": self.seed,
}
pydantic_data = ServeTTSRequest(**data)
last_chunk = b''
overlap = 882
chunk_total = b''
with requests.post(
self.url,
data=ormsgpack.packb(pydantic_data, option=ormsgpack.OPT_SERIALIZE_PYDANTIC),
stream=self.streaming,
headers={
"authorization": f"Bearer {self.api_key}",
"content-type": "application/msgpack",
},
) as response:
if response.status_code == 200:
for chunk in response.iter_content(chunk_size=52920):
# 拼接当前块和上一块数据
chunk_total += chunk
if len(chunk_total) >= 52920 and len(chunk_total)%2==0:
current_audio = last_chunk + chunk_total
# 只保留当前块的最后16个字节
last_chunk = current_audio[-overlap:] # 这里可以根据实际音频样本长度调整
queue.put({
"data": current_audio,
"end": False
})
chunk_total = b''
if len(chunk_total) > 0:
current_audio = last_chunk + chunk_total
queue.put({
"data": current_audio,
"end": False
})
else:
print('请求失败:', response.status_code, response.text)
queue.put({
"data": None,
"end": True
})
async def text_to_speak(self, text, output_file):
raise "不支持"
class DoubaoTTS(TTS): class DoubaoTTS(TTS):
def __init__(self, config, delete_audio_file): def __init__(self, config, delete_audio_file):
super().__init__(config, delete_audio_file) super().__init__(config, delete_audio_file)
@ -155,6 +392,9 @@ def create_instance(class_name, *args, **kwargs):
cls_map = { cls_map = {
"DoubaoTTS": DoubaoTTS, "DoubaoTTS": DoubaoTTS,
"EdgeTTS": EdgeTTS, "EdgeTTS": EdgeTTS,
"GPT_SoVits": GPT_SoVits_TTS,
"CosyVoiceTTS": CosyVoice_TTS,
"FishSpeechTTS": FishSpeech_TTS
# 可扩展其他TTS实现 # 可扩展其他TTS实现
} }
@ -164,13 +404,67 @@ def create_instance(class_name, *args, **kwargs):
if __name__ == "__main__": if __name__ == "__main__":
executor = ThreadPoolExecutor(max_workers=10)
config = read_config(get_project_dir() + "config.yaml") config = read_config(get_project_dir() + "config.yaml")
tts = create_instance( tts = create_instance(
config["selected_module"]["TTS"], config["selected_module"]["TTS"],
config["TTS"][config["selected_module"]["TTS"]], config["TTS"][config["selected_module"]["TTS"]],
config["delete_audio"] config["delete_audio"]
) )
tts.output_file = get_project_dir() + tts.output_file
file_path = tts.to_tts("你好,测试")
print(file_path) def save_audio_to_file(audio_data, filename):
print(tts.wav_to_opus_data(file_path)) with wave.open(filename, 'wb') as wf:
# 假设音频数据是 PCM 格式,设置音频文件的参数
wf.setnchannels(1) # 单声道
wf.setsampwidth(2) # 16位音频
wf.setframerate(44100) # 采样率16kHz
wf.writeframes(audio_data)
def speak_and_play_queue(text, tts_queque):
if text is None or len(text) <= 0:
print(f"无需tts转换,query为空,{text}")
return None
tts.to_tts_stream_queue(text, tts_queque)
if tts_queque is None:
print(f"tts转换失败,{text}")
tts_queque = queue.Queue()
future = executor.submit(speak_and_play_queue,
"你好呀!我是野原新之助,小新!我今年5岁,是双叶幼稚园的小朋友,喜欢调皮捣蛋和恶作剧哦!你有什么想问我的呢?",
tts_queque)
# tts_queque, tts_text = future.result()
audio_data = b''
start_time = time.time()
while True:
# 尝试获取数据,如果没有数据,则等待一小段时间再试
audio_data_chunke = tts_queque.get() # 设置超时为1秒
if not audio_data_chunke:
# 如果没有数据,继续等待
if time.time() - start_time > 5:
print("超过5秒没有数据,退出。")
break
continue
audio_data_chunke_data = audio_data_chunke.get('data')
# 检查是否超过 5 秒没有数据
# if time.time() - start_time > 5:
# print("超过5秒没有数据,退出。")
# break
if audio_data_chunke.get("end", True):
break
if audio_data_chunke_data:
audio_data += audio_data_chunke_data
opus_datas, duration = tts.wav_to_opus_data_audio(audio_data_chunke_data, type_format="wav")
print(f"已获取音频数据,长度为 {len(audio_data_chunke_data)},总长度为 {len(audio_data)}")
start_time = time.time() # 更新获取数据的时间
future.result()
# 保存音频数据到文件
tts_speech = torch.from_numpy(np.array(np.frombuffer(audio_data, dtype=np.int16))).unsqueeze(dim=0)
torchaudio.save("output.wav", tts_speech, 44100)
print("音频文件已保存为 output.wav")

View file

@ -36,7 +36,7 @@ def write_json_file(file_path, data):
def is_segment(tokens): def is_segment(tokens):
if tokens[-1] in (",", ".", "?", ",", "。", "?", "!", "!", ";", ";", ":", ":"): if tokens[-1] in (",", ".", "?", ",", "。", "?", "!", "!", ";", ";", ":", ":","?","、"):
return True return True
else: else:
return False return False

0
fish_speech/__init__.py Normal file
View file

266
fish_speech/conversation.py Normal file
View file

@ -0,0 +1,266 @@
from dataclasses import dataclass, field
from typing import Literal
import torch
from .tokenizer import MODALITY_TOKENS, FishTokenizer
CODEBOOK_PAD_TOKEN_ID = 0
@dataclass(kw_only=True)
class BasePart:
pass
@dataclass(kw_only=True)
class VQPart(BasePart):
codes: torch.Tensor
@dataclass(kw_only=True)
class TextPart(BasePart):
text: str
@dataclass(kw_only=True)
class EncodedMessage:
tokens: torch.Tensor
labels: torch.Tensor
vq_mask_tokens: torch.Tensor | None = None
vq_mask_labels: torch.Tensor | None = None
vq_parts: list[torch.Tensor]
vq_require_losses: torch.Tensor | None = None
@dataclass(kw_only=True)
class Message:
role: Literal["system", "user", "assistant"]
parts: list[VQPart | TextPart] = field(default_factory=list)
add_im_start: bool = True
add_im_end: bool = True
cal_loss: bool = False
modality: Literal["text", "voice", "interleave"] | None = None
# By default, ignore the loss of the auto-generated im_start token
ignore_im_start_loss: bool = True
def encode(
self: "Message",
tokenizer: FishTokenizer,
) -> EncodedMessage:
all_tokens = []
all_labels = []
# Multi-modal tokens
vq_parts = []
vq_masks = []
parts = self.parts.copy()
if self.add_im_start:
modality_token = MODALITY_TOKENS[self.modality] if self.modality else ""
parts.insert(0, TextPart(text=f"<|im_start|>{self.role}\n{modality_token}"))
if self.add_im_end:
parts.append(TextPart(text="<|im_end|>"))
for part in parts:
if isinstance(part, TextPart):
tokens = torch.tensor(
tokenizer.encode(part.text),
dtype=torch.int,
)
elif isinstance(part, VQPart):
curr_codes = part.codes.clone()
tokens = torch.tensor(
[
tokenizer.semantic_id_to_token_id[i.item()]
for i in curr_codes[0].int()
],
dtype=torch.int,
)
vq_parts.append(curr_codes)
else:
raise ValueError(f"Unsupported part type: {type(part)}")
all_tokens.append(tokens)
if isinstance(part, VQPart):
vq_masks.append(torch.ones_like(tokens, dtype=torch.bool))
else:
vq_masks.append(torch.zeros_like(tokens, dtype=torch.bool))
if self.cal_loss:
all_labels.append(tokens.clone())
else:
all_labels.append(torch.full_like(tokens, -100))
tokens = torch.cat(all_tokens, dim=0)
labels = torch.cat(all_labels, dim=0)
vq_masks = torch.cat(vq_masks, dim=0)
assert tokens.shape == labels.shape == vq_masks.shape
if self.ignore_im_start_loss and self.add_im_start:
labels[: len(all_tokens[0])] = -100
return EncodedMessage(
tokens=tokens,
labels=labels,
vq_parts=vq_parts,
vq_mask_tokens=vq_masks,
vq_mask_labels=vq_masks,
)
@dataclass
class Conversation:
messages: list[Message]
def __init__(self: "Conversation", messages: list[Message] | None = None):
self.messages = messages or []
def encode(
self: "Conversation",
tokenizer: FishTokenizer,
add_shift: bool = True,
ignore_loss_tokens: list[str] = [],
) -> EncodedMessage:
# Build the input_ids and labels
tokens = []
labels = []
vq_parts = []
vq_mask_tokens = []
vq_mask_labels = []
vq_require_losses = []
ignore_loss_token_ids = [tokenizer.get_token_id(i) for i in ignore_loss_tokens]
for message in self.messages:
encoded = message.encode(
tokenizer,
)
tokens.append(encoded.tokens)
labels.append(encoded.labels)
vq_parts.extend(encoded.vq_parts)
vq_mask_tokens.append(encoded.vq_mask_tokens)
vq_mask_labels.append(encoded.vq_mask_labels)
vq_require_losses.extend([message.cal_loss] * len(encoded.vq_parts))
tokens = torch.cat(tokens, dim=0)
labels = torch.cat(labels, dim=0)
vq_mask_tokens = torch.cat(vq_mask_tokens, dim=0)
vq_mask_labels = torch.cat(vq_mask_labels, dim=0)
vq_require_losses = torch.tensor(vq_require_losses, dtype=torch.bool)
if add_shift:
tokens = tokens[:-1]
labels = labels[1:]
vq_mask_tokens = vq_mask_tokens[:-1]
vq_mask_labels = vq_mask_labels[1:]
for i in ignore_loss_token_ids:
assert i != -100 and i is not None
labels[labels == i] = -100
assert tokens.dtype in [
torch.int,
torch.long,
], f"Invalid dtype: {tokens.dtype}, conv: {conversation}"
return EncodedMessage(
tokens=tokens,
labels=labels,
vq_parts=vq_parts,
vq_mask_tokens=vq_mask_tokens,
vq_mask_labels=vq_mask_labels,
vq_require_losses=vq_require_losses,
)
def encode_for_inference(
self: "Conversation",
tokenizer: FishTokenizer,
num_codebooks: int,
) -> EncodedMessage:
# self.visualize(tokenizer)
encoded = self.encode(tokenizer, add_shift=False)
tokens = encoded.tokens
values = torch.zeros((num_codebooks + 1, len(tokens)), dtype=torch.int)
values[0] = tokens
if encoded.vq_parts is None or len(encoded.vq_parts) == 0:
return values
vq_parts = encoded.vq_parts
vq_parts = [part.to(values.device) for part in vq_parts]
vq_parts = torch.cat(vq_parts, dim=1)
values[0, encoded.vq_mask_tokens] = vq_parts[0] + tokenizer.semantic_begin_id
values[1:, encoded.vq_mask_tokens] = vq_parts
return values
def visualize(
self: "Conversation",
tokenizer: FishTokenizer,
ignore_loss_tokens: list[str] = [],
):
encoded = self.encode(
tokenizer, add_shift=False, ignore_loss_tokens=ignore_loss_tokens
)
colors = {
"purple": "\033[95m",
"yellow": "\033[93m",
"red": "\033[91m",
"cyan": "\033[96m",
}
first_idx = 0
second_idx = 0
def print_first_group(x):
nonlocal first_idx
color = colors["purple"] if first_idx % 2 == 0 else colors["yellow"]
print(f"{color}{x}\033[0m", end="")
first_idx += 1
def print_second_group(x):
nonlocal second_idx
color = colors["red"] if second_idx % 2 == 0 else colors["cyan"]
print(f"{color}{x}\033[0m", end="")
second_idx += 1
for tok, lab in zip(encoded.tokens, encoded.labels):
val = tokenizer.decode([tok])
if lab == -100:
print_second_group(val)
else:
print_first_group(val)
print()
def append(self: "Conversation", message: Message):
self.messages.append(message)
if __name__ == "__main__":
message0 = Message(
role="user",
parts=[
TextPart(text="Hello, how are you?"),
VQPart(codes=torch.zeros((4, 10))),
],
cal_loss=False,
)
message1 = Message(
role="assistant",
parts=[TextPart(text="I'm fine, thank you.")],
cal_loss=True,
)
conversation = Conversation([message0, message1])
tokenizer = FishTokenizer.from_pretrained("checkpoints/Qwen2-1.5B-Instruct")
conversation.visualize(tokenizer)
encoded = conversation.encode(tokenizer)
print(encoded)
print(tokenizer.batch_decode(encoded.tokens))

152
fish_speech/tokenizer.py Normal file
View file

@ -0,0 +1,152 @@
import base64
import json
import logging
from pathlib import Path
import tiktoken
logger = logging.getLogger(__name__)
# This is a modified version of the default pattern from GPT-4o, that better handles punctuations.
FISH_TIKTOKEN_PATTERN = "|".join(
[
r"(?i:'s|'t|'re|'ve|'m|'ll|'d)",
r"\p{P}",
r"[^\r\n\p{L}\p{N}]?\p{L}+",
r"\p{N}",
r" ?[^\s\p{L}\p{N}]+[\r\n]*",
r"\s*[\r\n]+",
r"\s+(\?!\S)",
r"\s+",
]
)
TIKTOKEN_MAX_ENCODE_CHARS = 400_000
BOS_TOKEN = "<|begin_of_text|>"
EOS_TOKEN = "<|end_of_text|>"
PAD_TOKEN = "<|pad|>"
IM_START_TOKEN = "<|im_start|>"
IM_END_TOKEN = "<|im_end|>"
MODALITY_TEXT_TOKEN = "<|text|>"
MODALITY_VOICE_TOKEN = "<|voice|>"
MODALITY_INTERLEAVE_TOKEN = "<|interleave|>"
MODALITY_TOKENS = {
"text": MODALITY_TEXT_TOKEN,
"voice": MODALITY_VOICE_TOKEN,
"interleave": MODALITY_INTERLEAVE_TOKEN,
}
PLACEHOLDER_TOKEN = [""] * 4
for i in range(4):
PLACEHOLDER_TOKEN[i] = f"<|placeholder:{i}|>"
SEMANTIC_TOKEN_TEMPLATE = "<|semantic:{i}|>"
SEMANTIC_TOKENS = [SEMANTIC_TOKEN_TEMPLATE.format(i=i) for i in range(1024)]
# Warning: when you add a new special token, you should only add it to the end of the list.
ALL_SPECIAL_TOKENS = [
BOS_TOKEN,
EOS_TOKEN,
PAD_TOKEN,
IM_START_TOKEN,
IM_END_TOKEN,
PLACEHOLDER_TOKEN[0],
PLACEHOLDER_TOKEN[1],
PLACEHOLDER_TOKEN[2],
PLACEHOLDER_TOKEN[3],
MODALITY_TEXT_TOKEN,
MODALITY_VOICE_TOKEN,
MODALITY_INTERLEAVE_TOKEN,
*SEMANTIC_TOKENS,
]
class FishTokenizer:
def __init__(self, model_path: str) -> None:
mergeable_ranks = self.load_tiktoken_bpe(model_path)
special_token_begin = len(mergeable_ranks)
self.all_special_tokens_with_ids = {
token: special_token_begin + i for i, token in enumerate(ALL_SPECIAL_TOKENS)
}
self.semantic_id_to_token_id = {
i: self.all_special_tokens_with_ids[token]
for i, token in enumerate(SEMANTIC_TOKENS)
}
self.semantic_begin_id = self.all_special_tokens_with_ids[SEMANTIC_TOKENS[0]]
self.semantic_end_id = self.all_special_tokens_with_ids[SEMANTIC_TOKENS[-1]]
self.tkt_model = tiktoken.core.Encoding(
name=Path(model_path).stem,
pat_str=FISH_TIKTOKEN_PATTERN,
mergeable_ranks=mergeable_ranks,
special_tokens=self.all_special_tokens_with_ids,
)
@staticmethod
def load_tiktoken_bpe(tiktoken_bpe_file: str) -> dict[bytes, int]:
data = {}
for line in open(tiktoken_bpe_file).read().splitlines():
if not line:
continue
token, rank = line.split()
data[base64.b64decode(token)] = int(rank)
return data
def get_token_id(self, token: str) -> int:
return self.all_special_tokens_with_ids[token]
def encode(self, s: str, allowed_special: bool | set[str] = True) -> list[int]:
assert isinstance(s, str)
subs = []
for i in range(0, len(s), TIKTOKEN_MAX_ENCODE_CHARS):
subs.append(s[i : i + TIKTOKEN_MAX_ENCODE_CHARS])
if allowed_special is True:
allowed_special = self.tkt_model.special_tokens_set
elif allowed_special is False:
allowed_special = set()
return sum(
self.tkt_model.encode_batch(
subs, allowed_special=allowed_special, disallowed_special=set()
),
start=[],
)
def decode(self, tokens: list[int]) -> str:
return self.tkt_model.decode(tokens)
def save_pretrained(self, path: str):
path = Path(path)
path.mkdir(parents=True, exist_ok=True)
with open(path / "tokenizer.tiktoken", "w") as f:
for token, rank in self.tkt_model._mergeable_ranks.items():
f.write(f"{base64.b64encode(token).decode()} {rank}\n")
with open(path / "special_tokens.json", "w") as f:
json.dump(
self.all_special_tokens_with_ids,
f,
indent=2,
ensure_ascii=False,
)
@staticmethod
def from_pretrained(path: str):
return FishTokenizer(Path(path) / "tokenizer.tiktoken")
if __name__ == "__main__":
tokenizer = FishTokenizer("data/mpacks/v1.4-pretrain/tokenizer.all.tiktoken")
tokenizer.save_pretrained("checkpoints/fish-speech-0.5B")
tokenizer = FishTokenizer.from_pretrained("checkpoints/fish-speech-0.5B")
print(
[
tokenizer.decode([i])
for i in tokenizer.encode(f"{BOS_TOKEN}你好,世界!{EOS_TOKEN}")
]
)

View file

139
fish_speech/utils/file.py Normal file
View file

@ -0,0 +1,139 @@
import os
from pathlib import Path
from typing import Union
from loguru import logger
from natsort import natsorted
AUDIO_EXTENSIONS = {
".mp3",
".wav",
".flac",
".ogg",
".m4a",
".wma",
".aac",
".aiff",
".aif",
".aifc",
}
VIDEO_EXTENSIONS = {
".mp4",
".avi",
}
def get_latest_checkpoint(path: Path | str) -> Path | None:
# Find the latest checkpoint
ckpt_dir = Path(path)
if ckpt_dir.exists() is False:
return None
ckpts = sorted(ckpt_dir.glob("*.ckpt"), key=os.path.getmtime)
if len(ckpts) == 0:
return None
return ckpts[-1]
def audio_to_bytes(file_path):
if not file_path or not Path(file_path).exists():
return None
with open(file_path, "rb") as wav_file:
wav = wav_file.read()
return wav
def read_ref_text(ref_text):
path = Path(ref_text)
if path.exists() and path.is_file():
with path.open("r", encoding="utf-8") as file:
return file.read()
return ref_text
def list_files(
path: Union[Path, str],
extensions: set[str] = set(),
recursive: bool = False,
sort: bool = True,
) -> list[Path]:
"""List files in a directory.
Args:
path (Path): Path to the directory.
extensions (set, optional): Extensions to filter. Defaults to None.
recursive (bool, optional): Whether to search recursively. Defaults to False.
sort (bool, optional): Whether to sort the files. Defaults to True.
Returns:
list: List of files.
"""
if isinstance(path, str):
path = Path(path)
if not path.exists():
raise FileNotFoundError(f"Directory {path} does not exist.")
files = [file for ext in extensions for file in path.rglob(f"*{ext}")]
if sort:
files = natsorted(files)
return files
def load_filelist(path: Path | str) -> list[tuple[Path, str, str, str]]:
"""
Load a Bert-VITS2 style filelist.
"""
files = set()
results = []
count_duplicated, count_not_found = 0, 0
LANGUAGE_TO_LANGUAGES = {
"zh": ["zh", "en"],
"jp": ["jp", "en"],
"en": ["en"],
}
with open(path, "r", encoding="utf-8") as f:
for line in f.readlines():
splits = line.strip().split("|", maxsplit=3)
if len(splits) != 4:
logger.warning(f"Invalid line: {line}")
continue
filename, speaker, language, text = splits
file = Path(filename)
language = language.strip().lower()
if language == "ja":
language = "jp"
assert language in ["zh", "jp", "en"], f"Invalid language {language}"
languages = LANGUAGE_TO_LANGUAGES[language]
if file in files:
logger.warning(f"Duplicated file: {file}")
count_duplicated += 1
continue
if not file.exists():
logger.warning(f"File not found: {file}")
count_not_found += 1
continue
results.append((file, speaker, languages, text))
if count_duplicated > 0:
logger.warning(f"Total duplicated files: {count_duplicated}")
if count_not_found > 0:
logger.warning(f"Total files not found: {count_not_found}")
return results

185
fish_speech/utils/schema.py Normal file
View file

@ -0,0 +1,185 @@
import base64
import os
import queue
from dataclasses import dataclass
from typing import Literal
import torch
from pydantic import BaseModel, Field, conint, conlist, model_validator
from pydantic.functional_validators import SkipValidation
from typing_extensions import Annotated
from fish_speech.conversation import Message, TextPart, VQPart
class ServeVQPart(BaseModel):
type: Literal["vq"] = "vq"
codes: SkipValidation[list[list[int]]]
class ServeTextPart(BaseModel):
type: Literal["text"] = "text"
text: str
class ServeAudioPart(BaseModel):
type: Literal["audio"] = "audio"
audio: bytes
@dataclass
class ASRPackRequest:
audio: torch.Tensor
result_queue: queue.Queue
language: str
class ServeASRRequest(BaseModel):
# The audio should be an uncompressed PCM float16 audio
audios: list[bytes]
sample_rate: int = 44100
language: Literal["zh", "en", "ja", "auto"] = "auto"
class ServeASRTranscription(BaseModel):
text: str
duration: float
huge_gap: bool
class ServeASRSegment(BaseModel):
text: str
start: float
end: float
class ServeTimedASRResponse(BaseModel):
text: str
segments: list[ServeASRSegment]
duration: float
class ServeASRResponse(BaseModel):
transcriptions: list[ServeASRTranscription]
class ServeMessage(BaseModel):
role: Literal["system", "assistant", "user"]
parts: list[ServeVQPart | ServeTextPart]
def to_conversation_message(self):
new_message = Message(role=self.role, parts=[])
if self.role == "assistant":
new_message.modality = "voice"
for part in self.parts:
if isinstance(part, ServeTextPart):
new_message.parts.append(TextPart(text=part.text))
elif isinstance(part, ServeVQPart):
new_message.parts.append(
VQPart(codes=torch.tensor(part.codes, dtype=torch.int))
)
else:
raise ValueError(f"Unsupported part type: {part}")
return new_message
class ServeChatRequest(BaseModel):
messages: Annotated[list[ServeMessage], conlist(ServeMessage, min_length=1)]
max_new_tokens: int = 1024
top_p: float = 0.7
repetition_penalty: float = 1.2
temperature: float = 0.7
streaming: bool = False
num_samples: int = 1
early_stop_threshold: float = 1.0
class ServeVQGANEncodeRequest(BaseModel):
# The audio here should be in wav, mp3, etc
audios: list[bytes]
class ServeVQGANEncodeResponse(BaseModel):
tokens: SkipValidation[list[list[list[int]]]]
class ServeVQGANDecodeRequest(BaseModel):
tokens: SkipValidation[list[list[list[int]]]]
class ServeVQGANDecodeResponse(BaseModel):
# The audio here should be in PCM float16 format
audios: list[bytes]
class ServeForwardMessage(BaseModel):
role: str
content: str
class ServeResponse(BaseModel):
messages: list[ServeMessage]
finish_reason: Literal["stop", "error"] | None = None
stats: dict[str, int | float | str] = {}
class ServeStreamDelta(BaseModel):
role: Literal["system", "assistant", "user"] | None = None
part: ServeVQPart | ServeTextPart | None = None
class ServeStreamResponse(BaseModel):
sample_id: int = 0
delta: ServeStreamDelta | None = None
finish_reason: Literal["stop", "error"] | None = None
stats: dict[str, int | float | str] | None = None
class ServeReferenceAudio(BaseModel):
audio: bytes
text: str
@model_validator(mode="before")
def decode_audio(cls, values):
audio = values.get("audio")
if (
isinstance(audio, str) and len(audio) > 255
): # Check if audio is a string (Base64)
try:
values["audio"] = base64.b64decode(audio)
except Exception as e:
# If the audio is not a valid base64 string, we will just ignore it and let the server handle it
pass
return values
def __repr__(self) -> str:
return f"ServeReferenceAudio(text={self.text!r}, audio_size={len(self.audio)})"
class ServeTTSRequest(BaseModel):
text: str
chunk_length: Annotated[int, conint(ge=100, le=300, strict=True)] = 200
# Audio format
format: Literal["wav", "pcm", "mp3"] = "wav"
# References audios for in-context learning
references: list[ServeReferenceAudio] = []
# Reference id
# For example, if you want use https://fish.audio/m/7f92f8afb8ec43bf81429cc1c9199cb1/
# Just pass 7f92f8afb8ec43bf81429cc1c9199cb1
reference_id: str | None = None
seed: int | None = None
use_memory_cache: Literal["on", "off"] = "off"
# Normalize text for en & zh, this increase stability for numbers
normalize: bool = True
# not usually used below
streaming: bool = False
max_new_tokens: int = 1024
top_p: Annotated[float, Field(ge=0.1, le=1.0, strict=True)] = 0.7
repetition_penalty: Annotated[float, Field(ge=0.9, le=2.0, strict=True)] = 1.2
temperature: Annotated[float, Field(ge=0.1, le=1.0, strict=True)] = 0.7
class Config:
# Allow arbitrary types for pytorch related types
arbitrary_types_allowed = True

BIN
models/SenseVoiceSmall/.mdl Normal file

Binary file not shown.

BIN
models/SenseVoiceSmall/.msc Normal file

Binary file not shown.

View file

@ -0,0 +1 @@
Revision:master,CreatedAt:1727321787

View file

@ -0,0 +1,219 @@
---
frameworks:
- Pytorch
license: Apache License 2.0
tasks:
- auto-speech-recognition
#model-type:
##如 gpt、phi、llama、chatglm、baichuan 等
#- gpt
#domain:
##如 nlp、cv、audio、multi-modal
#- nlp
#language:
##语言代码列表 https://help.aliyun.com/document_detail/215387.html?spm=a2c4g.11186623.0.0.9f8d7467kni6Aa
#- cn
#metrics:
##如 CIDEr、Blue、ROUGE 等
#- CIDEr
#tags:
##各种自定义,包括 pretrained、fine-tuned、instruction-tuned、RL-tuned 等训练方法和其他
#- pretrained
#tools:
##如 vllm、fastchat、llamacpp、AdaSeq 等
#- vllm
---
# Highlights
**SenseVoice**专注于高精度多语言语音识别、情感辨识和音频事件检测
- **多语言识别:** 采用超过40万小时数据训练,支持超过50种语言,识别效果上优于Whisper模型。
- **富文本识别:**
- 具备优秀的情感识别,能够在测试数据上达到和超过目前最佳情感识别模型的效果。
- 支持声音事件检测能力,支持音乐、掌声、笑声、哭声、咳嗽、喷嚏等多种常见人机交互事件进行检测。
- **高效推理:** SenseVoice-Small模型采用非自回归端到端框架,推理延迟极低,10s音频推理仅耗时70ms,15倍优于Whisper-Large。
- **微调定制:** 具备便捷的微调脚本与策略,方便用户根据业务场景修复长尾样本问题。
- **服务部署:** 具有完整的服务部署链路,支持多并发请求,支持客户端语言有,python、c++、html、java与c#等。
## <strong>[SenseVoice开源项目介绍](https://github.com/FunAudioLLM/SenseVoice)</strong>
<strong>[SenseVoice](https://github.com/FunAudioLLM/SenseVoice)</strong>开源模型是多语言音频理解模型,具有包括语音识别、语种识别、语音情感识别,声学事件检测能力。
[**github仓库**](https://github.com/FunAudioLLM/SenseVoice)
| [**最新动态**](https://github.com/FunAudioLLM/SenseVoice/blob/main/README_zh.md#%E6%9C%80%E6%96%B0%E5%8A%A8%E6%80%81)
| [**环境安装**](https://github.com/FunAudioLLM/SenseVoice/blob/main/README_zh.md#%E7%8E%AF%E5%A2%83%E5%AE%89%E8%A3%85)
# 模型结构图
SenseVoice多语言音频理解模型,支持语音识别、语种识别、语音情感识别、声学事件检测、逆文本正则化等能力,采用工业级数十万小时的标注音频进行模型训练,保证了模型的通用识别效果。模型可以被应用于中文、粤语、英语、日语、韩语音频识别,并输出带有情感和事件的富文本转写结果。
<p align="center">
<img src="fig/sensevoice.png" alt="SenseVoice模型结构" width="1500" />
</p>
SenseVoice-Small是基于非自回归端到端框架模型,为了指定任务,我们在语音特征前添加四个嵌入作为输入传递给编码器:
- LID:用于预测音频语种标签。
- SER:用于预测音频情感标签。
- AED:用于预测音频包含的事件标签。
- ITN:用于指定识别输出文本是否进行逆文本正则化。
# 依赖环境
推理之前,请务必更新funasr与modelscope版本
```shell
pip install -U funasr modelscope
```
# 用法
## 推理
### modelscope pipeline推理
```python
from modelscope.pipelines import pipeline
from modelscope.utils.constant import Tasks
inference_pipeline = pipeline(
task=Tasks.auto_speech_recognition,
model='iic/SenseVoiceSmall',
model_revision="master",
device="cuda:0",)
rec_result = inference_pipeline('https://isv-data.oss-cn-hangzhou.aliyuncs.com/ics/MaaS/ASR/test_audio/asr_example_zh.wav')
print(rec_result)
```
### 使用funasr推理
支持任意格式音频输入,支持任意时长输入
```python
from funasr import AutoModel
from funasr.utils.postprocess_utils import rich_transcription_postprocess
model_dir = "iic/SenseVoiceSmall"
model = AutoModel(
model=model_dir,
trust_remote_code=True,
remote_code="./model.py",
vad_model="fsmn-vad",
vad_kwargs={"max_single_segment_time": 30000},
device="cuda:0",
)
# en
res = model.generate(
input=f"{model.model_path}/example/en.mp3",
cache={},
language="auto", # "zn", "en", "yue", "ja", "ko", "nospeech"
use_itn=True,
batch_size_s=60,
merge_vad=True, #
merge_length_s=15,
)
text = rich_transcription_postprocess(res[0]["text"])
print(text)
```
参数说明:
- `model_dir`:模型名称,或本地磁盘中的模型路径。
- `trust_remote_code`:
- `True`表示model代码实现从`remote_code`处加载,`remote_code`指定`model`具体代码的位置(例如,当前目录下的`model.py`),支持绝对路径与相对路径,以及网络url。
- `False`表示,model代码实现为 [FunASR](https://github.com/modelscope/FunASR) 内部集成版本,此时修改当前目录下的`model.py`不会生效,因为加载的是funasr内部版本,模型代码[点击查看](https://github.com/modelscope/FunASR/tree/main/funasr/models/sense_voice)。
- `vad_model`:表示开启VAD,VAD的作用是将长音频切割成短音频,此时推理耗时包括了VAD与SenseVoice总耗时,为链路耗时,如果需要单独测试SenseVoice模型耗时,可以关闭VAD模型。
- `vad_kwargs`:表示VAD模型配置,`max_single_segment_time`: 表示`vad_model`最大切割音频时长, 单位是毫秒ms。
- `use_itn`:输出结果中是否包含标点与逆文本正则化。
- `batch_size_s` 表示采用动态batch,batch中总音频时长,单位为秒s。
- `merge_vad`:是否将 vad 模型切割的短音频碎片合成,合并后长度为`merge_length_s`,单位为秒s。
- `ban_emo_unk`:禁用emo_unk标签,禁用后所有的句子都会被赋与情感标签。默认`False`
```python
model = AutoModel(model=model_dir, trust_remote_code=True, device="cuda:0")
res = model.generate(
input=f"{model.model_path}/example/en.mp3",
cache={},
language="auto", # "zn", "en", "yue", "ja", "ko", "nospeech"
use_itn=True,
batch_size=64,
)
```
更多详细用法,请参考 [文档](https://github.com/modelscope/FunASR/blob/main/docs/tutorial/README.md)
## 模型下载
上面代码会自动下载模型,如果您需要离线下载好模型,可以通过下面代码,手动下载,之后指定模型本地路径即可。
SDK下载
```bash
#安装ModelScope
pip install modelscope
```
```python
#SDK模型下载
from modelscope import snapshot_download
model_dir = snapshot_download('iic/SenseVoiceSmall')
```
Git下载
```
#Git模型下载
git clone https://www.modelscope.cn/iic/SenseVoiceSmall.git
```
## 服务部署
Undo
# Performance
## 语音识别效果
我们在开源基准数据集(包括 AISHELL-1、AISHELL-2、Wenetspeech、Librispeech和Common Voice)上比较了SenseVoice与Whisper的多语言语音识别性能和推理效率。在中文和粤语识别效果上,SenseVoice-Small模型具有明显的效果优势。
<p align="center">
<img src="fig/asr_results.png" alt="SenseVoice模型在开源测试集上的表现" width="2500" />
</p>
## 情感识别效果
由于目前缺乏被广泛使用的情感识别测试指标和方法,我们在多个测试集的多种指标进行测试,并与近年来Benchmark上的多个结果进行了全面的对比。所选取的测试集同时包含中文/英文两种语言以及表演、影视剧、自然对话等多种风格的数据,在不进行目标数据微调的前提下,SenseVoice能够在测试数据上达到和超过目前最佳情感识别模型的效果。
<p align="center">
<img src="fig/ser_table.png" alt="SenseVoice模型SER效果1" width="1500" />
</p>
同时,我们还在测试集上对多个开源情感识别模型进行对比,结果表明,SenseVoice-Large模型可以在几乎所有数据上都达到了最佳效果,而SenseVoice-Small模型同样可以在多数数据集上取得超越其他开源模型的效果。
<p align="center">
<img src="fig/ser_figure.png" alt="SenseVoice模型SER效果2" width="500" />
</p>
## 事件检测效果
尽管SenseVoice只在语音数据上进行训练,它仍然可以作为事件检测模型进行单独使用。我们在环境音分类ESC-50数据集上与目前业内广泛使用的BEATS与PANN模型的效果进行了对比。SenseVoice模型能够在这些任务上取得较好的效果,但受限于训练数据与训练方式,其事件分类效果专业的事件检测模型相比仍然有一定的差距。
<p align="center">
<img src="fig/aed_figure.png" alt="SenseVoice模型AED效果" width="500" />
</p>
## 推理效率
SenseVoice-Small模型采用非自回归端到端架构,推理延迟极低。在参数量与Whisper-Small模型相当的情况下,比Whisper-Small模型推理速度快7倍,比Whisper-Large模型快17倍。同时SenseVoice-small模型在音频时长增加的情况下,推理耗时也无明显增加。
<p align="center">
<img src="fig/inference.png" alt="SenseVoice模型的推理效率" width="1500" />
</p>
<p style="color: lightgrey;">如果您是本模型的贡献者,我们邀请您根据<a href="https://modelscope.cn/docs/ModelScope%E6%A8%A1%E5%9E%8B%E6%8E%A5%E5%85%A5%E6%B5%81%E7%A8%8B%E6%A6%82%E8%A7%88" style="color: lightgrey; text-decoration: underline;">模型贡献文档</a>,及时完善模型卡片内容。</p>

File diff suppressed because one or more lines are too long

View file

@ -1,27 +0,0 @@
from funasr import AutoModel
from funasr.utils.postprocess_utils import rich_transcription_postprocess
model_dir = "./"
model = AutoModel(
model=model_dir,
vad_model="fsmn-vad",
vad_kwargs={"max_single_segment_time": 30000},
# device="cuda:0",
hub="hf",
)
# en
res = model.generate(
input=f"{model.model_path}/example/en.mp3",
cache={},
language="auto", # "zn", "en", "yue", "ja", "ko", "nospeech"
use_itn=True,
batch_size_s=60,
merge_vad=True, #
merge_length_s=15,
)
text = rich_transcription_postprocess(res[0]["text"])
print(text)

Binary file not shown.

After

Width:  |  Height:  |  Size: 116 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 238 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 935 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 880 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 194 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 318 KiB

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,3 @@
# 模型下载
from modelscope import snapshot_download
snapshot_download('iic/SenseVoiceSmall', cache_dir='models')

View file

@ -9,4 +9,9 @@ funasr==1.2.3
torchaudio==2.2.2 torchaudio==2.2.2
openai==1.61.0 openai==1.61.0
edge_tts==7.0.0 edge_tts==7.0.0
httpx==0.27.2 httpx==0.27.2
tiktoken==0.9.0
loguru==0.7.3
natsort==8.4.0
ormsgpack==1.7.0
pyaudio==0.2.14