Coder Social home page Coder Social logo

nidhaloff / deep-translator Goto Github PK

View Code? Open in Web Editor NEW
1.4K 19.0 157.0 1012 KB

A flexible free and unlimited python tool to translate between different languages in a simple way using multiple translators.

Home Page: https://deep-translator.readthedocs.io/en/latest/?badge=latest

License: Apache License 2.0

Makefile 2.09% Python 97.91%
translation translator translate python google-translator linguee pons translations translation-files translating

deep-translator's Introduction

deep-translator

deep-translator-icon

image

image

Documentation Status

image

image

image

image

image

Twitter URL

Translation for humans

A flexible FREE and UNLIMITED tool to translate between different languages in a simple way using multiple translators.

|

Table of Contents

|

Motivation

I needed to translate a text using python. It was hard to find a simple way to do it. There are other libraries that can be used for this task, but most of them are buggy, not free, limited, not supported anymore or complex to use.

Therefore, I decided to build this simple tool. It is 100% free, unlimited, easy to use and provides support for all languages.

Basically, my goal was to integrate support for multiple famous translators in this tool.

When you should use it

  • If you want to translate text using python
  • If you want to translate from a file
  • If you want to get translations from many sources and not only one
  • If you want to automate translations
  • If you want to use ChatGpt for translations
  • If you want to compare different translations
  • If you want to detect language automatically

Why you should use it

  • It's the only python tool that integrates many translators
  • Multi language support
  • Support for ChatGpt (version >= 1.11.0)
  • Supports batch translation
  • High level of abstraction
  • Automatic language detection
  • Easy to use and extend
  • Support for most famous universal translators
  • Stable and maintained regularly
  • The API is very easy to use
  • Proxy integration is supported

Features

Installation

Install the stable release:

$ pip install -U deep-translator

$ poetry add deep-translator   # for poetry usage

take a look at the docs if you want to install from source.

Also, you can install extras if you want support for specific use case. For example, translating Docx and PDF files

$ pip install deep-translator[docx]  # add support for docx translation

$ pip install deep-translator[pdf]  # add support for pdf translation

$ pip install deep-translator[ai]   # add support for ChatGpt

$ poetry add deep-translator --extras "docx pdf ai"   # for poetry usage

Quick Start

from deep_translator import GoogleTranslator

# Use any translator you like, in this example GoogleTranslator
translated = GoogleTranslator(source='auto', target='de').translate("keep it up, you are awesome")  # output -> Weiter so, du bist großartig

or using proxies:

from deep_translator import GoogleTranslator

proxies_example = {
    "https": "34.195.196.27:8080",
    "http": "34.195.196.27:8080"
}
translated = GoogleTranslator(source='auto', target='de', proxies=proxies_example).translate("keep it up, you are awesome")  # output -> Weiter so, du bist großartig

or even directly from terminal:

$ deep-translator --source "en" --target "de" --text "hello world"

or shorter

$ dt -tg de -txt "hello world"

Usage

In this section, demos on how to use all different integrated translators in this tool are provided.

Note

You can always pass the languages by the name or by abbreviation.

Example: If you want to use english as a source or target language, you can pass english or en as an argument

Note

For all translators that require an ApiKey, you can either specify it as an argument to the translator class or you can export it as an environment variable, this way you won't have to provide it to the class.

Example: export OPENAI_API_KEY="your_key"

Imports

from deep_translator import (GoogleTranslator,
                             ChatGptTranslator,
                             MicrosoftTranslator,
                             PonsTranslator,
                             LingueeTranslator,
                             MyMemoryTranslator,
                             YandexTranslator,
                             PapagoTranslator,
                             DeeplTranslator,
                             QcriTranslator,
                             single_detection,
                             batch_detection)

Check Supported Languages

Note

You can check the supported languages of each translator by calling the get_supported_languages function.

# default return type is a list
langs_list = GoogleTranslator().get_supported_languages()  # output: [arabic, french, english etc...]

# alternatively, you can the dictionary containing languages mapped to their abbreviation
langs_dict = GoogleTranslator().get_supported_languages(as_dict=True)  # output: {arabic: ar, french: fr, english:en etc...}

Language Detection

Note

You can also detect language automatically. Notice that this package is free and my goal is to keep it free. Therefore, you will need to get your own api_key if you want to use the language detection function. I figured out you can get one for free here: https://detectlanguage.com/documentation

  • Single Text Detection
lang = single_detection('bonjour la vie', api_key='your_api_key')
print(lang) # output: fr
  • Batch Detection
lang = batch_detection(['bonjour la vie', 'hello world'], api_key='your_api_key')
print(lang) # output: [fr, en]

Google Translate

text = 'happy coding'
  • You can use automatic language detection to detect the source language:
translated = GoogleTranslator(source='auto', target='de').translate(text=text)
  • You can pass languages by name or by abbreviation:
translated = GoogleTranslator(source='auto', target='german').translate(text=text)

# Alternatively, you can pass languages by their abbreviation:
translated = GoogleTranslator(source='en', target='de').translate(text=text)
  • You can also reuse the Translator class and change/update its properties.

(Notice that this is important for performance too, since instantiating new objects is expensive)

# let's say first you need to translate from auto to german
my_translator = GoogleTranslator(source='auto', target='german')
result = my_translator.translate(text=text)
print(f"Translation using source = {my_translator.source} and target = {my_translator.target} -> {result}")

