diff --git a/importar_to_master.py b/1_importar_to_master.py similarity index 98% rename from importar_to_master.py rename to 1_importar_to_master.py index a25bcab..862ceef 100644 --- a/importar_to_master.py +++ b/1_importar_to_master.py @@ -84,7 +84,7 @@ def importar(archivo_maestro, archivo_importacion): if __name__ == "__main__": # Cargar el archivo maestro y el archivo de importación - archivo_maestro = "hmi_master_translates.xlsx" + archivo_maestro = "/data/1_hmi_master_translates.xlsx" archivo_importacion = select_file("xlsx") if archivo_importacion: importar(archivo_maestro, archivo_importacion) diff --git a/master_export2translate.py b/2_master_export2translate.py similarity index 92% rename from master_export2translate.py rename to 2_master_export2translate.py index 2a10e92..6a8bd23 100644 --- a/master_export2translate.py +++ b/2_master_export2translate.py @@ -28,10 +28,10 @@ def exportar_para_traduccion(archivo_maestro): df_export[columna] = df_maestro[columna].apply(lambda x: transformar_texto(str(x)) if pd.notnull(x) else x) # Guardar el archivo exportado - ruta_export = os.path.join(os.path.dirname(archivo_maestro), 'master_export2translate.xlsx') + ruta_export = os.path.join(os.path.dirname(archivo_maestro), '/data/2_master_export2translate.xlsx') df_export.to_excel(ruta_export, index=False) print(f"Archivo exportado para traducción: {ruta_export}") if __name__ == "__main__": - archivo_maestro = "hmi_master_translates.xlsx" + archivo_maestro = "/data/1_hmi_master_translates.xlsx" exportar_para_traduccion(archivo_maestro) diff --git a/llm_translate_text.py b/3_llm_translate_text.py similarity index 82% rename from llm_translate_text.py rename to 3_llm_translate_text.py index 346ceac..d96877f 100644 --- a/llm_translate_text.py +++ b/3_llm_translate_text.py @@ -4,7 +4,7 @@ import os import re import logging from openai_api_key import api_key -from master_export2translate import transformar_texto +from 2_master_export2translate import transformar_texto client = OpenAI(api_key=api_key()) @@ -22,7 +22,7 @@ IDIOMAS = { def configurar_logger(): logger = logging.getLogger("translate_logger") logger.setLevel(logging.DEBUG) # Cambiado a DEBUG para más información - fh = logging.FileHandler("translate_log.log", encoding="utf-8") + fh = logging.FileHandler("/data/translate_log.log", encoding="utf-8") fh.setLevel(logging.DEBUG) formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s") fh.setFormatter(formatter) @@ -59,20 +59,27 @@ def translate_text(text, source_lang, target_lang): logger.info(f"Respuesta recibida: {translated_text}") return translated_text - +def read_system_prompt(): + try: + with open("/data/system_prompt.txt", "r", encoding="utf-8") as file: + return file.read().strip() + except FileNotFoundError: + logger.warning("Archivo system_prompt.txt no encontrado. Usando prompt por defecto.") + return "You are a translator." + def translate_batch(texts, source_lang, target_lang): joined_text = "\n".join(texts) + system_prompt = read_system_prompt() logger.info( f"Solicitando traducción de {source_lang} a {target_lang} para el lote de textos:\n{joined_text}" ) - print("Traduciendo batch ... ") response = client.chat.completions.create( model="gpt-3.5-turbo", messages=[ - {"role": "system", "content": f"You are a translator."}, + {"role": "system", "content": system_prompt}, { "role": "user", - "content": f"Translate the following texts from {source_lang} to {target_lang} while preserving special fields like <> and <#>:\n\n{joined_text}", + "content": f"Translate the following texts from {source_lang} to {target_lang} while preserving special fields like <> and <#>. This texts are for an HMI industrial machine: \n\n{joined_text}", }, ], max_tokens=1500, @@ -80,7 +87,6 @@ def translate_batch(texts, source_lang, target_lang): ) translations = response.choices[0].message.content.strip().split("\n") logger.info(f"Respuestas recibidas:\n{translations}") - print("Recibida traduccion.") return translations @@ -96,7 +102,7 @@ def texto_requiere_traduccion(texto): return requiere_traduccion -def main(file_path, target_lang_code, traducir_todo, batch_size=10): +def main(file_path, target_lang_code,target_lang, traducir_todo, batch_size=10): df = pd.read_excel(file_path) source_col = "it-IT" source_translated_col = target_lang_code @@ -128,12 +134,14 @@ def main(file_path, target_lang_code, traducir_todo, batch_size=10): num_texts = len(texts_to_translate) logger.info(f"Número total de textos a traducir: {num_texts}") - + print(f"Número total de textos a traducir: {num_texts}") + translations = [] for start_idx in range(0, num_texts, batch_size): end_idx = min(start_idx + batch_size, num_texts) batch_texts = texts_to_translate[start_idx:end_idx] - batch_translations = translate_batch(batch_texts, 'Italian', target_lang_code) + print(f"Traduciendo : celdas desde: {start_idx} a :{end_idx}.") + batch_translations = translate_batch(batch_texts, 'Italian', target_lang) translations.extend(batch_translations) logger.info(f"Número total de traducciones recibidas: {len(translations)}") @@ -147,23 +155,23 @@ def main(file_path, target_lang_code, traducir_todo, batch_size=10): else: logger.error(f"No hay traducción disponible para el índice {index}") - output_path = os.path.join(os.path.dirname(file_path), 'master_export2translate_translated.xlsx') + output_path = os.path.join(os.path.dirname(file_path), '/data/3_master_export2translate_translated.xlsx') df.to_excel(output_path, index=False) logger.info(f"Archivo traducido guardado en: {output_path}") print(f"Archivo traducido guardado en: {output_path}") if __name__ == "__main__": - batch_size = 10 - translate_file = "master_export2translate.xlsx" + batch_size = 20 + translate_file = "/data/2_master_export2translate.xlsx" mostrar_idiomas() seleccion_idioma = int(input("Introduce el número del idioma de destino: ")) if seleccion_idioma not in IDIOMAS: print("Selección inválida.") else: - _, target_lang_code = IDIOMAS[seleccion_idioma] + target_lang, target_lang_code = IDIOMAS[seleccion_idioma] traducir_todo = ( input("¿Desea traducir todas las celdas (s/n)? ").strip().lower() == "s" ) - main(translate_file, target_lang_code, traducir_todo, batch_size) + main(translate_file, target_lang_code,target_lang, traducir_todo, batch_size) diff --git a/import_translate2master.py b/4_import_translate2master.py similarity index 94% rename from import_translate2master.py rename to 4_import_translate2master.py index 707abf1..3e80a61 100644 --- a/import_translate2master.py +++ b/4_import_translate2master.py @@ -5,7 +5,7 @@ import logging from manejoArchivos import select_file def configurar_logger(ruta_log): - logger = logging.getLogger('importacion_logger') + logger = logging.getLogger('/data/importacion_logger') logger.setLevel(logging.INFO) fh = logging.FileHandler(ruta_log, encoding='utf-8') fh.setLevel(logging.INFO) @@ -63,6 +63,6 @@ def importar_traduccion(archivo_maestro, archivo_traduccion): if __name__ == "__main__": - archivo_maestro = "hmi_master_translates.xlsx" - archivo_traduccion = "master_export2translate.xlsx" + archivo_maestro = "/data/1_hmi_master_translates.xlsx" + archivo_traduccion = "/data/2_master_export2translate.xlsx" importar_traduccion(archivo_maestro, archivo_traduccion) diff --git a/update_from_master.py b/5_update_from_master.py similarity index 98% rename from update_from_master.py rename to 5_update_from_master.py index 544d6cd..5ab7ec9 100644 --- a/update_from_master.py +++ b/5_update_from_master.py @@ -96,7 +96,7 @@ def update_from_master(archivo_maestro, archivo_to_update): print(f"Se han actualizado las filas en {archivo_to_update} desde el archivo maestro. Detalles de los cambios en {nombre_log}") if __name__ == "__main__": - archivo_maestro = "hmi_master_translates.xlsx" + archivo_maestro = "/data/1_hmi_master_translates.xlsx" archivo_to_update = select_file("xlsx") if archivo_to_update: update_from_master(archivo_maestro, archivo_to_update) diff --git a/hmi_master_translates.xlsx b/data/1_hmi_master_translates.xlsx similarity index 98% rename from hmi_master_translates.xlsx rename to data/1_hmi_master_translates.xlsx index 16b64cc..7c3e863 100644 Binary files a/hmi_master_translates.xlsx and b/data/1_hmi_master_translates.xlsx differ diff --git a/data/2_master_export2translate.xlsx b/data/2_master_export2translate.xlsx new file mode 100644 index 0000000..fb459a1 Binary files /dev/null and b/data/2_master_export2translate.xlsx differ diff --git a/data/system_prompt.txt b/data/system_prompt.txt new file mode 100644 index 0000000..4ce72b9 --- /dev/null +++ b/data/system_prompt.txt @@ -0,0 +1 @@ +This texts are for an HMI industrial machine. Preserve the next words without translation: TILTER, ON, OFF, HMI, STOP, SD, USB, PLC, PID, FF, VFD, +A, +B, +CG, +D, +E, UPS, EMD, Pack, TableTop, Air, DCS, SKID, ALLEN BRADLEY, CPU, DANFOSS, Vetromeccanica, mBar, m/sec, mm, EEPROM, Ethernet, FIFO, PDF, RAM. \ No newline at end of file diff --git a/importacion_traduccion.log b/importacion_traduccion.log deleted file mode 100644 index e69de29..0000000 diff --git a/master_export2translate.xlsx b/master_export2translate.xlsx deleted file mode 100644 index 037f526..0000000 Binary files a/master_export2translate.xlsx and /dev/null differ diff --git a/master_export2translate_translated.xlsx b/master_export2translate_translated.xlsx deleted file mode 100644 index 4299fd4..0000000 Binary files a/master_export2translate_translated.xlsx and /dev/null differ diff --git a/translate_log.log b/translate_log.log deleted file mode 100644 index c4e5f9e..0000000 --- a/translate_log.log +++ /dev/null @@ -1,47 +0,0 @@ -2024-07-30 16:11:05,490 - DEBUG - Decisión de traducción para texto ' SK<#>F': No (palabras > 3 letras: False, solo campos especiales: True) -2024-07-30 16:11:05,491 - DEBUG - Decisión de traducción para texto ' SK<#>T': No (palabras > 3 letras: False, solo campos especiales: True) -2024-07-30 16:11:05,491 - DEBUG - Decisión de traducción para texto '### ERRORE ###': Sí (palabras > 3 letras: True, solo campos especiales: True) -2024-07-30 16:11:05,492 - DEBUG - Decisión de traducción para texto 'Bypass': Sí (palabras > 3 letras: True, solo campos especiales: True) -2024-07-30 16:11:05,492 - DEBUG - Decisión de traducción para texto 'W<#>/<#>/<#> General - Attesa EBI': Sí (palabras > 3 letras: True, solo campos especiales: True) -2024-07-30 16:11:05,492 - DEBUG - Decisión de traducción para texto 'W<#>/<#>/<#> General - Attesa FBI': Sí (palabras > 3 letras: True, solo campos especiales: True) -2024-07-30 16:11:05,492 - DEBUG - Decisión de traducción para texto 'W<#>/<#>/<#> General - ': Sí (palabras > 3 letras: True, solo campos especiales: True) -2024-07-30 16:11:05,492 - DEBUG - Decisión de traducción para texto 'W<#>/<#>/<#> General - Pressure sensor Maximun reached': Sí (palabras > 3 letras: True, solo campos especiales: True) -2024-07-30 16:11:05,492 - DEBUG - Decisión de traducción para texto 'W<#>/<#>/<#> General - Tank under minimun level': Sí (palabras > 3 letras: True, solo campos especiales: True) -2024-07-30 16:11:05,492 - DEBUG - Decisión de traducción para texto 'W<#>/<#>/<#> General - Stop Filler for Overtemperature': Sí (palabras > 3 letras: True, solo campos especiales: True) -2024-07-30 16:11:05,492 - DEBUG - Decisión de traducción para texto 'W<#>/<#>/<#> General -': Sí (palabras > 3 letras: True, solo campos especiales: True) -2024-07-30 16:11:05,493 - DEBUG - Decisión de traducción para texto 'W<#>/<#>/<#> General - Signals Forced': Sí (palabras > 3 letras: True, solo campos especiales: True) -2024-07-30 16:11:05,493 - DEBUG - Decisión de traducción para texto 'W<#>/<#>/<#> General - Richiesta Di Calibrazione Da FBI': Sí (palabras > 3 letras: True, solo campos especiales: True) -2024-07-30 16:11:05,493 - DEBUG - Decisión de traducción para texto 'Waiting for product': Sí (palabras > 3 letras: True, solo campos especiales: True) -2024-07-30 16:11:05,493 - DEBUG - Decisión de traducción para texto 'Waiting Infeed Selector Enable': Sí (palabras > 3 letras: True, solo campos especiales: True) -2024-07-30 16:11:05,493 - DEBUG - Decisión de traducción para texto 'Waiting Minimal Accumulation': Sí (palabras > 3 letras: True, solo campos especiales: True) -2024-07-30 16:11:05,493 - DEBUG - Decisión de traducción para texto 'Warnings': Sí (palabras > 3 letras: True, solo campos especiales: True) -2024-07-30 16:11:05,493 - DEBUG - Decisión de traducción para texto 'Watchdog del sistema': Sí (palabras > 3 letras: True, solo campos especiales: True) -2024-07-30 16:11:05,493 - DEBUG - Decisión de traducción para texto 'Water supply': Sí (palabras > 3 letras: True, solo campos especiales: True) -2024-07-30 16:11:05,493 - DEBUG - Decisión de traducción para texto 'X<#> M<#>': No (palabras > 3 letras: False, solo campos especiales: True) -2024-07-30 16:11:05,493 - DEBUG - Decisión de traducción para texto 'YV<#>': No (palabras > 3 letras: False, solo campos especiales: True) -2024-07-30 16:11:05,493 - INFO - Número total de textos a traducir: 17 -2024-07-30 16:11:05,493 - INFO - Solicitando traducción de Italian a ru-RU para el lote de textos: -### ERRORE ### -Bypass -W<#>/<#>/<#> General - Attesa EBI -W<#>/<#>/<#> General - Attesa FBI -W<#>/<#>/<#> General - -W<#>/<#>/<#> General - Pressure sensor Maximun reached -W<#>/<#>/<#> General - Tank under minimun level -W<#>/<#>/<#> General - Stop Filler for Overtemperature -W<#>/<#>/<#> General - -W<#>/<#>/<#> General - Signals Forced -2024-07-30 16:11:08,884 - INFO - Respuestas recibidas: -['### ОШИБКА ###', 'Обход', 'W<#>/<#>/<#> Общее - Ожидание EBI', 'W<#>/<#>/<#> Общее - Ожидание FBI', 'W<#>/<#>/<#> Общее - ', 'W<#>/<#>/<#> Общее - Достигнут максимум датчика давления', 'W<#>/<#>/<#> Общее - Резервуар ниже минимального уровня', 'W<#>/<#>/<#> Общее - Остановка насоса из-за перегрева', 'W<#>/<#>/<#> Общее -', 'W<#>/<#>/<#> Общее - Принудительные сигналы'] -2024-07-30 16:11:08,884 - INFO - Solicitando traducción de Italian a ru-RU para el lote de textos: -W<#>/<#>/<#> General - Richiesta Di Calibrazione Da FBI -Waiting for product -Waiting Infeed Selector Enable -Waiting Minimal Accumulation -Warnings -Watchdog del sistema -Water supply -2024-07-30 16:11:10,624 - INFO - Respuestas recibidas: -['W<#>/<#>/<#> Генерал - Запрос на калибровку от ФБР', 'Ожидание продукта', 'Ожидание активации селектора подачи', 'Ожидание минимальной накопительной способности', 'Предупреждения', 'Дежурный системы', 'Подача воды'] -2024-07-30 16:11:10,624 - INFO - Número total de traducciones recibidas: 17 -2024-07-30 16:11:10,669 - INFO - Archivo traducido guardado en: master_export2translate_translated.xlsx