mirror of
https://github.com/GayPizzaSpecifications/stable-diffusion-rpc.git
synced 2025-08-03 13:31:32 +00:00
Formatting, linting, and hopefully a CI build.
This commit is contained in:
52
Sources/StableDiffusionCore/ModelState.swift
Normal file
52
Sources/StableDiffusionCore/ModelState.swift
Normal 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
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user