Coverage for app/venv/lib/python3.14/site-packages/weblate/machinery/youdao.py: 50%

26 statements  

« prev     ^ index     » next       coverage.py v7.15.2, created at 2026-10-07 07:15 +0000

1# Copyright © Michal Čihař <michal@weblate.org> 

2# Copyright © Sun Zhigang <hzsunzhigang@corp.netease.com> 

3# 

4# SPDX-License-Identifier: GPL-3.0-or-later 

5from __future__ import annotations 

6 

7from typing import TYPE_CHECKING, ClassVar 

8 

9from .base import MachineTranslation, MachineTranslationError 

10from .forms import KeySecretMachineryForm 

11 

12if TYPE_CHECKING: 12 ↛ 13line 12 didn't jump to line 13 because the condition on line 12 was never true

13 from .base import DownloadTranslations 

14 

15YOUDAO_API_ROOT = "https://openapi.youdao.com/api" 

16 

17 

18class YoudaoTranslation(MachineTranslation): 

19 """Youdao Zhiyun API machine translation support.""" 

20 

21 name = "Youdao Zhiyun" 

22 max_score = 90 

23 

24 # Map codes used by Youdao to codes used by Weblate 

25 language_map: ClassVar[dict[str, str]] = { 

26 "zh_Hans": "zh-CHS", 

27 "zh": "zh-CHS", 

28 "en": "EN", 

29 } 

30 settings_form = KeySecretMachineryForm 

31 

32 def download_languages(self): 

33 """List of supported languages.""" 

34 return [ 

35 "zh-CHS", 

36 "ja", 

37 "EN", # Officially youdao uses uppercase for en 

38 "ko", 

39 "fr", 

40 "ru", 

41 "pt", 

42 "es", 

43 "vi", 

44 "de", 

45 "ar", 

46 "id", 

47 ] 

48 

49 def check_failure(self, response) -> None: 

50 super().check_failure(response) 

51 payload = response.json() 

52 if int(payload["errorCode"]) != 0: 

53 msg = "Error code: {}".format(payload["errorCode"]) 

54 raise MachineTranslationError(msg) 

55 

56 def download_translations( 

57 self, 

58 source_language, 

59 target_language, 

60 text: str, 

61 unit, 

62 user, 

63 threshold: int = 75, 

64 ) -> DownloadTranslations: 

65 """Download list of possible translations from a service.""" 

66 salt, sign = self.signed_salt( 

67 self.settings["key"], self.settings["secret"], text 

68 ) 

69 

70 response = self.request( 

71 "get", 

72 YOUDAO_API_ROOT, 

73 params={ 

74 "q": text, 

75 "_from": source_language, 

76 "to": target_language, 

77 "appKey": self.settings["key"], 

78 "salt": salt, 

79 "sign": sign, 

80 }, 

81 ) 

82 payload = response.json() 

83 

84 translation = payload["translation"][0] 

85 

86 yield { 

87 "text": translation, 

88 "quality": self.max_score, 

89 "service": self.name, 

90 "source": text, 

91 }