"""Build the DaNE constituent of the Danish dyna-instruct collection. Source: schneiderkamplab/dfm10-alexandra-dane Revision: 9c4bcb8a2f7e51ad52caa71bff1ef42dc012ee52 The source renders the DaNE named-entity annotation of the Danish Universal Dependencies treebank as instruction/answer pairs: each row asks for the PER, ORG, LOC and MISC entities of one sentence and returns the gold entity strings as JSON. Only the treebank's training split is packaged upstream, so held-out sentences are not available here. `messages` are already chat turns, so conversion validates the chat structure, checks the recorded split, pins the revision plus manifest and shard checksums, and reuses the shared cleaning/tokenization helpers. Rows are preserved as released: no deduplication, filtering or sampling beyond the shared empty-message guard, and the row count is checked against the pinned manifest. Staging files live in this constituent's own `tmp//` directory and the converter deletes only the files it created there; the shared repository `tmp/` directory is never removed wholesale. """ from __future__ import annotations import gzip import hashlib import json import logging import os from pathlib import Path from typing import Any import pyarrow as pa import pyarrow.parquet as pq from datasets import Dataset, load_dataset from huggingface_hub import hf_hub_download from dynainst.dataset_structure import SampleSchema from dynainst.process_dataset import ( add_token_count, ensure_column_order, remove_empty_messages, ) logger = logging.getLogger(__name__) SOURCE = "dane" HF_DATASET = "schneiderkamplab/dfm10-alexandra-dane" REVISION = "9c4bcb8a2f7e51ad52caa71bff1ef42dc012ee52" ADDED = "2026-11-15" SAVE_DIR = Path(__file__).parent TMP_DIR = SAVE_DIR.parents[1] / "tmp" STAGING_DIR = TMP_DIR / SOURCE MANIFEST_PATH = "metadata/manifest.json" MANIFEST_SHA256 = "4bf2598dda2af7265f0958f3447a0b8614b8f905329e888476b867d41c7fc0c6" SHARD_PATH = "data/train-00000.jsonl.gz" SHARD_SHA256 = "aff0c5189234692e173bdf6f2a597868e2c4b1287fd5db0e2d3d0fad9bfdcf58" EXPECTED_ROWS = 4_383 EXPECTED_SHARDS = 1 EXPECTED_SPLIT = "train" SOURCE_LANGUAGE = "da" TARGET_LANGUAGE = "dan" # Each row asks for the named entities of one sentence in a fixed JSON format. TASK = "instruction_following" # DaNE was published in 2020 (LREC 2020); the release records no text dates. CREATED_START = "2020-01-01" CREATED_END = "2020-12-31" TOKENIZER_NAME = "AI-Sweden-Models/Llama-3-8B-instruct" TOKENIZER_REVISION = "88546994bd2b86c823a8f12238ac9236221979eb" ROWS_SCHEMA = pa.schema( [ pa.field("id", pa.string()), pa.field( "messages", pa.list_( pa.struct( [pa.field("role", pa.string()), pa.field("content", pa.string())] ) ), ), pa.field("source", pa.string()), pa.field("added", pa.string()), pa.field("created", pa.string()), pa.field("language", pa.list_(pa.string())), pa.field("task", pa.string()), pa.field("token_count", pa.int64()), ] ) BATCH_SIZE = 2_000 def source_path(relative_path: str) -> Path: """Download a pinned source file and return its local path.""" return Path( hf_hub_download( repo_id=HF_DATASET, repo_type="dataset", filename=relative_path, revision=REVISION, ) ) def sha256(path: Path) -> str: digest = hashlib.sha256() with path.open("rb") as source: for chunk in iter(lambda: source.read(1024 * 1024), b""): digest.update(chunk) return digest.hexdigest() def load_manifest() -> dict[str, Any]: manifest_path = source_path(MANIFEST_PATH) digest = sha256(manifest_path) if digest != MANIFEST_SHA256: raise ValueError(f"Manifest checksum changed: {digest}") manifest: dict[str, Any] = json.loads(manifest_path.read_text(encoding="utf-8")) if manifest["rows"] != EXPECTED_ROWS: raise ValueError(f"Manifest rows changed: {manifest['rows']}") if manifest["shards"] != EXPECTED_SHARDS: raise ValueError(f"Manifest shards changed: {manifest['shards']}") if manifest["languages"] != [SOURCE_LANGUAGE]: raise ValueError(f"Manifest languages changed: {manifest['languages']}") if len(manifest["data_files"]) != EXPECTED_SHARDS: raise ValueError("Manifest data file count does not match the shard count") return manifest def convert(raw: dict[str, Any], index: int) -> dict[str, Any]: metadata = raw.get("metadata") or {} if metadata.get("split") != EXPECTED_SPLIT: raise ValueError(f"Row {index}: unexpected split {metadata.get('split')}") messages = [] for position, message in enumerate(raw["messages"]): expected_role = "user" if position % 2 == 0 else "assistant" if message.get("role") != expected_role: raise ValueError(f"Row {index}: unexpected role order") content = message.get("content") if not isinstance(content, str) or not content.strip(): raise ValueError(f"Row {index}: empty message content") messages.append({"role": expected_role, "content": content}) return { "id": f"{SOURCE}_{index:04d}", "messages": messages, "source": SOURCE, "added": ADDED, "created": f"{CREATED_START}, {CREATED_END}", "language": [TARGET_LANGUAGE], "task": TASK, "token_count": -1, } def stage_source(manifest: dict[str, Any], output_path: Path) -> dict[str, Any]: """Stream the pinned shard into an intermediate Parquet file.""" if output_path.exists(): output_path.unlink() rows_read = 0 turns: dict[int, int] = {} writer = pq.ParquetWriter(output_path, ROWS_SCHEMA, compression="zstd") batch: list[dict[str, Any]] = [] try: for file_info in manifest["data_files"]: relative_path = file_info["file"] if relative_path != SHARD_PATH: raise ValueError(f"Unexpected shard {relative_path}") shard_path = source_path(relative_path) digest = sha256(shard_path) if digest != file_info["sha256"] or digest != SHARD_SHA256: raise ValueError(f"Checksum mismatch for {relative_path}") logger.info("Converting %s", relative_path) with gzip.open(shard_path, "rt", encoding="utf-8") as source: for line in source: raw = json.loads(line) row = convert(raw, rows_read) rows_read += 1 turns[len(row["messages"])] = turns.get(len(row["messages"]), 0) + 1 batch.append(row) if len(batch) >= BATCH_SIZE: writer.write_table( pa.Table.from_pylist(batch, schema=ROWS_SCHEMA) ) batch.clear() if batch: writer.write_table(pa.Table.from_pylist(batch, schema=ROWS_SCHEMA)) batch.clear() finally: writer.close() if rows_read != EXPECTED_ROWS: raise ValueError(f"Read {rows_read:,} rows, expected {EXPECTED_ROWS:,}") return {"rows_read": rows_read, "turns": turns} def cleanup_staging(intermediate_path: Path) -> None: """Remove only the staging files this converter created.""" staging_dir = intermediate_path.parent if intermediate_path.exists(): intermediate_path.unlink() for leftover in staging_dir.glob(f"{SOURCE}_*"): leftover.unlink() try: staging_dir.rmdir() except OSError: logger.info("Left foreign files in %s; not removing the directory", staging_dir) def main() -> None: logging.basicConfig(level=logging.INFO, format="%(message)s") STAGING_DIR.mkdir(parents=True, exist_ok=True) manifest = load_manifest() intermediate_path = STAGING_DIR / f"{SOURCE}_rows.parquet" report = stage_source(manifest, intermediate_path) logger.info("Converted %d rows", report["rows_read"]) dataset: Dataset = load_dataset( "parquet", data_files=str(intermediate_path), split="train", ) # type: ignore[assignment] for row in dataset: SampleSchema(**row) dataset = remove_empty_messages(dataset, num_proc=1) dataset = add_token_count( dataset, tokenizer_name=TOKENIZER_NAME, tokenizer_revision=TOKENIZER_REVISION, num_proc=1, ) dataset = ensure_column_order(dataset) identifiers = dataset["id"] if len(identifiers) != len(set(identifiers)): raise ValueError("Converted dataset contains duplicate IDs") if len(dataset) != EXPECTED_ROWS: raise ValueError(f"Retained {len(dataset):,} rows, expected {EXPECTED_ROWS:,}") for row in dataset: sample = SampleSchema(**row) if sample.token_count <= 0: raise ValueError(f"Sample {sample.id} has a non-positive token count") output_path = SAVE_DIR / f"{SOURCE}.parquet" staged_output = STAGING_DIR / output_path.name if staged_output.exists(): staged_output.unlink() dataset.to_parquet(str(staged_output)) if pq.read_metadata(staged_output).num_rows != len(dataset): raise RuntimeError("Staged Parquet row count does not match the dataset") if not pq.read_schema(staged_output).equals(ROWS_SCHEMA, check_metadata=False): raise RuntimeError("Staged Parquet schema does not match the expected schema") os.replace(staged_output, output_path) cleanup_staging(intermediate_path) report["rows_retained"] = len(dataset) report["tokens_total"] = int(sum(dataset["token_count"])) print(json.dumps(report, indent=2, sort_keys=True)) print(f"Wrote {len(dataset):,} samples to {output_path}") if __name__ == "__main__": main()