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

βŒˆβŒ‹ βŽ‡ branch:  PageTranslate


Check-in [748623aaf6]

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

Overview
Comment:Introduce pt_opts handler for settings window
Downloads: Tarball | ZIP archive | SQL archive
Timelines: family | ancestors | descendants | both | trunk
Files: files | file ages | folders
SHA1:748623aaf663946bb35c3e40230170745c71c1a2
User & Date: mario 2020-05-23 14:05:33
Context
2020-05-23
19:34
slightly move text box around check-in: 8c2dabc86f user: mario tags: trunk
14:05
Introduce pt_opts handler for settings window check-in: 748623aaf6 user: mario tags: trunk
09:37
move Addons.xcu out from excessively nested folder structure (serves no factual purpose AFAIK; prolly just a Javaism) prepare Makefile for pythonloader/ population. check-in: 90cf15335d user: mario tags: trunk
Changes

Changes to Addons.xcu.

7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
..
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
..
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
        <node oor:name="S1" oor:op="replace">
          <prop oor:name="MergePoint"><value>.uno:ToolsMenu\.uno:WordCountDialog</value></prop>
          <prop oor:name="MergeCommand"><value>AddAfter</value></prop>
          <prop oor:name="MergeFallback"><value>AddPath</value></prop>
          <node oor:name="MenuItems">
            <node oor:name="M1" oor:op="replace">
              <prop oor:name="Title"><value xml:lang="en">PageTranslate</value></prop>
              <prop oor:name="ImageIdentifier" oor:type="xs:string"><value>vnd.include-once.pagetranslate.flags</value></prop>
              <node oor:name="Submenu">
                <node oor:name="M2" oor:op="replace">
                  <prop oor:name="Context" oor:type="xs:string"><value/></prop>
                  <prop oor:name="URL" oor:type="xs:string"><value>service:org.openoffice.comp.pyuno.pagetranslate?trigger&amp;lang=en</value></prop>
                  <prop oor:name="Title" oor:type="xs:string"><value/><value xml:lang="en-US">β†’English πŸ‡¬πŸ‡§</value></prop>
                  <prop oor:name="Target" oor:type="xs:string"><value>_self</value></prop>
                </node>
................................................................................
          <prop oor:name="MergeContext"><value/></prop>
          <node oor:name="ToolBarItems">
            <node oor:name="T2" oor:op="replace">
              <prop oor:name="URL" oor:type="xs:string"><value>private:separator</value></prop>
            </node>
            <node oor:name="T3" oor:op="replace">
              <prop oor:name="URL" oor:type="xs:string"><value>service:org.openoffice.comp.pyuno.pagetranslate?trigger&amp;lang=en</value></prop>
              <prop oor:name="ImageIdentifier" oor:type="xs:string"><value>vnd.include-once.pagetranslate.flags</value></prop>
              <prop oor:name="Target" oor:type="xs:string"><value>_self</value></prop>
              <prop oor:name="Context" oor:type="xs:string"><value>com.sun.star.text.TextDocument,com.sun.star.drawing.DrawingDocument,com.sun.star.presentation.PresentationDocument</value></prop>
              <prop oor:name="ControlType" oor:type="xs:string"><value>ImageButton</value></prop>
              <prop oor:name="Title" oor:type="xs:string"><value>Tβ†’πŸ‡¬πŸ‡§</value></prop>
            </node>
            <node oor:name="T4" oor:op="replace">
              <prop oor:name="URL" oor:type="xs:string"><value>service:org.openoffice.comp.pyuno.pagetranslate?page&amp;lang=locale</value></prop>
................................................................................
      </node>
    </node>

    <node oor:name="Images">
      <node oor:name="vnd.include-once.pagetranslate.flags" oor:op="replace">
        <prop oor:name="URL"><value>service:org.openoffice.comp.pyuno.pagetranslate?trigger&amp;lang=en</value></prop>
        <node oor:name="UserDefinedImages">
            <prop oor:name="ImageSmallURL" oor:type="xs:string"><value>vnd.sun.star.extension://vnd.include-once.pagetranslate/icons/flags_16.png</value></prop>
            <prop oor:name="ImageBigURL" oor:type="xs:string"><value>vnd.sun.star.extension://vnd.include-once.pagetranslate/icons/flags_26.png</value></prop>
        </node>
      </node>
    </node>

  </node>
