""" Módulo de control de calidad y normalización de eventos y entidades. Incluye: 1. Herramientas para limpiar texto y validar eventos (5W1H). 2. Lógica de deduplicación de entidades. 3. Auditoría de calidad para Entity Linking. """ import logging import unicodedata import string from urllib.parse import unquote from typing import List, Dict, Any logger = logging.getLogger(__name__) # ========================================== # 1. HERRAMIENTAS DE NORMALIZACIÓN Y EVENTOS # ========================================== def clean_punctuation(text: str) -> str: """ Reemplaza puntuación por ESPACIOS. Crucial para casos como 'dijo,que' -> 'dijo que'. """ if not isinstance(text, str): return "" # Creamos una tabla de traducción: cada signo de puntuación se vuelve un espacio translator = str.maketrans(string.punctuation, ' ' * len(string.punctuation)) return text.translate(translator) def normalize_text(text: str) -> str: """ Normalización base para comparación de texto (sin tildes, minúsculas). """ if not isinstance(text, str): return "" # Eliminar tildes (NFKD separa la tilde de la letra, encode la descarta) normalized = unicodedata.normalize('NFKD', text) ascii_text = normalized.encode('ascii', 'ignore').decode('ascii') return ascii_text.lower().strip() def generate_slug(text: str) -> str: """ Específico para crear IDs de Neo4j (local:pedro_sanchez). Usa la normalización base pero asegura guiones bajos. """ # Quitamos tildes y bajamos a minúsculas clean = normalize_text(text) # Quitamos puntuación (aquí sí podemos borrarla o cambiarla por nada) clean = clean.translate(str.maketrans('', '', string.punctuation)) # Reemplazamos espacios internos por guiones bajos return clean.replace(' ', '_') # ========================================== # 2. LISTAS DE CONTROL # ========================================== # Stop-verbs _STOP_VERBS_RAW = { 'ser', 'estar', 'parecer', 'haber', 'tener', 'hacer', 'ir', 'poder', 'deber', 'querer', 'decir', 'señalar', 'indicar', 'afirmar', 'explicar', 'asegurar', 'manifestar', 'comentar', 'es', 'son', 'era', 'fue', 'fueron', 'sido', 'siendo', 'está', 'están', 'estaba', 'estuvo', 'estuvieron', 'ha', 'han', 'había', 'hubo', 'habido', 'dijo', 'dijeron', 'dice', 'dicen', 'señaló', 'señalaron', 'señala', 'afirmó', 'afirmaron', 'afirma', 'explicó', 'explicaron', 'explica', 'aseguró', 'aseguraron', 'asegura', 'manifestó', 'manifestaron', 'manifiesta', 'comentó', 'comentaron', 'comenta' } # Normalizamos la lista al cargar para asegurar coincidencia perfecta STOP_VERBS = {normalize_text(v) for v in _STOP_VERBS_RAW} # Partículas a ignorar al inicio del verbo PARTICLES = {'se', 'no', 'le', 'les', 'lo', 'la', 'los', 'las', 'me', 'te', 'nos', 'os'} # Pronombres relativos y patrones inválidos para WHO INVALID_WHO_PATTERNS = { # Relativos 'que', 'quien', 'quienes', 'cual', 'cuales', 'cuyo', 'cuya', # Demostrativos 'eso', 'esto', 'aquello', 'ello', # Indefinidos 'algo', 'alguien', 'nadie', 'nada', 'todo', 'todos', 'ambos', # Personales (sin referente en el grafo) 'yo', 'tu', 'nosotros', 'vosotros', 'usted', 'ustedes' } # Añadir a las listas de control UNICODE_PUNCTUATION = '—–«»""''…•·¿¡' # Puntuación común no-ASCII # ========================================== # 3. LÓGICA DE FILTRADO DE EVENTOS # ========================================== def get_main_verb(what_span: str) -> str: """Extrae el verbo principal limpiando puntuación y saltando partículas.""" clean_span = clean_punctuation(what_span) words = clean_span.split() for word in words: word_normalized = normalize_text(word) if word_normalized not in PARTICLES: return word_normalized return words[0] if words else '' def is_valid_who(who: Dict[str, Any]) -> bool: """Filtro para el campo WHO.""" span = who.get('span', '').strip() has_uri = who.get('uri') is not None ner_type = who.get('type') if len(span) < 2 or len(span) > 60: return False if span[0] in string.punctuation or span[0] in UNICODE_PUNCTUATION: return False if span[-1] in string.punctuation or span[-1] in UNICODE_PUNCTUATION: return False if ',' in span: return False clean_span = clean_punctuation(span) words = clean_span.split() if len(words) > 5: return False if words: first_word = normalize_text(words[0]) if first_word in INVALID_WHO_PATTERNS: return False if not has_uri and ner_type not in ['PER', 'ORG', 'LOC']: return False return True def is_valid_event(event: Dict[str, Any]) -> bool: """Aplica filtro de calidad al evento completo.""" has_valid_who = False for who in event.get('who', []): if not is_valid_who(who): continue if who.get('uri') or who.get('type') in ['PER', 'ORG', 'LOC']: has_valid_who = True break if not has_valid_who: return False what_list = event.get('what', []) if not what_list or what_list[0].get('start', -1) == -1: return False what_span = what_list[0].get('span', '') main_verb = get_main_verb(what_span) if main_verb in STOP_VERBS: return False if len(what_span) < 3 or len(what_span) > 200: return False return True def deduplicate_entities(entities_list: List[Dict[str, Any]]) -> Dict[str, Dict[str, Any]]: """Deduplicación de entidades basada en frecuencia y completitud.""" unique_entities = {} name_frequency = {} for ent in entities_list: uri = ent.get('uri') raw_name = ent.get('span', '').strip() if not uri: uri = f"local:{generate_slug(raw_name)}" if uri not in unique_entities: unique_entities[uri] = { 'name': raw_name, 'type': ent.get('type'), 'uri': uri, 'mention_count': 0 } name_frequency[uri] = {} if raw_name not in name_frequency[uri]: name_frequency[uri][raw_name] = 0 name_frequency[uri][raw_name] += 1 unique_entities[uri]['mention_count'] += 1 if not unique_entities[uri]['type'] and ent.get('type'): unique_entities[uri]['type'] = ent.get('type') # Selección del nombre canónico for uri in unique_entities: if not name_frequency[uri]: continue total_mentions = unique_entities[uri]['mention_count'] most_frequent = max(name_frequency[uri], key=name_frequency[uri].get) best_name = most_frequent base_normalized = normalize_text(most_frequent) for candidate, count in name_frequency[uri].items(): if len(candidate) <= len(best_name): continue if base_normalized not in normalize_text(candidate): continue if count >= total_mentions * 0.10: best_name = candidate unique_entities[uri]['name'] = best_name return unique_entities # ========================================== # 4. AUDITORÍA DE ENTITY LINKING (Añadido) # ========================================== KNOWN_DISAMBIGUATION_ERRORS = { "Homo_erectus_pekinensis": "Falso positivo crítico: Capital (Pekín) -> Especie homínida", "Bandera_de_Europa": "Error metonímico: Organización (UE) -> Símbolo (Bandera)", "Bandera_de_la_República_Popular_China": "Error metonímico: País (China) -> Símbolo (Bandera)", "Agencia_Espacial_Europea": "Ambigüedad contextual: Pronombre ('esa') -> Organización (ESA)", "Mariano_Rajoy": "Asociación obsoleta: Cargo (Presidente) -> Entidad histórica", "Parlamento_Europeo": "Desviación semántica: Organización relacionada -> Institución específica", "Hoja": "Ruido: Sustantivo común -> Entidad botánica", "Cerdo": "Ruido: Sustantivo común -> Entidad biológica", "Masa": "Ruido: Magnitud física -> Entidad", "Guerra_comercial": "Generalización: Concepto abstracto -> Evento histórico" } SUSPICIOUS_TYPES = { "DBpedia:Eukaryote", "DBpedia:Mammal", "DBpedia:Animal", "DBpedia:Fungus", "DBpedia:Species", "DBpedia:Biomolecule" } SAFE_TYPES = { "DBpedia:Person", "DBpedia:Place", "DBpedia:Organisation", "DBpedia:Country", "DBpedia:City", "DBpedia:Company" } def audit_linking_quality(text: str, linker: Any, thresholds: List[float]) -> None: for confidence in thresholds: print(f"--- Evaluando con umbral: {confidence} ---") try: annotations = linker.annotate_text(text, confidence=confidence) count = len(annotations) print(f" > Entidades encontradas: {count}") if count > 0: _analyze_anomalies(annotations) else: print(" > Sin resultados.") except Exception as e: import traceback traceback.print_exc() print(f" > Error en ejecución: {str(e)}") print("") def _analyze_anomalies(annotations: List[Dict[str, Any]]) -> None: detected_problems = [] for entity in annotations: raw_uri = entity.get('uri', '') text = entity.get('text', '') decoded_uri = unquote(raw_uri) uri_suffix = decoded_uri.split('/')[-1] if uri_suffix in KNOWN_DISAMBIGUATION_ERRORS: description = KNOWN_DISAMBIGUATION_ERRORS[uri_suffix] detected_problems.append(f"[URI PROHIBIDA] '{text}' -> {uri_suffix} ({description})") continue raw_types = entity.get('types', []) if isinstance(raw_types, list): entity_types = set(raw_types) elif isinstance(raw_types, str): entity_types = set(raw_types.split(',')) if raw_types else set() else: entity_types = set() suspicious_matches = entity_types.intersection(SUSPICIOUS_TYPES) has_safe_type = not entity_types.isdisjoint(SAFE_TYPES) if suspicious_matches and not has_safe_type: detected_problems.append(f"[TIPO SOSPECHOSO] '{text}' -> {uri_suffix} ({', '.join(suspicious_matches)})") if detected_problems: print(" [!] ANOMALÍAS DETECTADAS:") for problem in sorted(list(set(detected_problems))): print(f" * {problem}") else: print(" > No se detectaron anomalías obvias en esta muestra.")