From acf4672603a94b87dff1a7008703dcf0728d6cd6 Mon Sep 17 00:00:00 2001 From: shellbear Date: Sat, 28 Nov 2026 17:29:36 +0100 Subject: [PATCH] fix: close the gaps an independent review found in the scripted commands A review of the merged scripted commands turned up defects, one destructive: - render --out overwrote the source images with downscaled, drawn-on copies. It is now refused (exit 64), however the folder is spelled. - annotate read stdin whenever it wasn't a terminal, so inside a 'while read' loop it swallowed the loop's input. stdin is now read only with --from -; naming an image with no boxes and no --negatives is a usage error instead of a silent no-op. - For up to 256 named images annotate checked existence only, so A.JPG created a second entry beside a.jpg and annotations.json was accepted as an image. Names must now match what a listing returns: an image extension, spelled as stored, not hidden, directly in the folder. - A negative width or height was silently flipped positive by CGRect. Refused. - A box under one pixel rounded to zero on disk and was re-added on every run, breaking idempotency. Refused. - --image-size (and an entry's width/height) was ignored when the image could not be read, writing unscaled numbers. Now a reported problem. - An image supplied with no boxes was cleared in replace mode without --negatives, so 'detect | annotate --mode replace' wiped labels wherever the detector found nothing. 'No boxes' is now a no-op in both modes unless --negatives is given; an image whose every box was refused is left alone. - A corrupt annotations file exited 64 with a usage banner. It is a dataset problem: exit 1, and validate reports it as invalid-annotations-file. Unparseable --from content is exit 1 as well. - With --image, a single box object is accepted, and a code fence on one line is stripped. - Records hold the 2-decimal values the file will hold, so replacing an image's boxes with the same boxes no longer reports a change. Each has a unit test, and the smoke test gained a check per command-level finding. Help text, the skill and docs/agents.md describe the new behaviour. --- Sources/LabelKit/Headless/AgentGuide.swift | 33 +++-- .../LabelKit/Headless/AnnotationMerge.swift | 79 ++++++++---- Sources/LabelKit/Headless/BoxImport.swift | 24 ++-- .../LabelKit/Headless/DatasetDocument.swift | 34 ++++- .../LabelKit/Headless/DatasetValidator.swift | 17 +++ Sources/LabelKitApp/AnnotateCommand.swift | 48 ++++--- Sources/LabelKitApp/HeadlessSupport.swift | 25 +++- Sources/LabelKitApp/RenderCommand.swift | 6 +- Sources/LabelKitApp/ValidateCommand.swift | 21 +++- .../LabelKitTests/BoxImportParserTests.swift | 18 +++ .../LabelKitTests/HeadlessDatasetTests.swift | 118 ++++++++++++++++-- docs/agents.md | 15 ++- scripts/smoke-scripted.sh | 41 ++++++ skills/labelkit/SKILL.md | 33 +++-- 14 files changed, 405 insertions(+), 107 deletions(-) diff --git a/Sources/LabelKit/Headless/AgentGuide.swift b/Sources/LabelKit/Headless/AgentGuide.swift index 25baa6f..bd3485c 100644 --- a/Sources/LabelKit/Headless/AgentGuide.swift +++ b/Sources/LabelKit/Headless/AgentGuide.swift @@ -74,7 +74,8 @@ public enum AgentGuide { 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). + (stdout says what, or stderr if there is no report) · `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.) @@ -89,7 +90,8 @@ public enum AgentGuide { `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`. + and `height`. `--out` is a scratch directory, never the dataset folder + (labelkit refuses that). 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). @@ -137,8 +139,9 @@ public enum AgentGuide { 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: + From a file or stdin, for any number of images. stdin is read only with + `--from -`. JSON, a JSON array, or NDJSON; a Markdown code fence around it + is fine: ```json {"image": "a.jpg", "boxes": [ @@ -146,8 +149,9 @@ public enum AgentGuide { ]} ``` - 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. + With `--image a.jpg --from answer.json` the file is just that image's boxes + (a list of them, or a single box object), so a vision model's raw answer can + be passed straight through. Shapes that describe themselves need no flags: @@ -181,13 +185,16 @@ public enum AgentGuide { 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`. + - **An image given with no boxes is left untouched**, in either mode, so a + detector that found nothing can never wipe existing labels. `--negatives` + makes it count: `--image empty.jpg --negatives` records an object-free + image as a negative example (real training signal), and + `--image a.jpg --mode replace --negatives` clears an image's boxes. - **`--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`. + - Boxes hanging over an edge are trimmed and counted as `clamped`. A box + smaller than one pixel, or with a negative width or height, is refused. ## Letting a detector do the first pass @@ -205,9 +212,9 @@ public enum AgentGuide { `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`). + - **errors** (exit 1): `no-annotations-file`, `invalid-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`. diff --git a/Sources/LabelKit/Headless/AnnotationMerge.swift b/Sources/LabelKit/Headless/AnnotationMerge.swift index 3f2311d..9a4c20d 100644 --- a/Sources/LabelKit/Headless/AnnotationMerge.swift +++ b/Sources/LabelKit/Headless/AnnotationMerge.swift @@ -24,9 +24,11 @@ public enum AnnotationMerge { /// 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. + /// Act on an image supplied with no boxes: record it as a negative + /// example (an entry with zero annotations), which in `replace` mode + /// also means clearing the boxes it had. Off by default, in both + /// modes, so that "the detector found nothing" never silently becomes + /// training signal or wipes existing labels. public var recordNegatives: Bool public init(mode: Mode = .add, dedupeIoU: CGFloat = 0.5, recordNegatives: Bool = false) { @@ -115,6 +117,10 @@ public enum AnnotationMerge { } } + // "No boxes" only means something when asked for; and an image + // whose every box was refused is left alone rather than emptied. + if supplied.isEmpty ? !options.recordNegatives : resolved.isEmpty { continue } + var boxes = existingIndex.map { document.records[$0].boxes } ?? [] var added = 0, duplicates = 0, removed = 0 switch options.mode { @@ -135,10 +141,8 @@ public enum AnnotationMerge { 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 + newRecords.append(ImageAnnotationRecord(image: image, boxes: boxes)) } outcomes.append(ImageOutcome( image: image, added: added, duplicates: duplicates, removed: removed, @@ -161,32 +165,41 @@ public enum AnnotationMerge { let label = box.label.trimmingCharacters(in: .whitespacesAndNewlines) guard !label.isEmpty else { return .failure(BoxImportError(message: "empty label")) } + // Judge the numbers as given: CGRect's own accessors would quietly + // flip a negative width or height into a positive one. + let given: CGRect + switch box.geometry { + case .pixels(let rect), .normalized(let rect), .scaledPixels(let rect, _): given = rect + } + guard given.origin.x.isFinite, given.origin.y.isFinite, + given.size.width.isFinite, given.size.height.isFinite, + given.size.width > 0, given.size.height > 0 else { + return .failure(BoxImportError(message: "width and height must be positive")) + } + 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 .pixels: + rect = given + case .scaledPixels(_, let reference): + guard let imageSize else { + return .failure(BoxImportError( + message: "coordinates measured on a \(Int(reference.width))x\(Int(reference.height)) copy " + + "need the image's own size, and the file can't be read")) } - case .normalized(let fraction): + // Same size (the usual case, e.g. `labelkit detect` output): the + // numbers are used as they are, with no float round trip. + // Otherwise scale from the copy to the real image. + let sx = imageSize.width / reference.width, sy = imageSize.height / reference.height + rect = imageSize == reference ? given : CGRect( + x: given.minX * sx, y: given.minY * sy, width: given.width * sx, height: given.height * sy) + case .normalized: 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")) + rect = CGRect(x: given.minX * imageSize.width, y: given.minY * imageSize.height, + width: given.width * imageSize.width, height: given.height * imageSize.height) } var wasClamped = false @@ -202,8 +215,20 @@ public enum AnnotationMerge { 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)) + // Coordinates are saved to 2 decimals, so a box under a pixel can round + // to nothing on disk — and then never match itself on a second run. + guard rect.width >= 1, rect.height >= 1 else { + return .failure(BoxImportError(message: "smaller than one pixel")) + } + // Hold the values the file will hold, so comparing records is the same + // as comparing saved bytes. + return .success((BoxRecord(label: label, x: saved(rect.midX), y: saved(rect.midY), + width: saved(rect.width), height: saved(rect.height)), wasClamped)) + } + + /// A coordinate at the precision `CreateMLWriter` stores. + private static func saved(_ value: CGFloat) -> Double { + (Double(value) * 100).rounded() / 100 } private static func isSameBox(_ a: BoxRecord, _ b: BoxRecord, threshold: CGFloat) -> Bool { diff --git a/Sources/LabelKit/Headless/BoxImport.swift b/Sources/LabelKit/Headless/BoxImport.swift index 4f4e71d..9169464 100644 --- a/Sources/LabelKit/Headless/BoxImport.swift +++ b/Sources/LabelKit/Headless/BoxImport.swift @@ -213,6 +213,11 @@ public enum BoxImportParser { switch whole { case let object as [String: Any]: if let coco = try coco(from: object) { return coco } + if let image = options.image, !isImageEntry(object) { + // A single box for the one named image. + return [ImportedImage(image: image, boxes: [try box( + from: object, at: "input (\(image))", convention: options.convention, options: options)])] + } return [try image(from: object, at: "input", options: options)] case let array as [Any]: if let image = options.image, array.contains(where: { !isImageEntry($0) }) { @@ -282,14 +287,19 @@ public enum BoxImportParser { 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. + /// A model asked for JSON usually wraps it in a Markdown fence, on its own + /// lines or all on one. Returns what is between the first and last fence, + /// without an info string such as `json`. 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)..= open.upperBound else { return text } + var body = text[open.upperBound.. Bool { diff --git a/Sources/LabelKit/Headless/DatasetDocument.swift b/Sources/LabelKit/Headless/DatasetDocument.swift index 908247e..27baabb 100644 --- a/Sources/LabelKit/Headless/DatasetDocument.swift +++ b/Sources/LabelKit/Headless/DatasetDocument.swift @@ -36,12 +36,7 @@ public struct DatasetDocument: Sendable { 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) - } + imagesOnDisk = onlyImages.uniqued().filter { Self.isListedImage($0, in: location.imagesDirectory) } } else { imagesOnDisk = ImageDirectoryScanner.scan(directory: location.imagesDirectory, glob: imageGlob) } @@ -50,6 +45,33 @@ public struct DatasetDocument: Sendable { /// Up to this many images, checking each beats listing a large directory. static let listingThreshold = 256 + /// Whether a directory listing would include `name` — answered for one + /// file without listing. The checks mirror `ImageDirectoryScanner`: an + /// image extension, directly in the folder, not hidden, and spelled exactly + /// as stored (the file system matches `A.JPG` to `a.jpg`; a listing never + /// would, and two spellings of one image must not become two entries). + static func isListedImage(_ name: String, in directory: URL) -> Bool { + guard !name.contains("/"), + ImageDirectoryScanner.imageExtensions.contains((name as NSString).pathExtension.lowercased()), + let values = try? URL(fileURLWithPath: directory.path + "/" + name) + .resourceValues(forKeys: [.nameKey, .isHiddenKey]) + else { return false } + return values.name == name && values.isHidden != true + } + + /// True when `url` is this dataset's images folder, however it is spelled + /// (symlinks, case, trailing slash). Output must never be written there: + /// a rendered `a.jpg` would replace the source `a.jpg`. + public func isImagesDirectory(_ url: URL) -> Bool { + func identity(_ url: URL) -> (any NSCopying & NSSecureCoding & NSObjectProtocol)? { + (try? url.resolvingSymlinksInPath().resourceValues(forKeys: [.fileResourceIdentifierKey]))? + .fileResourceIdentifier + } + if let a = identity(url), let b = identity(location.imagesDirectory) { return a.isEqual(b) } + return url.resolvingSymlinksInPath().standardizedFileURL.path + == location.imagesDirectory.resolvingSymlinksInPath().standardizedFileURL.path + } + /// For tests and callers that already hold the pieces. public init(location: DatasetLocation, records: [ImageAnnotationRecord], imagesOnDisk: [String], indentUnit: String = CreateMLWriter.defaultIndentUnit) { diff --git a/Sources/LabelKit/Headless/DatasetValidator.swift b/Sources/LabelKit/Headless/DatasetValidator.swift index 59cb941..96870c8 100644 --- a/Sources/LabelKit/Headless/DatasetValidator.swift +++ b/Sources/LabelKit/Headless/DatasetValidator.swift @@ -31,6 +31,8 @@ public struct ValidationReport: Codable, Equatable, Sendable { public enum Code: String, Codable, Sendable, CaseIterable { /// The annotations file doesn't exist. case noAnnotationsFile = "no-annotations-file" + /// The annotations file exists but can't be read as Create ML JSON. + case invalidAnnotationsFile = "invalid-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. @@ -56,6 +58,21 @@ public struct ValidationReport: Codable, Equatable, Sendable { } } +public extension ValidationReport { + /// The report for a dataset whose annotations file can't be read at all: + /// one error saying why, so `validate` still answers on stdout. + static func unreadable( + location: DatasetLocation, reason: String, labelkitVersion version: String = labelkitVersion + ) -> ValidationReport { + ValidationReport( + schemaVersion: 1, labelkit: version, + dataset: location.imagesDirectory.path, annotations: location.annotationsURL.path, + ok: false, errors: 1, warnings: 0, + issues: [Issue(severity: .error, code: .invalidAnnotationsFile, image: nil, box: nil, label: nil, + message: "the annotations file can't be read: \(reason)")]) + } +} + public enum DatasetValidator { public struct Options: Sendable { /// When set, any other label is an error and any of these with no boxes diff --git a/Sources/LabelKitApp/AnnotateCommand.swift b/Sources/LabelKitApp/AnnotateCommand.swift index 4446c7c..30adbd5 100644 --- a/Sources/LabelKitApp/AnnotateCommand.swift +++ b/Sources/LabelKitApp/AnnotateCommand.swift @@ -13,7 +13,8 @@ struct AnnotateCommand: ParsableCommand { discussion: """ Give boxes one of two ways: - --from FILE JSON, a JSON array, or NDJSON; '-' reads stdin. Each entry + --from FILE JSON, a JSON array, or NDJSON; '-' reads stdin (stdin is + never read unless you ask for it this way). Each entry names an image and lists its boxes: {"image": "a.jpg", "boxes": [ {"label": "cat", "x": 40, "y": 30, "width": 200, "height": 160}]} @@ -55,6 +56,11 @@ struct AnnotateCommand: ParsableCommand { twice changes nothing. replace gives the listed images exactly the boxes supplied and leaves every other image alone. + An image given with NO boxes is left untouched in both modes, so a + detector that found nothing can't create negatives or wipe labels by + accident. --negatives makes it count: the image is recorded as a + negative example, and with --mode replace its existing boxes are cleared. + 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 @@ -100,7 +106,7 @@ struct AnnotateCommand: ParsableCommand { @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.") + @Flag(name: .long, help: "Act on an image given with no boxes: record it as a negative example (with --mode replace, clearing its boxes).") var negatives = false @Flag(name: .long, help: "Report what would change without writing the file.") @@ -119,6 +125,12 @@ struct AnnotateCommand: ParsableCommand { if !box.isEmpty, from != nil { throw ValidationError("Use either --from or --box, not both.") } + // An image with no boxes and no --negatives changes nothing. Saying so + // beats exiting 0 — most often the boxes were piped in without --from -. + if let image, from == nil, box.isEmpty, !negatives { + throw ValidationError("No boxes given for \(image). Pass --box, read them with --from " + + "(--from - for stdin), or add --negatives to record an image that has none.") + } if let imageSize, BoxImportParser.parseSize(imageSize) == nil { throw ValidationError("--image-size must look like 1568x1176.") } @@ -179,9 +191,13 @@ struct AnnotateCommand: ParsableCommand { // 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 { + // Without --from, the boxes are the --box flags and nothing else. + // stdin is read only when asked for: a command that drained it + // unprompted would swallow the input of a surrounding `while read` loop. + guard let from else { + guard let image else { + throw ValidationError("Give boxes with --from (--from - for stdin), or --image with --box.") + } do { let boxes = try box.map { try BoxImportParser.parseInlineBox($0, options: parserOptions) } return [ImportedImage(image: image, boxes: boxes)] @@ -191,30 +207,24 @@ struct AnnotateCommand: ParsableCommand { } let data: Data - switch from { - case "-"?: + if from == "-" { data = FileHandle.standardInput.readDataToEndOfFile() - case let file?: - let url = URL(fileURLWithPath: (file as NSString).expandingTildeInPath) + } else { + let url = URL(fileURLWithPath: (from as NSString).expandingTildeInPath) guard let contents = try? Data(contentsOf: url) else { - throw ValidationError("Couldn't read \(file).") + throw ValidationError("Couldn't read \(from).") } 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). + // A named image with empty input still means "this image, no boxes". if parsed.isEmpty, let image { return [ImportedImage(image: image, boxes: [])] } return parsed } catch { - throw ValidationError("Couldn't read the boxes: \(Headless.describe(error))") + // The call was fine; what it was given was not. + Headless.note("couldn't read the boxes: \(Headless.describe(error))") + throw ExitCode(1) } } diff --git a/Sources/LabelKitApp/HeadlessSupport.swift b/Sources/LabelKitApp/HeadlessSupport.swift index db809d8..e8c4acf 100644 --- a/Sources/LabelKitApp/HeadlessSupport.swift +++ b/Sources/LabelKitApp/HeadlessSupport.swift @@ -8,22 +8,21 @@ import LabelKit /// /// - 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. +/// (stdout, or failing that stderr, 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 { + /// Find the dataset a path names. A path that isn't a dataset is a usage + /// error (exit 64). + static func locate(path: String, annotations: String?) throws -> DatasetLocation { 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) + return location } catch let error as ValidationError { throw error } catch { @@ -31,6 +30,20 @@ enum Headless { } } + /// Open a dataset for scripted work. An annotations file that exists but + /// can't be read is a problem with the dataset, not with the call: a note + /// on stderr and exit 1. + static func openDocument(path: String, annotations: String?, + onlyImages: [String]? = nil) throws -> DatasetDocument { + let location = try locate(path: path, annotations: annotations) + do { + return try DatasetDocument(location: location, onlyImages: onlyImages) + } catch { + note("can't read \(location.annotationsURL.path): \(describe(error))") + throw ExitCode(1) + } + } + /// 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 { diff --git a/Sources/LabelKitApp/RenderCommand.swift b/Sources/LabelKitApp/RenderCommand.swift index 1411c9f..5c31fb4 100644 --- a/Sources/LabelKitApp/RenderCommand.swift +++ b/Sources/LabelKitApp/RenderCommand.swift @@ -41,7 +41,7 @@ struct RenderCommand: ParsableCommand { @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).") + @Option(name: [.customShort("o"), .long], help: "Directory to write the rendered images into (created if needed). Not the dataset folder itself.") var out: String @Option(name: .long, help: "Explicit annotations.json path (overrides auto-detection).") @@ -112,6 +112,10 @@ struct RenderCommand: ParsableCommand { if let limit { targets = Array(targets.prefix(max(0, limit))) } let outURL = URL(fileURLWithPath: (out as NSString).expandingTildeInPath) + guard !document.isImagesDirectory(outURL) else { + throw ValidationError( + "--out is the dataset's own folder; rendering there would overwrite its images. Choose another directory.") + } do { try FileManager.default.createDirectory(at: outURL, withIntermediateDirectories: true) } catch { diff --git a/Sources/LabelKitApp/ValidateCommand.swift b/Sources/LabelKitApp/ValidateCommand.swift index d0043e2..1705c16 100644 --- a/Sources/LabelKitApp/ValidateCommand.swift +++ b/Sources/LabelKitApp/ValidateCommand.swift @@ -16,8 +16,9 @@ struct ValidateCommand: ParsableCommand { 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. + Errors (exit 1): no-annotations-file, invalid-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. @@ -41,7 +42,15 @@ struct ValidateCommand: ParsableCommand { var format: Headless.OutputFormat = .json func run() throws { - let document = try Headless.openDocument(path: path, annotations: annotations) + let location = try Headless.locate(path: path, annotations: annotations) + let document: DatasetDocument + do { + document = try DatasetDocument(location: location) + } catch { + // Unreadable annotations are exactly what validate exists to report. + emit(.unreadable(location: location, reason: Headless.describe(error))) + throw ExitCode(1) + } let allowed = labels?.split(separator: ",") .map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty } @@ -58,11 +67,15 @@ struct ValidateCommand: ParsableCommand { document, options: .init(allowedLabels: allowed, duplicateImages: duplicates), pixelSize: { sizes[$0] }) + emit(report) + if !report.ok || (strict && report.warnings > 0) { throw ExitCode(1) } + } + + private func emit(_ report: ValidationReport) { 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 { diff --git a/Tests/LabelKitTests/BoxImportParserTests.swift b/Tests/LabelKitTests/BoxImportParserTests.swift index 1fe4d68..3ea109c 100644 --- a/Tests/LabelKitTests/BoxImportParserTests.swift +++ b/Tests/LabelKitTests/BoxImportParserTests.swift @@ -88,6 +88,24 @@ final class BoxImportParserTests: XCTestCase { assertNormalized(parsed[1].geometry, 0, 0, 1, 1) } + func testCodeFenceOnOneLineAndWithoutAnInfoString() throws { + let oneLine = try boxes("```json [{\"box_2d\": [100, 200, 500, 400], \"label\": \"cat\"}] ```") + assertNormalized(oneLine[0].geometry, 0.2, 0.1, 0.2, 0.4) + let bare = try boxes("```\n[{\"label\": \"cat\", \"xyxy\": [1, 2, 3, 4]}]\n```") + XCTAssertEqual(bare[0].geometry, .pixels(CGRect(x: 1, y: 2, width: 2, height: 2))) + // Text that merely contains one fence is left as it is. + XCTAssertEqual(BoxImportParser.stripCodeFence("a ``` b"), "a ``` b") + XCTAssertEqual(BoxImportParser.stripCodeFence("no fence"), "no fence") + } + + /// The simplest thing a model can answer for one image: one box. + func testASingleBoxObjectForANamedImage() throws { + let parsed = try boxes(#"{"label": "cat", "xyxy": [40, 30, 240, 190]}"#) + XCTAssertEqual(parsed, [ImportedBox(label: "cat", geometry: .pixels(CGRect(x: 40, y: 30, width: 200, height: 160)))]) + // Without a named image the same object has no image to go to. + XCTAssertThrowsError(try parse(#"{"label": "cat", "xyxy": [40, 30, 240, 190]}"#)) + } + func testGeminiBox2DKeepsItsMeaningWhateverTheFlagsSay() throws { let parsed = try boxes(#"[{"box_2d":[100,200,500,400],"label":"cat"}]"#, .init(units: .pixel, anchor: .center, order: .xyxy)) diff --git a/Tests/LabelKitTests/HeadlessDatasetTests.swift b/Tests/LabelKitTests/HeadlessDatasetTests.swift index 26c0948..341c2e5 100644 --- a/Tests/LabelKitTests/HeadlessDatasetTests.swift +++ b/Tests/LabelKitTests/HeadlessDatasetTests.swift @@ -117,10 +117,13 @@ final class HeadlessDatasetTests: XCTestCase { try Data([0xFF]).write(to: outside) defer { try? FileManager.default.removeItem(at: outside) } + try Data([0xFF]).write(to: tempDir.appendingPathComponent(".hidden.jpg")) 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") + onlyImages: ["c.jpg", "nope.jpg", "c.jpg", "a.jpg", "../\(outside.lastPathComponent)", + "A.JPG", "C.jpg", "annotations.json", ".hidden.jpg"]) + XCTAssertEqual(document.imagesOnDisk, ["c.jpg", "a.jpg"], + "what a listing would return: images, spelled as stored, not hidden, in this folder") XCTAssertEqual(document.records.count, 3, "the annotations file is still read in full") // Past the threshold it falls back to a normal listing. @@ -129,6 +132,20 @@ final class HeadlessDatasetTests: XCTestCase { ["a.jpg", "b.jpg", "c.jpg", "d.jpg"]) } + func testImagesDirectoryIsRecognisedHoweverItIsSpelled() throws { + let document = try load() + XCTAssertTrue(document.isImagesDirectory(tempDir)) + XCTAssertTrue(document.isImagesDirectory(URL(fileURLWithPath: tempDir.path + "/"))) + XCTAssertTrue(document.isImagesDirectory(tempDir.appendingPathComponent("sub/.."))) + let link = tempDir.deletingLastPathComponent().appendingPathComponent("link-\(UUID().uuidString)") + try FileManager.default.createSymbolicLink(at: link, withDestinationURL: tempDir) + defer { try? FileManager.default.removeItem(at: link) } + XCTAssertTrue(document.isImagesDirectory(link)) + + XCTAssertFalse(document.isImagesDirectory(tempDir.appendingPathComponent("renders")), "a subfolder is fine") + XCTAssertFalse(document.isImagesDirectory(tempDir.deletingLastPathComponent())) + } + // MARK: - Merge: add func testAddWritesCentreAnchoredCoordinatesAndAppendsNewEntriesInNameOrder() throws { @@ -224,7 +241,7 @@ final class HeadlessDatasetTests: XCTestCase { 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) + XCTAssertEqual(saved[1].x, 116.92, "records hold the 2-decimal values the file will hold") } func testBoxHangingOverAnEdgeIsClampedAndCounted() throws { @@ -282,12 +299,85 @@ final class HeadlessDatasetTests: XCTestCase { XCTAssertEqual(document.records[2].boxes.count, 1, "ghost.jpg untouched") } - func testReplaceWithNoBoxesLeavesANegativeNotAHole() throws { + /// `detect … | annotate --mode replace` lists every image, including the + /// ones where the detector found nothing. Those must not be wiped. + func testReplaceWithNoBoxesLeavesTheImageAloneUnlessNegativesAreAsked() throws { + var untouched = try load() + let skipped = AnnotationMerge.apply([ImportedImage(image: "b.jpg", boxes: [])], + to: &untouched, options: .init(mode: .replace), pixelSize: size) + XCTAssertFalse(skipped.changed) + XCTAssertTrue(skipped.outcomes.isEmpty) + XCTAssertEqual(untouched.records[0].boxes.count, 1) + + var cleared = try load() + let result = AnnotationMerge.apply( + [ImportedImage(image: "b.jpg", boxes: [])], to: &cleared, + options: .init(mode: .replace, recordNegatives: true), pixelSize: size) + XCTAssertEqual(result.outcomes.first?.removed, 1) + XCTAssertEqual(cleared.records.map(\.image), ["b.jpg", "a.jpg", "ghost.jpg"], "a negative, not a hole") + XCTAssertTrue(cleared.records[0].boxes.isEmpty) + } + + /// With --lenient the valid input is applied; an image whose every box was + /// refused must not be emptied by a replace. + func testReplaceLeavesAnImageAloneWhenAllItsBoxesWereRefused() 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) + let result = AnnotationMerge.apply( + [ImportedImage(image: "b.jpg", boxes: [pixels("card", 900, 900, 10, 10)])], + to: &document, options: .init(mode: .replace, recordNegatives: true), pixelSize: size) + XCTAssertEqual(result.problems.count, 1) + XCTAssertFalse(result.changed) + XCTAssertEqual(document.records[0].boxes.count, 1) + } + + func testReplacingWithTheSameBoxesChangesNothing() throws { + var document = try load() + // b.jpg holds card centred 50,50 size 20x20 with an extra key; the same + // geometry without the extra is a real change, the second run is not. + let same = [ImportedImage(image: "b.jpg", boxes: [pixels("card", 40.001, 40.002, 20.003, 19.999)])] + XCTAssertTrue(AnnotationMerge.apply(same, to: &document, options: .init(mode: .replace), pixelSize: size).changed) + XCTAssertFalse(AnnotationMerge.apply(same, to: &document, options: .init(mode: .replace), pixelSize: size).changed) + } + + // MARK: - Merge: boxes that must be refused + + func testNegativeSizesAreRefusedNotFlipped() throws { + var document = try load() + let result = AnnotationMerge.apply([ImportedImage(image: "c.jpg", boxes: [ + pixels("card", 100, 80, -50, -40), + ImportedBox(label: "card", geometry: .normalized(CGRect(x: 0.5, y: 0.5, width: -0.2, height: 0.2))), + ImportedBox(label: "card", geometry: .scaledPixels( + CGRect(x: 10, y: 10, width: 20, height: -5), reference: CGSize(width: 100, height: 50))), + ])], to: &document, pixelSize: size) + XCTAssertEqual(result.problems.count, 3) + XCTAssertTrue(result.problems.allSatisfy { $0.message.contains("positive") }) + XCTAssertFalse(result.changed) + } + + /// A box that would round to zero on disk could never match itself again. + func testBoxesSmallerThanAPixelAreRefused() throws { + var document = try load() + let result = AnnotationMerge.apply([ImportedImage(image: "c.jpg", boxes: [ + pixels("card", 10, 10, 0.004, 0.004), + pixels("card", 10, 10, 50, 0.9), + ImportedBox(label: "card", geometry: .normalized(CGRect(x: 0.1, y: 0.1, width: 0.001, height: 0.5))), + ])], to: &document, pixelSize: size) + XCTAssertEqual(result.problems.map(\.message), Array(repeating: "box #1 (card): smaller than one pixel", count: 1) + + ["box #2 (card): smaller than one pixel", "box #3 (card): smaller than one pixel"]) + XCTAssertFalse(result.changed) + } + + /// Coordinates tied to a copy's size can't be placed without the real size; + /// writing them unscaled would be a guess. + func testResizedCopyCoordinatesNeedAReadableImage() throws { + var document = try load() + let box = ImportedBox(label: "card", geometry: .scaledPixels( + CGRect(x: 1, y: 1, width: 2, height: 2), reference: CGSize(width: 800, height: 600))) + let result = AnnotationMerge.apply([ImportedImage(image: "ghost.jpg", boxes: [box])], + to: &document, pixelSize: size) + XCTAssertEqual(result.problems.count, 1) + XCTAssertTrue(result.problems[0].message.contains("800x600")) + XCTAssertFalse(result.changed) } func testAnImageWithNoBoxesIsOnlyRecordedAsANegativeWhenAsked() throws { @@ -424,6 +514,18 @@ final class HeadlessDatasetTests: XCTestCase { XCTAssertTrue(report.issues.isEmpty) } + func testUnreadableAnnotationsFileStillGetsAReport() throws { + let location = try XCTUnwrap(DatasetLocator.resolve(path: tempDir.path)) + try Data(#"{"not": "an array"}"#.utf8).write(to: annotationsURL) + XCTAssertThrowsError(try DatasetDocument(location: location)) + + let report = ValidationReport.unreadable(location: location, reason: "not an array", labelkitVersion: "test") + XCTAssertFalse(report.ok) + XCTAssertEqual(report.errors, 1) + XCTAssertEqual(report.issues.map(\.code), [.invalidAnnotationsFile]) + XCTAssertEqual(report.issues[0].message, "the annotations file can't be read: not an array") + } + func testValidateReportsAMissingAnnotationsFile() throws { try FileManager.default.removeItem(at: annotationsURL) let report = DatasetValidator.validate(try load(), pixelSize: size) diff --git a/docs/agents.md b/docs/agents.md index fb17f8e..f5fa675 100644 --- a/docs/agents.md +++ b/docs/agents.md @@ -131,8 +131,9 @@ By default a box is `x, y, width, height` in **pixels of the image file, with ``` 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 +(`--from boxes.json`) or stdin (`--from -`; stdin is never read unless you ask +for it this way). With `--image a.jpg` the input is just that image's boxes, as +a list or a single box. 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 @@ -168,13 +169,20 @@ 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. + (the JSON says what; if the input itself was unreadable, stderr does) · `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. +- **"No boxes" changes nothing unless you say so.** An image given with an + empty box list is left untouched in both modes, so piping a detector through + `annotate` can't create negatives or wipe labels where it found nothing. + `--negatives` makes it count (and with `--mode replace`, clears the image). +- **Source images are never written.** `render` refuses an `--out` that is the + dataset folder. - **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` @@ -212,6 +220,7 @@ refused, each with its `image` and a `message`. | Code | Severity | Meaning | |---|---|---| | `no-annotations-file` | error | the dataset has no annotations file | +| `invalid-annotations-file` | error | the annotations file can't be read as Create ML JSON | | `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 | diff --git a/scripts/smoke-scripted.sh b/scripts/smoke-scripted.sh index 01c1735..13f03da 100755 --- a/scripts/smoke-scripted.sh +++ b/scripts/smoke-scripted.sh @@ -54,6 +54,47 @@ 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" +# stdin belongs to the caller: without --from it is left alone, so a loop +# feeding image names is not swallowed by the first command. +count=0 +while read -r name; do + expect 0 "$lk" annotate "$ds" --image "$name" --negatives --dry-run + count=$((count + 1)) +done < <(printf 'a.png\nb.png\n') +[[ "$count" -eq 2 ]] || fail "annotate consumed the loop's stdin (ran $count of 2)" + +# "No boxes" is a no-op unless --negatives says otherwise, even with replace. +echo '{"image": "a.png", "boxes": []}' | "$lk" annotate "$ds" --from - --mode replace >/dev/null +cmp -s "$ds/annotations.json" "$work/before-bad.json" || fail "an empty box list wiped an image without --negatives" + +# A name is only accepted spelled as it is on disk, and only for images. +expect 1 "$lk" annotate "$ds" --image A.PNG --box 'thing:1,1,5,5' +expect 1 "$lk" annotate "$ds" --image annotations.json --box 'thing:1,1,5,5' +expect 1 "$lk" annotate "$ds" --image a.png --box 'thing:10,10,-50,-40' +cmp -s "$ds/annotations.json" "$work/before-bad.json" || fail "a refused annotate changed the file" + +# Rendering into the dataset folder would overwrite the images: refused. +cp "$ds/a.png" "$work/a-original.png" +expect 64 "$lk" render "$ds" --out "$ds" +expect 64 "$lk" render "$ds" --out "$ds/../dataset/" +cmp -s "$ds/a.png" "$work/a-original.png" || fail "render touched a source image" + +# An annotations file that isn't Create ML JSON is a dataset problem (1), not a +# usage error, and validate still reports it as JSON. +broken="$work/broken" +mkdir "$broken" +cp docs/icon.png "$broken/a.png" +echo '{"not": "an array"}' > "$broken/annotations.json" +expect 1 "$lk" stats "$broken" +expect 1 "$lk" validate "$broken" +report="$("$lk" validate "$broken" 2>/dev/null || true)" +grep -q '"invalid-annotations-file"' <<<"$report" \ + || fail "validate should report an unreadable annotations file as an issue" +expect 1 "$lk" annotate "$ds" --from "$broken/annotations.json" + +# Piping boxes in without --from - would silently do nothing; it is refused. +expect 64 "$lk" annotate "$ds" --image a.png + # 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' diff --git a/skills/labelkit/SKILL.md b/skills/labelkit/SKILL.md index 7b1a5b7..8629331 100644 --- a/skills/labelkit/SKILL.md +++ b/skills/labelkit/SKILL.md @@ -19,7 +19,8 @@ changes. 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). + (stdout says what, or stderr if there is no report) · `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.) @@ -34,7 +35,8 @@ changes. `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`. + and `height`. `--out` is a scratch directory, never the dataset folder + (labelkit refuses that). 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). @@ -82,8 +84,9 @@ 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: +From a file or stdin, for any number of images. stdin is read only with +`--from -`. JSON, a JSON array, or NDJSON; a Markdown code fence around it +is fine: ```json {"image": "a.jpg", "boxes": [ @@ -91,8 +94,9 @@ array, or NDJSON; a Markdown code fence around it is fine: ]} ``` -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. +With `--image a.jpg --from answer.json` the file is just that image's boxes +(a list of them, or a single box object), so a vision model's raw answer can +be passed straight through. Shapes that describe themselves need no flags: @@ -126,13 +130,16 @@ Behaviour worth knowing: 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`. +- **An image given with no boxes is left untouched**, in either mode, so a + detector that found nothing can never wipe existing labels. `--negatives` + makes it count: `--image empty.jpg --negatives` records an object-free + image as a negative example (real training signal), and + `--image a.jpg --mode replace --negatives` clears an image's boxes. - **`--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`. +- Boxes hanging over an edge are trimmed and counted as `clamped`. A box + smaller than one pixel, or with a negative width or height, is refused. ## Letting a detector do the first pass @@ -150,9 +157,9 @@ render and review them like any other boxes. `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`). +- **errors** (exit 1): `no-annotations-file`, `invalid-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`.