</oor:component-data>







|







 







|







 







|
|
|





7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
..
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
..
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
        <node oor:name="S1" oor:op="replace">
          <prop oor:name="MergePoint"><value>.uno:ToolsMenu\.uno:WordCountDialog</value></prop>
          <prop oor:name="MergeCommand"><value>AddAfter</value></prop>
          <prop oor:name="MergeFallback"><value>AddPath</value></prop>
          <node oor:name="MenuItems">
            <node oor:name="M1" oor:op="replace">
              <prop oor:name="Title"><value xml:lang="en">PageTranslate</value></prop>
              <prop oor:name="ImageIdentifier" oor:type="xs:string"><value></value></prop>
              <node oor:name="Submenu">
                <node oor:name="M2" oor:op="replace">
                  <prop oor:name="Context" oor:type="xs:string"><value/></prop>
                  <prop oor:name="URL" oor:type="xs:string"><value>service:org.openoffice.comp.pyuno.pagetranslate?trigger&amp;lang=en</value></prop>
                  <prop oor:name="Title" oor:type="xs:string"><value/><value xml:lang="en-US">β†’English πŸ‡¬πŸ‡§</value></prop>
                  <prop oor:name="Target" oor:type="xs:string"><value>_self</value></prop>
                </node>
................................................................................
          <prop oor:name="MergeContext"><value/></prop>
          <node oor:name="ToolBarItems">
            <node oor:name="T2" oor:op="replace">
              <prop oor:name="URL" oor:type="xs:string"><value>private:separator</value></prop>
            </node>
            <node oor:name="T3" oor:op="replace">
              <prop oor:name="URL" oor:type="xs:string"><value>service:org.openoffice.comp.pyuno.pagetranslate?trigger&amp;lang=en</value></prop>
              <prop oor:name="ImageIdentifier" oor:type="xs:string"><value></value></prop>
              <prop oor:name="Target" oor:type="xs:string"><value>_self</value></prop>
              <prop oor:name="Context" oor:type="xs:string"><value>com.sun.star.text.TextDocument,com.sun.star.drawing.DrawingDocument,com.sun.star.presentation.PresentationDocument</value></prop>
              <prop oor:name="ControlType" oor:type="xs:string"><value>ImageButton</value></prop>
              <prop oor:name="Title" oor:type="xs:string"><value>Tβ†’πŸ‡¬πŸ‡§</value></prop>
            </node>
            <node oor:name="T4" oor:op="replace">
              <prop oor:name="URL" oor:type="xs:string"><value>service:org.openoffice.comp.pyuno.pagetranslate?page&amp;lang=locale</value></prop>
................................................................................
      </node>
    </node>

    <node oor:name="Images">
      <node oor:name="vnd.include-once.pagetranslate.flags" oor:op="replace">
        <prop oor:name="URL"><value>service:org.openoffice.comp.pyuno.pagetranslate?trigger&amp;lang=en</value></prop>
        <node oor:name="UserDefinedImages">
            <prop oor:name="ImageSmallURL" oor:type="xs:string"><value>%origin%/icons/flags_16.png</value></prop>
            <prop oor:name="ImageBigURL" oor:type="xs:string"><value>%origin%/icons/flags_26.png</value></prop>
        </node>                                                  <!--vnd.sun.star.extension://vnd.include-once.pagetranslate/icons/flags_26.png-->
      </node>
    </node>

  </node>
</oor:component-data>

Changes to Makefile.

2
3
4
5
6
7
8
9
10
11
12
13

install:
	unopkg remove vnd.include-once.pagetranslate
	unopkg add --log-file log.txt -s pagetranslate.oxt

oxt:
	version  --read pagetranslate.py  --incr  --write pagetranslate.py  --write description.xml
	zip pagetranslate.oxt -r META-INF pagetranslate.py *xcu *xcs *xdl *desc* icons

pythonloader:
	pip install requests -t pythonloader/ --upgrade








|

|
<

2
3
4
5
6
7
8
9
10
11

12

install:
	unopkg remove vnd.include-once.pagetranslate
	unopkg add --log-file log.txt -s pagetranslate.oxt

oxt:
	version  --read pagetranslate.py  --incr  --write pagetranslate.py  --write description.xml
	zip pagetranslate.oxt -r META-INF pagetranslate.py *xcu *xcs *xdl *desc* icons pythonpath/

#pythonpath:


