Skip to content

Biotope Annotate

Draft stage

Biotope is in draft stage. Functionality may be missing or incomplete.
The API is subject to change.

biotope annotate is the editorial companion to biotope add.

  • biotope add creates or refreshes the canonical JSON-LD.
  • biotope annotate apply merges bulk human edits from a scoped YAML scaffold.
  • biotope annotate edit is the interactive fallback.
  • biotope status remains the completeness gate.

Commands

biotope annotate apply

Apply a scoped .biotope.yaml scaffold to one dataset JSON-LD.

Usage

biotope annotate apply <dir-or-yaml> [--set KEY=VALUE ...]

<dir-or-yaml> can be:

  • a dataset directory, which resolves to <dir>/.biotope.yaml
  • a YAML file (.biotope.yaml or another scaffold path), typically the one produced by biotope add <dir>

--set applies overrides at apply time. Bare keys default to the dataset scope for shared fields. Use dataset.<field>=... or record_set.<field>=... for explicit scope.

Examples

# Apply the scaffold next to a dataset directory
biotope annotate apply data/opentargets

# Apply an explicit scaffold file
biotope annotate apply data/opentargets/.biotope.yaml

# Override one dataset field at apply time
biotope annotate apply data/opentargets --set creator="Open Targets Consortium"

# Override a record-set field across all record-set rows
biotope annotate apply data/opentargets --set record_set.description="Needs review"

Scaffold format

biotope add <dir> writes one .biotope.yaml per dataset directory. The scaffold has one dataset block and a record_sets list:

dataset:
  source_path: data/opentargets
  name: Open Targets
  description: OT v3
  creator: Open Targets
  creator_email: info@opentargets.org
  license: CC-BY-4.0
  url: https://opentargets.org
  citation: "Please cite..."
  version: "3"
  keywords: [gene, disease, variant]
  access_restrictions: public

record_sets:
  - id: "#genes"
    source_path: data/opentargets/genes
    name: genes
    description: Gene table
    encoding_format: application/parquet
  - id: "#diseases"
    source_path: data/opentargets/diseases
    name: diseases
    description: Disease table
    encoding_format: application/parquet

Join rules:

  • exactly one dataset block is required
  • each record_sets[] entry joins to a recordSet[] in the JSON-LD by id
  • unknown ids and missing dataset blocks are hard errors
  • source_path is for human context, not a primary key

biotope annotate edit

Interactive metadata editing for one file or tracked file set.

Usage

biotope annotate edit [OPTIONS]

Options

  • --file-path, -f: specific file to annotate
  • --prefill-metadata, -p: JSON string with pre-filled metadata
  • --staged, -s: annotate staged files
  • --incomplete, -i: revisit tracked files with incomplete metadata

Examples

biotope annotate edit --staged
biotope annotate edit --incomplete
biotope annotate edit --file-path data/experiment.csv

biotope annotate interactive remains available as a hidden alias.

biotope annotate validate

Validate a Croissant metadata file using the mlcroissant CLI.

biotope annotate validate --jsonld .biotope/datasets/data/opentargets.jsonld

biotope annotate load

Load records from a dataset using its Croissant metadata.

biotope annotate load --jsonld .biotope/datasets/data/opentargets.jsonld --record-set genes

Completeness

Use biotope status to see whether tracked metadata meets the current annotation requirements.

Command for creating dataset metadata definitions in Croissant format.

annotate(ctx)

Create dataset metadata in Croissant format.

Source code in biotope/biotope/commands/annotate.py
@click.group(invoke_without_command=True)
@click.pass_context
def annotate(ctx: click.Context) -> None:
    """Create dataset metadata in Croissant format."""
    if ctx.invoked_subcommand is None:
        click.echo(ctx.get_help())
        ctx.fail("Missing command.")

apply(path, set_pairs)

Apply a scoped YAML scaffold to one dataset JSON-LD.

Source code in biotope/biotope/commands/annotate.py
@annotate.command()
@click.argument("path", type=click.Path(exists=True, path_type=Path))
@click.option(
    "--set",
    "set_pairs",
    multiple=True,
    help="Apply KEY=VALUE overrides. Use dataset.<field>=... or record_set.<field>=... for explicit scope.",
)
def apply(path: Path, set_pairs: tuple[str, ...]) -> None:
    """Apply a scoped YAML scaffold to one dataset JSON-LD."""
    console = Console()
    biotope_root = find_biotope_root()
    if not biotope_root:
        click.echo("❌ Not in a biotope project. Run 'biotope init' first.")
        raise click.Abort

    try:
        overrides = parse_key_value_pairs(set_pairs, "--set")
    except ValueError as exc:
        raise click.BadParameter(str(exc)) from exc

    resolved = path.resolve()
    if resolved.is_dir():
        try:
            target = resolve_target(resolved, biotope_root)
        except ValueError as exc:
            click.echo(f"❌ {exc}")
            raise click.Abort from exc
        scaffold_path = target.scaffold_path
        if not scaffold_path.exists():
            click.echo(f"❌ No {SCAFFOLD_FILENAME} in {resolved}. Run `biotope add {path}` first.")
            raise click.Abort
    else:
        scaffold_path = resolved
        if scaffold_path.suffix not in {".yaml", ".yml"}:
            click.echo("❌ annotate apply expects a directory or a YAML scaffold.")
            raise click.Abort
        try:
            target = resolve_target(scaffold_path.parent, biotope_root)
        except ValueError as exc:
            click.echo(f"❌ {exc}")
            raise click.Abort from exc

    if not target.metadata_path.exists():
        click.echo(f"❌ Target metadata file not found: {target.metadata_path}")
        raise click.Abort

    updated = _apply_scaffold(console, scaffold_path, target, overrides, biotope_root)
    if updated:
        try:
            subprocess.run(["git", "add", ".biotope/"], cwd=biotope_root, check=True)
            console.print("\n✅ Staged metadata changes in Git")
        except subprocess.CalledProcessError as exc:
            console.print(f"⚠️  Warning: Could not stage changes in Git: {exc}")

edit(file_path=None, prefill_metadata=None, staged=False, incomplete=False)

Interactive annotation process for files.

This command supports multiple modes: 1. Single file annotation: --file-path 2. Staged files annotation: --staged 3. Incomplete files annotation: --incomplete

For bulk annotation from CSV files, use: biotope annotate apply

Examples:

biotope annotate edit --file-path data.csv biotope annotate edit --staged biotope annotate edit --incomplete

Parameters:

Name Type Description Default
file_path str | None

Path to a single file to annotate.

None
prefill_metadata str | None

JSON string of metadata to pre-fill the prompts with.

None
staged bool

Annotate all staged files.

False
incomplete bool

Annotate all tracked files with incomplete metadata.

