Datasets:
Tasks:
Feature Extraction
Formats:
parquet
Languages:
Multiple languages
Size:
100K - 1M
ArXiv:
License:
| """Verify concept-analysis trajectory configs are reproducible from HF. | |
| Downloads all inputs directly from HuggingFace, reruns the build logic for | |
| concept_verse_edge_sp and concept_trajectory_sp, then compares freshly-built | |
| outputs against the published NuBerea/concept-analysis parquets. | |
| Exits 0 if everything matches, 1 if any check fails. | |
| Note: Only the trajectory (_sp) configs are HF-reproducible from first principles. | |
| community_candidate, community_membership, concept_centroids, and concept_drift | |
| are outputs of other pipelines (concept-graph BERTopic, drift analysis) and are | |
| not independently verified here. | |
| """ | |
| from __future__ import annotations | |
| import re | |
| import sys | |
| import tempfile | |
| from collections import defaultdict | |
| from pathlib import Path | |
| import numpy as np | |
| import pandas as pd | |
| from huggingface_hub import hf_hub_download | |
| def dl(repo_id: str, config: str, tmp: Path) -> pd.DataFrame: | |
| fname = f"data/{config}/train-00000-of-00001.parquet" | |
| print(f" Downloading {repo_id}/{config} ...") | |
| path = hf_hub_download( | |
| repo_id=repo_id, | |
| filename=fname, | |
| repo_type="dataset", | |
| local_dir=str(tmp / repo_id.replace("/", "__")), | |
| ) | |
| df = pd.read_parquet(path) | |
| print(f" {len(df):,} rows, cols: {list(df.columns)}") | |
| return df | |
| def parse_osis(ref: str): | |
| if " " in ref and ":" in ref: | |
| book, cv = ref.split(" ", 1) | |
| ch_s, v_s = cv.split(":") | |
| else: | |
| parts = ref.split(".") | |
| book = parts[0]; ch_s = parts[1]; v_s = parts[2] | |
| ch = int(ch_s) | |
| m = re.match(r"^(\d+)([a-zA-Z]?)$", v_s) | |
| if not m: | |
| raise ValueError(f"Cannot parse verse '{v_s}' in ref '{ref}'") | |
| return book, ch, (int(m.group(1)), m.group(2)) | |
| def group_by_book(df: pd.DataFrame) -> dict: | |
| by_book: dict = defaultdict(list) | |
| for osis_ref, emb in zip(df["osis_ref"], df["embedding"]): | |
| book, ch, v_tup = parse_osis(osis_ref) | |
| by_book[book].append((ch, v_tup, osis_ref, np.array(emb, dtype=np.float32))) | |
| for book in by_book: | |
| by_book[book].sort(key=lambda x: (x[0], x[1])) | |
| return by_book | |
| def get_verses_in_range(by_book: dict, start_ref: str, end_ref: str) -> list: | |
| start_book, start_ch, start_v = parse_osis(start_ref) | |
| end_book, end_ch, end_v = parse_osis(end_ref) | |
| assert start_book == end_book | |
| result = [] | |
| for ch, v_tup, osis_ref, emb in by_book.get(start_book, []): | |
| if (start_ch, start_v) <= (ch, v_tup) <= (end_ch, end_v): | |
| result.append((osis_ref, emb)) | |
| return result | |
| def rebuild(cse: pd.DataFrame, sn: pd.DataFrame, cn: pd.DataFrame, | |
| lxx: pd.DataFrame, nt: pd.DataFrame, vg: pd.DataFrame): | |
| MODEL_ID = "bowphs/SPhilBerta" | |
| pericopes = sn[sn["span_grain"] == "pericope"][ | |
| ["span_id", "corpus_id", "osis_start", "osis_end"] | |
| ].copy() | |
| edges = cse[["src", "dst", "weight"]].merge( | |
| pericopes, left_on="dst", right_on="span_id", how="inner" | |
| ) | |
| concept_labels = cn.set_index("concept_id")["label"].to_dict() | |
| print(f" {len(edges)} concept-pericope edges ({edges['src'].nunique()} concepts)") | |
| lxx_by_book = group_by_book(lxx) | |
| nt_by_book = group_by_book(nt) | |
| vg_ot_by_book = group_by_book(vg[vg["stratum"] == "vg_ot"]) | |
| vg_nt_by_book = group_by_book(vg[vg["stratum"] == "vg_nt"]) | |
| records, miss = [], {"lxx": 0, "nt": 0, "vg": 0} | |
| for _, edge in edges.iterrows(): | |
| cid = edge["src"] | |
| label = concept_labels.get(cid, "") | |
| is_ot = edge["corpus_id"] == "ot" | |
| greek_bb = lxx_by_book if is_ot else nt_by_book | |
| greek_st = "lxx" if is_ot else "nt" | |
| for ref, emb in get_verses_in_range(greek_bb, edge["osis_start"], edge["osis_end"]) or (miss.__setitem__(greek_st, miss[greek_st]+1), []): | |
| records.append({"concept_id": cid, "concept_label": label, | |
| "osis_ref": ref, "stratum": greek_st, | |
| "edge_weight": float(edge["weight"]), | |
| "embedding": emb.tolist()}) | |
| for ref, emb in get_verses_in_range(vg_ot_by_book if is_ot else vg_nt_by_book, | |
| edge["osis_start"], edge["osis_end"]) or (miss.__setitem__("vg", miss["vg"]+1), []): | |
| records.append({"concept_id": cid, "concept_label": label, | |
| "osis_ref": ref, "stratum": "vg", | |
| "edge_weight": float(edge["weight"]), | |
| "embedding": emb.tolist()}) | |
| cve = pd.DataFrame(records) | |
| cve["model_id"] = MODEL_ID | |
| print(f" concept_verse_edge_sp: {len(cve):,} rows misses={miss}") | |
| traj = [] | |
| for (cid, stratum), grp in cve.groupby(["concept_id", "stratum"]): | |
| mats = np.stack([np.array(e, dtype=np.float32) for e in grp["embedding"]]) | |
| centroid = mats.mean(axis=0) | |
| cnorm = np.linalg.norm(centroid) | |
| cu = centroid / (cnorm + 1e-8) | |
| norms = np.linalg.norm(mats, axis=1, keepdims=True) | |
| units = mats / (norms + 1e-8) | |
| cosine = float((units @ cu).mean()) | |
| traj.append({"concept_id": cid, "concept_label": grp["concept_label"].iloc[0], | |
| "stratum": stratum, "verse_count": len(grp), | |
| "centroid": centroid.tolist(), | |
| "mean_cosine_to_centroid": cosine, | |
| "verse_refs": grp["osis_ref"].tolist(), | |
| "model_id": MODEL_ID}) | |
| traj_df = pd.DataFrame(traj) | |
| print(f" concept_trajectory_sp: {len(traj_df):,} rows") | |
| return cve, traj_df | |
| def check(name: str, rebuilt: pd.DataFrame, published: pd.DataFrame) -> list[str]: | |
| errors = [] | |
| if len(rebuilt) != len(published): | |
| errors.append(f"{name}: row count {len(rebuilt)} vs published {len(published)}") | |
| else: | |
| print(f" {name}: rows match ({len(rebuilt):,})") | |
| rb_cols, pb_cols = set(rebuilt.columns), set(published.columns) | |
| if rb_cols != pb_cols: | |
| errors.append(f"{name}: columns differ — extra={rb_cols-pb_cols} missing={pb_cols-rb_cols}") | |
| else: | |
| print(f" {name}: columns match") | |
| return errors | |
| def check_drift_stats(traj: pd.DataFrame, label: str) -> None: | |
| lxx_t = traj[traj["stratum"] == "lxx"].set_index("concept_id") | |
| nt_t = traj[traj["stratum"] == "nt"].set_index("concept_id") | |
| vg_t = traj[traj["stratum"] == "vg"].set_index("concept_id") | |
| for a_label, a_t, b_label, b_t in [("LXX", lxx_t, "VG", vg_t), ("NT", nt_t, "VG", vg_t)]: | |
| common = a_t.index.intersection(b_t.index) | |
| sims = [ | |
| float(np.dot( | |
| np.array(a_t.loc[cid, "centroid"], dtype=np.float32), | |
| np.array(b_t.loc[cid, "centroid"], dtype=np.float32), | |
| ) / ( | |
| np.linalg.norm(np.array(a_t.loc[cid, "centroid"], dtype=np.float32)) * | |
| np.linalg.norm(np.array(b_t.loc[cid, "centroid"], dtype=np.float32)) + 1e-8 | |
| )) | |
| for cid in common | |
| ] | |
| print(f" [{label}] {a_label} vs {b_label} ({len(common)} concepts): " | |
| f"mean={np.mean(sims):.4f} min={np.min(sims):.4f} max={np.max(sims):.4f}") | |
| def main() -> int: | |
| errors: list[str] = [] | |
| with tempfile.TemporaryDirectory() as tmp_str: | |
| tmp = Path(tmp_str) | |
| print("\n=== Downloading concept-graph inputs ===") | |
| cse = dl("NuBerea/concept-graph", "concept_span_edge", tmp) | |
| sn = dl("NuBerea/concept-graph", "span_node", tmp) | |
| cn = dl("NuBerea/concept-graph", "concept_node", tmp) | |
| print("\n=== Downloading greek-embeddings-primitives (_sp configs) ===") | |
| lxx = dl("NuBerea/greek-embeddings-primitives", "lxx_verse_embeddings_sp", tmp) | |
| nt = dl("NuBerea/greek-embeddings-primitives", "nt_verse_embeddings_sp", tmp) | |
| vg = dl("NuBerea/greek-embeddings-primitives", "vulgate_verse_embeddings", tmp) | |
| print("\n=== Downloading published concept-analysis outputs ===") | |
| pub_cve = dl("NuBerea/concept-analysis", "concept_verse_edge_sp", tmp) | |
| pub_traj = dl("NuBerea/concept-analysis", "concept_trajectory_sp", tmp) | |
| print("\n=== Rebuilding from HF inputs ===") | |
| rb_cve, rb_traj = rebuild(cse, sn, cn, lxx, nt, vg) | |
| print("\n=== Comparing ===") | |
| errors += check("concept_verse_edge_sp", rb_cve, pub_cve) | |
| errors += check("concept_trajectory_sp", rb_traj, pub_traj) | |
| print("\n=== Drift stats (rebuilt) ===") | |
| check_drift_stats(rb_traj, "rebuilt") | |
| print("\n=== Drift stats (published) ===") | |
| check_drift_stats(pub_traj, "published") | |
| if errors: | |
| print("\nFAIL:") | |
| for e in errors: | |
| print(" ", e) | |
| return 1 | |
| print("\nPASS — HF-native rebuild matches published outputs.") | |
| return 0 | |
| if __name__ == "__main__": | |
| sys.exit(main()) | |