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

39 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# 

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

4from __future__ import annotations 

5 

6from typing import TYPE_CHECKING 

7 

8from .base import ResponseStatusMachineTranslation 

9from .forms import MyMemoryMachineryForm 

10 

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

12 from .base import DownloadTranslations 

13 

14 

15class MyMemoryTranslation(ResponseStatusMachineTranslation): 

16 """MyMemory machine translation support.""" 

17 

18 name = "MyMemory" 

19 do_cleanup = False 

20 settings_form = MyMemoryMachineryForm 

21 

22 def map_language_code(self, code): 

23 """Convert language to service specific code.""" 

24 return super().map_language_code(code).replace("_", "-") 

25 

26 def is_supported(self, source_language, target_language): 

27 """Check whether given language combination is supported.""" 

28 return ( 

29 self.lang_supported(source_language) 

30 and self.lang_supported(target_language) 

31 and source_language != target_language 

32 ) 

33 

34 @staticmethod 

35 def lang_supported(language): 

36 """Almost any language without modifiers is supported.""" 

37 if language in {"ia", "tt", "ug"}: 

38 return False 

39 return "@" not in language 

40 

41 def format_match(self, match): 

42 """Reformat match to (translation, quality) tuple.""" 

43 result = { 

44 "text": match["translation"], 

45 "quality": int(100 * match["match"]), 

46 "service": self.name, 

47 "source": match["segment"], 

48 } 

49 

50 if match["last-updated-by"]: 

51 result["origin"] = match["last-updated-by"] 

52 

53 if match["reference"]: 

54 result["origin_detail"] = match["reference"] 

55 

56 return result 

57 

58 def download_translations( 

59 self, 

60 source_language, 

61 target_language, 

62 text: str, 

63 unit, 

64 user, 

65 threshold: int = 75, 

66 ) -> DownloadTranslations: 

67 """Download list of possible translations from MyMemory.""" 

68 args = { 

69 "q": text.split(". ", 1)[0][:500], 

70 "langpair": f"{source_language}|{target_language}", 

71 } 

72 if self.settings["email"]: 

73 args["de"] = self.settings["email"] 

74 if self.settings["username"]: 

75 args["user"] = self.settings["username"] 

76 if self.settings["key"]: 

77 args["key"] = self.settings["key"] 

78 

79 response = self.request( 

80 "get", "https://mymemory.translated.net/api/get", params=args 

81 ).json() 

82 for match in response["matches"]: 

83 result = self.format_match(match) 

84 if result["quality"] > threshold: 

85 yield result