-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathtranslate.py
33 lines (24 loc) · 886 Bytes
/
translate.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import uuid
import requests
class Translator(object):
def __init__(self):
self.key = '6e5021f027974f9dbaebb4b39c3afcf3'
def translate(self, text, to_lang):
base_url = 'https://api.cognitive.microsofttranslator.com'
path = '/translate?api-version=3.0'
params = '&to=' + to_lang
constructed_url = base_url + path + params
headers = {
'Ocp-Apim-Subscription-Key': self.key,
'Content-type': 'application/json',
'X-ClientTraceId': str(uuid.uuid4())
}
body = [{
'text': text
}]
request = requests.post(constructed_url, headers=headers, json=body)
if request.status_code == requests.codes.ok:
request.encoding = 'utf-8'
return request.json()
else:
raise Exception('Failed to obtain translation')