xinference 1.0.1__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.

Files changed (170) hide show
  1. xinference/_compat.py +2 -0
  2. xinference/_version.py +3 -3
  3. xinference/api/restful_api.py +28 -6
  4. xinference/core/utils.py +10 -6
  5. xinference/deploy/cmdline.py +3 -1
  6. xinference/deploy/test/test_cmdline.py +56 -0
  7. xinference/isolation.py +24 -0
  8. xinference/model/audio/core.py +10 -0
  9. xinference/model/audio/cosyvoice.py +25 -3
  10. xinference/model/audio/f5tts.py +200 -0
  11. xinference/model/audio/f5tts_mlx.py +260 -0
  12. xinference/model/audio/fish_speech.py +36 -111
  13. xinference/model/audio/model_spec.json +27 -3
  14. xinference/model/audio/model_spec_modelscope.json +18 -0
  15. xinference/model/audio/utils.py +32 -0
  16. xinference/model/embedding/core.py +203 -142
  17. xinference/model/embedding/model_spec.json +7 -0
  18. xinference/model/embedding/model_spec_modelscope.json +8 -0
  19. xinference/model/image/core.py +69 -1
  20. xinference/model/image/model_spec.json +127 -4
  21. xinference/model/image/model_spec_modelscope.json +130 -4
  22. xinference/model/image/stable_diffusion/core.py +45 -13
  23. xinference/model/llm/__init__.py +2 -2
  24. xinference/model/llm/llm_family.json +219 -53
  25. xinference/model/llm/llm_family.py +15 -36
  26. xinference/model/llm/llm_family_modelscope.json +167 -20
  27. xinference/model/llm/mlx/core.py +287 -51
  28. xinference/model/llm/sglang/core.py +1 -0
  29. xinference/model/llm/transformers/chatglm.py +9 -5
  30. xinference/model/llm/transformers/core.py +1 -0
  31. xinference/model/llm/transformers/qwen2_vl.py +2 -0
  32. xinference/model/llm/transformers/utils.py +16 -8
  33. xinference/model/llm/utils.py +5 -1
  34. xinference/model/llm/vllm/core.py +16 -2
  35. xinference/thirdparty/cosyvoice/bin/average_model.py +92 -0
  36. xinference/thirdparty/cosyvoice/bin/export_jit.py +12 -2
  37. xinference/thirdparty/cosyvoice/bin/export_onnx.py +112 -0
  38. xinference/thirdparty/cosyvoice/bin/export_trt.sh +9 -0
  39. xinference/thirdparty/cosyvoice/bin/inference.py +5 -7
  40. xinference/thirdparty/cosyvoice/bin/train.py +42 -8
  41. xinference/thirdparty/cosyvoice/cli/cosyvoice.py +96 -25
  42. xinference/thirdparty/cosyvoice/cli/frontend.py +77 -30
  43. xinference/thirdparty/cosyvoice/cli/model.py +330 -80
  44. xinference/thirdparty/cosyvoice/dataset/dataset.py +6 -2
  45. xinference/thirdparty/cosyvoice/dataset/processor.py +76 -14
  46. xinference/thirdparty/cosyvoice/flow/decoder.py +92 -13
  47. xinference/thirdparty/cosyvoice/flow/flow.py +99 -9
  48. xinference/thirdparty/cosyvoice/flow/flow_matching.py +110 -13
  49. xinference/thirdparty/cosyvoice/flow/length_regulator.py +5 -4
  50. xinference/thirdparty/cosyvoice/hifigan/discriminator.py +140 -0
  51. xinference/thirdparty/cosyvoice/hifigan/generator.py +58 -42
  52. xinference/thirdparty/cosyvoice/hifigan/hifigan.py +67 -0
  53. xinference/thirdparty/cosyvoice/llm/llm.py +139 -6
  54. xinference/thirdparty/cosyvoice/tokenizer/assets/multilingual_zh_ja_yue_char_del.tiktoken +58836 -0
  55. xinference/thirdparty/cosyvoice/tokenizer/tokenizer.py +279 -0
  56. xinference/thirdparty/cosyvoice/transformer/embedding.py +2 -2
  57. xinference/thirdparty/cosyvoice/transformer/encoder_layer.py +7 -7
  58. xinference/thirdparty/cosyvoice/transformer/upsample_encoder.py +318 -0
  59. xinference/thirdparty/cosyvoice/utils/common.py +28 -1
  60. xinference/thirdparty/cosyvoice/utils/executor.py +69 -7
  61. xinference/thirdparty/cosyvoice/utils/file_utils.py +2 -12
  62. xinference/thirdparty/cosyvoice/utils/frontend_utils.py +9 -5
  63. xinference/thirdparty/cosyvoice/utils/losses.py +20 -0
  64. xinference/thirdparty/cosyvoice/utils/scheduler.py +1 -2
  65. xinference/thirdparty/cosyvoice/utils/train_utils.py +101 -45
  66. xinference/thirdparty/f5_tts/api.py +166 -0
  67. xinference/thirdparty/f5_tts/configs/E2TTS_Base_train.yaml +44 -0
  68. xinference/thirdparty/f5_tts/configs/E2TTS_Small_train.yaml +44 -0
  69. xinference/thirdparty/f5_tts/configs/F5TTS_Base_train.yaml +46 -0
  70. xinference/thirdparty/f5_tts/configs/F5TTS_Small_train.yaml +46 -0
  71. xinference/thirdparty/f5_tts/eval/README.md +49 -0
  72. xinference/thirdparty/f5_tts/eval/ecapa_tdnn.py +330 -0
  73. xinference/thirdparty/f5_tts/eval/eval_infer_batch.py +207 -0
  74. xinference/thirdparty/f5_tts/eval/eval_infer_batch.sh +13 -0
  75. xinference/thirdparty/f5_tts/eval/eval_librispeech_test_clean.py +84 -0
  76. xinference/thirdparty/f5_tts/eval/eval_seedtts_testset.py +84 -0
  77. xinference/thirdparty/f5_tts/eval/utils_eval.py +405 -0
  78. xinference/thirdparty/f5_tts/infer/README.md +191 -0
  79. xinference/thirdparty/f5_tts/infer/SHARED.md +74 -0
  80. xinference/thirdparty/f5_tts/infer/examples/basic/basic.toml +11 -0
  81. xinference/thirdparty/f5_tts/infer/examples/basic/basic_ref_en.wav +0 -0
  82. xinference/thirdparty/f5_tts/infer/examples/basic/basic_ref_zh.wav +0 -0
  83. xinference/thirdparty/f5_tts/infer/examples/multi/country.flac +0 -0
  84. xinference/thirdparty/f5_tts/infer/examples/multi/main.flac +0 -0
  85. xinference/thirdparty/f5_tts/infer/examples/multi/story.toml +19 -0
  86. xinference/thirdparty/f5_tts/infer/examples/multi/story.txt +1 -0
  87. xinference/thirdparty/f5_tts/infer/examples/multi/town.flac +0 -0
  88. xinference/thirdparty/f5_tts/infer/examples/vocab.txt +2545 -0
  89. xinference/thirdparty/f5_tts/infer/infer_cli.py +226 -0
  90. xinference/thirdparty/f5_tts/infer/infer_gradio.py +851 -0
  91. xinference/thirdparty/f5_tts/infer/speech_edit.py +193 -0
  92. xinference/thirdparty/f5_tts/infer/utils_infer.py +538 -0
  93. xinference/thirdparty/f5_tts/model/__init__.py +10 -0
  94. xinference/thirdparty/f5_tts/model/backbones/README.md +20 -0
  95. xinference/thirdparty/f5_tts/model/backbones/dit.py +163 -0
  96. xinference/thirdparty/f5_tts/model/backbones/mmdit.py +146 -0
  97. xinference/thirdparty/f5_tts/model/backbones/unett.py +219 -0
  98. xinference/thirdparty/f5_tts/model/cfm.py +285 -0
  99. xinference/thirdparty/f5_tts/model/dataset.py +319 -0
  100. xinference/thirdparty/f5_tts/model/modules.py +658 -0
  101. xinference/thirdparty/f5_tts/model/trainer.py +366 -0
  102. xinference/thirdparty/f5_tts/model/utils.py +185 -0
  103. xinference/thirdparty/f5_tts/scripts/count_max_epoch.py +33 -0
  104. xinference/thirdparty/f5_tts/scripts/count_params_gflops.py +39 -0
  105. xinference/thirdparty/f5_tts/socket_server.py +159 -0
  106. xinference/thirdparty/f5_tts/train/README.md +77 -0
  107. xinference/thirdparty/f5_tts/train/datasets/prepare_csv_wavs.py +139 -0
  108. xinference/thirdparty/f5_tts/train/datasets/prepare_emilia.py +230 -0
  109. xinference/thirdparty/f5_tts/train/datasets/prepare_libritts.py +92 -0
  110. xinference/thirdparty/f5_tts/train/datasets/prepare_ljspeech.py +65 -0
  111. xinference/thirdparty/f5_tts/train/datasets/prepare_wenetspeech4tts.py +125 -0
  112. xinference/thirdparty/f5_tts/train/finetune_cli.py +174 -0
  113. xinference/thirdparty/f5_tts/train/finetune_gradio.py +1846 -0
  114. xinference/thirdparty/f5_tts/train/train.py +75 -0
  115. xinference/thirdparty/fish_speech/fish_speech/conversation.py +94 -83
  116. xinference/thirdparty/fish_speech/fish_speech/models/text2semantic/llama.py +63 -20
  117. xinference/thirdparty/fish_speech/fish_speech/text/clean.py +1 -26
  118. xinference/thirdparty/fish_speech/fish_speech/text/spliter.py +1 -1
  119. xinference/thirdparty/fish_speech/fish_speech/tokenizer.py +152 -0
  120. xinference/thirdparty/fish_speech/fish_speech/train.py +2 -2
  121. xinference/thirdparty/fish_speech/fish_speech/webui/manage.py +1 -1
  122. xinference/thirdparty/fish_speech/tools/{post_api.py → api_client.py} +7 -13
  123. xinference/thirdparty/fish_speech/tools/api_server.py +98 -0
  124. xinference/thirdparty/fish_speech/tools/download_models.py +5 -5
  125. xinference/thirdparty/fish_speech/tools/fish_e2e.py +2 -2
  126. xinference/thirdparty/fish_speech/tools/inference_engine/__init__.py +192 -0
  127. xinference/thirdparty/fish_speech/tools/inference_engine/reference_loader.py +125 -0
  128. xinference/thirdparty/fish_speech/tools/inference_engine/utils.py +39 -0
  129. xinference/thirdparty/fish_speech/tools/inference_engine/vq_manager.py +57 -0
  130. xinference/thirdparty/fish_speech/tools/llama/eval_in_context.py +2 -2
  131. xinference/thirdparty/fish_speech/tools/llama/generate.py +117 -89
  132. xinference/thirdparty/fish_speech/tools/run_webui.py +104 -0
  133. xinference/thirdparty/fish_speech/tools/schema.py +11 -28
  134. xinference/thirdparty/fish_speech/tools/server/agent/__init__.py +57 -0
  135. xinference/thirdparty/fish_speech/tools/server/agent/generate.py +119 -0
  136. xinference/thirdparty/fish_speech/tools/server/agent/generation_utils.py +122 -0
  137. xinference/thirdparty/fish_speech/tools/server/agent/pre_generation_utils.py +72 -0
  138. xinference/thirdparty/fish_speech/tools/server/api_utils.py +75 -0
  139. xinference/thirdparty/fish_speech/tools/server/exception_handler.py +27 -0
  140. xinference/thirdparty/fish_speech/tools/server/inference.py +45 -0
  141. xinference/thirdparty/fish_speech/tools/server/model_manager.py +122 -0
  142. xinference/thirdparty/fish_speech/tools/server/model_utils.py +129 -0
  143. xinference/thirdparty/fish_speech/tools/server/views.py +246 -0
  144. xinference/thirdparty/fish_speech/tools/webui/__init__.py +173 -0
  145. xinference/thirdparty/fish_speech/tools/webui/inference.py +91 -0
  146. xinference/thirdparty/fish_speech/tools/webui/variables.py +14 -0
  147. xinference/thirdparty/matcha/utils/utils.py +2 -2
  148. xinference/web/ui/build/asset-manifest.json +3 -3
  149. xinference/web/ui/build/index.html +1 -1
  150. xinference/web/ui/build/static/js/{main.2f269bb3.js → main.4eb4ee80.js} +3 -3
  151. xinference/web/ui/build/static/js/main.4eb4ee80.js.map +1 -0
  152. xinference/web/ui/node_modules/.cache/babel-loader/8c5eeb02f772d02cbe8b89c05428d0dd41a97866f75f7dc1c2164a67f5a1cf98.json +1 -0
  153. {xinference-1.0.1.dist-info → xinference-1.1.1.dist-info}/METADATA +41 -17
  154. {xinference-1.0.1.dist-info → xinference-1.1.1.dist-info}/RECORD +160 -88
  155. xinference/thirdparty/cosyvoice/bin/export_trt.py +0 -8
  156. xinference/thirdparty/cosyvoice/flow/__init__.py +0 -0
  157. xinference/thirdparty/cosyvoice/hifigan/__init__.py +0 -0
  158. xinference/thirdparty/cosyvoice/llm/__init__.py +0 -0
  159. xinference/thirdparty/fish_speech/tools/__init__.py +0 -0
  160. xinference/thirdparty/fish_speech/tools/api.py +0 -943
  161. xinference/thirdparty/fish_speech/tools/msgpack_api.py +0 -95
  162. xinference/thirdparty/fish_speech/tools/webui.py +0 -548
  163. xinference/web/ui/build/static/js/main.2f269bb3.js.map +0 -1
  164. xinference/web/ui/node_modules/.cache/babel-loader/bd6ad8159341315a1764c397621a560809f7eb7219ab5174c801fca7e969d943.json +0 -1
  165. /xinference/thirdparty/{cosyvoice/bin → f5_tts}/__init__.py +0 -0
  166. /xinference/web/ui/build/static/js/{main.2f269bb3.js.LICENSE.txt → main.4eb4ee80.js.LICENSE.txt} +0 -0
  167. {xinference-1.0.1.dist-info → xinference-1.1.1.dist-info}/LICENSE +0 -0
  168. {xinference-1.0.1.dist-info → xinference-1.1.1.dist-info}/WHEEL +0 -0
  169. {xinference-1.0.1.dist-info → xinference-1.1.1.dist-info}/entry_points.txt +0 -0
  170. {xinference-1.0.1.dist-info → xinference-1.1.1.dist-info}/top_level.txt +0 -0
