2021/11/20
久々(1年ぶり)にAzureのCognitive Serviceにある翻訳機能「Translator」を使ってみようと思いました。1年前の
ブログではPython、Flaskを使ったサンプルコードそのままのWebアプリでしたが、今回はC#でデスクトップアプリに作り直す試みです。
Azure上の設定は1年前の
ブログのままで何も触りませんでした。プログラムを動かすために必要な情報は、
① Subscription key
② Service endpoint
③ Service Region location
の3つです。
作成したアプリは、GUI上で翻訳したい言語の文書を記入し、その言語と変換後の言語をドロップダウンリストで選択した上で、翻訳ボタンを押すと、Web API経由でAzureにデータを送り、変換後の翻訳を受け取り、表示する単純なものです。C#のConsoleアプリの
サンプルがあったので、参考にして、Formアプリに作り直しました。言語は、日本語、英語、中国語、韓国語の4言語としました。コード(処理部のみ)は以下の通りです。
// Azure-Translator program(C#)
using System;
using System.Text;
using System.Windows.Forms;
using System.Net.Http;
using Newtonsoft.Json;
namespace translate_test
{
public partial class Tranlate_test : Form
{
// Azure setting
private static readonly string subscriptionKey = "……………………"; // Subscription key
private static readonly string endpoint = "https://api.cognitive.microsofttranslator.com/"; // Service endpoint
private static readonly string location = "japaneast"; // Service Region location
private string FromLang = "";
private string ToLang = "";
public Tranlate_test()
{
InitializeComponent();
}
private string[] LangList = {"日本語", "英語", "中国語", "韓国語" };
private string[] LangCode = { "ja", "en", "zh-Hans", "ko" };
private void Tranlate_test_Load(object sender, EventArgs e)
{
this.FromTextBox.Text = "";
this.ToTextBox.Text = "";
foreach (string a in LangList)
{
this.FromComboBox.Items.Add(a);
this.ToComboBox.Items.Add(a);
}
this.FromComboBox.SelectedIndex = 0;
FromLang = LangCode[this.FromComboBox.SelectedIndex];
this.ToComboBox.SelectedIndex = 1;
ToLang = LangCode[this.ToComboBox.SelectedIndex];
}
private async void TranslateRun_Click(object sender, EventArgs e)
{
// Input and output languages are defined as parameters.
string route = "/translate?api-version=3.0&from="+ FromLang + "&to=" + ToLang;
string textToTranslate = this.FromTextBox.Text;
object[] body = new object[] { new { Text = textToTranslate } };
var requestBody = JsonConvert.SerializeObject(body);
using (var client = new HttpClient())
using (var request = new HttpRequestMessage())
{
// Build the request.
request.Method = HttpMethod.Post;
request.RequestUri = new Uri(endpoint + route);
request.Content = new StringContent(requestBody, Encoding.UTF8, "application/json");
request.Headers.Add("Ocp-Apim-Subscription-Key", subscriptionKey);
request.Headers.Add("Ocp-Apim-Subscription-Region", location);
// Send the request and get response.
HttpResponseMessage response = await client.SendAsync(request).ConfigureAwait(false);
// Read response as a string.
string result = await response.Content.ReadAsStringAsync();
// Remove [ ] from result string
string result_temp1 = result.Replace("[", "");
result = result_temp1.Replace("]", "");
// Deserialize data
dynamic d = JsonConvert.DeserializeObject(result);
// View of result sentense
this.Invoke((Action)(() => { this.ToTextBox.Text = d.translations.text; }));
}
}
private void FromComboBox_TextChanged(object sender, EventArgs e)
{
FromLang = LangCode[this.FromComboBox.SelectedIndex];
}
private void ToComboBox_TextChanged(object sender, EventArgs e)
{
ToLang = LangCode[this.ToComboBox.SelectedIndex];
}
}
}
久々にC#でコードを組んだので、つまづいて難儀した所もありました。はまったのは以下の2点です。
① 63-70行目のWeb APIのリターンであるJSONから必要なテキスト部分を抜き出す所
→ リターンの文字列から[]を取り除くという格好が悪いことをして対応・・。
② 73行目のテキストボックスに表示する所
→ フォームアプリにありがちなことを忘れていました・・。別スレッドでしたね。
作成したソフトで、以下の日本語の文章を英語、中国語、韓国語に変換し、韓国語に変換された文章を再度日本語に変換しました。
「NTTドコモは10日、10月に起きた大規模通信障害について、影響人数は音声通話で約460万人、データ通信サービスで830万人以上だったと発表した。のべ1290万人に達する。」
この文章の10日はニュースが出された11月10日のことなので、10月10日というのは違いますね。よくよく調べてみると、英語への変換でも、日本語から英語に変換した時点で、すでに10月10日になってしまっていました。
NTT DOCOMO announced on October 10 that ...
中国語は正常でした。
NTT DoCoMo公司10日宣布,10月份发生的大规模通信故障・・
また、韓国語への変換もGoogle翻訳で確認すると、正常であることが分かりました。結局、韓国語から日本語の変換で間違ったようです。このAzureのTranslatorの例では、「日→英」と「韓→日」が誤訳した結果でしたが、Google翻訳をかけてみると、すべて正しい翻訳でした。Google翻訳、さすがですね。
今回、C#でAzure-Translatorの簡便なGUIを作成できました。また、久々にコードを組んで、はまりながら大変勉強になりました。感覚が鈍らない程度にコードを組まなくてはならないですね・・。