annif.corpus.document   A
last analyzed

Complexity

Total Complexity 40

Size/Duplication

Total Lines 216
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 144
dl 0
loc 216
rs 9.2
c 0
b 0
f 0
wmc 40

19 Methods

Rating   Name   Duplication   Size   Complexity  
A DocumentDirectory._read_txt_file() 0 16 5
A DocumentDirectory._get_subject_filename() 0 11 3
A DocumentDirectory.__init__() 0 11 1
A DocumentDirectory.__iter__() 0 10 3
A LimitingDocumentCorpus.documents() 0 4 2
A TransformingDocumentCorpus.documents() 0 4 2
A DocumentFileTSV.__init__() 0 3 1
A DocumentFileCSV.documents() 0 16 5
A DocumentFileTSV._parse_tsv_line() 0 10 2
A DocumentList.__init__() 0 2 1
A DocumentFileCSV.__init__() 0 3 1
A DocumentFileCSV._check_fields() 0 3 1
A DocumentDirectory.documents() 0 15 4
A LimitingDocumentCorpus.__init__() 0 3 1
A DocumentFileTSV.documents() 0 9 4
A DocumentFileCSV._parse_row() 0 12 1
A TransformingDocumentCorpus.__init__() 0 3 1
A DocumentList.documents() 0 3 1
A DocumentFileCSV.is_csv_file() 0 6 1

How to fix   Complexity   

Complexity

Complex classes like annif.corpus.document often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1
"""Classes for supporting document corpora"""
2
3
from __future__ import annotations
4
5
import csv
6
import glob
7
import gzip
8
import os.path
9
import re
10
from itertools import islice
11
from typing import TYPE_CHECKING
12
13
import annif.util
14
from annif.exception import OperationFailedException
15
16
from .json import json_file_to_document
17
from .types import Document, DocumentCorpus, SubjectSet
18
19
if TYPE_CHECKING:
20
    from collections.abc import Iterator
21
22
    from annif.vocab import SubjectIndex
23
24
logger = annif.logger
25
26
27
class DocumentDirectory(DocumentCorpus):
28
    """A directory of files as a full text document corpus"""
29
30
    def __init__(
31
        self,
32
        path: str,
33
        subject_index: SubjectIndex | None = None,
34
        language: str | None = None,
35
        require_subjects: bool = False,
36
    ) -> None:
37
        self.path = path
38
        self.subject_index = subject_index
39
        self.language = language
40
        self.require_subjects = require_subjects
41
42
    def __iter__(self) -> Iterator[str]:
43
        """Iterate through the directory, yielding file paths with corpus documents."""
44
45
        # txt files
46
        for filename in sorted(glob.glob(os.path.join(self.path, "*.txt"))):
47
            yield filename
48
49
        # json files
50
        for filename in sorted(glob.glob(os.path.join(self.path, "*.json"))):
51
            yield filename
52
53
    @staticmethod
54
    def _get_subject_filename(filename: str) -> str | None:
55
        tsvfilename = re.sub(r"\.txt$", ".tsv", filename)
56
        if os.path.exists(tsvfilename):
57
            return tsvfilename
58
59
        keyfilename = re.sub(r"\.txt$", ".key", filename)
60
        if os.path.exists(keyfilename):
61
            return keyfilename
62
63
        return None
64
65
    def _read_txt_file(self, filename: str) -> Document | None:
66
        with open(filename, errors="replace", encoding="utf-8-sig") as docfile:
67
            text = docfile.read()
68
        if not self.require_subjects:
69
            return Document(text=text, subject_set=None, file_path=filename)
70
71
        subjfilename = self._get_subject_filename(filename)
72
        if subjfilename is None:
73
            # subjects required but not found, skipping this docfile
74
            return None
75
76
        with open(subjfilename, encoding="utf-8-sig") as subjfile:
77
            subjects = SubjectSet.from_string(
78
                subjfile.read(), self.subject_index, self.language
79
            )
80
        return Document(text=text, subject_set=subjects, file_path=filename)
81
82
    @property
83
    def documents(self) -> Iterator[Document]:
84
        for docfilename in self:
85
            if docfilename.endswith(".txt"):
86
                doc = self._read_txt_file(docfilename)
87
            else:
88
                doc = json_file_to_document(
89
                    docfilename,
90
                    self.subject_index,
91
                    self.language,
92
                    self.require_subjects,
93
                )
