Пример #1
0
        private string translate(string txtToTranslate, string languageCode)
        {
            try{
                string uri = string.Format("http://api.microsofttranslator.com/v2/Http.svc/Translate?text=" + System.Web.HttpUtility.UrlEncode(txtToTranslate) + "&to={0}", languageCode);

                WebRequest translationWebRequest = WebRequest.Create(uri);

                translationWebRequest.Headers.Add("Authorization", tokenProvider.GetAccessToken()); //header value is the "Bearer plus the token from ADM

                WebResponse response = null;

                response = translationWebRequest.GetResponse();

                Stream stream = response.GetResponseStream();

                Encoding encode = Encoding.GetEncoding("utf-8");

                StreamReader translatedStream = new StreamReader(stream, encode);

                System.Xml.XmlDocument xTranslation = new System.Xml.XmlDocument();

                xTranslation.LoadXml(translatedStream.ReadToEnd());

                String text = xTranslation.InnerText;
                //text = HttpUtility.HtmlEncode(text);
                text = text.Replace("&lt;", "<");
                text = text.Replace("&gt;", ">");
                return(text);
            }
            catch (WebException ex)
            {
                return(txtToTranslate);
            }
        }
 public MainWindow()
 {
     InitializeComponent();
     tokenProvider = new AzureAuthToken(TEXT_TRANSLATION_API_SUBSCRIPTION_KEY);
     GetLanguagesForTranslate();                                           //List of languages that can be translated
     GetLanguageNamesMethod(tokenProvider.GetAccessToken(), friendlyName); //Friendly name of languages that can be translated
     GetLanguagesForSpeakMethod(tokenProvider.GetAccessToken());           //List of languages that have a synthetic voice for text to speech
     enumLanguages();                                                      //Create the drop down list of langauges
 }
Пример #3
0
        public MainWindow()
        {
            InitializeComponent();
            tokenProvider = new AzureAuthToken(TEXT_TRANSLATION_API_SUBSCRIPTION_KEY);
            var languageCodes          = TranslateApi.GetLanguageCodesForTranslate(tokenProvider.GetAccessToken());
            var languageCodesAndTitles = TranslateApi.GetLanguageNamesMethod(tokenProvider.GetAccessToken(), languageCodes);

            //List of languages that have a synthetic voice for text to speech
            speakLanguages = TranslateApi.GetLanguagesForSpeakMethod(tokenProvider.GetAccessToken());
            PopulateLanguagesComboBox(languageCodesAndTitles); //Create the drop down list of langauges
        }
Пример #4
0
        /// <summary>
        /// Check if the Translation service is ready to use, with a valid client ID and secret
        /// </summary>
        /// <returns>true if ready, false if not</returns>
        public static bool IsTranslationServiceReady()
        {
            switch (authMode)
            {
            case AuthMode.Azure:
                try
                {
                    AzureAuthToken authTokenSource = new AzureAuthToken(_ClientID);
                    string         headerValue     = authTokenSource.GetAccessToken();
                }
                catch { return(false); }
                break;

            case AuthMode.AppId:
                try
                {
                    var bind = new BasicHttpBinding {
                        Name = "BasicHttpBinding_LanguageService"
                    };
                    var epa = new EndpointAddress(_EndPointAddress.Replace("https:", "http:") + "/V2/soap.svc");
                    LanguageServiceClient client = new LanguageServiceClient(bind, epa);
                    string[] languages           = new string[1];
                    languages[0] = "en";
                    client.GetLanguageNames(GetHeaderValue(), "en", languages, false);
                }
                catch { return(false); }
                break;

            default:
                return(false);
            }
            return(true);
        }
        /// <summary>
        /// Breaks a piece of text into sentences and returns an array containing the lengths in each sentence.
        /// </summary>
        /// <param name="text">The text to analyze and break.</param>
        /// <param name="languageID">The language identifier to use.</param>
        /// <returns>An array of integers representing the lengths of the sentences. The length of the array is the number of sentences, and the values are the length of each sentence.</returns>
        public static int[] BreakSentences(string text, string languageID)
        {
            var bind = new BasicHttpBinding
            {
                Name                   = "BasicHttpBinding_LanguageService",
                OpenTimeout            = TimeSpan.FromMinutes(5),
                CloseTimeout           = TimeSpan.FromMinutes(5),
                ReceiveTimeout         = TimeSpan.FromMinutes(5),
                MaxReceivedMessageSize = int.MaxValue,
                MaxBufferPoolSize      = int.MaxValue,
                MaxBufferSize          = int.MaxValue,
                Security               =
                    new BasicHttpSecurity {
                    Mode = BasicHttpSecurityMode.Transport
                }
            };

            var epa = new EndpointAddress("https://api.microsofttranslator.com/V2/soap.svc");

            TranslatorService.LanguageServiceClient client = new LanguageServiceClient(bind, epa);
            AzureAuthToken authTokenSource = new AzureAuthToken(_ClientID);
            string         headerValue     = authTokenSource.GetAccessToken();

            return(client.BreakSentences(headerValue, text, languageID));
        }
        /// <summary>
        /// Call once to initialize the static variables
        /// </summary>
        public static void Initialize()
        {
            LoadCredentials();
            if (!IsTranslationServiceReady())
            {
                return;
            }
            var bind = new BasicHttpBinding {
                Name = "BasicHttpBinding_LanguageService"
            };
            var epa = new EndpointAddress("http://api.microsofttranslator.com/V2/soap.svc");
            LanguageServiceClient client          = new LanguageServiceClient(bind, epa);
            AzureAuthToken        authTokenSource = new AzureAuthToken(_ClientID);
            string headerValue = authTokenSource.GetAccessToken();

            string[] languages     = client.GetLanguagesForTranslate(headerValue);
            string[] languagenames = client.GetLanguageNames(headerValue, "en", languages, false);
            for (int i = 0; i < languages.Length; i++)
            {
                if (!AvailableLanguages.ContainsKey(languages[i]))
                {
                    AvailableLanguages.Add(languages[i], languagenames[i]);
                }
            }
            client.Close();
        }
