Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
78 changes: 78 additions & 0 deletions apps/locales/en_US/LC_MESSAGES/django.po
Original file line number Diff line number Diff line change
Expand Up @@ -8570,4 +8570,82 @@ msgid "Edit user authorization status of resource"
msgstr ""

msgid "Get user authorization status of resource by page"
msgstr ""

msgid "Obtain resource authorization list by page"
msgstr ""

msgid "Engine model type"
msgstr ""

msgid "If not passed, the default value is 16k_zh (Chinese universal)"
msgstr ""

msgid "Chinese telephone universal"
msgstr ""

msgid "English telephone universal"
msgstr ""

msgid "Commonly used in Chinese"
msgstr ""

msgid "Chinese, English, and Guangdong"
msgstr ""

msgid "Chinese medical"
msgstr ""

msgid "English"
msgstr ""

msgid "Cantonese"
msgstr ""

msgid "Japanese"
msgstr ""

msgid "Korean"
msgstr ""

msgid "Vietnamese"
msgstr ""

msgid "Malay language"
msgstr ""

msgid "Indonesian language"
msgstr ""

msgid "Filipino language"
msgstr ""

msgid "Thai"
msgstr ""

msgid "Portuguese"
msgstr ""

msgid "Turkish"
msgstr ""

msgid "Arabic"
msgstr ""

msgid "Spanish"
msgstr ""

msgid "Hindi"
msgstr ""

msgid "French"
msgstr ""

msgid "German"
msgstr ""

msgid "Multiple dialects, supporting 23 dialects"
msgstr ""

msgid "This interface is used to recognize short audio files within 60 seconds. Supports Mandarin Chinese, English, Cantonese, Japanese, Vietnamese, Malay, Indonesian, Filipino, Thai, Portuguese, Turkish, Arabic, Hindi, French, German, and 23 Chinese dialects."
msgstr ""
80 changes: 79 additions & 1 deletion apps/locales/zh_CN/LC_MESSAGES/django.po
Original file line number Diff line number Diff line change
Expand Up @@ -8696,4 +8696,82 @@ msgid "Edit user authorization status of resource"
msgstr "修改资源对用户的授权状态"

msgid "Get user authorization status of resource by page"
msgstr "分页获取资源对用户的授权状态"
msgstr "分页获取资源对用户的授权状态"

msgid "Obtain resource authorization list by page"
msgstr "分页获取资源授权列表"

msgid "Engine model type"
msgstr "引擎模型类型"

msgid "If not passed, the default value is 16k_zh (Chinese universal)"
msgstr "如果未传递,默认值为 16k_zh(中文通用)"

msgid "Chinese telephone universal"
msgstr "中文电话通用"

msgid "English telephone universal"
msgstr "英文电话通用"

msgid "Commonly used in Chinese"
msgstr "中文常用"

msgid "Chinese, English, and Guangdong"
msgstr "中文、英文和广东话"

msgid "Chinese medical"
msgstr "中文医疗"

msgid "English"
msgstr "英文"

msgid "Cantonese"
msgstr "粤语"

msgid "Japanese"
msgstr "日语"

msgid "Korean"
msgstr "韩语"

msgid "Vietnamese"
msgstr "越南语"

msgid "Malay language"
msgstr "马来语"

msgid "Indonesian language"
msgstr "印尼语"

msgid "Filipino language"
msgstr "菲律宾语"

msgid "Thai"
msgstr "泰语"

msgid "Portuguese"
msgstr "葡萄牙语"

msgid "Turkish"
msgstr "土耳其语"

msgid "Arabic"
msgstr "阿拉伯语"

msgid "Spanish"
msgstr "西班牙语"

msgid "Hindi"
msgstr "印地语"

msgid "French"
msgstr "法语"

msgid "German"
msgstr "德语"

msgid "Multiple dialects, supporting 23 dialects"
msgstr "多种方言,支持 23 种方言"

msgid "This interface is used to recognize short audio files within 60 seconds. Supports Mandarin Chinese, English, Cantonese, Japanese, Vietnamese, Malay, Indonesian, Filipino, Thai, Portuguese, Turkish, Arabic, Hindi, French, German, and 23 Chinese dialects."
msgstr "本接口用于识别 60 秒之内的短音频文件。支持中文普通话、英语、粤语、日语、越南语、马来语、印度尼西亚语、菲律宾语、泰语、葡萄牙语、土耳其语、阿拉伯语、印地语、法语、德语及 23 种汉语方言。"
80 changes: 79 additions & 1 deletion apps/locales/zh_Hant/LC_MESSAGES/django.po
Original file line number Diff line number Diff line change
Expand Up @@ -8696,4 +8696,82 @@ msgid "Edit user authorization status of resource"
msgstr "修改資源對用戶的授權狀態"

msgid "Get user authorization status of resource by page"
msgstr "分頁獲取資源對用戶的授權狀態"
msgstr "分頁獲取資源對用戶的授權狀態"

msgid "Obtain resource authorization list by page"
msgstr "分頁獲取資源授權清單"

msgid "Engine model type"
msgstr "引擎模型類型"

