Agrgado la opcion OCRaTexto para hacer OCR de la pantalla y corregirlo usando LLM

This commit is contained in:
Miguel 2025-01-28 17:10:49 +01:00
parent e44f696ece
commit 5c6706aad1
10 changed files with 663 additions and 53 deletions

View File

@ -34,6 +34,18 @@ namespace GTPCorrgir
{
pasteLogic.SaveCurrentWindow();
if (Opciones.Instance.modo == Opciones.modoDeUso.OCRaTexto)
{
var captureWindow = new ScreenCaptureWindow();
captureWindow.Show();
}
else if (Opciones.Instance.modo == Opciones.modoDeUso.Chat)
{
var chatWindows = new Chat(GTP);
chatWindows.Show();
}
else {
if (Opciones.Instance.AutoCopy)
{
await pasteLogic.AutoCopyFromActiveWindow();
@ -62,10 +74,6 @@ namespace GTPCorrgir
// Ejecuta la tarea de corrección con timeout
_ = ProcessCorreccionWithTimeout();
}
else if (Opciones.Instance.modo == Opciones.modoDeUso.Chat)
{
var chatWindows = new Chat(GTP);
chatWindows.Show();
}
}
catch (Exception ex)
@ -117,21 +125,22 @@ namespace GTPCorrgir
ShowCustomNotification("Se puede pegar",
$"Corrección en: {Math.Round(stopwatch.ElapsedMilliseconds / 1000.0, 1)} s");
if (Opciones.Instance.modo == Opciones.modoDeUso.Corregir)
if (Opciones.Instance.modo == Opciones.modoDeUso.Corregir || Opciones.Instance.modo == Opciones.modoDeUso.Ortografia)
{
GTP.Log.Log("Ejecutando pegado automático");
await pasteLogic.RestoreAndSimulatePaste();
//GTP.Log.Log("Mostrando ventana de resultado");
// var resultadoWindow = new VentanaResultado(GTP.TextoCorregido);
// resultadoWindow.Show();
// await Task.Delay(1000);
if (Opciones.Instance.FuncionesOpcionales == Opciones.funcionesOpcionales.MostrarPopUp)
{
GTP.Log.Log("Mostrando ventana de resultado");
var resultadoWindow = new VentanaResultado(GTP.TextoCorregido);
resultadoWindow.Show();
await Task.Delay(1000);
}
else if (Opciones.Instance.modo == Opciones.modoDeUso.Ortografia)
else
{
GTP.Log.Log("Ejecutando pegado automático");
await pasteLogic.RestoreAndSimulatePaste();
}
}
}
else
{
GTP.Log.Log("Error: TextoCorregido es null");

View File

@ -24,6 +24,9 @@
<PackageReference Include="LanguageDetection" Version="1.2.0" />
<PackageReference Include="Markdown.Xaml" Version="1.0.0" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="System.Drawing.Common" Version="9.0.1" />
<PackageReference Include="Tesseract" Version="5.2.0" />
<PackageReference Include="Tesseract.Drawing" Version="5.2.0" />
</ItemGroup>
<ItemGroup>
@ -36,6 +39,15 @@
<None Update="appsettings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="tessdata\eng.traineddata">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="tessdata\ita.traineddata">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="tessdata\spa.traineddata">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>

View File

@ -39,15 +39,19 @@ namespace GTPCorrgir
// Pequeña pausa para asegurar que la ventana tiene el foco
await Task.Delay(100);
if (Opciones.Instance.FuncionesOpcionales == Opciones.funcionesOpcionales.CtrlA)
{
// Simular Ctrl+A
keybd_event(VK_CONTROL, 0, KEYEVENTF_EXTENDEDKEY, UIntPtr.Zero);
keybd_event(VK_A, 0, KEYEVENTF_EXTENDEDKEY, UIntPtr.Zero);
keybd_event(VK_A, 0, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, UIntPtr.Zero);
keybd_event(VK_CONTROL, 0, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, UIntPtr.Zero);
}
// Pequeña pausa entre comandos
await Task.Delay(50);
// Simular Ctrl+C
keybd_event(VK_CONTROL, 0, KEYEVENTF_EXTENDEDKEY, UIntPtr.Zero);
keybd_event(VK_C, 0, KEYEVENTF_EXTENDEDKEY, UIntPtr.Zero);
keybd_event(VK_C, 0, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, UIntPtr.Zero);
keybd_event(VK_CONTROL, 0, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, UIntPtr.Zero);

198
OcrTextProcessor.cs Normal file
View File

@ -0,0 +1,198 @@
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace GTPCorrgir
{
public class OcrTextProcessor : IDisposable
{
private readonly HttpClient _httpClient;
private string _openAiApiKey;
private bool _disposed;
public OcrTextProcessor()
{
_httpClient = new HttpClient();
InitializeProcessor();
}
private void InitializeProcessor()
{
try
{
LoadApiKey();
InitializeHttpClient();
}
catch (Exception ex)
{
throw new ApplicationException("Error initializing OCR Text Processor", ex);
}
}
private void LoadApiKey()
{
string configPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "appsettings.json");
if (!File.Exists(configPath))
{
throw new FileNotFoundException("Configuration file (appsettings.json) not found.");
}
string jsonContent = File.ReadAllText(configPath);
var settings = JsonConvert.DeserializeObject<ApiSettings>(jsonContent);
_openAiApiKey = settings?.ApiKeys?.OpenAI;
if (string.IsNullOrEmpty(_openAiApiKey))
{
throw new ApplicationException("OpenAI API key is missing");
}
}
private void InitializeHttpClient()
{
_httpClient.Timeout = TimeSpan.FromSeconds(30);
_httpClient.DefaultRequestHeaders.Clear();
_httpClient.DefaultRequestHeaders.Add("Accept", "application/json");
}
public async Task<string> ProcessOcrText(string ocrText)
{
try
{
// Correct OCR errors using LLM
// string correctedText = await CorrectOcrErrors(ocrText);
string correctedText = ocrText;
// Apply minimal markdown formatting
string formattedText = ApplyBasicFormatting(correctedText);
// Copiar al portapapeles usando ClipboardHelper
await ClipboardHelper.SetText(formattedText);
return formattedText;
}
catch (Exception ex)
{
throw new ApplicationException("Error processing OCR text", ex);
}
}
private async Task<string> CorrectOcrErrors(string text)
{
try
{
_httpClient.DefaultRequestHeaders.Clear();
_httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {_openAiApiKey}");
var requestData = new
{
model = "gpt-4",
messages = new[]
{
new {
role = "system",
content = "You are an expert at correcting OCR errors. Fix common OCR mistakes like: confused characters (0/O, l/I, rn/m), broken words, and formatting issues. Preserve the original structure and meaning. Respond only with the corrected text in JSON format: {\"corrected_text\": \"your text here\"}"
},
new {
role = "user",
content = $"Please correct any OCR errors in this text: {text}"
}
}
};
var content = new StringContent(
JsonConvert.SerializeObject(requestData),
Encoding.UTF8,
"application/json"
);
using var response = await _httpClient.PostAsync("https://api.openai.com/v1/chat/completions", content);
var responseContent = await response.Content.ReadAsStringAsync();
if (!response.IsSuccessStatusCode)
{
throw new HttpRequestException($"Error calling OpenAI API: {response.StatusCode} - {responseContent}");
}
var responseData = JsonConvert.DeserializeObject<dynamic>(responseContent);
string correctedText = responseData.choices[0].message.content;
// Extract the actual text from the JSON response
var jsonResponse = JsonConvert.DeserializeObject<dynamic>(correctedText);
return jsonResponse.corrected_text.ToString();
}
catch (Exception ex)
{
throw new ApplicationException("Error correcting OCR text", ex);
}
}
private string ApplyBasicFormatting(string text)
{
var lines = text.Split('\n');
var result = new StringBuilder();
for (int i = 0; i < lines.Length; i++)
{
string currentLine = lines[i].Trim();
// Skip empty lines
if (string.IsNullOrWhiteSpace(currentLine))
{
result.AppendLine();
continue;
}
// Basic heading detection (ALL CAPS lines)
if (currentLine == currentLine.ToUpper() && currentLine.Length > 20)
{
result.AppendLine($"# {currentLine}");
}
// Basic list detection
else if (currentLine.StartsWith("•") || currentLine.StartsWith("*"))
{
result.AppendLine($"- {currentLine.Substring(1).Trim()}");
}
// Numbered list detection
else if (System.Text.RegularExpressions.Regex.IsMatch(currentLine, @"^\d+[\.\)]"))
{
result.AppendLine(currentLine);
}
// Normal text
else
{
result.AppendLine(currentLine);
}
}
return result.ToString().Trim();
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!_disposed)
{
if (disposing)
{
_httpClient?.Dispose();
}
_disposed = true;
}
}
~OcrTextProcessor()
{
Dispose(false);
}
}
}

View File

@ -17,6 +17,14 @@ namespace GTPCorrgir
Grok
}
[Flags]
public enum funcionesOpcionales
{
None = 0,
CtrlA = 1 << 0, // Selecciona todo el texto en la ventana activa
MostrarPopUp = 1 << 1 // Muestra un pop-up con el resultado
}
public enum modoDeUso
{
Corregir,
@ -25,6 +33,7 @@ namespace GTPCorrgir
Traducir_a_Ingles,
Traducir_a_Italiano,
Traducir_a_Espanol,
OCRaTexto,
}
public Dictionary<LLM_a_Usar, string> nombreLLM = new Dictionary<LLM_a_Usar, string>
@ -46,7 +55,8 @@ namespace GTPCorrgir
{
_instance = new Opciones();
_instance.LLM = LLM_a_Usar.OpenAI;
_instance.modo = modoDeUso.Chat;
_instance.modo = modoDeUso.OCRaTexto;
_instance.FuncionesOpcionales = 0;
_instance.AutoCopy = false;
}
return _instance;
@ -55,6 +65,7 @@ namespace GTPCorrgir
public LLM_a_Usar LLM { get; set; }
public modoDeUso modo { get; set; }
public funcionesOpcionales FuncionesOpcionales { get; set; }
public string nombreDeLLM()
{
@ -86,19 +97,26 @@ namespace GTPCorrgir
else if (arg.Contains("OpenAI"))
Opciones.Instance.LLM = Opciones.LLM_a_Usar.OpenAI;
if (arg.Contains("CtrlA"))
Opciones.Instance.FuncionesOpcionales = Opciones.funcionesOpcionales.CtrlA;
if (arg.Contains("PopUp"))
Opciones.Instance.FuncionesOpcionales |= Opciones.funcionesOpcionales.MostrarPopUp;
if (arg.Contains("Chat"))
Opciones.Instance.modo = Opciones.modoDeUso.Chat;
else if (arg.Contains("Ortografia"))
if (arg.Contains("Ortografia"))
Opciones.Instance.modo = Opciones.modoDeUso.Ortografia;
else if (arg.Contains("Corregir"))
if (arg.Contains("Corregir"))
Opciones.Instance.modo = Opciones.modoDeUso.Corregir;
else if (arg.Contains("Traducir_a_Ingles"))
if (arg.Contains("Traducir_a_Ingles"))
Opciones.Instance.modo = Opciones.modoDeUso.Traducir_a_Ingles;
else if (arg.Contains("Traducir_a_Italiano"))
if (arg.Contains("Traducir_a_Italiano"))
Opciones.Instance.modo = Opciones.modoDeUso.Traducir_a_Italiano;
else if (arg.Contains("Traducir_a_Espanol"))
if (arg.Contains("Traducir_a_Espanol"))
Opciones.Instance.modo = Opciones.modoDeUso.Traducir_a_Espanol;
else if (arg.Contains("AutoCopy"))
if (arg.Contains("OCRaTexto"))
Opciones.Instance.modo = Opciones.modoDeUso.OCRaTexto;
if (arg.Contains("AutoCopy"))
Opciones.Instance.AutoCopy = true;
}
}

368
ScreenCaptureWindow.cs Normal file
View File

@ -0,0 +1,368 @@
using System;
using System.IO;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Controls;
using System.Windows.Shapes;
using Tesseract;
using System.Threading.Tasks;
using Point = System.Windows.Point;
using Rect = System.Windows.Rect;
using Size = System.Windows.Size;
using Brushes = System.Windows.Media.Brushes;
using Cursors = System.Windows.Input.Cursors;
using Cursor = System.Windows.Input.Cursor;
using Color = System.Windows.Media.Color;
using Path = System.IO.Path;
using MessageBox = System.Windows.MessageBox;
using MouseEventArgs = System.Windows.Input.MouseEventArgs;
using KeyEventArgs = System.Windows.Input.KeyEventArgs;
using Rectangle = System.Windows.Shapes.Rectangle;
namespace GTPCorrgir
{
public class ScreenCaptureWindow : Window
{
private Point startPoint;
private Point currentPoint;
private bool hasFirstPoint;
private System.Windows.Shapes.Rectangle selectionRectangle;
private Canvas overlayCanvas;
private readonly Cursor crosshairCursor = Cursors.Cross;
private Window overlayWindow;
private System.Windows.Forms.Screen targetScreen; // Añadimos esta referencia
public ScreenCaptureWindow()
{
InitializeInitialWindow();
}
private void InitializeInitialWindow()
{
// Calcular el rectángulo virtual que engloba todas las pantallas
var allScreens = System.Windows.Forms.Screen.AllScreens;
int minX = allScreens.Min(s => s.Bounds.Left);
int minY = allScreens.Min(s => s.Bounds.Top);
int maxX = allScreens.Max(s => s.Bounds.Right);
int maxY = allScreens.Max(s => s.Bounds.Bottom);
// Configurar la ventana inicial para cubrir todas las pantallas
this.WindowStyle = WindowStyle.None;
this.ResizeMode = ResizeMode.NoResize;
this.Width = maxX - minX;
this.Height = maxY - minY;
this.Left = minX;
this.Top = minY;
this.AllowsTransparency = true;
this.Background = new SolidColorBrush(Color.FromArgb(0, 0, 0, 0));
this.ShowInTaskbar = false;
this.Topmost = true;
this.Cursor = crosshairCursor;
// Añadir un panel transparente que cubra toda la ventana
var panel = new Grid
{
Background = new SolidColorBrush(Color.FromArgb(1, 0, 0, 0))
};
this.Content = panel;
// Agregar el evento del primer clic
this.MouseLeftButtonDown += InitialWindow_MouseLeftButtonDown;
}
private void InitialWindow_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
// Obtener la pantalla donde se hizo clic
var clickPoint = PointToScreen(e.GetPosition(this));
Console.WriteLine($"Click point screen coords: X={clickPoint.X}, Y={clickPoint.Y}");
targetScreen = System.Windows.Forms.Screen.FromPoint(
new System.Drawing.Point((int)clickPoint.X, (int)clickPoint.Y));
Console.WriteLine($"Target screen bounds: Left={targetScreen.Bounds.Left}, Top={targetScreen.Bounds.Top}, Right={targetScreen.Bounds.Right}, Bottom={targetScreen.Bounds.Bottom}");
// Remover este evento ya que solo lo necesitamos una vez
this.MouseLeftButtonDown -= InitialWindow_MouseLeftButtonDown;
// Calcular el punto relativo a la pantalla objetivo
startPoint = new Point(
clickPoint.X - targetScreen.Bounds.Left,
clickPoint.Y - targetScreen.Bounds.Top
);
Console.WriteLine($"Start point relative coords: X={startPoint.X}, Y={startPoint.Y}");
// Inicializar la ventana de overlay ANTES de posicionar el rectángulo
InitializeOverlayWindow(targetScreen);
// Asegurarse que el overlay esté completamente inicializado
overlayWindow.Dispatcher.Invoke(() =>
{
selectionRectangle.Visibility = Visibility.Visible;
Canvas.SetLeft(selectionRectangle, startPoint.X);
Canvas.SetTop(selectionRectangle, startPoint.Y);
selectionRectangle.Width = 0;
selectionRectangle.Height = 0;
hasFirstPoint = true;
});
}
private void InitializeOverlayWindow(System.Windows.Forms.Screen screen)
{
overlayWindow = new Window
{
WindowStyle = WindowStyle.None,
ResizeMode = ResizeMode.NoResize,
AllowsTransparency = true,
Background = new SolidColorBrush(Color.FromArgb(128, 0, 0, 0)),
Topmost = true,
ShowInTaskbar = false,
Width = screen.Bounds.Width,
Height = screen.Bounds.Height,
WindowStartupLocation = WindowStartupLocation.Manual,
Left = screen.Bounds.Left,
Top = screen.Bounds.Top
};
InitializeComponents(overlayWindow);
SetupEventHandlers();
overlayWindow.Show();
overlayWindow.Activate(); // Asegurar que la ventana tiene el foco
this.Hide();
}
private void InitializeComponents(Window window)
{
overlayCanvas = new Canvas
{
HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch,
VerticalAlignment = System.Windows.VerticalAlignment.Stretch
};
var grid = new Grid();
grid.Children.Add(overlayCanvas);
window.Content = grid;
selectionRectangle = new System.Windows.Shapes.Rectangle
{
Stroke = new SolidColorBrush(Colors.Red),
StrokeThickness = 2,
Fill = new SolidColorBrush(Color.FromArgb(50, 255, 255, 255)),
Visibility = Visibility.Collapsed
};
overlayCanvas.Children.Add(selectionRectangle);
}
private void SetupEventHandlers()
{
overlayWindow.MouseLeftButtonDown += OverlaySecondPoint_MouseLeftButtonDown;
overlayWindow.MouseMove += OverlayCanvas_MouseMove;
overlayWindow.KeyDown += MainWindow_KeyDown;
}
private void OverlayCanvas_MouseMove(object sender, MouseEventArgs e)
{
if (!hasFirstPoint) return;
currentPoint = e.GetPosition(overlayCanvas);
UpdateSelectionRectangle(startPoint, currentPoint);
}
private void OverlaySecondPoint_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
if (!hasFirstPoint) return;
// Capturar el segundo punto
var endPoint = e.GetPosition(overlayCanvas);
// Validar el tamaño del rectángulo
double width = Math.Abs(endPoint.X - startPoint.X);
double height = Math.Abs(endPoint.Y - startPoint.Y);
// Validar tamaño mínimo (5x5 pixels)
const double MIN_SIZE = 5.0;
if (width < MIN_SIZE || height < MIN_SIZE)
{
selectionRectangle.Visibility = Visibility.Collapsed;
var notification = new notificacion();
notification.UpdateNotification("Selección muy pequeña",
"Por favor, seleccione un área más grande (mínimo 5x5 píxeles)");
notification.Show();
hasFirstPoint = false;
return;
}
// Ocultar el rectángulo inmediatamente
selectionRectangle.Visibility = Visibility.Collapsed;
// Mostrar notificación de procesamiento
var processingNotification = new notificacion();
processingNotification.UpdateNotification("Procesando", "Analizando imagen seleccionada...");
processingNotification.Show();
// Si las validaciones pasan, proceder con la captura
CaptureAndProcessArea();
}
private void UpdateSelectionRectangle(Point start, Point current)
{
double x = Math.Min(start.X, current.X);
double y = Math.Min(start.Y, current.Y);
double width = Math.Abs(current.X - start.X);
double height = Math.Abs(current.Y - start.Y);
Canvas.SetLeft(selectionRectangle, x);
Canvas.SetTop(selectionRectangle, y);
selectionRectangle.Width = width;
selectionRectangle.Height = height;
}
private void MainWindow_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Escape)
{
overlayWindow?.Close();
this.Close();
}
}
private string GetTesseractExecutablePath()
{
string baseDir = AppDomain.CurrentDomain.BaseDirectory;
string tessDataDir = Path.Combine(baseDir, "tessdata");
if (!Directory.Exists(tessDataDir))
{
throw new DirectoryNotFoundException(
$"No se encontró el directorio tessdata en {tessDataDir}. " +
"Asegúrate de que la carpeta tessdata existe y contiene los archivos de entrenamiento.");
}
return tessDataDir;
}
private BitmapSource CaptureScreen(double x, double y, double width, double height)
{
try
{
// Usar la referencia guardada del screen objetivo
var screenPoint = new System.Drawing.Point(
(int)(targetScreen.Bounds.Left + x),
(int)(targetScreen.Bounds.Top + y)
);
Console.WriteLine($"Capture coordinates: X={screenPoint.X}, Y={screenPoint.Y}, Width={width}, Height={height}");
using (var screenBmp = new System.Drawing.Bitmap(
(int)width,
(int)height,
System.Drawing.Imaging.PixelFormat.Format32bppArgb))
{
using (var bmpGraphics = System.Drawing.Graphics.FromImage(screenBmp))
{
bmpGraphics.CopyFromScreen(
screenPoint.X,
screenPoint.Y,
0,
0,
new System.Drawing.Size((int)width, (int)height)
);
}
using (var memory = new MemoryStream())
{
screenBmp.Save(memory, System.Drawing.Imaging.ImageFormat.Png);
memory.Position = 0;
var bitmapImage = new BitmapImage();
bitmapImage.BeginInit();
bitmapImage.StreamSource = memory;
bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
bitmapImage.EndInit();
bitmapImage.Freeze();
return bitmapImage;
}
}
}
catch (Exception ex)
{
MessageBox.Show($"Error al capturar pantalla: {ex.Message}");
return null;
}
}
private async void CaptureAndProcessArea()
{
try
{
this.Hide();
await Task.Delay(100);
double x = Canvas.GetLeft(selectionRectangle);
double y = Canvas.GetTop(selectionRectangle);
double width = selectionRectangle.Width;
double height = selectionRectangle.Height;
var screenCapture = CaptureScreen(x, y, width, height);
if (screenCapture == null) return;
var screenBitmap = new RenderTargetBitmap(
(int)width,
(int)height,
96, 96,
PixelFormats.Pbgra32);
var visual = new DrawingVisual();
using (var context = visual.RenderOpen())
{
context.DrawImage(screenCapture, new Rect(0, 0, width, height));
}
screenBitmap.Render(visual);
var encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(screenBitmap));
using (var memoryStream = new MemoryStream())
{
encoder.Save(memoryStream);
memoryStream.Position = 0;
string tesseractPath = GetTesseractExecutablePath();
using (var engine = new TesseractEngine(tesseractPath, "eng", EngineMode.Default))
{
engine.SetVariable("tessedit_char_whitelist", " ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-.");
using (var img = Pix.LoadFromMemory(memoryStream.ToArray()))
{
var result = engine.Process(img);
string ocrText = result.GetText();
using (var textProcessor = new OcrTextProcessor())
{
string processedText = await textProcessor.ProcessOcrText(ocrText);
var notificationWindow = new notificacion();
notificationWindow.UpdateNotification("OCR Completado", "Texto copiado al portapapeles");
notificationWindow.Show();
}
}
}
}
}
catch (Exception ex)
{
MessageBox.Show($"Error processing capture: {ex.Message}",
"Error", MessageBoxButton.OK, MessageBoxImage.Error);
}
finally
{
overlayWindow?.Close();
this.Close();
}
}
}
}

View File

@ -263,6 +263,7 @@ namespace GTPCorrgir
}
TextoCorregido = _markdownProcessor.RemoveTechnicalTermMarkers_IgnoreCase(TextoCorregido).Trim('"');
TextoCorregido = _markdownProcessor.RemoveDoubleBrackets(TextoCorregido);
}
private async Task SimularCorreccion()
@ -303,12 +304,12 @@ namespace GTPCorrgir
return Opciones.Instance.modo switch
{
Opciones.modoDeUso.Corregir =>
"You are an engineer working in industrial automation. Your task is to review texts and rewrite them in a simple and concise manner, making sure to preserve important technical terms and markdown language if present. Please rewrite the following text in " + IdiomaDetectado + " and respond in the following JSON format: { \"Rewritten_text\": \"Your text here\" }.",
"You are an engineer working in industrial automation. Your task is to review texts and rewrite them in a simple and concise manner. If you find words enclosed in double brackets [[like this]], preserve them exactly as they appear without any modifications. For all other technical terms, write them normally without adding any brackets or special formatting. Preserve any existing markdown language if present. Please rewrite the following text in " + IdiomaDetectado + " and respond in the following JSON format: { \"Rewritten_text\": \"Your text here\" }. Important: Do not add any new brackets to words that aren't already enclosed in double brackets.",
Opciones.modoDeUso.Ortografia =>
"Please check the following text for spelling errors and provide the corrected version. Do not change the meaning or structure of the sentences. Only correct any spelling mistakes you find, making sure to preserve important technical terms and markdown language if present. Please write in " + IdiomaDetectado + " and respond in the following JSON format: { \"Rewritten_text\": \"Your text here\" }.",
"Please check the following text for spelling errors and provide the corrected version. Do not change the meaning or structure of the sentences. If you find words enclosed in double brackets [[like this]], preserve them exactly as they appear. For all other words, only correct spelling mistakes while preserving technical terms and any markdown language if present. Please write in " + IdiomaDetectado + " and respond in the following JSON format: { \"Rewritten_text\": \"Your text here\" }.",
_ => "You are an engineer working specialiazed industrial automation. Please answer the following question in " + IdiomaDetectado + " and respond in the following JSON format: { \"Reply_text\": \"Your text here\" }."
_ => "You are an engineer working specialized in industrial automation. If the question contains words in double brackets [[like this]], preserve them exactly as they appear. Please answer the following question in " + IdiomaDetectado + " and respond in the following JSON format: { \"Reply_text\": \"Your text here\" }."
};
}

BIN
tessdata/eng.traineddata Normal file

Binary file not shown.

BIN
tessdata/ita.traineddata Normal file

Binary file not shown.

BIN
tessdata/spa.traineddata Normal file

Binary file not shown.