stt.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. # coding=utf-8
  2. from typing import Dict
  3. from django.utils.translation import gettext as _
  4. from common import forms
  5. from common.exception.app_exception import AppApiException
  6. from common.forms import BaseForm
  7. from models_provider.base_model_provider import BaseModelCredential, ValidCode
  8. from common.utils.logger import maxkb_logger
  9. class SiliconCloudSTTModelCredential(BaseForm, BaseModelCredential):
  10. api_base = forms.TextInputField('API URL', required=True)
  11. api_key = forms.PasswordInputField('API Key', required=True)
  12. def is_valid(self, model_type: str, model_name, model_credential: Dict[str, object], model_params, provider,
  13. raise_exception=False):
  14. model_type_list = provider.get_model_type_list()
  15. if not any(list(filter(lambda mt: mt.get('value') == model_type, model_type_list))):
  16. raise AppApiException(ValidCode.valid_error.value,
  17. _('{model_type} Model type is not supported').format(model_type=model_type))
  18. for key in ['api_base', 'api_key']:
  19. if key not in model_credential:
  20. if raise_exception:
  21. raise AppApiException(ValidCode.valid_error.value, _('{key} is required').format(key=key))
  22. else:
  23. return False
  24. try:
  25. model = provider.get_model(model_type, model_name, model_credential,**model_params)
  26. model.check_auth()
  27. except Exception as e:
  28. maxkb_logger.error(f'Exception: {e}', exc_info=True)
  29. if isinstance(e, AppApiException):
  30. raise e
  31. if raise_exception:
  32. raise AppApiException(ValidCode.valid_error.value,
  33. _('Verification failed, please check whether the parameters are correct: {error}').format(
  34. error=str(e)))
  35. else:
  36. return False
  37. return True
  38. def encryption_dict(self, model: Dict[str, object]):
  39. return {**model, 'api_key': super().encryption(model.get('api_key', ''))}
  40. def get_model_params_setting_form(self, model_name):
  41. pass