Passed
Pull Request — main (#762)
by Juho
06:26 queued 03:09
created

annif.cli_util   A

Complexity

Total Complexity 37

Size/Duplication

Total Lines 250
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 156
dl 0
loc 250
rs 9.44
c 0
b 0
f 0
wmc 37
1
"""Utility functions for Annif CLI commands"""
2
3
from __future__ import annotations
4
5
import binascii
6
import collections
7
import configparser
8
import importlib
9
import io
10
import itertools
11
import os
12
import pathlib
13
import shutil
14
import sys
15
import tempfile
16
import time
17
import zipfile
18
from fnmatch import fnmatch
19
from typing import TYPE_CHECKING
20
21
import click
22
import click_log
23
from flask import current_app
24
25
import annif
26
from annif.exception import ConfigurationException, OperationFailedException
27
from annif.project import Access
28
29
if TYPE_CHECKING:
30
    from datetime import datetime
31
32
    from click.core import Argument, Context, Option
33
34
    from annif.corpus.document import DocumentCorpus, DocumentList
35
    from annif.corpus.subject import SubjectIndex
36
    from annif.project import AnnifProject
37
    from annif.suggestion import SuggestionResult
38
    from annif.vocab import AnnifVocabulary
39
40
logger = annif.logger
41
42
43
def _set_project_config_file_path(
44
    ctx: Context, param: Option, value: str | None
45
) -> None:
46
    """Override the default path or the path given in env by CLI option"""
47
    with ctx.obj.load_app().app_context():
48
        if value:
49
            current_app.config["PROJECTS_CONFIG_PATH"] = value
50
51
52
def common_options(f):
53
    """Decorator to add common options for all CLI commands"""
54
    f = click.option(
55
        "-p",
56
        "--projects",
57
        help="Set path to project configuration file or directory",
58
        type=click.Path(dir_okay=True, exists=True),
59
        callback=_set_project_config_file_path,
60
        expose_value=False,
61
        is_eager=True,
62
    )(f)
63
    return click_log.simple_verbosity_option(logger)(f)
64
65
66
def project_id(f):
67
    """Decorator to add a project ID parameter to a CLI command"""
68
    return click.argument("project_id", shell_complete=complete_param)(f)
69
70
71
def backend_param_option(f):
72
    """Decorator to add an option for CLI commands to override BE parameters"""
73
    return click.option(
74
        "--backend-param",
75
        "-b",
76
        multiple=True,
77
        help="Override backend parameter of the config file. "
78
        + "Syntax: `-b <backend>.<parameter>=<value>`.",
79
    )(f)
80
81
82
def docs_limit_option(f):
83
    """Decorator to add an option for CLI commands to limit the number of documents to
84
    use"""
85
    return click.option(
86
        "--docs-limit",
87
        "-d",
88
        default=None,
89
        type=click.IntRange(0, None),
90
        help="Maximum number of documents to use",
91
    )(f)
92
93
94
def get_project(project_id: str) -> AnnifProject:
95
    """
96
    Helper function to get a project by ID and bail out if it doesn't exist"""
97
    try:
98
        return annif.registry.get_project(project_id, min_access=Access.private)
99
    except ValueError:
100
        click.echo("No projects found with id '{0}'.".format(project_id), err=True)
101
        sys.exit(1)
102
103
104
def get_vocab(vocab_id: str) -> AnnifVocabulary:
105
    """
106
    Helper function to get a vocabulary by ID and bail out if it doesn't
107
    exist"""
108
    try:
109
        return annif.registry.get_vocab(vocab_id, min_access=Access.private)
110
    except ValueError:
111
        click.echo(f"No vocabularies found with the id '{vocab_id}'.", err=True)
112
        sys.exit(1)
113
114
115
def make_list_template(*rows) -> str:
116
    """Helper function to create a template for a list of entries with fields of
117
    variable width. The width of each field is determined by the longest item in the
118
    field in the given rows."""
119
120
    max_field_widths = collections.defaultdict(int)
121
    for row in rows:
122
        for field_ind, item in enumerate(row):
123
            max_field_widths[field_ind] = max(max_field_widths[field_ind], len(item))
124
125
    return "  ".join(
126
        [
127
            f"{{{field_ind}: <{field_width}}}"
128
            for field_ind, field_width in max_field_widths.items()
129
        ]
130
    )
131
132
133
def format_datetime(dt: datetime | None) -> str:
134
    """Helper function to format a datetime object as a string in the local time."""
135
    if dt is None:
136
        return "-"
137
    return dt.astimezone().strftime("%Y-%m-%d %H:%M:%S")
138
139
140
def open_documents(
141
    paths: tuple[str, ...],
142
    subject_index: SubjectIndex,
143
    vocab_lang: str,
144
    docs_limit: int | None,
145
) -> DocumentCorpus:
146
    """Helper function to open a document corpus from a list of pathnames,
147
    each of which is either a TSV file or a directory of TXT files. For
148
    directories with subjects in TSV files, the given vocabulary language
149
    will be used to convert subject labels into URIs. The corpus will be
150
    returned as an instance of DocumentCorpus or LimitingDocumentCorpus."""
151
152
    def open_doc_path(path, subject_index):
153
        """open a single path and return it as a DocumentCorpus"""
154
        if os.path.isdir(path):
155
            return annif.corpus.DocumentDirectory(
156
                path, subject_index, vocab_lang, require_subjects=True
157
            )
158
        return annif.corpus.DocumentFile(path, subject_index)
159
160
    if len(paths) == 0:
161
        logger.warning("Reading empty file")
162
        docs = open_doc_path(os.path.devnull, subject_index)
163
    elif len(paths) == 1:
164
        docs = open_doc_path(paths[0], subject_index)
165
    else:
166
        corpora = [open_doc_path(path, subject_index) for path in paths]
167
        docs = annif.corpus.CombinedCorpus(corpora)
168
    if docs_limit is not None:
169
        docs = annif.corpus.LimitingDocumentCorpus(docs, docs_limit)
170
    return docs
171
172
173
def open_text_documents(paths: tuple[str, ...], docs_limit: int | None) -> DocumentList:
174
    """
175
    Helper function to read text documents from the given file paths. Returns a
176
    DocumentList object with Documents having no subjects. If a path is "-", the
177
    document text is read from standard input. The maximum number of documents to read
178
    is set by docs_limit parameter.
179
    """
180
181
    def _docs(paths):
182
        for path in paths:
183
            if path == "-":
184
                doc = annif.corpus.Document(text=sys.stdin.read(), subject_set=None)
185
            else:
186
                with open(path, errors="replace", encoding="utf-8-sig") as docfile:
187
                    doc = annif.corpus.Document(text=docfile.read(), subject_set=None)
188
            yield doc
189
190
    return annif.corpus.DocumentList(_docs(paths[:docs_limit]))
191
192
193
def show_hits(
194
    hits: SuggestionResult,
195
    project: AnnifProject,
196
    lang: str,
197
    file: io.TextIOWrapper | None = None,
198
) -> None:
199
    """
200
    Print subject suggestions to the console or a file. The suggestions are displayed as
201
    a table, with one row per hit. Each row contains the URI, label, possible notation,
202
    and score of the suggestion. The label is given in the specified language.
203
    """
204
    template = "<{}>\t{}\t{:.04f}"
205
    for hit in hits:
206
        subj = project.subjects[hit.subject_id]
207
        line = template.format(
208
            subj.uri,
209
            "\t".join(filter(None, (subj.labels[lang], subj.notation))),
210
            hit.score,
211
        )
212
        click.echo(line, file=file)
213
214
215
def parse_backend_params(
216
    backend_param: tuple[str, ...] | tuple[()], project: AnnifProject
217
) -> collections.defaultdict[str, dict[str, str]]:
218
    """Parse a list of backend parameters given with the --backend-param
219
    option into a nested dict structure"""
220
    backend_params = collections.defaultdict(dict)
221
    for beparam in backend_param:
222
        backend, param = beparam.split(".", 1)
223
        key, val = param.split("=", 1)
224
        _validate_backend_params(backend, beparam, project)
225
        backend_params[backend][key] = val
226
    return backend_params
227
228
229
def _validate_backend_params(backend: str, beparam: str, project: AnnifProject) -> None:
230
    if backend != project.config["backend"]:
231
        raise ConfigurationException(
232
            'The backend {} in CLI option "-b {}" not matching the project'
233
            " backend {}.".format(backend, beparam, project.config["backend"])
234
        )
235
236
237
def generate_filter_params(filter_batch_max_limit: int) -> list[tuple[int, float]]:
238
    limits = range(1, filter_batch_max_limit + 1)
239
    thresholds = [i * 0.05 for i in range(20)]
240
    return list(itertools.product(limits, thresholds))
241
242
243
def _is_train_file(fname):
244
    train_file_patterns = ("-train", "tmp-")
245
    for pat in train_file_patterns:
246
        if pat in fname:
247
            return True
248
    return False
249
250
251
def archive_dir(data_dir):
252
    fp = tempfile.TemporaryFile()
253
    path = pathlib.Path(data_dir)
254
    fpaths = [fpath for fpath in path.glob("**/*") if not _is_train_file(fpath.name)]
255
    with zipfile.ZipFile(fp, mode="w") as zfile:
256
        zfile.comment = bytes(
257
            f"Archived by Annif {importlib.metadata.version('annif')}",
258
            encoding="utf-8",
259
        )
260
        for fpath in fpaths:
261
            logger.debug(f"Adding {fpath}")
262
            zfile.write(fpath)
263
    fp.seek(0)
264
    return fp
265
266
267
def write_config(project):
268
    fp = tempfile.TemporaryFile(mode="w+t")
269
    config = configparser.ConfigParser()
270
    config[project.project_id] = project.config
271
    config.write(fp)  # This needs tempfile in text mode
272
    fp.seek(0)
273
    # But for upload fobj needs to be in binary mode
274
    return io.BytesIO(fp.read().encode("utf8"))
275
276
277
def upload_to_hf_hub(fileobj, filename, repo_id, token, commit_message):
278
    from huggingface_hub import HfApi
279
    from huggingface_hub.utils import HfHubHTTPError, HFValidationError
280
281
    api = HfApi()
282
    try:
283
        api.upload_file(
284
            path_or_fileobj=fileobj,
285
            path_in_repo=filename,
286
            repo_id=repo_id,
287
            token=token,
288
            commit_message=commit_message,
289
        )
290
    except (HfHubHTTPError, HFValidationError) as err:
291
        raise OperationFailedException(str(err))
292
293
294
def get_selected_project_ids_from_hf_hub(project_ids_pattern, repo_id, token, revision):
295
    all_repo_file_paths = _list_files_in_hf_hub(repo_id, token, revision)
296
    return [
297
        path.rsplit(".zip")[0].split("projects/")[1]  # TODO Try-catch this
298
        for path in all_repo_file_paths
299
        if fnmatch(path, f"projects/{project_ids_pattern}.zip")
300
    ]
301
302
303
def _list_files_in_hf_hub(repo_id, token, revision):
304
    from huggingface_hub import list_repo_files
305
    from huggingface_hub.utils import HfHubHTTPError, HFValidationError
306
307
    try:
308
        return [
309
            repofile
310
            for repofile in list_repo_files(
311
                repo_id=repo_id, token=token, revision=revision
312
            )
313
        ]
314
    except (HfHubHTTPError, HFValidationError) as err:
315
        raise OperationFailedException(str(err))
316
317
318
def download_from_hf_hub(filename, repo_id, token, revision):
319
    from huggingface_hub import hf_hub_download
320
    from huggingface_hub.utils import HfHubHTTPError, HFValidationError
321
322
    try:
323
        return hf_hub_download(
324
            repo_id=repo_id,
325
            filename=filename,
326
            token=token,
327
            revision=revision,
328
        )
329
    except (HfHubHTTPError, HFValidationError) as err:
330
        raise OperationFailedException(str(err))
331
332
333
def unzip(src_path, force):
334
    with zipfile.ZipFile(src_path, "r") as zfile:
335
        logger.debug(
336
            f"Extracting archive {src_path}; archive comment: "
337
            f"\"{str(zfile.comment, encoding='utf-8')}\""
338
        )
339
        for member in zfile.infolist():
340
            if os.path.exists(member.filename) and not force:
341
                if _is_existing_identical(member):
342
                    logger.debug(
343
                        f"Skipping unzip of {member.filename}; already in place"
344
                    )
345
                else:
346
                    click.echo(
347
                        f"Not overwriting {member.filename} (use --force to override)"
348
                    )
349
            else:
350
                logger.debug(f"Unzipping {member.filename}")
351
                zfile.extract(member)
352
                date_time = time.mktime(member.date_time + (0, 0, -1))
353
                os.utime(member.filename, (date_time, date_time))
354
355
356
def move_project_config(src_path, force):
357
    dst_path = os.path.join("projects.d", os.path.basename(src_path))
358
    if os.path.exists(dst_path) and not force:
359
        if _compute_crc32(dst_path) == _compute_crc32(src_path):
360
            logger.debug(
361
                f"Skipping move of {os.path.basename(src_path)}; already in place"
362
            )
363
        else:
364
            click.echo(f"Not overwriting {dst_path} (use --force to override)")
365
    else:
366
        shutil.copy(src_path, dst_path)
367
368
369
def _is_existing_identical(member):
370
    file_crc = _compute_crc32(member.filename)
371
    return file_crc == member.CRC
372
373
374
def _compute_crc32(path):
375
    if os.path.isdir(path):
376
        return 0
377
378
    size = 1024 * 1024 * 10  # 10 MiB chunks
379
    with open(path, "rb") as fp:
380
        crcval = 0
381
        while chunk := fp.read(size):
382
            crcval = binascii.crc32(chunk, crcval)
383
    return crcval
384
385
386
def get_vocab_id(config_path):
387
    config = configparser.ConfigParser()
388
    config.read(config_path)
389
    section = config.sections()[0]
390
    return config[section]["vocab"]
391
392
393
def _get_completion_choices(
394
    param: Argument,
395
) -> dict[str, AnnifVocabulary] | dict[str, AnnifProject] | list:
396
    if param.name == "project_id":
397
        return annif.registry.get_projects()
398
    elif param.name == "vocab_id":
399
        return annif.registry.get_vocabs()
400
    else:
401
        return []
402
403
404
def complete_param(ctx: Context, param: Argument, incomplete: str) -> list[str]:
405
    with ctx.obj.load_app().app_context():
406
        return [
407
            choice
408
            for choice in _get_completion_choices(param)
409
            if choice.startswith(incomplete)
410
        ]
411