Skip to content
This repository has been archived by the owner on Aug 17, 2024. It is now read-only.

Commit

Permalink
修改阿里云机器翻译为私有API
Browse files Browse the repository at this point in the history
  • Loading branch information
Isayama-Kagura committed Aug 11, 2022
1 parent 452e7c4 commit e81014e
Show file tree
Hide file tree
Showing 6 changed files with 99 additions and 36 deletions.
22 changes: 18 additions & 4 deletions TsubakiTranslator/BasicLibrary/TranslateAPIConfig.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@ public class TranslateAPIConfig: ObservableObject
private string ttsRegion;
private string ttsResourceKey;

private bool aliyunIsEnabled;
private bool aliIsEnabled;
private string aliSecretId;
private string aliSecretKey;

private bool baiduIsEnabled;
private string baiduAppID;
Expand Down Expand Up @@ -62,10 +64,22 @@ public string TTSResourceKey
set => SetProperty(ref ttsResourceKey, value);
}

public bool AliyunIsEnabled
public bool AliIsEnabled
{
get => aliyunIsEnabled;
set => SetProperty(ref aliyunIsEnabled, value);
get => aliIsEnabled;
set => SetProperty(ref aliIsEnabled, value);
}

public string AliSecretId
{
get => aliSecretId;
set => SetProperty(ref aliSecretId, value);
}

public string AliSecretKey
{
get => aliSecretKey;
set => SetProperty(ref aliSecretKey, value);
}

public bool BaiduIsEnabled
Expand Down
3 changes: 2 additions & 1 deletion TsubakiTranslator/BasicLibrary/TranslateHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,10 @@ public static LinkedList<ITranslator> GetSelectedTranslators(TranslateAPIConfig
{
LinkedList<ITranslator> translators = new LinkedList<ITranslator>();

if (translateAPIConfig.AliyunIsEnabled)
if (translateAPIConfig.AliIsEnabled)
{
ITranslator aliyun = new AliyunTranslator();
aliyun.TranslatorInit(translateAPIConfig.AliSecretId, translateAPIConfig.AliSecretKey);
translators.AddLast(aliyun);
}

Expand Down
91 changes: 63 additions & 28 deletions TsubakiTranslator/TranslateAPILibrary/AliyunTranslator.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,11 @@
using System.Net.Http;
using RestSharp;
using RestSharp.Serializers;
using System;
using System.Net;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
using System.Web;

Expand All @@ -13,54 +20,82 @@ class AliyunTranslator : ITranslator

public string SourceLanguage { get; set; }

private string SecretId { get; set; }
private string SecretKey { get; set; }

public string Translate(string sourceText)
{
string desLang = "zh";


string bodyString = $"srcLanguage={SourceLanguage}&tgtLanguage={desLang}&srcText={HttpUtility.UrlEncode(sourceText)}&bizType=general&source=aliyun";
string method = "POST";
string accept = "application/json";
//string contentType = "application/json";
string date = DateTime.UtcNow.ToString("r");
string host = "mt.cn-hangzhou.aliyuncs.com";
string path = "/api/translate/web/general";

string url = @"https://translate.alibaba.com/trans/TranslateTextAddAlignment.do";

HttpClient client = CommonFunction.Client;
var body = new
{
FormatType = "text",
Scene = "general",
SourceLanguage = SourceLanguage,
SourceText = sourceText,
TargetLanguage = desLang,
};

string bodyString = JsonSerializer.Serialize(body);
string bodyMd5 = string.Empty;
using (MD5 md5Hash = MD5.Create())
{
// 将输入字符串转换为字节数组并计算哈希数据
byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(bodyString));
// 返回BASE64字符串
bodyMd5 = Convert.ToBase64String(data);
}

HttpContent content = new StringContent(bodyString);
content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/x-www-form-urlencoded");
string uuid = Guid.NewGuid().ToString();

string stringToSign = method + "\n" + accept + "\n" + bodyMd5 + "\n" + host + "\n" + date + "\n"
+ "x-acs-signature-method:HMAC-SHA1\n"
+ "x-acs-signature-nonce:" + uuid + "\n"
+ path;

try
string signature = string.Empty;
using (HMACSHA1 mac = new HMACSHA1(Encoding.UTF8.GetBytes(SecretKey)))
{
HttpResponseMessage response = client.PostAsync(url, content).GetAwaiter().GetResult();//改成自己的
response.EnsureSuccessStatusCode();//用来抛异常的
string responseBody = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
byte[] hash = mac.ComputeHash(Encoding.UTF8.GetBytes(stringToSign));
signature = Convert.ToBase64String(hash);
}

Regex reg = new Regex(@",""listTargetText"":\[""(.*?)""\],");
Match match = reg.Match(responseBody);
string authHeader = "acs " + SecretId + ":" + signature;

string result = match.Groups[1].Value;
return result;
//string ret = result.payload.translations[0].translation;
var client = new RestClient($"https://{host}");
var request = new RestRequest(path,Method.Post);
request.AddHeader("Authorization", authHeader);
request.AddHeader("Accept", accept);
request.AddHeader("Content-MD5", bodyMd5);
request.AddHeader("Content-Type", host);
request.AddHeader("Date", date);
request.AddHeader("x-acs-signature-method", "HMAC-SHA1");
request.AddHeader("x-acs-signature-nonce", uuid);

//return ret;
request.AddStringBody(bodyString,DataFormat.Json);

//return responseBody;
}
catch (System.Net.Http.HttpRequestException ex)
{

return ex.Message;
}
catch (System.Threading.Tasks.TaskCanceledException ex)
{
var response = client.Execute(request);

return ex.Message;
}
Regex reg = new Regex(@"""Translated"":""(.*?)""");
Match match = reg.Match(response.Content);
string result = match.Groups[1].Value;
return result;

}

