FLUX 快速开始

FLUX文生图模型

说明

支持的领域 / 任务:aigc

FLUX模型是由 Black Forest Labs 开源的高质量文本到图像生成模型,它在多个维度上展现了卓越性能,尤其在文本引导的图像生成、多主体场景构建以及精细的手部细节生成等方面,实现了显著的提升,为文生图领域设定了新的技术标杆。

上线的 FLUX.1 [schnell] 模型作为目前开源最先进的少步模型,不仅超越了同类竞争者,甚至还优于诸如 Midjourney v6.0 和 DALL·E 3 (HD) 等强大的非精馏模型。该模型经过专门微调,以保留预训练阶段的全部输出多样性,相较于当前市场上的最先进开源模型, FLUX.1 [schnell] 显著提升了在视觉质量、指令遵从、尺寸/比例变化、字体处理及输出多样性等方面的可能,为用户带来更为丰富多样的创意图像生成体验。

同时上线的 FLUX.1 [dev] 模型是一款面向非商业应用的开源权重、精炼模型。 FLUX.1 [dev] 在保持了与 FLUX 专业版相近的图像质量和指令遵循能力的同时,具备更高的运行效率。相较于同尺寸的标准模型,它在资源利用上更为高效。

除了为 FLUX 系列的官方模型与基于 FLUX 架构的开源社区模型提供服务化支撑外,我们还针对 FLUX 文生图模型实施了中文 Prompt 的适应性优化。此番调整确保了模型能够深刻理解并精准响应中文指令,进而生成与英文 Prompt 同等质量的图像成果。

快速开始

前提条件

  • 已开通服务并获得API-KEY:获取API-KEY

  • 我们推荐您将API-KEY配置到环境变量中以降低API-KEY的泄漏风险,详情可参考配置API-KEY到环境变量。您也可以在代码中配置API-KEY,但是泄漏风险会提高。

  • 已安装SDK:安装SDK

示例代码

以下示例展示了调用 flux-schnell 模型API进行文生图的快速示例代码。以下示例展示了调用 flux-schnell 模型API进行文生图的快速示例代码。如果要调用 flux-dev 模型,只需要修改 model 为 "flux-dev" 即可。

from http import HTTPStatus
from urllib.parse import urlparse, unquote
from pathlib import PurePosixPath
import requests
import dashscope

model = "flux-schnell"
prompt = "Eagle flying freely in the blue sky and white clouds"
prompt_cn = "一只飞翔在蓝天白云的鹰"  # Prompt支持中英文


def simple_call(input_prompt):
    rsp = dashscope.ImageSynthesis.call(model=model,
                                        prompt=input_prompt,
                                        size='1024*1024')
    if rsp.status_code == HTTPStatus.OK:
        print(rsp.output)
        print(rsp.usage)
        # save file to current directory
        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))


if __name__ == '__main__':
    simple_call(prompt)
    simple_call(prompt_cn)
// Copyright (c) Alibaba, Inc. and its affiliates.

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 okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class Main {
  private static final OkHttpClient CLIENT = new OkHttpClient();
  private static final String MODEL = "flux-schnell";
  private static final String PROMPT = "Eagle flying freely in the blue sky and white clouds";
  private static final String PROMPT_CN = "一只飞翔在蓝天白云的鹰";
  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(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);
  }
}

调用成功后,将会返回如下示例结果。

{
    "status_code": 200,
    "request_id": "ea8bfe77-2f35-9df3-ba47-7e05e917b3df",
    "code": null,
    "message": "",
    "output": {
        "task_id": "dea97660-9651-4e6b-a9c3-8afb325b28d0",
        "task_status": "SUCCEEDED",
        "results": [
            {
                "url": "url1"
            }
        ],
        "task_metrics": {
            "TOTAL": 1,
            "SUCCEEDED": 1,
            "FAILED": 0
        }
    },
    "usage": {
        "image_count": 1
    }
}

了解更多

有关 FLUX 文生图模型API的详细调用文档可前往API详情页面进行了解。