Caps-Train/Sources/ClassifierCreator.swift

519 lines
18 KiB
Swift
Raw Normal View History

2023-10-23 12:28:35 +02:00
import Foundation
import CreateML
2023-10-23 14:59:25 +02:00
import Combine
2023-10-23 12:28:35 +02:00
final class ClassifierCreator {
let server: URL
let configuration: Configuration
let imageDirectory: URL
let thumbnailDirectory: URL
2023-10-23 14:59:25 +02:00
let sessionDirectory: URL
2023-10-23 12:28:35 +02:00
let classifierUrl: URL
let df = DateFormatter()
2023-10-23 16:49:56 +02:00
private func print(info: String) {
Swift.print("[INFO] " + info)
}
2023-10-23 12:28:35 +02:00
// MARK: Step 1: Load configuration
init(configuration: Configuration) throws {
self.configuration = configuration
self.server = try configuration.serverUrl()
let contentDirectory = URL(fileURLWithPath: configuration.contentFolder)
self.imageDirectory = contentDirectory.appendingPathComponent("images")
2023-10-23 14:59:25 +02:00
self.sessionDirectory = contentDirectory.appendingPathComponent("session")
2023-10-23 12:28:35 +02:00
self.classifierUrl = contentDirectory.appendingPathComponent("classifier.mlmodel")
self.thumbnailDirectory = contentDirectory.appendingPathComponent("thumbnails")
df.dateFormat = "yy-MM-dd-HH-mm-ss"
}
// MARK: Main function
func run() async throws {
let imagesSnapshotDate = Date()
let (classes, changedImageCount, changedMainImages) = try await loadImages()
guard !classes.isEmpty else {
2023-10-23 16:49:56 +02:00
print(info: "No image classes found, exiting...")
2023-10-23 12:28:35 +02:00
return
}
guard changedImageCount > 0 else {
2023-10-23 16:49:56 +02:00
print(info: "No changed images, so no new classifier trained")
try await createThumbnails(changed: changedMainImages)
print(info: "Done")
2023-10-23 12:28:35 +02:00
return
}
let classifierVersion = try await getClassifierVersion()
let newVersion = classifierVersion + 1
2023-10-23 16:49:56 +02:00
print(info: "Image directory: \(imageDirectory.absoluteURL.path)")
print(info: "Model path: \(classifierUrl.path)")
print(info: "Version: \(newVersion)")
print(info: "Classes: \(classes.count)")
print(info: "Iterations: \(configuration.trainingIterations)")
2023-10-23 12:28:35 +02:00
2023-10-23 14:59:25 +02:00
try await trainAndSaveModel()
try await uploadModel(version: newVersion)
2023-10-23 12:28:35 +02:00
try await upload(classes: classes, lastUpdate: imagesSnapshotDate)
2023-10-23 16:49:56 +02:00
try await createThumbnails(changed: changedMainImages)
print(info: "Done")
2023-10-23 12:28:35 +02:00
}
// MARK: Step 2: Load changed images
func loadImages() async throws -> (classes: [Int], changedImageCount: Int, changedMainImages: [Int]) {
2023-10-23 16:49:56 +02:00
do {
try createFolderIfMissing(imageDirectory)
} catch {
throw TrainingError.mainImageFolderNotCreated(error)
2023-10-23 12:28:35 +02:00
}
2023-10-23 16:49:56 +02:00
let imageCounts = try await getImageCounts()
2023-10-23 12:28:35 +02:00
let missingImageList: [CapImage] = imageCounts
.sorted { $0.key < $1.key }
.reduce(into: []) { list, pair in
let missingImagesForCap: [CapImage] = (0..<pair.value).compactMap { image in
let image = CapImage(cap: pair.key, image: image)
let url = imageUrl(base: imageDirectory, image: image)
guard !FileManager.default.fileExists(atPath: url.path) else {
return nil
}
return image
}
list.append(contentsOf: missingImagesForCap)
}
if missingImageList.isEmpty {
2023-10-23 16:49:56 +02:00
print(info: "No missing images to load")
2023-10-23 12:28:35 +02:00
} else {
2023-10-23 16:49:56 +02:00
print(info: "Loading \(missingImageList.count) missing images...")
2023-10-23 12:28:35 +02:00
try await loadImages(missingImageList)
}
let changedImageList = try await getChangedImageList()
let filteredChangeList = changedImageList
.filter { $0.image < imageCounts[$0.cap] ?? 0 } // Filter non-existent images
.filter { !missingImageList.contains($0) }
let imagesAlreadyLoad = changedImageList.count - filteredChangeList.count
let suffix = imagesAlreadyLoad > 0 ? " (\(imagesAlreadyLoad) already loaded)" : ""
if filteredChangeList.isEmpty {
2023-10-23 16:49:56 +02:00
print(info: "No changed images to load" + suffix)
2023-10-23 12:28:35 +02:00
} else {
2023-10-23 16:49:56 +02:00
print(info: "Loading \(filteredChangeList.count) changed images" + suffix)
2023-10-23 12:28:35 +02:00
try await loadImages(filteredChangeList)
}
let changedMainImages = changedImageList.filter { $0.image == 0 }.map { $0.cap }
let classes = imageCounts.keys.sorted()
// Delete any image folders not present as caps
try deleteUnnecessaryImageFolders(caps: classes)
return (classes, missingImageList.count + changedImageList.count, changedMainImages)
}
2023-10-23 16:49:56 +02:00
private func getImageCounts() async throws -> [Int : Int] {
let data: Data
do {
data = try await get(server.appendingPathComponent("caps.json"))
} catch {
throw TrainingError.failedToGetCapDatabase(error)
2023-10-23 12:28:35 +02:00
}
do {
2023-10-23 16:49:56 +02:00
return try JSONDecoder()
.decode([Cap].self, from: data)
2023-10-23 12:28:35 +02:00
.reduce(into: [:]) { $0[$1.id] = $1.count }
} catch {
2023-10-23 16:49:56 +02:00
throw TrainingError.failedToDecodeCapDatabase(error)
2023-10-23 12:28:35 +02:00
}
}
private func deleteUnnecessaryImageFolders(caps: [Int]) throws {
let validNames = caps.map { String(format: "%04d", $0) }
let folders: [String]
do {
folders = try FileManager.default.contentsOfDirectory(atPath: imageDirectory.path)
} catch {
2023-10-23 16:49:56 +02:00
throw TrainingError.failedToGetListOfImageFolders(error)
2023-10-23 12:28:35 +02:00
}
for folder in folders {
if validNames.contains(folder) {
continue
}
// Not a valid cap folder
let url = imageDirectory.appendingPathComponent(folder)
do {
try FileManager.default.removeItem(at: url)
2023-10-23 16:49:56 +02:00
print(info: "Removed unused image folder '\(folder)'")
2023-10-23 12:28:35 +02:00
} catch {
2023-10-23 16:49:56 +02:00
throw TrainingError.failedToRemoveImageFolder(folder, error)
2023-10-23 12:28:35 +02:00
}
}
}
private func imageUrl(base: URL, image: CapImage) -> URL {
base.appendingPathComponent(String(format: "%04d/%04d-%02d.jpg", image.cap, image.cap, image.image))
}
2023-10-23 16:49:56 +02:00
private func load(image: CapImage) async throws {
do {
try createFolderIfMissing(imageDirectory.appendingPathComponent(String(format: "%04d", image.cap)))
} catch {
throw TrainingError.failedToCreateImageFolder(image.cap, error)
2023-10-23 12:28:35 +02:00
}
let url = imageUrl(base: server.appendingPathComponent("images"), image: image)
let tempFile: URL, response: URLResponse
do {
(tempFile, response) = try await URLSession.shared.download(from: url)
} catch {
2023-10-23 16:49:56 +02:00
throw TrainingError.failedToLoadImage(image, error)
2023-10-23 12:28:35 +02:00
}
let responseCode = (response as! HTTPURLResponse).statusCode
guard responseCode == 200 else {
2023-10-23 16:49:56 +02:00
throw TrainingError.invalidImageRequestResponse(image, responseCode)
2023-10-23 12:28:35 +02:00
}
do {
let localUrl = imageUrl(base: imageDirectory, image: image)
if FileManager.default.fileExists(atPath: localUrl.path) {
try FileManager.default.removeItem(at: localUrl)
}
try FileManager.default.moveItem(at: tempFile, to: localUrl)
} catch {
2023-10-23 16:49:56 +02:00
throw TrainingError.failedToSaveImage(image, error)
2023-10-23 12:28:35 +02:00
}
}
private func loadImages(_ list: [CapImage]) async throws {
2023-10-23 16:49:56 +02:00
var loadedImageCount = 0
var errors = [Error]()
await withTaskGroup(of: Error?.self) { group in
2023-10-23 12:28:35 +02:00
for image in list {
group.addTask {
2023-10-23 16:49:56 +02:00
do {
try await self.load(image: image)
return nil
} catch {
return error
}
2023-10-23 12:28:35 +02:00
}
}
2023-10-23 16:49:56 +02:00
for await error in group {
if let error {
errors.append(error)
} else {
loadedImageCount += 1
2023-10-23 12:28:35 +02:00
}
}
}
2023-10-23 16:49:56 +02:00
for error in errors {
Swift.print(error.localizedDescription)
}
let expectedCount = list.count
if loadedImageCount != expectedCount {
throw TrainingError.failedToLoadImages(expected: list.count, loaded: loadedImageCount)
2023-10-23 12:28:35 +02:00
}
}
func getChangedImageList() async throws -> [CapImage] {
2023-10-23 16:49:56 +02:00
let string: String
do {
string = try await get(server.appendingPathComponent("changes.txt"))
} catch {
throw TrainingError.failedToGetChangedImagesList(error)
2023-10-23 12:28:35 +02:00
}
2023-10-23 16:49:56 +02:00
return try string
2023-10-23 12:28:35 +02:00
.components(separatedBy: "\n")
2023-10-23 16:49:56 +02:00
.map { $0.trimmingCharacters(in: .whitespaces) }
2023-10-23 12:28:35 +02:00
.filter { $0 != "" }
.compactMap {
let parts = $0.components(separatedBy: ":")
2023-10-23 16:49:56 +02:00
guard parts.count == 3,
let _ = df.date(from: parts[0]),
let cap = Int(parts[1]),
let image = Int(parts[2]) else {
throw TrainingError.invalidEntryInChangeList($0)
2023-10-23 12:28:35 +02:00
}
return CapImage(cap: cap, image: image)
}
}
// MARK: Step 3: Compute version
func getClassifierVersion() async throws -> Int {
2023-10-23 16:49:56 +02:00
let string: String
do {
string = try await get(server.appendingPathComponent("version"))
} catch {
throw TrainingError.failedToGetClassifierVersion(error)
2023-10-23 12:28:35 +02:00
}
guard let version = Int(string) else {
throw TrainingError.invalidClassifierVersion(string)
}
return version
}
// MARK: Step 4: Train classifier
2023-10-23 14:59:25 +02:00
func trainAndSaveModel() async throws {
let model = try await trainModelAsync()
//let model = try trainModelSync()
try save(model: model)
}
func trainModelAsync() async throws -> MLImageClassifier {
let params = MLImageClassifier.ModelParameters(
maxIterations: configuration.trainingIterations,
augmentation: [])
let sessionParameters = MLTrainingSessionParameters(
sessionDirectory: sessionDirectory,
reportInterval: 10,
checkpointInterval: 100,
iterations: 1000)
var subscriptions = [AnyCancellable]()
let job: MLJob<MLImageClassifier>
do {
job = try MLImageClassifier.train(
trainingData: .labeledDirectories(at: imageDirectory),
parameters: params,
sessionParameters: sessionParameters)
} catch {
2023-10-24 10:38:13 +02:00
throw TrainingError.failedToCreateClassifier(error)
2023-10-23 14:59:25 +02:00
}
job.progress
.publisher(for: \.fractionCompleted)
.sink { completed in
2023-10-23 16:49:56 +02:00
Swift.print(String(format: " %.1f %% completed", completed * 100), terminator: "\r")
2023-10-23 14:59:25 +02:00
fflush(stdout)
//guard let progress = MLProgress(progress: job.progress) else {
// return
//}
//if let styleLoss = progress.metrics[.styleLoss] { _ = styleLoss }
//if let contentLoss = progress.metrics[.contentLoss] { _ = contentLoss }
}
.store(in: &subscriptions)
return try await withCheckedThrowingContinuation { continuation in
// Register a sink to receive the resulting model.
job.result.sink { result in
2023-10-24 10:38:13 +02:00
switch result {
case .finished:
break // Continuation already called with model
case .failure(let error):
continuation.resume(throwing: TrainingError.failedToCreateClassifier(error))
}
2023-10-23 16:49:56 +02:00
} receiveValue: { [weak self] model in
2023-10-23 14:59:25 +02:00
// Use model
2023-10-23 16:49:56 +02:00
self?.print(info: "Created model")
2023-10-23 14:59:25 +02:00
continuation.resume(returning: model)
}
.store(in: &subscriptions)
}
}
func trainModelSync() throws -> MLImageClassifier {
let params = MLImageClassifier.ModelParameters(
maxIterations: configuration.trainingIterations,
augmentation: [])
2023-10-23 12:28:35 +02:00
do {
2023-10-23 14:59:25 +02:00
return try MLImageClassifier(
2023-10-23 12:28:35 +02:00
trainingData: .labeledDirectories(at: imageDirectory),
parameters: params)
} catch {
2023-10-24 10:38:13 +02:00
throw TrainingError.failedToCreateClassifier(error)
2023-10-23 12:28:35 +02:00
}
2023-10-23 14:59:25 +02:00
}
private func save(model: MLImageClassifier) throws {
2023-10-23 16:49:56 +02:00
print(info: "Saving classifier...")
2023-10-23 12:28:35 +02:00
do {
try model.write(to: classifierUrl)
} catch {
throw TrainingError.failedToWriteClassifier(error)
}
}
// MARK: Step 5: Upload classifier
2023-10-23 14:59:25 +02:00
func uploadModel(version: Int) async throws {
2023-10-23 16:49:56 +02:00
print(info: "Uploading classifier...")
2023-10-23 12:28:35 +02:00
let modelData: Data
do {
modelData = try Data(contentsOf: classifierUrl)
} catch {
throw TrainingError.failedToReadClassifierData(error)
}
2023-10-23 16:49:56 +02:00
let url = server.appendingPathComponent("classifier/\(version)")
do {
try await post(url: url, body: modelData)
} catch {
throw TrainingError.failedToUploadClassifier(error)
2023-10-23 12:28:35 +02:00
}
}
// MARK: Step 6: Update classes
func upload(classes: [Int], lastUpdate: Date) async throws {
2023-10-23 16:49:56 +02:00
print(info: "Uploading trained classes...")
2023-10-23 12:28:35 +02:00
let dateString = df.string(from: lastUpdate)
let url = server.appendingPathComponent("classes/\(dateString)")
let body = classes.map(String.init).joined(separator: ",").data(using: .utf8)!
2023-10-23 16:49:56 +02:00
do {
try await post(url: url, body: body)
} catch {
throw TrainingError.failedToUploadClassifierClasses(error)
2023-10-23 12:28:35 +02:00
}
}
// MARK: Step 7: Create thumbnails
2023-10-23 16:49:56 +02:00
func createThumbnails(changed: [Int]) async throws {
try ensureMagickAvailability()
do {
try createFolderIfMissing(thumbnailDirectory)
} catch {
throw TrainingError.failedToCreateThumbnailFolder(error)
2023-10-23 12:28:35 +02:00
}
2023-10-23 16:49:56 +02:00
let capIdsOfMissingThumbnails = try await getMissingThumbnailIds()
2023-10-23 12:28:35 +02:00
let all = Set(capIdsOfMissingThumbnails).union(changed)
2023-10-23 16:49:56 +02:00
print(info: "Creating \(all.count) thumbnails...")
2023-10-23 12:28:35 +02:00
for cap in all {
2023-10-23 16:49:56 +02:00
try await createThumbnail(for: cap)
2023-10-23 12:28:35 +02:00
}
}
2023-10-23 16:49:56 +02:00
func ensureMagickAvailability() throws {
2023-10-23 12:28:35 +02:00
do {
let (code, output) = try safeShell("magick --version")
guard code == 0, let version = output.components(separatedBy: "ImageMagick ").dropFirst().first?
.components(separatedBy: " ").first else {
2023-10-23 16:49:56 +02:00
throw TrainingError.magickDependencyNotFound
2023-10-23 12:28:35 +02:00
}
2023-10-23 16:49:56 +02:00
print(info: "Using magick \(version)")
2023-10-23 12:28:35 +02:00
} catch {
2023-10-23 16:49:56 +02:00
throw TrainingError.magickDependencyCheckFailed(error)
2023-10-23 12:28:35 +02:00
}
}
2023-10-23 16:49:56 +02:00
private func getMissingThumbnailIds() async throws -> [Int] {
let string: String
do {
string = try await get(server.appendingPathComponent("thumbnails/missing"))
} catch {
throw TrainingError.failedToGetMissingThumbnailIds(error)
2023-10-23 12:28:35 +02:00
}
return string.components(separatedBy: ",").compactMap(Int.init)
}
2023-10-23 16:49:56 +02:00
private func createThumbnail(for cap: Int) async throws {
2023-10-23 12:28:35 +02:00
let mainImage = CapImage(cap: cap, image: 0)
let inputUrl = imageUrl(base: imageDirectory, image: mainImage)
guard FileManager.default.fileExists(atPath: inputUrl.path) else {
2023-10-23 16:49:56 +02:00
throw TrainingError.missingMainImage(cap)
2023-10-23 12:28:35 +02:00
}
let output = thumbnailDirectory.appendingPathComponent(String(format: "%04d.jpg", cap))
do {
let command = "magick convert \(inputUrl.path) -quality 70% -resize 100x100 \(output.path)"
let (code, output) = try safeShell(command)
if code != 0 {
2023-10-23 16:49:56 +02:00
throw TrainingError.failedToCreateThumbnail(cap, output)
2023-10-23 12:28:35 +02:00
}
} catch {
2023-10-23 16:49:56 +02:00
throw TrainingError.failedToCreateThumbnail(cap, "\(error)")
2023-10-23 12:28:35 +02:00
}
let data: Data
do {
data = try Data(contentsOf: output)
} catch {
2023-10-23 16:49:56 +02:00
throw TrainingError.failedToReadCreatedThumbnail(cap, error)
2023-10-23 12:28:35 +02:00
}
2023-10-23 16:49:56 +02:00
do {
try await post(url: server.appendingPathComponent("thumbnails/\(cap)"), body: data)
} catch {
throw TrainingError.failedToUploadCreatedThumbnail(cap, error)
2023-10-23 12:28:35 +02:00
}
}
// MARK: Helper
@discardableResult
private func safeShell(_ command: String) throws -> (code: Int32, output: String) {
let task = Process()
let pipe = Pipe()
task.standardOutput = pipe
task.standardError = pipe
task.arguments = ["-cl", command]
task.executableURL = URL(fileURLWithPath: "/bin/zsh")
task.standardInput = nil
try task.run()
task.waitUntilExit()
let data = pipe.fileHandleForReading.readDataToEndOfFile()
let output = String(data: data, encoding: .utf8)!
return (task.terminationStatus, output)
}
2023-10-23 16:49:56 +02:00
private func createFolderIfMissing(_ folder: URL) throws {
2023-10-23 12:28:35 +02:00
guard !FileManager.default.fileExists(atPath: folder.path) else {
2023-10-23 16:49:56 +02:00
return
2023-10-23 12:28:35 +02:00
}
2023-10-23 16:49:56 +02:00
try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
2023-10-23 12:28:35 +02:00
}
// MARK: Requests
2023-10-23 16:49:56 +02:00
private func post(url: URL, body: Data) async throws {
2023-10-23 12:28:35 +02:00
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.httpBody = body
request.addValue(configuration.authenticationToken, forHTTPHeaderField: "key")
2023-10-23 16:49:56 +02:00
_ = try await perform(request)
2023-10-23 12:28:35 +02:00
}
2023-10-23 16:49:56 +02:00
private func perform(_ request: URLRequest) async throws -> Data {
let (data, response) = try await URLSession.shared.data(for: request)
2023-10-23 12:28:35 +02:00
let code = (response as! HTTPURLResponse).statusCode
guard code == 200 else {
2023-10-23 16:49:56 +02:00
throw TrainingError.invalidResponse(request.url!, code)
2023-10-23 12:28:35 +02:00
}
return data
}
2023-10-23 16:49:56 +02:00
private func get(_ url: URL) async throws -> Data {
try await perform(URLRequest(url: url))
2023-10-23 12:28:35 +02:00
}
2023-10-23 16:49:56 +02:00
private func get(_ url: URL) async throws -> String {
let data: Data = try await get(url)
2023-10-23 12:28:35 +02:00
guard let string = String(data: data, encoding: .utf8) else {
2023-10-23 16:49:56 +02:00
throw TrainingError.invalidGetResponseData(data.count)
2023-10-23 12:28:35 +02:00
}
return string
}
}