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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 20 additions & 13 deletions Sources/LabelKit/Headless/AgentGuide.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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.)
Expand All @@ -89,7 +90,8 @@ public enum AgentGuide {
`labelkit render <dataset> --unlabeled --grid 100 --limit 10 --out <dir>`
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 <dataset> --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).
Expand Down Expand Up @@ -137,17 +139,19 @@ public enum AgentGuide {
labelkit annotate <dataset> --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": [
{"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.
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:

Expand Down Expand Up @@ -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

Expand All @@ -205,9 +212,9 @@ public enum AgentGuide {

`labelkit validate <dataset>` 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`.
Expand Down
79 changes: 52 additions & 27 deletions Sources/LabelKit/Headless/AnnotationMerge.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -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 {
Expand All @@ -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,
Expand All @@ -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
Expand All @@ -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 {
Expand Down
24 changes: 17 additions & 7 deletions Sources/LabelKit/Headless/BoxImport.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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) }) {
Expand Down Expand Up @@ -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)..<close.lowerBound])
guard let open = text.range(of: "```"),
let close = text.range(of: "```", options: .backwards),
close.lowerBound >= open.upperBound else { return text }
var body = text[open.upperBound..<close.lowerBound]
let info = body.prefix { $0.isLetter || $0.isNumber }
if !info.isEmpty, body.dropFirst(info.count).first?.isWhitespace == true {
body = body.dropFirst(info.count)
}
return String(body)
}

private static func isImageEntry(_ element: Any) -> Bool {
Expand Down
34 changes: 28 additions & 6 deletions Sources/LabelKit/Headless/DatasetDocument.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand All @@ -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) {
Expand Down
17 changes: 17 additions & 0 deletions Sources/LabelKit/Headless/DatasetValidator.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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
Expand Down
Loading
Loading