False
Source code in biotope/biotope/commands/annotate.py
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
@annotate.command(name="edit")
@click.option(
    "--file-path",
    "-f",
    type=click.Path(exists=True),
    help="Path to the file to annotate",
)
@click.option(
    "--prefill-metadata",
    "-p",
    type=str,
    help="JSON string containing pre-filled metadata",
)
@click.option(
    "--staged",
    "-s",
    is_flag=True,
    help="Annotate all staged files",
)
@click.option(
    "--incomplete",
    "-i",
    is_flag=True,
    help="Annotate all tracked files with incomplete metadata",
)
def edit(
    file_path: str | None = None,
    prefill_metadata: str | None = None,
    staged: bool = False,
    incomplete: bool = False,
) -> None:
    """Interactive annotation process for files.

    This command supports multiple modes:
    1. Single file annotation: --file-path
    2. Staged files annotation: --staged
    3. Incomplete files annotation: --incomplete

    For bulk annotation from CSV files, use: biotope annotate apply <dir-or-csv>

    Examples:
        biotope annotate edit --file-path data.csv
        biotope annotate edit --staged
        biotope annotate edit --incomplete

    Args:
        file_path: Path to a single file to annotate.
        prefill_metadata: JSON string of metadata to pre-fill the prompts with.
        staged: Annotate all staged files.
        incomplete: Annotate all tracked files with incomplete metadata.
    """
    console = Console()

    # Initialize metadata with pre-filled values if provided
    dynamic_metadata = json.loads(prefill_metadata) if prefill_metadata else {}

    # Load project-level metadata for pre-filling if we're in a biotope project
    biotope_root = find_biotope_root()
    if biotope_root:
        from biotope.utils import load_project_metadata

        project_metadata = load_project_metadata(biotope_root)

        # Merge project metadata with any provided prefill metadata
        # Project metadata takes precedence for common fields
        for key, value in project_metadata.items():
            if key not in dynamic_metadata:
                dynamic_metadata[key] = value

    # Merge with standard context and structure
    metadata = merge_metadata(dynamic_metadata)

    # Handle staged files
    if staged:
        if not biotope_root:
            click.echo("❌ Not in a biotope project. Run 'biotope init' first.")
            raise click.Abort

        staged_files = get_staged_files(biotope_root)
        if not staged_files:
            click.echo("❌ No files staged. Use 'biotope add <file>' first.")
            raise click.Abort

        console.print(f"[bold blue]Annotating {len(staged_files)} staged file(s)[/]")

        for i, file_info in enumerate(staged_files):
            file_path = biotope_root / file_info["file_path"]
            console.print(f"\n[bold green]File {i+1}/{len(staged_files)}: {file_path.name}[/]")

            # Find the existing metadata file for this data file
            datasets_dir = biotope_root / ".biotope" / "datasets"
            relative_path = file_path.relative_to(biotope_root)
            metadata_file = datasets_dir / relative_path.with_suffix(".jsonld")

            # Check if metadata file exists
            if metadata_file.exists():
                # Load existing metadata to pre-fill
                try:
                    with open(metadata_file) as f:
                        existing_metadata = normalize_metadata_shape(json.load(f))
                except (json.JSONDecodeError, IOError):
                    existing_metadata = {}

                # Extract file information from existing metadata
                file_metadata = {
                    "name": existing_metadata.get("name", file_path.stem),
                    "description": existing_metadata.get("description", f"Dataset for {file_path.name}"),
                    "distribution": existing_metadata.get("distribution", []),
                }

                # Merge with project metadata
                if biotope_root:
                    from biotope.utils import load_project_metadata

                    project_metadata = load_project_metadata(biotope_root)
                    for key, value in project_metadata.items():
                        if key not in file_metadata and key not in existing_metadata:
                            file_metadata[key] = value

                # Run interactive annotation for this file (updating existing)
                _run_interactive_annotation(console, metadata_file, file_metadata, biotope_root, update_existing=True)
            else:
                # Pre-fill with file information for new metadata
                file_metadata = {
                    "name": file_path.stem,
                    "description": f"Dataset for {file_path.name}",
                    "distribution": [
                        {
                            "@type": FILE_OBJECT_TYPE,
                            "@id": f"file_{file_info['sha256'][:8]}",
                            "name": file_path.name,
                            "contentUrl": str(file_path.relative_to(biotope_root)),
                            "sha256": file_info["sha256"],
                            "contentSize": file_info["size"],
                        }
                    ],
                }

                # Merge with project metadata
                if biotope_root:
                    from biotope.utils import load_project_metadata

                    project_metadata = load_project_metadata(biotope_root)
                    for key, value in project_metadata.items():
                        if key not in file_metadata:
                            file_metadata[key] = value

                # Run interactive annotation for this file (creating new)
                _run_interactive_annotation(console, file_path, file_metadata, biotope_root)

        return

    # Handle incomplete files
    if incomplete:
        if not biotope_root:
            click.echo("❌ Not in a biotope project. Run 'biotope init' first.")
            raise click.Abort

        # Get all tracked files and check their annotation status
        from biotope.validation import get_all_tracked_files, get_annotation_status_for_files

        tracked_files = get_all_tracked_files(biotope_root)
        if not tracked_files:
            click.echo("❌ No tracked files found. Use 'biotope add <file>' first.")
            raise click.Abort

        annotation_status = get_annotation_status_for_files(biotope_root, tracked_files)
        incomplete_files = [file_path for file_path, (is_annotated, _) in annotation_status.items() if not is_annotated]

        if not incomplete_files:
            click.echo("✅ All tracked files are properly annotated!")
            return

        console.print(f"[bold blue]Found {len(incomplete_files)} file(s) with incomplete annotation[/]")

        for i, file_path in enumerate(incomplete_files):
            metadata_file = biotope_root / file_path
            console.print(f"\n[bold green]File {i+1}/{len(incomplete_files)}: {metadata_file.stem}[/]")

            # Load existing metadata to pre-fill
            try:
                with open(metadata_file) as f:
                    existing_metadata = normalize_metadata_shape(json.load(f))
            except (json.JSONDecodeError, IOError):
                existing_metadata = {}

            # Extract file information from existing metadata
            file_info = {
                "name": existing_metadata.get("name", metadata_file.stem),
                "description": existing_metadata.get("description", f"Dataset for {metadata_file.stem}"),
                "distribution": existing_metadata.get("distribution", []),
            }

            # Merge with project metadata for missing fields
            if biotope_root:
                from biotope.utils import load_project_metadata

                project_metadata = load_project_metadata(biotope_root)
                for key, value in project_metadata.items():
                    if key not in file_info and key not in existing_metadata:
                        file_info[key] = value

            # Run interactive annotation for this file (updating existing)
            _run_interactive_annotation(console, metadata_file, file_info, biotope_root, update_existing=True)

        return

    # If file path is provided, use it
    if file_path:
        metadata["file_path"] = file_path

    # Create a nice header
    console.print(
        Panel(
            "[bold blue]Biotope Dataset Metadata Creator[/]",
            subtitle="Create scientific dataset metadata in Croissant format",
        ),
    )

    console.print(Markdown("This wizard will help you document your scientific dataset with standardized metadata."))
    console.print()

    # Show project metadata info if available
    if biotope_root:
        from biotope.utils import load_project_metadata

        project_metadata = load_project_metadata(biotope_root)
        if project_metadata:
            console.print("[bold green]Project Metadata Available[/]")
            console.print("─" * 50)
            console.print("The following project-level metadata will be used as defaults:")

            table = Table(show_header=False)
            table.add_column("Field", style="cyan")
            table.add_column("Value", style="green")

            for key, value in project_metadata.items():
                if key == "creator" and isinstance(value, dict):
                    display_value = value.get("name", str(value))
                else:
                    display_value = str(value)
                table.add_row(key, display_value)

            console.print(table)
            console.print()

    # Section: Basic Information
    console.print("[bold green]Basic Dataset Information[/]")
    console.print("─" * 50)

    # Use pre-filled name if available, otherwise prompt
    dataset_name = metadata.get("name", "")
    if not dataset_name:
        dataset_name = click.prompt(
            "Dataset name (a short, descriptive title; no spaces allowed)",
            default="",
        )
    else:
        dataset_name = click.prompt(
            "Dataset name (a short, descriptive title; no spaces allowed)",
            default=dataset_name,
        )

    description = click.prompt(
        "Dataset description (what does this dataset contain and what is it used for?)",
        default=metadata.get("description", ""),
    )

    # Section: Source Information
    console.print("\n[bold green]Data Source Information[/]")
    console.print("─" * 50)
    console.print("Where did this data come from? (e.g., a URL, database name, or experiment)")
    data_source = click.prompt("Data source", default=metadata.get("url", ""))

    # Section: Ownership and Dates
    console.print("\n[bold green]Ownership and Dates[/]")
    console.print("─" * 50)

    project_name = click.prompt(
        "Project name",
        default=metadata.get("cr:projectName", Path.cwd().name),
    )

    contact = click.prompt(
        "Contact person (email preferred)",
        default=metadata.get("creator", {}).get("name", getpass.getuser()),
    )

    date = click.prompt(
        "Creation date (YYYY-MM-DD)",
        default=metadata.get("dateCreated", datetime.now(tz=timezone.utc).isoformat()),
    )

    # Section: Access Information
    console.print("\n[bold green]Access Information[/]")
    console.print("─" * 50)

    # Create a table for examples
    table = Table(title="Access Restriction Examples")
    table.add_column("Type", style="cyan")
    table.add_column("Description", style="green")
    table.add_row("Public", "Anyone can access and use the data")
    table.add_row("Academic", "Restricted to academic/research use only")
    table.add_row("Approval", "Requires explicit approval from data owner")
    table.add_row("Embargo", "Will become public after a specific date")
    console.print(table)

    has_access_restrictions = Confirm.ask(
        "Does this dataset have access restrictions?",
        default=bool(metadata.get("cr:accessRestrictions")),
    )

    access_restrictions = None
    if has_access_restrictions:
        access_restrictions = Prompt.ask(
            "Please describe the access restrictions",
            default=metadata.get("cr:accessRestrictions", ""),
        )
        if not access_restrictions.strip():
            access_restrictions = None

    # Section: Additional Information
    console.print("\n[bold green]Additional Information[/]")
    console.print("─" * 50)
    console.print("[italic]The following fields are optional but recommended for scientific datasets[/]")

    # Get default format from distribution if available
    default_format = ""
    distribution = metadata.get("distribution", [])
    if distribution and len(distribution) > 0:
        default_format = distribution[0].get("encodingFormat", "")

    format = click.prompt(
        "File format (MIME type, e.g., text/csv, application/json, application/x-hdf5, application/fastq)",
        default=metadata.get("encodingFormat") or metadata.get("format") or default_format,
    )

    legal_obligations = click.prompt(
        "Legal obligations (e.g., citation requirements, licenses)",
        default=metadata.get("cr:legalObligations", ""),
    )

    collaboration_partner = click.prompt(
        "Collaboration partner and institute",
        default=metadata.get("cr:collaborationPartner", ""),
    )

    # Section: Publication Information
    console.print("\n[bold green]Publication Information[/]")
    console.print("─" * 50)
    console.print("[italic]The following fields are recommended for proper dataset citation[/]")

    publication_date = click.prompt(
        "Publication date (YYYY-MM-DD)",
        default=metadata.get("datePublished", date),  # Use creation date as default
    )

    version = click.prompt(
        "Dataset version",
        default=metadata.get("version", "1.0"),
    )

    license_url = click.prompt(
        "License URL",
        default=metadata.get("license", "https://creativecommons.org/licenses/by/4.0/"),
    )

    citation = click.prompt(
        "Citation text",
        default=metadata.get("citation", f"Please cite this dataset as: {dataset_name} ({date.split('-')[0]})"),
    )

    # Update metadata with new values while preserving any existing fields
    new_metadata = {
        "@context": get_standard_context(),  # Use the standard context
        "@type": "sc:Dataset",
        "name": dataset_name,
        "description": description,
        "url": data_source,
        "creator": {
            "@type": "Person",
            "name": contact,
        },
        "dateCreated": date,
        "cr:projectName": project_name,
        "datePublished": publication_date,
        "version": version,
        "license": license_url,
        "citation": citation,
    }

    # Only add access restrictions if they exist
    if access_restrictions:
        new_metadata["cr:accessRestrictions"] = access_restrictions

    # Add optional fields if provided
    if format:
        new_metadata["encodingFormat"] = format
    if legal_obligations:
        new_metadata["cr:legalObligations"] = legal_obligations
    if collaboration_partner:
        new_metadata["cr:collaborationPartner"] = collaboration_partner

    # Update metadata while preserving pre-filled values
    for key, value in new_metadata.items():
        if key not in ["distribution"]:  # Don't overwrite distribution
            metadata[key] = value

    # Initialize distribution array for FileObjects/FileSets if it doesn't exist
    if "distribution" not in metadata:
        metadata["distribution"] = []

    # Section: File Resources
    console.print("\n[bold green]File Resources[/]")
    console.print("─" * 50)
    console.print("Croissant datasets can include file resources (FileObject) and file collections (FileSet).")

    # If we have pre-filled distribution, use it
    if prefill_metadata and "distribution" in dynamic_metadata:
        # Create a table to display pre-filled file information
        table = Table(title="Pre-filled File Resources")
        table.add_column("Type", style="cyan")
        table.add_column("Name", style="green")
        table.add_column("Format", style="yellow")
        table.add_column("Hash", style="magenta")

        for resource in dynamic_metadata["distribution"]:
            resource_type = resource.get("@type", "").replace("sc:", "").replace("cr:", "")
            name = resource.get("name", "")
            format = resource.get("encodingFormat", "")
            hash = resource.get("sha256", "")[:8] + "..." if resource.get("sha256") else ""

            table.add_row(resource_type, name, format, hash)

        console.print(table)

        if click.confirm("Would you like to use these pre-filled file resources?", default=True):
            metadata["distribution"] = dynamic_metadata["distribution"]
            console.print("[bold green]Using pre-filled file resources[/]")
        else:
            console.print("[yellow]You can now add new file resources manually[/]")
            metadata["distribution"] = []
    elif click.confirm("Would you like to add file resources to your dataset?", default=True):
        while True:
            resource_type = click.prompt(
                "Resource type",
                type=click.Choice(["FileObject", "FileSet"]),
                default="FileObject",
            )

            if resource_type == "FileObject":
                file_id = click.prompt("File ID (unique identifier for this file)")
                file_name = click.prompt("File name (including extension)")
                content_url = click.prompt("Content URL (where the file can be accessed)")
                encoding_format = click.prompt(
                    "Encoding format (MIME type, e.g., text/csv, application/json, "
                    "application/x-hdf5, application/fastq)",
                )

                file_object = {
                    "@type": FILE_OBJECT_TYPE,
                    "@id": file_id,
                    "name": file_name,
                    "contentUrl": content_url,
                    "encodingFormat": encoding_format,
                    "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
                }

                # Optional SHA256 checksum
                if click.confirm("Add SHA256 checksum?", default=False):
                    sha256 = click.prompt("SHA256 checksum")
                    file_object["sha256"] = sha256

                # Optional containedIn property
                if click.confirm("Is this file contained in another file (e.g., in an archive)?", default=False):
                    container_id = click.prompt("Container file ID")
                    file_object["containedIn"] = {"@id": container_id}

                metadata["distribution"].append(file_object)

            else:  # FileSet
                fileset_id = click.prompt("FileSet ID (unique identifier for this file set)")

                # Container information
                container_id = click.prompt("Container file ID (archive or directory)")

                fileset = {
                    "@type": "cr:FileSet",
                    "@id": fileset_id,
                    "containedIn": {"@id": container_id},
                }

                # File pattern information
                encoding_format = click.prompt(
                    "Encoding format of files in this set (MIME type, e.g., text/csv, "
                    "application/json, application/x-hdf5, application/fastq)",
                    default="",
                )
                if encoding_format:
                    fileset["encodingFormat"] = encoding_format

                includes_pattern = click.prompt("Include pattern (e.g., *.jpg, data/*.csv)", default="")
                if includes_pattern:
                    fileset["includes"] = includes_pattern

                # Optional exclude pattern
                if click.confirm("Add exclude pattern?", default=False):
                    excludes_pattern = click.prompt("Exclude pattern")
                    fileset["excludes"] = excludes_pattern

                metadata["distribution"].append(fileset)

            if not click.confirm("Add another file resource?", default=False):
                break

    # Section: Data Structure
    console.print("\n[bold green]Data Structure[/]")
    console.print("─" * 50)

    # Create a table for record set examples
    table = Table(title="Record Set Examples")
    table.add_column("Dataset Type", style="cyan")
    table.add_column("Record Sets", style="green")
    table.add_row("Genomics", "patients, samples, gene_expressions")
    table.add_row("Climate", "locations, time_series, measurements")
    table.add_row("Medical", "patients, visits, treatments, outcomes")
    console.print(table)

    console.print("Record sets describe the structure of your data.")

    if click.confirm("Would you like to add a record set to describe your data structure?", default=True):
        metadata["recordSet"] = []

        while True:
            record_set_name = click.prompt("Record set name (e.g., 'patients', 'samples')")
            record_set_description = click.prompt(f"Description of the '{record_set_name}' record set", default="")

            # Create record set with proper Croissant format
            record_set = {
                "@type": "cr:RecordSet",
                "@id": f"#{record_set_name}",
                "name": record_set_name,
                "description": record_set_description,
            }

            # Ask about data type
            if click.confirm(
                f"Would you like to specify a data type for the '{record_set_name}' record set?",
                default=False,
            ):
                data_type = click.prompt("Data type (e.g., sc:GeoCoordinates, sc:Person)")
                record_set["dataType"] = data_type

            # Ask about fields with examples
            console.print(f"\n[bold]Fields in '{record_set_name}'[/]")
            console.print("Fields describe the data columns or attributes in this record set.")

            if click.confirm(f"Would you like to add fields to the '{record_set_name}' record set?", default=True):
                record_set["field"] = []

                while True:
                    field_name = click.prompt("Field name (column or attribute name)")
                    field_description = click.prompt(f"Description of '{field_name}'", default="")

                    # Create field with proper Croissant format
                    field = {
                        "@type": "cr:Field",
                        "@id": f"#{record_set_name}/{field_name}",
                        "name": field_name,
                        "description": field_description,
                    }

                    # Ask about data type
                    if click.confirm(
                        f"Would you like to specify a data type for the '{field_name}' field?",
                        default=False,
                    ):
                        data_type = click.prompt("Data type (e.g., sc:Text, sc:Integer, sc:Float, sc:ImageObject)")
                        field["dataType"] = data_type

                    # Ask about source
                    if click.confirm(
                        f"Would you like to specify a data source for the '{field_name}' field?",
                        default=False,
                    ):
                        source_type = click.prompt(
                            "Source type",
                            type=click.Choice(["FileObject", "FileSet"]),
                            default="FileObject",
                        )
                        source_id = click.prompt(f"{source_type} ID")

                        source = {"source": {}}
                        if source_type == "FileObject":
                            source["source"]["fileObject"] = {"@id": source_id}
                        else:
                            source["source"]["fileSet"] = {"@id": source_id}

                        # Ask about extraction method
                        extract_type = click.prompt(
                            "Extraction method",
                            type=click.Choice(["column", "jsonPath", "fileProperty", "none"]),
                            default="none",
                        )

                        if extract_type != "none":
                            source["source"]["extract"] = {}
                            if extract_type == "column":
                                column_name = click.prompt("Column name")
                                source["source"]["extract"]["column"] = column_name
                            elif extract_type == "jsonPath":
                                json_path = click.prompt("JSONPath expression")
                                source["source"]["extract"]["jsonPath"] = json_path
                            elif extract_type == "fileProperty":
                                file_property = click.prompt(
                                    "File property",
                                    type=click.Choice(["fullpath", "filename", "content", "lines", "lineNumbers"]),
                                )
                                source["source"]["extract"]["fileProperty"] = file_property

                        # Add source to field
                        for key, value in source["source"].items():
                            field[key] = value

                    # Ask if the field is repeated (array)
                    if click.confirm(f"Is '{field_name}' a repeated field (array/list)?", default=False):
                        field["repeated"] = True

                    # Ask if the field references another field
                    if click.confirm(f"Does '{field_name}' reference another field (foreign key)?", default=False):
                        ref_record_set = click.prompt("Referenced record set name")
                        ref_field = click.prompt("Referenced field name")
                        field["references"] = {"@id": f"#{ref_record_set}/{ref_field}"}

                    # Add field to record set
                    record_set["field"].append(field)

                    if not click.confirm("Add another field?", default=True):
                        break

            # Ask about key fields
            if click.confirm(
                f"Would you like to specify key fields for the '{record_set_name}' record set?",
                default=False,
            ):
                record_set["key"] = []
                while True:
                    key_field = click.prompt("Key field name")
                    record_set["key"].append({"@id": f"#{record_set_name}/{key_field}"})

                    if not click.confirm("Add another key field?", default=False):
                        break

            # Add record set to metadata
            metadata["recordSet"].append(record_set)

            if not click.confirm("Add another record set?", default=False):
                break

    # Save metadata with a suggested filename
    default_filename = f"{dataset_name.lower().replace(' ', '_')}_metadata.json"
    output_path = click.prompt("Output file path", default=default_filename)

    metadata = normalize_metadata_shape(metadata)
    with open(output_path, "w") as f:
        json.dump(metadata, f, indent=2)

    # Stage the changes in Git if we're in a biotope project
    try:
        biotope_root = find_biotope_root()
        if biotope_root:
            import subprocess

            subprocess.run(["git", "add", ".biotope/"], cwd=biotope_root, check=True)
            console.print("✅ Staged changes in Git")
    except (subprocess.CalledProcessError, FileNotFoundError):
        pass  # Not in a biotope project or Git not available

    # Final success message with rich formatting
    console.print()
    console.print(
        Panel(
            f"[bold green]✅ Created Croissant metadata file at:[/] [blue]{output_path}[/]",
            title="Success",
            border_style="green",
        ),
    )

    console.print("[italic]Validate this file with:[/]")
    console.print(f"[bold yellow]biotope annotate validate --jsonld {output_path}[/]")

