Passed
Pull Request — master (#663)
by Juho
03:15
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 4
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
        # allow overriding returned subject via uri parameter
29
        if "uri" in params:
30
            subject_id = self.project.subjects.by_uri(params["uri"])
31
        else:
32
            subject_id = self.subject_id
33
34
        return ListSuggestionResult(
35
            [SubjectSuggestion(subject_id=subject_id, score=score)]
36
        )
37
38
    def _suggest_batch(self, corpus, transform, params):
39
        return [self._suggest(doc.text, params) for doc in corpus.documents]
40
41
    def _learn(self, corpus, params):
42
        # in this dummy backend we "learn" by picking up the subject ID
43
        # of the first subject of the first document in the learning set
44
        # and using that in subsequent analysis results
45
        for doc in corpus.documents:
46
            if doc.subject_set:
47
                self.subject_id = doc.subject_set[0]
48
            break
49