"""Compara LIME, KernelSHAP y anchors sobre 100 ejemplos SST-2.

Requiere torch, transformers, pandas, pyarrow, spacy, lime, shap y anchor-exp.
Uso: python text_lab.py --output results.json [--data validation.parquet] [--limit 100]
Sin --data descarga la validación fijada y verifica su SHA-256.
"""
import argparse, hashlib, io, json, urllib.request
from pathlib import Path
print('Cargando NumPy y pandas',flush=True)
import numpy as np
import pandas as pd
print('Cargando SHAP, spaCy y PyTorch',flush=True)
import shap, spacy, torch
print('Cargando Transformers, LIME y anchors',flush=True)
from transformers import AutoModelForSequenceClassification, AutoTokenizer
from lime.lime_text import LimeTextExplainer
from anchor import anchor_text

MODEL='distilbert/distilbert-base-uncased-finetuned-sst-2-english'
REV='714eb0fa89d2f80546fda750413ed43d93601a13'
DATA_URL='https://huggingface.co/datasets/stanfordnlp/sst2/resolve/8d51e7e4887a4caaa95b3fbebbf53c0490b58bbb/data/validation-00000-of-00001.parquet?download=true'
DATA_SHA='fb00fe008f6828f86ba2beda8415a4cf5da0c884f21c5f238c87131b5aa19529'
parser=argparse.ArgumentParser()
parser.add_argument('--output',required=True); parser.add_argument('--data'); parser.add_argument('--limit',type=int,default=100)
args=parser.parse_args()
raw=Path(args.data).read_bytes() if args.data else urllib.request.urlopen(DATA_URL,timeout=120).read()
assert hashlib.sha256(raw).hexdigest()==DATA_SHA
data=pd.read_parquet(io.BytesIO(raw)); nlp=spacy.blank('en')
cases=[]
for index,row in data.iterrows():
    words=[t.text for t in nlp(row['sentence'])]
    stable=[t.text for t in nlp(' '.join(words))]
    if words==stable and 3<=len(words)<=12:
        cases.append((int(index),int(row['label']),words))
    if len(cases)==args.limit:break
if len(cases)<args.limit: raise RuntimeError('No hay suficientes textos en el rango de longitud')
print('Preparando clasificador para',len(cases),'casos',flush=True)
try:
    tokenizer=AutoTokenizer.from_pretrained(MODEL,revision=REV,local_files_only=True)
    model=AutoModelForSequenceClassification.from_pretrained(MODEL,revision=REV,local_files_only=True)
except OSError:
    tokenizer=AutoTokenizer.from_pretrained(MODEL,revision=REV)
    model=AutoModelForSequenceClassification.from_pretrained(MODEL,revision=REV)
device=torch.device('cuda' if torch.cuda.is_available() else 'cpu')
model.to(device).eval()
print('Clasificador listo en',device,flush=True)
cache={}
def probs(texts):
    texts=list(texts); missing=list(dict.fromkeys(s for s in texts if s not in cache))
    for start in range(0,len(missing),32):
        batch=missing[start:start+32]
        tokens=tokenizer(batch,return_tensors='pt',padding=True,truncation=True,max_length=64).to(device)
        with torch.inference_mode(): out=torch.softmax(model(**tokens).logits,dim=-1).cpu().numpy()
        for text,row in zip(batch,out):cache[text]=row
    return np.asarray([cache[s] for s in texts])

def jaccard(a,b):
    a,b=set(a),set(b)
    return len(a&b)/len(a|b) if a|b else 1.0

records=[]
for k,(index,label,words) in enumerate(cases):
    text=' '.join(words); original=probs([text])[0]; predicted=int(np.argmax(original)); m=len(words)
    lime=LimeTextExplainer(class_names=['negative','positive'],split_expression=r'\s+',bow=False,
                           mask_string='UNK',random_state=1000+k)
    exp=lime.explain_instance(text,probs,labels=(predicted,),num_features=m,num_samples=256)
    lime_top=[int(i) for i,_ in sorted(exp.local_exp[predicted],key=lambda t:-abs(t[1]))[:3]]
    def mask_predict(mask):
        mask=np.atleast_2d(mask)
        texts=[' '.join(word if row[j]>.5 else 'UNK' for j,word in enumerate(words)) for row in mask]
        return probs(texts)[:,predicted]
    np.random.seed(2000+k)
    explain=shap.KernelExplainer(mask_predict,np.zeros((1,m)))
    shap_values=np.asarray(explain.shap_values(np.ones((1,m)),nsamples=128,l1_reg=0,silent=True)).reshape(-1)
    shap_top=np.argsort(-np.abs(shap_values))[:3].astype(int).tolist()
    np.random.seed(3000+k)
    anchors=anchor_text.AnchorText(nlp,['negative','positive'],use_unk_distribution=True,mask_string='UNK')
    anchor=anchors.explain_instance(text,lambda texts:np.argmax(probs(texts),axis=1),
        threshold=.9,delta=.1,tau=.2,batch_size=32,beam_size=1,max_anchor_size=3,min_samples_start=32)
    anchor_ids=[int(i) for i in anchor.exp_map['feature']]
    records.append({'index':index,'label':label,'predicted':predicted,'words':words,
        'lime_top':lime_top,'shap_top':shap_top,'anchor':anchor_ids,
        'lime_shap_jaccard':jaccard(lime_top,shap_top),
        'lime_anchor_jaccard':jaccard(lime_top,anchor_ids),
        'shap_anchor_jaccard':jaccard(shap_top,anchor_ids),
        'anchor_precision':float(anchor.precision()) if anchor_ids else None,
        'lime_local_r2':float(exp.score)})
    print('ejemplo',k+1,'/',len(cases),'índice',index,'palabras',m,flush=True)
    # Guardado parcial recuperable, sin afirmar que una ejecución interrumpida está completa.
    Path(args.output).write_text(json.dumps({'completed':len(records),'records':records},ensure_ascii=False,indent=2),encoding='utf-8')
for key in ('lime_shap_jaccard','lime_anchor_jaccard','shap_anchor_jaccard'):
    print(key,'media',round(float(np.mean([r[key] for r in records])),4),flush=True)
print('exactitud sobre esta selección',round(float(np.mean([r['label']==r['predicted'] for r in records])),4),flush=True)
