forked from lokinmodar/Echoglossian
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTranslationHandler.cs
83 lines (65 loc) · 2.55 KB
/
TranslationHandler.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
// <copyright file="TranslationHandler.cs" company="lokinmodar">
// Copyright (c) lokinmodar. All rights reserved.
// Licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International Public License license.
// </copyright>
using System.Collections.Concurrent;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
namespace Echoglossian;
public class TranslationHandler
{
private readonly ConcurrentDictionary<string, string> translations = new();
public async Task HandleTextEntered(string text, DbContext dbContext)
{
// Check if the translated text already exists in the database
var translatedTextFromDb = await dbContext.Set<Translation>()
.Where(t => t.OriginalText == text)
.Select(t => t.TranslatedText)
.FirstOrDefaultAsync();
if (translatedTextFromDb != null)
{
// The translated text already exists in the database, show it in the UI
this.ShowTranslatedText(text, translatedTextFromDb);
}
else
{
// Add the original text to the ConcurrentDictionary with the value set to "translating..."
this.translations.TryAdd(text, "translating...");
// Update the UI to show "translating..."
this.ShowTranslating(text);
// Call the TranslateAsync method on a separate thread
var translatedText = await Task.Run(() => this.TranslateAsync(text));
// Update the value of the key in the ConcurrentDictionary with the translated text
this.translations.TryUpdate(text, translatedText, "translating...");
// Store the translated text in the database
var translation = new Translation
{ OriginalText = text, TranslatedText = translatedText };
dbContext.Set<Translation>().Add(translation);
await dbContext.SaveChangesAsync();
// Update the UI to show the translated text
this.ShowTranslatedText(text, translatedText);
}
}
private async Task<string> TranslateAsync(string text)
{
// Call the translation API and get the translated text
// string translatedText = await YourTranslationAPICall(text);
// Return the translated text
return $"a {text.ToString()}"; // translatedText;
}
private void ShowTranslating(string text)
{
// Update the UI to show "translating..."
}
private void ShowTranslatedText(string originalText, string translatedText)
{
// Update the UI to show the translated text
}
}
public class Translation
{
public int Id { get; set; }
public string OriginalText { get; set; }
public string TranslatedText { get; set; }
}