Skip to content

Instantly share code, notes, and snippets.

@juancarlospaco
Last active April 6, 2018 19:32
Show Gist options
  • Save juancarlospaco/abef209ae8028087dce3 to your computer and use it in GitHub Desktop.
Save juancarlospaco/abef209ae8028087dce3 to your computer and use it in GitHub Desktop.
Translate from internet via API from mymemory.translated.net, with Fall-back, DoNotTrack HTTPS, Time-Out and Legally.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Tinyslations, smallest possible Translations from Internet with fallback."""
from urllib import parse, request
from locale import getdefaultlocale
from json import loads
def tinyslation(s: str, to: str=getdefaultlocale()[0][:2], fm="en") -> str:
"""Translate from internet via API from mymemory.translated.net,legally."""
api = "https://mymemory.translated.net/api/get?q={st}&langpair={fm}|{to}"
req = request.Request(url=api.format(st=parse.quote(s), fm=fm, to=to),
headers={'User-Agent': '', 'DNT': 1}) # DoNotTrack
try:
responze = request.urlopen(req, timeout=3).read().decode("utf-8")
return loads(responze)['responseData']['translatedText']
except:
return str(s).strip()
@juancarlospaco
Copy link
Author

>>> tinyslation("cute cat", "es")
'lindo gato'
>>> tinyslation("lindo gato", "en", "es")
'cute cat'
>>> tinyslation("cute cat", "it")
'gatto carino'
>>> tinyslation("cat beer wine eye hair skin computer", "es")
'gato cervezas vino ojo pelo piel ordenador'

Alias

  • Set a Fixed "To" Language, and use it like Gettext _( ) using a simple Variable to alias tinyslation( ).
_ = lambda s:  tinyslation(s, "es") 
>>> _("cute cat")
'lindo gato'

NOTE:

  • Please if you need exact translations use gettext with manual translation and professional translators.
  • If not feel free to thinker with this, but always make the user know its Experimental, make it optional.
  • API has a Limit of 1.000 Words / Day, but its Legal to use.

🌏 🌍 🌎

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment