Machine Transal...'s profileMachine Translation - th...PhotosBlog Tools Help

Blog


    October 09

    Translating using the Bing Api/Traduzindo usando a Api do Bing

    Very few people know that anyone can write code using our translation Api, and even fewer know about the interface available in the Bing Api. I’ll use the later for this next sample: an ASPX page that invokes the translation services, show the result and then invokes the Speech feature from the client (using Javascript).

    Let’s start with the basics: the Bing Api offers tons of services, and anyone can use it - all you need to to is apply for an AppId. Follow the instructions at http://www.bing.com/developers/appids.aspx and you’ll get one immediately. Once you have your shiny new code, you can then start playing with the many (many) samples available at http://msdn.microsoft.com/en-us/library/dd251056.aspx. It’s a quite powerful Api, and it works really well.

    For the sake of this project we’ll only use the Translate methods. There are three “flavors” of protocols available: JSON, XML and SOAP. the XML protocol is really simple: it’s basically a REST implementation that returns a Xml as response. As any REST interface, you can even invoke it from the browser. For example:

    http://api.bing.net/xml.aspx?AppId=FD087E7F3CDFEC530B63A2AC2FEEC5846127DA39&Query=mais+um+exemplo+usando+a+interface+do+Bing&Sources=Translation&Version=2.2&Translation.SourceLanguage=pt&Translation.TargetLanguage=en

    ,returns

    image

    (This AppId is registered to H2KTech, so please get your own)

    As you can see, the result is a very simple Xml that can be loaded and parsed very easily. MSDN has a pretty good example that I copied and modified for this sample application: http://msdn.microsoft.com/en-us/library/dd877832.aspx.

    This application is also very simple, and I even kept the Javascript Speech interface code (I think it’s pretty neat that it runs totally asynchronously from the rest of the page). The code is available here: http://www.h2ktech.net/h2ktechsamples/TranslateUsingBingSpeechSample.txt, and the application here: http://www.h2ktech.net/h2ktechsamples/TranslateUsingBingSpeechSample.aspx

    image

    Looking at the code you’ll notice that querying the translation services is really simple: just format the url string correctly and open an Http request:

    protected void Button1_Click(object sender, EventArgs e)
    {
        // retrieve the basic parameters
        string sourceText = TextBox1.Text;
        string targetLang = DropDownList1.SelectedValue;

        // Sample code from the Bing API documentation, with minor modifications
        // see
    http://msdn.microsoft.com/en-us/library/dd877832.aspx
        HttpWebRequest request = BuildRequest(sourceText, targetLang);

        try
        {
            // Send the request; display the response.
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            TextBox2.Text = DisplayResponse(response);
        }
        catch (WebException ex)
        {
            // An exception occurred while accessing the network.
            TextBox2.Text = ex.Message;
        }
    }

    static HttpWebRequest BuildRequest(string sourceText, string targetLang)
    {
        string requestString = "
    http://api.bing.net/xml.aspx?"

            // Common request fields (required)
            + "AppId=" + AppId
            + "&Query=" + HttpUtility.UrlEncode(sourceText)
            + "&Sources=Translation"

            // Common request fields (optional)
            + "&Version=2.2"

            // SourceType-specific request fields (required)
            + "&Translation.SourceLanguage=en"
            + "&Translation.TargetLanguage=" + targetLang;

        // Create and initialize the request.
        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(
            requestString);

        return request;
    }

    The response comes in the form of a Xml formatted string, so it’s ready to be loaded into a XmlDocument object. After that, just add the namespace and you’re ready to parse it:

    static string DisplayResponse(HttpWebResponse response)

    {

        // Load the response into an XmlDocument.

        XmlDocument document = new XmlDocument();

        document.Load(response.GetResponseStream());

        // Add the default namespace to the namespace manager.

        XmlNamespaceManager nsmgr = new XmlNamespaceManager(

            document.NameTable);

        nsmgr.AddNamespace(

            "api",

            "http://schemas.microsoft.com/LiveSearch/2008/04/XML/element");

        XmlNodeList errors = document.DocumentElement.SelectNodes(

            "./api:Errors/api:Error",

            nsmgr);

        if (errors.Count > 0)

        {

            // There are errors in the response. Display error details.

            return DisplayErrors(errors);

        }

        else

        {

            // There were no errors in the response. Display the

            // Translation results.

            return DisplayResults(document.DocumentElement, nsmgr);

        }

    }

    static string DisplayResults(XmlNode root, XmlNamespaceManager nsmgr)

    {

        string results = String.Empty;

        string version = root.SelectSingleNode("./@Version", nsmgr).InnerText;

        string searchTerms = root.SelectSingleNode(

            "./api:Query/api:SearchTerms",

            nsmgr).InnerText;

        // Add the Translation SourceType namespace to the namespace manager.

        nsmgr.AddNamespace(

            "tra",

            "http://schemas.microsoft.com/LiveSearch/2008/04/XML/translation");

        XmlNodeList nodes = root.SelectNodes(

            "./tra:Translation/tra:Results/tra:TranslationResult",

            nsmgr);

        // Display the Translation results.

        foreach (XmlNode result in nodes)

        {

            results = String.Concat(results, result.SelectSingleNode("./tra:TranslatedTerm",

            nsmgr).InnerText);

        }

        return results;

    }

    Note that I’ve hooked the call to the Search Api to the OnClick handler, so the response will be blocked until we get a result back – and this is bad. However, for the sake of this exercise it doesn’t hurt much. Once we have the translation results, we populate the text box and return. The client Javascript code will then detect that the text box is not empty and invokes the Speech service using the Active X inside the IFrame, just like in the previous sample.

    I didn’t add any checks for exceptions, so if the results text box is populated with an error message funny things will certainly happen :-).

    Cheers,

    Helvecio

    English - Portuguese

    Muito poucas pessoas sabem que qualquer um pode escrever código usando nossa API detradução, e ainda menos sabem sobre a interface disponível na API de Bing. Usarei esta para meu próximo exemplo: uma página ASPX que invoca os serviços de tradução, mostra o resultado e, em seguida, chama o recurso de voz a partir do cliente (usando JavaScript).

    Vamos começar com os princípios básicos: a API de Bing oferece toneladas de serviços e qualquer pessoa pode usá-los - tudo o que você precisa é obter um AppId. Siga as instruções em http://www.bing.com/Developers/APPIDs.aspx e você obterá um imediatamente. Depois de ter seu novo código, você pode então começar a brincar com os varios (muitos) exemplos disponíveis em http://MSDN.Microsoft.com/en-US/Library/dd251056.aspx. É uma API bastante poderosa e funciona muito bem.

    Para este projeto só vamos usar os métodos de traduzir. Existem três "flavors" de protocolos disponíveis: JSON, XML e SOAP. O protocolo XML é realmente simples: é basicamente uma implementação de REST que retorna um XML como resposta. Como qualquer interface REST, você pode até mesmo invocá-lo do navegador. Por exemplo:

    http://API.bing.NET/XML.aspx?AppId=FD087E7F3CDFEC530B63A2AC2FEEC5846127DA39

    , retorna

    image(Este AppId está registrado para H2KTech, então, por favor obtenha seu próprio)

    Como você pode ver, o resultado é um XML muito simples que pode ser carregado e analisado muito facilmente. MSDN tem um exemplo muito bom que eu copei e modifiquei para este aplicativo: http://MSDN.Microsoft.com/en-US/Library/dd877832.aspx.

    Esse aplicativo também é muito simples e eu até manti o código da interface de Speech em JavaScript (achoque é bastante elegante que ele seja executado totalmente assincronamente do resto da página). O código está disponível aqui: http://www.h2ktech.NET/h2ktechsamples/TranslateUsingBingSpeechSample.txt e a aplicação aqui: http://www.h2ktech.NET/h2ktechsamples/TranslateUsingBingSpeechSample.aspx

    Olhando o código, você notará que ao consultar os serviços de tradução é realmente facil: basta formatar a cadeia de caracteres de url corretamente e abrir uma solicitação de http.

    A resposta vem na forma de uma string formatada como XML, portanto está pronto para ser carregado em um objeto XmlDocument. Após isso, basta adicionar o namespace e você está pronto para analisá-lo.

    Observe que eu já implementei a chamada para a API no handler de OnClick, portanto, a resposta será bloqueada até obtermos a um resultado de volta – e isso é ruim. No entanto, por razões deste exercício não importa tanto. Assim que tivermos os resultados de tradução, nós preenchemos a caixa de texto e retornamos. O  código JavaScript que roda no cliente irá detectar que a caixa de texto não está vazia e invoca o serviço de voz usando o Active X dentro do IFrame, tal como no exemplo anterior.

    Não adicionei testes para exceções, portanto, se a caixa de texto de resultados for preenchida com uma mensagem de erro coisas engraçadas certamente irão acontecer:-).

    []s,

    Helvecio


    October 08

    A simple ASP Translate to Speech Application/Um exemplo de Traducao com Voz em ASP

    So here is a first sample application using the new service. It’s a really basic Javascript client that doesn’t do much more than formatting a string with the url and the correct parameters to invoke the T2S feature. The only thing that is remotely interesting is that this string is passed directly to the Media Player Active X, so there’s no extra work to play the wave file.

    You can play with the app here: http://www.h2ktech.net/h2ktechsamples/Translate2SpeechSample.aspx (by the way, I’ll be posting all new samples to this very same location). You can ‘view source’ to check the code, or simply download it from the text file: http://www.h2ktech.net/h2ktechsamples/Translate2SpeechSample.cs.txt

    The two Javascript functions work as follows:

    • InvokeService builds the string based on the content of the textbox (there’s some basic filtering to emulate escaping some characters) and adds the language parameters based on the dropdown.
    image

    • PlayWave: uses the iframe as a container and creates a document on the fly with references to the Media Player Active X. It also adds a regular http link (like the ones in the previous blog post) in case the users doesn’t have (and doesn’t want to install) the control.

    image

    Here’s a good reference on embedding Media Active X controls: http://cit.ucsf.edu/embedmedia/step3.php

    Give it a try, and feel free to play with the code – just don’t use it for any commercial application alright?

    Cheers,
    Helvecio

    English - Portuguese

    Aqui está um primeiro exemplo de um aplicativo usando o novo serviço. É um programa realmente básico em JavaScript que não faz muito mais do que formatar uma string com a url e os parâmetros corretos para invocar o recurso de T2S. A única coisa que é remotamente interessante é que esta string é passaao diretamente para o Active X do Media Player, portanto, não há nenhum trabalho extra para reproduzir o arquivo wave.

    Você pode brincar com o aplicativo aqui: http://www.h2ktech.NET/h2ktechsamples/Translate2SpeechSample.aspx (a propósito, eu vou colocar todos os code samples neste mesmo local daqui para frente). Você pode 'Exibir fonte' para ler o código, ou simplesmente o download do arquivo de texto:http://www.h2ktech.NET/h2ktechsamples/Translate2SpeechSample.cs.txt

    As duas funções de JavaScript funcionam da seguinte forma:

    • InvokeService constrói a cadeia de caracteres com base no conteúdo da caixa de texto (adicionei alguns filtros básicos para emular escaping alguns caracteres) e adicionar os parâmetros de idiomas com base na lista.

    • PlayWave: utiliza o iframe como um recipiente e cria um documento com referências para o Media Player ACTIVEX. Também adiciona um link http normal (como aqueles na postagem do blog anterior), caso os usuários não tenham (e não queiram instalar) o controle.

    Aqui está uma boa referência sobre a incorporação de controles Active X de mídia: http://Cit.ucsf.edu/embedmedia/step3.php

    Experimente e sinta-se a vontade para brincar com o código – só não use em nenhum aplicativo comercial ok?

    []s,
    Helvecio


    October 07

    Making the case for Text-to-Speech Integration with Machine Translation/Integrando Sintese de Voz ‘a Traducao Automatica

    So my new personal project is taking shape, but as I mentioned in my previous post it will probably take a long time before there’s any real product implementation of a Speech-to-speech translator. That said, I believe there’s nothing preventing us from seriously integrating Text-to-Speech with our current offerings.

    For the few of you that have been following this blog – yes, I know it’s not a new concept. The first TBot even had it implemented somehow (see http://mtbotprototype.spaces.live.com/blog/cns!3F1A4578DEE8B!376.entry ). Unfortunately, it takes a while to create momentum to push for ideas.

    The circumstances have changed since February 2008, and now I believe it’s time to start pushing – our team now has open APIS for translations (http://msdn.microsoft.com/en-us/library/dd576287.aspx), more languages and a heck of a lot more hits daily. Since we’ve already reached out and offered developers and webmasters/blog owners ways to incorporate MT to theirs sites or products, offering a way to add Translated TTS seems like a natural progression.

    So I’m putting my money where my mouth is (literally) and I’ve acquired a domain to host some of my prototypes. The first is a simple ASPX page that works similar to our Http Translate method – you invoke it thru a url that takes query parameters. The utility translates the sentence and then returns a wave file back to the caller. It even works directly from the browser, so anyone can add links to invoke the service – like these:

    http://www.h2ktech.net/translatespeak/text2speech.aspx?from=en&to=es&text=this+is+another+option+for+integrating+speech+synthesis +and+machine+translation

    or

    http://www.h2ktech.net/translatespeak/text2speech.aspx?from=es&to=en&text=buenas+noches+señor+.+¿+Cómo+estás+?

    For now I’m only offering 4 languages – English, French, Spanish and German (en, fr, es, de). If there’s interest in the service I’ll try to add more languages.

    Hopefully people out there will build interesting applications using the utility (attention mobile developers: it doesn’t get any easier to integrate than that!) , and help build the case for TTS. On my side, I’ll keep pushing for adoption: I honestly believe that all of our offerings should offer something similar to that...

    Enjoy the new free service!

    Cheers,
    Helvecio

     

    English - Portuguese

    Meu novo projeto pessoal está a ganhar forma, mas como mencionei no meu post anterior provavelmente levará muito tempo até que apareça qualquer implementação real de um produto tradutor de speech-to-speech. Entretanto, creio que não há nada que nos impeça de integrar seriamente conversão de texto em fala com nossas interfaces atuais.

    Para já vem seguindo esse blog faz tempo – sim, sei que não é um conceito novo. O primeiro TBot já a mesma função implementada de outra forma (ver http://mtbotprototype.spaces.Live.com/blog/CNS!3F1A4578DEE8B!376.entry ). Infelizmente, leva um tempo para criar o impulso para empurrar novas idéias.

    As circunstâncias mudaram desde Fevereiro de 2008, e agora penso que é hora de tentar novamente – nossa equipe tem agora APIS abertos para traduções (http://MSDN.Microsoft.com/en-US/Library/dd576287.aspx), mais idiomas e muito mais page views diariamente. Desde do inicio do ano nós já oferecemos a desenvolvedores e webmasters/bloggers maneiras de incorporar MT para seus sites ou produtos. Oferecer uma maneira de adicionar que Translated TTS parece ser uma progressão natural.

    Assim, eu estou colocando meu dinheiro onde minha boca está (literalmente) e já adquiri a um domínio para hospedar alguns dos meus protótipos. O primeiro é uma simples página ASPX que funciona de forma similar ao nosso método HTTP Translate– invocá-lo por meio de um url que leva os parâmetros de consulta. O utilitário traduz-se a frase e em seguida, retorna um arquivo wave de volta para o chamador. Até funciona diretamente do navegador, portanto qualquer pessoa possa adicionar links para invocar o serviço – como estes:

    http://www.h2ktech.net/translatespeak/text2speech.aspx?from=en&to=es&text=this+is+another+option+for+integrating+speech+synthesis +and+machine+translation

    ou

    http://www.h2ktech.net/translatespeak/text2speech.aspx?from=es&to=en&text=buenas+noches+señor+.+¿+Cómo+estás+?

    Por agora eu estou oferecendo apenas 4 idiomas – inglês, francês, espanhol e alemão (en, fr, es, de). Se houver interesse no serviço tentarei adicionar mais idiomas.

    Espero que desenvolvedores por aí criem aplicativos interessantes usando o utilitário (atenção desenvolvedores para mobile: não tem integração mais fácil do que essa!) e ajudem a construir apoio para TTS. No meu lado, eu vou continuar a empurrar a adopção: acredito sinceramente que todas as nossas interfaces devem oferecer algo similar...

    Aproveite o novo serviço gratuito!

    []s,
    Helvecio