From 069af095becc0dcd794525e1e214ee3f00b322fb Mon Sep 17 00:00:00 2001 From: shellbear Date: Sat, 28 Nov 2026 18:06:49 +0100 Subject: [PATCH 1/3] feat: import and export YOLO, COCO and Hugging Face datasets A labelkit dataset is Apple's Create ML format and nothing more; these two commands are how it trades with everything else. - import: reads a YOLO, COCO or Hugging Face image-folder dataset (format detected, splits merged), copies its images in and merges its boxes. Built from ImageImporter and AnnotationMerge, so it never overwrites a file (a clashing name is renamed and its boxes follow), repeating it changes nothing, and a source with unusable boxes imports nothing unless --lenient. --names supplies class names for a source that only has numeric ids, which a first trial on a public YOLO download showed is common. - export: writes YOLO (images/, labels/, classes.txt, data.yaml), COCO (_annotations.coco.json) or a Hugging Face image dataset (metadata.jsonl plus a dataset card, ready for 'hf upload') into a new folder. Class ids follow the labels alphabetically; coordinates are written as short decimals. - docs/datasets.md: recipes for publishing on Hugging Face, keeping images in an R2/S3 bucket with annotations.json in git, and using a large model as a teacher to label data for a small Create ML model - README: a quick start that imports a public 8-image dataset The smoke test round-trips each format and checks a repeated import leaves the file byte-identical. --- AGENTS.md | 13 +- CHANGELOG.md | 17 + README.md | 41 +- Sources/LabelKit/Headless/AgentGuide.swift | 18 + .../LabelKit/Headless/DatasetDocument.swift | 2 +- Sources/LabelKit/Interop/DatasetExport.swift | 266 ++++++++++++ Sources/LabelKit/Interop/DatasetImport.swift | 122 ++++++ Sources/LabelKit/Interop/ForeignDataset.swift | 389 ++++++++++++++++++ Sources/LabelKitApp/ExportCommand.swift | 70 ++++ Sources/LabelKitApp/ImportCommand.swift | 123 ++++++ Sources/LabelKitApp/LabelKitCommand.swift | 2 +- Tests/LabelKitTests/DatasetInteropTests.swift | 375 +++++++++++++++++ docs/datasets.md | 172 ++++++++ scripts/smoke-scripted.sh | 19 +- skills/labelkit/SKILL.md | 18 + 15 files changed, 1638 insertions(+), 9 deletions(-) create mode 100644 Sources/LabelKit/Interop/DatasetExport.swift create mode 100644 Sources/LabelKit/Interop/DatasetImport.swift create mode 100644 Sources/LabelKit/Interop/ForeignDataset.swift create mode 100644 Sources/LabelKitApp/ExportCommand.swift create mode 100644 Sources/LabelKitApp/ImportCommand.swift create mode 100644 Tests/LabelKitTests/DatasetInteropTests.swift create mode 100644 docs/datasets.md diff --git a/AGENTS.md b/AGENTS.md index efd5259..7f981a2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -21,6 +21,8 @@ swift run labelkit stats # headless: what is labelled, what is not ( swift run labelkit validate # headless: dataset problems, exit 1 on errors swift run labelkit annotate --image a.jpg --box 'cat:40,30,200,160' # headless: write boxes swift run labelkit render --out /tmp/check # headless: draw the boxes to look at them +swift run labelkit import --into # headless: bring in a YOLO / COCO / Hugging Face dataset +swift run labelkit export --format yolo --out # 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 @@ -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 diff --git a/CHANGELOG.md b/CHANGELOG.md index 100838f..7abb16b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/README.md b/README.md index b098664..f3d7a68 100644 --- a/README.md +++ b/README.md @@ -106,6 +106,8 @@ labelkit render … # draw the boxes onto pictures to check them labelkit validate # find problems; exits 1 on errors labelkit detect … # run a detector labelkit train # train a Core ML model +labelkit import --into # bring in a YOLO, COCO or Hugging Face dataset +labelkit export --format yolo --out # …or write one out ``` ## Using it from an AI agent @@ -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) @@ -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 diff --git a/Sources/LabelKit/Headless/AgentGuide.swift b/Sources/LabelKit/Headless/AgentGuide.swift index bd3485c..3e5e320 100644 --- a/Sources/LabelKit/Headless/AgentGuide.swift +++ b/Sources/LabelKit/Headless/AgentGuide.swift @@ -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 # YOLO, COCO or Hugging Face layout, detected + labelkit export --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 ` reports, as JSON `issues` with a stable `code`: @@ -257,6 +273,8 @@ public enum AgentGuide { | `labelkit annotate …` | adds or replaces boxes | `annotations.json` | | `labelkit render [images…] --out DIR [--grid N] [--unlabeled]` | pictures with boxes drawn | files in DIR | | `labelkit detect --model M \| --detector D` | runs a detector, prints boxes | nothing | + | `labelkit import --into ` | brings in a YOLO, COCO or Hugging Face dataset | images and `annotations.json` | + | `labelkit export --format F --out DIR` | writes the dataset as YOLO, COCO or Hugging Face | files in DIR | | `labelkit train [-o model.mlmodel]` | trains a Core ML detector | the model file | Every command has `--help` with examples. `stats`, `validate` and `annotate` diff --git a/Sources/LabelKit/Headless/DatasetDocument.swift b/Sources/LabelKit/Headless/DatasetDocument.swift index 27baabb..91eebba 100644 --- a/Sources/LabelKit/Headless/DatasetDocument.swift +++ b/Sources/LabelKit/Headless/DatasetDocument.swift @@ -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 diff --git a/Sources/LabelKit/Interop/DatasetExport.swift b/Sources/LabelKit/Interop/DatasetExport.swift new file mode 100644 index 0000000..bf6c25d --- /dev/null +++ b/Sources/LabelKit/Interop/DatasetExport.swift @@ -0,0 +1,266 @@ +import CoreGraphics +import Foundation + +/// Writes a Create ML dataset out in another layout, into a fresh folder. The +/// dataset itself is only read. +/// +/// What is exported is what a trainer would see: every entry whose image file +/// exists, negatives included. Images with no entry are unlabelled work in +/// progress and are left out. Class ids follow the labels in alphabetical +/// order, so the same dataset always exports the same numbering. +public enum DatasetExport { + public struct Options: Sendable { + public var format: DatasetFormat + /// Copy the image files alongside the annotations. On APFS a copy is a + /// clone and takes no extra space until one side changes. + public var copyImages: Bool + + public init(format: DatasetFormat, copyImages: Bool = true) { + self.format = format + self.copyImages = copyImages + } + } + + public struct Report: Codable, Equatable, Sendable { + public var schemaVersion: Int + public var labelkit: String + public var dataset: String + public var out: String + public var format: String + /// Images written to the export (entries with a file on disk). + public var images: Int + public var boxes: Int + /// Class names in id order. + public var labels: [String] + /// Entries left out, each with the reason. + public var skipped: [Skipped] + /// The annotation files written, relative to `out`. + public var files: [String] + + public struct Skipped: Codable, Equatable, Sendable { + public var image: String + public var reason: String + } + } + + public struct ExportError: LocalizedError, Equatable { + public var message: String + public var errorDescription: String? { message } + } + + /// Hugging Face asks for at most 10,000 entries per folder; stay well under. + static let imagesPerFolder = 5_000 + + /// - Parameter pixelSize: display-orientation size of a dataset image, or + /// nil if it can't be read. YOLO and COCO need it; such images are skipped. + public static func run( + _ document: DatasetDocument, + to out: URL, + options: Options, + labelkitVersion version: String = labelkitVersion, + pixelSize: (String) -> CGSize? + ) throws -> Report { + let fm = FileManager.default + guard !document.isImagesDirectory(out) else { + throw ExportError(message: "the output folder is the dataset itself; choose another directory") + } + if let existing = try? fm.contentsOfDirectory(atPath: out.path), !existing.isEmpty { + throw ExportError(message: "\(out.path) is not empty; export into a new or empty directory") + } + + let onDisk = Set(document.imagesOnDisk) + var skipped: [Report.Skipped] = [] + var entries: [(record: ImageAnnotationRecord, size: CGSize?)] = [] + for record in document.uniqueRecords { + guard onDisk.contains(record.image) else { + skipped.append(.init(image: record.image, reason: "image file not found")) + continue + } + let size = pixelSize(record.image) + if options.format != .huggingface, size == nil { + skipped.append(.init(image: record.image, reason: "couldn't read the image's size")) + continue + } + entries.append((record, size)) + } + let labels = Set(entries.flatMap { $0.record.boxes.map(\.label) }).sorted() + let classID = Dictionary(uniqueKeysWithValues: labels.enumerated().map { ($1, $0) }) + + // Where each image goes inside the export, relative to `out`. + let imagePaths: [String] + var files: [String] + switch options.format { + case .yolo: + let stems = entries.map { ($0.record.image as NSString).deletingPathExtension.lowercased() } + if let clash = Dictionary(grouping: stems, by: { $0 }).first(where: { $1.count > 1 })?.key { + throw ExportError(message: "two images are named '\(clash)' with different extensions; " + + "YOLO pairs images and labels by name, so rename one first") + } + imagePaths = entries.map { "images/" + $0.record.image } + try fm.createDirectory(at: out.appendingPathComponent("labels"), withIntermediateDirectories: true) + for (record, size) in entries { + let stem = (record.image as NSString).deletingPathExtension + try yoloRows(record.boxes, size: size ?? .zero, classID: classID) + .write(to: out.appendingPathComponent("labels/\(stem).txt"), atomically: true, encoding: .utf8) + } + try (labels.joined(separator: "\n") + "\n") + .write(to: out.appendingPathComponent("classes.txt"), atomically: true, encoding: .utf8) + try yoloConfig(labels).write(to: out.appendingPathComponent("data.yaml"), atomically: true, encoding: .utf8) + files = ["data.yaml", "classes.txt", "labels/"] + + case .coco: + imagePaths = entries.map(\.record.image) + try fm.createDirectory(at: out, withIntermediateDirectories: true) + try coco(entries, labels: labels, classID: classID) + .write(to: out.appendingPathComponent("_annotations.coco.json"), options: .atomic) + files = ["_annotations.coco.json"] + + case .huggingface: + let shard = entries.count > imagesPerFolder + imagePaths = entries.enumerated().map { index, entry in + shard ? String(format: "train/images/%03d/", index / imagesPerFolder) + entry.record.image + : "train/images/" + entry.record.image + } + try fm.createDirectory(at: out.appendingPathComponent("train"), withIntermediateDirectories: true) + // metadata.jsonl sits in train/, so file_name is relative to that. + let rows = try zip(entries, imagePaths).map { entry, path in + try huggingFaceRow(entry.record, fileName: String(path.dropFirst("train/".count))) + } + try (rows.joined(separator: "\n") + "\n") + .write(to: out.appendingPathComponent("train/metadata.jsonl"), atomically: true, encoding: .utf8) + try datasetCard(name: document.location.displayName, labels: labels, images: entries.count) + .write(to: out.appendingPathComponent("README.md"), atomically: true, encoding: .utf8) + files = ["README.md", "train/metadata.jsonl"] + } + + if options.copyImages { + for (entry, path) in zip(entries, imagePaths) { + let destination = out.appendingPathComponent(path) + try fm.createDirectory(at: destination.deletingLastPathComponent(), withIntermediateDirectories: true) + try fm.copyItem(at: document.imageURL(for: entry.record.image), to: destination) + } + switch options.format { + case .yolo: files.append("images/") + case .coco: files.append("images alongside the JSON") + case .huggingface: files.append("train/images/") + } + } + + return Report( + schemaVersion: 1, labelkit: version, + dataset: document.location.imagesDirectory.path, out: out.path, + format: options.format.rawValue, images: entries.count, + boxes: entries.reduce(0) { $0 + $1.record.boxes.count }, + labels: labels, skipped: skipped, files: files) + } + + // MARK: - YOLO + + /// One `class cx cy w h` row per box, normalized, 6 decimals. An image with + /// no boxes gets an empty file, which is how YOLO marks a background image. + static func yoloRows(_ boxes: [BoxRecord], size: CGSize, classID: [String: Int]) -> String { + guard size.width > 0, size.height > 0 else { return "" } + return boxes.map { box in + String(format: "%d %.6f %.6f %.6f %.6f\n", classID[box.label] ?? 0, + box.x / size.width, box.y / size.height, box.width / size.width, box.height / size.height) + }.joined() + } + + static func yoloConfig(_ labels: [String]) -> String { + var text = "# Exported by labelkit. Every image is under train; make a validation split before training.\n" + text += "path: .\ntrain: images\nval: images\nnames:\n" + for (index, label) in labels.enumerated() { + text += " \(index): \(yamlString(label))\n" + } + return text + } + + // MARK: - COCO + + /// `bbox` is `[x, y, width, height]` in pixels from the top-left corner; + /// ids start at 1, as COCO tools expect. + static func coco(_ entries: [(record: ImageAnnotationRecord, size: CGSize?)], + labels: [String], classID: [String: Int]) throws -> Data { + var images: [[String: Any]] = [] + var annotations: [[String: Any]] = [] + for (index, entry) in entries.enumerated() { + let size = entry.size ?? .zero + images.append(["id": index + 1, "file_name": entry.record.image, + "width": Int(size.width), "height": Int(size.height)]) + for box in entry.record.boxes { + annotations.append([ + "id": annotations.count + 1, "image_id": index + 1, + "category_id": (classID[box.label] ?? 0) + 1, + "bbox": [hundredths(box.rect.minX), hundredths(box.rect.minY), + hundredths(box.width), hundredths(box.height)], + "area": hundredths(box.width * box.height), "iscrowd": 0, + ]) + } + } + let root: [String: Any] = [ + "info": ["description": "Exported by labelkit"], + "images": images, "annotations": annotations, + "categories": labels.enumerated().map { ["id": $0 + 1, "name": $1] }, + ] + return try JSONSerialization.data(withJSONObject: root, options: [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes]) + } + + // MARK: - Hugging Face + + /// The row shape from Hugging Face's image-dataset docs. Categories are + /// written as names rather than ids, so the file needs no side table. + static func huggingFaceRow(_ record: ImageAnnotationRecord, fileName: String) throws -> String { + let row: [String: Any] = [ + "file_name": fileName, + "objects": [ + "bbox": record.boxes.map { [hundredths($0.rect.minX), hundredths($0.rect.minY), + hundredths($0.width), hundredths($0.height)] }, + "categories": record.boxes.map(\.label), + ], + ] + let data = try JSONSerialization.data(withJSONObject: row, options: [.sortedKeys, .withoutEscapingSlashes]) + return String(decoding: data, as: UTF8.self) + } + + static func datasetCard(name: String, labels: [String], images: Int) -> String { + """ + --- + pretty_name: \(yamlString(name)) + task_categories: + - object-detection + tags: + - labelkit + - createml + --- + + # \(name) + + An object-detection dataset of \(images) images, exported from an Apple Create ML + dataset with [labelkit](https://github.com/shellbear/labelkit). + + Boxes are in `train/metadata.jsonl` as `objects.bbox` — `[x, y, width, height]` in + pixels from the top-left corner — with the matching class names in + `objects.categories`. + + Classes: \(labels.map { "`\($0)`" }.joined(separator: ", ")) + + Add a `license:` to the YAML above before publishing. To turn this back into a + Create ML dataset: `labelkit import --into `. + + """ + } + + // MARK: - Helpers + + /// A coordinate at labelkit's 2-decimal precision, as a decimal number so + /// JSON prints `810.03` rather than the nearest binary double's + /// `810.02999999999997`. + private static func hundredths(_ value: CGFloat) -> NSDecimalNumber { + NSDecimalNumber(string: CreateMLWriter.coordString(Double(value))) + } + + /// A YAML scalar that is safe whatever the label contains. + private static func yamlString(_ text: String) -> String { + "'" + text.replacingOccurrences(of: "'", with: "''") + "'" + } +} diff --git a/Sources/LabelKit/Interop/DatasetImport.swift b/Sources/LabelKit/Interop/DatasetImport.swift new file mode 100644 index 0000000..d2abf91 --- /dev/null +++ b/Sources/LabelKit/Interop/DatasetImport.swift @@ -0,0 +1,122 @@ +import CoreGraphics +import Foundation + +/// Brings a dataset in another layout into a Create ML dataset: its images are +/// copied into the folder and its boxes merged into `annotations.json`. +/// +/// It is built from the same parts as the rest of labelkit rather than beside +/// them — `ImageImporter` decides file names (never overwriting), and +/// `AnnotationMerge` writes the boxes — so an import has the properties an +/// `annotate` run has: running it twice changes nothing, and if anything in +/// the source can't be applied, nothing is copied or written. +public enum DatasetImport { + public struct Options: Sendable { + /// Record source images that have no boxes as negative examples. + public var recordNegatives: Bool + /// Apply what is valid instead of refusing the whole import. + public var lenient: Bool + /// Work everything out, copy and write nothing. + public var dryRun: Bool + + public init(recordNegatives: Bool = false, lenient: Bool = false, dryRun: Bool = false) { + self.recordNegatives = recordNegatives + self.lenient = lenient + self.dryRun = dryRun + } + } + + public struct Report: Codable, Equatable, Sendable { + public var schemaVersion: Int + public var labelkit: String + public var dataset: String + public var annotations: String + /// `yolo`, `coco` or `huggingface`. + public var format: String + public var dryRun: Bool + /// True when images were copied and/or the annotations file rewritten. + public var written: Bool + public var images: ImageCounts + public var boxes: BoxCounts + /// Labels found in the source, sorted. + public var labels: [String] + /// Images whose name was taken by a different file and were given a new one. + public var renamed: [Rename] + /// Source entries whose image file wasn't found; they are skipped. + public var missing: [String] + public var problems: [AnnotationMerge.Problem] + + public struct ImageCounts: Codable, Equatable, Sendable { + /// Images in the source. + public var found: Int + /// Copied into the dataset by this run. + public var copied: Int + /// Already in the dataset (same name and size); not copied again. + public var alreadyPresent: Int + } + + public struct BoxCounts: Codable, Equatable, Sendable { + public var added: Int + public var duplicates: Int + public var clamped: Int + } + + public struct Rename: Codable, Equatable, Sendable { + public var from: String + public var to: String + } + } + + public static func run( + _ foreign: ForeignDataset, + into document: inout DatasetDocument, + options: Options = Options(), + labelkitVersion version: String = labelkitVersion + ) throws -> Report { + let directory = document.location.imagesDirectory + let plan = ImageImporter.plan( + sources: foreign.images.map(\.source), into: directory, + reservedNames: Set(document.records.map(\.image))) + + // Sizes come from the source files, so nothing has to be copied before + // it is known that the whole import can go through. + let measured = foreign.images.map(\.source).concurrentMap(ImageMetadata.pixelSize(of:)) + var sizes: [String: CGSize] = [:] + for (item, size) in zip(plan, measured) { + if let size { sizes[item.finalName] = size } + } + + var merged = document + merged.imagesOnDisk = (document.imagesOnDisk + plan.map(\.finalName)).uniqued() + let imports = zip(plan, foreign.images).map { ImportedImage(image: $0.finalName, boxes: $1.boxes) } + let result = AnnotationMerge.apply( + imports, to: &merged, + options: .init(mode: .add, recordNegatives: options.recordNegatives), + pixelSize: { sizes[$0] }) + + let blocked = !result.problems.isEmpty && !options.lenient + let toCopy = plan.filter(\.needsCopy) + let apply = !options.dryRun && !blocked + if apply { + try ImageImporter.execute(plan, into: directory) + if result.changed { try merged.save() } + document = merged + } + + let outcomes = result.outcomes + return Report( + schemaVersion: 1, labelkit: version, + dataset: directory.path, annotations: document.location.annotationsURL.path, + format: foreign.format.rawValue, dryRun: options.dryRun, + written: apply && (result.changed || !toCopy.isEmpty), + images: .init(found: foreign.images.count, copied: toCopy.count, + alreadyPresent: plan.count - toCopy.count), + boxes: .init(added: outcomes.reduce(0) { $0 + $1.added }, + duplicates: outcomes.reduce(0) { $0 + $1.duplicates }, + clamped: outcomes.reduce(0) { $0 + $1.clamped }), + labels: Set(foreign.images.flatMap { $0.boxes.map(\.label) }).sorted(), + renamed: plan.filter { $0.finalName != $0.source.lastPathComponent } + .map { .init(from: $0.source.lastPathComponent, to: $0.finalName) }, + missing: foreign.missingImages, + problems: result.problems) + } +} diff --git a/Sources/LabelKit/Interop/ForeignDataset.swift b/Sources/LabelKit/Interop/ForeignDataset.swift new file mode 100644 index 0000000..44d0e96 --- /dev/null +++ b/Sources/LabelKit/Interop/ForeignDataset.swift @@ -0,0 +1,389 @@ +import CoreGraphics +import Foundation + +/// The dataset layouts labelkit can read and write besides its own. +public enum DatasetFormat: String, CaseIterable, Sendable { + /// Ultralytics YOLO: `images/` and `labels/*.txt` (`class cx cy w h`, + /// normalized), class names in `data.yaml` or `classes.txt`. + case yolo + /// COCO detection JSON: `images`, `annotations`, `categories`. + case coco + /// Hugging Face ImageFolder: images plus `metadata.jsonl` whose rows carry + /// `objects.bbox` (`[x, y, width, height]`, pixels) and `objects.categories`. + case huggingface +} + +/// A dataset in another layout, read into neutral terms: where each image file +/// is, and its boxes. Nothing has been copied or converted yet. +public struct ForeignDataset: Equatable, Sendable { + public struct Image: Equatable, Sendable { + /// The image file on disk. + public var source: URL + public var boxes: [ImportedBox] + + public init(source: URL, boxes: [ImportedBox]) { + self.source = source + self.boxes = boxes + } + } + + public var format: DatasetFormat + public var images: [Image] + /// Entries that named an image file which isn't there. + public var missingImages: [String] + + public init(format: DatasetFormat, images: [Image], missingImages: [String] = []) { + self.format = format + self.images = images + self.missingImages = missingImages + } +} + +public struct ForeignDatasetError: LocalizedError, Equatable { + public var message: String + /// True when the caller pointed at the wrong thing (no such path, not a + /// dataset), as opposed to a dataset whose contents are broken. + public var isUsage = false + public var errorDescription: String? { message } +} + +/// Reads YOLO, COCO and Hugging Face datasets from disk. Splits +/// (`train/`, `valid/`, `test/`) are read together: a Create ML dataset is one +/// folder, and Create ML makes its own validation split when training. +public enum ForeignDatasetReader { + /// Read the dataset at `url` (a folder, or for COCO its JSON file), + /// working out the format from what is there unless one is given. + /// + /// - Parameter classNames: names for numeric class ids, in id order, when + /// the dataset doesn't carry them itself (many YOLO downloads ship + /// without their `data.yaml`). They take precedence over any found. + public static func read(at url: URL, format: DatasetFormat? = nil, + classNames: [String]? = nil) throws -> ForeignDataset { + var isDirectory: ObjCBool = false + guard FileManager.default.fileExists(atPath: url.path, isDirectory: &isDirectory) else { + throw ForeignDatasetError(message: "no such file or directory: \(url.path)", isUsage: true) + } + let files: Tree + if isDirectory.boolValue { + files = Tree(root: url) + } else { + // A lone annotation file: its images are beside it, or — in the + // standard COCO layout, annotations/instances_*.json — one level up. + let folder = url.deletingLastPathComponent() + let root = folder.lastPathComponent == "annotations" ? folder.deletingLastPathComponent() : folder + files = Tree(root: root, only: url) + } + + switch try format ?? detect(files, at: url) { + case .coco: return try readCOCO(files) + case .yolo: return try readYOLO(files, classNames: classNames) + case .huggingface: return try readHuggingFace(files, classNames: classNames) + } + } + + static func detect(_ files: Tree, at url: URL) throws -> DatasetFormat { + if !files.named("metadata.jsonl").isEmpty { return .huggingface } + if !files.cocoFiles().isEmpty { return .coco } + if !files.yoloLabelFiles().isEmpty { return .yolo } + throw ForeignDatasetError( + message: "couldn't tell what kind of dataset \(url.path) is; pass --format yolo, coco or huggingface", + isUsage: true) + } + + // MARK: - COCO + + private static func readCOCO(_ files: Tree) throws -> ForeignDataset { + let jsons = files.cocoFiles() + guard !jsons.isEmpty else { throw ForeignDatasetError(message: "no COCO annotation file found") } + var result = ForeignDataset(format: .coco, images: []) + for json in jsons { + let parsed: [ImportedImage] + do { + parsed = try BoxImportParser.parse(Data(contentsOf: json)) + } catch { + throw ForeignDatasetError(message: "\(json.lastPathComponent): \(describe(error))") + } + for entry in parsed { + // COCO file names are relative to an images folder that varies + // by tool; the parser keeps the basename, which is looked up + // next to the JSON first and then anywhere in the dataset. + if let source = files.image(named: entry.image, near: json.deletingLastPathComponent()) { + result.images.append(.init(source: source, boxes: entry.boxes)) + } else { + result.missingImages.append(entry.image) + } + } + } + return result + } + + // MARK: - YOLO + + private static func readYOLO(_ files: Tree, classNames: [String]?) throws -> ForeignDataset { + let names = try classNames ?? yoloClassNames(files) + var boxesByImage: [URL: [ImportedBox]] = [:] + var result = ForeignDataset(format: .yolo, images: []) + + for label in files.yoloLabelFiles() { + let stem = label.deletingPathExtension().lastPathComponent + guard let image = files.yoloImage(forLabel: label) else { + result.missingImages.append(stem) + continue + } + let text = try String(contentsOf: label, encoding: .utf8) + var boxes: [ImportedBox] = [] + for (index, line) in text.split(whereSeparator: \.isNewline).enumerated() { + let fields = line.split(whereSeparator: \.isWhitespace) + if fields.isEmpty { continue } + let numbers = fields.compactMap { Double($0) } + guard numbers.count == fields.count, numbers.count >= 5, let rect = yoloRect(numbers.dropFirst()) else { + throw ForeignDatasetError( + message: "\(label.lastPathComponent) line \(index + 1): expected 'class cx cy w h'") + } + let classIndex = Int(numbers[0]) + let name = names.indices.contains(classIndex) ? names[classIndex] : "class_\(classIndex)" + boxes.append(ImportedBox(label: name, geometry: .normalized(rect))) + } + boxesByImage[image] = boxes + } + // An image with no label file is a background image in YOLO — as long + // as it sits in a folder the dataset demonstrably uses for images. + let imageFolders = Set(boxesByImage.keys.map { $0.deletingLastPathComponent().path }) + for image in files.images where imageFolders.contains(image.deletingLastPathComponent().path) { + result.images.append(.init(source: image, boxes: boxesByImage[image] ?? [])) + } + return result + } + + /// `cx cy w h`, or a segmentation polygon `x1 y1 x2 y2 …` reduced to the + /// box around it. Normalized, top-left origin. + private static func yoloRect(_ values: ArraySlice) -> CGRect? { + let v = Array(values) + if v.count == 4 { + return CGRect(x: v[0] - v[2] / 2, y: v[1] - v[3] / 2, width: v[2], height: v[3]) + } + guard v.count >= 6, v.count.isMultiple(of: 2) else { return nil } + let xs = stride(from: 0, to: v.count, by: 2).map { v[$0] } + let ys = stride(from: 1, to: v.count, by: 2).map { v[$0] } + guard let minX = xs.min(), let maxX = xs.max(), let minY = ys.min(), let maxY = ys.max() else { return nil } + return CGRect(x: minX, y: minY, width: maxX - minX, height: maxY - minY) + } + + private static func yoloClassNames(_ files: Tree) throws -> [String] { + for name in ["data.yaml", "data.yml", "dataset.yaml", "classes.txt", "obj.names", "labels.txt"] { + if let file = files.named(name).first { + let names = try ClassNames.read(file) + if !names.isEmpty { return names } + } + } + return [] + } + + // MARK: - Hugging Face + + private static func readHuggingFace(_ files: Tree, classNames: [String]?) throws -> ForeignDataset { + let metadataFiles = files.named("metadata.jsonl") + guard !metadataFiles.isEmpty else { throw ForeignDatasetError(message: "no metadata.jsonl found") } + // Integer categories take their names from the dataset card, if it has them. + let names = try classNames ?? files.named("README.md").first + .map { ClassNames.parseYAML(try String(contentsOf: $0, encoding: .utf8)) } ?? [] + + var result = ForeignDataset(format: .huggingface, images: []) + for metadata in metadataFiles { + let directory = metadata.deletingLastPathComponent() + let text = try String(contentsOf: metadata, encoding: .utf8) + for (index, line) in text.split(whereSeparator: \.isNewline).enumerated() { + let here = "\(metadata.lastPathComponent) line \(index + 1)" + guard let row = try? JSONSerialization.jsonObject(with: Data(line.utf8)) as? [String: Any], + let fileName = row["file_name"] as? String else { + throw ForeignDatasetError(message: "\(here): expected a JSON object with \"file_name\"") + } + let boxes = try huggingFaceBoxes(row["objects"], names: names, at: here) + let source = directory.appendingPathComponent(fileName).standardizedFileURL + if FileManager.default.fileExists(atPath: source.path) { + result.images.append(.init(source: source, boxes: boxes)) + } else { + result.missingImages.append(fileName) + } + } + } + return result + } + + /// `{"bbox": [[x, y, w, h], …], "categories": […]}` — boxes are pixels from + /// the top-left corner. The label list is `categories` in the ImageFolder + /// docs and `category` in many published datasets; both are read. + private static func huggingFaceBoxes(_ raw: Any?, names: [String], at place: String) throws -> [ImportedBox] { + guard let objects = raw as? [String: Any], let rawBoxes = objects["bbox"] as? [[Any]] else { return [] } + let labels = (objects["categories"] ?? objects["category"]) as? [Any] ?? [] + return try rawBoxes.enumerated().map { index, raw in + let numbers = raw.compactMap { ($0 as? NSNumber)?.doubleValue } + guard numbers.count == 4, raw.count == 4 else { + throw ForeignDatasetError(message: "\(place): box #\(index + 1) is not [x, y, width, height]") + } + let label: String + switch index < labels.count ? labels[index] : nil { + case let name as String: label = name + case let number as NSNumber: + label = names.indices.contains(number.intValue) ? names[number.intValue] : "class_\(number.intValue)" + default: throw ForeignDatasetError(message: "\(place): box #\(index + 1) has no category") + } + return ImportedBox(label: label, geometry: .pixels( + CGRect(x: numbers[0], y: numbers[1], width: numbers[2], height: numbers[3]))) + } + } + + private static func describe(_ error: Error) -> String { + (error as? LocalizedError)?.errorDescription ?? "\(error)" + } +} + +/// Class names as YOLO's `data.yaml` and a Hugging Face dataset card write +/// them. Both are YAML, and both use one of three small shapes, so those +/// shapes are read directly rather than pulling in a YAML parser: +/// +/// ```yaml +/// names: [cat, dog] # inline list +/// names: # block list +/// - cat +/// - dog +/// names: # index map +/// 0: cat +/// '1': dog +/// ``` +public enum ClassNames { + /// Class names from a file: a YAML file with a `names:` entry (a YOLO + /// `data.yaml`, a dataset card), or a plain list with one name per line. + public static func read(_ url: URL) throws -> [String] { + let text = try String(contentsOf: url, encoding: .utf8) + if ["yaml", "yml", "md"].contains(url.pathExtension.lowercased()) { return parseYAML(text) } + return text.split(whereSeparator: \.isNewline) + .map { $0.trimmingCharacters(in: .whitespaces) } + .filter { !$0.isEmpty } + } + + static func parseYAML(_ text: String) -> [String] { + let lines = text.components(separatedBy: .newlines) + guard let start = lines.firstIndex(where: { $0.trimmingCharacters(in: .whitespaces).hasPrefix("names:") }) + else { return [] } + + let inline = lines[start].trimmingCharacters(in: .whitespaces).dropFirst("names:".count) + .trimmingCharacters(in: .whitespaces) + if inline.hasPrefix("[") { + return inline.trimmingCharacters(in: CharacterSet(charactersIn: "[]")) + .split(separator: ",").map { unquote(String($0)) }.filter { !$0.isEmpty } + } + + let indent = lines[start].prefix { $0 == " " || $0 == "\t" }.count + var listed: [String] = [] + var indexed: [Int: String] = [:] + for line in lines[(start + 1)...] { + let trimmed = line.trimmingCharacters(in: .whitespaces) + if trimmed.isEmpty || trimmed.hasPrefix("#") { continue } + let depth = line.prefix { $0 == " " || $0 == "\t" }.count + if trimmed.hasPrefix("- ") { + guard depth >= indent else { break } + listed.append(unquote(String(trimmed.dropFirst(2)))) + } else if depth > indent, let colon = trimmed.firstIndex(of: ":"), + let index = Int(unquote(String(trimmed[.. String { + text.trimmingCharacters(in: .whitespaces).trimmingCharacters(in: CharacterSet(charactersIn: "'\"")) + } +} + +/// The files under a dataset folder, listed once. Dataset layouts differ in +/// where they keep things, so readers ask this for files by name or role +/// instead of assuming paths. +struct Tree { + let root: URL + private(set) var all: [URL] = [] + private(set) var images: [URL] = [] + private var imagesByName: [String: [URL]] = [:] + /// Folder path + file stem → image, for matching a label file to its image. + private var imageByFolderAndStem: [String: URL] = [:] + + /// Everything under `root`, a few levels deep (splits and their + /// `images`/`labels` folders), hidden files skipped. + init(root: URL) { + self.root = root + let enumerator = FileManager.default.enumerator( + at: root, includingPropertiesForKeys: [.isRegularFileKey], options: [.skipsHiddenFiles]) + var found: [URL] = [] + while let url = enumerator?.nextObject() as? URL { + if enumerator?.level ?? 0 > 6 { enumerator?.skipDescendants(); continue } + found.append(url.standardizedFileURL) + } + index(found.sorted { $0.path < $1.path }) + } + + /// A single annotation file plus the images around it. + init(root: URL, only file: URL) { + self.init(root: root) + all = all.filter { $0.pathExtension.lowercased() != "json" } + [file.standardizedFileURL] + } + + private mutating func index(_ urls: [URL]) { + all = urls + images = urls.filter(ImageImporter.isImageFile) + imagesByName = Dictionary(grouping: images, by: \.lastPathComponent) + for image in images { + let key = Self.key(image.deletingLastPathComponent().path, image.deletingPathExtension().lastPathComponent) + if imageByFolderAndStem[key] == nil { imageByFolderAndStem[key] = image } + } + } + + private static func key(_ folder: String, _ stem: String) -> String { folder + "\u{0}" + stem } + + func named(_ name: String) -> [URL] { + all.filter { $0.lastPathComponent == name } + } + + /// JSON files that are COCO annotation files (checked by content, since + /// their names follow no single convention). + func cocoFiles() -> [URL] { + all.filter { $0.pathExtension.lowercased() == "json" }.filter { url in + guard let data = try? Data(contentsOf: url, options: .mappedIfSafe), + let object = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { return false } + return object["images"] is [Any] && object["annotations"] is [Any] && object["categories"] is [Any] + } + } + + /// An image by file name: next to `directory` if there, otherwise the only + /// one of that name anywhere in the dataset. + func image(named name: String, near directory: URL) -> URL? { + let candidates = imagesByName[name] ?? [] + let base = directory.standardizedFileURL.path + return candidates.first { $0.path.hasPrefix(base + "/") } ?? (candidates.count == 1 ? candidates[0] : nil) + } + + // MARK: YOLO layout + + /// Label files: `.txt` files that have an image of the same name, either + /// beside them or in the matching `images` folder. (This is what tells + /// them apart from `classes.txt` and READMEs.) + func yoloLabelFiles() -> [URL] { + all.filter { $0.pathExtension.lowercased() == "txt" && yoloImage(forLabel: $0) != nil } + } + + /// `…/labels/train/a.txt` ↔ `…/images/train/a.jpg`, or the image beside it. + func yoloImage(forLabel label: URL) -> URL? { + let stem = label.deletingPathExtension().lastPathComponent + var folders = [label.deletingLastPathComponent().path] + var components = label.deletingLastPathComponent().pathComponents + if let index = components.lastIndex(of: "labels") { + components[index] = "images" + folders.append(NSString.path(withComponents: components)) + } + return folders.lazy.compactMap { imageByFolderAndStem[Self.key($0, stem)] }.first + } +} diff --git a/Sources/LabelKitApp/ExportCommand.swift b/Sources/LabelKitApp/ExportCommand.swift new file mode 100644 index 0000000..d13d61a --- /dev/null +++ b/Sources/LabelKitApp/ExportCommand.swift @@ -0,0 +1,70 @@ +import ArgumentParser +import Foundation +import LabelKit + +/// `labelkit export` — write a Create ML dataset out as YOLO, COCO or a +/// Hugging Face image dataset, into a new folder. The dataset is only read. +struct ExportCommand: ParsableCommand { + static let configuration = CommandConfiguration( + commandName: "export", + abstract: "Write a dataset out as YOLO, COCO or a Hugging Face image dataset.", + discussion: """ + Examples: + labelkit export ./cards --format huggingface --out ./cards-hf + labelkit export ./cards --format yolo --out ./cards-yolo + labelkit export ./cards --format coco --out ./cards-coco --no-images + + What is written into --out (which must be new or empty): + + yolo images/, labels/.txt ('class cx cy w h', normalized), + classes.txt and data.yaml + coco _annotations.coco.json with the images beside it + huggingface README.md (a dataset card) and train/metadata.jsonl with + the images under train/images/ — ready for + 'hf upload --repo-type=dataset' + + Every entry whose image file exists is exported, negatives included. + Images that have no entry yet are unlabelled and are left out. Class ids + follow the labels in alphabetical order. Images are copied (on APFS a + copy takes no extra space); --no-images writes only the annotations. + + stdout carries a JSON report. Exit 0 on success, 1 if the export failed, + 64 for a usage error. + """) + + @Argument(help: "Dataset directory, or path to an annotations .json file.") + var path: String + + @Option(name: .long, help: "Target format: yolo, coco or huggingface.") + var format: DatasetFormat + + @Option(name: [.customShort("o"), .long], help: "Folder to write the export into. Must be new or empty.") + var out: String + + @Option(name: .long, help: "Explicit annotations.json path (overrides auto-detection).") + var annotations: String? + + @Flag(name: .long, inversion: .prefixedNo, help: "Copy the image files into the export.") + var images = true + + func run() throws { + let document = try Headless.openDocument(path: path, annotations: annotations) + let outURL = URL(fileURLWithPath: (out as NSString).expandingTildeInPath) + + // YOLO and COCO need each image's size; one parallel header-only pass. + let onDisk = Set(document.imagesOnDisk) + let sizes = format == .huggingface + ? [:] : document.pixelSizes(of: document.uniqueRecords.map(\.image).filter(onDisk.contains)) + + do { + Headless.printJSON(try DatasetExport.run( + document, to: outURL, options: .init(format: format, copyImages: images), + pixelSize: { sizes[$0] })) + } catch let error as DatasetExport.ExportError { + throw ValidationError(error.message) + } catch { + Headless.note("export failed: \(Headless.describe(error))") + throw ExitCode(1) + } + } +} diff --git a/Sources/LabelKitApp/ImportCommand.swift b/Sources/LabelKitApp/ImportCommand.swift new file mode 100644 index 0000000..a05ab41 --- /dev/null +++ b/Sources/LabelKitApp/ImportCommand.swift @@ -0,0 +1,123 @@ +import ArgumentParser +import Foundation +import LabelKit + +/// `labelkit import` — bring a YOLO, COCO or Hugging Face dataset into a +/// Create ML dataset: images copied in, boxes merged into annotations.json. +struct ImportCommand: ParsableCommand { + static let configuration = CommandConfiguration( + commandName: "import", + abstract: "Bring a YOLO, COCO or Hugging Face dataset into a Create ML dataset.", + discussion: """ + Examples: + labelkit import ./yolo-export --into ./cards + labelkit import ./coco/_annotations.coco.json --into ./cards + labelkit import ./hf-download --into ./cards --format huggingface --negatives + labelkit import ./yolo-export --into ./cards --dry-run + labelkit import ./coco8 --into ./coco8-ml --names coco8.yaml + + The source is a folder (or a COCO .json file). Its format is worked out + from what is there: metadata.jsonl means Hugging Face, a JSON with + images/annotations/categories means COCO, .txt label files next to + images mean YOLO. --format overrides. Splits (train/valid/test) are + imported together, since a Create ML dataset is one folder and Create ML + makes its own validation split. + + A YOLO download often comes without its class names; boxes then import + as class_0, class_1, … Pass the names with --names data.yaml (or a text + file, one name per line, in id order). + + Images are copied into (created if needed); an existing file + is never overwritten — a different image with the same name is given a + new one, reported under "renamed". Boxes are added the way 'annotate' + adds them, so importing the same source twice changes nothing. + + Source images that have no boxes are skipped unless --negatives is + given. If anything in the source can't be applied, nothing is copied or + written and the command exits 1; --lenient applies the rest. + + stdout carries a JSON report. Exit 0 on success, 1 when there were + problems, 64 for a usage error. + """) + + @Argument(help: "The dataset to import: a folder, or a COCO .json file.") + var source: String + + @Option(name: .long, help: "The Create ML dataset folder to import into (created if it doesn't exist).") + var into: String + + @Option(name: .long, help: "Source format: yolo, coco or huggingface. Default: detected.") + var format: DatasetFormat? + + @Option(name: .long, help: "File naming the classes, for a source that only has numeric ids: a YOLO data.yaml, or a text file with one name per line.") + var names: String? + + @Flag(name: .long, help: "Record source images that have no boxes as negative examples.") + var negatives = false + + @Flag(name: .long, help: "Report what would happen without copying or writing anything.") + var dryRun = false + + @Flag(name: .long, help: "Apply what is valid instead of refusing the whole import.") + var lenient = false + + func run() throws { + let sourceURL = URL(fileURLWithPath: (source as NSString).expandingTildeInPath) + var classNames: [String]? + if let names { + let url = URL(fileURLWithPath: (names as NSString).expandingTildeInPath) + guard let read = try? ClassNames.read(url), !read.isEmpty else { + throw ValidationError("Couldn't read class names from \(names).") + } + classNames = read + } + let foreign: ForeignDataset + do { + foreign = try ForeignDatasetReader.read(at: sourceURL, format: format, classNames: classNames) + } catch let error as ForeignDatasetError where error.isUsage { + throw ValidationError(error.message) + } catch { + // A dataset that is there but broken is a problem with the data, not the call. + Headless.note("couldn't read \(source): \(Headless.describe(error))") + throw ExitCode(1) + } + + let datasetURL = URL(fileURLWithPath: (into as NSString).expandingTildeInPath) + if !dryRun { + do { + try FileManager.default.createDirectory(at: datasetURL, withIntermediateDirectories: true) + } catch { + throw ValidationError("Couldn't create \(into): \(Headless.describe(error))") + } + } + var document: DatasetDocument + if FileManager.default.fileExists(atPath: datasetURL.path) { + document = try Headless.openDocument(path: datasetURL.path, annotations: nil) + } else { + // --dry-run into a folder that doesn't exist yet: an empty dataset. + document = DatasetDocument( + location: DatasetLocation( + imagesDirectory: datasetURL, + annotationsURL: datasetURL.appendingPathComponent("annotations.json"), + annotationsExists: false), + records: [], imagesOnDisk: []) + } + + let report: DatasetImport.Report + do { + report = try DatasetImport.run( + foreign, into: &document, + options: .init(recordNegatives: negatives, lenient: lenient, dryRun: dryRun)) + } catch { + Headless.note("import failed: \(Headless.describe(error))") + throw ExitCode(1) + } + Headless.printJSON(report) + if !report.problems.isEmpty { + if !lenient { Headless.note("nothing imported: \(report.problems.count) problem(s) (--lenient applies the rest)") } + throw ExitCode(1) + } + } +} + +extension DatasetFormat: ExpressibleByArgument {} diff --git a/Sources/LabelKitApp/LabelKitCommand.swift b/Sources/LabelKitApp/LabelKitCommand.swift index c4804dc..90cd96f 100644 --- a/Sources/LabelKitApp/LabelKitCommand.swift +++ b/Sources/LabelKitApp/LabelKitCommand.swift @@ -14,7 +14,7 @@ struct LabelKitCommand: ParsableCommand { subcommands: [ OpenCommand.self, DetectCommand.self, TrainCommand.self, StatsCommand.self, ValidateCommand.self, AnnotateCommand.self, RenderCommand.self, - SkillCommand.self, + ImportCommand.self, ExportCommand.self, SkillCommand.self, ], defaultSubcommand: OpenCommand.self ) diff --git a/Tests/LabelKitTests/DatasetInteropTests.swift b/Tests/LabelKitTests/DatasetInteropTests.swift new file mode 100644 index 0000000..8c3616c --- /dev/null +++ b/Tests/LabelKitTests/DatasetInteropTests.swift @@ -0,0 +1,375 @@ +import CoreGraphics +import XCTest +@testable import LabelKit + +/// Import and export against real folders on disk, with real (tiny) images, +/// since the formats differ exactly in where files live and what size the +/// images are. +final class DatasetInteropTests: XCTestCase { + var root: URL! + var dataset: URL { root.appendingPathComponent("dataset") } + + override func setUpWithError() throws { + root = FileManager.default.temporaryDirectory.appendingPathComponent("labelkit-interop-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: dataset, withIntermediateDirectories: true) + try image("a.png", 200, 100, in: dataset) + try image("b.png", 100, 200, in: dataset) + try image("c.png", 50, 50, in: dataset) // on disk, no entry: unlabelled + try write(""" + [ + {"image": "a.png", "annotations": [ + {"label": "coin", "coordinates": {"x": 150, "y": 50, "width": 40, "height": 60}}, + {"label": "card", "coordinates": {"x": 50, "y": 50, "width": 20, "height": 20}}]}, + {"image": "b.png", "annotations": []}, + {"image": "ghost.png", "annotations": [ + {"label": "card", "coordinates": {"x": 5, "y": 5, "width": 2, "height": 2}}]} + ] + """, to: dataset.appendingPathComponent("annotations.json")) + } + + override func tearDownWithError() throws { + try? FileManager.default.removeItem(at: root) + } + + // MARK: - Fixtures + + func image(_ name: String, _ width: Int, _ height: Int, in directory: URL) throws { + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + let made = try writeTempPNG(size: CGSize(width: width, height: height)) + try FileManager.default.moveItem(at: made, to: directory.appendingPathComponent(name)) + } + + func write(_ text: String, to url: URL) throws { + try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true) + try Data(text.utf8).write(to: url) + } + + func read(_ path: String, in directory: URL) throws -> String { + try String(contentsOf: directory.appendingPathComponent(path), encoding: .utf8) + } + + func document(_ url: URL? = nil) throws -> DatasetDocument { + let target = url ?? dataset + try FileManager.default.createDirectory(at: target, withIntermediateDirectories: true) + return try DatasetDocument(location: XCTUnwrap(DatasetLocator.resolve(path: target.path))) + } + + @discardableResult + func export(_ format: DatasetFormat, to name: String, copyImages: Bool = true) throws -> (URL, DatasetExport.Report) { + let source = try document() + let out = root.appendingPathComponent(name) + let report = try DatasetExport.run( + source, to: out, options: .init(format: format, copyImages: copyImages), labelkitVersion: "test", + pixelSize: { source.pixelSize(of: $0) }) + return (out, report) + } + + @discardableResult + func importing(_ source: URL, into target: URL, format: DatasetFormat? = nil, + options: DatasetImport.Options = .init(recordNegatives: true)) throws -> DatasetImport.Report { + var destination = try document(target) + let foreign = try ForeignDatasetReader.read(at: source, format: format) + return try DatasetImport.run(foreign, into: &destination, options: options, labelkitVersion: "test") + } + + /// The exported dataset, imported into a fresh folder, must hold the same + /// labelled images and boxes as the original (minus the entry whose image + /// file never existed). + func assertRoundTrips(_ format: DatasetFormat, line: UInt = #line) throws { + let (out, exported) = try export(format, to: "out-\(format.rawValue)") + XCTAssertEqual(exported.images, 2, line: line) + XCTAssertEqual(exported.boxes, 2, line: line) + XCTAssertEqual(exported.labels, ["card", "coin"], line: line) + XCTAssertEqual(exported.skipped, [.init(image: "ghost.png", reason: "image file not found")], line: line) + + let back = root.appendingPathComponent("back-\(format.rawValue)") + let report = try importing(out, into: back) + XCTAssertEqual(report.format, format.rawValue, "format is detected", line: line) + XCTAssertEqual(report.images, .init(found: 2, copied: 2, alreadyPresent: 0), line: line) + XCTAssertEqual(report.boxes.added, 2, line: line) + XCTAssertTrue(report.problems.isEmpty, line: line) + + let original = try document().records.filter { $0.image != "ghost.png" } + let returned = try document(back).records + XCTAssertEqual(returned.map(\.image), ["a.png", "b.png"], line: line) + for (a, b) in zip(original, returned) { + XCTAssertEqual(a.boxes.count, b.boxes.count, line: line) + // Class order isn't preserved by formats that group by class id. + for box in a.boxes { + let match = try XCTUnwrap(b.boxes.first { $0.label == box.label }, line: line) + XCTAssertEqual(match.x, box.x, accuracy: 0.011, line: line) + XCTAssertEqual(match.y, box.y, accuracy: 0.011, line: line) + XCTAssertEqual(match.width, box.width, accuracy: 0.011, line: line) + XCTAssertEqual(match.height, box.height, accuracy: 0.011, line: line) + } + } + XCTAssertEqual(try document(back).imagesOnDisk, ["a.png", "b.png"], "the unlabelled image isn't exported", line: line) + } + + // MARK: - Round trips + + func testYOLORoundTrip() throws { try assertRoundTrips(.yolo) } + func testCOCORoundTrip() throws { try assertRoundTrips(.coco) } + func testHuggingFaceRoundTrip() throws { try assertRoundTrips(.huggingface) } + + // MARK: - What gets written + + func testYOLOExportFiles() throws { + let (out, report) = try export(.yolo, to: "yolo") + // a.png is 200x100: coin centre (150,50) 40x60 → 0.75 0.5 0.2 0.6; card is class 0. + XCTAssertEqual(try read("labels/a.txt", in: out), + "1 0.750000 0.500000 0.200000 0.600000\n0 0.250000 0.500000 0.100000 0.200000\n") + XCTAssertEqual(try read("labels/b.txt", in: out), "", "a negative is an empty label file") + XCTAssertEqual(try read("classes.txt", in: out), "card\ncoin\n") + XCTAssertTrue(try read("data.yaml", in: out).contains("names:\n 0: 'card'\n 1: 'coin'\n")) + XCTAssertTrue(FileManager.default.fileExists(atPath: out.appendingPathComponent("images/a.png").path)) + XCTAssertEqual(report.files, ["data.yaml", "classes.txt", "labels/", "images/"]) + } + + func testCOCOExportUsesTopLeftBoxesAndOneBasedIDs() throws { + let (out, _) = try export(.coco, to: "coco") + let json = try XCTUnwrap(JSONSerialization.jsonObject( + with: Data(contentsOf: out.appendingPathComponent("_annotations.coco.json"))) as? [String: Any]) + let images = try XCTUnwrap(json["images"] as? [[String: Any]]) + XCTAssertEqual(images.map { $0["file_name"] as? String }, ["a.png", "b.png"]) + XCTAssertEqual(images[0]["width"] as? Int, 200) + XCTAssertEqual(images[0]["id"] as? Int, 1) + let annotations = try XCTUnwrap(json["annotations"] as? [[String: Any]]) + XCTAssertEqual(annotations[0]["bbox"] as? [Double], [130, 20, 40, 60]) // coin, top-left corner + XCTAssertEqual(annotations[0]["category_id"] as? Int, 2) + let categories = try XCTUnwrap(json["categories"] as? [[String: Any]]) + XCTAssertEqual(categories.map { $0["name"] as? String }, ["card", "coin"]) + } + + func testHuggingFaceExportIsAnImageFolderWithACard() throws { + let (out, _) = try export(.huggingface, to: "hf") + let rows = try read("train/metadata.jsonl", in: out).split(separator: "\n").map(String.init) + XCTAssertEqual(rows, [ + #"{"file_name":"images/a.png","objects":{"bbox":[[130,20,40,60],[40,40,20,20]],"categories":["coin","card"]}}"#, + #"{"file_name":"images/b.png","objects":{"bbox":[],"categories":[]}}"#, + ]) + let card = try read("README.md", in: out) + XCTAssertTrue(card.hasPrefix("---\npretty_name: 'dataset'\ntask_categories:\n- object-detection\n")) + XCTAssertTrue(FileManager.default.fileExists(atPath: out.appendingPathComponent("train/images/a.png").path)) + } + + /// Coordinates are written at 2 decimals, never as a binary double's long tail. + func testExportedCoordinatesAreShortDecimals() throws { + var source = try document() + source.records[0].boxes = [BoxRecord(label: "card", x: 100.33, y: 50.17, width: 20.03, height: 10.07)] + try source.save() + for (format, file) in [(DatasetFormat.coco, "_annotations.coco.json"), (.huggingface, "train/metadata.jsonl")] { + let (out, _) = try export(format, to: "decimals-\(format.rawValue)") + let text = try read(file, in: out) + XCTAssertTrue(text.contains("20.03"), "\(format): the width as written") + XCTAssertNil(text.range(of: #"\d\.\d{3,}"#, options: .regularExpression), "\(format): \(text)") + } + } + + func testExportWithoutImagesWritesOnlyAnnotations() throws { + let (out, report) = try export(.yolo, to: "yolo-bare", copyImages: false) + XCTAssertFalse(FileManager.default.fileExists(atPath: out.appendingPathComponent("images").path)) + XCTAssertEqual(report.files, ["data.yaml", "classes.txt", "labels/"]) + } + + func testExportRefusesTheDatasetFolderAndNonEmptyFolders() throws { + let source = try document() + XCTAssertThrowsError(try DatasetExport.run(source, to: dataset, options: .init(format: .coco), pixelSize: { _ in nil })) + let busy = root.appendingPathComponent("busy") + try write("x", to: busy.appendingPathComponent("keep.txt")) + XCTAssertThrowsError(try DatasetExport.run(source, to: busy, options: .init(format: .coco), pixelSize: { _ in nil })) + XCTAssertEqual(try read("keep.txt", in: busy), "x") + } + + func testYOLOExportRefusesImagesThatWouldShareALabelFile() throws { + try image("a.jpg", 10, 10, in: dataset) + var source = try document() + source.records.append(ImageAnnotationRecord(image: "a.jpg", boxes: [])) + XCTAssertThrowsError(try DatasetExport.run( + source, to: root.appendingPathComponent("clash"), options: .init(format: .yolo), + pixelSize: { source.pixelSize(of: $0) })) + } + + // MARK: - Reading other people's layouts + + /// Ultralytics layout: images// and labels//, names in data.yaml. + func testYOLOSplitLayoutWithPolygonsAndBackgroundImages() throws { + let yolo = root.appendingPathComponent("yolo-in") + try image("one.png", 100, 100, in: yolo.appendingPathComponent("images/train")) + try image("two.png", 100, 100, in: yolo.appendingPathComponent("images/val")) + try image("empty.png", 100, 100, in: yolo.appendingPathComponent("images/train")) + try write("0 0.5 0.5 0.2 0.4\n\n2 0.1 0.1 0.1 0.1\n", to: yolo.appendingPathComponent("labels/train/one.txt")) + // A segmentation row: the box around the polygon (0.2..0.6, 0.3..0.9). + try write("1 0.2 0.3 0.6 0.3 0.6 0.9 0.2 0.9\n", to: yolo.appendingPathComponent("labels/val/two.txt")) + try write("path: .\ntrain: images/train\nnames:\n 0: cat\n 1: 'dog'\n", to: yolo.appendingPathComponent("data.yaml")) + try write("not a label file", to: yolo.appendingPathComponent("README.txt")) + + let foreign = try ForeignDatasetReader.read(at: yolo) + XCTAssertEqual(foreign.format, .yolo) + let byName = Dictionary(uniqueKeysWithValues: foreign.images.map { ($0.source.lastPathComponent, $0.boxes) }) + XCTAssertEqual(Set(byName.keys), ["one.png", "two.png", "empty.png"]) + XCTAssertEqual(byName["empty.png"], [], "an image with no label file is a background image") + XCTAssertEqual(byName["one.png"]?.map(\.label), ["cat", "class_2"], "a class with no name still imports") + guard case .normalized(let polygon)? = byName["two.png"]?.first?.geometry else { return XCTFail() } + XCTAssertEqual(polygon.minX, 0.2, accuracy: 1e-9) + XCTAssertEqual(polygon.minY, 0.3, accuracy: 1e-9) + XCTAssertEqual(polygon.width, 0.4, accuracy: 1e-9) + XCTAssertEqual(polygon.height, 0.6, accuracy: 1e-9) + + XCTAssertThrowsError(try { + try self.write("0 0.5 0.5\n", to: yolo.appendingPathComponent("labels/train/one.txt")) + _ = try ForeignDatasetReader.read(at: yolo) + }(), "a malformed row is an error, not a skipped box") + } + + /// Many YOLO downloads ship without their names file; the caller supplies it. + func testClassNamesCanBeSuppliedForASourceThatHasOnlyIDs() throws { + let yolo = root.appendingPathComponent("yolo-ids") + try image("z.png", 100, 100, in: yolo) + try write("1 0.5 0.5 0.2 0.2\n0 0.2 0.2 0.1 0.1\n", to: yolo.appendingPathComponent("z.txt")) + XCTAssertEqual(try ForeignDatasetReader.read(at: yolo).images[0].boxes.map(\.label), ["class_1", "class_0"]) + + let yaml = root.appendingPathComponent("names.yaml") + try write("path: x\nnames:\n 0: person\n 1: zebra\ndownload: https://example.com/x.zip\n", to: yaml) + let list = root.appendingPathComponent("names.txt") + try write("person\n zebra \n\n", to: list) + for file in [yaml, list] { + let names = try ClassNames.read(file) + XCTAssertEqual(names, ["person", "zebra"]) + XCTAssertEqual(try ForeignDatasetReader.read(at: yolo, classNames: names).images[0].boxes.map(\.label), + ["zebra", "person"]) + } + } + + func testClassNameShapes() { + XCTAssertEqual(ClassNames.parseYAML("nc: 2\nnames: ['cat', \"dog\"]\n"), ["cat", "dog"]) + XCTAssertEqual(ClassNames.parseYAML("names:\n- cat\n- dog\nother: 1\n"), ["cat", "dog"]) + XCTAssertEqual(ClassNames.parseYAML("names:\n 0: cat\n 2: bird\ntrain: x\n"), ["cat", "class_1", "bird"]) + XCTAssertEqual(ClassNames.parseYAML(""" + dataset_info: + features: + - name: objects + sequence: + - name: category + dtype: + class_label: + names: + '0': card + '1': coin + """), ["card", "coin"]) + XCTAssertEqual(ClassNames.parseYAML("train: images\n"), []) + } + + func testHuggingFaceIntegerCategoriesTakeNamesFromTheCard() throws { + let hf = root.appendingPathComponent("hf-in") + try image("x.png", 100, 100, in: hf.appendingPathComponent("train")) + try write(#"{"file_name": "x.png", "objects": {"bbox": [[10, 20, 30, 40]], "category": [1]}}"# + "\n" + + #"{"file_name": "gone.png", "objects": {"bbox": [], "category": []}}"# + "\n", + to: hf.appendingPathComponent("train/metadata.jsonl")) + try write("---\ndataset_info:\n names:\n '0': card\n '1': coin\n---\n", to: hf.appendingPathComponent("README.md")) + + let foreign = try ForeignDatasetReader.read(at: hf) + XCTAssertEqual(foreign.format, .huggingface) + XCTAssertEqual(foreign.images.map(\.boxes), [[ + ImportedBox(label: "coin", geometry: .pixels(CGRect(x: 10, y: 20, width: 30, height: 40))), + ]]) + XCTAssertEqual(foreign.missingImages, ["gone.png"]) + } + + func testCOCOFileFindsItsImagesInASiblingFolder() throws { + let coco = root.appendingPathComponent("coco-in") + try image("p.png", 100, 100, in: coco.appendingPathComponent("train2017")) + try write(#""" + {"images":[{"id":1,"file_name":"p.png","width":100,"height":100},{"id":2,"file_name":"absent.png"}], + "categories":[{"id":1,"name":"cat"}], + "annotations":[{"id":1,"image_id":1,"category_id":1,"bbox":[10,20,30,40]}]} + """#, to: coco.appendingPathComponent("annotations/instances_train2017.json")) + + for source in [coco, coco.appendingPathComponent("annotations/instances_train2017.json")] { + let foreign = try ForeignDatasetReader.read(at: source, format: source == coco ? nil : .coco) + XCTAssertEqual(foreign.images.map(\.source.lastPathComponent), ["p.png"]) + XCTAssertEqual(foreign.missingImages, ["absent.png"]) + } + } + + func testUnrecognisableFolderIsAUsageError() throws { + let empty = root.appendingPathComponent("nothing") + try FileManager.default.createDirectory(at: empty, withIntermediateDirectories: true) + XCTAssertThrowsError(try ForeignDatasetReader.read(at: empty)) { + XCTAssertEqual(($0 as? ForeignDatasetError)?.isUsage, true) + } + XCTAssertThrowsError(try ForeignDatasetReader.read(at: root.appendingPathComponent("absent"))) { + XCTAssertEqual(($0 as? ForeignDatasetError)?.isUsage, true) + } + } + + // MARK: - Import behaviour + + func testImportingTwiceChangesNothing() throws { + let (out, _) = try export(.yolo, to: "yolo") + let target = root.appendingPathComponent("twice") + try importing(out, into: target) + let first = try Data(contentsOf: target.appendingPathComponent("annotations.json")) + + let again = try importing(out, into: target) + XCTAssertEqual(again.images, .init(found: 2, copied: 0, alreadyPresent: 2)) + XCTAssertEqual(again.boxes.added, 0) + XCTAssertEqual(again.boxes.duplicates, 2) + XCTAssertFalse(again.written) + XCTAssertEqual(try Data(contentsOf: target.appendingPathComponent("annotations.json")), first) + } + + /// A different picture that happens to share a name must not be overwritten, + /// and the boxes must follow the copy to its new name. + func testNameTakenByADifferentImageGetsANewNameAndItsBoxes() throws { + let (out, _) = try export(.coco, to: "coco") + let target = root.appendingPathComponent("taken") + try image("a.png", 640, 480, in: target) + let before = try Data(contentsOf: target.appendingPathComponent("a.png")) + + let report = try importing(out, into: target) + XCTAssertEqual(report.renamed, [.init(from: "a.png", to: "a-2.png")]) + XCTAssertEqual(try Data(contentsOf: target.appendingPathComponent("a.png")), before) + let records = try document(target).records + XCTAssertEqual(records.first { $0.image == "a-2.png" }?.boxes.count, 2) + XCTAssertNil(records.first { $0.image == "a.png" }) + } + + func testNegativesAreOnlyRecordedWhenAsked() throws { + let (out, _) = try export(.yolo, to: "yolo") + let target = root.appendingPathComponent("no-negatives") + try importing(out, into: target, options: .init()) + XCTAssertEqual(try document(target).records.map(\.image), ["a.png"]) + XCTAssertEqual(try document(target).imagesOnDisk, ["a.png", "b.png"], "the image is still copied") + } + + func testASourceWithAnUnusableBoxImportsNothingUnlessLenient() throws { + let yolo = root.appendingPathComponent("bad") + try image("good.png", 100, 100, in: yolo) + try image("bad.png", 100, 100, in: yolo) + try write("0 0.5 0.5 0.2 0.2\n", to: yolo.appendingPathComponent("good.txt")) + try write("0 5.0 5.0 0.2 0.2\n", to: yolo.appendingPathComponent("bad.txt")) // far outside the image + try write("thing\n", to: yolo.appendingPathComponent("classes.txt")) + + let strict = root.appendingPathComponent("strict") + let refused = try importing(yolo, into: strict) + XCTAssertEqual(refused.problems.count, 1) + XCTAssertFalse(refused.written) + XCTAssertEqual(try FileManager.default.contentsOfDirectory(atPath: strict.path), [], "nothing copied, nothing written") + + let lenient = root.appendingPathComponent("lenient") + let applied = try importing(yolo, into: lenient, options: .init(lenient: true)) + XCTAssertTrue(applied.written) + XCTAssertEqual(try document(lenient).records.map(\.image), ["good.png"]) + } + + func testDryRunTouchesNothing() throws { + let (out, _) = try export(.huggingface, to: "hf") + let target = root.appendingPathComponent("dry") + let report = try importing(out, into: target, options: .init(recordNegatives: true, dryRun: true)) + XCTAssertEqual(report.images.copied, 2) + XCTAssertEqual(report.boxes.added, 2) + XCTAssertFalse(report.written) + XCTAssertEqual(try FileManager.default.contentsOfDirectory(atPath: target.path), []) + } +} diff --git a/docs/datasets.md b/docs/datasets.md new file mode 100644 index 0000000..4ad5fd0 --- /dev/null +++ b/docs/datasets.md @@ -0,0 +1,172 @@ +# Sharing, storing and reusing datasets + +A labelkit dataset is Apple's Create ML object-detection format: a folder of +images plus one `annotations.json`. That is deliberately all there is, so the +question of where the images live, and how to trade datasets with people using +other tools, is answered with commands and recipes rather than a service. + +- [Import a dataset made elsewhere](#import-a-dataset-made-elsewhere) +- [Export for another tool](#export-for-another-tool) +- [Publish or back up on Hugging Face](#publish-or-back-up-on-hugging-face) +- [Keep images in your own bucket](#keep-images-in-your-own-bucket) +- [Use a big model to label, train a small one](#use-a-big-model-to-label-train-a-small-one) + +## Import a dataset made elsewhere + +```bash +labelkit import ./downloaded-dataset --into ./cards +``` + +`import` reads **YOLO**, **COCO** and **Hugging Face image-folder** datasets, +copies their images into your dataset folder and merges their boxes into +`annotations.json`. The format is worked out from what is in the folder; +`--format yolo|coco|huggingface` overrides. + +| Source | Recognised by | Notes | +|---|---|---| +| YOLO | `.txt` label files beside images, or `labels/` next to `images/` | class names from `data.yaml` or `classes.txt`; segmentation rows become the box around the polygon | +| COCO | a JSON with `images`, `annotations`, `categories` | pass the folder or the `.json` itself | +| Hugging Face | `metadata.jsonl` with `objects.bbox` | `[x, y, width, height]` in pixels; `categories` or `category`, as names or ids | + +A YOLO download often comes without its class names, in which case boxes +import as `class_0`, `class_1`, …. Give the names with `--names`, pointing at +the dataset's `data.yaml` or a text file with one name per line: + +```bash +labelkit import ./coco8 --into ./coco8-ml --names coco8.yaml +``` + +Things it is careful about: + +- **Nothing is overwritten.** If a different image already has the same name, + the incoming one is renamed (`a.jpg` → `a-2.jpg`) and its boxes follow it. +- **Safe to repeat.** Importing the same source again copies nothing and adds + nothing. +- **All or nothing.** If any box can't be used (outside its image, no size), + nothing is copied or written and the exit code is `1`. `--lenient` applies + the rest; `--dry-run` shows what would happen. +- **Splits are merged.** `train/`, `valid/` and `test/` come in together: a + Create ML dataset is one folder, and Create ML makes its own validation split + when it trains. +- **Images without boxes are skipped** unless you pass `--negatives`, because + in a downloaded dataset an image with no boxes may be a deliberate negative + or simply unlabelled. + +Datasets from **Roboflow Universe** can be downloaded in "CreateML" format, in +which case there is nothing to import: open the folder with `labelkit`. + +## Export for another tool + +```bash +labelkit export ./cards --format yolo --out ./cards-yolo +labelkit export ./cards --format coco --out ./cards-coco +labelkit export ./cards --format huggingface --out ./cards-hf +``` + +| Format | Written into `--out` | +|---|---| +| `yolo` | `images/`, `labels/.txt` (`class cx cy w h`, normalized), `classes.txt`, `data.yaml` | +| `coco` | `_annotations.coco.json` with the images beside it | +| `huggingface` | `README.md` (a dataset card) and `train/metadata.jsonl`, images under `train/images/` | + +Every entry whose image file exists is exported, negatives included; images +that have no entry yet are unlabelled and are left out. Class ids follow the +labels in alphabetical order, so a dataset always exports the same numbering. +`--out` must be a new or empty folder, and your dataset is only read. Images +are copied (on APFS a copy takes no extra space until one side changes); +`--no-images` writes just the annotation files. + +The YOLO export puts every image under `train`. Split off a validation set with +your YOLO tooling before training. + +## Publish or back up on Hugging Face + +[Hugging Face](https://huggingface.co/docs/hub/datasets-image) hosts image +datasets as versioned repositories, public or private, and the `huggingface` +export is exactly the layout it expects. It needs their `hf` command-line tool +and an account; labelkit never sees your token. + +```bash +labelkit export ./cards --format huggingface --out ./cards-hf +hf auth login +hf upload your-name/cards ./cards-hf --repo-type=dataset +``` + +A repository is public unless you make it private; set that when creating it +(on the website, or with the option their CLI documents) before uploading +anything you don't want published. + +and, on another machine or for someone else's dataset: + +```bash +hf download your-name/cards --repo-type dataset --local-dir ./cards-hf +labelkit import ./cards-hf --into ./cards --negatives +``` + +Before publishing, open the generated `README.md` and add a `license:` line to +the YAML at the top. Worth knowing, from Hugging Face's documentation at the +time of writing: private storage is free up to 100 GB per account, a repository +should stay under 100,000 files, and no folder should hold more than 10,000 +(the export splits images into numbered subfolders once a dataset passes 5,000). + +## Keep images in your own bucket + +For a team that keeps data in-house, the simplest arrangement is: **the +annotations file in git, the images in a bucket.** `annotations.json` is small +and diffs well; the images are large and never change. + +Any S3-compatible store works (Cloudflare R2, Backblaze B2, AWS S3), synced with +[rclone](https://rclone.org), which keeps the credentials in its own config: + +```bash +# .gitignore: everything in the dataset folder except the annotations +cards/* +!cards/annotations.json + +rclone copy ./cards remote:my-bucket/cards --exclude annotations.json # upload images +rclone copy remote:my-bucket/cards ./cards # fetch them elsewhere +``` + +After fetching, `labelkit validate ./cards` tells you whether every image the +annotations refer to has arrived (`missing-image`), and `labelkit stats ./cards` +lists any that are there but not yet labelled. + +If you already use [DVC](https://dvc.org), it works as it is: track the images +with `dvc add` and keep `annotations.json` in git. labelkit needs nothing +special either way, because it only ever reads and writes the local folder. + +## Use a big model to label, train a small one + +You can't shrink an existing detector with labelkit, but you can use one as a +teacher: let it label your images, check its work, and train a small Create ML +model on the result. For an on-device model this is often the quickest route +to good training data. + +```bash +# 1. Draft labels from the teacher +labelkit detect ./cards --model teacher.mlpackage --format ndjson \ + | labelkit annotate ./cards --from - + +# 2. Check them: by eye in pictures, and in the editor for the doubtful ones +labelkit render ./cards --out /tmp/check +labelkit ./cards + +# 3. Validate, then train the small model +labelkit validate ./cards +labelkit train ./cards -o cards.mlmodel +``` + +The teacher can be: + +- **Any Core ML object detector** via `detect --model`. A YOLO model qualifies + once exported to Core ML with its own tooling. The built-in Vision detectors + (`--detector`) cover only a few things (people, faces, cats and dogs, + rectangles), so expect them to find a fraction of what a trained model would. +- **A vision-language model** (Claude, Gemini, GPT, Qwen, …): have it answer + with boxes and pass them to `labelkit annotate`. An AI agent with the + labelkit skill does this loop on its own; see [agents.md](agents.md). +- **A dataset someone already labelled**: `labelkit import` it, then add your + own images on top. + +Treat teacher labels as a draft. A detector trained on unreviewed labels learns +the teacher's mistakes along with its strengths. diff --git a/scripts/smoke-scripted.sh b/scripts/smoke-scripted.sh index 13f03da..c8c204d 100755 --- a/scripts/smoke-scripted.sh +++ b/scripts/smoke-scripted.sh @@ -28,7 +28,7 @@ expect() { [[ "$got" -eq "$want" ]] || fail "expected exit $want, got $got: $*" } -for command in stats validate annotate render skill; do +for command in stats validate annotate render import export skill; do expect 0 "$lk" "$command" --help done @@ -108,6 +108,23 @@ expect 64 "$lk" stats "$work/no-such-dataset" expect 0 "$lk" render "$ds" --grid 100 --out "$work/out" [[ -s "$work/out/a.jpg" && -s "$work/out/b.jpg" ]] || fail "render didn't write both pictures" +# Export to each format and import it back: same images, same boxes, and a +# second import that changes nothing. +for format in yolo coco huggingface; do + expect 0 "$lk" export "$ds" --format "$format" --out "$work/out-$format" + expect 0 "$lk" import "$work/out-$format" --into "$work/back-$format" + cp "$work/back-$format/annotations.json" "$work/back-$format.json" + expect 0 "$lk" import "$work/out-$format" --into "$work/back-$format" + cmp -s "$work/back-$format/annotations.json" "$work/back-$format.json" \ + || fail "a repeated $format import changed the file" + "$lk" stats "$work/back-$format" | grep -q '"annotated" : 2' || fail "$format round trip lost images" + expect 0 "$lk" validate "$work/back-$format" --labels thing --strict +done +expect 64 "$lk" export "$ds" --format yolo --out "$work/out-yolo" # not empty +expect 64 "$lk" export "$ds" --format yolo --out "$ds" # the dataset itself +expect 64 "$lk" import "$work/no-such-source" --into "$work/x" +[[ ! -e "$work/x" ]] || fail "a refused import created its target" + # The skill prints, matches the committed copy, and installs. "$lk" skill | cmp -s - skills/labelkit/SKILL.md || fail "labelkit skill differs from skills/labelkit/SKILL.md" expect 0 "$lk" skill --install --dir "$work/skills" diff --git a/skills/labelkit/SKILL.md b/skills/labelkit/SKILL.md index 8629331..3c89b36 100644 --- a/skills/labelkit/SKILL.md +++ b/skills/labelkit/SKILL.md @@ -153,6 +153,22 @@ labelkit detect --detector rectangles -l card --format ndjson | labelk 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 # YOLO, COCO or Hugging Face layout, detected +labelkit export --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 ` reports, as JSON `issues` with a stable `code`: @@ -202,6 +218,8 @@ were unsure about. | `labelkit annotate …` | adds or replaces boxes | `annotations.json` | | `labelkit render [images…] --out DIR [--grid N] [--unlabeled]` | pictures with boxes drawn | files in DIR | | `labelkit detect --model M \| --detector D` | runs a detector, prints boxes | nothing | +| `labelkit import --into ` | brings in a YOLO, COCO or Hugging Face dataset | images and `annotations.json` | +| `labelkit export --format F --out DIR` | writes the dataset as YOLO, COCO or Hugging Face | files in DIR | | `labelkit train [-o model.mlmodel]` | trains a Core ML detector | the model file | Every command has `--help` with examples. `stats`, `validate` and `annotate` From 486498d7e9fab5954025810636fc3c9b70e7a59e Mon Sep 17 00:00:00 2001 From: shellbear Date: Sat, 28 Nov 2026 18:07:47 +0100 Subject: [PATCH 2/3] fix: confine Hugging Face import rows to images inside the source folder A metadata.jsonl row's file_name was joined to the folder and used if the file existed, so a row in an untrusted download could name a file outside the dataset (../../x.png, or an absolute path) and have it copied in. Rows are now resolved against the listing of the source folder, so only image files found under it are accepted; anything else is reported as missing. COCO and YOLO already resolved images through that listing. --- Sources/LabelKit/Interop/ForeignDataset.swift | 14 +++++++++-- Tests/LabelKitTests/DatasetInteropTests.swift | 25 +++++++++++++++++++ 2 files changed, 37 insertions(+), 2 deletions(-) diff --git a/Sources/LabelKit/Interop/ForeignDataset.swift b/Sources/LabelKit/Interop/ForeignDataset.swift index 44d0e96..1de4c34 100644 --- a/Sources/LabelKit/Interop/ForeignDataset.swift +++ b/Sources/LabelKit/Interop/ForeignDataset.swift @@ -199,8 +199,10 @@ public enum ForeignDatasetReader { throw ForeignDatasetError(message: "\(here): expected a JSON object with \"file_name\"") } let boxes = try huggingFaceBoxes(row["objects"], names: names, at: here) - let source = directory.appendingPathComponent(fileName).standardizedFileURL - if FileManager.default.fileExists(atPath: source.path) { + // The row is untrusted input: only an image that the listing of + // this dataset found is accepted, so a `file_name` such as + // `../../x.png` can't pull a file in from outside it. + if let source = files.listedImage(at: directory.appendingPathComponent(fileName)) { result.images.append(.init(source: source, boxes: boxes)) } else { result.missingImages.append(fileName) @@ -344,6 +346,14 @@ struct Tree { private static func key(_ folder: String, _ stem: String) -> String { folder + "\u{0}" + stem } + /// The image at `url`, if it is one of the image files found under `root`. + /// A path that leads anywhere else — outside the dataset, or to a file + /// that isn't an image — is nil. + func listedImage(at url: URL) -> URL? { + let path = url.standardizedFileURL.path + return imagesByName[url.lastPathComponent]?.first { $0.path == path } + } + func named(_ name: String) -> [URL] { all.filter { $0.lastPathComponent == name } } diff --git a/Tests/LabelKitTests/DatasetInteropTests.swift b/Tests/LabelKitTests/DatasetInteropTests.swift index 8c3616c..54ee4e1 100644 --- a/Tests/LabelKitTests/DatasetInteropTests.swift +++ b/Tests/LabelKitTests/DatasetInteropTests.swift @@ -276,6 +276,31 @@ final class DatasetInteropTests: XCTestCase { XCTAssertEqual(foreign.missingImages, ["gone.png"]) } + /// A downloaded dataset is untrusted: a row must not be able to name a file + /// outside it (or a non-image inside it) and have it copied into yours. + func testHuggingFaceRowsCannotReachOutsideTheDataset() throws { + let hf = root.appendingPathComponent("hf-evil") + try image("ok.png", 50, 50, in: hf.appendingPathComponent("train")) + try image("secret.png", 50, 50, in: root.appendingPathComponent("elsewhere")) + try write("secret", to: hf.appendingPathComponent("train/notes.txt")) + let outside = root.appendingPathComponent("elsewhere/secret.png").path + try write([ + #"{"file_name": "ok.png", "objects": {"bbox": [], "categories": []}}"#, + #"{"file_name": "../../elsewhere/secret.png", "objects": {"bbox": [], "categories": []}}"#, + "{\"file_name\": \"\(outside)\", \"objects\": {\"bbox\": [], \"categories\": []}}", + #"{"file_name": "notes.txt", "objects": {"bbox": [], "categories": []}}"#, + ].joined(separator: "\n") + "\n", to: hf.appendingPathComponent("train/metadata.jsonl")) + + let foreign = try ForeignDatasetReader.read(at: hf) + XCTAssertEqual(foreign.images.map(\.source.lastPathComponent), ["ok.png"]) + XCTAssertEqual(foreign.missingImages.count, 3) + + let target = root.appendingPathComponent("safe") + try importing(hf, into: target) + XCTAssertEqual(try FileManager.default.contentsOfDirectory(atPath: target.path).sorted(), + ["annotations.json", "ok.png"]) + } + func testCOCOFileFindsItsImagesInASiblingFolder() throws { let coco = root.appendingPathComponent("coco-in") try image("p.png", 100, 100, in: coco.appendingPathComponent("train2017")) From 267502d432db128d3c1fd98f813f0a67451c93b8 Mon Sep 17 00:00:00 2001 From: shellbear Date: Sat, 28 Nov 2026 18:20:02 +0100 Subject: [PATCH 3/3] fix: address the review of import and export A correctness review, a simplification pass and a trial with real tools found these before merging: - symlinked images were copied as links, leaving dangling files; the file a link points to is copied, under the dataset's name for it - a copy failing midway left earlier images behind, and a refused import still created its target folder; the folder is now created only when the import goes through, and a failed run removes what it copied - source images without boxes were copied in even without --negatives; they are left out and counted as withoutBoxes - overlapping same-class boxes within a source were dropped as duplicates; import now de-duplicates only against what the dataset already had - an image renamed on a first import (a.jpg -> a-2.jpg) was copied again on the next; the earlier copy is recognised by content - COCO file names that share a basename across folders resolved to one file; the path is now kept and resolved exactly - class names: trailing comments, quoted commas and colons, doubled quotes and lists wrapped over lines are read correctly, so labels round-trip - a YOLO class id of nan, 1e30, 1.5 or -1 crashed or was truncated; it is a reported error - COCO sizes recorded before an EXIF rotation distorted boxes; reported as a problem instead - a symlinked source folder is read; --into inside the source is refused - export: data.yaml no longer sets a relative path (YOLO tooling resolved it against its own datasets folder; verified loading with Ultralytics), a failed export removes its folder, hidden files don't make --out non-empty, and a file-name clash exits 1 rather than 64 - small cleanups from the simplification pass --- .../LabelKit/Headless/AnnotationMerge.swift | 23 ++- Sources/LabelKit/Headless/BoxImport.swift | 10 +- Sources/LabelKit/Interop/DatasetExport.swift | 48 ++++- Sources/LabelKit/Interop/DatasetImport.swift | 85 ++++++-- Sources/LabelKit/Interop/ForeignDataset.swift | 159 ++++++++++----- Sources/LabelKit/Store/ImageImporter.swift | 10 +- Sources/LabelKitApp/ExportCommand.swift | 2 +- Sources/LabelKitApp/ImportCommand.swift | 21 +- Tests/LabelKitTests/DatasetInteropTests.swift | 191 +++++++++++++++++- 9 files changed, 454 insertions(+), 95 deletions(-) diff --git a/Sources/LabelKit/Headless/AnnotationMerge.swift b/Sources/LabelKit/Headless/AnnotationMerge.swift index 9a4c20d..e7651a7 100644 --- a/Sources/LabelKit/Headless/AnnotationMerge.swift +++ b/Sources/LabelKit/Headless/AnnotationMerge.swift @@ -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 } } @@ -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) @@ -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. diff --git a/Sources/LabelKit/Headless/BoxImport.swift b/Sources/LabelKit/Headless/BoxImport.swift index 9169464..9cfe37b 100644 --- a/Sources/LabelKit/Headless/BoxImport.swift +++ b/Sources/LabelKit/Headless/BoxImport.swift @@ -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 } } @@ -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) diff --git a/Sources/LabelKit/Interop/DatasetExport.swift b/Sources/LabelKit/Interop/DatasetExport.swift index bf6c25d..417a0ee 100644 --- a/Sources/LabelKit/Interop/DatasetExport.swift +++ b/Sources/LabelKit/Interop/DatasetExport.swift @@ -45,6 +45,9 @@ public enum DatasetExport { public struct ExportError: LocalizedError, Equatable { public var message: String + /// True when the call was wrong (a bad `--out`), as opposed to a + /// dataset that can't be exported as it stands. + public var isUsage = false public var errorDescription: String? { message } } @@ -62,11 +65,30 @@ public enum DatasetExport { ) throws -> Report { let fm = FileManager.default guard !document.isImagesDirectory(out) else { - throw ExportError(message: "the output folder is the dataset itself; choose another directory") + throw ExportError(message: "the output folder is the dataset itself; choose another directory", + isUsage: true) } - if let existing = try? fm.contentsOfDirectory(atPath: out.path), !existing.isEmpty { - throw ExportError(message: "\(out.path) is not empty; export into a new or empty directory") + // Finder's .DS_Store and the like don't make a folder "not empty". + let existed = fm.fileExists(atPath: out.path) + if let existing = try? fm.contentsOfDirectory(atPath: out.path), + existing.contains(where: { !$0.hasPrefix(".") }) { + throw ExportError(message: "\(out.path) is not empty; export into a new or empty directory", + isUsage: true) } + do { + return try write(document, to: out, options: options, version: version, pixelSize: pixelSize) + } catch { + // A half-written export would be refused as "not empty" next time. + if !existed { try? fm.removeItem(at: out) } + throw error + } + } + + private static func write( + _ document: DatasetDocument, to out: URL, options: Options, version: String, + pixelSize: (String) -> CGSize? + ) throws -> Report { + let fm = FileManager.default let onDisk = Set(document.imagesOnDisk) var skipped: [Report.Skipped] = [] @@ -137,7 +159,9 @@ public enum DatasetExport { for (entry, path) in zip(entries, imagePaths) { let destination = out.appendingPathComponent(path) try fm.createDirectory(at: destination.deletingLastPathComponent(), withIntermediateDirectories: true) - try fm.copyItem(at: document.imageURL(for: entry.record.image), to: destination) + // The file itself, even when the dataset holds a symlink to it. + try fm.copyItem(at: document.imageURL(for: entry.record.image).resolvingSymlinksInPath(), + to: destination) } switch options.format { case .yolo: files.append("images/") @@ -168,7 +192,9 @@ public enum DatasetExport { static func yoloConfig(_ labels: [String]) -> String { var text = "# Exported by labelkit. Every image is under train; make a validation split before training.\n" - text += "path: .\ntrain: images\nval: images\nnames:\n" + // No `path:` — YOLO tooling then resolves train/val against this file's + // own folder, wherever the export is moved to. + text += "train: images\nval: images\nnames:\n" for (index, label) in labels.enumerated() { text += " \(index): \(yamlString(label))\n" } @@ -191,8 +217,7 @@ public enum DatasetExport { annotations.append([ "id": annotations.count + 1, "image_id": index + 1, "category_id": (classID[box.label] ?? 0) + 1, - "bbox": [hundredths(box.rect.minX), hundredths(box.rect.minY), - hundredths(box.width), hundredths(box.height)], + "bbox": pixelBox(box), "area": hundredths(box.width * box.height), "iscrowd": 0, ]) } @@ -213,8 +238,7 @@ public enum DatasetExport { let row: [String: Any] = [ "file_name": fileName, "objects": [ - "bbox": record.boxes.map { [hundredths($0.rect.minX), hundredths($0.rect.minY), - hundredths($0.width), hundredths($0.height)] }, + "bbox": record.boxes.map(pixelBox), "categories": record.boxes.map(\.label), ], ] @@ -252,6 +276,12 @@ public enum DatasetExport { // MARK: - Helpers + /// `[x, y, width, height]` in pixels from the top-left corner, as COCO and + /// Hugging Face both write a box. + private static func pixelBox(_ box: BoxRecord) -> [NSDecimalNumber] { + [hundredths(box.rect.minX), hundredths(box.rect.minY), hundredths(box.width), hundredths(box.height)] + } + /// A coordinate at labelkit's 2-decimal precision, as a decimal number so /// JSON prints `810.03` rather than the nearest binary double's /// `810.02999999999997`. diff --git a/Sources/LabelKit/Interop/DatasetImport.swift b/Sources/LabelKit/Interop/DatasetImport.swift index d2abf91..b07c58d 100644 --- a/Sources/LabelKit/Interop/DatasetImport.swift +++ b/Sources/LabelKit/Interop/DatasetImport.swift @@ -11,7 +11,9 @@ import Foundation /// the source can't be applied, nothing is copied or written. public enum DatasetImport { public struct Options: Sendable { - /// Record source images that have no boxes as negative examples. + /// Bring in source images that have no boxes, as negative examples. + /// Without it they are left out altogether: in someone else's dataset + /// "no boxes" can mean a deliberate negative or simply unlabelled. public var recordNegatives: Bool /// Apply what is valid instead of refusing the whole import. public var lenient: Bool @@ -48,10 +50,19 @@ public enum DatasetImport { public struct ImageCounts: Codable, Equatable, Sendable { /// Images in the source. public var found: Int - /// Copied into the dataset by this run. + /// Copied into the dataset by this run (with `dryRun`, that would be). public var copied: Int - /// Already in the dataset (same name and size); not copied again. + /// Already in the dataset; not copied again. public var alreadyPresent: Int + /// Left out because they have no boxes and negatives weren't asked for. + public var withoutBoxes: Int + + public init(found: Int, copied: Int, alreadyPresent: Int, withoutBoxes: Int = 0) { + self.found = found + self.copied = copied + self.alreadyPresent = alreadyPresent + self.withoutBoxes = withoutBoxes + } } public struct BoxCounts: Codable, Equatable, Sendable { @@ -72,14 +83,21 @@ public enum DatasetImport { options: Options = Options(), labelkitVersion version: String = labelkitVersion ) throws -> Report { + let fm = FileManager.default let directory = document.location.imagesDirectory - let plan = ImageImporter.plan( - sources: foreign.images.map(\.source), into: directory, - reservedNames: Set(document.records.map(\.image))) + let included = foreign.images.filter { options.recordNegatives || !$0.boxes.isEmpty } + // A symlinked image (common in download caches) is imported as the + // file it points to; copying the link would leave it dangling. + let sources = included.map { $0.source.resolvingSymlinksInPath() } + let names = included.map(\.source.lastPathComponent) + let plan = reusingEarlierCopies( + ImageImporter.plan(sources: sources, into: directory, + reservedNames: Set(document.records.map(\.image)), names: names), + named: names, in: directory) // Sizes come from the source files, so nothing has to be copied before // it is known that the whole import can go through. - let measured = foreign.images.map(\.source).concurrentMap(ImageMetadata.pixelSize(of:)) + let measured = sources.concurrentMap(ImageMetadata.pixelSize(of:)) var sizes: [String: CGSize] = [:] for (item, size) in zip(plan, measured) { if let size { sizes[item.finalName] = size } @@ -87,18 +105,30 @@ public enum DatasetImport { var merged = document merged.imagesOnDisk = (document.imagesOnDisk + plan.map(\.finalName)).uniqued() - let imports = zip(plan, foreign.images).map { ImportedImage(image: $0.finalName, boxes: $1.boxes) } + let imports = zip(plan, included).map { ImportedImage(image: $0.finalName, boxes: $1.boxes) } let result = AnnotationMerge.apply( imports, to: &merged, - options: .init(mode: .add, recordNegatives: options.recordNegatives), + options: .init(mode: .add, recordNegatives: options.recordNegatives, dedupeWithinInput: false), pixelSize: { sizes[$0] }) let blocked = !result.problems.isEmpty && !options.lenient let toCopy = plan.filter(\.needsCopy) let apply = !options.dryRun && !blocked if apply { - try ImageImporter.execute(plan, into: directory) - if result.changed { try merged.save() } + try fm.createDirectory(at: directory, withIntermediateDirectories: true) + var copied: [URL] = [] + do { + for item in toCopy { + let destination = directory.appendingPathComponent(item.finalName) + try fm.copyItem(at: item.source, to: destination) + copied.append(destination) + } + if result.changed { try merged.save() } + } catch { + // All or nothing: take back what this run put there. + copied.forEach { try? fm.removeItem(at: $0) } + throw error + } document = merged } @@ -108,15 +138,40 @@ public enum DatasetImport { dataset: directory.path, annotations: document.location.annotationsURL.path, format: foreign.format.rawValue, dryRun: options.dryRun, written: apply && (result.changed || !toCopy.isEmpty), - images: .init(found: foreign.images.count, copied: toCopy.count, - alreadyPresent: plan.count - toCopy.count), + images: .init(found: foreign.images.count, copied: blocked ? 0 : toCopy.count, + alreadyPresent: plan.count - toCopy.count, + withoutBoxes: foreign.images.count - included.count), boxes: .init(added: outcomes.reduce(0) { $0 + $1.added }, duplicates: outcomes.reduce(0) { $0 + $1.duplicates }, clamped: outcomes.reduce(0) { $0 + $1.clamped }), labels: Set(foreign.images.flatMap { $0.boxes.map(\.label) }).sorted(), - renamed: plan.filter { $0.finalName != $0.source.lastPathComponent } - .map { .init(from: $0.source.lastPathComponent, to: $0.finalName) }, + renamed: zip(plan, names).filter { $0.finalName != $1 }.map { .init(from: $1, to: $0.finalName) }, missing: foreign.missingImages, problems: result.problems) } + + /// An image that had to be renamed on an earlier import (`a.jpg` → `a-2.jpg`) + /// would be planned as a third copy the next time. Recognise the copy that + /// is already there, by content, so repeating an import stays a no-op. + private static func reusingEarlierCopies( + _ plan: [ImageImporter.Item], named names: [String], in directory: URL + ) -> [ImageImporter.Item] { + let fm = FileManager.default + let existing = ((try? fm.contentsOfDirectory(atPath: directory.path)) ?? []).sorted() + var taken = Set(plan.filter { !$0.needsCopy }.map(\.finalName)) + return zip(plan, names).map { item, name in + guard item.needsCopy, item.finalName != name else { return item } + let stem = (name as NSString).deletingPathExtension + "-" + let ext = (name as NSString).pathExtension + let earlier = existing.first { candidate in + candidate.hasPrefix(stem) && (candidate as NSString).pathExtension == ext + && !taken.contains(candidate) + && Int((candidate as NSString).deletingPathExtension.dropFirst(stem.count)) != nil + && fm.contentsEqual(atPath: item.source.path, andPath: directory.appendingPathComponent(candidate).path) + } + guard let earlier else { return item } + taken.insert(earlier) + return ImageImporter.Item(source: item.source, finalName: earlier, needsCopy: false) + } + } } diff --git a/Sources/LabelKit/Interop/ForeignDataset.swift b/Sources/LabelKit/Interop/ForeignDataset.swift index 1de4c34..d4913df 100644 --- a/Sources/LabelKit/Interop/ForeignDataset.swift +++ b/Sources/LabelKit/Interop/ForeignDataset.swift @@ -59,6 +59,8 @@ public enum ForeignDatasetReader { /// without their `data.yaml`). They take precedence over any found. public static func read(at url: URL, format: DatasetFormat? = nil, classNames: [String]? = nil) throws -> ForeignDataset { + // A folder reached through a symlink is listed as the folder it is. + let url = url.resolvingSymlinksInPath() var isDirectory: ObjCBool = false guard FileManager.default.fileExists(atPath: url.path, isDirectory: &isDirectory) else { throw ForeignDatasetError(message: "no such file or directory: \(url.path)", isUsage: true) @@ -104,13 +106,10 @@ public enum ForeignDatasetReader { throw ForeignDatasetError(message: "\(json.lastPathComponent): \(describe(error))") } for entry in parsed { - // COCO file names are relative to an images folder that varies - // by tool; the parser keeps the basename, which is looked up - // next to the JSON first and then anywhere in the dataset. - if let source = files.image(named: entry.image, near: json.deletingLastPathComponent()) { + if let source = files.cocoImage(path: entry.path ?? entry.image, annotationFile: json) { result.images.append(.init(source: source, boxes: entry.boxes)) } else { - result.missingImages.append(entry.image) + result.missingImages.append(entry.path ?? entry.image) } } } @@ -136,13 +135,15 @@ public enum ForeignDatasetReader { let fields = line.split(whereSeparator: \.isWhitespace) if fields.isEmpty { continue } let numbers = fields.compactMap { Double($0) } - guard numbers.count == fields.count, numbers.count >= 5, let rect = yoloRect(numbers.dropFirst()) else { + // `Int(exactly:)` rejects `nan`, `1e30` and `1.5`, any of which + // would otherwise crash or silently become another class. + guard numbers.count == fields.count, numbers.count >= 5, + let classID = Int(exactly: numbers[0]), classID >= 0, + let rect = yoloRect(numbers.dropFirst()) else { throw ForeignDatasetError( message: "\(label.lastPathComponent) line \(index + 1): expected 'class cx cy w h'") } - let classIndex = Int(numbers[0]) - let name = names.indices.contains(classIndex) ? names[classIndex] : "class_\(classIndex)" - boxes.append(ImportedBox(label: name, geometry: .normalized(rect))) + boxes.append(ImportedBox(label: className(classID, in: names), geometry: .normalized(rect))) } boxesByImage[image] = boxes } @@ -226,8 +227,7 @@ public enum ForeignDatasetReader { let label: String switch index < labels.count ? labels[index] : nil { case let name as String: label = name - case let number as NSNumber: - label = names.indices.contains(number.intValue) ? names[number.intValue] : "class_\(number.intValue)" + case let number as NSNumber: label = className(number.intValue, in: names) default: throw ForeignDatasetError(message: "\(place): box #\(index + 1) has no category") } return ImportedBox(label: label, geometry: .pixels( @@ -235,6 +235,11 @@ public enum ForeignDatasetReader { } } + /// The name for a numeric class id, or `class_` when none is known. + private static func className(_ id: Int, in names: [String]) -> String { + names.indices.contains(id) ? names[id] : "class_\(id)" + } + private static func describe(_ error: Error) -> String { (error as? LocalizedError)?.errorDescription ?? "\(error)" } @@ -272,8 +277,15 @@ public enum ClassNames { let inline = lines[start].trimmingCharacters(in: .whitespaces).dropFirst("names:".count) .trimmingCharacters(in: .whitespaces) if inline.hasPrefix("[") { - return inline.trimmingCharacters(in: CharacterSet(charactersIn: "[]")) - .split(separator: ",").map { unquote(String($0)) }.filter { !$0.isEmpty } + // A flow list may run over several lines; read up to its closing bracket. + var body = String(inline.dropFirst()) + var next = start + 1 + while closingBracket(in: body) == nil, next < lines.count { + body += " " + lines[next] + next += 1 + } + if let end = closingBracket(in: body) { body = String(body[..= indent else { break } - listed.append(unquote(String(trimmed.dropFirst(2)))) + listed.append(scalar(String(trimmed.dropFirst(2)))) } else if depth > indent, let colon = trimmed.firstIndex(of: ":"), - let index = Int(unquote(String(trimmed[.. String { - text.trimmingCharacters(in: .whitespaces).trimmingCharacters(in: CharacterSet(charactersIn: "'\"")) + /// One YAML scalar: quoted (`'it''s'`, `"a, b"`) or plain, where a plain + /// value ends at a ` #` comment. + static func scalar(_ raw: String) -> String { + let text = raw.trimmingCharacters(in: .whitespaces) + guard let quote = text.first, quote == "'" || quote == "\"" else { + let value = text.range(of: " #").map { String(text[..<$0.lowerBound]) } ?? text + return value.trimmingCharacters(in: .whitespaces) + } + var value = "" + var rest = text.dropFirst() + while let character = rest.first { + rest = rest.dropFirst() + if character == quote { + // In single quotes a doubled quote is a literal one. + if quote == "'", rest.first == "'" { value.append("'"); rest = rest.dropFirst(); continue } + break + } + if character == "\\", quote == "\"", let escaped = rest.first { + value.append(escaped) + rest = rest.dropFirst() + continue + } + value.append(character) + } + return value + } + + /// Where an unquoted `]` is, if there is one. + private static func closingBracket(in text: String) -> String.Index? { + var quote: Character? + for index in text.indices { + let character = text[index] + if let open = quote { if character == open { quote = nil } } + else if character == "'" || character == "\"" { quote = character } + else if character == "]" { return index } + } + return nil + } + + private static func splitOutsideQuotes(_ text: String, on separator: Character) -> [String] { + var parts = [""] + var quote: Character? + for character in text { + if let open = quote { if character == open { quote = nil } } + else if character == "'" || character == "\"" { quote = character } + else if character == separator { parts.append(""); continue } + parts[parts.count - 1].append(character) + } + return parts } } @@ -307,8 +366,8 @@ public enum ClassNames { /// where they keep things, so readers ask this for files by name or role /// instead of assuming paths. struct Tree { - let root: URL - private(set) var all: [URL] = [] + private let root: URL + private var all: [URL] = [] private(set) var images: [URL] = [] private var imagesByName: [String: [URL]] = [:] /// Folder path + file stem → image, for matching a label file to its image. @@ -317,15 +376,21 @@ struct Tree { /// Everything under `root`, a few levels deep (splits and their /// `images`/`labels` folders), hidden files skipped. init(root: URL) { - self.root = root - let enumerator = FileManager.default.enumerator( - at: root, includingPropertiesForKeys: [.isRegularFileKey], options: [.skipsHiddenFiles]) - var found: [URL] = [] - while let url = enumerator?.nextObject() as? URL { - if enumerator?.level ?? 0 > 6 { enumerator?.skipDescendants(); continue } - found.append(url.standardizedFileURL) + self.root = root.standardizedFileURL + if let enumerator = FileManager.default.enumerator( + at: root, includingPropertiesForKeys: nil, options: [.skipsHiddenFiles]) { + for case let url as URL in enumerator { + if enumerator.level > 6 { enumerator.skipDescendants(); continue } + all.append(url.standardizedFileURL) + } + } + all.sort { $0.path < $1.path } + images = all.filter(ImageImporter.isImageFile) + imagesByName = Dictionary(grouping: images, by: \.lastPathComponent) + for image in images { + let key = Self.key(image.deletingLastPathComponent().path, image.deletingPathExtension().lastPathComponent) + if imageByFolderAndStem[key] == nil { imageByFolderAndStem[key] = image } } - index(found.sorted { $0.path < $1.path }) } /// A single annotation file plus the images around it. @@ -334,16 +399,6 @@ struct Tree { all = all.filter { $0.pathExtension.lowercased() != "json" } + [file.standardizedFileURL] } - private mutating func index(_ urls: [URL]) { - all = urls - images = urls.filter(ImageImporter.isImageFile) - imagesByName = Dictionary(grouping: images, by: \.lastPathComponent) - for image in images { - let key = Self.key(image.deletingLastPathComponent().path, image.deletingPathExtension().lastPathComponent) - if imageByFolderAndStem[key] == nil { imageByFolderAndStem[key] = image } - } - } - private static func key(_ folder: String, _ stem: String) -> String { folder + "\u{0}" + stem } /// The image at `url`, if it is one of the image files found under `root`. @@ -361,19 +416,26 @@ struct Tree { /// JSON files that are COCO annotation files (checked by content, since /// their names follow no single convention). func cocoFiles() -> [URL] { - all.filter { $0.pathExtension.lowercased() == "json" }.filter { url in - guard let data = try? Data(contentsOf: url, options: .mappedIfSafe), + all.filter { url in + guard url.pathExtension.lowercased() == "json", + let data = try? Data(contentsOf: url, options: .mappedIfSafe), let object = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { return false } return object["images"] is [Any] && object["annotations"] is [Any] && object["categories"] is [Any] } } - /// An image by file name: next to `directory` if there, otherwise the only - /// one of that name anywhere in the dataset. - func image(named name: String, near directory: URL) -> URL? { - let candidates = imagesByName[name] ?? [] - let base = directory.standardizedFileURL.path - return candidates.first { $0.path.hasPrefix(base + "/") } ?? (candidates.count == 1 ? candidates[0] : nil) + /// The image a COCO `file_name` refers to. Tools write that path relative + /// to different places, so it is tried against the annotation file's + /// folder, that folder's parent, and the dataset root; a bare name that + /// matches nothing there is accepted only if exactly one image in the + /// dataset has it. Two images that merely share a name are never confused. + func cocoImage(path: String, annotationFile: URL) -> URL? { + let folder = annotationFile.deletingLastPathComponent() + for base in [folder, folder.deletingLastPathComponent(), root] { + if let found = listedImage(at: base.appendingPathComponent(path)) { return found } + } + let sameName = imagesByName[(path as NSString).lastPathComponent] ?? [] + return sameName.count == 1 ? sameName[0] : nil } // MARK: YOLO layout @@ -388,8 +450,9 @@ struct Tree { /// `…/labels/train/a.txt` ↔ `…/images/train/a.jpg`, or the image beside it. func yoloImage(forLabel label: URL) -> URL? { let stem = label.deletingPathExtension().lastPathComponent - var folders = [label.deletingLastPathComponent().path] - var components = label.deletingLastPathComponent().pathComponents + let folder = label.deletingLastPathComponent() + var folders = [folder.path] + var components = folder.pathComponents if let index = components.lastIndex(of: "labels") { components[index] = "images" folders.append(NSString.path(withComponents: components)) diff --git a/Sources/LabelKit/Store/ImageImporter.swift b/Sources/LabelKit/Store/ImageImporter.swift index f7335d6..89b7c31 100644 --- a/Sources/LabelKit/Store/ImageImporter.swift +++ b/Sources/LabelKit/Store/ImageImporter.swift @@ -46,8 +46,12 @@ public enum ImageImporter { /// `reservedNames` are filenames already claimed by the dataset's entries /// (including ghost entries whose file is missing) — merged with the /// directory's actual contents so nothing on disk is clobbered either. + /// + /// `names` gives each source the filename it should take, when that isn't + /// the last component of its URL — a file reached through a symlink keeps + /// the link's name, not the name of whatever it pointed to. public static func plan(sources: [URL], into directory: URL, - reservedNames: Set) -> [Item] { + reservedNames: Set, names: [String]? = nil) -> [Item] { let fm = FileManager.default var claimed = reservedNames if let onDisk = try? fm.contentsOfDirectory(atPath: directory.path) { @@ -55,8 +59,8 @@ public enum ImageImporter { } var items: [Item] = [] - for source in sources { - let name = source.lastPathComponent + for (index, source) in sources.enumerated() { + let name = names?[index] ?? source.lastPathComponent let destination = directory.appendingPathComponent(name) // Same name + same byte size already there → treat as the same // image: no copy, just surface it (parent-folder case, re-drag). diff --git a/Sources/LabelKitApp/ExportCommand.swift b/Sources/LabelKitApp/ExportCommand.swift index d13d61a..1e7b16c 100644 --- a/Sources/LabelKitApp/ExportCommand.swift +++ b/Sources/LabelKitApp/ExportCommand.swift @@ -60,7 +60,7 @@ struct ExportCommand: ParsableCommand { Headless.printJSON(try DatasetExport.run( document, to: outURL, options: .init(format: format, copyImages: images), pixelSize: { sizes[$0] })) - } catch let error as DatasetExport.ExportError { + } catch let error as DatasetExport.ExportError where error.isUsage { throw ValidationError(error.message) } catch { Headless.note("export failed: \(Headless.describe(error))") diff --git a/Sources/LabelKitApp/ImportCommand.swift b/Sources/LabelKitApp/ImportCommand.swift index a05ab41..f861f13 100644 --- a/Sources/LabelKitApp/ImportCommand.swift +++ b/Sources/LabelKitApp/ImportCommand.swift @@ -32,8 +32,8 @@ struct ImportCommand: ParsableCommand { new one, reported under "renamed". Boxes are added the way 'annotate' adds them, so importing the same source twice changes nothing. - Source images that have no boxes are skipped unless --negatives is - given. If anything in the source can't be applied, nothing is copied or + Source images that have no boxes are left out (not copied) unless + --negatives is given, which brings them in as negative examples. If anything in the source can't be applied, nothing is copied or written and the command exits 1; --lenient applies the rest. stdout carries a JSON report. Exit 0 on success, 1 when there were @@ -83,18 +83,21 @@ struct ImportCommand: ParsableCommand { } let datasetURL = URL(fileURLWithPath: (into as NSString).expandingTildeInPath) - if !dryRun { - do { - try FileManager.default.createDirectory(at: datasetURL, withIntermediateDirectories: true) - } catch { - throw ValidationError("Couldn't create \(into): \(Headless.describe(error))") - } + // A target inside the source would be read back as part of the source + // on the next run. + let sourceFolder = sourceURL.hasDirectoryPath || (try? sourceURL.resourceValues(forKeys: [.isDirectoryKey]).isDirectory) == true + ? sourceURL : sourceURL.deletingLastPathComponent() + let sourcePath = sourceFolder.resolvingSymlinksInPath().standardizedFileURL.path + let targetPath = datasetURL.resolvingSymlinksInPath().standardizedFileURL.path + if targetPath == sourcePath || targetPath.hasPrefix(sourcePath + "/") { + throw ValidationError("--into is inside the dataset being imported; choose a folder outside \(source).") } + + // The folder is only created once the import is known to go through. var document: DatasetDocument if FileManager.default.fileExists(atPath: datasetURL.path) { document = try Headless.openDocument(path: datasetURL.path, annotations: nil) } else { - // --dry-run into a folder that doesn't exist yet: an empty dataset. document = DatasetDocument( location: DatasetLocation( imagesDirectory: datasetURL, diff --git a/Tests/LabelKitTests/DatasetInteropTests.swift b/Tests/LabelKitTests/DatasetInteropTests.swift index 54ee4e1..24f0da7 100644 --- a/Tests/LabelKitTests/DatasetInteropTests.swift +++ b/Tests/LabelKitTests/DatasetInteropTests.swift @@ -121,7 +121,9 @@ final class DatasetInteropTests: XCTestCase { "1 0.750000 0.500000 0.200000 0.600000\n0 0.250000 0.500000 0.100000 0.200000\n") XCTAssertEqual(try read("labels/b.txt", in: out), "", "a negative is an empty label file") XCTAssertEqual(try read("classes.txt", in: out), "card\ncoin\n") - XCTAssertTrue(try read("data.yaml", in: out).contains("names:\n 0: 'card'\n 1: 'coin'\n")) + let yaml = try read("data.yaml", in: out) + XCTAssertTrue(yaml.contains("train: images\nval: images\nnames:\n 0: 'card'\n 1: 'coin'\n")) + XCTAssertFalse(yaml.contains("path:"), "a relative path would be resolved against YOLO's own datasets folder") XCTAssertTrue(FileManager.default.fileExists(atPath: out.appendingPathComponent("images/a.png").path)) XCTAssertEqual(report.files, ["data.yaml", "classes.txt", "labels/", "images/"]) } @@ -179,15 +181,23 @@ final class DatasetInteropTests: XCTestCase { try write("x", to: busy.appendingPathComponent("keep.txt")) XCTAssertThrowsError(try DatasetExport.run(source, to: busy, options: .init(format: .coco), pixelSize: { _ in nil })) XCTAssertEqual(try read("keep.txt", in: busy), "x") + // Only hidden clutter (a Finder .DS_Store) still counts as empty. + let finder = root.appendingPathComponent("finder") + try write("", to: finder.appendingPathComponent(".DS_Store")) + XCTAssertNoThrow(try DatasetExport.run(source, to: finder, options: .init(format: .coco), + pixelSize: { source.pixelSize(of: $0) })) } func testYOLOExportRefusesImagesThatWouldShareALabelFile() throws { try image("a.jpg", 10, 10, in: dataset) var source = try document() source.records.append(ImageAnnotationRecord(image: "a.jpg", boxes: [])) + let out = root.appendingPathComponent("clash") XCTAssertThrowsError(try DatasetExport.run( - source, to: root.appendingPathComponent("clash"), options: .init(format: .yolo), - pixelSize: { source.pixelSize(of: $0) })) + source, to: out, options: .init(format: .yolo), pixelSize: { source.pixelSize(of: $0) })) { + XCTAssertEqual(($0 as? DatasetExport.ExportError)?.isUsage, false, "a problem with the data, not the call") + } + XCTAssertFalse(FileManager.default.fileExists(atPath: out.path), "a failed export leaves no folder behind") } // MARK: - Reading other people's layouts @@ -241,6 +251,17 @@ final class DatasetInteropTests: XCTestCase { } } + func testYOLOClassIDMustBeAWholeNumber() throws { + for bad in ["nan", "1e30", "1.5", "-1", "inf"] { + let yolo = root.appendingPathComponent("yolo-bad-\(bad)") + try image("z.png", 100, 100, in: yolo) + try write("\(bad) 0.5 0.5 0.2 0.2\n", to: yolo.appendingPathComponent("z.txt")) + XCTAssertThrowsError(try ForeignDatasetReader.read(at: yolo, format: .yolo), "class '\(bad)'") { + XCTAssertTrue((($0 as? ForeignDatasetError)?.message ?? "").contains("expected 'class cx cy w h'")) + } + } + } + func testClassNameShapes() { XCTAssertEqual(ClassNames.parseYAML("nc: 2\nnames: ['cat', \"dog\"]\n"), ["cat", "dog"]) XCTAssertEqual(ClassNames.parseYAML("names:\n- cat\n- dog\nother: 1\n"), ["cat", "dog"]) @@ -260,6 +281,31 @@ final class DatasetInteropTests: XCTestCase { XCTAssertEqual(ClassNames.parseYAML("train: images\n"), []) } + /// The shapes real `data.yaml` files use: trailing comments, quotes that + /// protect commas and colons, a list broken over lines. + func testClassNamesWithCommentsQuotesAndWrappedLists() { + XCTAssertEqual(ClassNames.parseYAML("names: ['cat', 'dog'] # class names\n"), ["cat", "dog"]) + XCTAssertEqual(ClassNames.parseYAML("names:\n 0: cat # feline\n 1: dog\n"), ["cat", "dog"]) + XCTAssertEqual(ClassNames.parseYAML("names: [cat,\n dog,\n 'traffic light']\nnc: 3\n"), + ["cat", "dog", "traffic light"]) + XCTAssertEqual(ClassNames.parseYAML(#"names: ["a, b", 'c: d', "e]"]"#), ["a, b", "c: d", "e]"]) + XCTAssertEqual(ClassNames.parseYAML("names:\n - 'it''s'\n - \"say \\\"hi\\\"\"\n - C#\n"), + ["it's", "say \"hi\"", "C#"]) + } + + /// A label survives export and import whatever characters it contains. + func testAwkwardLabelsRoundTripThroughYOLO() throws { + var source = try document() + source.records[0].boxes = ["it's", "a, b", "x: y # z", "plain"].enumerated().map { index, label in + BoxRecord(label: label, x: Double(20 + index * 40), y: 50, width: 20, height: 20) + } + try source.save() + let (out, _) = try export(.yolo, to: "awkward") + let back = root.appendingPathComponent("awkward-back") + try importing(out, into: back) + XCTAssertEqual(Set(try document(back).records[0].boxes.map(\.label)), ["it's", "a, b", "x: y # z", "plain"]) + } + func testHuggingFaceIntegerCategoriesTakeNamesFromTheCard() throws { let hf = root.appendingPathComponent("hf-in") try image("x.png", 100, 100, in: hf.appendingPathComponent("train")) @@ -360,12 +406,144 @@ final class DatasetInteropTests: XCTestCase { XCTAssertNil(records.first { $0.image == "a.png" }) } - func testNegativesAreOnlyRecordedWhenAsked() throws { + /// In someone else's dataset "no boxes" may mean negative or unlabelled, so + /// such images are left out entirely unless negatives are asked for. + func testImagesWithoutBoxesAreLeftOutUnlessNegativesAreAsked() throws { let (out, _) = try export(.yolo, to: "yolo") let target = root.appendingPathComponent("no-negatives") - try importing(out, into: target, options: .init()) + let report = try importing(out, into: target, options: .init()) + XCTAssertEqual(report.images, .init(found: 2, copied: 1, alreadyPresent: 0, withoutBoxes: 1)) XCTAssertEqual(try document(target).records.map(\.image), ["a.png"]) - XCTAssertEqual(try document(target).imagesOnDisk, ["a.png", "b.png"], "the image is still copied") + XCTAssertEqual(try document(target).imagesOnDisk, ["a.png"], "not copied either") + } + + /// Download caches store images as symlinks to blobs. The file is imported, + /// under the dataset's name for it, not the link. + func testSymlinkedImagesAreImportedAndExportedAsFiles() throws { + let hf = root.appendingPathComponent("hf-links") + try image("abc123", 60, 40, in: root.appendingPathComponent("blobs")) + try FileManager.default.createDirectory(at: hf.appendingPathComponent("train"), withIntermediateDirectories: true) + try FileManager.default.moveItem(at: root.appendingPathComponent("blobs/abc123"), + to: root.appendingPathComponent("blobs/abc123.png")) + try FileManager.default.createSymbolicLink( + atPath: hf.appendingPathComponent("train/pic.png").path, withDestinationPath: "../../blobs/abc123.png") + try write(#"{"file_name": "pic.png", "objects": {"bbox": [[5, 5, 20, 20]], "categories": ["thing"]}}"# + "\n", + to: hf.appendingPathComponent("train/metadata.jsonl")) + + let target = root.appendingPathComponent("from-links") + let report = try importing(hf, into: target) + XCTAssertEqual(report.images.copied, 1) + XCTAssertTrue(report.renamed.isEmpty) + let imported = target.appendingPathComponent("pic.png") + XCTAssertEqual(try imported.resourceValues(forKeys: [.isSymbolicLinkKey]).isSymbolicLink, false) + XCTAssertNotNil(try document(target).pixelSize(of: "pic.png")) + + // And a dataset made of symlinks exports real files. + let linked = root.appendingPathComponent("linked-dataset") + try FileManager.default.createDirectory(at: linked, withIntermediateDirectories: true) + try FileManager.default.createSymbolicLink( + atPath: linked.appendingPathComponent("p.png").path, withDestinationPath: "../blobs/abc123.png") + try write(#"[{"image": "p.png", "annotations": []}]"#, to: linked.appendingPathComponent("annotations.json")) + let source = try document(linked) + let out = root.appendingPathComponent("linked-out") + _ = try DatasetExport.run(source, to: out, options: .init(format: .coco), pixelSize: { source.pixelSize(of: $0) }) + XCTAssertEqual(try out.appendingPathComponent("p.png").resourceValues(forKeys: [.isSymbolicLinkKey]).isSymbolicLink, false) + } + + /// Crowded objects of one class overlap. They are separate boxes in the + /// source and must stay separate; only what the dataset already had is a duplicate. + func testOverlappingBoxesInTheSourceAreAllKept() throws { + let yolo = root.appendingPathComponent("crowd") + try image("c.png", 100, 100, in: yolo) + try write("0 0.5 0.5 0.4 0.4\n0 0.52 0.5 0.4 0.4\n0 0.5 0.53 0.4 0.4\n", to: yolo.appendingPathComponent("c.txt")) + let target = root.appendingPathComponent("crowd-in") + XCTAssertEqual(try importing(yolo, into: target).boxes, .init(added: 3, duplicates: 0, clamped: 0)) + XCTAssertEqual(try importing(yolo, into: target).boxes, .init(added: 0, duplicates: 3, clamped: 0)) + } + + /// Two splits can each have an `a.png`. Both are imported, each with its own + /// boxes, and importing again recognises both. + func testSameFileNameInTwoSplitsStaysTwoImagesAndRepeatsCleanly() throws { + let coco = root.appendingPathComponent("splits") + try image("a.png", 100, 100, in: coco.appendingPathComponent("train")) + try image("a.png", 120, 90, in: coco.appendingPathComponent("val")) + try write(#""" + {"images":[{"id":1,"file_name":"train/a.png","width":100,"height":100}, + {"id":2,"file_name":"val/a.png","width":120,"height":90}], + "categories":[{"id":1,"name":"cat"},{"id":2,"name":"dog"}], + "annotations":[{"id":1,"image_id":1,"category_id":1,"bbox":[10,10,30,30]}, + {"id":2,"image_id":2,"category_id":2,"bbox":[50,40,60,40]}]} + """#, to: coco.appendingPathComponent("annotations.json")) + + let foreign = try ForeignDatasetReader.read(at: coco) + XCTAssertEqual(foreign.images.map { $0.source.deletingLastPathComponent().lastPathComponent }, ["train", "val"]) + + let target = root.appendingPathComponent("splits-in") + let first = try importing(coco, into: target) + XCTAssertEqual(first.renamed, [.init(from: "a.png", to: "a-2.png")]) + let records = try document(target).records + let labels = Dictionary(uniqueKeysWithValues: records.map { ($0.image, $0.boxes.map(\.label)) }) + XCTAssertEqual(labels, ["a.png": ["cat"], "a-2.png": ["dog"]], "each image keeps its own boxes") + XCTAssertEqual(try document(target).pixelSize(of: "a-2.png"), CGSize(width: 120, height: 90)) + + let before = try FileManager.default.contentsOfDirectory(atPath: target.path).sorted() + let again = try importing(coco, into: target) + XCTAssertEqual(again.images, .init(found: 2, copied: 0, alreadyPresent: 2)) + XCTAssertFalse(again.written) + XCTAssertEqual(try FileManager.default.contentsOfDirectory(atPath: target.path).sorted(), before) + } + + func testASymlinkedSourceFolderIsRead() throws { + let (out, _) = try export(.yolo, to: "yolo") + let link = root.appendingPathComponent("yolo-link") + try FileManager.default.createSymbolicLink(at: link, withDestinationURL: out) + XCTAssertEqual(try ForeignDatasetReader.read(at: link).images.count, 2) + } + + /// COCO sizes written before a photo's EXIF rotation can't be mapped onto + /// the image as displayed; that is reported, never guessed. + func testCoordinatesFromBeforeAnEXIFRotationAreAProblem() throws { + var destination = try document() + let box = ImportedBox(label: "card", geometry: .scaledPixels( + CGRect(x: 60, y: 10, width: 30, height: 20), reference: CGSize(width: 100, height: 200))) + // b.png is 100x200 on disk in the fixture; pretend it displays as 200x100. + let result = AnnotationMerge.apply([ImportedImage(image: "b.png", boxes: [box])], to: &destination, + pixelSize: { _ in CGSize(width: 200, height: 100) }) + XCTAssertEqual(result.problems.count, 1) + XCTAssertTrue(result.problems[0].message.contains("EXIF rotation")) + XCTAssertFalse(result.changed) + } + + func testAFailedCopyLeavesNothingBehind() throws { + let yolo = root.appendingPathComponent("unreadable") + try image("one.png", 50, 50, in: yolo) + try image("two.png", 50, 50, in: yolo) + try write("0 0.5 0.5 0.2 0.2\n", to: yolo.appendingPathComponent("one.txt")) + try write("0 0.5 0.5 0.2 0.2\n", to: yolo.appendingPathComponent("two.txt")) + let foreign = try ForeignDatasetReader.read(at: yolo) + // The file disappears between reading the dataset and copying it. + try FileManager.default.removeItem(at: yolo.appendingPathComponent("two.png")) + + let target = root.appendingPathComponent("rolled-back") + var destination = try document(target) + XCTAssertThrowsError(try DatasetImport.run(foreign, into: &destination, options: .init(lenient: true))) + XCTAssertEqual(try FileManager.default.contentsOfDirectory(atPath: target.path), []) + } + + func testARefusedImportDoesNotCreateItsTarget() throws { + let yolo = root.appendingPathComponent("refused") + try image("bad.png", 100, 100, in: yolo) + try write("0 5.0 5.0 0.2 0.2\n", to: yolo.appendingPathComponent("bad.txt")) + let target = root.appendingPathComponent("never-made") + var destination = DatasetDocument( + location: DatasetLocation(imagesDirectory: target, + annotationsURL: target.appendingPathComponent("annotations.json"), + annotationsExists: false), + records: [], imagesOnDisk: []) + let report = try DatasetImport.run(try ForeignDatasetReader.read(at: yolo), into: &destination) + XCTAssertEqual(report.problems.count, 1) + XCTAssertEqual(report.images.copied, 0, "nothing was copied, so nothing is counted as copied") + XCTAssertFalse(FileManager.default.fileExists(atPath: target.path)) } func testASourceWithAnUnusableBoxImportsNothingUnlessLenient() throws { @@ -381,6 +559,7 @@ final class DatasetInteropTests: XCTestCase { XCTAssertEqual(refused.problems.count, 1) XCTAssertFalse(refused.written) XCTAssertEqual(try FileManager.default.contentsOfDirectory(atPath: strict.path), [], "nothing copied, nothing written") + XCTAssertEqual(refused.images.copied, 0) let lenient = root.appendingPathComponent("lenient") let applied = try importing(yolo, into: lenient, options: .init(lenient: true))