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

30 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 

7import random 

8import time 

9from hashlib import sha1 

10from typing import TYPE_CHECKING, ClassVar 

11 

12from .base import MachineTranslation, MachineTranslationError 

13from .forms import KeySecretMachineryForm 

14 

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

16 from .base import DownloadTranslations 

17 

18NETEASE_API_ROOT = "https://jianwai.netease.com/api/text/trans" 

19 

20 

21class NeteaseSightTranslation(MachineTranslation): 

22 """Netease Sight API machine translation support.""" 

23 

24 name = "Netease Sight" 

25 max_score = 90 

26 

27 # Map codes used by Netease Sight to codes used by Weblate 

28 language_map: ClassVar[dict[str, str]] = {"zh_Hans": "zh"} 

29 settings_form = KeySecretMachineryForm 

30 

31 def download_languages(self): 

32 """List of supported languages.""" 

33 return ["zh", "en"] 

34 

35 def get_headers(self): 

36 """Add authentication headers to request.""" 

37 nonce = str(random.randint(1000, 99999999)) # noqa: S311 

38 timestamp = str(int(1000 * time.time())) 

39 

40 payload = self.settings["secret"] + nonce + timestamp 

41 signature = sha1(payload.encode(), usedforsecurity=False).hexdigest() 

42 

43 return { 

44 "Content-Type": "application/json", 

45 "appkey": self.settings["key"], 

46 "nonce": nonce, 

47 "timestamp": timestamp, 

48 "signature": signature, 

49 } 

50 

51 def download_translations( 

52 self, 

53 source_language, 

54 target_language, 

55 text: str, 

56 unit, 

57 user, 

58 threshold: int = 75, 

59 ) -> DownloadTranslations: 

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

61 response = self.request( 

62 "post", NETEASE_API_ROOT, json={"lang": target_language, "content": text} 

63 ) 

64 payload = response.json() 

65 

66 if not payload["success"]: 

67 raise MachineTranslationError(payload["message"]) 

68 

69 translation = payload["relatedObject"]["content"][0]["transContent"] 

70 

71 yield { 

72 "text": translation, 

73 "quality": self.max_score, 

74 "service": self.name, 

75 "source": text, 

76 }