Skip to content

Commit

Permalink
♻️ Change Translation to a Namespace
Browse files Browse the repository at this point in the history
  • Loading branch information
Freed-Wu committed Oct 15, 2023
1 parent 085ca3e commit 3d907c3
Show file tree
Hide file tree
Showing 14 changed files with 180 additions and 95 deletions.
43 changes: 41 additions & 2 deletions src/translate_shell/translate.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,46 @@ def __init__(self, text: str, target_lang: str, source_lang: str) -> None:
from_lang=source_lang,
)

@staticmethod
def any2any(v: Any) -> Any:
"""Convert any to any.
:param v:
:type v: Any
:rtype: Any
"""
if isinstance(v, Namespace):
return Translations.namespace2dict(v)
if isinstance(v, list):
return Translations.list2list(v)
if isinstance(v, dict):
return Translations.dict2dict(v)
return v

@staticmethod
def list2list(d: list) -> list:
"""Convert list to list.
:param d:
:type d: list
:rtype: list
"""
for k, v in enumerate(d):
d[k] = Translations.any2any(v)
return d

@staticmethod
def dict2dict(d: dict) -> dict:
"""Convert dict to dict.
:param d:
:type d: dict
:rtype: dict
"""
for k, v in d.items():
d[k] = Translations.any2any(v)
return d

@staticmethod
def namespace2dict(namespace: Namespace) -> OrderedDict:
"""Convert Namespace to OrderedDict.
Expand All @@ -47,8 +87,7 @@ def namespace2dict(namespace: Namespace) -> OrderedDict:
"""
d = OrderedDict(vars(namespace))
for k, v in d.items():
if isinstance(v, Namespace):
d[k] = Translations.namespace2dict(v)
d[k] = Translations.any2any(v)
return d

def to_dict(self) -> OrderedDict:
Expand Down
82 changes: 64 additions & 18 deletions src/translate_shell/translators/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
from __future__ import annotations

import logging
from argparse import Namespace
from typing import TYPE_CHECKING, Any, Callable

if TYPE_CHECKING:
Expand All @@ -15,10 +16,56 @@
from .stardict import StardictTranslator

logger = logging.getLogger(__name__)
TRANSLATION = dict[
str,
str | list[str] | dict[str, str] | dict[str, dict[str, str]],
]


class Translation(Namespace):
"""Translation."""

def __init__(
self,
translator: str,
sl: str,
tl: str,
text: str,
phonetic: str,
paraphrase: str,
explains: dict[str, str],
details: dict[str, dict[str, str]],
alternatives: list[str],
) -> None:
"""Init.
:param translator:
:type translator: str
:param sl:
:type sl: str
:param tl:
:type tl: str
:param text:
:type text: str
:param phonetic:
:type phonetic: str
:param paraphrase:
:type paraphrase: str
:param explains:
:type explains: dict[str, str]
:param details:
:type details: dict[str, dict[str, str]]
:param alternatives:
:type alternatives: list[str]
:rtype: None
"""
super().__init__(
translator=translator,
sl=sl,
tl=tl,
text=text,
phonetic=phonetic,
paraphrase=paraphrase,
explains=explains,
details=details,
alternatives=alternatives,
)