# let's say later you want to reuse the class but your target is french now
# This is the best practice and how you should use deep-translator.
# Please don't over-instantiate translator objects without a good reason, otherwise you will run into performance issues
my_translator.target = 'fr'  # this will override the target 'german' passed previously
result = my_translator.translate(text=text)
print(f"Translation using source = {my_translator.source} and target = {my_translator.target} -> {result}")

# you can also update the source language as well
my_translator.source = 'en'  # this will override the source 'auto' passed previously
result = my_translator.translate(text=text)
print(f"Translation using source = {my_translator.source} and target = {my_translator.target} -> {result}")
  • Translate batch of texts
texts = ["hallo welt", "guten morgen"]

# the translate_sentences function is deprecated, use the translate_batch function instead
translated = GoogleTranslator('de', 'en').translate_batch(texts)
  • Translate text from txt/docx/pdf:
path = "your_file.txt"

translated = GoogleTranslator(source='auto', target='german').translate_file(path)

Mymemory Translator

Note

As in google translate, you can use the automatic language detection with mymemory by using "auto" as an argument for the source language. However, this feature in the mymemory translator is not so powerful as in google translate.

  • Simple translation
text = 'Keep it up. You are awesome'

translated = MyMemoryTranslator(source='auto', target='french').translate(text)
  • Translate batch of texts
texts = ["hallo welt", "guten morgen"]

# the translate_sentences function is deprecated, use the translate_batch function instead
translated = MyMemoryTranslator('de', 'en').translate_batch(texts)
  • Translate text from txt/docx/pdf:
path = "your_file.txt"

translated = MyMemoryTranslator(source='en', target='fr').translate_file(path)

DeeplTranslator

Note

In order to use the DeeplTranslator translator, you need to generate an api key. Deepl offers a Pro and a free API. deep-translator supports both Pro and free APIs. Just check the examples below. Visit https://www.deepl.com/en/docs-api/ for more information on how to generate your Deepl api key

  • Simple translation
text = 'Keep it up. You are awesome'

translated = DeeplTranslator(api_key="your_api_key", source="en", target="en", use_free_api=True).translate(text)

Note

deep-translator uses free deepl api by default. If you have the pro version then simply set the use_free_api to false.

  • Translate batch of texts
texts = ["hallo welt", "guten morgen"]

# the translate_sentences function is deprecated, use the translate_batch function instead
translated = DeeplTranslator("your_api_key").translate_batch(texts)

QcriTranslator

Note

In order to use the QcriTranslator translator, you need to generate a free api key. Visit https://mt.qcri.org/api/ for more information

  • Check languages
# as a property
print("language pairs: ", QcriTranslator("your_api_key").languages)
  • Check domains
# as a property
print("domains: ", QcriTranslator("your_api_key").domains)
  • Text translation
text = 'Education is great'

translated = QcriTranslator("your_api_key").translate(source='en', target='ar', domain="news", text=text)
# output -> التعليم هو عظيم

# see docs for batch translation and more.

Linguee Translator

word = 'good'
  • Simple Translation
translated_word = LingueeTranslator(source='english', target='french').translate(word)
  • Return all synonyms or words that match
# set the argument return_all to True if you want to get all synonyms of the word to translate
translated_word = LingueeTranslator(source='english', target='french').translate(word, return_all=True)
  • Translate a batch of words
translated_words = LingueeTranslator(source='english', target='french').translate_words(["good", "awesome"])

PONS Translator

Note

You can pass the languages by the name or by abbreviation just like previous examples using GoogleTranslate

word = 'awesome'
  • Simple Translation
translated_word = PonsTranslator(source='english', target='french').translate(word)

# pass language by their abbreviation
translated_word = PonsTranslator(source='en', target='fr').translate(word)
  • Return all synonyms or words that match
# set the argument return_all to True if you want to get all synonyms of the word to translate
translated_word = PonsTranslator(source='english', target='french').translate(word, return_all=True)
  • Translate a batch of words
translated_words = PonsTranslator(source='english', target='french').translate_words(["good", "awesome"])

Yandex Translator

Note

You need to require a private api key if you want to use the yandex translator. Visit the official website for more information about how to get one

  • Language detection
lang = YandexTranslator('your_api_key').detect('Hallo, Welt')
print(f"language detected: {lang}")  # output -> language detected: 'de'
  • Text translation
# with auto detection | meaning provide only the target language and let yandex detect the source
translated = YandexTranslator('your_api_key').translate(source="auto", target="en", text='Hallo, Welt')
print(f"translated text: {translated}")  # output -> translated text: Hello world

# provide source and target language explicitly
translated = YandexTranslator('your_api_key').translate(source="de", target="en", text='Hallo, Welt')
print(f"translated text: {translated}")  # output -> translated text: Hello world
  • File translation
translated = YandexTranslator('your_api_key').translate_file(source="auto", target="en", path="path_to_your_file")
  • Batch translation
translated = YandexTranslator('your_api_key').translate_batch(source="auto", target="de", batch=["hello world", "happy coding"])

Microsoft Translator

Note

You need to require an api key if you want to use the microsoft translator. Visit the official website for more information about how to get one. Microsoft offers a free tier 0 subscription (2 million characters per month).

text = 'happy coding'
translated = MicrosoftTranslator(api_key='some-key', target='de').translate(text=text)
translated_two_targets = MicrosoftTranslator(api_key='some-key', target=['de', 'ru']).translate(text=text)
translated_with_optional_attr = MicrosoftTranslator(api_key='some-key', target='de', textType='html']).translate(text=text)
  • You can pass languages by name or by abbreviation:
translated = MicrosoftTranslator(api_key='some-key', target='german').translate(text=text)

