Text-to-Image

Description

This API processes text-to-image requests in the cloud. See the documentation below for details.

Note: Download and save generated images/videos promptly. The service periodically removes these files. The minimum retention period is 1 hour.

Version

1.0

Changelog

Request URL

Production: https://openapi.meitu.com/whee/business/text2image.json

Signature Verification

Open Platform API Request Signing

HTTP Method

POST

The request headers must include: Content-Type:application/json

Access Requirements

Apply for an AccessKey and a SecretKey before using this API.

Request Parameters

RequiredParameterTypeDescription
RequiredparamsstringText-to-image inference parameters
Requiredtaskstringtxt2img
Requiredtask_typestringinference
Optionaltask_idstringTask ID. Ensure that it is unique within your application.

The params inference parameters are provided as a JSON string with the following structure:

RequiredFieldTypeDescription
RequiredmodelstringModel. Retrieve available models through the API. API documentation
RequiredpromptstringPositive prompt and style model settings. Use (prompt:weight) to control text weights and <lora:model:weight> to configure a style model and its weight. Retrieve available style models through the API. API documentation
Example: girl,(cartoon:1.1),<lora:074594b2d60230282482d176d28c7c2e_1.0:0.8>
Explanation: girl is a regular prompt term; cartoon has a weight of 1.1; the LoRA uses the Poetic Ink Wash style at a strength of 0.8.
OptionalseedintRandom seed. Default: -1. Accepts a positive integer or -1. A positive seed produces images with consistent, related content; -1 introduces random variation.
RequiredwidthintWidth. Default: 768. Retrieve supported dimensions through the API. API documentation
RequiredheightintHeight. Default: 1024. Retrieve supported dimensions through the API. API documentation
Optionalnegative_promptstringNegative prompt
Optionalalwayson_scriptsobjectPlugin configuration
OptionalstepsintSampling steps used to generate an image. Default: 50.
Optionalcfg_scalefloat64Prompt guidance scale, which controls how strongly the input prompt and negative prompt influence the generated result. Range: [1-20], in increments of 0.5. Default: 5.
Optionalbatch_sizeintNumber of images to generate. Defaults to 4 if omitted. Allowed range: 1 to 4.
Optionaladetailer_faceintFace restoration plugin: 1 enables it; 2 disables it. Enabled by default.
Optionalcontrolnet_unitsobject[]Image control plugin for guiding image generation. Omit if not needed.

The controlnet_units image control parameters have the following structure:

RequiredParameterTypeDescription
Requiredinput_imagestringImage URL. Has no effect if omitted or empty.
OptionalmodulestringPreprocessor. Retrieve available preprocessors through the API. Defaults to the first preprocessor in the returned list. API documentation
Optionalweightfloat64Weight applied to image control during generation. Higher values produce a stronger effect. Range: 0-1. Recommended range: 0.4-0.6.
Optionalguidance_startfloat64Guidance start point. Higher values introduce image control guidance later, reducing its effect. Range: 0-1. Recommended range: 0-0.1.
Optionalguidance_endfloat64Guidance end point. Higher values keep image control guidance active longer, increasing its effect. Range: 0-1. Recommended range: 0.5-0.7.

alwayson_scripts Plugin Parameters

ADetailer Plugin (Face Restoration)

"alwayson_scripts": {
      "ADetailer": {
        "args": [
          true,
          {
            "ad_cfg_scale": 6,
            "ad_confidence": 0.3,
            "ad_denoising_strength": 0.3,
            "ad_dilate_erode": 4,
            "ad_enable_face_generation": true,
            "ad_inpaint_height": -1,
            "ad_inpaint_width": -1,
            "ad_mask_blur": 4,
            "ad_mask_max_ratio": 0.15,
            "ad_mask_min_ratio": 0,
            "ad_model": "face_yolov8m.pt",
            "ad_negative_prompt": "",
            "ad_prompt": "",
            "ad_steps": 30
          }
        ]
      }
	}
RequiredParameterTypeDescription
RequiredargsarrayPlugin parameters

args Parameters

RequiredParameterTypeDescription
RequiredFirst array elementboolWhether to enable the plugin
OptionalSecond array element: configobjectPlugin configuration parameters

config Parameters