get_staged_files(biotope_root)

Get list of staged files from Git.

Source code in biotope/biotope/commands/annotate.py
def get_staged_files(biotope_root: Path) -> list:
    """Get list of staged files from Git."""
    import json
    import subprocess

    staged_files = []

    try:
        # Get the git root directory to understand relative paths
        git_root_result = subprocess.run(
            ["git", "rev-parse", "--show-toplevel"], cwd=biotope_root, capture_output=True, text=True, check=True
        )
        git_root = Path(git_root_result.stdout.strip())

        # Calculate the relative path from git root to biotope root
        biotope_relative_to_git = biotope_root.relative_to(git_root)

        # Get staged files from Git
        result = subprocess.run(
            ["git", "diff", "--cached", "--name-only"], cwd=biotope_root, capture_output=True, text=True, check=True
        )

        for file_path in result.stdout.splitlines():
            # Handle both cases: biotope project at git root and in subdirectory
            if biotope_relative_to_git == Path("."):
                # Biotope project is at git root
                expected_prefix = ".biotope/datasets/"
                metadata_file_path = file_path
            else:
                # Biotope project is in a subdirectory
                expected_prefix = f"{biotope_relative_to_git}/.biotope/datasets/"
                if file_path.startswith(str(biotope_relative_to_git) + "/"):
                    # Strip the biotope relative path to get the path relative to biotope root
                    metadata_file_path = file_path[len(str(biotope_relative_to_git)) + 1 :]
                else:
                    continue

            if file_path.startswith(expected_prefix) and file_path.endswith(".jsonld"):
                # Read the metadata file to get file information
                metadata_file = biotope_root / metadata_file_path
                try:
                    with open(metadata_file) as f:
                        metadata = normalize_metadata_shape(json.load(f))
                        for distribution in metadata.get("distribution", []):
                            if distribution.get("@type") == FILE_OBJECT_TYPE:
                                staged_files.append(
                                    {
                                        "file_path": distribution.get("contentUrl"),
                                        "sha256": distribution.get("sha256"),
                                        "size": distribution.get("contentSize"),
                                    }
                                )
                except (json.JSONDecodeError, KeyError):
                    continue

    except subprocess.CalledProcessError:
        pass

    return staged_files

