Coder Social home page Coder Social logo

uliontse / translators Goto Github PK

View Code? Open in Web Editor NEW
1.5K 22.0 189.0 655 KB

🌏🌍🌎Translators🌎🌍🌏 is a library that aims to bring free, multiple, enjoyable translations to individuals and students in Python. Translators是一个旨在用Python为个人和学生带来免费、多样、愉快翻译的库。

Home Page: https://pypi.org/project/translators/

License: GNU General Public License v3.0

Python 100.00%
youdao alibaba sogou deepl bing tencent baidu google yandex caiyun

translators's Introduction

PyPI - Version Conda - Version PyPI - License PyPI - Python PyPI - Status PyPI - Wheel PyPI - Downloads


Translators is a library that aims to bring free, multiple, enjoyable translations to individuals and students in Python.

Supported Translation Services

ID Translator Number of Supported Languages Advantage Service Status
1 Niutrans 452 support the most languages in the world Northeastern University / Niutrans, China /
2 MyMemory 330 support the most languages in the world Translated, Italy stable
3 Alibaba 221 support most languages, support professional field Alibaba, China stable
4 Baidu 201 support most languages, support professional field, support classical Chinese Baidu, China stable
5 ModernMt 200 open-source, support more languages in the world Modernmt / Translated, Italy stable
6 VolcEngine 189 support more languages in the world, support professional field ByteDance, China /
7 Iciba 187 support the most languages in the world Kingsoft / Xiaomi, China stable
8 Iflytek 137 support the most languages in the world Iflytek, China /
9 Google 134 support more languages in the world Google, America stable(offline in China inland)
10 Bing 128 support more languages in the world Microsoft, America stable
11 Lingvanex 112 support translation of different regions but the same language Lingvanex, Cyprus stable
12 Yandex 102 support more languages in the world, support word to emoji Yandex, Russia /
13 Itranslate 101 support translation of different regions but the same language, such as en-US, en-UK, en-AU Itranslate, Austria stable
14 SysTran 52 support more languages in the world SysTran, France stable
15 Argos 46 open-source Argos / Libre, America stable
16 Apertium 45 open-source Apertium, Spain stable
17 Reverso 42 popular on Mac and Iphone Reverso, France stable
18 Deepl 30 high quality to translate but response slowly Deepl, Germany stable
19 CloudTranslation 28 support main languages Xiamen University / CloudTranslation, China stable
20 QQTranSmart 22 support main languages Tencent, China stable
21 TranslateCom 21 good at English translation TranslateCom, America stable
22 Sogou 20 support more languages in the world Tencent, China stable
23 Tilde 20 good at lv, de, fr translation Tilde, Latvia /
24 QQFanyi 17 support main languages Tencent, China stable
25 TranslateMe 16 good at English translation TranslateMe / Neosus, Lithuania /
26 Papago 15 good at Korean translation Naver, South Korea stable
27 Mirai 15 good at Japanese translation MiraiTranslate, Japan /
28 Youdao 12 support main languages, high quality Netease, China stable
29 Iflyrec 12 good at Chinese translation Iflytek, China stable
30 Hujiang 12 supported by baidu Hujiang, China stable
31 Yeekit 10 support main languages CTC, China /
32 LanguageWire 8 good at English translation LanguageWire, Denmark stable
33 Caiyun 7 high quality to translate but response slowly, support professional field ColorfulClouds, China stable
34 Elia 6 good at Basque translation Elhuyar, Spain stable
35 Judic 4 good at European translation CrossLang, Belgium /
36 Mglip 3 good at Mongolia translation Inner Mongolia University, China stable
37 Utibet 2 good at Tibet translation Tibet University, China stable

Installation

# PYPI
pip install --upgrade translators

# Conda
conda install conda-forge::translators

# Source
git clone https://github.com/UlionTse/translators.git
cd translators
python setup.py install

Getting Started

import translators as ts

q_text = '季姬寂,集鸡,鸡即棘鸡。棘鸡饥叽,季姬及箕稷济鸡。'
q_html = '''<!DOCTYPE html><html><head><title>《季姬击鸡记》</title></head><body><p>还有另一篇文章《施氏食狮史》。</p></body></html>'''

### usage
_ = ts.preaccelerate_and_speedtest()  # Optional. Caching sessions in advance, which can help improve access speed.

print(ts.translators_pool)
print(ts.translate_text(q_text))
print(ts.translate_html(q_html, translator='alibaba'))

### parameters
help(ts.translate_text)

