import CoreGraphics import DataModels import Diffusion import ImageGenerator import ImageIO import ModelZoo import NNC import ScriptDataModels import UniformTypeIdentifiers #if canImport(UIKit) import UIKit #endif #if canImport(CoreML) import CoreML import NNCCoreMLConversion import DiffusionCoreML import ZIPFoundation #endif public enum ImageConverter { public static func cgImage(from data: Data) -> CGImage? { guard let source = CGImageSourceCreateWithData(data as CFData, nil) else { return nil } return CGImageSourceCreateImageAtIndex(source, 0, nil) } public static func bitmapContext(from cgImage: CGImage) -> CGContext? { guard let bitmapContext = CGContext( data: nil, width: cgImage.width, height: cgImage.height, bitsPerComponent: 8, bytesPerRow: cgImage.width * 4, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGBitmapInfo.byteOrderDefault.rawValue | CGImageAlphaInfo.premultipliedLast.rawValue, releaseCallback: nil, releaseInfo: nil) else { return nil } bitmapContext.draw( cgImage, in: CGRect(x: 0, y: 0, width: cgImage.width, height: cgImage.height)) return bitmapContext } public static func resize( from cgImage: CGImage, imageWidth: Int, imageHeight: Int, interpolationQuality: CGInterpolationQuality = .high ) -> CGContext? { guard let bitmapContext = CGContext( data: nil, width: imageWidth, height: imageHeight, bitsPerComponent: 8, bytesPerRow: imageWidth * 4, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGBitmapInfo.byteOrderDefault.rawValue | CGImageAlphaInfo.premultipliedLast.rawValue, releaseCallback: nil, releaseInfo: nil) else { return nil } bitmapContext.interpolationQuality = interpolationQuality let scaledWidth: Int let scaledHeight: Int if cgImage.width * imageHeight > cgImage.height * imageWidth { scaledHeight = imageHeight scaledWidth = cgImage.width * imageHeight / cgImage.height } else { scaledWidth = imageWidth scaledHeight = cgImage.height * imageWidth / cgImage.width } bitmapContext.draw( cgImage, in: CGRect( x: (imageWidth - scaledWidth) / 2, y: (imageHeight - scaledHeight) / 2, width: scaledWidth, height: scaledHeight)) return bitmapContext } #if canImport(UIKit) public static func resize( from image: UIImage, imageWidth: Int, imageHeight: Int, interpolationQuality: CGInterpolationQuality = .high ) -> CGContext? { guard let cgImage = image.cgImage, let bitmapContext = CGContext( data: nil, width: imageWidth, height: imageHeight, bitsPerComponent: 8, bytesPerRow: imageWidth * 4, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGBitmapInfo.byteOrderDefault.rawValue | CGImageAlphaInfo.premultipliedLast.rawValue, releaseCallback: nil, releaseInfo: nil) else { return nil } bitmapContext.interpolationQuality = interpolationQuality // Scale to fill. var cgImageWidth = cgImage.width var cgImageHeight = cgImage.height if image.imageOrientation == .left || image.imageOrientation == .leftMirrored || image.imageOrientation == .right || image.imageOrientation == .rightMirrored { swap(&cgImageWidth, &cgImageHeight) } var scaledWidth: Int var scaledHeight: Int if cgImageWidth * imageHeight > cgImageHeight * imageWidth { scaledHeight = imageHeight scaledWidth = cgImageWidth * imageHeight / cgImageHeight } else { scaledWidth = imageWidth scaledHeight = cgImageHeight * imageWidth / cgImageWidth } if image.imageOrientation == .left || image.imageOrientation == .leftMirrored || image.imageOrientation == .right || image.imageOrientation == .rightMirrored { swap(&scaledWidth, &scaledHeight) } // Set rotation angle with image orientation. Don't deal with mirrored just yet. switch image.imageOrientation { case .up: break case .upMirrored: bitmapContext.translateBy(x: CGFloat(imageWidth) / 2, y: CGFloat(imageHeight) / 2) bitmapContext.scaleBy(x: -1, y: 1) bitmapContext.translateBy(x: -CGFloat(imageWidth) / 2, y: -CGFloat(imageHeight) / 2) case .down, .downMirrored: bitmapContext.translateBy(x: CGFloat(imageWidth) / 2, y: CGFloat(imageHeight) / 2) if image.imageOrientation == .downMirrored { bitmapContext.scaleBy(x: -1, y: 1) } bitmapContext.rotate(by: .pi) bitmapContext.translateBy(x: -CGFloat(imageWidth) / 2, y: -CGFloat(imageHeight) / 2) case .left, .rightMirrored: bitmapContext.translateBy(x: CGFloat(imageWidth) / 2, y: CGFloat(imageHeight) / 2) if image.imageOrientation == .rightMirrored { bitmapContext.scaleBy(x: -1, y: 1) } bitmapContext.rotate(by: .pi / 2) bitmapContext.translateBy(x: -CGFloat(imageWidth) / 2, y: -CGFloat(imageHeight) / 2) case .right, .leftMirrored: bitmapContext.translateBy(x: CGFloat(imageWidth) / 2, y: CGFloat(imageHeight) / 2) if image.imageOrientation == .leftMirrored { bitmapContext.scaleBy(x: -1, y: 1) } bitmapContext.rotate(by: .pi * 3 / 2) bitmapContext.translateBy(x: -CGFloat(imageWidth) / 2, y: -CGFloat(imageHeight) / 2) @unknown default: break } bitmapContext.draw( cgImage, in: CGRect( x: (imageWidth - scaledWidth) / 2, y: (imageHeight - scaledHeight) / 2, width: scaledWidth, height: scaledHeight)) return bitmapContext } public static func grayscaleTensor(from image: UIImage, imageWidth: Int, imageHeight: Int) -> Tensor< UInt8 >? { guard let cgImage = image.cgImage, let bitmapContext = CGContext( data: nil, width: imageWidth, height: imageHeight, bitsPerComponent: 8, bytesPerRow: imageWidth * 4, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGBitmapInfo.byteOrderDefault.rawValue | CGImageAlphaInfo.premultipliedLast.rawValue, releaseCallback: nil, releaseInfo: nil) else { return nil } bitmapContext.interpolationQuality = .high // Scale to fill. var cgImageWidth = cgImage.width var cgImageHeight = cgImage.height if image.imageOrientation == .left || image.imageOrientation == .leftMirrored || image.imageOrientation == .right || image.imageOrientation == .rightMirrored { swap(&cgImageWidth, &cgImageHeight) } var scaledWidth: Int var scaledHeight: Int if cgImageWidth * imageHeight > cgImageHeight * imageWidth { scaledHeight = imageHeight scaledWidth = cgImageWidth * imageHeight / cgImageHeight } else { scaledWidth = imageWidth scaledHeight = cgImageHeight * imageWidth / cgImageWidth } if image.imageOrientation == .left || image.imageOrientation == .leftMirrored || image.imageOrientation == .right || image.imageOrientation == .rightMirrored { swap(&scaledWidth, &scaledHeight) } // Set rotation angle with image orientation. Don't deal with mirrored just yet. switch image.imageOrientation { case .up: break case .upMirrored: bitmapContext.translateBy(x: CGFloat(imageWidth) / 2, y: CGFloat(imageHeight) / 2) bitmapContext.scaleBy(x: -1, y: 1) bitmapContext.translateBy(x: -CGFloat(imageWidth) / 2, y: -CGFloat(imageHeight) / 2) case .down, .downMirrored: bitmapContext.translateBy(x: CGFloat(imageWidth) / 2, y: CGFloat(imageHeight) / 2) if image.imageOrientation == .downMirrored { bitmapContext.scaleBy(x: -1, y: 1) } bitmapContext.rotate(by: .pi) bitmapContext.translateBy(x: -CGFloat(imageWidth) / 2, y: -CGFloat(imageHeight) / 2) case .left, .rightMirrored: bitmapContext.translateBy(x: CGFloat(imageWidth) / 2, y: CGFloat(imageHeight) / 2) if image.imageOrientation == .rightMirrored { bitmapContext.scaleBy(x: -1, y: 1) } bitmapContext.rotate(by: .pi / 2) bitmapContext.translateBy(x: -CGFloat(imageWidth) / 2, y: -CGFloat(imageHeight) / 2) case .right, .leftMirrored: bitmapContext.translateBy(x: CGFloat(imageWidth) / 2, y: CGFloat(imageHeight) / 2) if image.imageOrientation == .leftMirrored { bitmapContext.scaleBy(x: -1, y: 1) } bitmapContext.rotate(by: .pi * 3 / 2) bitmapContext.translateBy(x: -CGFloat(imageWidth) / 2, y: -CGFloat(imageHeight) / 2) @unknown default: break } bitmapContext.draw( cgImage, in: CGRect( x: (imageWidth - scaledWidth) / 2, y: (imageHeight - scaledHeight) / 2, width: scaledWidth, height: scaledHeight)) return grayscaleTensor(from: bitmapContext) } #endif public static func grayscaleTensor(from bitmapContext: CGContext) -> Tensor? { precondition(bitmapContext.bytesPerRow >= bitmapContext.width * 4) guard let data = bitmapContext.data else { return nil } let bytes = data.assumingMemoryBound(to: UInt8.self) let bytesPerRow = bitmapContext.bytesPerRow let imageHeight = bitmapContext.height let imageWidth = bitmapContext.width func fillGrayscaleTensor(destination u8: UnsafeMutablePointer) { for y in 0..> 15) } } } } var tensor = Tensor(.CPU, .NC(bitmapContext.height, bitmapContext.width)) tensor.withUnsafeMutableBytes { (unsafeMutableRawBufferPointer: UnsafeMutableRawBufferPointer) in guard let u8: UnsafeMutablePointer = unsafeMutableRawBufferPointer.baseAddress? .assumingMemoryBound(to: UInt8.self) else { return } fillGrayscaleTensor(destination: u8) } return tensor } public static func scribbleRGB(from tensor: Tensor) -> Tensor { let imageHeight = tensor.shape[0] let imageWidth = tensor.shape[1] var rgb = Tensor(.CPU, .NHWC(1, imageHeight, imageWidth, 3)) rgb.withUnsafeMutableBytes { guard let fp16 = $0.baseAddress?.assumingMemoryBound(to: FloatType.self) else { return } tensor.withUnsafeBytes { guard let u8 = $0.baseAddress?.assumingMemoryBound(to: UInt8.self) else { return } for i in 0.. 128 { fp16[i * 3] = 0 fp16[i * 3 + 1] = 0 fp16[i * 3 + 2] = 0 } else { fp16[i * 3] = 1 fp16[i * 3 + 1] = 1 fp16[i * 3 + 2] = 1 } } } } return rgb } static func scribble(from binaryMask: Tensor) -> Tensor? { let maskHeight = binaryMask.shape[0] let maskWidth = binaryMask.shape[1] var flag = true var paintCount = 0 binaryMask.withUnsafeBytes { guard let u8 = $0.baseAddress?.assumingMemoryBound(to: UInt8.self) else { return } for y in 0..(.CPU, .NC(maskHeight, maskWidth)) scribble.withUnsafeMutableBytes { guard let s8 = $0.baseAddress?.assumingMemoryBound(to: UInt8.self) else { return } binaryMask.withUnsafeBytes { guard let u8 = $0.baseAddress?.assumingMemoryBound(to: UInt8.self) else { return } for y in 0..) -> UIImage { let imageHeight = binaryMask.shape[0] let imageWidth = binaryMask.shape[1] let bytes = UnsafeMutablePointer.allocate(capacity: imageWidth * imageHeight * 4) binaryMask.withUnsafeBytes { guard let u8 = $0.baseAddress?.assumingMemoryBound(to: UInt8.self) else { return } for i in 0..) -> UIImage { let imageHeight = tensor.shape[0] let imageWidth = tensor.shape[1] let bytes = UnsafeMutablePointer.allocate(capacity: imageWidth * imageHeight * 4) tensor.withUnsafeBytes { guard let u8 = $0.baseAddress?.assumingMemoryBound(to: UInt8.self) else { return } for i in 0..) -> UIImage { let imageHeight = tensor.shape[1] let imageWidth = tensor.shape[2] let bytes = UnsafeMutablePointer.allocate(capacity: imageWidth * imageHeight * 4) tensor.withUnsafeBytes { guard let fp16 = $0.baseAddress?.assumingMemoryBound(to: FloatType.self) else { return } for i in 0.. Tensor< FloatType >? { let bitmapInfo = CGBitmapInfo.byteOrderDefault.rawValue | CGImageAlphaInfo.premultipliedLast.rawValue guard let cgImage = image.cgImage, let bitmapContext = CGContext( data: nil, width: imageWidth, height: imageHeight, bitsPerComponent: 8, bytesPerRow: imageWidth * 4, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: bitmapInfo, releaseCallback: nil, releaseInfo: nil) else { return nil } bitmapContext.interpolationQuality = .high // Scale to fill. var cgImageWidth = cgImage.width var cgImageHeight = cgImage.height if image.imageOrientation == .left || image.imageOrientation == .leftMirrored || image.imageOrientation == .right || image.imageOrientation == .rightMirrored { swap(&cgImageWidth, &cgImageHeight) } var scaledWidth: Int var scaledHeight: Int if cgImageWidth * imageHeight > cgImageHeight * imageWidth { scaledHeight = imageHeight scaledWidth = cgImageWidth * imageHeight / cgImageHeight } else { scaledWidth = imageWidth scaledHeight = cgImageHeight * imageWidth / cgImageWidth } if image.imageOrientation == .left || image.imageOrientation == .leftMirrored || image.imageOrientation == .right || image.imageOrientation == .rightMirrored { swap(&scaledWidth, &scaledHeight) } // Set rotation angle with image orientation. Don't deal with mirrored just yet. switch image.imageOrientation { case .up: break case .upMirrored: bitmapContext.translateBy(x: CGFloat(imageWidth) / 2, y: CGFloat(imageHeight) / 2) bitmapContext.scaleBy(x: -1, y: 1) bitmapContext.translateBy(x: -CGFloat(imageWidth) / 2, y: -CGFloat(imageHeight) / 2) case .down, .downMirrored: bitmapContext.translateBy(x: CGFloat(imageWidth) / 2, y: CGFloat(imageHeight) / 2) if image.imageOrientation == .downMirrored { bitmapContext.scaleBy(x: -1, y: 1) } bitmapContext.rotate(by: .pi) bitmapContext.translateBy(x: -CGFloat(imageWidth) / 2, y: -CGFloat(imageHeight) / 2) case .left, .rightMirrored: bitmapContext.translateBy(x: CGFloat(imageWidth) / 2, y: CGFloat(imageHeight) / 2) if image.imageOrientation == .rightMirrored { bitmapContext.scaleBy(x: -1, y: 1) } bitmapContext.rotate(by: .pi / 2) bitmapContext.translateBy(x: -CGFloat(imageWidth) / 2, y: -CGFloat(imageHeight) / 2) case .right, .leftMirrored: bitmapContext.translateBy(x: CGFloat(imageWidth) / 2, y: CGFloat(imageHeight) / 2) if image.imageOrientation == .leftMirrored { bitmapContext.scaleBy(x: -1, y: 1) } bitmapContext.rotate(by: .pi * 3 / 2) bitmapContext.translateBy(x: -CGFloat(imageWidth) / 2, y: -CGFloat(imageHeight) / 2) @unknown default: break } bitmapContext.draw( cgImage, in: CGRect( x: (imageWidth - scaledWidth) / 2, y: (imageHeight - scaledHeight) / 2, width: scaledWidth, height: scaledHeight)) return positiveRangeTensor(from: bitmapContext) } #endif public static func positiveRangeTensor(from bitmapContext: CGContext) -> Tensor? { precondition(bitmapContext.bytesPerRow >= bitmapContext.width * 4) guard let data = bitmapContext.data else { return nil } let bytes = data.assumingMemoryBound(to: UInt8.self) let bytesPerRow = bitmapContext.bytesPerRow let imageHeight = bitmapContext.height let imageWidth = bitmapContext.width var tensor = Tensor(.CPU, .NHWC(1, imageHeight, imageWidth, 3)) tensor.withUnsafeMutableBytes { guard let f16 = $0.baseAddress?.assumingMemoryBound(to: FloatType.self) else { return } for y in 0..) -> ( Tensor, Tensor? ) { let shape = argbTensor.shape guard shape[3] == 4 else { precondition(shape[3] == 3) return (argbTensor, nil) } let rgbTensor = argbTensor[0..(.CPU, .NC(shape[1], shape[2])) let height = shape[1] let width = shape[2] argbTensor.withUnsafeBytes { guard let f16 = $0.baseAddress?.assumingMemoryBound(to: FloatType.self) else { return } binaryMask.withUnsafeMutableBytes { guard let u8 = $0.baseAddress?.assumingMemoryBound(to: UInt8.self) else { return } for y in 0.., scaleFactor: CGFloat, binaryMask: Tensor? = nil, only1: Bool = false, overlayRects: [CGRect] = [] ) -> UIImage { let imageHeight = tensor.shape[1] let imageWidth = tensor.shape[2] let bytes = UnsafeMutablePointer.allocate(capacity: imageWidth * imageHeight * 4) tensor.withUnsafeBytes { guard let fp16 = $0.baseAddress?.assumingMemoryBound(to: FloatType.self) else { return } for i in 0..= $0.minY && ii <= $0.maxY && ij >= $0.minX && ij <= $0.maxX } // We make it transparent if it is 1 or it is overlapped by the overlay rects. if (byteMask & 7) == 1 || (flag && (byteMask & 7) != 0 && (byteMask & 7) != 3) { let alpha = byteMask & 0xf8 if alpha > 0 { bytes[i * imageWidth * 4 + j * 4] = UInt8( min((Int32(bytes[i * imageWidth * 4 + j * 4]) * Int32(alpha)) >> 8, 255)) bytes[i * imageWidth * 4 + j * 4 + 1] = UInt8( min((Int32(bytes[i * imageWidth * 4 + j * 4 + 1]) * Int32(alpha)) >> 8, 255)) bytes[i * imageWidth * 4 + j * 4 + 2] = UInt8( min((Int32(bytes[i * imageWidth * 4 + j * 4 + 2]) * Int32(alpha)) >> 8, 255)) bytes[i * imageWidth * 4 + j * 4 + 3] = alpha } else { bytes[i * imageWidth * 4 + j * 4] = 0 bytes[i * imageWidth * 4 + j * 4 + 1] = 0 bytes[i * imageWidth * 4 + j * 4 + 2] = 0 bytes[i * imageWidth * 4 + j * 4 + 3] = 0 } } } } } } else { binaryMask.withUnsafeBytes { guard let u8 = $0.baseAddress?.assumingMemoryBound(to: UInt8.self) else { return } for i in 0.. 0 { bytes[i * imageWidth * 4 + j * 4] = UInt8( min((Int32(bytes[i * imageWidth * 4 + j * 4]) * Int32(alpha)) >> 8, 255)) bytes[i * imageWidth * 4 + j * 4 + 1] = UInt8( min((Int32(bytes[i * imageWidth * 4 + j * 4 + 1]) * Int32(alpha)) >> 8, 255)) bytes[i * imageWidth * 4 + j * 4 + 2] = UInt8( min((Int32(bytes[i * imageWidth * 4 + j * 4 + 2]) * Int32(alpha)) >> 8, 255)) bytes[i * imageWidth * 4 + j * 4 + 3] = alpha } else { bytes[i * imageWidth * 4 + j * 4] = 0 bytes[i * imageWidth * 4 + j * 4 + 1] = 0 bytes[i * imageWidth * 4 + j * 4 + 2] = 0 bytes[i * imageWidth * 4 + j * 4 + 3] = 0 } } } } } } return UIImage( cgImage: CGImage( width: imageWidth, height: imageHeight, bitsPerComponent: 8, bitsPerPixel: 32, bytesPerRow: 4 * imageWidth, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGBitmapInfo( rawValue: CGBitmapInfo.byteOrder32Big.rawValue | CGImageAlphaInfo.premultipliedLast.rawValue), provider: CGDataProvider( dataInfo: nil, data: bytes, size: imageWidth * imageHeight * 4, releaseData: { _, p, _ in p.deallocate() })!, decode: nil, shouldInterpolate: false, intent: CGColorRenderingIntent.defaultIntent)!) } else { return UIImage( cgImage: CGImage( width: imageWidth, height: imageHeight, bitsPerComponent: 8, bitsPerPixel: 32, bytesPerRow: 4 * imageWidth, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGBitmapInfo( rawValue: CGBitmapInfo.byteOrder32Big.rawValue | CGImageAlphaInfo.noneSkipLast.rawValue), provider: CGDataProvider( dataInfo: nil, data: bytes, size: imageWidth * imageHeight * 4, releaseData: { _, p, _ in p.deallocate() })!, decode: nil, shouldInterpolate: false, intent: CGColorRenderingIntent.defaultIntent)!) } } #endif @inline(__always) static private func OKlabToLinearsRGB(L: Float, a: Float, b: Float) -> (Float, Float, Float) { let l_ = L + 0.3963377774 * a + 0.2158037573 * b let m_ = L - 0.1055613458 * a - 0.0638541728 * b let s_ = L - 0.0894841775 * a - 1.2914855480 * b let l = l_ * l_ * l_ let m = m_ * m_ * m_ let s = s_ * s_ * s_ return ( +4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s, -1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s, -0.0041960863 * l - 0.7034186147 * m + 1.7076147010 * s ) } @inline(__always) static private func linearsRGBTosRGB(x: Float) -> Float { if x >= 0.04045 { return pow((x + 0.055) / (1 + 0.055), 2.4) } else { return x / 12.92 } } #if canImport(CoreML) public static func imagesWithTAESD(fromLatent tensor: Tensor, version: ModelVersion) -> [CGImage] { var tensor = tensor var shape = tensor.shape let imageHeight: Int let imageWidth: Int let imagePaddingSize: Int let taesd: ManagedMLModel? let isVideo: Bool switch version { case .hiDreamO1: return [] case .flux1, .hiDreamI1, .zImage: imageHeight = shape[1] * 8 imageWidth = shape[2] * 8 isVideo = false switch max(imageWidth, imageHeight) { case 0...768: taesd = flux1TinyDecoderFor768 imagePaddingSize = 768 case 769...1024: taesd = flux1TinyDecoderFor1024 imagePaddingSize = 1024 case 1025...1280: taesd = flux1TinyDecoderFor1280 imagePaddingSize = 1280 case 1281...1536: taesd = flux1TinyDecoderFor1536 imagePaddingSize = 1536 case 1537...1792: taesd = flux1TinyDecoderFor1792 imagePaddingSize = 1792 case 1793...2048: taesd = flux1TinyDecoderFor2048 imagePaddingSize = 2048 default: return [] } case .v1, .v2, .svdI2v: imageHeight = shape[1] * 8 imageWidth = shape[2] * 8 isVideo = false switch max(imageWidth, imageHeight) { case 0...768: taesd = sdTinyDecoderFor768 imagePaddingSize = 768 case 769...1024: taesd = sdTinyDecoderFor1024 imagePaddingSize = 1024 case 1025...1280: taesd = sdTinyDecoderFor1280 imagePaddingSize = 1280 case 1281...1536: taesd = sdTinyDecoderFor1536 imagePaddingSize = 1536 case 1537...1792: taesd = sdTinyDecoderFor1792 imagePaddingSize = 1792 case 1793...2048: taesd = sdTinyDecoderFor2048 imagePaddingSize = 2048 default: return [] } case .sd3, .sd3Large: imageHeight = shape[1] * 8 imageWidth = shape[2] * 8 isVideo = false switch max(imageWidth, imageHeight) { case 0...768: taesd = sd3TinyDecoderFor768 imagePaddingSize = 768 case 769...1024: taesd = sd3TinyDecoderFor1024 imagePaddingSize = 1024 case 1025...1280: taesd = sd3TinyDecoderFor1280 imagePaddingSize = 1280 case 1281...1536: taesd = sd3TinyDecoderFor1536 imagePaddingSize = 1536 case 1537...1792: taesd = sd3TinyDecoderFor1792 imagePaddingSize = 1792 case 1793...2048: taesd = sd3TinyDecoderFor2048 imagePaddingSize = 2048 default: return [] } case .sdxlBase, .sdxlRefiner, .ssd1b, .pixart, .auraflow: imageHeight = shape[1] * 8 imageWidth = shape[2] * 8 isVideo = false switch max(imageWidth, imageHeight) { case 0...768: taesd = sdxlTinyDecoderFor768 imagePaddingSize = 768 case 769...1024: taesd = sdxlTinyDecoderFor1024 imagePaddingSize = 1024 case 1025...1280: taesd = sdxlTinyDecoderFor1280 imagePaddingSize = 1280 case 1281...1536: taesd = sdxlTinyDecoderFor1536 imagePaddingSize = 1536 case 1537...1792: taesd = sdxlTinyDecoderFor1792 imagePaddingSize = 1792 case 1793...2048: taesd = sdxlTinyDecoderFor2048 imagePaddingSize = 2048 default: return [] } case .qwenImage2_1: imageHeight = shape[1] * 16 imageWidth = shape[2] * 16 isVideo = false switch max(imageWidth, imageHeight) { case 0...768: taesd = qwenImage2_1TinyDecoderFor768 imagePaddingSize = 768 case 769...1024: taesd = qwenImage2_1TinyDecoderFor1024 imagePaddingSize = 1024 case 1025...1280: taesd = qwenImage2_1TinyDecoderFor1280 imagePaddingSize = 1280 case 1281...1536: taesd = qwenImage2_1TinyDecoderFor1536 imagePaddingSize = 1536 case 1537...1792: taesd = qwenImage2_1TinyDecoderFor1792 imagePaddingSize = 1792 case 1793...2048: taesd = qwenImage2_1TinyDecoderFor2048 imagePaddingSize = 2048 default: return [] } case .qwenImage, .cosmos2_5_2b, .krea2: imageHeight = shape[1] * 8 imageWidth = shape[2] * 8 isVideo = false switch max(imageWidth, imageHeight) { case 0...768: taesd = qwenImageTinyDecoderFor768 imagePaddingSize = 768 case 769...1024: taesd = qwenImageTinyDecoderFor1024 imagePaddingSize = 1024 case 1025...1280: taesd = qwenImageTinyDecoderFor1280 imagePaddingSize = 1280 case 1281...1536: taesd = qwenImageTinyDecoderFor1536 imagePaddingSize = 1536 case 1537...1792: taesd = qwenImageTinyDecoderFor1792 imagePaddingSize = 1792 case 1793...2048: taesd = qwenImageTinyDecoderFor2048 imagePaddingSize = 2048 default: return [] } case .wan21_1_3b, .wan21_14b, .longcatVideoAvatar1_5: imageHeight = shape[1] * 8 imageWidth = shape[2] * 8 isVideo = true switch max(imageWidth, imageHeight) { case 0...512: taesd = wan21TinyDecoderFor512 imagePaddingSize = 512 case 0...768: taesd = wan21TinyDecoderFor768 imagePaddingSize = 768 case 769...1024: taesd = wan21TinyDecoderFor1024 imagePaddingSize = 1024 case 1025...1280: taesd = wan21TinyDecoderFor1280 imagePaddingSize = 1280 default: return [] } case .ernieImage, .flux2, .flux2_4b, .flux2_9b, .ideogram4: imageHeight = shape[1] * 8 imageWidth = shape[2] * 8 isVideo = false switch max(imageWidth, imageHeight) { case 0...768: taesd = flux2TinyDecoderFor768 imagePaddingSize = 768 case 769...1024: taesd = flux2TinyDecoderFor1024 imagePaddingSize = 1024 case 1025...1280: taesd = flux2TinyDecoderFor1280 imagePaddingSize = 1280 case 1281...1536: taesd = flux2TinyDecoderFor1536 imagePaddingSize = 1536 case 1537...1792: taesd = flux2TinyDecoderFor1792 imagePaddingSize = 1792 case 1793...2048: taesd = flux2TinyDecoderFor2048 imagePaddingSize = 2048 default: return [] } case .ltx2: let (_, audioHeight) = LTX2ExtractAudioFramesAndHeight(shape) tensor = tensor[0.. audioHeight else { return [] } tensor = tensor[0..) -> CGImage { CGImage( width: imageWidth, height: imageHeight, bitsPerComponent: 8, bitsPerPixel: 32, bytesPerRow: 4 * imageWidth, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGBitmapInfo( rawValue: CGBitmapInfo.byteOrder32Big.rawValue | CGImageAlphaInfo.noneSkipLast.rawValue), provider: CGDataProvider( dataInfo: nil, data: bytes, size: imageWidth * imageHeight * 4, releaseData: { _, p, _ in p.deallocate() })!, decode: nil, shouldInterpolate: false, intent: CGColorRenderingIntent.defaultIntent)! } guard let latentConstraint = model.modelDescription.inputDescriptionsByName["latent"]? .multiArrayConstraint, let imageConstraint = model.modelDescription.outputDescriptionsByName["image"]? .multiArrayConstraint else { return [] } let latentModelShape = latentConstraint.shape.map { $0.intValue } let imageModelShape = imageConstraint.shape.map { $0.intValue } guard latentConstraint.dataType == .float16, imageConstraint.dataType == .float16, latentModelShape.count == 5, imageModelShape.count == 5 else { return [] } let chunkT = latentModelShape[1] let paddedLatentHeight = latentModelShape[2] let paddedLatentWidth = latentModelShape[3] let latentChannels = latentModelShape[4] let outputFramesPerCall = imageModelShape[1] let outputHeight = imageModelShape[2] let outputWidth = imageModelShape[3] let outputChannels = imageModelShape[4] guard chunkT > 0, outputFramesPerCall > 0, outputFramesPerCall % chunkT == 0 else { return [] } let tUpscale = outputFramesPerCall / chunkT let framesToTrim = max(0, tUpscale - 1) guard shape.count == 4, shape[1] <= paddedLatentHeight, shape[2] <= paddedLatentWidth, shape[3] == latentChannels, outputHeight >= imageHeight, outputWidth >= imageWidth, outputChannels >= 3 else { return [] } let actInputNames = (0...8).map { "act_\($0)" } let actOutputNames = (0...8).map { "act_\($0)_out" } var states = [MLMultiArray]() states.reserveCapacity(actInputNames.count) for name in actInputNames { guard let constraint = model.modelDescription.inputDescriptionsByName[name]? .multiArrayConstraint, constraint.dataType == .float16 else { return [] } guard let state = try? MLMultiArray( shape: constraint.shape, dataType: constraint.dataType) else { return [] } zeroFill(state) states.append(state) } func copyLatentChunk(from sourceStartFrame: Int, realFrames: Int) -> MLMultiArray { var latentChunkTensor = Tensor( Array( repeating: 0, count: chunkT * paddedLatentHeight * paddedLatentWidth * shape[3]), .CPU, .NHWC(chunkT, paddedLatentHeight, paddedLatentWidth, shape[3])) latentChunkTensor[0.. CGImage? { let strides = outputArray.strides.map { $0.intValue } guard strides.count == 5 else { return nil } let tStride = strides[1] let hStride = strides[2] let wStride = strides[3] let cStride = strides[4] let bytes = UnsafeMutablePointer.allocate( capacity: imageWidth * imageHeight * 4) guard outputArray.dataType == .float16 else { bytes.deallocate() return nil } let ptr = outputArray.dataPointer.bindMemory( to: FloatType.self, capacity: outputArray.count) var o = bytes let frameBase = frameIndex * tStride for y in 0..]() if imageWidth != imagePaddingSize || imageHeight != imagePaddingSize { for i in 0..( Array( repeating: 0, count: latentPaddingSize * latentPaddingSize * shape[3]), .CPU, .NHWC(1, latentPaddingSize, latentPaddingSize, shape[3])) image[0..<1, 0.. 1 { for i in 0...allocate( capacity: imageWidth * imageHeight * 4) var o = bytes for _ in 0.., canUseTAESD: Bool, version: ModelVersion ) -> ([CGImage], Bool) { let shape = tensor.shape let batchSize = shape[0] let imageHeight = shape[1] let imageWidth = shape[2] let channels = shape[3] if version == .hiDreamO1 { let patchSize = 32 guard channels == 3 * patchSize * patchSize else { return ([], false) } let outputWidth = imageWidth * patchSize let outputHeight = imageHeight * patchSize return tensor.withUnsafeBytes { guard let fp16 = $0.baseAddress?.assumingMemoryBound(to: FloatType.self) else { return ([], false) } var images = [CGImage]() for b in 0...allocate(capacity: outputWidth * outputHeight * 4) let fp16 = fp16 + b * imageHeight * imageWidth * channels for y in 0.. 0 else { return ([], false) } var images = [CGImage]() for b in 0...allocate(capacity: imageWidth * imageHeight * 4) let fp16 = fp16 + b * shape[1] * imageWidth * channels switch version { case _ where channels == 24: for i in 0.., canUseTAESD: Bool, version: ModelVersion ) -> ([UIImage], Bool) { let (cgImages, usedTAESD) = cgImages( fromLatent: tensor, canUseTAESD: canUseTAESD, version: version) return (cgImages.map(UIImage.init(cgImage:)), usedTAESD) } #endif #if canImport(UIKit) public static func imageData( from tensor: Tensor, binaryMask: Tensor?, configuration: GenerationConfiguration, savedPositivePrompt: String, savedNegativePrompt: String, memorizedBy: Set, profile: GenerationProfile? = nil ) -> Data? { return autoreleasepool { () -> Data? in guard let cgImage = image(from: tensor, scaleFactor: 1, binaryMask: binaryMask).cgImage else { return nil } let data = NSMutableData() guard let imageDestination = CGImageDestinationCreateWithData( data as CFMutableData, UTType.png.identifier as CFString, 1, nil) else { return nil } var description = "\(savedPositivePrompt.trimmingCharacters(in: .whitespacesAndNewlines))\n" if savedNegativePrompt.count > 0 { description += "-\(savedNegativePrompt.trimmingCharacters(in: .whitespacesAndNewlines))\n" } let model = configuration.model ?? ModelZoo.defaultSpecification.file let modelVersion = ModelZoo.versionForModel(model) let hasTeaCache = ModelZoo.teaCacheCoefficientsForModel(model) != nil let modifier = ImageGeneratorUtils.modifierForModel( model, LoRAs: configuration.loras.compactMap(\.file)) let seedMode: String switch configuration.seedMode { case .legacy: seedMode = "Legacy" case .torchCpuCompatible: seedMode = "Torch CPU Compatible" case .scaleAlike: seedMode = "Scale Alike" case .nvidiaGpuCompatible: seedMode = "NVIDIA GPU Compatible" } let sampler = configuration.sampler.description description += "Steps: \(configuration.steps), Sampler: \(sampler), Guidance Scale: \(configuration.guidanceScale), Seed: \(configuration.seed), Size: \(configuration.startWidth * 64)x\(configuration.startHeight * 64), Model: \(model), Strength: \(configuration.strength), Seed Mode: \(seedMode)" var json = [String: Any]() let jsonEncoder = JSONEncoder() if let data = try? jsonEncoder.encode( JSGenerationConfiguration(configuration: configuration)) { json["v2"] = try? JSONSerialization.jsonObject( with: data, options: [.topLevelDictionaryAssumed]) } json["c"] = savedPositivePrompt.trimmingCharacters(in: .whitespacesAndNewlines) json["uc"] = savedNegativePrompt.trimmingCharacters(in: .whitespacesAndNewlines) json["steps"] = configuration.steps json["sampler"] = sampler json["scale"] = configuration.guidanceScale json["seed"] = configuration.seed json["size"] = "\(configuration.startWidth * 64)x\(configuration.startHeight * 64)" json["model"] = model json["strength"] = configuration.strength json["seed_mode"] = seedMode if let upscaler = configuration.upscaler, UpscalerZoo.isModelDownloaded(upscaler, memorizedBy: memorizedBy) { json["upscaler"] = upscaler description += ", Upscaler: \(upscaler)" } if configuration.shift != 1 { json["shift"] = configuration.shift description += ", Shift: \(configuration.shift)" } if configuration.clipSkip > 1 { json["clip_skip"] = configuration.clipSkip description += ", CLIP Skip: \(configuration.clipSkip)" } if configuration.sharpness > 0 { json["sharpness"] = configuration.sharpness description += ", Sharpness: \(configuration.sharpness)" } if configuration.maskBlur > 0 { json["mask_blur"] = configuration.maskBlur } if configuration.maskBlurOutset != 0 { json["mask_blur_outset"] = configuration.maskBlurOutset description += ", Mask Blur Outset: \(configuration.maskBlurOutset)" } if modifier == .editing { json["image_guidance"] = configuration.imageGuidanceScale description += ", Image Guidance: \(configuration.imageGuidanceScale)" } if configuration.hiresFix && modelVersion != .wurstchenStageC { description += ", Hires Fix: true, First Stage Size: \(configuration.hiresFixStartWidth * 64)x\(configuration.hiresFixStartHeight * 64), Second Stage Strength: \(configuration.hiresFixStrength)" json["hires_fix"] = configuration.hiresFix json["first_stage_size"] = "\(configuration.hiresFixStartWidth * 64)x\(configuration.hiresFixStartHeight * 64)" json["second_stage_strength"] = configuration.hiresFixStrength } let refinerVersion: ModelVersion? = configuration.refinerModel.flatMap { guard $0 != configuration.model, ModelZoo.isModelDownloaded($0, memorizedBy: memorizedBy) else { return nil } let version = ModelZoo.versionForModel($0) guard ModelZoo.isCompatibleRefiner(modelVersion, refinerVersion: version) else { return nil } return ModelZoo.versionForModel($0) } let loras: [LoRAConfiguration] = configuration.loras.compactMap { guard let file = $0.file, LoRAZoo.isModelDownloaded(file, memorizedBy: memorizedBy) else { return nil } let loraVersion = LoRAZoo.versionForModel(file) guard modelVersion == loraVersion || refinerVersion == loraVersion else { return nil } return LoRAConfiguration( file: file, weight: $0.weight, version: modelVersion, isLoHa: LoRAZoo.isLoHaForModel(file), modifier: LoRAZoo.modifierForModel(file), mode: .init(from: $0.mode)) } if modelVersion == .kandinsky21 { json["clip_weight"] = configuration.clipWeight description += ", CLIP Weight: \(configuration.clipWeight.formatted(.percent.precision(.fractionLength(0))))" json["image_prior_steps"] = configuration.imagePriorSteps description += ", Image Prior Steps: \(configuration.imagePriorSteps)" json["negative_prompt_for_image_prior"] = configuration.negativePromptForImagePrior description += ", Negative Prompt for Image Prior: \(configuration.negativePromptForImagePrior ? "true" : "false")" } if modelVersion == .minimaxH3 { json["shift_for_audio"] = configuration.shiftForAudio description += ", Audio Shift: \(configuration.shiftForAudio)" } if modelVersion == .ideogram4 { json["expand_prompt_to_json"] = configuration.expandPromptToJson description += ", Expand Prompt to JSON: \(configuration.expandPromptToJson ? "true" : "false")" } if modelVersion == .wurstchenStageC { let width = Int( ((Double( configuration.hiresFixStartWidth > 0 && configuration.hiresFix ? configuration.hiresFixStartWidth : configuration.startWidth) * 3) / 2).rounded( .up)) let height = Int( ((Double( configuration.hiresFixStartHeight > 0 && configuration.hiresFix ? configuration.hiresFixStartHeight : configuration.startHeight) * 3) / 2).rounded( .up)) json["stage_1_latents_size"] = "\(width)x\(height)" description += ", Stage 1 Latents Size: \(width)x\(height)" json["stage_2_steps"] = configuration.stage2Steps description += ", Stage 2 Steps: \(configuration.stage2Steps)" json["stage_2_guidance"] = configuration.stage2Cfg description += ", Stage 2 Guidance: \(configuration.stage2Cfg)" if configuration.stage2Shift != 1 { json["stage_2_shift"] = configuration.stage2Shift description += ", Stage 2 Shift: \(configuration.stage2Shift)" } } if let refiner = configuration.refinerModel { json["refiner"] = refiner json["refiner_start"] = configuration.refinerStart description += ", Refiner: \(refiner), Refiner Start: \(configuration.refinerStart.formatted(.percent.precision(.fractionLength(0))))" } if modelVersion == .sdxlBase || modelVersion == .sdxlRefiner || modelVersion == .ssd1b { json["target_size"] = "\(configuration.targetImageWidth)x\(configuration.targetImageHeight)" json["crop_top"] = configuration.cropTop json["crop_left"] = configuration.cropLeft json["original_size"] = "\(configuration.originalImageWidth)x\(configuration.originalImageHeight)" json["aesthetic_score"] = configuration.aestheticScore json["negative_aesthetic_score"] = configuration.negativeAestheticScore json["zero_negative_prompt"] = configuration.zeroNegativePrompt json["negative_original_size"] = "\(configuration.negativeOriginalImageWidth)x\(configuration.negativeOriginalImageHeight)" description += ", Target Size: \(configuration.targetImageWidth)x\(configuration.targetImageHeight), Crop: (\(configuration.cropTop), \(configuration.cropLeft)), Original Size: \(configuration.originalImageWidth)x\(configuration.originalImageHeight), Negative Original Size: \(configuration.negativeOriginalImageWidth)x\(configuration.negativeOriginalImageHeight), Aesthetic Score: \(configuration.aestheticScore.formatted(.number.precision(.fractionLength(1)))), Negative Aesthetic Score: \(configuration.negativeAestheticScore.formatted(.number.precision(.fractionLength(1)))), Zero Negative Prompt: \(configuration.zeroNegativePrompt ? "true" : "false")" } if modelVersion == .svdI2v { json["num_frames"] = configuration.numFrames json["fps"] = configuration.fpsId json["motion_scale"] = configuration.motionBucketId json["cond_aug"] = configuration.condAug json["min_cfg"] = configuration.startFrameCfg description += ", Number of Frames: \(configuration.numFrames), FPS: \(configuration.fpsId), Motion Scale: \(configuration.motionBucketId), Guiding Frame Noise: \(configuration.condAug.formatted(.number.precision(.fractionLength(2)))), Start Frame Guidance: \(configuration.startFrameCfg.formatted(.number.precision(.fractionLength(1))))" } else if modelVersion == .hunyuanVideo { json["num_frames"] = configuration.numFrames description += ", Number of Frames: \(configuration.numFrames)" } if configuration.tiledDecoding && (configuration.startWidth > configuration.decodingTileWidth || configuration.startHeight > configuration.decodingTileHeight) { json["tiled_decoding"] = configuration.tiledDecoding json["decoding_tile_width"] = configuration.decodingTileWidth * 64 json["decoding_tile_height"] = configuration.decodingTileHeight * 64 json["decoding_tile_overlap"] = configuration.decodingTileOverlap * 64 description += ", Tiled Decoding Enabled: \(configuration.decodingTileWidth * 64)x\(configuration.decodingTileHeight * 64) [\(configuration.decodingTileOverlap * 64)]" } if configuration.tiledDiffusion && (configuration.startWidth > configuration.diffusionTileWidth || configuration.startHeight > configuration.diffusionTileHeight) { json["tiled_diffusion"] = configuration.tiledDiffusion json["diffusion_tile_width"] = configuration.diffusionTileWidth * 64 json["diffusion_tile_height"] = configuration.diffusionTileHeight * 64 json["diffusion_tile_overlap"] = configuration.diffusionTileOverlap * 64 description += ", Tiled Diffusion Enabled: \(configuration.diffusionTileWidth * 64)x\(configuration.diffusionTileHeight * 64) [\(configuration.diffusionTileOverlap * 64)]" } if modelVersion == .minimaxH3 && configuration.usesSolAttention { json["uses_sol_attention"] = true json["sol_attention_start"] = configuration.solAttentionStart json["sol_attention_tau"] = configuration.solAttentionTau description += ", Sol Attention Enabled: \(configuration.solAttentionStart), \(configuration.solAttentionTau.formatted(.number.precision(.fractionLength(2))))" } if hasTeaCache && configuration.teaCache && configuration.teaCacheThreshold > 0 { json["tea_cache"] = configuration.teaCache json["tea_cache_start"] = configuration.teaCacheStart json["tea_cache_end"] = configuration.teaCacheEnd json["tea_cache_threshold"] = configuration.teaCacheThreshold json["tea_cache_max_skip_steps"] = configuration.teaCacheMaxSkipSteps var teaCacheEnd = configuration.teaCacheEnd < 0 ? Int32(configuration.steps) + 1 + configuration.teaCacheEnd : configuration.teaCacheEnd let teaCacheStart = min( max(configuration.teaCacheStart, 0), Int32(configuration.steps)) teaCacheEnd = min( max(max(teaCacheStart, teaCacheEnd), 0), Int32(configuration.steps)) description += ", TeaCache Enabled: \(min(teaCacheStart, teaCacheEnd)) - \(max(teaCacheStart, teaCacheEnd)), \(configuration.teaCacheThreshold.formatted(.number.precision(.fractionLength(2)))), \(configuration.teaCacheMaxSkipSteps)" } if configuration.causalInferenceEnabled && configuration.causalInference > 0 { json["causal_inference"] = configuration.causalInference description += ", Causal Inference: \(configuration.causalInference)" } if configuration.sampler == .TCD || configuration.sampler == .tCDTrailing { json["stochastic_sampling_gamma"] = configuration.stochasticSamplingGamma description += ", Strategic Stochastic Sampling: \(configuration.stochasticSamplingGamma)" } if loras.count > 0 { if let firstLoRA = loras.first, loras.count == 1 { description += ", LoRA Model: \(firstLoRA.file), LoRA Weight: \(firstLoRA.weight)" } else { description += ", \(loras.enumerated().map({ "LoRA \($0 + 1) Model: \($1.file), LoRA \($0 + 1) Weight: \($1.weight)" }).joined(separator: ", "))" } json["lora"] = loras.map { ["model": $0.file, "weight": $0.weight] as [String: Any] } } let ( canInjectControls, canInjectT2IAdapters, canInjectAttentionKVs, canInjectPrompts, injectIPAdapterLengths, _ ) = ImageGeneratorUtils.canInjectControls( hasImage: true, hasDepth: true, hasHints: Set([.scribble, .pose, .color]), hasCustom: true, shuffleCount: 1, controls: configuration.controls, version: modelVersion, memorizedBy: memorizedBy) if canInjectControls || canInjectT2IAdapters || canInjectAttentionKVs || canInjectPrompts || !injectIPAdapterLengths.isEmpty { let controls: [( file: String, weight: Float, guidanceStart: Float, guidanceEnd: Float, noPrompt: Bool, globalAveragePooling: Bool, inputOverride: ControlInputType )] = configuration.controls.compactMap { guard let file = $0.file, let specification = ControlNetZoo.specificationForModel(file), ControlNetZoo.isModelDownloaded(specification, memorizedBy: memorizedBy), let modifier = ControlNetZoo.modifierForModel(file) ?? ControlHintType(from: $0.inputOverride) else { return nil } switch modifier { case .canny, .custom, .depth, .scribble, .pose, .color, .normalbae, .lineart, .softedge, .seg, .inpaint, .ip2p, .shuffle, .mlsd, .tile, .blur, .gray, .lowquality: return ( file, $0.weight, $0.guidanceStart, $0.guidanceEnd, $0.noPrompt, $0.globalAveragePooling, $0.inputOverride ) case .audio: return nil } } if controls.count > 1 { var jsonControls = [[String: Any]]() for (i, control) in controls.enumerated() { description += ", Control \(i + 1): \(control.file), Control \(i + 1) No Prompt: \(control.noPrompt ? "true" : "false"), Control \(i + 1) Weight: \(control.weight), Control \(i + 1) Start: \(control.guidanceStart), Control \(i + 1) End: \(control.guidanceEnd)" var subjson: [String: Any] = [ "file": control.file, "weight": control.weight, "no_prompt": control.noPrompt, "guidance_start": control.guidanceStart, "guidance_end": control.guidanceEnd, ] let modifier = ControlNetZoo.modifierForModel(control.file) ?? ControlHintType(from: control.inputOverride) if modifier == .shuffle { subjson["global_average_pooling"] = control.globalAveragePooling description += ", Control \(i + 1) Global Average Pooling: \(control.globalAveragePooling ? "true" : "false")" } jsonControls.append(subjson) } json["control"] = jsonControls } else if let control = controls.first { description += ", Control: \(control.file), Control No Prompt: \(control.noPrompt ? "true" : "false"), Control Weight: \(control.weight), Control Start: \(control.guidanceStart), Control End: \(control.guidanceEnd)" json["control"] = [ [ "file": control.file, "weight": control.weight, "no_prompt": control.noPrompt, "guidance_start": control.guidanceStart, "guidance_end": control.guidanceEnd, ] as [String: Any] ] } } if let profile = profile { let jsonEncoder = JSONEncoder() jsonEncoder.keyEncodingStrategy = .convertToSnakeCase if let data = try? jsonEncoder.encode(profile), let dict = try? JSONSerialization.jsonObject(with: data) as? [String: Any] { json["profile"] = dict } } var info = [String: Any]() info[kCGImagePropertyPNGDescription as String] = description if let jsonData = try? JSONSerialization.data(withJSONObject: json, options: .sortedKeys) { info[kCGImagePropertyPNGComment as String] = String(data: jsonData, encoding: .utf8) } info[kCGImagePropertyPNGSoftware as String] = "Draw Things" var metadata = [String: Any]() metadata[kCGImagePropertyPNGDictionary as String] = info CGImageDestinationAddImage(imageDestination, cgImage, metadata as CFDictionary) CGImageDestinationFinalize(imageDestination) return data as Data } } #endif public static func tensor(from bitmapContext: CGContext) -> ( Tensor?, Tensor?, Bool ) { precondition(bitmapContext.bytesPerRow >= bitmapContext.width * 4) guard let data = bitmapContext.data else { return (nil, nil, false) } let bytes = data.assumingMemoryBound(to: UInt8.self) var tensor = Tensor(.CPU, .NHWC(1, bitmapContext.height, bitmapContext.width, 3)) let bytesPerRow = bitmapContext.bytesPerRow var hasTransparent = false var hasNonTransparent = true let imageHeight = bitmapContext.height let imageWidth = bitmapContext.width tensor.withUnsafeMutableBytes { guard let fp16 = $0.baseAddress?.assumingMemoryBound(to: FloatType.self) else { return } for y in 0..? = nil if hasTransparent && hasNonTransparent { // Create binaryMask. var binaryMask = Tensor(.CPU, .NC(bitmapContext.height, bitmapContext.width)) binaryMask.withUnsafeMutableBytes { guard let u8 = $0.baseAddress?.assumingMemoryBound(to: UInt8.self) else { return } for y in 0.. ) -> ( String?, String?, GenerationConfiguration? ) { var savedPositivePrompt: String? var savedNegativePrompt: String? var previousConfiguration: GenerationConfiguration? if let imageProperties = imageProperties { if let imageData = imageProperties[kCGImagePropertyExifDictionary as String] as? [String: Any], let userComments = imageData[kCGImagePropertyExifUserComment as String] as? String, let commentsJsonData = userComments.data(using: .utf8), let commentsJsonDictionary = try? JSONSerialization.jsonObject(with: commentsJsonData) as? [String: Any] { var configurationBuilder = GenerationConfigurationBuilder(from: configuration) if let positivePrompt = commentsJsonDictionary["c"] as? String { savedPositivePrompt = positivePrompt } if let negativePrompt = commentsJsonDictionary["uc"] as? String { savedNegativePrompt = negativePrompt } if let steps = commentsJsonDictionary["steps"] as? UInt32 { configurationBuilder.steps = steps } if let sampler = commentsJsonDictionary["sampler"] as? String, !sampler.isEmpty { configurationBuilder.sampler = SamplerType(from: sampler) } if let guidanceScale = commentsJsonDictionary["scale"] as? Float32 { configurationBuilder.guidanceScale = guidanceScale } if let seed = commentsJsonDictionary["seed"] as? Int64 { configurationBuilder.seed = UInt32(seed) } if let size = commentsJsonDictionary["size"] as? String, !size.isEmpty { let components = size.split(separator: "x").compactMap { Int($0) } if components.count == 2 { var width = components[0] var height = components[1] let maxSupportLength = Int(DeviceCapability.maxSupportScale() * 64) if width > maxSupportLength || height > maxSupportLength { if width > height { height = maxSupportLength * height / width width = maxSupportLength } else { width = maxSupportLength * width / height height = maxSupportLength } } configurationBuilder.startWidth = UInt16(width / 64) configurationBuilder.startHeight = UInt16(height / 64) } } if let model = commentsJsonDictionary["model"] as? String { configurationBuilder.model = model } if let strength = commentsJsonDictionary["strength"] as? Float { configurationBuilder.strength = strength } if let seedModeString = commentsJsonDictionary["seed_mode"] as? String { configurationBuilder.seedMode = SeedMode(from: seedModeString) } if let upscaler = commentsJsonDictionary["upscaler"] as? String, UpscalerZoo.isModelDownloaded(upscaler, memorizedBy: memorizedBy) { configurationBuilder.upscaler = upscaler } if let clipSkip = commentsJsonDictionary["clip_skip"] as? UInt32 { configurationBuilder.clipSkip = clipSkip } if let imageGuidance = commentsJsonDictionary["image_guidance"] as? Float32 { configurationBuilder.imageGuidanceScale = imageGuidance } if let hiresFix = commentsJsonDictionary["hires_fix"] as? Bool { configurationBuilder.hiresFix = hiresFix } if let hiresFixSize = commentsJsonDictionary["first_stage_size"] as? String { let components = hiresFixSize.split(separator: "x").compactMap { UInt16($0) } if components.count == 2 { configurationBuilder.hiresFixStartWidth = components[0] / 64 configurationBuilder.hiresFixStartHeight = components[1] / 64 } } if let hiresFixStrength = commentsJsonDictionary["second_stage_strength"] as? Float32 { configurationBuilder.hiresFixStrength = hiresFixStrength } if let clipWeight = commentsJsonDictionary["clip_weight"] as? Float32 { configurationBuilder.clipWeight = clipWeight } if let imagePriorSteps = commentsJsonDictionary["image_prior_steps"] as? UInt32 { configurationBuilder.imagePriorSteps = imagePriorSteps } if let negativePromptImagePrior = commentsJsonDictionary[ "negative_prompt_for_image_prior"] as? Bool { configurationBuilder.negativePromptForImagePrior = negativePromptImagePrior } if let refinerModel = commentsJsonDictionary["refiner"] as? String, !refinerModel.isEmpty { configurationBuilder.refinerModel = refinerModel } if let refinerStart = commentsJsonDictionary["refiner_start"] as? Float32 { configurationBuilder.refinerStart = refinerStart } if let targetSize = commentsJsonDictionary["target_size"] as? String { let components = targetSize.split(separator: "x").compactMap { UInt32($0) } if components.count == 2 { configurationBuilder.targetImageWidth = components[0] configurationBuilder.targetImageHeight = components[1] } } if let cropTop = commentsJsonDictionary["crop_top"] as? Int32 { configurationBuilder.cropTop = cropTop } if let cropLeft = commentsJsonDictionary["crop_left"] as? Int32 { configurationBuilder.cropLeft = cropLeft } if let originalSize = commentsJsonDictionary["original_size"] as? String { let components = originalSize.split(separator: "x").compactMap { UInt32($0) } if components.count == 2 { configurationBuilder.originalImageWidth = components[0] configurationBuilder.originalImageHeight = components[1] } } if let aestheticScore = commentsJsonDictionary["aesthetic_score"] as? Int64 { configurationBuilder.aestheticScore = Float(aestheticScore) } if let negtiveAestheticScore = commentsJsonDictionary["negative_aesthetic_score"] as? Float { configurationBuilder.negativeAestheticScore = negtiveAestheticScore } if let zeroNegativePrompt = commentsJsonDictionary["zero_negative_prompt"] as? Bool { configurationBuilder.zeroNegativePrompt = zeroNegativePrompt } if let usesSolAttention = commentsJsonDictionary["uses_sol_attention"] as? Bool { configurationBuilder.usesSolAttention = usesSolAttention } if let solAttentionStart = commentsJsonDictionary["sol_attention_start"] as? Int32 { configurationBuilder.solAttentionStart = max(0, solAttentionStart) } if let solAttentionTau = commentsJsonDictionary["sol_attention_tau"] as? Float, solAttentionTau.isFinite { configurationBuilder.solAttentionTau = min(max(solAttentionTau, 0), 4) } if let shiftForAudio = commentsJsonDictionary["shift_for_audio"] as? Float, shiftForAudio.isFinite && shiftForAudio > 0 { configurationBuilder.shiftForAudio = shiftForAudio } if let expandPromptToJson = commentsJsonDictionary["expand_prompt_to_json"] as? Bool { configurationBuilder.expandPromptToJson = expandPromptToJson } if let negativeOriginalSize = commentsJsonDictionary["negative_original_size"] as? String { let components = negativeOriginalSize.split(separator: "x").compactMap { UInt32($0) } if components.count == 2 { configurationBuilder.negativeOriginalImageWidth = components[0] configurationBuilder.negativeOriginalImageHeight = components[1] } } if let loraArray = commentsJsonDictionary["lora"] as? [[String: Any]] { let loras = loraArray.compactMap { (lora) -> DataModels.LoRA? in if let file = lora["model"] as? String, LoRAZoo.isModelDownloaded(file, memorizedBy: memorizedBy), let weight = lora["weight"] as? Float { let mode: DataModels.LoRAMode = { switch lora["mode"] as? String { case "base": return .base case "refiner": return .refiner case "all": return .all default: return .all } }() return DataModels.LoRA(file: file, weight: weight, mode: mode) } return nil } configurationBuilder.loras = loras } if let controlsArray = commentsJsonDictionary["control"] as? [[String: Any]] { let controls = controlsArray.compactMap { (control) -> DataModels.Control? in if let file = control["file"] as? String, let specification = ControlNetZoo.specificationForModel(file), ControlNetZoo.isModelDownloaded(specification, memorizedBy: memorizedBy), let weight = control["weight"] as? Float32, let guidanceStart = control["guidance_start"] as? Float32, let guidanceEnd = control["guidance_end"] as? Float32, let noPrompt = control["no_prompt"] as? Bool { var controlObject = DataModels.Control( file: file, weight: weight, guidanceStart: guidanceStart, guidanceEnd: guidanceEnd, noPrompt: noPrompt) if let globalAveragePooling = control["global_average_pooling"] as? Bool { controlObject.globalAveragePooling = globalAveragePooling } return controlObject } return nil } configurationBuilder.controls = controls } previousConfiguration = configurationBuilder.build() } } return (savedPositivePrompt, savedNegativePrompt, previousConfiguration) } }