public void TranslatorInit(string param1, string param2)
{

SecretId = param1;
SecretKey = param2;
}
}
}
4 changes: 2 additions & 2 deletions TsubakiTranslator/TranslateAPILibrary/TencentTranslator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ namespace TsubakiTranslator.TranslateAPILibrary
public class TencentTranslator : ITranslator
{

private string SecretId;//腾讯翻译API SecretId
private string SecretKey;//腾讯翻译API SecretKey
private string SecretId { get; set; }//腾讯翻译API SecretId
private string SecretKey { get; set; }//腾讯翻译API SecretKey

private readonly string name = "腾讯";
public string Name { get => name; }
Expand Down
1 change: 1 addition & 0 deletions TsubakiTranslator/TsubakiTranslator.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
<PackageReference Include="CommunityToolkit.Mvvm" Version="7.1.2" />
<PackageReference Include="MaterialDesignThemes" Version="4.3.0" />
<PackageReference Include="Microsoft.CognitiveServices.Speech" Version="1.20.0" />
<PackageReference Include="RestSharp" Version="108.0.1" />
</ItemGroup>

<ItemGroup>
Expand Down
14 changes: 13 additions & 1 deletion TsubakiTranslator/UserConfigPage.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,19 @@
<TextBlock Text="详情请搜索『阿里云机器翻译』。"
Style="{StaticResource MaterialDesignHelperTextBlock}"
FontSize="13" Margin="0 8 0 8"/>
<CheckBox Content="启用" IsChecked="{Binding AliyunIsEnabled,Mode=TwoWay}"/>
<CheckBox Content="启用" x:Name="AliEnabledComboBox"
IsChecked="{Binding AliIsEnabled,Mode=TwoWay}"/>

<TextBox materialDesign:HintAssist.Hint="SecretId"
Style="{StaticResource MaterialDesignFloatingHintTextBox}"
VerticalAlignment="Center"
IsEnabled="{Binding Path=IsChecked, ElementName=AliEnabledComboBox}" Cursor="IBeam"
Text="{Binding Path=AliSecretId,Mode=TwoWay}"/>
<TextBox materialDesign:HintAssist.Hint="SecretKey"
Style="{StaticResource MaterialDesignFloatingHintTextBox}"
VerticalAlignment="Center"
IsEnabled="{Binding Path=IsChecked, ElementName=AliEnabledComboBox}" Cursor="IBeam"
Text="{Binding Path=AliSecretKey,Mode=TwoWay}"/>
</StackPanel>
</Expander>

Expand Down

0 comments on commit e81014e

Please sign in to comment.