E. Opel
E. Opel

Reputation: 27

Get Multiple Translations using Microsoft Translator API

I would like to get multiple poosible translations for a given word using the /getTranslations method from the Microsoft Translator API according to the API reference. Unfortunately, the provided example on github is outdated: Outdated Example. I did manage to update the getTokens function and references to it, and I did get a translation back, but I need multiple.

Does anyone have a working example/know a fix to my code?

Here is my code:

<?php
class AccessTokenAuthentication {
    /*
     * Get the access token.
     *
     * @param string $grantType    Grant type.
     * @param string $scopeUrl     Application Scope URL.
     * @param string $clientID     Application client ID.
     * @param string $clientSecret Application client ID.
     * @param string $authUrl      Oauth Url.
     *
     * @return string.
     */
function getToken($azure_key)
{
    $url = 'https://api.cognitive.microsoft.com/sts/v1.0/issueToken';
    $ch = curl_init();
    $data_string = json_encode('{body}');
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json',
            'Content-Length: ' . strlen($data_string),
            'Ocp-Apim-Subscription-Key: ' . $azure_key
        )
    );
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    $strResponse = curl_exec($ch);
    curl_close($ch);
    return $strResponse;
}
}
/*
 * Class:HTTPTranslator
 *
 * Processing the translator request.
 */
Class HTTPTranslator {
    /*
     * Create and execute the HTTP CURL request.
     *
     * @param string $url        HTTP Url.
     * @param string $authHeader Authorization Header string.
     *
     * @return string.
     *
     */
    function curlRequest($url, $authHeader) {
        //Initialize the Curl Session.
        $ch = curl_init();
        //Set the Curl url.
        curl_setopt ($ch, CURLOPT_URL, $url);
        //Set the HTTP HEADER Fields.
        curl_setopt ($ch, CURLOPT_HTTPHEADER, array($authHeader,"Content-Type: text/xml", 'Content-Length: 0'));
        //CURLOPT_RETURNTRANSFER- TRUE to return the transfer as a string of the return value of curl_exec().
        curl_setopt ($ch, CURLOPT_RETURNTRANSFER, TRUE);
        //CURLOPT_SSL_VERIFYPEER- Set FALSE to stop cURL from verifying the peer's certificate.
        curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, False);
        //Set HTTP POST Request.
        curl_setopt($ch, CURLOPT_POST, TRUE);
        //Execute the  cURL session.
        $curlResponse = curl_exec($ch);
        //Get the Error Code returned by Curl.
        $curlErrno = curl_errno($ch);
        if ($curlErrno) {
            $curlError = curl_error($ch);
            throw new Exception($curlError);
        }
        //Close a cURL session.
        curl_close($ch);
        return $curlResponse;
    }
}
try {
    //Azure Key
    $azure_key      = "<my key>";
    //Client ID of the application.
    //$clientID       = "clientId";
    //Client Secret key of the application.
    //$clientSecret = "ClientSecret";
    //OAuth Url.
    $authUrl      = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13/";
    //Application Scope Url
    //$scopeUrl     = "http://api.microsofttranslator.com";
    //Application grant type
    //$grantType    = "client_credentials";
    //Create the AccessTokenAuthentication object.
    $authObj      = new AccessTokenAuthentication();
    //Get the Access token.
    $accessToken  = $authObj->getToken($azure_key);
    //Create the authorization Header string.
    $authHeader = "Authorization: Bearer ". $accessToken;
    //Set the Params.
    $inputStr        = "get";
    $fromLanguage   = "en";
    $toLanguage        = "de";
    //$user            = 'TestUser';
    $category       = "general";
    //$uri             = null;
    $contentType    = "text/plain";
    $maxTranslation = 5;
    //Create the string for passing the values through GET method.
    $params = "from=$fromLanguage".
                "&to=$toLanguage".
                "&maxTranslations=$maxTranslation".
                "&text=".urlencode($inputStr).
                //"&user=$user".
                //"&uri=$uri".
                "&contentType=$contentType";
    //HTTP getTranslationsMethod URL.
    $getTranslationUrl = "http://api.microsofttranslator.com/V2/Http.svc/GetTranslations?$params";
    //Create the Translator Object.
    $translatorObj = new HTTPTranslator();
    //Call the curlRequest.
    $curlResponse = $translatorObj->curlRequest($getTranslationUrl, $authHeader);
    //Interprets a string of XML into an object.
    $xmlObj = simplexml_load_string($curlResponse);
    $translationObj = $xmlObj->Translations;
    $translationMatchArr = $translationObj->TranslationMatch;
    print_r($translationMatchArr);
    echo "Get Translation For <b>$inputStr</b>";
    echo "<table border ='2px'>";
    echo "<tr><td><b>Count</b></td><td><b>MatchDegree</b></td>
        <td><b>Rating</b></td><td><b>TranslatedText</b></td></tr>";
    foreach($translationMatchArr as $translationMatch) {
        echo "<tr><td>$translationMatch->Count</td><td>$translationMatch->MatchDegree</td><td>$translationMatch->Rating</td>
            <td>$translationMatch->TranslatedText</td></tr>";
    }
    echo "</table></br>";
} catch (Exception $e) {
    echo "Exception: " . $e->getMessage() . PHP_EOL;
}

Upvotes: 1

Views: 471

Answers (2)

Sober
Sober

Reputation: 11

I solved the problem this way: (IncludeMultipleMTAlternatives mast be first in options section)

<GetTranslationsArrayRequest>
  <AppId></AppId>
  <From>en</From>
  <Options>
    <IncludeMultipleMTAlternatives xmlns="http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2">true</IncludeMultipleMTAlternatives>
    <State xmlns="http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2">777</State>
  </Options>
  <Texts>
  	<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays">world</string>
  	<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays">sun</string>
  </Texts>
  <To>ru</To>
  <MaxTranslations>10</MaxTranslations>
</GetTranslationsArrayRequest>

Upvotes: 1

Chris Wendt
Chris Wendt

Reputation: 571

The GetTranslations() and GetTranslationsArray() methods in the V2 API of Microsoft Translator include an optional Boolean flag "IncludeMultipleMTAlternatives". The method will return up to maxTranslations alternatives, even if there are not as many CTF entries available, where the delta is supplied from the n-best list of the translator engine. The machine-generated alternatives are returned with a rating of 0. The human-curated alternatives will have a rating of 1 or higher.

Upvotes: 0

Related Questions