# Alternatively, you can pass languages by their abbreviation:
translated = MicrosoftTranslator(api_key='some-key', target='de').translate(text=text)
  • Translate batch of texts
texts = ["hallo welt", "guten morgen"]
translated = MicrosoftTranslator(api_key='some-key', target='english').translate_batch(texts)
  • Translate from a file:
translated = MicrosoftTranslator(api_key='some-key', target='german').translate_file('path/to/file')

ChatGpt Translator

Note

You need to install the openai support extra. pip install deep-translator[ai]

Note

You need to require an api key if you want to use the ChatGpt translator. If you have an openai account, you can create an api key (https://platform.openai.com/account/api-keys).

  • Required and optional attributes

    There are two required attributes, namely "api_key" (string) and "target" (string or list). Attribute "source" is optional.

    You can provide your api key as an argument or you can export it as an env var e.g. export OPENAI_API_KEY="your_key"

text = 'happy coding'
translated = ChatGptTranslator(api_key='your_key', target='german').translate(text=text)
  • Translate batch of texts
texts = ["hallo welt", "guten morgen"]
translated = ChatGptTranslator(api_key='some-key', target='english').translate_batch(texts)
  • Translate from a file:
translated = ChatGptTranslator(api_key='some-key', target='german').translate_file('path/to/file')

Papago Translator

Note

You need to require a client id and client secret key if you want to use the papago translator. Visit the official website for more information about how to get one.

text = 'happy coding'
translated = PapagoTranslator(client_id='your_client_id', secret_key='your_secret_key', source='en', target='ko').translate(text=text)  # output: 행복한 부호화

Libre Translator

Note

Libre translate has multiple mirrors which can be used for the API endpoint. Some require an API key to be used. By default the base url is set to libretranslate.de . This can be set using the "base_url" input parameter.

text = 'laufen'
translated = LibreTranslator(source='auto', target='en', base_url = 'https://libretranslate.com/', api_key = 'your_api_key').translate(text=text)  # output: run
  • You can pass languages by name or by abbreviation:
translated = LibreTranslator(source='german', target='english').translate(text=text)

# Alternatively, you can pass languages by their abbreviation:
translated = LibreTranslator(source='de', target='en').translate(text=text)
  • Translate batch of texts
texts = ["hallo welt", "guten morgen"]
translated = LibreTranslator(source='auto', target='en').translate_batch(texts)
  • Translate from a file:
translated = LibreTranslator(source='auto', target='en').translate_file('path/to/file')

TencentTranslator

Note

In order to use the TencentTranslator translator, you need to generate a secret_id and a secret_key. deep-translator supports both Pro and free APIs. Just check the examples below. Visit https://cloud.tencent.com/document/api/551/15619 for more information on how to generate your Tencent secret_id and secret_key.

  • Simple translation
text = 'Hello world'
translated = TencentTranslator(secret_id="your-secret_id", secret_key="your-secret_key" source="en", target="zh").translate(text)
  • Translate batch of texts
texts = ["Hello world", "How are you?"]
translated = TencentTranslator(secret_id="your-secret_id", secret_key="your-secret_key" source="en", target="zh").translate_batch(texts)
  • Translate from a file:
translated = TencentTranslator(secret_id="your-secret_id", secret_key="your-secret_key" source="en", target="zh").translate_file('path/to/file')

BaiduTranslator

Note

In order to use the BaiduTranslator translator, you need to generate a secret_id and a secret_key. deep-translator supports both Pro and free APIs. Just check the examples below. Visit http://api.fanyi.baidu.com/product/113 for more information on how to generate your Baidu appid and appkey.

  • Simple translation
text = 'Hello world'
translated = BaiduTranslator(appid="your-appid", appkey="your-appkey" source="en", target="zh").translate(text)
  • Translate batch of texts
texts = ["Hello world", "How are you?"]
translated = BaiduTranslator(appid="your-appid", appkey="your-appkey" source="en", target="zh").translate_batch(texts)
  • Translate from a file:
translated = BaiduTranslator(appid="your-appid", appkey="your-appkey" source="en", target="zh").translate_file('path/to/file')

BaiduTranslator

Note

In order to use the BaiduTranslator translator, you need to generate a secret_id and a secret_key. deep-translator supports both Pro and free APIs. Just check the examples below. Visit http://api.fanyi.baidu.com/product/113 for more information on how to generate your Baidu appid and appkey.

  • Simple translation
text = 'Hello world'
translated = BaiduTranslator(appid="your-appid", appkey="your-appkey" source="en", target="zh").translate(text)
  • Translate batch of texts
texts = ["Hello world", "How are you?"]
translated = BaiduTranslator(appid="your-appid", appkey="your-appkey" source="en", target="zh").translate_batch(texts)
  • Translate from a file:
translated = BaiduTranslator(appid="your-appid", appkey="your-appkey" source="en", target="zh").translate_file('path/to/file')

Proxy usage

deep-translator provides out of the box usage of proxies. Just define your proxies config as a dictionary and pass it to the corresponding translator. Below is an example using the GoogleTranslator, but this feature can be used with all supported translators.

from deep_translator import GoogleTranslator

# define your proxy configs:
proxies_example = {
    "https": "your https proxy",  # example: 34.195.196.27:8080
    "http": "your http proxy if available"
}
translated = GoogleTranslator(source='auto', target='de', proxies=proxies_example).translate("this package is awesome")

File Translation

Deep-translator (version >= 1.9.4) supports not only text file translation, but docx and PDF files too. However, you need to install deep-translator using the specific extras.

For docx translation:

pip install deep-translator[docx]

For PDF translation:

pip install deep-translator[pdf]
  • Translate text from txt/docx/pdf:

Here is sample code for translating text directly from files

path = "example/test.pdf"

translated = GoogleTranslator(source='auto', target='german').translate_file(path)

Usage from Terminal

Deep-translator supports a series of command line arguments for quick and simple access to the translators directly in your console.

Note

The program accepts deep-translator or dt as a command, feel free to substitute whichever you prefer.

For a list of available translators:

$ deep-translator list

To translate a string or line of text:

$ deep_translator google --source "english" --target "german" --text "happy coding"

Alternate short option names, along with using language abbreviations:

$ deep_translator google -src "en" -tgt "de" -txt "happy coding"

Finally, to retrieve a list of available languages for a given translator:

$ deep-translator languages google

Tests

Developers can install the development version of deep-translator and execute unit tests to verify functionality. For more information on doing this, see the contribution guidelines

Check this article on medium to know why you should use the deep-translator package and how to translate text using python. https://medium.com/@nidhalbacc/how-to-translate-text-with-python-9d203139dcf5

Help

If you are facing any problems, please feel free to open an issue. Additionally, you can make contact with the author for further information/questions.

Do you like deep-translator? You can always help the development of this project by:

  • Following on github and/or twitter
  • Promote the project (ex: by giving it a star on github)
  • Watch the github repo for new releases
  • Tweet about the package
  • Help others with issues on github
  • Create issues and pull requests
  • Sponsor the project

Next Steps

Take a look in the examples folder for more :) Contributions are always welcome. Read the Contribution guidelines Here

