#!/usr/bin/env python3 """ Convert PubMedCausal to HF-compatible parquet files, loading data directly from GitHub. PubMedCausal (Adewole et al., 2025; arXiv:2605.28363): 30K paragraph-level rows from PubMed abstracts; 3,945 causal sentences with 6,491 annotated cause-effect pairs. Pairs are typed as Explicit/Implicit and Intra/Inter-sentential. No countercausal labels. Source files (fetched at runtime — no local download needed): Detection: detection_train.json / detection_test.json {"s/n": int, "sentence": str, "label": 0|1} Extraction: extraction_combined/train.json / extraction_combined/test.json {"s/n": int, "sentence": str, "pairs": [{"cause", "effect", "sententiality", "causality"}], "num_pairs": int} Note: inter-sentential pairs (sententiality="Inter") are included in detection and extraction but skipped for identification, as cause and effect may not both appear in the single sentence string. """ import json import urllib.request from pathlib import Path import pandas as pd from ctk.data.constants import ClassLabel, Relation, Task from ctk.data.conversion._converter import FormatConverter _BASE = "https://raw.githubusercontent.com/josiahpaul07/PubMedCausal_Exp/main/PUBMEDCAUSAL/data/prepared" _DETECTION_URLS = { "train": f"{_BASE}/detection_train.json", "test": f"{_BASE}/detection_test.json", } _EXTRACTION_URLS = { "train": f"{_BASE}/extraction_combined/train.json", "test": f"{_BASE}/extraction_combined/test.json", } def _fetch(url: str) -> list[dict]: with urllib.request.urlopen(url) as resp: return json.load(resp) def _find_span(text: str, span: str) -> tuple[int, int] | None: """Return (start, end) of span in text; case-insensitive fallback.""" idx = text.find(span) if idx == -1: idx = text.lower().find(span.lower()) return (idx, idx + len(span)) if idx != -1 else None class PubMedCausal2HF(FormatConverter): def __init__(self, target: Path) -> None: super().__init__(target) def _convert(self, task: str, split: str) -> pd.DataFrame: dispatch = { Task.CausalityDetection: self._convert_detection, Task.CausalCandidateExtraction: self._convert_extraction, Task.CausalityIdentification: self._convert_identification, } return dispatch[task](split) def _convert_detection(self, split: str) -> pd.DataFrame: rows = [ {"index": f"pubmedcausal_{r['s/n']}", "text": r["sentence"], "label": int(r["label"])} for r in _fetch(_DETECTION_URLS[split]) ] return pd.DataFrame(rows).set_index("index") def _convert_extraction(self, split: str) -> pd.DataFrame: rows = [] for rec in _fetch(_EXTRACTION_URLS[split]): text = rec["sentence"] seen: set[tuple[int, int]] = set() spans: list[list[int]] = [] for pair in rec.get("pairs", []): for span_text in (pair["cause"], pair["effect"]): offsets = _find_span(text, span_text) if offsets and offsets not in seen: seen.add(offsets) spans.append(list(offsets)) rows.append({"index": f"pubmedcausal_{rec['s/n']}", "text": text, "entity": spans}) return pd.DataFrame(rows).set_index("index") def _convert_identification(self, split: str) -> pd.DataFrame: rows = [] skipped_pairs = 0 for rec in _fetch(_EXTRACTION_URLS[split]): text = rec["sentence"] intra = [p for p in rec.get("pairs", []) if p.get("sententiality") == "Intra"] if not intra: continue # Only keep pairs where both spans can be located verbatim in the sentence. # PubMedCausal sometimes records canonical/normalised span text that differs # from the surface form (e.g. "precludes X" vs "precluding X"), making exact # insertion of entity markers impossible. Such pairs are dropped here and # counted in the summary printed after conversion. resolvable = [] for pair in intra: cause_loc = _find_span(text, pair["cause"]) effect_loc = _find_span(text, pair["effect"]) if cause_loc is None or effect_loc is None: skipped_pairs += 1 print( f" [skip] s/n={rec['s/n']}: span not found in sentence\n" f" cause: {pair['cause']!r}\n" f" effect: {pair['effect']!r}\n" f" sentence: {text!r}", flush=True, ) continue resolvable.append((pair, cause_loc, effect_loc)) if not resolvable: continue # Assign stable entity IDs to the resolved spans only. span_to_id: dict[str, int] = {} for pair, _, __ in resolvable: for span_text in (pair["cause"], pair["effect"]): if span_text not in span_to_id: span_to_id[span_text] = len(span_to_id) + 1 relations = [ { "relationship": int(Relation.Procausal), "first": f"e{span_to_id[p['cause']]}", "second": f"e{span_to_id[p['effect']]}", } for p, _, __ in resolvable ] located: list[tuple[int, int, str]] = [ (*offsets, f"e{span_to_id[span_text]}") for span_text, offsets in ( (p["cause"], cause_loc) for p, cause_loc, _ in resolvable ) ] + [ (*offsets, f"e{span_to_id[span_text]}") for span_text, offsets in ( (p["effect"], effect_loc) for p, _, effect_loc in resolvable ) ] # Deduplicate (same span may appear in multiple pairs). seen_locs: set[tuple[int, int]] = set() unique_located = [] for start, end, tag in located: if (start, end) not in seen_locs: seen_locs.add((start, end)) unique_located.append((start, end, tag)) marked = text for start, end, tag in sorted(unique_located, key=lambda x: x[0], reverse=True): marked = marked[:start] + f"<{tag}>" + marked[start:end] + f"" + marked[end:] rows.append({"index": f"pubmedcausal_{rec['s/n']}", "text": marked, "relations": relations}) if skipped_pairs: print(f" [{split}] skipped {skipped_pairs} pair(s) where a span could not be located in the sentence.") if not rows: return pd.DataFrame(columns=["text", "relations"]).rename_axis("index") return pd.DataFrame(rows).set_index("index") if __name__ == "__main__": here = Path(__file__).parent converter = PubMedCausal2HF(here) for split in ("train", "test"): print(f"Converting {split}...") converter.convert(Task.CausalityDetection, split) converter.convert(Task.CausalCandidateExtraction, split) converter.convert(Task.CausalityIdentification, split) print("\nDone. Parquet files written to:") for task in ("causality-detection", "causal-candidate-extraction", "causality-identification"): for split in ("train", "test"): p = here / task / f"{split}.parquet" if p.exists(): df = pd.read_parquet(p) print(f" {p.relative_to(here)} ({len(df):,} rows)")