94
95
            if doc is not None:
96
                yield doc
97
98
99
class DocumentFileTSV(DocumentCorpus):
100
    """A TSV file as a corpus of documents with subjects"""
101
102
    def __init__(self, path: str, subject_index: SubjectIndex) -> None:
103
        self.path = path
104
        self.subject_index = subject_index
105
106
    @property
107
    def documents(self) -> Iterator[Document]:
108
        if self.path.endswith(".gz"):
109
            opener = gzip.open
110
        else:
111
            opener = open
112
        with opener(self.path, mode="rt", encoding="utf-8-sig") as tsvfile:
113
            for line in tsvfile:
114
                yield from self._parse_tsv_line(line)
115
116
    def _parse_tsv_line(self, line: str) -> Iterator[Document]:
117
        if "\t" in line:
118
            text, uris = line.split("\t", maxsplit=1)
119
            subject_ids = {
120
                self.subject_index.by_uri(annif.util.cleanup_uri(uri))
121
                for uri in uris.split()
122
            }
123
            yield Document(text=text, subject_set=SubjectSet(subject_ids))
124
        else:
125
            logger.warning('Skipping invalid line (missing tab): "%s"', line.rstrip())
126
127
128
class DocumentFileCSV(DocumentCorpus):
129
    """A CSV file as a corpus of documents with subjects"""
130
131
    def __init__(self, path: str, subject_index: SubjectIndex) -> None:
132
        self.path = path
133
        self.subject_index = subject_index
134
135
    @property
136
    def documents(self) -> Iterator[Document]:
137
        if self.path.endswith(".gz"):
138
            opener = gzip.open
139
        else:
140
            opener = open
141
        with opener(self.path, mode="rt", encoding="utf-8-sig") as csvfile:
142
            reader = csv.DictReader(csvfile)
143
            if not self._check_fields(reader):
144
                raise OperationFailedException(
145
                    f"Cannot parse CSV file {self.path}. "
146
                    + "The file must have a header row that defines at least "
147
                    + "the columns 'text' and 'subject_uris'."
148
                )
149
            for row in reader:
150
                yield from self._parse_row(row)
151
152
    def _parse_row(self, row: dict[str, str]) -> Iterator[Document]:
153
        subject_ids = {
154
            self.subject_index.by_uri(annif.util.cleanup_uri(uri))
155
            for uri in (row["subject_uris"] or "").strip().split()
156
        }
157
        metadata = {
158
            key: val for key, val in row.items() if key not in ("text", "subject_uris")
159
        }
160
        yield Document(
161
            text=(row["text"] or ""),
162
            subject_set=SubjectSet(subject_ids),
163
            metadata=metadata,
164
        )
165
166
    def _check_fields(self, reader: csv.DictReader) -> bool:
167
        fns = reader.fieldnames
168
        return fns is not None and "text" in fns and "subject_uris" in fns
169
170
    @staticmethod
171
    def is_csv_file(path: str) -> bool:
172
        """return True if the path looks like a CSV file"""
173
174
        path_lc = path.lower()
175
        return path_lc.endswith(".csv") or path_lc.endswith(".csv.gz")
176
177
178
class DocumentList(DocumentCorpus):
179
    """A document corpus based on a list of other iterable of Document
180
    objects"""
181
182
    def __init__(self, documents):
183
        self._documents = documents
184
185
    @property
186
    def documents(self):
187
        yield from self._documents
188
189
190
class TransformingDocumentCorpus(DocumentCorpus):
191
    """A document corpus that wraps another document corpus but transforms the
192
    documents using a given transform function"""
193
194
    def __init__(self, corpus, transform_fn):
195
        self._orig_corpus = corpus
196
        self._transform_fn = transform_fn
197
198
    @property
199
    def documents(self):
200
        for doc in self._orig_corpus.documents:
201
            yield self._transform_fn(doc)
202
203
204
class LimitingDocumentCorpus(DocumentCorpus):
205
    """A document corpus that wraps another document corpus but limits the
206
    number of documents to a given limit"""
207
208
    def __init__(self, corpus, docs_limit):
209
        self._orig_corpus = corpus
210
        self.docs_limit = docs_limit
211
212
    @property
213
    def documents(self):
214
        for doc in islice(self._orig_corpus.documents, self.docs_limit):
215
            yield doc
216