Skip to content

Commit 8d072e2

Browse files
Apply ruff format across the codebase.
One-time reformat to 88-character line length; no logic changes. Co-authored-by: Cursor <cursoragent@cursor.com>
1 parent 6cd6ac9 commit 8d072e2

79 files changed

Lines changed: 3759 additions & 1607 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

autotranslate.py

Lines changed: 64 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -8,57 +8,76 @@
88
from googletrans import Translator
99
from configparser import ConfigParser
1010

11-
TIMEOUT: int = 30 # Timeout after 30s (prevent indefinite hanging when there is network issues)
11+
TIMEOUT: int = (
12+
30 # Timeout after 30s (prevent indefinite hanging when there is network issues)
13+
)
1214

1315

1416
class TranslationTool:
1517
def __init__(self, config: ConfigParser):
16-
if not config.has_option('autotranslate', 'site') or \
17-
not config.has_option('autotranslate', 'username'):
18-
raise RuntimeError("Missing connection settings for autotranslate in config.ini")
18+
if not config.has_option("autotranslate", "site") or not config.has_option(
19+
"autotranslate", "username"
20+
):
21+
raise RuntimeError(
22+
"Missing connection settings for autotranslate in config.ini"
23+
)
1924

20-
self.logger: logging.Logger = logging.getLogger('pywikitools.autotranslate')
25+
self.logger: logging.Logger = logging.getLogger("pywikitools.autotranslate")
2126

22-
code = config.get('autotranslate', 'site')
27+
code = config.get("autotranslate", "site")
2328
family = Family()
24-
self.site = pywikibot.Site(code=code, fam=family, user=config.get('autotranslate', 'username'))
29+
self.site = pywikibot.Site(
30+
code=code, fam=family, user=config.get("autotranslate", "username")
31+
)
2532
if not self.site.logged_in():
2633
self.site.login()
2734
if not self.site.logged_in():
2835
raise RuntimeError("Login with pywikibot failed.")
2936
# Set throttle to 0 to speed up write operations (otherwise pywikibot would wait up to 10s after each write)
3037
self.site.throttle.set_delays(delay=0, writedelay=0, absolute=True)
31-
self.fortraininglib: ForTrainingLib = ForTrainingLib(family.base_url(code, ''),
32-
family.scriptpath(code))
38+
self.fortraininglib: ForTrainingLib = ForTrainingLib(
39+
family.base_url(code, ""), family.scriptpath(code)
40+
)
3341

3442
self.language_supported_by_deepl = True
35-
if not config.has_option('autotranslate', 'deeplendpoint') or \
36-
not config.has_option('autotranslate', 'deeplapikey'):
43+
if not config.has_option(
44+
"autotranslate", "deeplendpoint"
45+
) or not config.has_option("autotranslate", "deeplapikey"):
3746
self.logger.warning("Missing settings for DeepL connection in config.ini")
3847
self.language_supported_by_deepl = False
3948
else:
40-
self.deepl_endpoint = config.get('autotranslate', 'deeplendpoint')
41-
self.deepl_api_key = config.get('autotranslate', 'deeplapikey')
49+
self.deepl_endpoint = config.get("autotranslate", "deeplendpoint")
50+
self.deepl_api_key = config.get("autotranslate", "deeplapikey")
4251

4352
self.google_translator = Translator()
4453

45-
def fetch_and_translate(self, page_name, language_code, force=False, simulate=False):
54+
def fetch_and_translate(
55+
self, page_name, language_code, force=False, simulate=False
56+
):
4657
translated_page = self.fortraininglib.get_translation_units(page_name, "en")
4758

4859
if (
49-
not simulate and not force
50-
and self.fortraininglib.get_translated_title(page_name, language_code) is not None
60+
not simulate
61+
and not force
62+
and self.fortraininglib.get_translated_title(page_name, language_code)
63+
is not None
5164
):
52-
self.logger.warning("Translation already exists. If you want to force overwrite, use the -f flag.")
65+
self.logger.warning(
66+
"Translation already exists. If you want to force overwrite, use the -f flag."
67+
)
5368
return
5469

