├── .banners ├── banner_de.png ├── banner_en.png ├── banner_es.png ├── banner_fr.png ├── banner_it.png └── banner_ru.png ├── .gitignore ├── README.md ├── README_de.md ├── README_es.md ├── README_fr.md ├── README_it.md ├── README_ru.md └── dist ├── __init__.py ├── adapters.py ├── client.py ├── compat.py ├── constants.py ├── gtoken.py ├── html_connector.py ├── html_translator.py ├── models.py ├── urls.py └── utils.py /.banners/banner_de.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/markolofsen/py_translator/d7e0e28508d508484cf9590ea8eb47d4888d98bc/.banners/banner_de.png -------------------------------------------------------------------------------- /.banners/banner_en.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/markolofsen/py_translator/d7e0e28508d508484cf9590ea8eb47d4888d98bc/.banners/banner_en.png -------------------------------------------------------------------------------- /.banners/banner_es.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/markolofsen/py_translator/d7e0e28508d508484cf9590ea8eb47d4888d98bc/.banners/banner_es.png -------------------------------------------------------------------------------- /.banners/banner_fr.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/markolofsen/py_translator/d7e0e28508d508484cf9590ea8eb47d4888d98bc/.banners/banner_fr.png -------------------------------------------------------------------------------- /.banners/banner_it.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/markolofsen/py_translator/d7e0e28508d508484cf9590ea8eb47d4888d98bc/.banners/banner_it.png -------------------------------------------------------------------------------- /.banners/banner_ru.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/markolofsen/py_translator/d7e0e28508d508484cf9590ea8eb47d4888d98bc/.banners/banner_ru.png -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | # Created by https://www.gitignore.io/api/macos,node 3 | # Edit at https://www.gitignore.io/?templates=macos,node 4 | 5 | ### macOS ### 6 | # General 7 | .DS_Store 8 | .AppleDouble 9 | .LSOverride 10 | 11 | # Icon must end with two \r 12 | Icon 13 | 14 | # Thumbnails 15 | ._* 16 | 17 | # Files that might appear in the root of a volume 18 | .DocumentRevisions-V100 19 | .fseventsd 20 | .Spotlight-V100 21 | .TemporaryItems 22 | .Trashes 23 | .VolumeIcon.icns 24 | .com.apple.timemachine.donotpresent 25 | 26 | # Directories potentially created on remote AFP share 27 | .AppleDB 28 | .AppleDesktop 29 | Network Trash Folder 30 | Temporary Items 31 | .apdisk 32 | 33 | ### Node ### 34 | # Logs 35 | logs 36 | *.log 37 | npm-debug.log* 38 | yarn-debug.log* 39 | yarn-error.log* 40 | 41 | # Runtime data 42 | pids 43 | *.pid 44 | *.seed 45 | *.pid.lock 46 | 47 | # Directory for instrumented libs generated by jscoverage/JSCover 48 | lib-cov 49 | 50 | # Coverage directory used by tools like istanbul 51 | coverage 52 | 53 | # nyc test coverage 54 | .nyc_output 55 | 56 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 57 | .grunt 58 | 59 | # Bower dependency directory (https://bower.io/) 60 | bower_components 61 | 62 | # node-waf configuration 63 | .lock-wscript 64 | 65 | # Compiled binary addons (https://nodejs.org/api/addons.html) 66 | build/Release 67 | 68 | # Dependency directories 69 | node_modules/ 70 | jspm_packages/ 71 | 72 | # TypeScript v1 declaration files 73 | typings/ 74 | 75 | # Optional npm cache directory 76 | .npm 77 | 78 | # Optional eslint cache 79 | .eslintcache 80 | 81 | # Optional REPL history 82 | .node_repl_history 83 | 84 | # Output of 'npm pack' 85 | *.tgz 86 | 87 | # Yarn Integrity file 88 | .yarn-integrity 89 | 90 | # dotenv environment variables file 91 | .env 92 | .env.test 93 | 94 | # parcel-bundler cache (https://parceljs.org/) 95 | .cache 96 | 97 | # next.js build output 98 | .next 99 | 100 | # nuxt.js build output 101 | .nuxt 102 | 103 | # vuepress build output 104 | .vuepress/dist 105 | 106 | # Serverless directories 107 | .serverless/ 108 | 109 | # FuseBox cache 110 | .fusebox/ 111 | 112 | # DynamoDB Local files 113 | .dynamodb/ 114 | 115 | # End of https://www.gitignore.io/api/macos,node 116 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

🛠️ This repository was created using the GitUpload.

2 |

3 |

Languages:
Deutsch | English | Spanish | French | Italian | Russian

4 | 5 | --- 6 | 7 | Version = 2.1.9
8 | Library name = py_translator
9 | Title = Free Google Translate API
10 | Keywords = Google API Cloud Translate, google api translate free
11 | 12 | ### Info 13 | The end goal is a simple application for translating text in the terminal. Text can be generated interactively or programmatically in the shell environment. Through command line arguments, file descriptors or pipes generating translated output that can be piped to a file or displayed on the terminal. 14 | 15 | Also, you can check our additional library with Google Cloud API 16 | 17 | https://pypi.org/project/google-api-translate/ 18 | 19 | 20 | ### Features 21 | * Made for Python 3 but still works on Python 2 22 | * Fast and easy to install, easy to use 23 | * Supports translation from any language 24 | * Highly composable interface, the power of Unix pipes and filters. 25 | * Simple API and documentation 26 | 27 | ### Hot to install 28 | 29 | ```sh 30 | pip3 install py_translator==2.1.9 31 | ``` 32 | 33 | 34 | ### How to use 35 | ```python 36 | from py_translator import Translator 37 | s = Translator().translate(text='Hello my friend', dest='es').text 38 | print(s) 39 | ``` 40 | 41 | ### With proxy 42 | ```python 43 | from py_translator import Translator 44 | proxy = { 45 | 'http': 'http://username:password@1.1.1.1:1234', 46 | 'https': 'http://username:password@1.1.1.1:1234', 47 | } 48 | s = Translator(proxies=proxy).translate(text='Hello my friend', dest='es').text 49 | print(s) 50 | ``` 51 | 52 | ### Shell 53 | ```shell 54 | translate [--flags] [source] dest 55 | ``` 56 | 57 | 58 | # html translation 59 | 60 | ### Python 61 | ```python 62 | from py_translator import TEXTLIB 63 | s = TEXTLIB().translator(is_html=False, text='Hello my friend', lang_to='cn', proxy=False) 64 | print(s) 65 | ``` 66 | 67 | ### With proxy 68 | ```python 69 | from py_translator import TEXTLIB 70 | proxy = [ 71 | 'http://username:password@1.1.1.1:1234', 72 | 'http://username:password@1.1.1.1:1234', 73 | ] 74 | 75 | s = TEXTLIB().translator(is_html=False, text='Hello my friend', lang_to='cn', proxy=proxy) 76 | print(s) 77 | ``` 78 | 79 | ### With multithreading 80 | ```python 81 | from py_translator import TEXTLIB 82 | 83 | #with massTranslator() 84 | s = TEXTLIB().massTranslator(is_html=False, text='Hello my friend', lang_to='cn', proxy=False) 85 | print(s) 86 | ``` 87 | 88 | -------- 89 | # Examples 90 | Hello World from English to Traditional Chinese 91 | ```sh 92 | $ translate en zh-TW <<< 'Hello World!' 93 | 你好世界! 94 | Just as easily specify a source language by providing it as first argument 95 | ``` 96 | 97 | ```sh 98 | #Translate Hello from French to English 99 | $ translate fr en <<< 'Bonjour, comment allez-vous!' 100 | Hello, how are you? 101 | ``` 102 | 103 | ### Smart Language Detection 104 | Omitting the source language will try to detect it based on the text content 105 | ```sh 106 | $ translate fr <<< 'I think therefore I am' 107 | Je pense donc je suis 108 | ``` 109 | 110 | 111 | ### Romanified Transliteration 112 | ```sh 113 | $ translate --translit en ko <<< 'Want to fight!' 114 | ssaugo sip-eo! 115 | 116 | $ translate --translit en zh-TW <<< 'Kidding, we should be friends' 117 | Kāiwánxiào, wǒmen yīnggāi shì péngyǒu 118 | ``` 119 | 120 | 121 | ### Redirect from File 122 | ```sh 123 | $ translate zh-TW < 'alice.txt' 124 | 125 | 阿麗思道:「你不是說你要告訴你的歷史嗎?告訴我你為甚麼恨—那個—那些—C和D,」 126 | 她末了兩個字母輕輕兒地說的,怕回來又得罪了牠。 127 | 128 | 那老鼠對著阿麗思嘆了一口氣道,「唉﹗我的身世說來可真是又長又苦又委屈呀—」 129 | 130 | 阿麗思聽了,瞧著那老鼠的尾巴說,「你這尾是曲啊﹗可是為甚麼又叫它苦呢﹗」 131 | 她就一頭聽著那老鼠說話,一頭在在心上納悶,所以她聽的那老鼠講的「尾曲」 132 | 的歷史是差不多像這個樣了的 133 | .... 134 | ``` 135 | 136 | ### Chaining together Pipes 137 | ```sh 138 | #Multiple Chaining 139 | $ echo 'What is love?' | translate en zh-TW | translate zh-TW ko | translate ko fr | translate fr en 140 | What is love? 141 | ``` 142 | 143 | ### Be Creative! 144 | ```sh 145 | #Grocery List 146 | $ cat << BUY | translate ko 147 | Celery 148 | Milk 149 | Eggs 150 | Bread 151 | Cereal 152 | BUY 153 | 154 | 셀러리 155 | 우유 156 | 달걀 157 | 빵 158 | 시리얼 159 | ``` 160 | 161 | # Support 162 | Python 3 163 | 164 | # Documentation 165 | Find the latest documentation http://pythonhosted.org/py-translate/ 166 | 167 | 168 | 169 | --- 170 | 171 |