RequiredParameterTypeDescription
Optionalad_dilate_erodeintExpands the detected detail region when positive, or shrinks it when negative. Default: 4.
Optionalad_confidencefloatConfidence threshold for detecting details such as faces and hands. Default: 0.3.
Optionalad_cfg_scaleintControls how closely the restored image follows the prompt. Range: 0-10.
Optionalad_denoising_strengthdoubleRange: 0-1. Controls how much the restored image differs from the original. Higher values produce greater changes.
Optionalad_enable_face_generationbooltrue or false. Controls whether to use face guidance.
Optionalad_inpaint_heightintDefault: -1. Controls the width of the image input to the generation model. Defaults to the original image width.
Optionalad_inpaint_widthintDefault: -1. Controls the height of the image input to the generation model. Defaults to the original image height.
Optionalad_mask_blurintRange: 0-64. Softens sharp edges when blending the restored image with the original. Lower values make the blending edges more visible. Default: 4.
Optionalad_mask_max_ratiofloat1.0. Minimum area for detected details.
Optionalad_mask_min_ratiofloat0.0. Maximum area for detected details.
Optionalad_modelstringFace restoration model. Currently, only "face_yolov8m.pt" is supported.
Optionalad_negative_promptstringNegative prompt for face restoration
Optionalad_promptstringPrompt for face restoration
Optionalad_stepsintNumber of face restoration iterations. Higher values increase restoration strength but slow down processing. Default: 30.
{
            "ad_cfg_scale": 6,

            "ad_denoising_strength": 0.3,
            "ad_enable_face_generation": true,
            "ad_inpaint_height": -1,
            "ad_inpaint_width": -1,
            "ad_mask_blur": 4,
            "ad_mask_max_ratio": 0.15,
            "ad_mask_min_ratio": 0,
            "ad_model": "face_yolov8m.pt",
            "ad_negative_prompt": "",
            "ad_prompt": "",
            "ad_steps": 30
          }

Request Body Example

{
	"params": "{\"model\":\"miracle-vision_v3.1-realistic1.zip\",\"prompt\":\"girl,(cartoon:1.1),<lora:074594b2d60230282482d176d28c7c2e_1.0:0.8>\",\"seed\":-1,\"width\":768,\"height\":1024,\"negative_prompt\":\"Malformed Limbs\"}",
	"task": "txt2img",
	"task_type": "inference"
}

Response Fields

Successful Response Fields

FieldTypeDescription
dataObjectResponse data
messageStringError message
codeNumberError code

Fields of an individual element in data:

FieldTypeDescription
statusNumberTask status: -1 = task not found; 0 = task created successfully; 1 = task in progress; 2 = task failed; 9 = task status must be queried through the status API; 10 = task succeeded. When status is 9, use the Status API to query the task status.
msgStringDescription of the media file properties
resultObjectResult
progressNumberTask progress, for example: 0.1, 0.85, or 1.

Fields of an individual element in result:

FieldTypeDescription
idStringTask ID
urlsString[]URLs of the resulting images

Failed Response Fields

FieldTypeDescription
dataStringResponse data
messageStringError message
codeIntError code

Response Examples

Successful Response Example

Response Status: 200

content-type: application/json; charset=utf-8

{
	"code": 0,
	"message":"",
	"data": {
		"status": 10,
		"result": {
			"id": "50309bd5-a827-4125-bc96-62039c93770b",
			"urls": ["https://obs.mtlab.meitu.com/mtopen/rF5GIhp5ReLKgLV91CKj5BO1q2FTLMmc/MTY5Mjg1MzIwMA==/1c39ef92-04f1-40b4-5b7e-8fcfca0c11ea.png"]
		},
		"progress": 1
	}
}

Failed Response Example

Response Status: 400

content-type: application/json; charset=utf-8

{
	"code": 20008, 
	"message": "UNSUITABLE_IMAGE", 
	"data": null
}

API-Specific Error Codes and Messages

ErrorCodeError messageDescription
20001PROCESS_ERRORProcessing error
21007JSON_ERRORInvalid JSON content

Common Error Codes and Messages

See API Error Codes.

Request Example

curl -vX POST "https://openapi.meitu.com/whee/business/text2image.json" -d @p.json --header "Content-Type: application/json" --header 'Authorization:Bearer YourSignAuthCode' --header 'X-SDK-Date:20230824T102323Z'

Code Examples

Go

package main

