Skip to content

Commit 49f84df

Browse files
committed
feat: i18n
1 parent 86dafda commit 49f84df

24 files changed

+183
-154
lines changed

apps/common/auth/authenticate.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616

1717
from common.exception.app_exception import AppAuthenticationFailed, AppEmbedIdentityFailed, AppChatNumOutOfBoundsFailed, \
1818
ChatException, AppApiException
19-
19+
from django.utils.translation import gettext_lazy as _
2020
token_cache = cache.caches['token_cache']
2121

2222

@@ -59,19 +59,19 @@ def authenticate(self, request):
5959
auth = auth.replace('Bearer ', '')
6060
# 未认证
6161
if auth is None:
62-
raise AppAuthenticationFailed(1003, '未登录,请先登录')
62+
raise AppAuthenticationFailed(1003, _('Not logged in, please log in first'))
6363
try:
6464
token_details = TokenDetails(auth)
6565
for handle in handles:
6666
if handle.support(request, auth, token_details.get_token_details):
6767
return handle.handle(request, auth, token_details.get_token_details)
68-
raise AppAuthenticationFailed(1002, "身份验证信息不正确!非法用户")
68+
raise AppAuthenticationFailed(1002, _('Authentication information is incorrect! illegal user'))
6969
except Exception as e:
7070
traceback.format_exc()
7171
if isinstance(e, AppEmbedIdentityFailed) or isinstance(e, AppChatNumOutOfBoundsFailed) or isinstance(e,
7272
AppApiException):
7373
raise e
74-
raise AppAuthenticationFailed(1002, "身份验证信息不正确!非法用户")
74+
raise AppAuthenticationFailed(1002, _('Authentication information is incorrect! illegal user'))
7575

7676

7777
class TokenAuth(TokenAuthentication):
@@ -80,16 +80,16 @@ def authenticate(self, request):
8080
auth = request.META.get('HTTP_AUTHORIZATION')
8181
# 未认证
8282
if auth is None:
83-
raise AppAuthenticationFailed(1003, '未登录,请先登录')
83+
raise AppAuthenticationFailed(1003, _('Not logged in, please log in first'))
8484
try:
8585
token_details = TokenDetails(auth)
8686
for handle in handles:
8787
if handle.support(request, auth, token_details.get_token_details):
8888
return handle.handle(request, auth, token_details.get_token_details)
89-
raise AppAuthenticationFailed(1002, "身份验证信息不正确!非法用户")
89+
raise AppAuthenticationFailed(1002, _('Authentication information is incorrect! illegal user'))
9090
except Exception as e:
9191
traceback.format_exc()
9292
if isinstance(e, AppEmbedIdentityFailed) or isinstance(e, AppChatNumOutOfBoundsFailed) or isinstance(e,
9393
AppApiException):
9494
raise e
95-
raise AppAuthenticationFailed(1002, "身份验证信息不正确!非法用户")
95+
raise AppAuthenticationFailed(1002, _('Authentication information is incorrect! illegal user'))

apps/common/auth/authentication.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
from common.constants.permission_constants import ViewPermission, CompareConstants, RoleConstants, PermissionConstants, \
1212
Permission
1313
from common.exception.app_exception import AppUnauthorizedFailed
14-
14+
from django.utils.translation import gettext_lazy as _
1515

1616
def exist_permissions_by_permission_constants(user_permission: List[PermissionConstants],
1717
permission_list: List[PermissionConstants]):
@@ -91,7 +91,7 @@ def run(view, request, **kwargs):
9191
# 判断是否有权限
9292
if any(exit_list) if compare == CompareConstants.OR else all(exit_list):
9393
return func(view, request, **kwargs)
94-
raise AppUnauthorizedFailed(403, "没有权限访问")
94+
raise AppUnauthorizedFailed(403, _('No permission to access'))
9595

9696
return run
9797

apps/common/auth/handle/impl/application_key.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,15 +13,16 @@
1313
from common.constants.authentication_type import AuthenticationType
1414
from common.constants.permission_constants import Permission, Group, Operate, RoleConstants, Auth
1515
from common.exception.app_exception import AppAuthenticationFailed
16+
from django.utils.translation import gettext_lazy as _
1617

1718

