fix: add translate & fix bugs

This commit is contained in:
chliny
2025-05-11 23:18:06 +08:00
parent 9aedcabdcc
commit 221b45b4e6
8 changed files with 73 additions and 38 deletions
+2
View File
@@ -0,0 +1,2 @@
__pycache__
test.py
@@ -6,6 +6,11 @@ DOMAIN = "tencentcloud_asr"
PLATFORMS = (Platform.STT,) PLATFORMS = (Platform.STT,)
# const key
SecretIdKey = "secretid"
SecretKeyKey = "secretkey"
ModelKey = "model"
async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry): async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry):
await hass.config_entries.async_forward_entry_setups(config_entry, PLATFORMS) await hass.config_entries.async_forward_entry_setups(config_entry, PLATFORMS)
@@ -1,43 +1,39 @@
import homeassistant.helpers.config_validation as cv
import voluptuous as vol import voluptuous as vol
from homeassistant.config_entries import ConfigFlow, ConfigFlowResult from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
from typing import Any, Dict from typing import Any, Dict
import aiohttp
import logging 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 from . import DOMAIN
_LOGGER = logging.getLogger(__name__) _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): class ConfigFlowHandler(ConfigFlow, domain=DOMAIN):
async def async_step_user(self, user_input: dict[str, Any] | None = None) -> ConfigFlowResult: async def async_step_user(self, user_input: dict[str, Any] | None = None) -> ConfigFlowResult:
errors: Dict[str, str] = {} errors: Dict[str, str] = {}
if user_input: 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( return self.async_show_form(
step_id="user", step_id="user",
data_schema=vol.Schema( data_schema=vol.Schema(
{ {
vol.Required("secretid"): str, vol.Required(SecretIdKey): str,
vol.Required("secretkey"): str, vol.Required(SecretKeyKey): str,
vol.Optional("model", default="16k_zh"): vol.In(Modules.keys()), vol.Optional(ModelKey, default=DefaultModel): vol.In(Modules.keys()),
}, },
), ),
errors=errors errors=errors
@@ -1,6 +1,6 @@
{ {
"domain": "tencentcloud_asr", "domain": "tencentcloud_asr",
"name": "TencnetCloud Asr", "name": "TencnetCloud ASR",
"codeowners": [ "codeowners": [
"@chliny" "@chliny"
], ],
+12 -7
View File
@@ -1,13 +1,16 @@
import logging import logging
import base64 import base64
from functools import partial
from collections.abc import AsyncIterable from collections.abc import AsyncIterable
from homeassistant.components import stt from homeassistant.components import stt
from homeassistant.config_entries import ConfigEntry from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.entity_platform import AddEntitiesCallback
from tencentcloud_api import TencentCloudAsrAPi from .tencentcloud_api import TencentCloudAsrAPi
from tencentcloud_api import ModuleSupportLanguage from .tencentcloud_api import ModuleSupportLanguage
from .tencentcloud_api import DefaultModel
from . import SecretIdKey, SecretKeyKey, ModelKey
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
@@ -22,13 +25,15 @@ async def async_setup_entry(
class ASRSTT(stt.SpeechToTextEntity): class ASRSTT(stt.SpeechToTextEntity):
def __init__(self, hass: HomeAssistant, config_entry: ConfigEntry) -> None: def __init__(self, hass: HomeAssistant, config_entry: ConfigEntry) -> None:
secretId = config_entry.data.get("secretid", "") secretId = config_entry.data.get(SecretIdKey, "")
secretKey = config_entry.data.get("secretKey", "") secretKey = config_entry.data.get(SecretKeyKey, "")
self.tencentCloudApi = TencentCloudAsrAPi(secretId, secretKey) 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_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 @property
def supported_languages(self) -> list[str]: def supported_languages(self) -> list[str]:
@@ -65,7 +70,7 @@ class ASRSTT(stt.SpeechToTextEntity):
data = base64.b64encode(audio).decode("utf8", "ignore").strip() data = base64.b64encode(audio).decode("utf8", "ignore").strip()
_LOGGER.debug(f"process_audio_stream transcribe: {data}") _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: if not ret:
return stt.SpeechResult(result, stt.SpeechResultState.ERROR) return stt.SpeechResult(result, stt.SpeechResultState.ERROR)
if not result: if not result:
@@ -1,5 +1,5 @@
import logging import logging
from homeassistant.components.stt import AudioFormats from homeassistant.components.stt import AudioCodecs
from tencentcloud.common import credential from tencentcloud.common import credential
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.asr.v20190614.asr_client import AsrClient from tencentcloud.asr.v20190614.asr_client import AsrClient
@@ -24,23 +24,20 @@ ModuleSupportLanguage = {
"16k_yue": ["yue"], "16k_yue": ["yue"],
"16k_zh_dialect": ["zh"], "16k_zh_dialect": ["zh"],
} }
DefaultModel = "16k_zh"
class TencentCloudAsrAPi(object): class TencentCloudAsrAPi(object):
def __init__(self, secretId, secretKey): def __init__(self, secretId, secretKey):
try: cred = credential.Credential(secretId, secretKey)
cred = credential.Credential(secretId, secretKey) region = ""
region = "" self.asrClient = AsrClient(cred, region)
self.asrClient = AsrClient(cred, region)
except TencentCloudSDKException as err:
_LOGGER.error("tencent cloud sdk err:%s", err.message)
raise err
def SentenceRecognition(self, engSerViceType, data: str) -> (tuple[bool, str | None]): def SentenceRecognition(self, engSerViceType, data: str) -> (tuple[bool, str | None]):
req = SentenceRecognitionRequest() req = SentenceRecognitionRequest()
req.EngSerViceType = engSerViceType req.EngSerViceType = engSerViceType
req.SourceType = SentenceRecognitionSourceTypePost req.SourceType = SentenceRecognitionSourceTypePost
req.VoiceFormat = AudioFormats.WAV req.VoiceFormat = AudioCodecs.PCM
req.ProjectId = 0 req.ProjectId = 0
req.SubServiceType = 2 req.SubServiceType = 2
req.UsrAudioKey = "" req.UsrAudioKey = ""
@@ -0,0 +1,15 @@
{
"title": "tencent cloud asr service",
"config": {
"error": {},
"step": {
"user": {
"data": {
"secretid": "tencentcloud asr secretid",
"secretkey": "tencnetcloud asr secretkey",
"model": "model"
}
}
}
}
}
@@ -0,0 +1,15 @@
{
"title": "腾讯云 ASR 服务",
"config": {
"error": {},
"step": {
"user": {
"data": {
"secretid": "请输入腾讯云ASR服务secretid",
"secretkey": "请输入腾讯云ASR服务secretkey",
"model": "模型"
}
}
}
}
}