Cambio de nombres

This commit is contained in:
Miguel 2024-07-30 17:16:58 +02:00
parent db236afd6d
commit d338d4c9c2
12 changed files with 31 additions and 69 deletions

View File

@ -84,7 +84,7 @@ def importar(archivo_maestro, archivo_importacion):
if __name__ == "__main__": if __name__ == "__main__":
# Cargar el archivo maestro y el archivo de importación # 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") archivo_importacion = select_file("xlsx")
if archivo_importacion: if archivo_importacion:
importar(archivo_maestro, archivo_importacion) importar(archivo_maestro, archivo_importacion)

View File

@ -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) df_export[columna] = df_maestro[columna].apply(lambda x: transformar_texto(str(x)) if pd.notnull(x) else x)
# Guardar el archivo exportado # 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) df_export.to_excel(ruta_export, index=False)
print(f"Archivo exportado para traducción: {ruta_export}") print(f"Archivo exportado para traducción: {ruta_export}")
if __name__ == "__main__": if __name__ == "__main__":
archivo_maestro = "hmi_master_translates.xlsx" archivo_maestro = "/data/1_hmi_master_translates.xlsx"
exportar_para_traduccion(archivo_maestro) exportar_para_traduccion(archivo_maestro)

View File

@ -4,7 +4,7 @@ import os
import re import re
import logging import logging
from openai_api_key import api_key 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()) client = OpenAI(api_key=api_key())
@ -22,7 +22,7 @@ IDIOMAS = {
def configurar_logger(): def configurar_logger():
logger = logging.getLogger("translate_logger") logger = logging.getLogger("translate_logger")
logger.setLevel(logging.DEBUG) # Cambiado a DEBUG para más información 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) fh.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s") formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s")
fh.setFormatter(formatter) fh.setFormatter(formatter)
@ -59,20 +59,27 @@ def translate_text(text, source_lang, target_lang):
logger.info(f"Respuesta recibida: {translated_text}") logger.info(f"Respuesta recibida: {translated_text}")
return 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): def translate_batch(texts, source_lang, target_lang):
joined_text = "\n".join(texts) joined_text = "\n".join(texts)
system_prompt = read_system_prompt()
logger.info( logger.info(
f"Solicitando traducción de {source_lang} a {target_lang} para el lote de textos:\n{joined_text}" 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( response = client.chat.completions.create(
model="gpt-3.5-turbo", model="gpt-3.5-turbo",
messages=[ messages=[
{"role": "system", "content": f"You are a translator."}, {"role": "system", "content": system_prompt},
{ {
"role": "user", "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, max_tokens=1500,
@ -80,7 +87,6 @@ def translate_batch(texts, source_lang, target_lang):
) )
translations = response.choices[0].message.content.strip().split("\n") translations = response.choices[0].message.content.strip().split("\n")
logger.info(f"Respuestas recibidas:\n{translations}") logger.info(f"Respuestas recibidas:\n{translations}")
print("Recibida traduccion.")
return translations return translations
@ -96,7 +102,7 @@ def texto_requiere_traduccion(texto):
return requiere_traduccion 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) df = pd.read_excel(file_path)
source_col = "it-IT" source_col = "it-IT"
source_translated_col = target_lang_code 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) num_texts = len(texts_to_translate)
logger.info(f"Número total de textos a traducir: {num_texts}") logger.info(f"Número total de textos a traducir: {num_texts}")
print(f"Número total de textos a traducir: {num_texts}")
translations = [] translations = []
for start_idx in range(0, num_texts, batch_size): for start_idx in range(0, num_texts, batch_size):
end_idx = min(start_idx + batch_size, num_texts) end_idx = min(start_idx + batch_size, num_texts)
batch_texts = texts_to_translate[start_idx:end_idx] 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) translations.extend(batch_translations)
logger.info(f"Número total de traducciones recibidas: {len(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: else:
logger.error(f"No hay traducción disponible para el índice {index}") 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) df.to_excel(output_path, index=False)
logger.info(f"Archivo traducido guardado en: {output_path}") logger.info(f"Archivo traducido guardado en: {output_path}")
print(f"Archivo traducido guardado en: {output_path}") print(f"Archivo traducido guardado en: {output_path}")
if __name__ == "__main__": if __name__ == "__main__":
batch_size = 10 batch_size = 20
translate_file = "master_export2translate.xlsx" translate_file = "/data/2_master_export2translate.xlsx"
mostrar_idiomas() mostrar_idiomas()
seleccion_idioma = int(input("Introduce el número del idioma de destino: ")) seleccion_idioma = int(input("Introduce el número del idioma de destino: "))
if seleccion_idioma not in IDIOMAS: if seleccion_idioma not in IDIOMAS:
print("Selección inválida.") print("Selección inválida.")
else: else:
_, target_lang_code = IDIOMAS[seleccion_idioma] target_lang, target_lang_code = IDIOMAS[seleccion_idioma]
traducir_todo = ( traducir_todo = (
input("¿Desea traducir todas las celdas (s/n)? ").strip().lower() == "s" 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)

View File

@ -5,7 +5,7 @@ import logging
from manejoArchivos import select_file from manejoArchivos import select_file
def configurar_logger(ruta_log): def configurar_logger(ruta_log):
logger = logging.getLogger('importacion_logger') logger = logging.getLogger('/data/importacion_logger')
logger.setLevel(logging.INFO) logger.setLevel(logging.INFO)
fh = logging.FileHandler(ruta_log, encoding='utf-8') fh = logging.FileHandler(ruta_log, encoding='utf-8')
fh.setLevel(logging.INFO) fh.setLevel(logging.INFO)
@ -63,6 +63,6 @@ def importar_traduccion(archivo_maestro, archivo_traduccion):
if __name__ == "__main__": if __name__ == "__main__":
archivo_maestro = "hmi_master_translates.xlsx" archivo_maestro = "/data/1_hmi_master_translates.xlsx"
archivo_traduccion = "master_export2translate.xlsx" archivo_traduccion = "/data/2_master_export2translate.xlsx"
importar_traduccion(archivo_maestro, archivo_traduccion) importar_traduccion(archivo_maestro, archivo_traduccion)

View File

@ -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}") 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__": if __name__ == "__main__":
archivo_maestro = "hmi_master_translates.xlsx" archivo_maestro = "/data/1_hmi_master_translates.xlsx"
archivo_to_update = select_file("xlsx") archivo_to_update = select_file("xlsx")
if archivo_to_update: if archivo_to_update:
update_from_master(archivo_maestro, archivo_to_update) update_from_master(archivo_maestro, archivo_to_update)

Binary file not shown.

1
data/system_prompt.txt Normal file
View File

@ -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.

Binary file not shown.

View File

@ -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