Skip to content

Example

Meonako edited this page Jun 3, 2023 · 33 revisions

Txt2Img

Text-To-Image

package main

import (
    "fmt"
    "os"

    "github.com/Meonako/webui-api"
    "github.com/Meonako/webui-api/sampler"
    "github.com/Meonako/webui-api/upscaler"
)

func main() {
    API := api.New(api.Config{
        Default: &api.Default{
            Steps:    20,
            Sampler:  sampler.DPM_PLUS_PLUS_2M_KARRAS,
            Width:    384,
            Height:   512,
            CFGScale: 7.0,
        },
    })

    response, err := API.Text2Image(&api.Txt2Image{
        Prompt: "long hair, skinny, narrow waist, gothic lolita, twintails",
        NegativePrompt: api.BuildPrompt(
            "(worst quality, low quality:1.4)",
            "simple background, white background",
        ),
        BatchSize:         2,
        EnableHR:          true,
        DenoisingStrength: 0.5,
        HRScale:           2,
        HRUpscaler:        upscaler.R_ESRGAN_4x_PLUS_ANIME_6B,
    })
    pif(err)

    for index := range response.Images {
        decoded, err := response.DecodeImage(index)
        pif(err)

        file, err := os.Create(fmt.Sprintf("result %v.png", index))
        pif(err)

        _, err = file.Write(decoded)
        pif(err)
    }
}

func pif(err error) {
    if err != nil {
        panic(err)
    }
}

Expected Output

File named "result 0.png" and "result 1.png"

Txt2Img with OverrideSettings

Text-To-Image with specified model for this request only

package main

import (
    "fmt"
    "os"

    "github.com/Meonako/webui-api"
    "github.com/Meonako/webui-api/sampler"
    "github.com/Meonako/webui-api/upscaler"
)

func main() {
    // Currently using `realdosmix_.safetensors [0d27c62ffa]` which is a realistic model
    API := api.New(api.Config{
        Default: &api.Default{
            Steps:    28,
            Sampler:  sampler.DPM_PLUS_PLUS_2M_KARRAS,
            Width:    384,
            Height:   512,
            CFGScale: 7.0,
        },
    })

    response, err := API.Text2Image(&api.Txt2Image{
        Prompt: api.BuildPrompt(
            "(masterpiece), (high quality), highres, (high resolution illustration), bishoujo, (game cg), intricate details, detailed_face",
            "1girl, skinny, narrow waist, white pantyhose",
            "(white serafuku), (school uniform), (blue sailor collar), (red neckerchief), (pleated skirt)",
            "large breasts, lipgloss, hair bow, (absurdly_long_hair:1.5)",
            "beautiful sky and beautiful garden, cowboy_shot",
        ),
        NegativePrompt: api.BuildPrompt(
            "(KHFB, AuroraNegative), EasyNegative, badhandv4",
            "(worst Quality, low quality:1.4), (multiple_girls:1.2), border, nsfw, skimpy, grayscale, umbrella",
        ),
        EnableHR:          true,
        HRScale:           2,
        HRUpscaler:        upscaler.R_ESRGAN_4x_PLUS_ANIME_6B,
        DenoisingStrength: 0.5,
        OverrideSettings: map[string]any{
            "sd_model_checkpoint": "AbyssOrangeMix2_hard", // an anime, semi-realistic style model
        },
        DecodeAfterResult: true,
    })
    pif(err)

    fmt.Println("Successfully decoded", len(response.DecodedImages), "images")
    for idx, decoded := range response.DecodedImages {
        file, err := os.Create(fmt.Sprint("override result", idx, ".png"))
        pif(err)

        file.Write(decoded)
        file.Close()
    }
}

func pif(err error) {
    if err != nil {
        panic(err)
    }
}

Expected Output

File named override result0.png

Txt2Img with Additional Networks

Text-To-Image with Additional Networks Extensions

package main

import (
    "fmt"
    "os"

    "github.com/Meonako/webui-api"
    "github.com/Meonako/webui-api/sampler"
    "github.com/Meonako/webui-api/scripts"
    "github.com/Meonako/webui-api/upscaler"
)

