File size: 2,407 Bytes
a3de7e3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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",
            features=Features({
                'subject': Value('string'),
                'predicate': Value('string'),
                'object': Value('string')
            })
        )
    
    def _split_generators(self, dl_manager):
        # Download and extract the dataset
        path = dl_manager.download_and_extract(["d3fend.nt.gz"])
        
        return [SplitGenerator(name=datasets.Split.TRAIN, 
                               gen_kwargs={'filepath': path})]
    
    def _generate_examples(self, filepath):
        id_ = 0
        graph = Graph(bind_namespaces="core")
        graph.bind("d3f", D3F)
        graph.bind("dcterms", DCTERMS)
        graph.bind("skos", SKOS)
        graph.bind("dcam", DCAM)
        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