Пример #7
0
        public void Initialize()
        {
            Uri issueTokenUri = new Uri("https://westeurope.api.cognitive.microsoft.com/sts/v1.0/issuetoken");

            ISubscriptionKeyProvider provider = new SubscriptionKeyEnviromentVariableProvider("SpeechServiceSubscriptionKey");
            var auth = new AzureAuthToken(provider, issueTokenUri);

            _accessToken = auth.GetAccessToken();
        }
Пример #8
0
        //*****BUTTON TO START TRANSLATION PROCESS
        private void translateButton_Click(object sender, EventArgs e)
        {
            var languageCode = (string)LanguageComboBox.SelectedValue ?? "en";

            //*****BEGIN CODE TO MAKE THE CALL TO THE TRANSLATOR SERVICE TO PERFORM A TRANSLATION FROM THE USER TEXT ENTERED INCLUDES A CALL TO A SPEECH METHOD*****

            string txtToTranslate = textToTranslate.Text;

            string translatedText = TranslateApi.Translate(tokenProvider.GetAccessToken(), txtToTranslate, languageCode);

            translatedTextLabel.Content = "Translation -->   " + translatedText;

            if (speakLanguages.Contains(languageCode) && txtToTranslate != "")
            {
                //call the method to speak the translated text
                SpeakMethod(tokenProvider.GetAccessToken(), translatedText, languageCode);
            }
        }
        //*****BUTTON TO START TRANSLATION PROCESS
        private void translateButton_Click(object sender, EventArgs e)
        {
            string languageCode;

            languageCodesAndTitles.TryGetValue(LanguageComboBox.Text, out languageCode); //get the language code from the dictionary based on the selection in the combobox

            if (languageCode == null)                                                    //in case no language is selected.
            {
                languageCode = "en";
            }

            //*****BEGIN CODE TO MAKE THE CALL TO THE TRANSLATOR SERVICE TO PERFORM A TRANSLATION FROM THE USER TEXT ENTERED INCLUDES A CALL TO A SPEECH METHOD*****

            string txtToTranslate = textToTranslate.Text;

            string uri = string.Format("http://api.microsofttranslator.com/v2/Http.svc/Translate?text=" + System.Web.HttpUtility.UrlEncode(txtToTranslate) + "&to={0}", languageCode);

            WebRequest translationWebRequest = WebRequest.Create(uri);

            translationWebRequest.Headers.Add("Authorization", tokenProvider.GetAccessToken()); //header value is the "Bearer plus the token from ADM

            WebResponse response = null;

            response = translationWebRequest.GetResponse();

            Stream stream = response.GetResponseStream();

            Encoding encode = Encoding.GetEncoding("utf-8");

            StreamReader translatedStream = new StreamReader(stream, encode);

            System.Xml.XmlDocument xTranslation = new System.Xml.XmlDocument();

            xTranslation.LoadXml(translatedStream.ReadToEnd());

            translatedTextLabel.Content = "Translation -->   " + xTranslation.InnerText;

            if (speakLanguages.Contains(languageCode) && txtToTranslate != "")
            {
                //call the method to speak the translated text
                SpeakMethod(tokenProvider.GetAccessToken(), xTranslation.InnerText, languageCode);
            }
        }
 /// <summary>
 /// Check if the Translation service is ready to use, with a valid client ID and secret
 /// </summary>
 /// <returns>true if ready, false if not</returns>
 public static bool IsTranslationServiceReady()
 {
     try
     {
         AzureAuthToken authTokenSource = new AzureAuthToken(_ClientID);
         string         headerValue     = authTokenSource.GetAccessToken();
     }
     catch { return(false); }
     return(true);
 }
        private static string GetHeaderValue()
        {
            string headerValue = null;

            if (authMode == AuthMode.Azure)
            {
                AzureAuthToken authTokenSource = new AzureAuthToken(_AzureKey, UseAzureGovernment ? AuthServiceUrlGov : AuthServiceUrlPublic);
                headerValue = authTokenSource.GetAccessToken();
            }
            else
            {
                headerValue = appid;
            }
            return(headerValue);
        }
        private static string GetHeaderValue()
        {
            string headerValue = null;

            if (authMode == AuthMode.Azure)
            {
                AzureAuthToken authTokenSource = new AzureAuthToken(_AzureKey);
                headerValue = authTokenSource.GetAccessToken();
            }
            else
            {
                headerValue = appid;
            }
            return(headerValue);
        }
