diff --git a/App.xaml.cs b/App.xaml.cs index 2ed46dd..dd1323d 100644 --- a/App.xaml.cs +++ b/App.xaml.cs @@ -73,6 +73,7 @@ namespace GTPCorrgir else { MostrarNotificacion("Error", "No se pudo corregir el texto."); + Application.Current.Shutdown(); } }); } diff --git a/VentanaResultado.xaml.cs b/VentanaResultado.xaml.cs index b75d3ea..90a5342 100644 --- a/VentanaResultado.xaml.cs +++ b/VentanaResultado.xaml.cs @@ -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 } diff --git a/gtpask.cs b/gtpask.cs index 00ba1d0..c8b9307 100644 --- a/gtpask.cs +++ b/gtpask.cs @@ -15,11 +15,13 @@ namespace GTPCorrgir public enum LLM_a_Usar { OpenAI, - Ollama + Ollama, + Groq } 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 languageMap = new Dictionary { @@ -34,13 +36,13 @@ namespace GTPCorrgir public string TextoACorregir; public string TextoCorregido; public string TextodeSistema; - private const bool Simulacion = false; - private const LLM_a_Usar LLM = LLM_a_Usar.OpenAI; + private const bool Simulacion = true; + private const LLM_a_Usar LLM = LLM_a_Usar.Groq; 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 and rewrite texts in a simple and concise manner, making sure to preserve all important technical terms and maintain any Markdown formatting such as headers, lists, code blocks, and links. 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 +80,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); @@ -102,10 +104,11 @@ namespace GTPCorrgir { if (LLM == LLM_a_Usar.OpenAI) RespuestaLLM = await CallOpenAiApi(TextoACorregir); if (LLM == LLM_a_Usar.Ollama) RespuestaLLM = await CallOllamaApi(TextoACorregir); + if (LLM == 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); @@ -119,7 +122,7 @@ namespace GTPCorrgir } } - static string ExtractCorrectedText(string input) + static string ExtractCorrectedText_UsingJObject(string input) { try { @@ -147,6 +150,44 @@ namespace GTPCorrgir } } + 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); + + // Encuentra el índice del inicio y del final del texto a extraer + int startText = jsonString.IndexOf('\'') + 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 CallOllamaApi(string input) { var httpClient = new HttpClient(); @@ -238,6 +279,48 @@ namespace GTPCorrgir } } + private async Task 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 } + } + }; + + 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; + } + + } } }