phenny-1/modules/translate.py

84 lines
2.5 KiB
Python
Raw Normal View History

#!/usr/bin/env python
# coding=utf-8
"""
translate.py - Phenny Translation Module
Copyright 2008, Sean B. Palmer, inamidst.com
Licensed under the Eiffel Forum License 2.
http://inamidst.com/phenny/
"""
2011-09-22 14:17:27 -04:00
import re, urllib.request, urllib.parse, urllib.error
import web
def detect(text):
uri = 'http://ajax.googleapis.com/ajax/services/language/detect'
2011-09-22 14:17:27 -04:00
q = urllib.parse.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'
2011-09-22 14:17:27 -04:00
q = urllib.parse.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 tr(phenny, context):
"""Translates a phrase, with an optional language hint."""
input, output, phrase = context.groups()
2011-09-22 14:17:27 -04:00
phrase = phrase
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)
2011-09-22 14:17:27 -04:00
output = (output or 'en')
if input != output:
msg = translate(phrase, input, output)
if isinstance(msg, str):
msg = msg.decode('utf-8')
if msg:
msg = web.decode(msg) # msg.replace(''', "'")
msg = '"%s" (%s to %s, translate.google.com)' % (msg, input, output)
else: msg = 'The %s to %s translation failed, sorry!' % (input, output)
phenny.reply(msg)
else: phenny.reply('Language guessing failed, so try suggesting one!')
2011-09-22 14:17:27 -04:00
tr.rule = ('$nick', r'(?:([a-z]{2}) +)?(?:([a-z]{2}) +)?["“](.+?)["”]\? *$')
tr.example = '$nickname: "mon chien"? or $nickname: fr "mon chien"?'
tr.priority = 'low'
def mangle(phenny, input):
2011-09-22 14:17:27 -04:00
phrase = input.group(2)
for lang in ['fr', 'de', 'es', 'it', 'ja']:
backup = phrase
phrase = translate(phrase, 'en', lang)
if not phrase:
phrase = backup
break
__import__('time').sleep(0.5)
backup = phrase
phrase = translate(phrase, lang, 'en')
if not phrase:
phrase = backup
break
__import__('time').sleep(0.5)
phenny.reply(phrase or 'ERRORS SRY')
mangle.commands = ['mangle']
if __name__ == '__main__':
2011-09-22 14:17:27 -04:00
print(__doc__.strip())