Skip to content

ibrahimsn98/sdwebui-kotlin

Repository files navigation

Stable Diffusion Kotlin API

Kotlin API client for AUTOMATIC1111/stable-diffusion-webui

Currently supports text2image, image2image processes, ControlNet, ADetailer, ReActor extensions.

Usage

You can create api client instance with custom host, port and protocol. Note that, API support have to be enabled from webui to use this client. You can check how to enable API from here.

val sdWebUiApi = SdWebUi.Builder()
    .host("127.0.0.1")
    .port(7860)
    .useHttps(false)
    .build()

Text2Image

You can use Kotlin DSL builder to create a text2image process with default parameter values.

val result = api.runText2Image {
    prompt("cute dog, high quality")
    negativePrompt("worst quality")
    samplerName("DPM++ 2M Karras")
    steps(25)
}

if (result.isFailure) {
    return println(result.exceptionOrNull())
}

val data = requireNotNull(result.getOrNull())

// Returned images in base64
val images = data.images

// JSON text info about the API call
val info = data.info

Or you can use payload model directly with the stable diffusion service. This usage will require to fill all the request parameters.

val payload = Text2ImagePayload(
    prompt = "cute dog, high quality",
    negativePrompt = "worst quality",
    samplerName = "DPM++ 2M Karras",
    steps = 25,
    //... other parameters
)
val result = api.stableDiffusion.text2Image(payload)

art1

Image2Image

You can use Kotlin DSL builder with default parameter values or payload model directly with the stable diffusion service to create a image2image process.

val result = api.runImage2Image {
    initImages(listOf(loadImage("input-1.jpg")))
    prompt("cute dog, high quality, dog clothes")
    negativePrompt("worst quality")
    samplerName("DPM++ 2M Karras")
    steps(25)
}

if (result.isFailure) {
    return println(result.exceptionOrNull())
}

val images = requireNotNull(result.getOrNull()).images

art1

Extra Single Image

You can use Kotlin DSL builder with default parameter values or payload model directly with the stable diffusion service to create a extraSingleImage process.

val result = api.runExtraSingleImage {
    image(loadImage("input-3.png"))
    upscaler1("R-ESRGAN 4x+")
    upscalingResize(2)
}
if (result.isFailure) {
    return println(result.exceptionOrNull())
}
saveImage(requireNotNull(result.getOrNull()).image)

Extra Batch Images

You can use Kotlin DSL builder with default parameter values or payload model directly with the stable diffusion service to create a extraBatchImages process.

val images = listOf(
    ExtraBatchImages.Image(
        data = loadImage("input-1.png"),
        name = "input-1.png",
    ),
    ExtraBatchImages.Image(
        data = loadImage("input-3.png"),
        name = "input-3.png",
    )
)

val result = api.runExtraBatchImages {
    images(images)
    upscaler1("R-ESRGAN 4x+")
    upscalingResize(2)
}
if (result.isFailure) {
    return println(result.exceptionOrNull())
}
result.getOrNull()?.images.orEmpty().forEach { imageBase64 ->
    saveImage(imageBase64)
}

Configuration and Utility APIs

You can use configuration API methods over client services directly. Response of the most of them are wrapped with a data class, however some of them returns raw string because of type safety. You can parse them your own.

api.core.getQueue()

api.stableDiffusion.setModel("v1-5-pruned-emaonly.safetensors [6ce0161689]")
api.stableDiffusion.refreshCheckpoints()

api.stableDiffusion.getModels() // v1-5-pruned-emaonly.safetensors [6ce0161689] ...
api.stableDiffusion.getSamplers() // DPM++ 2M Karras, DPM++ SDE Karras ...
api.stableDiffusion.getEmbeddings()
api.stableDiffusion.getVae()
api.stableDiffusion.getLoras() // add_detail ...
api.stableDiffusion.getOptions()
api.stableDiffusion.getCmdFlags()
api.stableDiffusion.getExtensions() // adetailer, sd-webui-controlnet ...
api.stableDiffusion.getHypernetworks()
api.stableDiffusion.getFaceRestorers() // CodeFormer, GFPGAN ...
api.stableDiffusion.getRealesrganModels() // R-ESRGAN General 4xV3, R-ESRGAN General WDN 4xV3 ...
api.stableDiffusion.getPromptStyles()
api.stableDiffusion.getUpscalers() // None, Lanczos, Nearest ...
api.stableDiffusion.getLatentUpscaleModes() // Latent, Latent (antialiased) ...
api.stableDiffusion.getScripts() // txt2img, img2img
api.stableDiffusion.getScriptInfo()
api.stableDiffusion.getProgress()
api.stableDiffusion.getMemory()

