File size: 7,001 Bytes
2d16d8f |
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 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 |
"""HuggingFace Datasets loader for .causal knowledge graph files."""
import datasets
from datasets import DatasetInfo, Features, Value, Sequence
class CausalConfig(datasets.BuilderConfig):
"""BuilderConfig for .causal files."""
def __init__(
self,
include_inferred: bool = True,
min_confidence: float = 0.0,
**kwargs,
):
"""
Args:
include_inferred: Include inferred triplets (default: True)
min_confidence: Minimum confidence threshold (default: 0.0)
"""
super().__init__(**kwargs)
self.include_inferred = include_inferred
self.min_confidence = min_confidence
class CausalDataset(datasets.GeneratorBasedBuilder):
"""
HuggingFace Dataset loader for .causal knowledge graph files.
The .causal format is a binary knowledge graph with embedded deterministic
inference. It provides zero-hallucination fact retrieval with full provenance.
Usage:
from datasets import load_dataset
# Load from local file
ds = load_dataset("chkmie/dotcausal", data_files="knowledge.causal")
# Load with config
ds = load_dataset(
"chkmie/dotcausal",
data_files="knowledge.causal",
include_inferred=True,
min_confidence=0.5,
)
Features:
- trigger (str): The cause/trigger entity
- mechanism (str): The relationship type
- outcome (str): The effect/outcome entity
- confidence (float): Confidence score (0-1)
- is_inferred (bool): Whether derived or explicit
- source (str): Original source (e.g., paper)
- provenance (list): Source triplets for inferred facts
References:
- PyPI: https://pypi.org/project/dotcausal/
- GitHub: https://github.com/DT-Foss/dotcausal
- Paper: https://doi.org/10.5281/zenodo.18326222
"""
BUILDER_CONFIG_CLASS = CausalConfig
BUILDER_CONFIGS = [
CausalConfig(
name="default",
version=datasets.Version("1.0.0"),
description="Load all triplets from .causal files",
),
CausalConfig(
name="explicit_only",
version=datasets.Version("1.0.0"),
description="Load only explicit triplets (no inferred)",
include_inferred=False,
),
CausalConfig(
name="high_confidence",
version=datasets.Version("1.0.0"),
description="Load triplets with confidence >= 0.8",
min_confidence=0.8,
),
]
DEFAULT_CONFIG_NAME = "default"
def _info(self):
return DatasetInfo(
description="""\
.causal knowledge graph dataset with embedded deterministic inference.
Each row represents a causal triplet (trigger → mechanism → outcome).
""",
features=Features(
{
"trigger": Value("string"),
"mechanism": Value("string"),
"outcome": Value("string"),
"confidence": Value("float32"),
"is_inferred": Value("bool"),
"source": Value("string"),
"provenance": Sequence(Value("string")),
}
),
homepage="https://dotcausal.com",
license="MIT",
citation="""\
@article{foss2026causal,
author = {Foss, David Tom},
title = {The .causal Format: Deterministic Inference for AI-Assisted Hypothesis Amplification},
journal = {Zenodo},
year = {2026},
doi = {10.5281/zenodo.18326222}
}
""",
)
def _split_generators(self, dl_manager):
"""Generate splits from data files."""
data_files = self.config.data_files
if not data_files:
raise ValueError(
"No data_files specified. Use: load_dataset('chkmie/dotcausal', data_files='your_file.causal')"
)
# Handle different data_files formats
if isinstance(data_files, dict):
# {"train": ["file1.causal"], "test": ["file2.causal"]}
splits = []
for split_name, files in data_files.items():
if isinstance(files, str):
files = [files]
downloaded = dl_manager.download_and_extract(files)
splits.append(
datasets.SplitGenerator(
name=split_name,
gen_kwargs={"filepaths": downloaded},
)
)
return splits
elif isinstance(data_files, (list, tuple)):
# ["file1.causal", "file2.causal"]
downloaded = dl_manager.download_and_extract(list(data_files))
return [
datasets.SplitGenerator(
name=datasets.Split.TRAIN,
gen_kwargs={"filepaths": downloaded},
)
]
else:
# Single file string
downloaded = dl_manager.download_and_extract([data_files])
return [
datasets.SplitGenerator(
name=datasets.Split.TRAIN,
gen_kwargs={"filepaths": downloaded},
)
]
def _generate_examples(self, filepaths):
"""Generate examples from .causal files."""
try:
from dotcausal import CausalReader
except ImportError:
raise ImportError(
"dotcausal package required. Install with: pip install dotcausal"
)
if isinstance(filepaths, str):
filepaths = [filepaths]
idx = 0
for filepath in filepaths:
reader = CausalReader(filepath)
# Get all triplets via search
results = reader.search("", limit=100000)
for r in results:
# Apply filters from config
confidence = r.get("confidence", 1.0)
is_inferred = r.get("is_inferred", False)
if confidence < self.config.min_confidence:
continue
if not self.config.include_inferred and is_inferred:
continue
# Convert provenance to list of strings
provenance = r.get("provenance", [])
if not isinstance(provenance, list):
provenance = [str(provenance)] if provenance else []
else:
provenance = [str(p) for p in provenance]
yield idx, {
"trigger": r.get("trigger", ""),
"mechanism": r.get("mechanism", ""),
"outcome": r.get("outcome", ""),
"confidence": float(confidence),
"is_inferred": bool(is_inferred),
"source": r.get("source", ""),
"provenance": provenance,
}
idx += 1
|