BookmarkSubscribeRSS Feed
FriedEgg
SAS Employee

I was inspired to post this by status message, a link to many translations of Merry Christmas.  The below code will let you use Microsoft's translation service api to translate a given text from one language to another.

/*Sign up for the Bing Translator, 2million characters/month of free translating!*/

%let client_id=<<Your Client ID>>;

%let client_secret=<<Your Client Secret>>;

%let text=Merry Christmas;

%let from=en; /*English*/

%let to=es; /*Spanish*/

/*Link to language codes: http://msdn.microsoft.com/en-us/library/hh456380.aspx*/

filename ivy "%sysfunc(pathname(work,l))/ivy.jar";

proc http

   method = "get"

   url    = "http://central.maven.org/maven2/org/apache/ivy/ivy/2.3.0-rc1/ivy-2.3.0-rc1.jar"

   out    = ivy;

run;

filename cp  temp;

proc groovy classpath=cp;

   add classpath=ivy;

   add sasjar="groovy_2.1.3" version="2.1.3.0_SAS_20130517000930";

   submit parseonly;

@Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.7')

import groovy.json.JsonSlurper

import groovyx.net.http.HTTPBuilder

import static groovyx.net.http.ContentType.JSON

import static groovyx.net.http.ContentType.XML

import static groovyx.net.http.Method.GET

import static groovyx.net.http.Method.POST

class TranslateApi {

    def client_id

    def client_secret

    def scope = "http://api.microsofttranslator.com"

    def grant_type = "client_credentials"

    def translate(text, from, to){

        def token = getToken()

        def http = new HTTPBuilder("http://api.microsofttranslator.com/v2/Http.svc/Translate?text=" + java.net.URLEncoder.encode(text) + "&from=" + from + "&to=" + to)

        def translate = ""

        http.request(GET, XML) { req ->

            headers."Authorization" = "Bearer " + token

            response.failure = { resp ->

                println "Unexpected error:"

                resp.headers.each { println "${it.name} : ${it.value}" }

            }

            response.success = { resp, xml ->

                resp.headers.each { println "${it.name} : ${it.value}" }

                translate = xml.toString()

            }

        }

        return translate

    }

    private getToken(){

        def http = new HTTPBuilder("https://datamarket.accesscontrol.windows.net/v2/OAuth2-13")

        def token

        http.request(POST, JSON) { req ->

            headers."Content-Type" = "application/x-www-form-urlencoded;charset=UTF-8"

            body = "grant_type=${grant_type}&client_id=${client_id}&client_secret=${client_secret}&scope=${scope}"

            response.failure = { resp, json ->

                println "Unexpected error:"

                resp.headers.each { println "---> ${it.name} : ${it.value}" }

                println "---> " + json

            }

            response.success = { resp, json ->

                token = json.access_token

            }

        }

        return token

    }

}

   endsubmit;

   submit "&client_id" "&client_secret" "&text" "&from" "&to";

      x = new TranslateApi()

      x.client_id = args[0]

      x.client_secret = args[1]

      y = x.translate(args[2], args[3], args[4])

      println y

      exports.translated_text = y

   endsubmit;

quit;

%put &translated_text;

/*Feliz Navidad*/

Link to Gist: Utilize the Bing/Microsoft Translator API for Multi-Language Translating of text in SAS using PROC G...

6 REPLIES 6
MichelleHomes
Meteorite | Level 14

In the words of Austin Powers... Groooooovy! Smiley Happy

Pleased to hear my status update gave you inspiration... I wasn't sure if people saw them. 🙂

Hope you have a festive season and SAS community members.

Kind Regards,

Michelle

//Contact me to learn how Metacoda software can help keep your SAS platform secure - https://www.metacoda.com
William
Calcite | Level 5

Hello FriedEgg,

I am new to proc groovy. So I just copied your script (except client_id and client_secret), and submitted it in SAS 9.4 (Win7 x64), but it complained some errors (log attached below), do you have any suggestion how to fix it?

thanks, William

...

NOTE: The SUBMIT command completed.

87

88

89      submit "&client_id" "&client_secret" "&text" "&from" "&to";

90         x = new TranslateApi()

91         x.client_id = args[0]

92         x.client_secret = args[1]

93         y = x.translate(args[2], args[3], args[4])

94         println y

95         exports.translated_text = y

96      endsubmit;

NOTE: Exporting macro variable "translated_text".

Unexpected error:

---> Cache-Control : private

---> Content-Type : application/json; charset=utf-8

