开发者社区> 问答> 正文

如何通过API调用Stable Diffusion文生图模型?

如何通过API调用Stable Diffusion文生图模型?

展开
收起
人一月 2024-08-10 13:25:23 73 0
3 条回答
写回答
取消 提交回答
  • 要通过API调用Stable Diffusion文生图模型,遵循以下步骤:

    1.准备条件

    • 确保已开通DashScope服务并获取API-Key。
    • 安装DashScope SDK(如需编程调用)。

    2.调用API

    • 模型选择:决定使用stable-diffusion-xlstable-diffusion-v1.5版本。
    • 构建请求:发起POST请求至https://dashscope.aliyuncs.com/api/v1/services/aigc/text2image/image-synthesis,设置Header中的Content-Typeapplication/json,并在Authorization中使用Bearer {your-api-key}格式携带API-Key。
    • 请求体参数
    • prompt: 文本描述,指示生成图片的主题。
    • negative_prompt: 负向提示,指明不想在图片中出现的内容。
    • size: 图片尺寸。
    • n: 期望生成的图片数量。

    3.处理响应

    • API响应包含作业ID,需异步查询作业状态。
    • 使用作业ID调用查询接口,监控任务直至完成。
    • 任务完成后,从响应中获取生成的图片。

    注意

    • 保持API-Key安全,避免泄露。
    • 调用为异步模式,需主动检查任务状态获取结果。

    此过程概括了使用API调用Stable Diffusion文生图模型的基本步骤,确保按官方文档指引操作。

    参考链接:https://help.aliyun.com/zh/dashscope/developer-reference/stable-diffusion-apis----

    2024-08-10 19:36:50
    赞同 4 展开评论 打赏
  • demo如下:
    python如下

    from http import HTTPStatus
    from urllib.parse import urlparse, unquote
    from pathlib import PurePosixPath
    import requests
    from dashscope import ImageSynthesis
    import os
    
    model = "stable-diffusion-xl"
    prompt = "Eagle flying freely in the blue sky and white clouds"
    
    # 同步调用
    def sample_block_call():
        rsp = ImageSynthesis.call(model=model,
                                  api_key=os.getenv("DASHSCOPE_API_KEY"),
                                  prompt=prompt,
                                  negative_prompt="garfield",
                                  n=1,
                                  size='1024*1024')
        if rsp.status_code == HTTPStatus.OK:
            print(rsp)
            # 保存图片到当前文件夹
            for result in rsp.output.results:
                file_name = PurePosixPath(unquote(urlparse(result.url).path)).parts[-1]
                with open('./%s' % file_name, 'wb+') as f:
                    f.write(requests.get(result.url).content)
        else:
            print('Failed, status_code: %s, code: %s, message: %s' %
                  (rsp.status_code, rsp.code, rsp.message))
    
    # 异步调用
    def sample_async_call():
        rsp = ImageSynthesis.async_call(model=model,
                                        api_key=os.getenv("DASHSCOPE_API_KEY"),
                                        prompt=prompt,
                                        negative_prompt="garfield",
                                        n=1,
                                        size='512*512')
        if rsp.status_code == HTTPStatus.OK:
            print(rsp)
        else:
            print('Failed, status_code: %s, code: %s, message: %s' %
                  (rsp.status_code, rsp.code, rsp.message))
        status = ImageSynthesis.fetch(rsp)
        if status.status_code == HTTPStatus.OK:
            print(status.output.task_status)
        else:
            print('Failed, status_code: %s, code: %s, message: %s' %
                  (status.status_code, status.code, status.message))
    
        rsp = ImageSynthesis.wait(rsp)
        if rsp.status_code == HTTPStatus.OK:
            print(rsp)
        else:
            print('Failed, status_code: %s, code: %s, message: %s' %
                  (rsp.status_code, rsp.code, rsp.message))
    
    
    if __name__ == '__main__':
        sample_block_call()
        sample_async_call()
    
    // Copyright (c) Alibaba, Inc. and its affiliates.
    // 需要安装okhttp依赖
    
    import java.io.IOException;
    import java.net.URL;
    import java.nio.file.Files;
    import java.nio.file.Path;
    import java.nio.file.Paths;
    import java.util.Map;
    import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesis;
    import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisParam;
    import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisResult;
    import com.alibaba.dashscope.exception.ApiException;
    import com.alibaba.dashscope.exception.NoApiKeyException;
    import com.alibaba.dashscope.utils.JsonUtils;
    import okhttp3.OkHttpClient;
    import okhttp3.Request;
    import okhttp3.Response;
    
    public class Main {
        private static final OkHttpClient CLIENT = new OkHttpClient();
        private static final String MODEL = "stable-diffusion-xl";
        private static final String PROMPT = "Eagle flying freely in the blue sky and white clouds";
        private static final String SIZE = "1024*1024";
    
        public static void basicCall() throws ApiException, NoApiKeyException, IOException {
            ImageSynthesis is = new ImageSynthesis();
            ImageSynthesisParam param =
                    ImageSynthesisParam.builder()
                            .model(Main.MODEL)
                            .n(1)
                            .size(Main.SIZE)
                            .prompt(Main.PROMPT)
                            .negativePrompt("garfield")
                            .build();
    
            ImageSynthesisResult result = is.call(param);
            System.out.println(JsonUtils.toJson(result));
            // save image to local files.
            for(Map<String, String> item :result.getOutput().getResults()){
                String paths = new URL(item.get("url")).getPath();
                String[] parts = paths.split("/");
                String fileName = parts[parts.length-1];
                Request request = new Request.Builder()
                        .url(item.get("url"))
                        .build();
    
                try (Response response = CLIENT.newCall(request).execute()) {
                    if (!response.isSuccessful()) {
                        throw new IOException("Unexpected code " + response);
                    }
                    Path file = Paths.get(fileName);
                    Files.write(file, response.body().bytes());
                }
    
            }
        }
    
        public void fetchTask() throws ApiException, NoApiKeyException {
            String taskId = "your task id";
            ImageSynthesis is = new ImageSynthesis();
            // If set DASHSCOPE_API_KEY environment variable, apiKey can null.
            ImageSynthesisResult result = is.fetch(taskId, null);
            System.out.println(result.getOutput());
            System.out.println(result.getUsage());
        }
    
        public static void main(String[] args){
            try{
                basicCall();
            }catch(ApiException|NoApiKeyException | IOException e){
                System.out.println(e.getMessage());
            }
            System.exit(0);
        }
    }
    

    image.png
    参考链接
    https://help.aliyun.com/zh/model-studio/developer-reference/stable-diffusion-apis

    2024-08-10 15:16:56
    赞同 5 展开评论 打赏
  • 2024-08-10 13:54:09
    赞同 1 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
API 平台的安全实践 立即下载
API 网关实践 立即下载
ACE 区域技术发展峰会:Flink Python Table API入门及实践 立即下载