🛠️ This repository was created using the GitUpload.

-------------------------------------------------------------------------------- /README_de.md: -------------------------------------------------------------------------------- 1 |

🛠️ Dieses Repository wurde mit GitUpload erstellt.

2 |

3 |

Languages:
Deutsch | English | Spanish | French | Italian | Russian

4 | 5 | --- 6 | 7 | Version = 2.1.9
8 | Bibliotheksname = py_translator
9 | Titel = Free Google Translate API
10 | Schlüsselwörter = Google API Cloud Translate, google api translate free
11 | 12 | ### Info 13 | Das Endziel ist eine einfache Anwendung zum Übersetzen von Text im Terminal. Text kann interaktiv oder programmgesteuert in der Shell-Umgebung generiert werden. Über Befehlszeilenargumente, Dateideskriptoren oder Pipes werden übersetzte Ausgaben generiert, die in eine Datei geleitet oder auf dem Terminal angezeigt werden können. 14 | 15 | Sie können auch unsere zusätzliche Bibliothek mit der Google Cloud-API überprüfen 16 | 17 | https://pypi.org/project/google-api-translate/ 18 | 19 | 20 | ### Eigenschaften 21 | * Für Python 3 gemacht, funktioniert aber immer noch mit Python 2 22 | * Schnell und einfach zu installieren, einfach zu bedienen 23 | * Unterstützt Übersetzungen aus jeder Sprache 24 | * Hochkomposierbare Schnittstelle, die Leistung von Unix-Pipes und -Filtern. 25 | * Einfache API und Dokumentation 26 | 27 | ### Heiß zu installieren 28 | 29 | ```sh 30 | pip3 install py_translator==2.1.9 31 | ``` 32 | 33 | 34 | ### Wie benutzt man 35 | ```python 36 | from py_translator import Translator 37 | s = Translator().translate(text='Hello my friend', dest='es').text 38 | print(s) 39 | ``` 40 | 41 | ### Mit Proxy 42 | ```python 43 | from py_translator import Translator 44 | proxy = { 45 | 'http': 'http://username:password@1.1.1.1:1234', 46 | 'https': 'http://username:password@1.1.1.1:1234', 47 | } 48 | s = Translator(proxies=proxy).translate(text='Hello my friend', dest='es').text 49 | print(s) 50 | ``` 51 | 52 | ### Shell 53 | ```shell 54 | translate [--flags] [source] dest 55 | ``` 56 | 57 | 58 | # HTML-Übersetzung 59 | 60 | ### Python 61 | ```python 62 | from py_translator import TEXTLIB 63 | s = TEXTLIB().translator(is_html=False, text='Hello my friend', lang_to='cn', proxy=False) 64 | print(s) 65 | ``` 66 | 67 | ### Mit Proxy 68 | ```python 69 | from py_translator import TEXTLIB 70 | proxy = [ 71 | 'http://username:password@1.1.1.1:1234', 72 | 'http://username:password@1.1.1.1:1234', 73 | ] 74 | 75 | s = TEXTLIB().translator(is_html=False, text='Hello my friend', lang_to='cn', proxy=proxy) 76 | print(s) 77 | ``` 78 | 79 | ### Mit Multithreading 80 | ```python 81 | from py_translator import TEXTLIB 82 | 83 | #with massTranslator() 84 | s = TEXTLIB().massTranslator(is_html=False, text='Hello my friend', lang_to='cn', proxy=False) 85 | print(s) 86 | ``` 87 | 88 | -------- 89 | # Beispiele 90 | Hallo Welt vom Englischen zum Traditionellen Chinesisch 91 | (fünfzehn)] 92 | 93 | ```sh 94 | #Translate Hello from French to English 95 | $ translate fr en <<< 'Bonjour, comment allez-vous!' 96 | Hello, how are you? 97 | ``` 98 | 99 | ### Intelligente Spracherkennung 100 | Wenn Sie die Ausgangssprache nicht angeben, wird versucht, sie anhand des Textinhalts zu ermitteln 101 | ```sh 102 | $ translate fr <<< 'I think therefore I am' 103 | Je pense donc je suis 104 | ``` 105 | 106 | 107 | ### Romanifizierte Transliteration 108 | ```sh 109 | $ translate --translit en ko <<< 'Want to fight!' 110 | ssaugo sip-eo! 111 | 112 | $ translate --translit en zh-TW <<< 'Kidding, we should be friends' 113 | Kāiwánxiào, wǒmen yīnggāi shì péngyǒu 114 | ``` 115 | 116 | 117 | ### Umleitung von Datei 118 | ```sh 119 | $ translate zh-TW < 'alice.txt' 120 | 121 | 阿麗思道:「你不是說你要告訴你的歷史嗎?告訴我你為甚麼恨—那個—那些—C和D,」 122 | 她末了兩個字母輕輕兒地說的,怕回來又得罪了牠。 123 | 124 | 那老鼠對著阿麗思嘆了一口氣道,「唉﹗我的身世說來可真是又長又苦又委屈呀—」 125 | 126 | 阿麗思聽了,瞧著那老鼠的尾巴說,「你這尾是曲啊﹗可是為甚麼又叫它苦呢﹗」 127 | 她就一頭聽著那老鼠說話,一頭在在心上納悶,所以她聽的那老鼠講的「尾曲」 128 | 的歷史是差不多像這個樣了的 129 | .... 130 | ``` 131 | 132 | ### Verketten von Rohren 133 | ```sh 134 | #Multiple Chaining 135 | $ echo 'What is love?' | translate en zh-TW | translate zh-TW ko | translate ko fr | translate fr en 136 | What is love? 137 | ``` 138 | 139 | ### Seien Sie kreativ! 140 | ```sh 141 | #Grocery List 142 | $ cat << BUY | translate ko 143 | Celery 144 | Milk 145 | Eggs 146 | Bread 147 | Cereal 148 | BUY 149 | 150 | 셀러리 151 | 우유 152 | 달걀 153 | 빵 154 | 시리얼 155 | ``` 156 | 157 | # Unterstützung 158 | Python 3 159 | 160 | # Dokumentation 161 | Die neueste Dokumentation finden Sie unter http://pythonhosted.org/py-translate/. 162 | 163 | 164 | --- 165 | 166 |

