LibreOffice plugin to pipe whole Writer documents through Google Translate, that ought to keep most of the page formatting.

⌈⌋ branch:  PageTranslate


Check-in [c62b11cb0e]

Many hyperlinks are disabled.
Use anonymous login to enable hyperlinks.

Overview
Comment:Change exception names, and use `LangSelection` for dialog (makes error more understandable).
Downloads: Tarball | ZIP archive | SQL archive
Timelines: family | ancestors | descendants | both | trunk
Files: files | file ages | folders
SHA1: c62b11cb0e01175c0ffc24715bd4f478e136ece1
User & Date: mario 2021-06-10 14:53:13
Context
2021-09-16
14:59
Hurried fixes for --merriamwebster and --synonyms.com Leaf check-in: b0666af4c8 user: mario tags: trunk
2021-06-10
14:53
Change exception names, and use `LangSelection` for dialog (makes error more understandable). check-in: c62b11cb0e user: mario tags: trunk
14:52
Notes about ArgosTranslate, CLI alternative check-in: b1b7271886 user: mario tags: trunk
Changes
Hide Diffs Unified Diffs Ignore Whitespace Patch

Changes to pythonpath/pt_dialogs.py.

208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
        pass

    app = ExcApp(ctx=ctx, err=err, exc=exc)
    app.showDialog()



class LangApp(unohelper.Base, XActionListener, XJobExecutor):
    """
    Class documentation...
    """
    def __init__(self, ctx=uno.getComponentContext()):
        self.LocalContext = ctx
        self.ServiceManager = self.LocalContext.ServiceManager
        self.Toolkit = self.ServiceManager.createInstanceWithContext("com.sun.star.awt.ExtToolkit", self.LocalContext)







|







208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
        pass

    app = ExcApp(ctx=ctx, err=err, exc=exc)
    app.showDialog()



class LangSelection(unohelper.Base, XActionListener, XJobExecutor):
    """
    Class documentation...
    """
    def __init__(self, ctx=uno.getComponentContext()):
        self.LocalContext = ctx
        self.ServiceManager = self.LocalContext.ServiceManager
        self.Toolkit = self.ServiceManager.createInstanceWithContext("com.sun.star.awt.ExtToolkit", self.LocalContext)
343
344
345
346
347
348
349
350
351
352
353
def langselect(*args):

    try:
        ctx = remote_ctx                    # IDE
    except:
        ctx = uno.getComponentContext()     # UI

    app = LangApp(ctx=ctx)
    app.showDialog()
    return app.fr, app.to








|



343
344
345
346
347
348
349
350
351
352
353
def langselect(*args):

    try:
        ctx = remote_ctx                    # IDE
    except:
        ctx = uno.getComponentContext()     # UI

    app = LangSelection(ctx=ctx)
    app.showDialog()
    return app.fr, app.to

Changes to pythonpath/translationbackends.py.

358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
        #self.error = pagetranslate.MessageBox

        Translator = None
        try:
            from translate import Translator
        except:
            log.error(format_exc())
            raise Exception("Run `pip install translate` to use this module.")
            
        # interestingly this backend function might just work as is.
        if re.search("mymemory", params.get("backend", ""), re.I):
            self.translate = Translator(
                provider="mymemory", to_lang=params["lang"], email=params.get("email", "")
            ).translate
        else:







|







358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
        #self.error = pagetranslate.MessageBox

        Translator = None
        try:
            from translate import Translator
        except:
            log.error(format_exc())
            raise ImportException("Run `pip install translate` to use this module.")
            
        # interestingly this backend function might just work as is.
        if re.search("mymemory", params.get("backend", ""), re.I):
            self.translate = Translator(
                provider="mymemory", to_lang=params["lang"], email=params.get("email", "")
            ).translate
        else:
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
        j = http.get(url).content.decode("utf-8")
        log.debug(j)
        j = json.loads(j)
        if j["responseStatus"] in ("200", 200):
            text = j["responseData"]["translatedText"]
            # or match[0]…
        else:
            raise Exception(j)
        return text


# Because, why not?
# Invokes a commandline tool for translating texts.
# The "cmd" can be:
#







|







487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
        j = http.get(url).content.decode("utf-8")
        log.debug(j)
        j = json.loads(j)
        if j["responseStatus"] in ("200", 200):
            text = j["responseData"]["translatedText"]
            # or match[0]…
        else:
            raise RuntimeError(j)
        return text


# Because, why not?
# Invokes a commandline tool for translating texts.
# The "cmd" can be:
#
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
                "impressionId": self.session,
                "sourceLanguage": src_lang,
                "targetLanguage": dst_lang,
                "text": text
            }
        ).json()
        if r.get("serviceMessage"):
            raise Exception(r)
        elif r.get("text"):
            #log.debug(f"'{text}' ==> {repr(r)} // {src_lang}→{dst_lang}")
            return r["text"]
        else:
            return text
    
    # detect language, and avoid non-text snippets







|







559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
                "impressionId": self.session,
                "sourceLanguage": src_lang,
                "targetLanguage": dst_lang,
                "text": text
            }
        ).json()
        if r.get("serviceMessage"):
            raise RuntimeError(r)
        elif r.get("text"):
            #log.debug(f"'{text}' ==> {repr(r)} // {src_lang}→{dst_lang}")
            return r["text"]
        else:
            return text
    
    # detect language, and avoid non-text snippets
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649

    def chpath(self):
        pass # PYTHONPATH has no effect on numpy import errors, seems to work only with distro-bound python installs

    def translate(self, text):
        source, target = self.lang(text), self.params["lang"]
        if source == target:
            raise Exception("Can't have same source and target language")
        pair = self.get_langpair(source, target)
        #self.translate = pair.translate
        return pair.translate(text)

    def get_langpair(self, source, target):
        import argostranslate.translate
        model = { m.code: m for m in argostranslate.translate.get_installed_languages() }
        try:
            return model[source].get_translation(model[target])
        except Exception as e:
            raise Exception("Requested language model/pair ({}→{}) not found, use `argos-translate-gui` to download/install the combination".format(source, target))


# maps a pagetranslate.t.* object (in main module),
# according to configured backend (now a string)
def assign_service(params):
    w = params.get("backend", "Google")
    map = {







|










|







624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649

    def chpath(self):
        pass # PYTHONPATH has no effect on numpy import errors, seems to work only with distro-bound python installs

    def translate(self, text):
        source, target = self.lang(text), self.params["lang"]
        if source == target:
            raise ValueError("Can't have same source and target language")
        pair = self.get_langpair(source, target)
        #self.translate = pair.translate
        return pair.translate(text)

    def get_langpair(self, source, target):
        import argostranslate.translate
        model = { m.code: m for m in argostranslate.translate.get_installed_languages() }
        try:
            return model[source].get_translation(model[target])
        except Exception as e:
            raise ValueError("Requested language model/pair ({}→{}) not found, use `argos-translate-gui` to download/install the combination".format(source, target))


# maps a pagetranslate.t.* object (in main module),
# according to configured backend (now a string)
def assign_service(params):
    w = params.get("backend", "Google")
    map = {