88from googletrans import Translator
99from 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
1416class 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+ )
0 commit comments