Testeado ultimos cambios en la funcion de afinidad.
This commit is contained in:
parent
2262ac1f67
commit
b31644553e
Binary file not shown.
Binary file not shown.
File diff suppressed because it is too large
Load Diff
|
@ -11,6 +11,8 @@ import json
|
||||||
from google.cloud import translate_v2 as translate
|
from google.cloud import translate_v2 as translate
|
||||||
from google.oauth2 import service_account
|
from google.oauth2 import service_account
|
||||||
import html
|
import html
|
||||||
|
from tqdm import tqdm
|
||||||
|
import time
|
||||||
|
|
||||||
openai_client = OpenAI(api_key=openai_api_key())
|
openai_client = OpenAI(api_key=openai_api_key())
|
||||||
GOOGLE_APPLICATION_CREDENTIALS = "translate-431108-020c17463fbb.json"
|
GOOGLE_APPLICATION_CREDENTIALS = "translate-431108-020c17463fbb.json"
|
||||||
|
@ -25,6 +27,28 @@ IDIOMAS = {
|
||||||
6: ("German", "de-DE"),
|
6: ("German", "de-DE"),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
def save_dataframe_with_retries(df, output_path, max_retries=5, retry_delay=5):
|
||||||
|
"""
|
||||||
|
Guarda un DataFrame en un archivo Excel, reintentando si el archivo está en uso.
|
||||||
|
|
||||||
|
:param df: El DataFrame a guardar.
|
||||||
|
:param output_path: La ruta del archivo donde se guardará el DataFrame.
|
||||||
|
:param max_retries: El número máximo de reintentos en caso de error.
|
||||||
|
:param retry_delay: El tiempo de espera (en segundos) entre cada reintento.
|
||||||
|
"""
|
||||||
|
retries = 0
|
||||||
|
while retries < max_retries:
|
||||||
|
try:
|
||||||
|
df.to_excel(output_path, index=False)
|
||||||
|
print("Archivo guardado exitosamente.")
|
||||||
|
return
|
||||||
|
except PermissionError as e:
|
||||||
|
print(f"Error de permiso: {e}. Reintentando en {retry_delay} segundos...")
|
||||||
|
retries += 1
|
||||||
|
time.sleep(retry_delay)
|
||||||
|
|
||||||
|
print(f"No se pudo guardar el archivo después de {max_retries} intentos.")
|
||||||
|
|
||||||
|
|
||||||
def configurar_logger():
|
def configurar_logger():
|
||||||
logger = logging.getLogger("translate_logger")
|
logger = logging.getLogger("translate_logger")
|
||||||
|
@ -141,8 +165,11 @@ def translate_batch_openai(texts_dict, source_lang, target_lang):
|
||||||
|
|
||||||
|
|
||||||
def affinity_batch_openai(texts_dict):
|
def affinity_batch_openai(texts_dict):
|
||||||
system_prompt = "Evaluate the semantic similarity between the following pairs of texts on a scale from 0 to 1. Return the similarity score in JSON format for each pair in the same order."
|
system_prompt = (
|
||||||
original_list = list(texts_dict.keys())
|
"Evaluate the semantic similarity between the following table of pairs of texts in json format on a scale from 0 to 1. "
|
||||||
|
"Return the similarity scores for every row in JSON format as a list of numbers, without any additional text or formatting."
|
||||||
|
)
|
||||||
|
original_list = [transformar_texto(key) for key in texts_dict.keys()]
|
||||||
re_translated_list = list(texts_dict.values())
|
re_translated_list = list(texts_dict.values())
|
||||||
|
|
||||||
request_payload = json.dumps(
|
request_payload = json.dumps(
|
||||||
|
@ -155,15 +182,32 @@ def affinity_batch_openai(texts_dict):
|
||||||
messages=[
|
messages=[
|
||||||
{
|
{
|
||||||
"role": "system",
|
"role": "system",
|
||||||
"content": f"You are a semantic similarity evaluator.{system_prompt}",
|
"content": system_prompt,
|
||||||
},
|
},
|
||||||
{"role": "user", "content": request_payload},
|
{"role": "user", "content": request_payload},
|
||||||
],
|
],
|
||||||
max_tokens=1500,
|
max_tokens=1500,
|
||||||
temperature=0.3,
|
temperature=0.3,
|
||||||
)
|
)
|
||||||
response_payload = json.loads(response.choices[0].message.content.strip("'```json\n").strip("```"))
|
response_content = response.choices[0].message.content
|
||||||
|
|
||||||
|
# Limpiar y convertir el contenido de la respuesta
|
||||||
|
cleaned_response_content = response_content.strip().strip("'```json").strip("```")
|
||||||
|
|
||||||
|
# Intentar convertir el contenido a JSON
|
||||||
|
try:
|
||||||
|
response_payload = json.loads(cleaned_response_content)
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
raise ValueError("La respuesta no se pudo decodificar como JSON.")
|
||||||
|
|
||||||
|
# Manejar diferentes formatos de respuesta
|
||||||
|
if isinstance(response_payload, dict) and 'similarity_scores' in response_payload:
|
||||||
|
scores = response_payload['similarity_scores']
|
||||||
|
elif isinstance(response_payload, list):
|
||||||
scores = response_payload
|
scores = response_payload
|
||||||
|
else:
|
||||||
|
raise ValueError("Formato de respuesta inesperado.")
|
||||||
|
|
||||||
logger.info(f"Respuestas recibidas:\n{scores}")
|
logger.info(f"Respuestas recibidas:\n{scores}")
|
||||||
|
|
||||||
if len(scores) != len(original_list):
|
if len(scores) != len(original_list):
|
||||||
|
@ -173,6 +217,7 @@ def affinity_batch_openai(texts_dict):
|
||||||
|
|
||||||
return dict(zip(texts_dict.keys(), scores))
|
return dict(zip(texts_dict.keys(), scores))
|
||||||
|
|
||||||
|
|
||||||
def main(file_path, target_lang_code, target_lang, 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"
|
||||||
|
@ -252,7 +297,7 @@ def main(file_path, target_lang_code, target_lang, traducir_todo, batch_size=10)
|
||||||
|
|
||||||
# Traduccion inversa
|
# Traduccion inversa
|
||||||
# Actualizar el DataFrame con las traducciones y hacemos la Traduccion inversa
|
# Actualizar el DataFrame con las traducciones y hacemos la Traduccion inversa
|
||||||
for index, row in df.iterrows():
|
for index, row in tqdm(df.iterrows(), total=df.shape[0], desc="Procesando traducciones"):
|
||||||
source_text = str(row[source_col])
|
source_text = str(row[source_col])
|
||||||
if source_text in translations:
|
if source_text in translations:
|
||||||
df.at[index, target_col] = translations[source_text]
|
df.at[index, target_col] = translations[source_text]
|
||||||
|
@ -270,6 +315,7 @@ def main(file_path, target_lang_code, target_lang, traducir_todo, batch_size=10)
|
||||||
# Afinidades
|
# Afinidades
|
||||||
# Se calculan las Afinidades
|
# Se calculan las Afinidades
|
||||||
affinities = {}
|
affinities = {}
|
||||||
|
batch_size = 10
|
||||||
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 = dict(list(texts_to_translate.items())[start_idx:end_idx])
|
batch_texts = dict(list(texts_to_translate.items())[start_idx:end_idx])
|
||||||
|
@ -301,13 +347,13 @@ def main(file_path, target_lang_code, target_lang, traducir_todo, batch_size=10)
|
||||||
# Actualizar el DataFrame con las Afinidades
|
# Actualizar el DataFrame con las Afinidades
|
||||||
for index, row in df.iterrows():
|
for index, row in df.iterrows():
|
||||||
source_text = str(row[source_col])
|
source_text = str(row[source_col])
|
||||||
if source_text in translations:
|
if source_text in affinities:
|
||||||
df.at[index, affinity_col] = affinities[source_text]
|
df.at[index, affinity_col] = affinities[source_text]
|
||||||
|
|
||||||
output_path = os.path.join(
|
output_path = os.path.join(
|
||||||
os.path.dirname(file_path), "3_master_export2translate_translated.xlsx"
|
os.path.dirname(file_path), "3_master_export2translate_translated.xlsx"
|
||||||
)
|
)
|
||||||
df.to_excel(output_path, index=False)
|
save_dataframe_with_retries(df,output_path=output_path)
|
||||||
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}")
|
||||||
|
|
||||||
|
|
Loading…
Reference in New Issue