"""
translate_text(query_text: str, translator: str = 'bing', from_language: str = 'auto', to_language: str = 'en', **kwargs) -> Union[str, dict]
    :param query_text: str, must.
    :param translator: str, default 'bing'.
    :param from_language: str, default 'auto'.
    :param to_language: str, default 'en'.
    :param if_use_preacceleration: bool, default False.
    :param **kwargs:
            :param is_detail_result: bool, default False.
            :param professional_field: str, default None. Support alibaba(), baidu(), caiyun(), cloudTranslation(), elia(), sysTran(), youdao(), volcEngine() only.
            :param timeout: float, default None.
            :param proxies: dict, default None.
            :param sleep_seconds: float, default 0.
            :param update_session_after_freq: int, default 1000.
            :param update_session_after_seconds: float, default 1500.
            :param if_use_cn_host: bool, default False. Support google(), bing() only.                
            :param reset_host_url: str, default None. Support google(), yandex() only.
            :param if_check_reset_host_url: bool, default True. Support google(), yandex() only.
            :param if_ignore_empty_query: bool, default False.
            :param limit_of_length: int, default 20000.
            :param if_ignore_limit_of_length: bool, default False.
            :param if_show_time_stat: bool, default False.
            :param show_time_stat_precision: int, default 2.
            :param if_print_warning: bool, default True.
            :param lingvanex_mode: str, default 'B2C', choose from ("B2C", "B2B").
            :param myMemory_mode: str, default "web", choose from ("web", "api").
    :return: str or dict
"""

Supported Languages

Language Language of Translator Google Yandex Bing Baidu Alibaba Tencent Youdao Sogou Deepl Caiyun Argos others...
english en Y Y Y Y Y Y Y Y Y Y Y ...
chinese zh Y Y Y Y Y Y Y Y Y Y Y
arabic ar Y Y Y Y(ara) Y Y Y Y Y
russian ru Y Y Y Y Y Y Y Y Y Y Y
french fr Y Y Y Y(fra) Y Y Y Y Y Y Y
german de Y Y Y Y Y Y Y Y Y
spanish es Y Y Y Y(spa) Y Y Y Y Y Y Y
portuguese pt Y Y Y(pt/pt-pt) Y Y Y Y Y Y Y
italian it Y Y Y Y Y Y Y Y Y Y
japanese ja Y Y Y Y(jp) Y Y Y Y Y Y
korean ko Y Y Y Y(kor) Y Y Y Y
greek el Y Y Y Y Y Y
dutch nl Y Y Y Y Y Y Y
hindi hi Y Y Y Y Y Y
turkish tr Y Y Y Y Y Y Y
malay ms Y Y Y Y Y
thai th Y Y Y Y Y Y Y
vietnamese vi Y Y Y Y(vie) Y Y Y Y Y
indonesian id Y Y Y Y Y Y Y Y
hebrew he Y(iw) Y Y Y
polish pl Y Y Y Y Y Y Y
mongolian mn Y Y
czech cs Y Y Y Y Y Y
hungarian hu Y Y Y Y Y Y
estonian et Y Y Y Y(est) Y Y
bulgarian bg Y Y Y Y(bul) Y Y
danish da Y Y Y Y(dan) Y Y
finnish fi Y Y Y Y(fin) Y Y
romanian ro Y Y Y Y(rom) Y Y
swedish sv Y Y Y Y(swe) Y Y
slovenian sl Y Y Y Y(slo) Y Y
persian/farsi fa Y Y Y Y
bosnian bs Y Y Y(bs-Latn) Y(bs-Latn)
serbian sr Y Y Y(sr-Latn/sr-Cyrl) Y(sr-Latn/sr-Cyrl)
fijian fj Y Y
filipino tl Y Y Y(fil) Y(fil)
haitiancreole ht Y Y Y Y
catalan ca Y Y Y Y
croatian hr Y Y Y Y
latvian lv Y Y Y Y Y
lithuanian lt Y Y Y Y Y
urdu ur Y Y Y Y
ukrainian uk Y Y Y Y
welsh cy Y Y Y Y
tahiti ty Y Y
tongan to Y Y
swahili sw Y Y Y Y
samoan sm Y Y Y
slovak sk Y Y Y Y Y
afrikaans af Y Y Y Y
norwegian no Y Y Y Y
bengali bn Y Y Y(bn-BD) Y
malagasy mg Y Y Y Y
maltese mt Y Y Y Y
queretaro otomi otq Y Y
klingon/tlhingan hol tlh Y Y
gujarati gu Y Y Y
tamil ta Y Y Y
telugu te Y Y Y
punjabi pa Y Y Y
amharic am Y Y
azerbaijani az Y Y
bashkir ba Y
belarusian be Y Y
cebuano ceb Y Y
chuvash cv Y
esperanto eo Y Y
basque eu Y Y
irish ga Y Y Y
emoji emj Y
... ...

About Chinese Language

