Datasets:
File size: 3,684 Bytes
77fb120 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 | """
Módulo de análisis cuantitativo de eventos extraídos.
Proporciona funciones para estimar la dimensión del grafo
antes de aplicar filtros de calidad.
"""
import pandas as pd
import json
from tqdm import tqdm
from typing import Dict
def compute_raw_statistics(df: pd.DataFrame, column_name: str = 'events_5w1h') -> Dict[str, int]:
"""
Calcula estadísticas descriptivas sobre los eventos extraídos antes de aplicar filtros.
Permite estimar la dimensión del grafo bruto.
"""
stats = {
"total_documentos": len(df),
"total_eventos": 0,
"total_menciones_entidades": 0,
"total_menciones_lugares": 0,
"total_menciones_fechas": 0,
"total_relaciones_potenciales": 0,
"uris_unicas_count": 0
}
uris_unicas = set()
print(f"Iniciando análisis cuantitativo sobre {len(df)} documentos...")
for _, row in tqdm(df.iterrows(), total=len(df), desc="Analizando eventos"):
try:
cadena_json = row.get(column_name, '[]')
if not isinstance(cadena_json, str):
continue
lista_eventos = json.loads(cadena_json)
stats["total_eventos"] += len(lista_eventos)
for evento in lista_eventos:
# Relación implícita: Evento -> Documento
stats["total_relaciones_potenciales"] += 1
# Análisis de participantes (Who)
for item in evento.get('who', []):
if item.get('start') != -1:
stats["total_menciones_entidades"] += 1
stats["total_relaciones_potenciales"] += 1
if item.get('uri'):
uris_unicas.add(item['uri'])
# Análisis de lugares (Where)
for item in evento.get('where', []):
if item.get('start') != -1:
stats["total_menciones_lugares"] += 1
stats["total_relaciones_potenciales"] += 1
# Análisis de fechas (When)
for item in evento.get('when', []):
if item.get('start') != -1:
stats["total_menciones_fechas"] += 1
stats["total_relaciones_potenciales"] += 1
# Análisis de objetos (What - si contienen entidades con URI)
for item in evento.get('what', []):
if item.get('start') != -1 and item.get('uri'):
stats["total_menciones_entidades"] += 1
stats["total_relaciones_potenciales"] += 1
uris_unicas.add(item['uri'])
except json.JSONDecodeError:
continue
except Exception:
continue
stats["uris_unicas_count"] = len(uris_unicas)
return stats
def print_stats_report(stats: Dict[str, int]):
"""Imprime un informe formateado con los resultados del análisis."""
print("\n" + "=" * 50)
print("ESTIMACIÓN DIMENSIONAL (DATOS BRUTOS)")
print("=" * 50)
print(f"Documentos Procesados: {stats['total_documentos']:,}")
print(f"Eventos Detectados: {stats['total_eventos']:,}")
print("-" * 50)
print(f"Menciones a Entidades: {stats['total_menciones_entidades']:,}")
print(f"Menciones a Lugares: {stats['total_menciones_lugares']:,}")
print(f"Menciones a Fechas: {stats['total_menciones_fechas']:,}")
print("-" * 50)
print(f"Total Relaciones Estimadas: {stats['total_relaciones_potenciales']:,}")
print(f"URIs Únicas Identificadas: {stats['uris_unicas_count']:,}")
print("=" * 50)
|