5570
# Split the translation units into snippets to avoid mark-up symbols
5671
for translation_unit in translated_page:
57-
translation_unit.split_all_tags = True # We want that to get rid of all markup
72+
translation_unit.split_all_tags = (
73+
True # We want that to get rid of all markup
74+
)
5875
translation_unit.remove_links()
5976

6077
for orig_snippet, trans_snippet in translation_unit:
61-
trans_snippet.content = self.translate_with_deepl_or_google(orig_snippet.content, language_code)
78+
trans_snippet.content = self.translate_with_deepl_or_google(
79+
orig_snippet.content, language_code
80+
)
6281
translation_unit.sync_from_snippets()
6382
identifier = f"{translation_unit.identifier}/{language_code}"
6483
translated_text = translation_unit.get_translation()
@@ -72,19 +91,20 @@ def fetch_and_translate(self, page_name, language_code, force=False, simulate=Fa
7291
def translate_with_deepl_or_google(self, text, language_code) -> str:
7392
"""Do the translation: First try DeepL, if that doesn't work (DeepL supports less languages), use Google"""
7493
if self.language_supported_by_deepl:
75-
data = {
76-
"text": text,
77-
"target_lang": language_code
78-
}
79-
headers = {
80-
"Authorization": f"DeepL-Auth-Key {self.deepl_api_key}"
81-
}
82-
response = requests.post(self.deepl_endpoint, data=data, headers=headers, timeout=TIMEOUT)
94+
data = {"text": text, "target_lang": language_code}
95+
headers = {"Authorization": f"DeepL-Auth-Key {self.deepl_api_key}"}
96+
response = requests.post(
97+
self.deepl_endpoint, data=data, headers=headers, timeout=TIMEOUT
98+
)
8399
if response.status_code == 200:
84-
return response.json()['translations'][0]['text']
100+
return response.json()["translations"][0]["text"]
85101
else:
86-
self.logger.warning(f"DeepL error {response.status_code}: {response.text}")
87-
self.logger.warning(f"DeepL cannot translate to {language_code}. Using Google Translate instead.")
102+
self.logger.warning(
103+
f"DeepL error {response.status_code}: {response.text}"
104+
)
105+
self.logger.warning(
106+
f"DeepL cannot translate to {language_code}. Using Google Translate instead."
107+
)
88108
self.language_supported_by_deepl = False
89109

90110
# If DeepL fails, use Google Translate
@@ -104,16 +124,23 @@ def upload_translation(self, identifier: str, translated_text: str):
104124
parser = argparse.ArgumentParser(description="Machine-translate a worksheet.")
105125
parser.add_argument("worksheet_name", help="Name of the worksheet to translate.")
106126
parser.add_argument("language_code", help="Target language code for translation.")
107-
parser.add_argument("-f", "--force", action="store_true", help="Force overwrite if translation exists.")
108-
parser.add_argument("--simulate", action="store_true",
109-
help="Print translated units without uploading to MediaWiki.")
127+
parser.add_argument(
128+
"-f",
129+
"--force",
130+
action="store_true",
131+
help="Force overwrite if translation exists.",
132+
)
133+
parser.add_argument(
134+
"--simulate",
135+
action="store_true",
136+
help="Print translated units without uploading to MediaWiki.",
137+
)
110138
args = parser.parse_args()
111139

112140
config = ConfigParser()
113141
config.read(join(dirname(abspath(__file__)), "config.ini"))
114142

115143
translator_tool = TranslationTool(config)
116-
translator_tool.fetch_and_translate(args.worksheet_name,
117-
args.language_code,
118-
args.force,
119-
args.simulate)
144+
translator_tool.fetch_and_translate(
145+
args.worksheet_name, args.language_code, args.force, args.simulate
146+
)

check_for_typos.py

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -23,12 +23,20 @@ def parse_arguments() -> argparse.Namespace:
2323
Returns:
2424
argparse.Namespace: parsed arguments
2525
"""
26-
log_levels: List[str] = ['debug', 'info', 'warning', 'error']
26+
log_levels: List[str] = ["debug", "info", "warning", "error"]
2727

2828
parser = argparse.ArgumentParser()
2929
parser.add_argument("language_code", help="Language code")
30-
parser.add_argument("-l", "--loglevel", choices=log_levels, default="warning", help="set loglevel for the script")
31-
parser.add_argument("--only", help="Only apply the correction rule with the specified method name")
30+
parser.add_argument(
31+
"-l",
32+
"--loglevel",
33+
choices=log_levels,
34+
default="warning",
35+
help="set loglevel for the script",
36+
)
37+
parser.add_argument(
38+
"--only", help="Only apply the correction rule with the specified method name"
39+
)
3240
return parser.parse_args()
3341

3442

@@ -37,7 +45,7 @@ def parse_arguments() -> argparse.Namespace:
3745
root = logging.getLogger()
3846
root.setLevel(logging.DEBUG)
3947
sh = logging.StreamHandler(sys.stdout)
40-
fformatter = logging.Formatter('%(levelname)s: %(message)s')
48+
fformatter = logging.Formatter("%(levelname)s: %(message)s")
4149
sh.setFormatter(fformatter)
4250
numeric_level = getattr(logging, args.loglevel.upper(), None)
4351
assert isinstance(numeric_level, int)
@@ -55,7 +63,10 @@ def parse_arguments() -> argparse.Namespace:
5563
for worksheet in correctbot.fortraininglib.get_worksheet_list():
5664
correctbot.check_page(worksheet, args.language_code, apply_only_rule)
5765
print(f"{worksheet}: {correctbot.get_correction_counter()} corrections")
58-
if correctbot.get_correction_counter() > 0 or correctbot.get_suggestion_counter() > 0:
66+
if (
67+
correctbot.get_correction_counter() > 0
68+
or correctbot.get_suggestion_counter() > 0
69+
):
5970
print(correctbot.get_correction_stats())
6071
print(correctbot.get_correction_diff())
6172
print(correctbot.get_suggestion_stats())

check_pdf_metadata.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,9 @@ def build_worksheet_info(
5959
resolved_version = fetched.strip()
6060

6161
progress = TranslationProgress(translated=1, fuzzy=0, total=1)
62-
return WorksheetInfo(worksheet_name, language_code, resolved_title, progress, resolved_version)
62+
return WorksheetInfo(
63+
worksheet_name, language_code, resolved_title, progress, resolved_version
64+
)
6365

6466

6567
def main(argv: Optional[List[str]] = None) -> int:

correct_bot.py

Lines changed: 18 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -35,15 +35,27 @@ def parse_arguments() -> argparse.Namespace:
3535
Returns:
3636
CorrectBot instance
3737
"""
38-
log_levels: List[str] = ['debug', 'info', 'warning', 'error']
38+
log_levels: List[str] = ["debug", "info", "warning", "error"]
3939

4040
parser = argparse.ArgumentParser()
4141
parser.add_argument("page", help="Name of the mediawiki page")
4242
parser.add_argument("language_code", help="Language code")
43-
parser.add_argument("-s", "--simulate", action="store_true",
44-
help="Simulates the corrections but does not apply them to the webpage.")
45-
parser.add_argument("-l", "--loglevel", choices=log_levels, default="warning", help="set loglevel for the script")
46-
parser.add_argument("--only", help="Only apply the correction rule with the specified method name")
43+
parser.add_argument(
44+
"-s",
45+
"--simulate",
46+
action="store_true",
47+
help="Simulates the corrections but does not apply them to the webpage.",
48+
)
49+
parser.add_argument(
50+
"-l",
51+
"--loglevel",
52+
choices=log_levels,
53+
default="warning",
54+
help="set loglevel for the script",
55+
)
56+
parser.add_argument(
57+
"--only", help="Only apply the correction rule with the specified method name"
58+
)
4759
return parser.parse_args()
4860

4961

@@ -54,7 +66,7 @@ def parse_arguments() -> argparse.Namespace:
5466
root = logging.getLogger()
5567
root.setLevel(logging.DEBUG)
5668
sh = logging.StreamHandler(sys.stdout)
57-
fformatter = logging.Formatter('%(levelname)s: %(message)s')
69+
fformatter = logging.Formatter("%(levelname)s: %(message)s")
5870
sh.setFormatter(fformatter)
5971
numeric_level = getattr(logging, args.loglevel.upper(), None)
6072
assert isinstance(numeric_level, int)

downloadalltranslations.py

Lines changed: 19 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
The PDF files are named [languagename in English] - [language autonym].pdf
66
They're put into a (newly created) subdirectory named after the worksheet
77
"""
8+
89
import sys
910
import os
1011
import logging
@@ -14,10 +15,12 @@
1415

1516

1617
def usage():
17-
print("Usage: python3 downloadalltranslations.py [-l {debug, info, warning, error, critical}] <worksheetname>")
18+
print(
19+
"Usage: python3 downloadalltranslations.py [-l {debug, info, warning, error, critical}] <worksheetname>"
20+
)
1821

1922

20-
if __name__ == '__main__':
23+
if __name__ == "__main__":
2124
try:
2225
opts, args = getopt.getopt(sys.argv[1:], "hl:", ["help", "loglevel"])
2326
except getopt.GetoptError as err:
@@ -48,7 +51,9 @@ def usage():
4851

4952
fortraininglib = ForTrainingLib("https://www.4training.net")
5053
translations = fortraininglib.list_page_translations(worksheetname)
51-
logging.info(f'Worksheet {worksheetname} is translated into {len(translations)} languages: {translations.keys()}')
54+
logging.info(
55+
f"Worksheet {worksheetname} is translated into {len(translations)} languages: {translations.keys()}"
56+
)
5257
for language in translations.keys():
5358
pdf = fortraininglib.get_pdf_name(worksheetname, language)
5459
if pdf is None:
@@ -57,17 +62,23 @@ def usage():
5762
logging.debug(f"Language: {language}, filename: {pdf}")
5863
url = fortraininglib.get_file_url(pdf)
5964
if not url:
60-
logging.warning(f"Language: {language}, file: {pdf} doesn't seem to exist, ignoring")
65+
logging.warning(
66+
f"Language: {language}, file: {pdf} doesn't seem to exist, ignoring"
67+
)
6168
continue
6269
file_request = requests.get(url, allow_redirects=True)
6370
language_autonym = fortraininglib.get_language_name(language)
64-
language_english = fortraininglib.get_language_name(language, 'en')
71+
language_english = fortraininglib.get_language_name(language, "en")
6572
if language_autonym is None or language_english is None:
66-
logging.warning(f"Strang: couldn't get language name for language {language}, ignoring")
73+
logging.warning(
74+
f"Strang: couldn't get language name for language {language}, ignoring"
75+
)
6776
continue
6877
file_name = f"{worksheetname}/{language_english} - {language_autonym}.pdf"
6978
try:
70-
open(file_name, 'wb').write(file_request.content)
79+
open(file_name, "wb").write(file_request.content)
7180
except FileNotFoundError:
72-
logging.warning(f"Language: {language}, error while trying to open file {file_name}, ignoring")
81+
logging.warning(
82+
f"Language: {language}, error while trying to open file {file_name}, ignoring"
83+
)
7384
logging.info(f"We saved {file_name}")

0 commit comments

Comments
 (0)