| """ |
| Módulo para el enlazado de entidades (Entity Linking) con DBpedia Spotlight. |
| Incluye lógica de reintentos y manejo de errores para alta disponibilidad. |
| """ |
|
|
| import requests |
| import pandas as pd |
| import logging |
| import time |
| from tqdm.auto import tqdm |
|
|
| logger = logging.getLogger(__name__) |
|
|
| class DBpediaLinker: |
| def __init__(self, language='es'): |
| self.api_url = f"https://api.dbpedia-spotlight.org/{language}/annotate" |
| self.headers = {"Accept": "application/json"} |
|
|
| def annotate_text(self, text: str, confidence: float = 0.5, max_retries: int = 3) -> list: |
| """ |
| Extrae entidades con lógica de reintentos y pausa creciente. |
| """ |
| if not isinstance(text, str) or len(text.strip()) < 10: |
| return [] |
|
|
| data = {"text": text, "confidence": confidence} |
| |
| for attempt in range(max_retries): |
| try: |
| |
| response = requests.post(self.api_url, data=data, headers=self.headers, timeout=20) |
| response.raise_for_status() |
| response_data = response.json() |
|
|
| extracted_entities = [] |
| if 'Resources' in response_data: |
| for resource in response_data['Resources']: |
| extracted_entities.append({ |
| 'text': resource.get('@surfaceForm'), |
| 'uri': resource.get('@URI'), |
| |
| 'types': resource.get('@types', '').split(',') if resource.get('@types') else [] |
| }) |
| return extracted_entities |
|
|
| except (requests.exceptions.RequestException, requests.exceptions.Timeout) as e: |
| wait_time = 2 * (attempt + 1) |
| logger.warning(f"Intento {attempt + 1} fallido. Reintentando en {wait_time}s... Error: {e}") |
| time.sleep(wait_time) |
| |
| except Exception as e: |
| logger.error(f"Error inesperado en DBpedia: {e}") |
| break |
| |
| return [] |
|
|
| def process_dataframe(self, df: pd.DataFrame, column: str, confidence: float = 0.5) -> pd.DataFrame: |
| """ |
| Aplica el enlazado semántico a todo el dataset. |
| """ |
| logger.info(f"Iniciando enlace semántico (DBpedia) con reintentos.") |
| df_result = df.copy() |
| |
| tqdm.pandas(desc="Enlazando con DBpedia") |
| df_result['named_entities_dbpedia'] = df_result[column].progress_apply( |
| lambda x: self.annotate_text(x, confidence=confidence) |
| ) |
| |
| return df_result |