Changes to OptionsDialog.xcu.

3
4
5
6
7
8
9
10
11
12


13
14
15
16
17
18
19
20
21
22
23
24
25


26
27
28
29
30
31
32
33
  oor:name="OptionsDialog" oor:package="org.openoffice.Office"
  xmlns:oor="http://openoffice.org/2001/registry"
  xmlns:xs="http://www.w2.org/2001/XMLSchema"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <node oor:name="Nodes">
    <node oor:name="Writer" oor:op="fuse">
      <node oor:name="Leaves">
        <node oor:name="vnd.include-once.OptionsPageTranslate" oor:op="fuse">
          <prop oor:name="Id">
            <value>vnd.include-once.OptionsPageTranslate</value>


          </prop>
          <prop oor:name="Label">
            <value xml:lang="en-US">PageTranslate</value>
          </prop>
          <prop oor:name="OptionsPage">
            <value>%origin%/OptionsDialog.xdl</value>
            <!--value>vnd.sun.star.extension://vnd.include-once.pagetranslate/OptionsPage.xdl</value-->
          </prop>
          <prop oor:name="EventHandlerService">
            <value></value>
            <!--value>service:org.openoffice.comp.pyuno.pagetranslate_options</value-->
            <!--value>org.libreoffice.comp.pyuno.LightproofOptionsEventHandler.en</value-->
            <!--value>vnd.include-once.OptionsPageSettings</value-->


          </prop>
        </node>
      </node>
    </node>
  </node>
</oor:component-data>
<!-- https://github.com/p&mdash;-q/OptionsDialog/tree/master/OptionsDialog/src -->
<!-- https://wiki.openoffice.org/wiki/Documentation/DevGuide/Extensions/Adding_a_Leaf_to_an_Existing_Node -->







|


>
>






<


<
<
<
|
>
>








3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

21
22



23
24
25
26
27
28
29
30
31
32
33
  oor:name="OptionsDialog" oor:package="org.openoffice.Office"
  xmlns:oor="http://openoffice.org/2001/registry"
  xmlns:xs="http://www.w2.org/2001/XMLSchema"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <node oor:name="Nodes">
    <node oor:name="Writer" oor:op="fuse">
      <node oor:name="Leaves">
        <node oor:name="vnd.include-once.OptionsPageTranslate.leaf" oor:op="fuse">
          <prop oor:name="Id">
            <value>vnd.include-once.OptionsPageTranslate</value>
            <!-- seems irrelevant / just an ID,
                 and can be different from EventHandlerService even -->
          </prop>
          <prop oor:name="Label">
            <value xml:lang="en-US">PageTranslate</value>
          </prop>
          <prop oor:name="OptionsPage">
            <value>%origin%/OptionsDialog.xdl</value>

          </prop>
          <prop oor:name="EventHandlerService">



            <value>vnd.include-once.OptionsPageTranslate</value>
            <!-- must match g_ImplementationHelper.addImplementation(class, "IMPLEMENTATION_NAME", ())
                 and doesn't even have to be a service:….pyuno.… URL or anything specific -->
          </prop>
        </node>
      </node>
    </node>
  </node>
</oor:component-data>
<!-- https://github.com/p&mdash;-q/OptionsDialog/tree/master/OptionsDialog/src -->
<!-- https://wiki.openoffice.org/wiki/Documentation/DevGuide/Extensions/Adding_a_Leaf_to_an_Existing_Node -->

Changes to OptionsDialog.xdl.

1
2
3
4
5
6
7
8


9
10
11



12



