您现在的位置是:首页 > 技术教程 正文

Python - Bert-VITS2 语音推理服务部署

admin 阅读: 2024-03-21
后台-插件-广告管理-内容页头部广告(手机)

目录

一.引言

二.服务搭建

1.服务配置

2.服务代码

3.服务踩坑

三.服务使用

1.服务启动

2.服务调用

3.服务结果

四.总结


一.引言

上一篇文章我们介绍了如果使用 conda 搭建 Bert-VITS2 最新版本的环境并训练自定义语音,通过 1000 个 epoch 的训练,我们得到了自定义语音模型,本文基于上文得到的生成器模型介绍如何部署语音推理服务,获取自定义角色音频。

Tips:  

训练流程:  Bert-VITS2 自定义训练语音

二.服务搭建

1.服务配置

查看项目根目录下的配置文件修改对应配置:

vim config.yml

这里主要修改如下几点:

- port 修改服务监听的端口,主要不要与其他服务的端口重复

- models 自定义生成的模型内 G-xxxx.pth 为对应的生成器,可以尝试不同 Epoch 的模型都可以

- config 配置文件读取 ./configs/config.json 内的配置

- launguage 博主使用中文 ZH、大家如果是其他语言的话也可以修改 

  1. server:
  2. # 端口号
  3. port: 9876
  4. # 模型默认使用设备:但是当前并没有实现这个配置。
  5. device: "cuda"
  6. # 需要加载的所有模型的配置,可以填多个模型,也可以不填模型,等网页成功后手动加载模型
  7. # 不加载模型的配置格式:删除默认给的两个模型配置,给models赋值 [ ],也就是空列表。参考模型2的speakers 即 models: [ ]
  8. # 注意,所有模型都必须正确配置model与config的路径,空路径会导致加载错误。也可以不填模型,等网页加载成功后手动填写models。
  9. models:
  10. - # 模型的路径
  11. model: "data/models/G_15000.pth"
  12. # 模型config.json的路径
  13. config: "configs/config.json"
  14. # 模型使用设备,若填写则会覆盖默认配置
  15. device: "cuda"
  16. # 模型默认使用的语言
  17. language: "ZH"
  18. # 模型人物默认参数
  19. # 不必填写所有人物,不填的使用默认值
  20. # 暂时不用填写,当前尚未实现按人区分配置
  21. speakers:
  22. - speaker: "科比"
  23. sdp_ratio: 0.2
  24. noise_scale: 0.6
  25. noise_scale_w: 0.8
  26. length_scale: 1
  27. - speaker: "五条悟"
  28. sdp_ratio: 0.3
  29. noise_scale: 0.7
  30. noise_scale_w: 0.8
  31. length_scale: 0.5
  32. - speaker: "安倍晋三"
  33. sdp_ratio: 0.2
  34. noise_scale: 0.6
  35. noise_scale_w: 0.8
  36. length_scale: 1.2
  37. - # 模型的路径
  38. model: "data/models/G_15000.pth"
  39. # 模型config.json的路径
  40. config: "configs/config.json"
  41. # 模型使用设备,若填写则会覆盖默认配置
  42. device: "gpu"
  43. # 模型默认使用的语言
  44. language: "ZH"

2.服务代码

创建服务代码:

vim server_fastapi.py
  1. """
  2. api服务 多版本多模型 fastapi实现
  3. """
  4. import logging
  5. import gc
  6. import random
  7. from pydantic import BaseModel
  8. import gradio
  9. import numpy as np
  10. import utils
  11. from fastapi import FastAPI, Query, Request
  12. from fastapi.responses import Response, FileResponse
  13. from fastapi.staticfiles import StaticFiles
  14. from io import BytesIO
  15. from scipy.io import wavfile
  16. import uvicorn
  17. import torch
  18. import webbrowser
  19. import psutil
  20. import GPUtil
  21. from typing import Dict, Optional, List, Set
  22. import os
  23. from tools.log import logger
  24. from urllib.parse import unquote
  25. from infer import infer, get_net_g, latest_version
  26. import tools.translate as trans
  27. from re_matching import cut_sent
  28. from config import config
  29. os.environ["TOKENIZERS_PARALLELISM"] = "false"
  30. class Model:
  31. """模型封装类"""
  32. def __init__(self, config_path: str, model_path: str, device: str, language: str):
  33. self.config_path: str = os.path.normpath(config_path)
  34. self.model_path: str = os.path.normpath(model_path)
  35. self.device: str = device
  36. self.language: str = language
  37. self.hps = utils.get_hparams_from_file(config_path)
  38. self.spk2id: Dict[str, int] = self.hps.data.spk2id # spk - id 映射字典
  39. self.id2spk: Dict[int, str] = dict() # id - spk 映射字典
  40. for speaker, speaker_id in self.hps.data.spk2id.items():
  41. self.id2spk[speaker_id] = speaker
  42. self.version: str = (
  43. self.hps.version if hasattr(self.hps, "version") else latest_version
  44. )
  45. self.net_g = get_net_g(
  46. model_path=model_path,
  47. version=self.version,
  48. device=device,
  49. hps=self.hps,
  50. )
  51. def to_dict(self) -> Dict[str, any]:
  52. return {
  53. "config_path": self.config_path,
  54. "model_path": self.model_path,
  55. "device": self.device,
  56. "language": self.language,
  57. "spk2id": self.spk2id,
  58. "id2spk": self.id2spk,
  59. "version": self.version,
  60. }
  61. class Models:
  62. def __init__(self):
  63. self.models: Dict[int, Model] = dict()
  64. self.num = 0
  65. # spkInfo[角色名][模型id] = 角色id
  66. self.spk_info: Dict[str, Dict[int, int]] = dict()
  67. self.path2ids: Dict[str, Set[int]] = dict() # 路径指向的model的id
  68. def init_model(
  69. self, config_path: str, model_path: str, device: str, language: str
  70. ) -> int:
  71. """
  72. 初始化并添加一个模型
  73. :param config_path: 模型config.json路径
  74. :param model_path: 模型路径
  75. :param device: 模型推理使用设备
  76. :param language: 模型推理默认语言
  77. """
  78. # 若路径中的模型已存在,则不添加模型,若不存在,则进行初始化。
  79. model_path = os.path.realpath(model_path)
  80. if model_path not in self.path2ids.keys():
  81. self.path2ids[model_path] = {self.num}
  82. self.models[self.num] = Model(
  83. config_path=config_path,
  84. model_path=model_path,
  85. device=device,
  86. language=language,
  87. )
  88. logger.success(f"添加模型{model_path},使用配置文件{os.path.realpath(config_path)}")
  89. else:
  90. # 获取一个指向id
  91. m_id = next(iter(self.path2ids[model_path]))
  92. self.models[self.num] = self.models[m_id]
  93. self.path2ids[model_path].add(self.num)
  94. logger.success("模型已存在,添加模型引用。")
  95. # 添加角色信息
  96. for speaker, speaker_id in self.models[self.num].spk2id.items():
  97. if speaker not in self.spk_info.keys():
  98. self.spk_info[speaker] = {self.num: speaker_id}
  99. else:
  100. self.spk_info[speaker][self.num] = speaker_id
  101. # 修改计数
  102. self.num += 1
  103. return self.num - 1
  104. def del_model(self, index: int) -> Optional[int]:
  105. """删除对应序号的模型,若不存在则返回None"""
  106. if index not in self.models.keys():
  107. return None
  108. # 删除角色信息
  109. for speaker, speaker_id in self.models[index].spk2id.items():
  110. self.spk_info[speaker].pop(index)
  111. if len(self.spk_info[speaker]) == 0:
  112. # 若对应角色的所有模型都被删除,则清除该角色信息
  113. self.spk_info.pop(speaker)
  114. # 删除路径信息
  115. model_path = os.path.realpath(self.models[index].model_path)
  116. self.path2ids[model_path].remove(index)
  117. if len(self.path2ids[model_path]) == 0:
  118. self.path2ids.pop(model_path)
  119. logger.success(f"删除模型{model_path}, id = {index}")
  120. else:
  121. logger.success(f"删除模型引用{model_path}, id = {index}")
  122. # 删除模型
  123. self.models.pop(index)
  124. gc.collect()
  125. if torch.cuda.is_available():
  126. torch.cuda.empty_cache()
  127. return index
  128. def get_models(self):
  129. """获取所有模型"""
  130. return self.models
  131. if __name__ == "__main__":
  132. app = FastAPI()
  133. app.logger = logger
  134. # 挂载静态文件
  135. StaticDir: str = "./Web"
  136. dirs = [fir.name for fir in os.scandir(StaticDir) if fir.is_dir()]
  137. files = [fir.name for fir in os.scandir(StaticDir) if fir.is_dir()]
  138. for dirName in dirs:
  139. app.mount(
  140. f"/{dirName}",
  141. StaticFiles(directory=f"./{StaticDir}/{dirName}"),
  142. name=dirName,
  143. )
  144. loaded_models = Models()
  145. # 加载模型
  146. models_info = config.server_config.models
  147. for model_info in models_info:
  148. loaded_models.init_model(
  149. config_path=model_info["config"],
  150. model_path=model_info["model"],
  151. device=model_info["device"],
  152. language=model_info["language"],
  153. )
  154. @app.get("/")
  155. async def index():
  156. return FileResponse("./Web/index.html")
  157. class Text(BaseModel):
  158. text: str
  159. @app.post("/voice")
  160. def voice(
  161. request: Request, # fastapi自动注入
  162. text: Text,
  163. model_id: int = Query(..., description="模型ID"), # 模型序号
  164. speaker_name: str = Query(
  165. None, description="说话人名"
  166. ), # speaker_name与 speaker_id二者选其一
  167. speaker_id: int = Query(None, description="说话人id,与speaker_name二选一"),
  168. sdp_ratio: float = Query(0.2, description="SDP/DP混合比"),
  169. noise: float = Query(0.2, description="感情"),
  170. noisew: float = Query(0.9, description="音素长度"),
  171. length: float = Query(1, description="语速"),
  172. language: str = Query(None, description="语言"), # 若不指定使用语言则使用默认值
  173. auto_translate: bool = Query(False, description="自动翻译"),
  174. auto_split: bool = Query(False, description="自动切分"),
  175. ):
  176. """语音接口"""
  177. text = text.text
  178. logger.info(
  179. f"{request.client.host}:{request.client.port}/voice { unquote(str(request.query_params) )} text={text}"
  180. )
  181. # 检查模型是否存在
  182. if model_id not in loaded_models.models.keys():
  183. return {"status": 10, "detail": f"模型model_id={model_id}未加载"}
  184. # 检查是否提供speaker
  185. if speaker_name is None and speaker_id is None:
  186. return {"status": 11, "detail": "请提供speaker_name或speaker_id"}
  187. elif speaker_name is None:
  188. # 检查speaker_id是否存在
  189. if speaker_id not in loaded_models.models[model_id].id2spk.keys():
  190. return {"status": 12, "detail": f"角色speaker_id={speaker_id}不存在"}
  191. speaker_name = loaded_models.models[model_id].id2spk[speaker_id]
  192. # 检查speaker_name是否存在
  193. if speaker_name not in loaded_models.models[model_id].spk2id.keys():
  194. return {"status": 13, "detail": f"角色speaker_name={speaker_name}不存在"}
  195. if language is None:
  196. language = loaded_models.models[model_id].language
  197. if auto_translate:
  198. text = trans.translate(Sentence=text, to_Language=language.lower())
  199. if not auto_split:
  200. with torch.no_grad():
  201. audio = infer(
  202. text=text,
  203. emotion=None,
  204. sdp_ratio=sdp_ratio,
  205. noise_scale=noise,
  206. noise_scale_w=noisew,
  207. length_scale=length,
  208. sid=speaker_name,
  209. language=language,
  210. hps=loaded_models.models[model_id].hps,
  211. net_g=loaded_models.models[model_id].net_g,
  212. device=loaded_models.models[model_id].device,
  213. )
  214. else:
  215. texts = cut_sent(text)
  216. audios = []
  217. with torch.no_grad():
  218. for t in texts:
  219. audios.append(
  220. infer(
  221. text=t,
  222. sdp_ratio=sdp_ratio,
  223. noise_scale=noise,
  224. noise_scale_w=noisew,
  225. length_scale=length,
  226. sid=speaker_name,
  227. language=language,
  228. hps=loaded_models.models[model_id].hps,
  229. net_g=loaded_models.models[model_id].net_g,
  230. device=loaded_models.models[model_id].device,
  231. )
  232. )
  233. audios.append(np.zeros((int)(44100 * 0.3)))
  234. audio = np.concatenate(audios)
  235. audio = gradio.processing_utils.convert_to_16_bit_wav(audio)
  236. wavContent = BytesIO()
  237. wavfile.write(
  238. wavContent, loaded_models.models[model_id].hps.data.sampling_rate, audio
  239. )
  240. response = Response(content=wavContent.getvalue(), media_type="audio/wav")
  241. return response
  242. @app.get("/voice")
  243. def voice(
  244. request: Request, # fastapi自动注入
  245. text: str = Query(..., description="输入文字"),
  246. model_id: int = Query(..., description="模型ID"), # 模型序号
  247. speaker_name: str = Query(
  248. None, description="说话人名"
  249. ), # speaker_name与 speaker_id二者选其一
  250. speaker_id: int = Query(None, description="说话人id,与speaker_name二选一"),
  251. sdp_ratio: float = Query(0.2, description="SDP/DP混合比"),
  252. noise: float = Query(0.2, description="感情"),
  253. noisew: float = Query(0.9, description="音素长度"),
  254. length: float = Query(1, description="语速"),
  255. language: str = Query(None, description="语言"), # 若不指定使用语言则使用默认值
  256. auto_translate: bool = Query(False, description="自动翻译"),
  257. auto_split: bool = Query(False, description="自动切分"),
  258. ):
  259. """语音接口"""
  260. logger.info(
  261. f"{request.client.host}:{request.client.port}/voice { unquote(str(request.query_params) )}"
  262. )
  263. # 检查模型是否存在
  264. if model_id not in loaded_models.models.keys():
  265. return {"status": 10, "detail": f"模型model_id={model_id}未加载"}
  266. # 检查是否提供speaker
  267. if speaker_name is None and speaker_id is None:
  268. return {"status": 11, "detail": "请提供speaker_name或speaker_id"}
  269. elif speaker_name is None:
  270. # 检查speaker_id是否存在
  271. if speaker_id not in loaded_models.models[model_id].id2spk.keys():
  272. return {"status": 12, "detail": f"角色speaker_id={speaker_id}不存在"}
  273. speaker_name = loaded_models.models[model_id].id2spk[speaker_id]
  274. # 检查speaker_name是否存在
  275. if speaker_name not in loaded_models.models[model_id].spk2id.keys():
  276. return {"status": 13, "detail": f"角色speaker_name={speaker_name}不存在"}
  277. if language is None:
  278. language = loaded_models.models[model_id].language
  279. if auto_translate:
  280. text = trans.translate(Sentence=text, to_Language=language.lower())
  281. if not auto_split:
  282. with torch.no_grad():
  283. audio = infer(
  284. text=text,
  285. emotion=None,
  286. sdp_ratio=sdp_ratio,
  287. noise_scale=noise,
  288. noise_scale_w=noisew,
  289. length_scale=length,
  290. sid=speaker_name,
  291. language=language,
  292. hps=loaded_models.models[model_id].hps,
  293. net_g=loaded_models.models[model_id].net_g,
  294. device=loaded_models.models[model_id].device,
  295. )
  296. else:
  297. texts = cut_sent(text)
  298. audios = []
  299. with torch.no_grad():
  300. for t in texts:
  301. audios.append(
  302. infer(
  303. text=t,
  304. sdp_ratio=sdp_ratio,
  305. noise_scale=noise,
  306. noise_scale_w=noisew,
  307. length_scale=length,
  308. sid=speaker_name,
  309. language=language,
  310. hps=loaded_models.models[model_id].hps,
  311. net_g=loaded_models.models[model_id].net_g,
  312. device=loaded_models.models[model_id].device,
  313. )
  314. )
  315. audios.append(np.zeros((int)(44100 * 0.3)))
  316. audio = np.concatenate(audios)
  317. audio = gradio.processing_utils.convert_to_16_bit_wav(audio)
  318. wavContent = BytesIO()
  319. wavfile.write(
  320. wavContent, loaded_models.models[model_id].hps.data.sampling_rate, audio
  321. )
  322. response = Response(content=wavContent.getvalue(), media_type="audio/wav")
  323. return response
  324. @app.get("/models/info")
  325. def get_loaded_models_info(request: Request):
  326. """获取已加载模型信息"""
  327. result: Dict[str, Dict] = dict()
  328. for key, model in loaded_models.models.items():
  329. result[str(key)] = model.to_dict()
  330. return result
  331. @app.get("/models/delete")
  332. def delete_model(
  333. request: Request, model_id: int = Query(..., description="删除模型id")
  334. ):
  335. """删除指定模型"""
  336. logger.info(
  337. f"{request.client.host}:{request.client.port}/models/delete { unquote(str(request.query_params) )}"
  338. )
  339. result = loaded_models.del_model(model_id)
  340. if result is None:
  341. return {"status": 14, "detail": f"模型{model_id}不存在,删除失败"}
  342. return {"status": 0, "detail": "删除成功"}
  343. @app.get("/models/add")
  344. def add_model(
  345. request: Request,
  346. model_path: str = Query(..., description="添加模型路径"),
  347. config_path: str = Query(
  348. None, description="添加模型配置文件路径,不填则使用./config.json或../config.json"
  349. ),
  350. device: str = Query("cuda", description="推理使用设备"),
  351. language: str = Query("ZH", description="模型默认语言"),
  352. ):
  353. """添加指定模型:允许重复添加相同路径模型,且不重复占用内存"""
  354. logger.info(
  355. f"{request.client.host}:{request.client.port}/models/add { unquote(str(request.query_params) )}"
  356. )
  357. if config_path is None:
  358. model_dir = os.path.dirname(model_path)
  359. if os.path.isfile(os.path.join(model_dir, "config.json")):
  360. config_path = os.path.join(model_dir, "config.json")
  361. elif os.path.isfile(os.path.join(model_dir, "../config.json")):
  362. config_path = os.path.join(model_dir, "../config.json")
  363. else:
  364. return {
  365. "status": 15,
  366. "detail": "查询未传入配置文件路径,同时默认路径./与../中不存在配置文件config.json。",
  367. }
  368. try:
  369. model_id = loaded_models.init_model(
  370. config_path=config_path,
  371. model_path=model_path,
  372. device=device,
  373. language=language,
  374. )
  375. except Exception:
  376. logging.exception("模型加载出错")
  377. return {
  378. "status": 16,
  379. "detail": "模型加载出错,详细查看日志",
  380. }
  381. return {
  382. "status": 0,
  383. "detail": "模型添加成功",
  384. "Data": {
  385. "model_id": model_id,
  386. "model_info": loaded_models.models[model_id].to_dict(),
  387. },
  388. }
  389. def _get_all_models(root_dir: str = "Data", only_unloaded: bool = False):
  390. """从root_dir搜索获取所有可用模型"""
  391. result: Dict[str, List[str]] = dict()
  392. files = os.listdir(root_dir) + ["."]
  393. for file in files:
  394. if os.path.isdir(os.path.join(root_dir, file)):
  395. sub_dir = os.path.join(root_dir, file)
  396. # 搜索 "sub_dir" 、 "sub_dir/models" 两个路径
  397. result[file] = list()
  398. sub_files = os.listdir(sub_dir)
  399. model_files = []
  400. for sub_file in sub_files:
  401. relpath = os.path.realpath(os.path.join(sub_dir, sub_file))
  402. if only_unloaded and relpath in loaded_models.path2ids.keys():
  403. continue
  404. if sub_file.endswith(".pth") and sub_file.startswith("G_"):
  405. if os.path.isfile(relpath):
  406. model_files.append(sub_file)
  407. # 对模型文件按步数排序
  408. model_files = sorted(
  409. model_files,
  410. key=lambda pth: int(pth.lstrip("G_").rstrip(".pth"))
  411. if pth.lstrip("G_").rstrip(".pth").isdigit()
  412. else 10**10,
  413. )
  414. result[file] = model_files
  415. models_dir = os.path.join(sub_dir, "models")
  416. model_files = []
  417. if os.path.isdir(models_dir):
  418. sub_files = os.listdir(models_dir)
  419. for sub_file in sub_files:
  420. relpath = os.path.realpath(os.path.join(models_dir, sub_file))
  421. if only_unloaded and relpath in loaded_models.path2ids.keys():
  422. continue
  423. if sub_file.endswith(".pth") and sub_file.startswith("G_"):
  424. if os.path.isfile(os.path.join(models_dir, sub_file)):
  425. model_files.append(f"models/{sub_file}")
  426. # 对模型文件按步数排序
  427. model_files = sorted(
  428. model_files,
  429. key=lambda pth: int(pth.lstrip("models/G_").rstrip(".pth"))
  430. if pth.lstrip("models/G_").rstrip(".pth").isdigit()
  431. else 10**10,
  432. )
  433. result[file] += model_files
  434. if len(result[file]) == 0:
  435. result.pop(file)
  436. return result
  437. @app.get("/models/get_unloaded")
  438. def get_unloaded_models_info(
  439. request: Request, root_dir: str = Query("Data", description="搜索根目录")
  440. ):
  441. """获取未加载模型"""
  442. logger.info(
  443. f"{request.client.host}:{request.client.port}/models/get_unloaded { unquote(str(request.query_params) )}"
  444. )
  445. return _get_all_models(root_dir, only_unloaded=True)
  446. @app.get("/models/get_local")
  447. def get_local_models_info(
  448. request: Request, root_dir: str = Query("Data", description="搜索根目录")
  449. ):
  450. """获取全部本地模型"""
  451. logger.info(
  452. f"{request.client.host}:{request.client.port}/models/get_local { unquote(str(request.query_params) )}"
  453. )
  454. return _get_all_models(root_dir, only_unloaded=False)
  455. @app.get("/status")
  456. def get_status():
  457. """获取电脑运行状态"""
  458. cpu_percent = psutil.cpu_percent(interval=1)
  459. memory_info = psutil.virtual_memory()
  460. memory_total = memory_info.total
  461. memory_available = memory_info.available
  462. memory_used = memory_info.used
  463. memory_percent = memory_info.percent
  464. gpuInfo = []
  465. devices = ["cpu"]
  466. for i in range(torch.cuda.device_count()):
  467. devices.append(f"cuda:{i}")
  468. gpus = GPUtil.getGPUs()
  469. for gpu in gpus:
  470. gpuInfo.append(
  471. {
  472. "gpu_id": gpu.id,
  473. "gpu_load": gpu.load,
  474. "gpu_memory": {
  475. "total": gpu.memoryTotal,
  476. "used": gpu.memoryUsed,
  477. "free": gpu.memoryFree,
  478. },
  479. }
  480. )
  481. return {
  482. "devices": devices,
  483. "cpu_percent": cpu_percent,
  484. "memory_total": memory_total,
  485. "memory_available": memory_available,
  486. "memory_used": memory_used,
  487. "memory_percent": memory_percent,
  488. "gpu": gpuInfo,
  489. }
  490. @app.get("/tools/translate")
  491. def translate(
  492. request: Request,
  493. texts: str = Query(..., description="待翻译文本"),
  494. to_language: str = Query(..., description="翻译目标语言"),
  495. ):
  496. """翻译"""
  497. logger.info(
  498. f"{request.client.host}:{request.client.port}/tools/translate { unquote(str(request.query_params) )}"
  499. )
  500. return {"texts": trans.translate(Sentence=texts, to_Language=to_language)}
  501. all_examples: Dict[str, Dict[str, List]] = dict() # 存放示例
  502. @app.get("/tools/random_example")
  503. def random_example(
  504. request: Request,
  505. language: str = Query(None, description="指定语言,未指定则随机返回"),
  506. root_dir: str = Query("Data", description="搜索根目录"),
  507. ):
  508. """
  509. 获取一个随机音频+文本,用于对比,音频会从本地目录随机选择。
  510. """
  511. logger.info(
  512. f"{request.client.host}:{request.client.port}/tools/random_example { unquote(str(request.query_params) )}"
  513. )
  514. global all_examples
  515. # 数据初始化
  516. if root_dir not in all_examples.keys():
  517. all_examples[root_dir] = {"ZH": [], "JP": [], "EN": []}
  518. examples = all_examples[root_dir]
  519. # 从项目Data目录中搜索train/val.list
  520. for root, directories, _files in os.walk(root_dir):
  521. for file in _files:
  522. if file in ["train.list", "val.list"]:
  523. with open(
  524. os.path.join(root, file), mode="r", encoding="utf-8"
  525. ) as f:
  526. lines = f.readlines()
  527. for line in lines:
  528. data = line.split("|")
  529. if len(data) != 7:
  530. continue
  531. # 音频存在 且语言为ZH/EN/JP
  532. if os.path.isfile(data[0]) and data[2] in [
  533. "ZH",
  534. "JP",
  535. "EN",
  536. ]:
  537. examples[data[2]].append(
  538. {
  539. "text": data[3],
  540. "audio": data[0],
  541. "speaker": data[1],
  542. }
  543. )
  544. examples = all_examples[root_dir]
  545. if language is None:
  546. if len(examples["ZH"]) + len(examples["JP"]) + len(examples["EN"]) == 0:
  547. return {"status": 17, "detail": "没有加载任何示例数据"}
  548. else:
  549. # 随机选一个
  550. rand_num = random.randint(
  551. 0,
  552. len(examples["ZH"]) + len(examples["JP"]) + len(examples["EN"]) - 1,
  553. )
  554. # ZH
  555. if rand_num < len(examples["ZH"]):
  556. return {"status": 0, "Data": examples["ZH"][rand_num]}
  557. # JP
  558. if rand_num < len(examples["ZH"]) + len(examples["JP"]):
  559. return {
  560. "status": 0,
  561. "Data": examples["JP"][rand_num - len(examples["ZH"])],
  562. }
  563. # EN
  564. return {
  565. "status": 0,
  566. "Data": examples["EN"][
  567. rand_num - len(examples["ZH"]) - len(examples["JP"])
  568. ],
  569. }
  570. else:
  571. if len(examples[language]) == 0:
  572. return {"status": 17, "detail": f"没有加载任何{language}数据"}
  573. return {
  574. "status": 0,
  575. "Data": examples[language][
  576. random.randint(0, len(examples[language]) - 1)
  577. ],
  578. }
  579. @app.get("/tools/get_audio")
  580. def get_audio(request: Request, path: str = Query(..., description="本地音频路径")):
  581. logger.info(
  582. f"{request.client.host}:{request.client.port}/tools/get_audio { unquote(str(request.query_params) )}"
  583. )
  584. if not os.path.isfile(path):
  585. return {"status": 18, "detail": "指定音频不存在"}
  586. if not path.endswith(".wav"):
  587. return {"status": 19, "detail": "非wav格式文件"}
  588. return FileResponse(path=path)
  589. server_ip="1.1.1.1"
  590. logger.warning("本地服务,请勿将服务端口暴露于外网")
  591. logger.info(f"api文档地址 http://{server_ip}:{config.server_config.port}/docs")
  592. webbrowser.open(f"http://{server_ip}:{config.server_config.port}")
  593. uvicorn.run(
  594. app, port=config.server_config.port, host=server_ip, log_level="warning"
  595. )