🛠️ Dieses Repository wurde mit GitUpload erstellt.

-------------------------------------------------------------------------------- /README_es.md: -------------------------------------------------------------------------------- 1 |

🛠️ Este repositorio fue creado usando el GitUpload.

2 |

3 |

Languages:
Deutsch | English | Spanish | French | Italian | Russian

4 | 5 | --- 6 | 7 | Versión = 2.1.9
8 | Nombre de la biblioteca = py_translator
9 | Título = Free Google Translate API
10 | Palabras clave = Google API Cloud Translate, google api translate free
11 | 12 | ### Info 13 | El objetivo final es una aplicación sencilla para traducir texto en el terminal. El texto se puede generar de forma interactiva o programática en el entorno de shell. A través de la línea de comandos, los descriptores de archivos o los conductos generan resultados traducidos que se pueden canalizar a un archivo o mostrar en el terminal. 14 | 15 | Además, puede consultar nuestra biblioteca adicional con Google Cloud API 16 | 17 | https://pypi.org/project/google-api-translate/ 18 | 19 | 20 | ### Caracteristicas 21 | * Hecho para Python 3 pero aún funciona en Python 2 22 | * Rápido y fácil de instalar, fácil de usar 23 | * Soporta la traducción de cualquier idioma. 24 | * Interfaz altamente componible, el poder de las tuberías y filtros Unix. 25 | * API simple y documentación. 26 | 27 | ### Caliente para instalar 28 | 29 | ```sh 30 | pip3 install py_translator==2.1.9 31 | ``` 32 | 33 | 34 | ### Cómo utilizar 35 | ```python 36 | from py_translator import Translator 37 | s = Translator().translate(text='Hello my friend', dest='es').text 38 | print(s) 39 | ``` 40 | 41 | ### Con proxy 42 | ```python 43 | from py_translator import Translator 44 | proxy = { 45 | 'http': 'http://username:password@1.1.1.1:1234', 46 | 'https': 'http://username:password@1.1.1.1:1234', 47 | } 48 | s = Translator(proxies=proxy).translate(text='Hello my friend', dest='es').text 49 | print(s) 50 | ``` 51 | 52 | ### Cáscara 53 | ```shell 54 | translate [--flags] [source] dest 55 | ``` 56 | 57 | 58 | # traducción html 59 | 60 | ### Python 61 | ```python 62 | from py_translator import TEXTLIB 63 | s = TEXTLIB().translator(is_html=False, text='Hello my friend', lang_to='cn', proxy=False) 64 | print(s) 65 | ``` 66 | 67 | ### Con proxy 68 | ```python 69 | from py_translator import TEXTLIB 70 | proxy = [ 71 | 'http://username:password@1.1.1.1:1234', 72 | 'http://username:password@1.1.1.1:1234', 73 | ] 74 | 75 | s = TEXTLIB().translator(is_html=False, text='Hello my friend', lang_to='cn', proxy=proxy) 76 | print(s) 77 | ``` 78 | 79 | ### con multiproceso 80 | ```python 81 | from py_translator import TEXTLIB 82 | 83 | #with massTranslator() 84 | s = TEXTLIB().massTranslator(is_html=False, text='Hello my friend', lang_to='cn', proxy=False) 85 | print(s) 86 | ``` 87 | 88 | -------- 89 | # Ejemplos 90 | Hola mundo de inglés a chino tradicional 91 | ```sh 92 | $ translate en zh-TW <<< 'Hello World!' 93 | 你好世界! 94 | Just as easily specify a source language by providing it as first argument 95 | ``` 96 | 97 | (dieciséis)] 98 | 99 | ### Detección inteligente de lenguaje 100 | La omisión del idioma de origen intentará detectarlo en función del contenido del texto 101 | ```sh 102 | $ translate fr <<< 'I think therefore I am' 103 | Je pense donc je suis 104 | ``` 105 | 106 | 107 | ### Transliteración romanificada 108 | ```sh 109 | $ translate --translit en ko <<< 'Want to fight!' 110 | ssaugo sip-eo! 111 | 112 | $ translate --translit en zh-TW <<< 'Kidding, we should be friends' 113 | Kāiwánxiào, wǒmen yīnggāi shì péngyǒu 114 | ``` 115 | 116 | 117 | ### Redirigir desde archivo 118 | ```sh 119 | $ translate zh-TW < 'alice.txt' 120 | 121 | 阿麗思道:「你不是說你要告訴你的歷史嗎?告訴我你為甚麼恨—那個—那些—C和D,」 122 | 她末了兩個字母輕輕兒地說的,怕回來又得罪了牠。 123 | 124 | 那老鼠對著阿麗思嘆了一口氣道,「唉﹗我的身世說來可真是又長又苦又委屈呀—」 125 | 126 | 阿麗思聽了,瞧著那老鼠的尾巴說,「你這尾是曲啊﹗可是為甚麼又叫它苦呢﹗」 127 | 她就一頭聽著那老鼠說話,一頭在在心上納悶,所以她聽的那老鼠講的「尾曲」 128 | 的歷史是差不多像這個樣了的 129 | .... 130 | ``` 131 | 132 | ### Encadenando tuberías 133 | ```sh 134 | #Multiple Chaining 135 | $ echo 'What is love?' | translate en zh-TW | translate zh-TW ko | translate ko fr | translate fr en 136 | What is love? 137 | ``` 138 | 139 | ### ¡Ser creativo! 140 | ```sh 141 | #Grocery List 142 | $ cat << BUY | translate ko 143 | Celery 144 | Milk 145 | Eggs 146 | Bread 147 | Cereal 148 | BUY 149 | 150 | 셀러리 151 | 우유 152 | 달걀 153 | 빵 154 | 시리얼 155 | ``` 156 | 157 | # Soporte 158 | Python 3 159 | 160 | # Documentación 161 | Encuentre la documentación más reciente en http://pythonhosted.org/py-translate/ 162 | 163 | 164 | --- 165 | 166 |

🛠️ Este repositorio fue creado usando el GitUpload.

-------------------------------------------------------------------------------- /README_fr.md: -------------------------------------------------------------------------------- 1 |

🛠️ Ce référentiel a été créé en utilisant le GitUpload.

2 |

3 |

Languages:
Deutsch | English | Spanish | French | Italian | Russian