13
14
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE dlg:window PUBLIC "-//OpenOffice.org//DTD OfficeDocument 1.0//EN" "dialog.dtd">
<dlg:window xmlns:dlg="http://openoffice.org/2000/dialog" xmlns:script="http://openoffice.org/2000/script"
    dlg:id="OptionsPageTranslate" dlg:left="110" dlg:top="50" dlg:width="190" dlg:height="150"
    dlg:closeable="false" dlg:moveable="false" dlg:title="Title" dlg:withtitlebar="false">
 <dlg:bulletinboard>
  <dlg:checkbox dlg:id="useDeepL" dlg:tab-index="0" dlg:left="10" dlg:top="10" dlg:width="160" dlg:height="12" dlg:help-text="instead of the default Google Translate" dlg:value="use DeepL translation service" dlg:checked="false"/>
  <dlg:titledbox dlg:id="FrameControl1" dlg:tab-index="1" dlg:left="25" dlg:top="25" dlg:width="155" dlg:height="40" dlg:help-text="requires an API key / else will use *SLOWER* web page requests">


   <dlg:title dlg:value="API key"/>
   <dlg:textfield dlg:id="apiKey" dlg:tab-index="2" dlg:left="10" dlg:top="15" dlg:width="135" dlg:height="12" dlg:help-text="Key required for faster translation service"/>
  </dlg:titledbox>



  <dlg:checkbox dlg:id="debug" dlg:tab-index="3" dlg:left="10" dlg:top="70" dlg:width="160" dlg:height="12" dlg:value="additonal debugging" dlg:checked="true" dlg:help-text="Log file in /tmp/pagetranslate-libreoffice.txt"/>



 </dlg:bulletinboard>
</dlg:window>


|
<
<

<
<
>
>

<

>
>
>
|
>
>
>

|
1
2
3


4


5
6
7

8
9
10
11
12
13
14
15
16
17
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE dlg:window PUBLIC "-//OpenOffice.org//DTD OfficeDocument 1.0//EN" "dialog.dtd">
<dlg:window xmlns:dlg="http://openoffice.org/2000/dialog" xmlns:script="http://openoffice.org/2000/script" dlg:id="OptionsPageTranslate" dlg:left="110" dlg:top="50" dlg:width="220" dlg:height="150" dlg:closeable="true" dlg:moveable="true" dlg:title="Title" dlg:withtitlebar="false">


 <dlg:bulletinboard>


  <dlg:textfield dlg:id="apiKey" dlg:tab-index="1" dlg:left="35" dlg:top="66" dlg:width="125" dlg:height="12" dlg:help-text="Key required for faster translation service"/>
  <dlg:titledbox dlg:id="FrameControl1" dlg:tab-index="0" dlg:left="25" dlg:top="55" dlg:width="145" dlg:height="32" dlg:help-text="requires an API key / else will use *SLOWER* web page requests">
   <dlg:title dlg:value="API key"/>

  </dlg:titledbox>
  <dlg:checkbox dlg:id="debug" dlg:tab-index="2" dlg:left="10" dlg:top="110" dlg:width="160" dlg:height="12" dlg:help-text="Log file in /tmp/pagetranslate-libreoffice.txt" dlg:value="additonal debugging" dlg:checked="true"/>
  <dlg:checkbox dlg:id="CheckBox1" dlg:tab-index="3" dlg:left="10" dlg:top="95" dlg:width="160" dlg:height="12" dlg:help-text="Temporary placeholders instead of iterating over newline breaks" dlg:value="quick paragraph linebreak handling" dlg:checked="false"/>
  <dlg:radiogroup>
   <dlg:radio dlg:id="google" dlg:tab-index="4" dlg:left="10" dlg:top="10" dlg:width="160" dlg:height="12" dlg:value="use Google Translate web service (standard)" dlg:group-name="backend" dlg:checked="true"/>
   <dlg:radio dlg:id="deepl_web" dlg:tab-index="5" dlg:left="10" dlg:top="26" dlg:width="160" dlg:height="12" dlg:value="use DeepL web interface (slower?)" dlg:group-name="backend"/>
   <dlg:radio dlg:id="deepl_api" dlg:tab-index="6" dlg:left="10" dlg:top="40" dlg:width="160" dlg:height="12" dlg:value="use DeepL translation API (faster/better formatting?)" dlg:group-name="backend"/>
  </dlg:radiogroup>
 </dlg:bulletinboard>
</dlg:window>

Changes to OptionsSchema.xcs.

49
50
51
52
53
54
55
56
        <prop oor:name="lstLikeMostSelected" oor:type="oor:short-list">
          <value>0</value>
        </prop>
      </group>
    </group>
  </component>
</oor:component-schema>
y







<
49
50
51
52
53
54
55

        <prop oor:name="lstLikeMostSelected" oor:type="oor:short-list">
          <value>0</value>
        </prop>
      </group>
    </group>
  </component>
</oor:component-schema>

Changes to description.xml.

