current state
Browse filesFiles changed (12)
- .gitattributesAdded+59
- .gitignoreAdded+3
- causal-candidate-extraction/dev.parquetAdded+3
- causal-candidate-extraction/test.parquetAdded+3
- causal-candidate-extraction/train.parquetAdded+3
- causality-detection/dev.parquetAdded+3
- causality-detection/test.parquetAdded+3
- causality-detection/train.parquetAdded+3
- causality-identification/dev.parquetAdded+3
- causality-identification/test.parquetAdded+3
- causality-identification/train.parquetAdded+3
- conversion_script.py+275-19
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859*.7z filter=lfs diff=lfs merge=lfs -text*.arrow filter=lfs diff=lfs merge=lfs -text*.bin filter=lfs diff=lfs merge=lfs -text*.bz2 filter=lfs diff=lfs merge=lfs -text*.ckpt filter=lfs diff=lfs merge=lfs -text*.ftz filter=lfs diff=lfs merge=lfs -text*.gz filter=lfs diff=lfs merge=lfs -text*.h5 filter=lfs diff=lfs merge=lfs -text*.joblib filter=lfs diff=lfs merge=lfs -text*.lfs.* filter=lfs diff=lfs merge=lfs -text*.lz4 filter=lfs diff=lfs merge=lfs -text*.mds filter=lfs diff=lfs merge=lfs -text*.mlmodel filter=lfs diff=lfs merge=lfs -text*.model filter=lfs diff=lfs merge=lfs -text*.msgpack filter=lfs diff=lfs merge=lfs -text*.npy filter=lfs diff=lfs merge=lfs -text*.npz filter=lfs diff=lfs merge=lfs -text*.onnx filter=lfs diff=lfs merge=lfs -text*.ot filter=lfs diff=lfs merge=lfs -text*.parquet filter=lfs diff=lfs merge=lfs -text*.pb filter=lfs diff=lfs merge=lfs -text*.pickle filter=lfs diff=lfs merge=lfs -text*.pkl filter=lfs diff=lfs merge=lfs -text*.pt filter=lfs diff=lfs merge=lfs -text*.pth filter=lfs diff=lfs merge=lfs -text*.rar filter=lfs diff=lfs merge=lfs -text*.safetensors filter=lfs diff=lfs merge=lfs -textsaved_model/**/* filter=lfs diff=lfs merge=lfs -text*.tar.* filter=lfs diff=lfs merge=lfs -text*.tar filter=lfs diff=lfs merge=lfs -text*.tflite filter=lfs diff=lfs merge=lfs -text*.tgz filter=lfs diff=lfs merge=lfs -text*.wasm filter=lfs diff=lfs merge=lfs -text*.xz filter=lfs diff=lfs merge=lfs -text*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text# Audio files - uncompressed*.pcm filter=lfs diff=lfs merge=lfs -text*.sam filter=lfs diff=lfs merge=lfs -text*.raw filter=lfs diff=lfs merge=lfs -text# Audio files - compressed*.aac filter=lfs diff=lfs merge=lfs -text*.flac filter=lfs diff=lfs merge=lfs -text*.mp3 filter=lfs diff=lfs merge=lfs -text*.ogg filter=lfs diff=lfs merge=lfs -text*.wav filter=lfs diff=lfs merge=lfs -text# Image files - uncompressed*.bmp filter=lfs diff=lfs merge=lfs -text*.gif filter=lfs diff=lfs merge=lfs -text*.png filter=lfs diff=lfs merge=lfs -text*.tiff filter=lfs diff=lfs merge=lfs -text# Image files - compressed*.jpg filter=lfs diff=lfs merge=lfs -text*.jpeg filter=lfs diff=lfs merge=lfs -text*.webp filter=lfs diff=lfs merge=lfs -text# Video files - compressed*.mp4 filter=lfs diff=lfs merge=lfs -text*.webm filter=lfs diff=lfs merge=lfs -text123__pycache__/*.pyc.cache/123version https://git-lfs.github.com/spec/v1oid sha256:17b47069d0ea9a6aa3282ee2a5db4ea26c00515ea4eb1c7e8a737cd302ce816bsize 45224123version https://git-lfs.github.com/spec/v1oid sha256:606d2a57366c8deb97472f22b24880d7108f50c976913068f56fede33b91fe4asize 48622123version https://git-lfs.github.com/spec/v1oid sha256:143a2753aa36493f2dd4fd29dd139160dd9b55c9efeb84f46373dc33d66c47ccsize 216013123version https://git-lfs.github.com/spec/v1oid sha256:bb72c72e80a86c27bffef0674bd0b0606b7c68075c3c9a57b51bf67bbf5b0401size 44703123version https://git-lfs.github.com/spec/v1oid sha256:f2be511d213e726c45e0c7fdabbf53cf15e951e298c678418145efa2a06c568dsize 48118123version https://git-lfs.github.com/spec/v1oid sha256:a6210c0dd6c2aa12678db83720095ccd7bad77fcde872089ecfbc1fbbce352fesize 215175123version https://git-lfs.github.com/spec/v1oid sha256:8238c72f58d2cd9f398f0532c25f948c45db79dd617578a24894a0dfb17a7ec4size 46824123version https://git-lfs.github.com/spec/v1oid sha256:9e205a4fd3b9fd15144747a713d95b1bb5538bc7c3c1392e28509fd98603b5a3size 50309123version https://git-lfs.github.com/spec/v1oid sha256:e47c60e4b250675607aa8dd6259be0dca465dded8da4fe1934cf5c57ee81c644size 221070123456456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051528910115354555657585960616263646566676869707172737475767778798081828384858687888990919293949515169697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727818192021222327925262728280281282283284#!/usr/bin/env python3
"""Run this script as ./conversion_script.py to convert the BioCause entries fromthe CREST v2 aggregation file to HF-compatible parquet files."""Run this script as ./conversion_script.py to convert the BioCause datasetDIRECTLY from its original brat-format annotation files, bypassing theCREST aggregation (crest_v2.xlsx). CREST's own copy of BioCause has (a)train only, 0 dev/test rows (a real CREST-source gap, not fixable byadjusting causalatee's split logic), and (b) the sameidx/context character-offset misalignment already found and fixed forCaTeRS, dropping some spans on conversion.
Citation / original source---------------------------Mihaila, C., Ohta, T., Pyysalo, S., & Ananiadou, S. (2013). "BioCause:Annotating and analysing causality in the biomedical domain." BMCBioinformatics, 14, 2. https://doi.org/10.1186/1471-2105-14-2Corpus home: https://www.nactem.ac.uk/biocause/Direct download (verified working, no login): a zip archive athttps://www.nactem.ac.uk/biocause/download-biocause-corpus.php containingone BioCause_corpus/ directory of paired .ann/.txt files (brat standoff),one pair per section of a PMC Open-Access article's Discussion (alsoincludes TIAB/Introduction/Results sections for some articles) -- 198file pairs across 20 unique PMC article ids, verified directly.
Format: brat standoff, built on top of a pre-existing BioNLP-ST 2011Infectious Diseases event/entity layer in the SAME .ann files (Organism,Protein, Positive_regulation, Regulation, Gene_expression, ... -- ignoredhere, we only want the Causality layer). Causal relations are event-style: T<n> Causality <start> <end> <connective text, e.g. "resulting in"> E<n> Causality:T<n> Cause:T<a> Effect:T<b> E<n> Causality:T<n> Effect:T<b> Evidence:T<c> (no Cause -- common)Cause/Effect/Evidence roles always reference a T-line directly (verified:grepped the whole corpus for a role pointing at another E-line -- nonefound), so no recursive event resolution is needed. ~18 T-line spans arediscontinuous (semicolon-joined offset pairs) -- preserved viacausalatee's multi-segment entity schema.
Only 51 of 851 Causality events have an explicit Cause role; the other800 have Effect+Evidence with NO separate cause span at all -- thecausing participant is not marked as its own argument in those cases.Causality-DETECTION uses all 851 (a sentence is causal if it contains ANYCausality event, span or no span). Causal-candidate-extraction andcausality-IDENTIFICATION need an explicit (cause, effect) span pair, sothey only use the 51 Cause+Effect events -- a real, small, and worthdocumenting limitation of this corpus, not an artefact of this script.
No train/dev/test split exists upstream (checked: no filename in thearchive contains train/dev/test) -- CREST's own split was entirelyinvented. This script creates its own deterministic split BY ARTICLE(not by section) so sections of the same PMC article never end up splitacross train/dev/test: 14 articles -> train, 3 -> dev, 3 -> test.
# 1) Install dependencies:# pip install git+https://github.com/TheMrSheldon/causality-toolkit.git# 2) Source file (fetched automatically via pandas):# - https://raw.githubusercontent.com/phosseini/CREST/master/data/crest_v2.xlsxOnly 7 of the 20 articles contain any of the 51 Cause+Effect relations atall (the other 13 have Effect+Evidence-only Causality events, which countfor detection but not identification/extraction -- see below). A firstversion of this split just sorted article ids and sliced [:14]/[14:17]/[17:20] -- deterministic, but blind to where those 51 relations actuallylive: alphabetically, ALL THREE of the last 3 article ids happen to berelation-free, so causality-IDENTIFICATION's test split silently ended upwith 0 usable pairs (found the hard way: the dependency-baseline runnercrashed with "BioCause has no usable identification pairs"). Fixed by`_assign_documents_to_splits`: adeterministic greedy assignment that places the 20 articles (sorted byrelation count descending, ties by id) one at a time into whichever splitis currently furthest below its target relation share (train/dev/test's14/3/3 document-count ratio), so every split ends up with a reasonable,non-zero share of the 51 relations (currently 28/12/11) while wholearticles still never cross a split boundary.
Granularity: each row is a WHOLE SECTION (not a sentence). An earlierversion of this script cut each section into per-sentence rows (spaCyboundaries, one row per sentence), but ~30 of BioCause's 851 Causalityevents have a cause and/or effect span that references an ADJACENTsentence rather than the one their trigger is in (discourse-levelcausality, e.g. "X requires Y... [new sentence] This substitutiondecreases Z") -- verified this really happens by inspecting real output.A per-sentence schema can't represent such an event at all: either drop it(losing ~30 real relations for no reason other than granularity) orre-base it onto the wrong sentence's text (a real bug hit during thatattempt: a marker landing mid-word, "h<e1>istidine"). Keeping the wholesection as one unit sidesteps the tradeoff entirely -- every event's spansare always within the row's text, nothing is dropped or corrupted. Theper-sentence view can still be derived on demand from this whole-sectiondata via causalatee's reusable``causalatee.data.utils.split_identification_to_sentences`` /``split_extraction_to_sentences`` utilities -- built specifically togeneralise the guard this script used to hand-roll."""
import ioimport reimport urllib.requestimport zipfilefrom pathlib import Path
from ctk.data.constants import Taskfrom ctk.data.conversion import CREST2HF, CRESTSourceimport pandas as pd
from causalatee.data.constants import ClassLabel, Relation, Taskfrom causalatee.data.utils import insert_entity_markers, verify_dataset
_ZIP_URL = "https://www.nactem.ac.uk/biocause/download-biocause-corpus.php"_CACHE_DIR = Path(__file__).parent / ".cache"
def _fetch_corpus_dir() -> Path: """Download + extract the BioCause zip once, cached under .cache/.""" corpus_dir = _CACHE_DIR / "BioCause_corpus" if corpus_dir.is_dir() and any(corpus_dir.iterdir()): return corpus_dir _CACHE_DIR.mkdir(parents=True, exist_ok=True) with urllib.request.urlopen(_ZIP_URL) as resp: data = resp.read() with zipfile.ZipFile(io.BytesIO(data)) as zf: zf.extractall(_CACHE_DIR) return corpus_dir
def _parse_ann(ann_text: str) -> tuple[dict[str, list[tuple[int, int]]], dict[str, str], list[dict]]: """Parse one .ann file.
Returns (t_spans: T-line id -> segments, t_types: T-line id -> type, causality_events: list of {"trigger": tid, "cause": tid|None, "effect": tid|None} for every Causality-typed event). """ t_spans: dict[str, list[tuple[int, int]]] = {} t_types: dict[str, str] = {} for line in ann_text.splitlines(): if not line.startswith("T"): continue tid, mid, _ = (line.split("\t", 2) + [""])[:3] etype, offsets_str = mid.split(" ", 1) segments = [tuple(int(x) for x in pair.split()) for pair in offsets_str.split(";")] t_spans[tid] = sorted(segments) t_types[tid] = etype
causality_events = [] for line in ann_text.splitlines(): if not line.startswith("E"): continue _, mid = line.split("\t", 1) roles = mid.strip().split(" ") trigger_role, trigger_tid = roles[0].split(":") if trigger_role != "Causality": continue args = dict(r.split(":") for r in roles[1:] if ":" in r) causality_events.append({ "trigger": trigger_tid, "cause": args.get("Cause"), "effect": args.get("Effect"), }) return t_spans, t_types, causality_events
def _load_sections() -> list[dict]: """One dict per .ann/.txt pair: {"doc_id", "text", "events": [...]}.""" corpus_dir = _fetch_corpus_dir() sections = [] for ann_path in sorted(corpus_dir.glob("*.ann")): txt_path = ann_path.with_suffix(".txt") text = txt_path.read_text(encoding="utf-8") t_spans, _, events = _parse_ann(ann_path.read_text(encoding="utf-8")) doc_id = re.match(r"(PMC\d+)-", ann_path.stem).group(1) resolved = [ { "cause_segments": t_spans[e["cause"]] if e["cause"] else None, "effect_segments": t_spans[e["effect"]] if e["effect"] else None, } for e in events if e["effect"] in t_spans and (e["cause"] is None or e["cause"] in t_spans) ] sections.append({"doc_id": doc_id, "text": text, "events": resolved}) return sections
def _load_rows() -> list[dict]: """One row per whole section, cached across the 3 convert_for_* calls.
No sentence segmentation happens here at all -- every event's cause/effect segments are already within the section's own text by construction, so there is nothing to re-base and nothing to drop. """ if hasattr(_load_rows, "_cache"): return _load_rows._cache
rows = [] for section in _load_sections(): segments: dict[str, list[tuple[int, int]]] = {} relations = [] for i, ev in enumerate(section["events"]): effect_id = f"e{2 * i + 1}" segments[effect_id] = ev["effect_segments"] if ev["cause_segments"] is not None: cause_id = f"e{2 * i + 2}" segments[cause_id] = ev["cause_segments"] relations.append({"relationship": Relation.Procausal, "first": cause_id, "second": effect_id}) rows.append({"doc_id": section["doc_id"], "text": section["text"], "relations": relations, "segments": segments})
_load_rows._cache = rows return rows
_SPLIT_DOC_CAPACITY = {"train": 14, "dev": 3, "test": 3}
def _assign_documents_to_splits(rows: list[dict]) -> dict[str, set[str]]: """Deterministic greedy split assignment, balanced by relation count.
Sorts articles by their number of Cause+Effect relations (descending, ties broken by doc id), then assigns each one to whichever split still has capacity and is currently furthest below its target relation share (train/dev/test's document-count ratio) -- see module docstring for why a plain sorted-id slice isn't good enough here. """ doc_relations: dict[str, int] = {} for r in rows: doc_relations[r["doc_id"]] = doc_relations.get(r["doc_id"], 0) + len(r["relations"])
assigned: dict[str, set[str]] = {split: set() for split in _SPLIT_DOC_CAPACITY} rel_totals = {split: 0 for split in _SPLIT_DOC_CAPACITY} order = sorted(doc_relations, key=lambda d: (-doc_relations[d], d)) for doc_id in order: candidates = [s for s, cap in _SPLIT_DOC_CAPACITY.items() if len(assigned[s]) < cap] best = min(candidates, key=lambda s: (rel_totals[s] / _SPLIT_DOC_CAPACITY[s], -_SPLIT_DOC_CAPACITY[s])) assigned[best].add(doc_id) rel_totals[best] += doc_relations[doc_id] return assigned
def _split_by_document(rows: list[dict], split: str) -> list[dict]: wanted = _assign_documents_to_splits(rows)[split] return [r for r in rows if r["doc_id"] in wanted]
def convert_for_causality_detection(split: str) -> None: rows = _split_by_document(_load_rows(), split) df = pd.DataFrame([ { "index": f"biocause_{split}_{i}", "text": r["text"], "label": ClassLabel.Causal if r["relations"] or r["segments"] else ClassLabel.Uncausal, } for i, r in enumerate(rows) ]).set_index("index") for error in verify_dataset(df, Task.CausalityDetection): print(f"WARNING [BioCause {Task.CausalityDetection}/{split}]: {error}") df.to_parquet(f"./causality-detection/{split}.parquet", engine="pyarrow")
def convert_for_causal_candidate_extraction(split: str) -> None: rows = _split_by_document(_load_rows(), split) out = [] for i, r in enumerate(rows): # Only entities that participate in a full Cause+Effect relation have a # usable pair; entities from Effect-only (no Cause) events are dropped # here (extraction needs no relation to exist, but we still restrict to # spans backing an actual relation, matching the other converters' # "only causal_eids" convention). involved = {eid for rel in r["relations"] for eid in (rel["first"], rel["second"])} entity = [[x for seg in r["segments"][eid] for x in seg] for eid in involved] out.append({"index": f"biocause_{split}_{i}", "text": r["text"], "entity": entity}) df = pd.DataFrame(out).set_index("index") for error in verify_dataset(df, Task.CausalCandidateExtraction): print(f"WARNING [BioCause {Task.CausalCandidateExtraction}/{split}]: {error}") df.to_parquet(f"./causal-candidate-extraction/{split}.parquet", engine="pyarrow")
def convert_for_causality_identification(split: str) -> None: rows = _split_by_document(_load_rows(), split) out = [] for i, r in enumerate(rows): marked_text = insert_entity_markers(r["text"], r["segments"]) if r["segments"] else r["text"] out.append({"index": f"biocause_{split}_{i}", "text": marked_text, "relations": r["relations"]}) df = pd.DataFrame(out).set_index("index") for error in verify_dataset(df, Task.CausalityIdentification): print(f"WARNING [BioCause {Task.CausalityIdentification}/{split}]: {error}") df.to_parquet(f"./causality-identification/{split}.parquet", engine="pyarrow")
converter = CREST2HF( "https://raw.githubusercontent.com/phosseini/CREST/master/data/crest_v2.xlsx", Path.cwd(), prefix="biocause", filters={"source": CRESTSource.BioCause},)
for split in ["train", "dev", "test"]: converter.convert(Task.CausalityDetection, split) converter.convert(Task.CausalCandidateExtraction, split) converter.convert(Task.CausalityIdentification, split)if __name__ == "__main__": for split in ["train", "dev", "test"]: convert_for_causality_detection(split) convert_for_causal_candidate_extraction(split) convert_for_causality_identification(split).gitattributesAdded+59
.gitignoreAdded+3
causal-candidate-extraction/dev.parquetAdded+3
causal-candidate-extraction/test.parquetAdded+3
causal-candidate-extraction/train.parquetAdded+3
causality-detection/dev.parquetAdded+3
causality-detection/test.parquetAdded+3
causality-detection/train.parquetAdded+3
causality-identification/dev.parquetAdded+3
causality-identification/test.parquetAdded+3
causality-identification/train.parquetAdded+3
conversion_script.py+275-19