Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
module MicrosoftCognitiveTranslator
open System
open System.Net
open System.Net.Http
open System.Web
type Translator() =
let AsyncGetAccessToken () =
let CognitiveServicesAccountKey = "<your cognitive services key>" // see portal.azure.com
let ServiceUrl = new System.Uri("https://api.cognitive.microsoft.com/sts/v1.0/issueToken")
async {
let client = new HttpClient()
let request = new HttpRequestMessage()
request.Method <- HttpMethod.Post
request.RequestUri <- ServiceUrl
request.Content <- new StringContent("")
request.Headers.TryAddWithoutValidation("Ocp-Apim-Subscription-Key", CognitiveServicesAccountKey) |> ignore
use! response = Async.AwaitTask <| client.SendAsync(request)
response.EnsureSuccessStatusCode() |> ignore
let! token = Async.AwaitTask <| response.Content.ReadAsStringAsync()
return token
}
let Authtoken = AsyncGetAccessToken() |> Async.RunSynchronously
// track how many bytes we translate
let mutable BytesTranslated = 0
member this.Translate(text : string, fromLanguageCode, toLanguageCode) =
let encoded = HttpUtility.UrlEncode(text)
let uri = sprintf "https://api.microsofttranslator.com/v2/http.svc/Translate?text=%s&from=%s&to=%s&appid=Bearer%%20%s" encoded fromLanguageCode toLanguageCode Authtoken
let httpWebRequest = WebRequest.Create(uri) :?> HttpWebRequest
try
let response = httpWebRequest.GetResponse()
let stream = response.GetResponseStream()
let dcs = new System.Runtime.Serialization.DataContractSerializer(Type.GetType("System.String"))
let translation = dcs.ReadObject stream :?> string
BytesTranslated <- BytesTranslated + text.Length
translation
with | _ -> Unchecked.defaultof<string>
@aeshirey

This comment has been minimized.

Copy link
Owner Author

aeshirey commented Feb 6, 2017

An approximate translation from the C# code I was using in one of my projects. FWIW, the C# is twice as many LOC.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.