Package: goslate
NoteGoogle has updated its translation service recently with a ticket mechanism to prevent simple crawler programs likegoslatefrom accessing.
Though a more sophisticated crawler may still work technically, it would have crossed the fine line between using the service and breaking the service.goslatewill not be updated to break google’s ticket mechanism. Free lunch is over. Thanks for using.Simple UsageInstallationProxy SupportRomanizationLanguage DetectionConcurrent QueryingBatch TranslationPerformance ConsiderationLookup Details in DictionaryQuery ErrorAPI ReferencesCommand Line InterfaceHow to ContributeWhat’s New1.5.41.5.21.5.01.4.01.3.21.3.0goslateprovides youfreepython API to google translation service by querying google translation website.It is:Free: get translation through public google web site without feeFast: batch, cache and concurrently fetchSimple: single file module, justGoslate().translate('Hi!','zh')Simple UsageThe basic usage is simple:>>>importgoslate>>>gs=goslate.Goslate()>>>print(gs.translate('hello world','de'))halloweltInstallationgoslate support both Python2 and Python3. You could install it via:$pipinstallgoslateor just downloadlatest goslate.pydirectly and usefuturespackageis optional but recommended to install for best performance in large text translation tasks.Proxy SupportProxy support could be added as following:importurllib2importgoslateproxy_handler=urllib2.ProxyHandler({"http":"http://proxy-domain.name:8080"})proxy_opener=urllib2.build_opener(urllib2.HTTPHandler(proxy_handler),urllib2.HTTPSHandler(proxy_handler))gs_with_proxy=goslate.Goslate(opener=proxy_opener)translation=gs_with_proxy.translate("hello world","de")RomanizationRomanization or latinization (or romanisation, latinisation), in linguistics, is the conversion of writing from a different writing system to the Roman (Latin) script, or a system for doing so.For example, pinyin is the default romanization method for Chinese language.You could get translation in romanized writing as following:>>>importgoslate>>>roman_gs=goslate.Goslate(writing=goslate.WRITING_ROMAN)>>>print(roman_gs.translate('China','zh'))ZhōngguóYou could also get translation in both native writing system and ramon writing system>>>importgoslate>>>gs=goslate.Goslate(writing=goslate.WRITING_NATIVE_AND_ROMAN)>>>gs.translate('China','zh')('中国','Zhōngguó')You could see the result will be a tuple in this case:(Translation-in-Native-Writing,Translation-in-Roman-Writing)Language DetectionSometimes all you need is just find out which language the text is:>>>importgoslate>>>gs=goslate.Goslate()>>>language_id=gs.detect('hallo welt')>>>language_id'de'>>>gs.get_languages()[language_id]'German'Concurrent QueryingIt is not necessary to roll your own multi-thread solution to speed up massive translation. Goslate has already done it for you. It utilizesconcurrent.futuresfor concurrent querying. The max worker number is 120 by default.The worker number could be changed as following:>>>importgoslate>>>importconcurrent.futures>>>executor=concurrent.futures.ThreadPoolExecutor(max_workers=200)>>>gs=goslate.Goslate(executor=executor)>>>it=gs.translate(['text1','text2','text3'])>>>list(it)['translation1','translation2','translation3']It is advised to installconcurrent.futuresbackport lib in python2.7 (python3 has it by default) to enable concurrent querying.The input could be list, tuple or any iterator, even the file object which iterate line by line>>>translated_lines=gs.translate(open('readme.txt'))>>>translation='\n'.join(translated_lines)Do not worry about short texts will increase the query time. Internally, goslate will join small text into one big text to reduce the unnecessary query round trips.Batch TranslationGoogle translation does not support very long text, goslate bypasses this limitation by splitting the long text internally before sending it to Google and joining the multiple results into one translation text to the end user.>>>importgoslate>>>withopen('the game of thrones.txt','r')asf:>>>novel_text=f.read()>>>gs=goslate.Goslate()>>>gs.translate(novel_text)Performance ConsiderationGoslate uses batch and concurrent fetch aggressively to achieve maximized translation speed internally.All you need to do is reduce API calling times by utilizing batch translation and concurrent querying.For example, say if you want to translate 3 big text files. Instead of manually translate them one by one, line by line:importgoslatebig_files=['a.txt','b.txt','c.txt']gs=goslate.Goslate()translation=[]forbig_fileinbig_files:withopen(big_file,'r')asf:translated_lines=[]forlineinf:translated_line=gs.translate(line)translated_lines.append(translated_line)translation.append('\n'.join(translated_lines))It is better to leave them to Goslate totally. The following code is not only simpler but also much faster (+100x) :importgoslatebig_files=['a.txt','b.txt','c.txt']gs=goslate.Goslate()translation_iter=gs.translate(open(big_file,'r').read()forbig_fileinbig_files)translation=list(translation_iter)Internally, goslate will first adjust the text to make them not so big that do not fit Google query API, nor so small that increase the total HTTP querying times. Then it will use concurrent queries to speed things even further.Lookup Details in DictionaryIf you want detail dictionary explanation for a single word/phrase, you could>>>importgoslate>>>gs=goslate.Goslate()>>>gs.lookup_dictionary('sun','de')[[['Sonne','sun',0]],[['noun',['Sonne'],[['Sonne',['sun','Sun','Sol'],0.44374731,'die']],'sun',1],['verb',['der Sonne aussetzen'],[['der Sonne aussetzen',['sun'],1.1544633e-06]],'sun',2]],'en',0.9447732,[['en'],[0.9447732]]]There are 2 limitations for this API:The result is a complex list structure which you have to parse for your own usageThe input must be a single word/phase, batch translation and concurrent querying are not supportedQuery ErrorIf you get an HTTP 5xx error, it is probably because google has banned your client IP address from transaction querying.You could verify it by accessing google translation service in the browser manually.You could try the following to overcome this issue:query through a HTTP/SOCKS5 proxy, seeProxy Supportusing another google domain for translation:gs =Goslate(service_urls=['http://translate.google.de'])wait for 3 seconds before issue another queryingAPI Referencesplease checkAPI referenceCommand Line Interfacegoslate.pyis also a command line tool which you could use directlyTranslatestdininput into Chinese in GBK encoding$echo"hello world"|goslate.py-tzh-CN-ogbkTranslate 2 text files into Chinese, output to UTF-8 file$goslate.py-tzh-CN-outf-8source/1.txt"source 2.txt">output.txtuse--helpfor detail usage$goslate.py-hHow to ContributeReportissues & suggestionsForkrepositoryDonationWhat’s New1.5.4handle deprecatedthreading.currentThread()properlyaddretry_wait_durationparam to fine control the retry behavior in case of connection error1.5.2[fix bug] removes newlines from descriptions to avoid installation failure1.5.0Add new APIGoslate.lookup_dictionary()to get detail information for a single word/phrase, thanks for Adam’s suggestionImprove document with more user scenario and performance consideration1.4.0[fix bug] update to adapt latest google translation service changes1.3.2[fix bug] fix compatible issue with latest google translation service json format changes[fix bug] unit test failure1.3.0[new feature] Translation in roman writing system (romanization), thanks for Javier del Alamo’s contribution.[new feature] Customizable service URL. you could provide multiple google translation service URLs for better concurrency performance[new option] roman writing translation option for CLI[fix bug] Google translation may change normal space to no-break space[fix bug] Google web API changed for getting supported language list