|
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
|
|
|
|