Check-in [ad382edca0]
Many hyperlinks are disabled.
Use anonymous login
to enable hyperlinks.
Overview
| Comment: | rough privacy judgement |
|---|---|
| Downloads: | Tarball | ZIP archive | SQL archive |
| Timelines: | family | ancestors | descendants | both | trunk |
| Files: | files | file ages | folders |
| SHA1: |
ad382edca09755767b020a95869204df |
| User & Date: | mario 2022-10-23 05:51:31 |
Context
|
2022-10-23
| ||
| 22:09 | incorporate content.xml translation into tk_translate (→ [File] button) check-in: 592fcfe0ac user: mario tags: trunk | |
| 05:51 | rough privacy judgement check-in: ad382edca0 user: mario tags: trunk | |
| 05:51 | faux: move params= to .get check-in: 72453b0947 user: mario tags: trunk | |
Changes
Changes to doc.py.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
#!/usr/bin/env python3
# api: cli
# title: document backends
# description: markdown table from class attributes
# version: 0.1
#
import sys
sys.path.append("pythonpath")
from translationbackends import BackendUtils
# Generate overview list
def document_backends():
| | | > > | | | | | 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 |
#!/usr/bin/env python3
# api: cli
# title: document backends
# description: markdown table from class attributes
# version: 0.1
#
import sys
sys.path.append("pythonpath")
from translationbackends import BackendUtils
# Generate overview list
def document_backends():
print("| service | brief summary | lang_detect | error msgs | api key🔑| test quali | prvcy |")
print("|----------------|---------------------------------------------|-------------|------------|----------|------------|-------|")
_re = ["log", "popup"]
_kr = ["-", "required"]
classes = {cls.__name__: cls for cls in set(BackendUtils.subclasses())}
for name in sorted(classes):
c = classes[name]
print("| {name:<14} |{doc:<45}| {lang:<11} | {error:<10} | {key:<8} | {quality:<10s} | {privacyy:<5s} |".format(
name=name, doc=c.__doc__, lang=c.lang_detect, error=_re[c.raises_error],
key=_kr[c.requires_key], quality="+" * int(10 * c.is_tested), privacyy="+" * int(5 * c.privacy)
))
document_backends()
|
Changes to pythonpath/translationbackends.py.
| ︙ | ︙ | |||
38 39 40 41 42 43 44 | #import sys #import os import functools import subprocess import shlex import logging as log from traceback import format_exc | < | 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
#import sys
#import os
import functools
import subprocess
import shlex
import logging as log
from traceback import format_exc
from httprequests import http, quote_plus, update_headers
class rx: # pylint: disable=invalid-name, too-few-public-methods
#""" regex shorthands """
# Google Translate
|
| ︙ | ︙ | |||
75 76 77 78 79 80 81 82 83 84 85 86 87 88 |
Main API is .translate() and .linebreakwise().
With .skip() now also invoked from main to ignore empty text portions.
"""
match = r"ab$tract" # regex for assign_service()
requires_key = True # 🛈 documents api_key dependency
raises_error = False # 🛈 "forgiving" backends (Google) just return original text
is_tested = 1.0 # 🛈 actually probed for functionality
lang_detect = "-" # 🛈 service understands source="auto"?
max_len = 1900 # translate/spliterate segmenting
def __init__(self, **params):
""" Store and prepare some parameters (**params contains lang= and from=). """
self.params = params
self.log = log.getLogger(type(self).__name__)
| > | 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 |
Main API is .translate() and .linebreakwise().
With .skip() now also invoked from main to ignore empty text portions.
"""
match = r"ab$tract" # regex for assign_service()
requires_key = True # 🛈 documents api_key dependency
raises_error = False # 🛈 "forgiving" backends (Google) just return original text
is_tested = 1.0 # 🛈 actually probed for functionality
privacy = 0.0 # 🛈 rough privacy/sensitivity score
lang_detect = "-" # 🛈 service understands source="auto"?
max_len = 1900 # translate/spliterate segmenting
def __init__(self, **params):
""" Store and prepare some parameters (**params contains lang= and from=). """
self.params = params
self.log = log.getLogger(type(self).__name__)
|
| ︙ | ︙ | |||
209 210 211 212 213 214 215 |
@staticmethod
def subclasses(base=None):
""" recurse subclasses """
collect = (base or BackendUtils).__subclasses__()
for cls in collect:
collect.extend(BackendUtils.subclasses(cls))
| | | 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 |
@staticmethod
def subclasses(base=None):
""" recurse subclasses """
collect = (base or BackendUtils).__subclasses__()
for cls in collect:
collect.extend(BackendUtils.subclasses(cls))
return list(set(collect))
def __str__(self):
""" Summary with type/params and overriden funcs. """
try:
funcs = dict(list(
set(self.__class__.__dict__.items()) - set(BackendUtils.__dict__.items())
)).keys()
|
| ︙ | ︙ | |||
238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 |
""" broadest language support (130) """
match = r"^google$ | ^google [\s\-_]* (translate|web)$"
raises_error = False
requires_key = False
lang_detect = "auto"
is_tested = 1.0 # main backend, well tested
max_len = 1900
# request text translation from google
def fetch(self, text):
dst_lang = self.params["lang"]
src_lang = self.params["from"] # "auto" works
# fetch translation page
url = "https://translate.google.com/m?tl=%s&hl=%s&sl=%s&q=%s" % (
dst_lang, dst_lang, src_lang, quote_plus(text.encode("utf-8"))
)
| > | > | 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 |
""" broadest language support (130) """
match = r"^google$ | ^google [\s\-_]* (translate|web)$"
raises_error = False
requires_key = False
lang_detect = "auto"
is_tested = 1.0 # main backend, well tested
privacy = 0.1 # Google
max_len = 1900
# request text translation from google
def fetch(self, text):
dst_lang = self.params["lang"]
src_lang = self.params["from"] # "auto" works
# fetch translation page
url = "https://translate.google.com/m?tl=%s&hl=%s&sl=%s&q=%s" % (
dst_lang, dst_lang, src_lang, quote_plus(text.encode("utf-8"))
)
result = http.get(url).text
# extract content from text <div>
found = rx.gtrans.search(result)
if found:
text = found.group(1)
text = self.html_unescape(text)
else:
self.log.warning("NO TRANSLATION RESULT EXTRACTED: %s", html)
self.log.debug("ORIG TEXT: %r", text)
return text
# variant that uses the AJAX or API interface
class GoogleAjax(BackendUtils):
""" alternative/faster interface """
match = r"^google.*ajax"
raises_error = False
requires_key = False
lang_detect = "auto"
is_tested = 0.9 # main backend
privacy = 0.1 # Google
max_len = 1900
# request text translation from google
def fetch(self, text):
resp = http.get(
url="https://translate.googleapis.com/translate_a/single",
params={
|
| ︙ | ︙ | |||
301 302 303 304 305 306 307 308 309 310 311 312 313 314 |
""" commercial GTrans variant """
match = r"^google.*(cloud|api)"
requires_key = True
raises_error = True
lang_detect = "auto"
is_tested = 0.0 # can't be bothered to get a key
max_len = 1<<16 # probably unlimited
def translate(self, text):
resp = http.get(
"https://translation.googleapis.com/language/translate/v2",
data={
"q": text,
| > | 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 |
""" commercial GTrans variant """
match = r"^google.*(cloud|api)"
requires_key = True
raises_error = True
lang_detect = "auto"
is_tested = 0.0 # can't be bothered to get a key
privacy = 0.3 # more private, but still Google
max_len = 1<<16 # probably unlimited
def translate(self, text):
resp = http.get(
"https://translation.googleapis.com/language/translate/v2",
data={
"q": text,
|
| ︙ | ︙ | |||
330 331 332 333 334 335 336 337 338 339 340 341 342 343 |
""" 85 languages, MS Translte w/ privacy """
match = r"^duck | duckduck | duckgo | ^DDG"
requires_key = False
raises_error = True
lang_detect = "auto"
is_tested = 0.9 # regularly tested
max_len = 2000
def __init__(self, **params):
BackendUtils.__init__(self, **params)
# fetch likely search page
vqd = re.findall(
| > | 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 |
""" 85 languages, MS Translte w/ privacy """
match = r"^duck | duckduck | duckgo | ^DDG"
requires_key = False
raises_error = True
lang_detect = "auto"
is_tested = 0.9 # regularly tested
privacy = 0.9 # reputation
max_len = 2000
def __init__(self, **params):
BackendUtils.__init__(self, **params)
# fetch likely search page
vqd = re.findall(
|
| ︙ | ︙ | |||
380 381 382 383 384 385 386 387 388 389 390 391 392 393 |
""" 35 languages, screen scraping+API """
match = r"^pons \s* (text|web|$)"
requires_key = False
raises_error = False # well, silent per default, only for API rejects
lang_detect = "auto"
is_tested = 0.5 # infrequent
max_len = 5000
init_url = "https://en.pons.com/text-translation"
api_url = "https://api.pons.com/text-translation-web/v4/translate?locale=en"
def __init__(self, **params):
BackendUtils.__init__(self, **params)
self.session = self.impression_id()
| > | 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 |
""" 35 languages, screen scraping+API """
match = r"^pons \s* (text|web|$)"
requires_key = False
raises_error = False # well, silent per default, only for API rejects
lang_detect = "auto"
is_tested = 0.5 # infrequent
privacy = 0.2 # GDPR, but unclear
max_len = 5000
init_url = "https://en.pons.com/text-translation"
api_url = "https://api.pons.com/text-translation-web/v4/translate?locale=en"
def __init__(self, **params):
BackendUtils.__init__(self, **params)
self.session = self.impression_id()
|
| ︙ | ︙ | |||
431 432 433 434 435 436 437 438 439 440 441 442 443 444 |
""" online instaces of Argos/OpenNMT """
match = r"^libre"
requires_key = True
raises_error = True
lang_detect = "langdetect"
is_tested = 0.7 # passing
api_url = "https://libretranslate.com/translate"
api_free = [ # https://github.com/LibreTranslate/LibreTranslate#mirrors
"https://libretranslate.de/translate",
"https://translate.argosopentech.com/translate",
"https://translate.terraprint.co/translate",
"https://lt.vern.cc/translate",
]
| > | 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 |
""" online instaces of Argos/OpenNMT """
match = r"^libre"
requires_key = True
raises_error = True
lang_detect = "langdetect"
is_tested = 0.7 # passing
privacy = 0.0 # no statement
api_url = "https://libretranslate.com/translate"
api_free = [ # https://github.com/LibreTranslate/LibreTranslate#mirrors
"https://libretranslate.de/translate",
"https://translate.argosopentech.com/translate",
"https://translate.terraprint.co/translate",
"https://lt.vern.cc/translate",
]
|
| ︙ | ︙ | |||
484 485 486 487 488 489 490 491 492 493 494 495 |
""" 15 langs, screen scraping access """
match = r"^deepl [\s_\-]* web"
requires_key = False
raises_error = True
lang_detect = "auto" # source_lang_user_selected
is_tested = 0.5 # infrequent checks
max_len = 1000
def __init__(self, **params):
BackendUtils.__init__(self, **params)
self.lang = params["lang"].upper()
| > | | 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 |
""" 15 langs, screen scraping access """
match = r"^deepl [\s_\-]* web"
requires_key = False
raises_error = True
lang_detect = "auto" # source_lang_user_selected
is_tested = 0.5 # infrequent checks
privacy = 0.1 # public api
max_len = 1000
def __init__(self, **params):
BackendUtils.__init__(self, **params)
self.lang = params["lang"].upper()
self.id_ = random.randrange(202002000, 959009000) # e.g. 702005000, arbitrary, part of jsonrpc req-resp association
self.sess = str(uuid.uuid4()) # e.g. 233beb7c-96bc-459c-ae20-157c0bebb2e4
self.dap_uid = "" # e.g. ef629644-3d1b-41a4-a2de-0626d23c99ee
# fetch homepage (redundant)
self.versions = dict(
re.findall(
r"([\w.]+)\?v=(\d+)",
|
| ︙ | ︙ | |||
588 589 590 591 592 593 594 |
"priority": -1,
"timestamp": int(time.time()*1000),
}
})
def fetch(self, text):
# delay?
| | | 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 |
"priority": -1,
"timestamp": int(time.time()*1000),
}
})
def fetch(self, text):
# delay?
time.sleep(random.randrange(1, 15) / 10.0)
# request
resp = http.post(
"https://www2.deepl.com/jsonrpc",
data=self.rpc(text),
headers={"Referer": "https://www.deepl.com/translator", "Content-Type": "application/json"}
)
|
| ︙ | ︙ | |||
622 623 624 625 626 627 628 629 630 631 632 633 634 635 |
""" High quality AI translation, 15 langs"""
match = r"^deepl (free|translate|api|pro[\s/_-])*"
requires_key = True
raises_error = True
lang_detect = "auto"
is_tested = 0.1 # only free ever tested
max_len = 50000
api_url = "https://api.deepl.com/v2/translate"
api_free = "https://api-free.deepl.com/v2/translate"
headers = {}
def __init__(self, **params):
DeeplWeb.__init__(self, **params)
| > | 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 |
""" High quality AI translation, 15 langs"""
match = r"^deepl (free|translate|api|pro[\s/_-])*"
requires_key = True
raises_error = True
lang_detect = "auto"
is_tested = 0.1 # only free ever tested
privacy = 0.6 # GDPR, excluding free version
max_len = 50000
api_url = "https://api.deepl.com/v2/translate"
api_free = "https://api-free.deepl.com/v2/translate"
headers = {}
def __init__(self, **params):
DeeplWeb.__init__(self, **params)
|
| ︙ | ︙ | |||
687 688 689 690 691 692 693 694 695 696 697 698 699 700 |
""" Diverse services, text + dictionary """
match = r"linguee | pons\sdict | QCRI | yandex | libre | ^D-?T: | \(D-?T\)"
requires_key = False # Well, sometimes
raises_error = True
lang_detect = "mixed"
is_tested = 0.5 # quality varies between D-T handlers
identify = [
"linguee", "pons", "qcri", "yandex", "deepl", "free",
"microsoft", "papago", "libre", "google"
]
def __init__(self, **params):
# config+argparse
| > | 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 |
""" Diverse services, text + dictionary """
match = r"linguee | pons\sdict | QCRI | yandex | libre | ^D-?T: | \(D-?T\)"
requires_key = False # Well, sometimes
raises_error = True
lang_detect = "mixed"
is_tested = 0.5 # quality varies between D-T handlers
privacy = 0.0 # mixed backends
identify = [
"linguee", "pons", "qcri", "yandex", "deepl", "free",
"microsoft", "papago", "libre", "google"
]
def __init__(self, **params):
# config+argparse
|
| ︙ | ︙ | |||
732 733 734 735 736 737 738 |
flags = {
self.silence: {"linguee", "pons"},
self.from_words: {"linguee", "pons"},
self.lang_lookup: {"linguee", "pons", "libre"},
}
for wrap, when in flags.items():
if set(self.backends) & set(when):
| | > | | 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 |
flags = {
self.silence: {"linguee", "pons"},
self.from_words: {"linguee", "pons"},
self.lang_lookup: {"linguee", "pons", "libre"},
}
for wrap, when in flags.items():
if set(self.backends) & set(when):
log.debug("wrap %s with %s", func, wrap)
func = wrap(func)
return func
# shorten language co-DE to just two-letter moniker
@staticmethod
def coarse_lang(lang):
if lang.find("-") > 0:
lang = re.sub(r"(?<!zh)-\w+", "", lang)
return lang
# Online version of deep-translator (potential workaround for Python2-compat)
class DeepTransApi(DeepTranslator):
""" Online interface API """
match = r"deep-?(trans|translator)-*(api|online) | ^DT[AO]:"
requires_key = False # Well, sometimes
raises_error = True
lang_detect = "mixed"
is_tested = 0.4 # though this one seems stable
privacy = 0.0 # mixed backends
api_url = "https://deep-translator-api.azurewebsites.net/%s/"
def assign_backend(self):
# just store backend here:
if self.backends:
self.backend = self.backends[0]
else:
self.backend = "google"
# overrides self.translate==None
return self.translate_api
def translate_api(self, text):
# https://deep-translator-api.azurewebsites.net/docs
self.args["text"] = text
resp = http.post(
self.api_url % self.backend,
json=self.args,
)
self.log.debug(resp.content)
resp.raise_for_status()
return resp.json()["translation"]
# MyMemory, only allows max 500 bytes input per API request. Requires langdetect
# because there's no "auto" detection.
#
|
| ︙ | ︙ | |||
793 794 795 796 797 798 799 800 801 802 803 804 805 806 |
""" Dictionary-based, 140 languages """
match = r"^mymemory | translated\.net"
requires_key = False
raises_error = True
lang_detect = "langdetect"
is_tested = 0.5 # infrequent
max_len = 5000
# API
def fetch(self, text):
src_lang = self.source_lang(text)
dst_lang = self.params["lang"]
if dst_lang == src_lang:
| > | 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 |
""" Dictionary-based, 140 languages """
match = r"^mymemory | translated\.net"
requires_key = False
raises_error = True
lang_detect = "langdetect"
is_tested = 0.5 # infrequent
privacy = 0.0 # might even leave traces in accumulation
max_len = 5000
# API
def fetch(self, text):
src_lang = self.source_lang(text)
dst_lang = self.params["lang"]
if dst_lang == src_lang:
|
| ︙ | ︙ | |||
836 837 838 839 840 841 842 843 844 845 846 847 848 849 |
""" Diverse backends """
match = r"^command | ^CLI | tool | program"
requires_key = False
raises_error = False
lang_detect = "mixed"
is_tested = 0.5 # infrequent
def __init__(self, **params):
BackendUtils.__init__(self, **params)
self.cmd = params.get("cmd", "translate-cli -o -f auto -t {lang} {text}")
# pipe text through external program
def translate(self, text):
| > | 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 |
""" Diverse backends """
match = r"^command | ^CLI | tool | program"
requires_key = False
raises_error = False
lang_detect = "mixed"
is_tested = 0.5 # infrequent
privacy = 0.0 # mixed
def __init__(self, **params):
BackendUtils.__init__(self, **params)
self.cmd = params.get("cmd", "translate-cli -o -f auto -t {lang} {text}")
# pipe text through external program
def translate(self, text):
|
| ︙ | ︙ | |||
879 880 881 882 883 884 885 886 887 888 889 890 891 892 |
""" professional service, 50 languages """
match = r"^systran"
requires_key = True
raises_error = True
lang_detect = "auto"
is_tested = 0.2 # actually tested now
max_len = 10000
api_url = "https://api-translate.systran.net/translation/text/translate"
def fetch(self, text):
resp = http.post(
url=self.api_url,
data={
| > | 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 |
""" professional service, 50 languages """
match = r"^systran"
requires_key = True
raises_error = True
lang_detect = "auto"
is_tested = 0.2 # actually tested now
privacy = 0.8 # GDPR compliant
max_len = 10000
api_url = "https://api-translate.systran.net/translation/text/translate"
def fetch(self, text):
resp = http.post(
url=self.api_url,
data={
|
| ︙ | ︙ | |||
915 916 917 918 919 920 921 922 923 924 925 926 927 928 |
""" Language combos hinge on trained models"""
match = r"^argos | NMT"
requires_key = False
raises_error = True
lang_detect = "langdetect"
is_tested = 0.7 # infrequent, but seems stable
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):
target = self.params["lang"]
source = self.source_lang(text)
| > | 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 |
""" Language combos hinge on trained models"""
match = r"^argos | NMT"
requires_key = False
raises_error = True
lang_detect = "langdetect"
is_tested = 0.7 # infrequent, but seems stable
privacy = 1.0 # local setup
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):
target = self.params["lang"]
source = self.source_lang(text)
|
| ︙ | ︙ |