Language Language of Translator Google Yandex Bing Baidu Alibaba Tencent Youdao Sogou Iciba Iflytek Caiyun Deepl Argos Itranslate Reverso TranslateCom Papago Utibet
Chinese(简体) zh-CHS Y(zh-CN) Y(zh) Y(zh-Hans) Y(zh) Y(zh) Y(zh) Y Y Y(zh) Y(zh) Y(zh) Y(zh) Y(zh) Y(zh-CN) Y(zh/chi) ... Y(zh-CN) Y(zh)
Chinese(繁体) zh-CHT Y(zh-TW) Y(zh-Hant) Y(cht) Y(zh-TW) Y Y(cnt) Y(zh-TW) Y(zh-TW)
Chinese(文言文) wyw Y
Chinese(粤语) yue Y Y Y Y Y Y(zh-HK)
Chinese(内蒙语) mn N[外蒙] N[外蒙] Y[内蒙] N[外蒙]
Chinese(维吾尔语) uy Y
Chinese(藏语) ti Y Y
Chinese(白苗文) mww Y Y Y
Chinese(彝语) ii Y
Chinese(苗语) hmn Y
Chinese(壮语) zyb

Debug Tips

Linux Runtime Environment

  1. To support javascript runtime environment, you should download and install Node.js.
  2. Function baidu() doesn't work on Linux without desktop.

HttpError 4xx

  1. Check whether you made high frequency requests, especially httperror 429.
  2. Check whether this service is provided in your region.
  3. Detail to solve HttpError itself.
  4. Issue me, thanks.

NetworkError or ProxyError

  1. Check whether the network is connected correctly.
  2. Check the proxy are enabled on your computer. If it is enabled, try turning it off or otherwise.

Star History

Star History Chart

translators's People

Contributors

abbasudo avatar binglinggroup avatar dadas190 avatar ghtyrant avatar kevindragon avatar mercuree avatar nullmember avatar uliontse avatar wkcn avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

translators's Issues

Need help please !

Hello!
Im creating a personal script used to give me all traduction of all possibility of a word.
So eat : eat eta aet ate tea tae
At first i would know how to put in a variable the language from where the traduction come, cant find how to do write even with help setting (i put code on end)
Iam gonna try edit this script but need study before ,i dont code since many years , i got help to do that. Will edit to put a loop in the last print fonction which must say me all the possible traduction of each word variant ,but only if the result changed.
You know,what im doing now is very slow and check all language for each word assembly should take an hour really lol.
Do you have an advice to make it faster ? For example a loop in the loop or something like that.Im not really finding idea yet now which can make faster . I can remember one other things when i followed the the lesson ,years ago,its made to execute many things at same for if its to slow. Unfortunately i cant find this again, im not sure it was for python i learned many language but i hope so,if i am right and you have this in your memory ill take it ! Id really need a fast logiciel to dont waste time and study more&better.
If you no have time to share me a good helper idea 💡 there is no problem im can ask away i know its not rlly the spot for ahah but im trying by the way .just need the lang information !
Here the actually code :)

import translators as ts
from translators import apis
def permut(mot):
if not mot:
yield ""
return
# if

for i in range(len(mot)):
	for x in permut(mot[:i] + mot[i+1:]):
		yield mot[i] + x
# for

permut()

for x in permut("abced"):
print(x+" : "+ts.google(x)+" ("+NEED CODE HERE+")")

okok see u soon

应该增加一下调用频率相关的说明

这个包挺好用的,
一个小小的建议:应该增加一下调用频率相关的说明,比如间隔多长时间调用一次不会被block, 每天调用上限是多少?类似这方面的信息挺重要的。

多个接口失效

有道只翻译前50个字符,腾讯,DeepL接口报错,麻烦作者修改:)

youdao api text truncate problem

text = "PC Players: The recent lobby connectivity issues have now been resolved. https://twitter.com/PUBG_Support/status/1106138075493744642 …"

form
{'i': 'PC Players: The recent lobby connectivity issues have now been resolved. https://twitter.com/PUBG_Support/status/1106138075493744642\xa0…', 'from': 'AUTO', 'to': 'AUTO', 'smartresult': 'dict', 'client': 'fanyideskweb', 'ts': '1553074717864', 'salt': '15530747178642', 'sign': '6670e79e923ee7c2d1e1f81a09fe76b0', 'bv': '43e486d853ef63af6932375b449635ab', 'doctype': 'json', 'version': '2.1', 'keyfrom': 'fanyi.web', 'action': 'FY_BY_REALTIME', 'typoResult': 'false'}

result
{'translateResult': [[{'tgt': 'PC玩家:最近大厅连接问题', 'src': 'PC Players: The recent lobby connectivity issues h'}]], 'errorCode': 0, 'type': 'en2zh-CHS'}

TypeError: the JSON object must be str, bytes or bytearray, not 'NoneType'

