Permalink
Please sign in to comment.
Showing
with
85 additions
and 0 deletions.
- +21 −0 README.md
- +53 −0 bingtrans/__init__.py
- BIN bingtrans/__init__.pyc
- +11 −0 setup.py
21
README.md
@@ -0,0 +1,21 @@ | ||
+Bingtrans | ||
+========= | ||
+ | ||
+Bingtrans is a Python library for interfacing with Microsoft Translate API. | ||
+ | ||
+#Wikipydia is licensed under the [Apache Licence, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0.html) | ||
+ | ||
+Features | ||
+-------- | ||
+ | ||
+Bingtrans can: | ||
+ | ||
+- translate a text or html file in a language into another language | ||
+ | ||
+Install | ||
+------- | ||
+ | ||
+python ./setup.py install | ||
+ | ||
+ | ||
+Byung Gyu Ahn <<bahn@cs.jhu.edu>> |
@@ -0,0 +1,53 @@ | ||
+""" | ||
+Interface to Microsoft Translator API | ||
+""" | ||
+import urllib | ||
+import codecs | ||
+import json | ||
+ | ||
+api_url = "http://api.microsofttranslator.com/V2/Ajax.svc/Translate" | ||
+app_id = '' | ||
+ | ||
+def _unicode_urlencode(params): | ||
+ """ | ||
+ A unicode aware version of urllib.urlencode. | ||
+ Borrowed from pyfacebook :: http://github.com/sciyoshi/pyfacebook/ | ||
+ """ | ||
+ if isinstance(params, dict): | ||
+ params = params.items() | ||
+ return urllib.urlencode([(k, isinstance(v, unicode) and v.encode('utf-8') or v) for k, v in params]) | ||
+ | ||
+def _run_query(args): | ||
+ """ | ||
+ takes arguments and optional language argument and runs query on server | ||
+ """ | ||
+ data = _unicode_urlencode(args) | ||
+ sock = urllib.urlopen(api_url + '?' + data) | ||
+ result = sock.read() | ||
+ if result.startswith(codecs.BOM_UTF8): | ||
+ result = result.lstrip(codecs.BOM_UTF8).decode('utf-8') | ||
+ elif result.startswith(codecs.BOM_UTF16_LE): | ||
+ result = result.lstrip(codecs.BOM_UTF16_LE).decode('utf-16-le') | ||
+ elif result.startswith(codecs.BOM_UTF16_BE): | ||
+ result = result.lstrip(codecs.BOM_UTF16_BE).decode('utf-16-be') | ||
+ return json.loads(result) | ||
+ | ||
+def set_app_id(new_app_id): | ||
+ global app_id | ||
+ app_id = new_app_id | ||
+ | ||
+def translate(text, source, target, html=False): | ||
+ """ | ||
+ action=opensearch | ||
+ """ | ||
+ if not app_id: | ||
+ raise ValueError("AppId needs to be set by set_app_id") | ||
+ query_args = { | ||
+ 'appId': app_id, | ||
+ 'text': text, | ||
+ 'from': source, | ||
+ 'to': target, | ||
+ 'contentType': 'text/plain' if not html else 'text/html', | ||
+ 'category': 'general' | ||
+ } | ||
+ return _run_query(query_args) |
Binary file not shown.
11
setup.py
@@ -0,0 +1,11 @@ | ||
+#!/usr/bin/env python | ||
+ | ||
+from distutils.core import setup | ||
+ | ||
+setup(name='bingtrans', | ||
+ version='0.1', | ||
+ description='Python Client Library for the Microsoft Translate API', | ||
+ author='Byung Gyu Ahn', | ||
+ author_email='bahn@cs.jhu.edu', | ||
+ url='http://github.com/bahn/bingtrans', | ||
+ packages=['bingtrans']) |
0 comments on commit
41e04fd