Skip to content

Commit

Permalink
Change Translate Logic (#7)
Browse files Browse the repository at this point in the history
  • Loading branch information
imnotcode committed Dec 5, 2019
1 parent f5f9ca5 commit 4815673
Show file tree
Hide file tree
Showing 7 changed files with 212 additions and 70 deletions.
22 changes: 21 additions & 1 deletion NCodeParser/Config.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,11 @@ public static INIManager INIManager
private set;
}

public static List<Novel> NovelList = new List<Novel>();
public static List<Novel> NovelList
{
get;
set;
}

public static string NovelPath
{
Expand All @@ -42,6 +46,18 @@ public static string NovelPath
}
}

public static TranslatorType TranslatorType
{
get;
set;
}

public static bool TranslateWithSource
{
get;
set;
}

private static string _NovelPath = "";

public static void Init()
Expand All @@ -50,13 +66,17 @@ public static void Init()

NovelPath = INIManager.GetNovelPath();
NovelList = INIManager.GetNovels();
TranslatorType = TranslatorType.GSheet; // TODO
TranslateWithSource = true; // TODO
}

public static void Save()
{
INIManager.Clear();
INIManager.SetNovelPath(NovelPath);
INIManager.SetNovels(NovelList);
// TODO SetTranslatorType
// TODO
}
}
}
1 change: 1 addition & 0 deletions NCodeParser/Enum.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ public enum NovelType

public enum TranslatorType
{
None,
GSheet,
Google,
Papago,
Expand Down
1 change: 1 addition & 0 deletions NCodeParser/NCodeParser.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,7 @@
<Compile Include="Control\Converter\VisibilityConverter.cs" />
<Compile Include="Enum.cs" />
<Compile Include="Extensions.cs" />
<Compile Include="Translate\BingTranslator.cs" />
<Compile Include="Translate\Translator.cs" />
<Compile Include="IO\CookieAwareWebClient.cs">
<SubType>Component</SubType>
Expand Down
16 changes: 16 additions & 0 deletions NCodeParser/Translate/BingTranslator.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NCodeParser.Translate
{
public class BingTranslator : Translator
{
protected override async Task<string> TranslateOneLine(string input)
{
throw new NotImplementedException();
}
}
}
168 changes: 112 additions & 56 deletions NCodeParser/Translate/GSheetsTranslator.cs
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
using Google.Apis.Sheets.v4;
using Google.Apis.Sheets.v4.Data;
using Google.Apis.Util.Store;
using NCodeParser.Utility;
using static Google.Apis.Sheets.v4.SpreadsheetsResource.ValuesResource.UpdateRequest;

namespace NCodeParser.Translate
Expand All @@ -17,25 +19,28 @@ public class GSheetsTranslator : Translator, IDisposable
private readonly string[] Scopes = { SheetsService.Scope.Spreadsheets };
private readonly string SheetID = "1JZwDTknNzCIpFZNoDLqaWEZcm5oJYUiyD5kPH9T7VAI";

private readonly bool[] RowUsages = new bool[10];
private readonly SemaphoreSlim MainSemaphore = new SemaphoreSlim(10, 10);
private readonly bool[] RowUsages = new bool[1];
private readonly SemaphoreSlim MainSemaphore = new SemaphoreSlim(1, 1);
private readonly SemaphoreSlim IDSemaphore = new SemaphoreSlim(1, 1);

protected override async Task<string> TranslateOneLine(string input)
private SheetsService Service;

public GSheetsTranslator()
{
int rowID = -1;

}

public async Task InitializeService()
{
try
{
await MainSemaphore.WaitAsync().ConfigureAwait(false);

UserCredential credential;

if (!File.Exists("credentials.json"))
{
return input;
return;
}

UserCredential credential;

using (var stream = new FileStream("credentials.json", FileMode.Open, FileAccess.Read))
{
// The file token.json stores the user's access and refresh tokens, and is created
Expand All @@ -49,41 +54,109 @@ protected override async Task<string> TranslateOneLine(string input)
new FileDataStore(credPath, true)).ConfigureAwait(false);
}

using (var sheetService = new SheetsService(new BaseClientService.Initializer()
Service = new SheetsService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = Config.ApplicationName,
}))
ApplicationName = Config.ApplicationName
});
}
catch
{

}
}

