Azure Cognitive Service に、Translator API がやってきたのでちょっと使ってみました。
ちなみに Translator は、Microsoft DataMarket でこれまでも利用できていた機能です。
先月末に、Azure Cognitive Service に仲間入りして、Azure Portal から利用できるようになりました。
使い方は、ほぼほぼ一緒なのですが、API を呼び出すためのトークンの取得がちょっと楽になったのと、REST でたたく URL が変わったという違いはあります。
Azure Cognitive Service の Translator API については、API Documentation をご覧ください。
https://www.microsoft.com/cognitive-services/en-us/translator-api/documentation/TranslatorInfo/overview
サンプル
今回は、コンソールアプリで日本語を英語に変えるアプリをサンプルに作成しました。
注意事項は、Azure Portal で API を作成後、デプロイ成功したってメッセージが出てから、ちょっと時間を置いてからアプリを動かした方がいいです。
正しいコードでも、デプロイ後はややしばらくは、認証エラーが帰ってきてしまいました。
実行するとこんな感じ。
参考にしたのは、Git です。
https://github.com/MicrosoftTranslator
using System;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.IO;
namespace TextTransferDemo01
{
class Program
{
private const string SubscriptionKey = "{Key}";
static void Main(string[] args)
{
TranslateAsync().Wait();
Console.ReadKey();
}
private static async Task TranslateAsync()
{
var authTokenSource = new AzureTextTransfer(SubscriptionKey);
var token = string.Empty;
try
{
token = await authTokenSource.GetAccessTokenAsync();
}
catch (HttpRequestException)
{
switch (authTokenSource.RequestStatusCode)
{
case HttpStatusCode.Unauthorized:
Console.WriteLine("Request to token service is not authorized (401). Check that the Azure subscription key is valid.");
break;
case HttpStatusCode.Forbidden:
Console.WriteLine("Request to token service is not authorized (403). For accounts in the free-tier, check that the account quota is not exceeded.");
break;
}
throw;
}
Console.WriteLine("Enter Text(japanese) :");
string textToTransfer = Console.ReadLine();
Console.WriteLine(authTokenSource.TextTransfer(token, textToTransfer,"ja","en"));
}
}
public class AzureTextTransfer
{
/// URL of the token service
private static readonly Uri ServiceUrl = new Uri("https://api.cognitive.microsoft.com/sts/v1.0/issueToken");
/// Name of header used to pass the subscription key to the token service
private const string OcpApimSubscriptionKeyHeader = "Ocp-Apim-Subscription-Key";
/// After obtaining a valid token, this class will cache it for this duration.
/// Use a duration of 5 minutes, which is less than the actual token lifetime of 10 minutes.
private static readonly TimeSpan TokenCacheDuration = new TimeSpan(0, 5, 0);
/// Cache the value of the last valid token obtained from the token service.
private string storedTokenValue = string.Empty;
/// When the last valid token was obtained.
private DateTime storedTokenTime = DateTime.MinValue;
/// Gets the subscription key.
public string SubscriptionKey { get; private set; }
/// Gets the HTTP status code for the most recent request to the token service.
public HttpStatusCode RequestStatusCode { get; private set; }
///
/// Creates a client to obtain an access token.
///
///Subscription key to use to get an authentication token.
public AzureTextTransfer(string key)
{
if (string.IsNullOrEmpty(key))
{
throw new ArgumentNullException("key", "A subscription key is required");
}
this.SubscriptionKey = key;
this.RequestStatusCode = HttpStatusCode.InternalServerError;
}
/// Gets a token for the specified subscription.
///
/// The encoded JWT token prefixed with the string "Bearer ".
///
/// This method uses a cache to limit the number of request to the token service.
/// A fresh token can be re-used during its lifetime of 10 minutes. After a successful
/// request to the token service, this method caches the access token. Subsequent
/// invocations of the method return the cached token for the next 5 minutes. After
/// 5 minutes, a new token is fetched from the token service and the cache is updated.
///
public async Task GetAccessTokenAsync()
{
// Re-use the cached token if there is one.
if ((DateTime.Now - storedTokenTime) < TokenCacheDuration)
{
return storedTokenValue;
}
using (var client = new HttpClient())
using (var request = new HttpRequestMessage())
{
request.Method = HttpMethod.Post;
request.RequestUri = ServiceUrl;
request.Content = new StringContent(string.Empty);
request.Headers.TryAddWithoutValidation(OcpApimSubscriptionKeyHeader, this.SubscriptionKey);
var response = await client.SendAsync(request);
this.RequestStatusCode = response.StatusCode;
response.EnsureSuccessStatusCode();
var token = await response.Content.ReadAsStringAsync();
storedTokenTime = DateTime.Now;
storedTokenValue = "Bearer " + token;
return storedTokenValue;
}
}
public String TextTransfer(string AppID,string textToTransfer, string from, string to)
{
string translation = String.Empty;
string uri = "https://api.microsofttranslator.com/v2/http.svc/Translate?appid="+ AppID + "&text="
+ System.Web.HttpUtility.UrlEncode(textToTransfer) + "&from=" + from + "&to=" + to;
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);
WebResponse response = null;
try
{
response = httpWebRequest.GetResponse();
using (Stream stream = response.GetResponseStream())
{
System.Runtime.Serialization.DataContractSerializer dcs =
new System.Runtime.Serialization.DataContractSerializer(Type.GetType("System.String"));
translation = (string)dcs.ReadObject(stream);
}
}
catch
{
throw;
}
finally
{
if (response != null)
{
response.Close();
response = null;
}
}
return (translation);
}
}
}
まとめ
Azure Cognitive Service の Text Analytics API が、全て日本語対応しているわけではないので、Text Translator を使って、日本語から英語に翻訳して、そのあとのネガポジ判定などできそうな気がします。
そんな感じで、日本語非対応のAPIを使うときにワンクッションおくような使い方もできるような気がします。
その他にも、翻訳周りはちょっとしたことに使えそうですよね。
Microsoft Transletor というサイトもできてるみたいで、ビジネス向けな情報はここから出していくのかな?って感じです。
https://www.microsoft.com/ja-jp/translator/


コメント
[…] Azure Cognitive Service の Translator Speech API については、以下にブログっているのでよかったら見てみてください。 Azure Cognitive Service を使って、日本語を英語に翻訳 […]
[…] Azure Cognitive Service の Translator Speech API については、以下にブログっているのでよかったら見てみてください。 Azure Cognitive Service を使って、日本語を英語に翻訳 […]