| """ |
| Módulo de utilidades para el procesamiento de lenguaje natural (NLP). |
| Proporciona herramientas de limpieza, filtrado de stop-words y validación ontológica. |
| """ |
|
|
| import nltk |
| import ssl |
| from nltk.corpus import stopwords |
|
|
| |
| |
| try: |
| _create_unverified_https_context = ssl._create_unverified_context |
| except AttributeError: |
| pass |
| else: |
| ssl._create_default_https_context = _create_unverified_https_context |
|
|
| |
| nltk.download('stopwords', quiet=True) |
| ENTITY_STOPWORDS = set(stopwords.words('spanish')) |
|
|
| def filter_entities_with_context(entities_list, news_row): |
| """ |
| Filtra y depura la lista de entidades mediante una lógica de validación cuádruple: |
| composición, pertinencia semántica, relevancia contextual y léxica. |
| |
| Parámetros: |
| entities_list (list): Diccionarios de entidades obtenidos de DBpedia Spotlight. |
| news_row (pd.Series): Registro original de la noticia para análisis de contexto. |
| |
| Retorna: |
| list: Entidades que superan los criterios de calidad establecidos. |
| """ |
| |
| |
| VALID_TYPES = [ |
| 'Person', 'Politician', 'President', |
| 'Organisation', 'Organization', 'Company', 'PoliticalParty', |
| 'GovernmentAgency', 'EducationalInstitution', 'Newspaper', |
| 'Place', 'Location', 'PopulatedPlace', 'Country', 'City', |
| 'Region', 'AdministrativeRegion', 'Continent', 'Agent' |
| ] |
|
|
| |
| headline_content = str(news_row.get('headline', '')).lower() |
| description_content = str(news_row.get('description', '')).lower() |
| full_context = f"{headline_content} {description_content}" |
|
|
| filtered_results = [] |
|
|
| for entity in entities_list: |
| surface_form = entity.get('text', '') |
| entity_types = entity.get('types', []) |
| surface_lower = surface_form.lower() |
|
|
| |
| is_multi_word = ' ' in surface_form |
|
|
| |
| has_valid_type = any(v_type in t for t in entity_types for v_type in VALID_TYPES) |
|
|
| |
| is_in_context = f" {surface_lower} " in f" {full_context} " and not entity_types |
|
|
| |
| is_not_stopword = surface_lower not in ENTITY_STOPWORDS |
|
|
| |
| if (is_multi_word or has_valid_type or is_in_context) and is_not_stopword: |
| filtered_results.append(entity) |
|
|
| return filtered_results |
|
|
| def verificar_integridad_spans(texto_original, datos_anotacion): |
| """ |
| Comprueba la precisión de los índices de caracteres (start, end) |
| frente al contenido textual extraído por el modelo de lenguaje. |
| |
| Parámetros: |
| texto_original (str): El cuerpo de la noticia sin procesar. |
| datos_anotacion (dict): Diccionario con la estructura 5W1H y sus respectivos índices. |
| """ |
| total_registros = 0 |
| coincidencias_exactas = 0 |
| discrepancias_detectadas = 0 |
|
|
| |
| for categoria, lista_spans in datos_anotacion.items(): |
| |
| if not isinstance(lista_spans, list): |
| continue |
| |
| for i, info_span in enumerate(lista_spans): |
| |
| if info_span.get("start") == -1: |
| continue |
|
|
| total_registros += 1 |
| inicio = info_span.get("start") |
| fin = info_span.get("end") |
| texto_esperado = info_span.get("span") |
| |
| |
| texto_real = texto_original[inicio:fin] |
|
|
| |
| if texto_real == texto_esperado: |
| coincidencias_exactas += 1 |
| else: |
| discrepancias_detectadas += 1 |
| print(f"[ERROR DE INTEGRIDAD] Categoría: {categoria}, Índice: {i}") |
| print(f" Contenido esperado: '{texto_esperado}'") |
| print(f" Contenido obtenido: '{texto_real}'") |
|
|
| |
| print(f"\nINFORME DE AUDITORÍA DE SPANS") |
| print("-" * 35) |
| print(f"Total de registros analizados: {total_registros}") |
| print(f"Coincidencias exitosas: {coincidencias_exactas}") |
| print(f"Discrepancias identificadas: {discrepancias_detectadas}") |
| print("-" * 35) |
|
|
| if discrepancias_detectadas == 0 and total_registros > 0: |
| print("La validación ha finalizado satisfactoriamente: todos los índices son íntegros.") |