# API使用示例

注意: 本服务提供的所有API均需要使用appKey和appSecret进行身份验证, 并且需要由您的后端服务发起请求, 目前暂不支持直接由浏览器发起请求.

以图像算法 英雄联盟卡通化 为例

# Python 语言

# 创建任务

import base64
file_link = "可下载文件地址"

key = appKey + ":" + appSecret
Authorization = "Basic " + base64.b64encode(key.encode('utf-8')).decode('utf-8') // 注意: Basic后有一个空格

header = {
    "Content-Type": "application/json",
    "Authorization": Authorization
    }
url = "https://wsai-api.wondershare.cn/v3/pic/asc/batch"
file_arr = []
file_arr.append(file_link)
body = {
    "images": file_arr,
    "emotion": "ori",
    "priority": 1
    }
body = json.dumps(body).encode('utf-8')
resp = requests.post(url=url, data=body, headers=header)
resp = json.loads(resp._content)

return resp["data"]["task_id"]

# 轮询结果

import base64

key = appKey + ":" + appSecret
Authorization = "Basic " + base64.b64encode(key.encode('utf-8')).decode('utf-8') // 注意: Basic后有一个空格

header = {
    "Content-Type": "application/json",
    "Authorization": Authorization
}
    
url = "https://wsai-api.wondershare.cn/v3/pic/asc/result/" + task_id
while (1):
    resp = requests.get(url=url, headers=header)
    resp = json.loads(resp._content)
    if resp["data"]["status"] == 3:
        log_text = "League of Legends success##" + \
            "url:%s,reponse:%s" % (url, resp)
        mylog.info(log_text)
        break
    elif resp["data"]["status"] == 2:
        log_text = "League of Legends process##" + \
            "url:%s,reponse:%s" % (url, resp)
        mylog.info(log_text)
        time.sleep(2)
        continue
    else:
        log_text = "League of Legends fail##" + \
            "url:%s,reponse:%s" % (url, resp)
        mylog.error(log_text)
        break

return resp["data"]["list"][0]["image_result"]

# Go 语言

# 创建任务

package main

import (
    "bytes"
	"encoding/base64"
    "encoding/json"
    "fmt"
    "io/ioutil"
    "log"
    "net/http"
)

type requestData struct {
    Images   []string `json:"images"`
    Emotion  string   `json:"emotion"`
    Priority int      `json:"priority"`
}

type responseData struct {
    Data struct {
        TaskID string `json:"task_id"`
    } `json:"data"`
}

func main() {
    url := "https://wsai-api.wondershare.cn/v3/pic/asc/batch"

    authorization := "Basic " +  base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf(`%s:%s`, appKey, appSecret)))// 注意: Basic后有一个空格

    data := requestData{
        Images:   []string{"file_link"},
        Emotion:  "ori",
        Priority: 1,
    }

    jsonData, err := json.Marshal(data)
    if err != nil {
        log.Fatal("Error marshaling JSON:", err)
    }

    client := &http.Client{}
    req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
    req.Header.Set("Content-Type", "application/json")
    req.Header.Set("Authorization", authorization)

    resp, err := client.Do(req)
    if err != nil {
        log.Fatal("Error making request:", err)
    }
    defer resp.Body.Close()

    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        log.Fatal("Error reading response body:", err)
    }

    var response responseData
    err = json.Unmarshal(body, &response)
    if err != nil {
        log.Fatal("Error unmarshaling JSON response:", err)
    }

    fmt.Println("Task ID:", response.Data.TaskID)
}

# 轮询结果

package main

import (
	"encoding/json"
	"encoding/base64"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"time"
)

type APIResponse struct {
	Data struct {
		Status uint8 `json:"status"`
	} `json:"data"`
}

func pollApi(client *http.Client, url string) (APIResponse, error) {
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		return APIResponse{}, err
	}
    
    authorization := "Basic " +  base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf(`%s:%s`, appKey, appSecret)))// 注意: Basic后有一个空格

	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Authorization", authorization)

	resp, err := client.Do(req)
	if err != nil {
		return APIResponse{}, err
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return APIResponse{}, err
	}

	var result APIResponse
	err = json.Unmarshal(body, &result)
	if err != nil {
		return APIResponse{}, err
	}

	return result, nil
}

func getResult() (APIResponse, error) {
	taskID := "xxxx"
	url := "https://wsai-api.wondershare.cn/v3/pic/asc/result/" + taskID
	client := http.Client{}

	for {
		time.Sleep(5 * time.Second) // 轮询间隔
		res, err := pollApi(&client, url)
		if err != nil {
			log.Println("Error:", err)
			continue
		}

		switch res.Data.Status {
		case 3:
			log.Println("响应成功")
			return res, nil
		case 2:
			log.Println("任务处理中, 继续轮询")
		default:
			log.Println("任务错误")
			return res, nil
		}
	}
}

func main() {
	result, err := getResult()
	if err != nil {
		log.Fatal("Error:", err)
	}

	fmt.Println("任务结果:", result)
}

# JavaScript 语言

# 创建任务

const url = 'https://wsai-api.wondershare.cn/v3/pic/asc/batch';
const data = {
    "images": [file_link],
    "emotion": "ori",
    "priority": 1
};

let authorization = "Basic " +  btoa(`${appkey}:${appSecret}`)// 注意: Basic后有一个空格

fetch(url, {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
        "Authorization": authorization
    },
    body: JSON.stringify(data)
})
    .then(response => response.json())
    .then(json => console.log(json["data"]["task_id"]))
    .catch(error => console.error('Error:', error));

# 轮询结果

let authorization = "Basic " +  btoa(`${appkey}:${appSecret}`)// 注意: Basic后有一个空格
function pollApi(url) {
    return fetch(
        url, {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
                "Authorization": authorization
            },
        }
    )
        .then(response => response.json())
        .catch(error => error);
}


async function getResult () {
    let task_id = "xxxx"
    let url = "https://wsai-api.wondershare.cn/v3/pic/asc/result/" + task_id
    let res = null
    while (true) {
        res = await pollApi(url)
        if (res.data.status === 3) {
            console.log("响应成功");
            break
        } else if (res.data.status === 2) {
            console.log("任务处理中, 继续轮询");
            continue
        } else {
            console.log("任务错误")
            break
        }
    }
    return res
}


最后更新时间: 2/21/2024, 9:24:48 PM