HMI_Translate_Helper_wMaste.../llm_translate_text.py

170 lines
5.9 KiB
Python
Raw Normal View History

2024-07-30 09:19:19 -03:00
import pandas as pd
2024-07-30 09:58:19 -03:00
from openai import OpenAI
2024-07-30 09:19:19 -03:00
import os
import re
2024-07-30 09:58:19 -03:00
import logging
2024-07-30 09:19:19 -03:00
from openai_api_key import api_key
2024-07-30 09:58:19 -03:00
from master_export2translate import transformar_texto
2024-07-30 09:19:19 -03:00
2024-07-30 09:58:19 -03:00
client = OpenAI(api_key=api_key())
2024-07-30 09:19:19 -03:00
# Diccionario de idiomas
IDIOMAS = {
1: ("English", "en"),
2: ("Portuguese", "pt"),
3: ("Spanish", "es"),
4: ("Russian", "ru"),
5: ("French", "fr"),
2024-07-30 09:58:19 -03:00
6: ("German", "de"),
2024-07-30 09:19:19 -03:00
}
2024-07-30 09:58:19 -03:00
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.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s")
fh.setFormatter(formatter)
logger.addHandler(fh)
return logger
logger = configurar_logger()
2024-07-30 09:19:19 -03:00
def mostrar_idiomas():
print("Selecciona el idioma de destino:")
for numero, (nombre, _) in IDIOMAS.items():
print(f"{numero}: {nombre}")
2024-07-30 09:58:19 -03:00
2024-07-30 09:19:19 -03:00
def translate_text(text, source_lang, target_lang):
2024-07-30 09:58:19 -03:00
logger.info(
f"Solicitando traducción de {source_lang} a {target_lang} para el texto: {text}"
2024-07-30 09:19:19 -03:00
)
2024-07-30 09:58:19 -03:00
response = client.chat.completions.create(
model="gpt-3.5-turbo",
messages=[
{"role": "system", "content": f"You are a translator."},
{
"role": "user",
"content": f"Translate the following text from {source_lang} to {target_lang} while preserving special fields like <> and <#>. This texts are for an HMI industrial machine: {text}",
},
],
max_tokens=150,
temperature=0.3,
)
translated_text = response.choices[0].message.content.strip()
logger.info(f"Respuesta recibida: {translated_text}")
return translated_text
2024-07-30 09:19:19 -03:00
def translate_batch(texts, source_lang, target_lang):
joined_text = "\n".join(texts)
2024-07-30 09:58:19 -03:00
logger.info(
f"Solicitando traducción de {source_lang} a {target_lang} para el lote de textos:\n{joined_text}"
)
response = client.chat.completions.create(
model="gpt-3.5-turbo",
messages=[
{"role": "system", "content": f"You are a translator."},
{
"role": "user",
"content": f"Translate the following texts from {source_lang} to {target_lang} while preserving special fields like <> and <#>:\n\n{joined_text}",
},
],
max_tokens=1500,
temperature=0.3,
2024-07-30 09:19:19 -03:00
)
2024-07-30 09:58:19 -03:00
translations = response.choices[0].message.content.strip().split("\n")
logger.info(f"Respuestas recibidas:\n{translations}")
2024-07-30 09:19:19 -03:00
return translations
2024-07-30 09:58:19 -03:00
2024-07-30 09:19:19 -03:00
def texto_requiere_traduccion(texto):
2024-07-30 09:58:19 -03:00
palabras = re.findall(r"\b\w{4,}\b", texto)
campos_especiales = re.findall(r"<.*?>", texto)
requiere_traduccion = len(palabras) > 0 or len(campos_especiales) != len(
re.findall(r"<#>", texto)
)
logger.debug(
f"Decisión de traducción para texto '{texto}': {'' if requiere_traduccion else 'No'} (palabras > 3 letras: {len(palabras) > 0}, solo campos especiales: {len(campos_especiales) == len(re.findall(r'<#>', texto))})"
)
return requiere_traduccion
2024-07-30 09:19:19 -03:00
def main(file_path, target_lang_code, traducir_todo, batch_size=10):
df = pd.read_excel(file_path)
source_col = "it-IT"
target_col = f"{target_lang_code} Translated"
if target_col in df.columns and not traducir_todo:
df[target_col] = df[target_col]
else:
df[target_col] = None
2024-07-30 09:58:19 -03:00
texts_to_translate = []
indices_to_translate = []
2024-07-30 09:19:19 -03:00
if traducir_todo:
2024-07-30 09:58:19 -03:00
for index, text in df[source_col].astype(str).items():
processed_text = transformar_texto(text)
if texto_requiere_traduccion(processed_text):
texts_to_translate.append(text)
indices_to_translate.append(index)
2024-07-30 09:19:19 -03:00
else:
2024-07-30 09:58:19 -03:00
for index, text in (
df.loc[df[target_col].isnull(), source_col].astype(str).items()
):
processed_text = transformar_texto(text)
if texto_requiere_traduccion(processed_text):
texts_to_translate.append(text)
indices_to_translate.append(index)
2024-07-30 09:19:19 -03:00
2024-07-30 09:58:19 -03:00
num_texts = len(texts_to_translate)
logger.info(f"Número total de textos a traducir: {num_texts}")
2024-07-30 09:19:19 -03:00
2024-07-30 09:58:19 -03:00
translations = []
for start_idx in range(0, num_texts, batch_size):
end_idx = min(start_idx + batch_size, num_texts)
2024-07-30 09:19:19 -03:00
batch_texts = texts_to_translate[start_idx:end_idx]
2024-07-30 09:58:19 -03:00
batch_translations = translate_batch(batch_texts, "Italian", target_lang_code)
2024-07-30 09:19:19 -03:00
translations.extend(batch_translations)
2024-07-30 09:58:19 -03:00
logger.info(f"Número total de traducciones recibidas: {len(translations)}")
if len(translations) != len(indices_to_translate):
logger.warning(
f"Desajuste entre el número de traducciones ({len(translations)}) y el número de índices ({len(indices_to_translate)})"
)
for i, index in enumerate(indices_to_translate):
if i < len(translations):
df.at[index, target_col] = translations[i]
else:
logger.error(f"No hay traducción disponible para el índice {index}")
2024-07-30 09:19:19 -03:00
2024-07-30 09:58:19 -03:00
output_path = os.path.join(
os.path.dirname(file_path), "master_export2translate_translated.xlsx"
)
2024-07-30 09:19:19 -03:00
df.to_excel(output_path, index=False)
2024-07-30 09:58:19 -03:00
logger.info(f"Archivo traducido guardado en: {output_path}")
2024-07-30 09:19:19 -03:00
print(f"Archivo traducido guardado en: {output_path}")
2024-07-30 09:58:19 -03:00
2024-07-30 09:19:19 -03:00
if __name__ == "__main__":
batch_size = 10
2024-07-30 09:58:19 -03:00
translate_file = "master_export2translate.xlsx"
2024-07-30 09:19:19 -03:00
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]
2024-07-30 09:58:19 -03:00
traducir_todo = (
input("¿Desea traducir todas las celdas (s/n)? ").strip().lower() == "s"
)
main(translate_file, target_lang_code, traducir_todo, batch_size)