1
2
3
4
5
6
7
8
9
10
11
<?xml version="1.0" encoding="UTF-8"?>
<description xmlns="http://openoffice.org/extensions/description/2006" xmlns:dep="http://openoffice.org/extensions/description/2006" xmlns:xlink="http://www.w3.org/1999/xlink">
  <identifier value="vnd.include-once.pagetranslate"/>
  <version value="1.0.8"/>
  <display-name>
    <name lang="en">PageTranslate</name>
  </display-name>
  <dependencies>
    <OpenOffice.org-minimal-version value="3.0" dep:name="OpenOffice.org 3.0"/>
  </dependencies>
  <registration>



|







1
2
3
4
5
6
7
8
9
10
11
<?xml version="1.0" encoding="UTF-8"?>
<description xmlns="http://openoffice.org/extensions/description/2006" xmlns:dep="http://openoffice.org/extensions/description/2006" xmlns:xlink="http://www.w3.org/1999/xlink">
  <identifier value="vnd.include-once.pagetranslate"/>
  <version value="1.0.65"/>
  <display-name>
    <name lang="en">PageTranslate</name>
  </display-name>
  <dependencies>
    <OpenOffice.org-minimal-version value="3.0" dep:name="OpenOffice.org 3.0"/>
  </dependencies>
  <registration>

Changes to pagetranslate.py.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

20
21
22
23
24
25
26
27
28
29
30
..
36
37
38
39
40
41
42


43
44
45
46
47
48
49
..
56
57
58
59
60
61
62

63
64
65
66
67
68
69
70
71
72
73
..
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
...
149
150
151
152
153
154
155
156
157
158
159
160
161




162
163
164
165
166
167
168
...
295
296
297
298
299
300
301



























302
303
304
305
306
307
308
309
310
#!/usr/bin/python
# encoding: utf-8
# api: uno
# type: callback
# category: language
# title: PageTranslate
# description: Action button to get whole Writer document translated
# version: 1.0.8
# state: beta
# author: mario
# url: https://fossil.include-once.org/pagetranslate/
# depends: python:requests (>= 2.5)
# pack: *.py, META-INF/*, pkg-desc, *.x*, icons/*
# license: GNU LGPL 2.1
# forked-from: TradutorLibreText (Claudemir de Almeida Rosa)
# config: -
# 
# LibreOffice plugin for translating documents that's supposed to retain formatting.
# Per default does not require a text selection to operate, but works on the whole

# page. The original mode (TradutorLibreText) is still supported. But also uses the
# default target language (English).
# Additional operation modes/languages are available through the Tools>PageTranslate
# menu.
#
# Beware that Writer freezes during the dozens of translation calls to Google.
# In particular long documents might take ages, because each paragraph/line or
# text longer 1900 chars causes another roundtrip.
#
# Basic support for Draw/Impress documents is now provided. (No text selection
# mode there however).
................................................................................
# OpenOffice UNO bridge
import uno, unohelper
from com.sun.star.task import XJobExecutor
from com.sun.star.awt.MessageBoxButtons import BUTTONS_OK, BUTTONS_OK_CANCEL, BUTTONS_YES_NO, BUTTONS_YES_NO_CANCEL, BUTTONS_RETRY_CANCEL, BUTTONS_ABORT_IGNORE_RETRY
from com.sun.star.awt.MessageBoxButtons import DEFAULT_BUTTON_OK, DEFAULT_BUTTON_CANCEL, DEFAULT_BUTTON_RETRY, DEFAULT_BUTTON_YES, DEFAULT_BUTTON_NO, DEFAULT_BUTTON_IGNORE
from com.sun.star.awt.MessageBoxType import MESSAGEBOX, INFOBOX, WARNINGBOX, ERRORBOX, QUERYBOX
from com.sun.star.beans import PropertyValue


# sys modules
import string
import json
import sys
from traceback import format_exc
from tempfile import gettempdir
import re
................................................................................
    "Accept-Language": "*; q=1.0",
    "Accept-Encoding": "utf-8"
}
import urllib
from urllib.parse import urlencode, quote, quote_plus
try:
    import requests

    http = requests.Session()
    http.headers.update(http_headers)
except Exception as e:
    log.ERROR("pythonpath/requests/ not found", e, "β†’ Install via `pip install requests` in your LibreOffice program/ folder")
    requests = None
    from urllib.request import urlopen, Request
    ssl_args = dict()
    if sys.platform != 'win32':
        import ssl
        myssl = ssl.create_default_context();
        myssl.check_hostname = False
