Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixed #17 #19

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions AutoResxTranslator/AutoResxTranslator.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="DeepLTranslateService.cs" />
<Compile Include="Definitions\ResultHolder.cs" />
<Compile Include="Definitions\TranslationOptions.cs" />
<Compile Include="frmAbout.cs">
Expand Down
120 changes: 120 additions & 0 deletions AutoResxTranslator/DeepLTranslateService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Http;
using System.Threading.Tasks;
using AutoResxTranslator.Definitions;

namespace AutoResxTranslator
{
/// <summary>
/// Translation service using Microsoft Cogntive service.
///
/// ref: https://azure.microsoft.com/en-in/services/cognitive-services/translator-text-api/
/// </summary>
public class DeepLTranslateService
{
private readonly struct TextTranslateResult
{
/// <summary>Initializes a new instance of <see cref="TextTranslateResult" />, used for JSON deserialization.</summary>
[JsonConstructor]
public TextTranslateResult(TextResult[] translations)
{
Translations = translations;
}

/// <summary>Array of <see cref="TextResult" /> objects holding text translation results.</summary>
public TextResult[] Translations { get; }
public sealed class TextResult
{
/// <summary>Initializes a new instance of <see cref="TextResult" />.</summary>
/// <param name="text">Translated text.</param>
/// <param name="detectedSourceLanguageCode">The detected language code of the input text.</param>
/// <remarks>
/// The constructor for this class (and all other Model classes) should not be used by library users. Ideally it
/// would be marked <see langword="internal" />, but needs to be <see langword="public" /> for JSON deserialization.
/// In future this function may have backwards-incompatible changes.
/// </remarks>
[JsonConstructor]
public TextResult(string text, string detectedSourceLanguageCode)
{
Text = text;
DetectedSourceLanguageCode = detectedSourceLanguageCode;
}

/// <summary>The translated text.</summary>
public string Text { get; }

/// <summary>The language code of the source text detected by DeepL.</summary>
[JsonProperty("detected_source_language")]
public string DetectedSourceLanguageCode { get; }

/// <summary>Returns the translated text.</summary>
/// <returns>The translated text.</returns>
public override string ToString() => Text;
}
}
private const string DeepLFreeCognitiveServicesApiUrl = "https://api-free.deepl.com";
private const string DeepLProCognitiveServicesApiUrl = "https://api.deepl.com";
public static async Task<ResultHolder<string>> TranslateAsync(string text,
string fromLanguage,
string toLanguage,
string subscriptionKey,
string region)
{
if (fromLanguage.Equals("auto"))
{
fromLanguage = "";
}

var route = "/v2/translate";

try
{
using (var client = new HttpClient())
using (var request = new HttpRequestMessage())
{
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/x-www-form-urlencoded");
// Build the request.

Dictionary<string, string> data = new Dictionary<string, string>
{
{ "auth_key", subscriptionKey },
{ "text", text },
{ "target_lang", toLanguage.ToUpper() }
};
if (!string.IsNullOrEmpty(fromLanguage))
data.Add("source_lang", fromLanguage.ToUpper());
var response = await client.PostAsync((region == "0" ? DeepLFreeCognitiveServicesApiUrl : DeepLProCognitiveServicesApiUrl) + route,
new System.Net.Http.FormUrlEncodedContent(data));
response.EnsureSuccessStatusCode();

if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
// Read response as a string.
var resultFromDeepL = await response.Content.ReadAsStringAsync();
var deserializedOutput = JsonConvert.DeserializeObject<TextTranslateResult>(resultFromDeepL);

// Iterate over the results, return the first result
foreach (var t in deserializedOutput.Translations)
{
return new ResultHolder<string>(true, t.Text);
}
}
else
{
return new ResultHolder<string>(false, "Translation failed! Exception: " + response.ReasonPhrase);
}
}
return new ResultHolder<string>(false);
}
catch (Exception e)
{
return new ResultHolder<string>(false, "Translation failed! Exception: " + e.Message);
}
}
}
}
3 changes: 2 additions & 1 deletion AutoResxTranslator/Definitions/ServiceTypeEnum.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
public enum ServiceTypeEnum
{
Microsoft,
Google
Google,
DeepL
}
}
6 changes: 5 additions & 1 deletion AutoResxTranslator/Definitions/TranslationOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,5 +13,9 @@ public class TranslationOptions
public string MsSubscriptionKey { get; set; }

public string MsSubscriptionRegion { get; set; }
}

public string DeepLSubscriptionKey { get; set; }

public string DeepLSubscriptionRegion { get; set; }
}
}
26 changes: 25 additions & 1 deletion AutoResxTranslator/Properties/Settings.Designer.cs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions AutoResxTranslator/Properties/Settings.settings
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,11 @@
<Setting Name="MicrosoftTranslatorRegion" Type="System.String" Scope="User">
<Value Profile="(Default)">global</Value>
</Setting>
<Setting Name="DeepLTranslatorKey" Type="System.String" Scope="User">
<Value Profile="(Default)">YOUR_KEY_HERE</Value>
</Setting>
<Setting Name="DeepLTranslatorType" Type="System.Int16" Scope="User">
<Value Profile="(Default)">0</Value>
</Setting>
</Settings>
</SettingsFile>
10 changes: 6 additions & 4 deletions AutoResxTranslator/ResxExcel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,9 @@ public class ResxExcel
public class ExcelFileInfo
{
public string[] SheetNames { get; set; }
public string[] SheetColumns { get; set; }
}
public string[] SheetColumnsKey { get; set; }
public string[] SheetColumnsTranslation { get; set; }
}

public static ExcelFileInfo ReadExcel(string excelFile)
{
Expand Down Expand Up @@ -68,8 +69,9 @@ public static ExcelFileInfo ReadExcel(string excelFile)
columns.Add(column.ColumnName);
}
}
result.SheetColumns = columns.ToArray();
}
result.SheetColumnsKey = columns.ToArray();
result.SheetColumnsTranslation = columns.ToArray();
}
}

return result;
Expand Down
20 changes: 13 additions & 7 deletions AutoResxTranslator/app.config
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,18 @@
</startup>
<userSettings>
<AutoResxTranslator.Properties.Settings>
<setting name="MicrosoftTranslatorKey" serializeAs="String">
<value>YOUR_KEY_HERE</value>
</setting>
<setting name="MicrosoftTranslatorRegion" serializeAs="String">
<value>global</value>
</setting>
</AutoResxTranslator.Properties.Settings>
<setting name="MicrosoftTranslatorKey" serializeAs="String">
<value>YOUR_KEY_HERE</value>
</setting>
<setting name="MicrosoftTranslatorRegion" serializeAs="String">
<value>global</value>
</setting>
<setting name="DeepLTranslatorKey" serializeAs="String">
<value>YOUR_KEY_HERE</value>
</setting>
<setting name="DeepLTranslatorType" serializeAs="String">
<value>0</value>
</setting>
</AutoResxTranslator.Properties.Settings>
</userSettings>
</configuration>
Loading