Download scripts/auditar.py from antonn-dromundo/DignityAI-Validacion: direct link, hf CLI and curl.
- Browser
- Download file 4.85 kB
-
https://huggingface.co/datasets/antonn-dromundo/DignityAI-Validacion/resolve/main/scripts/auditar.py
- Command line
-
hf download hf://datasets/antonn-dromundo/DignityAI-Validacion/scripts/auditar.py
-
curl -L -o auditar.py https://huggingface.co/datasets/antonn-dromundo/DignityAI-Validacion/resolve/main/scripts/auditar.py
4.85 kB
| """Auditoría y versión limpia (v1.1) de MachismoDetect y SinOdio-LATAM, con el mismo método que Racismo/Clasismo.""" | |
| import glob, json, os, re, unicodedata | |
| import pandas as pd | |
| from sklearn.feature_extraction.text import TfidfVectorizer | |
| from sklearn.linear_model import LogisticRegression | |
| from sklearn.metrics import f1_score | |
| from sklearn.model_selection import GroupShuffleSplit | |
| SEED = 42 | |
| ABBREV = {"xq": "porque", "pq": "porque", "xk": "porque", "pk": "porque", "q": "que", "ke": "que", "k": "que", "pa": "para", | |
| "tb": "tambien", "tmb": "tambien", "toy": "estoy", "vdd": "verdad", "td": "todo", "nd": "nada", "grax": "gracias"} | |
| LAUGHS = {"jaja", "jajaja", "jeje", "lol", "jajaj", "xd", "v"} | |
| def skeleton(t): | |
| t = unicodedata.normalize("NFKD", str(t).lower()) | |
| t = "".join(c for c in t if not unicodedata.combining(c)) | |
| t = re.sub(r"[^a-zñ0-9 ]+", " ", t); t = re.sub(r"(.)\1{1,}", r"\1", t) | |
| return " ".join(w for w in (ABBREV.get(w, w) for w in t.split()) if w not in LAUGHS) | |
| def splits_of(prefix): | |
| return {os.path.basename(f).split("__")[1].replace(".parquet", ""): pd.read_parquet(f) for f in sorted(glob.glob(f"data/{prefix}__*.parquet"))} | |
| def to_long(name, parts): | |
| out = [] | |
| for sp, d in parts.items(): | |
| if name == "machismodetect": | |
| meta = d[["nivel", "subcategoria", "pais", "contexto"]] | |
| out.append(pd.concat([meta.assign(texto=d.texto_machista, etiqueta=1), meta.assign(texto=d.texto_inclusivo, etiqueta=0)]).assign(split_original=sp)) | |
| else: | |
| out.append(d.rename(columns={"text": "texto", "label": "etiqueta", "country": "pais", "scenario": "escenario"}).assign(split_original=sp)) | |
| df = pd.concat(out, ignore_index=True) | |
| df["texto"] = df.texto.astype(str).str.strip() | |
| df["esqueleto"] = df.texto.map(skeleton) | |
| return df | |
| def baseline(tr, te, col="etiqueta"): | |
| v = TfidfVectorizer(ngram_range=(1, 2), min_df=2, sublinear_tf=True) | |
| m = LogisticRegression(max_iter=3000, class_weight="balanced").fit(v.fit_transform(tr.texto), tr[col]) | |
| return round(float(f1_score(te[col], m.predict(v.transform(te.texto)), average="macro")), 3) | |
| def audit(name, group_col): | |
| parts = splits_of(name) | |
| df = to_long(name, parts) | |
| rep = {"dataset": name, "filas_originales_por_split": {k: len(v) for k, v in parts.items()}, | |
| "textos_formato_largo": len(df), "por_etiqueta_original": df.etiqueta.value_counts().to_dict()} | |
| # fuga en splits originales | |
| tr0, te0 = df[df.split_original == "train"], df[df.split_original == "test"] | |
| rep["fuga_original_test_en_train_exacta_pct"] = round(100 * te0.texto.isin(set(tr0.texto)).mean(), 1) | |
| rep["fuga_original_test_en_train_esqueleto_pct"] = round(100 * te0.esqueleto.isin(set(tr0.esqueleto)).mean(), 1) | |
| rep["baseline_split_original_f1"] = baseline(tr0, te0) | |
| # limpieza | |
| exact = df.drop_duplicates(["texto", "etiqueta"]) | |
| clean = exact.drop_duplicates(["esqueleto", "etiqueta"]) | |
| conf = clean.groupby("esqueleto").etiqueta.nunique(); ck = set(conf[conf > 1].index) | |
| clean = clean[~clean.esqueleto.isin(ck)].reset_index(drop=True) | |
| rep.update({"tras_duplicados_exactos": len(exact), "tras_casi_duplicados": len(clean), | |
| "esqueletos_con_etiqueta_contradictoria": len(ck), "por_etiqueta_v1_1": clean.etiqueta.value_counts().to_dict(), | |
| "unicos_por_etiqueta_pct_conservado": {int(k): round(100 * clean.etiqueta.eq(k).sum() / df.etiqueta.eq(k).sum(), 1) for k in [0, 1]}}) | |
| g1 = GroupShuffleSplit(1, test_size=0.3, random_state=SEED); a, b = next(g1.split(clean, groups=clean.esqueleto)) | |
| rest = clean.iloc[b]; g2 = GroupShuffleSplit(1, test_size=0.5, random_state=SEED); c, d = next(g2.split(rest, groups=rest.esqueleto)) | |
| sp = {"train": clean.iloc[a], "validation": rest.iloc[c], "test": rest.iloc[d]} | |
| rep["splits_v1_1"] = {k: len(v) for k, v in sp.items()} | |
| rep["baseline_split_v1_1_f1"] = baseline(sp["train"], sp["test"]) | |
| gs = GroupShuffleSplit(1, test_size=0.25, random_state=SEED); x, y = next(gs.split(clean, groups=clean[group_col])) | |
| rep[f"baseline_{group_col}_no_vistas_f1"] = baseline(clean.iloc[x], clean.iloc[y]) | |
| rep["longitud_mediana"] = clean.groupby("etiqueta").texto.apply(lambda s: int(s.str.len().median())).to_dict() | |
| os.makedirs(f"v11/{name}", exist_ok=True) | |
| cols = [c for c in clean.columns if c not in ("esqueleto", "split_original")] | |
| for k, v in sp.items(): | |
| v[cols].to_csv(f"v11/{name}/{k}.csv", index=False) | |
| clean[cols].to_parquet(f"v11/{name}/completo.parquet", index=False) | |
| json.dump(rep, open(f"v11/{name}/reporte_v1_1.json", "w"), ensure_ascii=False, indent=2, default=int) | |
| print(json.dumps(rep, ensure_ascii=False, default=int)) | |
| if __name__ == "__main__": | |
| audit("machismodetect", "subcategoria") | |
| audit("sinodio_latam", "escenario") | |