Skip to content

Instantly share code, notes, and snippets.

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
let ServiceUrl = new System.Uri("")
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 "" encoded fromLanguageCode toLanguageCode Authtoken
let httpWebRequest = WebRequest.Create(uri) :?> HttpWebRequest
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
with | _ -> Unchecked.defaultof<string>

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.