Skip to content

Commit

Permalink
初版 1.0.0
Browse files Browse the repository at this point in the history
  • Loading branch information
tangge233 committed Aug 23, 2024
1 parent 8b8655f commit 9146b53
Show file tree
Hide file tree
Showing 4 changed files with 90 additions and 46 deletions.
4 changes: 3 additions & 1 deletion XamlTranslater/MainWindow.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,9 @@
</ComboBox>
<Button Content="一键生草" VerticalAlignment="Center" Name="BtnStart" Click="BtnStart_Click"/>
<Button Content="开始写入" VerticalAlignment="Center" Name="BtnExport" Click="BtnExport_Click"/>
<TextBlock Text="DeepL Key:" VerticalAlignment="Center"/>
<TextBlock Text="ID:" VerticalAlignment="Center"/>
<TextBox VerticalAlignment="Center" Width="100" Name="TextSetID"/>
<TextBlock Text="Key:" VerticalAlignment="Center"/>
<TextBox VerticalAlignment="Center" Width="100" Name="TextSetkey"/>
</StackPanel>
</StackPanel>
Expand Down
76 changes: 31 additions & 45 deletions XamlTranslater/MainWindow.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -78,77 +78,63 @@ private async void BrowseButton_Click(object sender, RoutedEventArgs e)
}
}

private async Task<string> TranslateContent(string content, string targetLanguage)
{
using (var httpClient = new HttpClient())
{
var apiKey = TextSetkey.Text;
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("DeepL-Auth-Key", apiKey);

var requestBody = new Dictionary<string, string>
{
{ "text", content },
{ "target_lang", targetLanguage }
};

var response = await httpClient.PostAsync("https://api-free.deepl.com/v2/translate", new FormUrlEncodedContent(requestBody));

if (response.StatusCode !=HttpStatusCode.OK)
{
MessageBox.Show($"获取翻译失败:{response.ToString()}");
response.EnsureSuccessStatusCode();
}

var jsonResponse = await response.Content.ReadAsStringAsync();
var translationResult = JsonConvert.DeserializeObject<DeepLResponse>(jsonResponse);
return translationResult.Translations[0].Text;
}
}

public class DeepLResponse
{
public List<Translation> Translations { get; set; }
}

public class Translation
{
public string Text { get; set; }
}

private async void BtnStart_Click(object sender, RoutedEventArgs e)
{
var translater = new Translater.Ali(TextSetID.Text,TextSetkey.Text);
if (string.IsNullOrEmpty(filePath))
{
MessageBox.Show("请先选择文件");
return;
}
foreach (var item in ListViewTranslation.Items.OfType<ContentStructure>().ToList())
var newList = ListViewTranslation.Items.OfType<ContentStructure>().ToList();
foreach (var item in newList)
{
item.TranslatedText = await TranslateContent(item.OriginalContent,ComboLang.Text);
//item.TranslatedText = "测试加入" + item.Key;
//continue;
item.TranslatedText = await translater.GetTranslation(item.OriginalContent,ComboLang.Text);
if (item.TranslatedText == item.OriginalContent)
{
if (MessageBox.Show("内容疑似未翻译成功,是否继续?", "翻译疑似有问题", MessageBoxButton.YesNo) == MessageBoxResult.No)
{
return;
}
}
}
ListViewTranslation.ItemsSource = newList;
MessageBox.Show("所有生草已完成!");
}

private void BtnExport_Click(object sender, RoutedEventArgs e)
{
if( MessageBox.Show("即将修改当前文件,是否继续?","确认",MessageBoxButton.YesNo) != MessageBoxResult.OK)
if (string.IsNullOrEmpty(filePath))
{
return;
}
if( MessageBox.Show("即将修改当前文件,是否继续?","确认",MessageBoxButton.YesNo) != MessageBoxResult.Yes)
{
return;
}
XDocument xdoc = XDocument.Load(filePath);
int ModifyNum = 0;
foreach (var item in ListViewTranslation.Items.OfType<ContentStructure>().ToList())
{
var elementToModify = xdoc.Descendants().Where(e =>e.Attributes("x:Key").Any(a => a.Value == item.Key)).FirstOrDefault();
if (elementToModify != null)
try
{
var contentElement = elementToModify.Element("Content");
if (contentElement != null)
var elementToModify = xdoc.Descendants().ToList().Where(e => e.Attributes().ToList()[0].Value == item.Key).FirstOrDefault();
if (elementToModify != null)
{
contentElement.Value = item.TranslatedText;
elementToModify.Value = item.TranslatedText;
ModifyNum++;
}
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString(),"替换翻译字符失败",MessageBoxButton.OK,MessageBoxImage.Error);
return;
}
}
xdoc.Save(filePath);
MessageBox.Show($"共修改 {ModifyNum} 项","完成!");
}
}
}
55 changes: 55 additions & 0 deletions XamlTranslater/Translater.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
using AlibabaCloud.SDK.Alimt20181012.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Markup;

namespace XamlTranslater
{
public class Translater
{
public class Ali
{
private AlibabaCloud.SDK.Alimt20181012.Client Client;

public Ali(string KeyID,string KeySecret)
{
AlibabaCloud.OpenApiClient.Models.Config config = new AlibabaCloud.OpenApiClient.Models.Config
{
// 必填,请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。
AccessKeyId = Environment.GetEnvironmentVariable(KeyID),
// 必填,请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
AccessKeySecret = Environment.GetEnvironmentVariable(KeySecret),
};
// Endpoint 请参考 https://api.aliyun.com/product/alimt
config.Endpoint = "mt.cn-hangzhou.aliyuncs.com";
Client = new AlibabaCloud.SDK.Alimt20181012.Client(config);
}

public async Task<string> GetTranslation(string Content,string Target)
{
AlibabaCloud.SDK.Alimt20181012.Models.TranslateGeneralRequest translateGeneralRequest = new AlibabaCloud.SDK.Alimt20181012.Models.TranslateGeneralRequest
{
TargetLanguage = Target,
SourceText = Content,
Scene = "general",
};
AlibabaCloud.TeaUtil.Models.RuntimeOptions runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
try
{
var res = await Client.TranslateGeneralWithOptionsAsync(translateGeneralRequest, runtime);
return res.Body.Data.Translated;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(),ex.Message);
}
return Content;
}
}
}
}
1 change: 1 addition & 0 deletions XamlTranslater/XamlTranslater.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="AlibabaCloud.SDK.Alimt20181012" Version="2.3.0" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
</ItemGroup>

Expand Down

0 comments on commit 9146b53

Please sign in to comment.