#!/usr/bin/python2
#
# Peteris Krumins (peter@catonmat.net)
# http://www.catonmat.net  --  good coders code, great reuse
#
# A Google Python library:
# http://www.catonmat.net/blog/python-library-for-google-translate/
#
# Code is licensed under MIT license.
#
# Copyright (c) 2009 Peteris Krumins
#
#    Permission is hereby granted, free of charge, to any person
#    Obtaining a copy of this software and associated documentation
#    Files (the "Software"), to deal in the Software without
#    Restriction, including without limitation the rights to use,
#    Copy, modify, merge, publish, distribute, sublicense, and/or sell
#    Copies of the Software, and to permit persons to whom the
#    Software is furnished to do so, subject to the following
#    Conditions:
#
#    The above copyright notice and this permission notice shall be
#    Included in all copies or substantial portions of the Software.
#
#    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
#    EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
#    OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
#    NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
#    HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
#    WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
#    FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
#    OTHER DEALINGS IN THE SOFTWARE.

from browser import Browser, BrowserError
from urllib import quote_plus 
try:
	import simplejson as json
except: print "For Google Translate support, install package: python-simplejson"

class TranslationError(Exception):
    pass

class Translator(object):
    translate_url = "http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=%(message)s&langpair=%(from)s%%7C%(to)s"

    def __init__(self):
        self.browser = Browser()

    def translate(self, message, lang_to='en', lang_from=''):
        """
        Given a 'message' translate it from 'lang_from' to 'lang_to'.
        If 'lang_from' is empty, auto-detects the language.
        Returns the translated message.
        """

        if lang_to not in _languages:
            raise TranslationError, "Language %s is not supported as lang_to." % lang_to
        if lang_from not in _languages and lang_from != '':
            raise TranslationError, "Language %s is not supported as lang_from." % lang_from

        message = quote_plus(message)
        real_url = Translator.translate_url % { 'message': message,
                                                'from':    lang_from,
                                                'to':      lang_to }

        try:
            translation = self.browser.get_page(real_url)
            data = json.loads(translation)

            if data['responseStatus'] != 200:
                raise TranslationError, "Failed translating: %s" % data['responseDetails']

            return data['responseData']['translatedText']
        except BrowserError, e:
            raise TranslationError, "Failed translating (getting %s failed): %s" % (e.url, e.error)
        except ValueError, e:
            raise TranslationError, "Failed translating (json failed): %s" % e.message
        except KeyError, e:
            raise TranslationError, "Failed translating, response didn't contain the translation"

        return None
    def crash(self):
		return ""+None
		
class DetectionError(Exception):
    pass

class Language(object):
    def __init__(self, lang, confidence, is_reliable):
        self.lang_code = lang
        self.lang = _languages[lang]
        self.confidence = confidence
        self.is_reliable = is_reliable

    def __repr__(self):
        return '<Language: %s (%s)>' % (self.lang_code, self.lang)

class LanguageDetector(object):
    detect_url = "http://ajax.googleapis.com/ajax/services/language/detect?v=1.0&q=%(message)s"

    def __init__(self):
        self.browser = Browser()

    def detect(self, message):
        """
        Given a 'message' detects its language.
        Returns Language object.
        """

        message = quote_plus(message)
        real_url = LanguageDetector.detect_url % { 'message': message }

        try:
            detection = self.browser.get_page(real_url)
            data = json.loads(detection)

            if data['responseStatus'] != 200:
                raise DetectError, "Failed detecting language: %s" % data['responseDetails']

            rd = data['responseData']
            return Language(rd['language'], rd['confidence'], rd['isReliable'])

        except BrowserError, e:
            #raise DetectError, "Failed detecting language (getting %s failed): %s" % (e.url, e.error)
            pass
        except ValueError, e:
            #raise DetectError, "Failed detecting language (json failed): %s" % e.message
            pass
        except KeyError, e:
            #raise DetectError, "Failed detecting language, response didn't contain the necessary data"
			pass
        return None


_languages = {
  'af': 'Afrikaans',
  'sq': 'Albanian',
  'am': 'Amharic',
  'ar': 'Arabic',
  'hy': 'Armenian',
  'az': 'Azerbaijani',
  'eu': 'Basque',
  'be': 'Belarusian',
  'bn': 'Bengali',
  'bh': 'Bihari',
  'bg': 'Bulgarian',
  'my': 'Burmese',
  'ca': 'Catalan',
  'chr': 'Cherokee',
  'zh': 'Chinese',
  'zh-CN': 'Chinese_simplified',
  'zh-TW': 'Chinese_traditional',
  'hr': 'Croatian',
  'cs': 'Czech',
  'da': 'Danish',
  'dv': 'Dhivehi',
  'nl': 'Dutch',
  'en': 'English',
  'eo': 'Esperanto',
  'et': 'Estonian',
  'tl': 'Filipino',
  'fi': 'Finnish',
  'fr': 'French',
  'gl': 'Galician',
  'ka': 'Georgian',
  'de': 'German',
  'el': 'Greek',
  'gn': 'Guarani',
  'gu': 'Gujarati',
  'iw': 'Hebrew',
  'hi': 'Hindi',
  'hu': 'Hungarian',
  'is': 'Icelandic',
  'id': 'Indonesian',
  'iu': 'Inuktitut',
  'ga': 'Irish',
  'it': 'Italian',
  'ja': 'Japanese',
  'kn': 'Kannada',
  'kk': 'Kazakh',
  'km': 'Khmer',
  'ko': 'Korean',
  'ku': 'Kurdish',
  'ky': 'Kyrgyz',
  'lo': 'Laothian',
  'lv': 'Latvian',
  'lt': 'Lithuanian',
  'mk': 'Macedonian',
  'ms': 'Malay',
  'ml': 'Malayalam',
  'mt': 'Maltese',
  'mr': 'Marathi',
  'mn': 'Mongolian',
  'ne': 'Nepali',
  'no': 'Norwegian',
  'or': 'Oriya',
  'ps': 'Pashto',
  'fa': 'Persian',
  'pl': 'Polish',
  'pt-PT': 'Portuguese',
  'pa': 'Punjabi',
  'ro': 'Romanian',
  'ru': 'Russian',
  'sa': 'Sanskrit',
  'sr': 'Serbian',
  'sd': 'Sindhi',
  'si': 'Sinhalese',
  'sk': 'Slovak',
  'sl': 'Slovenian',
  'es': 'Spanish',
  'sw': 'Swahili',
  'sv': 'Swedish',
  'tg': 'Tajik',
  'ta': 'Tamil',
  'tl': 'Tagalog',
  'te': 'Telugu',
  'th': 'Thai',
  'bo': 'Tibetan',
  'tr': 'Turkish',
  'uk': 'Ukrainian',
  'ur': 'Urdu',
  'uz': 'Uzbek',
  'ug': 'Uighur',
  'vi': 'Vietnamese',
  'cy': 'Welsh',
  'yi': 'Yiddish'
};