Credits

Many thanks to @KirillSklyarenko for his work on integrating the microsoft translator

License

MIT license

Copyright (c) 2020-present, Nidhal Baccouri

Swagger UI

deep-translator offers an api server for easy integration with other applications. Non python applications can communicate with the api directly and leverage the features of deep-translator

Access the api here: https://deep-translator-api.azurewebsites.net/docs

The Translator++ mobile app

Icon of the app

You can download and try the app on play store https://play.google.com/store/apps/details?id=org.translator.translator&hl=en_US&gl=US

After developing the deep-translator, I realized how cool this would be if I can use it as an app on my mobile phone. Sure, there is google translate, pons and linguee apps etc.. but isn't it cooler to make an app where all these translators are integrated?

Long story short, I started working on the app. I decided to use the kivy framework since I wanted to code in python and to develop a cross platform app. I open sourced the Translator++ app on my github too. Feel free to take a look at the code or make a pull request ;)

Note

The Translator++ app is based on the deep-translator package. I just built the app to prove the capabilities of the deep-translator package ;)

I published the first release on google play store on 02-08-2020

Here are some screenshots:

  • Phone

screenshot1

screenshot2

spinner

  • Tablet:

screenshot3

Website & Desktop app

Currently, there are propositions for a website and/or desktop app based on deep-translator. You can follow the issue here: #144

deep-translator's People

Contributors

bigsbunny avatar dependabot[bot] avatar dh-rico-freitas avatar edi-sugiarto avatar fcolecumberri avatar gleidsonh avatar hanlhan avatar jettscythe avatar jiaulislam avatar joao-vitor-souza avatar kirillsklyarenko avatar kuspia avatar libialany avatar nidhaloff avatar prasanta-hembram avatar prataffel avatar rahulbanerjee26 avatar rubeneu avatar saminul avatar senk8 avatar simadovakin avatar thywoof avatar touch-night avatar tuyenhn avatar var-nan avatar vincent-stragier avatar wenbindu avatar wf001 avatar yelinz avatar yutkat 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

deep-translator's Issues

translate_batch() missing 2 required positional arguments: 'target' and 'batch'

  • deep_translator version: 1.4.1
  • Python version: 3.9.1
  • Operating System: macOS 10.13.6

Description

my Python file has

from deep_translator import DeepL
api_key="xxxx"
texts = ["hallo welt", "guten morgen"]
translated = DeepL(api_key).translate_batch(texts)

What I Did

I run the file as python3 deepl.py. The results are:

Traceback (most recent call last):
  File "/Users/souto/path/to/deepl.py", line 4, in <module>
    translated = DeepL(api_key).translate_batch(texts)
TypeError: translate_batch() missing 2 required positional arguments: 'target' and 'batch'

.translate(source=/target=) vs .__init__(source=/target=)

  • type: informational
  • priority: low
  • severity: none
  • deep_translator version: 1.4.3
  • Python version: 2.7 / 3.8
  • Operating System: Linux

