Package: translatepy
translatepy(originally: translate)An aggregation of multiple translation APITranslate, transliterate, get the language of texts in no time with the help of multiple APIs!Getting StartedThese instructions will get you a copy of the project up and running on your local machine for development and testing purposes. See deployment for notes on how to deploy the project on a live system.PrerequisitesYou will need Python 3 to use this module# vermin outputMinimumrequiredversions:3.2
Incompatibleversions:2According to Vermin (--backport typing), Python 3.2 is needed for the backport of typing but some may say that it is available for python versions higher than 3.0Always check if your Python version works withtranslatepybefore using it in productionInstallingOption 1: From PyPIpipinstall--upgradetranslatepyOption 2: From Gitpipinstall--upgradegit+https://github.com/Animenosekai/translateYou can check if you successfully installed it by printing out its version:$translatepy--version# output:translatepyv2.3or just:$python-c"import translatepy; print(translatepy.__version__)"# output:translatepyv2.3List of Built-in ServicesMicrosoft Bing TranslatorDeepLGoogle TranslateLibreTranslateMicrosoft TranslatorMyMemoryReversoTranslate.comYandex Translate... but plugins can be made and/or used. More on that in thepluginssection.All of the names belong to their respective rightholders.UsageCommand line interface modeInteractive Shell (REPL)$translatepyshell## Choose the action[?]Whatdoyouwanttodo?:Translate>TranslateTransliterateSpellcheckLanguageExampleQuit## Choose the language to translate in (this step can be skipped by passing the `--dest-lang` argument when starting the program)Inwhatlanguagedoyouwanttotranslatein?[?](translatepy~SelectLang.)>:...## TranslateEnter'.quit'tostoptranslating(translatepy~Translate)>...# type in whatever you want to translateIn other applications/from the terminalSelect an action:
{translate,transliterate,language,spellcheck}and pass it as a command with the right arguments:$translatepytranslate--dest-langFrançais--textHello{"success":true,"service":"Google","source":"Hello","sourceLanguage":"eng","destinationLanguage":"fra","result":"Bonjour"}In Python scriptThe Translator ClassThe translator lets you group and use multiple translators at the same time, to increase your chance on getting an answer.It takes twooptionalarguments: theservices_listargument, which is a list ofTranslatorobjects and the second one being therequestargument which is the object which will be used to make requests.It has all of the supported methods.translate: To translate thingstranslate_html : To translate HTML snippetstransliterate: To transliterate thingsspellcheck: To check the spelling of a textlanguage: To get the language of a textexample: To get a list of examples of a worddictionary: To get a list of translations categorized into "featured" and "less common" by DeepL and Lingueetext_to_speech: To get an audio file containing the speech version of the given textWhen something goes wrong or nothing got found, an exceptionwillbe raised.(this is in bold because it is one of the difference that comes withv2)>>>fromtranslatepyimportTranslator>>>translator=Translator()>>>translator.translate("Hello","French")TranslationResult(service=Yandex,source=Hello,source_language=auto,destination_language=French,result=Bonjour)>>>translator.language("こんにちは")LanguageResult(service=Yandex,source=こんにちは,result=Language(jpn))TranslatorsYou can use each translators separately by using them the same way as you would withtranslatepy.Translator(ortranslatepy.Translate)>>>fromtranslatepy.translators.googleimportGoogleTranslate>>>gtranslate=GoogleTranslate()>>>gtranslate.translate("Hello World","Japanese")TranslationResult(service=Google,source=HelloWorld,source_language=eng,destination_language=jpn,result=こんにちは世界)And some translators have their own parameters:>>>gtranslate_china=GoogleTranslate(service_url="translate.google.cn")>>>gtranslate_china.translate("Hello World","Japanese")TranslationResult(service=Google,source=HelloWorld,source_language=eng,destination_language=jpn,result=こんにちは世界)# it can even be used by translatepy.Translator>>>fromtranslatepyimportTranslator>>>t=Translator([gtranslate_china])>>>t.translate("Hello World","Japanese")TranslationResult(service=Google,source=HelloWorld,source_language=eng,destination_language=jpn,result=こんにちは世界)The Language ClassThe language class contains lots of information about a language.You need to pass the language name or code to the class initialization:>>>fromtranslatepyimportLanguage>>>Language("French")# Returns a Language class with the "fra" language>>>Language("en")# Returns a Language class with the "eng" language>>>Language("eng")# Returns a Language class with the "eng" language>>>Language("日本語")# Returns a Language class with the "jpn" languageThe Language Class contains both the ISO 639-1 Alpha-2 language code and the ISO 639-2 Alpha-3 language code.>>>Language("English").alpha2# ISO 639-1 (alpha 2), nullable'en'>>>Language("English").alpha3# ISO 639-3 (alpha 3)'eng'>>>Language("English").alpha3b# ISO 639-2B, nullable'eng'>>>Language("English").alpha3t# ISO 639-2T, nullable'eng'Each available language has its own ID, coming from the Alpha-3 Language Code most of the times (but which is also unique for languages such as the "Automatic" Language and the "Emoji" one)>>>Language("French").id'fra'>>>Language("Emoji").id'emj'>>>Language("Automatic").id'auto'It also contains the language name for a lot of languages:>>>Language("Français").in_foreign_languages.get("ja",None)# an alpha-2 code needs to be passed in, also make sure to have a fallback such as None here because not all of the languages had been translated.'フランス語'All of the languages which have analpha2code are assured to have at least their translation in all of the following languages:to=['af','am','ar','az','be','bg','bn','bs','ca','ceb','co','cs','cy','da','de','el','eo','es','et','eu','fa','fi','fr','fy','ga','gd','gl','gu','ha','haw','hi','hmn','hr','ht','hu','hy','id','ig','is','it','he','ja','jv','ka','kk','km','kn','ko','ku','ky','la','lb','lo','lt','lv','mg','mi','mk','ml','mn','mr','ms','mt','my','ne','nl','no','ny','or','pa','pl','ps','pt','ro','ru','sd','si','sk','sl','sm','sn','so','sq','sr','st','su','sv','sw','ta','te','tg','th','tl','tr','ug','uk','ur','uz','vi','xh','yi','yo','zh','zu']The other ones may or may not have a translation in more or less languages.The Language class also contains the "similarity" attribute which gives back a number between 0 and 100 which shows the similarity of the input language with what it found in the language code database:>>>round(Language("French").similarity,2)100.0>>>Language("Englesh").similarity94.86832980505137NoteOnly the languages which have analpha2language code and are of typeLivingorAncientare vectorized and will be used in the similarity search.Each language also have 'extra' data: their type(nullable)and the scope(nullable).>>>Language("French").extraLanguageExtra(type=LanguageType(Living),scope=LanguageScope(Individual))>>>Language("Latin").extra.typeLanguageType(Ancient)Atranslatepy.exceptions.UnknownLanguageexception is raised if the given language is unknown.This exception contains the most similar language along with its similarity:>>>fromtranslatepyimportLanguage>>>fromtranslatepy.exceptionsimportUnknownLanguage>>>try:...language=Language("中国")...exceptUnknownLanguageaserror:...print("The similarity seemed to be too low for translatepy to accept it as a correct language name")...print("The language found is:",error.guessed_language)...print("Its similarity from the passed input is:",str(error.similarity))If you find that the default threshold given to the language search is too low, you can always change it by passing thethresholdparameter when initializing aLanguage:>>>fromtranslatepyimportLanguage>>>Language("国語")Traceback(mostrecentcalllast):File"<stdin>",line1,in<module>File"/Users/animenosekai/Documents/Coding/Projects/translate/translatepy/language.py",line106,in__init__raiseUnknownLanguage(_search_result,self.similarity,raising_message)translatepy.exceptions.UnknownLanguage:Couldn't recognize the given language (中国)Didyoumean:中国語(Similarity:81.65%)?>>>Language("中国",threshold=80)Language(zho)ResultsAll of the methods should have its own result class (defined intranslatepy/models.py) which all have at least the service, source, result attributes and a "as_json" method to convert everything into a JSON String.ErrorsAll of thetranslatepyerrors are inherited fromtranslatepy.exceptions.TranslatepyExceptionso that you can easily catch atranslatepyerror.>>>fromtranslatepyimportTranslator>>>fromtranslatepy.exceptionsimportTranslatepyException,UnknownLanguage>>>t=Translator()>>>deftranslate(text,dest):...try:...result=t.translate(text,destination_language=dest)exceptUnknownLanguageaserr:print("An error occured while searching for the language you passed in")print("Similarity:",round(err.similarity),"%")returnexceptTranslatepyException:print("An error occured while translating with translatepy")returnexceptException:print("An unknown error occured")return...# do something with the result......PluginsYou can make your ownTranslatorusing thetranslatepy.translators.base.BaseTranslatorclass.Make sure that you inherit from this class when creating your translator and tofollow the instruction fromplugin.mdCachingAll of the operations are cached to provide the best performancesYou can empty the cache by calling the method "clean_cache"DeploymentThis module is currently in development and might contain bugs.Feel free to use it in production if you feel like it is suitable for your production even if you may encounter issues.ContributingPull requests are welcome. For major changes, please open an discussion first to discuss what you would like to change.Please make sure to update the tests as appropriate.Built Withpyuseragents- To generate the "User-Agent" HTTP headerrequests- To make HTTP requestsbeautifulsoup4- To parse HTMLinquirer- To make beautiful CLIsAuthorsAnime no Sekai-Initial work-AnimenosekaiZhymabek Roman-Major Contributor (PR #10, PR #15)-ZhymabekRomanDisclaimerPleasedo notuse this module in a commercial manner. Pay a proper API Key from one of the services to do so.LicenseThis project is licensed under the GNU Affero General Public License v3.0 License - see theLICENSEfile for detailsDatasetThe 'playground' folder contains a lot of our search and results for the language management ontranslatepy(this folder might be very messy because of all of our experiments in it)Thetranslatepy/utils/_language_cache.pyfile contains all of the data for the language searching used bytranslatepyPlease ask us if you want to use them in another project.Most of the language data come fromGoogle Translate,Yandex Translateandiso-639-3AcknowledgmentsThanks to @spamz23 (Diogo Silva) for the development of the code refactoring used in v2 (tests andTranslator) (check:spamz23/translate)Thanks to @ZhymabekRoman (Zhymabek Roman) for working on making Yandex more stable and on the v2!Inspired by py-googletrans (by @ssut) (especially the thread:Issue #268)