Google Translate

From PostgreSQL wiki
Jump to navigationJump to search

Library Snippets

Translate strings using Google Translate

Works with PostgreSQL

Any version

Written in

PL/PythonU

Depends on

python-simplejson

This function translates a string using the Google Translate service.

CREATE OR REPLACE FUNCTION gtranslate(src text, target text, phrase text) RETURNS text
LANGUAGE plpythonu
AS $$
import re
import urllib

import simplejson as json

class UrlOpener(urllib.FancyURLopener):
        version = "py-gtranslate/1.0"

base_uri = "http://ajax.googleapis.com/ajax/services/language/translate"
default_params = {'v': '1.0'}

def translate(src, to, phrase):
        args = default_params.copy()
        args.update({
                'langpair': '%s%%7C%s' % (src, to),
                'q': urllib.quote_plus(phrase),
        })
        argstring = '%s' % ('&'.join(['%s=%s' % (k,v) for (k,v) in args.iteritems()]))
        resp = json.load(UrlOpener().open('%s?%s' % (base_uri, argstring)))
        try:
                return resp['responseData']['translatedText']
        except:
                # should probably warn about failed translation
                return phrase

return translate(src, target, phrase)
$$;

The code was originally derived from the code provided at http://code.google.com/p/py-gtranslate .

Example:

SELECT gtranslate('de', 'en', 'Die Würde des Menschen ist unantastbar. Sie zu achten und zu schützen ist Verpflichtung aller staatlichen Gewalt.');
                                            gtranslate
--------------------------------------------------------------------------------------------------
 Human dignity is inviolable. To respect and protect it shall be the duty of all state authority.
(1 row)

(from the constitution of the Federal Republic of Germany)