func main() {
    API := api.New(api.Config{
        Default: &api.Default{
            Steps:    20,
            Sampler:  sampler.DPM_PLUS_PLUS_2M_KARRAS,
            Width:    384,
            Height:   512,
            CFGScale: 7.0,
        },
    })

    response, err := API.Text2Image(&api.Txt2Image{
        Prompt:            "asuna \\(blue archive\\)",
        NegativePrompt:    "EasyNegative, paintings, sketches, (worst quality:2), (low quality:2), (normal quality:2), lowres, normal quality, ((monochrome)), ((grayscale)), skin spots, acnes, skin blemishes, age spot, glans, extra fingers, fewer fingers,bad hands,bad legs,holding,nsfw,open mouth",
        Steps:             28,
        BatchSize:         2,
        BatchCount:        2,
        EnableHR:          true,
        DenoisingStrength: 0.5,
        HRUpscaler:        upscaler.R_ESRGAN_4x_PLUS_ANIME_6B,
        HRScale:           2,
        AlwaysOnScripts: map[string]any{
            // Its work the same
            // ---------------------------------------------------
            // "additional networks for generating": map[string]any{
            // 	"args": []any{
            // 		true,
            // 		false,
            // 		"LoRA",
            // 		"Asuna_Medium(4f210a6ad9fa)",
            // 		0.6,
            // 		0.6,
            // 	},
            // },
            // ---------------------------------------------------
            // scripts.ADDITIONAL_NETWORKS: map[string]any{
            //     "args": []any{
            //         true,
            //         false,
            //         "LoRA",
            //         "Asuna_Medium(4f210a6ad9fa)",
            //         0.6,
            //         0.6,
            //     },
            // },
            // ---------------------------------------------------
            scripts.ADD_NET: api.Opt{
                "args": []any{
                    true,  // Enable
                    false, // Separate UNet/Text Encoder weights

                    "LoRA",                       // Network module 1
                    "Asuna_Medium(4f210a6ad9fa)", // Model 1
                    0.6,                          // UNet Weight 1
                    0.6,                          // TEnc Weight 1

                    "LoRA",                                 // Network module 2
                    "koreanDollLikeness_v10(e2e472c06607)", // Model 2
                    0.6,                                    // UNet Weight 2
                    0.6,                                    // TEnc Weight 2
                },
            },
        },
    })
    pif(err)

    for index := range response.Images {
        decoded, err := response.DecodeImage(index)
        pif(err)

        file, err := os.Create(fmt.Sprintf("result %v.png", index))
        pif(err)

        _, err = file.Write(decoded)
        pif(err)
    }
}

func pif(err error) {
    if err != nil {
        panic(err)
    }
}

Expeceted Output

Files named result 0.png, result 1.png, result 2.png and result 3.png

Img2Img

Image-To-Image

Need any image file named original.png

package main

import (
    "fmt"
    "os"

    "github.com/Meonako/webui-api"
    "github.com/Meonako/webui-api/sampler"
    "github.com/Meonako/webui-api/utils"
)

func main() {
    API := api.New(api.Config{
        Default: &api.Default{
            Steps:    20,
            Sampler:  sampler.DPM_PLUS_PLUS_2M_KARRAS,
            Width:    384,
            Height:   512,
            CFGScale: 7.0,
        },
    })

    imageData, err := utils.Base64FromFiles("result 0.png", "result 1.png")
    pif(err)

    response, err := API.Image2Image(&api.Img2Img{
        InitImages:        imageData,
        Prompt:            "long hair, skinny, narrow waist, medium breasts, gothic lolita",
        NegativePrompt:    "(worst quality, low quality:1.4), simple background, white background",
        SamplerIndex:      sampler.EULER_A,
        Width:             768,
        Height:            1024,
        DenoisingStrength: 0.75,
        BatchSize:         2,
    })
    pif(err)

    for index := range response.Images {
        decoded, err := response.DecodeImage(index)
        pif(err)

        file, err := os.Create(fmt.Sprintf("result %v.png", index))
        pif(err)

        _, err = file.Write(decoded)
        pif(err)
    }
}

func pif(err error) {
    if err != nil {
        panic(err)
    }
}

Expected Output

File named "result 0.png" and "result 1.png"

Extra Single

Single Image Upscale & Face Restoration

Need any image file named original.png

package main

import (
    "fmt"
    "os"
    "text/tabwriter"

    "github.com/Meonako/webui-api"
    "github.com/Meonako/webui-api/extra"
    "github.com/Meonako/webui-api/utils"
)