msgid "If not passed, the default value is 16k_zh (Chinese universal)"
msgstr "如果未傳遞,默認值為 16k_zh(中文通用)"

msgid "Chinese telephone universal"
msgstr "中文電話通用"

msgid "English telephone universal"
msgstr "英文電話通用"

msgid "Commonly used in Chinese"
msgstr "中文常用"

msgid "Chinese, English, and Guangdong"
msgstr "中文、英文和廣東話"

msgid "Chinese medical"
msgstr "中文醫療"

msgid "English"
msgstr "英文"

msgid "Cantonese"
msgstr "粵語"

msgid "Japanese"
msgstr "日語"

msgid "Korean"
msgstr "韓語"

msgid "Vietnamese"
msgstr "越南語"

msgid "Malay language"
msgstr "馬來語"

msgid "Indonesian language"
msgstr "印尼語"

msgid "Filipino language"
msgstr "菲律賓語"

msgid "Thai"
msgstr "泰語"

msgid "Portuguese"
msgstr "葡萄牙語"

msgid "Turkish"
msgstr "土耳其語"

msgid "Arabic"
msgstr "阿拉伯語"

msgid "Spanish"
msgstr "西班牙語"

msgid "Hindi"
msgstr "印地語"

msgid "French"
msgstr "法語"

msgid "German"
msgstr "德語"

msgid "Multiple dialects, supporting 23 dialects"
msgstr "多種方言,支持 23 種方言"

msgid "This interface is used to recognize short audio files within 60 seconds. Supports Mandarin Chinese, English, Cantonese, Japanese, Vietnamese, Malay, Indonesian, Filipino, Thai, Portuguese, Turkish, Arabic, Hindi, French, German, and 23 Chinese dialects."
msgstr "本介面用於識別 60 秒之內的短音頻文件。支援中文普通話、英語、粵語、日語、越南語、馬來語、印度尼西亞語、菲律賓語、泰語、葡萄牙語、土耳其語、阿拉伯語、印地語、法語、德語及 23 種漢語方言。"
90 changes: 90 additions & 0 deletions apps/models_provider/impl/tencent_model_provider/credential/stt.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
import traceback

from common import forms
from common.exception.app_exception import AppApiException
from common.forms import BaseForm, TooltipLabel
from django.utils.translation import gettext_lazy as _, gettext

from models_provider.base_model_provider import BaseModelCredential, ValidCode


class TencentSSTModelParams(BaseForm):
EngSerViceType = forms.SingleSelect(
TooltipLabel(_('Engine model type'), _('If not passed, the default value is 16k_zh (Chinese universal)')),
required=True,
default_value='16k_zh',
option_list=[
{"value": "8k_zh", "label": _("Chinese telephone universal")},
{"value": "8k_en", "label": _("English telephone universal")},
{"value": "16k_zh", "label": _("Commonly used in Chinese")},
{"value": "16k_zh-PY", "label": _("Chinese, English, and Guangdong")},
{"value": "16k_zh_medical", "label": _("Chinese medical")},
{"value": "16k_en", "label": _("English")},
{"value": "16k_yue", "label": _("Cantonese")},
{"value": "16k_ja", "label": _("Japanese")},
{"value": "16k_ko", "label": _("Korean")},
{"value": "16k_vi", "label": _("Vietnamese")},
{"value": "16k_ms", "label": _("Malay language")},
{"value": "16k_id", "label": _("Indonesian language")},
{"value": "16k_fil", "label": _("Filipino language")},
{"value": "16k_th", "label": _("Thai")},
{"value": "16k_pt", "label": _("Portuguese")},
{"value": "16k_tr", "label": _("Turkish")},
{"value": "16k_ar", "label": _("Arabic")},
{"value": "16k_es", "label": _("Spanish")},
{"value": "16k_hi", "label": _("Hindi")},
{"value": "16k_fr", "label": _("French")},
{"value": "16k_de", "label": _("German")},
{"value": "16k_zh_dialect", "label": _("Multiple dialects, supporting 23 dialects")}
],
value_field='value',
text_field='label'
)

class TencentSTTModelCredential(BaseForm, BaseModelCredential):
REQUIRED_FIELDS = ["SecretId", "SecretKey"]

@classmethod
def _validate_model_type(cls, model_type, provider, raise_exception=False):
if not any(mt['value'] == model_type for mt in provider.get_model_type_list()):
if raise_exception:
raise AppApiException(ValidCode.valid_error.value,
gettext('{model_type} Model type is not supported').format(model_type=model_type))
return False
return True

@classmethod
def _validate_credential_fields(cls, model_credential, raise_exception=False):
missing_keys = [key for key in cls.REQUIRED_FIELDS if key not in model_credential]
if missing_keys:
if raise_exception:
raise AppApiException(ValidCode.valid_error.value,
gettext('{keys} is required').format(keys=", ".join(missing_keys)))
return False
return True

