Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 9 additions & 4 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ swift run labelkit stats <dataset> # headless: what is labelled, what is not (
swift run labelkit validate <dataset> # headless: dataset problems, exit 1 on errors
swift run labelkit annotate <dataset> --image a.jpg --box 'cat:40,30,200,160' # headless: write boxes
swift run labelkit render <dataset> --out /tmp/check # headless: draw the boxes to look at them
swift run labelkit import <source> --into <dataset> # headless: bring in a YOLO / COCO / Hugging Face dataset
swift run labelkit export <dataset> --format yolo --out <dir> # headless: write it out in another layout
swift run labelkit skill # print the guide for AI agents (SKILL.md)
swift build -c release # release binary at .build/release/labelkit
swift test # headless library tests
Expand Down Expand Up @@ -72,12 +74,15 @@ New logic belongs in `LabelKit` with tests unless it genuinely needs UI.

### The scripted surface (agents and scripts depend on it)

`stats`, `validate`, `annotate`, `render` and `skill` are the headless verbs
AI agents and shell scripts drive. Their logic is in
`stats`, `validate`, `annotate`, `render`, `import`, `export` and `skill` are
the headless verbs AI agents and shell scripts drive. Their logic is in
`Sources/LabelKit/Headless` (`DatasetDocument`, `BoxImportParser`,
`AnnotationMerge`, `DatasetSummary`, `DatasetValidator`, `DuplicateImages`,
`AgentGuide`); each command file in `LabelKitApp` only parses arguments and
prints. Treat the following as a public interface:
`AgentGuide`) and `Sources/LabelKit/Interop` (`ForeignDatasetReader`,
`DatasetImport`, `DatasetExport`); each command file in `LabelKitApp` only
parses arguments and prints. `import` is deliberately built from `ImageImporter`
and `AnnotationMerge` rather than beside them, so it inherits never-overwrite,
idempotency and all-or-nothing; keep it that way when adding a format. Treat the following as a public interface:

- **stdout is the result and nothing else** (JSON by default); notes go to
stderr via `Headless.note`. **Exit 0** success, **1** the command ran and
Expand Down
17 changes: 17 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,23 @@ release notes, so every release needs a `## [X.Y.Z] - YYYY-MM-DD` heading here.

## [Unreleased]

### Added

- **`labelkit import`.** Bring a YOLO, COCO or Hugging Face image dataset into
a Create ML dataset: images are copied in and boxes merged into
`annotations.json`. The format is detected, existing files are never
overwritten (a clashing name is renamed and its boxes follow), importing the
same source twice changes nothing, and a source with unusable boxes imports
nothing unless `--lenient` is given. `--names` supplies class names for a
source that only has numeric ids.
- **`labelkit export`.** Write a dataset out as YOLO (`images/`, `labels/`,
`data.yaml`), COCO (`_annotations.coco.json`) or a Hugging Face image dataset
(`metadata.jsonl` plus a dataset card), ready for `hf upload`.
- **[docs/datasets.md](docs/datasets.md).** Recipes for publishing on Hugging
Face, keeping images in an R2/S3 bucket with only `annotations.json` in git,
and using a large model as a teacher to label data for a small Create ML
model.

## [0.3.0] - 2026-11-28