So, I'm currently integrating some deep-translator backends with PageTranslate (a LibreOffice plugin). There's some overlap, and generally the API fits well. There's a few things I stumbled across however:

  • The "DEEPL_FREE" url in constants.py is missing a trailing slash. Probably also the /v2/ according to the API docs. (Albeit my API key isn't working, haven't tested any of this.)

  • Between Pons/Linguee and Qcri/Yandex there's a bit of inconsistency to initializing things. Namely the source=/target= parameter, which either goes along with the .translate() call, or with the class __init__(). I feel like that should be on the class constructor in any case (like the DeepL translator does). Else, you end up with currying if you want to switch between backends.

    For example translationbackends.py:

        elif re.search("pons", backend, re.I):
            self.translate = self.from_words(
                deep_translator.PonsTranslator(source=source, target=target).translate
            )
        elif re.search("QCRI", backend, re.I):
            self.translate = functools.partial(
                deep_translator.QCRI(params["api_key"]).translate, source=source, target=target
            )
    
  • The dictionary .translate() function might also be worth renaming/splitting up. Perhaps a general convenience wrapper to simulate text translations through the word-by-word interface might be worthwhile.

  • Now for my use case, I probably need to bundle deep-translator. Which comes with a hefty price tag, since beatifulsoup pulls in lxml - thus bloating a LibreOffice extension from a few KB to 20MB. (And that's not even cross-platform).

    Obviously there's some convenience in BS4. Though if feasible, it would be nice if that could be optionalized/omitted for some translation backends. If it's really just grepping from some HTML tags, and only concerns the dictionary translators, there are leaner options.

    Again, might not be feasible or worth the time. And after all that's just a downstream concern. And I'm still contemplating if importing just a singular class from deep_translator import Yandex avoids pulling in the other dependencies. (Also doesn't really matter for OpenOffice, since D-L won't run in that Python environment regardless. Only a worry for the LibreOffice bundle.).

  • Another more practical concern: source="auto" should be implicitly supported by D-L, regardless of the translation service. If there's no provider support then deep-translator should run an implicit language detection. (Btw, langdetect is still a functional alternative to the proprietary online service.)

can i get the from language in any way ?

hello!
im coding something for myself and i have someneed i wish you to informate me :)
so in first , is it possible to autodetect the language source but to recuperate the language source name in any case ?
and secundo is it possible to :
i give a word random, its give me the translation if different from the Input . but iwould its continue search traduction for this word while the trad is something identic. but only in autodetectlanguage and give me the result when its not the same than input .Thanks you 🦋

Can't translate 2000+ words from a text file - character limit?

  • deep_translator version: 1.3.9
  • Python version: 3.7.4
  • Operating System: Windows 10

Description

Hi! :)

I wanted to translate 2000+ words from a text file but when running:

translated = GoogleTranslator(source=select_source_language, target=select_target_language).translate_file("file.txt")

I got an error:

raise NotValidLength(payload, min_chars, max_chars)

with Text length need to be between 1 and 5000 characters.

It was working fine when I ran the code on 200+ words, though.

Does this package have a character limit then? If so, is there any workaround?

Error : Can't translate if text is less than 5k characters.

deep_translator.exceptions.NotValidPayload: {'text': 'some_text'} --> text must be a valid text with maximum 5000 character, otherwise it cannot be translated.

I am getting this error while I am trying to translate. Why is this issue happening, what should I do to solve this, please suggest me something.

Linguee translator adds pronouns (+ case) without spaces

  • deep_translator version: 1.1.4
  • Python version: 3.8.5
  • Operating System: Linux

The Linguee translator adds pronouns and possible information about correct cases to the translation without spaces.

deep_translator.LingueeTranslator("de", "en").translate("programmieren") returns 'programsth.'
deep_translator.LingueeTranslator("en", "de").translate("program", return_all=True) returns ['Programm', 'Sendung', 'etw.Akkprogrammieren']

The additional pronouns are passed in a span of the "placeholder" class.

Pons translator only returns the first word

  • deep_translator version: 1.1.3
  • Python version: 3.8.5
  • Operating System: Linux

Description

The Pons translator only returns the first word of the translation - even if the first entry of the list of all results contains multiple words.

What I Did

deep_translator.PonsTranslator(source='german', target='english').translate('laufen') returns 'to ' (expected would be 'to run' which is the first entry in the list returned by deep_translator.PonsTranslator(source='german', target='english').translate('laufen', return_all = True)).

Linguee Translator does not support all languages

  • deep_translator version: Latest
  • Python version: 3.8
  • Operating System: Ubuntu

Description

Linguee Translator does not support all languages in LINGUEE_LANGUAGES_TO_CODES. For example in the case of translating from Greek to English, I get Required element was not found in the API response error.

Add tests for the cli

Description

The cli was re-written using the click library. However, there are no tests for the functionality of cli at the moment.
Click offers great support for unit testing. Read here

I will let this issue open for newcomers or anyone who is looking for a good first issue. I think this would be a great task for anyone who wants to join the project.

add more examples and test cases

  • deep_translator version: >= 1.0.0
  • Python version: >=3

Description

This is a first good issue/enhancement for new comers. It would great to start documenting more examples.
Moreover, it would be great to write more tests.

Just check the examples and tests folder to have an idea. This issue/enhancement is a great start for new comers to contribute to the project.

Convert to API

  • deep_translator version:
  • Python version:
  • Operating System:

Description

Is it possible to get API with Key?

NotValidLength - 5000 chars limit?

Hi,

Is it possible to split a txt file in 5000 chars batches and submit them to google for translation? I suppose this error comes from this limit..
Thanks

  • deep_translator version:
  • Python version:
  • Operating System:

Description

Describe what you were trying to get done.
Tell us what happened, what went wrong, and what you expected to happen.

What I Did

Paste the command(s) you ran and the output.
If there was a crash, please include the traceback here.

Won't translate from English to Dutch

  • deep_translator version: 1.3.2
  • Python version: 3.6.9
  • Operating System: Linux dbe87b14d8a6 4.19.112+ #1 SMP Thu Jul 23 08:00:38 PDT 2020 x86_64 x86_64 x86_64 GNU/Linux

Description

GoogleTranslator returns English phrase as is when I try to translate it into Dutch
I tried it using https://colab.research.google.com/

What I Did

from deep_translator import GoogleTranslator

GoogleTranslator(source='en', target='nl').translate('why not Dutch')

