From 221b45b4e6e9077290aa9bca1e37cd6a149d4c1a Mon Sep 17 00:00:00 2001 From: chliny Date: Sun, 11 May 2025 23:18:06 +0800 Subject: [PATCH] fix: add translate & fix bugs --- .gitignore | 2 + .../tencentcloud_asr/__init__.py | 5 +++ .../tencentcloud_asr/config_flow.py | 38 +++++++++---------- .../tencentcloud_asr/manifest.json | 2 +- custom_components/tencentcloud_asr/stt.py | 19 ++++++---- .../tencentcloud_asr/tencentcloud_api.py | 15 +++----- .../tencentcloud_asr/translations/en.json | 15 ++++++++ .../translations/zh-Hans.json | 15 ++++++++ 8 files changed, 73 insertions(+), 38 deletions(-) create mode 100644 .gitignore create mode 100644 custom_components/tencentcloud_asr/translations/en.json create mode 100644 custom_components/tencentcloud_asr/translations/zh-Hans.json diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..a07fd7c --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +__pycache__ +test.py diff --git a/custom_components/tencentcloud_asr/__init__.py b/custom_components/tencentcloud_asr/__init__.py index ed4d668..1db77a7 100644 --- a/custom_components/tencentcloud_asr/__init__.py +++ b/custom_components/tencentcloud_asr/__init__.py @@ -6,6 +6,11 @@ DOMAIN = "tencentcloud_asr" PLATFORMS = (Platform.STT,) +# const key +SecretIdKey = "secretid" +SecretKeyKey = "secretkey" +ModelKey = "model" + async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry): await hass.config_entries.async_forward_entry_setups(config_entry, PLATFORMS) diff --git a/custom_components/tencentcloud_asr/config_flow.py b/custom_components/tencentcloud_asr/config_flow.py index 7a2611c..74d9a3d 100644 --- a/custom_components/tencentcloud_asr/config_flow.py +++ b/custom_components/tencentcloud_asr/config_flow.py @@ -1,43 +1,39 @@ -import homeassistant.helpers.config_validation as cv import voluptuous as vol from homeassistant.config_entries import ConfigFlow, ConfigFlowResult from typing import Any, Dict -import aiohttp import logging -from tencentcloud_api import Modules +from .tencentcloud_api import Modules, DefaultModel +from .tencentcloud_api import TencentCloudAsrAPi +from . import SecretIdKey, SecretKeyKey, ModelKey + from . import DOMAIN _LOGGER = logging.getLogger(__name__) -async def validate_path(path: str) -> None: - - try: - async with aiohttp.ClientSession() as session: - async with session.get(path) as response: - _LOGGER.info(f'response.status {response.status}') - if response.status != 200: - raise ValueError - await response.text() - except Exception as e: - _LOGGER.error('validate_path', e) - raise ValueError - - class ConfigFlowHandler(ConfigFlow, domain=DOMAIN): async def async_step_user(self, user_input: dict[str, Any] | None = None) -> ConfigFlowResult: errors: Dict[str, str] = {} if user_input: - return self.async_create_entry(title=DOMAIN, data=user_input) + try: + secretId = user_input.get(SecretIdKey) + secretKey = user_input.get(SecretKeyKey) + TencentCloudAsrAPi(secretId, secretKey) + except Exception as err: + errors["base"] = str(err) + _LOGGER.error("check secret failed:%s", err) + + if not errors: + return self.async_create_entry(title=DOMAIN, data=user_input) return self.async_show_form( step_id="user", data_schema=vol.Schema( { - vol.Required("secretid"): str, - vol.Required("secretkey"): str, - vol.Optional("model", default="16k_zh"): vol.In(Modules.keys()), + vol.Required(SecretIdKey): str, + vol.Required(SecretKeyKey): str, + vol.Optional(ModelKey, default=DefaultModel): vol.In(Modules.keys()), }, ), errors=errors diff --git a/custom_components/tencentcloud_asr/manifest.json b/custom_components/tencentcloud_asr/manifest.json index 00ed837..20e601f 100644 --- a/custom_components/tencentcloud_asr/manifest.json +++ b/custom_components/tencentcloud_asr/manifest.json @@ -1,6 +1,6 @@ { "domain": "tencentcloud_asr", - "name": "TencnetCloud Asr", + "name": "TencnetCloud ASR", "codeowners": [ "@chliny" ], diff --git a/custom_components/tencentcloud_asr/stt.py b/custom_components/tencentcloud_asr/stt.py index 978f1b7..39a7287 100644 --- a/custom_components/tencentcloud_asr/stt.py +++ b/custom_components/tencentcloud_asr/stt.py @@ -1,13 +1,16 @@ import logging import base64 +from functools import partial from collections.abc import AsyncIterable from homeassistant.components import stt from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddEntitiesCallback -from tencentcloud_api import TencentCloudAsrAPi -from tencentcloud_api import ModuleSupportLanguage +from .tencentcloud_api import TencentCloudAsrAPi +from .tencentcloud_api import ModuleSupportLanguage +from .tencentcloud_api import DefaultModel +from . import SecretIdKey, SecretKeyKey, ModelKey _LOGGER = logging.getLogger(__name__) @@ -22,13 +25,15 @@ async def async_setup_entry( class ASRSTT(stt.SpeechToTextEntity): def __init__(self, hass: HomeAssistant, config_entry: ConfigEntry) -> None: - secretId = config_entry.data.get("secretid", "") - secretKey = config_entry.data.get("secretKey", "") + secretId = config_entry.data.get(SecretIdKey, "") + secretKey = config_entry.data.get(SecretKeyKey, "") self.tencentCloudApi = TencentCloudAsrAPi(secretId, secretKey) - self.model: str = config_entry.data.get("model", "16k_zh") + self.model: str = config_entry.data.get(ModelKey, DefaultModel) # self._attr_name = f"TencentCloud Asr id: ({secretId})" - self._attr_unique_id = f"{config_entry.entry_id[:7]}-tencentcloud-asr" + self._attr_unique_id = f"tencentcloud_asr_stt" + self._attr_name = f"TencentCloud Asr STT" + self.hass = hass @property def supported_languages(self) -> list[str]: @@ -65,7 +70,7 @@ class ASRSTT(stt.SpeechToTextEntity): data = base64.b64encode(audio).decode("utf8", "ignore").strip() _LOGGER.debug(f"process_audio_stream transcribe: {data}") - ret, result = self.tencentCloudApi.SentenceRecognition(self.model, data) + ret, result = await self.hass.async_add_executor_job(partial(self.tencentCloudApi.SentenceRecognition, self.model, data)) if not ret: return stt.SpeechResult(result, stt.SpeechResultState.ERROR) if not result: diff --git a/custom_components/tencentcloud_asr/tencentcloud_api.py b/custom_components/tencentcloud_asr/tencentcloud_api.py index d8fc016..26c094c 100644 --- a/custom_components/tencentcloud_asr/tencentcloud_api.py +++ b/custom_components/tencentcloud_asr/tencentcloud_api.py @@ -1,5 +1,5 @@ import logging -from homeassistant.components.stt import AudioFormats +from homeassistant.components.stt import AudioCodecs from tencentcloud.common import credential from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException from tencentcloud.asr.v20190614.asr_client import AsrClient @@ -24,23 +24,20 @@ ModuleSupportLanguage = { "16k_yue": ["yue"], "16k_zh_dialect": ["zh"], } +DefaultModel = "16k_zh" class TencentCloudAsrAPi(object): def __init__(self, secretId, secretKey): - try: - cred = credential.Credential(secretId, secretKey) - region = "" - self.asrClient = AsrClient(cred, region) - except TencentCloudSDKException as err: - _LOGGER.error("tencent cloud sdk err:%s", err.message) - raise err + cred = credential.Credential(secretId, secretKey) + region = "" + self.asrClient = AsrClient(cred, region) def SentenceRecognition(self, engSerViceType, data: str) -> (tuple[bool, str | None]): req = SentenceRecognitionRequest() req.EngSerViceType = engSerViceType req.SourceType = SentenceRecognitionSourceTypePost - req.VoiceFormat = AudioFormats.WAV + req.VoiceFormat = AudioCodecs.PCM req.ProjectId = 0 req.SubServiceType = 2 req.UsrAudioKey = "" diff --git a/custom_components/tencentcloud_asr/translations/en.json b/custom_components/tencentcloud_asr/translations/en.json new file mode 100644 index 0000000..613351e --- /dev/null +++ b/custom_components/tencentcloud_asr/translations/en.json @@ -0,0 +1,15 @@ +{ + "title": "tencent cloud asr service", + "config": { + "error": {}, + "step": { + "user": { + "data": { + "secretid": "tencentcloud asr secretid", + "secretkey": "tencnetcloud asr secretkey", + "model": "model" + } + } + } + } +} diff --git a/custom_components/tencentcloud_asr/translations/zh-Hans.json b/custom_components/tencentcloud_asr/translations/zh-Hans.json new file mode 100644 index 0000000..f1d306f --- /dev/null +++ b/custom_components/tencentcloud_asr/translations/zh-Hans.json @@ -0,0 +1,15 @@ +{ + "title": "腾讯云 ASR 服务", + "config": { + "error": {}, + "step": { + "user": { + "data": { + "secretid": "请输入腾讯云ASR服务secretid", + "secretkey": "请输入腾讯云ASR服务secretkey", + "model": "模型" + } + } + } + } +}