Passed
Pull Request — master (#604)
by Osma
02:54
created

annif.vocab.AnnifVocabulary.as_skos_file()   A

Complexity

Conditions 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 3
Ratio 100 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nop 1
dl 3
loc 3
rs 10
c 0
b 0
f 0
1
"""Vocabulary management functionality for Annif"""
2
3
import os.path
4
import re
5
import annif
6
import annif.corpus
7
import annif.util
8
from annif.datadir import DatadirMixin
9
from annif.exception import NotInitializedException
10
from annif.util import parse_args
11
12
logger = annif.logger
13
14
15
def get_vocab(vocab_spec, datadir, default_language):
16
    match = re.match(r'(\w+)(\((.*)\))?', vocab_spec)
17
    if match is None:
18
        raise ValueError(f"Invalid vocabulary specification: {vocab_spec}")
19
    vocab_id = match.group(1)
20
    posargs, kwargs = parse_args(match.group(3))
21
    language = posargs[0] if posargs else default_language
22
23
    return AnnifVocabulary(vocab_id, datadir, language)
24
25
26 View Code Duplication
class AnnifVocabulary(DatadirMixin):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
27
    """Class representing a subject vocabulary which can be used by multiple
28
    Annif projects."""
29
30
    # defaults for uninitialized instances
31
    _subjects = None
32
33
    def __init__(self, vocab_id, datadir, language):
34
        DatadirMixin.__init__(self, datadir, 'vocabs', vocab_id)
35
        self.vocab_id = vocab_id
36
        self.language = language
37
        self._skos_vocab = None
38
39
    @staticmethod
40
    def _index_filename(language):
41
        return f"subjects.{language}.tsv"
42
43
    def _create_subject_index(self, subject_corpus, language):
44
        subjects = annif.corpus.SubjectIndex()
45
        subjects.load_subjects(subject_corpus, language)
46
        annif.util.atomic_save(subjects, self.datadir,
47
                               self._index_filename(language))
48
        return subjects
49
50
    def _update_subject_index(self, subject_corpus, language):
51
        old_subjects = self.subjects
52
        new_subjects = annif.corpus.SubjectIndex()
53
        new_subjects.load_subjects(subject_corpus, language)
54
        updated_subjects = annif.corpus.SubjectIndex()
55
56
        for old_subject in old_subjects:
57
            if new_subjects.contains_uri(old_subject.uri):
58
                new_subject = new_subjects[new_subjects.by_uri(
59
                    old_subject.uri)]
60
            else:  # subject removed from new corpus
61
                new_subject = annif.corpus.Subject(uri=old_subject.uri,
62
                                                   label=None,
63
                                                   notation=None)
64
            updated_subjects.append(new_subject)
65
        for new_subject in new_subjects:
66
            if not old_subjects.contains_uri(new_subject.uri):
67
                updated_subjects.append(new_subject)
68
        annif.util.atomic_save(updated_subjects, self.datadir,
69
                               self._index_filename(language))
70
        return updated_subjects
71
72
    @property
73
    def subjects(self):
74
        if self._subjects is None:
75
            path = os.path.join(self.datadir,
76
                                self._index_filename(self.language))
77
            if os.path.exists(path):
78
                logger.debug('loading subjects from %s', path)
79
                self._subjects = annif.corpus.SubjectIndex.load(path)
80
            else:
81
                raise NotInitializedException(
82
                    "subject file {} not found".format(path))
83
        return self._subjects
84
85
    @property
86
    def skos(self):
87
        """return the subject vocabulary from SKOS file"""
88
        if self._skos_vocab is not None:
89
            return self._skos_vocab
90
91
        # attempt to load graph from dump file
92
        dumppath = os.path.join(self.datadir, 'subjects.dump.gz')
93
        if os.path.exists(dumppath):
94
            logger.debug(f'loading graph dump from {dumppath}')
95
            try:
96
                self._skos_vocab = annif.corpus.SubjectFileSKOS(dumppath)
97
            except ModuleNotFoundError:
98
                # Probably dump has been saved using a different rdflib version
99
                logger.debug('could not load graph dump, using turtle file')
100
            else:
101
                return self._skos_vocab
102
103
        # graph dump file not found - parse ttl file instead
104
        path = os.path.join(self.datadir, 'subjects.ttl')
105
        if os.path.exists(path):
106
            logger.debug(f'loading graph from {path}')
107
            self._skos_vocab = annif.corpus.SubjectFileSKOS(path)
108
            # store the dump file so we can use it next time
109
            self._skos_vocab.save_skos(path, self.language)
110
            return self._skos_vocab
111
112
        raise NotInitializedException(f'graph file {path} not found')
113
114
    def load_vocabulary(self, subject_corpus, default_language, force=False):
115
        """Load subjects from a subject corpus and save them into one
116
        or more subject index files as well as a SKOS/Turtle file for later
117
        use. If force=True, replace the existing subject index completely."""
118
119
        # default to language from project config if subject corpus isn't
120
        # language-aware or can't detect languages
121
        languages = subject_corpus.languages or [default_language]
122
123
        for language in languages:
124
            if not force and os.path.exists(
125
                    os.path.join(self.datadir,
126
                                 self._index_filename(language))):
127
                logger.info('updating existing vocabulary')
128
                subjects = self._update_subject_index(subject_corpus, language)
129
            else:
130
                subjects = self._create_subject_index(subject_corpus, language)
131
132
            if language == default_language:
133
                self._subjects = subjects
134
135
        subject_corpus.save_skos(os.path.join(self.datadir, 'subjects.ttl'),
136
                                 default_language)
137
138
    def as_skos_file(self):
139
        """return the vocabulary as a file object, in SKOS/Turtle syntax"""
140
        return open(os.path.join(self.datadir, 'subjects.ttl'), 'rb')
141
142
    def as_graph(self):
143
        """return the vocabulary as an rdflib graph"""
144
        return self.skos.graph
145