4 | 5 | --- 6 | 7 | Version = 2.1.9
8 | Nom de la bibliothèque = py_translator
9 | Titre = Free Google Translate API
10 | Mots-clés = Google API Cloud Translate, google api translate free
11 | 12 | ### Info 13 | L'objectif final est une application simple pour traduire du texte dans le terminal. Le texte peut être généré de manière interactive ou par programme dans l'environnement shell. Par le biais d’arguments de ligne de commande, de descripteurs de fichier ou de canaux générant une sortie traduite pouvant être redirigée vers un fichier ou affichée sur le terminal. 14 | 15 | Vous pouvez également consulter notre bibliothèque supplémentaire avec Google Cloud API. 16 | 17 | https://pypi.org/project/google-api-translate/ 18 | 19 | 20 | ### Caractéristiques 21 | * Conçu pour Python 3 mais fonctionne toujours sur Python 2 22 | * Rapide et facile à installer, facile à utiliser 23 | * Prend en charge la traduction de n'importe quelle langue 24 | * Interface hautement composable, la puissance des pipes et filtres Unix. 25 | * API simple et documentation 26 | 27 | ### Chaud à installer 28 | 29 | ```sh 30 | pip3 install py_translator==2.1.9 31 | ``` 32 | 33 | 34 | ### Comment utiliser 35 | ```python 36 | from py_translator import Translator 37 | s = Translator().translate(text='Hello my friend', dest='es').text 38 | print(s) 39 | ``` 40 | 41 | ### Avec proxy 42 | (dix)] 43 | 44 | ### Coquille 45 | ```shell 46 | translate [--flags] [source] dest 47 | ``` 48 | 49 | 50 | traduction html 51 | 52 | ### Python 53 | ```python 54 | from py_translator import TEXTLIB 55 | s = TEXTLIB().translator(is_html=False, text='Hello my friend', lang_to='cn', proxy=False) 56 | print(s) 57 | ``` 58 | 59 | ### Avec proxy 60 | ```python 61 | from py_translator import TEXTLIB 62 | proxy = [ 63 | 'http://username:password@1.1.1.1:1234', 64 | 'http://username:password@1.1.1.1:1234', 65 | ] 66 | 67 | s = TEXTLIB().translator(is_html=False, text='Hello my friend', lang_to='cn', proxy=proxy) 68 | print(s) 69 | ``` 70 | 71 | ### Avec multithreading 72 | ```python 73 | from py_translator import TEXTLIB 74 | 75 | #with massTranslator() 76 | s = TEXTLIB().massTranslator(is_html=False, text='Hello my friend', lang_to='cn', proxy=False) 77 | print(s) 78 | ``` 79 | 80 | -------- 81 | # Exemples 82 | Bonjour tout le monde de l'anglais au chinois traditionnel 83 | ```sh 84 | $ translate en zh-TW <<< 'Hello World!' 85 | 你好世界! 86 | Just as easily specify a source language by providing it as first argument 87 | ``` 88 | 89 | ```sh 90 | #Translate Hello from French to English 91 | $ translate fr en <<< 'Bonjour, comment allez-vous!' 92 | Hello, how are you? 93 | ``` 94 | 95 | ### Détection intelligente de la langue 96 | L'omission de la langue source tentera de la détecter en fonction du contenu du texte 97 | ```sh 98 | $ translate fr <<< 'I think therefore I am' 99 | Je pense donc je suis 100 | ``` 101 | 102 | 103 | ### Translittération romanifiée 104 | ```sh 105 | $ translate --translit en ko <<< 'Want to fight!' 106 | ssaugo sip-eo! 107 | 108 | $ translate --translit en zh-TW <<< 'Kidding, we should be friends' 109 | Kāiwánxiào, wǒmen yīnggāi shì péngyǒu 110 | ``` 111 | 112 | 113 | ### Redirect from File 114 | ```sh 115 | $ translate zh-TW < 'alice.txt' 116 | 117 | 阿麗思道:「你不是說你要告訴你的歷史嗎?告訴我你為甚麼恨—那個—那些—C和D,」 118 | 她末了兩個字母輕輕兒地說的,怕回來又得罪了牠。 119 | 120 | 那老鼠對著阿麗思嘆了一口氣道,「唉﹗我的身世說來可真是又長又苦又委屈呀—」 121 | 122 | 阿麗思聽了,瞧著那老鼠的尾巴說,「你這尾是曲啊﹗可是為甚麼又叫它苦呢﹗」 123 | 她就一頭聽著那老鼠說話,一頭在在心上納悶,所以她聽的那老鼠講的「尾曲」 124 | 的歷史是差不多像這個樣了的 125 | .... 126 | ``` 127 | 128 | ### Chaînage de tuyaux 129 | ```sh 130 | #Multiple Chaining 131 | $ echo 'What is love?' | translate en zh-TW | translate zh-TW ko | translate ko fr | translate fr en 132 | What is love? 133 | ``` 134 | 135 | ### Sois créatif! 136 | ```sh 137 | #Grocery List 138 | $ cat << BUY | translate ko 139 | Celery 140 | Milk 141 | Eggs 142 | Bread 143 | Cereal 144 | BUY 145 | 146 | 셀러리 147 | 우유 148 | 달걀 149 | 빵 150 | 시리얼 151 | ``` 152 | 153 | # Soutien 154 | Python 3 155 | 156 | # Documentation 157 | Retrouvez la dernière documentation http://pythonhosted.org/py-translate/ 158 | 159 | 160 | --- 161 | 162 |

🛠️ Ce référentiel a été créé en utilisant le GitUpload.

-------------------------------------------------------------------------------- /README_it.md: -------------------------------------------------------------------------------- 1 |

🛠️ Questo repository è stato creato usando GitUpload.

2 |

3 |

Languages:
Deutsch | English | Spanish | French | Italian | Russian

4 | 5 | --- 6 | 7 | Versione = 2.1.9
8 | Nome libreria = py_translator
9 | Titolo = Free Google Translate API
10 | Parole chiave = Google API Cloud Translate, google api translate free
11 | 12 | ### Informazioni 13 | L'obiettivo finale è una semplice applicazione per la traduzione di testo nel terminale. Il testo può essere generato in modo interattivo o programmatico nell'ambiente della shell. Tramite gli argomenti della riga di comando, i descrittori di file o le pipe che generano l'output tradotto che può essere reindirizzato a un file o visualizzato sul terminale. 14 | 15 | Inoltre, puoi consultare la nostra libreria aggiuntiva con Google Cloud API 16 | 17 | https://pypi.org/project/google-api-translate/ 18 | 19 | 20 | ### Caratteristiche 21 | * Realizzato per Python 3, ma funziona ancora su Python 2 22 | * Veloce e facile da installare, facile da usare 23 | * Supporta la traduzione da qualsiasi lingua 24 | * Interfaccia altamente componibile, la potenza dei tubi e dei filtri Unix. 25 | * API e documentazione semplici 26 | 27 | ### Caldo da installare 28 | 29 | ```sh 30 | pip3 install py_translator==2.1.9 31 | ``` 32 | 33 | 34 | ### Come usare 35 | ```python 36 | from py_translator import Translator 37 | s = Translator().translate(text='Hello my friend', dest='es').text 38 | print(s) 39 | ``` 40 | 41 | ### Con proxy 42 | ```python 43 | from py_translator import Translator 44 | proxy = { 45 | 'http': 'http://username:password@1.1.1.1:1234', 46 | 'https': 'http://username:password@1.1.1.1:1234', 47 | } 48 | s = Translator(proxies=proxy).translate(text='Hello my friend', dest='es').text 49 | print(s) 50 | ``` 51 | 52 | ### Conchiglia 53 | ```shell 54 | translate [--flags] [source] dest 55 | ``` 56 | 57 | 58 | # traduzione HTML 59 | 60 | ### Python 61 | ```python 62 | from py_translator import TEXTLIB 63 | s = TEXTLIB().translator(is_html=False, text='Hello my friend', lang_to='cn', proxy=False) 64 | print(s) 65 | ``` 66 | 67 | ### Con proxy 68 | ```python 69 | from py_translator import TEXTLIB 70 | proxy = [ 71 | 'http://username:password@1.1.1.1:1234', 72 | 'http://username:password@1.1.1.1:1234', 73 | ] 74 | 75 | s = TEXTLIB().translator(is_html=False, text='Hello my friend', lang_to='cn', proxy=proxy) 76 | print(s) 77 | ``` 78 | 79 | ### Con il multithreading 80 | ```python 81 | from py_translator import TEXTLIB 82 | 83 | #with massTranslator() 84 | s = TEXTLIB().massTranslator(is_html=False, text='Hello my friend', lang_to='cn', proxy=False) 85 | print(s) 86 | ``` 87 | 88 | -------- 89 | # Esempi 90 | Ciao mondo dall'inglese al cinese tradizionale 91 | ```sh 92 | $ translate en zh-TW <<< 'Hello World!' 93 | 你好世界! 94 | Just as easily specify a source language by providing it as first argument 95 | ``` 96 | 97 | ```sh 98 | #Translate Hello from French to English 99 | $ translate fr en <<< 'Bonjour, comment allez-vous!' 100 | Hello, how are you? 101 | ``` 102 | 103 | ### Rilevamento intelligente della lingua 104 | L'omissione della lingua di partenza proverà a rilevarla in base al contenuto del testo 105 | ```sh 106 | $ translate fr <<< 'I think therefore I am' 107 | Je pense donc je suis 108 | ``` 109 | 110 | 111 | ### Traslitterazione romanificata 112 | ```sh 113 | $ translate --translit en ko <<< 'Want to fight!' 114 | ssaugo sip-eo! 115 | 116 | $ translate --translit en zh-TW <<< 'Kidding, we should be friends' 117 | Kāiwánxiào, wǒmen yīnggāi shì péngyǒu 118 | ``` 119 | 120 | 121 | ### Reindirizza dal file 122 | ```sh 123 | $ translate zh-TW < 'alice.txt' 124 | 125 | 阿麗思道:「你不是說你要告訴你的歷史嗎?告訴我你為甚麼恨—那個—那些—C和D,」 126 | 她末了兩個字母輕輕兒地說的,怕回來又得罪了牠。 127 | 128 | 那老鼠對著阿麗思嘆了一口氣道,「唉﹗我的身世說來可真是又長又苦又委屈呀—」 129 | 130 | 阿麗思聽了,瞧著那老鼠的尾巴說,「你這尾是曲啊﹗可是為甚麼又叫它苦呢﹗」 131 | 她就一頭聽著那老鼠說話,一頭在在心上納悶,所以她聽的那老鼠講的「尾曲」 132 | 的歷史是差不多像這個樣了的 133 | .... 134 | ``` 135 | 136 | ### Incatenare i tubi 137 | ```sh 138 | #Multiple Chaining 139 | $ echo 'What is love?' | translate en zh-TW | translate zh-TW ko | translate ko fr | translate fr en 140 | What is love? 141 | ``` 142 | 143 | ### Essere creativo! 144 | ```sh 145 | #Grocery List 146 | $ cat << BUY | translate ko 147 | Celery 148 | Milk 149 | Eggs 150 | Bread 151 | Cereal 152 | BUY 153 | 154 | 셀러리 155 | 우유 156 | 달걀 157 | 빵 158 | 시리얼 159 | ``` 160 | 161 | # Supporto 162 | Python 3 163 | 164 | # Documentazione 165 | Trova la documentazione più recente http://pythonhosted.org/py-translate/ 166 | 167 | 168 | --- 169 | 170 |

