Notice
- The URL of the result image is valid for 1 hour. Please download the image file promptly.
Supported Images
Format | Resolution | File size |
---|---|---|
jpg, jpeg, bmp, png, webp, tiff, tif, bitmap, raw, rgb, jfif, lzw | Up to 4096 x 4096 | Up to 15MB |
Get Started
See differences between the 3 API call types
API Call Types | Request | Return | Pros & Cons |
---|---|---|---|
Asynchronous | After sending a request, users do not have to wait for an immediate response from the server. The user can obtain the result via Polling. | Return the result by Polling. | Pros: High success rate when concurrency is high; high processing success rate when network transmission is slow or unstable. Cons: One more interface call compared to synchronous option. |
Synchronous | Send a request and wait to obtain real-time updates from the server. | Immediately return the result. | Pros: Easy to integrate. Cons: Lower success rate when concurrency is high or network transmission is slow or unstable as compared to asynchronous option. |
Callback | After sending a request, users do not have to wait for an immediate response from the server. When the task is completed, the server will send a callback notification. | After setting the callback URL, the server sends a notification back to the user. | Pros: Highest processing success rate. Cons: The user requires a server and corresponding back-end resources. |
Asynchronous API Call Sequence Diagram
Synchronous API Call Sequence Diagram
Callback Notification Sequence Diagram
#Create a task.
curl -k 'https://techsz.aoscdn.com/api/tasks/visual/segmentation' \
-H 'X-API-KEY: YOUR_API_KEY' \
-F 'sync=0' \
-F 'image_url=YOU_IMG_URL'
#Get the cutout result
#Polling requests using the following methods 1. The polling interval is set to 1 second, 2. The polling time does not exceed 30 seconds
curl -k 'https://techsz.aoscdn.com/api/tasks/visual/segmentation/{task_id}' \
-H 'X-API-KEY: YOUR_API_KEY' \
<?php
//Create a task
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'https://techsz.aoscdn.com/api/tasks/visual/segmentation');
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
"X-API-KEY: YOUR_API_KEY",
"Content-Type: multipart/form-data",
));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_POSTFIELDS, array('sync' => 0, 'image_url' => "YOUR_IMG_URL"));
$response = curl_exec($curl);
$result = curl_errno($curl) ? curl_error($curl) : $response;
curl_close($curl);
$result = json_decode($result, true);
if ( !isset($result["status"]) || $result["status"] != 200 ) {
// request failed, log the details
var_dump($result);
die("post request failed");
}
// var_dump($result);
$task_id = $result["data"]["task_id"];
//get the task result
// 1、"The polling interval is set to 1 second."
//2 "The polling time is around 30 seconds."
for ($i = 1; $i <= 30; $i++) {
if ($i != 1) {
sleep(1);
}
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "https://techsz.aoscdn.com/api/tasks/visual/segmentation/".$task_id);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
"X-API-KEY: YOUR_API_KEY",
));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($curl);
$result = curl_errno($curl) ? curl_error($curl) : $response;
curl_close($curl);
var_dump($result);
$result = json_decode($result, true);
if ( !isset($result["status"]) || $result["status"] != 200 ) {
// Task exception, logging the error.
//You can choose to continue the loop with 'continue' or break the loop with 'break'
var_dump($result);
continue;
}
if ( $result["data"]["state"] == 1 ) {
// task success
var_dump($result["data"]["image"]);
break;
} else if ( $result["data"]["state"] < 0) {
// request failed, log the details
var_dump($result);
break;
} else {
// Task processing
if ($i == 30) {
//Task processing, abnormal situation, seeking assistance from customer service of picwish
}
}
}
public static void main(String[] args) throws Exception {
String taskId = createTask();
String dataString = pollingTaskResult(taskId, 0);
System.out.println(dataString);
}
private static String createTask() throws Exception {
OkHttpClient okHttpClient = new OkHttpClient.Builder().build();
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("image_url", "IMAGE_HTTP_URL")
.addFormDataPart("sync", "0")
.build();
Request request = new Request.Builder()
.url("https://techsz.aoscdn.com/api/tasks/visual/segmentation")
.addHeader("X-API-KEY", "YOUR_API_KEY")
.post(requestBody)
.build();
Response response = okHttpClient.newCall(request).execute();
JSONObject jsonObject = new JSONObject(response.body().string());
int status = jsonObject.optInt("status");
if (status != 200) {
throw new Exception(jsonObject.optString("message"));
}
return jsonObject.getJSONObject("data").optString("task_id");
}
private static String pollingTaskResult(String taskId, int pollingTime) throws Exception {
if (pollingTime >= 30) throw new IllegalStateException("Polling result timeout.");
OkHttpClient okHttpClient = new OkHttpClient.Builder().build();
Request taskRequest = new Request.Builder()
.url("https://techsz.aoscdn.com/api/tasks/visual/segmentation/" + taskId)
.addHeader("X-API-KEY", "YOUR_API_KEY")
.get()
.build();
Response taskResponse = okHttpClient.newCall(taskRequest).execute();
JSONObject jsonObject = new JSONObject(taskResponse.body().string());
int state = jsonObject.getJSONObject("data").optInt("state");
if (state < 0) { // Cutout error.
throw new Exception(jsonObject.optString("message"));
}
if (state == 1) { // Cutout success and get result.
return jsonObject.getJSONObject("data").toString();
}
Thread.sleep(1000);
return pollingTaskResult(taskId, ++pollingTime);
}
const request = require("request");
const fs = require("fs");
const path = require('path')
const API_KEY = "YOUR_API_KEY";
(async function main() {
const taskId = await createTask()
const result = await polling(() => getTaskResult(taskId))
console.log(`result: ${JSON.stringify(result, null, 2)}`)
})()
const polling = async (fn, delay = 1 * 1000, timeout = 30 * 1000) => {
if (!fn) {
throw new Error('fn is required')
}
try {
const result = await fn()
return result
} catch (error) {
if (error && 'data' in error) {
throw new Error(JSON.stringify(error, null, 2))
}
if (timeout <= 0) {
throw new Error('timeout')
}
await new Promise((resolve) => {
setTimeout(() => {
resolve()
}, delay)
})
return polling(fn, delay, timeout - delay)
}
}
function createTask() {
return new Promise((resolve, reject) => {
request(
{
method: "POST",
url: "https://techsz.aoscdn.com/api/tasks/visual/segmentation",
headers: {
"X-API-KEY": API_KEY,
},
formData: {
image_url: 'IMAGE_HTTP_URL',
},
json: true
},
function (error, response) {
if (response.body.data) {
resolve(response.body.data.task_id)
} else {
reject(response.body)
}
}
);
})
}
function getTaskResult(taskId) {
return new Promise((resolve, reject) => {
request(
{
method: "GET",
url: `https://techsz.aoscdn.com/api/tasks/visual/segmentation/${taskId}`,
headers: {
"X-API-KEY": API_KEY,
},
json: true
},
function (error, response) {
if (!response.body.data) reject(response.body)
const { progress, state } = response.body.data
if (state < 0) reject(response.body)
if (progress >= 100) resolve(response.body)
reject(null)
}
);
})
}
import time
import requests
API_KEY = 'YOUR_API_KEY'
IMAGE_NETWORK_URL = 'YOUR_IMAGE_NETWORK_URL'
def create_task():
headers = {'X-API-KEY': API_KEY}
data = {'sync': '0', 'image_url': IMAGE_NETWORK_URL}
url = 'https://techsz.aoscdn.com/api/tasks/visual/segmentation'
# Create a task
response = requests.post(url, headers=headers, data=data)
task_id = None
response_json = response.json()
if 'status' in response_json and response_json['status'] == 200:
result_tag = 'failed'
if 'data' in response_json:
response_json_data = response_json['data']
if 'task_id' in response_json_data:
result_tag = 'successful'
task_id = response_json_data['task_id']
print(f'Result of created task({result_tag}): {response_json}')
else:
# request failed, log the details
print(f'Error: Failed to create task,{response.text}')
return task_id
# get the task result
# 1、"The polling interval is set to 1 second."
# 2、"The polling time is around 30 seconds."
def polling_task_result(task_id,time_out=30):
headers = {'X-API-KEY': API_KEY}
url = f'https://techsz.aoscdn.com/api/tasks/visual/segmentation/{task_id}'
for i in range(time_out):
if i != 0:
time.sleep(1)
response = requests.get(url, headers=headers)
response_json = response.json()
if 'status' in response_json and response_json['status'] == 200:
if 'data' in response_json:
response_json_data = response_json['data']
if 'state' in response_json_data:
task_state = response_json_data['state']
if task_state == 1:
# task success
print(f'Result(successful): {response_json}')
break
elif task_state < 0:
# Task exception, logging the error.
# You can choose to continue the loop with 'continue' or break the loop with 'break'
print(f'Result(failed): {response_json}')
break
print(f'Result(polling): {response_json}')
if i == time_out-1:
# Timeout, log the details, and search for support from the picwish service.
print('Error: Timeout while polling.')
else:
# Task exception, logging the error.
# You can choose to continue the loop with 'continue' or break the loop with 'break'
print(f'Error: Failed to get the task\'s result,{response.text}')
break
def main():
task_id = create_task()
if task_id is None:
print('Error: Failed to create task,task id is None.')
return
polling_task_result(task_id)
if __name__ == "__main__":
main()
using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
class Program
{
public static HttpClient client = new HttpClient();
private static string API_KEY = "YOUR_API_KEY";
private static string url = "https://techsz.aoscdn.com/api/tasks/visual/segmentation";
private static string imageUrl = "IMAGE_HTTP_URL";
static async Task Main(string[] args)
{
try
{
//Create a task.
var taskId = await CreateTask();
//Retrieve the results by looping thirty times.
var result = await Polling(() => GetTaskResult(taskId), TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(30));
Console.WriteLine($"result: {result.ToString()}");
}
catch (Exception ex)
{
//Request from user server failed. Please record the relevant error logs.
Console.WriteLine(ex.Message);
}
Console.ReadKey();
}
static async Task<string> CreateTask()
{
var requestUrl = url;
var multipartContent = new MultipartFormDataContent();
multipartContent.Add(new StringContent(imageUrl), "image_url");
client.DefaultRequestHeaders.Add("X-API-KEY", API_KEY);
//User server initiates a request.
var response = await client.PostAsync(requestUrl, multipartContent);
var responseJson = JObject.Parse(await response.Content.ReadAsStringAsync());
if (responseJson["data"] != null)
{
return responseJson["data"]["task_id"].ToString();
}
else
{
//Request from user server failed. Please record the relevant error logs.
throw new Exception(responseJson.ToString());
}
}
static async Task<JObject> GetTaskResult(string taskId)
{
var requestUrl = $"{url}/{taskId}";
var response = await client.GetAsync(requestUrl);
var responseJson = JObject.Parse(await response.Content.ReadAsStringAsync());
if (responseJson["data"]["image"] != null)
{
return responseJson;
}
else
{
//Task processing
throw new Exception(responseJson.ToString());
}
}
//Polling requests using the following methods
//1. The polling interval is set to 1 second,
//2. The polling time does not exceed 30 seconds
static async Task<JObject> Polling(Func<Task<JObject>> fn, TimeSpan delay, TimeSpan timeout)
{
var endTime = DateTime.Now + timeout;
while (DateTime.Now < endTime)
{
try
{
return await fn();
}
catch
{
//You can choose to continue the loop with "continue" or break the loop with "break".
Console.WriteLine("polling...");
//Wait for one second between each loop iteration.
await Task.Delay(delay);
}
}
//Timeout, log the details, and search for support from the picwish service.
throw new Exception("timeout");
}
}
import Alamofire
import Foundation
let API_KEY = "{YOUR_API_KEY}"
let BASE_URL = "https://techsz.aoscdn.com/api/tasks/visual/segmentation"
/// Begin task
func startEraser() {
createTask { taskId in
// Task succeed, get result. Polling requests using the following methods 1. The polling interval is set to 1 second, 2. The polling time does not exceed 30 seconds
let startTime = CFAbsoluteTimeGetCurrent()
getTaskResult(taskId: taskId, taskStartTime: startTime) { result in
print(result)
}
}
}
/// Create a task
func createTask(completion: @escaping (String) -> Void) {
let url = URL(string: BASE_URL)!
let headers: HTTPHeaders = [
"X-API-KEY": API_KEY
]
AF.upload(multipartFormData: { multipartFormData in
if let imageUrl = "{YOUR_IMAGE_NETWORK_URL}".data(using: .utf8) {
multipartFormData.append(imageUrl, withName: "image_url", fileName: "test.jpg", mimeType: "image/jpeg")
}
if let data = "1".data(using: .utf8) {
multipartFormData.append(data, withName: "output_type")
}
}, to: url, method: .post, headers: headers).responseData { response in
switch response.result {
case .success(let value):
if let json = try? JSONSerialization.jsonObject(with: value) as? [String: Any],
let data = json["data"] as? [String: Any],
let taskId = data["task_id"] as? String {
completion(taskId)
}
case .failure(let error):
print(error)
}
}
}
/// Get result
func getTaskResult(taskId: String,
taskStartTime: CFAbsoluteTime,
completion: @escaping ([String: Any]) -> Void) {
let url = URL(string: "\(BASE_URL)/\(taskId)")!
let headers: HTTPHeaders = [
"X-API-KEY": API_KEY
]
AF.request(url, method: .get, headers: headers).responseData { response in
switch response.result {
case .success(let value):
print(response.debugDescription)
guard let json = try? JSONSerialization.jsonObject(with: value) as? [String: Any],
let data = json["data"] as? [String: Any],
let state = data["state"] as? Int else {
print("parse failed")
return
}
// Task failed, log the details, and exit the loop
if state < 0 {
print("state < 0")
return
}
// Task successful
if state == 1 {
if let imageUrlStr = data["image"] as? String, let maskUrlStr = data["mask"] as? String {
completion(["image": imageUrlStr, "mask": maskUrlStr])
return
}
}
// Retrieve the results by looping only thirty times
let endTime = CFAbsoluteTimeGetCurrent()
if endTime - taskStartTime < 30 {
// Wait for one second between each loop iteration
sleep(1)
getTaskResult(taskId: taskId, taskStartTime: taskStartTime, completion: completion)
return
}
// Timeout, log the details, and search for support from the picwish service
print("timeout")
case .failure(let error):
// Request from user server failed. Please record the relevant error logs
print(error)
}
}
}
package main
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"mime/multipart"
"net/http"
"time"
)
const (
APIKey = "YOUR_API_KEY"
BaseURL = "https://techsz.aoscdn.com/api/tasks/visual/segmentation"
)
// taskResponse
type taskResponse struct {
Status int `json:"status"`
Message string `json:"message"`
Data struct {
TaskId string `json:"task_id"`
} `json:"data"`
}
type VisualSegmentationResponse struct {
Status int `json:"status"`
Message string `json:"message"`
Data struct {
TaskId string `json:"task_id"`
Image string `json:"image"`
Mask string `json:"mask"`
MaskObj string `json:"mask_obj"`
ImageObj string `json:"image_obj"`
ReturnType uint `json:"return_type"`
OutputType uint `json:"output_type"`
Type string `json:"type"`
ResultType string `json:"result_type"`
TimeElapsed float64 `json:"time_elapsed"`
Progress uint `json:"progress"`
State int `json:"state"`
ImageWidth uint `json:"image_width"`
ImageHeight uint `json:"image_height"`
} `json:"data"`
}
func createTask() (string, error) {
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
_ = writer.WriteField("image_url", "YOUR_IMG_URL")
err := writer.Close()
if err != nil {
fmt.Println("Close error", err)
return "", err
}
if err != nil {
return "", err
}
req, err := http.NewRequest("POST", BaseURL, body)
if err != nil {
return "", err
}
req.Header.Set("Content-Type", writer.FormDataContentType())
req.Header.Set("X-API-KEY", APIKey)
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
respBody, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
var taskResp *taskResponse
err = json.Unmarshal(respBody, &taskResp)
if err != nil {
fmt.Println("Error parsing JSON:", err)
return "", err
}
if taskResp.Status != 200 {
// Request from user server failed. Please record the relevant error logs.
var taskError error
taskError = errors.New("error task id")
return "", taskError
}
return taskResp.Data.TaskId, nil
}
func getTaskResult(taskId string) (*VisualSegmentationResponse, error) {
req, err := http.NewRequest("GET", fmt.Sprintf("%s/%s", BaseURL, taskId), nil)
if err != nil {
return nil, err
}
req.Header.Set("X-API-KEY", APIKey)
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
respBody, err := ioutil.ReadAll(resp.Body)
if err != nil {
// failed. Please record the relevant error logs.
return nil, err
}
var taskResp *VisualSegmentationResponse
err = json.Unmarshal(respBody, &taskResp)
if err != nil {
fmt.Println("Error parsing JSON:", err)
return nil, err
}
return taskResp, err
}
func main() {
taskId, err := createTask()
if err != nil {
fmt.Println("Error creating task:", err)
return
}
//Retrieve the results by looping thirty times.
for i := 0; i < 30; i++ {
if i != 0 {
time.Sleep(time.Second) // Wait for one second between each loop iteration.
}
result, err := getTaskResult(taskId)
if err != nil {
fmt.Println("Error getting task result:", err, taskId)
break
}
if result.Status != 200 {
// Request from user server failed. Please record the relevant error logs.
var taskError error
taskError = errors.New("error get task id")
fmt.Println("result error ", result, taskError, taskId)
//You can choose to continue polling or break, both options are acceptable.
continue
} else {
if result.Data.State == 1 {
//Complete the task and end the polling.
fmt.Println("result", result)
break
} else if result.Data.State < 0 {
// Task failed, log the details, and exit the loop.
fmt.Println("result", result)
break
}
// Other tasks in the 'state' are in progress, continue polling.
if i == 29 {
// Timeout, log the details, and search for support from the Zuo Tang customer service.
fmt.Println("result", result, taskId)
}
}
}
}
#Create a task.
curl -k 'https://techsz.aoscdn.com/api/tasks/visual/segmentation' \
-H 'X-API-KEY: YOUR_API_KEY' \
-F 'sync=1' \
-F 'image_url=YOU_IMG_URL'
<?php
//Create a task
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'https://techsz.aoscdn.com/api/tasks/visual/segmentation');
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
"X-API-KEY: YOUR_API_KEY",
"Content-Type: multipart/form-data",
));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_POSTFIELDS, array('sync' => 1, 'image_url' => "YOUR_IMG_URL"));
$response = curl_exec($curl);
$result = curl_errno($curl) ? curl_error($curl) : $response;
curl_close($curl);
if ( !isset($result["status"]) || $result["status"] != 200 ) {
// request failed, log the details
die("post request failed");
}
var_dump($result);
if ( $result["data"]["state"] == 1 ) {
// task success
var_dump($result["data"]["image"]);
} else if ( $result["data"]["state"] < 0) {
// request failed, log the details
} else {
//Task processing, abnormal situation, seeking assistance from customer service of picwish
}
OkHttpClient okHttpClient = new OkHttpClient.Builder().build();
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("image_url", "IMAGE_HTTP_URL")
.addFormDataPart("sync", "1")
.build();
Request request = new Request.Builder()
.url("https://techsz.aoscdn.com/api/tasks/visual/segmentation")
.addHeader("X-API-KEY", "YOUR_API_KEY")
.post(requestBody)
.build();
Response response = okHttpClient.newCall(request).execute();
const request = require("request");
request(
{
method: "POST",
url: "https://techsz.aoscdn.com/api/tasks/visual/segmentation",
headers: {
"X-API-KEY": "YOUR_API_KEY",
},
formData: {
sync: "1",
image_url: "IMAGE_HTTP_URL",
},
json: true
},
function (error, response) {
if (response.body.data) {
const { progress, state } = response.body.data
if (progress >= 100) {
return console.log(`result:`, response.body);
}
}
throw new Error(JSON.stringify(response.body, null, 2))
}
);
import requests
API_KEY = 'YOUR_API_KEY'
IMAGE_NETWORK_URL = 'YOUR_IMAGE_NETWORK_URL'
def main():
headers = {'X-API-KEY': API_KEY}
data = {'sync': '1', 'image_url': IMAGE_NETWORK_URL}
url = 'https://techsz.aoscdn.com/api/tasks/visual/segmentation'
response = requests.post(url, headers=headers, data=data)
response_json = response.json()
if 'status' in response_json and response_json['status'] == 200:
result_tag = 'failed'
if 'data' in response_json:
response_json_data = response_json['data']
if 'state' in response_json_data:
task_state = response_json_data['state']
# task success
if task_state == 1:
result_tag = 'successful'
elif task_state < 0:
# request failed, log the details
pass
else:
# Task processing, abnormal situation, seeking assistance from customer service of picwish
pass
print(f'Result({result_tag}): {response_json}')
else:
# request failed, log the details
print(f'Error: Failed to get the result,{response.text}')
if __name__ == "__main__":
main()
using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
public class Program
{
public static async Task Main()
{
string apiKey = "YOUR_API_KEY";
string url = "https://techsz.aoscdn.com/api/tasks/visual/segmentation";
string imageUrl = "IMAGE_HTTP_URL";
string sync = "1";
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Add("X-API-KEY", apiKey);
using (var content = new MultipartFormDataContent())
{
content.Add(new StringContent(sync), "sync");
content.Add(new StringContent(imageUrl), "image_url");
//User server initiates a request.
var response = await client.PostAsync(url, content);
var responseContent = await response.Content.ReadAsStringAsync();
if (response.IsSuccessStatusCode)
{
var responseData = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(responseContent);
var progress = (int)responseData.data.progress;
var state = (int)responseData.data.state;
if (progress >= 100)
{
//Task successful.
Console.WriteLine($"result: {responseContent}");
}
if (state == -1)
{
//Task processing, abnormal situation, seeking assistance from customer service of picwish
Console.WriteLine($"Error: {responseContent}");
}
}
else
{
//Task processing, abnormal situation, seeking assistance from customer service of picwish
Console.WriteLine($"Error: {responseContent}");
}
}
}
Console.ReadKey();
}
}
import Alamofire
import Foundation
let apiKey = "YOUR_API_KEY"
let url = "https://techsz.aoscdn.com/api/tasks/visual/segmentation"
let sync = "1"
let headers: HTTPHeaders = [
"X-API-KEY": apiKey,
]
AF.upload(multipartFormData: { multipartFormData in
multipartFormData.append(Data(sync.utf8), withName: "sync")
if let imageUrl = "{YOUR_IMAGE_NETWORK_URL}".data(using: .utf8) {
multipartFormData.append(imageUrl, withName: "image_url", fileName: "test.jpg", mimeType: "image/jpeg")
}
}, to: url, method: .post, headers: headers).responseJSON { response in
switch response.result {
case .success(let value):
if let jsonResponse = value as? [String: Any],
let data = jsonResponse["data"] as? [String: Any],
let progress = data["progress"] as? Int,
let state = data["state"] as? String {
if progress >= 100 {
print("Result: \(jsonResponse)")
}
}
case .failure(let error):
print("Error: \(error.localizedDescription)")
}
}
package api
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"mime/multipart"
"net/http"
"testing"
)
type VisualSegmentationResponse struct {
Status int `json:"status"`
Message string `json:"message"`
Data struct {
TaskId string `json:"task_id"`
Image string `json:"image"`
Mask string `json:"mask"`
MaskObj string `json:"mask_obj"`
ImageObj string `json:"image_obj"`
ReturnType uint `json:"return_type"`
OutputType uint `json:"output_type"`
Type string `json:"type"`
ResultType string `json:"result_type"`
TimeElapsed float64 `json:"time_elapsed"`
Progress uint `json:"progress"`
State int `json:"state"`
ImageWidth uint `json:"image_width"`
ImageHeight uint `json:"image_height"`
} `json:"data"`
}
func TestSegmentationTechApi(t *testing.T) {
url := "https://techsz.aoscdn.com/api/tasks/visual/segmentation"
payload := &bytes.Buffer{}
writer := multipart.NewWriter(payload)
_ = writer.WriteField("sync", "1")
_ = writer.WriteField("image_url", "YOUR_IMG_URL")
err := writer.Close()
if err != nil {
fmt.Println("Close error", err)
return
}
client := &http.Client{}
req, err := http.NewRequest("POST", url, payload)
if err != nil {
fmt.Println("Close error", err)
return
}
req.Header.Add("X-API-KEY", "YOUR_API_KEY")
req.Header.Set("Content-Type", writer.FormDataContentType())
res, err := client.Do(req)
if err != nil {
fmt.Println("client query error", err)
return
}
defer res.Body.Close()
respBody, err := ioutil.ReadAll(res.Body)
if err != nil {
fmt.Println("Read body error", err)
return
}
var taskResp *VisualSegmentationResponse
err = json.Unmarshal(respBody, &taskResp)
if err != nil {
fmt.Println("Error parsing JSON:", err)
return
}
if taskResp.Status != http.StatusOK {
// Request from user server failed. Please record the relevant error logs.
fmt.Println("failed to get the result", taskResp)
} else {
if taskResp.Data.State == 1 {
//Task successful. Recorded in the database with task ID.
fmt.Println("result Successfully", taskResp)
} else {
// Task failed. Please record the relevant error logs.
fmt.Println("result falied", taskResp)
}
}
}
#Create a task.
curl -k 'https://techsz.aoscdn.com/api/tasks/visual/segmentation' \
-H 'X-API-KEY: YOUR_API_KEY' \
-F 'callback_url=YOUR_SERVER_URL' \
-F 'sync=0' \
-F 'image_url=YOU_IMG_URL'
#Curl is not suitable for writing callbacks. You need to use backend languages like Go to write callback functions to receive parameters.
<?php
//Create a task
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'https://techsz.aoscdn.com/api/tasks/visual/segmentation');
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
"X-API-KEY: YOUR_API_KEY",
"Content-Type: multipart/form-data",
));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_POSTFIELDS, array('sync' => 0,'callback_url' => "YOUR_URL", 'image_url' => "YOUR_IMG_URL"));
$response = curl_exec($curl);
$result = curl_errno($curl) ? curl_error($curl) : $response;
curl_close($curl);
$result = json_decode($result, true);
if ( !isset($result["status"]) || $result["status"] != 200 ) {
// request failed, log the details
var_dump($result);
die("post request failed");
}
// Record the task ID and store it in the database.
$task_id = $result["data"]["task_id"];
<?php
// Callback code.
// Original JSON data.
$jsonData = '{
"status": 200,
"message": "success",
"data": {
"task_id": "13cc3f64-6753-4a59-a06d-38946bc91144",
"image": "13cc3f64-6753-4a59-a06d-38946bc91144.jpg",
"state": 1
}
}';
// if needed,Decode JSON data.
$data = json_decode($jsonData, true);
if ( !isset($data["status"]) || $data["status"] != 200 ) {
// request failed, log the details
var_dump($data);
die("post request failed");
}
if ( $data["data"]["state"] == 1 ) {
// task success Store the image in the database based on the taskId.
var_dump($data["data"]["image"]);
} else if ( $data["data"]["state"] < 0) {
// request failed, log the details
var_dump($data);
} else {
//Task processing, abnormal situation, seeking assistance from customer service of picwish
}
OkHttpClient okHttpClient = new OkHttpClient.Builder().build();
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("image_url", "IMAGE_HTTP_URL")
.addFormDataPart("callback_url", "YOUR_SERVER_URL")
.build();
Request request = new Request.Builder()
.url("https://techsz.aoscdn.com/api/tasks/visual/segmentation")
.addHeader("X-API-KEY", "YOUR_API_KEY")
.post(requestBody)
.build();
Response response = okHttpClient.newCall(request).execute();
System.out.println("Response json string: " + response.body().string());
const request = require("request");
const fs = require("fs");
const path = require('path')
request(
{
method: "POST",
url: "https://techsz.aoscdn.com/api/tasks/visual/segmentation",
headers: {
"X-API-KEY": "YOUR_API_KEY",
},
formData: {
callback_url: "YOUR_SERVER_URL",
image_url: "IMAGE_HTTP_URL",
},
json: true
},
function (error, response) {
if (response.body.data) {
console.log(response.body.data)
}
throw new Error(JSON.stringify(response.body, null, 2))
}
);
import requests
API_KEY = 'YOUR_API_KEY'
IMAGE_NETWORK_URL = 'YOUR_IMAGE_NETWORK_URL'
SERVER_URL = 'YOUR_SERVER_URL'
def main():
headers = {'X-API-KEY': API_KEY}
data = {'callback_url': SERVER_URL, 'image_url': IMAGE_NETWORK_URL}
url = 'https://techsz.aoscdn.com/api/tasks/visual/segmentation'
response = requests.post(url, headers=headers, data=data)
response_json = response.json()
if 'status' in response_json and response_json['status'] == 200:
# Task successful. Recorded in the database with task ID.
print(f'Result(successful): {response_json}')
else:
# Request from user server failed. Please record the relevant error logs.
print(f'Error: Failed to get the result,{response.text}')
if __name__ == "__main__":
main()
using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
public class Program
{
public static async Task Main()
{
string apiKey = "YOUR_API_KEY";
string url = "https://techsz.aoscdn.com/api/tasks/visual/segmentation";
string imageUrl = "IMAGE_HTTP_URL";
string callbackUrl = "YOUR_SERVER_URL";
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Add("X-API-KEY", apiKey);
using (var content = new MultipartFormDataContent())
{
content.Add(new StringContent(imageUrl), "image_url");
content.Add(new StringContent(callbackUrl), "callback_url");
//User server initiates a request.
var response = await client.PostAsync(url, content);
var responseContent = await response.Content.ReadAsStringAsync();
if (response.IsSuccessStatusCode)
{
//Task successful.
var responseData = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(responseContent);
Console.WriteLine($"result: {responseContent}");
}
else
{
//Task processing, abnormal situation, seeking assistance from customer service of picwish
Console.WriteLine($"Error: {responseContent}");
}
}
}
Console.ReadKey();
}
}
import Alamofire
import Foundation
let apiKey = "YOUR_API_KEY"
let url = "https://techsz.aoscdn.com/api/tasks/visual/segmentation"
let imagePath = Bundle.main.path(forResource: "test", ofType: "jpg")!
let callbackUrl = "YOUR_SERVER_URL"
let headers: HTTPHeaders = [
"X-API-KEY": apiKey,
]
AF.upload(multipartFormData: { multipartFormData in
multipartFormData.append(Data(callbackUrl.utf8), withName: "callback_url")
if let imageUrl = "{YOUR_IMAGE_NETWORK_URL}".data(using: .utf8) {
multipartFormData.append(imageUrl, withName: "image_url", fileName: "test.jpg", mimeType: "image/jpeg")
}
}, to: url, method: .post, headers: headers).responseJSON { response in
switch response.result {
case .success(let value):
print("Result: \(value)")
case .failure(let error):
print("Error: \(error.localizedDescription)")
}
}
// File 1: User server initiates a request.
package api
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"mime/multipart"
"net/http"
"testing"
)
type TaskResponse struct {
Status int `json:"status"`
Message string `json:"message"`
Data struct {
TaskId string `json:"task_id"`
} `json:"data"`
}
func TestSegmentationTechApi(t *testing.T) {
url := "https://techsz.aoscdn.com/api/tasks/visual/segmentation"
payload := &bytes.Buffer{}
writer := multipart.NewWriter(payload)
_ = writer.WriteField("callback_url", "YOUR_SERVER_URL")
_ = writer.WriteField("image_url", "YOUR_IMG_URL")
err := writer.Close()
if err != nil {
fmt.Println("Close error", err)
return
}
client := &http.Client{}
req, err := http.NewRequest("POST", url, payload)
if err != nil {
fmt.Println("Close error", err)
return
}
req.Header.Add("X-API-KEY", "YOUR_API_KEY")
req.Header.Set("Content-Type", writer.FormDataContentType())
res, err := client.Do(req)
if err != nil {
fmt.Println("client query error", err)
return
}
defer res.Body.Close()
respBody, err := ioutil.ReadAll(res.Body)
if err != nil {
fmt.Println("Read body error", err)
return
}
var taskResp *TaskResponse
err = json.Unmarshal(respBody, &taskResp)
if err != nil {
fmt.Println("Error parsing JSON:", err)
return
}
if taskResp.Status != http.StatusOK {
// Request from user server failed. Please record the relevant error logs.
fmt.Println("failed to get the result", taskResp)
} else {
//Task successful. Recorded in the database with task ID.
fmt.Println("result Successfully", taskResp)
}
}
// picwish server initiates a request to the user server, and the interface of the user server receives the parameters.
package main
import (
"encoding/json"
"fmt"
)
type VisualSegmentationResponse struct {
Status int `json:"status"`
Message string `json:"message"`
Data struct {
TaskId string `json:"task_id"`
Image string `json:"image"`
Mask string `json:"mask"`
MaskObj string `json:"mask_obj"`
ImageObj string `json:"image_obj"`
ReturnType uint `json:"return_type"`
OutputType uint `json:"output_type"`
Type string `json:"type"`
ResultType string `json:"result_type"`
TimeElapsed float64 `json:"time_elapsed"`
Progress uint `json:"progress"`
State int `json:"state"`
ImageWidth uint `json:"image_width"`
ImageHeight uint `json:"image_height"`
} `json:"data"`
}
func main() {
// JSON data is passed and received here, and code modification is required.
jsonData := `{
"status": 200,
"message": "Success",
"data": {
"task_id": "123456",
"image": "image_data",
"mask": "mask_data",
"mask_obj": "mask_obj_data",
"image_obj": "image_obj_data",
"return_type": 1,
"output_type": 1,
"type": "type_data",
"result_type": "result_type_data",
"time_elapsed": 2.5,
"progress": 100,
"state": 1,
"image_width": 800,
"image_height": 600
}
}`
// Parse JSON data into VisualSegmentationResponse struct
var response VisualSegmentationResponse
err := json.Unmarshal([]byte(jsonData), &response)
if err != nil {
fmt.Println("Error parsing JSON:", err)
return
}
// Query the relevant content in the database based on the taskID and associate it with the image below.
fmt.Println("Image:", response.Data.TaskId)
// Print the 'image' field
fmt.Println("Image:", response.Data.Image)
}
#Create a task
curl -k 'https://techsz.aoscdn.com/api/tasks/visual/segmentation' \
-H 'X-API-KEY: YOUR_API_KEY' \
-F 'sync=0' \
-F 'image_file=@/path/to/image.jpg'
#Get the cutout result
#Polling requests using the following methods 1. The polling interval is set to 1 second, 2. The polling time does not exceed 30 seconds
curl -k 'https://techsz.aoscdn.com/api/tasks/visual/segmentation/{task_id}' \
-H 'X-API-KEY: YOUR_API_KEY' \
<?php
//Create a task
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'https://techsz.aoscdn.com/api/tasks/visual/segmentation');
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
"X-API-KEY: YOUR_API_KEY",
"Content-Type: multipart/form-data",
));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_POSTFIELDS, array('sync' => 0, 'image_file' => new CURLFILE("/path/to/image.jpg")));
$response = curl_exec($curl);
$result = curl_errno($curl) ? curl_error($curl) : $response;
curl_close($curl);
$result = json_decode($result, true);
if ( !isset($result["status"]) || $result["status"] != 200 ) {
// request failed, log the details
var_dump($result);
die("post request failed");
}
// var_dump($result);
$task_id = $result["data"]["task_id"];
//get the task result
// 1、"The polling interval is set to 1 second."
//2 "The polling time is around 30 seconds."
for ($i = 1; $i <= 30; $i++) {
if ($i != 1) {
sleep(1);
}
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "https://techsz.aoscdn.com/api/tasks/visual/segmentation/".$task_id);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
"X-API-KEY: YOUR_API_KEY",
));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($curl);
$result = curl_errno($curl) ? curl_error($curl) : $response;
curl_close($curl);
var_dump($result);
$result = json_decode($result, true);
if ( !isset($result["status"]) || $result["status"] != 200 ) {
// Task exception, logging the error.
//You can choose to continue the loop with 'continue' or break the loop with 'break'
var_dump($result);
continue;
}
if ( $result["data"]["state"] == 1 ) {
// task success
var_dump($result["data"]["image"]);
break;
} else if ( $result["data"]["state"] < 0) {
// request failed, log the details
var_dump($result);
break;
} else {
// Task processing
if ($i == 30) {
//Task processing, abnormal situation, seeking assistance from customer service of picwish
}
}
}
public static void main(String[] args) throws Exception {
String taskId = createTask();
String dataString = pollingTaskResult(taskId, 0);
System.out.println(dataString);
}
private static String createTask() throws Exception {
OkHttpClient okHttpClient = new OkHttpClient.Builder().build();
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("image_file", JPG_FILE_NAME, RequestBody.create({JPG_FILE}, MediaType.parse("image/jpeg")))
.addFormDataPart("sync", "0")
.build();
Request request = new Request.Builder()
.url("https://techsz.aoscdn.com/api/tasks/visual/segmentation")
.addHeader("X-API-KEY", "YOUR_API_KEY")
.post(requestBody)
.build();
Response response = okHttpClient.newCall(request).execute();
JSONObject jsonObject = new JSONObject(response.body().string());
int status = jsonObject.optInt("status");
if (status != 200) {
throw new Exception(jsonObject.optString("message"));
}
return jsonObject.getJSONObject("data").optString("task_id");
}
private static String pollingTaskResult(String taskId, int pollingTime) throws Exception {
if (pollingTime >= 30) throw new IllegalStateException("Polling result timeout.");
OkHttpClient okHttpClient = new OkHttpClient.Builder().build();
Request taskRequest = new Request.Builder()
.url("https://techsz.aoscdn.com/api/tasks/visual/segmentation/" + taskId)
.addHeader("X-API-KEY", "YOUR_API_KEY")
.get()
.build();
Response taskResponse = okHttpClient.newCall(taskRequest).execute();
JSONObject jsonObject = new JSONObject(taskResponse.body().string());
int state = jsonObject.getJSONObject("data").optInt("state");
if (state < 0) { // Cutout error.
throw new Exception(jsonObject.optString("message"));
}
if (state == 1) { // Cutout success and get result.
return jsonObject.getJSONObject("data").toString();
}
Thread.sleep(1000);
return pollingTaskResult(taskId, ++pollingTime);
}
const request = require("request");
const fs = require("fs");
const path = require('path')
const API_KEY = "YOUR_API_KEY";
(async function main() {
const taskId = await createTask()
const result = await polling(() => getTaskResult(taskId))
console.log(`result: ${JSON.stringify(result, null, 2)}`)
})()
const polling = async (fn, delay = 1 * 1000, timeout = 30 * 1000) => {
if (!fn) {
throw new Error('fn is required')
}
try {
const result = await fn()
return result
} catch (error) {
if (error && 'data' in error) {
throw new Error(JSON.stringify(error, null, 2))
}
if (timeout <= 0) {
throw new Error('timeout')
}
await new Promise((resolve) => {
setTimeout(() => {
resolve()
}, delay)
})
return polling(fn, delay, timeout - delay)
}
}
function createTask() {
return new Promise((resolve, reject) => {
request(
{
method: "POST",
url: "https://techsz.aoscdn.com/api/tasks/visual/segmentation",
headers: {
"X-API-KEY": API_KEY,
},
formData: {
image_file: fs.createReadStream(path.join(__dirname, './test.jpg')),
},
json: true
},
function (error, response) {
if (response.body.data) {
resolve(response.body.data.task_id)
} else {
reject(response.body)
}
}
);
})
}
function getTaskResult(taskId) {
return new Promise((resolve, reject) => {
request(
{
method: "GET",
url: `https://techsz.aoscdn.com/api/tasks/visual/segmentation/${taskId}`,
headers: {
"X-API-KEY": API_KEY,
},
json: true
},
function (error, response) {
if (!response.body.data) reject(response.body)
const { progress, state } = response.body.data
if (state < 0) reject(response.body)
if (progress >= 100) resolve(response.body)
reject(null)
}
);
})
}
import os
import time
import requests
API_KEY = 'YOUR_API_KEY'
IMAGE_FILE_PATH = 'YOUR_IMAGE_FILE_PATH'
def create_task():
assert os.path.exists(IMAGE_FILE_PATH), f'Error: File({IMAGE_FILE_PATH}) does not exist.'
headers = {'X-API-KEY': API_KEY}
data = {'sync': '0'}
files = {'image_file': open(IMAGE_FILE_PATH, 'rb')}
url = 'https://techsz.aoscdn.com/api/tasks/visual/segmentation'
# Create a task
response = requests.post(url, headers=headers, data=data, files=files)
task_id = None
response_json = response.json()
if 'status' in response_json and response_json['status'] == 200:
result_tag = 'failed'
if 'data' in response_json:
response_json_data = response_json['data']
if 'task_id' in response_json_data:
result_tag = 'successful'
task_id = response_json_data['task_id']
print(f'Result of created task({result_tag}): {response_json}')
else:
# request failed, log the details
print(f'Error: Failed to create task,{response.text}')
return task_id
# get the task result
# 1、"The polling interval is set to 1 second."
# 2、"The polling time is around 30 seconds."
def polling_task_result(task_id,time_out=30):
headers = {'X-API-KEY': API_KEY}
url = f'https://techsz.aoscdn.com/api/tasks/visual/segmentation/{task_id}'
for i in range(time_out):
if i != 0:
time.sleep(1)
response = requests.get(url, headers=headers)
response_json = response.json()
if 'status' in response_json and response_json['status'] == 200:
if 'data' in response_json:
response_json_data = response_json['data']
if 'state' in response_json_data:
task_state = response_json_data['state']
if task_state == 1:
# task success
print(f'Result(successful): {response_json}')
break
elif task_state < 0:
# Task exception, logging the error.
# You can choose to continue the loop with 'continue' or break the loop with 'break'
print(f'Result(failed): {response_json}')
break
print(f'Result(polling): {response_json}')
if i == time_out-1:
# Timeout, log the details, and search for support from the picwish service.
print('Error: Timeout while polling.')
else:
# Task exception, logging the error.
# You can choose to continue the loop with 'continue' or break the loop with 'break'
print(f'Error: Failed to get the task\'s result,{response.text}')
break
def main():
task_id = create_task()
if task_id is None:
print('Error: Failed to create task,task id is None.')
return
polling_task_result(task_id)
if __name__ == "__main__":
main()
using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
class Program
{
public static HttpClient client = new HttpClient();
private static string url = "https://techsz.aoscdn.com/api/tasks/visual/segmentation";
private static string API_KEY = "YOUR_API_KEY";
private static string imagePath = "test.jpg";
static async Task Main(string[] args)
{
try
{
var taskId = await CreateTask();
var result = await Polling(() => GetTaskResult(taskId), TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(30));
Console.WriteLine($"result: {result.ToString()}");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadKey();
}
static async Task<string> CreateTask()
{
var requestUrl = url;
var multipartContent = new MultipartFormDataContent();
var fileStream = File.OpenRead(imagePath);
multipartContent.Add(new StreamContent(fileStream), "image_file", Path.GetFileName(imagePath));
client.DefaultRequestHeaders.Add("X-API-KEY", API_KEY);
//User server initiates a request.
var response = await client.PostAsync(requestUrl, multipartContent);
var responseJson = JObject.Parse(await response.Content.ReadAsStringAsync());
if (responseJson["data"] != null)
{
return responseJson["data"]["task_id"].ToString();
}
else
{
//Request from user server failed. Please record the relevant error logs.
throw new Exception(responseJson.ToString());
}
}
static async Task<JObject> GetTaskResult(string taskId)
{
var requestUrl = $"{url}/{taskId}";
var response = await client.GetAsync(requestUrl);
var responseJson = JObject.Parse(await response.Content.ReadAsStringAsync());
if (responseJson["data"]["image"] != null)
{
return responseJson;
}
else
{
//Task processing
throw new Exception(responseJson.ToString());
}
}
//Polling requests using the following methods
//1. The polling interval is set to 1 second,
//2. The polling time does not exceed 30 seconds
static async Task<JObject> Polling(Func<Task<JObject>> fn, TimeSpan delay, TimeSpan timeout)
{
var endTime = DateTime.Now + timeout;
while (DateTime.Now < endTime)
{
try
{
return await fn();
}
catch
{
//You can choose to continue the loop with "continue" or break the loop with "break".
Console.WriteLine("polling...");
//Wait for one second between each loop iteration.
await Task.Delay(delay);
}
}
//Timeout, log the details, and search for support from the picwish service.
throw new Exception("timeout");
}
}
import Alamofire
import Foundation
let API_KEY = "{YOUR_API_KEY}"
let BASE_URL = "https://techsz.aoscdn.com/api/tasks/visual/segmentation"
/// Begin task
func startEraser() {
createTask { taskId in
// Task succeed, get result. Polling requests using the following methods 1. The polling interval is set to 1 second, 2. The polling time does not exceed 30 seconds
let startTime = CFAbsoluteTimeGetCurrent()
getTaskResult(taskId: taskId, taskStartTime: startTime) { result in
print(result)
}
}
}
/// Create a task
func createTask(completion: @escaping (String) -> Void) {
let url = URL(string: BASE_URL)!
let headers: HTTPHeaders = [
"X-API-KEY": API_KEY
]
let imagePath = Bundle.main.path(forResource: "test", ofType: "jpg")!
AF.upload(multipartFormData: { multipartFormData in
multipartFormData.append(URL(fileURLWithPath: imagePath), withName: "image_file", fileName: "test.jpg", mimeType: "image/jpeg")
if let data = "1".data(using: .utf8) {
multipartFormData.append(data, withName: "output_type")
}
}, to: url, method: .post, headers: headers).responseData { response in
switch response.result {
case .success(let value):
if let json = try? JSONSerialization.jsonObject(with: value) as? [String: Any],
let data = json["data"] as? [String: Any],
let taskId = data["task_id"] as? String {
completion(taskId)
}
case .failure(let error):
print(error)
}
}
}
/// Get result
func getTaskResult(taskId: String,
taskStartTime: CFAbsoluteTime,
completion: @escaping ([String: Any]) -> Void) {
let url = URL(string: "\(BASE_URL)/\(taskId)")!
let headers: HTTPHeaders = [
"X-API-KEY": API_KEY
]
AF.request(url, method: .get, headers: headers).responseData { response in
switch response.result {
case .success(let value):
print(response.debugDescription)
guard let json = try? JSONSerialization.jsonObject(with: value) as? [String: Any],
let data = json["data"] as? [String: Any],
let state = data["state"] as? Int else {
print("parse failed")
return
}
// Task failed, log the details, and exit the loop
if state < 0 {
print("state < 0")
return
}
// Task successful
if state == 1 {
if let imageUrlStr = data["image"] as? String, let maskUrlStr = data["mask"] as? String {
completion(["image": imageUrlStr, "mask": maskUrlStr])
return
}
}
// Retrieve the results by looping only thirty times
let endTime = CFAbsoluteTimeGetCurrent()
if endTime - taskStartTime < 30 {
// Wait for one second between each loop iteration
sleep(1)
getTaskResult(taskId: taskId, taskStartTime: taskStartTime, completion: completion)
return
}
// Timeout, log the details, and search for support from the picwish service
print("timeout")
case .failure(let error):
// Request from user server failed. Please record the relevant error logs
print(error)
}
}
}
package main
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"mime/multipart"
"net/http"
"os"
"path/filepath"
)
const (
APIKey = "YOUR_API_KEY"
BaseURL = "https://techsz.aoscdn.com/api/tasks/visual/segmentation"
)
func createTask() (string, error) {
file, err := os.Open("test.jpg")
if err != nil {
return "", err
}
defer file.Close()
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
part, err := writer.CreateFormFile("image_file", filepath.Base("test.jpg"))
if err != nil {
return "", err
}
_, err = io.Copy(part, file)
err = writer.Close()
if err != nil {
return "", err
}
req, err := http.NewRequest("POST", BaseURL, body)
if err != nil {
return "", err
}
req.Header.Set("Content-Type", writer.FormDataContentType())
req.Header.Set("X-API-KEY", APIKey)
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
respBody, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
var result map[string]interface{}
json.Unmarshal(respBody, &result)
return result["data"].(map[string]interface{})["task_id"].(string), nil
}
func getTaskResult(taskId string) (map[string]interface{}, error) {
req, err := http.NewRequest("GET", fmt.Sprintf("%s/%s", BaseURL, taskId), nil)
if err != nil {
return nil, err
}
req.Header.Set("X-API-KEY", APIKey)
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
respBody, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
var result map[string]interface{}
json.Unmarshal(respBody, &result)
return result, nil
}
func main() {
taskId, err := createTask()
if err != nil {
fmt.Println("Error creating task:", err)
return
}
result, err := getTaskResult(taskId)
if err != nil {
fmt.Println("Error getting task result:", err)
return
}
fmt.Println("Task result:", result)
}
#Create a task.
curl -k 'https://techsz.aoscdn.com/api/tasks/visual/segmentation' \
-H 'X-API-KEY: YOUR_API_KEY' \
-F 'sync=1' \
-F 'image_file=@/path/to/image.jpg'
<?php
//Create a task
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'https://techsz.aoscdn.com/api/tasks/visual/segmentation');
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
"X-API-KEY: YOUR_API_KEY",
"Content-Type: multipart/form-data",
));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_POSTFIELDS, array('sync' => 1, 'image_file' => new CURLFILE("/path/to/image.jpg")));
$response = curl_exec($curl);
$result = curl_errno($curl) ? curl_error($curl) : $response;
curl_close($curl);
if ( !isset($result["status"]) || $result["status"] != 200 ) {
// request failed, log the details
var_dump($result);
die("post request failed");
}
var_dump($result);
if ( $result["data"]["state"] == 1 ) {
// task success
var_dump($result["data"]["image"]);
} else if ( $result["data"]["state"] < 0) {
// request failed, log the details
} else {
//Task processing, abnormal situation, seeking assistance from customer service of picwish
}
OkHttpClient okHttpClient = new OkHttpClient.Builder().build();
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("image_file", JPG_FILE_NAME, RequestBody.create({JPG_FILE}, MediaType.parse("image/jpeg")))
.addFormDataPart("sync", "1")
.build();
Request request = new Request.Builder()
.url("https://techsz.aoscdn.com/api/tasks/visual/segmentation")
.addHeader("X-API-KEY", "YOUR_API_KEY")
.post(requestBody)
.build();
Response response = okHttpClient.newCall(request).execute();
const request = require("request");
const fs = require("fs");
const path = require('path')
request(
{
method: "POST",
url: "https://techsz.aoscdn.com/api/tasks/visual/segmentation",
headers: {
"X-API-KEY": "YOUR_API_KEY",
},
formData: {
sync: "1",
image_file: fs.createReadStream(path.join(__dirname, './test.jpg')),
},
json: true
},
function (error, response) {
if (response.body.data) {
const { progress, state } = response.body.data
if (progress >= 100) {
return console.log(`result:`, response.body);
}
}
throw new Error(JSON.stringify(response.body, null, 2))
}
);
import os
import requests
API_KEY = 'YOUR_API_KEY'
IMAGE_FILE_PATH = 'YOUR_IMAGE_FILE_PATH'
def main():
assert os.path.exists(IMAGE_FILE_PATH), f'Error: File({IMAGE_FILE_PATH}) does not exist.'
headers = {'X-API-KEY': API_KEY}
data = {'sync': '1'}
files = {'image_file': open(IMAGE_FILE_PATH, 'rb')}
url = 'https://techsz.aoscdn.com/api/tasks/visual/segmentation'
# Create a task
response = requests.post(url, headers=headers, data=data, files=files)
response_json = response.json()
if 'status' in response_json and response_json['status'] == 200:
result_tag = 'failed'
if 'data' in response_json:
response_json_data = response_json['data']
if 'state' in response_json_data:
task_state = response_json_data['state']
# task success
if task_state == 1:
result_tag = 'successful'
elif task_state < 0:
# request failed, log the details
pass
else:
# Task processing, abnormal situation, seeking assistance from customer service of picwish
pass
print(f'Result({result_tag}): {response_json}')
else:
# request failed, log the details
print(f'Error: Failed to get the result,{response.text}')
if __name__ == "__main__":
main()
using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
public class Program
{
public static async Task Main()
{
string apiKey = "YOUR_API_KEY";
string url = "https://techsz.aoscdn.com/api/tasks/visual/segmentation";
string imagePath = "test.jpg";
string sync = "1";
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Add("X-API-KEY", apiKey);
using (var content = new MultipartFormDataContent())
{
var imageContent = new StreamContent(File.OpenRead(imagePath));
imageContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("image/jpeg");
content.Add(new StringContent(sync), "sync");
content.Add(imageContent, "image_file", Path.GetFileName(imagePath));
//User server initiates a request.
var response = await client.PostAsync(url, content);
var responseContent = await response.Content.ReadAsStringAsync();
if (response.IsSuccessStatusCode)
{
var responseData = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(responseContent);
var progress = (int)responseData.data.progress;
var state = (int)responseData.data.state;
if (progress >= 100)
{
//Task successful.
Console.WriteLine($"result: {responseContent}");
}
if (state == -1)
{
//Task processing, abnormal situation, seeking assistance from customer service of picwish
Console.WriteLine($"Error: {responseContent}");
}
}
else
{
//Task processing, abnormal situation, seeking assistance from customer service of picwish
Console.WriteLine($"Error: {responseContent}");
}
}
}
Console.ReadKey();
}
}
import Alamofire
import Foundation
let apiKey = "YOUR_API_KEY"
let url = "https://techsz.aoscdn.com/api/tasks/visual/segmentation"
let imagePath = Bundle.main.path(forResource: "test", ofType: "jpg")!
let sync = "1"
let headers: HTTPHeaders = [
"X-API-KEY": apiKey,
]
AF.upload(multipartFormData: { multipartFormData in
multipartFormData.append(Data(sync.utf8), withName: "sync")
multipartFormData.append(URL(fileURLWithPath: imagePath), withName: "image_file", fileName: "test.jpg", mimeType: "image/jpeg")
}, to: url, method: .post, headers: headers).responseJSON { response in
switch response.result {
case .success(let value):
if let jsonResponse = value as? [String: Any],
let data = jsonResponse["data"] as? [String: Any],
let progress = data["progress"] as? Int,
let state = data["state"] as? String {
if progress >= 100 {
print("Result: \(jsonResponse)")
}
}
case .failure(let error):
print("Error: \(error.localizedDescription)")
}
}
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"mime/multipart"
"net/http"
"os"
"path/filepath"
)
type VisualSegmentationResponse struct {
Status int `json:"status"`
Message string `json:"message"`
Data struct {
TaskId string `json:"task_id"`
Image string `json:"image"`
Mask string `json:"mask"`
MaskObj string `json:"mask_obj"`
ImageObj string `json:"image_obj"`
ReturnType uint `json:"return_type"`
OutputType uint `json:"output_type"`
Type string `json:"type"`
ResultType string `json:"result_type"`
TimeElapsed float64 `json:"time_elapsed"`
Progress uint `json:"progress"`
State int `json:"state"`
ImageWidth uint `json:"image_width"`
ImageHeight uint `json:"image_height"`
} `json:"data"`
}
func main() {
apiKey := "YOUR_API_KEY"
url := "https://techsz.aoscdn.com/api/tasks/visual/segmentation"
imagePath := "test.jpg"
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
_ = writer.WriteField("sync", "1")
file, err := os.Open(imagePath)
if err != nil {
fmt.Println("Error: ", err)
return
}
defer file.Close()
part, err := writer.CreateFormFile("image_file", filepath.Base(imagePath))
if err != nil {
fmt.Println("Error: ", err)
return
}
io.Copy(part, file)
writer.Close()
req, err := http.NewRequest("POST", url, body)
if err != nil {
fmt.Println("Error: ", err)
return
}
req.Header.Set("X-API-KEY", apiKey)
req.Header.Set("Content-Type", writer.FormDataContentType())
client := &http.Client{}
res, err := client.Do(req)
if err != nil {
fmt.Println("Error: ", err)
return
}
defer res.Body.Close()
respBody, err := ioutil.ReadAll(res.Body)
if err != nil {
fmt.Println("Error: ", err)
return
}
var taskResp VisualSegmentationResponse
err = json.Unmarshal(respBody, &taskResp)
if err != nil {
fmt.Println("Error parsing JSON:", err)
return
}
if taskResp.Status != http.StatusOK {
// Request from user server failed. Please record the relevant error logs.
fmt.Println("failed to get the result", taskResp)
} else {
if taskResp.Data.State == 1 {
//Task successful. Recorded in the database with task ID.
fmt.Println("result Successfully", taskResp)
} else {
// Task failed. Please record the relevant error logs.
fmt.Println("result falied", taskResp)
}
}
}
#Create a task.
curl -k 'https://techsz.aoscdn.com/api/tasks/visual/segmentation' \
-H 'X-API-KEY: YOUR_API_KEY' \
-F 'callback_url=YOUR_SERVER_URL' \
-F 'image_file=@/path/to/image.jpg'
#Curl is not suitable for writing callbacks. You need to use backend languages like Go to write callback functions to receive parameters.
<?php
//Create a task
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'https://techsz.aoscdn.com/api/tasks/visual/segmentation');
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
"X-API-KEY: YOUR_API_KEY",
"Content-Type: multipart/form-data",
));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_POSTFIELDS, array('sync' => 0,'callback_url' => "YOUR_URL", 'image_file' => new CURLFILE("/path/to/image.jpg")));
$response = curl_exec($curl);
$result = curl_errno($curl) ? curl_error($curl) : $response;
curl_close($curl);
$result = json_decode($result, true);
if ( !isset($result["status"]) || $result["status"] != 200 ) {
// request failed, log the details
var_dump($result);
die("post request failed");
}
// Record the task ID and store it in the database.
$task_id = $result["data"]["task_id"];
<?php
// Callback code.
// Original JSON data.
$jsonData = '{
"status": 200,
"message": "success",
"data": {
"task_id": "13cc3f64-6753-4a59-a06d-38946bc91144",
"image": "13cc3f64-6753-4a59-a06d-38946bc91144.jpg",
"state": 1
}
}';
// if needed,Decode JSON data.
$data = json_decode($jsonData, true);
if ( !isset($data["status"]) || $data["status"] != 200 ) {
// request failed, log the details
var_dump($data);
die("post request failed");
}
if ( $data["data"]["state"] == 1 ) {
// task success Store the image in the database based on the taskId.
var_dump($data["data"]["image"]);
} else if ( $data["data"]["state"] < 0) {
// request failed, log the details
var_dump($data);
} else {
//Task processing, abnormal situation, seeking assistance from customer service of picwish
}
OkHttpClient okHttpClient = new OkHttpClient.Builder().build();
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("image_file", JPG_FILE_NAME, RequestBody.create({JPG_FILE}, MediaType.parse("image/jpeg")))
.addFormDataPart("callback_url", "YOUR_SERVER_URL")
.build();
Request request = new Request.Builder()
.url("https://techsz.aoscdn.com/api/tasks/visual/segmentation")
.addHeader("X-API-KEY", "YOUR_API_KEY")
.post(requestBody)
.build();
Response response = okHttpClient.newCall(request).execute();
System.out.println("Response json string: " + response.body().string());
const request = require("request");
const fs = require("fs");
const path = require('path')
request(
{
method: "POST",
url: "https://techsz.aoscdn.com/api/tasks/visual/segmentation",
headers: {
"X-API-KEY": "YOUR_API_KEY",
},
formData: {
callback_url: "YOUR_SERVER_URL",
image_file: fs.createReadStream(path.join(__dirname, './test.jpg')),
},
json: true
},
function (error, response) {
if (response.body.data) {
console.log(response.body.data)
}
throw new Error(JSON.stringify(response.body, null, 2))
}
);
import os
import requests
API_KEY = 'YOUR_API_KEY'
IMAGE_FILE_PATH = 'YOUR_IMAGE_FILE_PATH'
SERVER_URL = 'YOUR_SERVER_URL'
def main():
assert os.path.exists(IMAGE_FILE_PATH), f'Error: File({IMAGE_FILE_PATH}) does not exist.'
headers = {'X-API-KEY': API_KEY}
data = {'callback_url': SERVER_URL}
files = {'image_file': open(IMAGE_FILE_PATH, 'rb')}
url = 'https://techsz.aoscdn.com/api/tasks/visual/segmentation'
# Create a task
response = requests.post(url, headers=headers, data=data, files=files)
response_json = response.json()
if 'status' in response_json and response_json['status'] == 200:
# Task successful. Recorded in the database with task ID.
print(f'Result(successful): {response_json}')
else:
# Request from user server failed. Please record the relevant error logs.
print(f'Error: Failed to get the result,{response.text}')
if __name__ == "__main__":
main()
using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
public class Program
{
public static async Task Main()
{
string apiKey = "YOUR_API_KEY";
string url = "https://techsz.aoscdn.com/api/tasks/visual/segmentation";
string imagePath = "test.jpg";
string callbackUrl = "YOUR_SERVER_URL";
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Add("X-API-KEY", apiKey);
using (var content = new MultipartFormDataContent())
{
var imageContent = new StreamContent(File.OpenRead(imagePath));
imageContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("image/jpeg");
content.Add(new StringContent(callbackUrl), "callback_url");
content.Add(imageContent, "image_file", Path.GetFileName(imagePath));
//User server initiates a request.
var response = await client.PostAsync(url, content);
var responseContent = await response.Content.ReadAsStringAsync();
if (response.IsSuccessStatusCode)
{
//Task successful.
var responseData = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(responseContent);
Console.WriteLine($"result: {responseContent}");
}
else
{
//Task processing, abnormal situation, seeking assistance from customer service of picwish
Console.WriteLine($"Error: {responseContent}");
}
}
}
Console.ReadKey();
}
}
import Alamofire
import Foundation
let apiKey = "YOUR_API_KEY"
let url = "https://techsz.aoscdn.com/api/tasks/visual/segmentation"
let imagePath = Bundle.main.path(forResource: "test", ofType: "jpg")!
let callbackUrl = "YOUR_SERVER_URL"
let headers: HTTPHeaders = [
"X-API-KEY": apiKey,
]
AF.upload(multipartFormData: { multipartFormData in
multipartFormData.append(Data(callbackUrl.utf8), withName: "callback_url")
multipartFormData.append(URL(fileURLWithPath: imagePath), withName: "image_file", fileName: "test.jpg", mimeType: "image/jpeg")
}, to: url, method: .post, headers: headers).responseJSON { response in
switch response.result {
case .success(let value):
print("Result: \(value)")
case .failure(let error):
print("Error: \(error.localizedDescription)")
}
}
// File 1: User server initiates a request.
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"mime/multipart"
"net/http"
"os"
"path/filepath"
)
type TaskResponse struct {
Status int `json:"status"`
Message string `json:"message"`
Data struct {
TaskId string `json:"task_id"`
} `json:"data"`
}
func main() {
apiKey := "YOUR_API_KEY"
url := "https://techsz.aoscdn.com/api/tasks/visual/segmentation"
imagePath := "test.jpg"
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
_ = writer.WriteField("callback_url", "YOUR_SERVER_URL")
file, err := os.Open(imagePath)
if err != nil {
fmt.Println("Error: ", err)
return
}
defer file.Close()
part, err := writer.CreateFormFile("image_file", filepath.Base(imagePath))
if err != nil {
fmt.Println("Error: ", err)
return
}
io.Copy(part, file)
writer.Close()
req, err := http.NewRequest("POST", url, body)
if err != nil {
fmt.Println("Error: ", err)
return
}
req.Header.Set("X-API-KEY", apiKey)
req.Header.Set("Content-Type", writer.FormDataContentType())
client := &http.Client{}
res, err := client.Do(req)
if err != nil {
fmt.Println("Error: ", err)
return
}
defer res.Body.Close()
respBody, err := ioutil.ReadAll(res.Body)
if err != nil {
fmt.Println("Error: ", err)
return
}
var taskResp TaskResponse
err = json.Unmarshal(respBody, &taskResp)
if err != nil {
fmt.Println("Error parsing JSON:", err)
return
}
if taskResp.Status != http.StatusOK {
// Request from user server failed. Please record the relevant error logs.
fmt.Println("failed to get the result", taskResp)
} else {
//Task successful. Recorded in the database with task ID.
fmt.Println("failed to get the result", taskResp)
}
}
// picwish server initiates a request to the user server, and the interface of the user server receives the parameters.
package main
import (
"encoding/json"
"fmt"
)
type VisualSegmentationResponse struct {
Status int `json:"status"`
Message string `json:"message"`
Data struct {
TaskId string `json:"task_id"`
Image string `json:"image"`
Mask string `json:"mask"`
MaskObj string `json:"mask_obj"`
ImageObj string `json:"image_obj"`
ReturnType uint `json:"return_type"`
OutputType uint `json:"output_type"`
Type string `json:"type"`
ResultType string `json:"result_type"`
TimeElapsed float64 `json:"time_elapsed"`
Progress uint `json:"progress"`
State int `json:"state"`
ImageWidth uint `json:"image_width"`
ImageHeight uint `json:"image_height"`
} `json:"data"`
}
func main() {
// JSON data is passed and received here, and code modification is required.
jsonData := `{
"status": 200,
"message": "Success",
"data": {
"task_id": "123456",
"image": "image_data",
"mask": "mask_data",
"mask_obj": "mask_obj_data",
"image_obj": "image_obj_data",
"return_type": 1,
"output_type": 1,
"type": "type_data",
"result_type": "result_type_data",
"time_elapsed": 2.5,
"progress": 100,
"state": 1,
"image_width": 800,
"image_height": 600
}
}`
// Parse JSON data into VisualSegmentationResponse struct
var response VisualSegmentationResponse
err := json.Unmarshal([]byte(jsonData), &response)
if err != nil {
fmt.Println("Error parsing JSON:", err)
return
}
// Query the relevant content in the database based on the taskID and associate it with the image below.
fmt.Println("Image:", response.Data.TaskId)
// Print the 'image' field
fmt.Println("Image:", response.Data.Image)
}