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2 |
+
import spacy
|
| 3 |
+
from transformers import AutoTokenizer, AutoModel
|
| 4 |
+
import torch
|
| 5 |
+
import numpy as np
|
| 6 |
+
import re
|
| 7 |
+
from patterns import (
|
| 8 |
+
PATRONES_AMBIGUEDAD_LEXICA,
|
| 9 |
+
PATRONES_AMBIGUEDAD_SINTACTICA,
|
| 10 |
+
SUGERENCIAS_MEJORA
|
| 11 |
+
)
|
| 12 |
+
|
| 13 |
+
class SemanticAnalyzer:
|
| 14 |
+
"""
|
| 15 |
+
Analizador semántico que utiliza embeddings para comparar textos.
|
| 16 |
+
"""
|
| 17 |
+
def __init__(self, model_name: str = "PlanTL-GOB-ES/roberta-base-bne"):
|
| 18 |
+
"""
|
| 19 |
+
Inicializa el analizador semántico.
|
| 20 |
+
|
| 21 |
+
Args:
|
| 22 |
+
model_name (str): Nombre del modelo de HuggingFace a utilizar
|
| 23 |
+
"""
|
| 24 |
+
try:
|
| 25 |
+
self.tokenizer = AutoTokenizer.from_pretrained(model_name)
|
| 26 |
+
self.model = AutoModel.from_pretrained(model_name)
|
| 27 |
+
except Exception as e:
|
| 28 |
+
raise RuntimeError(f"Error cargando el modelo {model_name}: {str(e)}")
|
| 29 |
+
|
| 30 |
+
def get_embedding(self, texto: str) -> np.ndarray:
|
| 31 |
+
"""
|
| 32 |
+
Obtiene el embedding de un texto usando el modelo de transformers.
|
| 33 |
+
|
| 34 |
+
Args:
|
| 35 |
+
texto (str): Texto a procesar
|
| 36 |
+
|
| 37 |
+
Returns:
|
| 38 |
+
np.ndarray: Vector de embedding
|
| 39 |
+
"""
|
| 40 |
+
inputs = self.tokenizer(texto, return_tensors="pt", padding=True, truncation=True)
|
| 41 |
+
with torch.no_grad():
|
| 42 |
+
outputs = self.model(**inputs)
|
| 43 |
+
return outputs.last_hidden_state.mean(dim=1).numpy()[0]
|
| 44 |
+
|
| 45 |
+
def calcular_similitud(self, texto1: str, texto2: str) -> float:
|
| 46 |
+
"""
|
| 47 |
+
Compara la similitud semántica entre dos textos.
|
| 48 |
+
|
| 49 |
+
Args:
|
| 50 |
+
texto1 (str): Primer texto
|
| 51 |
+
texto2 (str): Segundo texto
|
| 52 |
+
|
| 53 |
+
Returns:
|
| 54 |
+
float: Score de similitud entre 0 y 1
|
| 55 |
+
"""
|
| 56 |
+
emb1 = self.get_embedding(texto1)
|
| 57 |
+
emb2 = self.get_embedding(texto2)
|
| 58 |
+
similarity = np.dot(emb1, emb2) / (np.linalg.norm(emb1) * np.linalg.norm(emb2))
|
| 59 |
+
return float(similarity)
|
| 60 |
+
|
| 61 |
+
class AmbiguityClassifier:
|
| 62 |
+
"""
|
| 63 |
+
Clasificador de ambigüedades en historias de usuario.
|
| 64 |
+
Detecta ambigüedades léxicas y sintácticas, y proporciona sugerencias de mejora.
|
| 65 |
+
"""
|
| 66 |
+
|
| 67 |
+
def __init__(self, model_name: str = "PlanTL-GOB-ES/roberta-base-bne"):
|
| 68 |
+
"""
|
| 69 |
+
Inicializa el clasificador de ambigüedades.
|
| 70 |
+
|
| 71 |
+
Args:
|
| 72 |
+
model_name (str): Nombre del modelo de HuggingFace a utilizar
|
| 73 |
+
"""
|
| 74 |
+
try:
|
| 75 |
+
self.nlp = spacy.load("es_core_news_sm")
|
| 76 |
+
except OSError:
|
| 77 |
+
raise RuntimeError("Es necesario instalar el modelo es_core_news_sm. Ejecute: python -m spacy download es_core_news_sm")
|
| 78 |
+
|
| 79 |
+
self.semantic_analyzer = SemanticAnalyzer(model_name)
|
| 80 |
+
|
| 81 |
+
def __call__(self, texto: str) -> Dict[str, Union[bool, List[str], float]]:
|
| 82 |
+
"""
|
| 83 |
+
Analiza una historia de usuario en busca de ambigüedades.
|
| 84 |
+
|
| 85 |
+
Args:
|
| 86 |
+
texto (str): Historia de usuario a analizar
|
| 87 |
+
|
| 88 |
+
Returns:
|
| 89 |
+
Dict: Resultado del análisis con tipos de ambigüedad y sugerencias
|
| 90 |
+
"""
|
| 91 |
+
if not texto or not isinstance(texto, str):
|
| 92 |
+
return {
|
| 93 |
+
"tiene_ambiguedad": False,
|
| 94 |
+
"ambiguedad_lexica": [],
|
| 95 |
+
"ambiguedad_sintactica": [],
|
| 96 |
+
"sugerencias": ["El texto está vacío o no es válido"],
|
| 97 |
+
"score_ambiguedad": 0.0
|
| 98 |
+
}
|
| 99 |
+
|
| 100 |
+
# Procesar el texto con spaCy
|
| 101 |
+
doc = self.nlp(texto.strip())
|
| 102 |
+
|
| 103 |
+
# Detectar ambigüedades léxicas
|
| 104 |
+
ambiguedades_lexicas = []
|
| 105 |
+
for patron in PATRONES_AMBIGUEDAD_LEXICA:
|
| 106 |
+
if re.search(patron["patron"], texto, re.IGNORECASE):
|
| 107 |
+
ambiguedades_lexicas.append({
|
| 108 |
+
"tipo": patron["tipo"],
|
| 109 |
+
"descripcion": patron["descripcion"]
|
| 110 |
+
})
|
| 111 |
+
|
| 112 |
+
# Detectar ambigüedades sintácticas
|
| 113 |
+
ambiguedades_sintacticas = []
|
| 114 |
+
for patron in PATRONES_AMBIGUEDAD_SINTACTICA:
|
| 115 |
+
if re.search(patron["patron"], texto, re.IGNORECASE):
|
| 116 |
+
ambiguedades_sintacticas.append({
|
| 117 |
+
"tipo": patron["tipo"],
|
| 118 |
+
"descripcion": patron["descripcion"]
|
| 119 |
+
})
|
| 120 |
+
|
| 121 |
+
# Generar sugerencias de mejora
|
| 122 |
+
sugerencias = []
|
| 123 |
+
if ambiguedades_lexicas or ambiguedades_sintacticas:
|
| 124 |
+
for ambiguedad in ambiguedades_lexicas + ambiguedades_sintacticas:
|
| 125 |
+
tipo = ambiguedad["tipo"]
|
| 126 |
+
if tipo in SUGERENCIAS_MEJORA:
|
| 127 |
+
sugerencias.extend(SUGERENCIAS_MEJORA[tipo])
|
| 128 |
+
|
| 129 |
+
# Calcular score de ambigüedad
|
| 130 |
+
score = len(ambiguedades_lexicas) * 0.4 + len(ambiguedades_sintacticas) * 0.6
|
| 131 |
+
score_normalizado = min(1.0, score / 5.0) # Normalizar a un rango de 0 a 1
|
| 132 |
+
|
| 133 |
+
return {
|
| 134 |
+
"tiene_ambiguedad": bool(ambiguedades_lexicas or ambiguedades_sintacticas),
|
| 135 |
+
"ambiguedad_lexica": [amb["descripcion"] for amb in ambiguedades_lexicas],
|
| 136 |
+
"ambiguedad_sintactica": [amb["descripcion"] for amb in ambiguedades_sintacticas],
|
| 137 |
+
"sugerencias": sugerencias if sugerencias else ["No se encontraron ambigüedades"],
|
| 138 |
+
"score_ambiguedad": round(score_normalizado, 2)
|
| 139 |
+
}
|
| 140 |
+
|
| 141 |
+
def analizar_similitud_semantica(self, texto1: str, texto2: str) -> float:
|
| 142 |
+
"""
|
| 143 |
+
Compara la similitud semántica entre dos textos.
|
| 144 |
+
|
| 145 |
+
Args:
|
| 146 |
+
texto1 (str): Primer texto
|
| 147 |
+
texto2 (str): Segundo texto
|
| 148 |
+
|
| 149 |
+
Returns:
|
| 150 |
+
float: Score de similitud entre 0 y 1
|
| 151 |
+
"""
|
| 152 |
+
return self.semantic_analyzer.calcular_similitud(texto1, texto2)
|
requirements.txt
CHANGED
|
@@ -1,2 +1,14 @@
|
|
| 1 |
-
gradio
|
| 2 |
-
requests
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gradio>=5.25.2
|
| 2 |
+
requests
|
| 3 |
+
spacy>=3.7.0
|
| 4 |
+
es-core-news-sm @ https://github.com/explosion/spacy-models/releases/download/es_core_news_sm-3.7.0/es_core_news_sm-3.7.0-py3-none-any.whl
|
| 5 |
+
pytest>=8.0.0
|
| 6 |
+
typing-extensions>=4.9.0
|
| 7 |
+
nltk>=3.8.1
|
| 8 |
+
gradio>=4.19.2
|
| 9 |
+
requests>=2.31.0
|
| 10 |
+
pandas>=2.2.0
|
| 11 |
+
transformers>=4.30.0
|
| 12 |
+
torch>=2.0.0
|
| 13 |
+
numpy>=1.24.0
|
| 14 |
+
setuptools>=69.1.0
|