Extension Support

There are extensions that we can easily include in the generation process. These plugins work by simply adding their specific arguments to the alwayson_scripts parameter.

ControlNet

# https://github.com/Mikubill/sd-webui-controlnet

You can use configuration API below.

api.controlNet.getVersion() // 2
api.controlNet.getModels() // control_canny-fp16 [e3fe7712], control_depth-fp16 [400750f6] ...
api.controlNet.getModules() // none, canny, depth, depth_leres, depth_leres++ ...
api.controlNet.getControlTypes() // none, invert, blur_gaussian, canny ...
api.controlNet.getSettings() // {"control_net_unit_count":3}

To use the extension in your process, first you need to describe your ControlNet units.

val controlNetUnit = controlNetUnit {
    inputImage(loadImage("input-2.jpg"))
    module("canny")
    model("control_canny-fp16 [e3fe7712]")
}

Then, you can create ControlNet instance and use it in the process builder with its extension function.

val controlNet = controlNet {
    addUnit(controlNetUnit)
}

val result = api.runText2Image {
    prompt("cute dog, high quality")
    negativePrompt("worst quality")
    samplerName("DPM++ 2M Karras")
    steps(25)
    controlNet(controlNet) // Extension-specific extension function.
}

if (result.isFailure) {
    return println(result.exceptionOrNull())
}

val images = requireNotNull(result.getOrNull()).images

Alternatively, you can use direct payload model with the stable diffusion service.

val controlNetArgs = ControlNetScriptArgs(
    inputImage = loadImage("input-2.jpg"),
    module = "Canny",
    model = "control_canny-fp16 [e3fe7712]",
    //... other parameters
)
val payload = Text2ImagePayload(
    prompt = "cute dog, high quality",
    negativePrompt = "worst quality",
    samplerName = "DPM++ 2M Karras",
    steps = 25,
    //... other parameters
    alwaysonScripts = mapOf(
        "ControlNet" to listOf(controlNetArgs),
        //... other scripts
    )
)

val result = api.stableDiffusion.text2Image(payload)
ControlNet Input Canny Model Text2Image Output

ADetailer

# https://github.com/Bing-su/adetailer

To use the extension in your process, you can create ADetailer instance and use it in the process builder with its extension function.

val aDetailer = aDetailer {
    model("face_yolov8n.pt")
    prompt("woman, portrait, high quality, glasses")
}

val result = api.runText2Image {
    prompt("woman, portrait, high quality")
    negativePrompt("worst quality")
    samplerName("DPM++ 2M Karras")
    steps(25)
    aDetailer(aDetailer)
}

if (result.isFailure) {
    return println(result.exceptionOrNull())
}

val images = requireNotNull(result.getOrNull()).images
Initial Generation Detected Face Final Generation

ReActor

# https://github.com/Gourieff/sd-webui-reactor

You can use configuration API below.

api.reActor.getModels() // inswapper_128.onnx ...
api.reActor.getUpscalers() // None, Lanczos, Nearest, ESRGAN_4x ...

To use the extension in your process, you can create ReActor instance and use it in the process builder with its extension function.

val reActor = reActor {
    image(loadImage("input-3.jpg"))
    upscalerName("ESRGAN_4x")
}

val result = api.runText2Image {
    prompt("woman, wizard, portrait, high quality")
    negativePrompt("worst quality")
    samplerName("DPM++ 2M Karras")
    steps(25)
    reActor(reActor)
}

if (result.isFailure) {
    return println(result.exceptionOrNull())
}

val images = requireNotNull(result.getOrNull()).images
Initial Generation ReActor Input Final Generation

Installation

// project build.gradle
repositories {
 ....
 maven { url 'https://jitpack.io' }
}

// module build.gradle
dependencies { 
    ...
    implementation("com.github.ibrahimsn98:sdwebui-kotlin:1.0.1")
}

Roadmap

  • Authentication support.
  • Roop extension support.
  • Image upscaling support.
  • Web UI scripts support.
  • RemBG extension support.
  • SegmentAnything extension support.
  • Interrogate support.

References

License

MIT License

Copyright (c) 2024 İbrahim Süren

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.