Passed
Pull Request — master (#461)
by
unknown
03:02
created

annif.backend.yake   A

Complexity

Total Complexity 41

Size/Duplication

Total Lines 197
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 164
dl 0
loc 197
rs 9.1199
c 0
b 0
f 0
wmc 41

18 Methods

Rating   Name   Duplication   Size   Complexity  
A YakeBackend.default_params() 0 4 1
A YakeBackend.label_types() 0 14 3
A YakeBackend.is_trained() 0 3 1
B YakeBackend._create_index() 0 14 6
A YakeBackend.initialize() 0 10 1
A YakeBackend._lemmatize_phrase() 0 6 2
A YakeBackend._sort_phrase() 0 3 1
A YakeBackend._combine_suggestions() 0 10 3
A YakeBackend._load_index() 0 7 3
A YakeBackend._save_index() 0 5 3
A YakeBackend.graph() 0 6 2
A YakeBackend._keyphrases2suggestions() 0 16 5
A YakeBackend._keyphrase2uris() 0 4 1
A YakeBackend._transform_score() 0 5 2
A YakeBackend._initialize_index() 0 12 3
A YakeBackend._conflate_scores() 0 2 1
A YakeBackend._suggest() 0 16 1
A YakeBackend._normalize_label() 0 6 2

How to fix   Complexity   

Complexity

Complex classes like annif.backend.yake often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1
"""Annif backend using Yake keyword extraction"""
2
# TODO Mention GPLv3 license also here?
3
4
import yake
5
import os.path
6
import re
7
from collections import defaultdict
8
from rdflib.namespace import SKOS, RDF, OWL
9
import rdflib
10
import annif.util
11
from . import backend
12
from annif.suggestion import SubjectSuggestion, ListSuggestionResult
13
from annif.exception import ConfigurationException
14
15
16
class YakeBackend(backend.AnnifBackend):
17
    """Yake based backend for Annif"""
18
    name = "yake"
19
    needs_subject_index = False
20
21
    # defaults for uninitialized instances
22
    _index = None
23
    _graph = None
24
    INDEX_FILE = 'yake-index'
25
26
    DEFAULT_PARAMETERS = {
27
        'max_ngram_size': 4,
28
        'deduplication_threshold': 0.9,
29
        'deduplication_algo': 'levs',
30
        'window_size': 1,
31
        'num_keywords': 100,
32
        'features': None,
33
        'default_label_types': ['pref', 'alt'],
34
        'remove_specifiers': False
35
    }
36
37
    def default_params(self):
38
        params = backend.AnnifBackend.DEFAULT_PARAMETERS.copy()
39
        params.update(self.DEFAULT_PARAMETERS)
40
        return params
41
42
    @property
43
    def is_trained(self):
44
        return True
45
46
    @property
47
    def label_types(self):
48
        mapping = {'pref': SKOS.prefLabel,
49
                   'alt': SKOS.altLabel,
50
                   'hidden': SKOS.hiddenLabel}
51
        if 'label_types' in self.params:
52
            lt_entries = self.params['label_types'].split(',')
53
            try:
54
                return [mapping[lt.strip()] for lt in lt_entries]
55
            except KeyError as err:
56
                raise ConfigurationException(
57
                    f'invalid label type {err}', backend_id=self.backend_id)
58
        else:
59
            return [mapping[lt] for lt in self.params['default_label_types']]
60
61
    @property
62
    def graph(self):
63
        if self._graph is None:
64
            self.info('Loading graph')
65
            self._graph = self.project.vocab.as_graph()
66
        return self._graph
67
68
    def initialize(self):
69
        self._initialize_index()
70
        self._kw_extractor = yake.KeywordExtractor(
71
            lan=self.params['language'],
72
            n=self.params['max_ngram_size'],
73
            dedupLim=self.params['deduplication_threshold'],
74
            dedupFunc=self.params['deduplication_algo'],
75
            windowsSize=self.params['window_size'],
76
            top=self.params['num_keywords'],
77
            features=self.params['features'])
78
79
    def _initialize_index(self):
80
        if self._index is None:
81
            path = os.path.join(self.datadir, self.INDEX_FILE)
82
            if os.path.exists(path):
83
                self._index = self._load_index(path)
84
                self.info(
85
                    f'Loaded index from {path} with {len(self._index)} labels')
86
            else:
87
                self.info('Creating index')
88
                self._create_index()
89
                self._save_index(path)
90
                self.info(f'Created index with {len(self._index)} labels')
91
92
    def _save_index(self, path):
93
        with open(path, 'w', encoding='utf-8') as indexfile:
94
            for label, uris in self._index.items():
95
                line = label + '\t' + ' '.join(uris)
96
                print(line, file=indexfile)
97
98
    def _load_index(self, path):
99
        index = dict()
100
        with open(path, 'r', encoding='utf-8') as indexfile:
101
            for line in indexfile:
102
                label, uris = line.strip().split('\t')
103
                index[label] = uris.split()
104
        return index
105
106
    def _create_index(self):
107
        index = defaultdict(set)
108
        for concept in self.graph.subjects(RDF.type, SKOS.Concept):
109
            if (concept, OWL.deprecated, rdflib.Literal(True)) in self.graph:
110
                continue
111
            uri = str(concept)
112
            for label_type in self.label_types:
113
                for label in self.graph.objects(concept, label_type):
114
                    if not label.language == self.params['language']:
115
                        continue
116
                    label = self._normalize_label(label)
117
                    index[label].add(uri)
118
        index.pop('', None)  # Remove possible empty string entry
119
        self._index = dict(index)
120
121
    def _normalize_label(self, label):
122
        label = str(label)
123
        if annif.util.boolean(self.params['remove_specifiers']):
124
            label = re.sub(r' \(.*\)', '', label)
125
        lemmatized_label = self._lemmatize_phrase(label)
126
        return self._sort_phrase(lemmatized_label)
127
128
    def _lemmatize_phrase(self, phrase):
129
        normalized = []
130
        for word in phrase.split():
131
            normalized.append(
132
                self.project.analyzer.normalize_word(word).lower())
133
        return ' '.join(normalized)
134
135
    def _sort_phrase(self, phrase):
136
        words = phrase.split()
137
        return ' '.join(sorted(words))
138
139
    def _suggest(self, text, params):
140
        self.debug(
141
            f'Suggesting subjects for text "{text[:20]}..." (len={len(text)})')
142
        limit = int(params['limit'])
143
144
        keyphrases = self._kw_extractor.extract_keywords(text)
145
        suggestions = self._keyphrases2suggestions(keyphrases)
146
147
        subject_suggestions = [SubjectSuggestion(
148
                uri=uri,
149
                label=None,
150
                notation=None,
151
                score=score)
152
                for uri, score in suggestions[:limit] if score > 0.0]
153
        return ListSuggestionResult.create_from_index(subject_suggestions,
154
                                                      self.project.subjects)
155
156
    def _keyphrases2suggestions(self, keyphrases):
157
        suggestions = []
158
        not_matched = []
159
        for kp, score in keyphrases:
160
            uris = self._keyphrase2uris(kp)
161
            for uri in uris:
162
                suggestions.append(
163
                    (uri, self._transform_score(score)))
164
            if not uris:
165
                not_matched.append((kp, self._transform_score(score)))
166
        # Remove duplicate uris, conflating the scores
167
        suggestions = self._combine_suggestions(suggestions)
168
        self.debug('Keyphrases not matched:\n' + '\t'.join(
169
            [kp[0] + ' ' + str(kp[1]) for kp
170
             in sorted(not_matched, reverse=True, key=lambda kp: kp[1])]))
171
        return suggestions
172
173
    def _keyphrase2uris(self, keyphrase):
174
        keyphrase = self._lemmatize_phrase(keyphrase)
175
        keyphrase = self._sort_phrase(keyphrase)
176
        return self._index.get(keyphrase, [])
177
178
    def _transform_score(self, score):
179
        if score < 0:
180
            self.debug(f'Replacing negative YAKE score {score} with zero')
181
            return 1.0
182
        return 1.0 / (score + 1)
183
184
    def _combine_suggestions(self, suggestions):
185
        combined_suggestions = {}
186
        for uri, score in suggestions:
187
            if uri not in combined_suggestions:
188
                combined_suggestions[uri] = score
189
            else:
190
                old_score = combined_suggestions[uri]
191
                combined_suggestions[uri] = self._conflate_scores(
192
                    score, old_score)
193
        return list(combined_suggestions.items())
194
195
    def _conflate_scores(self, score1, score2):
196
        return score1 * score2 / (score1 * score2 + (1-score1) * (1-score2))
197