Hi, I am still doing batch french to english translation with google. I have come across a string which is detected as French and I read it and it is French, however, I get the above error for this particular bit of text.

The input I am giving is of class 'str' and is of length 5086 (that is the content variable). Is there a max length limit or is that fine? Anyway for this particular str and none others I have faced, I get the error. Let me give you the full stack trace.

Traceback (most recent call last):
File "/home/brick/eclipse-workspace/ARIACrawling/ProcessLinks.py", line 132, in
main()
File "/home/brick/eclipse-workspace/ARIACrawling/ProcessLinks.py", line 129, in main
process_links(links_file, basedata_dir)
File "/home/brick/eclipse-workspace/ARIACrawling/ProcessLinks.py", line 109, in process_links
result = process_link(line)
File "/home/brick/eclipse-workspace/ARIACrawling/ProcessLinks.py", line 58, in process_link
description_text = translate_french_to_english(content.getText())
File "/home/brick/eclipse-workspace/ARIACrawling/ProcessLinks.py", line 18, in translate_french_to_english
returnable = ts.translate_html(content, translator=ts.google, to_language='en', translator_params={})
File "/home/brick/.local/lib/python3.6/site-packages/translators/apis.py", line 67, in wrapper
r = func(*args, **kwargs)
File "/home/brick/.local/lib/python3.6/site-packages/translators/apis.py", line 1050, in translate_html
return re.sub(pattern=pattern, repl=repl, string=html_text)
File "/usr/lib64/python3.6/re.py", line 191, in sub
return _compile(pattern, flags).sub(repl, string, count)
File "/home/brick/.local/lib/python3.6/site-packages/translators/apis.py", line 1049, in
repl = lambda x: translator(query_text=x.group(1).strip(), to_language=to_language,**translator_params) if x.group(1).strip() else ''
File "/home/brick/.local/lib/python3.6/site-packages/translators/apis.py", line 336, in google_api
data = json.loads(json_data[0][2])
File "/usr/lib64/python3.6/json/init.py", line 348, in loads
'not {!r}'.format(s.class.name))
TypeError: the JSON object must be str, bytes or bytearray, not 'NoneType'

google挂逼了

I love you
{'en': ['en', 'auto'], 'auto': ['en', 'auto']}
Traceback (most recent call last):
File "translation.py", line 96, in
parse()
File "translation.py", line 64, in parse
print(ts.google('我爱你', from_language=from_language, to_language="en"))
File "/usr/local/lib/python3.8/dist-packages/translators/apis.py", line 367, in google_api
from_language, to_language = self.check_language(from_language, to_language, self.language_map, output_zh=self.output_zh)
File "/usr/local/lib/python3.8/dist-packages/translators/apis.py", line 106, in check_language
raise TranslatorError('Unsupported from_language[{}] in {}.'.format(from_language,sorted(language_map.keys())))
translators.apis.TranslatorError: Unsupported from_language[zh-CN] in ['auto', 'en'].

TranslatorError: query_text is not string

Ahoy=)
Im getting this error since a while, its asking me what server i am using (i type France), but then i cant run anything. Here the is the code error, i am on the last version. Iwill try an other server next time its asking me to type mine. Good luck with it !)

TranslatorError Traceback (most recent call last)
in
172 list2.append(1)
173 list3.append(1)
--> 174 list3[P]=trad(list1[P])
175 #to translate each by each permut of word
176

in trad(t)
154 #this function translate the list element given
155 def trad(t):
--> 156 u=ts.google(t,to_language="fr",is_detail_result=True)
157 return u
158

/var/mobile/Containers/Data/Application/891949C4-9BE2-44EF-82B1-76377D19A064/Library/lib/python3.9/site-packages/translators/apis.py in google_api(self, query_text, from_language, to_language, **kwargs)
359 sleep_seconds = kwargs.get('sleep_seconds', random.random())
360 if_ignore_limit_of_length = kwargs.get('if_ignore_limit_of_length', False)
--> 361 query_text = self.check_query_text(query_text, if_ignore_limit_of_length)
362 delete_temp_language_map_label = 0
363 if not query_text:

/var/mobile/Containers/Data/Application/891949C4-9BE2-44EF-82B1-76377D19A064/Library/lib/python3.9/site-packages/translators/apis.py in check_query_text(query_text, if_ignore_limit_of_length)
115 def check_query_text(query_text, if_ignore_limit_of_length=False):
116 if not isinstance(query_text, str):
--> 117 raise TranslatorError('query_text is not string.')
118 query_text = query_text.strip()
119 if not query_text:

TranslatorError: query_text is not string.

TranslateError ; cant find language destination bug on google trad

Hello :) im just getting an error on every of my script with this package used; my box just died one week ago and got repair today. I tried 2 different to_language value and getting this error :