import (
	"fmt"
	"io"
	"net/http"

	"github.com/mtlab/api/signer"
)

func main() {
	key := "your api_key"
	secret := "your api_secret"
	sign := signer.NewSigner(key, secret)

	url := "https://openapi.meitu.com/whee/business/text2image.json"
	method := "POST"
	headers := make(http.Header)
	headers.Set(signer.HeaderHost, "openapi.meitu.com")
	headers.Set("Content-Type", "application/json")

	body:=`{
	"params": "{\"model\":\"miracle-vision_v3.1-realistic1.zip\",\"prompt\":\"girl,(cartoon:1.1),<lora:074594b2d60230282482d176d28c7c2e_1.0:0.8>\",\"seed\":-1,\"width\":768,\"height\":1024,\"negative_prompt\":\"Malformed Limbs\"}",
	"task": "txt2img",
	"task_type": "inference"
}`
	req, err := sign.Sign(url, method, headers, body)

	if err != nil {
		fmt.Println("Failed to sign request:", err)
		return
	}

	// Use the signed request to make the actual HTTP request
	client := http.DefaultClient
	resp, err := client.Do(req)
	if err != nil {
		fmt.Println("Failed to send request:", err)
		return
	}
	defer resp.Body.Close()
	body1, err1 := io.ReadAll(resp.Body)
	if err1 != nil {
		fmt.Println("Failed to read response:", err1)
		return
	}
	fmt.Println("GetResponse=>",resp.StatusCode,string(body1),resp)

}

PHP

<html>
<head>
    <title>PHP test</title>
</head>
<body>
<pre>
    <?php
    require 'signer.php';
    
    $signer = new Signer("your api key","your api secret");

$url = 'https://openapi.meitu.com/whee/business/text2image.json';
$method = 'POST';
$headers = [
    'Content-Type' => 'application/json'
];
$body = '{
	"params": "{\"model\":\"miracle-vision_v3.1-realistic1.zip\",\"prompt\":\"girl,(cartoon:1.1),<lora:074594b2d60230282482d176d28c7c2e_1.0:0.8>\",\"seed\":-1,\"width\":768,\"height\":1024,\"negative_prompt\":\"Malformed Limbs\"}",
	"task": "txt2img",
	"task_type": "inference"
}';

$curl = $signer->sign($url, $method, $headers, $body);

$response = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ($status == 0) {
    echo curl_error($curl);
} else {
    echo $status . "\n";
    echo $response;
}
curl_close($curl);

    ?>
</pre>
</body>
</html>

Python

import json
import requests
from sign_sdk import sign

key = "your api key"
secret = "your api secret"
url = "https://openapi.meitu.com/whee/business/text2image.json"
method = "POST"
headers = {
    "Content-Type": "application/json",
    sign.HeaderHost: "openapi.meitu.com",
}
body = json.dumps({"params": "{\"model\": \"miracle-vision_v3.1-realistic1.zip\", \"prompt\": \"\\u5973\\u5b69\\uff0c\\u53ef\\u7231\\uff0c\\u6d01\\u767d\\u7684\\u76ae\\u80a4\\uff0c\\u4f4e\\u80f8,\\u9501\\u9aa8\\uff0c<lora:7aa93dca8909a4f27ac4282c60b7b264_1.0:0.8>\", \"width\": 512, \"height\": 1024, \"negative_prompt\": \"EasyNegative\"}", "task": "txt2img", "task_type": "inference"})

signer = sign.Signer(key, secret)

signed_request = signer.sign(url, method, headers, body)
session = requests.Session()
response = session.send(signed_request,verify=False)

print(response.status_code)
print(response.text)

def fetchResult(taskId,item):
    url = f"https://openapi.meitu.com/api/v1/sdk/status?task_id={taskId}"
    key = "your api key"
    secret = "your api secret"
    method = "GET"
    headers = {
        "Content-Type": "application/json",
        sign.HeaderHost: "openapi.meitu.com"
    }

    body = ""
    try:
        signer = sign.Signer(key, secret)

        signed_request = signer.sign(url,method,headers,body)
        session = requests.Session()
        response = session.send(signed_request,verify=False)

        print(response.status_code)
        print(response.text)

    except Exception as ex:
        print(ex)

fetchResult("mtlab-f3db4716-ed68-4f36-9eb6-a06b558aabec",None)