@@ -1,95 +0,0 @@
1
- import os
2
- from argparse import ArgumentParser
3
- from pathlib import Path
4
-
5
- import httpx
6
- import ormsgpack
7
-
8
- from tools.schema import ServeReferenceAudio, ServeTTSRequest
9
-
10
- api_key = os.environ.get("FISH_API_KEY", "YOUR_API_KEY")
11
-
12
-
13
- def audio_request():
14
- # priority: ref_id > references
15
- request = ServeTTSRequest(
16
- text="你说的对, 但是原神是一款由米哈游自主研发的开放世界手游.",
17
- # reference_id="114514",
18
- references=[
19
- ServeReferenceAudio(
20
- audio=open("lengyue.wav", "rb").read(),
21
- text=open("lengyue.lab", "r", encoding="utf-8").read(),
22
- )
23
- ],
24
- streaming=True,
25
- )
26
-
27
- api_key = os.environ.get("FISH_API_KEY", "YOUR_API_KEY")
28
-
29
- with (
30
- httpx.Client() as client,
31
- open("hello.wav", "wb") as f,
32
- ):
33
- with client.stream(
34
- "POST",
35
- "http://127.0.0.1:8080/v1/tts",
36
- content=ormsgpack.packb(request, option=ormsgpack.OPT_SERIALIZE_PYDANTIC),
37
- headers={
38
- "authorization": f"Bearer {api_key}",
39
- "content-type": "application/msgpack",
40
- },
41
- timeout=None,
42
- ) as response:
43
- for chunk in response.iter_bytes():
44
- f.write(chunk)
45
-
46
-
47
- def asr_request(audio_path: Path):
48
-
49
- # Read the audio file
50
- with open(
51
- str(audio_path),
52
- "rb",
53
- ) as audio_file:
54
- audio_data = audio_file.read()
55
-
56
- # Prepare the request data
57
- request_data = {
58
- "audio": audio_data,
59
- "language": "en", # Optional: specify the language
60
- "ignore_timestamps": False, # Optional: set to True to ignore precise timestamps
61
- }
62
-
63
- # Send the request
64
- with httpx.Client() as client:
65
- response = client.post(
66
- "https://api.fish.audio/v1/asr",
67
- headers={
68
- "Authorization": f"Bearer {api_key}",
69
- "Content-Type": "application/msgpack",
70
- },
71
- content=ormsgpack.packb(request_data),
72
- )
73
-
74
- # Parse the response
75
- result = response.json()
76
-
77
- print(f"Transcribed text: {result['text']}")
78
- print(f"Audio duration: {result['duration']} seconds")
79
-
80
- for segment in result["segments"]:
81
- print(f"Segment: {segment['text']}")
82
- print(f"Start time: {segment['start']}, End time: {segment['end']}")
83
-
84
-
85
- def parse_args():
86
- parser = ArgumentParser()
87
- parser.add_argument("--audio_path", type=Path, default="audio/ref/trump.mp3")
88
-
89
- return parser.parse_args()
90
-
91
-
92
- if __name__ == "__main__":
93
- args = parse_args()
94
-
95
- asr_request(args.audio_path)
@@ -1,548 +0,0 @@
1
- import gc
2
- import html
3
- import io
4
- import os
5
- import queue
6
- import wave
7
- from argparse import ArgumentParser
8
- from functools import partial
9
- from pathlib import Path
10
-
11
- import gradio as gr
12
- import librosa
13
- import numpy as np
14
- # import pyrootutils
15
- import torch
16
- from loguru import logger
17
- from transformers import AutoTokenizer
18
-
19
- # pyrootutils.setup_root(__file__, indicator=".project-root", pythonpath=True)
20
-
21
-
22
- from fish_speech.i18n import i18n
23
- from fish_speech.text.chn_text_norm.text import Text as ChnNormedText
24
- from fish_speech.utils import autocast_exclude_mps, set_seed
25
- from tools.api import decode_vq_tokens, encode_reference
26
- from tools.file import AUDIO_EXTENSIONS, list_files
27
- from tools.llama.generate import (
28
- GenerateRequest,
29
- GenerateResponse,
30
- WrappedGenerateResponse,
31
- launch_thread_safe_queue,
32
- )
33
- from tools.vqgan.inference import load_model as load_decoder_model
34
-
35
- # Make einx happy
36
- os.environ["EINX_FILTER_TRACEBACK"] = "false"
37
-
38
-
39
- HEADER_MD = f"""# Fish Speech
40
-
41
- {i18n("A text-to-speech model based on VQ-GAN and Llama developed by [Fish Audio](https://fish.audio).")}
42
-
43
- {i18n("You can find the source code [here](https://github.com/fishaudio/fish-speech) and models [here](https://huggingface.co/fishaudio/fish-speech-1.4).")}
44
-
45
- {i18n("Related code and weights are released under CC BY-NC-SA 4.0 License.")}
46
-
47
- {i18n("We are not responsible for any misuse of the model, please consider your local laws and regulations before using it.")}
48
- """
49
-
50
- TEXTBOX_PLACEHOLDER = i18n("Put your text here.")
51
- SPACE_IMPORTED = False
52
-
53
-
54
- def build_html_error_message(error):
55
- return f"""
56
- <div style="color: red;
57
- font-weight: bold;">
58
- {html.escape(str(error))}
59
- </div>
60
- """
61
-
62
-
63
- @torch.inference_mode()
64
- def inference(
65
- text,
66
- enable_reference_audio,
67
- reference_audio,
68
- reference_text,
69
- max_new_tokens,
70
- chunk_length,
71
- top_p,
72
- repetition_penalty,
73
- temperature,
74
- seed="0",
75
- streaming=False,
76
- ):
77
- if args.max_gradio_length > 0 and len(text) > args.max_gradio_length:
78
- return (
79
- None,
80
- None,
81
- i18n("Text is too long, please keep it under {} characters.").format(
82
- args.max_gradio_length
83
- ),
84
- )
85
-
86
- seed = int(seed)
87
- if seed != 0:
88
- set_seed(seed)
89
- logger.warning(f"set seed: {seed}")
90
-
91
- # Parse reference audio aka prompt
92
- prompt_tokens = encode_reference(
93
- decoder_model=decoder_model,
94
- reference_audio=reference_audio,
95
- enable_reference_audio=enable_reference_audio,
96
- )
97
-
98
- # LLAMA Inference
99
- request = dict(
100
- device=decoder_model.device,
101
- max_new_tokens=max_new_tokens,
102
- text=text,
103
- top_p=top_p,
104
- repetition_penalty=repetition_penalty,
105
- temperature=temperature,
106
- compile=args.compile,
107
- iterative_prompt=chunk_length > 0,
108
- chunk_length=chunk_length,
109
- max_length=2048,
110
- prompt_tokens=prompt_tokens if enable_reference_audio else None,
111
- prompt_text=reference_text if enable_reference_audio else None,
112
- )
113
-
114
- response_queue = queue.Queue()
115
- llama_queue.put(
116
- GenerateRequest(
117
- request=request,
118
- response_queue=response_queue,
119
- )
120
- )
121
-
122
- if streaming:
123
- yield wav_chunk_header(), None, None
124
-
125
- segments = []
126
-
127
- while True:
128
- result: WrappedGenerateResponse = response_queue.get()
129
- if result.status == "error":
130
- yield None, None, build_html_error_message(result.response)
131
- break
132
-
133
- result: GenerateResponse = result.response
134
- if result.action == "next":
135
- break
136
-
137
- with autocast_exclude_mps(
138
- device_type=decoder_model.device.type, dtype=args.precision
139
- ):
140
- fake_audios = decode_vq_tokens(
141
- decoder_model=decoder_model,
142
- codes=result.codes,
143
- )
144
-
145
- fake_audios = fake_audios.float().cpu().numpy()
146
- segments.append(fake_audios)
147
-
148
- if streaming:
149
- wav_header = wav_chunk_header()
150
- audio_data = (fake_audios * 32768).astype(np.int16).tobytes()
151
- yield wav_header + audio_data, None, None
152
-
153
- if len(segments) == 0:
154
- return (
155
- None,
156
- None,
157
- build_html_error_message(
158
- i18n("No audio generated, please check the input text.")
159
- ),
160
- )
161
-
162
- # No matter streaming or not, we need to return the final audio
163
- audio = np.concatenate(segments, axis=0)
164
- yield None, (decoder_model.spec_transform.sample_rate, audio), None
165
-
166
- if torch.cuda.is_available():
167
- torch.cuda.empty_cache()
168
- gc.collect()
169
-
170
-
171
- inference_stream = partial(inference, streaming=True)
172
-
173
- n_audios = 4
174
-
175
- global_audio_list = []
176
- global_error_list = []
177
-
178
-
179
- def inference_wrapper(
180
- text,
181
- enable_reference_audio,
182
- reference_audio,
183
- reference_text,
184
- max_new_tokens,
185
- chunk_length,
186
- top_p,
187
- repetition_penalty,
188
- temperature,
189
- seed,
190
- batch_infer_num,
191
- ):
192
- audios = []
193
- errors = []
194
-
195
- for _ in range(batch_infer_num):
196
- result = inference(
197
- text,
198
- enable_reference_audio,
199
- reference_audio,
200
- reference_text,
201
- max_new_tokens,
202
- chunk_length,
203
- top_p,
204
- repetition_penalty,
205
- temperature,
206
- seed,
207
- )
208
-
209
- _, audio_data, error_message = next(result)
210
-
211
- audios.append(
212
- gr.Audio(value=audio_data if audio_data else None, visible=True),
213
- )
214
- errors.append(
215
- gr.HTML(value=error_message if error_message else None, visible=True),
216
- )
217
-
218
- for _ in range(batch_infer_num, n_audios):
219
- audios.append(
220
- gr.Audio(value=None, visible=False),
221
- )
222
- errors.append(
223
- gr.HTML(value=None, visible=False),
224
- )
225
-
226
- return None, *audios, *errors
227
-
228
-
229
- def wav_chunk_header(sample_rate=44100, bit_depth=16, channels=1):
230
- buffer = io.BytesIO()
231
-
232
- with wave.open(buffer, "wb") as wav_file:
233
- wav_file.setnchannels(channels)
234
- wav_file.setsampwidth(bit_depth // 8)
235
- wav_file.setframerate(sample_rate)
236
-
237
- wav_header_bytes = buffer.getvalue()
238
- buffer.close()
239
- return wav_header_bytes
240
-
241
-
242
- def normalize_text(user_input, use_normalization):
243
- if use_normalization:
244
- return ChnNormedText(raw_text=user_input).normalize()
245
- else:
246
- return user_input
247
-
248
-
249
- def update_examples():
250
- examples_dir = Path("references")
251
- examples_dir.mkdir(parents=True, exist_ok=True)
252
- example_audios = list_files(examples_dir, AUDIO_EXTENSIONS, recursive=True)
253
- return gr.Dropdown(choices=example_audios + [""])
254
-
255
-
256
- def build_app():
257
- with gr.Blocks(theme=gr.themes.Base()) as app:
258
- gr.Markdown(HEADER_MD)
259
-
260
- # Use light theme by default
261
- app.load(
262
- None,
263
- None,
264
- js="() => {const params = new URLSearchParams(window.location.search);if (!params.has('__theme')) {params.set('__theme', '%s');window.location.search = params.toString();}}"
265
- % args.theme,
266
- )
267
-
268
- # Inference
269
- with gr.Row():
270
- with gr.Column(scale=3):
271
- text = gr.Textbox(
272
- label=i18n("Input Text"), placeholder=TEXTBOX_PLACEHOLDER, lines=10
273
- )
274
- refined_text = gr.Textbox(
275
- label=i18n("Realtime Transform Text"),
276
- placeholder=i18n(
277
- "Normalization Result Preview (Currently Only Chinese)"
278
- ),
279
- lines=5,
280
- interactive=False,
281
- )
282
-
283
- with gr.Row():
284
- if_refine_text = gr.Checkbox(
285
- label=i18n("Text Normalization"),
286
- value=False,
287
- scale=1,
288
- )
289
-
290
- with gr.Row():
291
- with gr.Column():
292
- with gr.Tab(label=i18n("Advanced Config")):
293
- with gr.Row():
294
- chunk_length = gr.Slider(
295
- label=i18n("Iterative Prompt Length, 0 means off"),
296
- minimum=50,
297
- maximum=300,
298
- value=200,
299
- step=8,
300
- )
301
-
302
- max_new_tokens = gr.Slider(
303
- label=i18n(
304
- "Maximum tokens per batch, 0 means no limit"
305
- ),
306
- minimum=0,
307
- maximum=2048,
308
- value=0, # 0 means no limit
309
- step=8,
310
- )
311
-
312
- with gr.Row():
313
- top_p = gr.Slider(
314
- label="Top-P",
315
- minimum=0.6,
316
- maximum=0.9,
317
- value=0.7,
318
- step=0.01,
319
- )
320
-
321
- repetition_penalty = gr.Slider(
322
- label=i18n("Repetition Penalty"),
323
- minimum=1,
324
- maximum=1.5,
325
- value=1.2,
326
- step=0.01,
327
- )
328
-
329
- with gr.Row():
330
- temperature = gr.Slider(
331
- label="Temperature",
332
- minimum=0.6,
333
- maximum=0.9,
334
- value=0.7,
335
- step=0.01,
336
- )
337
- seed = gr.Textbox(
338
- label="Seed",
339
- info="0 means randomized inference, otherwise deterministic",
340
- placeholder="any 32-bit-integer",
341
- value="0",
342
- )
343
-
344
- with gr.Tab(label=i18n("Reference Audio")):
345
- with gr.Row():
346
- gr.Markdown(
347
- i18n(
348
- "5 to 10 seconds of reference audio, useful for specifying speaker."
349
- )
350
- )
351
- with gr.Row():
352
- enable_reference_audio = gr.Checkbox(
353
- label=i18n("Enable Reference Audio"),
354
- )
355
-
356
- with gr.Row():
357
- example_audio_dropdown = gr.Dropdown(
358
- label=i18n("Select Example Audio"),
359
- choices=[""],
360
- value="",
361
- interactive=True,
362
- allow_custom_value=True,
363
- )
364
- with gr.Row():
365
- reference_audio = gr.Audio(
366
- label=i18n("Reference Audio"),
367
- type="filepath",
368
- )
369
- with gr.Row():
370
- reference_text = gr.Textbox(
371
- label=i18n("Reference Text"),
372
- lines=1,
373
- placeholder="在一无所知中,梦里的一天结束了,一个新的「轮回」便会开始。",
374
- value="",
375
- )
376
- with gr.Tab(label=i18n("Batch Inference")):
377
- with gr.Row():
378
- batch_infer_num = gr.Slider(
379
- label="Batch infer nums",
380
- minimum=1,
381
- maximum=n_audios,
382
- step=1,
383
- value=1,
384
- )
385
-
386
- with gr.Column(scale=3):
387
- for _ in range(n_audios):
388
- with gr.Row():
389
- error = gr.HTML(
390
- label=i18n("Error Message"),
391
- visible=True if _ == 0 else False,
392
- )
393
- global_error_list.append(error)
394
- with gr.Row():
395
- audio = gr.Audio(
396
- label=i18n("Generated Audio"),
397
- type="numpy",
398
- interactive=False,
399
- visible=True if _ == 0 else False,
400
- )
401
- global_audio_list.append(audio)
402
-
403
- with gr.Row():
404
- stream_audio = gr.Audio(
405
- label=i18n("Streaming Audio"),
406
- streaming=True,
407
- autoplay=True,
408
- interactive=False,
409
- show_download_button=True,
410
- )
411
- with gr.Row():
412
- with gr.Column(scale=3):
413
- generate = gr.Button(
414
- value="\U0001F3A7 " + i18n("Generate"), variant="primary"
415
- )
416
- generate_stream = gr.Button(
417
- value="\U0001F3A7 " + i18n("Streaming Generate"),
418
- variant="primary",
419
- )
420
-
421
- text.input(
422
- fn=normalize_text, inputs=[text, if_refine_text], outputs=[refined_text]
423
- )
424
-
425
- def select_example_audio(audio_path):
426
- audio_path = Path(audio_path)
427
- if audio_path.is_file():
428
- lab_file = Path(audio_path.with_suffix(".lab"))
429
-
430
- if lab_file.exists():
431
- lab_content = lab_file.read_text(encoding="utf-8").strip()
432
- else:
433
- lab_content = ""
434
-
435
- return str(audio_path), lab_content, True
436
- return None, "", False
437
-
438
- # Connect the dropdown to update reference audio and text
439
- example_audio_dropdown.change(
440
- fn=update_examples, inputs=[], outputs=[example_audio_dropdown]
441
- ).then(
442
- fn=select_example_audio,
443
- inputs=[example_audio_dropdown],
444
- outputs=[reference_audio, reference_text, enable_reference_audio],
445
- )
446
-
447
- # # Submit
448
- generate.click(
449
- inference_wrapper,
450
- [
451
- refined_text,
452
- enable_reference_audio,
453
- reference_audio,
454
- reference_text,
455
- max_new_tokens,
456
- chunk_length,
457
- top_p,
458
- repetition_penalty,
459
- temperature,
460
- seed,
461
- batch_infer_num,
462
- ],
463
- [stream_audio, *global_audio_list, *global_error_list],
464
- concurrency_limit=1,
465
- )
466
-
467
- generate_stream.click(
468
- inference_stream,
469
- [
470
- refined_text,
471
- enable_reference_audio,
472
- reference_audio,
473
- reference_text,
474
- max_new_tokens,
475
- chunk_length,
476
- top_p,
477
- repetition_penalty,
478
- temperature,
479
- seed,
480
- ],
481
- [stream_audio, global_audio_list[0], global_error_list[0]],
482
- concurrency_limit=1,
483
- )
484
- return app
485
-
486
-
487
- def parse_args():
488
- parser = ArgumentParser()
489
- parser.add_argument(
490
- "--llama-checkpoint-path",
491
- type=Path,
492
- default="checkpoints/fish-speech-1.4",
493
- )
494
- parser.add_argument(
495
- "--decoder-checkpoint-path",
496
- type=Path,
497
- default="checkpoints/fish-speech-1.4/firefly-gan-vq-fsq-8x1024-21hz-generator.pth",
498
- )
499
- parser.add_argument("--decoder-config-name", type=str, default="firefly_gan_vq")
500
- parser.add_argument("--device", type=str, default="cuda")
501
- parser.add_argument("--half", action="store_true")
502
- parser.add_argument("--compile", action="store_true")
503
- parser.add_argument("--max-gradio-length", type=int, default=0)
504
- parser.add_argument("--theme", type=str, default="light")
505
-
506
- return parser.parse_args()
507
-
508
-
509
- if __name__ == "__main__":
510
- args = parse_args()
511
- args.precision = torch.half if args.half else torch.bfloat16
512
-
513
- logger.info("Loading Llama model...")
514
- llama_queue = launch_thread_safe_queue(
515
- checkpoint_path=args.llama_checkpoint_path,
516
- device=args.device,
517
- precision=args.precision,
518
- compile=args.compile,
519
- )
520
- logger.info("Llama model loaded, loading VQ-GAN model...")
521
-
522
- decoder_model = load_decoder_model(
523
- config_name=args.decoder_config_name,
524
- checkpoint_path=args.decoder_checkpoint_path,
525
- device=args.device,
526
- )
527
-
528
- logger.info("Decoder model loaded, warming up...")
529
-
530
- # Dry run to check if the model is loaded correctly and avoid the first-time latency
531
- list(
532
- inference(
533
- text="Hello, world!",
534
- enable_reference_audio=False,
535
- reference_audio=None,
536
- reference_text="",
537
- max_new_tokens=0,
538
- chunk_length=200,
539
- top_p=0.7,
540
- repetition_penalty=1.2,
541
- temperature=0.7,
542
- )
543
- )
544
-
545
- logger.info("Warming up done, launching the web UI...")
546
-
547
- app = build_app()
548
- app.launch(show_api=True)