func main() {
    package main

    import (
        "fmt"
        "os"

        "github.com/Meonako/webui-api"
        "github.com/Meonako/webui-api/extra"
        "github.com/Meonako/webui-api/upscaler"
        "github.com/Meonako/webui-api/utils"
    )

    func main() {
        API := api.New()

        fmt.Println("Reading image data...")
        imageData, err := utils.Base64FromFile("original.png")
        pif(err)

        params := api.ExtraSingleImage{
            ResizeMode:      extra.SCALE_BY,                     // 0 || 1
            UpscalingResize: 4,                                  // Only use when ResizeMode = SCALE_BY (0)
            Upscaler1:       upscaler.R_ESRGAN_4x_PLUS_ANIME_6B,
            Image:           imageData,
        }

        result, err := API.ExtraSingleImage(params)
        pif(err)

        fmt.Println("Decoding...")
        fileBytes, err := result.DecodeImage()
        pif(err)

        fmt.Println("Saving...")
        file, err := os.OpenFile("upscaled.png", os.O_WRONLY|os.O_CREATE, 0777)
        pif(err)
        defer file.Close()

        file.Write(fileBytes)
    }

    func pif(err error) {
        if err != nil {
            panic(err)
        }
    }
}

Expected Output

File named upscaled.png

Extra Batch

Multiple Upscale & Face Restoration

Need 4 image file named original 0.png, original 1.png, original 2.png and original 3.png

package main

import (
    "fmt"
    "os"

    "github.com/Meonako/webui-api"
    "github.com/Meonako/webui-api/extra"
    "github.com/Meonako/webui-api/upscaler"
)

func main() {
    API := api.New()

    // images := extra.BuildBatch("base-64 encoded image here", "another one here", "and so on...")
    images, err := extra.BuildBatchFromFiles("original 0.png", "original 1.png", "original 2.png", "original 3.png")
    pif(err)

    params := &api.ExtraBatchImages{
        // ImagesList: []api.ImageData{
        // 	{Data: "data:image/png;base64," + utils.Base64FromFileIgnore("image.png"), Name: "1"},
        // 	{Data: "data:image/png;base64," + utils.Base64FromFileIgnore("original.png"), Name: "2"},
        // 	{Data: "data:image/png;base64," + utils.Base64FromFileIgnore("test.png"), Name: "3"},
        // },
        //
        // ----- Above is the manual way. DON'T FORGET THE "data:image/png;base64," because WITHOUT it, the server will raise an exception. -----
        //
        // ImagesList: extra.BuildBatch(
        // 	utils.Base64FromFileIgnore("test.png"),     // ONLY DO THIS IF YOU'RE SO SURE THAT IT WON'T CAUSE ANY ERRORS
        // 	utils.Base64FromFileIgnore("image.png"),    // Possible Error is from OS package where it can't access || can't find the file
        // 	utils.Base64FromFileIgnore("original.png"), // It'll be better if you caught the error before hand
        // ),
        ResizeMode:        extra.SCALE_BY,
        ImagesList:        images,
        UpscalingResize:   4,
        Upscaler1:         upscaler.R_ESRGAN_4x_PLUS_ANIME_6B,
        DecodeAfterResult: true,
    }

    fmt.Println("Len:", len(params.ImagesList))
    fmt.Println("Upscaler:", params.Upscaler1)

    resp, err := API.ExtraBatchImages(params)
    pif(err)

    fmt.Println("Result:", len(resp.Images))

    if _, err := os.Stat("result"); os.IsNotExist(err) {
        pif(os.Mkdir("result", 0777))
    }

    for index, imageData := range resp.DecodedImages {
        fmt.Println("Saving Index:", index)
        writeToFile(index, imageData)
    }
}

func pif(err error) {
    if err != nil {
        panic(err)
    }
}

// Save image to disk.
func writeToFile(index int, data []byte) {
    file, err := os.OpenFile(fmt.Sprintf("result/upscaled %v.png", index), os.O_CREATE|os.O_WRONLY, 0777)
    pif(err)
    defer file.Close()

    file.Write(data)
}

Expected Output

image

image

PNG Info

Get Generation Parameters in image

Need any image file named original.png

package main

import (
    "fmt"

    "github.com/Meonako/webui-api"
    "github.com/Meonako/webui-api/utils"
)

func main() {
    API := api.New()

    imageData, err := utils.Base64FromFile("original.png")
    if err != nil {
        panic(err)
    }

    result, err := API.PNGInfo(imageData)
    if err != nil {
        panic(err)
    }

    fmt.Println(result)
}

Expected Output

When contains any generation parameters image

Progress

Get Generation Progress

package main

import (
    "fmt"
    "os"
    "text/tabwriter"

    "github.com/Meonako/webui-api"
)

