Download scripts/utils.py from chcaa/dacy-data: direct link, hf CLI and curl.
- Browser
- Download file 4.17 kB
-
https://huggingface.co/datasets/chcaa/dacy-data/resolve/main/scripts/utils.py
- Command line
-
hf download hf://datasets/chcaa/dacy-data/scripts/utils.py
-
curl -L -o utils.py https://huggingface.co/datasets/chcaa/dacy-data/resolve/main/scripts/utils.py
4.17 kB
| """Helpers shared by the scripts that build the subsets.""" | |
| from __future__ import annotations | |
| import logging | |
| import urllib.request | |
| import zipfile | |
| from collections.abc import Callable | |
| from pathlib import Path | |
| import conllu | |
| import spacy | |
| from spacy.tokens import Doc, DocBin | |
| from spacy.training.converters import conllu_to_docs | |
| ROOT = Path(__file__).resolve().parents[1] | |
| ASSETS = ROOT / "assets" # downloaded sources | |
| BUILD = ROOT / "build" # intermediate files | |
| SPLITS = ("train", "dev", "test") | |
| Doc.set_extension("sent_id", default=None) | |
| Doc.set_extension("sent_ids", default=None) | |
| Doc.set_extension("doc_id", default=None) | |
| Doc.set_extension("domain", default=None) | |
| logging.basicConfig(level=logging.INFO, format="%(asctime)s %(message)s", datefmt="%H:%M:%S") | |
| log = logging.getLogger("dacy-data") | |
| nlp = spacy.blank("da") | |
| def download(url: str, path: Path) -> Path: | |
| if not path.exists(): | |
| log.info("Downloading %s", url) | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| urllib.request.urlretrieve(url, path) | |
| return path | |
| def download_zip(url: str, name: str) -> Path: | |
| """Download and extract a zip file to assets/<name>.""" | |
| folder = ASSETS / name | |
| with zipfile.ZipFile(download(url, ASSETS / f"{name}.zip")) as archive: | |
| archive.extractall(folder) | |
| return folder | |
| # DaCoref, which also holds the CDT document ids and the DaNED QIDs | |
| DACOREF_URL = "http://danlp-downloads.alexandra.dk/datasets/dacoref.zip" | |
| DACOREF_FIELDS = [ | |
| "id", | |
| "form", | |
| "lemma", | |
| "upos", | |
| "xpos", | |
| "feats", | |
| "head", | |
| "deprel", | |
| "deps", | |
| "misc", | |
| "coref_id", | |
| "coref_rel", | |
| "doc_id", | |
| "qid", | |
| ] | |
| def read_dacoref() -> tuple[list[conllu.TokenList], Path]: | |
| """The sentences of DaCoref and the folder it is extracted to.""" | |
| folder = download_zip(DACOREF_URL, "dacoref") | |
| text = (folder / "CDT_coref.conllu").read_text(encoding="utf-8") | |
| return conllu.parse(text, fields=DACOREF_FIELDS), folder | |
| def read_conllu(path: Path) -> list[Doc]: | |
| """One doc per sentence, as `spacy convert --converter conllu --merge-subtokens`.""" | |
| text = path.read_text(encoding="utf-8") | |
| docs = list(conllu_to_docs(text, n_sents=1, merge_subtokens=True, no_print=True)) | |
| sentences = conllu.parse(text) | |
| assert len(docs) == len(sentences) | |
| for doc, sent in zip(docs, sentences, strict=True): | |
| assert doc.text.strip() == sent.metadata["text"].strip() | |
| doc._.sent_id = sent.metadata["sent_id"] | |
| # the converter creates a new vocab for each doc | |
| return [Doc(nlp.vocab).from_bytes(doc.to_bytes()) for doc in docs] | |
| def write_docbin(docs: list[Doc], path: Path) -> None: | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| doc_bin = DocBin(store_user_data=True) | |
| for doc in docs: | |
| doc_bin.add(doc) | |
| doc_bin.to_disk(path) | |
| def read_docbin(path: Path) -> list[Doc]: | |
| return list(DocBin().from_disk(path).get_docs(nlp.vocab)) | |
| def read_subset(subset: str) -> dict[str, list[Doc]]: | |
| """The docs of a subset, as written by its script.""" | |
| return {split: read_docbin(ROOT / subset / f"{split}.spacy") for split in SPLITS} | |
| def write_subset(subset: str, docs: dict[str, list[Doc]], to_row: Callable[[Doc], dict]) -> None: | |
| """Write a subset to <subset>/ as parquet files and spaCy DocBins.""" | |
| from datasets import Dataset | |
| for split in SPLITS: | |
| write_docbin(docs[split], ROOT / subset / f"{split}.spacy") | |
| rows = [to_row(doc) for doc in docs[split]] | |
| Dataset.from_list(rows).to_parquet(ROOT / subset / f"{split}-00000-of-00001.parquet") | |
| log.info("%s/%s: %d rows", subset, split, len(rows)) | |
| def document_row(doc: Doc) -> dict: | |
| row = doc.to_json() | |
| row.pop("spans", None) | |
| keys = sorted( | |
| (k for k in doc.spans if k.startswith("coref_clusters_")), | |
| key=lambda k: int(k.rsplit("_", 1)[1]), | |
| ) | |
| return { | |
| **row, | |
| "sent_ids": doc._.sent_ids, | |
| "doc_id": doc._.doc_id, | |
| "domain": doc._.domain, | |
| "coref_clusters": [ | |
| [{"start": s.start_char, "end": s.end_char, "label": s.label_} for s in doc.spans[k]] | |
| for k in keys | |
| ], | |
| } | |