Stable diffusion webui Wensheng map (txt2img) api interface call (using C#)

Nag

This time, I will tell readers how to request the sd webui api [txt2img] interface through C#. If readers find the article useful, please give [like] it. If you have any questions, you can ask in the comment area.

combat

1. Configure api enable parameters

When starting the webui, you need to add the [–api] command to ensure that the api interface can be called. If you need to set a password, you can use [–api-auth account: password] and [–gradio-auth account: password] to enable it. Turn it on as shown in the figure below.
Note: It is invalid to only set the password of –api-auth here. The login interface is used for ui page login. The original code does not have the api-auth interface to return the token. (Please correct me if I am wrong)
insert image description here

2. Run locally

You can see the swagger document by visiting http://127.0.0.1:7860/docs , but sometimes, you will find that you cannot access it and report a timeout error.
The reason is that there are js files in the swagger interface that refer to cdn. If you surf the Internet scientifically, you can definitely access it. If you don’t surf the Internet scientifically, sometimes it can and sometimes it can’t!
insert image description here
insert image description here

3. Code combat

3.1 Request/Response Class

Create a C# project, here I use the console, it can also be webapi, mvc, etc. As follows, create two dto classes

/// <summary>
    ///  Txt2Img 文生图 请求实体类
    /// </summary>
    public partial class Text2ImgRequestDto
    {
    
    

        /// <summary>
        /// 高度(不适用这个去设置,容易导致图片生成重复的内容,因sd的模型,一般都是基于512去训练的)
        /// </summary>
        public long? height {
    
     get; set; } = 512;

        /// <summary>
        /// 宽度(不适用这个去设置,容易导致图片生成重复的内容,因sd的模型,一般都是基于512去训练的)
        /// </summary>
        public long? width {
    
     get; set; } = 512;

        /// <summary>
        /// 反向提示词
        /// </summary>
        public string? negative_prompt {
    
     get; set; }
        /// <summary>
        /// 正向提示词
        /// </summary>
        public string prompt {
    
     get; set; }

        /// <summary>
        /// 面部修复(画人像的时候可以考虑使用)
        /// </summary>
        public bool? restore_faces {
    
     get; set; } = false;

        /// <summary>
        /// 总批次数
        /// </summary>  
        public long? n_iter {
    
     get; set; } = 1;
        /// <summary>
        /// 单批数量(每次生成的图片数量)
        /// </summary>
        public long? batch_size {
    
     get; set; } = 4;
        /// <summary>
        /// Sampler 采样方法,默认Euler
        /// </summary>
        public string sampler_index {
    
     get; set; } = "Euler a";
        /// <summary>
        /// 随机种子数,默认为-1
        /// </summary>
        public long? seed {
    
     get; set; } = -1;
        /// <summary>
        /// 生成步数,默认20
        /// </summary>
        public long? steps {
    
     get; set; } = 20;

        
        /// <summary>
        /// 平铺
        /// </summary>
        public bool? tiling {
    
     get; set; } = false;

        /// <summary>
        /// 设置模型(不设置会自动有默认的模型)
        /// </summary>
        //public Dictionary<string, object> override_settings { get; set; }  = new Dictionary<string, object>() { { "sd_model_checkpoint", "deliberate_v2.ckpt" } };

        / <summary>
        / Hr Resize X
        / </summary>
        //public long? hr_resize_x { get; set; }

        / <summary>
        / Hr Resize Y
        / </summary>
        //public long? hr_resize_y { get; set; }

        / <summary>
        / 放大倍数
        / </summary>
        //public string hr_upscaler { get; set; }


        /// <summary>
        /// 关键词相关性
        /// </summary>
        public double? cfg_scale {
    
     get; set; } = 7;



    }
/// <summary>
    /// 文生图 响应体类
    /// </summary>
    public class Text2ImgResponseDto
    {
    
    
        /// <summary>
        /// 生成的图片数组
        /// </summary>
        public List<string> images = new List<string>();

        /// <summary>
        /// request请求中的body
        /// </summary>
        public Text2ImgRequestDto parameters = new Text2ImgRequestDto();

        /// <summary>
        /// 返回的图片数组生成参数信息
        /// </summary>
        public string? info {
    
     get; set; }
    }

3.2 Request sd api interface

1. In the console program, [RestSharp] and [Newtonsoft.Json] nuget packages need to be installed, one is used for api requests, and the other is used for serialization of json.
insert image description here
2. Add the following code to your project, just run it directly, the request is the interface running locally, the following [http://127.0.0.1:7860/sdapi/v1/txt2img] needs to be replaced by the reader's own path.
3. Set the request header: If the reader has set up the api interface access locally and needs to log in, you need to add [Authorization] to the header and set the token.
4. Set the request body: a [Text2ImgRequestDto] object needs to be created, and the attribute value of [prompt (prompt word)] needs to be assigned to ensure the normal call of the sd interface.

using ConsoleApp1;
using Newtonsoft.Json;
using RestSharp;
using System.Threading.Channels;

//使用restclient进行请求
var client = new RestClient("http://127.0.0.1:7860/sdapi/v1/txt2img");
var request = new RestRequest();

//添加i请求头
request.AddHeader("Content-Type", "application/json");
//request.AddHeader("Authorization", "Basic xxxxxx");  //如果启动时加了--api-auth,则需要加上token,否则会返回
request.AddHeader("Accept", "*/*");
request.AddHeader("Connection", "keep-alive");

//构造请求体内容,param中的参数,可以看【Text2ImgRequestDto】中的解析
var param = new Text2ImgRequestDto();
param.prompt = "a hat cat";//提示词
request.AddParameter("application/json", param, ParameterType.RequestBody);
RestResponse response = client.Post(request);
var result = JsonConvert.DeserializeObject<Text2ImgResponseDto>(response.Content);
Console.WriteLine("执行完!");

5. Execute the request: Execute the Post method of RestClient to make the request.
6. JSON serialization: Use [JsonConvert.DeserializeObject] of [Newtonsoft.Json] to convert the request result into an entity class, as shown in the figure below: (1)
images: It is the base64 image array returned to us by the interface, because [Text2ImgRequestDto] is set [4 pictures] are generated by default, so the length of the array here is [4].
(2) parameters: the body in the request request.
(3) info: The returned image array generates parameter information
insert image description here

3.4 Renderings

Copy the base64 value of one of the pictures in the images array, and find an online tool for converting base64 to pictures on the Internet. After pasting, you can see the generated picture as follows, which means that we have successfully requested the sd webui api interface through the interface.
insert image description here

Request failed with status code Unauthorized

If the "Request failed with status code Unauthorized" error is reported when calling the interface, at this time, you need to check whether the "–api-auth" parameter has been added? If so, you need to request the token and add it to the request token. You can refer to my article to request token.
insert image description here
If there is still a permission exception, you can use the following method to pass the account secret to call
insert image description here

Guess you like

Origin blog.csdn.net/qq_40600379/article/details/131147196