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