Execute batch of microsoft translation queries

2019-09-09 21:06发布

We are trying to use Microsoft translation service provided on Azure market place. I started with the sample code provided at http://code.msdn.microsoft.com/windowsazure/Walkthrough-Translator-in-7e0be0f7/view/SourceCode

Using their sample code I can get a single translation. However I would like to get multiple translations in a single request. I tried using DataServiceContext.ExecuteBatch but it throws WebException with "The remote server returned an error: (404) Not Found."

TranslatorContainer cont = new TranslatorContainer(new Uri("https://api.datamarket.azure.com/Bing/MicrosoftTranslator/"));
var accountKey = "<account-key>";
cont.Credentials = new NetworkCredential(accountKey, accountKey);

// This works
var result1 = cont.Translate("Nothing to translate", "nl", "en").Execute().ToList();

DataServiceQuery<Translation>[] queries = new DataServiceQuery<Translation>[]
{
    cont.Translate("Nothing", "nl", "en"),
    cont.Translate("Nothing to translate", "nl", "en"),
    cont.Translate("What happend", "nl", "en"),
};

// This throws exception
var result2 = cont.ExecuteBatch(queries);

I could use multiple threads and make multiple requests in parallel. But I like to avoid that. Anyone have tried this before ?

2条回答
别忘想泡老子
2楼-- · 2019-09-09 21:25

I’m not sure why your code doesn’t work. But you may want to use the REST API directly. Please try to use the following code which works fine on my side:

        string stringToTranslate = "test";
        WebClient client = new WebClient();
        client.Credentials = new NetworkCredential("[your user name]", "[your key]");
        string results = client.DownloadString("https://api.datamarket.azure.com/Data.ashx/Bing/MicrosoftTranslator/Translate?Text=%27" + stringToTranslate + "%27&To=%27zh-CHS%27");

The result is an AtomPub feed. You can then parse the feed (for example, use SyndicationFeed class: http://msdn.microsoft.com/en-us/library/system.servicemodel.syndication.syndicationfeed.aspx).

Best Regards,

Ming Xu.

查看更多
干净又极端
3楼-- · 2019-09-09 21:34

Use this NuGet package for batch translation on CognitiveServices Translator API 3.0

  • This Nuget can help you on Batch-Translation, easily and quickly.
    1. How it work: It'll transform your contents to some perfect packages for translating.
    2. Speed: On my PC, about 300~500 items(not characters) per second

Here are steps:

  1. Create an instance of Translator with your BaseUrl and Key:

    Translator translator = new Translator(BaseUrl, Key);
    
  2. Add content to the Translator:

    translator.AddContent("哈啰");
    //Here you can add many times, more than 100, 1000 or 10000.
    //You can also set the "Contents" property instead.
    
  3. Get results aysnc:

    List<string> translation = await translator.TranslateAsync("en");
    
查看更多
登录 后发表回答