2024-04-24 03:33:57 -03:00
using System ;
using System.Collections.Generic ;
using System.Linq ;
using System.Net.Http ;
using System.Text ;
using System.Threading.Tasks ;
using System.Windows.Threading ;
using LanguageDetection ;
using Newtonsoft.Json ;
2024-04-25 12:51:43 -03:00
using Newtonsoft.Json.Linq ;
2024-04-25 13:11:48 -03:00
using System.Diagnostics ;
2024-04-24 03:33:57 -03:00
namespace GTPCorrgir
{
internal class gtpask
{
private readonly string openAiApiKey = "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" ;
2024-04-25 13:11:48 -03:00
public Logger Log = new Logger ( ) ;
2024-04-24 03:33:57 -03:00
private Dictionary < string , string > languageMap = new Dictionary < string , string >
{
2024-04-25 12:51:43 -03:00
{ "en" , "English" } ,
{ "es" , "Spanish" } ,
{ "it" , "Italian" } ,
{ "pt" , "Portuguese" }
2024-04-24 03:33:57 -03:00
// Agrega más idiomas según sea necesario
} ;
2024-04-25 12:51:43 -03:00
2024-04-24 03:33:57 -03:00
public string IdiomaDetectado ;
public string TextoACorregir ;
public string TextoCorregido ;
2024-04-25 12:51:43 -03:00
public string TextodeSistema ;
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' }." ;
}
private string CrearMensajeDeUsuario ( string texto )
{
return "Please rewrite and improve the following text to make it clearer and more concise the words inside brackets are technical words: \"" + texto + "\"" ;
}
2024-04-24 03:33:57 -03:00
private string DetectarIdioma ( string TextoACorregir )
{
LanguageDetector detector = new LanguageDetector ( ) ;
2024-04-25 12:51:43 -03:00
detector . AddLanguages ( "en" , "es" , "it" ) ;
2024-04-24 03:33:57 -03:00
string detectedLanguageCode = detector . Detect ( TextoACorregir ) ;
string detectedLanguageName = languageMap . ContainsKey ( detectedLanguageCode )
? languageMap [ detectedLanguageCode ]
: "Desconocido" ;
return detectedLanguageName ;
}
private bool DetectarIdioma ( )
{
if ( TextoACorregir . Length > 0 )
{
IdiomaDetectado = DetectarIdioma ( TextoACorregir ) ;
2024-04-25 13:11:48 -03:00
Log . Log ( "Idioma: " + IdiomaDetectado ) ;
2024-04-24 03:33:57 -03:00
if ( IdiomaDetectado ! = "Desconocido" )
return true ;
else return false ;
}
return false ;
}
public async Task CorregirTexto ( )
2024-04-25 13:11:48 -03:00
{
2024-04-25 13:45:14 -03:00
Log . Log ( "" ) ;
2024-04-25 13:11:48 -03:00
Log . Log ( "Texto a corregir: " + TextoACorregir ) ;
2024-04-24 03:33:57 -03:00
if ( DetectarIdioma ( ) ) {
if ( IdiomaDetectado = = "Desconocido" | | this . TextoACorregir . Length = = 0 )
{
// Nada que hacer
TextoCorregido = TextoACorregir ;
return ;
}
2024-04-25 12:51:43 -03:00
var md = new Obsidean ( ) ;
md . LeerPalabrasTecnicas ( ) ;
TextoACorregir = md . MarkTechnicalTerms ( TextoACorregir ) ;
2024-04-25 13:45:14 -03:00
Log . Log ( "Texto marcado: " + TextoACorregir ) ;
2024-04-25 13:11:48 -03:00
2024-04-26 07:54:24 -03:00
string RespuestaLLM = await CallOpenAiApi ( TextoACorregir ) ;
//string RespuestaLLM = await CallOllamaApi(TextoACorregir);
2024-04-25 13:11:48 -03:00
Log . Log ( "Respuesta: " + RespuestaLLM ) ;
2024-04-24 03:33:57 -03:00
2024-04-25 12:51:43 -03:00
TextoCorregido = ExtractCorrectedText ( RespuestaLLM ) ;
2024-04-24 03:33:57 -03:00
// Elimina comillas al principio y al final si existen
TextoCorregido = TextoCorregido . Trim ( '\"' ) ;
2024-04-25 13:11:48 -03:00
2024-04-25 13:45:14 -03:00
Log . Log ( "Texto corregido: " + TextoCorregido ) ;
2024-04-24 03:33:57 -03:00
}
}
2024-04-25 12:51:43 -03:00
static string ExtractCorrectedText ( string input )
{
try
{
// Encuentra el índice del inicio y del final del JSON
int startJson = input . IndexOf ( '{' ) ;
int endJson = input . IndexOf ( '}' ) + 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 ) ;
// Parsea el JSON y extrae el campo "Rewritten_text"
JObject jsonObject = JObject . Parse ( jsonString ) ;
string rewrittenText = ( string ) jsonObject [ "Rewritten_text" ] ;
return rewrittenText ;
}
catch ( Exception ex )
{
Console . WriteLine ( "An error occurred: " + ex . Message ) ;
return null ;
}
}
2024-04-24 03:33:57 -03:00
private async Task < string > CallOllamaApi ( string input )
{
var httpClient = new HttpClient ( ) ;
2024-04-25 12:51:43 -03:00
string Mensaje_Sistema = CrearMensajeDeSistema ( ) ;
string Mensaje_Usuario = CrearMensajeDeUsuario ( input ) ;
2024-04-24 03:33:57 -03:00
httpClient . DefaultRequestHeaders . Add ( "Authorization" , $"Bearer {openAiApiKey}" ) ;
var requestData = new
{
model = "llama3" ,
messages = new [ ]
{
2024-04-25 12:51:43 -03:00
new { role = "system" , content = Mensaje_Sistema } ,
new { role = "user" , content = Mensaje_Usuario }
2024-04-24 03:33:57 -03:00
} ,
stream = false
} ;
var content = new StringContent ( JsonConvert . SerializeObject ( requestData ) , Encoding . UTF8 , "application/json" ) ;
try
{
2024-04-25 13:45:14 -03:00
Log . Log ( "Ask Ollama: " + JsonConvert . SerializeObject ( requestData ) ) ;
2024-04-24 03:33:57 -03:00
var response = await httpClient . PostAsync ( "http://127.0.0.1:11434/api/chat" , content ) ;
response . EnsureSuccessStatusCode ( ) ;
var jsonResponse = await response . Content . ReadAsStringAsync ( ) ;
dynamic data = JsonConvert . DeserializeObject ( jsonResponse ) ;
if ( data . done = = true & & data . message ! = null )
{
return data . message . content ;
}
return "No hubo respuesta del asistente o la sesión aún no ha concluido." ;
}
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 ;
}
}
2024-04-25 12:51:43 -03:00
2024-04-24 03:33:57 -03:00
private async Task < string > CallOpenAiApi ( string input )
{
var httpClient = new HttpClient ( ) ;
2024-04-25 12:51:43 -03:00
string Mensaje_Sistema = CrearMensajeDeSistema ( ) ;
string Mensaje_Usuario = CrearMensajeDeUsuario ( input ) ;
2024-04-24 03:33:57 -03:00
httpClient . DefaultRequestHeaders . Add ( "Authorization" , $"Bearer {openAiApiKey}" ) ;
var requestData = new
{
model = "gpt-4" ,
messages = new [ ]
{
2024-04-25 12:51:43 -03:00
new { role = "system" , content = Mensaje_Sistema } ,
new { role = "user" , content = Mensaje_Usuario }
2024-04-24 03:33:57 -03:00
}
} ;
var content = new StringContent ( JsonConvert . SerializeObject ( requestData ) , Encoding . UTF8 , "application/json" ) ;
try
{
2024-04-25 13:45:14 -03:00
Log . Log ( "Ask OpenAI: " + JsonConvert . SerializeObject ( requestData ) ) ;
2024-04-24 03:33:57 -03:00
var response = await httpClient . PostAsync ( "https://api.openai.com/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 ;
}
}
}
}