Completed
Push — master ( 2edd21...322e01 )
by
unknown
14s queued 11s
created

annif.vocab.AnnifVocabulary.as_skos()   A

Complexity

Conditions 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 2
dl 0
loc 3
rs 10
c 0
b 0
f 0
cc 1
nop 1
1
"""Vocabulary management functionality for Annif"""
2
3
import os.path
4
import annif
5
import annif.corpus
6
import annif.util
7
from annif.datadir import DatadirMixin
8
from annif.exception import NotInitializedException
9
10
logger = annif.logger
11
12
13
class AnnifVocabulary(DatadirMixin):
14
    """Class representing a subject vocabulary which can be used by multiple
15
    Annif projects."""
16
17
    # defaults for uninitialized instances
18
    _subjects = None
19
20
    def __init__(self, vocab_id, datadir, language):
21
        DatadirMixin.__init__(self, datadir, 'vocabs', vocab_id)
22
        self.vocab_id = vocab_id
23
        self.language = language
24
        self._skos_vocab = None
25
26
    def _create_subject_index(self, subject_corpus):
27
        self._subjects = annif.corpus.SubjectIndex(subject_corpus)
28
        annif.util.atomic_save(self._subjects, self.datadir, 'subjects')
29
30
    def _update_subject_index(self, subject_corpus):
31
        old_subjects = self.subjects
32
        new_subjects = annif.corpus.SubjectIndex(subject_corpus)
33
        updated_subjects = annif.corpus.SubjectIndex()
34
35
        for uri, label, notation in old_subjects:
36
            if new_subjects.contains_uri(uri):
37
                label, notation = new_subjects[new_subjects.by_uri(uri)][1:3]
38
            else:  # subject removed from new corpus
39
                label, notation = None, None
40
            updated_subjects.append(uri, label, notation)
41
        for uri, label, notation in new_subjects:
42
            if not old_subjects.contains_uri(uri):
43
                updated_subjects.append(uri, label, notation)
44
        self._subjects = updated_subjects
45
        annif.util.atomic_save(self._subjects, self.datadir, 'subjects')
46
47
    @property
48
    def subjects(self):
49
        if self._subjects is None:
50
            path = os.path.join(self.datadir, 'subjects')
51
            if os.path.exists(path):
52
                logger.debug('loading subjects from %s', path)
53
                self._subjects = annif.corpus.SubjectIndex.load(path)
54
            else:
55
                raise NotInitializedException(
56
                    "subject file {} not found".format(path))
57
        return self._subjects
58
59
    @property
60
    def skos(self):
61
        """return the subject vocabulary from SKOS file"""
62
        if self._skos_vocab is None:
63
            path = os.path.join(self.datadir, 'subjects.ttl')
64
            if os.path.exists(path):
65
                logger.debug(f'loading graph from {path}')
66
                self._skos_vocab = annif.corpus.SubjectFileSKOS(path,
67
                                                                self.language)
68
            else:
69
                raise NotInitializedException(f'graph file {path} not found')
70
        return self._skos_vocab
71
72
    def load_vocabulary(self, subject_corpus, language):
73
        """load subjects from a subject corpus and save them into a
74
        SKOS/Turtle file for later use"""
75
76
        if os.path.exists(os.path.join(self.datadir, 'subjects')):
77
            logger.info('updating existing vocabulary')
78
            self._update_subject_index(subject_corpus)
79
        else:
80
            self._create_subject_index(subject_corpus)
81
        subject_corpus.save_skos(os.path.join(self.datadir, 'subjects.ttl'),
82
                                 language)
83
84
    def as_skos_file(self):
85
        """return the vocabulary as a file object, in SKOS/Turtle syntax"""
86
        return open(os.path.join(self.datadir, 'subjects.ttl'), 'rb')
87
88
    def as_graph(self):
89
        """return the vocabulary as an rdflib graph"""
90
        return self.skos.graph
91