get_standard_context()

Get the standard Croissant context.

Source code in biotope/biotope/commands/annotate.py
def get_standard_context() -> dict:
    """Get the standard Croissant context."""
    return shared_get_standard_context()

interactive(file_path=None, prefill_metadata=None, staged=False, incomplete=False)

Hidden alias for annotate edit.

Source code in biotope/biotope/commands/annotate.py
@annotate.command(name="interactive", hidden=True)
@click.option(
    "--file-path",
    "-f",
    type=click.Path(exists=True),
    help="Path to the file to annotate",
)
@click.option(
    "--prefill-metadata",
    "-p",
    type=str,
    help="JSON string containing pre-filled metadata",
)
@click.option(
    "--staged",
    "-s",
    is_flag=True,
    help="Annotate all staged files",
)
@click.option(
    "--incomplete",
    "-i",
    is_flag=True,
    help="Annotate all tracked files with incomplete metadata",
)
def interactive(
    file_path: str | None = None,
    prefill_metadata: str | None = None,
    staged: bool = False,
    incomplete: bool = False,
) -> None:
    """Hidden alias for `annotate edit`."""
    edit.callback(
        file_path=file_path,
        prefill_metadata=prefill_metadata,
        staged=staged,
        incomplete=incomplete,
    )

load(jsonld, record_set, num_records)

