import os import datasets from datasets import SplitGenerator, DatasetInfo, GeneratorBasedBuilder from rdflib import Graph, URIRef, Literal, BNode from rdflib.namespace import RDF, RDFS, OWL, XSD, DCTERMS, SKOS, DCAM, Namespace from datasets.features import Features, Value D3F = Namespace('http://d3fend.mitre.org/ontologies/d3fend.owl#') class D3FENDDatasetBuilder(GeneratorBasedBuilder): VERSION = "1.0.0" def _info(self): return DatasetInfo( description="D3FEND is a framework which encodes a countermeasure knowledge base as a knowledge graph. The graph contains the types and relations that define key concepts in the cybersecurity countermeasure domain and the relations necessary to link those concepts to each other. Each of these concepts and relations are linked to references in the cybersecurity literature.", homepage="https://d3fend.mitre.org/", license="MIT", citation=r"""@techreport{kaloroumakis2021d3fend, title={Toward a Knowledge Graph of Cybersecurity Countermeasures}, author={Kaloroumakis, Peter E. and Smith, Michael J.}, institution={The MITRE Corporation}, year={2021}, url={https://d3fend.mitre.org/resources/D3FEND.pdf} }""", features=Features({ 'subject': Value('string'), 'predicate': Value('string'), 'object': Value('string') }) ) def _split_generators(self, dl_manager): # Download and extract the dataset extracted = dl_manager.download_and_extract("d3fend.nt.gz") return [SplitGenerator(name=datasets.Split.TRAIN, gen_kwargs={'filepath': extracted})] def _generate_examples(self, filepath): id_ = 0 graph = Graph(bind_namespaces="core") graph.parse(filepath) # Yield individual triples from the graph as N3 for (s, p, o) in graph.triples((None, None, None)): yield id_, { 'subject': s.n3(), 'predicate': p.n3(), 'object': o.n3() } id_ += 1 from rdflib.util import from_n3 def triple(features): try: subject_node = from_n3(features['subject']) predicate_node = from_n3(features['predicate']) object_node = from_n3(features['object']) return (subject_node, predicate_node, object_node) except Exception as e: print(f"Error transforming features {features}: {e}") return (None, None, None) from datasets import load_dataset