func main() {
    API := api.New()

    progress, err := API.Progress()
    if err != nil {
        panic(err)
    }

    writer := tabwriter.NewWriter(os.Stdout, 1, 1, 3, ' ', 0)
    fmt.Fprintf(writer, "Progress\t|\t%v\n", progress.GetProgress(""))
    fmt.Fprintf(writer, "ETA Name\t|\t%v\n", progress.GetETA())
    fmt.Fprintf(writer, "Current Steps\t|\t%v\n", progress.State.CurrentStep)
    fmt.Fprintf(writer, "Target Sampling Steps\t|\t%v\n", progress.State.TargetSamplingSteps)
    fmt.Fprintf(writer, "Job\t|\t%v\n", progress.State.Job)
    fmt.Fprintf(writer, "Job No\t|\t%v\n", progress.State.JobNo)
    fmt.Fprintf(writer, "Job Count\t|\t%v\n", progress.State.JobCount)
    fmt.Fprintf(writer, "Interrupted\t|\t%v\n", progress.State.Interrupted)
    fmt.Fprintf(writer, "Skipped\t|\t%v\n", progress.State.Skipped)
    writer.Flush()
}

Expected Output

When generating image(s)

image

Interrogate

Get caption of an image

Need any image file named original.png

package main

import (
    "fmt"

    "github.com/Meonako/webui-api"
    "github.com/Meonako/webui-api/interrogate"
    "github.com/Meonako/webui-api/utils"
)

func main() {
    API := api.New()

    image, err := utils.Base64FromFile("original.png")
    pif(err)

    result, err := API.Interrogate(&api.Interrogate{
        Image: image,
        Model: interrogate.DEEPBOORU,
    })
    pif(err)

    fmt.Println(result)
}

func pif(err error) {
    if err != nil {
        panic(err)
    }
}

Expected Output

image

Interrupt

Stop Image Generation and return any result accumulated so far [ NOT return in API ]

package main

import (
    "github.com/Meonako/webui-api"
)

func main() {
    API := api.New()

    err := API.Interrupt()
    if err != nil {
        panic(err)
    }
}

Expected Output

None on your console or error if any

Progress stop on server console

Skip

Skip processing current image and continue processing

package main

import (
    "github.com/Meonako/webui-api"
)

func main() {
    API := api.New()

    err := API.Skip()
    if err != nil {
        panic(err)
    }
}

Expected Output

None on your console or error if any

Get Options

Get Current Settings without Extension Settings

package main

import (
    "fmt"

    "github.com/Meonako/webui-api"
)

func main() {
    API := api.New()

    opt, err := API.Options()
    pif(err)

    fmt.Println(opt.AddModelHashToInfo)
    fmt.Println(opt.AddModelNameToInfo)
}

func pif(err error) {
    if err != nil {
        panic(err)
    }
}

Expected Output

image or value of these options

Get Options with Extension Options

Get All Current Settings

package main

import (
    "fmt"

    "github.com/Meonako/webui-api"
)

func main() {
    API := api.New()

    opt, err := API.OptionsWithExtensionOptions()
    if err != nil {
        panic(err)
    }

    if value, ok := opt["images_history_preload"]; ok {
        fmt.Println(value)
    }
}

Expected Output

None or value of your settings if you have Image Browser extension installed

Set Options

Change Settings without Extension Settings

package main

import (
    "github.com/Meonako/webui-api"
)

func main() {
    API := api.New()

    err := API.SetOptions(&api.Options{
        CleanTempDirAtStart: true,
    })
    if err != nil {
        panic(err)
    }
}

Expected Output

None but you can try and change value in settings or checkout config.json at Web Ui root dir

Set Options with Extension

Change All Settings

package main

import (
    "github.com/Meonako/webui-api"
)

func main() {
    API := api.New()

    err := API.SetOptionsWithExtensionOptions(api.Opt{
        "images_history_preload": true,
    })
    if err != nil {
        panic(err)
    }
}

Expected Output

None but you can try and change value in settings or checkout config.json at Web Ui root dir

SD-Models

Get Available Stable Diffusion Models

package main

import (
    "fmt"
    "os"
    "strings"
    "text/tabwriter"

    "github.com/Meonako/webui-api"
)

func main() {
    API := api.New()

    result, err := API.SDModels()
    if err != nil {
        panic(err)
    }

    writer := tabwriter.NewWriter(os.Stdout, 1, 1, 3, ' ', 0)
    for _, value := range result {
        fmt.Fprintf(writer, "Title\t|\t%v\n", value.Title)
        fmt.Fprintf(writer, "Model Name\t|\t%v\n", value.ModelName)
        fmt.Fprintf(writer, "Hash\t|\t%v\n", value.Hash)
        fmt.Fprintf(writer, "Filename\t|\t%v\n", value.Filename)
        fmt.Fprintf(writer, "Config\t|\t%v\n\n%v\n", value.Config, strings.Repeat("-", 45))
    }
    writer.Flush()
}

Expected Output

image

Clone this wiki locally