File size: 4,657 Bytes
b6b15da c2fb5ff b6b15da 1d9bdaf c2fb5ff b6b15da c2fb5ff b6b15da c2fb5ff b6b15da 1d9bdaf b6b15da 49fc347 b6b15da 49fc347 c2fb5ff 49fc347 b6b15da 49fc347 1d9bdaf b6b15da c2fb5ff b6b15da 1d9bdaf b6b15da | 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 | #!/usr/bin/env python3
"""
Run this script as ./conversion_script.py to convert the SCITE files to HF-compatible parquet files.
Source data is loaded directly from the upstream repository:
https://github.com/Das-Boot/scite/tree/master/corpus
"""
import re
from typing import Literal
import pandas as pd
from causalatee.data.constants import Task
from causalatee.data.utils import verify_dataset
_BASE_URL = "https://raw.githubusercontent.com/Das-Boot/scite/master/corpus"
Split = Literal["train", "test"]
def _read_xml(split: Split, **kwargs) -> pd.DataFrame:
return pd.read_xml(f"{_BASE_URL}/{split}-corpus.xml", **kwargs)
def convert_for_causality_detection(split: Split) -> None:
df = _read_xml(split)
df["label"] = df["label"].apply(lambda x: 0 if x == "Non-Causal" else 1)
df["text"] = df["sentence"].apply(lambda x: re.sub(r'</?e\d+>', "", x))
df["index"] = df["id"].apply(lambda x: f"scite_{split}_{x}")
df = df.set_index("index")
df = df[["label", "text"]]
for error in verify_dataset(df, Task.CausalityDetection):
print(f"WARNING [SCITE causality detection/{split}]: {error}")
df.to_parquet(f"./causality-detection/{split}.parquet", engine="pyarrow")
def convert_for_causal_candidate_extraction(split: Split) -> None:
def extract_entity_spans(tagged_text: str, relations: list) -> tuple[str, list]:
"""Return (plain_text, [[start, end], ...]) for entities in causal relations."""
causal_eids: set[str] = set()
for rel in relations:
if rel["relationship"] == 1:
causal_eids.add(rel["first"])
causal_eids.add(rel["second"])
# Single pass: track plain-text offset while consuming tags
plain_chars: list[str] = []
open_at: dict[str, int] = {}
spans: list[list[int]] = []
i = 0
while i < len(tagged_text):
m = re.match(r'<(/?)(e\d+)>', tagged_text[i:])
if m:
eid = m.group(2)
if m.group(1) == "": # opening tag
if eid in causal_eids:
open_at[eid] = len(plain_chars)
else: # closing tag
if eid in open_at:
spans.append([open_at.pop(eid), len(plain_chars)])
i += m.end()
else:
plain_chars.append(tagged_text[i])
i += 1
return "".join(plain_chars), spans
df = _read_xml(split, dtype_backend="pyarrow")
# Reuse the relation parsing from convert_for_causality_identification
def map_label(label: str) -> list:
if label == "Non-Causal":
return []
relations = []
for t in label[len("Cause-Effect("):-1].split("),("):
left, right = t.strip("()").split(",")
relations.append({"relationship": 1, "first": left, "second": right})
return relations
df["relations"] = df["label"].apply(map_label)
df[["text", "entity"]] = df.apply(
lambda row: pd.Series(extract_entity_spans(row["sentence"], row["relations"])),
axis=1,
)
df["index"] = df["id"].apply(lambda x: f"scite_{split}_{x}")
df = df[["index", "text", "entity"]].set_index("index")
for error in verify_dataset(df, Task.CausalCandidateExtraction):
print(f"WARNING [SCITE causal candidate extraction/{split}]: {error}")
df.to_parquet(f"./causal-candidate-extraction/{split}.parquet", engine="pyarrow")
def convert_for_causality_identification(split: Split) -> None:
def map_label(label: str):
if label == "Non-Causal":
return []
tmp = list()
for t in label[len("Cause-Effect("):-1].split("),("):
left, right = t.strip('()').split(',')
tmp.append({"relationship": 1, "first": left, "second": right})
return tmp
df = _read_xml(split, dtype_backend="pyarrow")
df["relations"] = df["label"].apply(map_label)
df["text"] = df["sentence"]
df["index"] = df["id"].apply(lambda x: f"scite_{split}_{x}")
df = df.set_index("index")
df = df[["text", "relations"]]
for error in verify_dataset(df, Task.CausalityIdentification):
print(f"WARNING [SCITE causality identification/{split}]: {error}")
df.to_parquet(f"./causality-identification/{split}.parquet", engine="pyarrow")
convert_for_causality_detection("test")
convert_for_causality_detection("train")
convert_for_causal_candidate_extraction("test")
convert_for_causal_candidate_extraction("train")
convert_for_causality_identification("test")
convert_for_causality_identification("train") |