Skip to content

Commit

Permalink
first commit
Browse files Browse the repository at this point in the history
  • Loading branch information
U-REDMOND\t-byahn committed Jun 10, 2011
0 parents commit 41e04fd
Show file tree
Hide file tree
Showing 4 changed files with 85 additions and 0 deletions.
21 changes: 21 additions & 0 deletions 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>>
53 changes: 53 additions & 0 deletions bingtrans/__init__.py
@@ -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 added bingtrans/__init__.pyc
Binary file not shown.
11 changes: 11 additions & 0 deletions 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

Please sign in to comment.