[kupfer: 10/13] plugin.google_translate: fix errors, add new actions.
- From: Ulrik Sverdrup <usverdrup src gnome org>
- To: svn-commits-list gnome org
- Cc:
- Subject: [kupfer: 10/13] plugin.google_translate: fix errors, add new actions.
- Date: Tue, 3 Nov 2009 12:00:47 +0000 (UTC)
commit 5f9903a844d4bbdd9b84ac4a60d30cc6ff203f04
Author: Karol BÄ?dkowski <karol bedkowsk+gh gmail com>
Date: Sat Oct 31 12:38:18 2009 +0100
plugin.google_translate: fix errors, add new actions.
Fix problem with encoding.
Add new action:
- for UrlLeaf - open translated page
- for TextLeaf - open Google Translate web page.
kupfer/plugin/google_translate.py | 113 +++++++++++++++++++++++++++++++-----
1 files changed, 97 insertions(+), 16 deletions(-)
---
diff --git a/kupfer/plugin/google_translate.py b/kupfer/plugin/google_translate.py
index 2e7abf8..0946555 100644
--- a/kupfer/plugin/google_translate.py
+++ b/kupfer/plugin/google_translate.py
@@ -1,12 +1,12 @@
# -*- coding: UTF-8 -*-
-from kupfer.objects import Source, Action, TextLeaf, Leaf
+from kupfer.objects import Source, Action, TextLeaf, Leaf, UrlLeaf
from kupfer import icons, utils, pretty
__kupfer_name__ = _("Google Translate")
-__kupfer_actions__ = ("Translate", )
+__kupfer_actions__ = ("Translate", "TranslateUrl", 'OpenTranslatePage')
__description__ = _("Use Google to Translate Text.")
-__version__ = ""
+__version__ = "2009-10-31"
__author__ = "Karol BÄ?dkowski <karol bedkowski gmail com>"
'''
@@ -26,9 +26,14 @@ except ImportError:
json_decoder = json.loads
_GOOGLE_TRANSLATE_HOST = 'translate.google.com'
-_GOOGLE_TRANSLATE_PATH = '/translate_a/t?sl=auto&client=t'
+_GOOGLE_TRANSLATE_PATH = '/translate_a/t?client=t&sl=auto&ie=UTF-8'
_GOOGLE_TRANS_LANG_PATH = '/translate_t'
+_HEADER = {
+ 'Content-type':'application/x-www-form-urlencoded',
+ 'Accept': 'text/xml,application/xml,application/xhtml+xml,text/html',
+ 'Accept-charset': 'utf-8;q=0.7'
+}
def _parse_encoding_header(response, default="UTF-8"):
"""Parse response's header for an encoding, that is return 'utf-8' for:
@@ -43,31 +48,31 @@ def _parse_encoding_header(response, default="UTF-8"):
def _translate(text, lang):
''' Translate @text to @lang. '''
- query_param = urllib.urlencode(dict(tl=lang, text=text))
+ query_param = urllib.urlencode(dict(tl=lang, text=text.encode('utf-8')))
try:
conn = httplib.HTTPConnection(_GOOGLE_TRANSLATE_HOST)
- conn.request("POST", _GOOGLE_TRANSLATE_PATH, query_param)
+ conn.request("POST", _GOOGLE_TRANSLATE_PATH, query_param, _HEADER)
resp = conn.getresponse()
if resp.status != 200:
raise Exception('invalid response %d, %s' % resp.status, resp.reason)
response_data = resp.read()
encoding = _parse_encoding_header(resp)
- response_data = response_data.decode(encoding)
+ response_data = response_data.decode(encoding, 'replace')
resp = json_decoder(response_data)
if len(resp) == 2:
- yield resp[0]
+ yield resp[0], ""
elif len(resp) == 3:
result, _lang, other_trans = resp
- yield result
+ yield result, ""
- if other_trans:
- for translation in other_trans[0]:
- yield translation
+ for other in other_trans:
+ for translation in other[1:]:
+ yield translation, other[0]
except Exception, err:
pretty.print_error(__name__, '_translate error', repr(text), lang, err)
- yield _("Error connecting to Google Translate")
+ yield _("Error connecting to Google Translate"), ""
finally:
conn.close()
@@ -140,9 +145,18 @@ class Translate (Action):
return _LangSource()
+class TranslationLeaf(TextLeaf):
+ def __init__(self, translation, descr):
+ TextLeaf.__init__(self, translation)
+ self._descrtiption = descr
+
+ def get_description(self):
+ return self._descrtiption or TextLeaf.get_description(self)
+
+
class _TransateQuerySource(Source):
def __init__(self, text, lang):
- Source.__init__(self, name=_("Translate into %s") % text)
+ Source.__init__(self, name=_("Translate into %s") % lang)
self._text = text
self._lang = lang
@@ -150,8 +164,8 @@ class _TransateQuerySource(Source):
return True
def get_items(self):
- for translation in _translate(self._text, self._lang):
- yield TextLeaf(translation)
+ for translation, desc in _translate(self._text, self._lang):
+ yield TranslationLeaf(translation.replace('\\n ', '\n'), desc)
class _Language(Leaf):
@@ -181,3 +195,70 @@ class _LangSource(Source):
def get_icon_name(self):
return "preferences-desktop-locale"
+
+
+class TranslateUrl(Action):
+ def __init__(self):
+ Action.__init__(self, _("Open Page Translated To..."))
+
+ def activate(self, leaf, iobj):
+ dest_lang = iobj.object
+ params = urllib.urlencode(dict(u=leaf.object, sl='auto', tl=dest_lang ))
+ url = 'http://translate.google.pl/translate?' + params
+ utils.show_url(url)
+
+ def item_types(self):
+ yield UrlLeaf
+
+ def valid_for_item(self, leaf):
+ return leaf.object.startswith('http://') or leaf.object.startswith('www.')
+
+ def get_description(self):
+ return _("Translate Page in Google and show in default viewer")
+
+ def get_icon_name(self):
+ return "accessories-dictionary"
+
+ def requires_object(self):
+ return True
+
+ def object_types(self):
+ yield _Language
+
+ def object_source(self, for_item=None):
+ return _LangSource()
+
+
+class OpenTranslatePage (Action):
+ def __init__(self):
+ Action.__init__(self, _("Open Google and Show Translation To..."))
+
+ def activate(self, leaf, iobj):
+ text = urllib.quote(unicode(leaf.object).encode('utf-8'))
+ dest_lang = iobj.object
+ url = 'http://' + _GOOGLE_TRANSLATE_HOST + _GOOGLE_TRANS_LANG_PATH + \
+ "#auto|" + dest_lang + "|" + text
+ utils.show_url(url)
+
+ def item_types(self):
+ yield TextLeaf
+
+ def valid_for_item(self, leaf):
+ return len(leaf.object.strip()) > 0
+
+ def get_description(self):
+ return _("Translate in Google")
+
+ def get_icon_name(self):
+ return "accessories-dictionary"
+
+ def requires_object(self):
+ return True
+
+ def object_types(self):
+ yield _Language
+
+ def object_source(self, for_item=None):
+ return _LangSource()
+
+
[
Date Prev][
Date Next] [
Thread Prev][
Thread Next]
[
Thread Index]
[
Date Index]
[
Author Index]