Using France server backend.
type word here :Nath
there is as much possibility: 24

TranslatorError Traceback (most recent call last)
in
28 list2.append(1)
29 list3.append(1)
---> 30 list3[P]=trad(str(list1[P]))
31
32 vo=str(list3[P]).lower()

in trad(t)
7
8 def trad(t):
----> 9 u=ts.google(t,to_language='fr',is_detail_result=False)
10 return u
11

/var/mobile/Containers/Data/Application/DE79D566-42C7-4545-B9DE-422DDE1F789C/Library/lib/python3.9/site-packages/translators/apis.py in google_api(self, query_text, from_language, to_language, **kwargs)
328 if not self.language_map:
329 self.language_map = self.get_language_map(host_html)
--> 330 from_language, to_language = self.check_language(from_language, to_language, self.language_map, output_zh=self.output_zh)
331
332 rpc_data = self.get_rpc(query_text, from_language, to_language)

/var/mobile/Containers/Data/Application/DE79D566-42C7-4545-B9DE-422DDE1F789C/Library/lib/python3.9/site-packages/translators/apis.py in check_language(from_language, to_language, language_map, output_zh, output_auto)
101 raise TranslatorError('Unsupported from_language[{}] in {}.'.format(from_language,sorted(language_map.keys())))
102 elif to_language not in language_map:
--> 103 raise TranslatorError('Unsupported to_language[{}] in {}.'.format(to_language,sorted(language_map.keys())))
104 elif from_language != output_auto and to_language not in language_map[from_language]:
105 logger.exception('language_map:', language_map)

TranslatorError: Unsupported to_language[fr] in [].

Thanks mate

Problem with google translation.

When google translation includes emoji (for example, 😃), translation fails with a 403 error.

requests.exceptions.HTTPError: 403 Client Error: Forbidden for url: https://translate.google.com/translate_a/single?client=webapp&sl=en&tl=ko&hl=zh-CN&dt=at&dt=bd&dt=ex&dt=ld&dt=md&dt=qca&dt=rw&dt=rm&dt=ss&dt=t&ie=UTF-8&oe=UTF-8&source=bh&ssel=0&tsel=0&kc=1&tk=141357.300780&q=hi~%20%F0%9F%98%83

Using Google translator, OverflowError: int too large to convert to float

When translating a random sentence from french to english using google, I get this rather unexpected error. It does not appear to have anything to do with the input phrase which is being entered.

I am guessing this would be self.query_count getting too large? Perhaps a value of 1024 would do it? Sleep seconds should be related to self.query_count in another way?

By the way, the sentence is: "Un incendie se déclare dans le séchoir à bois d’une menuiserie."

Traceback (most recent call last):
File "/home/brick/eclipse-workspace/ARIACrawling/ProcessLinks.py", line 77, in
main()
File "/home/brick/eclipse-workspace/ARIACrawling/ProcessLinks.py", line 74, in main
process_links(links_file, basedata_dir)
File "/home/brick/eclipse-workspace/ARIACrawling/ProcessLinks.py", line 54, in process_links
result = process_link(line)
File "/home/brick/eclipse-workspace/ARIACrawling/ProcessLinks.py", line 46, in process_link
description_text = translate_french_to_english(content.getText())
File "/home/brick/eclipse-workspace/ARIACrawling/ProcessLinks.py", line 16, in translate_french_to_english
return ts.translate_html(content, translator=ts.google, to_language='en', translator_params={})
File "/home/brick/.local/lib/python3.6/site-packages/translators/apis.py", line 67, in wrapper
r = func(*args, **kwargs)
File "/home/brick/.local/lib/python3.6/site-packages/translators/apis.py", line 1050, in translate_html
return re.sub(pattern=pattern, repl=repl, string=html_text)
File "/usr/lib64/python3.6/re.py", line 191, in sub
return _compile(pattern, flags).sub(repl, string, count)
File "/home/brick/.local/lib/python3.6/site-packages/translators/apis.py", line 1049, in
repl = lambda x: translator(query_text=x.group(1).strip(), to_language=to_language,**translator_params) if x.group(1).strip() else ''
File "/home/brick/.local/lib/python3.6/site-packages/translators/apis.py", line 324, in google_api
sleep_seconds = kwargs.get('sleep_seconds', 0.05 + random.random() / 2 + 1e-100 * 2 ** self.query_count)
OverflowError: int too large to convert to float

Problem with youdao translation

codes:

import translators as ts

to_trans = 'Time series is a series of observations listed in the order of time.The data points in a time series are usually recorded at constant successive time intervals.'
result = ts.youdao(to_trans, 'en', 'zh')
print(result)

results:

时间序列是一系列的观测中列出

Function youdao can only translate the first few words,can you solve it? thx.

