dacy-data / scripts /subsets.py
Kenneth Enevoldsen
Use whole documents with a document-level split (v2.10.0)
2cca161 unverified
Raw History Blame Contribute Delete
8.3 kB
"""Build the subsets from the documents and splits of documents.py.
Every subset uses the same documents and the same split of each document:
- `ddt`: all documents, with the syntax of DDT.
- `dane`: all documents, with the syntax of DDT and the named entities of DaNE.
- `dacoref`: the documents in DaCoref, with coreference clusters.
- `daned`: the documents in DaCoref, with the entity linking annotation (Wikidata
QIDs) from which DaNED was built.
- `default`: all documents, with syntax, named entities and the coreference clusters
of the documents in DaCoref. This is the data used to train DaCy.
The coreference clusters and QIDs are distributed with DaCoref, one per token. They
are read in the documents of DaCoref and moved to the same sentences in the documents
of documents.py. Consecutive tokens with the same QID form a QID span (within a
sentence), and entities whose tokens all have the same QID get it as their knowledge
base id (``kb_id``), as in DaCy 0.2.0.
Inputs ``build/ddt.spacy``, ``build/dane.spacy`` and ``build/documents.json`` (from
ddt.py, dane.py and documents.py). Outputs ``ddt/``, ``dane/``, ``dacoref/``,
``daned/`` and ``default/``.
"""
from __future__ import annotations
import json
import re
import warnings
from collections import defaultdict
import conllu
from spacy.tokens import Doc, Span
from utils import BUILD, ROOT, SPLITS, document_row, log, read_dacoref, read_docbin, write_subset
QID = re.compile(r"Q[0-9]+")
# the sent_id of each sentence is kept in the sent_ids of the document
warnings.filterwarnings("ignore", message=r"\[W101\]")
# a mention or QID span as (sent_id, start, end) within the sentence
SentSpan = tuple[str, int, int]
def coref_clusters(tokens: list[conllu.Token]) -> list[list[tuple[int, int]]]:
"""The coreference clusters of a DaCoref document as token offsets."""
clusters: dict[str, list] = defaultdict(list)
for i, token in enumerate(tokens):
if token["coref_rel"] == "-":
continue
for mention in sorted(token["coref_rel"].split("|"), reverse=True):
if mention.startswith("(") and mention.endswith(")"):
clusters[mention[1:-1]].insert(0, (i, i + 1))
elif mention.startswith("("):
clusters[mention[1:]].append(i)
elif mention.endswith(")"):
cid = mention[:-1]
start = clusters[cid].pop()
clusters[cid].insert(0, (start, i + 1))
return list(clusters.values())
def qid_spans(tokens: list[conllu.Token | None]) -> list[tuple[int, int, str]]:
"""Consecutive tokens with the same QID as (start, end, qid). A None token ends a span."""
spans = []
start, qid = None, None
for i, token in enumerate([*tokens, None]):
token_qid = None if token is None or token["qid"] == "-" else token["qid"]
if token_qid is not None and not QID.fullmatch(token_qid):
# two tokens in DaCoref have malformed QIDs ("S" and "id=81")
log.warning("Skipping malformed QID %r on %r", token_qid, token["form"])
token_qid = None
if qid is not None and token_qid != qid:
spans.append((start, i, qid))
start, qid = None, None
if token_qid is not None and qid is None:
start, qid = i, token_qid
return spans
def read_annotations() -> tuple[dict[str, list[list[SentSpan]]], dict[str, list[tuple[SentSpan, str]]]]:
"""The coreference clusters and QID spans of each DaCoref document, by sentence."""
sentences, _ = read_dacoref()
sentences_of_doc: dict[str, list[conllu.TokenList]] = defaultdict(list)
for sent in sentences:
sentences_of_doc[sent[0]["doc_id"]].append(sent)
clusters, qids = {}, {}
for doc_id, sents in sentences_of_doc.items():
tokens = [t for sent in sents for t in sent]
position = [(sent.metadata["sent_id"], i) for sent in sents for i in range(len(sent))]
def to_sent_span(start: int, end: int) -> SentSpan:
(sent_id, a), (end_sent_id, b) = position[start], position[end - 1]
assert sent_id == end_sent_id, f"span across sentences in {doc_id}"
return sent_id, a, b + 1
clusters[doc_id] = [[to_sent_span(a, b) for a, b in c] for c in coref_clusters(tokens)]
qids[doc_id] = [
((sent.metadata["sent_id"], a, b), qid) for sent in sents for a, b, qid in qid_spans(list(sent))
]
return clusters, qids
def build_doc(document: dict, sentences: dict[str, Doc]) -> tuple[Doc, dict[str, int]]:
"""The document and the start token of each of its sentences."""
parts = [sentences[sent_id] for sent_id in document["sent_ids"]]
doc = Doc.from_docs(parts)
doc._.sent_ids = document["sent_ids"]
doc._.doc_id = document["doc_id"]
doc._.domain = document["domain"]
starts, start = {}, 0
for sent_id, part in zip(document["sent_ids"], parts, strict=True):
starts[sent_id] = start
start += len(part)
return doc, starts
def add_coreference(doc: Doc, starts: dict[str, int], clusters: list[list[SentSpan]]) -> None:
for i, cluster in enumerate(clusters):
spans = [doc[starts[s] + a : starts[s] + b] for s, a, b in cluster]
doc.spans[f"coref_clusters_{i}"] = spans
heads = list({span.root.i for span in spans})
if len(heads) > 1:
doc.spans[f"coref_head_clusters_{i}"] = [doc[h : h + 1] for h in heads]
def add_qids(doc: Doc, starts: dict[str, int], qids: list[tuple[SentSpan, str]]) -> None:
"""Add the QID spans, and set the QID as kb_id of the entities whose tokens all have the same QID."""
doc.spans["qids"] = [Span(doc, starts[s] + a, starts[s] + b, label=qid) for (s, a, b), qid in qids]
token_qid = {i: s.label_ for s in doc.spans["qids"] for i in range(s.start, s.end)}
ents = []
for e in doc.ents:
ent_qids = {token_qid.get(i) for i in range(e.start, e.end)}
kb_id = ent_qids.pop() if len(ent_qids) == 1 and None not in ent_qids else ""
ents.append(Span(doc, e.start, e.end, label=e.label_, kb_id=kb_id))
doc.ents = ents
def ddt_row(doc: Doc) -> dict:
row = document_row(doc)
row.pop("ents", None) # see the dane subset
del row["coref_clusters"] # see the dacoref subset
return row
def dane_row(doc: Doc) -> dict:
row = document_row(doc)
del row["coref_clusters"] # see the dacoref subset
return row
def daned_row(doc: Doc) -> dict:
row = dane_row(doc)
for row_ent, ent in zip(row["ents"], doc.ents, strict=True):
row_ent["kb_id"] = ent.kb_id_
row["qids"] = [{"start": s.start_char, "end": s.end_char, "qid": s.label_} for s in doc.spans["qids"]]
return row
def main() -> None:
documents = json.loads((BUILD / "documents.json").read_text())
ddt = {doc._.sent_id: doc for doc in read_docbin(BUILD / "ddt.spacy")}
dane = {doc._.sent_id: doc for doc in read_docbin(BUILD / "dane.spacy")}
clusters, qids = read_annotations()
subsets: dict[str, dict[str, list[Doc]]] = {
name: {split: [] for split in SPLITS} for name in ("ddt", "dane", "dacoref", "daned", "default")
}
for document in documents:
split, doc_id = document["split"], document["doc_id"]
subsets["ddt"][split].append(build_doc(document, ddt)[0])
subsets["dane"][split].append(build_doc(document, dane)[0])
doc, starts = build_doc(document, dane)
if doc_id in clusters:
add_coreference(doc, starts, clusters[doc_id])
subsets["dacoref"][split].append(doc)
daned_doc, starts = build_doc(document, dane)
add_qids(daned_doc, starts, qids[doc_id])
subsets["daned"][split].append(daned_doc)
subsets["default"][split].append(doc)
rows = {"ddt": ddt_row, "dane": dane_row, "dacoref": document_row, "daned": daned_row, "default": document_row}
sources = {
"ddt": json.loads((BUILD / "ddt_source.json").read_text()),
"cdt": json.loads((BUILD / "cdt_source.json").read_text()),
}
for name, docs in subsets.items():
write_subset(name, docs, rows[name])
(ROOT / name / "source.json").write_text(json.dumps(sources, indent=2) + "\n")
if __name__ == "__main__":
main()