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
109 changes: 0 additions & 109 deletions Bokashi/Detection/AppleIntelligenceSensitiveRegionDetector.swift

This file was deleted.

26 changes: 13 additions & 13 deletions Bokashi/Detection/AutoMasker.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,37 +13,37 @@ enum AutoMasker {
observations: [OCRRunner.TextObservation],
customTerms: [String]
) async -> [Detection] {
// Order is dedup priority: deterministic detectors first so their
// precise rects win over near-duplicate AI findings.
// Order is dedup priority: text findings first so their precise
// glyph rects win over overlapping face rects.
let settings = DetectionSettings.shared
var detectors: [any SensitiveRegionDetector] = [
OCRSensitiveRegionDetector(observations: observations, customTerms: customTerms)
TextSensitiveRegionDetector(
observations: observations,
customTerms: customTerms,
usesLanguageModel: settings.aiDetectionEnabled
)
]
let settings = DetectionSettings.shared
if settings.faceMaskingEnabled {
detectors.append(FaceSensitiveRegionDetector())
}
if settings.aiDetectionEnabled, AppleIntelligenceSensitiveRegionDetector.isModelAvailable {
detectors.append(AppleIntelligenceSensitiveRegionDetector(observations: observations))
}

var labeled: [(region: DetectedRegion, detectorIdentifier: String)] = []
var regions: [DetectedRegion] = []
for detector in detectors {
do {
let regions = try await detector.detect(in: image)
labeled.append(contentsOf: regions.map { ($0, detector.identifier) })
regions += try await detector.detect(in: image)
} catch {
continue
}
}

let kept = RegionDeduplicator.keptIndices(of: labeled.map(\.region))
let kept = RegionDeduplicator.keptIndices(of: regions)
return kept.map { index in
Detection(
annotation: Annotation(
kind: .mosaic(rect: labeled[index].region.rect),
kind: .mosaic(rect: regions[index].rect),
style: .defaultOutline
),
detectorIdentifier: labeled[index].detectorIdentifier
detectorIdentifier: regions[index].label
)
}
}
Expand Down
40 changes: 0 additions & 40 deletions Bokashi/Detection/OCRSensitiveRegionDetector.swift

This file was deleted.

51 changes: 51 additions & 0 deletions Bokashi/Detection/TextSensitiveRegionDetector.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import BokashiCore
import CoreGraphics
import Foundation
import FoundationModels
import PrivMask

/// Runs privmask over the OCR text. The on-device model's findings go
/// through the same `DetectionPipeline` as the deterministic ones so that
/// privmask's precedence rules apply to them — a model "name" that wraps a
/// phone number is dropped there, which a rect-level dedup cannot see.
///
/// Every candidate is masked regardless of confidence: model-only names are
/// `.low`, and they are the reason the model runs at all. The user deletes
/// extras in the editor.
@MainActor
struct TextSensitiveRegionDetector: SensitiveRegionDetector {
nonisolated let identifier = "text"

let observations: [OCRRunner.TextObservation]
let customTerms: [String]
let usesLanguageModel: Bool

/// Pages the on-device model in ahead of the first Detect click.
static func prewarmIfNeeded() {
guard DetectionSettings.shared.aiDetectionEnabled, FoundationModelDetector.isAvailable else { return }
LanguageModelSession().prewarm()
}

func detect(in image: CGImage) async throws -> [DetectedRegion] {
guard !observations.isEmpty else { return [] }
let joined = JoinedLines(observations.map(\.text))

var modelMatches: [DetectedMatch] = []
if usesLanguageModel, FoundationModelDetector.isAvailable {
modelMatches = (try? await FoundationModelDetector().detect(in: joined.text).matches) ?? []
}

let candidates = DetectionPipeline(dictionaryTerms: customTerms)
.detect(in: joined.text, additional: modelMatches)

return candidates.compactMap { candidate in
guard
let located = joined.locate(candidate.range),
let rect = observations[located.lineIndex].imageRect(forSubrange: located.range)
else { return nil }
// AutoMasker reads the label as the debug-overlay source.
let source = candidate.sources == [.languageModel] ? "appleIntelligence" : "ocr"
return DetectedRegion(rect: rect.insetBy(dx: -2, dy: -2), label: source)
}
}
}
2 changes: 1 addition & 1 deletion Bokashi/Editor/EditorWindowController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ final class EditorWindowController: NSWindowController, NSWindowDelegate {
window.center()

Task { @MainActor [state, image, autoMask] in
AppleIntelligenceSensitiveRegionDetector.prewarmIfNeeded()
TextSensitiveRegionDetector.prewarmIfNeeded()
await state.runOCR(on: image)
if autoMask {
// Silent on empty: auto-mask runs because the toggle is
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import Foundation

/// OCR lines joined with "\n" into one text, so a text-level detector sees
/// them as a document, with the ability to map a UTF-16 range in that text
/// back to the line it came from.
public struct JoinedLines: Sendable {
public struct Located: Hashable, Sendable {
public let lineIndex: Int
public let range: NSRange

public init(lineIndex: Int, range: NSRange) {
self.lineIndex = lineIndex
self.range = range
}
}

public let text: String
private let lineStarts: [Int]
private let lineLengths: [Int]

public init(_ lines: [String]) {
text = lines.joined(separator: "\n")
var starts: [Int] = []
var lengths: [Int] = []
var cursor = 0
for line in lines {
let length = (line as NSString).length
starts.append(cursor)
lengths.append(length)
cursor += length + 1
}
lineStarts = starts
lineLengths = lengths
}

/// A range that runs past the end of its line is cut back to that line.
public func locate(_ range: NSRange) -> Located? {
guard range.location != NSNotFound, range.length > 0 else { return nil }
guard let index = lineStarts.lastIndex(where: { $0 <= range.location }) else { return nil }
let local = range.location - lineStarts[index]
let length = min(range.length, lineLengths[index] - local)
guard length > 0 else { return nil }
return Located(lineIndex: index, range: NSRange(location: local, length: length))
}
}
Loading