failed to eatablish a connection

ConnectionError: HTTPConnectionPool(host='fanyi.youdao.com', port=80): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x0000014A781D8D88>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed'))

Problem with yandex translation.

I get a JSONDecodeError error when trying to translate yandex.

>>> print(ts.yandex('hello', 'en', 'zh'))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.6/dist-packages/translators/apis.py", line 921, in yandex_api
    data = r.json()
  File "/usr/local/lib/python3.6/dist-packages/requests/models.py", line 898, in json
    return complexjson.loads(self.text, **kwargs)
  File "/usr/lib/python3.6/json/__init__.py", line 354, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python3.6/json/decoder.py", line 339, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib/python3.6/json/decoder.py", line 357, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

Also, in case of language detection, I get a 403 error.

>>> print(ts.yandex('hello'))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.6/dist-packages/translators/apis.py", line 910, in yandex_api
    from_language = self.detect_language(ss, query_text, self.sid, proxies) if from_language=='auto' else from_language
  File "/usr/local/lib/python3.6/dist-packages/translators/apis.py", line 879, in detect_language
    r.raise_for_status()
  File "/usr/local/lib/python3.6/dist-packages/requests/models.py", line 941, in raise_for_status
    raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 403 Client Error: Forbidden for url: https://translate.yandex.net/api/v1/tr.json/detect?sid=....&srv=tr-text&text=hello&hint=zh%2Cen&options=1

DeepL API不工作

pypi安装的4.7.9版本
deepl报错,请求返回400,查了一下请求
在PostMan里发送:
{ "jsonrpc": "2.0", "method": "LMT_handle_jobs", "params": { "jobs": [ { "kind": "default", "raw_en_sentence": "MIT License", "raw_en_context_before": [], "raw_en_context_after": [], "preferred_num_beams": 4 } ], "lang": { "user_preferred_langs": [ "JA", "ZH", "EN" ], "source_lang_computed": "EN", "target_lang": "ZH" }, "priority": 1, "commonJobParams": {}, "timestamp": 1606466429798 }, "id": 65830012 }
是可以工作的
但在split_sentences()中请求时返回:
{ "jsonrpc": "2.0", "error": { "code": 1042911, "message": "Too many requests." } }

tencent不能用啦

Traceback (most recent call last):
File "D:/python/trans/UlionTse_translators.py", line 15, in
print(ts.tencent(x))
File "D:\windows\soft\anaconda3\lib\site-packages\translators\apis.py", line 65, in wrapper
r = func(args, **kwargs)
File "D:\windows\soft\anaconda3\lib\site-packages\translators\apis.py", line 493, in tencent_api
qtv = re.findall('var qtv = "(.
?)"', host_html)[0]
IndexError: list index out of range

inconsistent results

I think I understand the intent of the project, so I ran the following code to do a simple English => Portuguese translation for each service using the following code:

# encoding: utf-8

import sys
import translators as ts


en_text = 'this is a test'

try:
	print('google:', ts.google(en_text, from_language='en', to_language='pt'))
except:
	print('google:', sys.exc_info()[0])
try:
	print('yandex:', ts.yandex(en_text, from_language='en', to_language='pt'))
except:
	print('yandex:', sys.exc_info()[0])
try:
	print('bing:', ts.bing(en_text, from_language='en', to_language='pt'))
except:
	print('bing:', sys.exc_info()[0])
try:
	print('sogou:', ts.sogou(en_text, from_language='en', to_language='pt'))
except:
	print('sogou:', sys.exc_info()[0])
try:
	print('baidu:', ts.baidu(en_text, from_language='en', to_language='pt'))
except:
	print('baidu:', sys.exc_info()[0])
try:
	print('tencent:', ts.tencent(en_text, from_language='en', to_language='pt'))
except:
	print('tencent:', sys.exc_info()[0])
try:
	print('youdao:', ts.youdao(en_text, from_language='en', to_language='pt'))
except:
	print('youdao:', sys.exc_info()[0])
try:
	print('alibaba:', ts.alibaba(en_text, from_language='en', to_language='pt'))
except:
	print('alibaba:', sys.exc_info()[0])
try:
	print('deeple:', ts.deepl(en_text, from_language='en', to_language='pt'))
except:
	print('deeple:', sys.exc_info()[0])

The results usually came out as:
Using United States server backend.
google: isto é um teste
yandex: <class 'translators.apis.TranslatorError'>
bing: Isso é um teste
sogou: Isso é um teste
baidu: <class 'execjs._exceptions.ProgramError'>
tencent: Istoéumteste.
[02:38:12] language_map:
NoneType: None
youdao: <class 'translators.apis.TranslatorError'>
alibaba: Este é um teste
deeple: este é um teste

