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