Saturday, January 13, 2018

Python Scripts to translate using Microsoft

#install additional libraries to add coloured text to output
!pip install termcolor
!pip install bs4
from termcolor import colored
from bs4 import BeautifulSoup
import requests
#Using Python for Text Translation with Microsoft Cognitive Services
# Specify the subscription Key
subscriptionKey = "ENTER YOUR COGNITIVE API KEY"
#Specify URLs for Cognitive Services - Translator Text API
translateUrl = 'https://api.microsofttranslator.com/v2/http.svc/Translate'
cognitiveServiceUrl = 'https://api.cognitive.microsoft.com/sts/v1.0/issueToken'
# Request Access Token
requestHeader = {'Ocp-Apim-Subscription-Key': subscriptionKey}
responseResult = requests.post(cognitiveServiceUrl, headers=requestHeader)
token = responseResult.text
print ("Access Token")
print (token)
# Original Text
text = "Créez des applications intelligentes et stratégiques avec une plateforme de base de données évolutive et hybride qui intègre tout ce qu'il vous faut : performances in-memory et sécurité avancée pour les analyses au sein de la base de données."
print(text)
# Specify source and target language
srcLanguage = "fr"
targetLanguage = "en"
# Define Parameters
params = {'appid': 'Bearer '+token, 'text': text, 'from': srcLanguage, 'to': targetLanguage}
requestHeader = {'Accept': 'application/xml'}
# Invoke Cognitive Services to perform translation
responseResult = requests.get(translateUrl, params=params, headers=requestHeader )
# Show original and target text
print(colored('Original Text\n', 'green'))
print(colored(text,'green'))
print ("\n")
print(colored('Translated Text\n', 'blue'))
soup = BeautifulSoup(responseResult.text,"lxml")
print(colored(soup.get_text(), 'blue'))
 
Or, even easier:
 
# -*- coding: utf-8 -*-

import http.client, urllib.parse

# *** Update or verify the following values. ***

# Replace the subscriptionKey string value with your valid subscription key.
subscriptionKey = 'ENTER KEY HERE'

host = 'api.microsofttranslator.com'
path = '/V2/Http.svc/Translate'

target = 'fr-fr'
text = 'Hello'

params = '?to=' + target + '&text=' + urllib.parse.quote (text)

def get_suggestions ():

    headers = {'Ocp-Apim-Subscription-Key': subscriptionKey}
    conn = http.client.HTTPSConnection(host)
    conn.request ("GET", path + params, None, headers)
    response = conn.getresponse ()
    return response.read ()

result = get_suggestions ()
print (result.decode("utf-8"))

Translate response
A successful response is returned in XML, as shown in the following example:
XML
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">Salut</string>