It would appear that yandex, baidu and youdao are broken. They all consistently gave the errors shown though the calls are identical, unless of course I'm doing something wrong. Also, it's the youdao call that is responsible for the language_map piece (I commented out all of the other calls and ran it again to make sure).

It's not showing up now, but the alibaba one was complaining about "too many requests" the first few times I ran the code. I had only made a few calls at that point. Are you aggregating the calls?

Last odd bit is that tencent appears to be stripping out the spaces.

Before I wrapped the calls in try/except blocks, I was getting some longer error readouts that seemed to indicate that you're using the requests package under the hood somewhere? Does that mean that requests style proxy parameters could be used?

‘NoneType’ object is not iterable

I have this error in some case,
For example if i give one letter,all the letter will work normally , its will gimme translate but if i give the "a" letter i got the following error.
Or someword give me the same error during the search generally during the translate of 100/200th word sometime less sometime more .

type word here :A
there is as much possibility: 1

TypeError Traceback (most recent call last)
in
28 list2.append(1)
29 list3.append(1)
---> 30 list3[P]=trad(str(list1[P]))
31
32 vo=(list3[P]).lower()

in trad(t)
7
8 def trad(t):
----> 9 u=ts.google(t,to_language='fr')
10 return u
11

/var/mobile/Containers/Data/Application/DE79D566-42C7-4545-B9DE-422DDE1F789C/Library/lib/python3.9/site-packages/translators/apis.py in google_api(self, query_text, from_language, to_language, **kwargs)
338 time.sleep(sleep_seconds)
339 self.query_count += 1
--> 340 return data if is_detail_result else ''.join([x[0] for x in data[1][0][0][5]])
341
342

TypeError: 'NoneType' object is not iterable

UserWarning info?

Hey

When i run something i got notified by this

Using France server backend.
/var/mobile/Containers/Data/Application/891949C4-9BE2-44EF-82B1-76377D19A064/Library/lib/python3.9/site-packages/translators/apis.py:117: UserWarning: Did not get a complete language map. And do not use from_language="auto".
warnings.warn('Did not get a complete language map. And do not use from_language="auto".')

I am wondering if you are working to get this to work same way as before if you get me ?
Nathan

Deepl not working for me((

line 4, in
var = ts.deepl('Hello', 'en', 'ru' )
line 66, in wrapper
r = func(*args, **kwargs)
line 852, in deepl_api
ss, sentences = self.split_sentences(ss, query_text, from_language, to_language, proxies)
line 794, in split_sentences
r.raise_for_status()
raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 415 Client Error: Unsupported Media Type for url: https://www2.deepl.com/jsonrpc

Baidu api returns partial result

For multi-line content, the baidu translator returns only first line in simple result. The actual simple result should be:

        simple_data = '\n'.join([x['prefixWrap'] * '\n' + x['dst'] for x in data['trans_result']['data']])

Great job!

can't install package

tried to install translators using pip, the module is loaded in the setup.py to get the version, but at this time dependencies aren't installed and the installation crashes.

baidu trans_result

--> 26 print(ts.baidu(wyw_text, professional_field='medicine')) # ('common','medicine','electronics','mechanics')
27
28 # property

~\AppData\Roaming\Python\Python36\site-packages\translators\apis.py in baidu_api(self, query_text, from_language, to_language, **kwargs)
490 time.sleep(sleep_seconds)
491 self.query_count += 1
--> 492 return data if is_detail_result else '\n'.join([x['dst'] for x in data['trans_result']['data']])
493
494

KeyError: 'trans_result'

Tencent returns translation with no whitespace

Tencent seems to be returning the correct translation as a string, but without whitespace.

import translators as ts

def tencent_translate(sentence):  
       translation = ts.tencent(sentence, from_language='en', to_language='es') 
       return translation

tencent_translate('Hi how are you') returns 'Hola,¿cómoestás?' (as opposed to 'Hola, ¿cómo estás?' )

I am using version 4.9.6 of the package in a Jupyter notebook with Python 3.8.8

JSONDecodeError: Expecting value: line 1 column 1 (char 0)

Hi,

I am trying to translate some reviews from English to Persian. Last time I used this API, it translated about 4K reviews and after that, I get the error below:

JSONDecodeError Traceback (most recent call last)
in ()
----> 1 translate_api.api('a new text', 'en', 'fa')

/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/translate_api/translate_api.py in api(text, from_language, to_language, host, proxy)

/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/translate_api/translate_api.py in translate(self, eng_txt, TK, from_language, to_language, host, proxy)

/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/requests/models.py in json(self, **kwargs)
894 # used.
895 pass
--> 896 return complexjson.loads(self.text, **kwargs)
897
898 @Property

/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/init.py in loads(s, encoding, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw)
346 parse_int is None and parse_float is None and
347 parse_constant is None and object_pairs_hook is None and not kw):
--> 348 return _default_decoder.decode(s)
349 if cls is None:
350 cls = JSONDecoder

/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/decoder.py in decode(self, s, _w)
335
336 """
--> 337 obj, end = self.raw_decode(s, idx=_w(s, 0).end())
338 end = _w(s, end).end()
339 if end != len(s):

/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/decoder.py in raw_decode(self, s, idx)
353 obj, end = self.scan_once(s, idx)
354 except StopIteration as err:
--> 355 raise JSONDecodeError("Expecting value", s, err.value) from None
356 return obj, end

JSONDecodeError: Expecting value: line 1 column 1 (char 0)

AssertionError

Hi
I may be looking bad or i miss something,i dont see any new information but not any of my code work they all stooped as i said yesterday.
Even this dont work but i dont see any required arguments needed its should go from french to english no ?:

import translators as ts
print(ts.google("bonjour"))

Ive got an insertion error in most part of case but also if i ask for the language map after its imported, its show me an empty map. I hope you can enlighten me.

"IndexError: list index out of range" at get_language_map

I keep getting this error. Sometimes it works but 90% of the time I get this.

File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\translators\apis.py", line 964, in <lambda>
    repl = lambda x: translator(query_text=x.group(1).strip(), **translator_params) if x.group(1).strip() else ''
  File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\translators\apis.py", line 248, in google_api
    self.language_map = self.get_language_map(host_html)
  File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\translators\apis.py", line 216, in get_language_map
    lang_list_str = re.findall("source_code_name:\[(.*?)\],", host_html)[0]
IndexError: list index out of range

I think it also happens when trying to find tkk ( tkk = re.findall("tkk:'(.*?)'", host_html)[0] )

Request: allow to set timeout to avoid hangs/freeze

seems like the request might hang forever, would be good that a timeout could be passed to the API (and passed down to requests lib) or at least that internally the lib use timeouts everywhere in requests calls to avoid hanging forever

Deepl, Bing and Baidu don't work

Would you please take a look?
Thank you!

Deepl:

>>> ts.deepl(s, from_language='zh', to_language='en', )                                                                        Traceback (most recent call last):                                                                                               File "<stdin>", line 1, in <module>                                                                                            File "/home/qspace/data/huajiehuang/work/ugatit/translators/translators/apis.py", line 60, in wrapper
    r = func(*args, **kwargs)
  File "/home/qspace/data/huajiehuang/work/ugatit/translators/translators/apis.py", line 789, in deepl_api
    r.raise_for_status()
  File "/home/qspace/data/huajiehuang/softs/miniconda3/lib/python3.6/site-packages/requests/models.py", line 941, in raise_for_status
    raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 429 Client Error: Too many Requests for url: https://www2.deepl.com/jsonrpc

Bing:

>>> ts.bing(s, if_use_cn_host=False)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/qspace/data/huajiehuang/work/ugatit/translators/translators/apis.py", line 60, in wrapper
    r = func(*args, **kwargs)
  File "/home/qspace/data/huajiehuang/work/ugatit/translators/translators/apis.py", line 619, in bing_api
    data = r.json()
  File "/home/qspace/data/huajiehuang/softs/miniconda3/lib/python3.6/site-packages/requests/models.py", line 898, in json
    return complexjson.loads(self.text, **kwargs)
  File "/home/qspace/data/huajiehuang/softs/miniconda3/lib/python3.6/json/__init__.py", line 354, in loads
    return _default_decoder.decode(s)
  File "/home/qspace/data/huajiehuang/softs/miniconda3/lib/python3.6/json/decoder.py", line 339, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/home/qspace/data/huajiehuang/softs/miniconda3/lib/python3.6/json/decoder.py", line 357, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

Baidu:

>>> ts.baidu(s, use_domain='common')                                                                                           Traceback (most recent call last):                                                                                               File "<stdin>", line 1, in <module>                                                                                            File "/home/qspace/data/huajiehuang/work/ugatit/translators/translators/apis.py", line 60, in wrapper
    r = func(*args, **kwargs)
  File "/home/qspace/data/huajiehuang/work/ugatit/translators/translators/apis.py", line 313, in baidu_api
    r.raise_for_status()
  File "/home/qspace/data/huajiehuang/softs/miniconda3/lib/python3.6/site-packages/requests/models.py", line 941, in raise_for_status
    raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 401 Client Error: Unauthorized for url: https://fanyi.baidu.com/v2transapi

How many quotas each API support?

First of all, thanks for your interesting work
I wonder what is the limit of each API?
I already tried to call continuously Bing API under 100 times and got HTTP Response message 429, which means I already reach limit quotas.
Do you have any information about quotas for each API. Glad to see it :D

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.