Formatting, linting, and hopefully a CI build.

This commit is contained in:
2023-04-22 15:43:22 -07:00
parent 2759c8d7fb
commit 4bf5ceefbe
13 changed files with 117 additions and 68 deletions

View File

@ -0,0 +1,52 @@
import CoreML
import Foundation
import StableDiffusion
import StableDiffusionProtos
public actor ModelState {
private let url: URL
private var pipeline: StableDiffusionPipeline?
private var tokenizer: BPETokenizer?
public init(url: URL) throws {
self.url = url
}
public func load() throws {
let config = MLModelConfiguration()
config.computeUnits = .all
pipeline = try StableDiffusionPipeline(
resourcesAt: url,
controlNet: [],
configuration: config,
disableSafety: true,
reduceMemory: false
)
let mergesUrl = url.appending(component: "merges.txt")
let vocabUrl = url.appending(component: "vocab.json")
tokenizer = try BPETokenizer(mergesAt: mergesUrl, vocabularyAt: vocabUrl)
}
public func generate(_ request: SdGenerateImagesRequest) throws -> SdGenerateImagesResponse {
guard let pipeline else {
throw SdCoreError.modelNotLoaded
}
var pipelineConfig = StableDiffusionPipeline.Configuration(prompt: request.prompt)
pipelineConfig.negativePrompt = request.negativePrompt
pipelineConfig.seed = UInt32.random(in: 0 ..< UInt32.max)
var response = SdGenerateImagesResponse()
for _ in 0 ..< request.imageCount {
let images = try pipeline.generateImages(configuration: pipelineConfig)
for cgImage in images {
guard let cgImage else { continue }
var image = SdImage()
image.content = try cgImage.toPngData()
response.images.append(image)
}
}
return response
}
}