class Translator:
Expand All @@ -33,7 +80,7 @@ def __init__(self, name: str) -> None:
"""
self.name = name

def create_translation(self, text: str, tl: str, sl: str) -> TRANSLATION:
def create_translation(self, text: str, tl: str, sl: str) -> Translation:
"""Create translation.
:param text:
Expand All @@ -42,20 +89,19 @@ def create_translation(self, text: str, tl: str, sl: str) -> TRANSLATION:
:type tl: str
:param sl:
:type sl: str
:rtype: TRANSLATION
:rtype: Translation
"""
res = {
"translator": self.name,
"sl": sl,
"tl": tl,
"text": text,
"phonetic": "",
"paraphrase": "",
"explains": {},
"details": {},
"alternatives": {},
}
return res
return Translation(
translator=self.name,
sl=sl,
tl=tl,
text=text,
phonetic="",
paraphrase="",
explains={},
details={},
alternatives=[],
)

@staticmethod
def convert_langs(*langs: str) -> list[str]:
Expand Down
12 changes: 6 additions & 6 deletions src/translate_shell/translators/llm/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@

from ...__main__ import LANGS
from ...external.platformdirs import AppDirs
from .. import TRANSLATION, Translator
from .. import Translation, Translator

TEMPLATES = []
for role in ["system", "user"]:
Expand Down Expand Up @@ -40,7 +40,7 @@ def __init__(self, name: str) -> None:

def __call__(
self, text: str, tl: str, sl: str, option: dict[str, Any]
) -> TRANSLATION | None:
) -> Translation | None:
"""Call.
:param text:
Expand All @@ -51,7 +51,7 @@ def __call__(
:type sl: str
:param option:
:type option: dict[str, Any]
:rtype: TRANSLATION | None
:rtype: Translation | None
"""
init_model = option.get("init_model", self.init_model)
init_messages = option.get("init_messages", self.init_messages)
Expand Down Expand Up @@ -153,14 +153,14 @@ def init_kwargs(option: dict) -> dict:
return kwargs

@staticmethod
def init_result(completion: Mapping, result: TRANSLATION) -> TRANSLATION:
def init_result(completion: Mapping, result: Translation) -> Translation:
"""Init result.
:param completion:
:type completion: Mapping
:param result:
:type result: TRANSLATION
:rtype: TRANSLATION
:type result: Translation
:rtype: Translation
"""
result["paraphrase"] = completion["choices"][0]["message"]["content"]
return result
Expand Down
10 changes: 5 additions & 5 deletions src/translate_shell/translators/online/bing.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from typing import Any
from urllib.parse import quote_plus

from .. import TRANSLATION
from .. import Translation
from . import OnlineTranslator


Expand All @@ -33,7 +33,7 @@ def __init__(self) -> None:

def __call__(
self, text: str, tl: str, sl: str, option: dict[str, Any]
) -> TRANSLATION | None:
) -> Translation | None:
"""Call.
:param text:
Expand All @@ -44,7 +44,7 @@ def __call__(
:type sl: str
:param option:
:type option: dict[str, Any]
:rtype: TRANSLATION | None
:rtype: Translation | None
"""
res = self.create_translation(text, tl, sl)
tl, sl = self.convert_langs(tl, sl)
Expand All @@ -61,8 +61,8 @@ def __call__(
resp = self.http_get(url, None, headers)
if not resp:
return None
res["phonetic"] = self.get_phonetic(resp)
res["explains"] = self.get_explains(resp)
res.phonetic = self.get_phonetic(resp)
res.explains = self.get_explains(resp)
return res

def get_phonetic(self, html: str) -> str:
Expand Down
16 changes: 8 additions & 8 deletions src/translate_shell/translators/online/google.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from typing import Any
from urllib.parse import quote_plus

from .. import TRANSLATION
from .. import Translation
from . import OnlineTranslator


Expand Down Expand Up @@ -43,7 +43,7 @@ def get_url(self, sl: str, tl: str, qry: str) -> str:

def __call__(
self, text: str, tl: str, sl: str, option: dict[str, Any]
) -> TRANSLATION | None:
) -> Translation | None:
"""Call.
:param text:
Expand All @@ -54,7 +54,7 @@ def __call__(
:type sl: str
:param option:
:type option: dict[str, Any]
:rtype: TRANSLATION | None
:rtype: Translation | None
"""
res = self.create_translation(text, tl, sl)
tl, sl = self.convert_langs(tl, sl)
Expand All @@ -64,11 +64,11 @@ def __call__(
return None
obj = json.loads(resp)

res["paraphrase"] = self.get_paraphrase(obj)
res["explains"] = self.get_explains(obj)
res["phonetic"] = self.get_phonetic(obj)
res["details"] = self.get_details(obj)
res["alternatives"] = self.get_alternatives(obj)
res.paraphrase = self.get_paraphrase(obj)
res.explains = self.get_explains(obj)
res.phonetic = self.get_phonetic(obj)
res.details = self.get_details(obj)
res.alternatives = self.get_alternatives(obj)
return res

@staticmethod
Expand Down
12 changes: 6 additions & 6 deletions src/translate_shell/translators/online/haici.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from typing import Any
from urllib.parse import quote_plus

from .. import TRANSLATION
from .. import Translation
from . import OnlineTranslator


Expand All @@ -25,7 +25,7 @@ def __init__(self) -> None:

def __call__(
self, text: str, tl: str, sl: str, option: dict[str, Any]
) -> TRANSLATION | None:
) -> Translation | None:
"""Call.
:param text:
Expand All @@ -36,7 +36,7 @@ def __call__(
:type sl: str
:param option:
:type option: dict[str, Any]
:rtype: TRANSLATION | None
:rtype: Translation | None
"""
res = self.create_translation(text, tl, sl)
tl, sl = self.convert_langs(tl, sl)
Expand All @@ -47,9 +47,9 @@ def __call__(
if not resp:
return None

res["phonetic"] = self.get_phonetic(resp)
res["explains"] = self.get_explains(resp)
res["details"] = self.get_details(resp)
res.phonetic = self.get_phonetic(resp)
res.explains = self.get_explains(resp)
res.details = self.get_details(resp)
return res

@staticmethod
Expand Down
14 changes: 7 additions & 7 deletions src/translate_shell/translators/online/youdaozhiyun.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
from ...__main__ import ASSETS_PATH
from ...external.keyring import get_keyring
from ...external.keyring.errors import NoKeyringError
from .. import TRANSLATION
from .. import Translation
from . import OnlineTranslator

logger = logging.getLogger(__name__)
Expand Down Expand Up @@ -64,7 +64,7 @@ def sign(self, text: str, salt: str) -> str:

def __call__(
self, text: str, tl: str, sl: str, option: dict[str, Any]
) -> TRANSLATION | None:
) -> Translation | None:
"""Call.
:param text:
Expand All @@ -75,7 +75,7 @@ def __call__(
:type sl: str
:param option:
:type option: dict[str, Any]
:rtype: TRANSLATION | None
:rtype: Translation | None
"""
res = self.create_translation(text, tl, sl)
tl, sl = self.convert_langs(tl, sl)
Expand Down Expand Up @@ -111,12 +111,12 @@ def __call__(
return None

basic = obj.get("basic")
res["paraphrase"] = obj.get("translation", "")
res["detail"] = obj.get("web", "")
res.paraphrase = obj.get("translation", "")
res.detail = obj.get("web", "")
if basic:
# ignore us/uk-phonetic
res["phonetic"] = basic.get("phonetic", "")
res["explains"] = basic.get("explains", [])
res.phonetic = basic.get("phonetic", "")
res.explains = basic.get("explains", [])
return res

@staticmethod
Expand Down

0 comments on commit 3d907c3

Please sign in to comment.