public override async Task<string> Translate(string input)
{
var dividedTexts = StringUtil.DivideString(input);

var sourceList = new List<string>();
var builder = new StringBuilder();

for (int i = 0; i < dividedTexts.Length; i++)
{
if (!string.IsNullOrWhiteSpace(dividedTexts[i]))
{
rowID = await GetRowID().ConfigureAwait(false);
if (rowID == -1)
sourceList.Add(dividedTexts[i]);

builder.Append(dividedTexts[i]);
builder.Append(" | ");
}
}

var result = await TranslateOneLine(builder.ToString()).ConfigureAwait(false);
var splitTexts = result.Split(new string[] { "|" }, StringSplitOptions.RemoveEmptyEntries);

builder.Clear();
for (int i = 0, j = 0; i < dividedTexts.Length; i++)
{
if (!string.IsNullOrWhiteSpace(dividedTexts[i]))
{
var translatedText = splitTexts[j++].Trim();

if (Config.TranslateWithSource && dividedTexts[i] != translatedText)
{
return input;
builder.Append(dividedTexts[i]);
builder.Append(Environment.NewLine);
}

string from = "A" + rowID;
string to = "E" + rowID;
builder.Append(translatedText);
}

builder.Append(Environment.NewLine);
}

return builder.ToString();
}

protected override async Task<string> TranslateOneLine(string input)
{
int rowID = -1;

try
{
if (Service == null)
{
return input;
}

await MainSemaphore.WaitAsync().ConfigureAwait(false);

rowID = await GetRowID().ConfigureAwait(false);
if (rowID == -1)
{
return input;
}

IList<IList<object>> list = new List<IList<object>>();
list.Add(new List<object>() { input, "=GOOGLETRANSLATE(" + from + ", \"ja\", \"ko\")" });
string from = "A" + rowID;
string to = "E" + rowID;

var range = new ValueRange();
range.Values = list;
IList<IList<object>> list = new List<IList<object>>();
list.Add(new List<object>() { input, "=GOOGLETRANSLATE(" + from + ", \"ja\", \"ko\")" });

var request = sheetService.Spreadsheets.Values.Update(range, SheetID, $"{from}:{to}");
request.ValueInputOption = ValueInputOptionEnum.USERENTERED;
var range = new ValueRange();
range.Values = list;

var response = await request.ExecuteAsync().ConfigureAwait(false);
var request = Service.Spreadsheets.Values.Update(range, SheetID, $"{from}:{to}");
request.ValueInputOption = ValueInputOptionEnum.USERENTERED;

var result = await Load(rowID).ConfigureAwait(false);
if (string.IsNullOrWhiteSpace(result))
{
return input;
}
else
var response = await request.ExecuteAsync().ConfigureAwait(false);

var result = await Load(rowID).ConfigureAwait(false);
if (string.IsNullOrWhiteSpace(result))
{
return input;
}
else
{
if (result == "로드 중...")
{
return result;
ReleaseRowID(rowID);

return await TranslateOneLine(input).ConfigureAwait(false);
}

return result;
}
}
catch
Expand Down Expand Up @@ -145,37 +218,20 @@ private async Task<string> Load(int rowID)
{
try
{
UserCredential credential;

using (var stream = new FileStream("credentials.json", FileMode.Open, FileAccess.Read))
if (Service == null)
{
// The file token.json stores the user's access and refresh tokens, and is created
// automatically when the authorization flow completes for the first time.
string credPath = "token.json";
credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
Scopes,
"user",
CancellationToken.None,
new FileDataStore(credPath, true)).ConfigureAwait(false);
return "";
}

using (var sheetService = new SheetsService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = Config.ApplicationName,
}))
{
string from = "A" + rowID;
string to = "E" + rowID;
string from = "A" + rowID;
string to = "E" + rowID;

var request = sheetService.Spreadsheets.Values.BatchGet(SheetID);
request.Ranges = $"{from}:{to}";
var request = Service.Spreadsheets.Values.BatchGet(SheetID);
request.Ranges = $"{from}:{to}";

var response = await request.ExecuteAsync().ConfigureAwait(false);
var response = await request.ExecuteAsync().ConfigureAwait(false);

return response.ValueRanges[0].Values[0][1].ToString();
}
return response.ValueRanges[0].Values[0][1].ToString();
}
catch
{
Expand Down
13 changes: 12 additions & 1 deletion NCodeParser/Translate/Translator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ namespace NCodeParser.Translate
{
public abstract class Translator
{
public async Task<string> Translate(string input)
public virtual async Task<string> Translate(string input)
{
var dividedTexts = StringUtil.DivideString(input);
var tasks = new List<Task<string>>();
Expand All @@ -31,10 +31,21 @@ public async Task<string> Translate(string input)
{
var translatedText = await tasks[j++].ConfigureAwait(false);

if (Config.TranslateWithSource && dividedTexts[i] != translatedText)
{
builder.Append(dividedTexts[i]);
builder.Append(Environment.NewLine);
}

builder.Append(translatedText);
}

builder.Append(Environment.NewLine);

if (Config.TranslateWithSource)
{
builder.Append(Environment.NewLine);
}
}

return builder.ToString();
Expand Down
Loading

0 comments on commit 4815673

Please sign in to comment.