Load records from a dataset using its Croissant metadata.

Source code in biotope/biotope/commands/annotate.py
@annotate.command()
@click.option(
    "--jsonld",
    "-j",
    type=click.Path(exists=True),
    required=True,
    help="Path to the JSON-LD metadata file.",
)
@click.option(
    "--record-set",
    "-r",
    required=True,
    help="Name of the record set to load.",
)
@click.option(
    "--num-records",
    "-n",
    type=int,
    default=10,
    help="Number of records to load.",
)
def load(jsonld, record_set, num_records):
    """Load records from a dataset using its Croissant metadata."""
    try:
        # Use mlcroissant CLI to load the dataset
        result = subprocess.run(
            [
                "mlcroissant",
                "load",
                "--jsonld",
                jsonld,
                "--record_set",
                record_set,
                "--num_records",
                str(num_records),
            ],
            capture_output=True,
            text=True,
            check=True,
        )

        # Display the output
        if result.stdout:
            click.echo(result.stdout)

        click.echo(f"Loaded {num_records} records from record set '{record_set}'")
    except subprocess.CalledProcessError as e:
        click.echo(f"Error loading dataset: {e.stderr}", err=True)
        exit(1)
    except Exception as e:
        click.echo(f"Error running load command: {e!s}", err=True)
        exit(1)