def is_valid(self, model_type, model_name, model_credential, model_params, provider, raise_exception=False):
if not (self._validate_model_type(model_type, provider, raise_exception) and
self._validate_credential_fields(model_credential, raise_exception)):
return False
try:
model = provider.get_model(model_type, model_name, model_credential, **model_params)
model.check_auth()
except Exception as e:
traceback.print_exc()
if raise_exception:
raise AppApiException(ValidCode.valid_error.value,
gettext(
'Verification failed, please check whether the parameters are correct: {error}').format(
error=str(e)))
return False
return True

def encryption_dict(self, model):
return {**model, 'SecretKey': super().encryption(model.get('SecretKey', ''))}

SecretId = forms.PasswordInputField('SecretId', required=True)
SecretKey = forms.PasswordInputField('SecretKey', required=True)

def get_model_params_setting_form(self, model_name):
return TencentSSTModelParams()
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The provided code looks mostly clean and well-structured, but there are a few suggestions for optimization and improvement:

  1. Comments: While comments can help clarify complex parts of the code, they should be concise and relevant to the functionality being described. You might want to remove comments that do not add significant explanation.

  2. Redundant gettext Calls: The method _validate_model_type calls gettext multiple times unnecessarily inside its body. Consider creating a helper function to handle localized strings and call it once at the start instead.

  3. Exception Handling in Model Initialization: In the __init__ method (if this is present), you might consider wrapping exception handling around the initialization of parent classes to ensure robustness. This is optional based on the context.

  4. Unused Methods: Ensure that all methods are necessary and contribute to the overall functionality. If methods like _validate_model_type are never called after creation, they may be candidates for removal or refactoring into utility functions.

  5. Field Validation Logic: There's no explicit validation logic for fields within each form field. However, assuming these fields have default values, ensuring valid data types or ranges would improve robustness.

Here’s an optimized version of your code with some minor adjustments:

import traceback

from common import forms
from common.exception.app_exception import AppApiException
from models_provider.base_model_provider import BaseModelCredential, ValidCode

ENG_SERVICE_TYPE_OPTIONS = [
    ("8k_zh", "Chinese telephone universal"),
    # ... other options ...
]

class TencentSSTModelParams(BaseForm):
    EngSerViceType = forms.SingleSelect(
        tooltip_label=_('Engine model type'),
        required=True,
        default_value='16k_zh',
        option_list=ENG_SERVE_TYPE_OPTIONS,
        value_field='value',
        text_field='label'
    )

def is_valid_model_type(model_type, provider_types):
    """Check if the model type is supported by the provider."""
    return any(type_["value"] == model_type for type_ in provider_types)

class TencentSTTModelCredential(BaseForm, BaseModelCredential):
    REQUIRED_FIELDS = ["SecretId", "SecretKey"]

    @classmethod
    def validate_credential_fields(cls, credentials, raise_exception=False):
        """Validate the presence of required credential fields."""
        missing_keys = [key for key in cls.REQUIRED_FIELDS if key not in credentials]
        if missing_keys:
            msg = gettext('{keys} is required')
            raise AppApiException(ValidCode.valid_error.value, msg.format(keys=", ".join(missing_keys)))

    def __init__(self, secret_id=None, secret_key=None):
        """Initialize with encrypted Secret keys."""
        super().__init__
        self.secret_id = secret_id
        self.secret_key = secret_key

    def encrypt_dictionary(self):
        """Return a dictionary of encryptions."""
        return {"SecretId": self.encrypt_secret_id(), "SecretKey": self.encrypt_secret_key()}

    def encrypt_secret_id(self):
        """Encrypt the secret ID."""
        if self.secret_id:
            return self.encryption_function(self.secret_id)
        return ""

    def encrypt_secret_key(self):
        """Encrypt the secret key."""
        if self.secret_key:
            return self.encryption_function(self.secret_key)
        return ""

    def is_valid(self, model_type, model_name, model_credential, model_params, provider):
        """Verify model configuration against constraints."""
        try:
            credentials_validated = self.validate_credential_fields(model_credentials)
            model_type_validated = is_valid_model_type(model_type, provider.model_types())
            if not (credentials_validated and model_type_validated):
                return False
            model_instance = provider.get_model(model_type, model_name, creds=model_credential, **model_params)
            model_instance.check_auth()
        except Exception as e:
            traceback.print_exc()
            if raise_exception:
                error_message = gettext(
                    'Verification failed, please check whether the parameters are correct: {error}')
                raise AppApiException(ValidCode.valid_error.value, error_message.format(error=str(e)))
            return False
        return True

    SecretId = forms.PasswordInputField('SecretId', required=True)
    SecretKey = forms.PasswordInputField('SecretKey', required=True)

    def get_model_params_settings_form(self, model_name):
        """Retrieve the settings form for model parameters."""
        return TencentSSTModelParams()

# Example usage:
credential = TencentSTTModelCredential(secret_id="your-secret-id", secret_key="encrypted-secret-key")
provider = SomeModelProvider()  # Replace with actual provider instance
form = TencentSSTModelParams()
params = {
    # Add model parameter mappings here
}

result = credential.is_valid("your-model-type", "default", params, provider, raise_exception=True) if result else None

This revised version aims to simplify repeated operations such as validating fields and improving readability through the use of more descriptive variable names and function definitions where applicable.

Binary file not shown.
Loading
Loading