Last active
September 13, 2023 03:03
-
-
Save satra/29404d965226e4c99fb48e7502953503 to your computer and use it in GitHub Desktop.
Add an existing asset to a new dandiset
This file contains 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
from dandi.dandiapi import DandiAPIClient | |
from dandischema.models import Resource, RelationType | |
from getpass import getpass | |
import pandas as pd | |
import json | |
token = getpass() # Enter dandi api token when prompted | |
df = pd.read_csv("dandi_assets_l1.csv") | |
da = DandiAPIClient(token=token) | |
# The new dandiset to write to | |
ds = da.get_dandiset('123456') # replace with new dandiset id | |
# post for one asset | |
for row in df.iterrows(): | |
print(f"processing row: {row[0]}") | |
# get asset | |
asset = da.get_asset(row[1].dandi_asset_id) | |
asset_meta = asset.get_metadata() | |
# connect asset to old asset | |
asset_meta.sameAs = [asset_meta.id.replace('dandiasset:', 'http://dandiarchive.org/asset/')] | |
# create payload for post | |
data = { | |
"metadata": json.dumps(asset_meta.json_dict()), | |
"blob_id": asset.blob, | |
} | |
# this will generate an exception if the path already exists | |
out = da.post(path=ds.api_path + 'versions/draft/assets/', data=data) | |
# Add old dandisets as sources of the current dandiset in the related resource section | |
ds_meta = ds.get_metadata() | |
resources = ds_meta.relatedResource or [] | |
for url in df.dandiset_url.unique(): | |
ds_old = da.get_dandiset(url.split('/')[-1]) | |
resources.append(Resource(url=url, | |
name=ds_old.get_metadata().name, | |
relation=RelationType.IsDerivedFrom | |
) | |
) | |
ds_meta.relatedResource = resources | |
ds.set_metadata(ds_meta) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment