Compare commits

...

2 Commits

6 changed files with 203 additions and 19 deletions

View File

@ -39,7 +39,7 @@ namespace GTPCorrgir
}
// Muestra notificación inicial y comienza el cronómetro en el hilo de la UI
ShowCustomNotification("Espera", "Corrigiendo texto...");
ShowCustomNotification("Espera", $"Corrigiendo texto con .{Opciones.Instance.nombreDeLLM()} ..");
IniciarCronometro();
@ -73,6 +73,7 @@ namespace GTPCorrgir
else
{
MostrarNotificacion("Error", "No se pudo corregir el texto.");
Application.Current.Shutdown();
}
});
}
@ -117,7 +118,7 @@ namespace GTPCorrgir
if (!CorreccionFinalizada) {
//notificacion.BalloonTipText = $"Texto en {GTP.IdiomaDetectado} pasados: {Math.Round(stopwatch.ElapsedMilliseconds/1000.0,1)} s";
//notificacion.ShowBalloonTip(1000);
ShowCustomNotification("Trabajando..", $"Texto en {GTP.IdiomaDetectado} pasados: {Math.Round(stopwatch.ElapsedMilliseconds / 1000.0, 1)} s");
ShowCustomNotification($"{Opciones.Instance.nombreDeLLM()} Trabajando..", $"Texto en {GTP.IdiomaDetectado} pasados: {Math.Round(stopwatch.ElapsedMilliseconds / 1000.0, 1)} s");
}
}

View File

@ -7,6 +7,7 @@
<ImplicitUsings>enable</ImplicitUsings>
<UseWPF>true</UseWPF>
<UseWindowsForms>true</UseWindowsForms>
<StartupObject>GTPCorrgir.Program</StartupObject>
<!-- Esta línea habilita Windows Forms -->
</PropertyGroup>

View File

@ -92,6 +92,22 @@ namespace GTPCorrgir
return word; // Devolver la palabra sin modificar si no es técnica
});
}
public string MarkTechnicalTerms_IgnoreCase(string text)
{
// Utilizar Regex para identificar palabras individualmente, ignorando mayúsculas y minúsculas
return Regex.Replace(text, @"\b(\w+)\b", match =>
{
string word = match.Groups[1].Value;
// Verificar si la palabra está en el conjunto de términos técnicos, ignorando mayúsculas y minúsculas
if (technicalTerms.Contains(word, StringComparer.OrdinalIgnoreCase))
{
return $"[[{word}]]"; // Encerrar la palabra en corchetes si es técnica
}
return word; // Devolver la palabra sin modificar si no es técnica
}, RegexOptions.IgnoreCase);
}
}
}

79
Program.cs Normal file
View File

@ -0,0 +1,79 @@
using GTPCorrgir;
using System;
using System.Configuration;
using System.Windows;
namespace GTPCorrgir
{
public class Opciones
{
public enum LLM_a_Usar
{
OpenAI,
Ollama,
Groq
}
private Dictionary<LLM_a_Usar, string> nombreLLM = new Dictionary<LLM_a_Usar, string>
{
{ Opciones.LLM_a_Usar.Ollama, "Ollama" },
{ Opciones.LLM_a_Usar.Groq, "Groq" },
{ Opciones.LLM_a_Usar.OpenAI, "OpenAI" },
};
private static Opciones _instance;
public static Opciones Instance
{
get
{
if (_instance == null)
{
_instance = new Opciones();
}
return _instance;
}
}
public LLM_a_Usar LLM { get; set; }
public string nombreDeLLM() {
return nombreLLM[LLM];
}
private Opciones() { }
}
public class Program
{
[STAThread]
public static void Main(string[] args)
{
var application = new App();
// Aquí puedes procesar los argumentos
foreach (var arg in args)
{
if (arg.StartsWith("--"))
{
// Procesa el argumento según tus necesidades
if (arg.StartsWith("--Ollama"))
Opciones.Instance.LLM = Opciones.LLM_a_Usar.Ollama;
else if (arg.StartsWith("--Groq"))
Opciones.Instance.LLM = Opciones.LLM_a_Usar.Groq;
else
Opciones.Instance.LLM = Opciones.LLM_a_Usar.OpenAI;
}
}
application.Run();
}
}
}

View File

@ -71,7 +71,6 @@ namespace GTPCorrgir
private void MainWindow_MouseLeave(object sender, MouseEventArgs e)
{
this.Close(); // Cierra la ventana cuando el ratón sale de su área
Application.Current.Shutdown(); // Terminar la aplicación
}

120
gtpask.cs
View File