why not Dutch

Other languages that I tried work fine.

Not translate some words / html tags

Is there a way to not translate some words? For example, I am translating html, but tags like < strong > are translated as well.

I could remove the tags and translate only the text, but in some cases tags are important. For example, "Eu quero < strong > comprar < /strong > um carro" (portuguese), if you are going to translate separately "Eu quero", "comprar", "um carro", translation will be different than translating it entirely.

For example, the translated phrase "I want to buy a car", "I want to" would be "I want", not being correct when putting everything back together: "I want buy a car". Translating with html tags this problem does not happen. Look here.

So I ask: is it possible not to translate some words, or is it at least possible to do this with html tags?

Mymemory auto detection doesn't work

  • deep_translator version: 1.1.0
  • Python version: 3.8
  • Operating System: OSX

Description

Auto language detection of the MyMemoryTranslator is not working.

Google wants certificate verification

  • deep_translator version: 1.0.6
  • Python version: 3.8.3
  • Operating System: Linux

Google gives warning before response

Request any translation from GoogleTranslate and the response comes back:

Warning: Unverified HTTPS request is being made to host 'translate.google.com'. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
warnings.warn

Followed by the translation. So it all works beautifully. At a minimum, I'd like to suppress the warning.

[enhancement] Auto translate language return

Currently, there is no way to find out what the auto translated language was...which makes it kind of iffy. I'd like to know what language it automatically detected. I understand that currently the scraping is done of mobile site, and I looked into it but it does not show detected language anywhere unfortunately. Are there any plans to enhance the scraping to scrape from the classic Google Translate?

deep_translator does not translate text in few languages

deep_translator does not translate text properly in a few languages.

Here's my code:

from deep_translator import GoogleTranslator

translator = GoogleTranslator(target="irish")

text_to_translate = "Hello, how are you?"

translated_text = translator.translate(text_to_translate)

print(translated_text)

Here when I run the code, the output is the same and the text does not seem to get translated.

I tried adding the source parameter to the GoogleTranslator class, but the output is still the same.

Can you please help me in fixing this problem?

Deep_translator version: 1.3.5
Python version: 3.9.1
OS: Windows 10

API connection error without connection problems

  • deep_translator version:1.5.0
  • Python version: 3.9
  • Operating System: Windows 10

Description

I was trying to execute this line: result += GoogleTranslator(source='ru', target='uk').translate(trans), where trans is a proper unicode string

What I Did

Here's the traceback:
Traceback (most recent call last):
File "C:\Users\ilyag\Desktop\Translation\Translate.py", line 35, in
print(translate(data[0]['content']))
File "C:\Users\ilyag\Desktop\Translation\Translate.py", line 22, in translate
result += GoogleTranslator(source='ru', target='uk').translate(trans)
File "C:\Users\ilyag\Desktop\Translation\venvpy\lib\site-packages\deep_translator\google_trans.py", line 100, in translate
raise RequestError()
deep_translator.exceptions.RequestError: Request exception can happen due to an api connection error. Please check your connection and try again

Text translation that once worked now does not work

  • deep_translator version: 1.1.7
  • Python version: 3.8.3
  • Operating System: Manjaro 20.0.3

I'm trying to semi-automatize an HTML page using BeautifulSoup.
I was very happy with deep-translator until something strange happened...

It rises 'TranslationNotFound' with some text that was already working!

text = 'If you are a school administrator or local official who has control over school opening decisions, we strongly urge you to keep schools closed until there is no more community transmission of the virus. There must be no more transmission of the virus in your community and the surrounding areas for 14 days. If you would like more guidance on why reopening schools is dangerous and how to talk to students, teachers, parents and staff, EndCoronavirus.org is here to help.Please contact us for more information.'

GoogleTranslator(source='auto', target='spanish').translate(text=tag.text)

Traceback:

TranslationNotFound                       Traceback (most recent call last)
<ipython-input-8-466242e1794e> in <module>
      1 # Using deep_translator with Google's engine (spanish)
----> 2 traslated = GoogleTranslator(source='auto', target='spanish').translate(text=tag.text)
      3 traslated

~/.local/lib/python3.8/site-packages/deep_translator/google_trans.py in translate(self, text, **kwargs)
     78             if not element:
     79                 # raise ElementNotFoundInGetRequest(element)
---> 80                 raise TranslationNotFound(text)
     81 
     82             return element.get_text(strip=True)

TranslationNotFound: If you are a school administrator or local official who has control over school opening decisions, we strongly urge you to keep schools closed until there is no more community transmission of the virus. There must be no more transmission of the virus in your community and the surrounding areas for 14 days. If you would like more guidance on why reopening schools is dangerous and how to talk to students, teachers, parents and staff, EndCoronavirus.org is here to help.Please contact us for more information. --> No translation was found using the current translator. Try another translator?

Maybe I exceeded the max translations allowed? It should be unlimited, right?

And when I use 'MyMemoryTranslator' I get:

'QUERY LENGTH LIMIT EXCEDEED. MAX ALLOWED QUERY : 500 CHARS'

Also unexpected!

Keyerror: 'h1' when performing translations

  • deep_translator version: 1.3.3
  • Python version: 3.6
  • Operating System: Google Colab

Description

I have been using this script to translate words but just today it stopped working and I get this error:
KeyError: 'hl'

Full error:
Screenshot 2021-02-13 at 1 06 25 AM

from deep_translator import GoogleTranslator
from deep_translator import GoogleTranslator as GT
from deep_translator import exceptions as excp


