From bfa309c39f4c68fa0ca4be96ecef7aec9416368c Mon Sep 17 00:00:00 2001 From: shellbear Date: Sat, 28 Nov 2026 17:18:40 +0100 Subject: [PATCH 1/3] perf: load, list and save large datasets several times faster Profiling the headless commands on a 10,000-image / 26,000-box dataset showed the time going to shared format code, most of it Foundation bridging: - CreateMLFormat.load reads JSONSerialization's NSArray/NSDictionary directly instead of casting each entry to [String: Any], which copied the dictionary and bridged every key - filenames and labels are converted to native Swift strings once, on the way in, so later Set/Dictionary work no longer hashes through NSString - CreateMLWriter caches its indentation strings, formats coordinates as integer hundredths instead of String(format:), and skips escaping for strings that need none - JSONIndent sniffs the first 64 KB rather than splitting the whole file - ImageDirectoryScanner lists with contentsOfDirectory and sorts by selector, keeping comparisons inside Foundation; names that compare equal are settled by plain comparison so the order is deterministic Saved bytes are unchanged: a test compares the new coordinate formatting with the previous implementation over 420,000 values, and the existing golden and round-trip tests still pass. Adds concurrentMap and uniqued helpers used by the commands that follow. --- Sources/LabelKit/Format/CreateMLFormat.swift | 59 ++++++++++++------- Sources/LabelKit/Format/CreateMLWriter.swift | 30 +++++++++- Sources/LabelKit/Format/JSONIndent.swift | 7 ++- .../Store/ImageDirectoryScanner.swift | 38 +++++++++--- Sources/LabelKit/Support/Collections.swift | 59 +++++++++++++++++++ Tests/LabelKitTests/CreateMLWriterTests.swift | 40 +++++++++++++ .../ImageDirectoryScannerTests.swift | 32 ++++++++++ 7 files changed, 233 insertions(+), 32 deletions(-) create mode 100644 Sources/LabelKit/Support/Collections.swift diff --git a/Sources/LabelKit/Format/CreateMLFormat.swift b/Sources/LabelKit/Format/CreateMLFormat.swift index 155b34c..647c428 100644 --- a/Sources/LabelKit/Format/CreateMLFormat.swift +++ b/Sources/LabelKit/Format/CreateMLFormat.swift @@ -23,39 +23,56 @@ public enum CreateMLFormat: AnnotationFormat { private static let annotationKeys: Set = ["label", "coordinates"] public static func load(_ data: Data) throws -> [ImageAnnotationRecord] { - guard let root = try JSONSerialization.jsonObject(with: data) as? [Any] else { + // JSONSerialization returns NSArray/NSDictionary. They are read as + // such: casting each one to a Swift dictionary copies it and bridges + // every key, which on a large file costs several times the parse itself. + guard let root = try JSONSerialization.jsonObject(with: data) as? NSArray else { throw CreateMLFormatError.rootIsNotArray } - return try root.enumerated().map { index, rawEntry in - let entry = rawEntry as? [String: Any] ?? [:] - guard let image = entry["image"] as? String else { + var records: [ImageAnnotationRecord] = [] + records.reserveCapacity(root.count) + for (index, rawEntry) in root.enumerated() { + let entry = rawEntry as? NSDictionary + guard let image = entry?["image"] as? String else { throw CreateMLFormatError.entryMissingImage(index: index) } - let rawAnnotations = entry["annotations"] as? [Any] ?? [] - let boxes = rawAnnotations.compactMap { rawAnnotation -> BoxRecord? in - guard let annotation = rawAnnotation as? [String: Any] else { return nil } - let coordinates = annotation["coordinates"] as? [String: Any] ?? [:] - func value(_ key: String) -> Double { (coordinates[key] as? NSNumber)?.doubleValue ?? 0 } - return BoxRecord( - label: annotation["label"] as? String ?? "unlabeled", - x: value("x"), y: value("y"), - width: value("width"), height: value("height"), - extras: extras(of: annotation, excluding: annotationKeys) - ) + var boxes: [BoxRecord] = [] + if let rawAnnotations = entry?["annotations"] as? NSArray { + boxes.reserveCapacity(rawAnnotations.count) + for case let annotation as NSDictionary in rawAnnotations { + let coordinates = annotation["coordinates"] as? NSDictionary + func value(_ key: String) -> Double { (coordinates?[key] as? NSNumber)?.doubleValue ?? 0 } + boxes.append(BoxRecord( + label: (annotation["label"] as? String)?.native ?? "unlabeled", + x: value("x"), y: value("y"), + width: value("width"), height: value("height"), + extras: extras(of: annotation, excluding: annotationKeys) + )) + } } - return ImageAnnotationRecord( - image: image, + records.append(ImageAnnotationRecord( + image: image.native, boxes: boxes, - extras: extras(of: entry, excluding: entryKeys) - ) + extras: entry.map { extras(of: $0, excluding: entryKeys) } ?? [:] + )) } + return records } public static func serialize(_ records: [ImageAnnotationRecord]) -> Data { CreateMLWriter.serialize(records) } - private static func extras(of dict: [String: Any], excluding known: Set) -> [String: JSONValue] { - dict.filter { !known.contains($0.key) }.mapValues(JSONValue.init) + private static func extras(of dict: NSDictionary, excluding known: Set) -> [String: JSONValue] { + // Almost every entry carries only the modelled keys; count those + // instead of building a filtered copy to find that out. + let modelled = known.reduce(0) { $0 + (dict[$1] == nil ? 0 : 1) } + guard dict.count > modelled else { return [:] } + var result: [String: JSONValue] = [:] + for (key, value) in dict { + guard let key = key as? String, !known.contains(key) else { continue } + result[key.native] = JSONValue(value) + } + return result } } diff --git a/Sources/LabelKit/Format/CreateMLWriter.swift b/Sources/LabelKit/Format/CreateMLWriter.swift index 69d52bf..1c6c934 100644 --- a/Sources/LabelKit/Format/CreateMLWriter.swift +++ b/Sources/LabelKit/Format/CreateMLWriter.swift @@ -18,7 +18,12 @@ public enum CreateMLWriter { ) -> Data { var out = String() out.reserveCapacity(records.count * 256) - let pad = { (depth: Int) in String(repeating: indentUnit, count: depth) } + // The writer asks for the same six indentation strings tens of + // thousands of times; build them once. + let cached = (0..<8).map { String(repeating: indentUnit, count: $0) } + let pad = { (depth: Int) in + depth < cached.count ? cached[depth] : String(repeating: indentUnit, count: depth) + } out.append("[") for (index, record) in records.enumerated() { @@ -32,6 +37,25 @@ public enum CreateMLWriter { /// Canonical number formatting: round half-away-from-zero to 2 dp, then /// drop trailing zeros and a dangling decimal point. public static func coordString(_ value: Double) -> String { + // Work in whole hundredths: integer formatting is several times faster + // than `String(format:)`, and this runs four times per box. + let scaled = (value * 100).rounded() + guard scaled.isFinite, abs(scaled) < 1e15 else { return formattedCoordString(value) } + let hundredths = Int64(scaled) + let magnitude = hundredths.magnitude + let fraction = magnitude % 100 + var text = hundredths < 0 ? "-" : "" + text += String(magnitude / 100) + if fraction != 0 { + text += fraction < 10 ? ".0" : "." + text += String(fraction % 10 == 0 ? fraction / 10 : fraction) + } + return text + } + + /// The reference formatting, used directly only for values too large (or + /// not finite) for the integer path. `coordString` must agree with it. + static func formattedCoordString(_ value: Double) -> String { let rounded = (value * 100).rounded() / 100 if rounded == rounded.rounded(), abs(rounded) < 1e15 { return String(Int(rounded)) @@ -100,6 +124,10 @@ public enum CreateMLWriter { } private static func escape(_ string: String) -> String { + // Nearly every label and filename needs no escaping at all. + if !string.utf8.contains(where: { $0 < 0x20 || $0 == UInt8(ascii: "\"") || $0 == UInt8(ascii: "\\") }) { + return "\"\(string)\"" + } var out = "\"" for scalar in string.unicodeScalars { switch scalar { diff --git a/Sources/LabelKit/Format/JSONIndent.swift b/Sources/LabelKit/Format/JSONIndent.swift index e3c9fee..1ef1908 100644 --- a/Sources/LabelKit/Format/JSONIndent.swift +++ b/Sources/LabelKit/Format/JSONIndent.swift @@ -4,11 +4,16 @@ import Foundation /// file's own convention (Python's `indent=1`, tabs, 4-space, …) instead of /// forcing a whole-file reformat on first save. public enum JSONIndent { + /// How much of the file is examined. Far more than any real first line. + static let sniffLength = 64 * 1024 + /// The leading whitespace of the first indented line — which, for a /// Create ML file (entries at depth 1), IS one indent unit. Returns nil /// for compact/single-line JSON. public static func detectUnit(in data: Data) -> String? { - guard let text = String(data: data, encoding: .utf8) else { return nil } + // A pretty-printed file indents within its first few lines, so sniff + // the head instead of decoding and splitting megabytes of JSON. + let text = String(decoding: data.prefix(sniffLength), as: UTF8.self) for line in text.split(separator: "\n", omittingEmptySubsequences: true) { let whitespace = line.prefix { $0 == " " || $0 == "\t" } if !whitespace.isEmpty, whitespace.count < line.count { diff --git a/Sources/LabelKit/Store/ImageDirectoryScanner.swift b/Sources/LabelKit/Store/ImageDirectoryScanner.swift index bff87ad..7527675 100644 --- a/Sources/LabelKit/Store/ImageDirectoryScanner.swift +++ b/Sources/LabelKit/Store/ImageDirectoryScanner.swift @@ -1,25 +1,45 @@ import Foundation -/// Lists image filenames in a directory — lazily, without stat-ing or -/// decoding anything, so a 10k-image folder scans in tens of milliseconds. +/// Lists image filenames in a directory — without stat-ing or decoding +/// anything, so a 10k-image folder scans in tens of milliseconds. public enum ImageDirectoryScanner { public static let imageExtensions: Set = ["jpg", "jpeg", "png", "heic", "heif", "tiff", "tif", "bmp", "gif", "webp"] + /// Image files directly inside `directory` (hidden files and + /// subdirectories' contents excluded), in Finder's name order. public static func scan(directory: URL, glob: String? = nil) -> [String] { - guard let enumerator = FileManager.default.enumerator( - at: directory, - includingPropertiesForKeys: [], - options: [.skipsHiddenFiles, .skipsSubdirectoryDescendants, .skipsPackageDescendants] + guard let urls = try? FileManager.default.contentsOfDirectory( + at: directory, includingPropertiesForKeys: nil, options: [.skipsHiddenFiles] ) else { return [] } var names: [String] = [] - for case let url as URL in enumerator { + names.reserveCapacity(urls.count) + for url in urls { let name = url.lastPathComponent - guard imageExtensions.contains(url.pathExtension.lowercased()) else { continue } + guard imageExtensions.contains((name as NSString).pathExtension.lowercased()) else { continue } if let glob, fnmatch(glob, name, 0) != 0 { continue } names.append(name) } - return names.sorted { $0.localizedStandardCompare($1) == .orderedAscending } + + // The sort dominates a large scan. Sorting by selector keeps every + // comparison inside Foundation, on the NSStrings the listing produced — + // measured at half the cost of a Swift closure, which bridges both + // sides each time. + var sorted = (names as NSArray) + .sortedArray(using: #selector(NSString.localizedStandardCompare(_:))) as! [String] + + // Finder's ordering can call two different names equal. Settle those by + // plain comparison so the result never depends on the sort's internals. + var start = 0 + while start < sorted.count { + var end = start + 1 + while end < sorted.count, sorted[start].localizedStandardCompare(sorted[end]) == .orderedSame { + end += 1 + } + if end - start > 1 { sorted[start..(maxConcurrency: Int? = nil, _ transform: (Element) -> Result) -> [Result] { + let workers = Swift.min(count, Swift.max(1, maxConcurrency ?? count)) + guard workers > 1 else { return map(transform) } + return [Result](unsafeUninitializedCapacity: count) { buffer, initialized in + // Worker w takes elements w, w + workers, w + 2·workers, … so every + // slot is initialized exactly once and there is no shared mutable + // state to guard. + let slots = buffer.baseAddress! + DispatchQueue.concurrentPerform(iterations: workers) { worker in + for index in stride(from: worker, to: count, by: workers) { + // Drain per element: Foundation and ImageIO autorelease + // their temporaries, and a worker thread would otherwise + // hold every image it has processed until it finishes. + autoreleasepool { + (slots + index).initialize(to: transform(self[index])) + } + } + } + initialized = count + } + } +} + +public extension Sequence where Element: Hashable { + /// The elements with later repeats dropped, order kept. + func uniqued() -> [Element] { + var seen = Set() + return filter { seen.insert($0).inserted } + } +} + +extension String { + /// The same string in Swift's own storage. Strings that arrive from + /// Foundation (`JSONSerialization`, `FileManager`) are bridged `NSString`s, + /// and every hash or comparison on one crosses into Objective-C — measured + /// at several times the cost of a native string. Filenames and labels are + /// used as dictionary keys throughout, so they are converted once, on the + /// way in. + var native: String { + var copy = self + copy.makeContiguousUTF8() + return copy + } +} diff --git a/Tests/LabelKitTests/CreateMLWriterTests.swift b/Tests/LabelKitTests/CreateMLWriterTests.swift index a6dfeb4..8cfac7a 100644 --- a/Tests/LabelKitTests/CreateMLWriterTests.swift +++ b/Tests/LabelKitTests/CreateMLWriterTests.swift @@ -12,6 +12,46 @@ final class CreateMLWriterTests: XCTestCase { XCTAssertEqual(CreateMLWriter.coordString(0), "0") } + /// `coordString` takes an integer fast path; saved bytes must not depend on + /// which path ran. Compare it with the reference formatting over a wide, + /// reproducible spread of values, including the awkward ones. + func testFastCoordStringAgreesWithTheReferenceFormatting() { + var state: UInt64 = 0x9E37_79B9_7F4A_7C15 + func next() -> Double { // xorshift64*: deterministic, no seedable RNG in the stdlib + state ^= state >> 12; state ^= state << 25; state ^= state >> 27 + return Double(state &* 0x2545_F491_4F6C_DD1D >> 11) / Double(1 << 53) + } + var values: [Double] = [ + 0, -0.0, 0.004, 0.005, -0.005, 0.01, 0.05, 0.1, 0.5, 0.995, 1, -1, 9.999, 99.995, 100, + 427.5, 450.2811789512634, -12.345, 1e6, 123456.785, 1e12, 9.99e12, 1e13, 1e14, 1e15, 1e18, + -1e15, .infinity, -.infinity, .nan, .greatestFiniteMagnitude, .leastNonzeroMagnitude, + ] + for magnitude in [1.0, 10, 1_000, 10_000, 1e7, 1e11, 1e13] { + for _ in 0..<20_000 { + let value = (next() * 2 - 1) * magnitude + values.append(value) + values.append((value * 100).rounded() / 100) // already 2 dp + values.append((value * 10).rounded() / 10 + 0.005) // right on a rounding edge + } + } + for value in values { + XCTAssertEqual(CreateMLWriter.coordString(value), CreateMLWriter.formattedCoordString(value), + "value \(value)") + } + } + + func testEscapingIsOnlyAppliedWhereNeeded() { + let records = [ImageAnnotationRecord(image: "naïve photo (1) é.jpg", boxes: [ + BoxRecord(label: "tab\there", x: 1, y: 1, width: 1, height: 1), + BoxRecord(label: "bell\u{07}", x: 1, y: 1, width: 1, height: 1), + ])] + let out = String(decoding: CreateMLWriter.serialize(records), as: UTF8.self) + XCTAssertTrue(out.contains(#""image": "naïve photo (1) é.jpg""#)) + XCTAssertTrue(out.contains(#""label": "tab\there""#)) + XCTAssertTrue(out.contains(#""label": "bell\u0007""#)) + XCTAssertEqual(try CreateMLFormat.load(Data(out.utf8)), records) + } + func testCanonicalLayoutGolden() { let records = [ ImageAnnotationRecord( diff --git a/Tests/LabelKitTests/ImageDirectoryScannerTests.swift b/Tests/LabelKitTests/ImageDirectoryScannerTests.swift index b27bf3d..848136d 100644 --- a/Tests/LabelKitTests/ImageDirectoryScannerTests.swift +++ b/Tests/LabelKitTests/ImageDirectoryScannerTests.swift @@ -26,6 +26,38 @@ final class ImageDirectoryScannerTests: XCTestCase { ) } + /// The listing is sorted by Foundation for speed; it must still be the + /// order a plain `localizedStandardCompare` sort gives (Finder's order), + /// with names that compare equal settled the same way every time. + func testOrderMatchesFinderOrderForAwkwardNames() throws { + let names = ["img1.jpg", "img01.jpg", "img001.jpg", "IMG2.jpg", "img10.jpg", "img9.jpg", + "Émile.png", "emile.png", "zebra.png", "Zebra 2.png", "a b.jpg", "a-b.jpg", "a_b.jpg", + "10.jpg", "9.jpg", "1.jpeg", "日本.jpg", "ß.jpg", "ss.jpg"] + let directory = tempDir.appendingPathComponent("order") + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + var created: [String] = [] + for name in names where FileManager.default.createFile( + atPath: directory.appendingPathComponent(name).path, contents: nil) { + created.append(name) + } + // A case-insensitive volume keeps only one of two names differing in + // case; compare against whatever actually exists. + let onDisk = try FileManager.default.contentsOfDirectory(atPath: directory.path) + + let scanned = ImageDirectoryScanner.scan(directory: directory) + XCTAssertEqual(Set(scanned), Set(onDisk)) + for (earlier, later) in zip(scanned, scanned.dropFirst()) { + let order = earlier.localizedStandardCompare(later) + XCTAssertNotEqual(order, .orderedDescending, "\(earlier) should not come after \(later)") + if order == .orderedSame { XCTAssertLessThan(earlier, later, "ties settle by plain comparison") } + } + XCTAssertEqual(ImageDirectoryScanner.scan(directory: directory), scanned, "stable across calls") + } + + func testUnreadableDirectoryIsEmpty() { + XCTAssertEqual(ImageDirectoryScanner.scan(directory: tempDir.appendingPathComponent("nope")), []) + } + func testGlobFilter() { XCTAssertEqual( ImageDirectoryScanner.scan(directory: tempDir, glob: "*.png"), From e43bc402286b3dca368ed6ef910d6bc9e8668713 Mon Sep 17 00:00:00 2001 From: shellbear Date: Sat, 28 Nov 2026 17:18:50 +0100 Subject: [PATCH 2/3] feat: scripted subcommands so AI agents and scripts can label datasets Until now nothing could write boxes into annotations.json from the terminal, so an agent had to hand-edit the file and lose the format guarantees. This adds the headless verbs for a full label-check-fix loop: - annotate: add or replace boxes from --box flags, JSON, NDJSON or stdin. Reads what models and tools emit (Gemini box_2d, corner lists, 0-1 and 0-1000 units, centre anchors, COCO files, detect output); --units, --origin, --anchor, --order and --image-size name a convention instead of converting. Adding is idempotent down to the bytes; unusable input writes nothing. - stats: JSON summary (labelled, negative, unlabelled, missing, per-label counts, the image with the most boxes) - validate: errors and warnings with stable codes, exit 1 on errors; also finds the same photo saved under two names - render: draw saved boxes on downscaled JPEGs, numbered to match validate; --grid adds a ruler in original-image pixels, --unlabeled renders the to-do - skill: print or install the Agent Skill that teaches a client the loop (~/.agents/skills and ~/.claude/skills, or --project / --dir / --snippet). The text is compiled in and mirrored at skills/labelkit/SKILL.md; a test keeps the two identical. - open --select : show a given image; with the editor already open it reloads the dataset from disk and jumps there The logic is in Sources/LabelKit/Headless with tests; the command files only parse and print. detect and train now share the same output helpers. All commands write the result to stdout, notes to stderr, and exit 0 / 1 / 64. scripts/smoke-scripted.sh exercises them end to end and runs in CI. --- .github/workflows/ci.yml | 6 + Sources/LabelKit/Detection/BoxRenderer.swift | 122 ++++- .../LabelKit/Format/AnnotationFormat.swift | 9 + Sources/LabelKit/Headless/AgentGuide.swift | 259 ++++++++++ .../LabelKit/Headless/AnnotationMerge.swift | 256 +++++++++ Sources/LabelKit/Headless/BoxImport.swift | 487 ++++++++++++++++++ .../LabelKit/Headless/DatasetDocument.swift | 104 ++++ .../LabelKit/Headless/DatasetSummary.swift | 140 +++++ .../LabelKit/Headless/DatasetValidator.swift | 199 +++++++ .../LabelKit/Headless/DuplicateImages.swift | 60 +++ Sources/LabelKit/Model/BoundingBox.swift | 11 +- Sources/LabelKitApp/AnnotateCommand.swift | 245 +++++++++ Sources/LabelKitApp/AppState.swift | 17 +- Sources/LabelKitApp/DetectCommand.swift | 44 +- Sources/LabelKitApp/HeadlessSupport.swift | 68 +++ Sources/LabelKitApp/LabelKitApp.swift | 2 +- Sources/LabelKitApp/LabelKitCommand.swift | 14 +- Sources/LabelKitApp/LaunchContext.swift | 4 +- Sources/LabelKitApp/RenderCommand.swift | 180 +++++++ Sources/LabelKitApp/SingleInstance.swift | 9 +- Sources/LabelKitApp/SkillCommand.swift | 82 +++ Sources/LabelKitApp/StatsCommand.swift | 76 +++ Sources/LabelKitApp/TrainCommand.swift | 23 +- Sources/LabelKitApp/ValidateCommand.swift | 80 +++ Tests/LabelKitTests/AgentGuideTests.swift | 73 +++ .../LabelKitTests/BoxImportParserTests.swift | 309 +++++++++++ Tests/LabelKitTests/BoxRendererTests.swift | 64 +++ .../LabelKitTests/HeadlessDatasetTests.swift | 433 ++++++++++++++++ scripts/smoke-scripted.sh | 76 +++ skills/labelkit/SKILL.md | 201 ++++++++ 30 files changed, 3568 insertions(+), 85 deletions(-) create mode 100644 Sources/LabelKit/Headless/AgentGuide.swift create mode 100644 Sources/LabelKit/Headless/AnnotationMerge.swift create mode 100644 Sources/LabelKit/Headless/BoxImport.swift create mode 100644 Sources/LabelKit/Headless/DatasetDocument.swift create mode 100644 Sources/LabelKit/Headless/DatasetSummary.swift create mode 100644 Sources/LabelKit/Headless/DatasetValidator.swift create mode 100644 Sources/LabelKit/Headless/DuplicateImages.swift create mode 100644 Sources/LabelKitApp/AnnotateCommand.swift create mode 100644 Sources/LabelKitApp/HeadlessSupport.swift create mode 100644 Sources/LabelKitApp/RenderCommand.swift create mode 100644 Sources/LabelKitApp/SkillCommand.swift create mode 100644 Sources/LabelKitApp/StatsCommand.swift create mode 100644 Sources/LabelKitApp/ValidateCommand.swift create mode 100644 Tests/LabelKitTests/AgentGuideTests.swift create mode 100644 Tests/LabelKitTests/BoxImportParserTests.swift create mode 100644 Tests/LabelKitTests/HeadlessDatasetTests.swift create mode 100755 scripts/smoke-scripted.sh create mode 100644 skills/labelkit/SKILL.md diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7a98de1..58bb378 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -46,3 +46,9 @@ jobs: else test $? -eq 64 fi + # Smoke: the scripted subcommands (stats, validate, annotate, render, + # skill) run end to end on a throwaway dataset, stay headless, keep their + # exit codes (0 ok / 1 problem / 64 usage), and a repeated `annotate` + # leaves the file byte-identical. + - name: Smoke-test the scripted subcommands + run: ./scripts/smoke-scripted.sh diff --git a/Sources/LabelKit/Detection/BoxRenderer.swift b/Sources/LabelKit/Detection/BoxRenderer.swift index 0d18ac5..d573db8 100644 --- a/Sources/LabelKit/Detection/BoxRenderer.swift +++ b/Sources/LabelKit/Detection/BoxRenderer.swift @@ -10,11 +10,27 @@ public struct RenderableBox: Sendable { public var rect: CGRect public var label: String public var confidence: Float? + /// Text for the chip, when it should differ from the label (e.g. "#2 card"). + /// The colour still follows `label`, so a given label keeps its colour. + public var caption: String? - public init(rect: CGRect, label: String, confidence: Float? = nil) { + public init(rect: CGRect, label: String, confidence: Float? = nil, caption: String? = nil) { self.rect = rect self.label = label self.confidence = confidence + self.caption = caption + } +} + +/// A coordinate grid drawn over the image, in **source-image pixels**: a line +/// every `spacing` pixels, each labelled with its coordinate. It turns a render +/// into a ruler — a vision model can read a box's extents straight off the +/// picture and write them back as pixel coordinates. +public struct RenderGrid: Sendable, Equatable { + public var spacing: CGFloat + + public init(spacing: CGFloat) { + self.spacing = spacing } } @@ -30,6 +46,39 @@ public enum BoxRenderer { /// to the decoded image's own dimensions. Returns PNG bytes, or nil if a /// context/encoder couldn't be created. public static func renderPNG(image: CGImage, sourceSize: CGSize, boxes: [RenderableBox]) -> Data? { + render(image: image, sourceSize: sourceSize, boxes: boxes, as: .png) + } + + /// Output encoding. JPEG is several times smaller and faster to write than + /// PNG for photos, which matters when an agent renders a batch only to + /// look at it; PNG stays lossless. + public enum Encoding: Sendable, Equatable { + case png + case jpeg(quality: Double) + + public var fileExtension: String { + switch self { + case .png: return "png" + case .jpeg: return "jpg" + } + } + } + + /// File names for a batch of rendered images: `photo.jpg` → `photo.`. + /// Images that differ only in their extension (`a.jpg`, `a.png`) would + /// land on the same file, so those keep their full name: `a.png.`. + /// Compared without regard to case, as the default macOS file system does. + public static func outputNames(for images: [String], fileExtension: String) -> [String] { + let stems = images.map { ($0 as NSString).deletingPathExtension } + let shared = Set(Dictionary(grouping: stems, by: { $0.lowercased() }).filter { $1.count > 1 }.keys) + return zip(images, stems).map { image, stem in + (shared.contains(stem.lowercased()) ? image : stem) + "." + fileExtension + } + } + + /// As `renderPNG`, with a choice of encoding. + public static func render(image: CGImage, sourceSize: CGSize, boxes: [RenderableBox], + grid: RenderGrid? = nil, as encoding: Encoding) -> Data? { let width = image.width, height = image.height guard width > 0, height > 0, let ctx = CGContext( @@ -47,6 +96,11 @@ public enum BoxRenderer { let lineWidth = max(2, minEdge / 300) let font = CTFontCreateWithName("Helvetica-Bold" as CFString, max(11, minEdge / 45), nil) + if let grid, grid.spacing > 0, sourceSize.width > 0, sourceSize.height > 0 { + drawGrid(grid, sourceSize: sourceSize, scaleX: scaleX, scaleY: scaleY, + drawSize: CGSize(width: width, height: height), in: ctx) + } + for box in boxes { let color = color(for: box.label) // Scale into draw space and flip Y (CGContext origin is bottom-left). @@ -67,14 +121,59 @@ public enum BoxRenderer { } guard let output = ctx.makeImage() else { return nil } - return encodePNG(output) + return encode(output, as: encoding) } // MARK: - Text private static func caption(_ box: RenderableBox) -> String { - guard let confidence = box.confidence else { return box.label } - return "\(box.label) \(Int((confidence * 100).rounded()))%" + let text = box.caption ?? box.label + guard let confidence = box.confidence else { return text } + return "\(text) \(Int((confidence * 100).rounded()))%" + } + + // MARK: - Grid + + /// Lines at multiples of `grid.spacing` source pixels, labelled along the + /// top and left edges. Each line is a light stroke over a dark one so it + /// stays readable on any photo. + private static func drawGrid(_ grid: RenderGrid, sourceSize: CGSize, scaleX: CGFloat, scaleY: CGFloat, + drawSize: CGSize, in ctx: CGContext) { + let minEdge = min(drawSize.width, drawSize.height) + let thin = max(1, minEdge / 900) + let font = CTFontCreateWithName("Helvetica-Bold" as CFString, max(9, minEdge / 70), nil) + let chipFill = CGColor(red: 0, green: 0, blue: 0, alpha: 0.62) + + var path = [(from: CGPoint, to: CGPoint)]() + var labels = [(text: String, topLeft: CGPoint)]() + var value = grid.spacing + while value < sourceSize.width { + let x = value * scaleX + path.append((CGPoint(x: x, y: 0), CGPoint(x: x, y: drawSize.height))) + labels.append((String(Int(value.rounded())), CGPoint(x: x + thin, y: drawSize.height))) + value += grid.spacing + } + value = grid.spacing + while value < sourceSize.height { + let y = drawSize.height - value * scaleY + path.append((CGPoint(x: 0, y: y), CGPoint(x: drawSize.width, y: y))) + labels.append((String(Int(value.rounded())), CGPoint(x: 0, y: y - thin))) + value += grid.spacing + } + + for (color, width) in [(CGColor(red: 0, green: 0, blue: 0, alpha: 0.35), thin * 3), + (CGColor(red: 1, green: 1, blue: 1, alpha: 0.75), thin)] { + ctx.setStrokeColor(color) + ctx.setLineWidth(width) + for segment in path { + ctx.move(to: segment.from) + ctx.addLine(to: segment.to) + } + ctx.strokePath() + } + for label in labels { + drawChip(text: label.text, topLeft: label.topLeft, font: font, fill: chipFill, in: ctx) + } } private static func drawChip(text: String, topLeft: CGPoint, font: CTFont, @@ -126,12 +225,21 @@ public enum BoxRenderer { // MARK: - Encode - private static func encodePNG(_ image: CGImage) -> Data? { + private static func encode(_ image: CGImage, as encoding: Encoding) -> Data? { + let type: UTType + var properties: [CFString: Any] = [:] + switch encoding { + case .png: + type = .png + case .jpeg(let quality): + type = .jpeg + properties[kCGImageDestinationLossyCompressionQuality] = quality + } guard let data = CFDataCreateMutable(nil, 0), let destination = CGImageDestinationCreateWithData( - data, UTType.png.identifier as CFString, 1, nil) + data, type.identifier as CFString, 1, nil) else { return nil } - CGImageDestinationAddImage(destination, image, nil) + CGImageDestinationAddImage(destination, image, properties as CFDictionary) guard CGImageDestinationFinalize(destination) else { return nil } return data as Data } diff --git a/Sources/LabelKit/Format/AnnotationFormat.swift b/Sources/LabelKit/Format/AnnotationFormat.swift index 0178f0b..5b31ff0 100644 --- a/Sources/LabelKit/Format/AnnotationFormat.swift +++ b/Sources/LabelKit/Format/AnnotationFormat.swift @@ -1,3 +1,4 @@ +import CoreGraphics import Foundation /// One bounding box as it exists on disk: Create ML center-anchored pixels. @@ -22,6 +23,14 @@ public struct BoxRecord: Equatable, Sendable { } } +public extension BoxRecord { + /// The box as a rect with its origin at the top-left corner — the editor's + /// and renderer's view of the centre-anchored values stored on disk. + var rect: CGRect { + CGRect(x: x - width / 2, y: y - height / 2, width: width, height: height) + } +} + /// One dataset entry as it exists on disk. `boxes` may be empty — a negative /// example — and such entries MUST survive save (they are training signal). public struct ImageAnnotationRecord: Equatable, Sendable { diff --git a/Sources/LabelKit/Headless/AgentGuide.swift b/Sources/LabelKit/Headless/AgentGuide.swift new file mode 100644 index 0000000..25baa6f --- /dev/null +++ b/Sources/LabelKit/Headless/AgentGuide.swift @@ -0,0 +1,259 @@ +import Foundation + +/// The instructions labelkit hands to AI agents: an Agent Skill (`SKILL.md`) +/// and a short snippet for a project's `AGENTS.md`. +/// +/// They are compiled into the binary on purpose. `labelkit skill` then always +/// describes the commands of the version that is actually installed, and an +/// agent can get the guide with nothing but the CLI on its PATH. The repo's +/// `skills/labelkit/SKILL.md` is the same text, kept identical by a test, so +/// installers that read a repository (`npx skills add`, plugin marketplaces) +/// serve the same thing. +public enum AgentGuide { + public static let skillName = "labelkit" + + /// Where agent clients look for user-level skills, relative to the home + /// directory. `.agents/skills` is the cross-client convention (Codex, + /// Cursor, opencode, Gemini CLI, Copilot, Amp, Goose, …); Claude Code reads + /// only its own directory, so both are written. + public static let userSkillDirectories = [".agents/skills", ".claude/skills"] + + /// Write `SKILL.md` into `/labelkit/`, creating + /// directories as needed, and return the file's URL. Overwrites a previous + /// install, so re-running after an upgrade refreshes the guide. + @discardableResult + public static func install(into skillsDirectory: URL) throws -> URL { + let folder = skillsDirectory.appendingPathComponent(skillName) + try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) + let file = folder.appendingPathComponent("SKILL.md") + try Data(skill.utf8).write(to: file, options: .atomic) + return file + } + + /// A few lines for a project's `AGENTS.md` (or `CLAUDE.md`, `GEMINI.md`, …): + /// enough for any agent that can run shell commands, including ones with no + /// skills support. + public static let agentsSnippet = #""" + ## Labelling images (labelkit) + + Object-detection datasets here are Apple Create ML folders (images plus one + `annotations.json`) and are edited with the `labelkit` CLI. Do not edit + `annotations.json` by hand. + + - `labelkit stats ` — what is labelled and what is not (JSON). + - `labelkit render --unlabeled --grid 100 --out ` — pictures to label from, with a pixel ruler. + - `labelkit annotate --image --box 'label:x,y,width,height'` — add boxes (x,y = top-left corner, in pixels of the image file). + - `labelkit render --out ` — draw the saved boxes to check them. + - `labelkit validate ` — exits 1 if the dataset has errors. + + Run `labelkit skill` for the full guide and `labelkit --help` for every option. + + """# + + /// The Agent Skill. Frontmatter sticks to the fields of the open Agent + /// Skills specification (`name`, `description`) so every client accepts it. + public static let skill = #""" + --- + name: labelkit + description: Label images for object detection with the labelkit CLI on macOS. Adds, checks and fixes bounding boxes in Apple Create ML datasets (a folder of images with an annotations.json), runs Core ML or Vision detectors, and trains a Core ML object detector. Use when asked to annotate or label images, draw or correct bounding boxes, review or validate an object-detection dataset, or train a Create ML model. + --- + + # labelkit + + labelkit edits Apple Create ML object-detection datasets: a folder of images + plus one `annotations.json`. Drive it through its subcommands. They write the + file through the same code as the editor, so entry order, unknown keys, + negative examples and formatting all survive, and `git diff` shows only real + changes. + + ## Ground rules + + - **Never edit `annotations.json` by hand.** Use `labelkit annotate`. + - **`labelkit ` with no subcommand opens the GUI editor.** Run it + only when the user wants to look at or fix labels themselves. Everything + below is headless. + - **stdout is the result (JSON), stderr is notes.** Parse stdout. + - **Exit codes:** `0` ok · `1` the command ran and found or hit a problem + (stdout says what) · `64` you called it wrong (read stderr, fix the call). + - **Coordinates are pixels of the image file, top-left origin, with `x`,`y` + at the box's top-left corner**, unless you state another convention with + flags. (On disk Create ML stores box centres; labelkit converts.) + - A dataset is addressed by its folder: `labelkit stats ./cards`. + + ## The loop + + 1. **See where things stand.** + `labelkit stats ` → counts, per-label totals, and `unlabeled` + (images with no entry yet, the work to do). + 2. **Look at the images to label.** + `labelkit render --unlabeled --grid 100 --limit 10 --out ` + writes downscaled copies with a labelled line every 100 pixels of the + *original* image. Open them. The JSON gives each image's real `width` + and `height`. + 3. **Write boxes.** + `labelkit annotate --image a.jpg --box 'cat:40,30,200,160' --box 'dog:300,90,120,210'` + or many images at once with `--from boxes.json` (shapes below). + 4. **Check your work by eye.** + `labelkit render a.jpg --out ` draws the saved boxes, + numbered `#1`, `#2`, … Open the picture. If a box is off, fix it with + `--mode replace` (step 3 again for that image) and re-render. Expect two + or three passes on hard images. + 5. **Check the dataset.** + `labelkit validate ` → exit `1` and a list of issues if anything + would break training. Fix and repeat. + + Before labelling a batch, agree the policy with the user and apply it the + same way everywhere, because inconsistent boxes hurt a detector more than + slightly loose ones: + + - **Extent:** the whole object, or only part of it (a card including its + border, or just the artwork)? + - **Cut-off and hidden objects:** box what is visible, or skip them? + - **Label names:** exact spelling. `validate --labels a,b,c` enforces the set. + + ## Getting coordinates right + + You are usually shown a downscaled copy of an image, so pixel positions you + estimate are positions in *that copy*, not in the file. Three safe ways to + give boxes, best first: + + 1. **Read them off the grid.** `render --grid N` labels its lines in + original-image pixels, so numbers read from the picture are already + correct. This is the most accurate method. + 2. **Use relative units.** `--units normalized` (0–1) or `--units 0-1000` + are independent of image size. + 3. **Say what size you looked at.** `--image-size 1568x1176`, or `"width"` + and `"height"` on a JSON entry, and labelkit rescales to the real image. + + Never guess a scale. A box that lies outside its image is rejected, not + silently moved. + + ## Giving boxes to `annotate` + + Inline, for one image: + + ``` + labelkit annotate --image a.jpg --box 'cat:40,30,200,160' + labelkit annotate --image a.jpg -l card --box 40,30,200,160 --box 300,90,120,210 + ``` + + From a file or stdin (`--from -`), for any number of images. JSON, a JSON + array, or NDJSON; a Markdown code fence around it is fine: + + ```json + {"image": "a.jpg", "boxes": [ + {"label": "cat", "x": 40, "y": 30, "width": 200, "height": 160} + ]} + ``` + + With `--image a.jpg --from answer.json` the file is just that image's boxes, + so a vision model's raw answer can be passed straight through. + + Shapes that describe themselves need no flags: + + | Box written as | Meaning | + |---|---| + | `"x","y","width","height"` (or under `"box"`) | the convention set by flags; by default top-left corner, pixels | + | `"normalized": {x,y,width,height}` | the same, as fractions 0–1 | + | `"xyxy": [x1,y1,x2,y2]`, or `x1/y1/x2/y2`, `xmin/ymin/xmax/ymax` keys | two corners | + | `"box_2d": [y1,x1,y2,x2]` | Gemini: y first, 0–1000 | + | `"bbox_2d": [x1,y1,x2,y2]` | Qwen: add `--units 0-1000` for Qwen3-VL | + | `"coordinates": {x,y,width,height}` | Create ML: centre-anchored pixels | + | a COCO file (`images`/`annotations`/`categories`) | read whole | + | `labelkit detect` output | read as is | + + For anything else, name the convention instead of converting numbers: + + | Flag | Use for | + |---|---| + | `--order xyxy` / `--order yxyx` | four bare numbers that are corners | + | `--anchor center` | `x`,`y` is the box centre | + | `--units normalized` / `0-1000` / `percent` | relative coordinates | + | `--units normalized --anchor center` | YOLO | + | `--units normalized --origin bottom-left` | Apple Vision | + | `--image-size WxH` | pixels of a resized copy | + | `-l NAME` | boxes that carry no label | + + Behaviour worth knowing: + + - **`--mode add` (default)** keeps existing boxes and skips any new box that + is already there (same label, overlapping). Re-running the same input + changes nothing, so retrying is always safe. + - **`--mode replace`** gives each listed image exactly the boxes supplied. + Other images are untouched. Use it to correct an image. + - **`--negatives`** records an image supplied with no boxes as a negative + example (an object-free image is real training signal). Without it, "no + boxes" writes nothing: `--image empty.jpg --negatives`. + - **`--dry-run`** reports what would change without writing. + - If any input is unusable (unknown image, box outside the image), nothing + is written and the exit code is `1`. `--lenient` applies the rest. + - Boxes hanging over an edge are trimmed and counted as `clamped`. + + ## Letting a detector do the first pass + + ``` + labelkit detect --model model.mlpackage --format ndjson | labelkit annotate --from - + labelkit detect --detector rectangles -l card --format ndjson | labelkit annotate --from - + ``` + + `--detector` is a built-in Apple Vision detector (`rectangles`, `faces`, + `humans`, `animals`, `saliency`); `--model` is a Core ML object detector, + including one trained earlier on this dataset. Detections are a draft: + render and review them like any other boxes. + + ## Checking a dataset + + `labelkit validate ` reports, as JSON `issues` with a stable `code`: + + - **errors** (exit 1): `no-annotations-file`, `missing-image`, + `duplicate-entry`, `empty-label`, `empty-box`, `box-outside-image`, + `unknown-label` (with `--labels`). + - **warnings** (exit 0, or 1 with `--strict`): `box-overflows-image`, + `duplicate-box`, `duplicate-image` (the same photo under two names), + `unreadable-image`, `unused-label`. + + Each issue names the `image` and the `box` number, matching the `#n` drawn + by `render`. + + `labelkit stats ` also shows what `validate` cannot judge: + + - labels with very few boxes. Apple's guidance is to start from roughly 30 + annotated images per class, balanced across classes; + - `boxesPerImage.max` and `maxImage`: one image with far more boxes than the + rest can skew a model, so look at it; + - `--per-image` lists every image with its status and box count. + + ## Training + + ``` + labelkit train -o model.mlmodel + ``` + + Trains a Create ML object detector and prints a JSON report. It can take + minutes to hours and needs real image files (not symlinks). Run `validate` + first. Create ML holds out part of the data for validation on its own + (`--validation-split` to control it). See `labelkit train --help`. + + ## When to hand over to the user + + The editor is the right tool for a human check: suggest `labelkit ` + when labels need a judgment call you cannot make from a picture, or before + training on labels nobody has reviewed. Say what you labelled and what you + were unsure about. + + ## Command summary + + | Command | Does | Writes | + |---|---|---| + | `labelkit stats [--per-image]` | counts, labels, unlabelled images | nothing | + | `labelkit validate [--labels a,b] [--strict]` | finds problems, exit 1 on errors | nothing | + | `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 train [-o model.mlmodel]` | trains a Core ML detector | the model file | + + Every command has `--help` with examples. `stats`, `validate` and `annotate` + also take `--format text` for a human-readable summary. + + """# +} diff --git a/Sources/LabelKit/Headless/AnnotationMerge.swift b/Sources/LabelKit/Headless/AnnotationMerge.swift new file mode 100644 index 0000000..3f2311d --- /dev/null +++ b/Sources/LabelKit/Headless/AnnotationMerge.swift @@ -0,0 +1,256 @@ +import CoreGraphics +import Foundation + +/// Applies imported boxes to a `DatasetDocument` — the write path behind +/// `labelkit annotate`. +/// +/// Built for callers that retry: in the default `add` mode a box that already +/// exists (same label, overlapping an existing one) is skipped, so sending the +/// same input twice changes nothing and saves the same bytes. Geometry is +/// resolved against the real image: normalized boxes are scaled, boxes hanging +/// over an edge are clamped, and boxes that end up empty are rejected rather +/// than written. +public enum AnnotationMerge { + public enum Mode: String, Sendable, CaseIterable { + /// Keep existing boxes; add the new ones that aren't already there. + case add + /// The listed images get exactly the supplied boxes; other images are + /// untouched. + case replace + } + + public struct Options: Sendable { + public var mode: Mode + /// In `add` mode, a new box overlapping an existing same-label box by + /// more than this IoU counts as already present. + public var dedupeIoU: CGFloat + /// Record an image supplied with no boxes as a negative example (an + /// entry with zero annotations). Off by default so that "the detector + /// found nothing" is never silently turned into training signal. + public var recordNegatives: Bool + + public init(mode: Mode = .add, dedupeIoU: CGFloat = 0.5, recordNegatives: Bool = false) { + self.mode = mode + self.dedupeIoU = dedupeIoU + self.recordNegatives = recordNegatives + } + } + + /// What happened to one image. Counts are boxes. + public struct ImageOutcome: Codable, Equatable, Sendable { + public var image: String + /// Boxes written by this run. + public var added: Int + /// Supplied boxes skipped because an equivalent one already existed. + public var duplicates: Int + /// Existing boxes removed (`replace` mode only). + public var removed: Int + /// Supplied boxes that had to be trimmed to the image bounds. + public var clamped: Int + /// Boxes on the image after this run. + public var total: Int + /// True when the image had no entry in the annotations file before. + public var created: Bool + } + + /// Input that could not be applied. Any problem makes the run fail unless + /// the caller opts into applying the rest. + public struct Problem: Codable, Equatable, Sendable { + public var image: String + public var message: String + } + + public struct Result: Equatable, Sendable { + public var outcomes: [ImageOutcome] + public var problems: [Problem] + /// True when the document's records differ from before the run. + public var changed: Bool + } + + /// - Parameter pixelSize: display-orientation size of a dataset image, or + /// nil if it can't be read. Injected so the merge stays pure and testable. + public static func apply( + _ imports: [ImportedImage], + to document: inout DatasetDocument, + options: Options = Options(), + pixelSize: (String) -> CGSize? + ) -> Result { + let before = document.records + let onDisk = Set(document.imagesOnDisk) + var indexByImage: [String: Int] = [:] + for (index, record) in document.records.enumerated() where indexByImage[record.image] == nil { + indexByImage[record.image] = index + } + + // Several input entries for one image are one request for that image. + var order: [String] = [] + var grouped: [String: [ImportedBox]] = [:] + for item in imports { + if grouped[item.image] == nil { order.append(item.image) } + grouped[item.image, default: []].append(contentsOf: item.boxes) + } + + var outcomes: [ImageOutcome] = [] + var problems: [Problem] = [] + var newRecords: [ImageAnnotationRecord] = [] + + for image in order { + let supplied = grouped[image] ?? [] + let existingIndex = indexByImage[image] + guard existingIndex != nil || onDisk.contains(image) else { + problems.append(Problem(image: image, message: "no such image in the dataset")) + continue + } + + let size = pixelSize(image) + var resolved: [BoxRecord] = [] + var clamped = 0 + for (offset, box) in supplied.enumerated() { + switch resolve(box, imageSize: size) { + case .success(let (record, wasClamped)): + resolved.append(record) + if wasClamped { clamped += 1 } + case .failure(let reason): + problems.append(Problem(image: image, message: "box #\(offset + 1) (\(box.label)): \(reason.message)")) + } + } + + var boxes = existingIndex.map { document.records[$0].boxes } ?? [] + var added = 0, duplicates = 0, removed = 0 + switch options.mode { + case .add: + for candidate in resolved { + if boxes.contains(where: { isSameBox($0, candidate, threshold: options.dedupeIoU) }) { + duplicates += 1 + } else { + boxes.append(candidate) + added += 1 + } + } + case .replace: + removed = boxes.count + boxes = resolved + added = resolved.count + } + + if let existingIndex { + document.records[existingIndex].boxes = boxes + } else if !boxes.isEmpty || options.recordNegatives { + newRecords.append(ImageAnnotationRecord(image: image, boxes: boxes)) + } else { + continue // nothing to record for an image with no entry and no boxes + } + outcomes.append(ImageOutcome( + image: image, added: added, duplicates: duplicates, removed: removed, + clamped: clamped, total: boxes.count, created: existingIndex == nil)) + } + + // New entries go after the existing ones in name order — the same place + // the editor puts them — so the file doesn't depend on input order. + newRecords.sort { $0.image.localizedStandardCompare($1.image) == .orderedAscending } + document.records.append(contentsOf: newRecords) + + return Result(outcomes: outcomes, problems: problems, changed: document.records != before) + } + + // MARK: - Geometry + + private static func resolve( + _ box: ImportedBox, imageSize: CGSize? + ) -> Swift.Result<(BoxRecord, Bool), BoxImportError> { + let label = box.label.trimmingCharacters(in: .whitespacesAndNewlines) + guard !label.isEmpty else { return .failure(BoxImportError(message: "empty label")) } + + var rect: CGRect + switch box.geometry { + case .pixels(let pixels): + rect = pixels + case .scaledPixels(let pixels, let reference): + // Same size (the usual case, e.g. `labelkit detect` output), or no + // way to tell: the numbers are used as they are, with no float + // round trip. Otherwise scale from the copy to the real image. + if let imageSize, imageSize != reference { + let sx = imageSize.width / reference.width, sy = imageSize.height / reference.height + rect = CGRect(x: pixels.minX * sx, y: pixels.minY * sy, + width: pixels.width * sx, height: pixels.height * sy) + } else { + rect = pixels + } + case .normalized(let fraction): + guard let imageSize else { + return .failure(BoxImportError( + message: "normalized coordinates need the image's size, and the file can't be read")) + } + rect = CGRect(x: fraction.minX * imageSize.width, y: fraction.minY * imageSize.height, + width: fraction.width * imageSize.width, height: fraction.height * imageSize.height) + } + guard rect.width.isFinite, rect.height.isFinite, rect.minX.isFinite, rect.minY.isFinite, + rect.width > 0, rect.height > 0 else { + return .failure(BoxImportError(message: "width and height must be positive")) + } + + var wasClamped = false + // A box already inside its image is written exactly as given; only one + // that reaches past an edge is trimmed. + if let imageSize, !CGRect(origin: .zero, size: imageSize).contains(rect) { + let inside = rect.intersection(CGRect(origin: .zero, size: imageSize)) + guard !inside.isNull, inside.width >= 1, inside.height >= 1 else { + return .failure(BoxImportError( + message: "lies outside the image (\(Int(imageSize.width))x\(Int(imageSize.height)))")) + } + // Sub-pixel overhang is rounding noise, not a mistake worth reporting. + wasClamped = abs(inside.width - rect.width) > 0.5 || abs(inside.height - rect.height) > 0.5 + rect = inside + } + return .success((BoxRecord(label: label, x: rect.midX, y: rect.midY, + width: rect.width, height: rect.height), wasClamped)) + } + + private static func isSameBox(_ a: BoxRecord, _ b: BoxRecord, threshold: CGFloat) -> Bool { + a.label == b.label && DetectionMerge.iou(a.rect, b.rect) > threshold + } +} + +/// What `labelkit annotate` prints: the outcome of one run, per image and in +/// total, plus anything that could not be applied. +public struct AnnotateReport: Codable, Equatable, Sendable { + public var schemaVersion: Int + public var labelkit: String + public var dataset: String + public var annotations: String + /// `add` or `replace`. + public var mode: String + public var dryRun: Bool + /// True when the annotations file was rewritten by this run. + public var written: Bool + public var totals: Totals + public var images: [AnnotationMerge.ImageOutcome] + public var problems: [AnnotationMerge.Problem] + + public struct Totals: Codable, Equatable, Sendable { + public var images: Int + public var added: Int + public var duplicates: Int + public var removed: Int + public var clamped: Int + } + + public static func make( + document: DatasetDocument, result: AnnotationMerge.Result, mode: AnnotationMerge.Mode, + dryRun: Bool, written: Bool, labelkitVersion version: String = labelkitVersion + ) -> AnnotateReport { + let outcomes = result.outcomes + return AnnotateReport( + schemaVersion: 1, labelkit: version, + dataset: document.location.imagesDirectory.path, + annotations: document.location.annotationsURL.path, + mode: mode.rawValue, dryRun: dryRun, written: written, + totals: Totals( + images: outcomes.count, + added: outcomes.reduce(0) { $0 + $1.added }, + duplicates: outcomes.reduce(0) { $0 + $1.duplicates }, + removed: outcomes.reduce(0) { $0 + $1.removed }, + clamped: outcomes.reduce(0) { $0 + $1.clamped }), + images: outcomes, problems: result.problems) + } +} diff --git a/Sources/LabelKit/Headless/BoxImport.swift b/Sources/LabelKit/Headless/BoxImport.swift new file mode 100644 index 0000000..4f4e71d --- /dev/null +++ b/Sources/LabelKit/Headless/BoxImport.swift @@ -0,0 +1,487 @@ +import CoreGraphics +import Foundation + +/// One box handed to `labelkit annotate`, before it is resolved against the +/// image it belongs to. +public struct ImportedBox: Equatable, Sendable { + /// Canonical geometry: top-left origin, `origin` = the box's top-left corner. + public enum Geometry: Equatable, Sendable { + /// Pixels of the image as it is on disk. + case pixels(CGRect) + /// Fractions of the image in `[0,1]`. + case normalized(CGRect) + /// Pixels of a copy of the image that is `reference` in size — what a + /// model reports when it was shown a downscaled picture. Rescaled to + /// the real image when the two sizes differ. + case scaledPixels(CGRect, reference: CGSize) + } + + public var label: String + public var geometry: Geometry + + public init(label: String, geometry: Geometry) { + self.label = label + self.geometry = geometry + } +} + +/// All the boxes supplied for one image. +public struct ImportedImage: Equatable, Sendable { + public var image: String + public var boxes: [ImportedBox] + + public init(image: String, boxes: [ImportedBox]) { + self.image = image + self.boxes = boxes + } +} + +/// How to read four numbers as a box. `units`, `origin` and `anchor` are the +/// axes Create ML itself uses to describe annotations; `order` and the extra +/// unit scales cover what vision models and other tools emit. Naming a +/// convention replaces writing a conversion script. +public struct BoxConvention: Equatable, Sendable { + public enum Units: String, Sendable, CaseIterable { + /// Image pixels. + case pixel + /// Fractions of the image, `0…1`. + case normalized + /// `0…1000` across the image (Gemini, Qwen3-VL). + case thousandths = "0-1000" + /// `0…100` across the image (Label Studio). + case percent + + /// The value that means "the full width or height"; nil for pixels. + var fullScale: Double? { + switch self { + case .pixel: return nil + case .normalized: return 1 + case .thousandths: return 1000 + case .percent: return 100 + } + } + } + + public enum Origin: String, Sendable, CaseIterable { + /// y grows downward from the top edge (images, Create ML, most tools). + case topLeft = "top-left" + /// y grows upward from the bottom edge (Apple Vision). + case bottomLeft = "bottom-left" + } + + public enum Anchor: String, Sendable, CaseIterable { + /// `x`,`y` is the box corner nearest the origin. + case corner + /// `x`,`y` is the centre of the box (Create ML, YOLO). + case center + } + + /// What four numbers in a row mean. + public enum Order: String, Sendable, CaseIterable { + /// x, y, width, height (COCO; with `anchor: .center`, YOLO). + case xywh + /// Two opposite corners, x first: x1, y1, x2, y2. + case xyxy + /// Two opposite corners, y first: y1, x1, y2, x2 (Gemini, PaliGemma). + case yxyx + } + + public var units: Units + public var origin: Origin + public var anchor: Anchor + public var order: Order + /// The image size that pixel coordinates refer to, when it is not the size + /// of the file on disk — a model that was shown a downscaled copy reports + /// pixels of that copy. Boxes are rescaled to the real image. + public var referenceSize: CGSize? + + public init(units: Units = .pixel, origin: Origin = .topLeft, anchor: Anchor = .corner, + order: Order = .xywh, referenceSize: CGSize? = nil) { + self.units = units + self.origin = origin + self.anchor = anchor + self.order = order + self.referenceSize = referenceSize + } + + /// labelkit's own reporting convention, and the default for input. + public static let pixelTopLeftCorner = BoxConvention() + /// What Create ML stores on disk. + public static let createML = BoxConvention(units: .pixel, origin: .topLeft, anchor: .center) + + /// Why this convention can't be used, if it can't. A bottom-left origin in + /// pixels would need every image's height before a box could be placed; + /// nothing in practice emits it, so it is refused rather than guessed at. + public var unsupportedReason: String? { + units == .pixel && origin == .bottomLeft + ? "a bottom-left origin is only supported with normalized units" + : nil + } + + /// Turn four numbers in this convention into canonical geometry. + func geometry(_ v: (Double, Double, Double, Double)) -> ImportedBox.Geometry { + var minX: Double, minY: Double, width: Double, height: Double + switch order { + case .xywh: + width = v.2 + height = v.3 + minX = anchor == .center ? v.0 - width / 2 : v.0 + minY = anchor == .center ? v.1 - height / 2 : v.1 + case .xyxy: + minX = min(v.0, v.2) + minY = min(v.1, v.3) + width = abs(v.2 - v.0) + height = abs(v.3 - v.1) + case .yxyx: + minX = min(v.1, v.3) + minY = min(v.0, v.2) + width = abs(v.3 - v.1) + height = abs(v.2 - v.0) + } + + if let full = units.fullScale { + if origin == .bottomLeft { minY = full - (minY + height) } + return .normalized(CGRect(x: minX / full, y: minY / full, width: width / full, height: height / full)) + } + let rect = CGRect(x: minX, y: minY, width: width, height: height) + if let reference = referenceSize, reference.width > 0, reference.height > 0 { + return .scaledPixels(rect, reference: reference) + } + return .pixels(rect) + } +} + +public struct BoxImportError: LocalizedError, Equatable { + public var message: String + public var errorDescription: String? { message } +} + +/// Reads the box input `labelkit annotate` accepts. It is forgiving about +/// *shape*, so that what labelkit prints, what a vision model answers, and the +/// common dataset files all work without a conversion step — and strict about +/// *meaning*: where a shape doesn't say what its numbers are, `Options` +/// decides, and nothing is guessed from the values. +/// +/// **Container** — one JSON object, a JSON array, or NDJSON (one object per +/// line). A Markdown code fence around it is ignored. A COCO file (`images`, +/// `annotations`, `categories`) is read as a whole dataset. +/// +/// **Per image** — a name under `image` (also `imagefilename`, `file_name`, +/// `filename`, or the basename of `path`) and a list under `boxes` (also +/// `detections`, `annotations`, `annotation`, `objects`, `predictions`). +/// `width` + `height` (or `imageWidth` + `imageHeight`) on the entry say what +/// size its pixel coordinates refer to. +/// +/// **Per box** — a label under `label` (also `class`, `name`, `category`; or +/// the default) and one geometry: +/// +/// | Shape | Read as | +/// |---|---| +/// | `x, y, width, height` on the box or under `box` | `Options.convention` | +/// | `normalized: {x,y,width,height}` | the same, in fractions | +/// | `coordinates: {x,y,width,height}` | Create ML: pixels, centre-anchored | +/// | `xyxy: [x1,y1,x2,y2]`, or `x1,y1,x2,y2` / `xmin,…` / `x_min,…` keys | corners, in the convention's units | +/// | `bbox_2d: [x1,y1,x2,y2]` | corners, in the convention's units (Qwen) | +/// | `box_2d: [y1,x1,y2,x2]` | corners, y first, 0–1000 (Gemini) | +/// | `bbox: [a,b,c,d]` or `box: [a,b,c,d]` | the convention's order and units | +/// +/// A list of bare `[a,b,c,d]` arrays with a parallel `labels` list is read the +/// same way as `bbox`. +public enum BoxImportParser { + public struct Options: Equatable, Sendable { + public var convention: BoxConvention + /// Label for boxes that don't carry one. Without it a box with no + /// label is an error. + public var defaultLabel: String? + /// When set, the input is the boxes of this one image: entries need no + /// `image` key, and a bare list of boxes is accepted. + public var image: String? + + public init(convention: BoxConvention = .pixelTopLeftCorner, defaultLabel: String? = nil, + image: String? = nil) { + self.convention = convention + self.defaultLabel = defaultLabel + self.image = image + } + } + + public static func parse(_ data: Data, options: Options = Options()) throws -> [ImportedImage] { + let text = stripCodeFence(String(decoding: data, as: UTF8.self)) + guard !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return [] } + + if let whole = try? JSONSerialization.jsonObject(with: Data(text.utf8), options: [.fragmentsAllowed]) { + switch whole { + case let object as [String: Any]: + if let coco = try coco(from: object) { return coco } + return [try image(from: object, at: "input", options: options)] + case let array as [Any]: + if let image = options.image, array.contains(where: { !isImageEntry($0) }) { + // A bare list of boxes for the one named image. + return [ImportedImage(image: image, boxes: try boxes( + from: array, labels: nil, at: "input (\(image))", + convention: options.convention, options: options))] + } + return try array.enumerated().map { index, element in + guard let object = element as? [String: Any] else { + throw BoxImportError(message: "entry #\(index + 1) is not a JSON object") + } + return try image(from: object, at: "entry #\(index + 1)", options: options) + } + default: + throw BoxImportError(message: "expected a JSON object, an array of objects, or NDJSON") + } + } + + // Not one JSON document: read it as NDJSON. + var images: [ImportedImage] = [] + for (index, rawLine) in text.split(omittingEmptySubsequences: false, whereSeparator: \.isNewline).enumerated() { + let line = rawLine.trimmingCharacters(in: .whitespaces) + if line.isEmpty { continue } + guard let object = try? JSONSerialization.jsonObject(with: Data(line.utf8)) as? [String: Any] else { + throw BoxImportError(message: "line \(index + 1) is not a JSON object") + } + images.append(try image(from: object, at: "line \(index + 1)", options: options)) + } + return images + } + + /// Parse the inline `--box` form: `label:a,b,c,d`, or just `a,b,c,d` when a + /// default label is set. The four numbers are read with the convention's + /// order. The label may itself contain colons; the numbers are whatever + /// follows the last one. + public static func parseInlineBox(_ text: String, options: Options = Options()) throws -> ImportedBox { + var label = options.defaultLabel ?? "" + var numbers = Substring(text) + if let colon = text.lastIndex(of: ":") { + label = String(text[.. CGSize? { + let parts = text.lowercased().split(separator: "x").map { Double($0.trimmingCharacters(in: .whitespaces)) } + guard parts.count == 2, let width = parts[0], let height = parts[1], width > 0, height > 0 else { + return nil + } + return CGSize(width: width, height: height) + } + + // MARK: - Containers + + private static let imageKeys = ["image", "imagefilename", "file_name", "filename"] + private static let listKeys = ["boxes", "detections", "annotations", "annotation", "objects", + "predictions", "bboxes"] + private static let labelKeys = ["label", "class", "name", "category"] + private static let parallelLabelKeys = ["labels", "text_labels", "classes", "names"] + + /// A model asked for JSON usually wraps it in a Markdown fence. + static func stripCodeFence(_ text: String) -> String { + guard let open = text.range(of: "```") else { return text } + let afterOpen = text[open.upperBound...] + guard let lineEnd = afterOpen.firstIndex(where: \.isNewline), + let close = afterOpen.range(of: "```", options: .backwards), + close.lowerBound > lineEnd else { return text } + return String(afterOpen[afterOpen.index(after: lineEnd).. Bool { + guard let object = element as? [String: Any] else { return false } + return listKeys.contains { object[$0] != nil } + } + + private static func image(from object: [String: Any], at place: String, + options: Options) throws -> ImportedImage { + let name: String + if let fixed = options.image { + name = fixed + } else if let key = imageKeys.first(where: { (object[$0] as? String)?.isEmpty == false }), + let value = object[key] as? String { + name = value + } else if let path = object["path"] as? String, !path.isEmpty { + name = URL(fileURLWithPath: path).lastPathComponent + } else { + throw BoxImportError(message: "\(place): missing \"image\"") + } + let here = "\(place) (\(name))" + + guard let key = listKeys.first(where: { object[$0] != nil }) else { + throw BoxImportError(message: "\(here): expected a \"boxes\", \"detections\" or \"annotations\" list") + } + guard let rawBoxes = object[key] as? [Any] else { + throw BoxImportError(message: "\(here): \"\(key)\" is not a list") + } + + // Pixel coordinates are relative to the size the entry states, if any. + var convention = options.convention + if let width = number(object["width"] ?? object["imageWidth"]), + let height = number(object["height"] ?? object["imageHeight"]), width > 0, height > 0 { + convention.referenceSize = CGSize(width: width, height: height) + } + let labels = parallelLabelKeys.lazy.compactMap { object[$0] as? [Any] }.first + return ImportedImage(image: name, boxes: try boxes( + from: rawBoxes, labels: labels, at: here, convention: convention, options: options)) + } + + private static func boxes(from rawBoxes: [Any], labels: [Any]?, at place: String, + convention: BoxConvention, options: Options) throws -> [ImportedBox] { + try rawBoxes.enumerated().map { index, raw in + let here = "\(place), box #\(index + 1)" + if let numbers = raw as? [Any] { + // Bare [a,b,c,d]; its label comes from a parallel list or the default. + let parallel = labels.flatMap { index < $0.count ? $0[index] as? String : nil } + guard let label = parallel ?? options.defaultLabel else { + throw BoxImportError(message: "\(here): missing \"label\"") + } + return ImportedBox(label: label, geometry: convention.geometry(try four(numbers, at: here))) + } + return try box(from: raw, at: here, convention: convention, options: options) + } + } + + /// COCO detection JSON: boxes are `[x, y, width, height]` in pixels from + /// the top-left corner, keyed to images and categories by id. Images with + /// no annotations come through with an empty box list. + private static func coco(from object: [String: Any]) throws -> [ImportedImage]? { + guard let images = object["images"] as? [[String: Any]], + let annotations = object["annotations"] as? [[String: Any]], + let categories = object["categories"] as? [[String: Any]] else { return nil } + + var categoryName: [Int: String] = [:] + for category in categories { + if let id = (category["id"] as? NSNumber)?.intValue, let name = category["name"] as? String { + categoryName[id] = name + } + } + var order: [Int] = [] + var result: [Int: ImportedImage] = [:] + var conventions: [Int: BoxConvention] = [:] + for image in images { + guard let id = (image["id"] as? NSNumber)?.intValue, let file = image["file_name"] as? String else { + 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: []) + 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) + } + conventions[id] = convention + } + for (index, annotation) in annotations.enumerated() { + let here = "COCO annotation #\(index + 1)" + guard let imageID = (annotation["image_id"] as? NSNumber)?.intValue, result[imageID] != nil else { + throw BoxImportError(message: "\(here): \"image_id\" matches no image") + } + guard let categoryID = (annotation["category_id"] as? NSNumber)?.intValue, + let label = categoryName[categoryID] else { + throw BoxImportError(message: "\(here): \"category_id\" matches no category") + } + guard let bbox = annotation["bbox"] as? [Any] else { + throw BoxImportError(message: "\(here): missing \"bbox\"") + } + let convention = conventions[imageID] ?? .pixelTopLeftCorner + result[imageID]?.boxes.append( + ImportedBox(label: label, geometry: convention.geometry(try four(bbox, at: here)))) + } + return order.compactMap { result[$0] } + } + + // MARK: - Boxes + + private static func box(from raw: Any, at place: String, convention: BoxConvention, + options: Options) throws -> ImportedBox { + guard let object = raw as? [String: Any] else { + throw BoxImportError(message: "\(place): not a JSON object") + } + let ownLabel = labelKeys.lazy.compactMap { object[$0] as? String }.first + guard let label = ownLabel ?? options.defaultLabel else { + throw BoxImportError(message: "\(place): missing \"label\"") + } + func made(_ values: (Double, Double, Double, Double), _ convention: BoxConvention) -> ImportedBox { + ImportedBox(label: label, geometry: convention.geometry(values)) + } + func with(_ change: (inout BoxConvention) -> Void) -> BoxConvention { + var copy = convention + change(©) + return copy + } + + if let coordinates = object["coordinates"] as? [String: Any] { + // Create ML's own shape; only the reference size carries over. + var createML = BoxConvention.createML + createML.referenceSize = convention.referenceSize + return made(try named(coordinates, ["x", "y", "width", "height"], at: "\(place) coordinates"), createML) + } + if let gemini = object["box_2d"] as? [Any] { + return made(try four(gemini, at: "\(place) box_2d"), + BoxConvention(units: .thousandths, order: .yxyx)) + } + for key in ["xyxy", "bbox_2d"] { + if let corners = object[key] as? [Any] { + return made(try four(corners, at: "\(place) \(key)"), with { $0.order = .xyxy }) + } + } + for key in ["bbox", "box"] { + if let numbers = object[key] as? [Any] { + return made(try four(numbers, at: "\(place) \(key)"), convention) + } + } + if let nested = object["box"] as? [String: Any] { + return made(try rect(nested, at: "\(place) box"), with { $0.order = .xywh }) + } + if let normalized = object["normalized"] as? [String: Any] { + return made(try rect(normalized, at: "\(place) normalized"), + with { $0.order = .xywh; $0.units = .normalized }) + } + for keys in [["x1", "y1", "x2", "y2"], ["xmin", "ymin", "xmax", "ymax"], + ["x_min", "y_min", "x_max", "y_max"]] where object[keys[0]] != nil { + return made(try named(object, keys, at: place), with { $0.order = .xyxy }) + } + if object["x"] != nil || object["width"] != nil || object["w"] != nil { + return made(try rect(object, at: place), with { $0.order = .xywh }) + } + throw BoxImportError(message: "\(place): no geometry — give x,y,width,height, or one of " + + "\"box\", \"normalized\", \"coordinates\", \"xyxy\", \"bbox\", \"box_2d\", \"bbox_2d\"") + } + + // MARK: - Numbers + + private static func number(_ value: Any?) -> Double? { + guard let value = value as? NSNumber, CFGetTypeID(value) != CFBooleanGetTypeID() else { return nil } + return value.doubleValue + } + + private static func four(_ values: [Any], at place: String) throws -> (Double, Double, Double, Double) { + let numbers = values.compactMap(number) + guard values.count == 4, numbers.count == 4 else { + throw BoxImportError(message: "\(place): expected four numbers") + } + return (numbers[0], numbers[1], numbers[2], numbers[3]) + } + + private static func named(_ object: [String: Any], _ keys: [String], + at place: String) throws -> (Double, Double, Double, Double) { + let numbers = try keys.map { key -> Double in + guard let value = number(object[key]) else { + throw BoxImportError(message: "\(place): \"\(key)\" must be a number") + } + return value + } + return (numbers[0], numbers[1], numbers[2], numbers[3]) + } + + /// `x, y, width, height`, accepting `w`/`h` for the last two. + private static func rect(_ object: [String: Any], at place: String) throws -> (Double, Double, Double, Double) { + let widthKey = object["width"] == nil && object["w"] != nil ? "w" : "width" + let heightKey = object["height"] == nil && object["h"] != nil ? "h" : "height" + return try named(object, ["x", "y", widthKey, heightKey], at: place) + } +} diff --git a/Sources/LabelKit/Headless/DatasetDocument.swift b/Sources/LabelKit/Headless/DatasetDocument.swift new file mode 100644 index 0000000..908247e --- /dev/null +++ b/Sources/LabelKit/Headless/DatasetDocument.swift @@ -0,0 +1,104 @@ +import CoreGraphics +import Foundation + +/// A dataset opened for scripted, headless work: the annotations file as plain +/// records plus the list of images on disk. This is what the `stats`, +/// `validate`, `annotate` and `render` subcommands operate on. +/// +/// It is deliberately not `DatasetStore`: that one is main-actor, observable +/// and built around undo for the editor. A document is a value — load it, +/// change `records`, `save()` — and it writes through the same +/// `CreateMLWriter`, so the format contract (order, unknown keys, negatives, +/// byte-stable output, the file's own indentation) holds for scripted edits +/// exactly as it does for the GUI. +public struct DatasetDocument: Sendable { + public let location: DatasetLocation + /// 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] + /// Indentation sniffed from the loaded file, reused on save. + public let indentUnit: String + + /// - Parameter onlyImages: when the caller will only ever ask about these + /// images (as `annotate` does), they are checked on disk one by one and + /// the directory is not listed at all. `imagesOnDisk` then holds just the + /// ones that exist. Past a few hundred names a full listing is cheaper, + /// so that is what happens instead. + public init(location: DatasetLocation, imageGlob: String? = nil, onlyImages: [String]? = nil) throws { + self.location = location + if location.annotationsExists { + let data = try Data(contentsOf: location.annotationsURL) + records = try CreateMLFormat.load(data) + indentUnit = JSONIndent.detectUnit(in: data) ?? CreateMLWriter.defaultIndentUnit + } else { + records = [] + indentUnit = CreateMLWriter.defaultIndentUnit + } + if let onlyImages, onlyImages.count <= Self.listingThreshold { + let directory = location.imagesDirectory.path + // Only files directly in the folder count, as with a listing: a + // name with a path in it must not reach outside the dataset. + imagesOnDisk = onlyImages.uniqued().filter { + !$0.contains("/") && FileManager.default.fileExists(atPath: directory + "/" + $0) + } + } else { + imagesOnDisk = ImageDirectoryScanner.scan(directory: location.imagesDirectory, glob: imageGlob) + } + } + + /// Up to this many images, checking each beats listing a large directory. + static let listingThreshold = 256 + + /// For tests and callers that already hold the pieces. + public init(location: DatasetLocation, records: [ImageAnnotationRecord], + imagesOnDisk: [String], indentUnit: String = CreateMLWriter.defaultIndentUnit) { + self.location = location + self.records = records + self.imagesOnDisk = imagesOnDisk + self.indentUnit = indentUnit + } + + public func imageURL(for filename: String) -> URL { + location.imagesDirectory.appendingPathComponent(filename) + } + + /// Display-orientation pixel size of an image in the dataset, or nil when + /// the file is missing or unreadable. + public func pixelSize(of filename: String) -> CGSize? { + ImageMetadata.pixelSize(of: imageURL(for: filename)) + } + + /// The exact bytes `save()` would write. + public func serialized() -> Data { + CreateMLWriter.serialize(records, indentUnit: indentUnit) + } + + public func save() throws { + try serialized().write(to: location.annotationsURL, options: .atomic) + } +} + +public extension DatasetDocument { + /// The file's entries with repeats of an image dropped — the first entry + /// wins, as in the editor. (`validate` reports the repeats.) + var uniqueRecords: [ImageAnnotationRecord] { + var seen = Set() + return records.filter { seen.insert($0.image).inserted } + } + + /// Pixel sizes for many images at once, read in parallel. Each read is a + /// header-only probe (no pixel decode), so this stays cheap on datasets of + /// tens of thousands of images; images that are missing or unreadable are + /// simply absent from the result. + func pixelSizes(of filenames: [String]) -> [String: CGSize] { + let directory = location.imagesDirectory + let sizes = filenames.concurrentMap { ImageMetadata.pixelSize(of: directory.appendingPathComponent($0)) } + var result: [String: CGSize] = [:] + result.reserveCapacity(filenames.count) + for (name, size) in zip(filenames, sizes) { + if let size { result[name] = size } + } + return result + } +} diff --git a/Sources/LabelKit/Headless/DatasetSummary.swift b/Sources/LabelKit/Headless/DatasetSummary.swift new file mode 100644 index 0000000..910d43a --- /dev/null +++ b/Sources/LabelKit/Headless/DatasetSummary.swift @@ -0,0 +1,140 @@ +import Foundation + +/// What `labelkit stats` reports: enough for a script or an agent to decide +/// what to do next (which images still need labels, which labels are thin) +/// without parsing the annotations file itself. +public struct DatasetSummary: Codable, Equatable, Sendable { + /// Output schema version — bump on any breaking field change. + public var schemaVersion: Int + public var labelkit: String + /// Absolute path of the images directory. + public var dataset: String + /// Absolute path of the annotations file. + public var annotations: String + /// False when the annotations file doesn't exist yet. + public var annotationsExists: Bool + public var images: ImageCounts + /// Total boxes across the dataset. + public var boxes: Int + /// How boxes are spread over the images that have any. An image far above + /// the median is worth a look: one crowded outlier can skew a model. + public var boxesPerImage: BoxSpread? + /// Most-used label first; ties broken by name. + public var labels: [LabelCount] + /// Images on disk with no entry in the annotations file. + public var unlabeled: [String] + /// Entries whose image file is missing on disk. + public var missing: [String] + /// One row per image, when asked for. + public var perImage: [ImageRow]? + + public struct ImageCounts: Codable, Equatable, Sendable { + /// Every image the dataset knows about: on disk or in the file. + public var total: Int + public var onDisk: Int + /// Entries with at least one box. + public var annotated: Int + /// Entries with zero boxes — negative examples. + public var negatives: Int + /// On disk, no entry yet. + public var unlabeled: Int + /// In the file, not on disk. + public var missing: Int + } + + public struct BoxSpread: Codable, Equatable, Sendable { + public var min: Int + public var median: Double + public var max: Int + /// The image holding `max` boxes (the first, if several tie). + public var maxImage: String + } + + public struct LabelCount: Codable, Equatable, Sendable { + public var label: String + /// Boxes carrying this label. + public var boxes: Int + /// Images with at least one box of this label. + public var images: Int + } + + public struct ImageRow: Codable, Equatable, Sendable { + public var image: String + public var status: Status + public var boxes: Int + public var labels: [String] + } + + public enum Status: String, Codable, Sendable { + case annotated, negative, unlabeled, missing + } +} + +public extension DatasetSummary { + static func make( + of document: DatasetDocument, + includePerImage: Bool = false, + labelkitVersion version: String = labelkitVersion + ) -> DatasetSummary { + let onDisk = Set(document.imagesOnDisk) + // A file can list one image twice; summarize what the editor would show. + let records = document.uniqueRecords + let inFile = Set(records.map(\.image)) + + var boxCount: [String: Int] = [:] + var imageCount: [String: Int] = [:] + var totalBoxes = 0 + for record in records { + totalBoxes += record.boxes.count + for box in record.boxes { boxCount[box.label, default: 0] += 1 } + for label in Set(record.boxes.map(\.label)) { imageCount[label, default: 0] += 1 } + } + let labels = boxCount + .map { LabelCount(label: $0.key, boxes: $0.value, images: imageCount[$0.key] ?? 0) } + .sorted { $0.boxes != $1.boxes ? $0.boxes > $1.boxes : $0.label < $1.label } + + var spread: BoxSpread? + let annotatedRecords = records.filter { !$0.boxes.isEmpty } + if let busiest = annotatedRecords.max(by: { $0.boxes.count < $1.boxes.count }) { + let counts = annotatedRecords.map(\.boxes.count).sorted() + let middle = counts.count / 2 + let median = counts.count % 2 == 1 + ? Double(counts[middle]) : Double(counts[middle - 1] + counts[middle]) / 2 + // max(by:) returns the last of equal elements; report the first. + let first = annotatedRecords.first { $0.boxes.count == busiest.boxes.count } ?? busiest + spread = BoxSpread(min: counts[0], median: median, max: busiest.boxes.count, maxImage: first.image) + } + + let unlabeled = document.imagesOnDisk.filter { !inFile.contains($0) } + let missing = records.map(\.image).filter { !onDisk.contains($0) } + let annotated = records.filter { !$0.boxes.isEmpty }.count + + var rows: [ImageRow]? + if includePerImage { + let recordByImage = Dictionary(records.map { ($0.image, $0) }, uniquingKeysWith: { first, _ in first }) + var built: [ImageRow] = document.imagesOnDisk.map { name in + guard let record = recordByImage[name] else { + return ImageRow(image: name, status: .unlabeled, boxes: 0, labels: []) + } + return ImageRow(image: name, status: record.boxes.isEmpty ? .negative : .annotated, + boxes: record.boxes.count, labels: Set(record.boxes.map(\.label)).sorted()) + } + built += records.filter { !onDisk.contains($0.image) }.map { + ImageRow(image: $0.image, status: .missing, boxes: $0.boxes.count, + labels: Set($0.boxes.map(\.label)).sorted()) + } + rows = built + } + + return DatasetSummary( + schemaVersion: 1, labelkit: version, + dataset: document.location.imagesDirectory.path, + annotations: document.location.annotationsURL.path, + annotationsExists: document.location.annotationsExists, + images: ImageCounts( + total: onDisk.union(inFile).count, onDisk: onDisk.count, annotated: annotated, + negatives: records.count - annotated, unlabeled: unlabeled.count, missing: missing.count), + boxes: totalBoxes, boxesPerImage: spread, labels: labels, + unlabeled: unlabeled, missing: missing, perImage: rows) + } +} diff --git a/Sources/LabelKit/Headless/DatasetValidator.swift b/Sources/LabelKit/Headless/DatasetValidator.swift new file mode 100644 index 0000000..59cb941 --- /dev/null +++ b/Sources/LabelKit/Headless/DatasetValidator.swift @@ -0,0 +1,199 @@ +import CoreGraphics +import Foundation + +/// What `labelkit validate` reports. Errors are things that make a dataset +/// wrong to train on; warnings are things worth a look. Nothing here modifies +/// the dataset. +public struct ValidationReport: Codable, Equatable, Sendable { + public var schemaVersion: Int + public var labelkit: String + public var dataset: String + public var annotations: String + /// True when there are no errors (warnings don't count). + public var ok: Bool + public var errors: Int + public var warnings: Int + public var issues: [Issue] + + public struct Issue: Codable, Equatable, Sendable { + public var severity: Severity + /// Stable machine-readable identifier; see `Code`. + public var code: Code + public var image: String? + /// 1-based position of the box within the image's annotations. + public var box: Int? + public var label: String? + public var message: String + } + + public enum Severity: String, Codable, Sendable { case error, warning } + + public enum Code: String, Codable, Sendable, CaseIterable { + /// The annotations file doesn't exist. + case noAnnotationsFile = "no-annotations-file" + /// An entry's image file is not on disk. + case missingImage = "missing-image" + /// An image file exists but its size can't be read. + case unreadableImage = "unreadable-image" + /// The same image has more than one entry. + case duplicateEntry = "duplicate-entry" + /// A box has an empty label. + case emptyLabel = "empty-label" + /// A box has a zero or negative width or height. + case emptyBox = "empty-box" + /// A box lies entirely outside its image. + case boxOutsideImage = "box-outside-image" + /// A box extends past an image edge. + case boxOverflowsImage = "box-overflows-image" + /// Two boxes on an image have the same label and near-identical geometry. + case duplicateBox = "duplicate-box" + /// Two labelled images are the same file under different names. + case duplicateImage = "duplicate-image" + /// A label is not in the allowed set. + case unknownLabel = "unknown-label" + /// An allowed label has no boxes at all. + case unusedLabel = "unused-label" + } +} + +public enum DatasetValidator { + public struct Options: Sendable { + /// When set, any other label is an error and any of these with no boxes + /// is a warning. + public var allowedLabels: [String]? + /// Same-label boxes overlapping by more than this IoU are duplicates. + public var duplicateIoU: CGFloat + /// How far (pixels) a box may hang over an edge before it's reported. + public var overflowTolerance: CGFloat + /// Groups of labelled images with identical file contents (see + /// `DuplicateImages`); each image after the first in a group is reported. + public var duplicateImages: [[String]] + + public init(allowedLabels: [String]? = nil, duplicateIoU: CGFloat = 0.95, + overflowTolerance: CGFloat = 1, duplicateImages: [[String]] = []) { + self.allowedLabels = allowedLabels + self.duplicateIoU = duplicateIoU + self.overflowTolerance = overflowTolerance + self.duplicateImages = duplicateImages + } + } + + /// - Parameter pixelSize: display-orientation size of a dataset image, or + /// nil if it can't be read. Injected so validation stays pure and testable. + public static func validate( + _ document: DatasetDocument, + options: Options = Options(), + labelkitVersion version: String = labelkitVersion, + pixelSize: (String) -> CGSize? + ) -> ValidationReport { + typealias Issue = ValidationReport.Issue + var issues: [Issue] = [] + let onDisk = Set(document.imagesOnDisk) + let allowed = options.allowedLabels.map(Set.init) + + if !document.location.annotationsExists { + issues.append(Issue(severity: .error, code: .noAnnotationsFile, image: nil, box: nil, label: nil, + message: "no annotations file at \(document.location.annotationsURL.path)")) + } + + var seenImages = Set() + var usedLabels = Set() + for record in document.records { + let image = record.image + if !seenImages.insert(image).inserted { + issues.append(Issue(severity: .error, code: .duplicateEntry, image: image, box: nil, label: nil, + message: "more than one entry for this image; only the first is used")) + continue + } + + var size: CGSize? + if !onDisk.contains(image) { + issues.append(Issue(severity: .error, code: .missingImage, image: image, box: nil, label: nil, + message: "image file not found in the dataset directory")) + } else if let read = pixelSize(image) { + size = read + } else { + issues.append(Issue(severity: .warning, code: .unreadableImage, image: image, box: nil, label: nil, + message: "couldn't read the image's size; its boxes weren't bounds-checked")) + } + + let rects = record.boxes.map(\.rect) + for (index, box) in record.boxes.enumerated() { + let number = index + 1 + let rect = rects[index] + usedLabels.insert(box.label) + + if box.label.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { + issues.append(Issue(severity: .error, code: .emptyLabel, image: image, box: number, + label: box.label, message: "box has an empty label")) + } else if let allowed, !allowed.contains(box.label) { + issues.append(Issue(severity: .error, code: .unknownLabel, image: image, box: number, + label: box.label, message: "label '\(box.label)' is not in the allowed set")) + } + + guard box.width > 0, box.height > 0 else { + issues.append(Issue(severity: .error, code: .emptyBox, image: image, box: number, + label: box.label, message: "box has no area (\(describe(box)))")) + continue + } + if let size { + let bounds = CGRect(origin: .zero, size: size) + let inside = rect.intersection(bounds) + let dimensions = "\(Int(size.width))x\(Int(size.height))" + if inside.isNull || inside.width <= 0 || inside.height <= 0 { + issues.append(Issue(severity: .error, code: .boxOutsideImage, image: image, box: number, + label: box.label, + message: "box lies outside the \(dimensions) image (\(describe(box)))")) + } else if !bounds.insetBy(dx: -options.overflowTolerance, dy: -options.overflowTolerance) + .contains(rect) { + issues.append(Issue(severity: .warning, code: .boxOverflowsImage, image: image, box: number, + label: box.label, + message: "box extends past the edge of the \(dimensions) image (\(describe(box)))")) + } + } + // Report each duplicate once, on the later box. + if let earlier = (0.. options.duplicateIoU + }) { + issues.append(Issue(severity: .warning, code: .duplicateBox, image: image, box: number, + label: box.label, + message: "near-identical to box #\(earlier + 1) with the same label")) + } + } + } + + // The same photo under two names: flag the copies, and say when the + // copies were labelled differently, since that is the harmful case. + let boxesByImage = Dictionary( + uniqueKeysWithValues: document.uniqueRecords.map { ($0.image, $0.boxes) }) + for group in options.duplicateImages { + guard let original = group.first else { continue } + for copy in group.dropFirst() { + let differ = boxesByImage[copy] != boxesByImage[original] + issues.append(Issue( + severity: .warning, code: .duplicateImage, image: copy, box: nil, label: nil, + message: "same file contents as '\(original)'" + + (differ ? ", and the two are labelled differently" : ""))) + } + } + + for label in (options.allowedLabels ?? []) where !usedLabels.contains(label) { + issues.append(Issue(severity: .warning, code: .unusedLabel, image: nil, box: nil, label: label, + message: "no boxes carry the label '\(label)'")) + } + + let errors = issues.filter { $0.severity == .error }.count + return ValidationReport( + schemaVersion: 1, labelkit: version, + dataset: document.location.imagesDirectory.path, + annotations: document.location.annotationsURL.path, + ok: errors == 0, errors: errors, warnings: issues.count - errors, issues: issues) + } + + private static func describe(_ box: BoxRecord) -> String { + let rect = box.rect + return "x=\(CreateMLWriter.coordString(rect.minX)) y=\(CreateMLWriter.coordString(rect.minY)) " + + "width=\(CreateMLWriter.coordString(box.width)) height=\(CreateMLWriter.coordString(box.height))" + } +} diff --git a/Sources/LabelKit/Headless/DuplicateImages.swift b/Sources/LabelKit/Headless/DuplicateImages.swift new file mode 100644 index 0000000..cce3bef --- /dev/null +++ b/Sources/LabelKit/Headless/DuplicateImages.swift @@ -0,0 +1,60 @@ +import CryptoKit +import Foundation + +/// Finds image files with byte-identical contents under different names — the +/// same photo saved twice. In a training set these are worse than wasted +/// space: the copies can carry different boxes, and one can land on each side +/// of a train/validation split. +/// +/// Built to cost almost nothing when there are no duplicates: files are +/// grouped by size first (one `stat` each), and only files that share a size +/// with another are read and hashed, in parallel. +public enum DuplicateImages { + /// Groups of two or more filenames whose files are identical, each group in + /// the order the names were given; groups ordered by their first member. + public static func groups(in directory: URL, filenames: [String]) -> [[String]] { + /// A file on disk, whatever name reached it. Several names can be one + /// file (symlinks, hard links); those are trivially identical and are + /// read once. + struct FileID: Hashable { var device: dev_t; var inode: ino_t } + struct Candidate { var index: Int; var file: FileID } + + // `stat` follows symlinks and gives size and identity in one call. + let base = directory.path + var bySize: [off_t: [Candidate]] = [:] + for (index, name) in filenames.enumerated() { + var info = stat() + guard stat(base + "/" + name, &info) == 0 else { continue } + bySize[info.st_size, default: []].append( + Candidate(index: index, file: FileID(device: info.st_dev, inode: info.st_ino))) + } + + // Only files sharing a size can be identical, so only those are read. + let suspects = bySize.values.filter { $0.count > 1 }.flatMap { $0 } + guard !suspects.isEmpty else { return [] } + var representative: [FileID: Int] = [:] + for candidate in suspects where representative[candidate.file] == nil { + representative[candidate.file] = candidate.index + } + let files = Array(representative.keys) + let digests = files.concurrentMap { file -> SHA256.Digest? in + let url = URL(fileURLWithPath: base + "/" + filenames[representative[file]!]) + return (try? Data(contentsOf: url, options: .mappedIfSafe)).map(SHA256.hash(data:)) + } + var digestByFile: [FileID: SHA256.Digest] = [:] + for (file, digest) in zip(files, digests) { + if let digest { digestByFile[file] = digest } + } + + var byContent: [SHA256.Digest: [Int]] = [:] + for candidate in suspects { + guard let digest = digestByFile[candidate.file] else { continue } + byContent[digest, default: []].append(candidate.index) + } + return byContent.values + .filter { $0.count > 1 } + .map { $0.sorted() } + .sorted { $0[0] < $1[0] } + .map { $0.map { filenames[$0] } } + } +} diff --git a/Sources/LabelKit/Model/BoundingBox.swift b/Sources/LabelKit/Model/BoundingBox.swift index 0260dfa..ca76f3d 100644 --- a/Sources/LabelKit/Model/BoundingBox.swift +++ b/Sources/LabelKit/Model/BoundingBox.swift @@ -24,16 +24,7 @@ public struct BoundingBox: Identifiable, Equatable, Sendable { } public init(record: BoxRecord) { - self.init( - label: record.label, - rect: CGRect( - x: record.x - record.width / 2, - y: record.y - record.height / 2, - width: record.width, - height: record.height - ), - extras: record.extras - ) + self.init(label: record.label, rect: record.rect, extras: record.extras) } public var record: BoxRecord { diff --git a/Sources/LabelKitApp/AnnotateCommand.swift b/Sources/LabelKitApp/AnnotateCommand.swift new file mode 100644 index 0000000..4446c7c --- /dev/null +++ b/Sources/LabelKitApp/AnnotateCommand.swift @@ -0,0 +1,245 @@ +import ArgumentParser +import Foundation +import LabelKit + +/// `labelkit annotate` — write boxes into a dataset from the terminal. The +/// headless counterpart of drawing boxes in the editor: input goes through the +/// same writer, so everything the editor guarantees about the file (order, +/// unknown keys, negatives, byte-stable output) holds here too. +struct AnnotateCommand: ParsableCommand { + static let configuration = CommandConfiguration( + commandName: "annotate", + abstract: "Add or replace boxes in a dataset from JSON, NDJSON or --box flags.", + discussion: """ + Give boxes one of two ways: + + --from FILE JSON, a JSON array, or NDJSON; '-' reads stdin. Each entry + names an image and lists its boxes: + {"image": "a.jpg", "boxes": [ + {"label": "cat", "x": 40, "y": 30, "width": 200, "height": 160}]} + The output of 'labelkit detect' and Create ML annotations + files are accepted as they are. + With --image NAME the input is that one image's boxes, + so a model's bare answer works as it is: + [{"label": "cat", "xyxy": [40, 30, 240, 190]}] + --image NAME --box 'label:x,y,width,height' [--box …] + boxes for one image, straight on the command line. + + By default four numbers are x, y, width, height with x,y the box's + TOP-LEFT corner, in pixels of the image file. If your boxes use another + convention, say so instead of converting them: + --order xyxy two corners: x1,y1,x2,y2 + --anchor center x,y is the box centre + --units normalized fractions of the image, 0-1 + --units 0-1000 0-1000 across the image + --image-size 1568x1176 pixels of a resized copy that size + --units normalized --anchor center YOLO + --units normalized --origin bottom-left Apple Vision + + Shapes that say what they are need no flags: "coordinates" (Create ML), + "box_2d" (Gemini: y first, 0-1000), "xyxy", x1/y1/x2/y2 keys, and COCO + files. An entry's own "width"/"height" work like --image-size. + + Examples: + labelkit annotate ./cards --from boxes.json + labelkit detect ./cards --detector rectangles --format ndjson \\ + | labelkit annotate ./cards --from - + labelkit annotate ./cards --image a.jpg --box 'card:40,30,200,160' + labelkit annotate ./cards --image a.jpg -l card --box 40,30,200,160 + labelkit annotate ./cards --image a.jpg --from model-answer.json + labelkit annotate ./cards --from coco.json + labelkit annotate ./cards --from boxes.json --mode replace --dry-run + + The default mode, add, keeps existing boxes and skips any new box that + is already there (same label, overlapping), so running the same input + twice changes nothing. replace gives the listed images exactly the boxes + supplied and leaves every other image alone. + + If any input can't be applied (unknown image, a box outside its image), + nothing is written and the command exits 1; --lenient applies the rest. + Boxes that hang over an image edge are trimmed to fit and counted as + "clamped". + + stdout carries a JSON report of what changed. Exit 0 on success, 1 when + there were problems, 64 for a usage error. + """) + + @Argument(help: "Dataset directory, or path to an annotations .json file.") + var path: String + + @Option(name: .long, help: "Explicit annotations.json path (overrides auto-detection).") + var annotations: String? + + @Option(name: .long, help: "Read boxes from this JSON/NDJSON file; '-' for stdin.") + var from: String? + + @Option(name: .long, help: "The one image all the given boxes belong to (a filename in the dataset).") + var image: String? + + @Option(name: .long, help: "A box as 'label:x,y,width,height' (top-left corner, pixels). Repeatable.") + var box: [String] = [] + + @Option(name: .long, help: "What the numbers are measured in: pixel, normalized (0-1), 0-1000, or percent.") + var units: BoxConvention.Units = .pixel + + @Option(name: .long, help: "What four bare numbers mean: xywh, xyxy (two corners), or yxyx (two corners, y first).") + var order: BoxConvention.Order = .xywh + + @Option(name: .long, help: "Size of the picture the pixel coordinates refer to, as WxH, when it isn't the file's own size.") + var imageSize: String? + + @Option(name: .long, help: "Where y=0 is: top-left, or bottom-left (Apple Vision; normalized units only).") + var origin: BoxConvention.Origin = .topLeft + + @Option(name: .long, help: "What x,y points at: the box corner nearest the origin, or its center (Create ML, YOLO).") + var anchor: BoxConvention.Anchor = .corner + + @Option(name: [.customShort("l"), .long], help: "Label for boxes that don't carry one.") + var label: String? + + @Option(name: .long, help: "add: keep existing boxes, skip duplicates. replace: listed images get exactly these boxes.") + var mode: AnnotationMerge.Mode = .add + + @Flag(name: .long, help: "Record an image given with no boxes as a negative example.") + var negatives = false + + @Flag(name: .long, help: "Report what would change without writing the file.") + var dryRun = false + + @Flag(name: .long, help: "Apply the input that is valid instead of refusing the whole run.") + var lenient = false + + @Option(name: .long, help: "Output format: json or text.") + var format: Headless.OutputFormat = .json + + func validate() throws { + if image == nil, !box.isEmpty { + throw ValidationError("--box needs --image to say which image the boxes belong to.") + } + if !box.isEmpty, from != nil { + throw ValidationError("Use either --from or --box, not both.") + } + if let imageSize, BoxImportParser.parseSize(imageSize) == nil { + throw ValidationError("--image-size must look like 1568x1176.") + } + if let reason = convention.unsupportedReason { + throw ValidationError("--origin \(origin.rawValue) with --units \(units.rawValue): \(reason).") + } + } + + private var convention: BoxConvention { + BoxConvention(units: units, origin: origin, anchor: anchor, order: order, + referenceSize: imageSize.flatMap(BoxImportParser.parseSize)) + } + + private var parserOptions: BoxImportParser.Options { + let trimmed = label?.trimmingCharacters(in: .whitespaces) ?? "" + return .init(convention: convention, defaultLabel: trimmed.isEmpty ? nil : trimmed, image: image) + } + + func run() throws { + // Read the boxes first: knowing which images they name lets the dataset + // open without listing its whole directory. + let imports = try readImports() + var document = try Headless.openDocument( + path: path, annotations: annotations, onlyImages: imports.map(\.image)) + + // Sizes are needed to scale normalized boxes and to keep every box + // inside its image; one parallel header-only pass covers the run. + let onDisk = Set(document.imagesOnDisk) + let sizes = document.pixelSizes(of: imports.map(\.image).uniqued().filter(onDisk.contains)) + + let result = AnnotationMerge.apply( + imports, to: &document, + options: .init(mode: mode, recordNegatives: negatives), + pixelSize: { sizes[$0] }) + + let blocked = !result.problems.isEmpty && !lenient + let shouldWrite = result.changed && !dryRun && !blocked + if shouldWrite { + do { try document.save() } catch { + Headless.note("couldn't write \(document.location.annotationsURL.path): \(Headless.describe(error))") + throw ExitCode(1) + } + } + + let report = AnnotateReport.make( + document: document, result: result, mode: mode, dryRun: dryRun, written: shouldWrite) + switch format { + case .json: Headless.printJSON(report) + case .text: print(text(report)) + } + if blocked { + Headless.note("nothing written: \(result.problems.count) problem(s) in the input " + + "(--lenient applies the rest)") + } + if !result.problems.isEmpty { throw ExitCode(1) } + } + + // MARK: - Input + + private func readImports() throws -> [ImportedImage] { + // --image with --box flags (or with nothing piped in: an explicit + // "this image has no boxes") is complete on its own. + if let image, from == nil, !box.isEmpty || isatty(FileHandle.standardInput.fileDescriptor) != 0 { + do { + let boxes = try box.map { try BoxImportParser.parseInlineBox($0, options: parserOptions) } + return [ImportedImage(image: image, boxes: boxes)] + } catch { + throw ValidationError(Headless.describe(error)) + } + } + + let data: Data + switch from { + case "-"?: + data = FileHandle.standardInput.readDataToEndOfFile() + case let file?: + let url = URL(fileURLWithPath: (file as NSString).expandingTildeInPath) + guard let contents = try? Data(contentsOf: url) else { + throw ValidationError("Couldn't read \(file).") + } + data = contents + case nil: + // No --from: take piped input, but never block waiting on a terminal. + guard isatty(FileHandle.standardInput.fileDescriptor) == 0 else { + throw ValidationError("Give boxes with --from (or '-' for stdin), or --image with --box.") + } + data = FileHandle.standardInput.readDataToEndOfFile() + } + do { + let parsed = try BoxImportParser.parse(data, options: parserOptions) + // Naming an image and supplying nothing still means "this image, + // no boxes" (agents rarely have a terminal on stdin). + if parsed.isEmpty, let image { return [ImportedImage(image: image, boxes: [])] } + return parsed + } catch { + throw ValidationError("Couldn't read the boxes: \(Headless.describe(error))") + } + } + + // MARK: - Output + + private func text(_ report: AnnotateReport) -> String { + var lines = report.images.map { outcome -> String in + var parts = ["+\(outcome.added)"] + if outcome.removed > 0 { parts.append("-\(outcome.removed)") } + if outcome.duplicates > 0 { parts.append("\(outcome.duplicates) already there") } + if outcome.clamped > 0 { parts.append("\(outcome.clamped) clamped") } + return "\(outcome.image) \(parts.joined(separator: ", ")) (\(outcome.total) total)" + } + lines += report.problems.map { "problem \($0.image): \($0.message)" } + let verb = report.dryRun ? "would add" : "added" + var summary = "\(verb) \(report.totals.added) box\(report.totals.added == 1 ? "" : "es") " + + "across \(report.totals.images) image\(report.totals.images == 1 ? "" : "s")" + if !report.written, !report.dryRun { summary += " — file not changed" } + lines.append(summary) + return lines.joined(separator: "\n") + } +} + +extension AnnotationMerge.Mode: ExpressibleByArgument {} +extension BoxConvention.Units: ExpressibleByArgument {} +extension BoxConvention.Origin: ExpressibleByArgument {} +extension BoxConvention.Anchor: ExpressibleByArgument {} +extension BoxConvention.Order: ExpressibleByArgument {} diff --git a/Sources/LabelKitApp/AppState.swift b/Sources/LabelKitApp/AppState.swift index 5c40bdd..7862548 100644 --- a/Sources/LabelKitApp/AppState.swift +++ b/Sources/LabelKitApp/AppState.swift @@ -45,15 +45,18 @@ final class AppState { recentProjects = RecentProjects(defaults: defaults) recentLocations = recentProjects.locations if let location = launch.location { - open(location: location) + open(location: location, select: launch.select) } } - func open(location: DatasetLocation) { + /// - Parameter select: image to show first, if the dataset has it; + /// otherwise (and by default) the first image in the list. + func open(location: DatasetLocation, select: String? = nil) { do { let opened = try DatasetStore(location: location, imageGlob: imageGlob) store = opened - selectSingle(opened.entries.first?.filename) + let requested = select.flatMap { opened.entry(for: $0)?.filename } + selectSingle(requested ?? opened.entries.first?.filename) loadError = nil recentProjects.record(opened.location) recentLocations = recentProjects.locations @@ -149,10 +152,14 @@ final class AppState { /// A CLI invocation forwarded from another process — adopts that /// invocation's glob (nil = unfiltered), matching fresh-launch semantics. - func requestOpenFromCLI(_ location: DatasetLocation, imageGlob newGlob: String?) { + /// + /// Opening the dataset that is already open is how the window catches up + /// with changes made outside it (`labelkit annotate`): it reloads from + /// disk, and `select` then lands on the image to look at. + func requestOpenFromCLI(_ location: DatasetLocation, imageGlob newGlob: String?, select: String? = nil) { guard confirmDiscardIfDirty() else { return } imageGlob = newGlob - open(location: location) + open(location: location, select: select) } func removeRecent(_ location: DatasetLocation) { diff --git a/Sources/LabelKitApp/DetectCommand.swift b/Sources/LabelKitApp/DetectCommand.swift index de72455..4b6d0e0 100644 --- a/Sources/LabelKitApp/DetectCommand.swift +++ b/Sources/LabelKitApp/DetectCommand.swift @@ -74,7 +74,7 @@ struct DetectCommand: ParsableCommand { imageURL: imageURL, detector: spec.detector, maxDecodePixel: CGFloat(maxPixel), fallbackLabel: fallback) } catch { - warn("\(imageURL.lastPathComponent): \(describe(error))") + Headless.note("\(imageURL.lastPathComponent): \(Headless.describe(error))") continue // skip a bad image, keep processing the batch } @@ -86,7 +86,7 @@ struct DetectCommand: ParsableCommand { pixelSize: result.pixelSize, detections: detections) reports.append(report) - if format == .ndjson { print(encode(report, pretty: false)) } // stream as we go + if format == .ndjson { print(Headless.json(report, pretty: false)) } // stream as we go if render != nil { try renderAnnotated(imageURL: imageURL, pixelSize: result.pixelSize, detections: detections, batch: images.count > 1) @@ -99,9 +99,9 @@ struct DetectCommand: ParsableCommand { case .json: // A single image emits the object; a batch emits an array. if images.count == 1, let only = reports.first { - print(encode(only, pretty: true)) + print(Headless.json(only, pretty: true)) } else { - print(encode(reports, pretty: true)) + print(Headless.json(reports, pretty: true)) } case .text: print(renderText(reports)) @@ -131,7 +131,7 @@ struct DetectCommand: ParsableCommand { let coreML = try CoreMLBoxDetector(modelURL: url) return DetectorSpec(detector: coreML, name: coreML.name, source: "coreml") } catch { - throw ValidationError("Couldn't load model \(path): \(describe(error))") + throw ValidationError("Couldn't load model \(path): \(Headless.describe(error))") } case let (nil, kind?): // ArgumentParser already rejected any name outside the enum (and @@ -169,19 +169,19 @@ struct DetectCommand: ParsableCommand { detections: [DetectionCandidate], batch: Bool) throws { guard let render else { return } guard let image = ImageDownsampler.decode(url: imageURL, maxPixel: CGFloat(maxPixel)) else { - warn("\(imageURL.lastPathComponent): couldn't decode for --render") + Headless.note("\(imageURL.lastPathComponent): couldn't decode for --render") return } let boxes = detections.map { RenderableBox(rect: $0.box.rect, label: $0.box.label, confidence: $0.confidence) } guard let png = BoxRenderer.renderPNG(image: image, sourceSize: pixelSize, boxes: boxes) else { - warn("\(imageURL.lastPathComponent): couldn't render overlay") + Headless.note("\(imageURL.lastPathComponent): couldn't render overlay") return } let outputURL = try renderDestination(for: imageURL, batch: batch, dest: render) try png.write(to: outputURL) - warn("wrote \(outputURL.path)") + Headless.note("wrote \(outputURL.path)") } /// A file when rendering one image to a `.png` path; otherwise a directory @@ -206,16 +206,7 @@ struct DetectCommand: ParsableCommand { && isDirectory.boolValue } - // MARK: - Encoding - - private func encode(_ value: T, pretty: Bool) -> String { - let encoder = JSONEncoder() - encoder.outputFormatting = pretty - ? [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes] - : [.sortedKeys, .withoutEscapingSlashes] - guard let data = try? encoder.encode(value) else { return "" } - return String(decoding: data, as: UTF8.self) - } + // MARK: - Text output private func renderText(_ reports: [DetectionReport]) -> String { var lines: [String] = [] @@ -232,23 +223,6 @@ struct DetectCommand: ParsableCommand { } return lines.joined(separator: "\n") } - - // MARK: - Diagnostics - - private func warn(_ message: String) { - FileHandle.standardError.write(Data("labelkit: \(message)\n".utf8)) - } - - private func describe(_ error: Error) -> String { - (error as? LocalizedError)?.errorDescription ?? "\(error)" - } -} - -private extension String { - /// Left-justify to `width` for aligned text output (never truncates). - func padded(to width: Int) -> String { - count >= width ? self : self + String(repeating: " ", count: width - count) - } } // Teach ArgumentParser the built-in detectors: because `Kind` is a diff --git a/Sources/LabelKitApp/HeadlessSupport.swift b/Sources/LabelKitApp/HeadlessSupport.swift new file mode 100644 index 0000000..db809d8 --- /dev/null +++ b/Sources/LabelKitApp/HeadlessSupport.swift @@ -0,0 +1,68 @@ +import ArgumentParser +import Foundation +import LabelKit + +/// Shared plumbing for the scripted subcommands (`stats`, `validate`, +/// `annotate`, `render`). They follow one contract, the same one `detect` +/// established, so a script or an agent only has to learn it once: +/// +/// - stdout carries the result and nothing else; notes go to stderr. +/// - Exit 0 on success, 1 when the command ran but found or hit a problem +/// (the JSON on stdout says what), 64 for a usage error. +/// - Never touches AppKit. +enum Headless { + enum OutputFormat: String, ExpressibleByArgument, CaseIterable { + case json, text + } + + /// Open a dataset for scripted work, turning "not a dataset" into a usage + /// error (exit 64) rather than a crash-style failure. + static func openDocument(path: String, annotations: String?, + onlyImages: [String]? = nil) throws -> DatasetDocument { + do { + guard let location = try DatasetLocator.resolve(path: path, annotationsOverride: annotations) else { + throw ValidationError("Specify a dataset directory or an annotations .json file.") + } + return try DatasetDocument(location: location, onlyImages: onlyImages) + } catch let error as ValidationError { + throw error + } catch { + throw ValidationError(describe(error)) + } + } + + /// Stable JSON for stdout: sorted keys, so two runs diff cleanly. Compact + /// (`pretty: false`) is one line, for NDJSON. + static func json(_ value: T, pretty: Bool = true) -> String { + let encoder = JSONEncoder() + encoder.outputFormatting = pretty + ? [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes] + : [.sortedKeys, .withoutEscapingSlashes] + guard let data = try? encoder.encode(value) else { return "" } + return String(decoding: data, as: UTF8.self) + } + + static func printJSON(_ value: T) { + print(json(value)) + } + + static func note(_ message: String) { + FileHandle.standardError.write(Data("labelkit: \(message)\n".utf8)) + } + + static func describe(_ error: Error) -> String { + (error as? LocalizedError)?.errorDescription ?? "\(error)" + } +} + +extension String { + /// Left-justify to `width` for aligned text output (never truncates). + func padded(to width: Int) -> String { + count >= width ? self : self + String(repeating: " ", count: width - count) + } + + /// Right-justify to `width` (never truncates). + func leftPadded(to width: Int) -> String { + count >= width ? self : String(repeating: " ", count: width - count) + self + } +} diff --git a/Sources/LabelKitApp/LabelKitApp.swift b/Sources/LabelKitApp/LabelKitApp.swift index 8fc0b46..9c1f2f8 100644 --- a/Sources/LabelKitApp/LabelKitApp.swift +++ b/Sources/LabelKitApp/LabelKitApp.swift @@ -82,7 +82,7 @@ final class AppController: NSObject, NSApplicationDelegate, NSWindowDelegate, NS window.makeKeyAndOrderFront(nil) Self.tryActivate() guard let request = SingleInstance.decodeOpenRequest(note) else { return } - appState.requestOpenFromCLI(request.location, imageGlob: request.imageGlob) + appState.requestOpenFromCLI(request.location, imageGlob: request.imageGlob, select: request.select) } private static func tryActivate() { diff --git a/Sources/LabelKitApp/LabelKitCommand.swift b/Sources/LabelKitApp/LabelKitCommand.swift index e262050..c4804dc 100644 --- a/Sources/LabelKitApp/LabelKitCommand.swift +++ b/Sources/LabelKitApp/LabelKitCommand.swift @@ -11,7 +11,11 @@ struct LabelKitCommand: ParsableCommand { commandName: "labelkit", abstract: "Annotate image datasets in Apple Create ML object-detection format.", version: labelkitVersion, - subcommands: [OpenCommand.self, DetectCommand.self, TrainCommand.self], + subcommands: [ + OpenCommand.self, DetectCommand.self, TrainCommand.self, + StatsCommand.self, ValidateCommand.self, AnnotateCommand.self, RenderCommand.self, + SkillCommand.self, + ], defaultSubcommand: OpenCommand.self ) } @@ -34,6 +38,9 @@ struct OpenCommand: ParsableCommand { @Option(name: .long, help: "Glob filter for image filenames, e.g. '*.jpg'.") var images: String? + @Option(name: .long, help: "Image to show first (a filename in the dataset). With the editor already open, reloads the dataset and jumps to it.") + var select: String? + @Flag(name: [.customShort("w"), .long], help: "Run one foreground instance tied to the window's lifetime — don't hand off to a running copy or relaunch via the .app. Blocks until the window closes. (Handy for scripting and tests.)") var wait = false @@ -54,7 +61,7 @@ struct OpenCommand: ParsableCommand { let handedOff = MainActor.assumeIsolated { () -> Bool in guard let running = SingleInstance.runningInstance() else { return false } if let location { - SingleInstance.postOpenRequest(location: location, imageGlob: images) + SingleInstance.postOpenRequest(location: location, imageGlob: images, select: select) } SingleInstance.activate(running) return true @@ -73,6 +80,7 @@ struct OpenCommand: ParsableCommand { arguments.append(contentsOf: ["--annotations", location.annotationsURL.path]) } if let images { arguments.append(contentsOf: ["--images", images]) } + if let select { arguments.append(contentsOf: ["--select", select]) } let open = Process() open.executableURL = URL(fileURLWithPath: "/usr/bin/open") open.arguments = arguments @@ -83,7 +91,7 @@ struct OpenCommand: ParsableCommand { } } - LaunchContext.current = LaunchContext(location: location, imageGlob: images) + LaunchContext.current = LaunchContext(location: location, imageGlob: images, select: select) MainActor.assumeIsolated { runLabelKitApp() } // never returns } diff --git a/Sources/LabelKitApp/LaunchContext.swift b/Sources/LabelKitApp/LaunchContext.swift index a217981..6b46ad0 100644 --- a/Sources/LabelKitApp/LaunchContext.swift +++ b/Sources/LabelKitApp/LaunchContext.swift @@ -5,9 +5,11 @@ import LabelKit /// LabelKitApp.main() starts the run loop. The one deliberately non-injected /// global — everything downstream takes explicit parameters. struct LaunchContext { - static var current = LaunchContext(location: nil, imageGlob: nil) + static var current = LaunchContext(location: nil, imageGlob: nil, select: nil) /// nil → the app shows an open panel. let location: DatasetLocation? let imageGlob: String? + /// Image to show first (`--select`); nil → the first in the list. + let select: String? } diff --git a/Sources/LabelKitApp/RenderCommand.swift b/Sources/LabelKitApp/RenderCommand.swift new file mode 100644 index 0000000..1411c9f --- /dev/null +++ b/Sources/LabelKitApp/RenderCommand.swift @@ -0,0 +1,180 @@ +import ArgumentParser +import CoreGraphics +import Foundation +import LabelKit + +/// `labelkit render` — draw a dataset's existing boxes onto its images and +/// write the pictures out. This is the "look at it" step for an agent with +/// vision: annotate, render, open the picture, correct what's wrong. +struct RenderCommand: ParsableCommand { + static let configuration = CommandConfiguration( + commandName: "render", + abstract: "Write images with their boxes drawn on, to check labels by eye.", + discussion: """ + Examples: + labelkit render ./cards --out /tmp/check + labelkit render ./cards a.jpg b.jpg --out /tmp/check + labelkit render ./cards --out /tmp/check --limit 20 --image-format png + labelkit render ./cards --unlabeled --grid 100 --out /tmp/todo + + With no image names, every image that has an entry in the annotations + file is rendered (cap it with --limit). Output files are named after the + image: a.heic → /a.jpg; the JSON on stdout gives each one's path. + Each label keeps the same colour from run to run. + + Renders are downscaled to --max-pixel on the longest edge and written as + JPEG by default: small and quick to produce, and plenty to judge a box + by. Boxes are numbered in file order (#1, #2, …), matching 'validate'. + + --grid N draws a labelled line every N pixels of the ORIGINAL image, so + coordinates read off a render are already the pixel coordinates + 'annotate' expects, whatever size the render is. The JSON also reports + each image's real width and height. + + stdout carries a JSON list of what was written. Exit 0 on success, 1 if + any image couldn't be rendered, 64 for a usage error. + """) + + @Argument(help: "Dataset directory, or path to an annotations .json file.") + var path: String + + @Argument(help: "Image filenames to render. Default: every image with an entry.") + var images: [String] = [] + + @Option(name: [.customShort("o"), .long], help: "Directory to write the rendered images into (created if needed).") + var out: String + + @Option(name: .long, help: "Explicit annotations.json path (overrides auto-detection).") + var annotations: String? + + @Option(name: .long, help: "Render at most this many images.") + var limit: Int? + + @Flag(name: .long, help: "Render the images that have no entry yet instead (to label them from the picture).") + var unlabeled = false + + @Option(name: .long, help: "Overlay a coordinate grid: a labelled line every N image pixels.") + var grid: Double? + + @Option(name: .long, help: "Longest edge of each render, in pixels.") + var maxPixel: Double = 1280 + + @Option(name: .long, help: "Encoding of the rendered files: jpg or png.") + var imageFormat: ImageFormat = .jpg + + enum ImageFormat: String, ExpressibleByArgument, CaseIterable { + case jpg, png + } + + struct Report: Encodable { + var schemaVersion = 1 + var labelkit = labelkitVersion + var out: String + var rendered: [Rendered] + var failed: [Failure] + + struct Rendered: Encodable { + var image: String + var output: String + var boxes: Int + /// Size of the source image, in the pixels boxes are measured in. + var width: Int + var height: Int + } + + struct Failure: Encodable { + var image: String + var message: String + } + } + + func run() throws { + let document = try Headless.openDocument(path: path, annotations: annotations) + let onDisk = Set(document.imagesOnDisk) + let boxesByImage = Dictionary( + uniqueKeysWithValues: document.uniqueRecords.map { ($0.image, $0.boxes) }) + + var targets: [String] + if unlabeled { + guard images.isEmpty else { + throw ValidationError("Use either image names or --unlabeled, not both.") + } + targets = document.imagesOnDisk.filter { boxesByImage[$0] == nil } + } else if images.isEmpty { + targets = document.uniqueRecords.map(\.image).filter(onDisk.contains) + } else { + if let unknown = images.first(where: { !onDisk.contains($0) }) { + throw ValidationError("No such image in the dataset: \(unknown)") + } + targets = images + } + targets = targets.uniqued() + if let limit { targets = Array(targets.prefix(max(0, limit))) } + + let outURL = URL(fileURLWithPath: (out as NSString).expandingTildeInPath) + do { + try FileManager.default.createDirectory(at: outURL, withIntermediateDirectories: true) + } catch { + throw ValidationError("Couldn't create \(out): \(Headless.describe(error))") + } + + let encoding: BoxRenderer.Encoding = imageFormat == .png ? .png : .jpeg(quality: 0.82) + let edge = CGFloat(maxPixel) + if let grid, grid <= 0 { throw ValidationError("--grid must be a positive number of pixels.") } + let overlay = grid.map { RenderGrid(spacing: CGFloat($0)) } + + // Decode + draw + encode is the whole cost and each image is + // independent, so fan out across cores. + let outputs = BoxRenderer.outputNames(for: targets, fileExtension: encoding.fileExtension) + let results = Array(zip(targets, outputs)).concurrentMap(maxConcurrency: Self.maxDecodes) { name, file in + Self.renderOne(name: name, document: document, boxes: boxesByImage[name] ?? [], + maxPixel: edge, grid: overlay, encoding: encoding, + output: outURL.appendingPathComponent(file)) + } + + var report = Report(out: outURL.path, rendered: [], failed: []) + for (name, result) in zip(targets, results) { + switch result { + case .success(let rendered): report.rendered.append(rendered) + case .failure(let error): report.failed.append(.init(image: name, message: error.message)) + } + } + Headless.printJSON(report) + if !report.failed.isEmpty { throw ExitCode(1) } + } + + /// Images decoded at once. Each one in flight holds its bitmaps, so this — + /// not the core count — bounds the peak memory of a render of very large + /// photos. Measured on 12-megapixel images, six is within a quarter of + /// the all-cores speed. + private static let maxDecodes = 6 + + private struct RenderError: Error { var message: String } + + private static func renderOne( + name: String, document: DatasetDocument, boxes: [BoxRecord], + maxPixel: CGFloat, grid: RenderGrid?, encoding: BoxRenderer.Encoding, output: URL + ) -> Result { + let url = document.imageURL(for: name) + guard let size = ImageMetadata.pixelSize(of: url), + let image = ImageDownsampler.decode(url: url, maxPixel: maxPixel) else { + return .failure(RenderError(message: "couldn't decode the image")) + } + // Number the boxes the way `validate` does (#1, #2, … in file order) so + // a problem report and a picture can be matched up. + let renderable = boxes.enumerated().map { index, box in + RenderableBox(rect: box.rect, label: box.label, caption: "#\(index + 1) \(box.label)") + } + guard let data = BoxRenderer.render(image: image, sourceSize: size, boxes: renderable, + grid: grid, as: encoding) else { + return .failure(RenderError(message: "couldn't draw the overlay")) + } + do { + try data.write(to: output, options: .atomic) + } catch { + return .failure(RenderError(message: "couldn't write \(output.path)")) + } + return .success(.init(image: name, output: output.path, boxes: boxes.count, + width: Int(size.width), height: Int(size.height))) + } +} diff --git a/Sources/LabelKitApp/SingleInstance.swift b/Sources/LabelKitApp/SingleInstance.swift index 813781c..194a926 100644 --- a/Sources/LabelKitApp/SingleInstance.swift +++ b/Sources/LabelKitApp/SingleInstance.swift @@ -24,17 +24,20 @@ enum SingleInstance { .first { $0.processIdentifier != ProcessInfo.processInfo.processIdentifier } } - static func postOpenRequest(location: DatasetLocation, imageGlob: String?) { + static func postOpenRequest(location: DatasetLocation, imageGlob: String?, select: String?) { var info: [String: String] = [ "imagesDirectory": location.imagesDirectory.path, "annotationsURL": location.annotationsURL.path, ] if let imageGlob { info["imageGlob"] = imageGlob } + if let select { info["select"] = select } DistributedNotificationCenter.default().postNotificationName( openRequestNotification, object: nil, userInfo: info, deliverImmediately: true) } - static func decodeOpenRequest(_ note: Notification) -> (location: DatasetLocation, imageGlob: String?)? { + static func decodeOpenRequest( + _ note: Notification + ) -> (location: DatasetLocation, imageGlob: String?, select: String?)? { guard let info = note.userInfo, let directory = info["imagesDirectory"] as? String, let annotations = info["annotationsURL"] as? String else { return nil } @@ -42,7 +45,7 @@ enum SingleInstance { imagesDirectory: URL(fileURLWithPath: directory), annotationsURL: URL(fileURLWithPath: annotations), annotationsExists: FileManager.default.fileExists(atPath: annotations)) - return (location, info["imageGlob"] as? String) + return (location, info["imageGlob"] as? String, info["select"] as? String) } /// Activate through LaunchServices — macOS 14+ cooperative activation diff --git a/Sources/LabelKitApp/SkillCommand.swift b/Sources/LabelKitApp/SkillCommand.swift new file mode 100644 index 0000000..0d6295f --- /dev/null +++ b/Sources/LabelKitApp/SkillCommand.swift @@ -0,0 +1,82 @@ +import ArgumentParser +import Foundation +import LabelKit + +/// `labelkit skill` — hand an AI agent its instructions for using labelkit. +/// The guide is compiled in, so it always matches this version's commands. +struct SkillCommand: ParsableCommand { + static let configuration = CommandConfiguration( + commandName: "skill", + abstract: "Print or install the guide that teaches an AI agent to use labelkit.", + discussion: """ + With no options, prints the guide (an Agent Skill, SKILL.md) to stdout. + + Examples: + labelkit skill # read it + labelkit skill --install # for every agent client, for your user + labelkit skill --install --project # for this project only (commit it) + labelkit skill --install --dir ~/.config/opencode/skills + labelkit skill --snippet >> AGENTS.md + + --install writes labelkit/SKILL.md into the two places agent clients + look: .agents/skills (Codex, Cursor, opencode, Gemini CLI, GitHub + Copilot, Amp, Goose and others) and .claude/skills (Claude Code) — + under your home directory, or under the current directory with + --project. Re-run it after upgrading labelkit to refresh the guide. + + --snippet prints a few lines for a project's AGENTS.md instead: enough + for any agent that can run shell commands, with or without skills. + """) + + @Flag(name: .long, help: "Install the skill where agent clients look for skills.") + var install = false + + @Flag(name: .long, help: "With --install: install into the current directory instead of your home directory.") + var project = false + + @Option(name: .long, help: "With --install: install into this skills directory only.") + var dir: String? + + @Flag(name: .long, help: "Print a short AGENTS.md snippet instead of the full skill.") + var snippet = false + + func validate() throws { + if !install, project || dir != nil { + throw ValidationError("--project and --dir only apply with --install.") + } + if install, snippet { + throw ValidationError("Use either --install or --snippet, not both.") + } + if project, dir != nil { + throw ValidationError("Use either --project or --dir, not both.") + } + } + + func run() throws { + guard install else { + print(snippet ? AgentGuide.agentsSnippet : AgentGuide.skill, terminator: "") + return + } + + let targets: [URL] + if let dir { + targets = [URL(fileURLWithPath: (dir as NSString).expandingTildeInPath)] + } else { + let base = project + ? URL(fileURLWithPath: FileManager.default.currentDirectoryPath) + : FileManager.default.homeDirectoryForCurrentUser + targets = AgentGuide.userSkillDirectories.map { base.appendingPathComponent($0) } + } + + var failed = false + for target in targets { + do { + print(try AgentGuide.install(into: target).path) + } catch { + Headless.note("couldn't install into \(target.path): \(Headless.describe(error))") + failed = true + } + } + if failed { throw ExitCode(1) } + } +} diff --git a/Sources/LabelKitApp/StatsCommand.swift b/Sources/LabelKitApp/StatsCommand.swift new file mode 100644 index 0000000..4f4caa1 --- /dev/null +++ b/Sources/LabelKitApp/StatsCommand.swift @@ -0,0 +1,76 @@ +import ArgumentParser +import Foundation +import LabelKit + +/// `labelkit stats` — summarize a dataset without opening it: how many images +/// are labelled, which still need labels, how the labels are distributed. +/// Reads only the annotations file and the directory listing (no image is +/// opened), so it is instant even on very large datasets. +struct StatsCommand: ParsableCommand { + static let configuration = CommandConfiguration( + commandName: "stats", + abstract: "Summarize a dataset: labelled and unlabelled images, boxes per label.", + discussion: """ + Examples: + labelkit stats ./cards + labelkit stats ./cards --per-image + labelkit stats ./cards --format text + + "unlabeled" lists images on disk with no entry in the annotations file — + the work still to do. "negatives" are entries with zero boxes, which are + deliberate training signal, not missing work. + + stdout carries the result (JSON by default). Exit 0 on success, 64 for a + usage error. + """) + + @Argument(help: "Dataset directory, or path to an annotations .json file.") + var path: String + + @Option(name: .long, help: "Explicit annotations.json path (overrides auto-detection).") + var annotations: String? + + @Flag(name: .long, help: "Include one row per image (status, box count, labels).") + var perImage = false + + @Option(name: .long, help: "Output format: json or text.") + var format: Headless.OutputFormat = .json + + func run() throws { + let document = try Headless.openDocument(path: path, annotations: annotations) + let summary = DatasetSummary.make(of: document, includePerImage: perImage) + switch format { + case .json: Headless.printJSON(summary) + case .text: print(text(summary)) + } + } + + private func text(_ summary: DatasetSummary) -> String { + let images = summary.images + var lines = [ + "\(summary.dataset)", + " images \(images.total) (\(images.onDisk) on disk)", + " annotated \(images.annotated)", + " negatives \(images.negatives)", + " unlabeled \(images.unlabeled)", + " missing \(images.missing)", + " boxes \(summary.boxes)", + ] + if let spread = summary.boxesPerImage { + lines.append(" per image min \(spread.min), median \(CreateMLWriter.coordString(spread.median)), " + + "max \(spread.max) (\(spread.maxImage))") + } + if !summary.labels.isEmpty { + lines.append("labels") + let width = summary.labels.map(\.label.count).max() ?? 0 + for label in summary.labels { + lines.append(" \(label.label.padded(to: width)) \(String(label.boxes).leftPadded(to: 6)) boxes " + + "\(String(label.images).leftPadded(to: 6)) images") + } + } + for row in summary.perImage ?? [] { + lines.append("\(row.image) \(row.status.rawValue) \(row.boxes) \(row.labels.joined(separator: ","))") + } + return lines.joined(separator: "\n") + } +} diff --git a/Sources/LabelKitApp/TrainCommand.swift b/Sources/LabelKitApp/TrainCommand.swift index 746b511..6777421 100644 --- a/Sources/LabelKitApp/TrainCommand.swift +++ b/Sources/LabelKitApp/TrainCommand.swift @@ -77,14 +77,14 @@ struct TrainCommand: ParsableCommand { maxIterations: maxIterations, validationSplitFraction: validationSplit > 0 ? validationSplit : nil) - warn("training \(records.count) image\(records.count == 1 ? "" : "s"), " + Headless.note("training \(records.count) image\(records.count == 1 ? "" : "s"), " + "\(labels.count) label\(labels.count == 1 ? "" : "s") → \(outputURL.path)") let result = try runTraining(location: location, outputURL: outputURL, options: options) let report = TrainingReport.make( algorithm: algorithm, maxIterations: maxIterations, result: result, images: records.count, labels: labels) - print(encode(report)) + print(Headless.json(report)) } // MARK: - Training @@ -126,7 +126,7 @@ struct TrainCommand: ParsableCommand { switch box.value { case let .success(result)?: return result - case let .failure(error)?: throw TrainCommandError.failed(describe(error)) + case let .failure(error)?: throw TrainCommandError.failed(Headless.describe(error)) case nil: throw TrainCommandError.noModel } } @@ -174,23 +174,6 @@ struct TrainCommand: ParsableCommand { return location.imagesDirectory.deletingLastPathComponent() .appendingPathComponent("\(location.displayName).mlmodel") } - - // MARK: - Output - - private func encode(_ report: TrainingReport) -> String { - let encoder = JSONEncoder() - encoder.outputFormatting = [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes] - guard let data = try? encoder.encode(report) else { return "" } - return String(decoding: data, as: UTF8.self) - } - - private func warn(_ message: String) { - FileHandle.standardError.write(Data("labelkit: \(message)\n".utf8)) - } - - private func describe(_ error: Error) -> String { - (error as? LocalizedError)?.errorDescription ?? "\(error)" - } } private enum TrainCommandError: LocalizedError { diff --git a/Sources/LabelKitApp/ValidateCommand.swift b/Sources/LabelKitApp/ValidateCommand.swift new file mode 100644 index 0000000..d0043e2 --- /dev/null +++ b/Sources/LabelKitApp/ValidateCommand.swift @@ -0,0 +1,80 @@ +import ArgumentParser +import Foundation +import LabelKit + +/// `labelkit validate` — check a dataset for the things that make it wrong to +/// train on, and say so with an exit code. Read-only: it never changes the +/// dataset. Image files are probed for their size only (header read, no pixel +/// decode), in parallel. +struct ValidateCommand: ParsableCommand { + static let configuration = CommandConfiguration( + commandName: "validate", + abstract: "Check a dataset for problems; exits 1 if it finds errors.", + discussion: """ + Examples: + labelkit validate ./cards + labelkit validate ./cards --labels card,coin + labelkit validate ./cards --strict --format text + + Errors (exit 1): no-annotations-file, missing-image, duplicate-entry, + empty-label, empty-box, box-outside-image, unknown-label. + Warnings (exit 0 unless --strict): unreadable-image, box-overflows-image, + duplicate-box, duplicate-image, unused-label. + + stdout carries the report (JSON by default) whether or not problems were + found. Exit 0 when clean, 1 when there are errors, 64 for a usage error. + """) + + @Argument(help: "Dataset directory, or path to an annotations .json file.") + var path: String + + @Option(name: .long, help: "Explicit annotations.json path (overrides auto-detection).") + var annotations: String? + + @Option(name: .long, help: "Comma-separated labels the dataset may use. Any other label is an error.") + var labels: String? + + @Flag(name: .long, help: "Treat warnings as failures too (exit 1).") + var strict = false + + @Option(name: .long, help: "Output format: json or text.") + var format: Headless.OutputFormat = .json + + func run() throws { + let document = try Headless.openDocument(path: path, annotations: annotations) + let allowed = labels?.split(separator: ",") + .map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty } + + // Only images that have an entry are read: their size bounds-checks the + // boxes, and their contents are compared to catch the same photo saved + // under two names. + let onDisk = Set(document.imagesOnDisk) + let toMeasure = document.uniqueRecords.map(\.image).filter(onDisk.contains) + let sizes = document.pixelSizes(of: toMeasure) + + let duplicates = DuplicateImages.groups(in: document.location.imagesDirectory, filenames: toMeasure) + + let report = DatasetValidator.validate( + document, options: .init(allowedLabels: allowed, duplicateImages: duplicates), + pixelSize: { sizes[$0] }) + + switch format { + case .json: Headless.printJSON(report) + case .text: print(text(report)) + } + if !report.ok || (strict && report.warnings > 0) { throw ExitCode(1) } + } + + private func text(_ report: ValidationReport) -> String { + var lines = report.issues.map { issue -> String in + var place = issue.image ?? "dataset" + if let box = issue.box { place += " #\(box)" } + return "\(issue.severity.rawValue) \(issue.code.rawValue) \(place): \(issue.message)" + } + lines.append(report.issues.isEmpty + ? "ok: no problems found" + : "\(report.errors) error\(report.errors == 1 ? "" : "s"), " + + "\(report.warnings) warning\(report.warnings == 1 ? "" : "s")") + return lines.joined(separator: "\n") + } +} diff --git a/Tests/LabelKitTests/AgentGuideTests.swift b/Tests/LabelKitTests/AgentGuideTests.swift new file mode 100644 index 0000000..28e77c2 --- /dev/null +++ b/Tests/LabelKitTests/AgentGuideTests.swift @@ -0,0 +1,73 @@ +import XCTest +@testable import LabelKit + +final class AgentGuideTests: XCTestCase { + /// Repo root, found from this file: Tests/LabelKitTests/AgentGuideTests.swift. + private var repoRoot: URL { + URL(fileURLWithPath: #filePath) + .deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent() + } + + /// `skills/labelkit/SKILL.md` is what repository-based installers serve + /// (`npx skills add`, plugin marketplaces); `labelkit skill` serves the + /// compiled-in text. They must not drift. To refresh the file after editing + /// the guide: `swift run labelkit skill > skills/labelkit/SKILL.md`. + func testRepoSkillFileMatchesTheBuiltInGuide() throws { + let file = repoRoot.appendingPathComponent("skills/labelkit/SKILL.md") + let onDisk = try String(contentsOf: file, encoding: .utf8) + XCTAssertEqual(onDisk, AgentGuide.skill, + "regenerate with: swift run labelkit skill > skills/labelkit/SKILL.md") + } + + /// The Agent Skills specification: `name` is lowercase letters, digits and + /// single hyphens, at most 64 characters, and equals the folder name; + /// `description` is 1–1024 characters. Only spec fields are used, so every + /// client accepts the file. + func testFrontmatterFollowsTheAgentSkillsSpecification() throws { + let lines = AgentGuide.skill.components(separatedBy: "\n") + XCTAssertEqual(lines.first, "---") + let end = try XCTUnwrap(lines.dropFirst().firstIndex(of: "---")) + var fields: [String: String] = [:] + for line in lines[1.. [ImportedImage] { + try BoxImportParser.parse(Data(text.utf8)) + } + + func testSimplestHandWrittenShape() throws { + let images = try parse(#"{"image":"a.jpg","boxes":[{"label":"cat","x":10,"y":20,"width":30,"height":40}]}"#) + XCTAssertEqual(images, [ImportedImage(image: "a.jpg", boxes: [ + ImportedBox(label: "cat", geometry: .pixels(CGRect(x: 10, y: 20, width: 30, height: 40))), + ])]) + } + + func testArrayOfImages() throws { + let images = try parse(#""" + [{"image":"a.jpg","boxes":[]}, + {"image":"b.jpg","boxes":[{"label":"cat","normalized":{"x":0.1,"y":0.2,"width":0.3,"height":0.4}}]}] + """#) + XCTAssertEqual(images.map(\.image), ["a.jpg", "b.jpg"]) + XCTAssertEqual(images[1].boxes.first?.geometry, + .normalized(CGRect(x: 0.1, y: 0.2, width: 0.3, height: 0.4))) + } + + func testNDJSONWithBlankLines() throws { + let images = try parse(""" + {"image":"a.jpg","boxes":[{"label":"cat","x":1,"y":2,"width":3,"height":4}]} + + {"image":"b.jpg","boxes":[]} + + """) + XCTAssertEqual(images.map(\.image), ["a.jpg", "b.jpg"]) + } + + /// `labelkit detect --format ndjson | labelkit annotate …` must just work. + func testDetectReportsRoundTripThroughTheParser() throws { + let box = BoundingBox(label: "card", rect: CGRect(x: 326.39, y: 490.28, width: 247.78, height: 427.68)) + let report = DetectionReport.make( + detector: "Rectangles", source: "vision", filename: "photo.jpg", path: "/tmp/x/photo.jpg", + pixelSize: CGSize(width: 2048, height: 1536), + detections: [DetectionCandidate(box: box, confidence: 0.97)]) + let line = try JSONEncoder().encode(report) + + // The report states the image's size, so the pixels are tied to it — + // and since that is the real size, the merge uses them untouched. + let images = try BoxImportParser.parse(line) + XCTAssertEqual(images, [ImportedImage(image: "photo.jpg", boxes: [ + ImportedBox(label: "card", geometry: .scaledPixels(box.rect, reference: CGSize(width: 2048, height: 1536))), + ])]) + } + + // MARK: - What vision models answer + + private func boxes(_ json: String, image: String? = "a.jpg", + _ convention: BoxConvention = .pixelTopLeftCorner, + label: String? = nil) throws -> [ImportedBox] { + let images = try BoxImportParser.parse( + Data(json.utf8), options: .init(convention: convention, defaultLabel: label, image: image)) + XCTAssertEqual(images.count, 1) + return images.first?.boxes ?? [] + } + + private func assertNormalized(_ geometry: ImportedBox.Geometry?, _ x: Double, _ y: Double, + _ w: Double, _ h: Double, line: UInt = #line) { + guard case .normalized(let rect)? = geometry else { return XCTFail("not normalized: \(String(describing: geometry))", line: line) } + XCTAssertEqual(rect.minX, x, accuracy: 1e-9, line: line) + XCTAssertEqual(rect.minY, y, accuracy: 1e-9, line: line) + XCTAssertEqual(rect.width, w, accuracy: 1e-9, line: line) + XCTAssertEqual(rect.height, h, accuracy: 1e-9, line: line) + } + + /// Gemini: a bare list, y first, 0–1000, usually inside a code fence. + func testGeminiBox2DInsideACodeFence() throws { + let answer = """ + Here are the boxes: + ```json + [ + {"box_2d": [100, 200, 500, 400], "label": "cat"}, + {"box_2d": [0, 0, 1000, 1000], "label": "table"} + ] + ``` + """ + let parsed = try boxes(answer) + XCTAssertEqual(parsed.map(\.label), ["cat", "table"]) + assertNormalized(parsed[0].geometry, 0.2, 0.1, 0.2, 0.4) // x from 200..400, y from 100..500 + assertNormalized(parsed[1].geometry, 0, 0, 1, 1) + } + + func testGeminiBox2DKeepsItsMeaningWhateverTheFlagsSay() throws { + let parsed = try boxes(#"[{"box_2d":[100,200,500,400],"label":"cat"}]"#, + .init(units: .pixel, anchor: .center, order: .xyxy)) + assertNormalized(parsed[0].geometry, 0.2, 0.1, 0.2, 0.4) + } + + /// Qwen uses one key for two scales, so the scale is stated, never guessed. + func testQwenBbox2DFollowsTheStatedUnits() throws { + let json = #"[{"bbox_2d":[200,100,400,500],"label":"cat"}]"# + XCTAssertEqual(try boxes(json)[0].geometry, .pixels(CGRect(x: 200, y: 100, width: 200, height: 400))) + assertNormalized(try boxes(json, .init(units: .thousandths))[0].geometry, 0.2, 0.1, 0.2, 0.4) + } + + func testCornerShapes() throws { + let expected = ImportedBox.Geometry.pixels(CGRect(x: 40, y: 30, width: 200, height: 160)) + XCTAssertEqual(try boxes(#"[{"label":"c","xyxy":[40,30,240,190]}]"#)[0].geometry, expected) + XCTAssertEqual(try boxes(#"[{"label":"c","x1":40,"y1":30,"x2":240,"y2":190}]"#)[0].geometry, expected) + XCTAssertEqual(try boxes(#"[{"label":"c","xmin":40,"ymin":30,"xmax":240,"ymax":190}]"#)[0].geometry, expected) + // Corners given in the other order describe the same box. + XCTAssertEqual(try boxes(#"[{"label":"c","xyxy":[240,190,40,30]}]"#)[0].geometry, expected) + // Moondream: named corners in fractions, no label. + let moondream = try boxes(#"{"objects":[{"x_min":0.2,"y_min":0.1,"x_max":0.4,"y_max":0.5}]}"#, + .init(units: .normalized), label: "cat") + XCTAssertEqual(moondream[0].label, "cat") + assertNormalized(moondream[0].geometry, 0.2, 0.1, 0.2, 0.4) + } + + func testBareArraysFollowTheStatedOrder() throws { + let json = #"[{"label":"c","bbox":[40,30,240,190]}]"# + XCTAssertEqual(try boxes(json)[0].geometry, .pixels(CGRect(x: 40, y: 30, width: 240, height: 190))) + XCTAssertEqual(try boxes(json, .init(order: .xyxy))[0].geometry, + .pixels(CGRect(x: 40, y: 30, width: 200, height: 160))) + XCTAssertEqual(try boxes(json, .init(order: .yxyx))[0].geometry, + .pixels(CGRect(x: 30, y: 40, width: 160, height: 200))) + } + + /// Grounding DINO / Florence style: boxes and labels as parallel lists. + func testParallelBoxAndLabelLists() throws { + let parsed = try boxes(#"{"boxes":[[40,30,240,190],[0,0,10,10]],"text_labels":["cat","dog"],"scores":[0.9,0.8]}"#, + .init(order: .xyxy)) + XCTAssertEqual(parsed.map(\.label), ["cat", "dog"]) + XCTAssertEqual(parsed[0].geometry, .pixels(CGRect(x: 40, y: 30, width: 200, height: 160))) + XCTAssertThrowsError(try boxes(#"{"boxes":[[40,30,240,190]]}"#), "no label anywhere") + XCTAssertEqual(try boxes(#"{"boxes":[[40,30,240,190]]}"#, label: "card").map(\.label), ["card"]) + } + + /// A model shown a downscaled copy answers in that copy's pixels. + func testPixelsOfAResizedCopyCarryTheirReferenceSize() throws { + let rect = CGRect(x: 40, y: 30, width: 200, height: 160) + let reference = CGSize(width: 1568, height: 1176) + XCTAssertEqual(try boxes(#"[{"label":"c","xyxy":[40,30,240,190]}]"#, + .init(referenceSize: reference))[0].geometry, + .scaledPixels(rect, reference: reference)) + // The entry can say it itself. + XCTAssertEqual(try boxes(#"{"width":1568,"height":1176,"boxes":[{"label":"c","xyxy":[40,30,240,190]}]}"#)[0].geometry, + .scaledPixels(rect, reference: reference)) + XCTAssertEqual(BoxImportParser.parseSize("1568x1176"), reference) + XCTAssertEqual(BoxImportParser.parseSize("1568 X 1176"), reference) + XCTAssertNil(BoxImportParser.parseSize("1568")) + XCTAssertNil(BoxImportParser.parseSize("0x10")) + } + + func testLabelAndImageKeyAliases() throws { + let images = try BoxImportParser.parse(Data(#""" + [{"imagefilename":"a.jpg","annotation":[{"label":"x","coordinates":{"x":5,"y":5,"width":2,"height":2}}]}, + {"file_name":"b.jpg","predictions":[{"class":"y","x":1,"y":2,"w":3,"h":4}]}] + """#.utf8)) + XCTAssertEqual(images.map(\.image), ["a.jpg", "b.jpg"]) + XCTAssertEqual(images[0].boxes[0].geometry, .pixels(CGRect(x: 4, y: 4, width: 2, height: 2))) + XCTAssertEqual(images[1].boxes[0], ImportedBox(label: "y", geometry: .pixels(CGRect(x: 1, y: 2, width: 3, height: 4)))) + } + + // MARK: - COCO + + func testCOCOFileBecomesOneEntryPerImageIncludingEmptyOnes() throws { + let images = try parse(#""" + {"images":[{"id":7,"file_name":"train/a.jpg","width":200,"height":100}, + {"id":9,"file_name":"b.jpg","width":200,"height":100}], + "categories":[{"id":1,"name":"cat"},{"id":2,"name":"dog"}], + "annotations":[{"id":1,"image_id":7,"category_id":2,"bbox":[10,20,30,40]}, + {"id":2,"image_id":7,"category_id":1,"bbox":[0,0,5,5]}]} + """#) + XCTAssertEqual(images.map(\.image), ["a.jpg", "b.jpg"]) + XCTAssertEqual(images[0].boxes.map(\.label), ["dog", "cat"]) + XCTAssertEqual(images[0].boxes[0].geometry, + .scaledPixels(CGRect(x: 10, y: 20, width: 30, height: 40), reference: CGSize(width: 200, height: 100))) + XCTAssertTrue(images[1].boxes.isEmpty) + } + + func testCOCOWithADanglingReferenceIsAnError() { + XCTAssertThrowsError(try parse(#""" + {"images":[{"id":7,"file_name":"a.jpg"}],"categories":[{"id":1,"name":"cat"}], + "annotations":[{"image_id":8,"category_id":1,"bbox":[1,2,3,4]}]} + """#)) + XCTAssertThrowsError(try parse(#""" + {"images":[{"id":7,"file_name":"a.jpg"}],"categories":[{"id":1,"name":"cat"}], + "annotations":[{"image_id":7,"category_id":5,"bbox":[1,2,3,4]}]} + """#)) + } + + func testNamingTheImageMakesTheImageKeyOptional() throws { + XCTAssertEqual(try boxes(#"{"boxes":[{"label":"c","x":1,"y":2,"width":3,"height":4}]}"#, image: "z.jpg").count, 1) + let images = try BoxImportParser.parse(Data(#"[{"label":"c","x":1,"y":2,"width":3,"height":4}]"#.utf8), + options: .init(image: "z.jpg")) + XCTAssertEqual(images.map(\.image), ["z.jpg"]) + // Without a named image a bare box list has nowhere to go. + XCTAssertThrowsError(try parse(#"[{"label":"c","x":1,"y":2,"width":3,"height":4}]"#)) + } + + /// A Create ML annotations file is valid input: its centre-anchored + /// coordinates become the same top-left rect the editor would show. + func testCreateMLEntriesUseCentreAnchoredCoordinates() throws { + let images = try parse(#""" + [{"image":"a.jpg","annotations":[{"label":"card","coordinates":{"x":50,"y":60,"width":20,"height":40}}]}] + """#) + XCTAssertEqual(images[0].boxes.first?.geometry, .pixels(CGRect(x: 40, y: 40, width: 20, height: 40))) + } + + func testImageFallsBackToTheBasenameOfPath() throws { + let images = try parse(#"{"path":"/data/set/a.jpg","boxes":[]}"#) + XCTAssertEqual(images.first?.image, "a.jpg") + } + + func testEmptyInputIsNoImages() throws { + XCTAssertEqual(try parse(" \n"), []) + } + + func testErrorsSayWhereTheProblemIs() { + func message(_ text: String) -> String { + do { + _ = try parse(text) + return "no error" + } catch { + return (error as? BoxImportError)?.message ?? "\(error)" + } + } + XCTAssertEqual(message(#"{"boxes":[]}"#), "input: missing \"image\"") + XCTAssertEqual(message(#"{"image":"a.jpg"}"#), + "input (a.jpg): expected a \"boxes\", \"detections\" or \"annotations\" list") + XCTAssertEqual(message(#"{"image":"a.jpg","boxes":[{"x":1,"y":2,"width":3,"height":4}]}"#), + "input (a.jpg), box #1: missing \"label\"") + XCTAssertTrue(message(#"{"image":"a.jpg","boxes":[{"label":"cat"}]}"#) + .hasPrefix("input (a.jpg), box #1: no geometry — give x,y,width,height, or one of")) + XCTAssertEqual(message(#"{"image":"a.jpg","boxes":[{"label":"cat","xyxy":[1,2,3]}]}"#), + "input (a.jpg), box #1 xyxy: expected four numbers") + XCTAssertEqual(message(#"{"image":"a.jpg","boxes":[{"label":"cat","x":1,"y":2,"width":"3","height":4}]}"#), + "input (a.jpg), box #1: \"width\" must be a number") + XCTAssertEqual(message("{\"image\":\"a.jpg\",\"boxes\":[]}\nnot json"), "line 2 is not a JSON object") + XCTAssertEqual(message("42"), "expected a JSON object, an array of objects, or NDJSON") + } + + func testInlineBox() throws { + XCTAssertEqual(try BoxImportParser.parseInlineBox("cat:10,20,30.5,40"), + ImportedBox(label: "cat", geometry: .pixels(CGRect(x: 10, y: 20, width: 30.5, height: 40)))) + let fractions = BoxImportParser.Options(convention: .init(units: .normalized)) + XCTAssertEqual(try BoxImportParser.parseInlineBox("red: car : 0.1, 0.2, 0.3, 0.4", options: fractions), + ImportedBox(label: "red: car", geometry: .normalized(CGRect(x: 0.1, y: 0.2, width: 0.3, height: 0.4)))) + XCTAssertEqual(try BoxImportParser.parseInlineBox("10,20,30,40", options: .init(defaultLabel: "card")), + ImportedBox(label: "card", geometry: .pixels(CGRect(x: 10, y: 20, width: 30, height: 40)))) + XCTAssertThrowsError(try BoxImportParser.parseInlineBox("10,20,30,40"), "no label and no default") + XCTAssertThrowsError(try BoxImportParser.parseInlineBox("cat 10,20,30,40")) + XCTAssertThrowsError(try BoxImportParser.parseInlineBox("cat:10,20,30")) + XCTAssertThrowsError(try BoxImportParser.parseInlineBox(":10,20,30,40")) + } + + // MARK: - Conventions + + /// The same box — top-left corner (40,40), 20 wide, 40 tall, in a + /// 200x100 image — written four ways. + func testEveryConventionLandsOnTheSameBox() throws { + func geometry(_ box: String, _ convention: BoxConvention) throws -> ImportedBox.Geometry { + let json = "{\"image\":\"a.jpg\",\"boxes\":[\(box)]}" + let images = try BoxImportParser.parse(Data(json.utf8), options: .init(convention: convention)) + return try XCTUnwrap(images.first?.boxes.first?.geometry) + } + let pixels = ImportedBox.Geometry.pixels(CGRect(x: 40, y: 40, width: 20, height: 40)) + XCTAssertEqual(try geometry(#"{"label":"c","x":40,"y":40,"width":20,"height":40}"#, .pixelTopLeftCorner), pixels) + XCTAssertEqual(try geometry(#"{"label":"c","x":50,"y":60,"width":20,"height":40}"#, .createML), pixels) + + func assertNormalized(_ result: ImportedBox.Geometry, line: UInt = #line) { + guard case .normalized(let rect) = result else { return XCTFail("not normalized", line: line) } + XCTAssertEqual(rect.minX, 0.2, accuracy: 1e-9, line: line) + XCTAssertEqual(rect.minY, 0.4, accuracy: 1e-9, line: line) + XCTAssertEqual(rect.width, 0.1, accuracy: 1e-9, line: line) + XCTAssertEqual(rect.height, 0.4, accuracy: 1e-9, line: line) + } + // YOLO: normalized, top-left origin, centre anchor. + assertNormalized(try geometry(#"{"label":"c","x":0.25,"y":0.6,"width":0.1,"height":0.4}"#, + .init(units: .normalized, anchor: .center))) + // Apple Vision: normalized, bottom-left origin, corner = bottom-left. + assertNormalized(try geometry(#"{"label":"c","x":0.2,"y":0.2,"width":0.1,"height":0.4}"#, + .init(units: .normalized, origin: .bottomLeft))) + } + + func testCoordinatesAndNormalizedKeysKeepTheirOwnMeaningUnderAnyConvention() throws { + let options = BoxImportParser.Options(convention: .init(anchor: .center)) + let images = try BoxImportParser.parse(Data(#""" + {"image":"a.jpg","boxes":[ + {"label":"c","coordinates":{"x":50,"y":60,"width":20,"height":40}}, + {"label":"c","normalized":{"x":0.5,"y":0.5,"width":0.2,"height":0.2}}]} + """#.utf8), options: options) + XCTAssertEqual(images[0].boxes[0].geometry, .pixels(CGRect(x: 40, y: 40, width: 20, height: 40))) + guard case .normalized(let rect) = images[0].boxes[1].geometry else { return XCTFail() } + XCTAssertEqual(rect.minX, 0.4, accuracy: 1e-9) // the centre anchor still applies; units are forced + XCTAssertEqual(rect.minY, 0.4, accuracy: 1e-9) + } + + func testDefaultLabelFillsInBoxesWithoutOne() throws { + let json = #"{"image":"a.jpg","boxes":[{"x":1,"y":2,"width":3,"height":4},{"label":"coin","x":1,"y":2,"width":3,"height":4}]}"# + let images = try BoxImportParser.parse(Data(json.utf8), options: .init(defaultLabel: "card")) + XCTAssertEqual(images[0].boxes.map(\.label), ["card", "coin"]) + } + + func testPixelBottomLeftIsRefused() { + XCTAssertNotNil(BoxConvention(units: .pixel, origin: .bottomLeft).unsupportedReason) + XCTAssertNil(BoxConvention(units: .normalized, origin: .bottomLeft).unsupportedReason) + XCTAssertNil(BoxConvention.createML.unsupportedReason) + } +} diff --git a/Tests/LabelKitTests/BoxRendererTests.swift b/Tests/LabelKitTests/BoxRendererTests.swift index e977991..0109c58 100644 --- a/Tests/LabelKitTests/BoxRendererTests.swift +++ b/Tests/LabelKitTests/BoxRendererTests.swift @@ -43,6 +43,70 @@ final class BoxRendererTests: XCTestCase { XCTAssertEqual(pixelSize(ofPNG: data), CGSize(width: 64, height: 64)) } + /// Decode rendered bytes to RGBA so tests can look at actual pixels. + private func pixels(of data: Data) throws -> (width: Int, height: Int, rgba: [UInt8]) { + let source = try XCTUnwrap(CGImageSourceCreateWithData(data as CFData, nil)) + let decoded = try XCTUnwrap(CGImageSourceCreateImageAtIndex(source, 0, nil)) + var rgba = [UInt8](repeating: 0, count: decoded.width * decoded.height * 4) + let ctx = try XCTUnwrap(CGContext( + data: &rgba, width: decoded.width, height: decoded.height, bitsPerComponent: 8, + bytesPerRow: decoded.width * 4, space: CGColorSpaceCreateDeviceRGB(), + bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)) + ctx.draw(decoded, in: CGRect(x: 0, y: 0, width: decoded.width, height: decoded.height)) + return (decoded.width, decoded.height, rgba) + } + + func testJPEGEncodingProducesAJPEGAtImageDimensions() throws { + let data = try XCTUnwrap(BoxRenderer.render( + image: image(200, 120), sourceSize: CGSize(width: 200, height: 120), + boxes: [RenderableBox(rect: CGRect(x: 20, y: 15, width: 80, height: 60), label: "card", caption: "#1 card")], + as: .jpeg(quality: 0.8))) + XCTAssertEqual(Array(data.prefix(3)), [0xFF, 0xD8, 0xFF], "JPEG magic bytes") + XCTAssertEqual(pixelSize(ofPNG: data), CGSize(width: 200, height: 120)) + XCTAssertEqual(BoxRenderer.Encoding.jpeg(quality: 0.8).fileExtension, "jpg") + XCTAssertEqual(BoxRenderer.Encoding.png.fileExtension, "png") + } + + /// The grid is measured in SOURCE pixels: on a 400x200 source drawn at + /// 200x100, a 100px grid puts vertical lines at draw x = 50, 100, 150 and a + /// horizontal line at draw y = 50 — and nowhere else. + func testGridLinesFallOnSourcePixelMultiples() throws { + let data = try XCTUnwrap(BoxRenderer.render( + image: image(200, 100), sourceSize: CGSize(width: 400, height: 200), boxes: [], + grid: RenderGrid(spacing: 100), as: .png)) + let (width, _, rgba) = try pixels(of: data) + func brightness(x: Int, y: Int) -> Int { Int(rgba[(y * width + x) * 4]) } + + // Sample along a row clear of the labels (which hug the top and left). + // The image is one flat grey, so any pixel that differs from an + // untouched one has had a line drawn through it. + let row = 80 + let background = brightness(x: 25, y: row) + for x in [50, 100, 150] { + XCTAssertGreaterThan(abs(brightness(x: x, y: row) - background), 5, "vertical line at draw x=\(x)") + } + XCTAssertGreaterThan(abs(brightness(x: 180, y: 50) - background), 5, "horizontal line at draw y=50") + for x in [75, 125, 175] { + XCTAssertEqual(brightness(x: x, y: row), background, "no line at draw x=\(x)") + } + } + + func testNoGridLeavesTheImageUntouched() throws { + let data = try XCTUnwrap(BoxRenderer.render( + image: image(200, 100), sourceSize: CGSize(width: 400, height: 200), boxes: [], as: .png)) + let (width, _, rgba) = try pixels(of: data) + XCTAssertEqual(rgba[(80 * width + 50) * 4], rgba[(80 * width + 25) * 4]) + XCTAssertEqual(rgba[(50 * width + 180) * 4], rgba[(80 * width + 25) * 4]) + } + + func testOutputNamesKeepImagesThatShareAStemApart() { + XCTAssertEqual( + BoxRenderer.outputNames(for: ["a.jpg", "b.heic", "a.png", "c.tar.jpg", "B.JPG"], fileExtension: "jpg"), + ["a.jpg.jpg", "b.heic.jpg", "a.png.jpg", "c.tar.jpg", "B.JPG.jpg"]) + XCTAssertEqual(BoxRenderer.outputNames(for: ["a.jpg", "b.heic"], fileExtension: "png"), ["a.png", "b.png"]) + XCTAssertEqual(BoxRenderer.outputNames(for: [], fileExtension: "jpg"), []) + } + func testScalesBoxesFromSourceSpaceToRenderSize() throws { // Boxes measured in a 400x240 space, drawn onto a 200x120 image — must // not crash and must still produce the render-sized PNG. diff --git a/Tests/LabelKitTests/HeadlessDatasetTests.swift b/Tests/LabelKitTests/HeadlessDatasetTests.swift new file mode 100644 index 0000000..26c0948 --- /dev/null +++ b/Tests/LabelKitTests/HeadlessDatasetTests.swift @@ -0,0 +1,433 @@ +import CoreGraphics +import XCTest +@testable import LabelKit + +/// The headless path behind `annotate`, `stats` and `validate`. Everything is +/// exercised through a real dataset directory on disk so the tests cover what +/// a scripted caller actually gets, including the bytes that are saved. +final class HeadlessDatasetTests: XCTestCase { + var tempDir: URL! + let imageSize = CGSize(width: 200, height: 100) + + /// 2-space, canonical: exactly what labelkit itself writes. + let canonical = """ + [ + { + "image": "b.jpg", + "annotations": [ + { + "label": "card", + "coordinates": { + "x": 50, + "y": 50, + "width": 20, + "height": 20 + }, + "score": 0.5 + } + ], + "imageWidth": 200 + }, + { + "image": "a.jpg", + "annotations": [] + }, + { + "image": "ghost.jpg", + "annotations": [ + { + "label": "card", + "coordinates": { + "x": 5, + "y": 5, + "width": 2, + "height": 2 + } + } + ] + } + ] + + """ + + override func setUpWithError() throws { + tempDir = FileManager.default.temporaryDirectory + .appendingPathComponent("labelkit-headless-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: tempDir, withIntermediateDirectories: true) + for name in ["a.jpg", "b.jpg", "c.jpg", "d.jpg"] { + try Data([0xFF]).write(to: tempDir.appendingPathComponent(name)) + } + try Data(canonical.utf8).write(to: annotationsURL) + } + + override func tearDownWithError() throws { + try? FileManager.default.removeItem(at: tempDir) + } + + var annotationsURL: URL { tempDir.appendingPathComponent("annotations.json") } + + func load() throws -> DatasetDocument { + try DatasetDocument(location: XCTUnwrap(DatasetLocator.resolve(path: tempDir.path))) + } + + func savedText() throws -> String { + String(decoding: try Data(contentsOf: annotationsURL), as: UTF8.self) + } + + /// Every image is 200x100 except `ghost.jpg`, which isn't on disk. + func size(_ name: String) -> CGSize? { name == "ghost.jpg" ? nil : imageSize } + + func pixels(_ label: String, _ x: CGFloat, _ y: CGFloat, _ w: CGFloat, _ h: CGFloat) -> ImportedBox { + ImportedBox(label: label, geometry: .pixels(CGRect(x: x, y: y, width: w, height: h))) + } + + // MARK: - Document + + func testLoadThenSaveIsByteIdentical() throws { + let document = try load() + try document.save() + XCTAssertEqual(try savedText(), canonical) + } + + func testSaveKeepsTheFilesOwnIndentation() throws { + let fourSpace = canonical.replacingOccurrences(of: " ", with: " ") + try Data(fourSpace.utf8).write(to: annotationsURL) + var document = try load() + _ = AnnotationMerge.apply([ImportedImage(image: "c.jpg", boxes: [pixels("card", 10, 10, 30, 30)])], + to: &document, pixelSize: size) + try document.save() + let saved = try savedText() + XCTAssertTrue(saved.hasPrefix("[\n {\n \"image\": \"b.jpg\"")) + XCTAssertTrue(saved.contains("\n {\n \"image\": \"c.jpg\"")) + } + + func testDocumentWithoutAnnotationsFileStartsEmpty() throws { + try FileManager.default.removeItem(at: annotationsURL) + let document = try load() + XCTAssertTrue(document.records.isEmpty) + XCTAssertEqual(document.imagesOnDisk, ["a.jpg", "b.jpg", "c.jpg", "d.jpg"]) + XCTAssertEqual(String(decoding: document.serialized(), as: UTF8.self), "[]\n") + } + + /// `annotate` names the images it cares about, so the dataset opens by + /// checking those instead of listing the folder — with the same answers. + func testOpeningForSpecificImagesChecksThemInsteadOfListingTheFolder() throws { + let location = try XCTUnwrap(DatasetLocator.resolve(path: tempDir.path)) + let outside = tempDir.deletingLastPathComponent().appendingPathComponent("outside-\(UUID().uuidString).jpg") + try Data([0xFF]).write(to: outside) + defer { try? FileManager.default.removeItem(at: outside) } + + let document = try DatasetDocument( + location: location, + onlyImages: ["c.jpg", "nope.jpg", "c.jpg", "a.jpg", "../\(outside.lastPathComponent)"]) + XCTAssertEqual(document.imagesOnDisk, ["c.jpg", "a.jpg"], "existing ones, once each, never outside the folder") + XCTAssertEqual(document.records.count, 3, "the annotations file is still read in full") + + // Past the threshold it falls back to a normal listing. + let many = (0...DatasetDocument.listingThreshold).map { "img\($0).jpg" } + XCTAssertEqual(try DatasetDocument(location: location, onlyImages: many).imagesOnDisk, + ["a.jpg", "b.jpg", "c.jpg", "d.jpg"]) + } + + // MARK: - Merge: add + + func testAddWritesCentreAnchoredCoordinatesAndAppendsNewEntriesInNameOrder() throws { + var document = try load() + let result = AnnotationMerge.apply([ + ImportedImage(image: "d.jpg", boxes: [pixels("coin", 10, 20, 40, 60)]), + ImportedImage(image: "c.jpg", boxes: [pixels("card", 0, 0, 100, 50)]), + ], to: &document, pixelSize: size) + + XCTAssertTrue(result.problems.isEmpty) + XCTAssertTrue(result.changed) + // Existing order untouched; newcomers appended by name, not input order. + XCTAssertEqual(document.records.map(\.image), ["b.jpg", "a.jpg", "ghost.jpg", "c.jpg", "d.jpg"]) + let coin = try XCTUnwrap(document.records.last?.boxes.first) + XCTAssertEqual([coin.x, coin.y, coin.width, coin.height], [30, 50, 40, 60]) + XCTAssertEqual(result.outcomes.map(\.image), ["d.jpg", "c.jpg"]) + XCTAssertEqual(result.outcomes.map(\.created), [true, true]) + } + + func testAddIsIdempotentDownToTheBytes() throws { + let input = [ + ImportedImage(image: "b.jpg", boxes: [pixels("card", 100, 10, 50.005, 40)]), + ImportedImage(image: "c.jpg", boxes: [pixels("coin", 10, 20, 40, 60)]), + ] + var first = try load() + _ = AnnotationMerge.apply(input, to: &first, pixelSize: size) + try first.save() + let afterFirst = try savedText() + + var second = try load() + let result = AnnotationMerge.apply(input, to: &second, pixelSize: size) + try second.save() + + XCTAssertFalse(result.changed) + XCTAssertEqual(result.outcomes.map(\.added), [0, 0]) + XCTAssertEqual(result.outcomes.map(\.duplicates), [1, 1]) + XCTAssertEqual(try savedText(), afterFirst) + } + + func testAddKeepsExistingBoxesAndTheirUnknownKeys() throws { + var document = try load() + _ = AnnotationMerge.apply([ImportedImage(image: "b.jpg", boxes: [pixels("coin", 120, 10, 30, 30)])], + to: &document, pixelSize: size) + try document.save() + let saved = try savedText() + XCTAssertTrue(saved.contains("\"score\": 0.5")) + XCTAssertTrue(saved.contains("\"imageWidth\": 200")) + XCTAssertEqual(document.records[0].boxes.map(\.label), ["card", "coin"]) + } + + func testAddSkipsABoxThatAlreadyExistsButNotADifferentLabelInTheSamePlace() throws { + var document = try load() + // b.jpg already has card centred at 50,50 size 20 → top-left 40,40. + let result = AnnotationMerge.apply([ImportedImage(image: "b.jpg", boxes: [ + pixels("card", 41, 40, 20, 20), // same box, a pixel off + pixels("coin", 40, 40, 20, 20), // same place, different label + ])], to: &document, pixelSize: size) + XCTAssertEqual(result.outcomes.first?.duplicates, 1) + XCTAssertEqual(result.outcomes.first?.added, 1) + XCTAssertEqual(document.records[0].boxes.map(\.label), ["card", "coin"]) + } + + func testAddDeduplicatesWithinTheInputItself() throws { + var document = try load() + let result = AnnotationMerge.apply([ + ImportedImage(image: "c.jpg", boxes: [pixels("card", 10, 10, 50, 50)]), + ImportedImage(image: "c.jpg", boxes: [pixels("card", 10, 10, 50, 50)]), + ], to: &document, pixelSize: size) + XCTAssertEqual(result.outcomes.count, 1) + XCTAssertEqual(result.outcomes.first?.added, 1) + XCTAssertEqual(result.outcomes.first?.duplicates, 1) + } + + func testNormalizedBoxesScaleToTheImage() throws { + var document = try load() + let box = ImportedBox(label: "card", geometry: .normalized(CGRect(x: 0.25, y: 0.5, width: 0.5, height: 0.25))) + _ = AnnotationMerge.apply([ImportedImage(image: "c.jpg", boxes: [box])], to: &document, pixelSize: size) + let saved = try XCTUnwrap(document.records.last?.boxes.first) + // 200x100 image → top-left 50,50 size 100x25 → centre 100,62.5. + XCTAssertEqual([saved.x, saved.y, saved.width, saved.height], [100, 62.5, 100, 25]) + } + + func testPixelsOfAResizedCopyAreScaledToTheRealImage() throws { + var document = try load() + // The model saw a 100x50 copy of the 200x100 image: everything doubles. + let seen = ImportedBox(label: "card", geometry: .scaledPixels( + CGRect(x: 10, y: 5, width: 40, height: 20), reference: CGSize(width: 100, height: 50))) + // Stated size equals the real size: the numbers are used exactly. + let exact = ImportedBox(label: "coin", geometry: .scaledPixels( + CGRect(x: 100.25, y: 50.5, width: 33.33, height: 20), reference: imageSize)) + _ = AnnotationMerge.apply([ImportedImage(image: "c.jpg", boxes: [seen, exact])], + to: &document, pixelSize: size) + let saved = try XCTUnwrap(document.records.last?.boxes) + XCTAssertEqual([saved[0].x, saved[0].y, saved[0].width, saved[0].height], [60, 30, 80, 40]) + XCTAssertEqual(saved[1].width, 33.33) + XCTAssertEqual(saved[1].x, 100.25 + 33.33 / 2) + } + + func testBoxHangingOverAnEdgeIsClampedAndCounted() throws { + var document = try load() + let result = AnnotationMerge.apply( + [ImportedImage(image: "c.jpg", boxes: [pixels("card", 150, 50, 100, 100)])], + to: &document, pixelSize: size) + XCTAssertTrue(result.problems.isEmpty) + XCTAssertEqual(result.outcomes.first?.clamped, 1) + let saved = try XCTUnwrap(document.records.last?.boxes.first) + XCTAssertEqual([saved.x, saved.y, saved.width, saved.height], [175, 75, 50, 50]) + } + + // MARK: - Merge: problems + + func testUnknownImageAndUnusableBoxesAreProblemsNotWrites() throws { + var document = try load() + let result = AnnotationMerge.apply([ + ImportedImage(image: "nope.jpg", boxes: [pixels("card", 0, 0, 10, 10)]), + ImportedImage(image: "c.jpg", boxes: [ + pixels("card", 500, 500, 10, 10), // outside the 200x100 image + pixels("card", 10, 10, 0, 10), // no area + pixels(" ", 10, 10, 10, 10), // no label + ]), + ], to: &document, pixelSize: size) + + XCTAssertEqual(result.problems.map(\.image), ["nope.jpg", "c.jpg", "c.jpg", "c.jpg"]) + XCTAssertTrue(result.problems[1].message.contains("outside the image")) + XCTAssertTrue(result.problems[2].message.contains("positive")) + XCTAssertTrue(result.problems[3].message.contains("empty label")) + XCTAssertFalse(result.changed) + XCTAssertFalse(document.records.contains { $0.image == "c.jpg" }) + } + + func testNormalizedBoxOnAnUnreadableImageIsAProblem() throws { + var document = try load() + let box = ImportedBox(label: "card", geometry: .normalized(CGRect(x: 0, y: 0, width: 0.5, height: 0.5))) + let result = AnnotationMerge.apply([ImportedImage(image: "ghost.jpg", boxes: [box])], + to: &document, pixelSize: size) + XCTAssertEqual(result.problems.count, 1) + XCTAssertFalse(result.changed) + } + + // MARK: - Merge: replace and negatives + + func testReplaceSwapsOnlyTheListedImages() throws { + var document = try load() + let result = AnnotationMerge.apply( + [ImportedImage(image: "b.jpg", boxes: [pixels("coin", 0, 0, 10, 10)])], + to: &document, options: .init(mode: .replace), pixelSize: size) + XCTAssertEqual(result.outcomes.first?.removed, 1) + XCTAssertEqual(result.outcomes.first?.added, 1) + XCTAssertEqual(document.records[0].boxes.map(\.label), ["coin"]) + XCTAssertEqual(document.records[0].extras["imageWidth"], .number(200)) + XCTAssertEqual(document.records[2].boxes.count, 1, "ghost.jpg untouched") + } + + func testReplaceWithNoBoxesLeavesANegativeNotAHole() throws { + var document = try load() + _ = AnnotationMerge.apply([ImportedImage(image: "b.jpg", boxes: [])], + to: &document, options: .init(mode: .replace), pixelSize: size) + XCTAssertEqual(document.records.map(\.image), ["b.jpg", "a.jpg", "ghost.jpg"]) + XCTAssertTrue(document.records[0].boxes.isEmpty) + } + + func testAnImageWithNoBoxesIsOnlyRecordedAsANegativeWhenAsked() throws { + var quiet = try load() + let skipped = AnnotationMerge.apply([ImportedImage(image: "c.jpg", boxes: [])], + to: &quiet, pixelSize: size) + XCTAssertFalse(skipped.changed) + XCTAssertTrue(skipped.outcomes.isEmpty) + + var explicit = try load() + let recorded = AnnotationMerge.apply([ImportedImage(image: "c.jpg", boxes: [])], + to: &explicit, options: .init(recordNegatives: true), pixelSize: size) + XCTAssertTrue(recorded.changed) + XCTAssertEqual(explicit.records.last?.image, "c.jpg") + XCTAssertEqual(explicit.records.last?.boxes.count, 0) + } + + // MARK: - Summary + + func testSummaryCountsEveryKindOfImage() throws { + let summary = DatasetSummary.make(of: try load(), includePerImage: true, labelkitVersion: "test") + XCTAssertEqual(summary.images, .init(total: 5, onDisk: 4, annotated: 2, negatives: 1, unlabeled: 2, missing: 1)) + XCTAssertEqual(summary.boxes, 2) + XCTAssertEqual(summary.labels, [.init(label: "card", boxes: 2, images: 2)]) + XCTAssertEqual(summary.unlabeled, ["c.jpg", "d.jpg"]) + XCTAssertEqual(summary.missing, ["ghost.jpg"]) + XCTAssertEqual(summary.perImage?.map(\.status), [.negative, .annotated, .unlabeled, .unlabeled, .missing]) + XCTAssertEqual(summary.perImage?.map(\.image), ["a.jpg", "b.jpg", "c.jpg", "d.jpg", "ghost.jpg"]) + } + + func testSummaryReportsTheBoxSpreadAndItsBusiestImage() throws { + var document = try load() + XCTAssertEqual(DatasetSummary.make(of: document).boxesPerImage, + .init(min: 1, median: 1, max: 1, maxImage: "b.jpg")) + _ = AnnotationMerge.apply([ImportedImage(image: "c.jpg", boxes: [ + pixels("card", 0, 0, 10, 10), pixels("card", 50, 0, 10, 10), pixels("card", 100, 0, 10, 10), + pixels("card", 150, 0, 10, 10), + ])], to: &document, pixelSize: size) + // Counts per annotated image are now 1 (b), 1 (ghost), 4 (c); a.jpg is a negative and excluded. + XCTAssertEqual(DatasetSummary.make(of: document).boxesPerImage, + .init(min: 1, median: 1, max: 4, maxImage: "c.jpg")) + + var empty = document + empty.records = [] + XCTAssertNil(DatasetSummary.make(of: empty).boxesPerImage) + } + + func testSummaryOrdersLabelsByUseThenName() throws { + var document = try load() + _ = AnnotationMerge.apply([ImportedImage(image: "c.jpg", boxes: [ + pixels("zebra", 0, 0, 10, 10), pixels("apple", 20, 20, 10, 10), + ])], to: &document, pixelSize: size) + let summary = DatasetSummary.make(of: document) + XCTAssertEqual(summary.labels.map(\.label), ["card", "apple", "zebra"]) + XCTAssertNil(summary.perImage) + } + + // MARK: - Validate + + func testValidateFlagsWhatWouldBreakTraining() throws { + var document = try load() + document.records.append(ImageAnnotationRecord(image: "c.jpg", boxes: [ + BoxRecord(label: "card", x: 500, y: 500, width: 10, height: 10), // outside + BoxRecord(label: "card", x: 195, y: 50, width: 30, height: 20), // overflows right edge + BoxRecord(label: "card", x: 50, y: 50, width: 0, height: 10), // no area + BoxRecord(label: "", x: 20, y: 20, width: 10, height: 10), // no label + BoxRecord(label: "coin", x: 100, y: 50, width: 40, height: 40), + BoxRecord(label: "coin", x: 100, y: 50, width: 40, height: 40), // duplicate + ])) + document.records.append(ImageAnnotationRecord(image: "b.jpg", boxes: [])) // second entry for b.jpg + + let report = DatasetValidator.validate(document, labelkitVersion: "test", pixelSize: size) + let found = report.issues.map { "\($0.code.rawValue)@\($0.image ?? "-")#\($0.box ?? 0)" } + XCTAssertEqual(found, [ + "missing-image@ghost.jpg#0", + "box-outside-image@c.jpg#1", + "box-overflows-image@c.jpg#2", + "empty-box@c.jpg#3", + "empty-label@c.jpg#4", + "duplicate-box@c.jpg#6", + "duplicate-entry@b.jpg#0", + ]) + XCTAssertFalse(report.ok) + XCTAssertEqual(report.errors, 5) + XCTAssertEqual(report.warnings, 2) + } + + func testValidateAllowedLabels() throws { + let report = DatasetValidator.validate( + try load(), options: .init(allowedLabels: ["coin", "token"]), pixelSize: { _ in self.imageSize }) + let codes = report.issues.map(\.code) + XCTAssertEqual(codes.filter { $0 == .unknownLabel }.count, 2) // the two "card" boxes + XCTAssertEqual(report.issues.filter { $0.code == .unusedLabel }.map(\.label), ["coin", "token"]) + } + + // MARK: - Duplicate images + + func testDuplicateImagesAreFoundByContentNotName() throws { + let photo = Data((0..<4096).map { UInt8($0 % 251) }) + var other = photo + other[100] = 0 // same size, one byte different + try photo.write(to: tempDir.appendingPathComponent("a.jpg")) + try photo.write(to: tempDir.appendingPathComponent("c.jpg")) + try other.write(to: tempDir.appendingPathComponent("b.jpg")) + try FileManager.default.createSymbolicLink( + at: tempDir.appendingPathComponent("link.jpg"), + withDestinationURL: tempDir.appendingPathComponent("a.jpg")) + // d.jpg keeps its 1-byte contents from setUp: a size of its own. + + let groups = DuplicateImages.groups( + in: tempDir, filenames: ["a.jpg", "b.jpg", "c.jpg", "d.jpg", "link.jpg", "absent.jpg"]) + XCTAssertEqual(groups, [["a.jpg", "c.jpg", "link.jpg"]]) + XCTAssertEqual(DuplicateImages.groups(in: tempDir, filenames: ["b.jpg", "d.jpg"]), []) + } + + func testValidateWarnsAboutDuplicateImagesAndSaysWhenLabelsConflict() throws { + var document = try load() + document.records.removeAll { $0.image == "ghost.jpg" } + document.records.append(ImageAnnotationRecord(image: "c.jpg", boxes: document.records[0].boxes)) + let report = DatasetValidator.validate( + document, options: .init(duplicateImages: [["b.jpg", "c.jpg", "a.jpg"]]), pixelSize: size) + XCTAssertTrue(report.ok, "duplicates are warnings") + XCTAssertEqual(report.issues.map(\.code), [.duplicateImage, .duplicateImage]) + XCTAssertEqual(report.issues.map(\.image), ["c.jpg", "a.jpg"]) + XCTAssertEqual(report.issues[0].message, "same file contents as 'b.jpg'") + XCTAssertEqual(report.issues[1].message, "same file contents as 'b.jpg', and the two are labelled differently") + } + + func testValidateAcleanDatasetIsOK() throws { + var document = try load() + document.records.removeAll { $0.image == "ghost.jpg" } + let report = DatasetValidator.validate(document, pixelSize: size) + XCTAssertTrue(report.ok) + XCTAssertTrue(report.issues.isEmpty) + } + + func testValidateReportsAMissingAnnotationsFile() throws { + try FileManager.default.removeItem(at: annotationsURL) + let report = DatasetValidator.validate(try load(), pixelSize: size) + XCTAssertEqual(report.issues.map(\.code), [.noAnnotationsFile]) + XCTAssertFalse(report.ok) + } +} diff --git a/scripts/smoke-scripted.sh b/scripts/smoke-scripted.sh new file mode 100755 index 0000000..01c1735 --- /dev/null +++ b/scripts/smoke-scripted.sh @@ -0,0 +1,76 @@ +#!/usr/bin/env bash +# End-to-end smoke test of the scripted subcommands (stats, validate, annotate, +# render, skill) against a built binary, on a throwaway dataset. It checks the +# things unit tests can't: that the commands are wired into the CLI, stay +# headless, and keep their exit-code contract (0 ok, 1 problem, 64 usage). +# +# ./scripts/smoke-scripted.sh # uses .build/release/labelkit +# ./scripts/smoke-scripted.sh path/to/labelkit +set -euo pipefail +cd "$(dirname "$0")/.." + +lk="${1:-.build/release/labelkit}" +[[ "$lk" = /* ]] || lk="$PWD/$lk" +work="$(mktemp -d)" +trap 'rm -rf "$work"' EXIT +ds="$work/dataset" +mkdir "$ds" +cp docs/icon.png "$ds/a.png" # any real image will do: 512x512 +cp docs/icon.png "$ds/b.png" +printf 'x' >> "$ds/b.png" # same picture, different bytes: not a duplicate file + +fail() { echo "smoke: $*" >&2; exit 1; } +# expect : run it, discard output, require that exit code. +expect() { + local want="$1" got=0 + shift + "$@" >/dev/null 2>&1 || got=$? + [[ "$got" -eq "$want" ]] || fail "expected exit $want, got $got: $*" +} + +for command in stats validate annotate render skill; do + expect 0 "$lk" "$command" --help +done + +# A folder with no annotations yet: stats works, validate says so with exit 1. +expect 0 "$lk" stats "$ds" +expect 1 "$lk" validate "$ds" + +# Write a box, then the same box again: the file must not change by a byte. +expect 0 "$lk" annotate "$ds" --image a.png --box 'thing:10,20,100,80' +cp "$ds/annotations.json" "$work/first.json" +expect 0 "$lk" annotate "$ds" --image a.png --box 'thing:10,20,100,80' +cmp -s "$ds/annotations.json" "$work/first.json" || fail "a repeated annotate changed the file" +grep -q '"x": 60' "$ds/annotations.json" || fail "expected a centre-anchored x of 60 on disk" + +# Piped model-style input, in another convention, for the second image. +echo '[{"box_2d": [100, 200, 500, 400], "label": "thing"}]' \ + | "$lk" annotate "$ds" --image b.png --from - >/dev/null +expect 0 "$lk" validate "$ds" --labels thing --strict + +# Bad input is refused whole: exit 1 and the file untouched. +cp "$ds/annotations.json" "$work/before-bad.json" +expect 1 "$lk" annotate "$ds" --image missing.png --box 'thing:1,1,5,5' +expect 1 "$lk" annotate "$ds" --image a.png --box 'thing:9000,9000,5,5' +cmp -s "$ds/annotations.json" "$work/before-bad.json" || fail "a refused annotate changed the file" + +# Usage errors are 64, before anything is read. +expect 64 "$lk" annotate "$ds" --box 'thing:1,1,5,5' +expect 64 "$lk" annotate "$ds" --image a.png --origin bottom-left --box 'thing:1,1,5,5' +expect 64 "$lk" stats "$work/no-such-dataset" + +# Reports are JSON with the documented fields. +"$lk" stats "$ds" | grep -q '"annotated" : 2' || fail "stats should count 2 annotated images" +"$lk" validate "$ds" | grep -q '"ok" : true' || fail "validate should report ok" + +# Render writes one picture per image. +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" + +# 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" +[[ -s "$work/skills/labelkit/SKILL.md" ]] || fail "skill --install didn't write SKILL.md" +"$lk" skill --snippet | grep -q 'labelkit stats' || fail "skill --snippet is missing its commands" + +echo "smoke: scripted subcommands ok" diff --git a/skills/labelkit/SKILL.md b/skills/labelkit/SKILL.md new file mode 100644 index 0000000..7b1a5b7 --- /dev/null +++ b/skills/labelkit/SKILL.md @@ -0,0 +1,201 @@ +--- +name: labelkit +description: Label images for object detection with the labelkit CLI on macOS. Adds, checks and fixes bounding boxes in Apple Create ML datasets (a folder of images with an annotations.json), runs Core ML or Vision detectors, and trains a Core ML object detector. Use when asked to annotate or label images, draw or correct bounding boxes, review or validate an object-detection dataset, or train a Create ML model. +--- + +# labelkit + +labelkit edits Apple Create ML object-detection datasets: a folder of images +plus one `annotations.json`. Drive it through its subcommands. They write the +file through the same code as the editor, so entry order, unknown keys, +negative examples and formatting all survive, and `git diff` shows only real +changes. + +## Ground rules + +- **Never edit `annotations.json` by hand.** Use `labelkit annotate`. +- **`labelkit ` with no subcommand opens the GUI editor.** Run it + only when the user wants to look at or fix labels themselves. Everything + below is headless. +- **stdout is the result (JSON), stderr is notes.** Parse stdout. +- **Exit codes:** `0` ok · `1` the command ran and found or hit a problem + (stdout says what) · `64` you called it wrong (read stderr, fix the call). +- **Coordinates are pixels of the image file, top-left origin, with `x`,`y` + at the box's top-left corner**, unless you state another convention with + flags. (On disk Create ML stores box centres; labelkit converts.) +- A dataset is addressed by its folder: `labelkit stats ./cards`. + +## The loop + +1. **See where things stand.** + `labelkit stats ` → counts, per-label totals, and `unlabeled` + (images with no entry yet, the work to do). +2. **Look at the images to label.** + `labelkit render --unlabeled --grid 100 --limit 10 --out ` + writes downscaled copies with a labelled line every 100 pixels of the + *original* image. Open them. The JSON gives each image's real `width` + and `height`. +3. **Write boxes.** + `labelkit annotate --image a.jpg --box 'cat:40,30,200,160' --box 'dog:300,90,120,210'` + or many images at once with `--from boxes.json` (shapes below). +4. **Check your work by eye.** + `labelkit render a.jpg --out ` draws the saved boxes, + numbered `#1`, `#2`, … Open the picture. If a box is off, fix it with + `--mode replace` (step 3 again for that image) and re-render. Expect two + or three passes on hard images. +5. **Check the dataset.** + `labelkit validate ` → exit `1` and a list of issues if anything + would break training. Fix and repeat. + +Before labelling a batch, agree the policy with the user and apply it the +same way everywhere, because inconsistent boxes hurt a detector more than +slightly loose ones: + +- **Extent:** the whole object, or only part of it (a card including its + border, or just the artwork)? +- **Cut-off and hidden objects:** box what is visible, or skip them? +- **Label names:** exact spelling. `validate --labels a,b,c` enforces the set. + +## Getting coordinates right + +You are usually shown a downscaled copy of an image, so pixel positions you +estimate are positions in *that copy*, not in the file. Three safe ways to +give boxes, best first: + +1. **Read them off the grid.** `render --grid N` labels its lines in + original-image pixels, so numbers read from the picture are already + correct. This is the most accurate method. +2. **Use relative units.** `--units normalized` (0–1) or `--units 0-1000` + are independent of image size. +3. **Say what size you looked at.** `--image-size 1568x1176`, or `"width"` + and `"height"` on a JSON entry, and labelkit rescales to the real image. + +Never guess a scale. A box that lies outside its image is rejected, not +silently moved. + +## Giving boxes to `annotate` + +Inline, for one image: + +``` +labelkit annotate --image a.jpg --box 'cat:40,30,200,160' +labelkit annotate --image a.jpg -l card --box 40,30,200,160 --box 300,90,120,210 +``` + +From a file or stdin (`--from -`), for any number of images. JSON, a JSON +array, or NDJSON; a Markdown code fence around it is fine: + +```json +{"image": "a.jpg", "boxes": [ + {"label": "cat", "x": 40, "y": 30, "width": 200, "height": 160} +]} +``` + +With `--image a.jpg --from answer.json` the file is just that image's boxes, +so a vision model's raw answer can be passed straight through. + +Shapes that describe themselves need no flags: + +| Box written as | Meaning | +|---|---| +| `"x","y","width","height"` (or under `"box"`) | the convention set by flags; by default top-left corner, pixels | +| `"normalized": {x,y,width,height}` | the same, as fractions 0–1 | +| `"xyxy": [x1,y1,x2,y2]`, or `x1/y1/x2/y2`, `xmin/ymin/xmax/ymax` keys | two corners | +| `"box_2d": [y1,x1,y2,x2]` | Gemini: y first, 0–1000 | +| `"bbox_2d": [x1,y1,x2,y2]` | Qwen: add `--units 0-1000` for Qwen3-VL | +| `"coordinates": {x,y,width,height}` | Create ML: centre-anchored pixels | +| a COCO file (`images`/`annotations`/`categories`) | read whole | +| `labelkit detect` output | read as is | + +For anything else, name the convention instead of converting numbers: + +| Flag | Use for | +|---|---| +| `--order xyxy` / `--order yxyx` | four bare numbers that are corners | +| `--anchor center` | `x`,`y` is the box centre | +| `--units normalized` / `0-1000` / `percent` | relative coordinates | +| `--units normalized --anchor center` | YOLO | +| `--units normalized --origin bottom-left` | Apple Vision | +| `--image-size WxH` | pixels of a resized copy | +| `-l NAME` | boxes that carry no label | + +Behaviour worth knowing: + +- **`--mode add` (default)** keeps existing boxes and skips any new box that + is already there (same label, overlapping). Re-running the same input + changes nothing, so retrying is always safe. +- **`--mode replace`** gives each listed image exactly the boxes supplied. + Other images are untouched. Use it to correct an image. +- **`--negatives`** records an image supplied with no boxes as a negative + example (an object-free image is real training signal). Without it, "no + boxes" writes nothing: `--image empty.jpg --negatives`. +- **`--dry-run`** reports what would change without writing. +- If any input is unusable (unknown image, box outside the image), nothing + is written and the exit code is `1`. `--lenient` applies the rest. +- Boxes hanging over an edge are trimmed and counted as `clamped`. + +## Letting a detector do the first pass + +``` +labelkit detect --model model.mlpackage --format ndjson | labelkit annotate --from - +labelkit detect --detector rectangles -l card --format ndjson | labelkit annotate --from - +``` + +`--detector` is a built-in Apple Vision detector (`rectangles`, `faces`, +`humans`, `animals`, `saliency`); `--model` is a Core ML object detector, +including one trained earlier on this dataset. Detections are a draft: +render and review them like any other boxes. + +## Checking a dataset + +`labelkit validate ` reports, as JSON `issues` with a stable `code`: + +- **errors** (exit 1): `no-annotations-file`, `missing-image`, + `duplicate-entry`, `empty-label`, `empty-box`, `box-outside-image`, + `unknown-label` (with `--labels`). +- **warnings** (exit 0, or 1 with `--strict`): `box-overflows-image`, + `duplicate-box`, `duplicate-image` (the same photo under two names), + `unreadable-image`, `unused-label`. + +Each issue names the `image` and the `box` number, matching the `#n` drawn +by `render`. + +`labelkit stats ` also shows what `validate` cannot judge: + +- labels with very few boxes. Apple's guidance is to start from roughly 30 + annotated images per class, balanced across classes; +- `boxesPerImage.max` and `maxImage`: one image with far more boxes than the + rest can skew a model, so look at it; +- `--per-image` lists every image with its status and box count. + +## Training + +``` +labelkit train -o model.mlmodel +``` + +Trains a Create ML object detector and prints a JSON report. It can take +minutes to hours and needs real image files (not symlinks). Run `validate` +first. Create ML holds out part of the data for validation on its own +(`--validation-split` to control it). See `labelkit train --help`. + +## When to hand over to the user + +The editor is the right tool for a human check: suggest `labelkit ` +when labels need a judgment call you cannot make from a picture, or before +training on labels nobody has reviewed. Say what you labelled and what you +were unsure about. + +## Command summary + +| Command | Does | Writes | +|---|---|---| +| `labelkit stats [--per-image]` | counts, labels, unlabelled images | nothing | +| `labelkit validate [--labels a,b] [--strict]` | finds problems, exit 1 on errors | nothing | +| `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 train [-o model.mlmodel]` | trains a Core ML detector | the model file | + +Every command has `--help` with examples. `stats`, `validate` and `annotate` +also take `--format text` for a human-readable summary. From 3ce5a79804bad2241c0a7b4c18a462a17216dff2 Mon Sep 17 00:00:00 2001 From: shellbear Date: Sat, 28 Nov 2026 17:18:56 +0100 Subject: [PATCH 3/3] docs: document agent integration; make AGENTS.md the project instructions - docs/agents.md: one-minute setup, per-client skill locations (Claude Code, Codex, opencode, Cursor, Gemini CLI, Antigravity, Copilot, Amp, Goose, Aider), the label-check-fix loop, how to review, input formats per model and tool, the JSON and exit-code contract, measured timings - README: a section on using labelkit from an agent and the scripted commands - CHANGELOG: the new commands and the faster load/save under Unreleased - AGENTS.md is now the canonical instructions file, read natively by most agent clients; CLAUDE.md imports it so Claude Code reads the same text. It gains a section on the scripted surface as a public interface. - .claude-plugin/marketplace.json lets Claude Code install the skill as a plugin (passes 'claude plugin validate') --- .claude-plugin/marketplace.json | 19 +++ AGENTS.md | 174 ++++++++++++++++++++++ CHANGELOG.md | 38 +++++ CLAUDE.md | 131 +--------------- README.md | 60 +++++++- docs/agents.md | 254 ++++++++++++++++++++++++++++++++ 6 files changed, 545 insertions(+), 131 deletions(-) create mode 100644 .claude-plugin/marketplace.json create mode 100644 AGENTS.md create mode 100644 docs/agents.md diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json new file mode 100644 index 0000000..e3181db --- /dev/null +++ b/.claude-plugin/marketplace.json @@ -0,0 +1,19 @@ +{ + "name": "labelkit", + "owner": { + "name": "shellbear" + }, + "metadata": { + "description": "Label images for object detection with the labelkit CLI." + }, + "plugins": [ + { + "name": "labelkit", + "source": "./", + "description": "Teaches Claude Code to label Apple Create ML object-detection datasets with the labelkit CLI: add and check bounding boxes, validate a dataset, run detectors, train a Core ML model.", + "homepage": "https://github.com/shellbear/labelkit", + "license": "MIT", + "skills": ["./skills/labelkit"] + } + ] +} diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..efd5259 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,174 @@ +# labelkit + + + +A native macOS bounding-box annotator for **Apple Create ML object-detection +datasets**, launched from the terminal: `labelkit `. It treats the +dataset's `annotations.json` as the source of truth — edit boxes, hit ⌘S, and +the file is rewritten in place, byte-stable and git-diff friendly. + +Pure SwiftPM: there is no `.xcodeproj`. `Package.swift` drives everything +(macOS 14+, Swift 5.9 tools). + +## Build & test + +```sh +swift run labelkit # dev run (GUI editor) +swift run labelkit detect --detector rectangles # headless detect subcommand +swift run labelkit train # headless train subcommand (Create ML → .mlmodel) +swift run labelkit stats # headless: what is labelled, what is not (JSON) +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 skill # print the guide for AI agents (SKILL.md) +swift build -c release # release binary at .build/release/labelkit +swift test # headless library tests +./scripts/package-app.sh # assemble labelkit.app next to the binary +./scripts/package-app.sh --universal # arm64+x86_64 fat build (used by release CI) +./scripts/make-icon.sh # recompile the app icon after editing its source +``` + +The app icon's source of truth is `Resources/AppIcon.icon`, an Icon Composer +document (SVG layers + `icon.json`). Its compiled forms — `Resources/Assets.car`, +`Resources/AppIcon.icns` and the README's `docs/icon.png` — are **committed**: +`package-app.sh` only copies them, so packaging and the release CI never need an +Xcode that understands `.icon` files. After changing the icon, run +`make-icon.sh` (Xcode 26+) and commit the regenerated files with it. + +The `Makefile` wraps these (`make build/test/app/universal/install`); +`make install` puts the CLI + app bundle into the Homebrew prefix's `bin`. + +For scale/perf testing, generate a realistic dataset instead of hand-rolling +one: `swift scripts/make-sample-dataset.swift 10000 /tmp/labelkit-sample` draws +a few dozen distinct camera-resolution JPEGs (real decode cost) and fans out to +N via symlinks (tiny on disk). See the `swift-perf-profiling` skill in +`.claude/skills/` for the headless xctrace capture/analyze workflow. (Those +symlinked images are fine for the editor and `detect`, but Create ML *training* +reads real files only — dereference first, e.g. `cp -L`, before `labelkit train`.) + +CI (`.github/workflows/ci.yml`) builds and runs the test suite on macOS 15 +and 26. GitHub retired the macOS 14 runner image on 2026-11-02, so the macOS 14 +minimum deployment target is guarded only at compile time, by the SDK's +availability checks against `Package.swift`'s `.macOS(.v14)`. It then +smoke-runs `.build/release/labelkit --version`, `labelkit detect --help`, and +`labelkit train --help` — those invocations must exit cleanly without ever +touching AppKit (no window flash) or kicking off Create ML — and drives the +scripted subcommands (`stats`, `annotate`, `validate`, `render`, `skill`) end to +end on a throwaway dataset, checking their exit codes and that a repeated +`annotate` leaves the file byte-identical. + +## Architecture: two targets, hard boundary + +- **`Sources/LabelKit`** — the library: format IO, dataset store, geometry, + imaging. **No AppKit or SwiftUI imports allowed here.** Everything must run + headless; all tests (`Tests/LabelKitTests`) target this module only. +- **`Sources/LabelKitApp`** — thin executable shell: ArgumentParser CLI, + AppKit app controller, SwiftUI views. The directory is named `LabelKitApp` + rather than `labelkit` because APFS is case-insensitive and would collide + with the `labelkit` product name. + +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 +`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: + +- **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 + found or hit a problem, **64** usage error. Never touch AppKit. +- Every JSON report carries `schemaVersion`. Adding a field is fine; renaming, + removing or changing the meaning of one means bumping it. +- `validate` issue `code`s and the `annotate` input shapes are part of the + contract — extend, don't repurpose. +- Writes go through `DatasetDocument.save()` → `CreateMLWriter`, so the format + contract below holds for scripted edits. `annotate --mode add` must stay + idempotent down to the bytes (there is a test, and a CI check). +- **`AgentGuide.skill` is the guide agents read**, served by `labelkit skill` + and committed as `skills/labelkit/SKILL.md`. A test fails if the two differ: + after changing a command's behaviour or flags, update the guide and run + `swift run labelkit skill > skills/labelkit/SKILL.md`. `docs/agents.md` is the + human-facing version (per-client setup); keep it in step too. + +These commands are expected to stay fast on large datasets (measured on 10,000 +images / 26,000 boxes: `stats` ≈ 0.2 s, `annotate` ≈ 0.1 s, `validate` ≈ 0.6 s). +The costs that matter are Foundation bridging — keep filenames and labels as +native Swift strings (`String.native`), read `JSONSerialization` output as +`NSDictionary` rather than casting to `[String: Any]` — and per-file IO, which +goes through `concurrentMap`. Measure before and after if you touch the loader, +scanner or writer. + +### Launch rules (don't "modernize" these) + +- There is no `@main`: ArgumentParser and SwiftUI both claim it, so + `main.swift` calls `LabelKitCommand.main()`. `LabelKitCommand` is a pure + dispatcher; its `open` subcommand is the default, and only `OpenCommand.run()` + hands off to the app (after arguments validate). Headless paths — `--version`, + `--help`, argument errors, and the entire `detect` subcommand — must never + initialize AppKit. CI smoke-tests both `--version` and `detect` to enforce it. +- The app is a classic AppKit shell with an **imperatively created + `NSWindow`** hosting SwiftUI (`LabelKitApp.swift`). SwiftUI's `WindowGroup` + never creates its window while the app is inactive, and macOS 14+ + cooperative activation refuses terminal-spawned processes — a bare CLI + launch showed nothing until a Dock click. Do not refactor back to the + SwiftUI `App`/`WindowGroup` lifecycle. +- The window carries an empty `NSToolbar` on purpose: a hosted + `NavigationSplitView` only gets the unified-titlebar chrome when the window + has a toolbar. The toolbar **items** are declared in SwiftUI with `.toolbar` + on the split view (`RootView`), *not* via an AppKit `NSToolbarDelegate`: the + hosted `NavigationSplitView` owns that toolbar (it injects the sidebar + toggle), so delegate-provided items are silently ignored. Don't reintroduce a + toolbar delegate — add controls to the `.toolbar` block instead. +- Later CLI invocations hand their dataset to the running instance via + `DistributedNotificationCenter` (see `SingleInstance.swift`) instead of + spawning a second app. + +## Format contract (do not break) + +labelkit's whole value is being a well-behaved editor of Create ML JSON. +Invariants, enforced by tests in `Tests/LabelKitTests`: + +- **Filenames are never rewritten** — whatever `"image"` says is saved back. +- **Zero-annotation entries round-trip** — negatives are training signal, not + garbage. Deleting the last box keeps the entry. +- **Unknown keys survive verbatim** on entries and annotations + (`imageWidth`, custom metadata, …). +- **Canonical byte-stable output**: stable key order, 2-decimal coordinates, + 2-space indent, trailing newline. The same input always saves to the same + bytes. +- Entries whose image file is missing on disk are flagged in the UI but saved + back untouched — datasets never silently shrink. + +If a change can alter saved bytes, extend the writer tests to prove stability +before and after. + +## Versioning & release + +`Sources/LabelKit/Version.swift` is the single source of truth for the +version. `scripts/package-app.sh` extracts it with a grep for a quoted +numeric literal, so keep the exact shape +`public let labelkitVersion = "X.Y.Z"`. + +`CHANGELOG.md` (Keep a Changelog format) is the single source of release +notes: user-facing changes go under `## [Unreleased]` as they land. + +Releasing = bump that file, rename `[Unreleased]` to `## [X.Y.Z] - YYYY-MM-DD` +(add a fresh empty `[Unreleased]` and update the compare links at the bottom), +commit, then run `make release` (`scripts/release.sh`). It checks the tree and +the changelog, creates and pushes the `vX.Y.Z` tag, waits for +`.github/workflows/release.yml` to build the universal + per-arch artifacts and +publish the GitHub release (the changelog section becomes the notes; +`scripts/release-notes.sh` extracts it and fails the release if the section is +missing), then runs `scripts/update-tap.sh` to point the Homebrew tap +(`shellbear/tap/labelkit`, thin slices via `on_arm`/`on_intel`) at the new +version and checksums. + +**A release is not done until the tap is updated.** CI cannot push to the tap +repo, so that step runs locally with your own git/gh credentials. If the tag +was pushed some other way, run `./scripts/update-tap.sh` once the Release +workflow is green (`--dry-run` shows the formula diff first). diff --git a/CHANGELOG.md b/CHANGELOG.md index 019e5bd..d6df892 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,44 @@ release notes, so every release needs a `## [X.Y.Z] - YYYY-MM-DD` heading here. ## [Unreleased] +### Added + +- **Use labelkit from an AI agent.** `labelkit skill --install` teaches Claude + Code, Codex, opencode, Cursor, Gemini CLI, GitHub Copilot, Amp, Goose and + other clients how to label with labelkit, by installing an Agent Skill where + each of them looks for one (`--project` for a single repository, + `--snippet` for a few lines of `AGENTS.md` instead). The guide is built into + the binary, so it always matches the installed version. See + [docs/agents.md](docs/agents.md). +- **`labelkit annotate`.** Write boxes into a dataset from the terminal: inline + (`--image a.jpg --box 'cat:40,30,200,160'`), or from JSON / NDJSON on a file + or stdin. It reads what vision models and other tools actually produce — + Gemini `box_2d`, corner lists, 0–1 and 0–1000 coordinates, YOLO-style + centres, COCO files, `labelkit detect` output — with `--units`, `--origin`, + `--anchor`, `--order` and `--image-size` to name a convention rather than + convert it. Adding is idempotent (a repeat run leaves the file byte-identical), + `--mode replace` corrects an image, `--negatives` records object-free images, + and a run with any unusable input writes nothing. +- **`labelkit stats`.** A JSON summary of a dataset: labelled, negative, + unlabelled and missing images, boxes per label, and the image with the most + boxes. +- **`labelkit validate`.** Checks a dataset and exits 1 on errors: missing + images, boxes outside their image, empty or unknown labels, duplicate + entries; and warns about overflowing boxes, duplicate boxes, and the same + photo saved under two names. +- **`labelkit render`.** Draws a dataset's boxes onto downscaled pictures to + check labels by eye, numbered to match `validate`. `--grid N` adds a ruler in + original-image pixels and `--unlabeled` renders the images still to do. +- **`labelkit --select `.** Opens the editor on a given image; + if the editor is already open it reloads the dataset and jumps there. + +### Changed + +- **Large datasets open and save faster.** Reading an annotations file, + listing the image folder and writing the file back were reworked; on a + 10,000-image dataset saving is about five times faster and loading about + twice as fast. Saved files are byte-for-byte what they were before. + ## [0.2.1] - 2026-11-28 ### Added diff --git a/CLAUDE.md b/CLAUDE.md index 3db9098..43c994c 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,130 +1 @@ -# labelkit - -A native macOS bounding-box annotator for **Apple Create ML object-detection -datasets**, launched from the terminal: `labelkit `. It treats the -dataset's `annotations.json` as the source of truth — edit boxes, hit ⌘S, and -the file is rewritten in place, byte-stable and git-diff friendly. - -Pure SwiftPM: there is no `.xcodeproj`. `Package.swift` drives everything -(macOS 14+, Swift 5.9 tools). - -## Build & test - -```sh -swift run labelkit # dev run (GUI editor) -swift run labelkit detect --detector rectangles # headless detect subcommand -swift run labelkit train # headless train subcommand (Create ML → .mlmodel) -swift build -c release # release binary at .build/release/labelkit -swift test # headless library tests -./scripts/package-app.sh # assemble labelkit.app next to the binary -./scripts/package-app.sh --universal # arm64+x86_64 fat build (used by release CI) -./scripts/make-icon.sh # recompile the app icon after editing its source -``` - -The app icon's source of truth is `Resources/AppIcon.icon`, an Icon Composer -document (SVG layers + `icon.json`). Its compiled forms — `Resources/Assets.car`, -`Resources/AppIcon.icns` and the README's `docs/icon.png` — are **committed**: -`package-app.sh` only copies them, so packaging and the release CI never need an -Xcode that understands `.icon` files. After changing the icon, run -`make-icon.sh` (Xcode 26+) and commit the regenerated files with it. - -The `Makefile` wraps these (`make build/test/app/universal/install`); -`make install` puts the CLI + app bundle into the Homebrew prefix's `bin`. - -For scale/perf testing, generate a realistic dataset instead of hand-rolling -one: `swift scripts/make-sample-dataset.swift 10000 /tmp/labelkit-sample` draws -a few dozen distinct camera-resolution JPEGs (real decode cost) and fans out to -N via symlinks (tiny on disk). See the `swift-perf-profiling` skill in -`.claude/skills/` for the headless xctrace capture/analyze workflow. (Those -symlinked images are fine for the editor and `detect`, but Create ML *training* -reads real files only — dereference first, e.g. `cp -L`, before `labelkit train`.) - -CI (`.github/workflows/ci.yml`) builds and runs the test suite on macOS 15 -and 26. GitHub retired the macOS 14 runner image on 2026-11-02, so the macOS 14 -minimum deployment target is guarded only at compile time, by the SDK's -availability checks against `Package.swift`'s `.macOS(.v14)`. It then -smoke-runs `.build/release/labelkit --version`, `labelkit detect --help`, and -`labelkit train --help` — those invocations must exit cleanly without ever -touching AppKit (no window flash) or kicking off Create ML. - -## Architecture: two targets, hard boundary - -- **`Sources/LabelKit`** — the library: format IO, dataset store, geometry, - imaging. **No AppKit or SwiftUI imports allowed here.** Everything must run - headless; all tests (`Tests/LabelKitTests`) target this module only. -- **`Sources/LabelKitApp`** — thin executable shell: ArgumentParser CLI, - AppKit app controller, SwiftUI views. The directory is named `LabelKitApp` - rather than `labelkit` because APFS is case-insensitive and would collide - with the `labelkit` product name. - -New logic belongs in `LabelKit` with tests unless it genuinely needs UI. - -### Launch rules (don't "modernize" these) - -- There is no `@main`: ArgumentParser and SwiftUI both claim it, so - `main.swift` calls `LabelKitCommand.main()`. `LabelKitCommand` is a pure - dispatcher; its `open` subcommand is the default, and only `OpenCommand.run()` - hands off to the app (after arguments validate). Headless paths — `--version`, - `--help`, argument errors, and the entire `detect` subcommand — must never - initialize AppKit. CI smoke-tests both `--version` and `detect` to enforce it. -- The app is a classic AppKit shell with an **imperatively created - `NSWindow`** hosting SwiftUI (`LabelKitApp.swift`). SwiftUI's `WindowGroup` - never creates its window while the app is inactive, and macOS 14+ - cooperative activation refuses terminal-spawned processes — a bare CLI - launch showed nothing until a Dock click. Do not refactor back to the - SwiftUI `App`/`WindowGroup` lifecycle. -- The window carries an empty `NSToolbar` on purpose: a hosted - `NavigationSplitView` only gets the unified-titlebar chrome when the window - has a toolbar. The toolbar **items** are declared in SwiftUI with `.toolbar` - on the split view (`RootView`), *not* via an AppKit `NSToolbarDelegate`: the - hosted `NavigationSplitView` owns that toolbar (it injects the sidebar - toggle), so delegate-provided items are silently ignored. Don't reintroduce a - toolbar delegate — add controls to the `.toolbar` block instead. -- Later CLI invocations hand their dataset to the running instance via - `DistributedNotificationCenter` (see `SingleInstance.swift`) instead of - spawning a second app. - -## Format contract (do not break) - -labelkit's whole value is being a well-behaved editor of Create ML JSON. -Invariants, enforced by tests in `Tests/LabelKitTests`: - -- **Filenames are never rewritten** — whatever `"image"` says is saved back. -- **Zero-annotation entries round-trip** — negatives are training signal, not - garbage. Deleting the last box keeps the entry. -- **Unknown keys survive verbatim** on entries and annotations - (`imageWidth`, custom metadata, …). -- **Canonical byte-stable output**: stable key order, 2-decimal coordinates, - 2-space indent, trailing newline. The same input always saves to the same - bytes. -- Entries whose image file is missing on disk are flagged in the UI but saved - back untouched — datasets never silently shrink. - -If a change can alter saved bytes, extend the writer tests to prove stability -before and after. - -## Versioning & release - -`Sources/LabelKit/Version.swift` is the single source of truth for the -version. `scripts/package-app.sh` extracts it with a grep for a quoted -numeric literal, so keep the exact shape -`public let labelkitVersion = "X.Y.Z"`. - -`CHANGELOG.md` (Keep a Changelog format) is the single source of release -notes: user-facing changes go under `## [Unreleased]` as they land. - -Releasing = bump that file, rename `[Unreleased]` to `## [X.Y.Z] - YYYY-MM-DD` -(add a fresh empty `[Unreleased]` and update the compare links at the bottom), -commit, then run `make release` (`scripts/release.sh`). It checks the tree and -the changelog, creates and pushes the `vX.Y.Z` tag, waits for -`.github/workflows/release.yml` to build the universal + per-arch artifacts and -publish the GitHub release (the changelog section becomes the notes; -`scripts/release-notes.sh` extracts it and fails the release if the section is -missing), then runs `scripts/update-tap.sh` to point the Homebrew tap -(`shellbear/tap/labelkit`, thin slices via `on_arm`/`on_intel`) at the new -version and checksums. - -**A release is not done until the tap is updated.** CI cannot push to the tap -repo, so that step runs locally with your own git/gh credentials. If the tag -was pushed some other way, run `./scripts/update-tap.sh` once the Release -workflow is green (`--dry-run` shows the formula diff first). +@AGENTS.md diff --git a/README.md b/README.md index 6029063..b098664 100644 --- a/README.md +++ b/README.md @@ -94,8 +94,65 @@ labelkit # a Create ML JSON; images resolved next to it labelkit # open panel labelkit --annotations other.json # explicit annotations path labelkit --images '*.jpg' # filter images by glob +labelkit --select IMG_0412.jpg # open on that image (reloads if already open) ``` +The same binary also works without the editor, for scripts and AI agents: + +```bash +labelkit stats # what is labelled and what isn't +labelkit annotate … # write boxes +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 +``` + +## Using it from an AI agent + +labelkit can be driven end to end from the terminal, so a coding agent can +label a dataset, check its own work, and hand it to you for review. + +```bash +labelkit skill --install +``` + +That one command teaches Claude Code, Codex, opencode, Cursor, Gemini CLI, +GitHub Copilot, Amp, Goose and other clients how to use labelkit: it installs a +small [Agent Skill](https://agentskills.io) where each of them looks for one. +For an agent without skills, `labelkit skill --snippet >> AGENTS.md` adds a few +lines instead. Then just ask: + +> Label the photos in `./cards` for object detection, one box per card. + +What the agent runs is the same loop you could run by hand: + +```bash +labelkit stats ./cards # what's left to do +labelkit render ./cards --unlabeled --grid 100 --out /tmp/todo # pictures with a pixel ruler +labelkit annotate ./cards --image IMG_0412.jpg --box 'card:412,230,318,455' +labelkit render ./cards IMG_0412.jpg --out /tmp/check # look at the result +labelkit validate ./cards # anything wrong? +labelkit ./cards --select IMG_0412.jpg # show you that image in the editor +``` + +- **Boxes go in the way your model gives them.** Gemini's `box_2d`, corner + lists, 0–1 or 0–1000 coordinates, YOLO-style centres, COCO files and + `labelkit detect` output are all accepted; you name the convention instead of + converting numbers. +- **Safe to retry.** Running the same `annotate` twice changes nothing, and a + run with any bad input writes nothing at all. +- **Still your file.** Scripted edits go through the same writer as the editor, + so every guarantee under [Why](#why) holds and `git diff` shows only the boxes + that changed. +- **Fast enough to loop on.** On 10,000 images, `stats` takes 0.2 s and + `annotate` 0.1 s. + +Stdout is JSON, stderr is notes, and exit codes are `0` ok, `1` problem found, +`64` usage error. No server and no MCP setup are involved. + +**[Full guide: per-client setup, input formats, the JSON contract →](docs/agents.md)** + ## Detecting from the CLI `labelkit detect` runs an object detector over an image (or a whole directory) @@ -207,7 +264,8 @@ Notes: ## Roadmap -- YOLO / COCO import & export (the format layer is already pluggable) +- YOLO import and YOLO / COCO export (COCO import already works through + `labelkit annotate --from`) ## License diff --git a/docs/agents.md b/docs/agents.md new file mode 100644 index 0000000..fb17f8e --- /dev/null +++ b/docs/agents.md @@ -0,0 +1,254 @@ +# Using labelkit from an AI agent + +labelkit can be driven end to end from the terminal, so a coding agent (Claude +Code, Codex, opencode, Cursor, Gemini CLI, GitHub Copilot, Amp, Goose, Aider, +…) can label a dataset, check its own work, and hand the result to you for +review in the editor. + +There is nothing to run in the background and no server to configure. The +agent calls the same `labelkit` binary you do; labelkit ships the instructions +that teach it how. + +## Set up in one minute + +```bash +brew install shellbear/tap/labelkit # if you haven't already +labelkit skill --install # teach your agents how to use it +``` + +Then ask your agent, in a project that has a folder of images: + +> Label the photos in `./cards` for object detection: one box per playing +> card, label `card`. Show me the ones you're unsure about. + +`labelkit skill --install` writes a small instruction file (an +[Agent Skill](https://agentskills.io)) to the two places agent clients look for +them, `~/.agents/skills/labelkit/` and `~/.claude/skills/labelkit/`. The agent +loads it only when a task calls for it. Run the command again after upgrading +labelkit: the guide is built into the binary, so it always describes the +version you have. + +## Per-client setup + +Locations are the ones each client documented in November 2026. If yours +differs, `labelkit skill --install --dir ` puts the skill +anywhere. + +| Client | Picks the skill up from | Set up with | +|---|---|---| +| **Claude Code** | `~/.claude/skills`, `.claude/skills` | `labelkit skill --install` | +| **Codex CLI** | `~/.agents/skills`, `.agents/skills` | `labelkit skill --install` | +| **opencode** | `~/.agents/skills`, `~/.claude/skills`, `~/.config/opencode/skills` | `labelkit skill --install` | +| **Cursor** | `~/.agents/skills`, `.agents/skills`, `~/.cursor/skills` | `labelkit skill --install` | +| **Gemini CLI** | `~/.agents/skills`, `~/.gemini/skills` | `labelkit skill --install` | +| **Antigravity CLI** | `.agents/skills` in the project, `~/.gemini/skills` | `labelkit skill --install --project`, or `--dir ~/.gemini/skills` | +| **GitHub Copilot** (CLI, coding agent) | `~/.agents/skills`, `.agents/skills`, `.github/skills` | `labelkit skill --install` | +| **Amp** | `~/.agents/skills`, `.agents/skills`, `~/.claude/skills` | `labelkit skill --install` | +| **Goose** | `~/.agents/skills`, `.agents/skills` | `labelkit skill --install` | +| **Aider**, and any agent without skills | whatever you tell it to read | `labelkit skill --snippet >> AGENTS.md` (Aider: add `read: AGENTS.md` to `.aider.conf.yml`) | + +Other ways to get the same file: + +- **For one project, shared with your team:** `labelkit skill --install --project` + writes `.agents/skills/labelkit/` and `.claude/skills/labelkit/` in the + current directory. Commit them. +- **From the repository, without labelkit installed yet:** + `npx skills add shellbear/labelkit` (the skill lives at + [`skills/labelkit/SKILL.md`](../skills/labelkit/SKILL.md)). +- **As a Claude Code plugin:** + `/plugin install labelkit --marketplace shellbear/labelkit`. +- **Just a few lines in `AGENTS.md`:** `labelkit skill --snippet` prints a short + section naming the commands. Any agent that can run a shell command can work + from that, and `labelkit --help` covers the rest. + +### Why there is no MCP server + +Every client above can already run shell commands, so a plain CLI with JSON +output works in all of them with nothing to install, start, or keep in sync. An +MCP server would add a second interface to maintain without reaching a single +extra client. + +## What the agent does + +The skill teaches this loop. You can run it by hand too; every step is one +command. + +```bash +# 1. Where do things stand? +labelkit stats ./cards +# → images, boxes per label, and "unlabeled": the images still to do + +# 2. Look at what needs labelling, with a pixel ruler drawn on +labelkit render ./cards --unlabeled --grid 100 --limit 10 --out /tmp/todo + +# 3. Write boxes +labelkit annotate ./cards --image IMG_0412.jpg \ + --box 'card:412,230,318,455' --box 'card:790,244,310,450' + +# 4. Draw the saved boxes and look again +labelkit render ./cards IMG_0412.jpg --out /tmp/check + +# 5. Anything wrong with the dataset as a whole? +labelkit validate ./cards +``` + +Two details make this dependable for a model working from pictures: + +- **The grid is in the original image's pixels.** A vision model is shown a + downscaled copy, so a position it estimates is a position in that copy. + `render --grid` labels its lines in real pixels, so numbers read off the + picture are already right. +- **Every step can be repeated.** Running the same `annotate` twice changes + nothing: boxes that are already there are skipped and the file's bytes stay + identical. An agent that retries after an interruption does no harm. + +## Reviewing the agent's work + +There are two reviewers, and each has its own tool: + +- **The agent checks itself with `render`.** It draws the saved boxes, numbered + `#1`, `#2`, …, onto downscaled JPEGs it can open. That is the quick inner + loop: 40 twelve-megapixel photos render in under half a second. +- **You check in the editor.** `labelkit ./cards --select IMG_0412.jpg` opens + the editor on that image. If the editor is already open on the dataset it + reloads from disk and jumps there, so an agent can run this to say "look at + this one". Fix a box by dragging it and press ⌘S. + +One caution: the editor does not notice changes made to `annotations.json` +while it is open. If an agent labels a dataset you have open, re-run +`labelkit ` to reload before you edit, or your next save will write the +older state back. (It asks before discarding unsaved edits of your own.) + +## Giving boxes to `annotate` + +By default a box is `x, y, width, height` in **pixels of the image file, with +`x`,`y` at the top-left corner**: + +```json +{"image": "a.jpg", "boxes": [ + {"label": "cat", "x": 40, "y": 30, "width": 200, "height": 160} +]} +``` + +Input can be one such object, a JSON array of them, or NDJSON, from a file +(`--from boxes.json`) or stdin (`--from -`). With `--image a.jpg` the input is +just that image's boxes. A Markdown code fence around the JSON is ignored, so a +model's raw answer can be piped straight in. + +You rarely need to convert anything. Shapes that describe themselves are read +as they are, and for the rest you name the convention with a flag: + +| What you have | How to pass it | +|---|---| +| **Gemini** — `[{"box_2d": [ymin, xmin, ymax, xmax], "label": …}]`, 0–1000 | `--image a.jpg --from answer.json` | +| **Claude, GPT** — ask for `{"label": …, "xyxy": [x1, y1, x2, y2]}` in pixels | `--image a.jpg --from answer.json`, plus `--image-size WxH` if the model saw a resized copy (or have it read the `render --grid` picture instead) | +| **Qwen3-VL** — `bbox_2d`, 0–1000 | `--units 0-1000` | +| **Qwen2.5-VL** — `bbox_2d`, pixels of the resized input | `--image-size WxH` | +| **Grounding DINO, OWL-ViT, Florence-2** — `boxes` and `labels` lists, corners in pixels | `--order xyxy` | +| **Moondream** — `objects` with `x_min … y_max`, 0–1, no label | `--units normalized -l cat` | +| **`labelkit detect`** output | `labelkit detect … --format ndjson \| labelkit annotate --from -` | +| **COCO** JSON | `--from instances.json` | +| **Create ML** annotations (to merge two datasets) | `--from other/annotations.json` | +| **YOLO** rows — `class cx cy w h`, normalized | as JSON boxes, with `--units normalized --anchor center` | +| **Label Studio** — percent units | `--units percent` | +| **Apple Vision** — normalized, origin bottom-left | `--units normalized --origin bottom-left` | +| Pascal VOC, CVAT, others | convert to COCO first (`supervision`, `datumaro` and FiftyOne all can) | + +The flags follow the three terms Create ML itself uses for annotations +(`--units`, `--origin`, `--anchor`), plus `--order` for four bare numbers +(`xywh`, `xyxy`, `yxyx`) and `--image-size` for coordinates measured on a +resized copy. Nothing is guessed from the values: a box that ends up outside +its image is reported, not moved. + +## The contract + +These hold for `stats`, `validate`, `annotate`, `render` and `skill`, and are +treated as a public interface. + +- **stdout is the result, and only the result.** JSON by default + (`--format text` for people). Notes and progress go to stderr. +- **Exit codes:** `0` success · `1` the command ran and found or hit a problem + (the JSON says what) · `64` usage error. +- **Reports are versioned.** Each carries `schemaVersion`; fields may be added, + but an existing field changing meaning bumps the version. +- **Writes are all-or-nothing.** If any input can't be applied — an image that + isn't in the dataset, a box outside its image — `annotate` writes nothing and + exits `1`. `--lenient` applies the valid part. `--dry-run` writes nothing + either way. +- **The file stays yours.** `annotate` writes through the same code as the + editor: entry order, unknown keys, negative examples and the file's own + indentation are preserved, and coordinates are saved to 2 decimals. `git diff` + shows the boxes that changed and nothing else. +- **Headless.** None of these commands opens a window or touches the GUI. + +### `annotate` report + +```json +{ + "schemaVersion": 1, + "mode": "add", + "dryRun": false, + "written": true, + "totals": { "images": 1, "added": 2, "duplicates": 0, "removed": 0, "clamped": 0 }, + "images": [ + { "image": "IMG_0412.jpg", "added": 2, "duplicates": 0, "removed": 0, + "clamped": 0, "total": 2, "created": true } + ], + "problems": [] +} +``` + +`duplicates` are boxes skipped because an equivalent one was already there. +`clamped` are boxes trimmed to the image edge. `problems` lists input that was +refused, each with its `image` and a `message`. + +### `validate` issues + +```json +{ "severity": "error", "code": "box-outside-image", "image": "IMG_0412.jpg", + "box": 3, "label": "card", "message": "box lies outside the 4032x3024 image (…)" } +``` + +| Code | Severity | Meaning | +|---|---|---| +| `no-annotations-file` | error | the dataset has no annotations file | +| `missing-image` | error | an entry's image file isn't in the folder | +| `duplicate-entry` | error | one image has two entries (only the first is used) | +| `empty-label` | error | a box has no label | +| `empty-box` | error | a box has zero or negative width or height | +| `box-outside-image` | error | a box lies entirely outside its image | +| `unknown-label` | error | a label isn't in `--labels a,b,c` | +| `box-overflows-image` | warning | a box extends past an image edge | +| `duplicate-box` | warning | two near-identical boxes with the same label | +| `duplicate-image` | warning | the same photo under two names (and whether they are labelled differently) | +| `unreadable-image` | warning | the image's size couldn't be read | +| `unused-label` | warning | a label from `--labels` has no boxes | + +Warnings exit `0` unless `--strict` is given. `box` is the box's position in +the image's annotations, starting at 1, and matches the `#n` that `render` +draws. + +## Speed + +The scripted commands are meant to be called in a loop, so they are kept +cheap. Measured on a 10,000-image dataset with 26,000 boxes (Apple silicon): + +| Command | Time | Peak memory | +|---|---|---| +| `labelkit stats` | 0.2 s | 44 MB | +| `labelkit annotate` (one image) | 0.1 s | 35 MB | +| `labelkit validate` | 0.5 s | 70 MB | + +On a dataset of a few hundred images each is a few hundredths of a second. +Images are only ever opened to read their dimensions (`annotate`, `validate`) +or to draw them (`render`), and that work is spread across cores. + +## For other tools and scripts + +Nothing here is specific to AI agents. The same commands work in a Makefile, a +CI job or a notebook: + +```bash +labelkit validate ./cards --labels card --strict # fail the build on a bad dataset +labelkit stats ./cards | jq '.images.unlabeled' # how much is left +```