Cotton code
154 lines · 9.0 KB · SwiftRaw
// WHAT THE PASS MEASURED (the lane's report: photos per minute, what 64,000 costs, what the phone holds offline, how// the face models compare). Read from the store; in the Dev build also written to the app's Documents as// `albums-measure.json` and, row by row, `albums-export.jsonl` (each photo's file name, date, print, scores and face// vectors) so the synthetic library's known moments and people can score Sets and faces on the Mac. Synthetic// libraries only: nothing here is ever read from a person's own photos.#if os(iOS)import Foundationenum AlbumsMeasure {    struct Numbers: Codable, Sendable {        var total = 0, photos = 0, videos = 0, looked = 0, onlyInCloud = 0, failed = 0, degraded = 0        /// Looked at from a picture short of 256 px, owed a closer look.        var small = 0        var sideMedian = 0, sideMin = 0, sideMax = 0        var lookMillisMean = 0.0, lookMillisP90 = 0.0        var perMinute: Double?        /// The pass's own time, its whole-look rate, the most memory it held (MB), memory warnings and heat rests.        var seconds = 0, averagePerMinute: Double?, peakFootprintMB = 0, memoryWarnings = 0, throttled = 0        var minutesFor64000: Double?        var bytes: Int64 = 0, exactShare = 0.0        var screenshots = 0, utility = 0, documents = 0, blurry = 0, dark = 0, bursts = 0        var faces = 0, facesBig = 0, vectors = 0, model: String?        var printLength = 0, printRevision = 0        var storeBytes: Int64 = 0    }    static func numbers() -> Numbers {        let store = AlbumsStore.shared        let items = store.items(vectors: true)        let counts = store.counts()        var n = Numbers()        n.total = counts.total; n.photos = counts.photos; n.videos = counts.videos; n.looked = counts.looked        n.onlyInCloud = counts.onlyInCloud; n.failed = counts.failed; n.small = counts.small        n.perMinute = counts.perMinute        let seconds = Double(store.meta("pass.seconds") ?? "") ?? 0        n.seconds = Int(seconds)        n.averagePerMinute = AlbumsPass.perMinute(counts, seconds: seconds)        n.peakFootprintMB = AlbumsPass.peakFootprintMB        n.memoryWarnings = AlbumsPass.memoryWarnings        n.throttled = AlbumsPass.throttled        n.minutesFor64000 = counts.perMinute.map { 64_000 / $0 }        n.bytes = counts.bytes        n.exactShare = counts.total > 0 ? Double(counts.exactBytes) / Double(counts.total) : 0        let looks = items.compactMap(\.look)        n.degraded = looks.filter(\.degraded).count        let sides = looks.map(\.side).sorted()        if !sides.isEmpty { n.sideMedian = sides[sides.count / 2]; n.sideMin = sides[0]; n.sideMax = sides[sides.count - 1] }        let millis = looks.map(\.millis).sorted()        if !millis.isEmpty {            n.lookMillisMean = millis.reduce(0, +) / Double(millis.count)            n.lookMillisP90 = millis[min(millis.count - 1, millis.count * 9 / 10)]        }        n.screenshots = items.filter { $0.asset.flags.contains(.screenshot) }.count        n.utility = looks.filter(\.utility).count        n.documents = looks.filter(\.document).count        n.blurry = looks.filter { $0.sharpness < 60 }.count        n.dark = looks.filter { $0.light < 0.12 }.count        n.bursts = Set(items.compactMap(\.asset.burst)).count        let faces = looks.flatMap(\.faces)        n.faces = faces.count        n.facesBig = faces.filter { $0.pixels >= AlbumsAnalysis.faceMinimum }.count        n.vectors = faces.filter { $0.vector != nil }.count        n.model = faces.compactMap(\.model).first ?? AlbumsFaces.model?.name        n.printLength = looks.first(where: { $0.printLength > 0 })?.printLength ?? 0        n.printRevision = looks.first(where: { $0.printRevision > 0 })?.printRevision ?? 0        n.storeBytes = (try? FileManager.default.attributesOfItem(atPath: AlbumsStore.url.path)[.size] as? Int64) ?? 0        return n    }    static func lines() async -> [(String, String)] {        let n = await Task.detached { numbers() }.value        #if COTTON_DEV        await Task.detached { write(n) }.value        #endif        func f(_ v: Double?) -> String { v.map { String(format: "%.0f", $0) } ?? "–" }        return [            ("Assets", n.total.formatted()), ("Photos", n.photos.formatted()), ("Videos", n.videos.formatted()),            ("Looked", n.looked.formatted()), ("Only in iCloud", n.onlyInCloud.formatted()), ("Owed a closer look", n.small.formatted()), ("Failed", n.failed.formatted()),            ("Degraded pictures", n.degraded.formatted()),            ("Picture side (median, min–max)", "\(n.sideMedian) (\(n.sideMin)–\(n.sideMax))"),            ("Look ms (mean, p90)", String(format: "%.1f, %.1f", n.lookMillisMean, n.lookMillisP90)),            ("Photos a minute", f(n.perMinute)), ("Minutes for 64,000", f(n.minutesFor64000)),            ("Size", AlbumsWords.size(n.bytes)), ("Exact sizes", String(format: "%.0f%%", n.exactShare * 100)),            ("Screenshots", n.screenshots.formatted()), ("Utility", n.utility.formatted()), ("Documents", n.documents.formatted()),            ("Blurry", n.blurry.formatted()), ("Dark", n.dark.formatted()), ("Bursts", n.bursts.formatted()),            ("Faces", n.faces.formatted()), ("Faces 48 px+", n.facesBig.formatted()), ("Vectors", n.vectors.formatted()),            ("Model", n.model ?? "none"), ("Print", "\(n.printLength) · rev \(n.printRevision)"),            ("Store", AlbumsWords.size(n.storeBytes)),        ]    }    #if COTTON_DEV    static var documents: URL { FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] }    static func write(_ n: Numbers) {        let encoder = JSONEncoder()        encoder.outputFormatting = [.prettyPrinted, .sortedKeys]        try? encoder.encode(n).write(to: documents.appendingPathComponent("albums-measure.json"))    }    /// Every looked-at photo, one JSON line each, for scoring on the Mac against the synthetic library's truth.    static func export() {        struct Row: Encodable {            let id: String, file: String?, created: Double?, w: Int, h: Int, flags: UInt32, burst: String?            let bytes: Int64, exact: Bool, state: Int            let side: Int?, print: String?, aesthetic: Float?, utility: Bool?, sharpness: Float?, light: Float?, clipped: Float?            let dhash: String?, document: Bool?, text: Float?, millis: Double?            let faces: [Face]            struct Face: Encodable { let box: [Float]; let quality: Float?; let pixels: Float; let points: [Float]; let vector: [Float]?; let model: String? }        }        let encoder = JSONEncoder()        var out = Data()        for item in AlbumsStore.shared.items(prints: true, vectors: true) {            let l = item.look            let row = Row(                id: item.asset.id, file: item.filename, created: item.asset.created?.timeIntervalSince1970, w: item.asset.width, h: item.asset.height,                flags: item.asset.flags.rawValue, burst: item.asset.burst, bytes: item.bytes, exact: item.exact, state: item.state.rawValue,                side: l?.side, print: l?.print?.base64EncodedString(), aesthetic: l?.aesthetic, utility: l?.utility, sharpness: l?.sharpness,                light: l?.light, clipped: l?.clipped, dhash: l.map { String($0.dhash, radix: 16) }, document: l?.document, text: l?.text,                millis: l?.millis,                faces: (l?.faces ?? []).map { .init(box: [$0.x, $0.y, $0.w, $0.h], quality: $0.quality, pixels: $0.pixels, points: $0.points, vector: $0.vector, model: $0.model) })            if let line = try? encoder.encode(row) { out.append(line); out.append(0x0A) }        }        try? out.write(to: documents.appendingPathComponent("albums-export.jsonl"))    }    /// The core's answers once the pass is done, for scoring Sets and Tidy against the synthetic library's truth:    /// `albums.tidy` and every page of `albums.sets`, written to Documents/albums-core.json. Queued behind every call    /// the feed still holds, so it reads what the pass sent.    static func exportCore(_ feed: AlbumsFeed) {        feed.later { feed in            var out: [String: Any] = [:]            out["start"] = await feed.answer("albums.start", ["platform": "ios", "permission": "full", "offset_s": TimeZone.current.secondsFromGMT()])            out["tidy"] = await feed.answer("albums.tidy")            out["lines"] = await feed.answer("albums.pass.lines")            var sets: [Any] = []            var from: Any = 0            while true {                guard let page = await feed.answer("albums.sets", ["from": from]) else { break }                sets += page["sets"] as? [Any] ?? []                guard let next = page["next_from"], !(next is NSNull) else { break }                from = next            }            out["sets"] = sets            if let data = try? JSONSerialization.data(withJSONObject: out, options: [.prettyPrinted]) {                try? data.write(to: documents.appendingPathComponent("albums-core.json"))            }            Log.write("albums: core answers exported (\(sets.count) sets)")        }    }    #endif}#endif