Skip to content

Commit

Permalink
[pre-commit.ci] auto fixes from pre-commit.com hooks
Browse files Browse the repository at this point in the history
for more information, see https://pre-commit.ci
  • Loading branch information
pre-commit-ci[bot] committed Jan 31, 2024
1 parent 9788759 commit db92242
Show file tree
Hide file tree
Showing 21 changed files with 96 additions and 43 deletions.
6 changes: 2 additions & 4 deletions scripts/test-bench.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,14 +29,12 @@
parser = get_parser()
args = parser.parse_args()
init(args)
print(
f"""
print(f"""
input text:\t{args.text}
target lang\t{args.target_lang}
source lang:\t{args.source_lang}
translators:\t{args.translators}
"""
)
""")
args.translators = args.translators.split(",")

translationss = {}
Expand Down
4 changes: 3 additions & 1 deletion src/translate_shell/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,9 @@ def get_parser() -> ArgumentParser:
parser.add_argument(
"-q", "--quiet", action="count", default=0, help="reduce logger level"
)
parser.add_argument("--lsp", action="store_true", help="start language server")
parser.add_argument(
"--lsp", action="store_true", help="start language server"
)
group = parser.add_mutually_exclusive_group()
group.add_argument(
"--no-clipboard",
Expand Down
4 changes: 3 additions & 1 deletion src/translate_shell/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,9 @@ def process_input(
"""
from .utils.input import process_input

return process_input(text, target_lang, source_lang, translators, is_repl)
return process_input(
text, target_lang, source_lang, translators, is_repl
)

@staticmethod
def process_output(translations: Translations) -> str:
Expand Down
7 changes: 5 additions & 2 deletions src/translate_shell/external/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,8 @@ def filter_var(variables: dict[str, Any]) -> dict[str, Any]:
"""
return dict(
filter(
lambda x: not x[0].startswith("_") and not isinstance(x[1], _SpecialForm),
lambda x: not x[0].startswith("_")
and not isinstance(x[1], _SpecialForm),
variables.items(),
)
)
Expand All @@ -49,7 +50,9 @@ def get_wrong_varnames(file: str, fake_vars: dict[str, Any]) -> list[str]:
return wrong_varnames


def print_wrong_varnames(file: str, fake_vars: dict[str, Any], end: str = "\n") -> int:
def print_wrong_varnames(
file: str, fake_vars: dict[str, Any], end: str = "\n"
) -> int:
"""Print wrong varnames.
:param file:
Expand Down
3 changes: 2 additions & 1 deletion src/translate_shell/tools/generate_prompt/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,8 @@ def main() -> None:
if args.section == []:
args.section = SECTION
args.section = [
section[0] if len(section) == 1 else section for section in args.section
section[0] if len(section) == 1 else section
for section in args.section
]
# sys.stdout.write will remove ANSI escape code when output is not a tty
with sys.stdout as f:
Expand Down
16 changes: 12 additions & 4 deletions src/translate_shell/tools/repl/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,9 @@

def get_parser() -> ArgumentParser:
r"""Get a parser for unit test."""
parser = ArgumentParser(epilog=EPILOG, formatter_class=RawDescriptionHelpFormatter)
parser = ArgumentParser(
epilog=EPILOG, formatter_class=RawDescriptionHelpFormatter
)
parser.add_argument("--version", version=VERSION, action="version")
shtab.add_argument_to(parser)
group = parser.add_mutually_exclusive_group()
Expand Down Expand Up @@ -55,23 +57,29 @@ def get_parser() -> ArgumentParser:
dest="jedi",
help="disable jedi",
)
group.add_argument("--jedi", action="store_true", help="enable jedi (default)")
group.add_argument(
"--jedi", action="store_true", help="enable jedi (default)"
)
group = parser.add_mutually_exclusive_group()
group.add_argument(
"--no-rich",
action="store_false",
dest="rich",
help="disable rich",
)
group.add_argument("--rich", action="store_true", help="enable rich (default)")
group.add_argument(
"--rich", action="store_true", help="enable rich (default)"
)
group = parser.add_mutually_exclusive_group()
group.add_argument(
"--no-ps1",
action="store_false",
dest="ps1",
help="disable ps1",
)
group.add_argument("--ps1", action="store_true", help="enable ps1 (default)")
group.add_argument(
"--ps1", action="store_true", help="enable ps1 (default)"
)
return parser


Expand Down
3 changes: 2 additions & 1 deletion src/translate_shell/tools/repl/ps1.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@ class Ps1:
def __init__(
self,
prompt_string: str = "\n>>> ",
sections: None | list[str | tuple[str, str, str | Callable[[], str]]] = None,
sections: None
| list[str | tuple[str, str, str | Callable[[], str]]] = None,
) -> None:
"""Init.
Expand Down
6 changes: 4 additions & 2 deletions src/translate_shell/translators/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,8 @@ def get_youdao() -> Callable[[], Translator] | None:
:rtype: Callable[[], Translator] | None
"""
logger.warning(
"youdao translator hasn't been implemented." " Maybe you want to send a PR?"
"youdao translator hasn't been implemented."
" Maybe you want to send a PR?"
)
return

Expand All @@ -178,7 +179,8 @@ def get_yandex() -> Callable[[], Translator] | None:
:rtype: Callable[[], Translator] | None
"""
logger.warning(
"yandex translator hasn't been implemented." " Maybe you want to send a PR?"
"yandex translator hasn't been implemented."
" Maybe you want to send a PR?"
)
return

Expand Down
13 changes: 10 additions & 3 deletions src/translate_shell/translators/llm/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,10 @@
template = AppDirs("translate-shell").user_config_path / (role + ".j2")
if not template.exists():
template = (
Path(__file__).parent.parent.parent / "assets" / "jinja2" / (role + ".j2")
Path(__file__).parent.parent.parent
/ "assets"
/ "jinja2"
/ (role + ".j2")
)
TEMPLATES += [{"role": role, "content": template.read_text()}]

Expand Down Expand Up @@ -59,7 +62,9 @@ def __call__(
messages = init_messages(tl, sl, text, option)
kwargs = init_kwargs(option)

completion = create_chat_completion(model=model, messages=messages, **kwargs)
completion = create_chat_completion(
model=model, messages=messages, **kwargs
)
result = self.create_translation(text, tl, sl)
result = init_result(completion, result)
return result
Expand Down Expand Up @@ -158,7 +163,9 @@ def init_result(completion: Mapping, result: Translation) -> Translation:
return result

@staticmethod
def create_chat_completion(model: Any, messages: list, **kwargs: Any) -> Mapping:
def create_chat_completion(
model: Any, messages: list, **kwargs: Any
) -> Mapping:
"""Create chat completion.
:param model:
Expand Down
6 changes: 4 additions & 2 deletions src/translate_shell/translators/online/bing.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,8 @@ def __post_init__(self) -> None:
r'<span class="ht_attr" lang=".*?">\[(.*?)\] </span>'
)
self.pat_trs = re.compile(
r'<span class="ht_pos">(.*?)</span>' r'<span class="ht_trs">(.*?)</span>'
r'<span class="ht_pos">(.*?)</span>'
r'<span class="ht_trs">(.*?)</span>'
)

async def __call__(
Expand All @@ -54,7 +55,8 @@ async def __call__(
params = {"q": text}
headers = {
"Accept": (
"text/html,application/xhtml+xml,application/xml;" "q=0.9,*/*;q=0.8"
"text/html,application/xhtml+xml,application/xml;"
"q=0.9,*/*;q=0.8"
),
"Accept-Language": "en-US,en;q=0.5",
"Cookie": "_EDGE_S=mkt=" + tl,
Expand Down
4 changes: 3 additions & 1 deletion src/translate_shell/translators/online/haici.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,9 @@ def get_details(html: str) -> dict[str, dict[str, str]]:
rst = {}
for item in m:
sentences = item.split("<br>")
for s1, s2 in list(zip(sentences[::2], sentences[1::2], strict=False)):
for s1, s2 in list(
zip(sentences[::2], sentences[1::2], strict=False)
):
_, _, v = s1.partition(". ")
rst[v] = s2
details["例句与用法"] = rst
Expand Down
12 changes: 9 additions & 3 deletions src/translate_shell/translators/online/youdaozhiyun.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,9 @@

logger = logging.getLogger(__name__)
ERROR = json.loads(
(ASSETS_PATH / "json" / "youdaozhiyun-error.json").read_text(encoding="utf-8")
(ASSETS_PATH / "json" / "youdaozhiyun-error.json").read_text(
encoding="utf-8"
)
)


Expand Down Expand Up @@ -141,9 +143,13 @@ def get_youdaozhiyun_app_info(
logger.error("no installed backend!")
return "", ""
if not YDAPPID:
logger.error(service_name + "/" + user_name4appid + "has no password!")
logger.error(
service_name + "/" + user_name4appid + "has no password!"
)
return "", ""
if not YDAPPSEC:
logger.error(service_name + "/" + user_name4appsec + "has no password!")
logger.error(
service_name + "/" + user_name4appsec + "has no password!"
)
return "", ""
return YDAPPID, YDAPPSEC
4 changes: 3 additions & 1 deletion src/translate_shell/translators/speaker.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,9 @@ class Speaker(Translator):

name: str = "speaker"

def __call__(self, text: str, tl: str, sl: str, option: dict[str, Any]) -> None:
def __call__(
self, text: str, tl: str, sl: str, option: dict[str, Any]
) -> None:
"""Call.
:param text:
Expand Down
8 changes: 6 additions & 2 deletions src/translate_shell/translators/stardict/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,9 @@ def __call__(
:rtype: Translation | None
"""
self.stardict = option.get("stardict", STARDICT)
tokens, dictionary, sl, tl, dictionaries = self.get_tokens(text, tl, sl)
tokens, dictionary, sl, tl, dictionaries = self.get_tokens(
text, tl, sl
)
if tokens == []:
logger.warning(
f"No appropriate dictionary ({', '.join(dictionaries)}) "
Expand Down Expand Up @@ -114,7 +116,9 @@ def get_tokens(
for dictionary in dictionaries:
expr = os.path.join(
directory,
os.path.join("**", dictionary + "*" + os.path.extsep + "dict*"),
os.path.join(
"**", dictionary + "*" + os.path.extsep + "dict*"
),
)
paths = glob(expr, recursive=True)
for path in paths:
Expand Down
4 changes: 3 additions & 1 deletion src/translate_shell/translators/stardict/langdao_ce_gb.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,9 @@ def parse_tokens(tokens: list[str], res: Translation) -> Translation:
paraphrases = []
for phrase in phrases:
paraphrase = (
translate(phrase, "en", "zh-cn", ["stardict"]).results[0].paraphrase
translate(phrase, "en", "zh-cn", ["stardict"])
.results[0]
.paraphrase
)
paraphrases += [paraphrase]
details["相关词组"] = dict(zip(phrases, paraphrases, strict=False))
Expand Down
4 changes: 3 additions & 1 deletion src/translate_shell/translators/stardict/langdao_ec_gb.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,9 @@ def parse_tokens(tokens: list[str], res: Translation) -> Translation:
paraphrases = []
for phrase in phrases:
paraphrase = (
translate(phrase, "zh-cn", "en", ["stardict"]).results[0].paraphrase
translate(phrase, "zh-cn", "en", ["stardict"])
.results[0]
.paraphrase
)
paraphrases += [paraphrase]
details["相关词组"] = dict(zip(phrases, paraphrases, strict=False))
Expand Down
4 changes: 3 additions & 1 deletion src/translate_shell/ui/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,9 @@ def init_config(path: Path) -> Configuration:
logger.warning("Ignore configuration() of " + str(CONFIG_FILE))
return config
if not isinstance(new_config, Configuration):
logger.error("configuration() of " + str(CONFIG_FILE) + "is not legal!")
logger.error(
"configuration() of " + str(CONFIG_FILE) + "is not legal!"
)
return config
return new_config

Expand Down
3 changes: 2 additions & 1 deletion src/translate_shell/utils/input.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,8 @@ def process_translators_code(
return "", translators
if any(translator not in TRANSLATORS for translator in code.split(",")):
logger.error(
"Incorrect translators. Currently support " + " ".join(TRANSLATORS.keys())
"Incorrect translators. Currently support "
+ " ".join(TRANSLATORS.keys())
)
return "", translators
translators = code
Expand Down
12 changes: 9 additions & 3 deletions src/translate_shell/utils/output.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@
from ..translators import Translation
from .section import p10k_sections

NUMBER = json.loads((ASSETS_PATH / "json" / "number.json").read_text(encoding="utf-8"))
NUMBER = json.loads(
(ASSETS_PATH / "json" / "number.json").read_text(encoding="utf-8")
)


def process_output_firstline(rst: Translation) -> str:
Expand Down Expand Up @@ -102,7 +104,9 @@ def process_output_p10k(translations: Translations) -> str:
+ " "
+ Style.RESET_ALL
+ " "
+ examples[0].replace("<em>", Fore.RED).replace("</em>", Fore.RESET)
+ examples[0]
.replace("<em>", Fore.RED)
.replace("</em>", Fore.RESET)
]
if examples[1] != "":
outputs += [examples[1]]
Expand All @@ -121,5 +125,7 @@ def process_output(translations: Translations) -> str:
with suppress(ImportError):
from repl_python_wakatime.hooks.wakatime import wakatime_hook

wakatime_hook(plugin="translate-shell-wakatime", category="translating")
wakatime_hook(
plugin="translate-shell-wakatime", category="translating"
)
return rst
12 changes: 5 additions & 7 deletions src/translate_shell/utils/setting.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,13 +43,11 @@ def get_setting(name: SETTING | None) -> str:
elif name == "dictionary_priorities":
from ..translators.stardict import STARDICT

result = "\n".join(
[
"\t".join([sl, tl] + [",".join(dictionaries)])
for sl, v in STARDICT.items()
for tl, dictionaries in v.items()
]
)
result = "\n".join([
"\t".join([sl, tl] + [",".join(dictionaries)])
for sl, v in STARDICT.items()
for tl, dictionaries in v.items()
])
elif name is None:
result = "\n\n".join(
"## " + setting + "\n\n" + get_setting(setting)
Expand Down
4 changes: 3 additions & 1 deletion tests/translate_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,5 +15,7 @@ class Test:
def test_google() -> None:
"""Test google"""
rst = asdict(translate("The Mythical Man-Month", "zh_CN"))
expected = json.loads((ASSETS_PATH / "json" / "google.json").read_text())
expected = json.loads(
(ASSETS_PATH / "json" / "google.json").read_text()
)
assert rst == expected

0 comments on commit db92242

Please sign in to comment.