🛠️ Questo repository è stato creato usando GitUpload.

-------------------------------------------------------------------------------- /README_ru.md: -------------------------------------------------------------------------------- 1 |

🛠️ Этот репозиторий был создан с использованием GitUpload.

2 |

3 |

Languages:
Deutsch | English | Spanish | French | Italian | Russian

4 | 5 | --- 6 | 7 | Версия = 2.1.9
8 | Название библиотеки = py_translator
9 | Название = Free Google Translate API
10 | Ключевые слова = Google API Cloud Translate, google api translate free
11 | 12 | ### Информация 13 | Конечная цель - простое приложение для перевода текста в терминале. Текст может быть сгенерирован интерактивно или программно в среде оболочки. Посредством аргументов командной строки, файловых дескрипторов или каналов, генерирующих переведенный вывод, который может быть передан в файл или отображен на терминале. 14 | 15 | Кроме того, вы можете проверить нашу дополнительную библиотеку с Google Cloud API 16 | 17 | https://pypi.org/project/google-api-translate/ 18 | 19 | 20 | ### Характеристики 21 | * Сделано для Python 3, но все еще работает на Python 2 22 | * Быстрый и простой в установке, простой в использовании 23 | * Поддерживает перевод с любого языка 24 | * Композитный интерфейс, мощь Unix-каналов и фильтров. 25 | * Простой API и документация 26 | 27 | ### Горячая установка 28 | 29 | ```sh 30 | pip3 install py_translator==2.1.9 31 | ``` 32 | 33 | 34 | ### Как пользоваться 35 | ```python 36 | from py_translator import Translator 37 | s = Translator().translate(text='Hello my friend', dest='es').text 38 | print(s) 39 | ``` 40 | 41 | ### с прокси 42 | ```python 43 | from py_translator import Translator 44 | proxy = { 45 | 'http': 'http://username:password@1.1.1.1:1234', 46 | 'https': 'http://username:password@1.1.1.1:1234', 47 | } 48 | s = Translator(proxies=proxy).translate(text='Hello my friend', dest='es').text 49 | print(s) 50 | ``` 51 | 52 | ### Ракушка 53 | ```shell 54 | translate [--flags] [source] dest 55 | ``` 56 | 57 | 58 | # перевод html 59 | 60 | ### Питон 61 | ```python 62 | from py_translator import TEXTLIB 63 | s = TEXTLIB().translator(is_html=False, text='Hello my friend', lang_to='cn', proxy=False) 64 | print(s) 65 | ``` 66 | 67 | ### с прокси 68 | ```python 69 | from py_translator import TEXTLIB 70 | proxy = [ 71 | 'http://username:password@1.1.1.1:1234', 72 | 'http://username:password@1.1.1.1:1234', 73 | ] 74 | 75 | s = TEXTLIB().translator(is_html=False, text='Hello my friend', lang_to='cn', proxy=proxy) 76 | print(s) 77 | ``` 78 | 79 | ### с многопоточностью 80 | ```python 81 | from py_translator import TEXTLIB 82 | 83 | #with massTranslator() 84 | s = TEXTLIB().massTranslator(is_html=False, text='Hello my friend', lang_to='cn', proxy=False) 85 | print(s) 86 | ``` 87 | 88 | -------- 89 | # Примеры 90 | Hello World с английского на традиционный китайский 91 | ```sh 92 | $ translate en zh-TW <<< 'Hello World!' 93 | 你好世界! 94 | Just as easily specify a source language by providing it as first argument 95 | ``` 96 | 97 | ```sh 98 | #Translate Hello from French to English 99 | $ translate fr en <<< 'Bonjour, comment allez-vous!' 100 | Hello, how are you? 101 | ``` 102 | 103 | ### Smart Language Detection 104 | Пропустив исходный язык, постараюсь обнаружить его на основе текстового содержимого. 105 | ```sh 106 | $ translate fr <<< 'I think therefore I am' 107 | Je pense donc je suis 108 | ``` 109 | 110 | 111 | ### Романизированная транслитерация 112 | ```sh 113 | $ translate --translit en ko <<< 'Want to fight!' 114 | ssaugo sip-eo! 115 | 116 | $ translate --translit en zh-TW <<< 'Kidding, we should be friends' 117 | Kāiwánxiào, wǒmen yīnggāi shì péngyǒu 118 | ``` 119 | 120 | 121 | ### Перенаправление из файла 122 | ```sh 123 | $ translate zh-TW < 'alice.txt' 124 | 125 | 阿麗思道:「你不是說你要告訴你的歷史嗎?告訴我你為甚麼恨—那個—那些—C和D,」 126 | 她末了兩個字母輕輕兒地說的,怕回來又得罪了牠。 127 | 128 | 那老鼠對著阿麗思嘆了一口氣道,「唉﹗我的身世說來可真是又長又苦又委屈呀—」 129 | 130 | 阿麗思聽了,瞧著那老鼠的尾巴說,「你這尾是曲啊﹗可是為甚麼又叫它苦呢﹗」 131 | 她就一頭聽著那老鼠說話,一頭在在心上納悶,所以她聽的那老鼠講的「尾曲」 132 | 的歷史是差不多像這個樣了的 133 | .... 134 | ``` 135 | 136 | ### Цепные трубы 137 | ```sh 138 | #Multiple Chaining 139 | $ echo 'What is love?' | translate en zh-TW | translate zh-TW ko | translate ko fr | translate fr en 140 | What is love? 141 | ``` 142 | 143 | ### Будь креативным! 144 | ```sh 145 | #Grocery List 146 | $ cat << BUY | translate ko 147 | Celery 148 | Milk 149 | Eggs 150 | Bread 151 | Cereal 152 | BUY 153 | 154 | 셀러리 155 | 우유 156 | 달걀 157 | 빵 158 | 시리얼 159 | ``` 160 | 161 | # Служба поддержки 162 | Python 3 163 | 164 | # Документация 165 | Найти последнюю документацию http://pythonhosted.org/py-translate/ 166 | 167 | 168 | --- 169 | 170 |

