├── .gitignore ├── LICENSE ├── README.md ├── libretranslatepy ├── __init__.py └── api.py └── setup.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 95 | __pypackages__/ 96 | 97 | # Celery stuff 98 | celerybeat-schedule 99 | celerybeat.pid 100 | 101 | # SageMath parsed files 102 | *.sage.py 103 | 104 | # Environments 105 | .env 106 | .venv 107 | env/ 108 | venv/ 109 | ENV/ 110 | env.bak/ 111 | venv.bak/ 112 | 113 | # Spyder project settings 114 | .spyderproject 115 | .spyproject 116 | 117 | # Rope project settings 118 | .ropeproject 119 | 120 | # mkdocs documentation 121 | /site 122 | 123 | # mypy 124 | .mypy_cache/ 125 | .dmypy.json 126 | dmypy.json 127 | 128 | # Pyre type checker 129 | .pyre/ 130 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 Argos Open Tech 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # LibreTranslate-py 2 | 3 | Python bindings to connect to a [LibreTranslate API](https://github.com/LibreTranslate/LibreTranslate) 4 | 5 | https://pypi.org/project/libretranslatepy/ 6 | 7 | ## Install 8 | ``` 9 | pip install libretranslatepy 10 | ``` 11 | 12 | ## Example usage 13 | ```python 14 | from libretranslatepy import LibreTranslateAPI 15 | 16 | lt = LibreTranslateAPI("https://libretranslate.com/") 17 | 18 | print(lt.translate("LibreTranslate is awesome!", "en", "es")) 19 | # LibreTranslate es impresionante! 20 | 21 | print(lt.detect("Hello World")) 22 | # [{"confidence": 0.6, "language": "en"}] 23 | 24 | print(lt.languages()) 25 | # [{"code":"en", "name":"English"}, {"code":"es", "name":"Spanish"}] 26 | ``` 27 | 28 | ## [LibreTranslate Mirrors](https://github.com/LibreTranslate/LibreTranslate#mirrors) 29 | 30 | ## Source 31 | ```python 32 | import json 33 | import sys 34 | from urllib import request, parse 35 | 36 | 37 | class LibreTranslateAPI: 38 | """Connect to the LibreTranslate API""" 39 | 40 | """Example usage: 41 | from libretranslatepy import LibreTranslateAPI 42 | 43 | lt = LibreTranslateAPI("https://translate.terraprint.co/") 44 | 45 | print(lt.translate("LibreTranslate is awesome!", "en", "es")) 46 | # LibreTranslate es impresionante! 47 | 48 | print(lt.detect("Hello World")) 49 | # [{"confidence": 0.6, "language": "en"}] 50 | 51 | print(lt.languages()) 52 | # [{"code":"en", "name":"English"}] 53 | """ 54 | 55 | DEFAULT_URL = "https://translate.terraprint.co/" 56 | 57 | def __init__(self, url=None, api_key=None): 58 | """Create a LibreTranslate API connection. 59 | 60 | Args: 61 | url (str): The url of the LibreTranslate endpoint. 62 | api_key (str): The API key. 63 | """ 64 | self.url = LibreTranslateAPI.DEFAULT_URL if url is None else url 65 | self.api_key = api_key 66 | 67 | # Add trailing slash 68 | assert len(self.url) > 0 69 | if self.url[-1] != "/": 70 | self.url += "/" 71 | 72 | def translate(self, q, source="en", target="es"): 73 | """Translate string 74 | 75 | Args: 76 | q (str): The text to translate 77 | source (str): The source language code (ISO 639) 78 | target (str): The target language code (ISO 639) 79 | 80 | Returns: 81 | str: The translated text 82 | """ 83 | url = self.url + "translate" 84 | params = {"q": q, "source": source, "target": target} 85 | if self.api_key is not None: 86 | params["api_key"] = self.api_key 87 | url_params = parse.urlencode(params) 88 | req = request.Request(url, data=url_params.encode()) 89 | response = request.urlopen(req) 90 | response_str = response.read().decode() 91 | return json.loads(response_str)["translatedText"] 92 | 93 | def detect(self, q): 94 | """Detect the language of a single text. 95 | 96 | Args: 97 | q (str): Text to detect 98 | 99 | Returns: 100 | The detected languages ex: [{"confidence": 0.6, "language": "en"}] 101 | """ 102 | url = self.url + "detect" 103 | params = {"q": q} 104 | if self.api_key is not None: 105 | params["api_key"] = self.api_key 106 | url_params = parse.urlencode(params) 107 | req = request.Request(url, data=url_params.encode()) 108 | response = request.urlopen(req) 109 | response_str = response.read().decode() 110 | return json.loads(response_str) 111 | 112 | def languages(self): 113 | """Retrieve list of supported languages. 114 | 115 | Returns: 116 | A list of available languages ex: [{"code":"en", "name":"English"}] 117 | """ 118 | url = self.url + "languages" 119 | params = dict() 120 | if self.api_key is not None: 121 | params["api_key"] = self.api_key 122 | url_params = parse.urlencode(params) 123 | req = request.Request(url, data=url_params.encode(), method="GET") 124 | response = request.urlopen(req) 125 | response_str = response.read().decode() 126 | return json.loads(response_str) 127 | 128 | ``` 129 | 130 | ## License 131 | Licensed under either the MIT License or Public Domain 132 | 133 | Developed by P.J. Finlay 134 | -------------------------------------------------------------------------------- /libretranslatepy/__init__.py: -------------------------------------------------------------------------------- 1 | from libretranslatepy.api import * 2 | -------------------------------------------------------------------------------- /libretranslatepy/api.py: -------------------------------------------------------------------------------- 1 | import json 2 | import sys 3 | from typing import Any, Dict 4 | from urllib import request, parse 5 | 6 | 7 | class LibreTranslateAPI: 8 | """Connect to the LibreTranslate API""" 9 | 10 | """Example usage: 11 | from libretranslatepy import LibreTranslateAPI 12 | 13 | lt = LibreTranslateAPI("https://translate.terraprint.co/") 14 | 15 | print(lt.translate("LibreTranslate is awesome!", "en", "es")) 16 | # LibreTranslate es impresionante! 17 | 18 | print(lt.detect("Hello World")) 19 | # [{"confidence": 0.6, "language": "en"}] 20 | 21 | print(lt.languages()) 22 | # [{"code":"en", "name":"English"}] 23 | """ 24 | 25 | DEFAULT_URL = "https://translate.terraprint.co/" 26 | 27 | def __init__(self, url: str | None = None, api_key: str | None = None): 28 | """Create a LibreTranslate API connection. 29 | 30 | Args: 31 | url (str): The url of the LibreTranslate endpoint. 32 | api_key (str): The API key. 33 | """ 34 | self.url = LibreTranslateAPI.DEFAULT_URL if url is None else url 35 | self.api_key = api_key 36 | 37 | # Add trailing slash 38 | assert len(self.url) > 0 39 | if self.url[-1] != "/": 40 | self.url += "/" 41 | 42 | def translate(self, q: str, source: str = "en", target: str = "es", timeout: int | None = None) -> Any: 43 | """Translate string 44 | 45 | Args: 46 | q (str): The text to translate 47 | source (str): The source language code (ISO 639) 48 | target (str): The target language code (ISO 639) 49 | timeout (int): Request timeout in seconds 50 | 51 | Returns: 52 | str: The translated text 53 | """ 54 | url = self.url + "translate" 55 | params: Dict[str, str] = {"q": q, "source": source, "target": target} 56 | if self.api_key is not None: 57 | params["api_key"] = self.api_key 58 | url_params = parse.urlencode(params) 59 | req = request.Request(url, data=url_params.encode()) 60 | response = request.urlopen(req, timeout = timeout) 61 | response_str = response.read().decode() 62 | return json.loads(response_str)["translatedText"] 63 | 64 | def detect(self, q: str, timeout: int | None = None) -> Any: 65 | """Detect the language of a single text. 66 | 67 | Args: 68 | q (str): Text to detect 69 | timeout (int): Request timeout in seconds 70 | 71 | Returns: 72 | The detected languages ex: [{"confidence": 0.6, "language": "en"}] 73 | """ 74 | url = self.url + "detect" 75 | params: Dict[str, str] = {"q": q} 76 | if self.api_key is not None: 77 | params["api_key"] = self.api_key 78 | url_params = parse.urlencode(params) 79 | req = request.Request(url, data=url_params.encode()) 80 | response = request.urlopen(req, timeout = timeout) 81 | response_str = response.read().decode() 82 | return json.loads(response_str) 83 | 84 | def languages(self, timeout: int | None = None) -> Any: 85 | """Retrieve list of supported languages. 86 | 87 | Args: 88 | timeout (int): Request timeout in seconds 89 | 90 | Returns: 91 | A list of available languages ex: [{"code":"en", "name":"English"}] 92 | """ 93 | url = self.url + "languages" 94 | params: Dict[str, str] = dict() 95 | if self.api_key is not None: 96 | params["api_key"] = self.api_key 97 | url_params = parse.urlencode(params) 98 | req = request.Request(url, data=url_params.encode(), method="GET") 99 | response = request.urlopen(req, timeout = timeout) 100 | response_str = response.read().decode() 101 | return json.loads(response_str) 102 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import find_packages, setup 2 | 3 | setup(name='libretranslatepy', 4 | version='2.1.4', 5 | description='Python bindings for LibreTranslate API', 6 | keywords="translation libretranslate", 7 | url='https://github.com/argosopentech/LibreTranslate-py', 8 | python_requires=">=2.6", 9 | classifiers=[ 10 | "Development Status :: 5 - Production/Stable", 11 | "Topic :: Scientific/Engineering :: Interface Engine/Protocol Translator", 12 | "Intended Audience :: Developers", 13 | "License :: OSI Approved :: MIT License", 14 | "Programming Language :: Python :: 2", 15 | "Programming Language :: Python :: 3", 16 | ], 17 | project_urls={ 18 | "Bug Reports": "https://github.com/argosopentech/LibreTranslate-py/issues", 19 | "Source": "https://github.com/argosopentech/LibreTranslate-py/", 20 | }, 21 | packages=find_packages() 22 | ) 23 | --------------------------------------------------------------------------------