diff options
author | Sean B. Palmer <sean@miscoranda.com> | 2011-12-27 14:48:24 +0000 |
---|---|---|
committer | Sean B. Palmer <sean@miscoranda.com> | 2011-12-27 14:48:24 +0000 |
commit | 3724ba37cd02a2bf57012839f84c627eb5df65a2 (patch) | |
tree | 18639fc049fe9cd482e3af8c754771838f7e5829 /modules/translate.py | |
parent | 12d983561a2098141ca1c8b7270060997112c810 (diff) | |
download | bot-3724ba37cd02a2bf57012839f84c627eb5df65a2.tar.gz bot-3724ba37cd02a2bf57012839f84c627eb5df65a2.tar.bz2 bot-3724ba37cd02a2bf57012839f84c627eb5df65a2.zip |
Fixed translation module, with the help of der Hörmi
Diffstat (limited to 'modules/translate.py')
-rwxr-xr-x | modules/translate.py | 47 |
1 files changed, 26 insertions, 21 deletions
diff --git a/modules/translate.py b/modules/translate.py index d5ae41f..209e5bd 100755 --- a/modules/translate.py +++ b/modules/translate.py @@ -11,22 +11,30 @@ http://inamidst.com/phenny/ import re, urllib import web -def detect(text): - uri = 'http://ajax.googleapis.com/ajax/services/language/detect' - q = urllib.quote(text) - bytes = web.get(uri + '?q=' + q + '&v=1.0') - result = web.json(bytes) - try: return result['responseData']['language'] - except Exception: return None - -def translate(text, input, output): - uri = 'http://ajax.googleapis.com/ajax/services/language/translate' - q = urllib.quote(text) - pair = input + '%7C' + output - bytes = web.get(uri + '?q=' + q + '&v=1.0&langpair=' + pair) - result = web.json(bytes) - try: return result['responseData']['translatedText'].encode('cp1252') - except Exception: return None +def translate(text, input='auto', output='en'): + import urllib2, json + opener = urllib2.build_opener() + opener.addheaders = [( + 'User-Agent', 'Mozilla/5.0' + + '(X11; U; Linux i686)' + + 'Gecko/20071127 Firefox/2.0.0.11' + )] + + input, output = urllib.quote(input), urllib.quote(output) + text = urllib.quote(text) + + result = opener.open('http://translate.google.com/translate_a/t?' + + ('client=t&hl=en&sl=%s&tl=%s&multires=1' % (input, output)) + + ('&otf=1&ssel=0&tsel=0&uptl=en&sc=1&text=%s' % text)).read() + + while ',,' in result: + result = result.replace(',,', ',null,') + data = json.loads(result) + + try: language = data[-2][0][0] + except: language = '?' + + return ''.join(x[0] for x in data[0]), language def tr(phenny, context): """Translates a phrase, with an optional language hint.""" @@ -37,15 +45,12 @@ def tr(phenny, context): if (len(phrase) > 350) and (not context.admin): return phenny.reply('Phrase must be under 350 characters.') - input = input or detect(phrase) - if not input: - err = 'Unable to guess your crazy moon language, sorry.' - return phenny.reply(err) + input = input or 'auto' input = input.encode('utf-8') output = (output or 'en').encode('utf-8') if input != output: - msg = translate(phrase, input, output) + msg, input = translate2(phrase, input, output) if isinstance(msg, str): msg = msg.decode('utf-8') if msg: |