def translate(x):
    try:
        v = GT(source='auto', target='en').translate(x['tweet_text']) if (x['tweet_text'] != " " and x['lang'] != "en") else x['tweet_text']
    except (excp.NotValidPayload, excp.NotValidLength) as e:
        v = f'Translation Exception: {type(e)}'
    return v

# translate the column
df_bdtu['translated'] = df_bdtu[['tweet_text', 'lang']].swifter.apply(lambda x: translate(x), axis = 1)

How to use DeepL Api Free?

Hello I saw the new update, it includes a deepL free api but there's no instruction how to use it. Plss help

Convert from setup_tools to poetry for build backend

What it says on the tin: convert the build backend to Poetry. I already have a working Poetry workflow in my own project, and can do the conversion easily in a new branch, all that will be needed before merging to master is either reconfiguring Travis or switching to another CI. I haven't done much research on the different CI options, but @nidhaloff mentioned GitHub Actions which may be viable.

[Feature Request] make library api more homogeneous

  • deep_translator version: 1.4.4
  • Python version: 3.9.5
  • Operating System: Linux

I am trying to run this:

#! /usr/bin/python3

from deep_translator import (
    GoogleTranslator,
    MicrosoftTranslator,
    PonsTranslator,
    LingueeTranslator,
    MyMemoryTranslator,
    YandexTranslator,
    DeepL,
    QCRI
)

translators = [
    GoogleTranslator,
    MicrosoftTranslator,
    PonsTranslator,
    LingueeTranslator,
    MyMemoryTranslator,
    YandexTranslator,
    DeepL,
    QCRI
]

if __name__ == '__main__':
    for translator_t in translators:
        try:
            print(translator_t)
            print(translator_t.get_supported_languages())
        except Exception as e:
            print(e)

And I find that some of the back-ends like YandexTranslator, DeepL & QCRI have not implemented the get_supported_languages() function (or at least not as a static function, YandexTranslator & QCRI have it as a non static)

This could be neat for people trying to find out which back-ends are useful for a given situation.

documentation needs updated

There have been many recent changes to deep-translator, including a recent update to introduce new CLI functionality. These changes need to be added to the documentation.

Good first issue: The documentation is mostly accurate, there is just some missing coverage of new features, so this should be simple enough for someone who either knows restructuredText or wants to learn it.

Result is different from translate.google.com/m?.

  • deep_translator version: 4.1.2
  • Python version: 3+
  • Operating System: Windows 10

Description

I compare the translation to translate.google.com/m, and I found that the result is different. But After I try it again, the result become the same.

Conclusion: After you translate a word or sentence you already translated from translate.google.com/m? the result will become the same.

GoogleTranslator works intermittently

  • deep_translator version: 1.3.1
  • Python version: 3.8.5
  • Operating System: macOS Catalina, Ubuntu 18

Description

GoogleTranslator returns the correct translation sometimes, and the deep_translator.exceptions.TranslationNotFound exception is raised sometimes with the same input.

What I Did

Sample case (translates the same string 10 times):

python -c 'from deep_translator import GoogleTranslator; [print(GoogleTranslator(source="en", target="ar").translate("Hello how are you")) for _ in range(10)]'

Sample Output (varies how many times the call succeeds, but has consistently failed before reaching all 10):

مرحبا كيف حالك
مرحبا كيف حالك
مرحبا كيف حالك
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "<string>", line 1, in <listcomp>
  File "/Users/fahim/Software/miniconda3/envs/mt-dialect-translation/lib/python3.8/site-packages/deep_translator/google_trans.py", line 103, in translate
    raise TranslationNotFound(text)
deep_translator.exceptions.TranslationNotFound: Hello how are you --> No translation was found using the current translator. Try another translator?

Integrate more translators

  • deep_translator version: >=1.0.0
  • Python version: >=3

Description

I'm opening this issue for new comers. If you want to contribute to the project, then this is a good issue/enhancement to start with. Hopefully you know that the goal of the project is to integrate many translators in one tool.

Until now, the google, pons, linguee and mymemory translators are integrated. Feel free to come up with new ideas

Docs shows failing

I have to dig through the RTD site, but for some reason the current version of the documentation shows failing. I'm putting an Issue here to either remind myself to investigate or allow someone to come in and dig through it themselves. Most likely the docs for main.py just need correcting, but there could be more.

CLI -lang switch fails

Description

Current iteration of "deep-translator xxx -lang" does not perform correctly. -lang switch needs to be converted to a subcommand instead of an option.

PonsTranslator raises IndexError translating arabic to english

  • deep_translator version: 1.1.5
  • Python version: Python 3.9.0b5
  • Operating System: Win 10 Pro

Description

I am trying to translate an arabic sentence to english.
I believe this was working, or at least not raising an exception with version 1.1.4.
The arabic sentence آخُذ اَلْباص. should translate to something like I take the bus..

Note: this form is rendering the FULL_STOP at the right end of the string. Several other LTR renders will place it in the correct position at the left end of the string.

What I Did

