from cmdbox.app import common, client, feature
from cmdbox.app.commons import cache, convert, redis_client, resdata, validator
from cmdbox.app.options import Options
from cmdbox.app.features.cli import cmdbox_tts_say
from pathlib import Path
from typing import Dict, Any, Tuple, List, Union
import argparse
import logging
import pydantic
[docs]
class TtsList(feature.UnsupportEdgeFeature, validator.Validator):
[docs]
def get_mode(self) -> Union[str, List[str]]:
"""
この機能のモードを返します
Returns:
Union[str, List[str]]: モード
"""
return 'tts'
[docs]
def get_cmd(self):
"""
この機能のコマンドを返します
Returns:
str: コマンド
"""
return 'list'
[docs]
def get_option(self):
"""
この機能のオプションを返します
Returns:
Dict[str, Any]: オプション
"""
return dict(
use_redis=self.USE_REDIS_MEIGHT, nouse_webmode=False, use_agent=True,
description_ja="Text-to-Speech(TTS)エンジンのリストを取得します。",
description_en="Lists the Text-to-Speech (TTS) engines.",
choice=[
dict(opt="host", type=Options.T_STR, default=self.default_host, required=True, multi=False, hide=True, choice=None, web="mask",
description_ja="Redisサーバーのサービスホストを指定します。",
description_en="Specify the service host of the Redis server."),
dict(opt="port", type=Options.T_INT, default=self.default_port, required=True, multi=False, hide=True, choice=None, web="mask",
description_ja="Redisサーバーのサービスポートを指定します。",
description_en="Specify the service port of the Redis server."),
dict(opt="password", type=Options.T_PASSWD, default=self.default_pass, required=True, multi=False, hide=True, choice=None, web="mask",
description_ja=f"Redisサーバーのアクセスパスワード(任意)を指定します。省略時は `{self.default_pass}` を使用します。",
description_en=f"Specify the access password of the Redis server (optional). If omitted, `{self.default_pass}` is used."),
dict(opt="svname", type=Options.T_STR, default=self.default_svname, required=True, multi=False, hide=True, choice=None, web="readonly",
description_ja="サーバーのサービス名を指定します。省略時は `server` を使用します。",
description_en="Specify the service name of the inference server. If omitted, `server` is used."),
dict(opt="retry_count", type=Options.T_INT, default=3, required=False, multi=False, hide=True, choice=None,
description_ja="Redisサーバーへの再接続回数を指定します。0以下を指定すると永遠に再接続を行います。",
description_en="Specifies the number of reconnections to the Redis server.If less than 0 is specified, reconnection is forever."),
dict(opt="retry_interval", type=Options.T_INT, default=5, required=False, multi=False, hide=True, choice=None,
description_ja="Redisサーバーに再接続までの秒数を指定します。",
description_en="Specifies the number of seconds before reconnecting to the Redis server."),
dict(opt="timeout", type=Options.T_INT, default="60", required=False, multi=False, hide=True, choice=None,
description_ja="サーバーの応答が返ってくるまでの最大待ち時間を指定。",
description_en="Specify the maximum waiting time until the server responds."),
dict(opt="tts_engine", type=Options.T_STR, default="voicevox", required=True, multi=False, hide=False,
choice=["", "voicevox"],
description_ja="使用するTTSエンジンを指定します。",
description_en="Specify the TTS engine to use."),
]
)
@cache.async_apprun_cache
@validator.async_apprun_check
async def apprun(self, logger:logging.Logger, args:argparse.Namespace, tm:float, pf:List[Dict[str, float]]=[]) -> Tuple[int, Dict[str, Any], Any]:
"""
この機能の実行を行います
Args:
logger (logging.Logger): ロガー
args (argparse.Namespace): 引数
tm (float): 実行開始時間
pf (List[Dict[str, float]]): 呼出元のパフォーマンス情報
Returns:
Tuple[int, Dict[str, Any], Any]: 終了コード, 結果, オブジェクト
"""
tts_engine_b64 = convert.str2b64str(args.tts_engine)
cl = client.Client(logger, redis_host=args.host, redis_port=args.port, redis_password=args.password, svname=args.svname)
ret = await cl.redis_cli.asend_cmd(self.get_svcmd(), [tts_engine_b64],
retry_count=args.retry_count, retry_interval=args.retry_interval, timeout=args.timeout, nowait=False)
common.print_format(ret, False, tm, pf=pf)
if 'success' not in ret:
return self.RESP_WARN, ret, None
return self.RESP_SUCCESS, ret, None
[docs]
def output_schema(self) -> type:
class TtsRecord(resdata.Base):
engine: Union[str, None] = pydantic.Field(default=None, description="TTSエンジン名")
model: Union[str, None] = pydantic.Field(default=None, description="モデル名")
character: Union[str, None] = pydantic.Field(default=None, description="キャラクター名")
style: Union[str, None] = pydantic.Field(default=None, description="スタイル名")
class Data(resdata.Data):
data: Union[List[TtsRecord], None] = pydantic.Field(default=None, description="処理結果のデータ")
class Result(resdata.Result):
error: Union[str, None] = pydantic.Field(default=None, description="エラーが発生した場合の結果")
success: Union[Data, None] = pydantic.Field(default=None, description="成功した場合の結果")
return Result
[docs]
def is_cluster_redirect(self):
"""
クラスター宛のメッセージの場合、メッセージを転送するかどうかを返します
Returns:
bool: メッセージを転送する場合はTrue
"""
return False
[docs]
def svrun(self, data_dir:Path, logger:logging.Logger, redis_cli:redis_client.RedisClient, msg:List[str],
sessions:Dict[str, Dict[str, Any]]) -> int:
"""
この機能のサーバー側の実行を行います
Args:
data_dir (Path): データディレクトリ
logger (logging.Logger): ロガー
redis_cli (redis_client.RedisClient): Redisクライアント
msg (List[str]): 受信メッセージ
sessions (Dict[str, Dict[str, Any]]): セッション情報
Returns:
int: 終了コード
"""
tts_engine = convert.b64str2str(msg[2])
try:
if tts_engine == 'voicevox':
from voicevox_core.blocking import Onnxruntime, OpenJtalk, Synthesizer, VoiceModelFile
result = []
for key, val in cmdbox_tts_say.TtsSay.VOICEVOX_STYLE.items():
result.append(dict(
engine='voicevox',
model=val['select'],
character=val['ch'],
style=val['md']
))
ret = dict(success=result)
redis_cli.rpush(msg[1], ret)
except ModuleNotFoundError as e:
logger.error(f"TTS List svrun module not found error: {e}")
ret = dict(error=f"VoiceVox engine is not installed. Please install it using the '{self.ver.__appid__} -m tts -c install' command.")
redis_cli.rpush(msg[1], ret)
return self.RESP_WARN
except Exception as e:
logger.error(f"TTS List svrun error: {e}")
ret = dict(error=str(e))
redis_cli.rpush(msg[1], ret)
return self.RESP_WARN
return self.RESP_SUCCESS