├── .gitignore
├── LICENSE
├── MANIFEST.in
├── README.md
├── py_trans
├── __init__.py
├── async_translator.py
├── data
│ ├── README.md
│ ├── languages.json
│ └── version.json
├── errors.py
├── extras.py
└── translator.py
├── requirements.txt
└── setup.py
/.gitignore:
--------------------------------------------------------------------------------
1 | tests/
2 | dist/
3 | py_trans.egg-info/
4 | .venv
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Copyright 2023 Itz-fork
2 |
3 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
4 |
5 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
6 |
7 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------------
/MANIFEST.in:
--------------------------------------------------------------------------------
1 | include py_trans/data/*.json
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # py-trans
2 | ```py
3 | from py_trans import PyTranslator
4 |
5 | tr = PyTranslator()
6 | print(tr.google("Hi", "es"))
7 | ```
8 |
9 |
10 | A Fast, hassle-free way to translate text 📖
11 |
12 |
13 |
14 | Features
15 | Install
16 | Usage
17 |
18 |
19 |
20 | ## Features
21 | - Simple and free
22 | - Multiple translators to choose
23 | - Both synchronous & asynchronous versions
24 |
25 |
26 | ## Supported translators
27 | | Engine | Function |
28 | | ------------------------------------------------ | --------------- |
29 | |[Google Translate](https://translate.google.com/) | `google` |
30 | |[translate.com](https://www.translate.com/) | `translate_com` |
31 | |[MyMemory](https://mymemory.translated.net/) | `my_memory` |
32 | |[Translate Dict](https://www.translatedict.com/) | `translate_dict` |
33 |
34 |
35 | ## Installation
36 |
37 | ```sh
38 | pip3 install py-trans
39 | ```
40 |
41 |
42 | Install from source
43 |
44 | ```sh
45 | pip install git+https://github.com/Itz-fork/py-trans.git
46 | ```
47 |
48 |
49 |
50 | ## Usage
51 |
52 | ```py
53 | # Sync version
54 | from py_trans import PyTranslator
55 |
56 | # Async version
57 | from py_trans import Async_PyTranslator
58 | ```
59 |
60 | - Detect language of the provided text
61 | - `detect`
62 | -
63 | ```py
64 | tr.detect("Hello!")
65 | ```
66 | - Translate text using Google translate
67 | - `google`
68 | -
69 | ```py
70 | tr.google("Hello!", "es")
71 | ```
72 | - Translate text using Translate.com
73 | - `translate_com`
74 | -
75 | ```py
76 | tr.translate_com("Hello!", "es")
77 | ```
78 | - Translate text using My Memory
79 | - `my_memory`
80 | -
81 | ```py
82 | tr.my_memory("Hello!", "es")
83 | ```
84 | - Translate text using Translate dict
85 | - `translate_dict`
86 | -
87 | ```py
88 | tr.translate_dict("Hello!", "es")
89 | ```
90 | - Get language code/name
91 | -
92 | ```py
93 | # Sync version
94 | tr.get_lang_code("arabic")
95 | tr.get_lang_name("ar")
96 |
97 | # Async version
98 | tr.get_lang_code_async("arabic")
99 | tr.get_lang_name_async("ar")
100 | ```
101 |
102 | > [!NOTE]
103 | > All the above examples also applies to async version (`Async_PyTranslator`)
104 |
105 |
106 | ## License
107 | - Copyright (C) 2023 [@Itz-fork](https://github.com/Itz-fork)
108 | - Licensed under [MIT](/LICENSE)
109 |
--------------------------------------------------------------------------------
/py_trans/__init__.py:
--------------------------------------------------------------------------------
1 | # Author: https://github.com/Itz-fork
2 | # Project: https://github.com/Itz-fork/py-trans
3 | # License: MIT License
4 |
5 | # Version
6 | import os, json
7 |
8 |
9 | def get_version():
10 | with open(f"{os.path.dirname(__file__)}/data/version.json", "r") as jsn_f:
11 | ver = json.load(jsn_f)
12 | return ver["version"]
13 |
14 |
15 | __version__ = get_version()
16 |
17 |
18 | from .translator import PyTranslator
19 | from .async_translator import Async_PyTranslator
20 | from .extras import get_lang_code, get_lang_name
21 |
--------------------------------------------------------------------------------
/py_trans/async_translator.py:
--------------------------------------------------------------------------------
1 | # Author: https://github.com/Itz-fork
2 | # Project: https://github.com/Itz-fork/py-trans
3 | # License: MIT License
4 |
5 | from requests import exceptions, get
6 | from aiohttp import ClientSession
7 | from .errors import NoInternet, UnableToTranslate, UnknownError
8 |
9 |
10 | class Async_PyTranslator:
11 | """
12 | Aync PyTranslator Class
13 |
14 | Methods:
15 |
16 | detect: Detect language of the provided text
17 | google: Translate text using Google Translate
18 | translate_com: Translate text using Translate.com
19 | my_memory: Translate text using My Memory
20 | translate_dict: Translate text using Translate Dict
21 | """
22 |
23 | def __init__(self, connection_check=True):
24 | # Check internet connection
25 | if connection_check is True:
26 | try:
27 | get("https://www.google.com/")
28 | except (exceptions.ConnectionError, exceptions.Timeout):
29 | raise NoInternet
30 |
31 | async def detect(self, text):
32 | """
33 | Detect language of the provided text
34 |
35 | Arguments:
36 | text: Text that needs to be detected
37 | """
38 | async with ClientSession() as client:
39 | async with client.post(
40 | "https://www.translate.com/translator/ajax_lang_auto_detect",
41 | data={"text_to_translate": str(text)},
42 | ) as fetch:
43 | resp = await fetch.json()
44 | if resp["result"] == "success":
45 | return resp["language"]
46 | else:
47 | raise UnknownError
48 |
49 | async def _fetch(self, url):
50 | async with ClientSession() as client:
51 | async with client.get(url) as ft:
52 | return await ft.json()
53 |
54 | async def google(self, text, dest):
55 | """
56 | Translate text using Google Translate
57 |
58 | Arguments:
59 | text: Text that needs to be translated
60 | dest: The language that the text needs to be translated into
61 | """
62 | try:
63 | async with ClientSession() as client:
64 | async with client.get(
65 | f"https://clients5.google.com/translate_a/t?client=at&sl=auto&tl={dest}&q={text}"
66 | ) as fetch:
67 | resp = (await fetch.json())[0]
68 | out = {
69 | "status": "success",
70 | "engine": "Google Translate",
71 | "translation": resp[0],
72 | "dest": dest,
73 | "orgin": text,
74 | "origin_lang": resp[1],
75 | }
76 | return out
77 | except Exception as e:
78 | raise UnableToTranslate(e)
79 |
80 | async def translate_com(self, text, dest):
81 | """
82 | Translate text using translate.com
83 |
84 | Arguments:
85 | text: Text that needs to be translated
86 | dest: The language that the text needs to be translated into
87 | """
88 | try:
89 | origin_lang = await self.detect(text)
90 | async with ClientSession() as client:
91 | async with client.post(
92 | "https://www.translate.com/translator/ajax_translate",
93 | data={
94 | "text_to_translate": str(text),
95 | "source_lang": origin_lang,
96 | "translated_lang": dest,
97 | "use_cache_only": "false",
98 | },
99 | ) as fetch:
100 | resp = await fetch.json()
101 | out = {
102 | "status": "success",
103 | "engine": "Translate.com",
104 | "translation": resp["translated_text"],
105 | "dest": dest,
106 | "orgin": text,
107 | "origin_lang": origin_lang,
108 | }
109 | return out
110 | except Exception as e:
111 | raise UnableToTranslate(e)
112 |
113 | async def my_memory(self, text, dest):
114 | """
115 | Translate text using My Memory
116 |
117 | Arguments:
118 | text: Text that needs to be translated
119 | dest: The language that the text needs to be translated into
120 | """
121 | try:
122 | origin_lang = self.detect(text)
123 | async with ClientSession() as client:
124 | async with client.get(
125 | "https://api.mymemory.translated.net/get",
126 | params={"q": text, "langpair": f"{origin_lang}|{dest}"},
127 | ) as fetch:
128 | resp = await fetch.json()
129 | out = {
130 | "status": "success",
131 | "engine": "My Memory",
132 | "translation": resp["matches"][0]["translation"],
133 | "dest": dest,
134 | "orgin": text,
135 | "origin_lang": origin_lang,
136 | }
137 | return out
138 | except Exception as e:
139 | raise UnableToTranslate(e)
140 |
141 | async def translate_dict(self, text, dest, detect_origin=False):
142 | """
143 | Translate text using Translate Dict
144 |
145 | Arguments:
146 | text: Text that needs to be translated
147 | dest: The language that the text needs to be translated into
148 | detect_origin: Pass "True" to detect origin language. Defaults to "False"
149 | """
150 | try:
151 | async with ClientSession() as client:
152 | async with client.get(
153 | f"https://t3.translatedict.com/1.php?p1=auto&p2={dest}&p3={text}"
154 | ) as fetch:
155 | resp = await fetch.text()
156 | if detect_origin is True:
157 | origin_lang = self.detect(text)
158 | else:
159 | origin_lang = None
160 | out = {
161 | "status": "success",
162 | "engine": "Translate Dict",
163 | "translation": resp,
164 | "dest": dest,
165 | "orgin": text,
166 | "origin_lang": origin_lang,
167 | }
168 | return out
169 | except Exception as e:
170 | return UnableToTranslate(e)
171 |
--------------------------------------------------------------------------------
/py_trans/data/README.md:
--------------------------------------------------------------------------------
1 | - [version.json](/version.json) - Contains the version of library
2 | - [languages.json](/languages.json) - Contains ISO 639-1 language codes (compiled from wikipedia by @josantonius)
--------------------------------------------------------------------------------
/py_trans/data/languages.json:
--------------------------------------------------------------------------------
1 | {
2 | "aa": "afar",
3 | "ab": "abkhazian",
4 | "af": "afrikaans",
5 | "am": "amharic",
6 | "ar": "arabic",
7 | "ar-ae": "arabic (u.a.e.)",
8 | "ar-bh": "arabic (bahrain)",
9 | "ar-dz": "arabic (algeria)",
10 | "ar-eg": "arabic (egypt)",
11 | "ar-iq": "arabic (iraq)",
12 | "ar-jo": "arabic (jordan)",
13 | "ar-kw": "arabic (kuwait)",
14 | "ar-lb": "arabic (lebanon)",
15 | "ar-ly": "arabic (libya)",
16 | "ar-ma": "arabic (morocco)",
17 | "ar-om": "arabic (oman)",
18 | "ar-qa": "arabic (qatar)",
19 | "ar-sa": "arabic (saudi arabia)",
20 | "ar-sy": "arabic (syria)",
21 | "ar-tn": "arabic (tunisia)",
22 | "ar-ye": "arabic (yemen)",
23 | "as": "assamese",
24 | "ay": "aymara",
25 | "az": "azeri",
26 | "ba": "bashkir",
27 | "be": "belarusian",
28 | "bg": "bulgarian",
29 | "bh": "bihari",
30 | "bi": "bislama",
31 | "bn": "bengali",
32 | "bo": "tibetan",
33 | "br": "breton",
34 | "ca": "catalan",
35 | "co": "corsican",
36 | "cs": "czech",
37 | "cy": "welsh",
38 | "da": "danish",
39 | "de": "german",
40 | "de-at": "german (austria)",
41 | "de-ch": "german (switzerland)",
42 | "de-li": "german (liechtenstein)",
43 | "de-lu": "german (luxembourg)",
44 | "div": "divehi",
45 | "dz": "bhutani",
46 | "el": "greek",
47 | "en": "english",
48 | "en-au": "english (australia)",
49 | "en-bz": "english (belize)",
50 | "en-ca": "english (canada)",
51 | "en-gb": "english (united kingdom)",
52 | "en-ie": "english (ireland)",
53 | "en-jm": "english (jamaica)",
54 | "en-nz": "english (new zealand)",
55 | "en-ph": "english (philippines)",
56 | "en-tt": "english (trinidad)",
57 | "en-us": "english (united states)",
58 | "en-za": "english (south africa)",
59 | "en-zw": "english (zimbabwe)",
60 | "eo": "esperanto",
61 | "es": "spanish",
62 | "es-ar": "spanish (argentina)",
63 | "es-bo": "spanish (bolivia)",
64 | "es-cl": "spanish (chile)",
65 | "es-co": "spanish (colombia)",
66 | "es-cr": "spanish (costa rica)",
67 | "es-do": "spanish (dominican republic)",
68 | "es-ec": "spanish (ecuador)",
69 | "es-es": "spanish (espa\u00f1a)",
70 | "es-gt": "spanish (guatemala)",
71 | "es-hn": "spanish (honduras)",
72 | "es-mx": "spanish (mexico)",
73 | "es-ni": "spanish (nicaragua)",
74 | "es-pa": "spanish (panama)",
75 | "es-pe": "spanish (peru)",
76 | "es-pr": "spanish (puerto rico)",
77 | "es-py": "spanish (paraguay)",
78 | "es-sv": "spanish (el salvador)",
79 | "es-us": "spanish (united states)",
80 | "es-uy": "spanish (uruguay)",
81 | "es-ve": "spanish (venezuela)",
82 | "et": "estonian",
83 | "eu": "basque",
84 | "fa": "farsi",
85 | "fi": "finnish",
86 | "fj": "fiji",
87 | "fo": "faeroese",
88 | "fr": "french",
89 | "fr-be": "french (belgium)",
90 | "fr-ca": "french (canada)",
91 | "fr-ch": "french (switzerland)",
92 | "fr-lu": "french (luxembourg)",
93 | "fr-mc": "french (monaco)",
94 | "fy": "frisian",
95 | "ga": "irish",
96 | "gd": "gaelic",
97 | "gl": "galician",
98 | "gn": "guarani",
99 | "gu": "gujarati",
100 | "ha": "hausa",
101 | "he": "hebrew",
102 | "hi": "hindi",
103 | "hr": "croatian",
104 | "hu": "hungarian",
105 | "hy": "armenian",
106 | "ia": "interlingua",
107 | "id": "indonesian",
108 | "ie": "interlingue",
109 | "ik": "inupiak",
110 | "in": "indonesian",
111 | "is": "icelandic",
112 | "it": "italian",
113 | "it-ch": "italian (switzerland)",
114 | "iw": "hebrew",
115 | "ja": "japanese",
116 | "ji": "yiddish",
117 | "jw": "javanese",
118 | "ka": "georgian",
119 | "kk": "kazakh",
120 | "kl": "greenlandic",
121 | "km": "cambodian",
122 | "kn": "kannada",
123 | "ko": "korean",
124 | "kok": "konkani",
125 | "ks": "kashmiri",
126 | "ku": "kurdish",
127 | "ky": "kirghiz",
128 | "kz": "kyrgyz",
129 | "la": "latin",
130 | "ln": "lingala",
131 | "lo": "laothian",
132 | "ls": "slovenian",
133 | "lt": "lithuanian",
134 | "lv": "latvian",
135 | "mg": "malagasy",
136 | "mi": "maori",
137 | "mk": "fyro macedonian",
138 | "ml": "malayalam",
139 | "mn": "mongolian",
140 | "mo": "moldavian",
141 | "mr": "marathi",
142 | "ms": "malay",
143 | "mt": "maltese",
144 | "my": "burmese",
145 | "na": "nauru",
146 | "nb-no": "norwegian (bokmal)",
147 | "ne": "nepali (india)",
148 | "nl": "dutch",
149 | "nl-be": "dutch (belgium)",
150 | "nn-no": "norwegian",
151 | "no": "norwegian (bokmal)",
152 | "oc": "occitan",
153 | "om": "(afan)/oromoor/oriya",
154 | "or": "oriya",
155 | "pa": "punjabi",
156 | "pl": "polish",
157 | "ps": "pashto/pushto",
158 | "pt": "portuguese",
159 | "pt-br": "portuguese (brazil)",
160 | "qu": "quechua",
161 | "rm": "rhaeto-romanic",
162 | "rn": "kirundi",
163 | "ro": "romanian",
164 | "ro-md": "romanian (moldova)",
165 | "ru": "russian",
166 | "ru-md": "russian (moldova)",
167 | "rw": "kinyarwanda",
168 | "sa": "sanskrit",
169 | "sb": "sorbian",
170 | "sd": "sindhi",
171 | "sg": "sangro",
172 | "sh": "serbo-croatian",
173 | "si": "singhalese",
174 | "sk": "slovak",
175 | "sl": "slovenian",
176 | "sm": "samoan",
177 | "sn": "shona",
178 | "so": "somali",
179 | "sq": "albanian",
180 | "sr": "serbian",
181 | "ss": "siswati",
182 | "st": "sesotho",
183 | "su": "sundanese",
184 | "sv": "swedish",
185 | "sv-fi": "swedish (finland)",
186 | "sw": "swahili",
187 | "sx": "sutu",
188 | "syr": "syriac",
189 | "ta": "tamil",
190 | "te": "telugu",
191 | "tg": "tajik",
192 | "th": "thai",
193 | "ti": "tigrinya",
194 | "tk": "turkmen",
195 | "tl": "tagalog",
196 | "tn": "tswana",
197 | "to": "tonga",
198 | "tr": "turkish",
199 | "ts": "tsonga",
200 | "tt": "tatar",
201 | "tw": "twi",
202 | "uk": "ukrainian",
203 | "ur": "urdu",
204 | "us": "english",
205 | "uz": "uzbek",
206 | "vi": "vietnamese",
207 | "vo": "volapuk",
208 | "wo": "wolof",
209 | "xh": "xhosa",
210 | "yi": "yiddish",
211 | "yo": "yoruba",
212 | "zh": "chinese",
213 | "zh-cn": "chinese (china)",
214 | "zh-hk": "chinese (hong kong sar)",
215 | "zh-mo": "chinese (macau sar)",
216 | "zh-sg": "chinese (singapore)",
217 | "zh-tw": "chinese (taiwan)",
218 | "zu": "zulu"
219 | }
--------------------------------------------------------------------------------
/py_trans/data/version.json:
--------------------------------------------------------------------------------
1 | {
2 | "version": "v0.6.1"
3 | }
--------------------------------------------------------------------------------
/py_trans/errors.py:
--------------------------------------------------------------------------------
1 | # Author: https://github.com/Itz-fork
2 | # Project: https://github.com/Itz-fork/py-trans
3 | # License: MIT License
4 |
5 |
6 | class NoInternet(Exception):
7 | "Please turn on your internet connection!"
8 | pass
9 |
10 | class UnableToTranslate(Exception):
11 | def __init__(self, e):
12 | super().__init__({"status": "failed", "error": e})
13 |
14 | class UnknownError(Exception):
15 | "Unknown error"
16 | pass
--------------------------------------------------------------------------------
/py_trans/extras.py:
--------------------------------------------------------------------------------
1 | # Author: https://github.com/Itz-fork
2 | # Project: https://github.com/Itz-fork/py-trans
3 | # License: MIT License
4 |
5 | import os, json, aiofiles
6 |
7 | async def json_read():
8 | async with aiofiles.open(f"{os.path.dirname(__file__)}/data/languages.json", "r") as jsn_f:
9 | codes = json.load(jsn_f)
10 | return codes
11 |
12 |
13 | # Get language code
14 | def get_lang_code(name):
15 | with open(f"{os.path.dirname(__file__)}/data/languages.json", "r") as jsn_f:
16 | dt = json.load(jsn_f)
17 | return list(dt.keys())[list(dt.values()).index(str(name).lower())]
18 |
19 | async def get_lang_code_async(name):
20 | async with aiofiles.open(f"{os.path.dirname(__file__)}/data/languages.json", "r") as jsn_f:
21 | dt = json.load(jsn_f)
22 | return list(dt.keys())[list(dt.values()).index(str(name).lower())]
23 |
24 | # Get language name
25 | def get_lang_name(code):
26 | with open(f"{os.path.dirname(__file__)}/data/languages.json", "r") as jsn_f:
27 | dt = json.load(jsn_f)
28 | return dt[str(code)]
29 |
30 | async def get_lang_name_async(code):
31 | async with aiofiles.open(f"{os.path.dirname(__file__)}/data/languages.json", "r") as jsn_f:
32 | dt = json.load(jsn_f)
33 | return dt[str(name)]
--------------------------------------------------------------------------------
/py_trans/translator.py:
--------------------------------------------------------------------------------
1 | # Author: https://github.com/Itz-fork
2 | # Project: https://github.com/Itz-fork/py-trans
3 | # License: MIT License
4 |
5 | import requests
6 | from .errors import NoInternet, UnableToTranslate, UnknownError
7 |
8 |
9 | class PyTranslator:
10 | """
11 | PyTranslator Class
12 |
13 | Methods:
14 |
15 | detect: Detect language of the provided text
16 | google: Translate text using Google Translate
17 | translate_com: Translate text using Translate.com
18 | my_memory: Translate text using My Memory
19 | translate_dict: Translate text using Translate Dict
20 | """
21 |
22 | def __init__(self, connection_check=True):
23 | # Check internet connection
24 | if connection_check is True:
25 | try:
26 | requests.get("https://www.google.com/")
27 | except (requests.exceptions.ConnectionError, requests.exceptions.Timeout):
28 | raise NoInternet
29 |
30 | def detect(self, text):
31 | """
32 | Detect language of the provided text
33 |
34 | Arguments:
35 | text: Text that needs to be detected
36 | """
37 | resp = requests.post(
38 | "https://www.translate.com/translator/ajax_lang_auto_detect",
39 | data={"text_to_translate": str(text)},
40 | ).json()
41 | if resp["result"] == "success":
42 | return resp["language"]
43 | else:
44 | raise UnknownError
45 |
46 | def google(self, text, dest):
47 | """
48 | Translate text using Google Translate
49 |
50 | Arguments:
51 | text: Text that needs to be translated
52 | dest: The language that the text needs to be translated into
53 | """
54 | try:
55 | resp = requests.get(
56 | f"https://clients5.google.com/translate_a/t?client=at&sl=auto&tl={dest}&q={text}"
57 | ).json()[0]
58 | out = {
59 | "status": "success",
60 | "engine": "Google Translate",
61 | "translation": resp[0],
62 | "dest": dest,
63 | "orgin": text,
64 | "origin_lang": resp[1],
65 | }
66 | return out
67 | except Exception as e:
68 | raise UnableToTranslate(e)
69 |
70 | def translate_com(self, text, dest):
71 | """
72 | Translate text using translate.com
73 |
74 | Arguments:
75 | text: Text that needs to be translated
76 | dest: The language that the text needs to be translated into
77 | """
78 | try:
79 | origin_lang = self.detect(text)
80 | resp = requests.post(
81 | "https://www.translate.com/translator/ajax_translate",
82 | data={
83 | "text_to_translate": str(text),
84 | "source_lang": origin_lang,
85 | "translated_lang": dest,
86 | "use_cache_only": "false",
87 | },
88 | ).json()
89 | out = {
90 | "status": "success",
91 | "engine": "Translate.com",
92 | "translation": resp["translated_text"],
93 | "dest": dest,
94 | "orgin": text,
95 | "origin_lang": origin_lang,
96 | }
97 | return out
98 | except Exception as e:
99 | raise UnableToTranslate(e)
100 |
101 | def my_memory(self, text, dest):
102 | """
103 | Translate text using My Memory
104 |
105 | Arguments:
106 | text: Text that needs to be translated
107 | dest: The language that the text needs to be translated into
108 | """
109 | try:
110 | origin_lang = self.detect(text)
111 | resp = requests.get(
112 | "https://api.mymemory.translated.net/get",
113 | params={"q": text, "langpair": f"{origin_lang}|{dest}"},
114 | ).json()
115 | out = {
116 | "status": "success",
117 | "engine": "My Memory",
118 | "translation": resp["matches"][0]["translation"],
119 | "dest": dest,
120 | "orgin": text,
121 | "origin_lang": origin_lang,
122 | }
123 | return out
124 | except Exception as e:
125 | raise UnableToTranslate(e)
126 |
127 | def translate_dict(self, text, dest, detect_origin=False):
128 | """
129 | Translate text using Translate Dict
130 |
131 | Arguments:
132 | text: Text that needs to be translated
133 | dest: The language that the text needs to be translated into
134 | detect_origin: Pass "True" to detect origin language. Defaults to "False"
135 | """
136 | try:
137 | resp = requests.get(
138 | f"https://t3.translatedict.com/1.php?p1=auto&p2={dest}&p3={text}"
139 | ).text
140 | if detect_origin is True:
141 | origin_lang = self.detect(text)
142 | else:
143 | origin_lang = None
144 | out = {
145 | "status": "success",
146 | "engine": "Translate Dict",
147 | "translation": resp,
148 | "dest": dest,
149 | "orgin": text,
150 | "origin_lang": origin_lang,
151 | }
152 | return out
153 | except Exception as e:
154 | return UnableToTranslate(e)
155 |
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | requests
2 | aiohttp
3 | aiofiles
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 | # Author: https://github.com/Itz-fork
2 | # Project: https://github.com/Itz-fork/py-trans
3 | # License: MIT License
4 |
5 | import os, json
6 | from setuptools import setup, find_packages
7 |
8 |
9 | os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
10 |
11 | # Readme & Reqs
12 | if os.path.isfile("requirements.txt"):
13 | reques = [r.strip() for r in open("requirements.txt").readlines()]
14 | else:
15 | reques = ["requests", "aiohttp"]
16 |
17 | if os.path.isfile("README.md"):
18 | with open(("README.md"), encoding="utf-8") as readmeh:
19 | lg_desc = readmeh.read()
20 | else:
21 | lg_desc = "py-trans is a free python library to translate text into different languages."
22 |
23 |
24 | # py-trans version
25 | def get_pytrans_version():
26 | with open("py_trans/data/version.json", "r") as jsn_f:
27 | ver = json.load(jsn_f)
28 | return ver["version"]
29 |
30 | pyt_version = get_pytrans_version()
31 |
32 |
33 | setup(name="py-trans",
34 | version=pyt_version,
35 | description="Free python library to translate text to different languages.",
36 | url="https://github.com/Itz-fork/py-trans",
37 | author="Itz-fork",
38 | author_email="git.itzfork@gmail.com",
39 | license="MIT",
40 | packages=find_packages(),
41 | include_package_data=True,
42 | download_url=f"https://github.com/Itz-fork/py-trans/releases/tag/py-trans-pypi-{pyt_version}",
43 | keywords=["google translate", "text translator", "translator", "py-trans"],
44 | long_description=lg_desc,
45 | long_description_content_type="text/markdown",
46 | install_requires=reques,
47 | classifiers=[
48 | "Development Status :: 5 - Production/Stable",
49 | "Intended Audience :: Developers",
50 | "Topic :: Education",
51 | "License :: OSI Approved :: MIT License",
52 | "Programming Language :: Python :: 3",
53 | "Programming Language :: Python :: 3.4",
54 | "Programming Language :: Python :: 3.5",
55 | "Programming Language :: Python :: 3.6",
56 | "Programming Language :: Python :: 3.9",
57 | "Programming Language :: Python :: 3.10",
58 | "Programming Language :: Python :: 3.11",
59 | ],
60 | )
--------------------------------------------------------------------------------