diff --git a/CHANGES.rst b/CHANGES.rst index 5ea6d03..0ecf643 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -1,5 +1,24 @@ Unreleased ========== +``tfmgr sanitize`` becomes a linter, and ``tfmgr add`` stops changing data silently. + +* ``tfmgr sanitize`` reports the image rules (TF701 to TF711) and fixes what it can: + ``--check`` (the default) lists the problems, ``--fix`` applies the safe fixes (values + and world coordinates kept), ``--fix-unsafe`` also those that rescale, round or move. + The silent int16 cast, probseg rescaling and intensity normalization are gone (the + latter for good), and the swapped ``--force-dtype``/``--deoblique`` options with them. +* New rules: TF707 not-ras, TF708 oblique, TF709 storage-dtype, TF710 image-units and + TF711 unreadable-image. Issues say whether ``--fix`` or ``--fix-unsafe`` corrects them. +* ``tfmgr add`` copies the template without changing it, validates it strictly (images + included) before uploading anything, and records each step in a work directory + (``--workdir``, by default in the user cache directory), so a failed run resumes where + it stopped. Failing commands stop it. It reconfigures existing GIN and GitHub + siblings instead of replacing them, opens the pull request with ``gh`` (``hub`` is no + longer needed), names the intake file ``tpl-.toml``, honours ``--nprocs``, asks + for an SPDX license identifier, and writes the ``SPDX-License-Identifier`` header. + +26.0.0rc1 (December 2, 2026) +============================ TemplateFlow 2.0 rule set and validator. * New ``tfmgr validate`` checks templates (directories, Archive checkouts or skeleton zips) diff --git a/README.rst b/README.rst index 23f9832..7472f27 100644 --- a/README.rst +++ b/README.rst @@ -19,4 +19,36 @@ and values are only checked with ``--level content``, which needs ``tfmanager[co and the images' data. The command exits with 1 when there are errors, and 2 when it could not run. -Adding a template needs DataLad and the TemplateFlow client: ``pip install tfmanager[add]``. +Checking and fixing images +-------------------------- +``tfmgr sanitize`` works like a linter on the images of a template (rules TF701 to +TF711; needs ``tfmanager[content]``):: + + tfmgr sanitize tpl-MyTemplate # --check (the default): list the problems + tfmgr sanitize --fix tpl-MyTemplate # apply the safe fixes + tfmgr sanitize --fix-unsafe tpl-MyTemplate # apply all of them + +Safe fixes keep the values and the world coordinates of every voxel: reorienting to RAS, +setting unset units to mm, storing labels as the smallest unsigned integer type, and +integer-valued images as int16. Unsafe fixes change values or move the image: rescaling +probabilities into [0, 1], removing the rotation of oblique images, setting the qform to +the sform when they disagree, and storing floating-point images as int16 with a slope and +an intercept. When a fix moves the grid of every image of a resolution, the ``res`` block +of template_description.json is updated to match. Annexed images are replaced by regular +files (``datalad save`` annexes them again). + +Adding a template +----------------- +Adding a template needs DataLad, the GitHub CLI (``gh``) and the TemplateFlow client: +``pip install tfmanager[add]``:: + + tfmgr add MyTemplate --path tpl-MyTemplate + +``tfmgr add`` asks for the metadata that template_description.json misses (with an SPDX +license identifier), copies the template into a DataLad dataset without changing it +(``--fix`` and ``--fix-unsafe`` apply ``tfmgr sanitize`` fixes to the copies), and checks +it with ``tfmgr validate --mode strict --level content``: errors stop it before anything +is uploaded. The data then go to GIN, the dataset to GitHub, and a pull request proposes +the template to the Archive. Each step is recorded in a work directory (by default in +the user's cache directory; ``--workdir`` sets another one), so a run that fails resumes +where it stopped; ``--restart`` starts again. diff --git a/pyproject.toml b/pyproject.toml index 07cb122..50fcef2 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -18,5 +18,7 @@ quote-style = "single" [tool.ruff.lint] select = ["E", "F", "W", "I", "UP", "B"] -# cli.py, io.py and utils.py predate the linter -per-file-ignores = { "{setup.py,tfmanager/cli.py,tfmanager/io.py,tfmanager/utils.py}" = ["E", "W", "I", "UP", "B"] } + +# setup.py predates the linter +[tool.ruff.lint.per-file-ignores] +"setup.py" = ["E", "W", "I", "UP", "B"] diff --git a/setup.cfg b/setup.cfg index 10a5b69..5605f0d 100644 --- a/setup.cfg +++ b/setup.cfg @@ -52,6 +52,7 @@ add = datalad >= 0.16 nibabel numpy + platformdirs templateflow >= 0.4.2 content = nibabel diff --git a/tfmanager/add.py b/tfmanager/add.py new file mode 100644 index 0000000..c696d0a --- /dev/null +++ b/tfmanager/add.py @@ -0,0 +1,563 @@ +"""``tfmgr add``: propose a new template to the TemplateFlow Archive. + +The work happens in a work directory (by default, in the user's cache directory), and each +step is recorded in its ``state.json``, so that a run that fails resumes where it stopped: + +1. ``copy``: the source folder is copied, byte for byte, into a DataLad dataset, with the + template's metadata and LICENSE (``--fix``/``--fix-unsafe`` then apply + ``tfmgr sanitize`` to the copies); +2. ``validate``: the TemplateFlow rules, strict and with image content: errors stop the + run here, before anything is uploaded; +3. ``save``: ``datalad save``; +4. ``gin``: the data go to GIN, which the dataset records as its common data source; +5. ``github``: the dataset goes to the contributor's GitHub account; +6. ``pull-request``: ``tpl-.toml`` on a branch of the contributor's fork of the + Archive, and a pull request to its intake branch. + +When the source folder changes, the steps run again from ``copy``. +""" + +from __future__ import annotations + +import datetime +import filecmp +import hashlib +import json +import os +import re +import shutil +from collections.abc import Callable +from dataclasses import dataclass, field +from pathlib import Path + +from .io import run_command +from .tables import dump_json + +STEPS = ('copy', 'validate', 'save', 'gin', 'github', 'pull-request') +UPSTREAM = 'templateflow/templateflow' +INTAKE_BRANCH = 'tpl-intake' +#: Files of the dataset that the copy step writes (not copied from the source) +GENERATED = ('template_description.json', 'LICENSE', 'CHANGES') +#: Files of the dataset that are never deleted when mirroring the source +PROTECTED = ('.datalad', '.git', '.gitattributes', '.github', '.gitmodules') +ANNEX_KEY = re.compile(r'^MD5E-s(?P[0-9]+)--(?P[0-9a-f]{32})') + + +class AddError(RuntimeError): + """``tfmgr add`` cannot go on (the message says why and what to do).""" + + +def default_workdir(template_id: str) -> Path: + from platformdirs import user_cache_dir + + return Path(user_cache_dir('tfmanager')) / f'tpl-{template_id}' + + +def _visible(root: Path): + for dirpath, dirnames, filenames in os.walk(root): + dirnames[:] = sorted(d for d in dirnames if not d.startswith('.')) + for name in sorted(filenames): + if not name.startswith('.'): + yield Path(dirpath, name).relative_to(root) + + +def fingerprint(source: Path) -> str: + """Changes when a file of ``source`` is added, removed, or its content changes. + + Contents are hashed: sizes and modification times can stay the same after an edit + (``cp -p``, ``touch -r``). + """ + digest = hashlib.sha256() + for rel in _visible(source): + digest.update(f'{rel.as_posix()}\0{_md5(source / rel)}\n'.encode()) + return digest.hexdigest() + + +@dataclass +class State: + """Progress of ``tfmgr add`` (``/state.json``).""" + + path: Path + data: dict = field(default_factory=dict) + + @classmethod + def load(cls, workdir: Path) -> State: + path = workdir / 'state.json' + data = json.loads(path.read_text()) if path.exists() else {} + return cls(path, data) + + def save(self) -> None: + self.path.parent.mkdir(parents=True, exist_ok=True) + self.path.write_text(dump_json(self.data)) + + def done(self, step: str) -> bool: + return step in self.data.get('done', []) + + def mark(self, step: str) -> None: + self.data['done'] = [s for s in STEPS if s == step or self.done(s)] + self.save() + + def reset_from(self, step: str) -> None: + index = STEPS.index(step) + self.data['done'] = [s for s in self.data.get('done', []) if STEPS.index(s) < index] + self.save() + + +def _md5(path: Path) -> str: + digest = hashlib.md5() # noqa: S324 (git-annex MD5E keys) + with path.open('rb') as handle: + while chunk := handle.read(1 << 20): + digest.update(chunk) + return digest.hexdigest() + + +def _same(src: Path, dest: Path) -> bool: + """Whether ``dest`` (a file, or an annex link) already holds the content of ``src``.""" + if dest.is_symlink(): + match = ANNEX_KEY.match(Path(os.readlink(dest)).name) + return bool( + match and int(match['size']) == src.stat().st_size and match['md5'] == _md5(src) + ) + return dest.is_file() and filecmp.cmp(src, dest, shallow=False) + + +def mirror(source: Path, dest: Path) -> list[str]: + """Make ``dest`` hold the visible files of ``source``. Returns the paths that changed.""" + changed = [] + wanted = {rel for rel in _visible(source) if rel.as_posix() not in GENERATED} + for rel in sorted(wanted): + target = dest / rel + if (target.exists() or target.is_symlink()) and _same(source / rel, target): + continue + target.parent.mkdir(parents=True, exist_ok=True) + if target.is_symlink() or target.exists(): + target.unlink() + shutil.copy2(source / rel, target) + changed.append(rel.as_posix()) + for rel in list(_visible(dest)): + top = rel.parts[0] + if rel in wanted or top in PROTECTED or rel.as_posix() in GENERATED: + continue + (dest / rel).unlink() + changed.append(rel.as_posix()) + return changed + + +#: License texts tfmgr can write when the source has no LICENSE file +BUNDLED_LICENSES = {'CC0-1.0': 'CC0.LICENSE', 'CC-BY-4.0': 'CC-BY.LICENSE'} +DOI = re.compile(r'^(?:doi:\s*|https?://(?:dx\.)?doi\.org/)?(?P10\.[0-9]{4,}/\S+)$', re.I) +#: Questions ``prepare_metadata`` asks: ``ask(key, question) -> answer`` +Ask = Callable[[str, str], str] + + +def _pattern(name: str) -> re.Pattern: + from .ruleset import load_ruleset + + return re.compile(load_ruleset().description_schema['$defs'][name]['pattern']) + + +def normalize_reference(ref: str) -> str: + """DOIs as https://doi.org/ URLs (``doi:10.1/x`` and ``10.1/x`` included). + + >>> normalize_reference('doi:10.1101/2021.02.10.430678') + 'https://doi.org/10.1101/2021.02.10.430678' + >>> normalize_reference('https://example.org/x') + 'https://example.org/x' + """ + ref = ref.strip().strip('"') + match = DOI.match(ref) + return f'https://doi.org/{match["doi"]}' if match else ref + + +def _license_file(source: Path) -> Path | None: + for name in ('LICENSE', 'LICENCE', 'COPYING', 'LICENSE.txt', 'LICENSE.md'): + if (source / name).is_file(): + return source / name + return None + + +def prepare_license( + source: Path, declared: str | None, ask: Ask, answers: dict | None = None +) -> tuple[str, str]: + """The SPDX expression of the template and the text of its LICENSE file.""" + from importlib.resources import files + + from . import licenses + + answers = {} if answers is None else answers + path = _license_file(source) + text = path.read_text() if path else None + expression = licenses.header(text) or declared + if not expression or not licenses.check(expression).valid: + expression = _ask_until( + ask, + 'License', + 'SPDX license identifier of the template (for example CC-BY-4.0 or CC0-1.0; ' + 'LicenseRef- for other terms, with their text in LICENSE)', + lambda text: licenses.check(text).valid, + answers, + ) + result = licenses.check(expression) + if not result.valid: + hint = '; '.join(f'{k}: did you mean {licenses.suggest(k)}?' for k in result.invalid) + raise AddError(f'{expression!r} is not an SPDX license expression. {hint}'.strip()) + if result.software_only: + raise AddError( + f'{", ".join(result.software_only)}: GPL licenses are for software, and ' + 'TemplateFlow does not accept them for data.' + ) + expression = result.normalized + header = f'SPDX-License-Identifier: {expression}' + if text is not None: + declared_header = licenses.header(text) + if declared_header is None: + return expression, f'{header}\n\n{text}' + if not licenses.same(declared_header, expression): + raise AddError( + f'LICENSE says {declared_header!r}, but the template declares {expression!r}.' + ) + return expression, text + if expression not in BUNDLED_LICENSES: + raise AddError( + f'Write the text of {expression} in a LICENSE file of the template ' + '(tfmgr can only write CC0-1.0 and CC-BY-4.0 for you).' + ) + bundled = (files('tfmanager') / 'data' / BUNDLED_LICENSES[expression]).read_text() + return expression, f'{header}\n\n{bundled}' + + +def _ask_until( + ask: Ask, key: str, question: str, valid: Callable[[str], bool], answers: dict +) -> str: + """An answer (remembered in ``answers`` from earlier runs, or asked up to 3 times).""" + if key in answers and valid(answers[key]): + return answers[key] + for _ in range(3): + answer = ask(key, question).strip() + if valid(answer): + answers[key] = answer + return answer + question = f'{answer!r} is not valid. {question}' + raise AddError(f'No valid {key} was given.') + + +def prepare_metadata( + source: Path, template_id: str, ask: Ask, answers: dict | None = None +) -> tuple[dict, str]: + """template_description.json and the LICENSE text, asking for what is missing. + + ``answers`` keeps the answers (a run that resumes does not ask again). + """ + answers = {} if answers is None else answers + from .ruleset import TEMPLATEFLOW_VERSION, load_ruleset + + if not (source / 'README.md').is_file(): + raise AddError( + 'README.md is missing: write a summary of how the template was built ' + '(subjects, acquisition, registration and averaging, references).' + ) + path = source / 'template_description.json' + metadata = json.loads(path.read_text()) if path.is_file() else {} + if not isinstance(metadata, dict): + raise AddError('template_description.json is not a JSON object.') + metadata['Identifier'] = template_id + + if not str(metadata.get('Name', '')).strip(): + metadata['Name'] = _ask_until( + ask, 'Name', 'A short description of the template (its "Name")', bool, answers + ) + + person = _pattern('person') + authors = [a.strip() for a in metadata.get('Authors') or [] if str(a).strip()] + if not authors or not all(person.match(a) for a in authors): + answer = _ask_until( + ask, + 'Authors', + 'Authors, as "Family I" (family name, then initials), separated by semicolons', + lambda text: all(person.match(a.strip()) for a in text.split(';') if a.strip()), + answers, + ) + authors = [a.strip() for a in answer.split(';') if a.strip()] + metadata['Authors'] = authors + + species = _pattern('species') + if not isinstance(metadata.get('Species'), list) and not species.match( + str(metadata.get('Species', '')) + ): + metadata['Species'] = _ask_until( + ask, + 'Species', + 'Species, as its NCBI Taxonomy scientific name (for example Homo sapiens)', + lambda text: bool(species.match(text)), + answers, + ) + + refs = [normalize_reference(r) for r in metadata.get('ReferencesAndLinks') or [] if r] + if not refs: + answer = _ask_until( + ask, + 'ReferencesAndLinks', + 'Publications (DOIs) and links describing the template, separated by spaces', + bool, + answers, + ) + refs = [normalize_reference(r) for r in answer.split()] + metadata['ReferencesAndLinks'] = refs + + rrid = str(metadata.get('RRID') or '').strip() + if rrid and not rrid.startswith('RRID:'): + rrid = f'RRID:{rrid}' + if rrid: + metadata['RRID'] = rrid + + expression, license_text = prepare_license(source, metadata.get('License'), ask, answers) + metadata['License'] = expression + metadata['BIDSVersion'] = load_ruleset().bids_version + metadata['TemplateFlowVersion'] = TEMPLATEFLOW_VERSION + return metadata, license_text + + +def pr_message(metadata: dict, template_id: str, gh_user: str, validation: str) -> str: + cohorts = metadata.get('cohort') or {} + return '\n'.join( + [ + f'## {metadata.get("Name", "")}', + '', + f'Identifier: `{template_id}`', + f'DataLad dataset: https://github.com/{gh_user}/tpl-{template_id}', + '', + '### Authors', + ', '.join(metadata.get('Authors', [])) + '.', + '', + '### License', + f'`{metadata.get("License", "")}`', + '', + '### Cohorts', + f'{len(cohorts)} cohorts.' if cohorts else 'No cohorts.', + '', + '### References and links', + '\n'.join(f'- {ref}' for ref in metadata.get('ReferencesAndLinks', [])) or 'N/A', + '', + '### Validation', + validation, + '', + ] + ) + + +@dataclass +class Add: + """The steps of ``tfmgr add`` for one template.""" + + template_id: str + source: Path + workdir: Path + metadata: dict + license_text: str + gh_user: str + gh_token: str + nprocs: int = 1 + fix: str | None = None + """``'safe'`` or ``'unsafe'``: apply ``tfmgr sanitize`` fixes to the copies.""" + echo: Callable[[str], None] = print + + @property + def dataset(self) -> Path: + return self.workdir / f'tpl-{self.template_id}' + + @property + def branch(self) -> str: + return f'pr/tpl-{self.template_id}' + + def run(self) -> State: + state = State.load(self.workdir) + source = fingerprint(self.source) + inputs = {'source': source, 'metadata': self.metadata, 'fix': self.fix} + if any(state.data.get(k) != v for k, v in inputs.items()): + if state.data.get('done'): + self.echo('The source or its metadata changed: starting again from the copy.') + state.data.update(inputs) + state.reset_from('copy') + for step in STEPS: + if state.done(step): + self.echo(f'[{step}] done in a previous run.') + continue + self.echo(f'[{step}] ...') + getattr(self, f'step_{step.replace("-", "_")}')(state) + state.mark(step) + return state + + # Steps ------------------------------------------------------------------------------ + + def step_copy(self, state: State) -> None: + from datalad import api as dl + + dataset = self.dataset + if not (dataset / '.datalad').exists(): + dl.create( + path=str(dataset), + cfg_proc='text2git', + initopts={'initial-branch': 'main'}, + description=self.metadata['Name'], + on_failure='stop', + ) + gitattributes = dataset / '.gitattributes' + text = gitattributes.read_text().rstrip('\n') + gitattributes.write_text(f'{text}\n*.gii annex.largefiles=anything\n') + changed = mirror(self.source, dataset) + self.echo(f' {len(changed)} files copied or removed.') + (dataset / 'template_description.json').write_text(dump_json(self.metadata)) + (dataset / 'LICENSE').write_text(self.license_text) + if (self.source / 'CHANGES').exists(): + shutil.copy2(self.source / 'CHANGES', dataset / 'CHANGES') + else: + today = datetime.date.today().isoformat() + (dataset / 'CHANGES').write_text(f'{today}: proposed with tfmgr add.\n') + if self.fix: + from .sanitize import fix + + fixed, updated = fix(dataset, unsafe=self.fix == 'unsafe') + for path, codes in fixed.items(): + self.echo(f' fixed {path}: {", ".join(codes)}') + for line in updated: + self.echo(f' updated {line}') + + def step_validate(self, state: State) -> None: + from .tree import DirectoryTree + from .validate import render, summary, validate_template + + issues = validate_template( + DirectoryTree(self.dataset, trusted=True), mode='strict', level='content' + ) + if any(i.code == 'TF700' for i in issues): + raise AddError('The images could not be checked: install tfmanager[add].') + meta = {'ruleset': _ruleset_version(), 'mode': 'strict', 'level': 'content'} + state.data['validation'] = render(issues, 'markdown', meta) + state.save() + if summary(issues)['error']: + raise AddError( + render(issues, 'human', meta) + + '\n\nFix these problems in the source folder and run `tfmgr add` again ' + '(`tfmgr sanitize --check` lists the image problems tfmgr can fix).' + ) + self.echo(f' {render(issues, "human", meta).splitlines()[-1]}') + + def step_save(self, state: State) -> None: + from datalad import api as dl + + dl.save( + dataset=str(self.dataset), + message=f'add(tpl-{self.template_id}): contents proposed with tfmgr add', + on_failure='stop', + ) + + def step_gin(self, state: State) -> None: + # GIN stores the data (annexed files). Once it holds them, publishing it as the + # dataset's common data source records it in the dataset, so anyone cloning the + # GitHub repository (reviewers, the intake previews, the Archive's intake) gets + # the data from GIN. Tokens are looked up by credential name (DATALAD_CREDENTIAL_ + # GIN_TOKEN), and an existing sibling is reconfigured, never replaced. + from datalad import api as dl + + dataset = str(self.dataset) + dl.create_sibling_gin( + f'tpl-{self.template_id}', + dataset=dataset, + credential='gin', + name='gin', + access_protocol='https-ssh', + existing='reconfigure', + description=self.metadata['Name'], + on_failure='stop', + ) + dl.push(dataset=dataset, to='gin', jobs=self.nprocs, on_failure='stop') + dl.siblings( + action='configure', + dataset=dataset, + name='gin', + as_common_datasrc='gin-src', + on_failure='stop', + ) + + def step_github(self, state: State) -> None: + from datalad import api as dl + + dataset = str(self.dataset) + dl.create_sibling_github( + reponame=f'tpl-{self.template_id}', + dataset=dataset, + name='github', + credential='github', + publish_depends='gin', + existing='reconfigure', + access_protocol='ssh', + on_failure='stop', + ) + dl.push(dataset=dataset, to='github', jobs=self.nprocs, on_failure='stop') + + def step_pull_request(self, state: State) -> None: + env = {'GH_TOKEN': self.gh_token} + found = run_command( + [ + 'gh', 'pr', 'list', '--repo', UPSTREAM, '--head', self.branch, + '--state', 'open', '--json', 'url', '--jq', '.[0].url // ""', + ], + env=env, + ).stdout.strip() # fmt: skip + if found: + self.echo(f' The pull request is open: {found}') + state.data['pull_request'] = found + return + + run_command(['gh', 'repo', 'fork', UPSTREAM, '--clone=false'], env=env) + repo = self.workdir / 'templateflow' + shutil.rmtree(repo, ignore_errors=True) + run_command( + [ + 'git', 'clone', '--depth', '1', '--branch', INTAKE_BRANCH, + f'https://github.com/{UPSTREAM}.git', str(repo), + ] + ) # fmt: skip + run_command(['git', '-C', str(repo), 'checkout', '-b', self.branch]) + import toml + + intake = f'tpl-{self.template_id}.toml' + (repo / intake).write_text(toml.dumps({'github': {'user': self.gh_user}})) + run_command(['git', '-C', str(repo), 'add', intake]) + run_command( + [ + 'git', '-C', str(repo), 'commit', '-m', + f'add(tpl-{self.template_id}): create intake file', + ] + ) # fmt: skip + run_command( + [ + 'git', '-C', str(repo), + '-c', 'credential.helper=', '-c', 'credential.helper=!gh auth git-credential', + 'push', '--force', f'https://github.com/{self.gh_user}/templateflow.git', + f'HEAD:refs/heads/{self.branch}', + ], + env=env, + ) # fmt: skip + message = self.workdir / 'message.md' + message.write_text( + pr_message( + self.metadata, self.template_id, self.gh_user, state.data.get('validation', '') + ) + ) + url = run_command( + [ + 'gh', 'pr', 'create', '--repo', UPSTREAM, '--base', INTAKE_BRANCH, + '--head', f'{self.gh_user}:{self.branch}', + '--title', f'ADD: ``tpl-{self.template_id}``', '--body-file', str(message), + ], + env=env, + ).stdout.strip() # fmt: skip + self.echo(f' Pull request: {url}') + state.data['pull_request'] = url + + +def _ruleset_version() -> str: + from .ruleset import load_ruleset + + return load_ruleset().version diff --git a/tfmanager/cli.py b/tfmanager/cli.py index feb17c8..d336d77 100644 --- a/tfmanager/cli.py +++ b/tfmanager/cli.py @@ -1,396 +1,157 @@ """CLI.""" -import os -from os import cpu_count, getcwd, chdir -import datetime + import json +import os +from os import cpu_count, getcwd from pathlib import Path + import click -from tempfile import TemporaryDirectory -import toml -from importlib.resources import files as _pkg_files def validate_name(ctx, param, value): """Check whether this template already exists in the Archive.""" from templateflow.api import templates - value = value[4:] if value.startswith("tpl-") else value + value = value[4:] if value.startswith('tpl-') else value if value in templates(): - raise click.BadParameter( - f"A template with name {value} already exists in the Archive." - ) + raise click.BadParameter(f'A template with name {value} already exists in the Archive.') return value @click.group() -@click.version_option(message="TF Archive manager %(version)s") +@click.version_option(message='TF Archive manager %(version)s') def cli(): """The TemplateFlow Archive manager assists you in adding and updating templates.""" pass @cli.command() -@click.argument("template_id", callback=validate_name) +@click.argument('template_id', callback=validate_name) @click.option( - "--gh-user", - envvar="GITHUB_USER", + '--gh-user', + envvar='GITHUB_USER', ) @click.password_option( - "--gh-token", - prompt="GitHub personal authentication token", + '--gh-token', + prompt='GitHub personal authentication token', confirmation_prompt=False, - envvar="GITHUB_TOKEN", + envvar='GITHUB_TOKEN', ) @click.password_option( - "--gin-token", - prompt="GIN access token (https://gin.g-node.org/user/settings/applications)", + '--gin-token', + prompt='GIN access token (https://gin.g-node.org/user/settings/applications)', confirmation_prompt=False, - envvar="GIN_TOKEN", + envvar='GIN_TOKEN', ) -@click.option("--path", type=click.Path(exists=True)) -@click.option("-j", "--nprocs", type=click.IntRange(min=1), default=cpu_count()) -def add( - template_id, - gh_user, - gh_token, - gin_token, - path, - nprocs, -): +@click.option('--path', type=click.Path(exists=True, file_okay=False)) +@click.option('-j', '--nprocs', type=click.IntRange(min=1), default=cpu_count()) +@click.option( + '--workdir', + type=click.Path(file_okay=False), + help='Where the dataset is prepared, and progress recorded ' + "(default: tfmanager's cache directory). Run again to resume.", +) +@click.option( + '--fix', + 'fix', + flag_value='safe', + default=None, + help='Apply the safe fixes of `tfmgr sanitize` to the copied images.', +) +@click.option( + '--fix-unsafe', + 'fix', + flag_value='unsafe', + help='Apply all the fixes of `tfmgr sanitize` (rescaling, rounding) to the copies.', +) +@click.option('--restart', is_flag=True, help='Forget earlier progress and start again.') +def add(template_id, gh_user, gh_token, gin_token, path, nprocs, workdir, fix, restart): """Add a new template. - The template's data are uploaded to GIN (https://gin.g-node.org), its DataLad dataset - is published on GitHub, and a pull request proposes it to the TemplateFlow Archive. + The template is copied into a DataLad dataset and checked against the TemplateFlow + rules; its data are uploaded to GIN (https://gin.g-node.org), the dataset is + published on GitHub, and a pull request proposes it to the TemplateFlow Archive. + Each step is recorded, so a run that fails resumes where it stopped. """ - from .io import run_command - from .utils import copy_template - import shutil - from datalad import api as dl + from .add import Add, AddError, State, default_workdir, prepare_metadata if not gh_user or not gh_token: - raise click.BadParameter("Insufficient secrets to login into GitHub") + raise click.BadParameter('Insufficient secrets to login into GitHub') if not gin_token: - raise click.BadParameter("A GIN access token is needed to upload the data") - - os.environ["DATALAD_CREDENTIAL_GITHUB_TOKEN"] = gh_token - os.environ["DATALAD_CREDENTIAL_GIN_TOKEN"] = gin_token - - path = Path(path or f"tpl-{template_id}").absolute() - cwd = Path.cwd() - - if not path.exists(): - raise click.UsageError(f"<{path}> does not exist.") - - metadata = {} - - # Check metadata - if (path / "template_description.json").exists(): - metadata = json.loads((path / "template_description.json").read_text()) - metadata["Identifier"] = template_id - - # Check license - license_path = path / "LICENSE" - if not license_path.exists(): - license_path = path / "LICENCE" - if not license_path.exists(): - license_path = path / "COPYING" - - if not license_path.exists(): - license_prompt = click.prompt( - text="""\ -A LICENSE file MUST be distributed with the template. The TemplateFlow Manager can \ -set a license (either CC0 or CC-BY) for you.""", - type=click.Choice(("CC0", "CC-BY", "Custom (abort)")), - default="Custom (abort)", - ) - if license_prompt == "Custom (abort)": - raise click.UsageError( - "Cannot proceed without a valid license. Please write a LICENSE " - "file before uploading." - ) - - license_path = Path(str(_pkg_files("tfmanager") / "data" / f"{license_prompt}.LICENSE")) - metadata["License"] = license_prompt - - # Check RRID - if not metadata.get("RRID"): - rrid = click.prompt( - text="Has a RRID (research resource ID) already been assigned?", - type=str, - default='' - ) or None - - if rrid: - metadata["RRID"] = rrid - - # Check short description - if not metadata.get("Name", "").strip(): - short_desc = click.prompt( - text="""\ -The "Name" metadata is not found within the file. \ -Please provide a short description for this resource.""", - type=str, - ) - - if not short_desc: - raise click.UsageError( - "Cannot proceed without a short description." - ) - - metadata["Name"] = short_desc - - # Check authors - authors_prompt = [a.strip() for a in metadata.get("Authors", []) if a.strip()] - if not authors_prompt: - authors_prompt = [ - n.strip() for n in click.prompt( - text="""\ -The "Authors" metadata is not found within the file. \ -Please provide a list of authors separated by semicolon (;) in format.""", - type=str, - ).split(";") - if n - ] - if not authors_prompt: - click.confirm("No authors were given, do you want to continue?", abort=True) - - metadata["Authors"] = authors_prompt - - # Check references - refs_prompt = [ - f"""\ -{'https://doi.org/' if not a.strip().startswith('http') else ''}\ -{a.replace("doi:", "").strip()}""" - for a in metadata.get("ReferencesAndLinks", []) if a.strip() - ] - if not refs_prompt: - refs_prompt = [ - n.replace('"', "").strip() for n in click.prompt( - text="""\ -The "ReferencesAndLinks" metadata is not found within the file. \ -Please provide a list of links and publications within double-quotes \ -(for example, "doi:10.1101/2021.02.10.430678") and separated by spaces (< >).""", - type=str, - ).split(" ") - if n - ] - if not refs_prompt: - click.confirm("No authors were given, do you want to continue?", abort=True) - metadata["ReferencesAndLinks"] = refs_prompt - - with TemporaryDirectory() as tmpdir: - repodir = Path(tmpdir) / "templateflow" - - # Clone root /templateflow project - fork if necessary - click.echo(f"Preparing Pull-Request (wd={tmpdir}).") - clone = run_command( - f"git clone https://github.com/{gh_user}/templateflow.git " - "--branch tpl-intake --single-branch", - cwd=tmpdir, - capture_output=False, - ) - if clone.returncode != 0: - run_command( - "hub clone templateflow/templateflow", - cwd=tmpdir, - capture_output=False, - env={"GITHUB_TOKEN": gh_token}, - ) - run_command( - "hub fork --remote-name origin", - cwd=str(repodir), - capture_output=False, - env={"GITHUB_TOKEN": gh_token}, - ) - else: - run_command( - "git remote add upstream https://github.com/templateflow/templateflow.git", - cwd=str(repodir), - capture_output=False, - ) - - chdir(repodir) - - # Create datalad dataset - dl.create( - path=f"tpl-{template_id}", - cfg_proc="text2git", - initopts={"initial-branch": "main"}, - description=metadata["Name"], - ) - gitattr = (repodir / f"tpl-{template_id}" / ".gitattributes").read_text().strip() - (repodir / f"tpl-{template_id}" / ".gitattributes").write_text("\n".join([ - gitattr, - "*.gii annex.largefiles=anything", - "", - ])) - - # Populate template - copy_template( - path=path, - dest=repodir / f"tpl-{template_id}", - ) - # Copy license - shutil.copy(license_path, repodir / f"tpl-{template_id}" / "LICENSE") - # (Over)write template_description.json - (repodir / f"tpl-{template_id}" / "template_description.json").write_text( - json.dumps(metadata, indent=2) - ) - # Init/update CHANGELOG - changelog = repodir / f"tpl-{template_id}" / "CHANGES" - changes = [f""" -## {datetime.date.today().ctime()} - TemplateFlow Manager Upload -Populated contents after NIfTI sanitizing by the TF Manager. - -"""] - if changelog.exists(): - changes += [changelog.read_text()] - changelog.write_text("\n".join(changes)) - - dataset = str(repodir / f"tpl-{template_id}") - - # Save added contents - dl.save( - dataset=dataset, - message="ADD: TemplateFlow Manager initialized contents" - ) - - # GIN stores the data (annexed files). Once it holds them, publishing it as the - # dataset's common data source records it in the dataset, so anyone cloning the - # GitHub repository (reviewers, the intake previews, the Archive's intake) gets - # the data from GIN. - # DataLad looks up tokens by credential name; without one, it uses the API host - # (gin.g-node.org, api.github.com) and ignores DATALAD_CREDENTIAL_{GIN,GITHUB}_TOKEN - dl.create_sibling_gin( - f"tpl-{template_id}", - dataset=dataset, - credential="gin", - name="gin", - access_protocol="https-ssh", - description=metadata["Name"], - ) - dl.push(dataset=dataset, to="gin", jobs=cpu_count()) - dl.siblings( - action="configure", - dataset=dataset, - name="gin", - as_common_datasrc="gin-src", - ) - # GitHub holds the dataset (pushing to it updates GIN first) - dl.create_sibling_github( - reponame=f"tpl-{template_id}", - dataset=dataset, - credential="github", - publish_depends="gin", - existing="replace", - access_protocol="ssh" - ) - - # Push to siblings - dl.push( - dataset=str(repodir / f"tpl-{template_id}"), - to="github", - jobs=cpu_count(), - ) - - # Back home - chdir(cwd) - - run_command( - "git fetch upstream tpl-intake", cwd=str(repodir), capture_output=False, - ) - run_command( - f"git checkout -b pr/tpl-{template_id} upstream/tpl-intake", - cwd=str(repodir), - capture_output=False, - ) - (repodir / f"{path.name}.toml").write_text( - toml.dumps({"github": {"user": gh_user},}) - ) - run_command( - f"git add {path.name}.toml", cwd=str(repodir), capture_output=False, - ) - run_command( - f"git commit -m 'add(tpl-{template_id}): create intake file'", - cwd=str(repodir), - capture_output=False, - ) - run_command( - f"git push -u origin pr/tpl-{template_id}", - cwd=str(repodir), - capture_output=False, - env={"GITHUB_USER": gh_user, "GITHUB_TOKEN": gh_token}, - ) - - (repodir.parent / "message.md").write_text( - f"""\ -ADD: ``tpl-{template_id}`` - -## {metadata.get('Name', '')} - -Identifier: {metadata.get('Identifier', '')} -Datalad: https://github.com/{gh_user}/tpl-{template_id} - -### Authors -{', '.join(metadata['Authors'])}. - -### License -{metadata.get('License', metadata.get('Licence', ''))} - -### Cohorts -{' '.join(('The dataset contains', str(len(metadata.get('cohort', []))), 'cohorts.')) - if metadata.get('cohort') else 'The dataset does not contain cohorts.'} - -### References and links -{', '.join(metadata.get('ReferencesAndLinks', [])) or 'N/A'} - -""" - ) - run_command( - "hub pull-request -b templateflow:tpl-intake " - f"-h {gh_user}:pr/tpl-{template_id} " - f"-F {repodir.parent / 'message.md'}", - cwd=str(repodir), - capture_output=False, - env={"GITHUB_TOKEN": gh_token}, - ) - - del os.environ["DATALAD_CREDENTIAL_GITHUB_TOKEN"] - del os.environ["DATALAD_CREDENTIAL_GIN_TOKEN"] + raise click.BadParameter('A GIN access token is needed to upload the data') + + source = Path(path or f'tpl-{template_id}').absolute() + if not source.is_dir(): + raise click.UsageError(f'<{source}> does not exist.') + workdir = Path(workdir).absolute() if workdir else default_workdir(template_id) + state = State.load(workdir) + if restart: + state.data.pop('answers', None) + state.reset_from('copy') + answers = state.data.setdefault('answers', {}) + + def ask(key, question): + return click.prompt(question, type=str) + + os.environ['DATALAD_CREDENTIAL_GITHUB_TOKEN'] = gh_token + os.environ['DATALAD_CREDENTIAL_GIN_TOKEN'] = gin_token + try: + metadata, license_text = prepare_metadata(source, template_id, ask, answers) + state.save() + click.echo(f'Work directory: {workdir}') + state = Add( + template_id=template_id, + source=source, + workdir=workdir, + metadata=metadata, + license_text=license_text, + gh_user=gh_user, + gh_token=gh_token, + nprocs=nprocs, + fix=fix, + echo=click.echo, + ).run() + except AddError as exc: + click.echo(str(exc), err=True) + raise SystemExit(1) from exc + finally: + os.environ.pop('DATALAD_CREDENTIAL_GITHUB_TOKEN', None) + os.environ.pop('DATALAD_CREDENTIAL_GIN_TOKEN', None) + click.echo(f'Done: {state.data.get("pull_request", "")}') @cli.command() -@click.argument("paths", nargs=-1, type=click.Path(exists=True)) +@click.argument('paths', nargs=-1, type=click.Path(exists=True)) @click.option( - "--mode", - type=click.Choice(("auto", "strict", "legacy")), - default="auto", + '--mode', + type=click.Choice(('auto', 'strict', 'legacy')), + default='auto', show_default=True, - help="strict: TemplateFlow 2.0 rules; legacy: naming problems are warnings; " - "auto: legacy for templates older than TemplateFlowVersion 2.0.0.", + help='strict: TemplateFlow 2.0 rules; legacy: naming problems are warnings; ' + 'auto: legacy for templates older than TemplateFlowVersion 2.0.0.', ) @click.option( - "--level", - type=click.Choice(("names", "metadata", "content")), - default="metadata", + '--level', + type=click.Choice(('names', 'metadata', 'content')), + default='metadata', show_default=True, - help="content opens images (needs their data and tfmanager[content]).", + help='content opens images (needs their data and tfmanager[content]).', ) @click.option( - "--format", - "fmt", - type=click.Choice(("human", "json", "github", "markdown")), - default="human", + '--format', + 'fmt', + type=click.Choice(('human', 'json', 'github', 'markdown')), + default='human', show_default=True, ) -@click.option("--archive/--no-archive", default=None, help="Also check the Archive (TF8xx).") -@click.option("--show-info", is_flag=True, help="Also show informational issues.") +@click.option('--archive/--no-archive', default=None, help='Also check the Archive (TF8xx).') +@click.option('--show-info', is_flag=True, help='Also show informational issues.') @click.option( - "--trusted", + '--trusted', is_flag=True, - help="Follow git-annex links to open image data (do not use on untrusted clones).", + help='Follow git-annex links to open image data (do not use on untrusted clones).', ) -@click.option("-o", "--output", type=click.Path(dir_okay=False, writable=True)) +@click.option('-o', '--output', type=click.Path(dir_okay=False, writable=True)) def validate(paths, mode, level, fmt, archive, show_info, trusted, output): """Validate templates against the TemplateFlow rule set. @@ -407,48 +168,82 @@ def validate(paths, mode, level, fmt, archive, show_info, trusted, output): ) issues += found except Exception as exc: # an internal error must not read as "errors found" - click.echo(f"tfmgr validate failed: {exc!r}", err=True) + click.echo(f'tfmgr validate failed: {exc!r}', err=True) raise SystemExit(2) from exc text = render(issues, fmt=fmt, meta=meta, show_info=show_info) if output: - Path(output).write_text(text + "\n") + Path(output).write_text(text + '\n') else: click.echo(text) - raise SystemExit(1 if summary(issues)["error"] else 0) + raise SystemExit(1 if summary(issues)['error'] else 0) @cli.command() -@click.argument("template_dir", type=click.Path(exists=True), default=getcwd()) -@click.option("--normalize/--no-normalize", default=True) -@click.option("--force-dtype/--no-force-dtype", default=True) -@click.option("--deoblique/--no-deoblique", default=False) -def sanitize(template_dir, normalize, force_dtype, deoblique): - """Check orientation and datatypes of NIfTI files in template folder.""" - from .utils import copy_template as _copy_template +@click.argument( + 'template_dir', type=click.Path(exists=True, file_okay=False), default='.', required=False +) +@click.option( + '--check', + 'action', + flag_value='check', + default=True, + help='List the problems of the images (the default); change nothing.', +) +@click.option('--fix', 'action', flag_value='safe', help='Apply the safe fixes.') +@click.option( + '--fix-unsafe', + 'action', + flag_value='unsafe', + help='Apply all fixes, including those that rescale or round values, or move images.', +) +@click.option( + '--format', 'fmt', type=click.Choice(('human', 'json')), default='human', show_default=True +) +def sanitize(template_dir, action, fmt): + """Check the images of a template (TF7xx rules), and fix what can be fixed. - updated = _copy_template(template_dir, normalize, force_dtype, deoblique) - if updated: - print( - "\n * ".join( - ["Modified:"] + [f"<{u.relative_to(template_dir)}>" for u in updated] - ) - ) + Like a linter: --check lists the problems, --fix applies the safe fixes (values and + world coordinates are preserved), and --fix-unsafe also applies those that rescale or + round values, or move the image in space. Exits with 1 if problems remain. + """ + from . import sanitize as lint + from .validate import render + + try: + fixed, updated = ({}, []) + if action != 'check': + fixed, updated = lint.fix(template_dir, unsafe=action == 'unsafe') + issues = lint.lint(template_dir) + except ImportError as exc: + click.echo(f'tfmgr sanitize needs tfmanager[content]: {exc}', err=True) + raise SystemExit(2) from exc + if fmt == 'json': + click.echo(lint.as_json(issues, fixed, updated)) + else: + for path, codes in fixed.items(): + click.echo(f'Fixed {path}: {", ".join(codes)}') + for line in updated: + click.echo(f'Updated template_description.json: {line}') + if issues: + click.echo(render(issues, 'human').rsplit('\n\n', 1)[0]) + click.echo(lint.summary(issues)) + raise SystemExit(1 if issues else 0) @cli.command() -@click.argument("template_id") -@click.argument("field") -@click.option("--path", type=click.Path(exists=True)) +@click.argument('template_id') +@click.argument('field') +@click.option('--path', type=click.Path(exists=True)) def metadata(template_id, field, path): """Get a metadata entry from a template.""" - import json - if template_id.startswith("tpl-"): + + if template_id.startswith('tpl-'): template_id = template_id[4:] - path = Path(path or f"tpl-{template_id}") - metadata = json.loads((path / "template_description.json").read_text()) + path = Path(path or f'tpl-{template_id}') + metadata = json.loads((path / 'template_description.json').read_text()) print(metadata.get(field)) -if __name__ == "__main__": +if __name__ == '__main__': """ Install entry-point """ cli() diff --git a/tfmanager/images.py b/tfmanager/images.py new file mode 100644 index 0000000..52a9c14 --- /dev/null +++ b/tfmanager/images.py @@ -0,0 +1,255 @@ +"""Problems of NIfTI images (TF702-TF710) and their fixes (``tfmgr sanitize``). + +Each problem has a TF7xx code and, when tfmgr can correct it, a fix that is either +*safe* (data values and world coordinates are preserved: ``--fix``) or *unsafe* +(``--fix-unsafe``: values are rescaled or rounded, or the image moves in space). + +Needs nibabel and numpy (``tfmanager[content]``). +""" + +from __future__ import annotations + +from dataclasses import dataclass, field + +import nibabel as nb +import numpy as np + +ATOL = 1e-3 +#: Rotations (radians) beyond which an image is oblique +MAX_OBLIQUITY = 1e-2 +#: Suffixes whose values are labels (stored as unsigned integers) +LABELS = ('dseg', 'mask') +INT16 = np.iinfo(np.int16) + + +@dataclass(frozen=True) +class Finding: + code: str + message: str + fix: str | None = None + """``'safe'``, ``'unsafe'``, or ``None`` when tfmgr cannot correct it.""" + action: str | None = None + """How the fix corrects it, when a code has several (TF709: ``int16``, ``scaled``).""" + + +@dataclass +class Fixed: + """An image after its fixes, and what changed.""" + + image: nb.Nifti1Image + applied: list[Finding] = field(default_factory=list) + moved: bool = False + """Whether the grid (zooms, shape or origin) changed.""" + + +def _defined_affine(img) -> bool: + return bool(img.header.get_sform(coded=True)[1] or img.header.get_qform(coded=True)[1]) + + +def _integer_valued(data) -> bool: + if np.issubdtype(data.dtype, np.integer): + return True + return bool(np.all(np.isfinite(data)) and np.all(np.mod(data, 1) == 0)) + + +def _label_dtype(data): + """The smallest unsigned integer type that holds the (integer, non-negative) labels.""" + low, high = (float(np.min(data)), float(np.max(data))) if data.size else (0.0, 0.0) + if low < 0: + return None + for dtype in (np.uint8, np.uint16, np.uint32): + if high <= np.iinfo(dtype).max: + return np.dtype(dtype) + return None + + +def payload_problem(path, img) -> str | None: + """Why the voxel data of the NIfTI file at ``path`` cannot be read in full, if so. + + nibabel reads data lazily, so a valid header can hide a truncated or corrupt payload. + The file is streamed (and decompressed) in chunks, without holding it in memory. + """ + import gzip + import zlib + + hdr = img.header + # The proxy's offset: a loaded header resets vox_offset to 0 + offset = getattr(img.dataobj, 'offset', None) or int(hdr.get_data_offset()) + expected = int(offset) + int(np.prod(hdr.get_data_shape(), dtype=np.int64)) * int( + hdr.get_data_dtype().itemsize + ) + opener = gzip.open if str(path).endswith('.gz') else open + size = 0 + try: + with opener(path, 'rb') as stream: + while chunk := stream.read(1 << 22): + size += len(chunk) + except (OSError, EOFError, zlib.error) as exc: + return f'{type(exc).__name__}: {exc}' + if size < expected: + return f'Truncated: {size} bytes, the header needs {expected}.' + return None + + +def inspect(img, suffix: str, anatomical: bool) -> list[Finding]: + """The problems of an image (``anatomical``: a T1w, T2w... image of the template).""" + found = [] + hdr = img.header + sform, scode = hdr.get_sform(coded=True) + qform, qcode = hdr.get_qform(coded=True) + if scode == 0 and qcode == 0: + found.append(Finding('TF702', 'Neither sform nor qform is set.')) + elif scode and qcode and not np.allclose(sform, qform, atol=ATOL): + found.append(Finding('TF702', 'sform and qform disagree (fix: qform := sform).', 'unsafe')) + + units = hdr.get_xyzt_units()[0] + if units == 'unknown': + found.append(Finding('TF710', 'Spatial units are not set (fix: mm).', 'safe')) + elif units != 'mm': + found.append(Finding('TF710', f'Spatial units are {units}, not mm.')) + + if _defined_affine(img): + obliquity = float(np.max(nb.affines.obliquity(img.affine))) + if obliquity > MAX_OBLIQUITY: + found.append( + Finding('TF708', f'Oblique by {obliquity:.3f} rad (fix: deoblique).', 'unsafe') + ) + axes = ''.join(nb.aff2axcodes(img.affine)) + if axes != 'RAS': + found.append(Finding('TF707', f'Axes {axes}, not RAS (fix: reorient).', 'safe')) + + dtype = img.get_data_dtype() + if suffix in LABELS or anatomical: + data = np.asanyarray(img.dataobj) + integer = _integer_valued(data) + if suffix in LABELS and integer: + target = _label_dtype(data) + if target is not None and ( + not np.issubdtype(dtype, np.integer) or dtype.itemsize > target.itemsize + ): + found.append( + Finding( + 'TF709', f'Labels stored as {dtype} (fix: {target}).', 'safe', 'labels' + ) + ) + elif anatomical and np.issubdtype(dtype, np.integer): + if ( + dtype.itemsize > 2 + and integer + and data.size + and INT16.min <= data.min() + and data.max() <= INT16.max + ): + found.append( + Finding('TF709', f'Values stored as {dtype} fit in int16.', 'safe', 'int16') + ) + elif anatomical and np.issubdtype(dtype, np.floating): + if not np.all(np.isfinite(data)): + found.append(Finding('TF709', f'Stored as {dtype}, with non-finite values.')) + elif integer and data.size and INT16.min <= data.min() and data.max() <= INT16.max: + found.append( + Finding( + 'TF709', f'Integer values stored as {dtype} (fix: int16).', 'safe', 'int16' + ) + ) + else: + found.append( + Finding( + 'TF709', + f'Stored as {dtype} (fix: int16 with slope and intercept, ' + 'which rounds values).', + 'unsafe', + 'scaled', + ) + ) + + if suffix == 'probseg': + data = np.asanyarray(img.dataobj) + low, high = float(np.nanmin(data)), float(np.nanmax(data)) + if low < -ATOL or high > 1 + ATOL: + found.append( + Finding( + 'TF703', + f'Values in [{low:g}, {high:g}] (fix: clip below 0, divide by the maximum).', + 'unsafe' if high > 0 else None, + ) + ) + return found + + +def _deoblique(affine, shape): + """The closest cardinal affine, keeping voxel sizes and the world center of the image.""" + rotation = affine[:3, :3] + zooms = np.sqrt((rotation**2).sum(axis=0)) + ornt = nb.orientations.io_orientation(affine) + cardinal = np.zeros((3, 3)) + for axis, (world, flip) in enumerate(ornt): + cardinal[int(world), axis] = flip * zooms[axis] + center = (np.asarray(shape[:3], dtype=float) - 1) / 2 + world_center = affine[:3, :3] @ center + affine[:3, 3] + new = np.eye(4) + new[:3, :3] = cardinal + new[:3, 3] = world_center - cardinal @ center + return new + + +def apply(img, findings: list[Finding], unsafe: bool = False) -> Fixed: + """Apply the fixes of ``findings`` (safe ones, and unsafe ones if ``unsafe``).""" + todo = [f for f in findings if f.fix == 'safe' or (unsafe and f.fix == 'unsafe')] + codes = {f.code for f in todo} + if not todo: + return Fixed(img) + + hdr = img.header.copy() + sform, scode = hdr.get_sform(coded=True) + qform, qcode = hdr.get_qform(coded=True) + affine = img.affine.copy() + data = np.asanyarray(img.dataobj) + before = (tuple(np.round(img.header.get_zooms()[:3], 6)), img.shape[:3], affine[:3, 3]) + + if 'TF710' in codes: + hdr.set_xyzt_units(xyz='mm', t=hdr.get_xyzt_units()[1]) + if 'TF708' in codes: + affine = _deoblique(affine, data.shape) + if 'TF707' in codes: + ornt = nb.orientations.io_orientation(affine) + transform = nb.orientations.ornt_transform(ornt, nb.orientations.axcodes2ornt('RAS')) + data = nb.orientations.apply_orientation(data, transform) + affine = affine @ nb.orientations.inv_ornt_aff(transform, img.shape) + + target = hdr.get_data_dtype() + for finding in todo: + if finding.code == 'TF703': + data = np.clip(np.asarray(data, dtype=np.float32), 0, None) + high = float(data.max()) + if high > 1: + data = data / high + target = np.dtype(np.float32) + elif finding.code == 'TF709': + if finding.action == 'scaled': + target = np.dtype(np.int16) # nibabel computes slope and intercept + elif finding.action == 'int16': + data = np.asarray(data).astype(np.int16) + target = np.dtype(np.int16) + elif finding.action == 'labels': + target = _label_dtype(data) + data = np.asarray(data).astype(target) + + hdr.set_data_dtype(target) + hdr.set_slope_inter(np.nan, np.nan) + new = nb.Nifti1Image(data, affine, hdr) + # Both forms get the (fixed) affine: qform := sform when they disagreed (TF702) + new.header.set_sform(affine, int(scode)) + new.header.set_qform(affine, int(qcode)) + after = (tuple(np.round(new.header.get_zooms()[:3], 6)), new.shape[:3], affine[:3, 3]) + moved = before[0] != after[0] or before[1] != after[1] or not np.allclose(before[2], after[2]) + return Fixed(new, applied=todo, moved=moved) + + +def grid(img) -> dict: + """The grid of an image, as a ``res`` block describes it.""" + return { + 'zooms': [round(float(z), 6) for z in img.header.get_zooms()[:3]], + 'shape': [int(n) for n in img.shape[:3]], + 'origin': [round(float(o), 6) for o in img.affine[:3, 3]], + } diff --git a/tfmanager/io.py b/tfmanager/io.py index 9b0ccbd..c9889ea 100644 --- a/tfmanager/io.py +++ b/tfmanager/io.py @@ -1,26 +1,28 @@ -"""I/O support.""" -from typing import Mapping +"""Running external commands (git, gh).""" +from __future__ import annotations + +import os +import subprocess +from collections.abc import Mapping, Sequence -def run_command( - cmd: str, - env: Mapping[str, str] = None, - cwd: str = None, - capture_output: bool = True, -) -> str: - """ - Run prepared behave command in shell and return its output. - :param cmd: Well-formed behave command to run. - :return: Command output as string. - """ - import os - from subprocess import run +class CommandError(RuntimeError): + """A command failed.""" - if env: - _env = dict(os.environ) - _env.update(env) - env = _env - proc = run(cmd, capture_output=capture_output, shell=True, env=env, cwd=cwd,) +def run_command( + cmd: Sequence[str], + env: Mapping[str, str] | None = None, + cwd: str | os.PathLike | None = None, + check: bool = True, +) -> subprocess.CompletedProcess: + """Run ``cmd`` (no shell); raise :class:`CommandError` with its output if it fails.""" + full_env = {**os.environ, **env} if env else None + proc = subprocess.run( # noqa: S603 + list(cmd), capture_output=True, text=True, env=full_env, cwd=cwd, check=False + ) + if check and proc.returncode != 0: + output = (proc.stderr or proc.stdout or '').strip() + raise CommandError(f'`{" ".join(cmd[:2])}` failed: {output}') return proc diff --git a/tfmanager/sanitize.py b/tfmanager/sanitize.py new file mode 100644 index 0000000..f861bd5 --- /dev/null +++ b/tfmanager/sanitize.py @@ -0,0 +1,143 @@ +"""``tfmgr sanitize``: lint the images of a template (TF7xx), and fix what can be fixed. + +``lint`` reports the content rules. ``fix`` rewrites the images whose problems have a safe +fix (and an unsafe one, with ``unsafe=True``), then updates the ``res`` blocks of +template_description.json that described the old grids, so that a reoriented or deobliqued +image does not contradict its metadata. Annexed images are replaced by regular files +(``datalad save`` annexes them again). Needs nibabel (``tfmanager[content]``). +""" + +from __future__ import annotations + +import json +import os +from collections import defaultdict +from pathlib import Path + +from .tree import DirectoryTree +from .validate.core import Context, Issue, run_checks + +#: Content rules sanitize reports (TF700 and TF701-TF710) +PREFIX = 'TF7' + + +def _context(root: Path) -> Context: + return Context(tree=DirectoryTree(root, trusted=True), mode='strict', level='content') + + +def lint(root: str | os.PathLike) -> list[Issue]: + """The image problems of the template at ``root`` (errors and warnings). + + Raises :class:`ImportError` when the images could not be checked (no nibabel). + """ + issues = run_checks(_context(Path(root))) + if any(i.code == 'TF700' for i in issues): + raise ImportError('nibabel and numpy are needed to check images') + return [i for i in issues if i.code.startswith(PREFIX) and i.severity != 'info'] + + +def _write(path: Path, img) -> None: + """Write ``img`` at ``path``, replacing the file (or the annex link) atomically.""" + tmp = path.parent / f'.tfmgr-{path.name}' + img.to_filename(tmp) + os.replace(tmp, path) + + +def _where(desc: dict, res: str, cohort: str | None, key: str) -> tuple | None: + """The ``res`` block that describes ``key`` of a ``res``/``cohort`` image.""" + override = (((desc.get('cohort') or {}).get(cohort) or {}).get('res') or {}).get(res) + if cohort is not None and isinstance(override, dict) and key in override: + return ('cohort', cohort, 'res', res) + block = (desc.get('res') or {}).get(res) + if isinstance(block, dict) and key in block: + return ('res', res) + return None + + +def _block(desc: dict, where: tuple) -> dict: + node = desc + for part in where: + node = node[part] + return node + + +def fix(root: str | os.PathLike, unsafe: bool = False) -> tuple[dict[str, list[str]], list[str]]: + """Fix the images of the template at ``root``. + + Returns ``({path: [codes fixed]}, [res blocks updated])``. + """ + import nibabel as nb + import numpy as np + + from . import images + from .tables import dump_json + from .validate.content import ATOL, nifti_files + + root = Path(root) + ctx = _context(root) + anatomical = { + s for s, spec in ctx.ruleset.suffixes.items() if spec.get('group') == 'anatomical' + } + fixed: dict[str, list[str]] = {} + grids: dict[tuple, list[tuple[list, list]]] = defaultdict(list) + desc = ctx.description if isinstance(ctx.description, dict) else {} + for path, f, local in list(nifti_files(ctx)): + try: + img = nb.load(local) + if images.payload_problem(local, img): + continue # lint reports it (TF711) + findings = images.inspect(img, f.suffix, f.suffix in anatomical) + except Exception: # lint reports it (TF711) + continue + result = images.apply(img, findings, unsafe=unsafe) + old = images.grid(img) + new = images.grid(result.image) if result.applied else old + if result.applied: + _write(root / path, result.image) + fixed[path] = [x.code for x in result.applied] + res = f.entities.get('res') + if not res: + continue + for key in ('zooms', 'shape', 'origin'): + where = _where(desc, res, f.entities.get('cohort'), key) + if where: + grids[(where, key)].append((old[key], new[key])) + + updated = [] + for (where, key), values in sorted(grids.items(), key=str): + block = _block(desc, where) + described = block[key] + matched = all(np.allclose(described, old, atol=ATOL) for old, _ in values) + moved = any(not np.allclose(old, new, atol=ATOL) for old, new in values) + first = values[0][1] + agree = all(np.allclose(new, first, atol=ATOL) for _, new in values) + if matched and moved and agree: + block[key] = first + updated.append(f'{".".join(where)}.{key}: {described} -> {first}') + if updated: + (root / 'template_description.json').write_text(dump_json(desc)) + return fixed, updated + + +def summary(issues: list[Issue]) -> str: + safe = sum(1 for i in issues if i.autofix == 'safe') + unsafe = sum(1 for i in issues if i.autofix == 'unsafe') + if not issues: + return 'No problems.' + parts = [f'{len(issues)} problem{"s" if len(issues) != 1 else ""}'] + if safe or unsafe: + parts.append( + f'{safe} fixable with --fix' + (f', {unsafe} more with --fix-unsafe' if unsafe else '') + ) + return ': '.join(parts) + '.' + + +def as_json(issues: list[Issue], fixed: dict | None = None, updated: list | None = None) -> str: + return json.dumps( + { + 'issues': [i.as_dict() for i in issues], + 'fixed': fixed or {}, + 'updated': updated or [], + }, + indent=2, + ) diff --git a/tfmanager/schema/rules.yaml b/tfmanager/schema/rules.yaml index 413f2a0..907c6c0 100644 --- a/tfmanager/schema/rules.yaml +++ b/tfmanager/schema/rules.yaml @@ -349,12 +349,12 @@ TF702: slug: image-orientation severity: warning summary: The image has no valid sform/qform code, or the two disagree. - fix: Set the sform and qform of the image consistently. + fix: Set the sform and qform of the image consistently (`tfmgr sanitize --fix-unsafe` sets the qform to the sform). TF703: slug: probseg-range severity: error summary: A probabilistic segmentation has values outside [0, 1]. - fix: Rescale the probabilities. + fix: Rescale the probabilities (`tfmgr sanitize --fix-unsafe` clips them below 0 and divides them by their maximum). TF704: slug: dseg-values severity: error @@ -370,6 +370,35 @@ TF706: severity: error summary: The number of volumes of a 4D probabilistic segmentation and the rows of its table disagree. fix: Give the table one row per volume, in volume order. +TF707: + slug: not-ras + severity: warning + legacy: info + summary: The image's voxel axes are not in RAS order. + fix: Reorient the image to RAS (`tfmgr sanitize --fix`); world coordinates do not change. +TF708: + slug: oblique + severity: warning + legacy: info + summary: The image's axes are rotated with respect to the world axes. + fix: Remove the rotation (`tfmgr sanitize --fix-unsafe`), which keeps the world center of the image but moves its corners. +TF709: + slug: storage-dtype + severity: warning + legacy: info + summary: The image is stored with a wider data type than its values need. + fix: Store labels as the smallest unsigned integer type, and images as int16 (`tfmgr sanitize --fix`; with `--fix-unsafe`, floating-point images become int16 with a slope and intercept, which rounds their values). +TF710: + slug: image-units + severity: warning + legacy: info + summary: The image's spatial units are not millimeters. + fix: Set the units to mm when they are unset (`tfmgr sanitize --fix`); other units need the image to be rescaled by its authors. +TF711: + slug: unreadable-image + severity: error + summary: The image cannot be read (empty, truncated, or not a NIfTI file). + fix: Replace the file with a valid NIfTI image. TF801: slug: templates-table severity: error diff --git a/tfmanager/tests/test_add.py b/tfmanager/tests/test_add.py new file mode 100644 index 0000000..a1bd356 --- /dev/null +++ b/tfmanager/tests/test_add.py @@ -0,0 +1,296 @@ +"""``tfmgr add``: metadata, the mirror copy, and resuming (DataLad, git and gh mocked).""" + +from __future__ import annotations + +import hashlib +import json +import os +import subprocess +import sys +import types +from pathlib import Path + +import pytest + +from tfmanager import add as add_mod +from tfmanager.add import Add, AddError, State, mirror, prepare_license, prepare_metadata +from tfmanager.tests import test_content +from tfmanager.tests.conftest import LABEL + +pytest.importorskip('nibabel') +#: The strict-valid template, with images +template = test_content.template + + +def _never(key, question): + raise AssertionError(f'asked for {key}') + + +def _answers(**values): + asked = [] + + def ask(key, question): + asked.append(key) + value = values[key] + return value.pop(0) if isinstance(value, list) else value + + ask.asked = asked + return ask + + +# Metadata ------------------------------------------------------------------------------ + + +def test_complete_metadata_asks_nothing(template): + metadata, text = prepare_metadata(template, LABEL, _never) + assert metadata['License'] == 'CC-BY-4.0' + assert metadata['TemplateFlowVersion'] == '2.0.0' + assert metadata['BIDSVersion'] == '1.11.0' + assert text.startswith('SPDX-License-Identifier: CC-BY-4.0\n') + + +def test_readme_is_required(template): + (template / 'README.md').unlink() + with pytest.raises(AddError, match='README.md is missing'): + prepare_metadata(template, LABEL, _never) + + +def test_missing_fields_are_asked_until_valid(template): + desc = json.loads((template / 'template_description.json').read_text()) + del desc['Authors'], desc['ReferencesAndLinks'] + desc['RRID'] = 'SCR_008796' + (template / 'template_description.json').write_text(json.dumps(desc)) + ask = _answers( + Authors=['Oscar Esteban', 'Esteban O; Ciric R'], + ReferencesAndLinks='doi:10.1101/2021.02.10.430678 https://example.org', + ) + answers = {} + metadata, _ = prepare_metadata(template, LABEL, ask, answers) + assert ask.asked == ['Authors', 'Authors', 'ReferencesAndLinks'] + assert metadata['Authors'] == ['Esteban O', 'Ciric R'] + assert metadata['ReferencesAndLinks'] == [ + 'https://doi.org/10.1101/2021.02.10.430678', + 'https://example.org', + ] + assert metadata['RRID'] == 'RRID:SCR_008796' + # A run that resumes does not ask again + prepare_metadata(template, LABEL, _never, answers) + + +def test_license_header_is_added(tmp_path): + (tmp_path / 'LICENSE').write_text('Attribution 4.0 International\n') + expression, text = prepare_license(tmp_path, 'CC-BY-4.0', _never) + assert text == 'SPDX-License-Identifier: CC-BY-4.0\n\nAttribution 4.0 International\n' + + +def test_license_is_asked_and_written(tmp_path): + expression, text = prepare_license(tmp_path, 'CC-BY 4.0', _answers(License='CC0-1.0')) + assert expression == 'CC0-1.0' + assert text.startswith('SPDX-License-Identifier: CC0-1.0\n\nCC0 1.0 Universal') + + +@pytest.mark.parametrize( + ('declared', 'message'), + [ + ('GPL-2.0-only', 'GPL licenses are for software'), + ('LicenseRef-Custom', 'Write the text of LicenseRef-Custom'), + ], +) +def test_licenses_refused(tmp_path, declared, message): + with pytest.raises(AddError, match=message): + prepare_license(tmp_path, declared, _never) + + +def test_license_header_disagrees(tmp_path): + (tmp_path / 'LICENSE').write_text('SPDX-License-Identifier: CC0-1.0\n\ntext\n') + assert prepare_license(tmp_path, 'CC-BY-4.0', _never)[0] == 'CC0-1.0' + + +# Mirror -------------------------------------------------------------------------------- + + +def test_mirror(tmp_path): + source, dest = tmp_path / 'source', tmp_path / 'dest' + (source / 'sub').mkdir(parents=True) + (source / 'a.txt').write_text('a') + (source / 'sub' / 'b.nii.gz').write_bytes(b'image') + (source / '.hidden').write_text('x') + (source / 'LICENSE').write_text('generated by add') + assert sorted(mirror(source, dest)) == ['a.txt', 'sub/b.nii.gz'] + assert not (dest / '.hidden').exists() and not (dest / 'LICENSE').exists() + assert mirror(source, dest) == [] + + # After datalad save, the image is an annex link: same content is not copied again + md5 = hashlib.md5(b'image').hexdigest() # noqa: S324 + key = f'MD5E-s5--{md5}.nii.gz' + (dest / 'sub' / 'b.nii.gz').unlink() + os.symlink(f'../.git/annex/objects/x/y/{key}/{key}', dest / 'sub' / 'b.nii.gz') + (dest / '.git').mkdir() + (dest / 'stale.txt').write_text('removed from the source') + assert mirror(source, dest) == ['stale.txt'] + assert (dest / '.git').exists() + + +# Steps --------------------------------------------------------------------------------- + + +class FakeDataLad: + def __init__(self): + self.calls = [] + self.fail = None + + def _call(self, _op, **kwargs): + self.calls.append((_op, kwargs)) + if self.fail and self.fail(_op, kwargs): + raise RuntimeError(f'{_op} failed') + + def create(self, path, **kwargs): + self._call('create', path=path, **kwargs) + Path(path, '.datalad').mkdir(parents=True) + Path(path, '.gitattributes').write_text('* annex.backend=MD5E\n') + + def save(self, **kwargs): + self._call('save', **kwargs) + + def create_sibling_gin(self, reponame, **kwargs): + self._call('create_sibling_gin', reponame=reponame, **kwargs) + + def create_sibling_github(self, **kwargs): + self._call('create_sibling_github', **kwargs) + + def push(self, **kwargs): + self._call('push', **kwargs) + + def siblings(self, **kwargs): + self._call('siblings', **kwargs) + + def names(self): + return [name if name != 'push' else f'push:{kw["to"]}' for name, kw in self.calls] + + +@pytest.fixture +def datalad(monkeypatch): + fake = FakeDataLad() + module = types.ModuleType('datalad') + module.api = fake + monkeypatch.setitem(sys.modules, 'datalad', module) + monkeypatch.setitem(sys.modules, 'datalad.api', fake) + return fake + + +@pytest.fixture +def commands(monkeypatch): + calls = [] + state = {'open': ''} + + def run(cmd, env=None, cwd=None, check=True): + calls.append(list(cmd)) + out = '' + if cmd[:3] == ['gh', 'pr', 'list']: + out = state['open'] + elif cmd[:2] == ['git', 'clone']: + Path(cmd[-1]).mkdir(parents=True) + elif cmd[:3] == ['gh', 'pr', 'create']: + out = 'https://github.com/templateflow/templateflow/pull/300\n' + assert env is None or 'GH_TOKEN' in env + return subprocess.CompletedProcess(cmd, 0, out, '') + + monkeypatch.setattr(add_mod, 'run_command', run) + run.calls = calls + run.state = state + return run + + +def _add(template, workdir, fix=None): + metadata, text = prepare_metadata(template, LABEL, _never) + return Add( + template_id=LABEL, + source=template, + workdir=workdir, + metadata=metadata, + license_text=text, + gh_user='someone', + gh_token='token', + nprocs=3, + fix=fix, + echo=lambda line: None, + ) + + +def test_add_resumes_where_it_failed(template, tmp_path, datalad, commands): + workdir = tmp_path / 'work' + datalad.fail = lambda name, kw: name == 'push' and kw['to'] == 'gin' + with pytest.raises(RuntimeError, match='push failed'): + _add(template, workdir).run() + assert State.load(workdir).data['done'] == ['copy', 'validate', 'save'] + + datalad.fail = None + datalad.calls.clear() + state = _add(template, workdir).run() + assert datalad.names() == [ + 'create_sibling_gin', + 'push:gin', + 'siblings', + 'create_sibling_github', + 'push:github', + ] + assert all(kw.get('on_failure') == 'stop' for _, kw in datalad.calls) + assert all(kw.get('jobs') == 3 for name, kw in datalad.calls if name == 'push') + github = dict(datalad.calls)['create_sibling_github'] + assert github['existing'] == 'reconfigure' + assert dict(datalad.calls)['create_sibling_gin']['existing'] == 'reconfigure' + + assert state.data['pull_request'].endswith('/pull/300') + repo = workdir / 'templateflow' + assert (repo / f'tpl-{LABEL}.toml').read_text() == '[github]\nuser = "someone"\n' + create = next(c for c in commands.calls if c[:3] == ['gh', 'pr', 'create']) + assert create[create.index('--base') + 1] == 'tpl-intake' + assert create[create.index('--head') + 1] == f'someone:pr/tpl-{LABEL}' + body = (workdir / 'message.md').read_text() + assert '**Validation passed**' in body + + # The dataset has the template, its metadata and its LICENSE + dataset = workdir / f'tpl-{LABEL}' + assert (dataset / 'README.md').read_text() == (template / 'README.md').read_text() + assert json.loads((dataset / 'template_description.json').read_text())['Identifier'] == LABEL + assert '*.gii annex.largefiles=anything' in (dataset / '.gitattributes').read_text() + + # Nothing left to do + datalad.calls.clear() + _add(template, workdir).run() + assert datalad.calls == [] + + +def test_validation_errors_stop_before_uploading(template, tmp_path, datalad, commands): + (template / f'tpl-{LABEL}_T1w_res-1.nii.gz').write_bytes(b'') + with pytest.raises(AddError, match='TF100'): + _add(template, tmp_path / 'work').run() + assert datalad.names() == ['create'] + assert commands.calls == [] + + +def test_open_pull_request_is_not_duplicated(template, tmp_path, datalad, commands): + commands.state['open'] = 'https://github.com/templateflow/templateflow/pull/299\n' + state = _add(template, tmp_path / 'work').run() + assert state.data['pull_request'].endswith('/pull/299') + assert [c[:3] for c in commands.calls] == [['gh', 'pr', 'list']] + + +def test_source_changes_restart_from_the_copy(template, tmp_path, datalad, commands): + workdir = tmp_path / 'work' + _add(template, workdir).run() + (template / 'CHANGES').write_text('2.0.1: fixed\n') + datalad.calls.clear() + _add(template, workdir).run() + assert datalad.names()[0] == 'save' + assert (workdir / f'tpl-{LABEL}' / 'CHANGES').read_text() == '2.0.1: fixed\n' + + +def test_fingerprint_sees_content(tmp_path): + """An edit that keeps the size and the modification time still counts.""" + (tmp_path / 'a.txt').write_text('first') + before = add_mod.fingerprint(tmp_path) + stat = (tmp_path / 'a.txt').stat() + (tmp_path / 'a.txt').write_text('other') + os.utime(tmp_path / 'a.txt', ns=(stat.st_atime_ns, stat.st_mtime_ns)) + assert add_mod.fingerprint(tmp_path) != before diff --git a/tfmanager/tests/test_content.py b/tfmanager/tests/test_content.py index c52bacd..fb7df98 100644 --- a/tfmanager/tests/test_content.py +++ b/tfmanager/tests/test_content.py @@ -31,6 +31,7 @@ def _image(path, data, zooms=(1.0, 1.0, 1.0), origin=(-5.0, -6.0, -5.0)): img = nb.Nifti1Image(np.asarray(data), affine) img.header.set_sform(affine, 4) img.header.set_qform(affine, 4) + img.header.set_xyzt_units('mm') img.to_filename(path) @@ -42,9 +43,9 @@ def template(tmp_path): seg = np.zeros((10, 12, 10), dtype='uint8') seg[2:4, 2:4, 2:4] = 1 seg[5:7, 5:7, 5:7] = 2 - _image(root / f'{T}_res-1_T1w.nii.gz', np.ones((10, 12, 10), dtype='float32')) + _image(root / f'{T}_res-1_T1w.nii.gz', np.ones((10, 12, 10), dtype='int16')) _image( - root / f'{T}_res-2_T1w.nii.gz', np.ones((5, 6, 5), dtype='float32'), zooms=(2.0, 2.0, 2.0) + root / f'{T}_res-2_T1w.nii.gz', np.ones((5, 6, 5), dtype='int16'), zooms=(2.0, 2.0, 2.0) ) _image(root / f'{T}_atlas-Smith2020_res-1_dseg.nii.gz', seg) _image( @@ -112,3 +113,31 @@ def test_cohort_override(template): ) issues = validate_template(DirectoryTree(template), mode='strict', level='content') assert 'TF701' not in {i.code for i in issues} + + +def test_unreadable_image(template): + (template / f'{T}_res-1_T1w.nii.gz').write_bytes(b'not an image') + assert content_codes(template) == {'TF711'} + + +def _truncate(path): + """Keep the header and half of the voxel data (a valid gzip stream).""" + import gzip + + raw = gzip.decompress(path.read_bytes()) + path.write_bytes(gzip.compress(raw[: 352 + (len(raw) - 352) // 2])) + + +def test_truncated_payloads(template): + """nibabel reads lazily: images whose data are never read are streamed in full.""" + boldref = template / f'{T}_res-1_boldref.nii.gz' + _image(boldref, np.ones((10, 12, 10), dtype='int16')) + assert 'TF711' not in content_codes(template) + _truncate(boldref) + issues = validate_template(DirectoryTree(template), mode='strict', level='content') + assert [i.message for i in issues if i.code == 'TF711'] == [ + 'Truncated: 1552 bytes, the header needs 2752.' + ] + # A broken gzip stream + boldref.write_bytes(boldref.read_bytes()[:-12]) + assert 'TF711' in content_codes(template) diff --git a/tfmanager/tests/test_images.py b/tfmanager/tests/test_images.py new file mode 100644 index 0000000..4b2a872 --- /dev/null +++ b/tfmanager/tests/test_images.py @@ -0,0 +1,153 @@ +"""TF702-TF710 on synthetic images, and their fixes.""" + +from __future__ import annotations + +import pytest + +nb = pytest.importorskip('nibabel') +np = pytest.importorskip('numpy') + +from tfmanager import images # noqa: E402 + +SHAPE = (6, 7, 8) + + +def _img(data, affine=None, units='mm'): + affine = np.diag([1.0, 1.0, 1.0, 1.0]) if affine is None else affine + img = nb.Nifti1Image(np.asarray(data), affine) + img.header.set_sform(affine, 4) + img.header.set_qform(affine, 4) + if units: + img.header.set_xyzt_units(units) + return nb.Nifti1Image.from_bytes(img.to_bytes()) + + +def _codes(img, suffix='T1w', anatomical=True): + return {f.code: f for f in images.inspect(img, suffix, anatomical)} + + +def _world(img, ijk): + return nb.affines.apply_affine(img.affine, ijk) + + +def test_clean_image(): + assert _codes(_img(np.ones(SHAPE, dtype='int16'))) == {} + + +def test_reorient_is_safe_and_keeps_world_coordinates(): + lps = np.diag([-1.0, -1.0, 1.0, 1.0]) + lps[:3, 3] = [10, 20, -5] + data = np.arange(np.prod(SHAPE), dtype='int16').reshape(SHAPE) + img = _img(data, lps) + finding = _codes(img)['TF707'] + assert finding.fix == 'safe' + assert 'LPS' in finding.message + + fixed = images.apply(img, [finding]) + assert ''.join(nb.aff2axcodes(fixed.image.affine)) == 'RAS' + assert fixed.moved # the origin is now another corner + # The voxel holding a value is at the same place in the world + out = np.asanyarray(fixed.image.dataobj) + value = data[1, 2, 3] + where = np.argwhere(out == value)[0] + assert np.allclose(_world(fixed.image, where), _world(img, (1, 2, 3))) + + +def test_oblique_is_unsafe(): + angle = 0.1 + rotation = np.eye(4) + rotation[:2, :2] = [[np.cos(angle), -np.sin(angle)], [np.sin(angle), np.cos(angle)]] + img = _img(np.ones(SHAPE, dtype='int16'), rotation) + finding = _codes(img)['TF708'] + assert finding.fix == 'unsafe' + assert images.apply(img, [finding]).applied == [] # not without unsafe=True + + fixed = images.apply(img, [finding], unsafe=True) + assert np.max(nb.affines.obliquity(fixed.image.affine)) < 1e-6 + center = (np.asarray(SHAPE) - 1) / 2 + assert np.allclose(_world(fixed.image, center), _world(img, center)) + + +def test_labels_narrow_safely(): + mask = np.zeros(SHAPE, dtype='float64') + mask[1:3, 1:3, 1:3] = 1 + img = _img(mask) + finding = _codes(img, 'mask', False)['TF709'] + assert finding.fix == 'safe' + fixed = images.apply(img, [finding]) + assert fixed.image.get_data_dtype() == np.uint8 + assert np.array_equal(np.asanyarray(fixed.image.dataobj), mask) + assert not fixed.moved + + many = np.arange(np.prod(SHAPE), dtype='int32').reshape(SHAPE) + assert 'uint16' in _codes(_img(many), 'dseg', False)['TF709'].message + + +def test_float_anatomical_to_int16(): + integers = np.arange(np.prod(SHAPE), dtype='float32').reshape(SHAPE) + finding = _codes(_img(integers))['TF709'] + assert (finding.fix, finding.action) == ('safe', 'int16') + fixed = images.apply(_img(integers), [finding]) + assert fixed.image.get_data_dtype() == np.int16 + assert np.array_equal(np.asanyarray(fixed.image.dataobj), integers) + + rng = np.random.default_rng(0) + floats = rng.normal(500, 100, SHAPE).astype('float32') + finding = _codes(_img(floats))['TF709'] + assert (finding.fix, finding.action) == ('unsafe', 'scaled') + fixed = images.apply(_img(floats), [finding], unsafe=True) + stored = nb.Nifti1Image.from_bytes(fixed.image.to_bytes()) + assert stored.get_data_dtype() == np.int16 + slope = float(stored.dataobj.slope) # nibabel moves scl_slope to the data proxy + assert slope not in (0, 1) + assert np.max(np.abs(stored.get_fdata() - floats)) <= slope / 2 + 1e-6 + + wide = np.arange(np.prod(SHAPE), dtype='int32').reshape(SHAPE) + finding = _codes(_img(wide))['TF709'] + assert (finding.fix, finding.action) == ('safe', 'int16') + fixed = images.apply(_img(wide), [finding]) + assert fixed.image.get_data_dtype() == np.int16 + assert np.array_equal(np.asanyarray(fixed.image.dataobj), wide) + assert 'TF709' not in _codes(_img(wide * 1000)) # beyond int16: int32 is needed + + with_nan = floats.copy() + with_nan[0, 0, 0] = np.nan + assert _codes(_img(with_nan))['TF709'].fix is None + + +def test_units(): + finding = _codes(_img(np.ones(SHAPE, dtype='int16'), units=None))['TF710'] + assert finding.fix == 'safe' + fixed = images.apply(_img(np.ones(SHAPE, dtype='int16'), units=None), [finding]) + assert fixed.image.header.get_xyzt_units()[0] == 'mm' + assert _codes(_img(np.ones(SHAPE, dtype='int16'), units='micron'))['TF710'].fix is None + + +def test_forms(): + unset = _img(np.ones(SHAPE, dtype='int16')) + unset.header.set_sform(unset.affine, 0) + unset.header.set_qform(unset.affine, 0) + assert _codes(unset)['TF702'].fix is None + img = _img(np.ones(SHAPE, dtype='int16')) + shifted = img.affine.copy() + shifted[0, 3] = 3 + img.header.set_qform(shifted, 4) + img = nb.Nifti1Image.from_bytes(img.to_bytes()) + finding = _codes(img)['TF702'] + assert finding.fix == 'unsafe' + fixed = images.apply(img, [finding], unsafe=True) + sform, qform = fixed.image.header.get_sform(), fixed.image.header.get_qform() + assert np.allclose(sform, qform) + assert np.allclose(qform, img.header.get_sform()) + + +def test_probseg_range(): + data = np.zeros(SHAPE, dtype='float32') + data[1, 1, 1] = 255 + data[2, 2, 2] = -1 + finding = _codes(_img(data), 'probseg', False)['TF703'] + assert finding.fix == 'unsafe' + fixed = images.apply(_img(data), [finding], unsafe=True) + out = np.asanyarray(fixed.image.dataobj) + assert out.min() == 0 and out.max() == 1 + assert out[1, 1, 1] == 1 diff --git a/tfmanager/tests/test_ruleset.py b/tfmanager/tests/test_ruleset.py index f3e2809..0034920 100644 --- a/tfmanager/tests/test_ruleset.py +++ b/tfmanager/tests/test_ruleset.py @@ -24,7 +24,7 @@ def test_entity_order_is_pinned(): def test_codes_used_are_defined(): rules = load_ruleset().rules used = set() - for source in (PACKAGE / 'validate').glob('*.py'): + for source in [*(PACKAGE / 'validate').glob('*.py'), PACKAGE / 'images.py']: used |= set(re.findall(r"'(TF[0-9]{3})'", source.read_text())) assert used - set(rules) == set() schema = (SCHEMA_DIR / 'template_description.schema.json').read_text() diff --git a/tfmanager/tests/test_sanitize.py b/tfmanager/tests/test_sanitize.py new file mode 100644 index 0000000..94fff89 --- /dev/null +++ b/tfmanager/tests/test_sanitize.py @@ -0,0 +1,133 @@ +"""``tfmgr sanitize``: lint the images, fix them, keep the res blocks in step.""" + +from __future__ import annotations + +import json +import os + +import pytest +from click.testing import CliRunner + +from tfmanager.cli import cli +from tfmanager.tests import test_content +from tfmanager.tests.test_content import T, _image + +#: The strict-valid template, with images +template = test_content.template +nb = pytest.importorskip('nibabel') +np = pytest.importorskip('numpy') + + +def _lps_t1w(root, name=f'{T}_res-1_T1w.nii.gz'): + """The res-1 T1w in LPS order, on the grid template_description.json describes.""" + affine = np.diag([-1.0, -1.0, 1.0, 1.0]) + affine[:3, 3] = [-5.0, -6.0, -5.0] # the described origin + data = np.arange(10 * 12 * 10, dtype='int16').reshape((10, 12, 10)) + img = nb.Nifti1Image(data, affine) + img.header.set_sform(affine, 4) + img.header.set_qform(affine, 4) + img.header.set_xyzt_units('mm') + img.to_filename(root / name) + return img + + +def _run(*args): + return CliRunner().invoke(cli, ['sanitize', *map(str, args)]) + + +def test_check_lists_and_changes_nothing(template): + assert _run(template).exit_code == 0 + _lps_t1w(template) + before = (template / f'{T}_res-1_T1w.nii.gz').read_bytes() + result = _run(template, '--check') + assert result.exit_code == 1 + assert 'TF707 not-ras' in result.output + assert '[fix]' in result.output + assert '1 problem: 1 fixable with --fix.' in result.output + assert (template / f'{T}_res-1_T1w.nii.gz').read_bytes() == before + + +def test_fix_reorients_and_updates_the_res_block(template): + """Reorienting moves the origin: the res-1 block follows, so TF701 does not appear.""" + # Every res-1 image in LPS, so that the block can follow them all + for name in (f'{T}_res-1_T1w.nii.gz',): + _lps_t1w(template, name) + for name in (f'{T}_atlas-Smith2020_res-1_dseg.nii.gz', f'{T}_res-1_label-GM_probseg.nii.gz'): + img = nb.load(template / name) + data = np.asanyarray(img.dataobj)[::-1, ::-1, :] + _lps = np.diag([-1.0, -1.0, 1.0, 1.0]) + _lps[:3, 3] = [-5.0, -6.0, -5.0] + out = nb.Nifti1Image(data, _lps) + out.header.set_sform(_lps, 4) + out.header.set_qform(_lps, 4) + out.header.set_xyzt_units('mm') + out.to_filename(template / name) + + result = _run(template, '--fix', '--format', 'json') + report = json.loads(result.output) + assert result.exit_code == 0, result.output + assert set(report['fixed']) == { + f'{T}_res-1_T1w.nii.gz', + f'{T}_atlas-Smith2020_res-1_dseg.nii.gz', + f'{T}_res-1_label-GM_probseg.nii.gz', + } + assert report['issues'] == [] + desc = json.loads((template / 'template_description.json').read_text()) + # The new origin is the world position of the old voxel (9, 11, 0) + assert desc['res']['1']['origin'] == [-14.0, -17.0, -5.0] + assert desc['res']['2']['origin'] == [-5.0, -6.0, -5.0] + fixed = nb.load(template / f'{T}_res-1_T1w.nii.gz') + assert ''.join(nb.aff2axcodes(fixed.affine)) == 'RAS' + + +def test_res_block_kept_when_images_disagree(template): + """Only the T1w moves: the res-1 block still describes the other res-1 images.""" + _lps_t1w(template) + result = _run(template, '--fix', '--format', 'json') + report = json.loads(result.output) + assert report['updated'] == [] + assert [i['code'] for i in report['issues']] == ['TF701'] + assert result.exit_code == 1 + + +def test_unsafe_fixes_need_the_flag(template): + data = np.zeros((10, 12, 10), dtype='float32') + data[2, 2, 2] = 100 + _image(template / f'{T}_res-1_label-GM_probseg.nii.gz', data) + result = _run(template, '--fix') + assert result.exit_code == 1 + assert 'TF703 probseg-range' in result.output + assert '[fix-unsafe]' in result.output + assert '0 fixable with --fix, 1 more with --fix-unsafe' in result.output + + result = _run(template, '--fix-unsafe') + assert result.exit_code == 0, result.output + assert f'Fixed {T}_res-1_label-GM_probseg.nii.gz: TF703' in result.output + fixed = np.asanyarray(nb.load(template / f'{T}_res-1_label-GM_probseg.nii.gz').dataobj) + assert fixed.max() == 1 + + +def test_annexed_images_become_regular_files(template): + """The annex object is never written: the link is replaced by the fixed image.""" + name = f'{T}_res-1_T1w.nii.gz' + key = 'MD5E-s1--0123456789abcdef0123456789abcdef.nii.gz' + objects = template / '.git' / 'annex' / 'objects' / 'Xx' / 'Yy' / key + objects.mkdir(parents=True) + _lps_t1w(objects, key) + (template / name).unlink() + os.symlink(os.path.relpath(objects / key, template), template / name) + original = (objects / key).read_bytes() + + _run(template, '--fix') + assert not (template / name).is_symlink() + assert ''.join(nb.aff2axcodes(nb.load(template / name).affine)) == 'RAS' + assert (objects / key).read_bytes() == original + + +def test_without_nibabel_sanitize_fails(template, monkeypatch): + import sys + + monkeypatch.setitem(sys.modules, 'nibabel', None) + result = _run(template, '--check') + assert result.exit_code == 2 + assert 'needs tfmanager[content]' in result.output diff --git a/tfmanager/utils.py b/tfmanager/utils.py deleted file mode 100644 index d4e4ef9..0000000 --- a/tfmanager/utils.py +++ /dev/null @@ -1,114 +0,0 @@ -"""Genearal purpose routines.""" -import shutil -from pathlib import Path -from contextlib import suppress -from typing import Union, Generator -import numpy as np -import nibabel as nb - - -def glob_all(path: Union[Path, str]) -> Generator[Path, None, None]: - """Return all files in a tree recursively, skipping dot folders.""" - for p in Path(path).iterdir(): - if p.name.startswith("."): - continue - if p.is_dir(): - yield from glob_all(p) - else: - yield p - - -def copy_template( - path=None, - normalize=False, - deoblique=True, - force_dtype=True, - norm_max=1e4, - dest=None, -): - """Revise orientation and dtype of NIfTI files in path.""" - path = Path(path or ".") - dest = dest or path - - retval = [] - - for filename in glob_all(path): - relname = filename.relative_to(path) - destname = dest / relname - destname.parent.mkdir(parents=True, exist_ok=True) - if not filename.name.endswith((".nii", ".nii.gz")): - with suppress(shutil.SameFileError): - shutil.copy(filename, destname) - print(f"Copied: {relname} -> {destname}") - continue - - stem = filename.name[: -len("".join(filename.suffixes))] - modality = stem.split("_")[-1] - - im = nb.as_closest_canonical(nb.load(filename)) - hdr = im.header.copy() - data_dtype = im.get_data_dtype() - data = np.asanyarray(im.dataobj, dtype=data_dtype) - - dtype = "int16" - if modality in ("mask",): - dtype = "uint8" - elif modality in ("dseg",) and np.all(0 <= data) and np.all(data < 256): - dtype = "uint8" - elif not force_dtype or modality not in ("T1w", "T2w", "PD", "PDw"): - dtype = data_dtype - - modified = np.dtype(dtype) != np.dtype(data_dtype) - - if modality in ("probseg",): - modified = True - dtype = "float32" - data = im.get_fdata(dtype="float32") - data -= data.min() - data *= 1.0 / data.max() - - elif normalize and modality in ("T1w", "T2w", "PD", "PDw"): - fdata = im.get_fdata() - fdata -= fdata.min() - data = np.round(norm_max * fdata / np.percentile(fdata, 99.9)).astype(dtype) - hdr["cal_min"] = 0 - hdr["cal_max"] = norm_max - - affine = im.affine.copy() - hdr.set_data_dtype(dtype) - - if deoblique and np.any(nb.affines.obliquity(affine) > 1e-2): - modified = True - card = np.diag(im.header.get_zooms()[:3]) - cardrot = affine[:3, :3].dot(np.linalg.inv(card)) - # If center of coordinates not at volume's center - # do not modify its relative location w.r.t. data - affine = np.linalg.inv(cardrot).dot(affine) - affine[:3, :3] = card # round off-diagonal elements - - sform, scode = im.header.get_sform(coded=True) - qform, qcode = im.header.get_qform(coded=True) - - if ( - modified - or not all(code == 4 for code in (scode, qcode)) - or sform is None - or not np.allclose(sform, affine) - or qform is None - or not np.allclose(qform, affine) - ): - nii = nb.Nifti1Image(data.astype(dtype), affine, hdr) - nii.header.set_sform(affine, 4) - nii.header.set_qform(affine, 4) - nii.header.set_slope_inter(slope=1.0, inter=0.0) - nii.header.set_xyzt_units(xyz="mm") - nii.to_filename(destname) - print(f"Fixed NIfTI headers: {relname} -> {destname}") - retval.append(filename) - elif filename != destname: - shutil.copy(filename, destname) - print(f"Copied: {relname} -> {destname}") - else: - print(f"File {filename} not modified.") - - return retval diff --git a/tfmanager/validate/content.py b/tfmanager/validate/content.py index ad35334..35b1b6e 100644 --- a/tfmanager/validate/content.py +++ b/tfmanager/validate/content.py @@ -17,58 +17,81 @@ def _grid(ctx: Context, res: str, cohort: str | None) -> dict | None: return grid or None +def grid_mismatch(described: dict | None, actual: dict) -> list[str]: + """The keys (zooms, shape, origin) where an image's grid and its ``res`` block differ.""" + import numpy as np + + return [ + key + for key in ('zooms', 'shape', 'origin') + if described + and key in described + and not ( + isinstance(described[key], list) + and len(described[key]) == len(actual[key]) + and np.allclose(described[key], actual[key], atol=ATOL) + ) + ] + + +def nifti_files(ctx: Context): + """``(path, parsed name, local path)`` of the NIfTI images whose content is available.""" + for path, f in ctx.bids_files.items(): + if f.extension not in ('.nii.gz', '.nii'): + continue + local = ctx.tree.local_path(path) + if local is not None: + yield path, f, local + + @check('content') def check_images(ctx: Context): - """TF701-TF706: headers against the res block; segmentation values against tables.""" + """TF701-TF710: headers against the res block, storage, and segmentation values.""" try: import nibabel as nb import numpy as np + + from .. import images except ImportError: # pragma: no cover ctx.report('TF700', None, 'Install tfmanager[content] to check image content.') return - for path, f in ctx.bids_files.items(): - if f.extension not in ('.nii.gz', '.nii'): + anatomical = { + s for s, spec in ctx.ruleset.suffixes.items() if spec.get('group') == 'anatomical' + } + for path, f, local in nifti_files(ctx): + try: + img = nb.load(local) + problem = images.payload_problem(local, img) + if problem is None: + findings = images.inspect(img, f.suffix, f.suffix in anatomical) + except Exception as exc: # any reading error is the file's problem + problem = f'{type(exc).__name__}: {exc}' + if problem is not None: + ctx.report('TF711', path, problem[:300]) continue - local = ctx.tree.local_path(path) - if local is None: - continue - img = nb.load(local) - hdr = img.header - - sform, scode = hdr.get_sform(coded=True) - qform, qcode = hdr.get_qform(coded=True) - if scode == 0 and qcode == 0: - ctx.report('TF702', path, 'Neither sform nor qform is set.') - elif scode and qcode and not np.allclose(sform, qform, atol=ATOL): - ctx.report('TF702', path, 'sform and qform disagree.') + for finding in findings: + ctx.report(finding.code, path, finding.message, autofix=finding.fix) res = f.entities.get('res') grid = _grid(ctx, res, f.entities.get('cohort')) if res else None - if grid: - zooms = [float(z) for z in hdr.get_zooms()[:3]] - shape = list(img.shape[:3]) - origin = [float(o) for o in img.affine[:3, 3]] - for key, value in (('zooms', zooms), ('shape', shape), ('origin', origin)): - if key in grid and not np.allclose(grid[key], value, atol=ATOL): - ctx.report('TF701', path, f'{key} {value} (res-{res} says {grid[key]}).') - - if f.suffix not in ('dseg', 'probseg'): - continue - data = np.asanyarray(img.dataobj) + actual = images.grid(img) + for key in grid_mismatch(grid, actual): + ctx.report('TF701', path, f'{key} {actual[key]} (res-{res} says {grid[key]}).') + if f.suffix == 'probseg': - low, high = float(np.nanmin(data)), float(np.nanmax(data)) - if low < -ATOL or high > 1 + ATOL: - ctx.report('TF703', path, f'Values in [{low:g}, {high:g}].') - if data.ndim == 4 and 'label' not in f.entities: + if len(img.shape) == 4 and 'label' not in f.entities: table = lookup_for(ctx, f) rows = len(read(ctx, table.path).rows) if table else None - if rows is not None and rows != data.shape[3]: + if rows is not None and rows != img.shape[3]: ctx.report( - 'TF706', path, f'{data.shape[3]} volumes, {rows} rows in {table.path}.' + 'TF706', path, f'{img.shape[3]} volumes, {rows} rows in {table.path}.' ) continue + if f.suffix != 'dseg': + continue + data = np.asanyarray(img.dataobj) if not np.issubdtype(data.dtype, np.integer) and not np.all(np.mod(data, 1) == 0): ctx.report('TF704', path, f'Non-integer values ({data.dtype}).') continue diff --git a/tfmanager/validate/core.py b/tfmanager/validate/core.py index 215c33d..0a2aa24 100644 --- a/tfmanager/validate/core.py +++ b/tfmanager/validate/core.py @@ -28,6 +28,8 @@ class Issue: """Path relative to the template directory (or to the Archive for TF8xx).""" suggestion: str | None = None """A suggested value, e.g. the file's name in BIDS order.""" + autofix: str | None = None + """``'safe'`` or ``'unsafe'`` when ``tfmgr sanitize --fix`` / ``--fix-unsafe`` corrects it.""" def as_dict(self) -> dict: return {k: v for k, v in asdict(self).items() if v is not None} @@ -95,7 +97,14 @@ def json(self, path: str): except ValueError: return None - def report(self, code: str, path: str | None, message: str, suggestion: str | None = None): + def report( + self, + code: str, + path: str | None, + message: str, + suggestion: str | None = None, + autofix: str | None = None, + ): rule = self.ruleset.rule(code) severity = rule.legacy if self.legacy else rule.severity self.issues.append( @@ -107,6 +116,7 @@ def report(self, code: str, path: str | None, message: str, suggestion: str | No template=self.tree.name, path=path, suggestion=suggestion, + autofix=autofix, ) ) diff --git a/tfmanager/validate/licenses.py b/tfmanager/validate/licenses.py index 3c5764f..103ee2a 100644 --- a/tfmanager/validate/licenses.py +++ b/tfmanager/validate/licenses.py @@ -68,11 +68,17 @@ def check_licenses(ctx: Context): elif expression is not None: declared = licenses.header(text) if declared is None: + # Suggest the header only for a valid expression (TF502 reports the others) + valid = licenses.check(expression) if isinstance(expression, str) else None ctx.report( 'TF505', 'LICENSE', 'No SPDX-License-Identifier header line.', - suggestion=f'SPDX-License-Identifier: {expression}', + suggestion=( + f'SPDX-License-Identifier: {valid.normalized}' + if valid is not None and valid.valid + else None + ), ) elif not licenses.same(declared, expression): ctx.report('TF505', 'LICENSE', f'Header says {declared!r}; License is {expression!r}.') diff --git a/tfmanager/validate/report.py b/tfmanager/validate/report.py index f6e4e50..5d55472 100644 --- a/tfmanager/validate/report.py +++ b/tfmanager/validate/report.py @@ -55,6 +55,8 @@ def _human(issues, shown, meta) -> str: current = i.template lines.append(f'\n{current or "Archive"}') line = f' {i.severity.upper():7} {i.code} {i.slug:24} {i.path or ""}: {i.message}' + if i.autofix: + line += ' [fix]' if i.autofix == 'safe' else ' [fix-unsafe]' if i.suggestion: line += f'\n{"":44}-> {i.suggestion}' lines.append(line)