File size: 11,165 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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
"""
Mejora F — Texto CLIP más informativo.

El pipeline original usa los labels c-TF-IDF (4 keywords como
"lince_cría_ejemplares_hábitat") como texto para CLIP. Esto produce
una señal de solo 1.10× sobre baseline aleatorio.

Este módulo proporciona funciones para seleccionar el headline más
representativo de cada micro-evento como texto CLIP, obteniendo
oraciones completas y naturales mejor alineadas con el espacio visual.

Uso típico en Colab:
    from src.multimodal.clip_utils import build_clip_text_inputs, compute_clip_coherence
    text_inputs = build_clip_text_inputs(df_final, clip_model, clip_preprocess)
    df_clip = compute_clip_coherence(df_final, text_inputs, image_embeddings)
"""

from __future__ import annotations

import logging
from typing import Literal, Optional

import numpy as np
import pandas as pd
from sklearn.metrics.pairwise import cosine_similarity

logger = logging.getLogger(__name__)

TextStrategy = Literal['best_headline', 'concat_headlines', 'label_jit']


# ─────────────────────────────────────────────────────────────────────────────
# Selección del texto representativo por micro-evento
# ─────────────────────────────────────────────────────────────────────────────
def _centroid_representative_headline(
    grupo: pd.DataFrame,
    embeddings_matrix: np.ndarray,
) -> str:
    """
    Devuelve el headline del artículo más cercano al centroide semántico
    del micro-evento (mejor representante del grupo).
    """
    idx = grupo.index.tolist()
    if not idx:
        return ''
    embs = embeddings_matrix[idx]
    centroide = embs.mean(axis=0, keepdims=True)
    sims = cosine_similarity(centroide, embs)[0]
    best_local = int(np.argmax(sims))
    best_global = idx[best_local]
    headline = grupo.loc[best_global, 'headline']
    return str(headline) if not pd.isna(headline) else ''


def build_event_texts(
    df_final: pd.DataFrame,
    embeddings_matrix: Optional[np.ndarray] = None,
    strategy: TextStrategy = 'best_headline',
    max_headlines: int = 3,
    event_id_col: str = 'micro_event_id',
    headline_col: str = 'headline',
) -> dict[str, str]:
    """
    Construye un diccionario {micro_event_id → texto} para usar como input de CLIP.

    Estrategias disponibles
    -----------------------
    'best_headline'    : El headline del artículo más cercano al centroide del evento.
                         Requiere embeddings_matrix.
    'concat_headlines' : Concatenación de los max_headlines titulares más largos.
                         No requiere embeddings.
    'label_jit'        : Usa el label c-TF-IDF actual (baseline, para comparación).

    Parámetros
    ----------
    df_final          : DataFrame con columnas micro_event_id y headline.
    embeddings_matrix : Array (N_total, D) de embeddings (solo para 'best_headline').
    strategy          : Estrategia de selección de texto.
    max_headlines     : Número máximo de headlines a concatenar ('concat_headlines').
    event_id_col      : Nombre de la columna de ID de micro-evento.
    headline_col      : Nombre de la columna de titular.

    Retorna
    -------
    dict {event_id: texto}
    """
    texts: dict[str, str] = {}

    for event_id, grupo in df_final.groupby(event_id_col):
        if strategy == 'best_headline':
            if embeddings_matrix is None:
                raise ValueError("'best_headline' requiere embeddings_matrix")
            texto = _centroid_representative_headline(grupo, embeddings_matrix)

        elif strategy == 'concat_headlines':
            headlines = (
                grupo[headline_col]
                .dropna()
                .sort_values(key=lambda s: s.str.len(), ascending=False)
                .head(max_headlines)
                .tolist()
            )
            texto = '. '.join(h.strip().rstrip('.') for h in headlines if h.strip())

        elif strategy == 'label_jit':
            label = grupo['label_jit'].dropna().iloc[0] if 'label_jit' in grupo.columns else ''
            texto = str(label).replace('_', ' ')

        else:
            raise ValueError(f"Estrategia desconocida: {strategy!r}")

        texts[str(event_id)] = texto

    empty = sum(1 for t in texts.values() if not t.strip())
    logger.info(
        f"Textos CLIP construidos ({strategy}): "
        f"{len(texts)} eventos, {empty} vacíos ({empty/max(len(texts),1)*100:.1f}%)"
    )
    return texts


