2020-05-16 11:21:55 +02:00
|
|
|
import Foundation
|
2022-06-10 21:20:49 +02:00
|
|
|
import SwiftUI
|
|
|
|
import Vision
|
|
|
|
import CryptoKit
|
2020-05-16 11:21:55 +02:00
|
|
|
|
2022-06-10 21:20:49 +02:00
|
|
|
final class Database: ObservableObject {
|
|
|
|
|
|
|
|
static let imageCacheMemory = 10_000_000
|
|
|
|
|
|
|
|
static let imageCacheStorage = 200_000_000
|
|
|
|
|
|
|
|
private let imageCompressionQuality: CGFloat = 0.3
|
|
|
|
|
|
|
|
private static var documentDirectory: URL {
|
|
|
|
try! FileManager.default.url(
|
|
|
|
for: .documentDirectory,
|
|
|
|
in: .userDomainMask,
|
|
|
|
appropriateFor: nil, create: true)
|
2021-01-13 21:43:46 +01:00
|
|
|
}
|
2022-06-10 21:20:49 +02:00
|
|
|
|
|
|
|
private var fm: FileManager {
|
|
|
|
.default
|
2021-01-13 21:43:46 +01:00
|
|
|
}
|
2022-06-10 21:20:49 +02:00
|
|
|
|
|
|
|
private var localDbUrl: URL {
|
|
|
|
Database.documentDirectory.appendingPathComponent("db.json")
|
2021-01-13 21:43:46 +01:00
|
|
|
}
|
2022-06-10 21:20:49 +02:00
|
|
|
|
|
|
|
private var localClassifierUrl: URL {
|
|
|
|
Database.documentDirectory.appendingPathComponent("classifier.mlmodel")
|
2021-01-13 21:43:46 +01:00
|
|
|
}
|
|
|
|
|
2022-06-10 21:20:49 +02:00
|
|
|
private var imageUploadFolderUrl: URL {
|
|
|
|
Database.documentDirectory.appendingPathComponent("uploads")
|
|
|
|
}
|
2021-01-13 21:43:46 +01:00
|
|
|
|
2022-06-10 21:20:49 +02:00
|
|
|
private var serverDbUrl: URL {
|
|
|
|
serverUrl.appendingPathComponent("caps.json")
|
|
|
|
}
|
2020-05-16 11:21:55 +02:00
|
|
|
|
2022-06-10 21:20:49 +02:00
|
|
|
private var serverClassifierUrl: URL {
|
|
|
|
serverUrl.appendingPathComponent("classifier.mlmodel")
|
2020-05-16 11:21:55 +02:00
|
|
|
}
|
|
|
|
|
2022-06-10 21:20:49 +02:00
|
|
|
private var serverClassifierVersionUrl: URL {
|
|
|
|
serverUrl.appendingPathComponent("classifier.version")
|
2020-05-16 11:21:55 +02:00
|
|
|
}
|
2022-06-10 21:20:49 +02:00
|
|
|
|
|
|
|
private let encoder = JSONEncoder()
|
|
|
|
private let decoder = JSONDecoder()
|
|
|
|
|
|
|
|
let serverUrl: URL
|
|
|
|
|
|
|
|
@AppStorage("authKey")
|
2022-06-11 11:27:56 +02:00
|
|
|
private var serverAuthenticationKey: String = ""
|
2022-06-10 21:20:49 +02:00
|
|
|
|
|
|
|
var hasServerAuthentication: Bool {
|
2022-06-11 11:27:56 +02:00
|
|
|
serverAuthenticationKey != ""
|
2021-01-13 21:43:46 +01:00
|
|
|
}
|
2022-06-10 21:20:49 +02:00
|
|
|
|
|
|
|
@Published
|
|
|
|
private(set) var caps: [Int : Cap] {
|
|
|
|
didSet { scheduleSave() }
|
2020-06-18 22:55:51 +02:00
|
|
|
}
|
2022-06-10 21:20:49 +02:00
|
|
|
|
|
|
|
var nextCapId: Int {
|
|
|
|
(caps.values.max()?.id ?? 0) + 1
|
2020-05-16 11:21:55 +02:00
|
|
|
}
|
2022-06-10 21:20:49 +02:00
|
|
|
|
|
|
|
@AppStorage("changed")
|
|
|
|
private var changedCapStorage: String = ""
|
|
|
|
|
|
|
|
private(set) var changedCaps: Set<Int> {
|
|
|
|
get {
|
|
|
|
Set(changedCapStorage.components(separatedBy: ",").compactMap(Int.init))
|
|
|
|
}
|
|
|
|
set {
|
|
|
|
changedCapStorage = newValue.map { "\($0)" }.joined(separator: ",")
|
|
|
|
}
|
2020-05-16 11:21:55 +02:00
|
|
|
}
|
2022-06-10 21:20:49 +02:00
|
|
|
|
|
|
|
private lazy var imageUploads: [Int: Int] = loadImageUploadCounts()
|
|
|
|
|
|
|
|
private var uploadTimer: Timer?
|
|
|
|
|
|
|
|
/// The classifications for all caps from the classifier
|
|
|
|
@Published
|
|
|
|
var matches = [Int : Float]()
|
|
|
|
|
|
|
|
@Published
|
|
|
|
var image: UIImage? = nil {
|
|
|
|
didSet { classifyImage() }
|
2020-05-16 11:21:55 +02:00
|
|
|
}
|
2022-06-10 21:20:49 +02:00
|
|
|
|
|
|
|
private var classifier: Classifier?
|
|
|
|
|
|
|
|
/**
|
|
|
|
The time to wait for changes to be written to disk.
|
|
|
|
|
|
|
|
This delay is used to prevent file writes for each small update to the caps.
|
|
|
|
*/
|
|
|
|
private let saveDelay: TimeInterval = 1
|
|
|
|
|
|
|
|
/**
|
|
|
|
The time when a save should occur.
|
|
|
|
|
|
|
|
No save is necessary if this property is `nil`.
|
|
|
|
*/
|
|
|
|
private var nextSaveTime: Date?
|
|
|
|
|
|
|
|
let imageCache: URLCache
|
|
|
|
|
|
|
|
init(server: URL) {
|
|
|
|
self.serverUrl = server
|
|
|
|
self.caps = [:]
|
|
|
|
|
|
|
|
let cacheDirectory = Database.documentDirectory.appendingPathComponent("images")
|
|
|
|
self.imageCache = URLCache(
|
|
|
|
memoryCapacity: Database.imageCacheMemory,
|
|
|
|
diskCapacity: Database.imageCacheStorage,
|
|
|
|
directory: cacheDirectory)
|
|
|
|
loadCaps()
|
2020-06-18 22:55:51 +02:00
|
|
|
}
|
2022-06-10 21:20:49 +02:00
|
|
|
|
|
|
|
@Published
|
|
|
|
var isUploading = false
|
|
|
|
|
|
|
|
// MARK: Disk storage
|
|
|
|
|
|
|
|
private func loadCaps() {
|
|
|
|
guard fm.fileExists(atPath: localDbUrl.path) else {
|
|
|
|
return
|
2021-01-13 21:43:46 +01:00
|
|
|
}
|
2022-06-10 21:20:49 +02:00
|
|
|
let data: Data
|
2021-01-13 21:43:46 +01:00
|
|
|
do {
|
2022-06-10 21:20:49 +02:00
|
|
|
data = try Data(contentsOf: localDbUrl)
|
2021-01-13 21:43:46 +01:00
|
|
|
} catch {
|
2022-06-10 21:20:49 +02:00
|
|
|
print("Failed to read database file: \(error)")
|
|
|
|
return
|
2021-01-13 21:43:46 +01:00
|
|
|
}
|
2020-05-16 11:21:55 +02:00
|
|
|
do {
|
2022-06-10 21:20:49 +02:00
|
|
|
let array = try JSONDecoder().decode([Cap].self, from: data)
|
|
|
|
self.caps = array.reduce(into: [:]) { $0[$1.id] = $1 }
|
|
|
|
// Prevent immediate save after modifying caps
|
|
|
|
nextSaveTime = nil
|
2020-05-16 11:21:55 +02:00
|
|
|
} catch {
|
2022-06-10 21:20:49 +02:00
|
|
|
print("Failed to decode database file: \(error)")
|
|
|
|
return
|
2020-05-16 11:21:55 +02:00
|
|
|
}
|
|
|
|
}
|
2022-06-10 21:20:49 +02:00
|
|
|
|
|
|
|
private func scheduleSave() {
|
|
|
|
nextSaveTime = Date.now.addingTimeInterval(saveDelay)
|
|
|
|
DispatchQueue.main.asyncAfter(deadline: .now() + saveDelay) {
|
|
|
|
self.performScheduledSave()
|
2021-01-10 16:11:31 +01:00
|
|
|
}
|
|
|
|
}
|
2022-06-10 21:20:49 +02:00
|
|
|
|
|
|
|
private func performScheduledSave() {
|
|
|
|
guard let date = nextSaveTime else {
|
|
|
|
// No save necessary, or already saved
|
|
|
|
return
|
2020-05-16 11:21:55 +02:00
|
|
|
}
|
2022-06-10 21:20:49 +02:00
|
|
|
guard date < .now else {
|
|
|
|
// Save pushed to future
|
|
|
|
return
|
2020-05-16 11:21:55 +02:00
|
|
|
}
|
2022-06-10 21:20:49 +02:00
|
|
|
save()
|
|
|
|
nextSaveTime = nil
|
2020-05-16 11:21:55 +02:00
|
|
|
}
|
2022-06-10 21:20:49 +02:00
|
|
|
|
|
|
|
private func save() {
|
|
|
|
let data: Data
|
|
|
|
do {
|
|
|
|
data = try encoder.encode(caps.values.sorted())
|
|
|
|
} catch {
|
|
|
|
print("Failed to encode database: \(error)")
|
|
|
|
return
|
2020-08-09 21:04:30 +02:00
|
|
|
}
|
2022-06-10 21:20:49 +02:00
|
|
|
do {
|
|
|
|
try data.write(to: localDbUrl)
|
|
|
|
} catch {
|
|
|
|
print("Failed to save database: \(error)")
|
2020-08-09 21:04:30 +02:00
|
|
|
}
|
2022-06-10 21:20:49 +02:00
|
|
|
print("Database saved")
|
2020-08-09 21:04:30 +02:00
|
|
|
}
|
2022-06-10 21:20:49 +02:00
|
|
|
|
|
|
|
private func ensureFolderExistence(_ url: URL) -> Bool {
|
|
|
|
guard !fm.fileExists(atPath: url.path) else {
|
|
|
|
return true
|
2020-05-16 11:21:55 +02:00
|
|
|
}
|
|
|
|
do {
|
2022-06-10 21:20:49 +02:00
|
|
|
try fm.createDirectory(at: url, withIntermediateDirectories: true)
|
2020-05-16 11:21:55 +02:00
|
|
|
return true
|
|
|
|
} catch {
|
2022-06-10 21:20:49 +02:00
|
|
|
log("Failed to create folder \(url.path): \(error)")
|
2020-05-16 11:21:55 +02:00
|
|
|
return false
|
|
|
|
}
|
|
|
|
}
|
2022-06-10 21:20:49 +02:00
|
|
|
|
|
|
|
// MARK: Downloads
|
|
|
|
|
|
|
|
@discardableResult
|
|
|
|
func downloadCaps() async -> Bool {
|
|
|
|
print("Downloading cap data")
|
|
|
|
let data: Data
|
|
|
|
let response: URLResponse
|
|
|
|
do {
|
|
|
|
(data, response) = try await URLSession.shared.data(from: serverDbUrl)
|
|
|
|
} catch {
|
|
|
|
print("Failed to download classifier version: \(error)")
|
2020-05-16 11:21:55 +02:00
|
|
|
return false
|
|
|
|
}
|
2022-06-10 21:20:49 +02:00
|
|
|
guard (response as? HTTPURLResponse)?.statusCode == 200 else {
|
2020-05-16 11:21:55 +02:00
|
|
|
return false
|
|
|
|
}
|
2022-06-10 21:20:49 +02:00
|
|
|
|
|
|
|
let capData: [CapData]
|
|
|
|
do {
|
|
|
|
capData = try decoder.decode([CapData].self, from: data)
|
|
|
|
} catch {
|
|
|
|
print("Failed to decode server database: \(error)")
|
2020-05-16 11:21:55 +02:00
|
|
|
return false
|
|
|
|
}
|
2022-06-10 21:20:49 +02:00
|
|
|
var inserts = 0
|
|
|
|
var updates = 0
|
|
|
|
for cap in capData {
|
|
|
|
guard var oldCap = caps[cap.id] else {
|
|
|
|
caps[cap.id] = Cap(data: cap)
|
|
|
|
inserts += 1
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
guard oldCap != cap else {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
if changedCaps.contains(oldCap.id) {
|
|
|
|
#warning("Merge changed caps with server updates")
|
|
|
|
} else {
|
|
|
|
oldCap.update(with: cap)
|
|
|
|
caps[cap.id] = oldCap
|
|
|
|
updates += 1
|
|
|
|
}
|
2020-05-16 11:21:55 +02:00
|
|
|
}
|
2022-06-10 21:20:49 +02:00
|
|
|
print("Updated database from server (\(inserts) added, \(updates) updated)")
|
2020-05-16 11:21:55 +02:00
|
|
|
return true
|
|
|
|
}
|
2022-06-10 21:20:49 +02:00
|
|
|
|
|
|
|
@discardableResult
|
|
|
|
func serverHasNewClassifier() async -> Bool {
|
|
|
|
let data: Data
|
|
|
|
let response: URLResponse
|
2020-05-16 11:21:55 +02:00
|
|
|
do {
|
2022-06-10 21:20:49 +02:00
|
|
|
(data, response) = try await URLSession.shared.data(from: serverClassifierVersionUrl)
|
2020-05-16 11:21:55 +02:00
|
|
|
} catch {
|
2022-06-10 21:20:49 +02:00
|
|
|
print("Failed to download classifier version: \(error)")
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
guard (response as? HTTPURLResponse)?.statusCode == 200 else {
|
2020-05-16 11:21:55 +02:00
|
|
|
return false
|
|
|
|
}
|
2020-06-18 22:55:51 +02:00
|
|
|
|
2022-06-10 21:20:49 +02:00
|
|
|
guard let string = String(data: data, encoding: .utf8) else {
|
|
|
|
log("Classifier version is invalid data (not a string)")
|
2020-06-18 22:55:51 +02:00
|
|
|
return false
|
|
|
|
}
|
2022-06-10 21:20:49 +02:00
|
|
|
guard let serverVersion = Int(string.trimmingCharacters(in: .whitespacesAndNewlines)) else {
|
|
|
|
log("Classifier version has an invalid value '\(string)'")
|
|
|
|
return false
|
2020-05-16 11:21:55 +02:00
|
|
|
}
|
2022-06-10 21:20:49 +02:00
|
|
|
DispatchQueue.main.async {
|
|
|
|
self.serverClassifierVersion = serverVersion
|
2020-05-16 11:21:55 +02:00
|
|
|
}
|
2022-06-10 21:20:49 +02:00
|
|
|
guard serverVersion > self.classifierVersion else {
|
|
|
|
print("No new classifier available")
|
|
|
|
return false
|
2020-05-16 11:21:55 +02:00
|
|
|
}
|
2022-06-10 21:20:49 +02:00
|
|
|
print("New classifier \(serverVersion) available")
|
|
|
|
return true
|
2020-05-16 11:21:55 +02:00
|
|
|
}
|
2022-06-10 21:20:49 +02:00
|
|
|
|
2021-01-13 21:43:46 +01:00
|
|
|
@discardableResult
|
2022-06-10 21:20:49 +02:00
|
|
|
func downloadClassifier() async -> Bool {
|
|
|
|
print("Downloading classifier")
|
|
|
|
let tempUrl: URL
|
|
|
|
let response: URLResponse
|
2020-05-16 11:21:55 +02:00
|
|
|
do {
|
2022-06-10 21:20:49 +02:00
|
|
|
(tempUrl, response) = try await URLSession.shared.download(from: serverClassifierUrl)
|
2020-05-16 11:21:55 +02:00
|
|
|
} catch {
|
2022-06-10 21:20:49 +02:00
|
|
|
print("Failed to download classifier version: \(error)")
|
2020-05-16 11:21:55 +02:00
|
|
|
return false
|
|
|
|
}
|
2022-06-10 21:20:49 +02:00
|
|
|
guard (response as? HTTPURLResponse)?.statusCode == 200 else {
|
2020-05-16 11:21:55 +02:00
|
|
|
return false
|
|
|
|
}
|
|
|
|
do {
|
2022-06-10 21:20:49 +02:00
|
|
|
let url = self.localClassifierUrl
|
|
|
|
if fm.fileExists(atPath: url.path) {
|
|
|
|
try self.fm.removeItem(at: url)
|
2020-05-16 11:21:55 +02:00
|
|
|
}
|
2022-06-10 21:20:49 +02:00
|
|
|
try self.fm.moveItem(at: tempUrl, to: url)
|
2020-05-16 11:21:55 +02:00
|
|
|
} catch {
|
2022-06-10 21:20:49 +02:00
|
|
|
print("Failed to replace classifier: \(error)")
|
|
|
|
return false
|
2020-05-16 11:21:55 +02:00
|
|
|
}
|
2022-06-10 21:20:49 +02:00
|
|
|
DispatchQueue.main.async {
|
|
|
|
self.classifierVersion = self.serverClassifierVersion
|
|
|
|
self.classifier = nil
|
2020-05-16 11:21:55 +02:00
|
|
|
}
|
2022-06-10 21:20:49 +02:00
|
|
|
print("Downloaded classifier \(classifierVersion)")
|
|
|
|
return true
|
2020-05-16 11:21:55 +02:00
|
|
|
}
|
2022-06-10 21:20:49 +02:00
|
|
|
|
|
|
|
/**
|
|
|
|
Indicate that the cap has pending operations, such as determining the color or a thumbnail
|
|
|
|
*/
|
|
|
|
func hasPendingOperations(for cap: Int) -> Bool {
|
|
|
|
return false
|
2020-05-16 11:21:55 +02:00
|
|
|
}
|
2022-06-10 21:20:49 +02:00
|
|
|
|
|
|
|
// MARK: Adding new data
|
|
|
|
|
|
|
|
func save(newCap name: String) -> Cap {
|
|
|
|
let cap = Cap(id: nextCapId, name: name, classifier: serverClassifierVersion)
|
|
|
|
caps[cap.id] = cap
|
2022-06-11 11:27:56 +02:00
|
|
|
DispatchQueue.main.async {
|
|
|
|
self.changedCaps.insert(cap.id)
|
|
|
|
}
|
2022-06-10 21:20:49 +02:00
|
|
|
return cap
|
|
|
|
}
|
|
|
|
|
|
|
|
@discardableResult
|
|
|
|
func save(_ image: UIImage, for capId: Int) -> Bool {
|
|
|
|
guard caps[capId] != nil else {
|
|
|
|
log("Failed to save image for missing cap \(capId)")
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
guard ensureFolderExistence(imageUploadFolderUrl) else {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
guard let data = image.jpegData(compressionQuality: imageCompressionQuality) else {
|
|
|
|
log("Failed to compress image for cap: \(capId)")
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
let hash = Data(SHA256.hash(data: data)).hexEncoded.prefix(16)
|
|
|
|
let url = imageUploadFolderUrl.appendingPathComponent("\(capId)-\(hash).jpg")
|
2020-05-16 11:21:55 +02:00
|
|
|
do {
|
2022-06-10 21:20:49 +02:00
|
|
|
try data.write(to: url)
|
2020-05-16 11:21:55 +02:00
|
|
|
} catch {
|
2022-06-10 21:20:49 +02:00
|
|
|
log("Failed to save \(url.lastPathComponent): \(error)")
|
|
|
|
return false
|
2020-05-16 11:21:55 +02:00
|
|
|
}
|
2022-06-10 21:20:49 +02:00
|
|
|
log("Saved \(url.lastPathComponent) for upload")
|
|
|
|
caps[capId]?.imageCount += 1
|
|
|
|
return true
|
2020-05-16 11:21:55 +02:00
|
|
|
}
|
2022-06-10 21:20:49 +02:00
|
|
|
|
|
|
|
private func loadImageUploadCounts() -> [Int : Int] {
|
|
|
|
var result = [Int : Int]()
|
|
|
|
pendingImageUploads.forEach { url in
|
|
|
|
guard let capId = capId(from: url) else {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if let old = result[capId] {
|
|
|
|
result[capId] = old + 1
|
|
|
|
} else {
|
|
|
|
result[capId] = 1
|
2020-05-16 11:21:55 +02:00
|
|
|
}
|
|
|
|
}
|
2022-06-10 21:20:49 +02:00
|
|
|
return result
|
2020-05-16 11:21:55 +02:00
|
|
|
}
|
2022-06-10 21:20:49 +02:00
|
|
|
|
|
|
|
// MARK: Uploads
|
|
|
|
|
|
|
|
func startRegularUploads() {
|
2022-06-11 11:27:56 +02:00
|
|
|
guard uploadTimer == nil else {
|
2022-06-10 21:20:49 +02:00
|
|
|
return
|
2020-06-18 22:55:51 +02:00
|
|
|
}
|
2022-06-11 11:27:56 +02:00
|
|
|
log("Starting upload timer")
|
2022-06-10 21:20:49 +02:00
|
|
|
DispatchQueue.main.async {
|
|
|
|
self.uploadTimer = Timer.scheduledTimer(withTimeInterval: 5, repeats: true, block: self.uploadTimerElapsed)
|
2020-05-16 11:21:55 +02:00
|
|
|
}
|
|
|
|
}
|
2022-06-10 21:20:49 +02:00
|
|
|
|
|
|
|
private func uploadTimerElapsed(timer: Timer) {
|
|
|
|
Task {
|
|
|
|
await uploadAll()
|
|
|
|
}
|
2021-01-13 21:43:46 +01:00
|
|
|
}
|
2022-06-10 21:20:49 +02:00
|
|
|
|
|
|
|
private func uploadAll() async {
|
|
|
|
guard !isUploading else {
|
2022-06-11 11:27:56 +02:00
|
|
|
log("Already uploading")
|
2022-06-10 21:20:49 +02:00
|
|
|
return
|
2021-01-13 21:43:46 +01:00
|
|
|
}
|
2022-06-10 21:20:49 +02:00
|
|
|
DispatchQueue.main.async {
|
|
|
|
self.isUploading = true
|
2021-01-13 21:43:46 +01:00
|
|
|
}
|
2022-06-11 11:27:56 +02:00
|
|
|
log("Starting uploads")
|
|
|
|
let uploaded = await uploadAllChangedCaps()
|
|
|
|
DispatchQueue.main.async {
|
|
|
|
self.changedCaps.subtract(uploaded)
|
|
|
|
}
|
2022-06-10 21:20:49 +02:00
|
|
|
await uploadAllImages()
|
2022-06-11 11:27:56 +02:00
|
|
|
log("Uploads finished")
|
2022-06-10 21:20:49 +02:00
|
|
|
DispatchQueue.main.async {
|
|
|
|
self.isUploading = false
|
2021-01-13 21:43:46 +01:00
|
|
|
}
|
|
|
|
}
|
2022-06-10 21:20:49 +02:00
|
|
|
|
|
|
|
/**
|
|
|
|
Indicate that the cap has pending uploads, either changes or images
|
|
|
|
*/
|
|
|
|
func hasPendingUpdates(for cap: Int) -> Bool {
|
|
|
|
changedCaps.contains(cap) || imageUploads[cap] != nil
|
2021-01-13 21:43:46 +01:00
|
|
|
}
|
2022-06-10 21:20:49 +02:00
|
|
|
|
|
|
|
private var pendingImageUploads: [URL] {
|
|
|
|
(try? fm.contentsOfDirectory(at: imageUploadFolderUrl, includingPropertiesForKeys: nil)) ?? []
|
2021-01-13 21:43:46 +01:00
|
|
|
}
|
2022-06-10 21:20:49 +02:00
|
|
|
|
|
|
|
var pendingImageUploadCount: Int {
|
|
|
|
pendingImageUploads.count
|
2021-01-13 21:43:46 +01:00
|
|
|
}
|
2022-06-10 21:20:49 +02:00
|
|
|
|
|
|
|
private func capId(from url: URL) -> Int? {
|
|
|
|
Int(url.lastPathComponent.components(separatedBy: "-").first!)
|
2021-01-13 21:43:46 +01:00
|
|
|
}
|
2022-06-10 21:20:49 +02:00
|
|
|
|
|
|
|
private func uploadAllImages() async {
|
|
|
|
guard hasServerAuthentication else {
|
|
|
|
log("No server authentication to upload to server")
|
2021-01-13 21:43:46 +01:00
|
|
|
return
|
2020-05-16 11:21:55 +02:00
|
|
|
}
|
2022-06-10 21:20:49 +02:00
|
|
|
for url in pendingImageUploads {
|
|
|
|
guard let capId = capId(from: url) else {
|
|
|
|
log("Unexpected image \(url.lastPathComponent) in upload folder")
|
|
|
|
continue
|
2021-01-13 21:43:46 +01:00
|
|
|
}
|
2022-06-11 11:27:56 +02:00
|
|
|
guard fm.fileExists(atPath: url.path) else {
|
|
|
|
log("Missing image \(url.lastPathComponent) in upload folder")
|
|
|
|
continue
|
|
|
|
}
|
2022-06-10 21:20:49 +02:00
|
|
|
guard await upload(imageAt: url, for: capId) else {
|
2022-06-11 11:27:56 +02:00
|
|
|
log("Failed to upload image \(url.lastPathComponent)")
|
2022-06-10 21:20:49 +02:00
|
|
|
continue
|
2021-01-13 21:43:46 +01:00
|
|
|
}
|
2022-06-11 11:27:56 +02:00
|
|
|
log("Uploaded image \(url.lastPathComponent)")
|
2022-06-10 21:20:49 +02:00
|
|
|
do {
|
|
|
|
try fm.removeItem(at: url)
|
|
|
|
} catch {
|
|
|
|
log("Failed to remove uploaded image \(url.lastPathComponent): \(error)")
|
2021-01-13 21:43:46 +01:00
|
|
|
}
|
|
|
|
}
|
2022-06-10 21:20:49 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
@discardableResult
|
|
|
|
private func upload(imageAt url: URL, for cap: Int) async -> Bool {
|
2022-06-11 11:27:56 +02:00
|
|
|
guard hasServerAuthentication else {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
guard let data = try? Data(contentsOf: url) else {
|
2021-01-13 21:43:46 +01:00
|
|
|
return false
|
|
|
|
}
|
2022-06-10 21:20:49 +02:00
|
|
|
let url = serverUrl
|
|
|
|
.appendingPathComponent("images")
|
2022-06-11 11:27:56 +02:00
|
|
|
.appendingPathComponent("\(cap)")
|
2022-06-10 21:20:49 +02:00
|
|
|
var request = URLRequest(url: url)
|
2022-06-11 11:27:56 +02:00
|
|
|
request.addValue(serverAuthenticationKey, forHTTPHeaderField: "key")
|
2022-06-10 21:20:49 +02:00
|
|
|
request.httpMethod = "POST"
|
|
|
|
do {
|
2022-06-11 11:27:56 +02:00
|
|
|
let (_, response) = try await URLSession.shared.upload(for: request, from: data)
|
2022-06-10 21:20:49 +02:00
|
|
|
guard let httpResponse = response as? HTTPURLResponse else {
|
|
|
|
log("Unexpected response for upload of image \(url.lastPathComponent): \(response)")
|
|
|
|
return false
|
2021-01-13 21:43:46 +01:00
|
|
|
}
|
2022-06-10 21:20:49 +02:00
|
|
|
guard httpResponse.statusCode == 200 else {
|
|
|
|
log("Failed to upload image \(url.lastPathComponent): Response \(httpResponse.statusCode)")
|
2021-01-13 21:43:46 +01:00
|
|
|
return false
|
|
|
|
}
|
2022-06-10 21:20:49 +02:00
|
|
|
return true
|
|
|
|
} catch {
|
|
|
|
log("Failed to upload image \(url.lastPathComponent): \(error)")
|
|
|
|
return false
|
2021-01-13 21:43:46 +01:00
|
|
|
}
|
|
|
|
}
|
2022-06-10 21:20:49 +02:00
|
|
|
|
|
|
|
var pendingCapUploadCount: Int {
|
|
|
|
changedCaps.count
|
|
|
|
}
|
|
|
|
|
2022-06-11 11:27:56 +02:00
|
|
|
private func uploadAllChangedCaps() async -> Set<Int> {
|
2022-06-10 21:20:49 +02:00
|
|
|
guard hasServerAuthentication else {
|
|
|
|
log("No server authentication to upload to server")
|
2022-06-11 11:27:56 +02:00
|
|
|
return .init()
|
2022-06-10 21:20:49 +02:00
|
|
|
}
|
|
|
|
var uploaded = Set<Int>()
|
|
|
|
for capId in changedCaps {
|
|
|
|
guard let cap = caps[capId] else {
|
2022-06-11 11:27:56 +02:00
|
|
|
log("Missing cap \(capId) to upload")
|
2022-06-10 21:20:49 +02:00
|
|
|
uploaded.insert(capId)
|
2021-01-13 21:43:46 +01:00
|
|
|
continue
|
|
|
|
}
|
2022-06-10 21:20:49 +02:00
|
|
|
guard await upload(cap: cap) else {
|
2021-01-13 21:43:46 +01:00
|
|
|
continue
|
|
|
|
}
|
2022-06-11 11:27:56 +02:00
|
|
|
log("Uploaded cap \(capId)")
|
2022-06-10 21:20:49 +02:00
|
|
|
uploaded.insert(capId)
|
2021-01-13 21:43:46 +01:00
|
|
|
}
|
2022-06-11 11:27:56 +02:00
|
|
|
return uploaded
|
2021-01-13 21:43:46 +01:00
|
|
|
}
|
2022-06-10 21:20:49 +02:00
|
|
|
|
|
|
|
@discardableResult
|
|
|
|
private func upload(cap: Cap) async -> Bool {
|
2022-06-11 11:27:56 +02:00
|
|
|
guard hasServerAuthentication else {
|
2021-01-13 21:43:46 +01:00
|
|
|
return false
|
|
|
|
}
|
2022-06-10 21:20:49 +02:00
|
|
|
let data: Data
|
|
|
|
do {
|
|
|
|
/// `Cap` and `CapData` have equivalent JSON layout
|
2022-06-11 11:27:56 +02:00
|
|
|
data = try encoder.encode(cap.data)
|
2022-06-10 21:20:49 +02:00
|
|
|
} catch {
|
|
|
|
log("Failed to encode cap \(cap.id) for upload: \(error)")
|
2021-01-13 21:43:46 +01:00
|
|
|
return false
|
|
|
|
}
|
2022-06-10 21:20:49 +02:00
|
|
|
let url = serverUrl
|
2022-06-11 11:27:56 +02:00
|
|
|
.appendingPathComponent("cap")
|
2022-06-10 21:20:49 +02:00
|
|
|
var request = URLRequest(url: url)
|
|
|
|
request.httpMethod = "POST"
|
2022-06-11 11:27:56 +02:00
|
|
|
request.addValue(serverAuthenticationKey, forHTTPHeaderField: "key")
|
2022-06-10 21:20:49 +02:00
|
|
|
do {
|
|
|
|
let (_, response) = try await URLSession.shared.upload(for: request, from: data)
|
|
|
|
guard let httpResponse = response as? HTTPURLResponse else {
|
|
|
|
log("Unexpected response for upload of cap \(cap.id): \(response)")
|
|
|
|
return false
|
2021-01-13 21:43:46 +01:00
|
|
|
}
|
2022-06-10 21:20:49 +02:00
|
|
|
guard httpResponse.statusCode == 200 else {
|
|
|
|
log("Failed to upload cap \(cap.id): Response \(httpResponse.statusCode)")
|
|
|
|
return false
|
|
|
|
}
|
2022-06-11 11:27:56 +02:00
|
|
|
DispatchQueue.main.async {
|
|
|
|
self.changedCaps.remove(cap.id)
|
|
|
|
}
|
2022-06-10 21:20:49 +02:00
|
|
|
return true
|
|
|
|
} catch {
|
|
|
|
log("Failed to upload cap \(cap.id): \(error)")
|
2021-01-13 21:43:46 +01:00
|
|
|
return false
|
|
|
|
}
|
|
|
|
}
|
2022-06-10 21:20:49 +02:00
|
|
|
|
|
|
|
// MARK: Classification
|
|
|
|
|
|
|
|
/// The compiled recognition model on disk
|
|
|
|
private var recognitionModel: VNCoreMLModel? {
|
|
|
|
guard fm.fileExists(atPath: localClassifierUrl.path) else {
|
|
|
|
log("No recognition model to load from disk")
|
|
|
|
return nil
|
2020-05-16 11:21:55 +02:00
|
|
|
}
|
2022-06-10 21:20:49 +02:00
|
|
|
do {
|
|
|
|
log("Loading model from disk")
|
|
|
|
let newUrl = try MLModel.compileModel(at: localClassifierUrl)
|
|
|
|
let model = try MLModel(contentsOf: newUrl)
|
|
|
|
return try VNCoreMLModel(for: model)
|
|
|
|
} catch {
|
|
|
|
log("Failed to load recognition model: \(error)")
|
|
|
|
return nil
|
2021-01-13 21:43:46 +01:00
|
|
|
}
|
2020-05-16 11:21:55 +02:00
|
|
|
}
|
2022-06-10 21:20:49 +02:00
|
|
|
|
|
|
|
private func classifyImage() {
|
|
|
|
guard let image = image?.cgImage else {
|
|
|
|
matches.removeAll()
|
|
|
|
log("Image removed")
|
|
|
|
return
|
|
|
|
}
|
|
|
|
DispatchQueue.global().async {
|
|
|
|
guard let classifier = self.getClassifier() else {
|
2020-05-16 11:21:55 +02:00
|
|
|
return
|
|
|
|
}
|
2022-06-10 21:20:49 +02:00
|
|
|
log("Image classification started")
|
|
|
|
classifier.recognize(image: image) { matches in
|
|
|
|
DispatchQueue.main.async {
|
|
|
|
self.matches = matches ?? [:]
|
|
|
|
}
|
2020-05-16 11:21:55 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2022-06-10 21:20:49 +02:00
|
|
|
|
|
|
|
private func getClassifier() -> Classifier? {
|
|
|
|
if let classifier = classifier {
|
|
|
|
return classifier
|
2020-05-16 11:21:55 +02:00
|
|
|
}
|
2022-06-10 21:20:49 +02:00
|
|
|
guard let model = recognitionModel else {
|
|
|
|
return nil
|
2020-05-16 11:21:55 +02:00
|
|
|
}
|
2022-06-10 21:20:49 +02:00
|
|
|
return Classifier(model: model)
|
2020-06-18 22:55:51 +02:00
|
|
|
}
|
2022-06-10 21:20:49 +02:00
|
|
|
|
|
|
|
// MARK: Statistics
|
|
|
|
|
|
|
|
var numberOfCaps: Int {
|
|
|
|
caps.count
|
2020-06-18 22:55:51 +02:00
|
|
|
}
|
2022-06-10 21:20:49 +02:00
|
|
|
|
|
|
|
var numberOfImages: Int {
|
|
|
|
caps.values.reduce(0) { $0 + $1.imageCount }
|
2020-05-16 11:21:55 +02:00
|
|
|
}
|
2022-06-10 21:20:49 +02:00
|
|
|
|
|
|
|
var averageImageCount: Float {
|
|
|
|
Float(numberOfImages) / Float(numberOfCaps)
|
|
|
|
}
|
|
|
|
|
|
|
|
@AppStorage("classifier")
|
|
|
|
private(set) var classifierVersion = 0
|
|
|
|
|
|
|
|
@AppStorage("serverClassifier")
|
|
|
|
private(set) var serverClassifierVersion = 0
|
|
|
|
|
|
|
|
var classifierClassCount: Int {
|
|
|
|
let version = classifierVersion
|
|
|
|
return caps.values.filter { $0.classifiable(by: version) }.count
|
|
|
|
}
|
|
|
|
|
|
|
|
var imageCacheSize: Int {
|
|
|
|
imageCache.currentDiskUsage
|
|
|
|
}
|
|
|
|
|
|
|
|
var databaseSize: Int {
|
|
|
|
localDbUrl.fileSize
|
|
|
|
}
|
|
|
|
|
|
|
|
var classifierSize: Int {
|
|
|
|
localClassifierUrl.fileSize
|
2020-05-16 11:21:55 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-06-10 21:20:49 +02:00
|
|
|
extension Database {
|
|
|
|
|
|
|
|
static var mock: Database {
|
|
|
|
let db = Database(server: URL(string: "https://christophhagen.de/caps")!)
|
|
|
|
db.caps = [
|
|
|
|
Cap(id: 123, name: "My new cap"),
|
|
|
|
Cap(id: 234, name: "My favorite cap"),
|
|
|
|
Cap(id: 345, name: "My oldest cap"),
|
|
|
|
Cap(id: 456, name: "My new cap"),
|
|
|
|
Cap(id: 567, name: "My favorite cap"),
|
|
|
|
Cap(id: 678, name: "My oldest cap"),
|
|
|
|
].reduce(into: [:]) { $0[$1.id] = $1 }
|
|
|
|
db.image = UIImage(systemSymbol: .photo)
|
|
|
|
return db
|
|
|
|
}
|
|
|
|
}
|