Commits

Jason R. Coombs committed ff90150

Adding initial implementation

Comments (0)

Files changed (5)

jaraco/__init__.py

+__import__("pkg_resources").declare_namespace(__name__)

jaraco/translate/__init__.py

Empty file added.

jaraco/translate/google.py

+
+import json
+import urllib
+import urllib2
+
+def translate(text, target_lang='en', source_lang=None):
+	"""
+	Use the Google v2 API to translate the text. You had better have set
+	the API key on this function before calling it.
+	"""
+	url_base = 'https://www.googleapis.com/language/translate/v2'
+	params = dict(
+		key = translate.API_KEY,
+		q = text,
+		target = target_lang,
+	)
+	if source_lang:
+		params['source'] = source_lang
+	u = urllib2.urlopen(url_base + '?' + urllib.urlencode(params))
+	return json.loads(u.read())['data']['translations']['translatedText']

jaraco/translate/pmxbot.py

+from . import google
+from pmxbot.botbase import command
+
+@command("translate", aliases=('trans', 'googletrans', 'googletranslate'),
+	doc="Translate a phrase using Google Translate. First argument should be "
+		"the language[s]. It is a 2 letter abbreviation. It will auto detect "
+		"the orig lang if you only give one; or two languages joined by a |, "
+		"for example 'en|de' to trans from English to German. Follow this by "
+		"the phrase you want to translate.")
+def translate(client, event, channel, nick, rest):
+	rest = rest.strip()
+	langpair, _, rest = rest.partition(' ')
+	source_lang, _, target_lang = langpair.rpartition('|')
+	return google.translate(rest.encode('utf-8'), target_lang, source_lang)
+
+def test_translate(self):
+	"""
+	The translate function should be able to translate a simple string.
+	"""
+	query = '|en que no desea la nueva pregunta'
+	res = translate(c, e, '#test', 'testrunner', query)
+	assert 'new question' in res.lower()
+	query = 'es|en que no desea la nueva pregunta'
+	res = translate(c, e, '#test', 'testrunner', query)
+	assert 'new question' in res.lower()
+
+def test_translate_invalid_lang(self):
+	"""
+	An invalid language should give a nice error message.
+	"""
+	# sp is not a language
+	invalid_query = 'sp|en que no desea la nueva pregunta'
+	res = translate(c, e, '#test', 'testrunner', invalid_query)
+	assert 'are you sure' in res.lower()
+#!/usr/bin/env python
+# Generated by jaraco.develop (https://bitbucket.org/jaraco/jaraco.develop)
+import setuptools
+
+setup_params = dict(
+	name='jaraco.translate',
+	use_hg_version=True,
+	author="Jason R. Coombs",
+	author_email="jaraco@jaraco.com",
+	url="https://bitbucket.org/jaraco/jaraco.translate",
+	packages=setuptools.find_packages(),
+	namespace_packages=['jaraco'],
+	zip_safe=False,
+	setup_requires=[
+		'hgtools',
+	],
+	entry_points = dict(
+		pmxbot_handlers = [
+			'jaraco.translate = jaraco.translate.pmxbot',
+		],
+	),
+)
+if __name__ == '__main__':
+	setuptools.setup(**setup_params)