................................................................................
    rx_gtrans = re.compile('class="t0">(.+?)</div>', re.S)
    rx_splitpara = re.compile("(.{1,1895\.}|.{1,1900}\s|.*$)", re.S)
    rx_empty = re.compile("^[\s\d,.:;Β§():-]+$")
    rx_letters = re.compile("\w\w+", re.UNICODE)
    rx_breakln = re.compile("\s?/\s?#\s?Β§\s?/\s?")

    def __init__(self, params={}):
        self.params = params

    # request text translation from google
    def askgoogle(self, text, dst_lang="en", src_lang='auto'):
        # fetch translation page
        url = "http://translate.google.com/m?hl=%s&sl=%s&q=%s" % (
            dst_lang, src_lang, urllib.parse.quote_plus(text)
        )
................................................................................
class via_deepl_api(via_deepl_web):
    pass


# Office plugin
class pagetranslate(unohelper.Base, XJobExecutor):

    # config + command args
    params = dict(
        mode = "page",
        lang = "en",
        crlf = "iterate",
        log = "debug"




    )
    t = None #via_googletranslate(self.params)

    # gets instantiated as XJobExecutor by LibreOffice
    def __init__(self, ctx):
        log.info("init")
        self.ctx = ctx
................................................................................
        ctx = uno.getComponentContext()
        sm = ctx.ServiceManager
        sv = sm.createInstanceWithContext("com.sun.star.awt.Toolkit", ctx)
        myBox = sv.createMessageBox(ParentWin, MsgType, MsgButtons, MsgTitle, MsgText)
        return myBox.execute()






























# register with LibreOffice
g_ImplementationHelper = unohelper.ImplementationHelper()
g_ImplementationHelper.addImplementation(
    pagetranslate,
    "org.openoffice.comp.pyuno.pagetranslate",
    ("com.sun.star.task.Job",),
)
#g_ImplementationHelper.addImplementation( pt_opts(), "org.libreoffice.comp.pyuno.pagetranslate_options", () )







|











>
|
|
<
|







 







>
>







 







>



|







 







|







 







|

|
|
|
|
>
>
>
>







 







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>








|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

23
24
25
26
27
28
29
30
..
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
..
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
..
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
...
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
...
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
#!/usr/bin/python
# encoding: utf-8
# api: uno
# type: callback
# category: language
# title: PageTranslate
# description: Action button to get whole Writer document translated
# version: 1.0.65
# state: beta
# author: mario
# url: https://fossil.include-once.org/pagetranslate/
# depends: python:requests (>= 2.5)
# pack: *.py, META-INF/*, pkg-desc, *.x*, icons/*
# license: GNU LGPL 2.1
# forked-from: TradutorLibreText (Claudemir de Almeida Rosa)
# config: -
# 
# LibreOffice plugin for translating documents that's supposed to retain formatting.
# Per default does not require a text selection to operate, but works on the whole
# page.
# The original mode (TradutorLibreText) is still supported and used whenever a text
# portion is selected. It also uses the default target language (English) then.

# Unless a different mode/language from the Tools>PageTranslate menu is requested.
#
# Beware that Writer freezes during the dozens of translation calls to Google.
# In particular long documents might take ages, because each paragraph/line or
# text longer 1900 chars causes another roundtrip.
#
# Basic support for Draw/Impress documents is now provided. (No text selection
# mode there however).
................................................................................
# OpenOffice UNO bridge
import uno, unohelper
from com.sun.star.task import XJobExecutor
from com.sun.star.awt.MessageBoxButtons import BUTTONS_OK, BUTTONS_OK_CANCEL, BUTTONS_YES_NO, BUTTONS_YES_NO_CANCEL, BUTTONS_RETRY_CANCEL, BUTTONS_ABORT_IGNORE_RETRY
from com.sun.star.awt.MessageBoxButtons import DEFAULT_BUTTON_OK, DEFAULT_BUTTON_CANCEL, DEFAULT_BUTTON_RETRY, DEFAULT_BUTTON_YES, DEFAULT_BUTTON_NO, DEFAULT_BUTTON_IGNORE
from com.sun.star.awt.MessageBoxType import MESSAGEBOX, INFOBOX, WARNINGBOX, ERRORBOX, QUERYBOX
from com.sun.star.beans import PropertyValue
from com.sun.star.awt import XActionListener, XContainerWindowEventHandler
from com.sun.star.lang import Locale, XServiceInfo, XInitialization
# sys modules
import string
import json
import sys
from traceback import format_exc
from tempfile import gettempdir
import re
................................................................................
    "Accept-Language": "*; q=1.0",
    "Accept-Encoding": "utf-8"
}
import urllib
from urllib.parse import urlencode, quote, quote_plus
try:
    import requests
    log.info(requests.__file__)
    http = requests.Session()
    http.headers.update(http_headers)