# ─────────────────────────────────────────────────────────────────────────────
# Generación de embeddings de texto CLIP
# ─────────────────────────────────────────────────────────────────────────────
def encode_texts_clip(
    event_texts: dict[str, str],
    clip_model,
    clip_tokenize,
    device: str = 'cuda',
    batch_size: int = 256,
) -> dict[str, np.ndarray]:
    """
    Codifica los textos de cada micro-evento con CLIP y devuelve
    {event_id: embedding L2-normalizado (512,)}.

    Parámetros
    ----------
    event_texts   : Salida de build_event_texts().
    clip_model    : Modelo CLIP (openai/clip).
    clip_tokenize : clip.tokenize.
    device        : 'cuda' o 'cpu'.
    batch_size    : Artículos por batch (CLIP text encoder es rápido).
    """
    import torch

    event_ids = list(event_texts.keys())
    texts     = [event_texts[eid] for eid in event_ids]
    embeddings: dict[str, np.ndarray] = {}

    clip_model.eval()

    with torch.no_grad():
        for i in range(0, len(texts), batch_size):
            batch_ids  = event_ids[i:i + batch_size]
            batch_txts = texts[i:i + batch_size]

            # Truncar a 77 tokens (límite CLIP)
            tokens = clip_tokenize(batch_txts, truncate=True).to(device)
            feats  = clip_model.encode_text(tokens)
            feats  = feats / feats.norm(dim=-1, keepdim=True)  # L2 normalize
            feats  = feats.cpu().numpy().astype(np.float32)

            for eid, vec in zip(batch_ids, feats):
                embeddings[eid] = vec

    logger.info(f"Embeddings de texto CLIP generados: {len(embeddings)} eventos")
    return embeddings


# ─────────────────────────────────────────────────────────────────────────────
# Cómputo de coherencia imagen-texto
# ─────────────────────────────────────────────────────────────────────────────
def compute_clip_coherence(
    df_resumen: pd.DataFrame,
    text_embeddings: dict[str, np.ndarray],
    image_embeddings_by_event: dict[str, np.ndarray],
    event_id_col: str = 'micro_event_id',
) -> pd.DataFrame:
    """
    Calcula la coherencia coseno imagen-texto para cada micro-evento.

    Parámetros
    ----------
    df_resumen               : DataFrame resumen con una fila por micro-evento.
    text_embeddings          : {event_id: text_emb(512,)} de encode_texts_clip().
    image_embeddings_by_event: {event_id: image_emb_mean(512,)} de la Fase 3.
    event_id_col             : Nombre de la columna de ID.

    Retorna
    -------
    df_resumen con columna 'clip_text_coherence_v2' añadida.
    """
    coherences: list[float] = []

    for _, row in df_resumen.iterrows():
        eid = str(row[event_id_col])
        t_emb = text_embeddings.get(eid)
        i_emb = image_embeddings_by_event.get(eid)

        if t_emb is None or i_emb is None:
            coherences.append(float('nan'))
            continue

        t = t_emb.reshape(1, -1)
        im = i_emb.reshape(1, -1)
        coh = float(cosine_similarity(t, im)[0, 0])
        coherences.append(coh)

    df_out = df_resumen.copy()
    df_out['clip_text_coherence'] = coherences

    valid = [c for c in coherences if not np.isnan(c)]
    if valid:
        baseline = np.mean(valid)
        real_m   = np.mean(valid)
        print(f"\nCoherencia CLIP (estrategia mejorada):")
        print(f"  N       : {len(valid)}")
        print(f"  Media   : {real_m:.4f}")
        print(f"  Mediana : {np.median(valid):.4f}")
        print(f"  Std     : {np.std(valid):.4f}")

    return df_out


# ─────────────────────────────────────────────────────────────────────────────
# Comparativa baseline vs improved
# ─────────────────────────────────────────────────────────────────────────────
def compare_coherence_strategies(
    df_resumen: pd.DataFrame,
    text_emb_original: dict[str, np.ndarray],
    text_emb_improved: dict[str, np.ndarray],
    image_embeddings_by_event: dict[str, np.ndarray],
    event_id_col: str = 'micro_event_id',
) -> pd.DataFrame:
    """
    Calcula la coherencia con ambas estrategias (label_jit vs best_headline)
    y muestra una comparativa directa.

    Útil para validar cuánto mejora la señal imagen-texto antes de reemplazar
    el pipeline completo.
    """
    df1 = compute_clip_coherence(df_resumen, text_emb_original, image_embeddings_by_event, event_id_col)
    df2 = compute_clip_coherence(df_resumen, text_emb_improved, image_embeddings_by_event, event_id_col)

    c_orig = df1['clip_text_coherence'].dropna()
    c_impr = df2['clip_text_coherence'].dropna()

    # Baseline aleatorio (permutación)
    rng = np.random.default_rng(42)
    event_ids = list(image_embeddings_by_event.keys())
    img_matrix = np.stack([image_embeddings_by_event[e] for e in event_ids])
    txt_improved = np.stack([text_emb_improved[e] for e in event_ids if e in text_emb_improved])
    if len(txt_improved) == len(img_matrix):
        perm = rng.permutation(len(img_matrix))
        baseline = float(cosine_similarity(txt_improved, img_matrix[perm]).diagonal().mean())
    else:
        baseline = float('nan')

    print("\n" + "=" * 55)
    print("  COMPARATIVA DE ESTRATEGIAS DE TEXTO CLIP")
    print("=" * 55)
    print(f"  Baseline aleatorio (random)  : {baseline:.4f}")
    print(f"  label c-TF-IDF (original)    : {c_orig.mean():.4f}  "
          f"({c_orig.mean()/baseline:.2f}× baseline)")
    print(f"  Best headline (mejorado)     : {c_impr.mean():.4f}  "
          f"({c_impr.mean()/baseline:.2f}× baseline)")
    print("=" * 55)

    return df2