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

annif.backend.yake   B

Complexity

Total Complexity 44

Size/Duplication

Total Lines 211
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 175
dl 0
loc 211
rs 8.8798
c 0
b 0
f 0
wmc 44

19 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
A YakeBackend.graph() 0 6 2
A YakeBackend._get_concept_labels() 0 7 4
A YakeBackend._create_index() 0 12 4
A YakeBackend.initialize() 0 2 1
A YakeBackend._lemmatize_phrase() 0 6 2
A YakeBackend._sort_phrase() 0 3 1
A YakeBackend._combine_scores() 0 6 1
A YakeBackend._combine_suggestions() 0 10 3
A YakeBackend._load_index() 0 7 3
A YakeBackend._save_index() 0 5 3
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._suggest() 0 28 2
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_parentheses': 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
71
    def _initialize_index(self):
72
        if self._index is None:
73
            path = os.path.join(self.datadir, self.INDEX_FILE)
74
            if os.path.exists(path):
75
                self._index = self._load_index(path)
76
                self.info(
77
                    f'Loaded index from {path} with {len(self._index)} labels')
78
            else:
79
                self.info('Creating index')
80
                self._index = self._create_index()
81
                self._save_index(path)
82
                self.info(f'Created index with {len(self._index)} labels')
83
84
    def _save_index(self, path):
85
        with open(path, 'w', encoding='utf-8') as indexfile:
86
            for label, uris in self._index.items():
87
                line = label + '\t' + ' '.join(uris)
88
                print(line, file=indexfile)
89
90
    def _load_index(self, path):
91
        index = dict()
92
        with open(path, 'r', encoding='utf-8') as indexfile:
93
            for line in indexfile:
94
                label, uris = line.strip().split('\t')
95
                index[label] = uris.split()
96
        return index
97
98
    def _create_index(self):
99
        index = defaultdict(set)
100
        for concept in self.graph.subjects(RDF.type, SKOS.Concept):
101
            if (concept, OWL.deprecated, rdflib.Literal(True)) in self.graph:
102
                continue
103
            uri = str(concept)
104
            labels = self._get_concept_labels(concept, self.label_types)
105
            for label in labels:
106
                label = self._normalize_label(label)
107
                index[label].add(uri)
108
        index.pop('', None)  # Remove possible empty string entry
109
        return dict(index)
110
111
    def _get_concept_labels(self, concept, label_types):
112
        labels = []
113
        for label_type in label_types:
114
            for label in self.graph.objects(concept, label_type):
115
                if label.language == self.params['language']:
116
                    labels.append(label)
117
        return labels
118
119
    def _normalize_label(self, label):
120
        label = str(label)
121
        if annif.util.boolean(self.params['remove_parentheses']):
122
            label = re.sub(r' \(.*\)', '', label)
123
        lemmatized_label = self._lemmatize_phrase(label)
124
        return self._sort_phrase(lemmatized_label)
125
126
    def _lemmatize_phrase(self, phrase):
127
        normalized = []
128
        for word in phrase.split():
129
            normalized.append(
130
                self.project.analyzer.normalize_word(word).lower())
131
        return ' '.join(normalized)
132
133
    def _sort_phrase(self, phrase):
134
        words = phrase.split()
135
        return ' '.join(sorted(words))
136
137
    def _suggest(self, text, params):
138
        self.debug(
139
            f'Suggesting subjects for text "{text[:20]}..." (len={len(text)})')
140
        limit = int(params['limit'])
141
142
        alphanum = re.compile('[^a-zA-Z0-9]')
143
        if len(re.sub(alphanum, '', text)) == 0:
144
            return ListSuggestionResult([])
145
146
        self._kw_extractor = yake.KeywordExtractor(
147
            lan=params['language'],
148
            n=int(params['max_ngram_size']),
149
            dedupLim=float(params['deduplication_threshold']),
150
            dedupFunc=params['deduplication_algo'],
151
            windowsSize=int(params['window_size']),
152
            top=int(params['num_keywords']),
153
            features=self.params['features'])
154
        keyphrases = self._kw_extractor.extract_keywords(text)
155
        suggestions = self._keyphrases2suggestions(keyphrases)
156
157
        subject_suggestions = [SubjectSuggestion(
158
                uri=uri,
159
                label=None,
160
                notation=None,
161
                score=score)
162
                for uri, score in suggestions[:limit] if score > 0.0]
163
        return ListSuggestionResult.create_from_index(subject_suggestions,
164
                                                      self.project.subjects)
165
166
    def _keyphrases2suggestions(self, keyphrases):
167
        suggestions = []
168
        not_matched = []
169
        for kp, score in keyphrases:
170
            uris = self._keyphrase2uris(kp)
171
            for uri in uris:
172
                suggestions.append(
173
                    (uri, self._transform_score(score)))
174
            if not uris:
175
                not_matched.append((kp, self._transform_score(score)))
176
        # Remove duplicate uris, conflating the scores
177
        suggestions = self._combine_suggestions(suggestions)
178
        self.debug('Keyphrases not matched:\n' + '\t'.join(
179
            [kp[0] + ' ' + str(kp[1]) for kp
180
             in sorted(not_matched, reverse=True, key=lambda kp: kp[1])]))
181
        return suggestions
182
183
    def _keyphrase2uris(self, keyphrase):
184
        keyphrase = self._lemmatize_phrase(keyphrase)
185
        keyphrase = self._sort_phrase(keyphrase)
186
        return self._index.get(keyphrase, [])
187
188
    def _transform_score(self, score):
189
        if score < 0:
190
            self.debug(f'Replacing negative YAKE score {score} with zero')
191
            return 1.0
192
        return 1.0 / (score + 1)
193
194
    def _combine_suggestions(self, suggestions):
195
        combined_suggestions = {}
196
        for uri, score in suggestions:
197
            if uri not in combined_suggestions:
198
                combined_suggestions[uri] = score
199
            else:
200
                old_score = combined_suggestions[uri]
201
                combined_suggestions[uri] = self._combine_scores(
202
                    score, old_score)
203
        return list(combined_suggestions.items())
204
205
    def _combine_scores(self, score1, score2):
206
        # The result is never smaller than the greater input
207
        score1 = score1/2 + 0.5
208
        score2 = score2/2 + 0.5
209
        confl = score1 * score2 / (score1 * score2 + (1-score1) * (1-score2))
210
        return (confl-0.5) * 2
211