@ -12,14 +12,11 @@ using System.Diagnostics;
namespace GTPCorrgir
{
public enum LLM_a_Usar
{
OpenAI,
Ollama
}
internal class gtpask
{
private readonly string openAiApiKey = "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";
private readonly string groqApiKey = "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";
public Logger Log = new Logger();
private Dictionary<string, string> languageMap = new Dictionary<string, string>
{
@ -35,12 +32,12 @@ namespace GTPCorrgir
public string TextoCorregido;
public string TextodeSistema;
private const bool Simulacion = false;
private const LLM_a_Usar LLM = LLM_a_Usar.OpenAI;
private string CrearMensajeDeSistema()
{
return "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 specially if they are in English. Please rewrite the following text in " + IdiomaDetectado + " and respond in the following JSON format: { 'Rewritten_text': 'Your text here' }.";
return "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' }.";
}
private string CrearMensajeDeUsuario(string texto)
@ -78,7 +75,7 @@ namespace GTPCorrgir
public async Task CorregirTexto()
{
if (Simulacion)
TextoACorregir = "La FB482 puo gestire un divider di 7 uscite a 3 punte di scambio pero su questa macchina abbiamo un divider a 3 uscite e solo un punto di scambio.";
TextoACorregir = "\t\t* Sic : Synchronism?\r\n\t\t* Cont ? \r\n\t\t* Sensor for tensioning?\r\n\t\t* Max ? Overspeed?\r\n\t\t* Min : Stop / Start\r\n\t\t* Variable Speed. - = reference by filler\r\n\t\t* Formats: ? 66mm a 93mm => 27mm. How is changed?";
Log.Log("");
Log.Log("Texto a corregir: " + TextoACorregir);
@ -93,24 +90,26 @@ namespace GTPCorrgir
var md = new Obsidean();
md.LeerPalabrasTecnicas();
TextoACorregir = md.MarkTechnicalTerms(TextoACorregir);
TextoACorregir = md.MarkTechnicalTerms_IgnoreCase(TextoACorregir);
Log.Log("Texto marcado: " + TextoACorregir);
string RespuestaLLM;
string RespuestaLLM = "";
if (!Simulacion)
{
if (LLM == LLM_a_Usar.OpenAI) RespuestaLLM = await CallOpenAiApi(TextoACorregir);
if (LLM == LLM_a_Usar.Ollama) RespuestaLLM = await CallOllamaApi(TextoACorregir);
if (Opciones.Instance.LLM == Opciones.LLM_a_Usar.OpenAI) RespuestaLLM = await CallOpenAiApi(TextoACorregir);
if (Opciones.Instance.LLM == Opciones.LLM_a_Usar.Ollama) RespuestaLLM = await CallOllamaApi(TextoACorregir);
if (Opciones.Instance.LLM == Opciones.LLM_a_Usar.Groq) RespuestaLLM = await CallGroqAiApi(TextoACorregir);
} else
{
await Task.Delay(1000);
RespuestaLLM = "{ 'Rewritten_text': 'Movimiento Continuo: Este enfoque hará que la ventana se mueva continuamente mientras el ratón se mueva sobre ella. Esto podría ser deseable para tu aplicación, pero ten en cuenta que puede parecer un comportamiento inusual desde la perspectiva del usuario.\r\nRendimiento: Mover la ventana de esta manera puede ser demandante en términos de recursos del sistema, especialmente si se realiza con mucha frecuencia (por ejemplo, durante un movimiento rápido del ratón). Si observas problemas de rendimiento, podrías necesitar optimizar cómo y cuándo se actualiza la posición de la ventana.' }";
RespuestaLLM = "Here is the rewritten text in a clearer and more concise manner:\r\n\r\n{\r\n'Rewritten_text': '\r\n### FB Tilting System Overview\r\n\r\nThe FB Tilting system consists of two main components:\r\n\r\n* **FB Tilting**: The main machine responsible for tilting and moving bottles.\r\n* **Sic (Synchronism)**: Ensures synchronized movement of the tilting machine with other system components.\r\n\r\n### Key Components and Functions\r\n\r\n* **Cont (Controller)**: The controlling unit that regulates the system's operation.\r\n* **Sensor for Tensioning**: Monitors and adjusts the tension of the moving parts.\r\n* **Max (Maximum Speed) and Overspeed Protection**: Safeguards the system from excessive speeds.\r\n* **Min (Minimum Speed) and Stop/Start Function**: Manages the system's startup and shutdown sequences.\r\n* **Variable Speed**: Allows for adjustable speed control, referenced by the filling machine.\r\n\r\n### Format Adaptation\r\n\r\nThe system accommodates various formats, including:\r\n* 66mm to 93mm, which are adapted to 27mm formats. The format change process is implemented as follows:\r\n\r\n### Startup Sequence\r\n\r\nThe startup procedure involves:\r\n\r\n1. **Fill to Sic with Minimum Accumulation**: Fills the Sic component with a minimum amount of material.\r\n2. **Run Chain at Fixed Speed**: Operates the chain at a constant speed.\r\n3. **Wait for Phase to Start**: Waits for the phase and ramp of the doser to be parameterized.\r\n4. **Ramp to Variable Speed**: Gradually adjusts the speed to the selected variable speed setting after a few bottles have been processed.'\r\n}";
}
Log.Log("Respuesta: " + RespuestaLLM);
TextoCorregido = ExtractCorrectedText(RespuestaLLM);
TextoCorregido = ExtractCorrectedText_UsingJObject(RespuestaLLM);
// Elimina comillas al principio y al final si existen
TextoCorregido = TextoCorregido.Trim('\"');
@ -119,7 +118,7 @@ namespace GTPCorrgir
}
}
static string ExtractCorrectedText(string input)
static string ExtractCorrectedText_UsingJObject(string input)
{
try
{
@ -141,12 +140,57 @@ namespace GTPCorrgir
return rewrittenText;
}
catch (Exception ex)
{
Console.WriteLine("An error occurred: " + ex.Message);
return input;
}
}
static string ExtractCorrectedText(string input)
{
try
{
// Encuentra el índice del inicio y del final del JSON
int startJson = input.IndexOf('{');
int endJson = input.LastIndexOf('}') + 1;
if (startJson == -1 || endJson == -1 || endJson <= startJson)
{
throw new Exception("No valid JSON found in the input string.");
}
// Extrae solo la parte JSON de la entrada
string jsonString = input.Substring(startJson, endJson - startJson);
// Busca el inicio del texto después de "Rewritten_text':"
int startKey = jsonString.IndexOf("'Rewritten_text':") + 17; // 17 es la longitud de "'Rewritten_text':"
if (startKey == -1)
{
throw new Exception("Key 'Rewritten_text' not found.");
}
// Ajusta para encontrar el inicio del texto después de las comillas simples adicionales
int startText = jsonString.IndexOf('\'', startKey) + 1;
int endText = jsonString.LastIndexOf('\'');
if (startText == -1 || endText == -1 || endText <= startText)
{
throw new Exception("No valid text found in the JSON string.");
}
// Extrae el texto entre las comillas simples
string rewrittenText = jsonString.Substring(startText, endText - startText);
return rewrittenText;
}
catch (Exception ex)
{
Console.WriteLine("An error occurred: " + ex.Message);
return null;
}
}
private async Task<string> CallOllamaApi(string input)
{
var httpClient = new HttpClient();
@ -157,7 +201,7 @@ namespace GTPCorrgir
var requestData = new
{
model = "llama3",
model = "phi3", //"llama3",
messages = new[]
{
new { role = "system", content = Mensaje_Sistema },
@ -238,6 +282,50 @@ namespace GTPCorrgir
}
}
private async Task<string> CallGroqAiApi(string input)
{
var httpClient = new HttpClient();
string Mensaje_Sistema = CrearMensajeDeSistema();
string Mensaje_Usuario = CrearMensajeDeUsuario(input);
httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {groqApiKey}");
var requestData = new
{
model = "llama3-70b-8192",
messages = new[]
{
new { role = "system", content = Mensaje_Sistema },
new { role = "user", content = Mensaje_Usuario }
},
max_tokens = 2048,
stream = false
};
var content = new StringContent(JsonConvert.SerializeObject(requestData), Encoding.UTF8, "application/json");
try
{
Log.Log("Ask Groq: " + JsonConvert.SerializeObject(requestData));
var response = await httpClient.PostAsync("https://api.groq.com/openai/v1/chat/completions", content);
response.EnsureSuccessStatusCode();
var jsonResponse = await response.Content.ReadAsStringAsync();
dynamic data = JsonConvert.DeserializeObject(jsonResponse);
return data.choices[0].message.content;
}
catch (HttpRequestException e)
{
// Captura errores en la solicitud HTTP, como problemas de red o respuestas de error HTTP.
Console.WriteLine($"Error making HTTP request: {e.Message}");
return null;
}
catch (Exception e)
{
// Captura cualquier otro error
Console.WriteLine($"An error occurred: {e.Message}");
return null;
}
}
}
}