Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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")
like image 846
aga Avatar asked Sep 18 '26 13:09

aga


1 Answers

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)

like image 153
Oren Mazor Avatar answered Sep 20 '26 04:09

Oren Mazor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!