diff --git a/__pycache__/openai_api_key.cpython-310.pyc b/__pycache__/openai_api_key.cpython-310.pyc new file mode 100644 index 0000000..4ca5560 Binary files /dev/null and b/__pycache__/openai_api_key.cpython-310.pyc differ diff --git a/llm_translate_text.py b/llm_translate_text.py new file mode 100644 index 0000000..2133f91 --- /dev/null +++ b/llm_translate_text.py @@ -0,0 +1,109 @@ +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() == 'sí' + main(translate_file, target_lang_code, traducir_todo, batch_size) \ No newline at end of file diff --git a/master_export2translate.xlsx b/master_export2translate.xlsx index 1f86c41..0850456 100644 Binary files a/master_export2translate.xlsx and b/master_export2translate.xlsx differ diff --git a/master_export2translate_translated.xlsx b/master_export2translate_translated.xlsx new file mode 100644 index 0000000..0883edf Binary files /dev/null and b/master_export2translate_translated.xlsx differ diff --git a/openai_api_key.py b/openai_api_key.py new file mode 100644 index 0000000..16478a4 --- /dev/null +++ b/openai_api_key.py @@ -0,0 +1,3 @@ +# Configura tu clave API de OpenAI +def api_key(): + return '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' \ No newline at end of file