---> x-ms-request-id : 73728b3e-16d9-436d-a5e7-b17481719ca4

---> request-id : 73728b3e-16d9-436d-a5e7-b17481719ca4

---> X-Content-Type-Options : nosniff

---> Strict-Transport-Security : max-age=31536000; includeSubDomains

---> Date : Fri, 26 Dec 2014 02:00:46 GMT

---> Content-Length : 222

---> [error:invalid_client, error_description:ACS50012: Authentication failed.

Trace ID: 73728b3e-16d9-436d-a5e7-b17481719ca4

Correlation ID: c6e16c29-c5c3-4524-9834-dd0470ff8c14

Timestamp: 2014-12-26 02:00:47Z]

Unexpected error:

Content-Length : 291

Content-Type : text/html; charset=utf-8

X-MS-Trans-Info : 6346.V2_Rest.Translate.39974939

Date : Fri, 26 Dec 2014 02:00:46 GMT

NOTE: The SUBMIT command completed.

FriedEgg
SAS Employee

Make sure you replaced the client_id and client_secret with valid values for your Microsoft account and that you signed up for the translate service.  It is a authentication error with Microsoft.

---> [error:invalid_client, error_description:ACS50012: Authentication failed.


Also, try to urlencode your id and secret for example:


%let client_id=%sysfunc(urlencode(f0wdf9sidf092i34234ijetrikje));

%let client_secret=%sysfunc(urlencode(sg092i34234=sdfs=-32r2/f/sdfw3er2039rjsfdf));


William
Calcite | Level 5

FriedEgg, you are awesome! Yes, it was a error in client_secret. After using function urlencode, it works now.

ankur_12
Calcite | Level 5

I need a little help on the code. When I executed I got the following error. Can anybody help how to resolve this? No Authentication error.

proc http

7012          method = "get"

7013          url    = "http://central.maven.org/maven2/org/apache/ivy/ivy/2.3.0-rc1/ivy-2.3.0-rc1.jar"

7014          out    = ivy;

7015       run;

ERROR: java.net.ConnectException: Connection timed out: connect

NOTE: PROCEDURE HTTP used (Total process time):

      real time           21.05 seconds

      cpu time            0.00 seconds

     

NOTE: The SAS System stopped processing this step because of errors.

7016      

7017       filename cp  temp;

NOTE: PROCEDURE GROOVY used (Total process time):

      real time           0.00 seconds

      cpu time            0.00 seconds

     

ERROR: PROC GROOVY is disabled when -noxcmd is specified.

NOTE: The SAS System stopped processing this step because of errors.

7018       proc groovy classpath=cp;

7019      

7020          add classpath=ivy;

FriedEgg
SAS Employee

You have two distinct, but also related, issues.  Your site's security it too strict to allow this program to run.

ERROR: java.net.ConnectException: Connection timed out: connect

This is most likely caused by your site requiring a proxy to access the open internet.  You can do this by using the options available in PROC HTTP:


proc http

   method = "get"

   url    = "http://central.maven.org/maven2/org/apache/ivy/ivy/2.3.0-rc1/ivy-2.3.0-rc1.jar"

   out    = ivy

   /* proxyhost="http://yourproxy.company.com" */

   ;

run;

You may also need to define a username/password for the proxy.

ERROR: PROC GROOVY is disabled when -noxcmd is specified.

This one means that your SAS installation site has purposefully disabled this PROC as well as all other statements and functions that enable OS access.  You would have to speak with your site's SAS administrator(s) about this.

sas-innovate-2024.png

Don't miss out on SAS Innovate - Register now for the FREE Livestream!

Can't make it to Vegas? No problem! Watch our general sessions LIVE or on-demand starting April 17th. Hear from SAS execs, best-selling author Adam Grant, Hot Ones host Sean Evans, top tech journalist Kara Swisher, AI expert Cassie Kozyrkov, and the mind-blowing dance crew iLuminate! Plus, get access to over 20 breakout sessions.

 

Register now!

What is Bayesian Analysis?

Learn the difference between classical and Bayesian statistical approaches and see a few PROC examples to perform Bayesian analysis in this video.

Find more tutorials on the SAS Users YouTube channel.

Click image to register for webinarClick image to register for webinar

Classroom Training Available!

Select SAS Training centers are offering in-person courses. View upcoming courses for:

View all other training opportunities.

Discussion stats
  • 6 replies
  • 2011 views
  • 2 likes
  • 4 in conversation