Passed
Pull Request — master (#663)
by Juho
02:51
created

annif.backend.dummy.DummyBackend._suggest_batch()   A

Complexity

Conditions 1

Size

Total Lines 2
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nop 3
dl 0
loc 2
rs 10
c 0
b 0
f 0
1
"""Dummy backend for testing basic interaction of projects and backends"""
2
3
4
from annif.suggestion import ListSuggestionResult, SubjectSuggestion
5
6
from . import backend
7
8
9
class DummyBackend(backend.AnnifLearningBackend):
10
    name = "dummy"
11
    initialized = False
12
    subject_id = 0
13
    is_trained = True
14
    modification_time = None
15
16
    def default_params(self):
17
        return backend.AnnifBackend.DEFAULT_PARAMETERS
18
19
    def initialize(self, parallel=False):
20
        self.initialized = True
21
22
    def _suggest(self, text, params):
23
        score = float(params.get("score", 1.0))
24
25
        # Ensure tests fail if "text" with wrong type ends up here
26
        assert isinstance(text, str)
27
28
        # Give no hits for no text
29
        if len(text) == 0:
30
            return ListSuggestionResult([])
31
32
        # allow overriding returned subject via uri parameter
33
        if "uri" in params:
34
            subject_id = self.project.subjects.by_uri(params["uri"])
35
        else:
36
            subject_id = self.subject_id
37
38
        return ListSuggestionResult(
39
            [SubjectSuggestion(subject_id=subject_id, score=score)]
40
        )
41
42
    def _suggest_batch(self, corpus, params):
43
        return [self._suggest(doc.text, params) for doc in corpus.documents]
44
45
    def _learn(self, corpus, params):
46
        # in this dummy backend we "learn" by picking up the subject ID
47
        # of the first subject of the first document in the learning set
48
        # and using that in subsequent analysis results
49
        for doc in corpus.documents:
50
            if doc.subject_set:
51
                self.subject_id = doc.subject_set[0]
52
            break
53