xinference 1.1.0__py3-none-any.whl → 1.1.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of xinference might be problematic. Click here for more details.
- xinference/_compat.py +2 -0
- xinference/_version.py +3 -3
- xinference/api/restful_api.py +23 -1
- xinference/core/model.py +1 -6
- xinference/core/utils.py +10 -6
- xinference/model/audio/core.py +5 -0
- xinference/model/audio/cosyvoice.py +25 -3
- xinference/model/audio/f5tts.py +15 -10
- xinference/model/audio/f5tts_mlx.py +260 -0
- xinference/model/audio/fish_speech.py +35 -111
- xinference/model/audio/model_spec.json +19 -3
- xinference/model/audio/model_spec_modelscope.json +9 -0
- xinference/model/audio/utils.py +32 -0
- xinference/model/image/core.py +69 -1
- xinference/model/image/model_spec.json +127 -4
- xinference/model/image/model_spec_modelscope.json +130 -4
- xinference/model/image/stable_diffusion/core.py +45 -13
- xinference/model/llm/llm_family.json +47 -0
- xinference/model/llm/llm_family.py +15 -36
- xinference/model/llm/llm_family_modelscope.json +49 -0
- xinference/model/llm/mlx/core.py +68 -13
- xinference/model/llm/transformers/core.py +1 -0
- xinference/model/llm/transformers/qwen2_vl.py +2 -0
- xinference/model/llm/utils.py +1 -0
- xinference/model/llm/vllm/core.py +11 -2
- xinference/thirdparty/cosyvoice/bin/average_model.py +92 -0
- xinference/thirdparty/cosyvoice/bin/export_jit.py +12 -2
- xinference/thirdparty/cosyvoice/bin/export_onnx.py +112 -0
- xinference/thirdparty/cosyvoice/bin/export_trt.sh +9 -0
- xinference/thirdparty/cosyvoice/bin/inference.py +5 -7
- xinference/thirdparty/cosyvoice/bin/train.py +42 -8
- xinference/thirdparty/cosyvoice/cli/cosyvoice.py +96 -25
- xinference/thirdparty/cosyvoice/cli/frontend.py +77 -30
- xinference/thirdparty/cosyvoice/cli/model.py +330 -80
- xinference/thirdparty/cosyvoice/dataset/dataset.py +6 -2
- xinference/thirdparty/cosyvoice/dataset/processor.py +76 -14
- xinference/thirdparty/cosyvoice/flow/decoder.py +92 -13
- xinference/thirdparty/cosyvoice/flow/flow.py +99 -9
- xinference/thirdparty/cosyvoice/flow/flow_matching.py +110 -13
- xinference/thirdparty/cosyvoice/flow/length_regulator.py +5 -4
- xinference/thirdparty/cosyvoice/hifigan/discriminator.py +140 -0
- xinference/thirdparty/cosyvoice/hifigan/generator.py +58 -42
- xinference/thirdparty/cosyvoice/hifigan/hifigan.py +67 -0
- xinference/thirdparty/cosyvoice/llm/llm.py +139 -6
- xinference/thirdparty/cosyvoice/tokenizer/assets/multilingual_zh_ja_yue_char_del.tiktoken +58836 -0
- xinference/thirdparty/cosyvoice/tokenizer/tokenizer.py +279 -0
- xinference/thirdparty/cosyvoice/transformer/embedding.py +2 -2
- xinference/thirdparty/cosyvoice/transformer/encoder_layer.py +7 -7
- xinference/thirdparty/cosyvoice/transformer/upsample_encoder.py +318 -0
- xinference/thirdparty/cosyvoice/utils/common.py +28 -1
- xinference/thirdparty/cosyvoice/utils/executor.py +69 -7
- xinference/thirdparty/cosyvoice/utils/file_utils.py +2 -12
- xinference/thirdparty/cosyvoice/utils/frontend_utils.py +9 -5
- xinference/thirdparty/cosyvoice/utils/losses.py +20 -0
- xinference/thirdparty/cosyvoice/utils/scheduler.py +1 -2
- xinference/thirdparty/cosyvoice/utils/train_utils.py +101 -45
- xinference/thirdparty/fish_speech/fish_speech/conversation.py +94 -83
- xinference/thirdparty/fish_speech/fish_speech/models/text2semantic/llama.py +63 -20
- xinference/thirdparty/fish_speech/fish_speech/text/clean.py +1 -26
- xinference/thirdparty/fish_speech/fish_speech/text/spliter.py +1 -1
- xinference/thirdparty/fish_speech/fish_speech/tokenizer.py +152 -0
- xinference/thirdparty/fish_speech/fish_speech/train.py +2 -2
- xinference/thirdparty/fish_speech/fish_speech/webui/manage.py +1 -1
- xinference/thirdparty/fish_speech/tools/{post_api.py → api_client.py} +7 -13
- xinference/thirdparty/fish_speech/tools/api_server.py +98 -0
- xinference/thirdparty/fish_speech/tools/download_models.py +5 -5
- xinference/thirdparty/fish_speech/tools/fish_e2e.py +2 -2
- xinference/thirdparty/fish_speech/tools/inference_engine/__init__.py +192 -0
- xinference/thirdparty/fish_speech/tools/inference_engine/reference_loader.py +125 -0
- xinference/thirdparty/fish_speech/tools/inference_engine/utils.py +39 -0
- xinference/thirdparty/fish_speech/tools/inference_engine/vq_manager.py +57 -0
- xinference/thirdparty/fish_speech/tools/llama/eval_in_context.py +2 -2
- xinference/thirdparty/fish_speech/tools/llama/generate.py +117 -89
- xinference/thirdparty/fish_speech/tools/run_webui.py +104 -0
- xinference/thirdparty/fish_speech/tools/schema.py +11 -28
- xinference/thirdparty/fish_speech/tools/server/agent/__init__.py +57 -0
- xinference/thirdparty/fish_speech/tools/server/agent/generate.py +119 -0
- xinference/thirdparty/fish_speech/tools/server/agent/generation_utils.py +122 -0
- xinference/thirdparty/fish_speech/tools/server/agent/pre_generation_utils.py +72 -0
- xinference/thirdparty/fish_speech/tools/server/api_utils.py +75 -0
- xinference/thirdparty/fish_speech/tools/server/exception_handler.py +27 -0
- xinference/thirdparty/fish_speech/tools/server/inference.py +45 -0
- xinference/thirdparty/fish_speech/tools/server/model_manager.py +122 -0
- xinference/thirdparty/fish_speech/tools/server/model_utils.py +129 -0
- xinference/thirdparty/fish_speech/tools/server/views.py +246 -0
- xinference/thirdparty/fish_speech/tools/webui/__init__.py +173 -0
- xinference/thirdparty/fish_speech/tools/webui/inference.py +91 -0
- xinference/thirdparty/fish_speech/tools/webui/variables.py +14 -0
- xinference/thirdparty/matcha/utils/utils.py +2 -2
- {xinference-1.1.0.dist-info → xinference-1.1.1.dist-info}/METADATA +11 -6
- {xinference-1.1.0.dist-info → xinference-1.1.1.dist-info}/RECORD +95 -74
- xinference/thirdparty/cosyvoice/bin/__init__.py +0 -0
- xinference/thirdparty/cosyvoice/bin/export_trt.py +0 -8
- xinference/thirdparty/cosyvoice/flow/__init__.py +0 -0
- xinference/thirdparty/cosyvoice/hifigan/__init__.py +0 -0
- xinference/thirdparty/cosyvoice/llm/__init__.py +0 -0
- xinference/thirdparty/fish_speech/tools/__init__.py +0 -0
- xinference/thirdparty/fish_speech/tools/api.py +0 -943
- xinference/thirdparty/fish_speech/tools/msgpack_api.py +0 -95
- xinference/thirdparty/fish_speech/tools/webui.py +0 -548
- {xinference-1.1.0.dist-info → xinference-1.1.1.dist-info}/LICENSE +0 -0
- {xinference-1.1.0.dist-info → xinference-1.1.1.dist-info}/WHEEL +0 -0
- {xinference-1.1.0.dist-info → xinference-1.1.1.dist-info}/entry_points.txt +0 -0
- {xinference-1.1.0.dist-info → xinference-1.1.1.dist-info}/top_level.txt +0 -0
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
import time
|
|
2
|
+
|
|
3
|
+
from tools.schema import ServeMessage, ServeResponse, ServeStreamResponse
|
|
4
|
+
from tools.server.agent.generation_utils import (
|
|
5
|
+
initialize_decode_buffers,
|
|
6
|
+
process_response_tokens,
|
|
7
|
+
send_reset_buffer,
|
|
8
|
+
)
|
|
9
|
+
from tools.server.agent.pre_generation_utils import (
|
|
10
|
+
create_generation_request,
|
|
11
|
+
send_generation_request,
|
|
12
|
+
)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def generate_responses(
|
|
16
|
+
input_queue, tokenizer, config, request, prompt, im_end_id, device
|
|
17
|
+
):
|
|
18
|
+
"""
|
|
19
|
+
Main generation function that handles the conversation, encodes the request,
|
|
20
|
+
sends the generation request, and handles decoding/streaming.
|
|
21
|
+
It returns a response generator (ServeResponse or ServeStreamResponse).
|
|
22
|
+
"""
|
|
23
|
+
stats = {}
|
|
24
|
+
start = time.time()
|
|
25
|
+
stats["start_time"] = start
|
|
26
|
+
stats["tokens_count"] = 0
|
|
27
|
+
|
|
28
|
+
# Prepare and send the generation request
|
|
29
|
+
req = create_generation_request(prompt, request, im_end_id, device)
|
|
30
|
+
response_queue = send_generation_request(input_queue, req)
|
|
31
|
+
decode_buffer, parts, finished = initialize_decode_buffers(request.num_samples)
|
|
32
|
+
|
|
33
|
+
while True:
|
|
34
|
+
response = response_queue.get()
|
|
35
|
+
|
|
36
|
+
# Handle abnormal finish or error
|
|
37
|
+
if response in ["stop", "error"]:
|
|
38
|
+
finish_reason = response
|
|
39
|
+
break
|
|
40
|
+
|
|
41
|
+
# Process the response tokens
|
|
42
|
+
is_first_token = stats["tokens_count"] == 0
|
|
43
|
+
responses = process_response_tokens(
|
|
44
|
+
response,
|
|
45
|
+
tokenizer,
|
|
46
|
+
config,
|
|
47
|
+
request,
|
|
48
|
+
decode_buffer,
|
|
49
|
+
parts,
|
|
50
|
+
finished,
|
|
51
|
+
im_end_id,
|
|
52
|
+
stats,
|
|
53
|
+
start,
|
|
54
|
+
is_first_token,
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
# Yield the responses if streaming
|
|
58
|
+
if request.streaming and responses:
|
|
59
|
+
for r in responses:
|
|
60
|
+
yield r
|
|
61
|
+
|
|
62
|
+
stats["tokens_count"] += 1
|
|
63
|
+
|
|
64
|
+
# Check if all samples are finished
|
|
65
|
+
if all(finished):
|
|
66
|
+
finish_reason = "stop"
|
|
67
|
+
break
|
|
68
|
+
|
|
69
|
+
# Finalize the response
|
|
70
|
+
final_responses = finalize_response(
|
|
71
|
+
request, finished, decode_buffer, tokenizer, parts, stats, finish_reason
|
|
72
|
+
)
|
|
73
|
+
for fr in final_responses:
|
|
74
|
+
yield fr
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def finalize_response(
|
|
78
|
+
request, finished, decode_buffer, tokenizer, parts, stats, finish_reason
|
|
79
|
+
):
|
|
80
|
+
"""
|
|
81
|
+
Finalize the response by sending the remaining text buffers.
|
|
82
|
+
"""
|
|
83
|
+
responses = []
|
|
84
|
+
|
|
85
|
+
# Send the remaining text buffers
|
|
86
|
+
for sample_id in range(request.num_samples):
|
|
87
|
+
responses.extend(
|
|
88
|
+
send_reset_buffer(sample_id, decode_buffer, tokenizer, parts, request)
|
|
89
|
+
)
|
|
90
|
+
|
|
91
|
+
# Calculate the final stats
|
|
92
|
+
stats["total_time"] = (time.time() - stats["start_time"]) * 1000
|
|
93
|
+
stats["total_tokens"] = stats["tokens_count"]
|
|
94
|
+
|
|
95
|
+
# If streaming, send the final chunks for each sample
|
|
96
|
+
if request.streaming:
|
|
97
|
+
for sample_id in range(request.num_samples):
|
|
98
|
+
if finished[sample_id]:
|
|
99
|
+
continue
|
|
100
|
+
responses.append(
|
|
101
|
+
ServeStreamResponse(
|
|
102
|
+
finish_reason=finish_reason, stats=stats, sample_id=sample_id
|
|
103
|
+
)
|
|
104
|
+
)
|
|
105
|
+
else:
|
|
106
|
+
# If not streaming, send the full messages for each sample
|
|
107
|
+
full_messages = [
|
|
108
|
+
ServeMessage(role="assistant", parts=parts[i])
|
|
109
|
+
for i in range(request.num_samples)
|
|
110
|
+
]
|
|
111
|
+
responses.append(
|
|
112
|
+
ServeResponse(
|
|
113
|
+
messages=full_messages,
|
|
114
|
+
finish_reason=finish_reason,
|
|
115
|
+
stats=stats,
|
|
116
|
+
)
|
|
117
|
+
)
|
|
118
|
+
|
|
119
|
+
return responses
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import time
|
|
2
|
+
|
|
3
|
+
from tools.schema import (
|
|
4
|
+
ServeStreamDelta,
|
|
5
|
+
ServeStreamResponse,
|
|
6
|
+
ServeTextPart,
|
|
7
|
+
ServeVQPart,
|
|
8
|
+
)
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def initialize_decode_buffers(num_samples):
|
|
12
|
+
"""Initialise the decode buffers for each sample."""
|
|
13
|
+
decode_buffer = [[] for _ in range(num_samples)]
|
|
14
|
+
parts = [[] for _ in range(num_samples)]
|
|
15
|
+
finished = [False for _ in range(num_samples)]
|
|
16
|
+
return decode_buffer, parts, finished
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def send_reset_buffer(sample_id, decode_buffer, tokenizer, parts, request):
|
|
20
|
+
"""Send the remaining text buffer for a sample."""
|
|
21
|
+
if len(decode_buffer[sample_id]) == 0:
|
|
22
|
+
return []
|
|
23
|
+
|
|
24
|
+
decoded = tokenizer.decode(decode_buffer[sample_id])
|
|
25
|
+
part = ServeTextPart(text=decoded)
|
|
26
|
+
|
|
27
|
+
responses = []
|
|
28
|
+
if request.streaming:
|
|
29
|
+
responses.append(ServeStreamResponse(delta=ServeStreamDelta(part=part)))
|
|
30
|
+
else:
|
|
31
|
+
parts[sample_id].append(part)
|
|
32
|
+
|
|
33
|
+
decode_buffer[sample_id] = []
|
|
34
|
+
return responses
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def handle_semantic_tokens(tokens, config, sample_id, parts, request):
|
|
38
|
+
"""Handle the semantic tokens returned by the model."""
|
|
39
|
+
responses = []
|
|
40
|
+
_tokens = tokens[1:].clone()
|
|
41
|
+
|
|
42
|
+
if not config.share_codebook_embeddings:
|
|
43
|
+
for i in range(len(_tokens)):
|
|
44
|
+
_tokens[i] -= config.codebook_size * i
|
|
45
|
+
|
|
46
|
+
# If streaming, send the VQ parts directly
|
|
47
|
+
if request.streaming:
|
|
48
|
+
responses.append(
|
|
49
|
+
ServeStreamResponse(
|
|
50
|
+
sample_id=sample_id,
|
|
51
|
+
delta=ServeStreamDelta(part=ServeVQPart(codes=_tokens.tolist())),
|
|
52
|
+
)
|
|
53
|
+
)
|
|
54
|
+
else:
|
|
55
|
+
# If not streaming, accumulate the VQ parts
|
|
56
|
+
if not parts[sample_id] or not isinstance(parts[sample_id][-1], ServeVQPart):
|
|
57
|
+
parts[sample_id].append(ServeVQPart(codes=_tokens.tolist()))
|
|
58
|
+
else:
|
|
59
|
+
# Accumulate the codes
|
|
60
|
+
for codebook_id, value in enumerate(_tokens):
|
|
61
|
+
parts[sample_id][-1].codes[codebook_id].append(value.item())
|
|
62
|
+
|
|
63
|
+
return responses
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def process_response_tokens(
|
|
67
|
+
response,
|
|
68
|
+
tokenizer,
|
|
69
|
+
config,
|
|
70
|
+
request,
|
|
71
|
+
decode_buffer,
|
|
72
|
+
parts,
|
|
73
|
+
finished,
|
|
74
|
+
im_end_id,
|
|
75
|
+
stats,
|
|
76
|
+
start,
|
|
77
|
+
is_first_token,
|
|
78
|
+
):
|
|
79
|
+
"""Process the response tokens returned by the model."""
|
|
80
|
+
responses = []
|
|
81
|
+
for sample_id, tokens in enumerate(response):
|
|
82
|
+
if finished[sample_id]:
|
|
83
|
+
continue
|
|
84
|
+
|
|
85
|
+
# End of the conversation
|
|
86
|
+
if tokens[0] == im_end_id:
|
|
87
|
+
finished[sample_id] = True
|
|
88
|
+
# Send the remaining text buffer
|
|
89
|
+
responses.extend(
|
|
90
|
+
send_reset_buffer(sample_id, decode_buffer, tokenizer, parts, request)
|
|
91
|
+
)
|
|
92
|
+
if request.streaming:
|
|
93
|
+
responses.append(
|
|
94
|
+
ServeStreamResponse(
|
|
95
|
+
sample_id=sample_id,
|
|
96
|
+
finish_reason="stop",
|
|
97
|
+
stats=stats,
|
|
98
|
+
)
|
|
99
|
+
)
|
|
100
|
+
continue
|
|
101
|
+
|
|
102
|
+
# Check if the token is semantic
|
|
103
|
+
is_semantic = (
|
|
104
|
+
tokenizer.semantic_begin_id <= tokens[0] <= tokenizer.semantic_end_id
|
|
105
|
+
)
|
|
106
|
+
|
|
107
|
+
if is_semantic:
|
|
108
|
+
# Before the semantic tokens, send the remaining text buffer
|
|
109
|
+
responses.extend(
|
|
110
|
+
send_reset_buffer(sample_id, decode_buffer, tokenizer, parts, request)
|
|
111
|
+
)
|
|
112
|
+
responses.extend(
|
|
113
|
+
handle_semantic_tokens(tokens, config, sample_id, parts, request)
|
|
114
|
+
)
|
|
115
|
+
else:
|
|
116
|
+
# Accumulate the text tokens (not implemented?)
|
|
117
|
+
decode_buffer[sample_id].append(tokens[0, 0])
|
|
118
|
+
|
|
119
|
+
if is_first_token:
|
|
120
|
+
stats["time_to_first_token"] = (time.time() - start) * 1000
|
|
121
|
+
|
|
122
|
+
return responses
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import queue
|
|
2
|
+
|
|
3
|
+
from fish_speech.conversation import Conversation, Message
|
|
4
|
+
from fish_speech.tokenizer import IM_END_TOKEN
|
|
5
|
+
from tools.llama.generate import GenerateRequest
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def prepare_messages(request, tokenizer, config):
|
|
9
|
+
"""
|
|
10
|
+
Reorganise the provided list of messages into a conversation.
|
|
11
|
+
Encode the conversation for inference.
|
|
12
|
+
"""
|
|
13
|
+
# Convert the messages to ConversationMessage objects
|
|
14
|
+
messages = [msg.to_conversation_message() for msg in request.messages]
|
|
15
|
+
|
|
16
|
+
if len(messages) < 1:
|
|
17
|
+
raise ValueError("At least one message is required")
|
|
18
|
+
|
|
19
|
+
# Check the last message to determine the next step
|
|
20
|
+
last_role = messages[-1].role
|
|
21
|
+
match last_role:
|
|
22
|
+
case "user":
|
|
23
|
+
# The last message is from the user, ask the assistant to respond with a new message
|
|
24
|
+
messages.append(
|
|
25
|
+
Message(role="assistant", parts=[], add_im_end=False, modality="voice")
|
|
26
|
+
)
|
|
27
|
+
case "raw":
|
|
28
|
+
# The last message is raw text, ask the assistant to complete it
|
|
29
|
+
messages[-1].add_im_start = False
|
|
30
|
+
messages[-1].add_im_end = False
|
|
31
|
+
messages[-1].modality = "voice"
|
|
32
|
+
case "assistant":
|
|
33
|
+
# The last message is from the assistant, ask the assistant to continue
|
|
34
|
+
messages[-1].add_im_end = False
|
|
35
|
+
case _:
|
|
36
|
+
# We expect it to be assistant if not user or raw
|
|
37
|
+
raise ValueError("The last message must be from the assistant, user or raw")
|
|
38
|
+
|
|
39
|
+
# Create a conversation object and encode it for inference
|
|
40
|
+
conv = Conversation(messages=messages)
|
|
41
|
+
prompt = conv.encode_for_inference(
|
|
42
|
+
tokenizer=tokenizer, num_codebooks=config.num_codebooks
|
|
43
|
+
)
|
|
44
|
+
im_end_id = tokenizer.get_token_id(IM_END_TOKEN)
|
|
45
|
+
|
|
46
|
+
return prompt, im_end_id
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def create_generation_request(prompt, request, im_end_id, device):
|
|
50
|
+
"""
|
|
51
|
+
Convert the request into a dictionary that can be sent to the model for generation.
|
|
52
|
+
"""
|
|
53
|
+
req = {
|
|
54
|
+
"prompt": prompt.to(device),
|
|
55
|
+
"max_new_tokens": request.max_new_tokens,
|
|
56
|
+
"im_end_id": im_end_id,
|
|
57
|
+
"temperature": request.temperature,
|
|
58
|
+
"top_p": request.top_p,
|
|
59
|
+
"repetition_penalty": request.repetition_penalty,
|
|
60
|
+
"num_samples": request.num_samples,
|
|
61
|
+
"early_stop_threshold": request.early_stop_threshold,
|
|
62
|
+
}
|
|
63
|
+
return req
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def send_generation_request(input_queue, req):
|
|
67
|
+
"""
|
|
68
|
+
Send the generation request to the model and return a queue to get the response.
|
|
69
|
+
"""
|
|
70
|
+
response_queue = queue.Queue()
|
|
71
|
+
input_queue.put(GenerateRequest(req, response_queue))
|
|
72
|
+
return response_queue
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
from argparse import ArgumentParser
|
|
2
|
+
from http import HTTPStatus
|
|
3
|
+
from typing import Annotated, Any
|
|
4
|
+
|
|
5
|
+
import ormsgpack
|
|
6
|
+
from baize.datastructures import ContentType
|
|
7
|
+
from kui.asgi import HTTPException, HttpRequest
|
|
8
|
+
|
|
9
|
+
from tools.inference_engine import TTSInferenceEngine
|
|
10
|
+
from tools.schema import ServeTTSRequest
|
|
11
|
+
from tools.server.inference import inference_wrapper as inference
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def parse_args():
|
|
15
|
+
parser = ArgumentParser()
|
|
16
|
+
parser.add_argument("--mode", type=str, choices=["agent", "tts"], default="tts")
|
|
17
|
+
parser.add_argument("--load-asr-model", action="store_true")
|
|
18
|
+
parser.add_argument(
|
|
19
|
+
"--llama-checkpoint-path",
|
|
20
|
+
type=str,
|
|
21
|
+
default="checkpoints/fish-speech-1.5",
|
|
22
|
+
)
|
|
23
|
+
parser.add_argument(
|
|
24
|
+
"--decoder-checkpoint-path",
|
|
25
|
+
type=str,
|
|
26
|
+
default="checkpoints/fish-speech-1.5/firefly-gan-vq-fsq-8x1024-21hz-generator.pth",
|
|
27
|
+
)
|
|
28
|
+
parser.add_argument("--decoder-config-name", type=str, default="firefly_gan_vq")
|
|
29
|
+
parser.add_argument("--device", type=str, default="cuda")
|
|
30
|
+
parser.add_argument("--half", action="store_true")
|
|
31
|
+
parser.add_argument("--compile", action="store_true")
|
|
32
|
+
parser.add_argument("--max-text-length", type=int, default=0)
|
|
33
|
+
parser.add_argument("--listen", type=str, default="127.0.0.1:8080")
|
|
34
|
+
parser.add_argument("--workers", type=int, default=1)
|
|
35
|
+
|
|
36
|
+
return parser.parse_args()
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class MsgPackRequest(HttpRequest):
|
|
40
|
+
async def data(
|
|
41
|
+
self,
|
|
42
|
+
) -> Annotated[
|
|
43
|
+
Any, ContentType("application/msgpack"), ContentType("application/json")
|
|
44
|
+
]:
|
|
45
|
+
if self.content_type == "application/msgpack":
|
|
46
|
+
return ormsgpack.unpackb(await self.body)
|
|
47
|
+
|
|
48
|
+
elif self.content_type == "application/json":
|
|
49
|
+
return await self.json
|
|
50
|
+
|
|
51
|
+
raise HTTPException(
|
|
52
|
+
HTTPStatus.UNSUPPORTED_MEDIA_TYPE,
|
|
53
|
+
headers={"Accept": "application/msgpack, application/json"},
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
async def inference_async(req: ServeTTSRequest, engine: TTSInferenceEngine):
|
|
58
|
+
for chunk in inference(req, engine):
|
|
59
|
+
if isinstance(chunk, bytes):
|
|
60
|
+
yield chunk
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
async def buffer_to_async_generator(buffer):
|
|
64
|
+
yield buffer
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def get_content_type(audio_format):
|
|
68
|
+
if audio_format == "wav":
|
|
69
|
+
return "audio/wav"
|
|
70
|
+
elif audio_format == "flac":
|
|
71
|
+
return "audio/flac"
|
|
72
|
+
elif audio_format == "mp3":
|
|
73
|
+
return "audio/mpeg"
|
|
74
|
+
else:
|
|
75
|
+
return "application/octet-stream"
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import traceback
|
|
2
|
+
from http import HTTPStatus
|
|
3
|
+
|
|
4
|
+
from kui.asgi import HTTPException, JSONResponse
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class ExceptionHandler:
|
|
8
|
+
|
|
9
|
+
async def http_exception_handler(self, exc: HTTPException):
|
|
10
|
+
return JSONResponse(
|
|
11
|
+
dict(
|
|
12
|
+
statusCode=exc.status_code,
|
|
13
|
+
message=exc.content,
|
|
14
|
+
error=HTTPStatus(exc.status_code).phrase,
|
|
15
|
+
),
|
|
16
|
+
exc.status_code,
|
|
17
|
+
exc.headers,
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
async def other_exception_handler(self, exc: Exception):
|
|
21
|
+
traceback.print_exc()
|
|
22
|
+
|
|
23
|
+
status = HTTPStatus.INTERNAL_SERVER_ERROR
|
|
24
|
+
return JSONResponse(
|
|
25
|
+
dict(statusCode=status, message=str(exc), error=status.phrase),
|
|
26
|
+
status,
|
|
27
|
+
)
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
from http import HTTPStatus
|
|
2
|
+
|
|
3
|
+
import numpy as np
|
|
4
|
+
from kui.asgi import HTTPException
|
|
5
|
+
|
|
6
|
+
from tools.inference_engine import TTSInferenceEngine
|
|
7
|
+
from tools.schema import ServeTTSRequest
|
|
8
|
+
|
|
9
|
+
AMPLITUDE = 32768 # Needs an explaination
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def inference_wrapper(req: ServeTTSRequest, engine: TTSInferenceEngine):
|
|
13
|
+
"""
|
|
14
|
+
Wrapper for the inference function.
|
|
15
|
+
Used in the API server.
|
|
16
|
+
"""
|
|
17
|
+
count = 0
|
|
18
|
+
for result in engine.inference(req):
|
|
19
|
+
match result.code:
|
|
20
|
+
case "header":
|
|
21
|
+
if isinstance(result.audio, tuple):
|
|
22
|
+
yield result.audio[1]
|
|
23
|
+
|
|
24
|
+
case "error":
|
|
25
|
+
raise HTTPException(
|
|
26
|
+
HTTPStatus.INTERNAL_SERVER_ERROR,
|
|
27
|
+
content=str(result.error),
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
case "segment":
|
|
31
|
+
count += 1
|
|
32
|
+
if isinstance(result.audio, tuple):
|
|
33
|
+
yield (result.audio[1] * AMPLITUDE).astype(np.int16).tobytes()
|
|
34
|
+
|
|
35
|
+
case "final":
|
|
36
|
+
count += 1
|
|
37
|
+
if isinstance(result.audio, tuple):
|
|
38
|
+
yield result.audio[1]
|
|
39
|
+
return None # Stop the generator
|
|
40
|
+
|
|
41
|
+
if count == 0:
|
|
42
|
+
raise HTTPException(
|
|
43
|
+
HTTPStatus.INTERNAL_SERVER_ERROR,
|
|
44
|
+
content="No audio generated, please check the input text.",
|
|
45
|
+
)
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import torch
|
|
2
|
+
from funasr import AutoModel
|
|
3
|
+
from loguru import logger
|
|
4
|
+
|
|
5
|
+
from tools.inference_engine import TTSInferenceEngine
|
|
6
|
+
from tools.llama.generate import (
|
|
7
|
+
launch_thread_safe_queue,
|
|
8
|
+
launch_thread_safe_queue_agent,
|
|
9
|
+
)
|
|
10
|
+
from tools.schema import ServeTTSRequest
|
|
11
|
+
from tools.server.inference import inference_wrapper as inference
|
|
12
|
+
from tools.vqgan.inference import load_model as load_decoder_model
|
|
13
|
+
|
|
14
|
+
ASR_MODEL_NAME = "iic/SenseVoiceSmall"
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class ModelManager:
|
|
18
|
+
def __init__(
|
|
19
|
+
self,
|
|
20
|
+
mode: str,
|
|
21
|
+
device: str,
|
|
22
|
+
half: bool,
|
|
23
|
+
compile: bool,
|
|
24
|
+
asr_enabled: bool,
|
|
25
|
+
llama_checkpoint_path: str,
|
|
26
|
+
decoder_checkpoint_path: str,
|
|
27
|
+
decoder_config_name: str,
|
|
28
|
+
) -> None:
|
|
29
|
+
|
|
30
|
+
self.mode = mode
|
|
31
|
+
self.device = device
|
|
32
|
+
self.half = half
|
|
33
|
+
self.compile = compile
|
|
34
|
+
|
|
35
|
+
self.precision = torch.half if half else torch.bfloat16
|
|
36
|
+
|
|
37
|
+
# Check if MPS or CUDA is available
|
|
38
|
+
if torch.backends.mps.is_available():
|
|
39
|
+
self.device = "mps"
|
|
40
|
+
logger.info("mps is available, running on mps.")
|
|
41
|
+
elif not torch.cuda.is_available():
|
|
42
|
+
self.device = "cpu"
|
|
43
|
+
logger.info("CUDA is not available, running on CPU.")
|
|
44
|
+
|
|
45
|
+
# Load the ASR model if enabled
|
|
46
|
+
if asr_enabled:
|
|
47
|
+
self.load_asr_model(self.device)
|
|
48
|
+
|
|
49
|
+
# Load the TTS models
|
|
50
|
+
self.load_llama_model(
|
|
51
|
+
llama_checkpoint_path, self.device, self.precision, self.compile, self.mode
|
|
52
|
+
)
|
|
53
|
+
self.load_decoder_model(
|
|
54
|
+
decoder_config_name, decoder_checkpoint_path, self.device
|
|
55
|
+
)
|
|
56
|
+
self.tts_inference_engine = TTSInferenceEngine(
|
|
57
|
+
llama_queue=self.llama_queue,
|
|
58
|
+
decoder_model=self.decoder_model,
|
|
59
|
+
precision=self.precision,
|
|
60
|
+
compile=self.compile,
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
# Warm up the models
|
|
64
|
+
if self.mode == "tts":
|
|
65
|
+
self.warm_up(self.tts_inference_engine)
|
|
66
|
+
|
|
67
|
+
def load_asr_model(self, device, hub="ms") -> None:
|
|
68
|
+
self.asr_model = AutoModel(
|
|
69
|
+
model=ASR_MODEL_NAME,
|
|
70
|
+
device=device,
|
|
71
|
+
disable_pbar=True,
|
|
72
|
+
hub=hub,
|
|
73
|
+
)
|
|
74
|
+
logger.info("ASR model loaded.")
|
|
75
|
+
|
|
76
|
+
def load_llama_model(
|
|
77
|
+
self, checkpoint_path, device, precision, compile, mode
|
|
78
|
+
) -> None:
|
|
79
|
+
|
|
80
|
+
if mode == "tts":
|
|
81
|
+
self.llama_queue = launch_thread_safe_queue(
|
|
82
|
+
checkpoint_path=checkpoint_path,
|
|
83
|
+
device=device,
|
|
84
|
+
precision=precision,
|
|
85
|
+
compile=compile,
|
|
86
|
+
)
|
|
87
|
+
elif mode == "agent":
|
|
88
|
+
self.llama_queue, self.tokenizer, self.config = (
|
|
89
|
+
launch_thread_safe_queue_agent(
|
|
90
|
+
checkpoint_path=checkpoint_path,
|
|
91
|
+
device=device,
|
|
92
|
+
precision=precision,
|
|
93
|
+
compile=compile,
|
|
94
|
+
)
|
|
95
|
+
)
|
|
96
|
+
else:
|
|
97
|
+
raise ValueError(f"Invalid mode: {mode}")
|
|
98
|
+
|
|
99
|
+
logger.info("LLAMA model loaded.")
|
|
100
|
+
|
|
101
|
+
def load_decoder_model(self, config_name, checkpoint_path, device) -> None:
|
|
102
|
+
self.decoder_model = load_decoder_model(
|
|
103
|
+
config_name=config_name,
|
|
104
|
+
checkpoint_path=checkpoint_path,
|
|
105
|
+
device=device,
|
|
106
|
+
)
|
|
107
|
+
logger.info("Decoder model loaded.")
|
|
108
|
+
|
|
109
|
+
def warm_up(self, tts_inference_engine) -> None:
|
|
110
|
+
request = ServeTTSRequest(
|
|
111
|
+
text="Hello world.",
|
|
112
|
+
references=[],
|
|
113
|
+
reference_id=None,
|
|
114
|
+
max_new_tokens=1024,
|
|
115
|
+
chunk_length=200,
|
|
116
|
+
top_p=0.7,
|
|
117
|
+
repetition_penalty=1.2,
|
|
118
|
+
temperature=0.7,
|
|
119
|
+
format="wav",
|
|
120
|
+
)
|
|
121
|
+
list(inference(request, tts_inference_engine))
|
|
122
|
+
logger.info("Models warmed up.")
|