Commits

Tetsuya Morimoto committed bfb6277

updated version 0.5.3 to 0.5.4
changed Google Translate API to MS Translate API as default
added error handling

Comments (0)

Files changed (6)

 from setuptools import setup, find_packages
 from os.path import join as pathjoin
 
-VERSION = "0.5.3"
+VERSION = "0.5.4"
 LONG_DESCRIPTION = "".join([
     open(pathjoin("src","README.txt")).read(),
     open(pathjoin("src","TODO.txt")).read()])

src/ikazuchi/core/handler/text.py

         self.sentences = opts.sentences
         self.encoding = opts.encoding
         self.quiet = opts.quiet
-        if opts.api == "microsoft":
+        if not opts.api or opts.api == "microsoft":
             self.method_name = "translate_array"
         if opts.detect:
             self.method_name = "detect"
-            if opts.api == "microsoft":
+            if not opts.api or opts.api == "microsoft":
                 self.method_name = "detect_array"
 
     def _encode(self, text):

src/ikazuchi/core/translator/__init__.py

 class TranslatingMicrosoft(MicrosoftTranslator, BaseTranslator): pass
 class TranslatingYahoo(YahooTranslator, BaseTranslator): pass  # is obsoleted
 
-TRANSLATE_API = defaultdict(lambda: TranslatingGoogle,
+TRANSLATE_API = defaultdict(lambda: TranslatingMicrosoft,
     {
         "google": TranslatingGoogle,
         "microsoft": TranslatingMicrosoft,

src/ikazuchi/core/translator/google.py

 from urllib import urlencode
 from utils import get_ip_address
 
+from ikazuchi.errors import NeedApiKeyError
+
 __all__ = [
     "GoogleTranslator",
 ]
     Translator with Google Translate API with version 2
     http://code.google.com/intl/ja/apis/language/translate/overview.html
     http://code.google.com/intl/ja/apis/language/translate/v2/using_rest.html
+    http://code.google.com/intl/ja/apis/language/translate/v2/pricing.html
     see also
     Google Translate API Terms of Use
     http://code.google.com/intl/ja/apis/language/translate/terms.html
     """
     domain = "www.googleapis.com"
     common_path = "/language/translate/"
-    apikey = "AIzaSyDDCHHwbfHLIsHWEhxAu41UmrRCg_Xmvm8"
+    apikey = None  # get from configuration file
     q_format = "html"
 
     def __init__(self, lang_from, lang_to, handler):
 
     def call_api(self, query, key, func=None):
         """high-level method to make url and request"""
+        if not self.apikey:
+            raise NeedApiKeyError("need API key !!!")
         url = self.get_url(func)
         response = self.request(url, urlencode(query, doseq=True))
         return self.api(), response[key]
             f.write(res.read())
             f.flush()
         return self.api()
-
-class GoogleTranslatorV1(object):
-    """
-    Translator with Google Translate API
-    http://code.google.com/intl/ja/apis/language/translate/overview.html
-    see also
-    Google Translate API Terms of Use
-    http://code.google.com/intl/ja/apis/language/translate/terms.html
-    """
-    domain = "ajax.googleapis.com"
-    common_path = "/ajax/services/language/"
-    apikey = "ABQIAAAAK6kpHnylgmAYtO7ZX01XXRSvW2ISZ2KI4wU-F"\
-             "k6WlRk77d73EhTtYeI1LUl3BfkKv-17KKEWzdRTMw"
-    userip = get_ip_address()
-    q_format = "html"
-
-    def __init__(self, lang_from, lang_to, handler):
-        self.lang_from = lang_from
-        self.lang_to = lang_to
-        self.handler = handler
-        self._url = "http://{0}{1}".format(self.domain, self.common_path)
-
-    def get_api_path(self, func):
-        return "{0}?".format(func.func_name)
-
-    def get_url(self, func, query):
-        return "{0}{1}{2}".format(self._url,
-                self.get_api_path(func), urlencode(query))
-
-    def request(self, url):
-        req = urllib2.Request(url)
-        with closing(urllib2.urlopen(req)) as res:
-            res_json = json.loads(res.read())
-            if res_json["responseStatus"] == 200:
-                response = res_json["responseData"]
-            else:
-                raise RuntimeError(res_json)
-        return response
-
-    def call_api(self, func, query, key=None):
-        """high-level method to make url and request"""
-        url = self.get_url(func, query)
-        response = self.request(url)
-        if key:
-            response = response[key]
-        return self.api(), response
-
-    def detect(self, text):
-        """ JSON Developer's Guide for Language Detect
-        http://code.google.com/intl/ja/apis/language/translate/v1/\
-        using_rest_langdetect.html
-        """
-        query = {
-            "v": "1.0",
-            "q": text.encode("utf-8"),
-            "key": self.apikey,
-            "userip": self.userip,
-        }
-        return self.call_api(self.detect, query, "language")
-
-    def translate(self, text):
-        """ JSON Developer's Guide for Translate
-        http://code.google.com/intl/ja/apis/language/translate/v1/\
-        using_rest_translate.html
-        """
-        query = {
-            "v": "1.0",
-            "q": text.encode("utf-8"),
-            "langpair": "{0}|{1}".format(self.lang_from, self.lang_to),
-            "key": self.apikey,
-            "userip": self.userip,
-            "format": self.q_format,
-        }
-        _key = "translatedText"
-        api, response = self.call_api(self.translate, query, _key)
-        return api, self.parse_html(response)

src/ikazuchi/ikazuchi.py

 
 from conf import (get_conf, get_conf_path)
 from core.translator import TRANSLATE_API
+from errors import *
 from locale import _
 from plugins.utils import (get_plugin, load_all_plugins)
 from utils import *
 
-__version__ = "0.5.3"
+__version__ = "0.5.4"
 
 # base parser object for common option
 base_parser = argparse.ArgumentParser(add_help=False)
     # pre process
     check_python_version()
     conf = get_conf(get_conf_path())
+
     # main process
     opts = get_args()
     if opts.plugin == "normal":
         if plugin_translator:
             TRANSLATE_API[opts.plugin] = plugin_translator
             opts.api = opts.api if opts.api else opts.plugin
-    t = TRANSLATE_API[opts.api](opts.lang_from, opts.lang_to, handler)
-    t.set_parameter_from_conf(conf)
-    t.call_method_with_handler()
+
+    try:
+        t = TRANSLATE_API[opts.api](opts.lang_from, opts.lang_to, handler)
+        t.set_parameter_from_conf(conf)
+        t.call_method_with_handler()
+    except IkazuchiError as err:
+        print err
 
 if __name__ == "__main__":
     main()

src/ikazuchi/tests/test_google_translator.py

 from ikazuchi.core.translator import TranslatingGoogle
 
 class TestGoogleTranslator(object):
+    """
+    Do not test to request actually since Google Translate API v2 is
+    a paid service from 2011/12/1
+    """
 
     def setup(self):
         self.t = TranslatingGoogle("ja", "en", None)
         expected = "https://www.googleapis.com/language/translate/v2/detect"
         assert_equal(expected, self.t.get_url(detect))
 
+    @nottest
     def test_detect(self):
         res = self.t.detect([unicode("テスト", "utf-8")])
         assert_equal(u"ja", res[1][0][0][u"language"])
 
+    @nottest
     def test_translate(self):
         assert_equal(('Google', [u'Test']),
                      self.t.translate([unicode("テスト", "utf-8")]))