Datasets:
File size: 7,794 Bytes
248821b 2575b12 248821b | 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 | #!/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 causalatee.data.constants import ClassLabel, Relation, Task
from causalatee.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"</{tag}>" + 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)")
|