Passed
Pull Request — master (#438)
by
unknown
04:05
created

annif.backend.stwfsa   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 118
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 102
dl 0
loc 118
rs 10
c 0
b 0
f 0
wmc 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A StwfsaBackend._train() 0 27 4
A StwfsaBackend.initialize() 0 11 3
A StwfsaBackend._suggest() 0 18 3
1
import os
2
from stwfsapy.predictor import StwfsapyPredictor
3
from annif.exception import NotInitializedException, NotSupportedException
4
from annif.suggestion import ListSuggestionResult, SubjectSuggestion
5
from . import backend
6
from annif.util import boolean
7
8
9
_KEY_CONCEPT_TYPE_URI = 'concept_type_uri'
10
_KEY_SUBTHESAURUS_TYPE_URI = 'sub_thesaurus_type_uri'
11
_KEY_THESAURUS_RELATION_TYPE_URI = 'thesaurus_relation_type_uri'
12
_KEY_THESAURUS_RELATION_IS_SPECIALISATION = (
13
    'thesaurus_relation_is_specialisation')
14
_KEY_REMOVE_DEPRECATED = 'remove_deprecated'
15
_KEY_HANDLE_TITLE_CASE = 'handle_title_case'
16
_KEY_EXTRACT_UPPER_CASE_FROM_BRACES = 'extract_upper_case_from_braces'
17
_KEY_EXTRACT_ANY_CASE_FROM_BRACES = 'extract_any_case_from_braces'
18
_KEY_EXPAND_AMPERSAND_WITH_SPACES = 'expand_ampersand_with_spaces'
19
_KEY_EXPAND_ABBREVIATION_WITH_PUNCTUATION = (
20
    'expand_abbreviation_with_punctuation')
21
_KEY_SIMPLE_ENGLISH_PLURAL_RULES = 'simple_english_plural_rules'
22
23
24
class StwfsaBackend(backend.AnnifBackend):
25
26
    name = "stwfsa"
27
    needs_subject_index = True
28
29
    STWFSA_PARAMETERS = {
30
        _KEY_CONCEPT_TYPE_URI: str,
31
        _KEY_SUBTHESAURUS_TYPE_URI: str,
32
        _KEY_THESAURUS_RELATION_TYPE_URI: str,
33
        _KEY_THESAURUS_RELATION_IS_SPECIALISATION: boolean,
34
        _KEY_REMOVE_DEPRECATED: boolean,
35
        _KEY_HANDLE_TITLE_CASE: boolean,
36
        _KEY_EXTRACT_UPPER_CASE_FROM_BRACES: boolean,
37
        _KEY_EXTRACT_ANY_CASE_FROM_BRACES: boolean,
38
        _KEY_EXPAND_AMPERSAND_WITH_SPACES: boolean,
39
        _KEY_EXPAND_ABBREVIATION_WITH_PUNCTUATION: boolean,
40
        _KEY_SIMPLE_ENGLISH_PLURAL_RULES: boolean,
41
    }
42
43
    DEFAULT_PARAMETERS = {
44
        _KEY_SUBTHESAURUS_TYPE_URI: '',
45
        _KEY_THESAURUS_RELATION_TYPE_URI: '',
46
        _KEY_THESAURUS_RELATION_IS_SPECIALISATION: False,
47
        _KEY_REMOVE_DEPRECATED: True,
48
        _KEY_HANDLE_TITLE_CASE: True,
49
        _KEY_EXTRACT_UPPER_CASE_FROM_BRACES: True,
50
        _KEY_EXTRACT_ANY_CASE_FROM_BRACES: False,
51
        _KEY_EXPAND_AMPERSAND_WITH_SPACES: True,
52
        _KEY_EXPAND_ABBREVIATION_WITH_PUNCTUATION: True,
53
        _KEY_SIMPLE_ENGLISH_PLURAL_RULES: False,
54
    }
55
56
    MODEL_FILE = 'stwfsa_predictor.zip'
57
58
    _model = None
59
60
    def initialize(self):
61
        if self._model is None:
62
            path = os.path.join(self.datadir, self.MODEL_FILE)
63
            self.debug(f'Loading STWFSA model from {path}.')
64
            if os.path.exists(path):
65
                self._model = StwfsapyPredictor.load(path)
66
                self.debug('Loaded model.')
67
            else:
68
                raise NotInitializedException(
69
                    f'Model not found at {path}',
70
                    backend_id=self.backend_id)
71
72
    def _train(self, corpus, params):
73
        if corpus == 'cached':
74
            raise NotSupportedException(
75
                'Training stwfsa project from cached data not supported.')
76
        if corpus.is_empty():
77
            raise NotSupportedException(
78
                'Cannot train stwfsa project with no documents.')
79
        self.debug("Transforming training data.")
80
        X = []
81
        y = []
82
        for doc in corpus.documents:
83
            X.append(doc.text)
84
            y.append(doc.uris)
85
        graph = self.project.vocab.as_graph()
86
        new_params = {
87
                key: self.STWFSA_PARAMETERS[key](val)
88
                for key, val
89
                in params.items()
90
                if key in self.STWFSA_PARAMETERS
91
            }
92
        p = StwfsapyPredictor(
93
            graph=graph,
94
            langs=frozenset([params['language']]),
95
            **new_params)
96
        p.fit(X, y)
97
        self._model = p
98
        p.store(os.path.join(self.datadir, self.MODEL_FILE))
99
100
    def _suggest(self, text, params):
101
        self.debug(
102
            f'Suggesting subjects for text "{text[:20]}..." (len={len(text)})')
103
        result = self._model.suggest_proba([text])[0]
104
        suggestions = []
105
        for uri, score in result:
106
            subject_id = self.project.subjects.by_uri(uri)
107
            if subject_id:
108
                label = self.project.subjects[subject_id][1]
109
            else:
110
                label = None
111
            suggestion = SubjectSuggestion(
112
                uri,
113
                label,
114
                None,
115
                score)
116
            suggestions.append(suggestion)
117
        return ListSuggestionResult(suggestions)
118