这里代码很长,但我们只需要修改结尾处的 server_ip 即可。而真正对应推理的在代码的 import 处,我们可以查看目录下的 infer.py 内的 infer 函数关注具体的推理流程:

from infer import infer, get_net_g, latest_version

3.服务踩坑

◆ NLTK Not Found

我们需要到 NLTK 的官方 github 代码库下载,下载地址: https://github.com/nltk/nltk_data

下载后把 packages 文件夹更名为 nltk_data,放置到上面 Searched in 的任一个目录下即可。

◆ No Such File or Dir

server 代码需要建立一个默认的 Web 文件夹,否则会报错:

mkdir Web

◆ Missing Argument

  1. audio = infer(
  2. TypeError: infer() missing 1 required positional argument: 'emotion'

VITS2 社区的更新比较频繁,最近在 Infer 的参数中新增了 emotion 的参数,我们这里直接偷懒 Pass 了,传参为 None,如果大家有 emotion 的需求,也可以在 infer 相关代码里研究下:

三.服务使用

1.服务启动

nohup python server_fastapi.py > log 2>&1 &

直接后台启动即可,得到如下日志代表启动成功:

这里模型我们配置中保留最近的 8 个 Checkpoint, 可以尝试不同步数的 CK 填写的 config.yml:

2.服务调用

FastAPI 服务对应的 url 根据 server_fastapi.py 的 ip 和 config.yml 内的 port 决定:

url=${ip}:${port} => 1.1.1.1:9876

◆ Get Voice

修改下面的 URL 对应我们的 ip 与 port,随后 Http get,Params 需传入我们对应的角色以及音频的参数配置。

  1. #! /usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. import requests
  4. import datetime
  5. def get(typ, output, params={}):
  6. url = "http://$ip:$port"
  7. url_type = url + typ
  8. if params.keys() == 0:
  9. response = requests.get(url_type)
  10. else:
  11. response = requests.get(url_type, params=params)
  12. if response.status_code == 200:
  13. print('成功获取!')
  14. if typ == "/voice":
  15. with open(f'{output}.mp3', 'wb') as f: # 将音频文件写入到“目标音乐.mp3”中
  16. f.write(response.content)
  17. elif typ == "/models/info":
  18. data = response.text
  19. print("data:", data)
  20. else:
  21. print('请求失败,状态码:', response.status_code)

◆ Main

names 可以对照前面训练数据处理时传入的 person 名称,根据不同的 name,构建 json 调用 voice 接口,text 传文字,output 传音频输出地址。

  1. def getMp3(text, output):
  2. names = ["swk"]
  3. for name in names:
  4. prams = {
  5. 'model_id': 0,
  6. 'text': text,
  7. 'speaker_name': name,
  8. 'language': 'ZH',
  9. 'length': 1.0,
  10. 'sdp_ratio': 0.5,
  11. 'noise': 0.1
  12. }
  13. get("/voice", output=output, params=prams)
  14. if __name__ == '__main__':
  15. time_now = datetime.datetime.now().strftime("%Y%m%d%H%M")
  16. print(time_now)
  17. getMp3("妖孽,吃俺老孙一棒!", "swk")

3.服务结果

调用后得到我们对应 output 的 mp3 结果,这里无法上传语音,大家可以自行测试听听效果。由于是语音生成,难免存在一些噪声,大家有兴趣也可以在服务后面添加噪声处理的逻辑。

四.总结

结合上文的训练流程,我们现在实现了自定义语音的训练到推理到服务的完整链路。整体来说音色还是比较相似的,由于训练音频的原因 G 生成器生成的音频可能存在噪声,也可以在生成 mp3 后再进行一道去噪的流程,优化整体语音质量。

标签:
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

在线投稿:投稿 站长QQ:1888636

后台-插件-广告管理-内容页尾部广告(手机)
关注我们

扫一扫关注我们,了解最新精彩内容

搜索