tti.py 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. # coding=utf-8
  2. from typing import Dict
  3. from django.utils.translation import gettext_lazy as _, gettext
  4. from common import forms
  5. from common.exception.app_exception import AppApiException
  6. from common.forms import BaseForm, TooltipLabel
  7. from models_provider.base_model_provider import BaseModelCredential, ValidCode
  8. from common.utils.logger import maxkb_logger
  9. class ZhiPuTTIModelParams(BaseForm):
  10. size = forms.SingleSelect(
  11. TooltipLabel(_('Image size'),
  12. _('Image size, only cogview-3-plus supports this parameter. Optional range: [1024x1024,768x1344,864x1152,1344x768,1152x864,1440x720,720x1440], the default is 1024x1024.')),
  13. required=True,
  14. default_value='1024x1024',
  15. option_list=[
  16. {'value': '1024x1024', 'label': '1024x1024'},
  17. {'value': '768x1344', 'label': '768x1344'},
  18. {'value': '864x1152', 'label': '864x1152'},
  19. {'value': '1344x768', 'label': '1344x768'},
  20. {'value': '1152x864', 'label': '1152x864'},
  21. {'value': '1440x720', 'label': '1440x720'},
  22. {'value': '720x1440', 'label': '720x1440'},
  23. ],
  24. text_field='label',
  25. value_field='value')
  26. class ZhiPuTextToImageModelCredential(BaseForm, BaseModelCredential):
  27. api_key = forms.PasswordInputField('API Key', required=True)
  28. def is_valid(self, model_type: str, model_name, model_credential: Dict[str, object], model_params, provider,
  29. raise_exception=False):
  30. model_type_list = provider.get_model_type_list()
  31. if not any(list(filter(lambda mt: mt.get('value') == model_type, model_type_list))):
  32. raise AppApiException(ValidCode.valid_error.value,
  33. gettext('{model_type} Model type is not supported').format(model_type=model_type))
  34. for key in ['api_key']:
  35. if key not in model_credential:
  36. if raise_exception:
  37. raise AppApiException(ValidCode.valid_error.value, gettext('{key} is required').format(key=key))
  38. else:
  39. return False
  40. try:
  41. model = provider.get_model(model_type, model_name, model_credential, **model_params)
  42. res = model.check_auth()
  43. except Exception as e:
  44. maxkb_logger.error(f'Exception: {e}', exc_info=True)
  45. if isinstance(e, AppApiException):
  46. raise e
  47. if raise_exception:
  48. raise AppApiException(ValidCode.valid_error.value,
  49. gettext(
  50. 'Verification failed, please check whether the parameters are correct: {error}').format(
  51. error=str(e)))
  52. else:
  53. return False
  54. return True
  55. def encryption_dict(self, model: Dict[str, object]):
  56. return {**model, 'api_key': super().encryption(model.get('api_key', ''))}
  57. def get_model_params_setting_form(self, model_name):
  58. return ZhiPuTTIModelParams()