### Added
Expand Down
41 changes: 39 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,8 @@ labelkit render <folder> … # draw the boxes onto pictures to check them
labelkit validate <folder> # find problems; exits 1 on errors
labelkit detect <image> … # run a detector
labelkit train <folder> # train a Core ML model
labelkit import <source> --into <folder> # bring in a YOLO, COCO or Hugging Face dataset
labelkit export <folder> --format yolo --out <dir> # …or write one out
```

## Using it from an AI agent
Expand Down Expand Up @@ -153,6 +155,40 @@ Stdout is JSON, stderr is notes, and exit codes are `0` ok, `1` problem found,

**[Full guide: per-client setup, input formats, the JSON contract →](docs/agents.md)**

## Working with other tools and formats

A labelkit dataset is Apple's Create ML format and nothing more, so it moves
between tools with two commands:

```bash
labelkit import ./yolo-or-coco-download --into ./cards # format detected; never overwrites; safe to repeat
labelkit export ./cards --format huggingface --out ./cards-hf
```

To see it on a real dataset in a minute, try COCO8, an 8-image sample of COCO
that Ultralytics publishes in YOLO format:

```bash
curl -LO https://github.com/ultralytics/assets/releases/download/v0.0.0/coco8.zip && unzip -q coco8.zip
curl -LO https://raw.githubusercontent.com/ultralytics/ultralytics/main/ultralytics/cfg/datasets/coco8.yaml
labelkit import coco8 --into coco8-ml --names coco8.yaml # 8 images, 30 boxes, 12 classes
labelkit coco8-ml # open it in the editor
```

(The zip carries no class names of its own, hence `--names`; without it the
boxes import as `class_0`, `class_1`, ….)

`import` and `export` cover **YOLO**, **COCO** and **Hugging Face** image
datasets. That gives you a few useful routes:

- **Start from a public dataset** instead of from nothing.
- **Publish or back up on Hugging Face**, public or private, with their `hf` tool.
- **Keep images in your own bucket** (R2, B2, S3) and only `annotations.json` in git.
- **Use a big model as a teacher**: let a YOLO or vision-language model label
your images, review, then train a small on-device model with `labelkit train`.

**[Recipes for each of these →](docs/datasets.md)**

## Detecting from the CLI

`labelkit detect` runs an object detector over an image (or a whole directory)
Expand Down Expand Up @@ -264,8 +300,9 @@ Notes:

## Roadmap

- YOLO import and YOLO / COCO export (COCO import already works through
`labelkit annotate --from`)
- A checksum manifest, so a dataset whose images live in a bucket can be
verified after download
- The editor noticing when `annotations.json` changes underneath it

## License

Expand Down
18 changes: 18 additions & 0 deletions Sources/LabelKit/Headless/AgentGuide.swift
Original file line number Diff line number Diff line change
Expand Up @@ -208,6 +208,22 @@ public enum AgentGuide {
including one trained earlier on this dataset. Detections are a draft:
render and review them like any other boxes.

## Datasets from and for other tools

```
labelkit import ./downloaded --into <dataset> # YOLO, COCO or Hugging Face layout, detected
labelkit export <dataset> --format yolo --out ./for-yolo # or coco, huggingface
```

`import` copies the source's images into the dataset and merges its boxes.
It never overwrites a file (a clashing name is renamed and reported),
repeating it changes nothing, and source images without boxes are skipped
unless `--negatives` is given. If labels come in as `class_0`, `class_1`, …
the source has no class names: pass its `data.yaml` or a one-name-per-line
file with `--names`. `export` writes a new folder and only reads
the dataset; `--out` must be new or empty. Use `--dry-run` on `import` first
when unsure what a folder contains.

## Checking a dataset

`labelkit validate <dataset>` reports, as JSON `issues` with a stable `code`:
Expand Down Expand Up @@ -257,6 +273,8 @@ public enum AgentGuide {
| `labelkit annotate <dataset> …` | adds or replaces boxes | `annotations.json` |
| `labelkit render <dataset> [images…] --out DIR [--grid N] [--unlabeled]` | pictures with boxes drawn | files in DIR |
| `labelkit detect <image-or-dir> --model M \| --detector D` | runs a detector, prints boxes | nothing |
| `labelkit import <source> --into <dataset>` | brings in a YOLO, COCO or Hugging Face dataset | images and `annotations.json` |
| `labelkit export <dataset> --format F --out DIR` | writes the dataset as YOLO, COCO or Hugging Face | files in DIR |
| `labelkit train <dataset> [-o model.mlmodel]` | trains a Core ML detector | the model file |

Every command has `--help` with examples. `stats`, `validate` and `annotate`
Expand Down
23 changes: 21 additions & 2 deletions Sources/LabelKit/Headless/AnnotationMerge.swift
Original file line number Diff line number Diff line change
Expand Up @@ -30,11 +30,18 @@ public enum AnnotationMerge {
/// modes, so that "the detector found nothing" never silently becomes
/// training signal or wipes existing labels.
public var recordNegatives: Bool
/// In `add` mode, also treat two overlapping same-label boxes within
/// the input as one. Right for a model's answer, where that is a
/// repeated detection; wrong for an existing dataset, where crowded
/// objects legitimately overlap, so `import` turns it off.
public var dedupeWithinInput: Bool

public init(mode: Mode = .add, dedupeIoU: CGFloat = 0.5, recordNegatives: Bool = false) {
public init(mode: Mode = .add, dedupeIoU: CGFloat = 0.5, recordNegatives: Bool = false,
dedupeWithinInput: Bool = true) {
self.mode = mode
self.dedupeIoU = dedupeIoU
self.recordNegatives = recordNegatives
self.dedupeWithinInput = dedupeWithinInput
}
}

Expand Down Expand Up @@ -125,8 +132,10 @@ public enum AnnotationMerge {
var added = 0, duplicates = 0, removed = 0
switch options.mode {
case .add:
let alreadyThere = boxes
for candidate in resolved {
if boxes.contains(where: { isSameBox($0, candidate, threshold: options.dedupeIoU) }) {
let known = options.dedupeWithinInput ? boxes : alreadyThere
if known.contains(where: { isSameBox($0, candidate, threshold: options.dedupeIoU) }) {
duplicates += 1
} else {
boxes.append(candidate)
Expand Down Expand Up @@ -187,6 +196,16 @@ public enum AnnotationMerge {
message: "coordinates measured on a \(Int(reference.width))x\(Int(reference.height)) copy "
+ "need the image's own size, and the file can't be read"))
}
// A size that is the image's own turned on its side means the
// numbers were measured before the photo's EXIF rotation. Which way
// it was turned isn't known here, so scaling would place the box
// somewhere wrong without saying so.
if imageSize != reference, reference.width == imageSize.height, reference.height == imageSize.width {
return .failure(BoxImportError(
message: "coordinates are for the image before its EXIF rotation "
+ "(\(Int(reference.width))x\(Int(reference.height)) stored, "
+ "\(Int(imageSize.width))x\(Int(imageSize.height)) as displayed)"))
}
// Same size (the usual case, e.g. `labelkit detect` output): the
// numbers are used as they are, with no float round trip.
// Otherwise scale from the copy to the real image.
Expand Down
10 changes: 8 additions & 2 deletions Sources/LabelKit/Headless/BoxImport.swift
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,15 @@ public struct ImportedBox: Equatable, Sendable {
public struct ImportedImage: Equatable, Sendable {
public var image: String
public var boxes: [ImportedBox]
/// The image's path as the source wrote it, when that was more than a bare
/// name (COCO's `file_name` can be `train/a.jpg`). `image` is its last
/// component; `import` uses the path to find the right file.
public var path: String?

public init(image: String, boxes: [ImportedBox]) {
public init(image: String, boxes: [ImportedBox], path: String? = nil) {
self.image = image
self.boxes = boxes
self.path = path
}
}

Expand Down Expand Up @@ -378,7 +383,8 @@ public enum BoxImportParser {
throw BoxImportError(message: "COCO: an image entry is missing \"id\" or \"file_name\"")
}
order.append(id)
result[id] = ImportedImage(image: URL(fileURLWithPath: file).lastPathComponent, boxes: [])
let name = URL(fileURLWithPath: file).lastPathComponent
result[id] = ImportedImage(image: name, boxes: [], path: name == file ? nil : file)
var convention = BoxConvention.pixelTopLeftCorner
if let width = number(image["width"]), let height = number(image["height"]), width > 0, height > 0 {
convention.referenceSize = CGSize(width: width, height: height)
Expand Down
2 changes: 1 addition & 1 deletion Sources/LabelKit/Headless/DatasetDocument.swift
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ public struct DatasetDocument: Sendable {
/// Entries in file order. Never reordered or dropped by a load → save.
public var records: [ImageAnnotationRecord]
/// Image filenames found in the images directory, name-sorted.
public let imagesOnDisk: [String]
public var imagesOnDisk: [String]
/// Indentation sniffed from the loaded file, reused on save.
public let indentUnit: String

Expand Down
Loading
Loading