HMI_Translate_Helper_wMaste.../llm_translate_text.py

109 lines
4.1 KiB
Python
Raw Normal View History

2024-07-30 09:19:19 -03:00
import pandas as pd
import openai
import os
import re
import argparse
from openai_api_key import api_key
openai_api_key = api_key()
# Diccionario de idiomas
IDIOMAS = {
1: ("English", "en"),
2: ("Portuguese", "pt"),
3: ("Spanish", "es"),
4: ("Russian", "ru"),
5: ("French", "fr"),
6: ("German", "de")
}
def mostrar_idiomas():
print("Selecciona el idioma de destino:")
for numero, (nombre, _) in IDIOMAS.items():
print(f"{numero}: {nombre}")
def translate_text(text, source_lang, target_lang):
response = openai.Completion.create(
engine="davinci",
prompt=f"Translate the following text from {source_lang} to {target_lang} while preserving special fields like <> and <#>: {text}",
max_tokens=150, # Ajusta esto según tus necesidades
n=1,
stop=None,
temperature=0.3
)
return response.choices[0].text.strip()
def translate_batch(texts, source_lang, target_lang):
joined_text = "\n".join(texts)
response = openai.Completion.create(
engine="davinci",
prompt=f"Translate the following texts from {source_lang} to {target_lang} while preserving special fields like <> and <#>:\n\n{joined_text}",
max_tokens=1500, # Ajusta esto según tus necesidades
n=1,
stop=None,
temperature=0.3
)
translations = response.choices[0].text.strip().split('\n')
return translations
def texto_requiere_traduccion(texto):
# Comprobar si hay una palabra con más de 3 letras y si no es solo campos especiales
palabras = re.findall(r'\b\w{4,}\b', texto)
campos_especiales = re.findall(r'<.*?>', texto)
return len(palabras) > 0 and len(campos_especiales) < len(re.findall(r'<#>', texto))
def main(file_path, target_lang_code, traducir_todo, batch_size=10):
# Cargar el archivo master_export2translate.xlsx
df = pd.read_excel(file_path)
# Identificar la columna clave y la columna de destino
source_col = "it-IT"
target_col = f"{target_lang_code} Translated"
# Si la columna de destino ya existe, mantenerla o eliminarla según la opción de traducción
if target_col in df.columns and not traducir_todo:
df[target_col] = df[target_col]
else:
df[target_col] = None
# Preparar los textos para traducir
if traducir_todo:
texts_to_translate = [text for text in df[source_col].astype(str).tolist() if texto_requiere_traduccion(text)]
else:
texts_to_translate = [text for text in df.loc[df[target_col].isnull(), source_col].astype(str).tolist() if texto_requiere_traduccion(text)]
num_rows = len(texts_to_translate)
translations = []
for start_idx in range(0, num_rows, batch_size):
end_idx = min(start_idx + batch_size, num_rows)
batch_texts = texts_to_translate[start_idx:end_idx]
batch_translations = translate_batch(batch_texts, 'Italian', target_lang_code)
translations.extend(batch_translations)
# Asignar las traducciones al DataFrame
if traducir_todo:
df[target_col] = [translate_batch([text], 'Italian', target_lang_code)[0] if texto_requiere_traduccion(text) else text for text in df[source_col].astype(str).tolist()]
else:
indices = df.loc[df[target_col].isnull()].index
for i, index in enumerate(indices):
if texto_requiere_traduccion(df.at[index, source_col]):
df.at[index, target_col] = translations[i]
# Guardar el archivo actualizado
output_path = os.path.join(os.path.dirname(file_path), 'master_export2translate_translated.xlsx')
df.to_excel(output_path, index=False)
print(f"Archivo traducido guardado en: {output_path}")
if __name__ == "__main__":
batch_size = 10
translate_file = '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]
traducir_todo = input("¿Desea traducir todas las celdas (sí/no)? ").strip().lower() == ''
main(translate_file, target_lang_code, traducir_todo, batch_size)