注意事项
- 接口返回的链接有效期为 1 小时,请及时下载存储。
文件格式要求
输入格式 | 输出格式 | 大小 |
---|---|---|
pdf, ppt, pptx, xls, xlsx, doc, docx, jpeg, jpg, png, gif, bmp | pdf, docx, pptx, xlsx, txt | 不超过 200 MB (含 200MB) |
快速开始
不同调用方式的区别&优缺点?
接口类型 | 请求方式 | 结果返回方式 | 优缺点 |
---|---|---|---|
异步 | 发送一个请求后,不需要实时等待服务器处理,通过轮询主动获取处理结果 | 通过轮询任务结果接口,查询处理结果 |
优点:在并发量大时,成功率高;在网络传输较慢或者不稳定时,处理成功率高。 缺点:相比同步,多一次接口调用。 |
同步 | 发送一个请求后,需要实时等待服务器处理,直到服务器返回处理结果 | 直接返回处理结果 |
优点:接入简单。 缺点:在并发量大时,成功率低;在网络传输较慢或者不稳定时,处理成功率低。 |
回调通知 | 发送一个请求后,不需要实时等待服务器处理,任务完成时,由服务商主动回调通知 | 填写回调地址后, 由服务商回调通知 |
优点:处理成功率最高。 缺点:需要有服务器和相应后端资源,才可以采用此方式。 |
异步调用时序图
同步调用时序图
回调通知时序图
#Create a task.
curl -k 'https://techsz.aoscdn.com/api/tasks/document/ocr' \
-H 'X-API-KEY: YOUR_API_KEY' \
-F 'image_url=YOU_IMG_URL'
-F 'format=txt'
#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 120 seconds
curl -k 'https://techsz.aoscdn.com/api/tasks/document/ocr/{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/document/ocr');
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,'format' => "txt", '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 120 seconds."
for ($i = 1; $i <= 120; $i++) {
if ($i != 1) {
sleep(1);
}
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "https://techsz.aoscdn.com/api/tasks/document/ocr/".$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"]["file"]);
break;
} else if ( $result["data"]["state"] < 0) {
// request failed, log the details
var_dump($result);
break;
} else {
// Task processing
if ($i == 120) {
//Task processing, abnormal situation, seeking assistance from customer service of picwish
}
}
}
public static void main(String[] args) throws Exception {
String taskId = createTask();
String result = pollingTaskResult(taskId, 0);
System.out.println(result);
}
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("format", "txt")
.addFormDataPart("sync", "0")
.build();
Request request = new Request.Builder()
.url("https://techsz.aoscdn.com/api/tasks/document/ocr")
.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 >= 120) throw new IllegalStateException("Polling result timeout.");
OkHttpClient okHttpClient = new OkHttpClient.Builder().build();
Request taskRequest = new Request.Builder()
.url("https://techsz.aoscdn.com/api/tasks/document/ocr/" + 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) { // Error.
throw new Exception(jsonObject.optString("message"));
}
if (state == 1) { // 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 = 120 * 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/document/ocr",
headers: {
"X-API-KEY": API_KEY,
},
formData: {
image_url: 'IMAGE_HTTP_URL',
format: 'txt'
},
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/document/ocr/${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 = {'format': 'txt', 'image_url': IMAGE_NETWORK_URL}
url = 'https://techsz.aoscdn.com/api/tasks/document/ocr'
# 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 120 seconds."
def polling_task_result(task_id,time_out=120):
headers = {'X-API-KEY': API_KEY}
url = f'https://techsz.aoscdn.com/api/tasks/document/ocr/{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/document/ocr";
private static string API_KEY = "YOUR_API_KEY";
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("txt"), "format");
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"]["file"] != 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");
}
}
#endif
import Alamofire
import Foundation
let API_KEY = "{YOUR_API_KEY}"
let BASE_URL = "https://techsz.aoscdn.com/api/tasks/document/ocr"
/// Begin task
func start() {
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 format = "txt".data(using: .utf8) {
multipartFormData.append(format, withName: "format")
}
}, 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 {
return
}
// Task successful
if state == 1 {
if let fileUrlStr = data["file"] as? String {
completion(["file": fileUrlStr])
return
}
}
// Retrieve the results by looping only 120 times
let endTime = CFAbsoluteTimeGetCurrent()
if endTime - taskStartTime < 120 {
// 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/document/ocr"
)
// taskResponse
type taskResponse struct {
Status int `json:"status"`
Message string `json:"message"`
Data struct {
TaskId string `json:"task_id"`
} `json:"data"`
}
type DocumentOcrResponse struct {
Status int `json:"status"`
Message string `json:"message"`
Data struct {
TaskId string `json:"task_id"`
File string `json:"file"`
Progress uint `json:"progress"`
State int `json:"state"`
Type int `json:"type"`
FilePages int `json:"file_pages,omitempty"`
OcrPages int `json:"ocr_pages,omitempty"`
InputSize int `json:"input_size,omitempty"`
OutputSize int `json:"output_size,omitempty"`
CreatedAt int64 `json:"created_at,omitempty"`
ProcessedAt int64 `json:"processed_at,omitempty"`
CompletedAt int64 `json:"completed_at,omitempty"`
Next g.Map `json:"next,omitempty"`
} `json:"data"`
}
func createTask() (string, error) {
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
_ = writer.WriteField("image_url", "YOUR_IMG_URL")
_ = writer.WriteField("format", "txt")
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) (*DocumentOcrResponse, 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 *DocumentOcrResponse
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 120 times.
for i := 0; i < 120; 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 == 59 {
// 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/document/ocr' \
-H 'X-API-KEY: YOUR_API_KEY' \
-F 'format=txt' \
-F 'callback_url=YOUR_SERVER_URL' \
-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/document/ocr');
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,'format' => "txt",'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",
"file": "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"]["file"]);
} 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")
.addFormDataPart("format", "txt")
.build();
Request request = new Request.Builder()
.url("https://techsz.aoscdn.com/api/tasks/document/ocr")
.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/document/ocr",
headers: {
"X-API-KEY": "YOUR_API_KEY",
},
formData: {
callback_url: "YOUR_SERVER_URL",
image_url: "IMAGE_HTTP_URL",
format: 'txt'
},
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, 'format': 'txt', 'image_url': IMAGE_NETWORK_URL}
url = 'https://techsz.aoscdn.com/api/tasks/document/ocr'
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/document/ocr";
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("txt"), "format");
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 API_KEY = "{YOUR_API_KEY}"
let BASE_URL = "https://techsz.aoscdn.com/api/tasks/document/ocr"
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 = "YOUR_SERVER_URL".data(using: .utf8) {
multipartFormData.append(data, withName: "callback_url")
}
if let format = "txt".data(using: .utf8) {
multipartFormData.append(format, withName: "format")
}
}, 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)
}
}
}
// 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 TestocrTechApi(t *testing.T) {
url := "https://techsz.aoscdn.com/api/tasks/document/ocr"
payload := &bytes.Buffer{}
writer := multipart.NewWriter(payload)
_ = writer.WriteField("callback_url", "YOUR_SERVER_URL")
_ = writer.WriteField("image_url", "YOUR_IMG_URL")
_ = writer.WriteField("format", "txt")
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 DocumentOcrResponse struct {
Status int `json:"status"`
Message string `json:"message"`
Data struct {
TaskId string `json:"task_id"`
File string `json:"file"`
Progress uint `json:"progress"`
State int `json:"state"`
Type int `json:"type"`
FilePages int `json:"file_pages,omitempty"`
OcrPages int `json:"ocr_pages,omitempty"`
InputSize int `json:"input_size,omitempty"`
OutputSize int `json:"output_size,omitempty"`
CreatedAt int64 `json:"created_at,omitempty"`
ProcessedAt int64 `json:"processed_at,omitempty"`
CompletedAt int64 `json:"completed_at,omitempty"`
Next g.Map `json:"next,omitempty"`
} `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",
"file": "file_data",
}
}`
// Parse JSON data into DocumentOcrResponse struct
var response DocumentOcrResponse
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.File)
}
#Create a task
curl -k 'https://techsz.aoscdn.com/api/tasks/document/ocr' \
-H 'X-API-KEY: YOUR_API_KEY' \
-F 'image_file=@/path/to/image.jpg'
-F 'format=txt'
#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 120 seconds
curl -k 'https://techsz.aoscdn.com/api/tasks/visual/document/ocr/{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/document/ocr');
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,'format' => "txt", '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 120 seconds."
for ($i = 1; $i <= 120; $i++) {
if ($i != 1) {
sleep(1);
}
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "https://techsz.aoscdn.com/api/tasks/document/ocr/".$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"]["file"]);
break;
} else if ( $result["data"]["state"] < 0) {
// request failed, log the details
var_dump($result);
break;
} else {
// Task processing
if ($i == 120) {
//Task processing, abnormal situation, seeking assistance from customer service of picwish
}
}
}
public static void main(String[] args) throws Exception {
String taskId = createTask();
String result = pollingTaskResult(taskId, 0);
System.out.println(result);
}
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("format", "txt")
.addFormDataPart("sync", "0")
.build();
Request request = new Request.Builder()
.url("https://techsz.aoscdn.com/api/tasks/document/ocr")
.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 >= 120) throw new IllegalStateException("Polling result timeout.");
OkHttpClient okHttpClient = new OkHttpClient.Builder().build();
Request taskRequest = new Request.Builder()
.url("https://techsz.aoscdn.com/api/tasks/document/ocr/" + 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) { // Error.
throw new Exception(jsonObject.optString("message"));
}
if (state == 1) { // 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 = 120 * 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/document/ocr",
headers: {
"X-API-KEY": API_KEY,
},
formData: {
image_file: fs.createReadStream(path.join(__dirname, './test.jpg')),
format: 'txt'
},
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/document/ocr/${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 = {'format': 'txt'}
files = {'image_file': open(IMAGE_FILE_PATH, 'rb')}
url = 'https://techsz.aoscdn.com/api/tasks/document/ocr'
# 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 120 seconds."
def polling_task_result(task_id,time_out=120):
headers = {'X-API-KEY': API_KEY}
url = f'https://techsz.aoscdn.com/api/tasks/document/ocr/{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/document/ocr";
private static string API_KEY = "YOUR_API_KEY";
private static string imagePath = "test.jpg";
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();
var fileStream = File.OpenRead(imagePath);
multipartContent.Add(new StreamContent(fileStream), "image_file", Path.GetFileName(imagePath));
multipartContent.Add(new StringContent("txt"), "format");
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"]["file"] != 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");
}
}
#endif
import Alamofire
import Foundation
let API_KEY = "{YOUR_API_KEY}"
let BASE_URL = "https://techsz.aoscdn.com/api/tasks/document/ocr"
/// Begin task
func start() {
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 format = "txt".data(using: .utf8) {
multipartFormData.append(format, withName: "format")
}
}, 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 {
return
}
// Task successful
if state == 1 {
if let fileUrlStr = data["file"] as? String {
completion(["file": fileUrlStr])
return
}
}
// Retrieve the results by looping only 120 times
let endTime = CFAbsoluteTimeGetCurrent()
if endTime - taskStartTime < 120 {
// 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"
_ "encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"mime/multipart"
"net/http"
"os"
"path/filepath"
"time"
)
const (
APIKey = "YOUR_API_KEY"
BaseURL = "https://techsz.aoscdn.com/api/tasks/document/ocr"
)
// taskResponse
type taskResponse struct {
Status int `json:"status"`
Message string `json:"message"`
Data struct {
TaskId string `json:"task_id"`
} `json:"data"`
}
type DocumentOcrResponse struct {
Status int `json:"status"`
Message string `json:"message"`
Data struct {
TaskId string `json:"task_id"`
File string `json:"file"`
Progress uint `json:"progress"`
State int `json:"state"`
Type int `json:"type"`
FilePages int `json:"file_pages,omitempty"`
OcrPages int `json:"ocr_pages,omitempty"`
InputSize int `json:"input_size,omitempty"`
OutputSize int `json:"output_size,omitempty"`
CreatedAt int64 `json:"created_at,omitempty"`
ProcessedAt int64 `json:"processed_at,omitempty"`
CompletedAt int64 `json:"completed_at,omitempty"`
Next g.Map `json:"next,omitempty"`
} `json:"data"`
}
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"))
_ = writer.WriteField("format", "txt")
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 taskResp *taskResponse
err = json.Unmarshal(respBody, &taskResp)
if err != nil {
fmt.Println("Error parsing JSON:", err)
return "", err
}
if err != nil {
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) (*DocumentOcrResponse, 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 *DocumentOcrResponse
err = json.Unmarshal(respBody, &taskResp)
if err != nil {
fmt.Println("Error parsing JSON:", err)
return nil, err
}
if err != nil {
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 120 times.
for i := 0; i < 120; 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 == 59 {
// 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/document/ocr' \
-H 'X-API-KEY: YOUR_API_KEY' \
-F 'callback_url=YOUR_SERVER_URL' \
-F 'image_file=@/path/to/image.jpg'
-F 'format=txt'
#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/document/ocr');
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,'format' => "txt",'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",
"file": "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"]["file"]);
} 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")
.addFormDataPart("format", "txt")
.build();
Request request = new Request.Builder()
.url("https://techsz.aoscdn.com/api/tasks/document/ocr")
.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/document/ocr",
headers: {
"X-API-KEY": "YOUR_API_KEY",
},
formData: {
callback_url: "YOUR_SERVER_URL",
format: "txt",
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, 'format': 'txt'}
files = {'image_file': open(IMAGE_FILE_PATH, 'rb')}
url = 'https://techsz.aoscdn.com/api/tasks/document/ocr'
# 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/document/ocr";
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));
content.Add(new StringContent("txt"), "format");
//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 API_KEY = "{YOUR_API_KEY}"
let BASE_URL = "https://techsz.aoscdn.com/api/tasks/document/ocr"
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 = "{YOUR_SERVER_URL}".data(using: .utf8) {
multipartFormData.append(data, withName: "callback_url")
}
if let format = "txt".data(using: .utf8) {
multipartFormData.append(format, withName: "format")
}
}, 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)
}
}
}
// 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/document/ocr"
imagePath := "test.jpg"
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
_ = writer.WriteField("callback_url", "YOUR_SERVER_URL")
_ = writer.WriteField("format", "txt")
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 DocumentOcrResponse struct {
Status int `json:"status"`
Message string `json:"message"`
Data struct {
TaskId string `json:"task_id"`
File string `json:"file"`
Progress uint `json:"progress"`
State int `json:"state"`
Type int `json:"type"`
FilePages int `json:"file_pages,omitempty"`
OcrPages int `json:"ocr_pages,omitempty"`
InputSize int `json:"input_size,omitempty"`
OutputSize int `json:"output_size,omitempty"`
CreatedAt int64 `json:"created_at,omitempty"`
ProcessedAt int64 `json:"processed_at,omitempty"`
CompletedAt int64 `json:"completed_at,omitempty"`
Next g.Map `json:"next,omitempty"`
} `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",
"file": "file_data",
}
}`
// Parse JSON data into DocumentOcrResponse struct
var response DocumentOcrResponse
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.File)
}