> py -3.9
Python 3.9.0b5 (tags/v3.9.0b5:8ad7d50, Jul 20 2020, 18:35:09) [MSC v.1924 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import deep_translator
>>> deep_translator.__version__
'1.1.5'
>>> from deep_translator import PonsTranslator
>>> t = PonsTranslator(source='arabic', target='english')
>>> t.translate('آخُذ اَلْباص.')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\Doug\AppData\Local\Programs\Python\Python39\lib\site-packages\deep_translator\pons.py", line 81, in translate
    return word_list if return_all else word_list[0]
IndexError: list index out of range
>>>

error Translation with DeepL as Translator

  • deep_translator version: 1.3.0
  • Python version: 3x
  • Operating System: Win10

Description

I have try to use DeepL (i have an api_key) in ur script but i become an error,
i have use follow commands

translated = DeepL("MYKEY").translate("keep it up, you are awesome")
print(translated)

What I Did

Traceback (most recent call last):
  File "test_deepl.py", line 5, in <module>
    translated = DeepL("KEY").translate("keep it up, you are awesome")
  File "C:\Python37-32\lib\site-packages\deep_translator\deepl.py", line 23, in __init__
    self.__base_url = BASE_URLS.get("DEEPL").format(version=self.version)
IndexError: tuple index out of range

DEEPL integration

@nothead31

If` you could open a separate ticket for your suggestion, I already work in Pandas and can tackle adding that in later after I finish my current work.

Hi nothead31 !
I will be great to have a DeepL integration in XLS files so that I can translate automatically multiple cells at once.
And what if I want DeepL to be working online with Google Sheets ? Do you think it can be done ?

Thank you very much for you answer and for help !

Proxy support?

  • deep_translator version: 1.4.1
  • Python version: 3.9
  • Operating System: win10 20H2

Description

Add a proxy argument to client to use a proxy connection.

What I Did

Like this.

GoogleTranslator(source='auto', target='de', proxies={'http':'http://localhost:1080'}).translate('I am a fool..')

Is there any way to speed up the process of translating bigger payloads?

  • deep_translator version: 1.4.1
  • Python version: 3.7.4
  • Operating System: Windows 10

Description

I'm wondering if there is any way to speed up the process of translating bigger payloads - hundreds, even thousands of words?

deep_translator sleeps for two seconds after each request in order to not spam the google server

That seems reasonable… but 250 words are gonna need 8+ minutes to process (250 words × 2 seconds = 500 seconds = 8.33 minutes).

Having a payload of ~ 2500 words one would need to wait for ~ 83 minutes before script is executed in full.

Can deep-translator wait for less than 2 seconds? Maybe 1 or even a fraction of a second to speed up the process?

Let's interop with js and python

Hi, i found this project and its seems very good.

I make same project, but for javascript: https://github.com/translate-tools/core

What you think about to set links to each other in our projects? For example make section "Related projects" or "Alternatives for other languages" in README.md and insert there a link.

I think that cross linking to related projects will useful for all people who search tool for their case and programming language.

For example not so long ago i was can't found good translator for python and now maybe someone can't find free translator for javascript, but ended up in this repo or vice versa

deep_translator - GoogleTranslator does not translate German to Dutch directly.

deep_translator version: 1.4.2
Python version: 3.8.5
Operating System: Ubuntu 20.04

Problem: deep_translator - GoogleTtranslator does not translate German to Dutch directly.

I need to translate first to English and than from English to Dutch.
Translate from German to other languages than Dutch is no problem.

To reproduce:

from deep_translator import GoogleTranslator
description = "Zwei minimale Dellchen auf der Rückseite."
translated_text = GoogleTranslator(source='de', target='nl').translate(description)

the output gives a translated text in English instead of Dutch.
gives "Two minimal dents on the back." instead of "Twee minimale deukjes op de achterkant."

GoogleTranslator Not working for Indian Languages

  • deep_translator version: 1.3.2
  • Python version: 3.7
  • Operating System: win10

Description

Translation to English not working for Indian language text transliterated in English

What I Did

GoogleTranslator(source='hindi', target='en').translate(text="ghar jaana hai")

is returning ghar jaana hai. Whereas the googletranslate website is returning proper translation want to go home here

Inviting contributors/maintainer(s) to the project

Hello everyone,

First of all, I want to take a moment to thank all contributors and people who supported this project in any way ;) you are awesome!

The deep-translator package contains now 9 famous translators, which can be used simply just by importing the right one. I tried to keep the API very simple and as consistent as it can be, which will hopefully make contributors' lives easier if they want to implement/add a new translator to the chain.

If you like the project and have any interest in contributing, you can contact me here or send me a msg privately:

Pons translator request ERROR

  • deep_translator version: Latest
  • Python version: 3.8
  • Operating System: Ubuntu

Description

Pons translator receiving error Request exception can happen due to an api connection error. Please check your connection and try again

`KeyError: 'hl'` when running `translate_batch()`

  • deep_translator version: 1.3.9
  • Python version: 3.7.4
  • Operating System: Windows 10

Description

I couldn't translate 2000+ words from a text file (described in here #40) so I thought about using translate_batch() instead. Running:

translated_list = GoogleTranslator(select_source_language, select_target_language).translate_batch(list_of_words)

gives me this error:

Traceback (most recent call last):
  File "script.py", line 113, in <module>
    translated_list = GoogleTranslator(select_source_language, select_target_language).translate_batch(list_of_words)
  File "C:\Users\USER\AppData\Local\Programs\Python\Python37\lib\site-packages\deep_translator\google_trans.py", line 169, in translate_batch
    translated = self.translate(text)
  File "C:\Users\USER\AppData\Local\Programs\Python\Python37\lib\site-packages\deep_translator\google_trans.py", line 113, in translate
    return self.translate(text)
  File "C:\Users\USER\AppData\Local\Programs\Python\Python37\lib\site-packages\deep_translator\google_trans.py", line 112, in translate
    del self._url_params["hl"]
KeyError: 'hl'

What's the reason behind it? How to make it work?

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.