🛠️ Этот репозиторий был создан с использованием GitUpload.

-------------------------------------------------------------------------------- /dist/__init__.py: -------------------------------------------------------------------------------- 1 | """Free Google Translate API for Python. Translates totally free of charge.""" 2 | __all__ = 'Translator', 3 | # __version__ = '2.3.0' 4 | 5 | 6 | from .client import Translator 7 | from .constants import LANGCODES, LANGUAGES 8 | from .html_connector import TEXTLIB 9 | -------------------------------------------------------------------------------- /dist/adapters.py: -------------------------------------------------------------------------------- 1 | from requests.adapters import HTTPAdapter 2 | 3 | 4 | class TimeoutAdapter(HTTPAdapter): 5 | """HTTP adapter that adds timeout to each query.""" 6 | def __init__(self, timeout=None, *args, **kwargs): 7 | """HTTP adapter that adds timeout to each query. 8 | 9 | :param timeout: Timeout that will be added to each query 10 | """ 11 | self.timeout = timeout 12 | super(TimeoutAdapter, self).__init__(*args, **kwargs) 13 | 14 | def send(self, *args, **kwargs): 15 | kwargs['timeout'] = self.timeout 16 | return super(TimeoutAdapter, self).send(*args, **kwargs) 17 | -------------------------------------------------------------------------------- /dist/client.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | A Translation module. 4 | 5 | You can translate text using this module. 6 | """ 7 | import requests 8 | import random 9 | 10 | from . import urls, utils 11 | from .adapters import TimeoutAdapter 12 | from .compat import PY3 13 | from .gtoken import TokenAcquirer 14 | from .constants import DEFAULT_USER_AGENT, LANGCODES, LANGUAGES, SPECIAL_CASES 15 | from .models import Translated, Detected 16 | 17 | 18 | EXCLUDES = ('en', 'ca', 'fr') 19 | 20 | 21 | class Translator(object): 22 | """Google Translate ajax API implementation class 23 | 24 | You have to create an instance of Translator to use this API 25 | 26 | :param service_urls: google translate url list. URLs will be used randomly. 27 | For example ``['translate.google.com', 'translate.google.co.kr']`` 28 | :type service_urls: a sequence of strings 29 | 30 | :param user_agent: the User-Agent header to send when making requests. 31 | :type user_agent: :class:`str` 32 | 33 | :param proxies: proxies configuration. 34 | Dictionary mapping protocol or protocol and host to the URL of the proxy 35 | For example ``{'http': 'foo.bar:3128', 'http://host.name': 'foo.bar:4012'}`` 36 | :type proxies: dictionary 37 | 38 | :param timeout: Definition of timeout for Requests library. 39 | Will be used by every request. 40 | :type timeout: number or a double of numbers 41 | """ 42 | 43 | def __init__(self, service_urls=None, user_agent=DEFAULT_USER_AGENT, 44 | proxies=None, timeout=None): 45 | 46 | self.session = requests.Session() 47 | if proxies is not None: 48 | self.session.proxies = proxies 49 | self.session.headers.update({ 50 | 'User-Agent': user_agent, 51 | }) 52 | if timeout is not None: 53 | self.session.mount('https://', TimeoutAdapter(timeout)) 54 | self.session.mount('http://', TimeoutAdapter(timeout)) 55 | 56 | self.service_urls = service_urls or ['translate.google.com'] 57 | self.token_acquirer = TokenAcquirer(session=self.session, host=self.service_urls[0]) 58 | 59 | # Use HTTP2 Adapter if hyper is installed 60 | try: # pragma: nocover 61 | from hyper.contrib import HTTP20Adapter 62 | self.session.mount(urls.BASE, HTTP20Adapter()) 63 | except ImportError: # pragma: nocover 64 | pass 65 | 66 | def _pick_service_url(self): 67 | if len(self.service_urls) == 1: 68 | return self.service_urls[0] 69 | return random.choice(self.service_urls) 70 | 71 | def _translate(self, text, dest, src): 72 | if not PY3 and isinstance(text, str): # pragma: nocover 73 | text = text.decode('utf-8') 74 | 75 | token = self.token_acquirer.do(text) 76 | params = utils.build_params(query=text, src=src, dest=dest, 77 | token=token) 78 | url = urls.TRANSLATE.format(host=self._pick_service_url()) 79 | r = self.session.get(url, params=params) 80 | 81 | data = utils.format_json(r.text) 82 | return data 83 | 84 | def _parse_extra_data(self, data): 85 | response_parts_name_mapping = { 86 | 0: 'translation', 87 | 1: 'all-translations', 88 | 2: 'original-language', 89 | 5: 'possible-translations', 90 | 6: 'confidence', 91 | 7: 'possible-mistakes', 92 | 8: 'language', 93 | 11: 'synonyms', 94 | 12: 'definitions', 95 | 13: 'examples', 96 | 14: 'see-also', 97 | } 98 | 99 | extra = {} 100 | 101 | for index, category in response_parts_name_mapping.items(): 102 | extra[category] = data[index] if (index < len(data) and data[index]) else None 103 | 104 | return extra 105 | 106 | def translate(self, text, dest='en', src='auto'): 107 | """Translate text from source language to destination language 108 | 109 | :param text: The source text(s) to be translated. Batch translation is supported via sequence input. 110 | :type text: UTF-8 :class:`str`; :class:`unicode`; string sequence (list, tuple, iterator, generator) 111 | 112 | :param dest: The language to translate the source text into. 113 | The value should be one of the language codes listed in :const:`googletrans.LANGUAGES` 114 | or one of the language names listed in :const:`googletrans.LANGCODES`. 115 | :param dest: :class:`str`; :class:`unicode` 116 | 117 | :param src: The language of the source text. 118 | The value should be one of the language codes listed in :const:`googletrans.LANGUAGES` 119 | or one of the language names listed in :const:`googletrans.LANGCODES`. 120 | If a language is not specified, 121 | the system will attempt to identify the source language automatically. 122 | :param src: :class:`str`; :class:`unicode` 123 | 124 | :rtype: Translated 125 | :rtype: :class:`list` (when a list is passed) 126 | 127 | Basic usage: 128 | >>> from googletrans import Translator 129 | >>> translator = Translator() 130 | >>> translator.translate('안녕하세요.') 131 | 132 | >>> translator.translate('안녕하세요.', dest='ja') 133 | 134 | >>> translator.translate('veritas lux mea', src='la') 135 | 136 | 137 | Advanced usage: 138 | >>> translations = translator.translate(['The quick brown fox', 'jumps over', 'the lazy dog'], dest='ko') 139 | >>> for translation in translations: 140 | ... print(translation.origin, ' -> ', translation.text) 141 | The quick brown fox -> 빠른 갈색 여우 142 | jumps over -> 이상 점프 143 | the lazy dog -> 게으른 개 144 | """ 145 | dest = dest.lower().split('_', 1)[0] 146 | src = src.lower().split('_', 1)[0] 147 | 148 | if src != 'auto' and src not in LANGUAGES: 149 | if src in SPECIAL_CASES: 150 | src = SPECIAL_CASES[src] 151 | elif src in LANGCODES: 152 | src = LANGCODES[src] 153 | else: 154 | raise ValueError('invalid source language') 155 | 156 | if dest not in LANGUAGES: 157 | if dest in SPECIAL_CASES: 158 | dest = SPECIAL_CASES[dest] 159 | elif dest in LANGCODES: 160 | dest = LANGCODES[dest] 161 | else: 162 | raise ValueError('invalid destination language') 163 | 164 | if isinstance(text, list): 165 | result = [] 166 | for item in text: 167 | translated = self.translate(item, dest=dest, src=src) 168 | result.append(translated) 169 | return result 170 | 171 | origin = text 172 | data = self._translate(text, dest, src) 173 | 174 | # this code will be updated when the format is changed. 175 | translated = ''.join([d[0] if d[0] else '' for d in data[0]]) 176 | 177 | extra_data = self._parse_extra_data(data) 178 | 179 | # actual source language that will be recognized by Google Translator when the 180 | # src passed is equal to auto. 181 | try: 182 | src = data[2] 183 | except Exception: # pragma: nocover 184 | pass 185 | 186 | pron = origin 187 | try: 188 | pron = data[0][1][-2] 189 | except Exception: # pragma: nocover 190 | pass 191 | if not PY3 and isinstance(pron, unicode) and isinstance(origin, str): # pragma: nocover 192 | origin = origin.decode('utf-8') 193 | if dest in EXCLUDES and pron == origin: 194 | pron = translated 195 | 196 | # for python 2.x compatbillity 197 | if not PY3: # pragma: nocover 198 | if isinstance(src, str): 199 | src = src.decode('utf-8') 200 | if isinstance(dest, str): 201 | dest = dest.decode('utf-8') 202 | if isinstance(translated, str): 203 | translated = translated.decode('utf-8') 204 | 205 | # put final values into a new Translated object 206 | result = Translated(src=src, dest=dest, origin=origin, 207 | text=translated, pronunciation=pron, extra_data=extra_data) 208 | 209 | return result 210 | 211 | def detect(self, text): 212 | """Detect language of the input text 213 | 214 | :param text: The source text(s) whose language you want to identify. 215 | Batch detection is supported via sequence input. 216 | :type text: UTF-8 :class:`str`; :class:`unicode`; string sequence (list, tuple, iterator, generator) 217 | 218 | :rtype: Detected 219 | :rtype: :class:`list` (when a list is passed) 220 | 221 | Basic usage: 222 | >>> from googletrans import Translator 223 | >>> translator = Translator() 224 | >>> translator.detect('이 문장은 한글로 쓰여졌습니다.') 225 | 226 | >>> translator.detect('この文章は日本語で書かれました。') 227 | 228 | >>> translator.detect('This sentence is written in English.') 229 | 230 | >>> translator.detect('Tiu frazo estas skribita en Esperanto.') 231 | 232 | 233 | Advanced usage: 234 | >>> langs = translator.detect(['한국어', '日本語', 'English', 'le français']) 235 | >>> for lang in langs: 236 | ... print(lang.lang, lang.confidence) 237 | ko 1 238 | ja 0.92929292 239 | en 0.96954316 240 | fr 0.043500196 241 | """ 242 | if isinstance(text, list): 243 | result = [] 244 | for item in text: 245 | lang = self.detect(item) 246 | result.append(lang) 247 | return result 248 | 249 | data = self._translate(text, dest='en', src='auto') 250 | 251 | # actual source language that will be recognized by Google Translator when the 252 | # src passed is equal to auto. 253 | src = '' 254 | confidence = 0.0 255 | try: 256 | src = ''.join(data[8][0]) 257 | confidence = data[8][-2][0] 258 | except Exception: # pragma: nocover 259 | pass 260 | result = Detected(lang=src, confidence=confidence) 261 | 262 | return result 263 | -------------------------------------------------------------------------------- /dist/compat.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import sys 3 | try: # pragma: nocover 4 | from urllib.parse import quote 5 | except: # pragma: nocover 6 | from urllib import quote 7 | 8 | 9 | PY3 = sys.version_info > (3, ) 10 | 11 | unicode = str if PY3 else unicode 12 | -------------------------------------------------------------------------------- /dist/constants.py: -------------------------------------------------------------------------------- 1 | DEFAULT_USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)' 2 | 3 | SPECIAL_CASES = { 4 | 'ee': 'et', 5 | } 6 | 7 | LANGUAGES = { 8 | 'af': 'afrikaans', 9 | 'sq': 'albanian', 10 | 'am': 'amharic', 11 | 'ar': 'arabic', 12 | 'hy': 'armenian', 13 | 'az': 'azerbaijani', 14 | 'eu': 'basque', 15 | 'be': 'belarusian', 16 | 'bn': 'bengali', 17 | 'bs': 'bosnian', 18 | 'bg': 'bulgarian', 19 | 'ca': 'catalan', 20 | 'ceb': 'cebuano', 21 | 'ny': 'chichewa', 22 | 'zh-cn': 'chinese (simplified)', 23 | 'zh-tw': 'chinese (traditional)', 24 | 'co': 'corsican', 25 | 'hr': 'croatian', 26 | 'cs': 'czech', 27 | 'da': 'danish', 28 | 'nl': 'dutch', 29 | 'en': 'english', 30 | 'eo': 'esperanto', 31 | 'et': 'estonian', 32 | 'tl': 'filipino', 33 | 'fi': 'finnish', 34 | 'fr': 'french', 35 | 'fy': 'frisian', 36 | 'gl': 'galician', 37 | 'ka': 'georgian', 38 | 'de': 'german', 39 | 'el': 'greek', 40 | 'gu': 'gujarati', 41 | 'ht': 'haitian creole', 42 | 'ha': 'hausa', 43 | 'haw': 'hawaiian', 44 | 'iw': 'hebrew', 45 | 'hi': 'hindi', 46 | 'hmn': 'hmong', 47 | 'hu': 'hungarian', 48 | 'is': 'icelandic', 49 | 'ig': 'igbo', 50 | 'id': 'indonesian', 51 | 'ga': 'irish', 52 | 'it': 'italian', 53 | 'ja': 'japanese', 54 | 'jw': 'javanese', 55 | 'kn': 'kannada', 56 | 'kk': 'kazakh', 57 | 'km': 'khmer', 58 | 'ko': 'korean', 59 | 'ku': 'kurdish (kurmanji)', 60 | 'ky': 'kyrgyz', 61 | 'lo': 'lao', 62 | 'la': 'latin', 63 | 'lv': 'latvian', 64 | 'lt': 'lithuanian', 65 | 'lb': 'luxembourgish', 66 | 'mk': 'macedonian', 67 | 'mg': 'malagasy', 68 | 'ms': 'malay', 69 | 'ml': 'malayalam', 70 | 'mt': 'maltese', 71 | 'mi': 'maori', 72 | 'mr': 'marathi', 73 | 'mn': 'mongolian', 74 | 'my': 'myanmar (burmese)', 75 | 'ne': 'nepali', 76 | 'no': 'norwegian', 77 | 'ps': 'pashto', 78 | 'fa': 'persian', 79 | 'pl': 'polish', 80 | 'pt': 'portuguese', 81 | 'pa': 'punjabi', 82 | 'ro': 'romanian', 83 | 'ru': 'russian', 84 | 'sm': 'samoan', 85 | 'gd': 'scots gaelic', 86 | 'sr': 'serbian', 87 | 'st': 'sesotho', 88 | 'sn': 'shona', 89 | 'sd': 'sindhi', 90 | 'si': 'sinhala', 91 | 'sk': 'slovak', 92 | 'sl': 'slovenian', 93 | 'so': 'somali', 94 | 'es': 'spanish', 95 | 'su': 'sundanese', 96 | 'sw': 'swahili', 97 | 'sv': 'swedish', 98 | 'tg': 'tajik', 99 | 'ta': 'tamil', 100 | 'te': 'telugu', 101 | 'th': 'thai', 102 | 'tr': 'turkish', 103 | 'uk': 'ukrainian', 104 | 'ur': 'urdu', 105 | 'uz': 'uzbek', 106 | 'vi': 'vietnamese', 107 | 'cy': 'welsh', 108 | 'xh': 'xhosa', 109 | 'yi': 'yiddish', 110 | 'yo': 'yoruba', 111 | 'zu': 'zulu', 112 | 'fil': 'Filipino', 113 | 'he': 'Hebrew' 114 | } 115 | 116 | LANGCODES = dict(map(reversed, LANGUAGES.items())) 117 | -------------------------------------------------------------------------------- /dist/gtoken.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import ast 3 | import math 4 | import re 5 | import time 6 | 7 | import requests 8 | 9 | 10 | from .compat import PY3 11 | from .compat import unicode 12 | from .utils import rshift 13 | 14 | 15 | class TokenAcquirer(object): 16 | """Google Translate API token generator 17 | 18 | translate.google.com uses a token to authorize the requests. If you are 19 | not Google, you do have this token and will have to pay for use. 20 | This class is the result of reverse engineering on the obfuscated and 21 | minified code used by Google to generate such token. 22 | 23 | The token is based on a seed which is updated once per hour and on the 24 | text that will be translated. 25 | Both are combined - by some strange math - in order to generate a final 26 | token (e.g. 744915.856682) which is used by the API to validate the 27 | request. 28 | 29 | This operation will cause an additional request to get an initial 30 | token from translate.google.com. 31 | 32 | Example usage: 33 | >>> from googletrans.gtoken import TokenAcquirer 34 | >>> acquirer = TokenAcquirer() 35 | >>> text = 'test' 36 | >>> tk = acquirer.do(text) 37 | >>> tk 38 | 950629.577246 39 | """ 40 | 41 | RE_TKK = re.compile(r'tkk:\'([^\']+)', re.DOTALL) 42 | 43 | def __init__(self, tkk='0', session=None, host='translate.google.com'): 44 | self.session = session or requests.Session() 45 | self.tkk = tkk 46 | self.host = host if 'http' in host else 'https://' + host 47 | 48 | def _update(self): 49 | """update tkk 50 | """ 51 | # we don't need to update the base TKK value when it is still valid 52 | r = self.session.get(self.host) 53 | self.tkk = self.RE_TKK.findall(r.text)[0] 54 | 55 | now = math.floor(int(time.time() * 1000) / 3600000.0) 56 | if self.tkk and int(self.tkk.split('.')[0]) == now: 57 | return 58 | 59 | # this will be the same as python code after stripping out a reserved word 'var' 60 | code = unicode(self.RE_TKK.search(r.text).group(1)).replace('var ', '') 61 | # unescape special ascii characters such like a \x3d(=) 62 | if PY3: # pragma: no cover 63 | code = code.encode().decode('unicode-escape') 64 | else: # pragma: no cover 65 | code = code.decode('string_escape') 66 | 67 | if code: 68 | tree = ast.parse(code) 69 | visit_return = False 70 | operator = '+' 71 | n, keys = 0, dict(a=0, b=0) 72 | for node in ast.walk(tree): 73 | if isinstance(node, ast.Assign): 74 | name = node.targets[0].id 75 | if name in keys: 76 | if isinstance(node.value, ast.Num): 77 | keys[name] = node.value.n 78 | # the value can sometimes be negative 79 | elif isinstance(node.value, ast.UnaryOp) and \ 80 | isinstance(node.value.op, ast.USub): # pragma: nocover 81 | keys[name] = -node.value.operand.n 82 | elif isinstance(node, ast.Return): 83 | # parameters should be set after this point 84 | visit_return = True 85 | elif visit_return and isinstance(node, ast.Num): 86 | n = node.n 87 | elif visit_return and n > 0: 88 | # the default operator is '+' but implement some more for 89 | # all possible scenarios 90 | if isinstance(node, ast.Add): # pragma: nocover 91 | pass 92 | elif isinstance(node, ast.Sub): # pragma: nocover 93 | operator = '-' 94 | elif isinstance(node, ast.Mult): # pragma: nocover 95 | operator = '*' 96 | elif isinstance(node, ast.Pow): # pragma: nocover 97 | operator = '**' 98 | elif isinstance(node, ast.BitXor): # pragma: nocover 99 | operator = '^' 100 | # a safety way to avoid Exceptions 101 | clause = compile('{1}{0}{2}'.format( 102 | operator, keys['a'], keys['b']), '', 'eval') 103 | value = eval(clause, dict(__builtin__={})) 104 | result = '{}.{}'.format(n, value) 105 | 106 | self.tkk = result 107 | 108 | def _lazy(self, value): 109 | """like lazy evalution, this method returns a lambda function that 110 | returns value given. 111 | We won't be needing this because this seems to have been built for 112 | code obfuscation. 113 | 114 | the original code of this method is as follows: 115 | 116 | ... code-block: javascript 117 | 118 | var ek = function(a) { 119 | return function() { 120 | return a; 121 | }; 122 | } 123 | """ 124 | return lambda: value 125 | 126 | def _xr(self, a, b): 127 | size_b = len(b) 128 | c = 0 129 | while c < size_b - 2: 130 | d = b[c + 2] 131 | d = ord(d[0]) - 87 if 'a' <= d else int(d) 132 | d = rshift(a, d) if '+' == b[c + 1] else a << d 133 | a = a + d & 4294967295 if '+' == b[c] else a ^ d 134 | 135 | c += 3 136 | return a 137 | 138 | def acquire(self, text): 139 | b = self.tkk if self.tkk != '0' else '' 140 | d = b.split('.') 141 | b = int(d[0]) if len(d) > 1 else 0 142 | 143 | # assume e means char code array 144 | e = [] 145 | g = 0 146 | size = len(text) 147 | for i, char in enumerate(text): 148 | l = ord(char) 149 | # just append if l is less than 128(ascii: DEL) 150 | if l < 128: 151 | e.append(l) 152 | # append calculated value if l is less than 2048 153 | else: 154 | if l < 2048: 155 | e.append(l >> 6 | 192) 156 | else: 157 | # append calculated value if l matches special condition 158 | if (l & 64512) == 55296 and g + 1 < size and \ 159 | ord(text[g + 1]) & 64512 == 56320: 160 | g += 1 161 | l = 65536 + ((l & 1023) << 10) + ord(text[g]) & 1023 162 | e.append(l >> 18 | 240) 163 | e.append(l >> 12 & 63 | 128) 164 | else: 165 | e.append(l >> 12 | 224) 166 | e.append(l >> 6 & 63 | 128) 167 | e.append(l & 63 | 128) 168 | a = b 169 | for i, value in enumerate(e): 170 | a += value 171 | a = self._xr(a, '+-a^+6') 172 | a = self._xr(a, '+-3^+b+-f') 173 | a ^= int(d[1]) if len(d) > 1 else 0 174 | if a < 0: # pragma: nocover 175 | a = (a & 2147483647) + 2147483648 176 | a %= 1000000 # int(1E6) 177 | 178 | return '{}.{}'.format(a, a ^ b) 179 | 180 | def do(self, text): 181 | self._update() 182 | tk = self.acquire(text) 183 | return tk -------------------------------------------------------------------------------- /dist/html_connector.py: -------------------------------------------------------------------------------- 1 | from .html_translator import superTranslator, massTranslator, setProxy 2 | 3 | import re 4 | from slugify import slugify 5 | from langdetect import detect 6 | 7 | 8 | class TEXTLIB(): 9 | 10 | def removeLinksByDomains(self, text, domains_arr): 11 | for domain in domains_arr: 12 | text = re.sub(']+href=["\'](.*{DOMAIN}.*)["\']>(.+?)'.format(DOMAIN=domain), lambda x: re.search('>(.+?){HTML}

'.format(HTML='
'.join(text.splitlines())) 35 | 36 | 37 | def translator(self, is_html, text, lang_to, proxy): 38 | if not text: 39 | return False 40 | 41 | setProxy(proxy) 42 | if is_html: 43 | return superTranslator().html(text, lang_to) 44 | else: 45 | return superTranslator().text(text, lang_to) 46 | 47 | def massTranslator(self, is_html, text, langs_arr, proxy): 48 | if not text: 49 | return False 50 | 51 | setProxy(proxy) 52 | if is_html: 53 | return massTranslator().html(text, langs_arr) 54 | else: 55 | return massTranslator().text(text, langs_arr) 56 | 57 | 58 | if __name__ == '__main__': 59 | pass 60 | 61 | text = ''' 62 |
63 |

Напомним, что не так давно власти ——[sitename]—— начали регулировать деятельность незаконных ICO., а функции регулятора были переданы в SEC (комиссия по ценным бумагам и биржам США).

64 |
65 | asdasd 66 |

Инвесторы обменивали свои [sitename]
деньги на валюты BitConnect, которая по мнению компании должна была вернуть хорошие дивиденды своим инвесторам.

67 |