sdwebuiapi

repository·main·Indexed 23 days ago

https://github.com/mix1009/sdwebuiapi

A Python client for interacting with the AUTOMATIC1111 Stable Diffusion WebUI API. It provides a high-level interface for text-to-image, image-to-image, inpainting, and image upscaling. The library supports asynchronous calls, ControlNet, ADetailer, X/Y/Z Plot scripts, and Promptgen extension integration, as well as utility methods for managing models and WebUI configurations.

Tokens
3.9K
Snippets
13
Records
16
Agent score
31%

What's inside sdwebuiapi

  1. Use Promptgen extension via API

    main

    To use the Promptgen API, you must install the specific api-implementation branch of the Promptgen extension.

    Once installed, you can:

    1. List available models using api.list_prompt_gen_models().
    2. Generate prompts using api.prompt_gen(text=...).

    api.prompt_gen supports parameters like batch_size, min_length, max_length, temperature, and sampling_mode.

    # Install via CLI
    # cd stable-diffusion-webui/extensions
    # git clone -b api-implementation https://github.com/davidmartinrius/stable-diffusion-webui-promptgen.git
    
    # Usage
    result = api.prompt_gen(
            text="a box", 
            model_name="AUTOMATIC/promptgen-majinai-unsafe",
            batch_size=10,
            min_length=20,
            max_length=150,
            temperature=1,
            sampling_mode="Top K",
            top_k=12
        )
  2. Use ControlNet with txt2img and img2img

    main

    ControlNet support is provided via ControlNetUnit objects.

    For txt2img: The controlnet_units parameter accepts a list of ControlNetUnit objects. Note that the image parameter in ControlNetUnit is used for the input image.

    For img2img: You can use multiple ControlNet units simultaneously by passing them in the controlnet_units list.

    # txt2img with ControlNet
    unit1 = webuiapi.ControlNetUnit(image=img, module='canny', model='control_v11p_sd15_canny [d14c016b]')
    r = api.txt2img(prompt="photo of a beautiful girl", controlnet_units=[unit1])
    
    # img2img with multiple ControlNets
    unit1 = webuiapi.ControlNetUnit(image=img, module='canny', model='control_v11p_sd15_canny [d14c016b]')
    unit2 = webuiapi.ControlNetUnit(image=img, module='depth', model='control_v11f1p_sd15_depth [cfd03158]', weight=0.5)
    
    r2 = api.img2img(prompt="girl",
                images=[img], 
                width=512,
                height=512,
                controlnet_units=[unit1, unit2],
                sampler_name="Euler a",
                cfg_scale=7,
               )
  3. Enable API support in Stable Diffusion WebUI

    main

    Before using the client, you must enable API support in your AUTOMATIC1111/stable-diffusion-webui instance by adding the --api flag when running the webui.

    If you require authentication, you can use the --api-auth username:password option. Note that because this uses basic HTTP authentication, credentials are transmitted in cleartext and are not protected unless using an encrypted communication channel (HTTPS).

  4. Use ADetailer for automatic face/detail enhancement

    main

    ADetailer can be used in both txt2img and img2img calls by passing an ADetailer object in the adetailer list parameter.

    import webuiapi
    
    # txt2img with ADetailer
    ads = webuiapi.ADetailer(ad_model="face_yolov8n.pt")
    result1 = api.txt2img(prompt="cute squirrel",
                        adetailer=[ads],
                        steps=30)
    
    # img2img with ADetailer
    ads = webuiapi.ADetailer(ad_model="face_yolov8n.pt")
    result1 = api.img2img(
        images=[img], 
        prompt="a cute squirrel", 
        adetailer=[ads],
    )
  5. Use X/Y/Z Plot scripts

    main

    You can run AUTOMATIC1111 scripts like X/Y/Z Plot by passing script_name="X/Y/Z Plot" and a list of arguments to script_args.

    Important Note on Arguments:

    • Boolean values (like draw_legend, include_lone_images, etc.) must be passed as strings ("True" or "False"), not Python Booleans.
    • Axis types (X, Y, Z) are passed as the index of the axis type from the available options list.

    Available Axis Options (txt2img): Nothing, Seed, Var. seed, Var. strength, Steps, Hires steps, CFG Scale, Prompt S/R, Prompt order, Sampler, Checkpoint name, Sigma Churn, Sigma min, Sigma max, Sigma noise, Eta, Clip skip, Denoising, Hires upscaler, VAE, Styles.

    Available Axis Options (img2img): Nothing, Seed, Var. seed, Var. strength, Steps, CFG Scale, Image CFG Scale, Prompt S/R, Prompt order, Sampler, Checkpoint name, Sigma Churn, Sigma min, Sigma max, Sigma noise, Eta, Clip skip, Denoising, Cond. Image Mask Weight, VAE, Styles.

    XAxisType = "Steps"
    XAxisValues = "20,30"
    XAxisValuesDropdown = ""
    YAxisType = "Sampler"
    YAxisValues = "Euler a, LMS"
    YAxisValuesDropdown = ""
    ZAxisType = "Nothing"
    ZAxisValues = ""
    ZAxisValuesDropdown = ""
    drawLegend = "True"
    includeLoneImages = "False"
    includeSubGrids = "False"
    noFixedSeeds = "False"
    marginSize = 0
    
    result = api.txt2img(
                        prompt="cute girl with short brown hair in black t-shirt in animation style",
                        seed=1003,
                        script_name="X/Y/Z Plot",
                        script_args=[
                            XYZPlotAvailableTxt2ImgScripts.index(XAxisType),
                            XAxisValues,
                            XAxisValuesDropdown,
                            XYZPlotAvailableTxt2ImgScripts.index(YAxisType),
                            YAxisValues,
                            YAxisValuesDropdown,
                            XYZPlotAvailableTxt2ImgScripts.index(ZAxisType),
                            ZAxisValues,
                            ZAxisValuesDropdown,
                            drawLegend,
                            includeLoneImages,
                            includeSubGrids,
                            noFixedSeeds,
                            marginSize,
                            ]
                        )
  6. Perform txt2img generation

    main

    Use the txt2img method to generate images from text prompts. You can specify parameters such as prompt, negative_prompt, seed, styles, cfg_scale, steps, enable_hr, denoising_strength, sampler_name, and scheduler. The result object contains an image attribute which is a PIL Image object.

    import webuiapi
    
    result1 = api.txt2img(prompt="cute squirrel",
                        negative_prompt="ugly, out of frame",
                        seed=-1,
                        styles=["anime"],
                        cfg_scale=1,
                        steps=20,
                        enable_hr=False,
                        denoising_strength=0.5,
                        sampler_name= "Euler",
                        scheduler= "Simple"
                )
                        
    img = result1.image
    img
    
    # OR
    
    file_path = "output_image.png"
    result1.image.save(file_path)
  7. Configure WebUI options and models

    main

    Use the following methods to manage the WebUI configuration and models:

    • get_options(): Returns a map of current options.
    • set_options(options): Updates options. Warning: Do not pass the entire dictionary returned by get_options(); only pass the keys you wish to change to avoid making the WebUI unusable.
    • get_sd_models(): Retrieves available Stable Diffusion models.
    • get_samplers(), get_schedulers(), get_embeddings(), get_scripts(): Retrieve various WebUI assets.
    • interrupt(): Interrupts the current process.
    • skip(): Skips the current process.
    # change sd model
    options = {}
    options['sd_model_checkpoint'] = 'model.ckpt [7460a6fa]'
    api.set_options(options)
    
    # get available sd models
    api.get_sd_models()
  8. Enable Async API support

    main

    Methods like txt2img, img2img, extra_single_image, and extra_batch_images support asynchronous calls. To use this, set use_async=True and ensure you have asyncio and aiohttp installed in your environment.

    result = await api.txt2img(prompt="cute kitten",
                        seed=1001,
                        use_async=True
                        )
    result.image
  9. Use Utility methods for model management

    main

    The util_ prefixed methods provide helper functions for common tasks:

    • util_get_current_model(): Returns the name of the currently loaded model.
    • util_get_model_names(): Returns a list of available model names.
    • util_set_model(name): Sets the model using the exact name or the closest match.
    • refresh_checkpoints(): Refreshes the list of available checkpoints.
    • util_wait_for_ready(): Blocks until the WebUI is ready for a new job.
    # get list of available models
    models = api.util_get_model_names()
    
    # set model (find closest match)
    api.util_set_model('robodiffusion')
    
    # wait for job complete
    api.util_wait_for_ready()
  10. Perform img2img inpainting

    main

    To perform inpainting, use the img2img method and provide a mask_image (a PIL Image) along with the inpainting_fill parameter.

    from PIL import Image, ImageDraw
    
    # Create a mask
    mask = Image.new('RGB', result2.image.size, color='black')
    draw = ImageDraw.Draw(mask)
    draw.ellipse((210, 150, 310, 250), fill='white')
    
    # Run inpainting
    inpainting_result = api.img2img(
        images=[result2.image],
        mask_image=mask,
        inpainting_fill=1,
        prompt="cute cat",
        seed=104,
        cfg_scale=5.0,
        denoising_strength=0.7
    )
    
    image = inpainting_result.image
  11. Perform extra-single-image processing

    main

    The extra_single_image method allows for post-processing a single image, such as upscaling. Use the upscaler_1 parameter with values from webuiapi.Upscaler.

    result3 = api.extra_single_image(
        image=result2.image,
        upscaler_1=webuiapi.Upscaler.ESRGAN_4x,
        upscaling_resize=1.5
    )
    
    image = result3.image