1819
class ApplicationKey(AuthBaseHandle):
1920
def handle(self, request, token: str, get_token_details):
2021
application_api_key = QuerySet(ApplicationApiKey).filter(secret_key=token).first()
2122
if application_api_key is None:
22-
raise AppAuthenticationFailed(500, "secret_key 无效")
23+
raise AppAuthenticationFailed(500, _('Secret key is invalid'))
2324
if not application_api_key.is_active:
24-
raise AppAuthenticationFailed(500, "secret_key 无效")
25+
raise AppAuthenticationFailed(500, _('Secret key is invalid'))
2526
permission_list = [Permission(group=Group.APPLICATION,
2627
operate=Operate.USE,
2728
dynamic_tag=str(

apps/common/auth/handle/impl/public_access_token.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
from common.exception.app_exception import AppAuthenticationFailed, ChatException
1616
from common.models.db_model_manage import DBModelManage
1717
from common.util.common import password_encrypt
18-
18+
from django.utils.translation import gettext_lazy as _
1919

2020
class PublicAccessToken(AuthBaseHandle):
2121
def support(self, request, token: str, get_token_details):
@@ -45,13 +45,13 @@ def handle(self, request, token: str, get_token_details):
4545
if application_setting.authentication_value.get('type') != authentication.get(
4646
'type') or password_encrypt(
4747
application_setting.authentication_value.get('value')) != authentication.get('value'):
48-
raise ChatException(1002, "身份验证信息不正确")
48+
raise ChatException(1002, _('Authentication information is incorrect'))
4949
if application_access_token is None:
50-
raise AppAuthenticationFailed(1002, "身份验证信息不正确")
50+
raise AppAuthenticationFailed(1002, _('Authentication information is incorrect'))
5151
if not application_access_token.is_active:
52-
raise AppAuthenticationFailed(1002, "身份验证信息不正确")
52+
raise AppAuthenticationFailed(1002, _('Authentication information is incorrect'))
5353
if not application_access_token.access_token == auth_details.get('access_token'):
54-
raise AppAuthenticationFailed(1002, "身份验证信息不正确")
54+
raise AppAuthenticationFailed(1002, _('Authentication information is incorrect'))
5555

5656
return application_access_token.application.user, Auth(
5757
role_list=[RoleConstants.APPLICATION_ACCESS_TOKEN],

apps/common/auth/handle/impl/user_token.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
from django.core import cache
1818

1919
from users.models.user import get_user_dynamics_permission
20-
20+
from django.utils.translation import gettext_lazy as _
2121
token_cache = cache.caches['token_cache']
2222

2323

@@ -31,7 +31,7 @@ def support(self, request, token: str, get_token_details):
3131
def handle(self, request, token: str, get_token_details):
3232
cache_token = token_cache.get(token)
3333
if cache_token is None:
34-
raise AppAuthenticationFailed(1002, "登录过期")
34+
raise AppAuthenticationFailed(1002, _('Login expired'))
3535
auth_details = get_token_details()
3636
user = QuerySet(User).get(id=auth_details['id'])
3737
# 续期

apps/common/constants/exception_code_constants.py

Lines changed: 14 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
from enum import Enum
1010

1111
from common.exception.app_exception import AppApiException
12+
from django.utils.translation import gettext_lazy as _
1213

1314

1415
class ExceptionCodeConstantsValue:
@@ -27,13 +28,16 @@ def to_app_api_exception(self):
2728

2829

2930
class ExceptionCodeConstants(Enum):
30-
INCORRECT_USERNAME_AND_PASSWORD = ExceptionCodeConstantsValue(1000, "用户名或者密码不正确")
31-
NOT_AUTHENTICATION = ExceptionCodeConstantsValue(1001, "请先登录,并携带用户Token")
32-
EMAIL_SEND_ERROR = ExceptionCodeConstantsValue(1002, "邮件发送失败")
33-
EMAIL_FORMAT_ERROR = ExceptionCodeConstantsValue(1003, "邮箱格式错误")
34-
EMAIL_IS_EXIST = ExceptionCodeConstantsValue(1004, "邮箱已经被注册,请勿重复注册")
35-
EMAIL_IS_NOT_EXIST = ExceptionCodeConstantsValue(1005, "邮箱尚未注册,请先注册")
36-
CODE_ERROR = ExceptionCodeConstantsValue(1005, "验证码不正确,或者验证码过期")
37-
USERNAME_IS_EXIST = ExceptionCodeConstantsValue(1006, "用户名已被使用,请使用其他用户名")
38-
USERNAME_ERROR = ExceptionCodeConstantsValue(1006, "用户名不能为空,并且长度在6-20")
39-
PASSWORD_NOT_EQ_RE_PASSWORD = ExceptionCodeConstantsValue(1007, "密码与确认密码不一致")
31+
INCORRECT_USERNAME_AND_PASSWORD = ExceptionCodeConstantsValue(1000, _('The username or password is incorrect'))
32+
NOT_AUTHENTICATION = ExceptionCodeConstantsValue(1001, _('Please log in first and bring the user Token'))
33+
EMAIL_SEND_ERROR = ExceptionCodeConstantsValue(1002, _('Email sending failed'))
34+
EMAIL_FORMAT_ERROR = ExceptionCodeConstantsValue(1003, _('Email format error'))
35+
EMAIL_IS_EXIST = ExceptionCodeConstantsValue(1004, _('The email has been registered, please log in directly'))
36+
EMAIL_IS_NOT_EXIST = ExceptionCodeConstantsValue(1005, _('The email is not registered, please register first'))
37+
CODE_ERROR = ExceptionCodeConstantsValue(1005,
38+
_('The verification code is incorrect or the verification code has expired'))
39+
USERNAME_IS_EXIST = ExceptionCodeConstantsValue(1006, _('The username has been registered, please log in directly'))
40+
USERNAME_ERROR = ExceptionCodeConstantsValue(1006,
41+
_('The username cannot be empty and must be between 6 and 20 characters long.'))
42+
PASSWORD_NOT_EQ_RE_PASSWORD = ExceptionCodeConstantsValue(1007,
43+
_('Password and confirmation password are inconsistent'))

apps/common/constants/permission_constants.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
"""
88
from enum import Enum
99
from typing import List
10-
10+
from django.utils.translation import gettext_lazy as _
1111

1212
class Group(Enum):
1313
"""
@@ -58,10 +58,10 @@ def __init__(self, name: str, decs: str, group: RoleGroup):
5858

5959

6060
class RoleConstants(Enum):
61-
ADMIN = Role("管理员", "管理员,预制目前不会使用", RoleGroup.USER)
62-
USER = Role("用户", "用户所有权限", RoleGroup.USER)
63-
APPLICATION_ACCESS_TOKEN = Role("会话", "只拥有应用会话框接口权限", RoleGroup.APPLICATION_ACCESS_TOKEN),
64-
APPLICATION_KEY = Role("应用私钥", "应用私钥", RoleGroup.APPLICATION_KEY)
61+
ADMIN = Role(_("ADMIN"), _('Admin, prefabs are not currently used'), RoleGroup.USER)
62+
USER = Role(_("USER"), _('All user permissions'), RoleGroup.USER)
63+
APPLICATION_ACCESS_TOKEN = Role(_('chat'), _('Only has application dialog interface permissions'), RoleGroup.APPLICATION_ACCESS_TOKEN),
64+
APPLICATION_KEY = Role(_('Apply private key'), _('Apply private key'), RoleGroup.APPLICATION_KEY)
6565

6666

6767
class Permission:

apps/common/event/__init__.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
import setting.models
1010
from setting.models import Model
1111
from .listener_manage import *
12+
from django.utils.translation import gettext_lazy as _
1213

1314
update_document_status_sql = """
1415
UPDATE "public"."document"
@@ -19,5 +20,5 @@
1920
def run():
2021
# QuerySet(Document).filter(status__in=[Status.embedding, Status.queue_up]).update(**{'status': Status.error})
2122
QuerySet(Model).filter(status=setting.models.Status.DOWNLOAD).update(status=setting.models.Status.ERROR,
22-
meta={'message': "下载程序被中断,请重试"})
23+
meta={'message': _('The download process was interrupted, please try again')})
2324
update_execute(update_document_status_sql, [])

apps/common/event/listener_manage.py

Lines changed: 22 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@
2929
from dataset.models import Paragraph, Status, Document, ProblemParagraphMapping, TaskType, State
3030
from embedding.models import SourceType, SearchMode
3131
from smartdoc.conf import PROJECT_DIR
32+
from django.utils.translation import gettext_lazy as _
3233

3334
max_kb_error = logging.getLogger(__file__)
3435
max_kb = logging.getLogger(__file__)
@@ -90,11 +91,12 @@ def embedding_by_paragraph_list(paragraph_id_list, embedding_model: Embeddings):
9091
ListenerManagement.embedding_by_paragraph_data_list(data_list, paragraph_id_list=paragraph_id_list,
9192
embedding_model=embedding_model)
9293
except Exception as e:
93-
max_kb_error.error(f'查询向量数据:{paragraph_id_list}出现错误{str(e)}{traceback.format_exc()}')
94+
max_kb_error.error(_('Query vector data: {paragraph_id_list} error {error} {traceback}').format(
95+
paragraph_id_list=paragraph_id_list, error=str(e), traceback=traceback.format_exc()))
9496

9597
@staticmethod
9698
def embedding_by_paragraph_data_list(data_list, paragraph_id_list, embedding_model: Embeddings):
97-
max_kb.info(f'开始--->向量化段落:{paragraph_id_list}')
99+
max_kb.info(_('Start--->Embedding paragraph: {paragraph_id_list}').format(paragraph_id_list=paragraph_id_list))
98100
status = Status.success
99101
try:
100102
# 删除段落
@@ -106,11 +108,13 @@ def is_save_function():
106108
# 批量向量化
107109
VectorStore.get_embedding_vector().batch_save(data_list, embedding_model, is_save_function)
108110
except Exception as e:
109-
max_kb_error.error(f'向量化段落:{paragraph_id_list}出现错误{str(e)}{traceback.format_exc()}')
111+
max_kb_error.error(_('Vectorized paragraph: {paragraph_id_list} error {error} {traceback}').format(
112+
paragraph_id_list=paragraph_id_list, error=str(e), traceback=traceback.format_exc()))
110113
status = Status.error
111114
finally:
112115
QuerySet(Paragraph).filter(id__in=paragraph_id_list).update(**{'status': status})
113-
max_kb.info(f'结束--->向量化段落:{paragraph_id_list}')
116+
max_kb.info(
117+
_('End--->Embedding paragraph: {paragraph_id_list}').format(paragraph_id_list=paragraph_id_list))
114118

115119
@staticmethod
116120
def embedding_by_paragraph(paragraph_id, embedding_model: Embeddings):
@@ -119,7 +123,7 @@ def embedding_by_paragraph(paragraph_id, embedding_model: Embeddings):
119123
@param paragraph_id: 段落id
120124
@param embedding_model: 向量模型
121125
"""
122-
max_kb.info(f"开始--->向量化段落:{paragraph_id}")
126+
max_kb.info(_('Start--->Embedding paragraph: {paragraph_id}').format(paragraph_id=paragraph_id))
123127
# 更新到开始状态
124128
ListenerManagement.update_status(QuerySet(Paragraph).filter(id=paragraph_id), TaskType.EMBEDDING, State.STARTED)
125129
try:
@@ -144,11 +148,12 @@ def is_the_task_interrupted():
144148
ListenerManagement.update_status(QuerySet(Paragraph).filter(id=paragraph_id), TaskType.EMBEDDING,
145149
State.SUCCESS)
146150
except Exception as e:
147-
max_kb_error.error(f'向量化段落:{paragraph_id}出现错误{str(e)}{traceback.format_exc()}')
151+
max_kb_error.error(_('Vectorized paragraph: {paragraph_id} error {error} {traceback}').format(
152+
paragraph_id=paragraph_id, error=str(e), traceback=traceback.format_exc()))
148153
ListenerManagement.update_status(QuerySet(Paragraph).filter(id=paragraph_id), TaskType.EMBEDDING,
149154
State.FAILURE)
150155
finally:
151-
max_kb.info(f'结束--->向量化段落:{paragraph_id}')
156+
max_kb.info(_('End--->Embedding paragraph: {paragraph_id}').format(paragraph_id=paragraph_id))
152157

153158
@staticmethod
154159
def embedding_by_data_list(data_list: List, embedding_model: Embeddings):
@@ -259,7 +264,8 @@ def is_the_task_interrupted():
259264

260265
if is_the_task_interrupted():
261266
return
262-
max_kb.info(f"开始--->向量化文档:{document_id}")
267+
max_kb.info(_('Start--->Embedding document: {document_id}').format(document_id=document_id)
268+
)
263269
# 批量修改状态为PADDING
264270
ListenerManagement.update_status(QuerySet(Document).filter(id=document_id), TaskType.EMBEDDING,
265271
State.STARTED)
@@ -274,11 +280,12 @@ def is_the_task_interrupted():
274280
document_id)),
275281
is_the_task_interrupted)
276282
except Exception as e:
277-
max_kb_error.error(f'向量化文档:{document_id}出现错误{str(e)}{traceback.format_exc()}')
283+
max_kb_error.error(_('Vectorized document: {document_id} error {error} {traceback}').format(
284+
document_id=document_id, error=str(e), traceback=traceback.format_exc()))
278285
finally:
279286
ListenerManagement.post_update_document_status(document_id, TaskType.EMBEDDING)
280287
ListenerManagement.get_aggregation_document_status(document_id)()
281-
max_kb.info(f"结束--->向量化文档:{document_id}")
288+
max_kb.info(_('End--->Embedding document: {document_id}').format(document_id=document_id))
282289
un_lock('embedding' + str(document_id))
283290

284291
@staticmethod
@@ -289,17 +296,18 @@ def embedding_by_dataset(dataset_id, embedding_model: Embeddings):
289296
@param embedding_model 向量模型
290297
:return: None
291298
"""
292-
max_kb.info(f"开始--->向量化数据集:{dataset_id}")
299+
max_kb.info(_('Start--->Embedding dataset: {dataset_id}').format(dataset_id=dataset_id))
293300
try:
294301
ListenerManagement.delete_embedding_by_dataset(dataset_id)
295302
document_list = QuerySet(Document).filter(dataset_id=dataset_id)
296-
max_kb.info(f"数据集文档:{[d.name for d in document_list]}")
303+
max_kb.info(_('Start--->Embedding document: {document_list}').format(document_list=document_list))
297304
for document in document_list:
298305
ListenerManagement.embedding_by_document(document.id, embedding_model=embedding_model)
299306
except Exception as e:
300-
max_kb_error.error(f'向量化数据集:{dataset_id}出现错误{str(e)}{traceback.format_exc()}')
307+
max_kb_error.error(_('Vectorized dataset: {dataset_id} error {error} {traceback}').format(
308+
dataset_id=dataset_id, error=str(e), traceback=traceback.format_exc()))
301309
finally:
302-
max_kb.info(f"结束--->向量化数据集:{dataset_id}")
310+
max_kb.info(_('End--->Embedding dataset: {dataset_id}').format(dataset_id=dataset_id))
303311

304312
@staticmethod
305313
def delete_embedding_by_document(document_id):

apps/common/field/common.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
@desc:
88
"""
99
from rest_framework import serializers
10-
10+
from django.utils.translation import gettext_lazy as _
1111

1212
class ObjectField(serializers.Field):
1313
def __init__(self, model_type_list, **kwargs):
@@ -18,7 +18,7 @@ def to_internal_value(self, data):
1818
for model_type in self.model_type_list:
1919
if isinstance(data, model_type):
2020
return data
21-
self.fail('message类型错误', value=data)
21+
self.fail(_('Message type error'), value=data)
2222

2323
def to_representation(self, value):
2424
return value
@@ -31,7 +31,7 @@ def __init__(self, model_type, **kwargs):
3131

3232
def to_internal_value(self, data):
3333
if not isinstance(data, self.model_type):
34-
self.fail('message类型错误', value=data)
34+
self.fail(_('Message type error'), value=data)
3535
return data
3636

3737
def to_representation(self, value):
@@ -42,7 +42,7 @@ class FunctionField(serializers.Field):
4242

4343
def to_internal_value(self, data):
4444
if not callable(data):
45-
self.fail('不是一个函數', value=data)
45+
self.fail(_('not a function'), value=data)
4646
return data
4747

4848
def to_representation(self, value):

0 commit comments

Comments
 (0)