merge_metadata(dynamic_metadata)

Merge dynamic metadata with standard context and structure.

Source code in biotope/biotope/commands/annotate.py
def merge_metadata(dynamic_metadata: dict) -> dict:
    """Merge dynamic metadata with standard context and structure."""
    return shared_merge_metadata(dynamic_metadata)

validate(jsonld)

Validate a Croissant metadata file.

Source code in biotope/biotope/commands/annotate.py
@annotate.command()
@click.option(
    "--jsonld",
    "-j",
    type=click.Path(exists=True),
    required=True,
    help="Path to the JSON-LD metadata file to validate.",
)
def validate(jsonld):
    """Validate a Croissant metadata file."""
    try:
        # Use mlcroissant CLI to validate the file
        result = subprocess.run(
            ["mlcroissant", "validate", "--jsonld", jsonld],
            capture_output=True,
            text=True,
            check=True,
        )
        click.echo("Validation successful! The metadata file is valid.")
        if result.stdout:
            # Filter out informational log messages
            filtered_output = "\n".join(
                line for line in result.stdout.splitlines() if not line.startswith("I") or not line.endswith("Done.")
            )
            if filtered_output:
                click.echo(f"Output: {filtered_output}")
        if result.stderr:
            # Filter out informational log messages
            filtered_stderr = "\n".join(
                line for line in result.stderr.splitlines() if not line.startswith("I") or not line.endswith("Done.")
            )
            if filtered_stderr:
                click.echo(f"Warnings: {filtered_stderr}")
    except subprocess.CalledProcessError as e:
        click.echo(f"Validation failed: {e.stderr}", err=True)
        exit(1)
    except Exception as e:
        click.echo(f"Error running validation: {e!s}", err=True)
        exit(1)