【大模型部署】在C# Winform中使用文生图Stable Diffusion XL 模型
前言
整了一个在C# Winform中调用文生图Stable Diffusion XL的小程序,基于百度智能云千帆平台
步骤
- 如何注册百度智能云和创建应用,获取API 密钥等和在之前的博客中基本相同,不再赘述了
【大模型部署】在C# Winform中使用文心一言ERNIE-3.5 4K 聊天模型 - 代码接入
步骤1-注册百度智能云
https://console.bce.baidu.com/qianfan/ais/console/applicationConsole/application
按提示注册即可
代码接入
定义AK和SK
// 您的AccessKey ID
const string API_KEY = "qSXXXXXXXXXXXXXXXXQ";
// 您的AccessKey Secret
const string SECRET_KEY = "Kb8XXXXXXXXXXXXXXXXXX24ZH";
定义发送和回传的数据结构
public class ImageGenerationRequest
{
public string Prompt { get; set; }
public string Size { get; set; }
public int N { get; set; }
public int Steps { get; set; }
public string SamplerIndex { get; set; }
}
ImageGenerationRequest imageGenerationRequest = new ImageGenerationRequest();
public class ImageData
{
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("object")]
public string Object { get; set; }
[JsonProperty("created")]
public long Created { get; set; }
[JsonProperty("data")]
public ImageDataDetail[] Data { get; set; }
[JsonProperty("usage")]
public Usage Usage { get; set; }
}
// 嵌套的Image数据类
public class ImageDataDetail
{
[JsonProperty("object")]
public string Object { get; set; }
[JsonProperty("b64_image")]
public string B64Image { get; set; } // 这里假设Base64字符串可能很长,因此使用string类型
[JsonProperty("index")]
public int Index { get; set; }
}
// 使用类
public class Usage
{
[JsonProperty("prompt_tokens")]
public int PromptTokens { get; set; }
[JsonProperty("total_tokens")]
public int TotalTokens { get; set; }
}
定义生成函数
private ImageData Generate(ImageGenerationRequest generationRequest)
{
var client = new RestClient($"https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/text2image/sd_xl?access_token={GetAccessTokenMethod()}");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/json");
request.AddHeader("Accept", "application/json");
var body = JsonConvert.SerializeObject(generationRequest, Formatting.None);
//var body = @"{""prompt"":""棕色小熊"",""size"":""768x768"",""n"":1,""steps"":20,""sampler_index"":""Euler a""}";
request.AddParameter("application/json", body, ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
ImageData? result = JsonConvert.DeserializeObject<ImageData>(response.Content);
return result;
}
完整代码
完整代码