aga
aga

Reputation: 29416

Microsoft Translator API in Python

I wrote small script in python to translate words from English to Russian language. It uses the Microsoft-Translator-Python-API for connection to Microsoft Translator API. However, there is a problem of delay - it takes up to three seconds to call API and get translation. Does anybody know the way to make it work faster if it's possible? I'll put piece of my code, just to show what am I doing here:

translator   = Translator('My-User-Id',
                            'My-Client-Secret')

current_word = subprocess.check_output(["xsel", "-o"])
translation  = translator.translate(current_word, "ru")

Upvotes: 3

Views: 7572

Answers (2)

Neeraj
Neeraj

Reputation: 8532

Shameless plug.

I have created a python module (its beer-ware :)), to make this process much simpler.

Using it is as simple as:

import azure_translate_api

client = azure_translate_api.MicrosoftTranslatorClient('client_id', 'client_secret')
print client.TranslateText('Hello World!', 'en', 'fr')

To get more details on where to download this module from and how to use it visit my github repo.

Upvotes: 2

Oren Mazor
Oren Mazor

Reputation: 4477

Interestingly enough, you can actually do this:

import json
import requests
import urllib
args = {
        'client_id': '',#your client id here
        'client_secret': '',#your azure secret here
        'scope': 'http://api.microsofttranslator.com',
        'grant_type': 'client_credentials'
    }
oauth_url = 'https://datamarket.accesscontrol.windows.net/v2/OAuth2-13'
oauth_junk = json.loads(requests.post(oauth_url,data=urllib.urlencode(args)).content)
translation_args = {
        'text': "hello",
        'to': 'ru',
        'from': 'en'
        }
headers={'Authorization': 'Bearer '+oauth_junk['access_token']}
translation_url = 'http://api.microsofttranslator.com/V2/Ajax.svc/Translate?'
translation_result = requests.get(translation_url+urllib.urlencode(translation_args),headers=headers)
print translation_result.content

and get an immediate response a bunch of times before it slows down (6-7 times with immediate response before it slows down). I haven't used Azure that much so I'm not sure how their rate limiting works, but I'm sure you can pay to up that rate.

(note: I grabbed bits of the above code right out of that microsoft library. just wanted to see what the logic alone behaves like)

Upvotes: 6

Related Questions