diff --git a/Sources/App/CapServer.swift b/Sources/App/CapServer.swift index 9803806..2c77fd2 100644 --- a/Sources/App/CapServer.swift +++ b/Sources/App/CapServer.swift @@ -10,6 +10,8 @@ final class CapServer { /// The file where the database of caps is stored private let dbFile: URL + private let classifierVersionFile: URL + private let fm = FileManager.default // MARK: Caps @@ -41,6 +43,7 @@ final class CapServer { init(in folder: URL, writers: [String]) throws { self.imageFolder = folder.appendingPathComponent("images") self.dbFile = folder.appendingPathComponent("caps.json") + self.classifierVersionFile = folder.appendingPathComponent("classifier.version") self.writers = Set(writers) var isDirectory: ObjCBool = false @@ -137,23 +140,6 @@ final class CapServer { } return try countImages(in: f) } - - // MARK: Names - - func set(name: String, for capId: Int) throws { - guard var cap = caps[capId] else { - let url = server.folder(of: capId) - if !fm.fileExists(atPath: url.path) { - try fm.createDirectory(at: url, withIntermediateDirectories: false) - } - caps[capId] = Cap(id: capId, name: name, count: 0, mainImage: 0, classifierVersion: nextClassifierVersion) - log("Added cap \(capId)") - return - } - cap.name = name - caps[capId] = cap - log("Set name for cap \(capId)") - } // MARK: Images @@ -209,6 +195,7 @@ final class CapServer { } var cap = cap cap.count = 0 + cap.classifierVersion = nextClassifierVersion caps[cap.id] = cap log("Added cap \(cap.id) '\(cap.name)'") } @@ -228,4 +215,40 @@ final class CapServer { caps[existingCap.id] = updatedCap log("Updated cap \(existingCap.id)") } + + func updateClassifierCaps(from url: URL) { + guard fm.fileExists(atPath: url.path) else { + return + } + let content: String + do { + content = try String(contentsOf: url) + } catch { + log("Failed to read classifier training result file: \(error)") + return + } + guard let version = readClassifierVersionFromDisk() else { + return + } + + let trainedCaps = content + .components(separatedBy: "\n") + .compactMap(Int.init) + + for cap in trainedCaps { + if caps[cap]?.classifierVersion == nil { + caps[cap]?.classifierVersion = version + } + } + } + + private func readClassifierVersionFromDisk() -> Int? { + do { + let content = try String(contentsOf: classifierVersionFile) + return Int(content) + } catch { + log("Failed to read classifier version file: \(error)") + return nil + } + } } diff --git a/Sources/App/routes.swift b/Sources/App/routes.swift index 71ddc3e..c12cc0c 100755 --- a/Sources/App/routes.swift +++ b/Sources/App/routes.swift @@ -39,4 +39,11 @@ func routes(_ app: Application) throws { let data = Data(buffer: buffer) try server.save(image: data, for: cap) } + + // Update the classifier versions from file on disk + app.getCatching("refresh") { _ in + let url = URL(fileURLWithPath: app.directory.resourcesDirectory) + .appendingPathComponent("classifier.trained") + server.updateClassifierCaps(from: url) + } }