Пример #13
0
        private void TranslateBtn_Clicked(object sender, EventArgs e)
        {
            AzureAuthToken azureAuthToken = new AzureAuthToken("731cf5d466e543409989ce06c9499979");
            var            authToken      = azureAuthToken.GetAccessToken();

            LanguageDetector languageDetector = new LanguageDetector(authToken);
            var lang = languageDetector.Detect(toTranslate.Text);

            Translator translator = new Translator(authToken);
            var        result     = translator.Translate(toTranslate.Text, lang, languagePicker.SelectedItem.ToString());

            translated.Text = result;

            App.Database.SaveItem(new Models.Translation {
                FromLang = languagePicker.SelectedItem.ToString(), ToLang = lang, FromText = toTranslate.Text, ToText = result
            });
        }
        public static UserTranslation[] GetUserTranslations(string fromlanguage, string tolanguage, int skip, int count)
        {
            var bind = new BasicHttpBinding
            {
                Name                   = "BasicHttpBinding_LanguageService",
                OpenTimeout            = TimeSpan.FromMinutes(5),
                CloseTimeout           = TimeSpan.FromMinutes(5),
                ReceiveTimeout         = TimeSpan.FromMinutes(5),
                MaxReceivedMessageSize = int.MaxValue,
                MaxBufferPoolSize      = int.MaxValue,
                MaxBufferSize          = int.MaxValue,
                Security               =
                    new BasicHttpSecurity {
                    Mode = BasicHttpSecurityMode.Transport
                }
            };

            var epa = new EndpointAddress("https://api.microsofttranslator.com/v2/beta/ctfreporting.svc");

            CtfReportingService.CtfReportingServiceClient client = new CtfReportingService.CtfReportingServiceClient(bind, epa);
            AzureAuthToken authTokenSource = new AzureAuthToken(_ClientID);
            string         headerValue     = authTokenSource.GetAccessToken();

            CtfReportingService.UserTranslation[] usertranslations = new CtfReportingService.UserTranslation[count];

            usertranslations = client.GetUserTranslations(headerValue, string.Empty, fromlanguage, tolanguage, 0, 10, string.Empty, string.Empty, DateTime.MinValue, DateTime.MaxValue, skip, count, true);

            UserTranslation[] usertranslationsreturn = new UserTranslation[count];
            usertranslationsreturn.Initialize();

            for (int i = 0; i < usertranslations.Length; i++)
            {
                usertranslationsreturn[i].CreatedDateUtc = usertranslations[i].CreatedDateUtc;
                usertranslationsreturn[i].From           = usertranslations[i].From;
                usertranslationsreturn[i].OriginalText   = usertranslations[i].OriginalText;
                usertranslationsreturn[i].To             = usertranslations[i].To;
                usertranslationsreturn[i].TranslatedText = usertranslations[i].TranslatedText;
                usertranslationsreturn[i].Rating         = usertranslations[i].Rating;
                usertranslationsreturn[i].Uri            = usertranslations[i].Uri;
                usertranslationsreturn[i].User           = usertranslations[i].User;
            }

            return(usertranslationsreturn);
        }
        /// <summary>
        /// Breaks a piece of text into sentences and returns an array containing the lengths in each sentence.
        /// </summary>
        /// <param name="text">The text to analyze and break.</param>
        /// <param name="languageID">The language identifier to use.</param>
        /// <returns>An array of integers representing the lengths of the sentences. The length of the array is the number of sentences, and the values are the length of each sentence.</returns>
        async public static Task <int[]> BreakSentencesAsync(string text, string languageID)
        {
            var bind = new BasicHttpBinding
            {
                Name                   = "BasicHttpBinding_LanguageService",
                OpenTimeout            = TimeSpan.FromMinutes(5),
                CloseTimeout           = TimeSpan.FromMinutes(5),
                ReceiveTimeout         = TimeSpan.FromMinutes(5),
                MaxReceivedMessageSize = int.MaxValue,
                MaxBufferPoolSize      = int.MaxValue,
                MaxBufferSize          = int.MaxValue,
                Security               =
                    new BasicHttpSecurity {
                    Mode = BasicHttpSecurityMode.Transport
                }
            };

            var epa = new EndpointAddress("https://api.microsofttranslator.com/V2/soap.svc");

            TranslatorService.LanguageServiceClient client = new LanguageServiceClient(bind, epa);
            AzureAuthToken authTokenSource = new AzureAuthToken(_ClientID);
            string         headerValue     = authTokenSource.GetAccessToken();

            int[] result = { 0 };
            try
            {
                Task <int[]> BSTask = client.BreakSentencesAsync(headerValue, text, languageID);
                result = await BSTask;
            }
            catch
            {
                for (int i = 1; i <= 10; i++)
                {
                    Thread.Sleep(5000 * i);
                    Task <int[]> BSTask = client.BreakSentencesAsync(headerValue, text, languageID);
                    result = await BSTask;
                }
            }
            return(result);
        }
        /// <summary>
        /// Test if a given category value is a valid category in the system
        /// </summary>
        /// <param name="category">Category ID</param>
        /// <returns>True if the category is valid</returns>
        public static bool IsCategoryValid(string category)
        {
            if (category == string.Empty)
            {
                return(true);
            }
            if (category == "")
            {
                return(true);
            }

            AzureAuthToken authTokenSource = new AzureAuthToken(_ClientID);

            bool returnvalue = true;

            //it may take a while until the category is loaded on server
            for (int i = 0; i < 3; i++)
            {
                try
                {
                    string headerValue = authTokenSource.GetAccessToken();
                    var    bind        = new BasicHttpBinding {
                        Name = "BasicHttpBinding_LanguageService"
                    };
                    var epa = new EndpointAddress("http://api.microsofttranslator.com/V2/soap.svc");
                    LanguageServiceClient client = new LanguageServiceClient(bind, epa);
                    client.Translate(headerValue, "Test", "en", "fr", "text/plain", category);
                    returnvalue = true;
                    break;
                }
                catch {
                    returnvalue = false;
                    Thread.Sleep(1000);
                    continue;
                }
            }
            return(returnvalue);
        }
        /// <summary>
        /// Adds a translation to Microsoft Translator's translation memory.
        /// </summary>
        /// <param name="originalText">Required. A string containing the text to translate from. The string has a maximum length of 1000 characters.</param>
        /// <param name="translatedText">Required. A string containing translated text in the target language. The string has a maximum length of 2000 characters. </param>
        /// <param name="from">Required. A string containing the language code of the source language. Must be a valid culture name. </param>
        /// <param name="to">Required. A string containing the language code of the target language. Must be a valid culture name. </param>
        /// <param name="rating">Optional. An int representing the quality rating for this string. Value between -10 and 10. Defaults to 1. </param>
        /// <param name="user">Required. A string used to track the originator of the submission. </param>
        public static void AddTranslation(string originalText, string translatedText, string from, string to, int rating, string user)
        {
            var bind = new BasicHttpBinding
            {
                Name                   = "BasicHttpBinding_LanguageService",
                OpenTimeout            = TimeSpan.FromMinutes(5),
                CloseTimeout           = TimeSpan.FromMinutes(5),
                ReceiveTimeout         = TimeSpan.FromMinutes(5),
                MaxReceivedMessageSize = int.MaxValue,
                MaxBufferPoolSize      = int.MaxValue,
                MaxBufferSize          = int.MaxValue,
                Security               =
                    new BasicHttpSecurity {
                    Mode = BasicHttpSecurityMode.Transport
                }
            };

            var epa = new EndpointAddress("https://api.microsofttranslator.com/V2/soap.svc");

            TranslatorService.LanguageServiceClient client = new LanguageServiceClient(bind, epa);
            AzureAuthToken authTokenSource = new AzureAuthToken(_ClientID);
            string         headerValue     = authTokenSource.GetAccessToken();

            try
            {
                client.AddTranslation(headerValue, originalText, translatedText, from, to, rating, "text/plain", _CategoryID, user, string.Empty);
            }
            catch
            {
                for (int i = 0; i < 3; i++)
                {
                    Thread.Sleep(500);
                    client.AddTranslation(headerValue, originalText, translatedText, from, to, rating, "text/plain", _CategoryID, user, string.Empty);
                }
            }
            return;
        }
        /// <summary>
        /// Translates an array of strings from the from langauge code to the to language code.
        /// From langauge code can stay empty, in that case the source language is auto-detected, across all elements of the array together.
        /// </summary>
        /// <param name="texts">Array of strings to translate</param>
        /// <param name="from">From language code. May be empty</param>
        /// <param name="to">To language code. Must be a valid language</param>
        /// <param name="contentType">Whether this is plain text or HTML</param>
        /// <returns></returns>
        public static string[] TranslateArray(string[] texts, string from, string to, string contentType)
        {
            string fromCode = string.Empty;
            string toCode   = string.Empty;

            if (from.ToLower() == "Auto-Detect".ToLower() || from == string.Empty)
            {
                fromCode = string.Empty;
            }
            else
            {
                try { fromCode = AvailableLanguages.First(t => t.Value == from).Key; }
                catch { fromCode = from; }
            }

            toCode = LanguageNameToLanguageCode(to);

            AzureAuthToken authTokenSource = new AzureAuthToken(_ClientID);
            string         headerValue     = authTokenSource.GetAccessToken();
            var            bind            = new BasicHttpBinding
            {
                Name                   = "BasicHttpBinding_LanguageService",
                OpenTimeout            = TimeSpan.FromMinutes(5),
                CloseTimeout           = TimeSpan.FromMinutes(5),
                ReceiveTimeout         = TimeSpan.FromMinutes(5),
                MaxReceivedMessageSize = int.MaxValue,
                MaxBufferPoolSize      = int.MaxValue,
                MaxBufferSize          = int.MaxValue,
                Security               =
                    new BasicHttpSecurity {
                    Mode = BasicHttpSecurityMode.Transport
                }
            };

            var epa = new EndpointAddress("https://api.microsofttranslator.com/V2/soap.svc");
            LanguageServiceClient client = new LanguageServiceClient(bind, epa);

            if (String.IsNullOrEmpty(toCode))
            {
                toCode = "en";
            }

            TranslateOptions options = new TranslateOptions();

            options.Category    = _CategoryID;
            options.ContentType = contentType;

            try
            {
                var translatedTexts = client.TranslateArray(
                    headerValue,
                    texts,
                    fromCode,
                    toCode,
                    options);
                string[] res = translatedTexts.Select(t => t.TranslatedText).ToArray();
                if (_CreateTMXOnTranslate)
                {
                    WriteToTmx(texts, res, from, to);
                }
                return(res);
            }
            catch   //try again forcing English as source language
            {
                var translatedTexts = client.TranslateArray(
                    headerValue,
                    texts,
                    "en",
                    toCode,
                    options);
                string[] res = translatedTexts.Select(t => t.TranslatedText).ToArray();
                if (_CreateTMXOnTranslate)
                {
                    WriteToTmx(texts, res, from, to);
                }
                return(res);
            }
        }