-
Notifications
You must be signed in to change notification settings - Fork 20
Metadata correction #2177
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Metadata correction #2177
Changes from 8 commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
8ea2255
feat: Add API management command for correcting corrupt metadata
candleindark 25e4cfa
feat: add solution to correct `Affiliation` corruption
candleindark eba4c3b
Move test_correct_metadata.py into tests/
jjnesbitt a21f6d0
feat: change call interface of `correct_metadata` cmd
candleindark 256a6dc
Add --check flag
jjnesbitt a895921
Simplify correct_metadata and helper functions
jjnesbitt b02e2ff
Only apply correction to draft versions
jjnesbitt c2c14f5
Add audit event to correct_metadata command
jjnesbitt 3ee22a7
Use queryset iterators to reduce memory usage
jjnesbitt File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,123 @@ | ||
| from __future__ import annotations | ||
|
|
||
| from copy import deepcopy | ||
| import sys | ||
| import typing | ||
| from typing import Any | ||
|
|
||
| from django.db import transaction | ||
| import djclick as click | ||
|
|
||
| from dandiapi.api.manifests import write_dandiset_jsonld, write_dandiset_yaml | ||
| from dandiapi.api.models import Version | ||
| from dandiapi.api.services import audit | ||
|
|
||
|
|
||
| @click.command( | ||
| help='Correct corrupted metadata. If `--all` is provided, apply the correction to ' | ||
| 'all Dandiset versions. Otherwise, provide the Dandiset to ' | ||
| 'apply the correction to.' | ||
| ) | ||
| @click.argument('dandiset', required=False) | ||
| @click.option( | ||
| '--all', | ||
| 'apply_to_all', | ||
| is_flag=True, | ||
| default=False, | ||
| help='Apply the correction to all Dandiset versions ' | ||
| '(cannot be combined with dandiset argument).', | ||
| ) | ||
| @click.option( | ||
| '--check', | ||
| is_flag=True, | ||
| help="Don't perform any changes, just check for corrupted metadata.", | ||
| ) | ||
| def correct_metadata( # noqa: C901 | ||
| *, dandiset: str | None, apply_to_all: bool, check: bool | ||
| ): | ||
| if apply_to_all: | ||
| if dandiset is not None: | ||
| raise click.UsageError('Cannot specify `--all` together with `dandiset` argument.') | ||
| elif dandiset is None: | ||
| raise click.UsageError('Either `--all` or `dandiset` argument must be provided.') | ||
|
|
||
| # Get version queryset | ||
| vers = Version.objects.all() | ||
| if not apply_to_all: | ||
| dandiset = typing.cast(str, dandiset) | ||
| vers = vers.filter(dandiset=int(dandiset), version='draft') | ||
|
|
||
| if not vers.exists(): | ||
| click.echo('No matching versions found') | ||
| return | ||
|
|
||
| # For each version, find and fix metadata corruptions, along with saving out manifest files | ||
| for ver in vers: | ||
| new_meta = correct_affiliation_corruption(ver.metadata) | ||
| if new_meta is None: | ||
| continue | ||
|
|
||
| click.echo(f'Found corruption in {ver}') | ||
| if check: | ||
| continue | ||
|
|
||
| # Save each version in a separate transaction to avoid de-sync with dandiset yaml/jsonld | ||
| with transaction.atomic(): | ||
| write_dandiset_yaml(ver) | ||
| write_dandiset_jsonld(ver) | ||
| click.echo(f'\tWrote dandiset yaml and json for version {ver}') | ||
|
|
||
| ver.metadata = new_meta | ||
| ver.save() | ||
|
|
||
| audit.update_metadata( | ||
| dandiset=ver.dandiset, | ||
| metadata=new_meta, | ||
| user=None, | ||
| admin=True, | ||
| description='Apply metadata correction from https://github.com/dandi/dandi-schema/issues/276', | ||
| ) | ||
|
|
||
| # Remaining check is not needed since no data was modified | ||
| if check: | ||
| return | ||
|
|
||
| # If we find any un-fixed instances, raise exception | ||
| remaining = [ver for ver in vers if correct_affiliation_corruption(ver.metadata) is not None] | ||
|
jjnesbitt marked this conversation as resolved.
Outdated
|
||
| if remaining: | ||
| click.echo( | ||
| click.style(f'\nFound remaining corrupted versions: {remaining}', fg='red', bold=True) | ||
| ) | ||
| sys.exit(1) | ||
|
|
||
|
|
||
| def correct_affiliation_corruption(meta: dict) -> dict | None: | ||
| """ | ||
| Correct corruptions in JSON objects with the `"schemaKey"` of `"Affiliation"`. | ||
|
|
||
| :param meta: The Dandiset metadata instance potentially containing the objects to be corrected. | ||
| :return: If there is correction to be made, return the corrected metadata; otherwise, return | ||
| `None`. | ||
|
|
||
| Note: This function corrects the corruptions described in | ||
| https://github.com/dandi/dandi-schema/issues/276 | ||
| """ | ||
| new_meta = deepcopy(meta) | ||
| correct_objs(new_meta) | ||
|
|
||
| return new_meta if new_meta != meta else None | ||
|
|
||
|
|
||
| def correct_objs(data: Any) -> None: | ||
| if isinstance(data, dict): | ||
| if 'schemaKey' in data and data['schemaKey'] == 'Affiliation': | ||
| data.pop('contactPoint', None) | ||
| data.pop('includeInCitation', None) | ||
| data.pop('roleName', None) | ||
| for value in data.values(): | ||
| correct_objs(value) | ||
| elif isinstance(data, list): | ||
| for item in data: | ||
| correct_objs(item) | ||
| else: | ||
| return | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,74 @@ | ||
| from __future__ import annotations | ||
|
|
||
| from copy import deepcopy | ||
|
|
||
| import pytest | ||
|
|
||
| from dandiapi.api.management.commands.correct_metadata import correct_affiliation_corruption | ||
|
|
||
|
|
||
| @pytest.mark.parametrize( | ||
| ('input_meta', 'expected_output'), | ||
| [ | ||
| # No Affiliation object: nothing to change. | ||
| ( | ||
| {'key': 'value'}, | ||
| None, | ||
| ), | ||
| # Affiliation exists but has no unwanted fields: returns None. | ||
| ( | ||
| {'affiliation': {'schemaKey': 'Affiliation', 'name': 'Alice'}}, | ||
| None, | ||
| ), | ||
| # Single unwanted field ("contactPoint") should be removed. | ||
| ( | ||
| {'affiliation': {'schemaKey': 'Affiliation', 'name': 'Alice', 'contactPoint': 'info'}}, | ||
| {'affiliation': {'schemaKey': 'Affiliation', 'name': 'Alice'}}, | ||
| ), | ||
| # Multiple unwanted fields should all be removed. | ||
| ( | ||
| { | ||
| 'affiliation': { | ||
| 'schemaKey': 'Affiliation', | ||
| 'name': 'Test', | ||
| 'contactPoint': 'a', | ||
| 'includeInCitation': 'b', | ||
| 'roleName': 'c', | ||
| } | ||
| }, | ||
| {'affiliation': {'schemaKey': 'Affiliation', 'name': 'Test'}}, | ||
| ), | ||
| # Nested Affiliation objects should be corrected. | ||
| ( | ||
| { | ||
| 'users': [ | ||
| {'profile': {'schemaKey': 'Affiliation', 'name': 'Bob', 'roleName': 'Member'}}, | ||
| {'profile': {'schemaKey': 'Affiliation', 'name': 'Charlie'}}, | ||
| ], | ||
| 'data': {'schemaKey': 'NotAffiliation', 'contactPoint': 'should not be touched'}, | ||
| }, | ||
| { | ||
| 'users': [ | ||
| {'profile': {'schemaKey': 'Affiliation', 'name': 'Bob'}}, | ||
| {'profile': {'schemaKey': 'Affiliation', 'name': 'Charlie'}}, | ||
| ], | ||
| 'data': {'schemaKey': 'NotAffiliation', 'contactPoint': 'should not be touched'}, | ||
| }, | ||
| ), | ||
| ], | ||
| ) | ||
| def test_correct_affiliation_corruption(input_meta, expected_output): | ||
| """ | ||
| Test `correct_affiliation_corruption()`. | ||
|
|
||
| Ensure that it returns the correct modified metadata (if any corrections are needed) | ||
| while not mutating the original input. | ||
| """ | ||
| # Make a deep copy of the input to ensure immutability. | ||
| original_meta = deepcopy(input_meta) | ||
| result = correct_affiliation_corruption(input_meta) | ||
|
|
||
| assert result == expected_output | ||
|
|
||
| # Verify that the original metadata has not been mutated. | ||
| assert input_meta == original_meta, 'The input metadata should remain unchanged.' |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.