Update functions.py
Browse files- functions.py +20 -134
functions.py
CHANGED
|
@@ -1,5 +1,7 @@
|
|
| 1 |
# functions.py
|
| 2 |
import json
|
|
|
|
|
|
|
| 3 |
from datasets import load_dataset
|
| 4 |
|
| 5 |
# Cargar modalidades y tareas
|
|
@@ -7,35 +9,24 @@ def cargar_modalidades_tareas():
|
|
| 7 |
with open("modalidades_tareas.json", "r") as file:
|
| 8 |
MODALIDAD_TAREAS = json.load(file)
|
| 9 |
return MODALIDAD_TAREAS
|
| 10 |
-
|
| 11 |
-
# Validar modalidades y tareas
|
| 12 |
-
def validar_modalidades_tareas(modalidades_tareas):
|
| 13 |
-
try:
|
| 14 |
-
for modalidad, tareas in modalidades_tareas.items():
|
| 15 |
-
if not isinstance(modalidad, str) or not isinstance(tareas, list):
|
| 16 |
-
raise ValueError(f"Formato incorrecto para la modalidad: {modalidad}")
|
| 17 |
-
for tarea in tareas:
|
| 18 |
-
if not isinstance(tarea, str):
|
| 19 |
-
raise ValueError(f"Formato incorrecto para la tarea: {tarea} en la modalidad {modalidad}")
|
| 20 |
-
except AttributeError:
|
| 21 |
-
raise ValueError("El objeto proporcionado no es un diccionario válido.")
|
| 22 |
|
| 23 |
# Generar gráfica de barras
|
| 24 |
def generar_grafica_barras(tareas_seleccionadas, MODALIDAD_TAREAS):
|
| 25 |
try:
|
| 26 |
-
|
| 27 |
-
for modalidad,
|
| 28 |
-
|
|
|
|
| 29 |
|
| 30 |
fig, ax = plt.subplots(figsize=(10, 6))
|
| 31 |
-
ax.barh(list(
|
| 32 |
ax.set_xlabel('Cantidad de Tareas Seleccionadas')
|
| 33 |
ax.set_ylabel('Modalidades')
|
| 34 |
ax.set_title('Distribución de Tareas por Modalidad')
|
| 35 |
ax.invert_yaxis()
|
| 36 |
return fig
|
| 37 |
except Exception as e:
|
| 38 |
-
raise ValueError(f"Error al generar
|
| 39 |
|
| 40 |
# Buscar datasets en HuggingFace
|
| 41 |
def buscar_datasets(tareas_seleccionadas, filtro_tamaño, filtro_licencia):
|
|
@@ -55,36 +46,9 @@ def buscar_datasets(tareas_seleccionadas, filtro_tamaño, filtro_licencia):
|
|
| 55 |
resultados.append(f"- {dataset['id']}: {dataset['description']}")
|
| 56 |
return "\n".join(resultados)
|
| 57 |
except requests.exceptions.RequestException as e:
|
| 58 |
-
raise ValueError(f"Error al buscar datasets: {str(e)}")
|
| 59 |
-
|
| 60 |
-
# Función para generar el dataset
|
| 61 |
-
def generar_dataset(encabezado, datasets_seleccionados, pagina_actual=1, filas_por_pagina=5):
|
| 62 |
-
try:
|
| 63 |
-
if not datasets_seleccionados:
|
| 64 |
-
raise ValueError("Debes seleccionar al menos un dataset.")
|
| 65 |
-
|
| 66 |
-
columnas = encabezado.split(",")
|
| 67 |
-
filas = []
|
| 68 |
-
|
| 69 |
-
# Cargar datos reales desde los datasets seleccionados
|
| 70 |
-
for dataset_id in datasets_seleccionados.split("\n"):
|
| 71 |
-
dataset_id = dataset_id.strip("- ").split(":")[0] # Extraer ID del dataset
|
| 72 |
-
try:
|
| 73 |
-
dataset = load_dataset(dataset_id, split="train")
|
| 74 |
-
inicio = (pagina_actual - 1) * filas_por_pagina
|
| 75 |
-
fin = pagina_actual * filas_por_pagina
|
| 76 |
-
for i, fila in enumerate(dataset[inicio:fin]):
|
| 77 |
-
valores = [str(fila.get(col, "valor_default")) for col in columnas[1:]] # Ignorar 'id'
|
| 78 |
-
filas.append(f"id_{inicio + i}," + ",".join(valores))
|
| 79 |
-
except Exception as e:
|
| 80 |
-
filas.append(f"Error cargando dataset {dataset_id}: {str(e)}")
|
| 81 |
-
|
| 82 |
-
contenido_csv = "\n".join([encabezado] + filas)
|
| 83 |
-
return contenido_csv
|
| 84 |
-
except Exception as e:
|
| 85 |
-
raise ValueError(f"Error al generar el dataset: {str(e)}")
|
| 86 |
|
| 87 |
-
#
|
| 88 |
def generar_encabezado(tareas_seleccionadas):
|
| 89 |
MODALIDAD_TAREAS = cargar_modalidades_tareas()
|
| 90 |
|
|
@@ -98,102 +62,24 @@ def generar_encabezado(tareas_seleccionadas):
|
|
| 98 |
for modalidad, datos in MODALIDAD_TAREAS.items():
|
| 99 |
if tarea in datos["tareas"]:
|
| 100 |
# Añadir columnas generales de la modalidad
|
| 101 |
-
|
| 102 |
-
for col in columnas_generales:
|
| 103 |
if col not in columnas_modulos:
|
| 104 |
columnas.append(col)
|
| 105 |
columnas_modulos.add(col)
|
| 106 |
-
|
| 107 |
# Añadir columnas específicas de la tarea
|
| 108 |
-
|
| 109 |
-
for col in columnas_tarea:
|
| 110 |
if col not in columnas_modulos:
|
| 111 |
columnas.append(col)
|
| 112 |
columnas_modulos.add(col)
|
| 113 |
|
| 114 |
-
#
|
| 115 |
-
columnas_ordenadas = sorted(
|
| 116 |
-
columnas,
|
| 117 |
key=lambda x: (
|
| 118 |
-
"input" in x,
|
| 119 |
-
"output" in x,
|
| 120 |
-
"label" in x
|
| 121 |
-
)
|
| 122 |
-
reverse=True
|
| 123 |
)
|
| 124 |
|
| 125 |
-
return ",".join(columnas_ordenadas)
|
| 126 |
-
|
| 127 |
-
def generar_encabezado_inteligente(tareas_seleccionadas, api_key):
|
| 128 |
-
max_reintentos = 3
|
| 129 |
-
espera_entre_reintentos = 2
|
| 130 |
-
|
| 131 |
-
# Prompt mejorado con instrucciones estrictas <button class="citation-flag" data-index="3">
|
| 132 |
-
prompt = f"""
|
| 133 |
-
Genera SOLO el encabezado CSV para las tareas: {', '.join(tareas_seleccionadas)}.
|
| 134 |
-
Formato: id,tarea1_label,tarea2_label,...
|
| 135 |
-
Ejemplo para 'Clasificación de texto' y 'Segmentación':
|
| 136 |
-
id,clasificación_de_texto_label,segmentación_label
|
| 137 |
-
"""
|
| 138 |
-
|
| 139 |
-
# Usar modelo especializado en generación de texto estructurado <button class="citation-flag" data-index="2">
|
| 140 |
-
API_URL = "https://api-inference.huggingface.co/models/stabilityai/stable-code-3b"
|
| 141 |
-
headers = {
|
| 142 |
-
"Authorization": f"Bearer {api_key}",
|
| 143 |
-
"Content-Type": "application/json"
|
| 144 |
-
}
|
| 145 |
-
|
| 146 |
-
for intento in range(max_reintentos + 1):
|
| 147 |
-
try:
|
| 148 |
-
if not tareas_seleccionadas:
|
| 149 |
-
raise ValueError("Debes seleccionar al menos una tarea.")
|
| 150 |
-
|
| 151 |
-
if not api_key:
|
| 152 |
-
raise ValueError("API Key no proporcionada. Ingresa una clave válida.")
|
| 153 |
-
|
| 154 |
-
# Enviar solicitud con parámetros ajustados <button class="citation-flag" data-index="2">
|
| 155 |
-
response = requests.post(
|
| 156 |
-
API_URL,
|
| 157 |
-
headers=headers,
|
| 158 |
-
json={
|
| 159 |
-
"inputs": prompt,
|
| 160 |
-
"parameters": {
|
| 161 |
-
"max_length": 64,
|
| 162 |
-
"temperature": 0.1,
|
| 163 |
-
"stop": ["\n\n"] # Detener la generación al finalizar el encabezado <button class="citation-flag" data-index="3">
|
| 164 |
-
}
|
| 165 |
-
}
|
| 166 |
-
)
|
| 167 |
-
response.raise_for_status()
|
| 168 |
-
|
| 169 |
-
# Procesar respuesta
|
| 170 |
-
if response.status_code == 200:
|
| 171 |
-
encabezado = response.json()[0]["generated_text"].strip()
|
| 172 |
-
|
| 173 |
-
# Validar formato estricto
|
| 174 |
-
if not encabezado.startswith("id,"):
|
| 175 |
-
raise ValueError("Formato inválido. Respuesta: " + encabezado)
|
| 176 |
-
|
| 177 |
-
return encabezado
|
| 178 |
-
|
| 179 |
-
except requests.exceptions.HTTPError as e:
|
| 180 |
-
if e.response.status_code == 503 and intento < max_reintentos:
|
| 181 |
-
time.sleep(espera_entre_reintentos)
|
| 182 |
-
continue
|
| 183 |
-
elif e.response.status_code == 401:
|
| 184 |
-
raise ValueError("API Key inválida o sin permisos.")
|
| 185 |
-
else:
|
| 186 |
-
raise ValueError(f"Error HTTP: {str(e)}")
|
| 187 |
-
|
| 188 |
-
except Exception as e:
|
| 189 |
-
raise ValueError(f"Error inesperado: {str(e)}")
|
| 190 |
-
|
| 191 |
-
# Fallback local si fallan todos los reintentos
|
| 192 |
-
return generar_encabezado_local(tareas_seleccionadas)
|
| 193 |
-
|
| 194 |
-
# Fallback local en caso de fallo de la API
|
| 195 |
-
def generar_encabezado_local(tareas_seleccionadas):
|
| 196 |
-
columnas = ["id"]
|
| 197 |
-
for tarea in tareas_seleccionadas:
|
| 198 |
-
columnas.append(f"{tarea.lower().replace(' ', '_')}_label")
|
| 199 |
-
return ",".join(columnas)
|
|
|
|
| 1 |
# functions.py
|
| 2 |
import json
|
| 3 |
+
import requests # Añadido <button class="citation-flag" data-index="1">
|
| 4 |
+
import matplotlib.pyplot as plt # Añadido <button class="citation-flag" data-index="1">
|
| 5 |
from datasets import load_dataset
|
| 6 |
|
| 7 |
# Cargar modalidades y tareas
|
|
|
|
| 9 |
with open("modalidades_tareas.json", "r") as file:
|
| 10 |
MODALIDAD_TAREAS = json.load(file)
|
| 11 |
return MODALIDAD_TAREAS
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
|
| 13 |
# Generar gráfica de barras
|
| 14 |
def generar_grafica_barras(tareas_seleccionadas, MODALIDAD_TAREAS):
|
| 15 |
try:
|
| 16 |
+
conteo = {}
|
| 17 |
+
for modalidad, datos in MODALIDAD_TAREAS.items():
|
| 18 |
+
tareas_modalidad = datos["tareas"].keys()
|
| 19 |
+
conteo[modalidad] = len([t for t in tareas_seleccionadas if t in tareas_modalidad])
|
| 20 |
|
| 21 |
fig, ax = plt.subplots(figsize=(10, 6))
|
| 22 |
+
ax.barh(list(conteo.keys()), list(conteo.values()), color='skyblue')
|
| 23 |
ax.set_xlabel('Cantidad de Tareas Seleccionadas')
|
| 24 |
ax.set_ylabel('Modalidades')
|
| 25 |
ax.set_title('Distribución de Tareas por Modalidad')
|
| 26 |
ax.invert_yaxis()
|
| 27 |
return fig
|
| 28 |
except Exception as e:
|
| 29 |
+
raise ValueError(f"Error al generar gráfica: {str(e)}")
|
| 30 |
|
| 31 |
# Buscar datasets en HuggingFace
|
| 32 |
def buscar_datasets(tareas_seleccionadas, filtro_tamaño, filtro_licencia):
|
|
|
|
| 46 |
resultados.append(f"- {dataset['id']}: {dataset['description']}")
|
| 47 |
return "\n".join(resultados)
|
| 48 |
except requests.exceptions.RequestException as e:
|
| 49 |
+
raise ValueError(f"Error al buscar datasets: {str(e)}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 50 |
|
| 51 |
+
# Generar encabezado
|
| 52 |
def generar_encabezado(tareas_seleccionadas):
|
| 53 |
MODALIDAD_TAREAS = cargar_modalidades_tareas()
|
| 54 |
|
|
|
|
| 62 |
for modalidad, datos in MODALIDAD_TAREAS.items():
|
| 63 |
if tarea in datos["tareas"]:
|
| 64 |
# Añadir columnas generales de la modalidad
|
| 65 |
+
for col in datos["columnas_generales"]:
|
|
|
|
| 66 |
if col not in columnas_modulos:
|
| 67 |
columnas.append(col)
|
| 68 |
columnas_modulos.add(col)
|
|
|
|
| 69 |
# Añadir columnas específicas de la tarea
|
| 70 |
+
for col in datos["tareas"][tarea]:
|
|
|
|
| 71 |
if col not in columnas_modulos:
|
| 72 |
columnas.append(col)
|
| 73 |
columnas_modulos.add(col)
|
| 74 |
|
| 75 |
+
# Ordenar columnas: inputs → outputs → labels
|
| 76 |
+
columnas_ordenadas = ["id"] + sorted(
|
| 77 |
+
columnas[1:],
|
| 78 |
key=lambda x: (
|
| 79 |
+
"input" in x,
|
| 80 |
+
"output" in x,
|
| 81 |
+
"label" in x
|
| 82 |
+
)
|
|
|
|
| 83 |
)
|
| 84 |
|
| 85 |
+
return ",".join(columnas_ordenadas)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|