except Exception as e:
    log.error("pythonpath/requests/ not found")
    requests = None
    from urllib.request import urlopen, Request
    ssl_args = dict()
    if sys.platform != 'win32':
        import ssl
        myssl = ssl.create_default_context();
        myssl.check_hostname = False
................................................................................
    rx_gtrans = re.compile('class="t0">(.+?)</div>', re.S)
    rx_splitpara = re.compile("(.{1,1895\.}|.{1,1900}\s|.*$)", re.S)
    rx_empty = re.compile("^[\s\d,.:;Β§():-]+$")
    rx_letters = re.compile("\w\w+", re.UNICODE)
    rx_breakln = re.compile("\s?/\s?#\s?Β§\s?/\s?")

    def __init__(self, params={}):
        self.params = params  # config+argparse

    # request text translation from google
    def askgoogle(self, text, dst_lang="en", src_lang='auto'):
        # fetch translation page
        url = "http://translate.google.com/m?hl=%s&sl=%s&q=%s" % (
            dst_lang, src_lang, urllib.parse.quote_plus(text)
        )
................................................................................
class via_deepl_api(via_deepl_web):
    pass


# Office plugin
class pagetranslate(unohelper.Base, XJobExecutor):

    # defaualts + config + command args
    params = dict(
        mode = "page",      # "trigger"/"page", or "tradutor"
        lang = "en",        # target language, or "paragraph", or "locale"
        crlf = "iterate",   # split paragraph sentences? or "quick" for temporary placeholder
        log = "debug",      # logging level
        google = 1,         # backend to use
        deepl_web = 0,
        deepl_api = 0,
        deepl_key = "",
    )
    t = None #via_googletranslate(self.params)

    # gets instantiated as XJobExecutor by LibreOffice
    def __init__(self, ctx):
        log.info("init")
        self.ctx = ctx
................................................................................
        ctx = uno.getComponentContext()
        sm = ctx.ServiceManager
        sv = sm.createInstanceWithContext("com.sun.star.awt.Toolkit", ctx)
        myBox = sv.createMessageBox(ParentWin, MsgType, MsgButtons, MsgTitle, MsgText)
        return myBox.execute()



# @src https://forum.openoffice.org/en/forum/viewtopic.php?f=20&t=96509 β†’ the __init__(,args) parameter was invalid
class pt_opts(unohelper.Base, XContainerWindowEventHandler, XServiceInfo):
    #sid = "org.libreoffice.comp.pyuno.pagetranslate_options"
    #sid = "org.openoffice.comp.pyuno.pagetranslate_options"
    #sid = "service:org.openoffice.comp.pyuno.pagetranslate_options"
    sid = "vnd.include-once.OptionsPageTranslate"

    def __init__(self, ctx, *kargs):
        log.info("pt_opts.init")
        self.ctx = ctx

    # XContainerWindowEventHandler
    def getSupportedMethodNames(self): return ("external_event",)
    # XServiceInfo
    def supportsService(self, name): return (name == self.sid)
    def getImplementationName(self): return self.sid
    def getSupportedServiceNames(self): return (self.sid,)
    def getServiceNames(self): return (self.sid,)
    
    def callHandlerMethod(self, window, ev, name):
        log.info(window)
        log.info(ev)
        log.info(name)
        return True
   


# register with LibreOffice
g_ImplementationHelper = unohelper.ImplementationHelper()
g_ImplementationHelper.addImplementation(
    pagetranslate,
    "org.openoffice.comp.pyuno.pagetranslate",
    ("com.sun.star.task.Job",),
)
g_ImplementationHelper.addImplementation( pt_opts, pt_opts.sid, () )

Added pythonpath/Makefile.



















>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
# The pythonpath/ directory can be packaged alongside, to inject new python
# packages into LibreOffices` python bundle. Which really just makes sense
# for the Windows package, because distro-packaged Office setups utilize the
# system python path.


all:
	pip install requests -t ./ --upgrade