osc/research/ms-acs/service/translator_client.py

30 lines
973 B
Python
Raw Normal View History

2025-05-28 19:16:17 +08:00
import requests, uuid, json
from settings import TRANSLATION_API_KEY, TRANSLATION_TEXT_ENDPOINT, TRANSLATION_SERVICE_LOCATION
path = '/translate'
constructed_url = TRANSLATION_TEXT_ENDPOINT + path
headers = {
'Ocp-Apim-Subscription-Key': TRANSLATION_API_KEY,
# location required if you're using a multi-service or regional (not global) resource.
'Ocp-Apim-Subscription-Region': TRANSLATION_SERVICE_LOCATION,
'Content-type': 'application/json',
'X-ClientTraceId': str(uuid.uuid4())
}
def get_translation(text, to_language):
params = {
'api-version': '3.0',
'from': 'en',
'to': to_language
}
# You can pass more than one object in body.
body = [{'text': text_item} for text_item in text]
request = requests.post(constructed_url, params=params, headers=headers, json=body)
response = request.json()
return json.dumps(response, sort_keys=True, ensure_ascii=False, indent=4, separators=(',', ': '))