Fixed translation module, with the help of der Hörmi

master
Sean B. Palmer 2011-12-27 14:48:24 +00:00
parent 12d983561a
commit 3724ba37cd
2 changed files with 26 additions and 21 deletions

View File

@ -11,22 +11,30 @@ http://inamidst.com/phenny/
import re, urllib import re, urllib
import web import web
def detect(text): def translate(text, input='auto', output='en'):
uri = 'http://ajax.googleapis.com/ajax/services/language/detect' import urllib2, json
q = urllib.quote(text) opener = urllib2.build_opener()
bytes = web.get(uri + '?q=' + q + '&v=1.0') opener.addheaders = [(
result = web.json(bytes) 'User-Agent', 'Mozilla/5.0' +
try: return result['responseData']['language'] '(X11; U; Linux i686)' +
except Exception: return None 'Gecko/20071127 Firefox/2.0.0.11'
)]
def translate(text, input, output): input, output = urllib.quote(input), urllib.quote(output)
uri = 'http://ajax.googleapis.com/ajax/services/language/translate' text = urllib.quote(text)
q = urllib.quote(text)
pair = input + '%7C' + output result = opener.open('http://translate.google.com/translate_a/t?' +
bytes = web.get(uri + '?q=' + q + '&v=1.0&langpair=' + pair) ('client=t&hl=en&sl=%s&tl=%s&multires=1' % (input, output)) +
result = web.json(bytes) ('&otf=1&ssel=0&tsel=0&uptl=en&sc=1&text=%s' % text)).read()
try: return result['responseData']['translatedText'].encode('cp1252')
except Exception: return None 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): def tr(phenny, context):
"""Translates a phrase, with an optional language hint.""" """Translates a phrase, with an optional language hint."""
@ -37,15 +45,12 @@ def tr(phenny, context):
if (len(phrase) > 350) and (not context.admin): if (len(phrase) > 350) and (not context.admin):
return phenny.reply('Phrase must be under 350 characters.') return phenny.reply('Phrase must be under 350 characters.')
input = input or detect(phrase) input = input or 'auto'
if not input:
err = 'Unable to guess your crazy moon language, sorry.'
return phenny.reply(err)
input = input.encode('utf-8') input = input.encode('utf-8')
output = (output or 'en').encode('utf-8') output = (output or 'en').encode('utf-8')
if input != output: if input != output:
msg = translate(phrase, input, output) msg, input = translate2(phrase, input, output)
if isinstance(msg, str): if isinstance(msg, str):
msg = msg.decode('utf-8') msg = msg.decode('utf-8')
if msg: if msg:

View File

@ -13,7 +13,7 @@ function commit() {
git commit -a && git push origin master git commit -a && git push origin master
} }
# log - Show a log of recent updates # history - Show a log of recent updates
function history() { function history() {
git log --pretty=oneline --no-merges -10 git log --pretty=oneline --no-merges -10
} }