Programmatically translate text using the Translator Text API
What to prepare in advance
Create a Microsoft Azure account beforehand. The creation procedure is described on this page.
Also, this time we will register with the free version, so please change it in a timely manner if you want to use the paid version.
Create API resources
Open the Microsoft Azure portal and click New in the left menu.
Select Intelligence + Analytics from the expanded menu.
From the expanded menu, select Cognitive Services APIs (Preview).
When the creation screen appears, enter a name of your choice (it will be the display name on the dashboard) and select "Free Trial" for the subscription. Then click API type.
Select Translator Text API from the list of APIs.
Then select Pricing tier.
Since you are using the free version, click "F0 Free" and click the "Select" button. The free version can convert up to 2 million characters per month.
If you are registering a service for the first time, create a new Resource group. You can group the resources you create into groups of any name.
A location is a place to put a service. When developing mainly in Japan, it is more likely to improve performance if it is installed in a Japan.
Finally, check "Pin to dashboard" and click the "Create" button.
The dashboard has the resource you created earlier, so click it to open it.
I think the Overview is open, so check the URL for "Endpoint" on the right. This is the URL of the API that should be accessed by authentication first. However, it rarely changes, and it is described in the program that I will introduce later, so it is good to remember that it is here for the time being.
Select Keys from the menu.
Make a note of the KEY 1 that appears and use it to authenticate. I think having two keys is probably a reserve. By the way, if the key leaks to the outside for some reason, you can recreate it with "Regenerate..." above.
This concludes the setup on the Azure side.
Programmatically access the API to translate text
Now it's time to actually create a program so that you can translate the text. Use Visual Studio 2015 to create a WPF application and create a screen that looks like this:
Enter text in From, and in Language, enter which language you want to convert to which language. And if you click on the "Convert Run" button, you will be able to see the translated text in the "Destination" below.
XAML (MainWindow.xaml)
It does not directly affect the translation, so only the code is included.
<Window x:Class="AzureTranslatorTextApi.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:AzureTranslatorTextApi"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition Height="*"/>
<RowDefinition Height="auto"/>
<RowDefinition Height="auto"/>
<RowDefinition Height="auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Label x:Name="label" Content="変換元" HorizontalAlignment="Left" Grid.Row="0"/>
<TextBox x:Name="textBoxInput" Margin="4" Text="ここに変換するテキストを入力します。" Grid.Row="1" AcceptsReturn="True" AcceptsTab="True" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto"/>
<Label x:Name="labelLang" Content="言語" HorizontalAlignment="Left" Grid.Row="2"/>
<Label x:Name="labelLangFrom" Content="from" HorizontalAlignment="Left" Grid.Row="2" Margin="56,0,0,0"/>
<TextBox x:Name="textBoxLangFrom" Margin="96,4,0,4" HorizontalAlignment="Left" Text="ja" Grid.Row="2" Width="50"/>
<Label x:Name="labelLangTo" Content="to" HorizontalAlignment="Left" Grid.Row="2" Margin="164,0,0,0"/>
<TextBox x:Name="textBoxLangTo" Margin="190,4,0,4" HorizontalAlignment="Left" Text="en" Grid.Row="2" Width="50" />
<Button x:Name="button" Content="変換実行" Margin="24,4" Height="24" Grid.Row="3" Click="button_Click"/>
<Label x:Name="label_Copy" Content="変換先" HorizontalAlignment="Left" Grid.Row="4"/>
<TextBox x:Name="textBoxOutput" Margin="4" Grid.Row="5" AcceptsReturn="True" AcceptsTab="True" VerticalScrollBarVisibility="Auto" IsReadOnly="True" Background="#FFE8E8E8" HorizontalScrollBarVisibility="Auto"/>
</Grid>
</Window>
Get Access Token (MainWindow.xaml.cs)
The basic flow for text translation is as follows:
- Throw KEY 1 into the API to get an access token.
- Use the access token to throw the text to the translation service to get the translated text.
- Get the access token again if needed
It comes to.
First, let's define a method to get an access token and make it easy to use. If you pass the KEY 1 obtained earlier as the argument, you can get the access token. It can also be obtained by synchronous processing, but since C# 5.0 async/await can be used, let's make it an asynchronous process easily.
As a point, set the URL to Endpoint + "/issueToken" as confirmed in Azure, and set KEY 1 obtained with "Ocp-Apim-Subscription-Key" as the key in the header to be sent.
As a response, the string of the access token can be obtained as it is, so it is used as the return value. By the way, this access token is only valid for 10 minutes.
<summary>
非同期でアクセストークンを取得します。
</summary>
<param name="subscriptionKey">認証に必要なキー文字列。</param>
<returns>取得したアクセストークン。</returns>
private async Task<string> GetAccessTokenAsync(string subscriptionKey)
{
using (var client = new HttpClient())
using (var request = new HttpRequestMessage())
{
request.Method = HttpMethod.Post;
request.RequestUri = new Uri("https://api.cognitive.microsoft.com/sts/v1.0/issueToken");
request.Content = new StringContent(string.Empty);
request.Headers.TryAddWithoutValidation("Ocp-Apim-Subscription-Key", subscriptionKey);
using (var response = await client.SendAsync(request))
{
response.EnsureSuccessStatusCode();
var token = await response.Content.ReadAsStringAsync();
Trace.WriteLine($"token={token}");
return token;
}
}
}
Access the API for text translation (MainWindow.xaml.cs)
This is also made into a method to make it easy to use. The arguments allow you to specify the access token you get and the text to translate, and which language to convert to which language.
Note that the URL you access is different from the URL where you obtained the token. The text and language to be translated are sent as a query string in the URL, so escape them using "Uri.EscapeDataString" in advance.
The GET method then sends the Authorization of the Header with the schema "Bearer" and the token in the parameter.
Since the response is taken in XML format, XDocument is used to retrieve the translated text inside. However, if the text contains XML escape characters, perhaps because you are using XML, they may remain escaped. Convert it as needed.
<summary>
テキストを翻訳します。
</summary>
<param name="token">API のアクセスに必要なトークン。</param>
<param name="text">翻訳するテキスト、</param>
<param name="fromLang">翻訳元の言語。</param>
<param name="toLang">翻訳先の言語。</param>
<returns>翻訳されたテキスト。</returns>
private async Task<string> TranslateText(string token, string text, string fromLang, string toLang)
{
using (var client = new HttpClient())
using (var request = new HttpRequestMessage())
{
// URL につけて送信するのでエンコードする
var escapeText = Uri.EscapeDataString(text);
Trace.WriteLine($"escapeText={escapeText}");
var uriStr = "http://api.microsofttranslator.com/V2/Http.svc/Translate?"
+ $"text={escapeText}&from={fromLang}&to={toLang}";
request.Method = HttpMethod.Get;
request.RequestUri = new Uri(uriStr);
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
using (var response = await client.SendAsync(request))
{
response.EnsureSuccessStatusCode();
var resultText = await response.Content.ReadAsStringAsync();
// <string>XXXXXX</string> 形式で取得されるので XDocument で操作する
XDocument xdoc = XDocument.Parse(resultText);
Trace.WriteLine($"xdoc={xdoc.ToString()}");
// XML エスケープ対象文字が正しく変換されない場合があるので
// 必要があれば対処すること
return xdoc.Descendants().First().Value;
}
}
}
Button execution process (MainWindow.xaml.cs)
Once you've implemented two methods, all you have to do is call each one. You can translate text by setting KEY1 and specifying the entered value for each method. Since it is an asynchronous process, please add async to the button handling method.
private async void button_Click(object sender, RoutedEventArgs e)
{
// ここに認証キー(KEY1)を入力してください
string subscriptionKey = "XXXXXXXXX";
// アクセストークンを取得します。有効時間は10分程度です。(おそらく)
var token = await GetAccessTokenAsync(subscriptionKey);
// テキストを翻訳し表示します
textBoxOutput.Text = await TranslateText(token, textBoxInput.Text, textBoxLangFrom.Text, textBoxLangTo.Text);
}
List of translatable languages
You may want to refer to the following Micorsoft pages: Since it is one of the cloud services, it may be changed at any time.