├── .gitignore
├── src
└── main
│ └── java
│ └── com
│ └── baidu
│ └── aip
│ ├── nlp
│ ├── EWsegType.java
│ ├── NlpLangId.java
│ ├── ESimnetType.java
│ ├── NlpConsts.java
│ └── AipNlp.java
│ ├── http
│ ├── HttpMethodName.java
│ ├── EBodyFormat.java
│ ├── HttpCharacterEncoding.java
│ ├── HttpContentType.java
│ ├── AipResponse.java
│ ├── Headers.java
│ ├── AipHttpClient.java
│ └── AipRequest.java
│ ├── contentcensor
│ ├── EImgType.java
│ ├── ContentCensorConsts.java
│ └── AipContentCensor.java
│ ├── client
│ ├── EAuthState.java
│ └── BaseClient.java
│ ├── speech
│ ├── SpeechConsts.java
│ ├── TtsResponse.java
│ └── AipSpeech.java
│ ├── imageprocess
│ ├── ImageProcessConsts.java
│ └── AipImageProcess.java
│ ├── kg
│ ├── KnowledgeGraphicConsts.java
│ └── AipKnowledgeGraphic.java
│ ├── exception
│ └── AipException.java
│ ├── bodyanalysis
│ ├── BodyAnalysisConsts.java
│ └── AipBodyAnalysis.java
│ ├── face
│ ├── FaceVerifyRequest.java
│ ├── MatchRequest.java
│ ├── FaceConsts.java
│ └── AipFace.java
│ ├── util
│ ├── AipClientConst.java
│ ├── AipClientConfiguration.java
│ ├── SignUtil.java
│ ├── ImageUtil.java
│ ├── Base64Util.java
│ └── Util.java
│ ├── imageclassify
│ └── ImageClassifyConsts.java
│ ├── error
│ └── AipError.java
│ ├── imagesearch
│ └── ImageSearchConsts.java
│ ├── auth
│ ├── DevAuth.java
│ └── CloudAuth.java
│ ├── easydl
│ └── AipEasyDL.java
│ └── ocr
│ └── OcrConsts.java
├── README.md
├── pom.xml
└── LICENSE
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | */META-INF/
3 | */target/
4 | out/
5 | .idea/
6 | *.gif
7 | *.GIF
8 | *.jpg
9 | *.JPG
10 | *.log
11 | *.md5
12 |
--------------------------------------------------------------------------------
/src/main/java/com/baidu/aip/nlp/EWsegType.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2017 Baidu, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
5 | * the License. You may obtain a copy of the License at
6 | *
7 | * http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
10 | * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
11 | * specific language governing permissions and limitations under the License.
12 | */
13 | package com.baidu.aip.nlp;
14 |
15 | public enum EWsegType {
16 | BASIC, WPCOMP
17 | }
18 |
--------------------------------------------------------------------------------
/src/main/java/com/baidu/aip/http/HttpMethodName.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2017 Baidu, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
5 | * the License. You may obtain a copy of the License at
6 | *
7 | * http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
10 | * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
11 | * specific language governing permissions and limitations under the License.
12 | */
13 | package com.baidu.aip.http;
14 |
15 | public enum HttpMethodName {
16 | GET, POST, PUT, DELETE, HEAD;
17 | }
--------------------------------------------------------------------------------
/src/main/java/com/baidu/aip/contentcensor/EImgType.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2017 Baidu, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
5 | * the License. You may obtain a copy of the License at
6 | *
7 | * http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
10 | * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
11 | * specific language governing permissions and limitations under the License.
12 | */
13 | package com.baidu.aip.contentcensor;
14 |
15 | public enum EImgType {
16 | FILE,
17 | URL
18 | }
19 |
--------------------------------------------------------------------------------
/src/main/java/com/baidu/aip/http/EBodyFormat.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2017 Baidu, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
5 | * the License. You may obtain a copy of the License at
6 | *
7 | * http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
10 | * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
11 | * specific language governing permissions and limitations under the License.
12 | */
13 | package com.baidu.aip.http;
14 |
15 | public enum EBodyFormat {
16 | FORM_KV, RAW_JSON, RAW_JSON_ARRAY
17 | }
18 |
--------------------------------------------------------------------------------
/src/main/java/com/baidu/aip/nlp/NlpLangId.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2017 Baidu, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
5 | * the License. You may obtain a copy of the License at
6 | *
7 | * http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
10 | * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
11 | * specific language governing permissions and limitations under the License.
12 | */
13 | package com.baidu.aip.nlp;
14 |
15 | public class NlpLangId {
16 | public static final int LANG_CHINESE = 1;
17 | }
18 |
--------------------------------------------------------------------------------
/src/main/java/com/baidu/aip/client/EAuthState.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2017 Baidu, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
5 | * the License. You may obtain a copy of the License at
6 | *
7 | * http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
10 | * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
11 | * specific language governing permissions and limitations under the License.
12 | */
13 | package com.baidu.aip.client;
14 |
15 | public enum EAuthState {
16 | STATE_UNKNOWN, STATE_AIP_AUTH_OK, STATE_TRUE_AIP_USER,
17 | STATE_POSSIBLE_CLOUD_USER, STATE_TRUE_CLOUD_USER
18 | }
19 |
--------------------------------------------------------------------------------
/src/main/java/com/baidu/aip/speech/SpeechConsts.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2017 Baidu, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
5 | * the License. You may obtain a copy of the License at
6 | *
7 | * http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
10 | * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
11 | * specific language governing permissions and limitations under the License.
12 | */
13 | package com.baidu.aip.speech;
14 |
15 | public class SpeechConsts {
16 |
17 | static final String SPEECH_ASR_URL = "http://vop.baidu.com/server_api";
18 | static final String SPEECH_TTS_URL = "http://tsn.baidu.com/text2audio";
19 | }
20 |
--------------------------------------------------------------------------------
/src/main/java/com/baidu/aip/http/HttpCharacterEncoding.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2017 Baidu, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
5 | * the License. You may obtain a copy of the License at
6 | *
7 | * http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
10 | * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
11 | * specific language governing permissions and limitations under the License.
12 | */
13 | package com.baidu.aip.http;
14 |
15 | public class HttpCharacterEncoding {
16 | public static final String DEFAULT_ENCODING = "UTF8";
17 | public static final String ENCODE_UTF8 = "UTF8";
18 | public static final String ENCODE_GBK = "GBK";
19 | }
20 |
--------------------------------------------------------------------------------
/src/main/java/com/baidu/aip/http/HttpContentType.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2017 Baidu, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
5 | * the License. You may obtain a copy of the License at
6 | *
7 | * http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
10 | * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
11 | * specific language governing permissions and limitations under the License.
12 | */
13 | package com.baidu.aip.http;
14 |
15 | public interface HttpContentType {
16 |
17 | public static final String FORM_DATA = "multipart/form-data";
18 | public static final String JSON_DATA = "application/json";
19 | public static final String FORM_URLENCODE_DATA = "application/x-www-form-urlencoded";
20 | }
21 |
--------------------------------------------------------------------------------
/src/main/java/com/baidu/aip/nlp/ESimnetType.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2017 Baidu, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
5 | * the License. You may obtain a copy of the License at
6 | *
7 | * http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
10 | * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
11 | * specific language governing permissions and limitations under the License.
12 | */
13 | package com.baidu.aip.nlp;
14 |
15 | public enum ESimnetType {
16 | UNSUPPORT_TYPE,
17 | HOTEL, // 酒店 = 1
18 | KTV, // KTV = 2
19 | BEAUTY, // 丽人 = 3
20 | FOOD, // 美食(默认) = 4
21 | TRAVEL, // 旅游 = 5
22 | HEALTH, // 健康 = 6
23 | EDU, // 教育 = 7
24 | BUSINESS, // 商业 = 8
25 | HOUSE, // 房产 = 9
26 | CAR, // 汽车 = 10
27 | LIFE, // 生活 = 11
28 | SHOPPING, // 购物 = 12
29 | _3C // 3C = 13
30 | }
31 |
--------------------------------------------------------------------------------
/src/main/java/com/baidu/aip/speech/TtsResponse.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2017 Baidu, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
5 | * the License. You may obtain a copy of the License at
6 | *
7 | * http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
10 | * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
11 | * specific language governing permissions and limitations under the License.
12 | */
13 | package com.baidu.aip.speech;
14 |
15 | import org.json.JSONObject;
16 |
17 | public class TtsResponse {
18 | private JSONObject result;
19 | private byte[] data;
20 |
21 | public JSONObject getResult() {
22 | return result;
23 | }
24 |
25 | public void setResult(JSONObject result) {
26 | this.result = result;
27 | }
28 |
29 |
30 | public byte[] getData() {
31 | return data;
32 | }
33 |
34 | public void setData(byte[] data) {
35 | this.data = data;
36 | }
37 |
38 | }
39 |
--------------------------------------------------------------------------------
/src/main/java/com/baidu/aip/imageprocess/ImageProcessConsts.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2017 Baidu, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
5 | * the License. You may obtain a copy of the License at
6 | *
7 | * http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
10 | * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
11 | * specific language governing permissions and limitations under the License.
12 | */
13 |
14 | package com.baidu.aip.imageprocess;
15 |
16 | public class ImageProcessConsts {
17 |
18 | static final String IMAGE_QUALITY_ENHANCE = "https://aip.baidubce.com/rest/2.0/image-process/v1/image_quality_enhance";
19 |
20 | static final String DEHAZE = "https://aip.baidubce.com/rest/2.0/image-process/v1/dehaze";
21 |
22 | static final String CONTRAST_ENHANCE = "https://aip.baidubce.com/rest/2.0/image-process/v1/contrast_enhance";
23 |
24 | static final String COLOURIZE = "https://aip.baidubce.com/rest/2.0/image-process/v1/colourize";
25 |
26 | static final String STRETCH_RESTORE = "https://aip.baidubce.com/rest/2.0/image-process/v1/stretch_restore";
27 |
28 | }
--------------------------------------------------------------------------------
/src/main/java/com/baidu/aip/kg/KnowledgeGraphicConsts.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2017 Baidu, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
5 | * the License. You may obtain a copy of the License at
6 | *
7 | * http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
10 | * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
11 | * specific language governing permissions and limitations under the License.
12 | */
13 |
14 | package com.baidu.aip.kg;
15 |
16 | public class KnowledgeGraphicConsts {
17 |
18 | static final String CREATE_TASK = "https://aip.baidubce.com/rest/2.0/kg/v1/pie/task_create";
19 |
20 | static final String UPDATE_TASK = "https://aip.baidubce.com/rest/2.0/kg/v1/pie/task_update";
21 |
22 | static final String TASK_INFO = "https://aip.baidubce.com/rest/2.0/kg/v1/pie/task_info";
23 |
24 | static final String TASK_QUERY = "https://aip.baidubce.com/rest/2.0/kg/v1/pie/task_query";
25 |
26 | static final String TASK_START = "https://aip.baidubce.com/rest/2.0/kg/v1/pie/task_start";
27 |
28 | static final String TASK_STATUS = "https://aip.baidubce.com/rest/2.0/kg/v1/pie/task_status";
29 |
30 | }
--------------------------------------------------------------------------------
/src/main/java/com/baidu/aip/exception/AipException.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2017 Baidu, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
5 | * the License. You may obtain a copy of the License at
6 | *
7 | * http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
10 | * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
11 | * specific language governing permissions and limitations under the License.
12 | */
13 | package com.baidu.aip.exception;
14 |
15 | public class AipException extends Exception {
16 |
17 | private String errorMsg;
18 | private int errorCode;
19 |
20 | public AipException(int code, String msg) {
21 | errorCode = code;
22 | errorMsg = msg;
23 | }
24 |
25 | public AipException(int code, Throwable e) {
26 | errorCode = code;
27 | errorMsg = e.getMessage();
28 | }
29 |
30 | public String getErrorMsg() {
31 | return errorMsg;
32 | }
33 |
34 | public void setErrorMsg(String errorMsg) {
35 | this.errorMsg = errorMsg;
36 | }
37 |
38 | public int getErrorCode() {
39 | return errorCode;
40 | }
41 |
42 | public void setErrorCode(int errorCode) {
43 | this.errorCode = errorCode;
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/src/main/java/com/baidu/aip/bodyanalysis/BodyAnalysisConsts.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2017 Baidu, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
5 | * the License. You may obtain a copy of the License at
6 | *
7 | * http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
10 | * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
11 | * specific language governing permissions and limitations under the License.
12 | */
13 |
14 | package com.baidu.aip.bodyanalysis;
15 |
16 | public class BodyAnalysisConsts {
17 |
18 | static final String BODY_ANALYSIS = "https://aip.baidubce.com/rest/2.0/image-classify/v1/body_analysis";
19 |
20 | static final String BODY_ATTR = "https://aip.baidubce.com/rest/2.0/image-classify/v1/body_attr";
21 |
22 | static final String BODY_NUM = "https://aip.baidubce.com/rest/2.0/image-classify/v1/body_num";
23 |
24 | static final String GESTURE = "https://aip.baidubce.com/rest/2.0/image-classify/v1/gesture";
25 |
26 | static final String BODY_SEG = "https://aip.baidubce.com/rest/2.0/image-classify/v1/body_seg";
27 |
28 | static final String DRIVER_BEHAVIOR = "https://aip.baidubce.com/rest/2.0/image-classify/v1/driver_behavior";
29 |
30 | static final String BODY_TRACKING = "https://aip.baidubce.com/rest/2.0/image-classify/v1/body_tracking";
31 |
32 | }
--------------------------------------------------------------------------------
/src/main/java/com/baidu/aip/face/FaceVerifyRequest.java:
--------------------------------------------------------------------------------
1 | package com.baidu.aip.face;
2 |
3 | import org.json.JSONObject;
4 |
5 | public class FaceVerifyRequest {
6 | private String image;
7 | private String imageType;
8 | private String faceField;
9 |
10 | public FaceVerifyRequest(String image, String imageType) {
11 | this.image = image;
12 | this.imageType = imageType;
13 | this.faceField = null;
14 | }
15 |
16 | public FaceVerifyRequest(String image, String imageType, String faceField) {
17 | this.image = image;
18 | this.imageType = imageType;
19 | this.faceField = faceField;
20 | }
21 |
22 | public JSONObject toJsonObject() {
23 | JSONObject obj = new JSONObject();
24 | obj.put("image", this.image);
25 | obj.put("image_type", this.imageType);
26 | if (this.faceField != null) {
27 | obj.put("face_field", this.faceField);
28 | }
29 | return obj;
30 | }
31 |
32 | public String getImage() {
33 | return image;
34 | }
35 |
36 | public String getImageType() {
37 | return imageType;
38 | }
39 |
40 | public String getFaceField() {
41 | return faceField;
42 | }
43 |
44 | public void setImage(String image) {
45 | this.image = image;
46 | }
47 |
48 | public void setImageType(String imageType) {
49 | this.imageType = imageType;
50 | }
51 |
52 | public void setFaceField(String faceField) {
53 | this.faceField = faceField;
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | ## 安装Java SDK
2 |
3 | **Java SDK主要目录结构**
4 |
5 | com.baidu.aip
6 | ├── auth //签名相关类
7 | ├── http //Http通信相关类
8 | ├── client //公用类
9 | ├── exception //exception类
10 | ├── ocr
11 | │ └── AipOcr //OCR服务入口
12 | ├── face
13 | │ └── AipFace //人脸服务入口
14 | ├── imagecensor
15 | │ └── AipImageCensor //图像审核服务入口
16 | ├── imageclassify
17 | │ └── AipImageClassify //图像识别服务入口
18 | ├── imageprocess
19 | │ └── AipImageProcess //图像处理服务入口
20 | ├── nlp
21 | │ └── AipNlp //Nlp服务入口
22 | ├── kg
23 | │ └── AipKnowledgeGraphic //知识图谱服务入口
24 | ├── speech
25 | │ └── AipSpeech //语音服务入口
26 | └── util //工具类
27 |
28 | **支持 JAVA版本:1.7+**
29 |
30 | **直接使用JAR包步骤如下:**
31 |
32 | 1.在[官方网站](http://ai.baidu.com/sdk)下载Java SDK压缩工具包。
33 |
34 | 2.将下载的`aip-java-sdk-version.zip`解压后,复制到工程文件夹中。
35 |
36 | 3.在Eclipse右键“工程 -> Properties -> Java Build Path -> Add JARs”。
37 |
38 | 4.添加SDK工具包`aip-java-sdk-version.jar`和第三方依赖工具包`json-20160810.jar`。
39 |
40 | 其中,`version`为版本号,添加完成后,用户就可以在工程中使用OCR Java SDK。
41 |
42 |
43 | **使用maven依赖:**
44 |
45 | 添加以下依赖:
46 |
47 | ```
48 |
49 | com.baidu.aip
50 | java-sdk
51 | 4.8.0
52 |
53 | ```
54 |
55 |
56 |
57 | ## 详细使用文档
58 |
59 | 参考[百度AI开放平台官方文档](http://ai.baidu.com/docs)
60 |
61 |
--------------------------------------------------------------------------------
/src/main/java/com/baidu/aip/util/AipClientConst.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2017 Baidu, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
5 | * the License. You may obtain a copy of the License at
6 | *
7 | * http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
10 | * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
11 | * specific language governing permissions and limitations under the License.
12 | */
13 | package com.baidu.aip.util;
14 |
15 | import java.util.Arrays;
16 | import java.util.HashSet;
17 | import java.util.List;
18 |
19 | public class AipClientConst {
20 |
21 | // for cloudAuth
22 | public static final Integer BCE_AUTH_EXPIRE_IN_SECONDS = 1800; // 30min
23 | public static final HashSet BCE_HEADER_TO_SIGN =
24 | new HashSet(Arrays.asList("host", "content-md5", "content-length", "content-type"));
25 | public static final String BCE_PREFIX = "x-bce-";
26 |
27 | // for openapi
28 | public static final String OAUTH_URL = "https://aip.baidubce.com/oauth/2.0/token";
29 |
30 | // encoding
31 | public static final String DEFAULT_ENCODING = "UTF8";
32 | public static final String ENCODING_GBK = "GBK";
33 |
34 | // openAPI access right
35 | public static final List AI_ACCESS_RIGHT =
36 | Arrays.asList(
37 | "audio_voice_assistant_get", // speech
38 | "audio_tts_post",
39 | "brain_all_scope");
40 |
41 |
42 | public static final Integer IAM_ERROR_CODE = 14;
43 | public static final Integer OPENAPI_NO_ACCESS_ERROR_CODE = 6;
44 | public static final String OPENAPI_NO_ACCESS_ERROR_MSG = "No permission to access data";
45 |
46 | public static final String LOG4J_CONF_PROPERTY = "aip.log4j.conf";
47 | }
48 |
--------------------------------------------------------------------------------
/src/main/java/com/baidu/aip/nlp/NlpConsts.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2017 Baidu, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
5 | * the License. You may obtain a copy of the License at
6 | *
7 | * http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
10 | * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
11 | * specific language governing permissions and limitations under the License.
12 | */
13 |
14 | package com.baidu.aip.nlp;
15 |
16 | public class NlpConsts {
17 |
18 | static final String LEXER = "https://aip.baidubce.com/rpc/2.0/nlp/v1/lexer";
19 |
20 | static final String LEXER_CUSTOM = "https://aip.baidubce.com/rpc/2.0/nlp/v1/lexer_custom";
21 |
22 | static final String DEP_PARSER = "https://aip.baidubce.com/rpc/2.0/nlp/v1/depparser";
23 |
24 | static final String WORD_EMBEDDING = "https://aip.baidubce.com/rpc/2.0/nlp/v2/word_emb_vec";
25 |
26 | static final String DNNLM_CN = "https://aip.baidubce.com/rpc/2.0/nlp/v2/dnnlm_cn";
27 |
28 | static final String WORD_SIM_EMBEDDING = "https://aip.baidubce.com/rpc/2.0/nlp/v2/word_emb_sim";
29 |
30 | static final String SIMNET = "https://aip.baidubce.com/rpc/2.0/nlp/v2/simnet";
31 |
32 | static final String COMMENT_TAG = "https://aip.baidubce.com/rpc/2.0/nlp/v2/comment_tag";
33 |
34 | static final String SENTIMENT_CLASSIFY = "https://aip.baidubce.com/rpc/2.0/nlp/v1/sentiment_classify";
35 |
36 | static final String KEYWORD = "https://aip.baidubce.com/rpc/2.0/nlp/v1/keyword";
37 |
38 | static final String TOPIC = "https://aip.baidubce.com/rpc/2.0/nlp/v1/topic";
39 |
40 | static final String ECNET = "https://aip.baidubce.com/rpc/2.0/nlp/v1/ecnet";
41 |
42 | static final String EMOTION = "https://aip.baidubce.com/rpc/2.0/nlp/v1/emotion";
43 |
44 | static final String NEWS_SUMMARY = "https://aip.baidubce.com/rpc/2.0/nlp/v1/news_summary";
45 |
46 | }
--------------------------------------------------------------------------------
/src/main/java/com/baidu/aip/imageclassify/ImageClassifyConsts.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2017 Baidu, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
5 | * the License. You may obtain a copy of the License at
6 | *
7 | * http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
10 | * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
11 | * specific language governing permissions and limitations under the License.
12 | */
13 |
14 | package com.baidu.aip.imageclassify;
15 |
16 | public class ImageClassifyConsts {
17 |
18 | static final String ADVANCED_GENERAL = "https://aip.baidubce.com/rest/2.0/image-classify/v2/advanced_general";
19 |
20 | static final String DISH_DETECT = "https://aip.baidubce.com/rest/2.0/image-classify/v2/dish";
21 |
22 | static final String CAR_DETECT = "https://aip.baidubce.com/rest/2.0/image-classify/v1/car";
23 |
24 | static final String LOGO_SEARCH = "https://aip.baidubce.com/rest/2.0/image-classify/v2/logo";
25 |
26 | static final String LOGO_ADD = "https://aip.baidubce.com/rest/2.0/realtime_search/v1/logo/add";
27 |
28 | static final String LOGO_DELETE = "https://aip.baidubce.com/rest/2.0/realtime_search/v1/logo/delete";
29 |
30 | static final String ANIMAL_DETECT = "https://aip.baidubce.com/rest/2.0/image-classify/v1/animal";
31 |
32 | static final String PLANT_DETECT = "https://aip.baidubce.com/rest/2.0/image-classify/v1/plant";
33 |
34 | static final String OBJECT_DETECT = "https://aip.baidubce.com/rest/2.0/image-classify/v1/object_detect";
35 |
36 | static final String LANDMARK = "https://aip.baidubce.com/rest/2.0/image-classify/v1/landmark";
37 |
38 | static final String FLOWER = "https://aip.baidubce.com/rest/2.0/image-classify/v1/flower";
39 |
40 | static final String INGREDIENT = "https://aip.baidubce.com/rest/2.0/image-classify/v1/classify/ingredient";
41 |
42 | static final String REDWINE = "https://aip.baidubce.com/rest/2.0/image-classify/v1/redwine";
43 |
44 | static final String CURRENCY = "https://aip.baidubce.com/rest/2.0/image-classify/v1/currency";
45 |
46 | }
--------------------------------------------------------------------------------
/src/main/java/com/baidu/aip/util/AipClientConfiguration.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2017 Baidu, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
5 | * the License. You may obtain a copy of the License at
6 | *
7 | * http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
10 | * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
11 | * specific language governing permissions and limitations under the License.
12 | */
13 | package com.baidu.aip.util;
14 |
15 |
16 | import java.net.InetSocketAddress;
17 | import java.net.Proxy;
18 | import java.net.SocketAddress;
19 |
20 | public class AipClientConfiguration {
21 |
22 | // 连接超时设置
23 | private int connectionTimeoutMillis;
24 | private int socketTimeoutMillis;
25 | private Proxy proxy;
26 |
27 | public AipClientConfiguration() {
28 | this.connectionTimeoutMillis = 0;
29 | this.socketTimeoutMillis = 0;
30 | this.proxy = Proxy.NO_PROXY;
31 | }
32 |
33 | public AipClientConfiguration(int connectionTimeoutMillis, int socketTimeoutMillis, Proxy proxy) {
34 | this.connectionTimeoutMillis = connectionTimeoutMillis;
35 | this.socketTimeoutMillis = socketTimeoutMillis;
36 | this.proxy = proxy;
37 | }
38 |
39 | public int getConnectionTimeoutMillis() {
40 | return connectionTimeoutMillis;
41 | }
42 |
43 | public void setConnectionTimeoutMillis(int connectionTimeoutMillis) {
44 | this.connectionTimeoutMillis = connectionTimeoutMillis;
45 | }
46 |
47 | public int getSocketTimeoutMillis() {
48 | return socketTimeoutMillis;
49 | }
50 |
51 | public void setSocketTimeoutMillis(int socketTimeoutMillis) {
52 | this.socketTimeoutMillis = socketTimeoutMillis;
53 | }
54 |
55 | public Proxy getProxy() {
56 | return proxy;
57 | }
58 |
59 | public void setProxy(Proxy proxy) {
60 | this.proxy = proxy;
61 | }
62 |
63 | public void setProxy(String host, int port, Proxy.Type type) {
64 | SocketAddress addr = new InetSocketAddress(host, port);
65 | this.proxy = new Proxy(type, addr);
66 | }
67 | }
68 |
--------------------------------------------------------------------------------
/src/main/java/com/baidu/aip/error/AipError.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2017 Baidu, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
5 | * the License. You may obtain a copy of the License at
6 | *
7 | * http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
10 | * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
11 | * specific language governing permissions and limitations under the License.
12 | */
13 | package com.baidu.aip.error;
14 |
15 | import org.json.JSONObject;
16 |
17 | public enum AipError {
18 | SUCCESS("0", "Success"),
19 | IMAGE_SIZE_ERROR("SDK100", "image size error"),
20 | IMAGE_LENGTH_ERROR("SDK101", "image length error"),
21 | IMAGE_READ_ERROR("SDK102", "read image file error"),
22 | USER_INFO_SIZE_ERROR("SDK103", "user_info size error"),
23 | GROUP_ID_FORMAT_ERROR("SDK104", "group_id format error"),
24 | GROUP_ID_SIZE_ERROR("SDK105", "group_id size error"),
25 | UID_FORMAT_ERROR("SDK106", "uid format error"),
26 | UID_SIZE_ERROR("SDK107", "uid size error"),
27 | NET_TIMEOUT_ERROR("SDK108", "connection or read data time out"),
28 | UNSUPPORTED_IMAGE_FORMAT_ERROR("SDK109", "unsupported image format"),
29 | ILLEGAL_REQUEST_ID_ERROR("SDK110", "illegal request id found: "), // 填充具体id
30 | ASYNC_TIMEOUT_ERROR("SDK111", "wait for aysnc result timeout"),
31 | DOWNLOAD_FILE_ERROR("SDK112", "download file failed");
32 |
33 | private final String errorCode;
34 | private final String errorMsg;
35 |
36 | AipError(String errorCode, String errorMsg) {
37 | this.errorCode = errorCode;
38 | this.errorMsg = errorMsg;
39 | }
40 |
41 | public String getErrorCode() {
42 | return errorCode;
43 | }
44 |
45 | public String getErrorMessage() {
46 | return errorMsg;
47 | }
48 |
49 | public JSONObject toJsonResult() {
50 | JSONObject json = new JSONObject();
51 | json.put("error_code", errorCode);
52 | json.put("error_msg", errorMsg);
53 | return json;
54 | }
55 |
56 | @Override
57 | public String toString() {
58 | return toJsonResult().toString();
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/src/main/java/com/baidu/aip/contentcensor/ContentCensorConsts.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2017 Baidu, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
5 | * the License. You may obtain a copy of the License at
6 | *
7 | * http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
10 | * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
11 | * specific language governing permissions and limitations under the License.
12 | */
13 | package com.baidu.aip.contentcensor;
14 |
15 | import java.util.Arrays;
16 | import java.util.HashSet;
17 |
18 | public class ContentCensorConsts {
19 |
20 | static final String ANTI_PORN_URL =
21 | "https://aip.baidubce.com/rest/2.0/antiporn/v1/detect";
22 |
23 | static final String ANTI_PORN_GIF_URL =
24 | "https://aip.baidubce.com/rest/2.0/antiporn/v1/detect_gif";
25 |
26 | static final String ANTI_TERROR_URL =
27 | "https://aip.baidubce.com/rest/2.0/antiterror/v1/detect";
28 |
29 | static final String IMAGE_CENSOR_COMB_URL =
30 | "https://aip.baidubce.com/api/v1/solution/direct/img_censor";
31 |
32 | static final String FACE_AUDIT_URL =
33 | "https://aip.baidubce.com/rest/2.0/solution/v1/face_audit";
34 |
35 | static final String REPORT_URL =
36 | "https://aip.baidubce.com/rpc/2.0/feedback/v1/report";
37 |
38 | static final String USER_DEFINED_IMAGE_URL =
39 | "https://aip.baidubce.com/rest/2.0/solution/v1/img_censor/v2/user_defined";
40 |
41 | static final String USER_DEFINED_TEXT_URL =
42 | "https://aip.baidubce.com/rest/2.0/solution/v1/text_censor/v2/user_defined";
43 |
44 | static final String TXT_CENSOR_URL =
45 | "https://aip.baidubce.com/rest/2.0/antispam/v2/spam";
46 |
47 | public static final Long ANTIPORN_MAX_IMAGE_SIZE = 4194304L; // 4 * 1024 * 1024
48 |
49 | public static final Integer ANTIPORN_MIN_IMAGE_SIDE_LENGTH = 10;
50 | public static final Integer ANTIPORN_MAX_IMAGE_SIDE_LENGTH = 2048;
51 |
52 | public static final HashSet ANTIPORN_SUPPORT_IMAGE_FORMAT =
53 | new HashSet(Arrays.asList("JPEG", "png", "bmp", "gif"));
54 | }
55 |
--------------------------------------------------------------------------------
/src/main/java/com/baidu/aip/http/AipResponse.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2017 Baidu, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
5 | * the License. You may obtain a copy of the License at
6 | *
7 | * http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
10 | * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
11 | * specific language governing permissions and limitations under the License.
12 | */
13 | package com.baidu.aip.http;
14 |
15 | import java.io.UnsupportedEncodingException;
16 | import java.util.List;
17 | import java.util.Map;
18 | import java.util.TreeMap;
19 |
20 | public class AipResponse {
21 |
22 | private Map> header;
23 | private byte[] body;
24 | private String charset;
25 | private int status;
26 |
27 | public AipResponse() {
28 | status = 0;
29 | charset = "UTF-8";
30 | }
31 |
32 | public int getStatus() {
33 | return status;
34 | }
35 |
36 | public void setStatus(int status) {
37 | this.status = status;
38 | }
39 |
40 | public String getBodyStr() {
41 | if (body == null) {
42 | return "";
43 | }
44 | try {
45 | return new String(body, charset);
46 | } catch (UnsupportedEncodingException e) {
47 | e.printStackTrace();
48 | return new String(body);
49 | }
50 | }
51 |
52 | public Map> getHeader() {
53 | return header;
54 | }
55 |
56 | public void setHeader(Map> header) {
57 | this.header = new TreeMap>(String.CASE_INSENSITIVE_ORDER);
58 | for (Map.Entry> entry: header.entrySet()) {
59 | if (entry.getKey() != null) {
60 | this.header.put(entry.getKey(), entry.getValue());
61 | }
62 | }
63 | }
64 |
65 | public byte[] getBody() {
66 | return body;
67 | }
68 |
69 | public void setBody(byte[] body) {
70 | this.body = body;
71 | }
72 |
73 | public String getCharset() {
74 | return charset;
75 | }
76 |
77 | public void setCharset(String charset) {
78 | this.charset = charset;
79 | }
80 | }
81 |
--------------------------------------------------------------------------------
/src/main/java/com/baidu/aip/imagesearch/ImageSearchConsts.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2017 Baidu, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
5 | * the License. You may obtain a copy of the License at
6 | *
7 | * http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
10 | * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
11 | * specific language governing permissions and limitations under the License.
12 | */
13 |
14 | package com.baidu.aip.imagesearch;
15 |
16 | public class ImageSearchConsts {
17 |
18 | static final String SAME_HQ_ADD =
19 | "https://aip.baidubce.com/rest/2.0/realtime_search/same_hq/add";
20 |
21 | static final String SAME_HQ_SEARCH =
22 | "https://aip.baidubce.com/rest/2.0/realtime_search/same_hq/search";
23 |
24 | static final String SAME_HQ_UPDATE =
25 | "https://aip.baidubce.com/rest/2.0/realtime_search/same_hq/update";
26 |
27 | static final String SAME_HQ_DELETE =
28 | "https://aip.baidubce.com/rest/2.0/realtime_search/same_hq/delete";
29 |
30 | static final String SIMILAR_ADD =
31 | "https://aip.baidubce.com/rest/2.0/image-classify/v1/realtime_search/similar/add";
32 |
33 | static final String SIMILAR_SEARCH =
34 | "https://aip.baidubce.com/rest/2.0/image-classify/v1/realtime_search/similar/search";
35 |
36 | static final String SIMILAR_UPDATE =
37 | "https://aip.baidubce.com/rest/2.0/image-classify/v1/realtime_search/similar/update";
38 |
39 | static final String SIMILAR_DELETE =
40 | "https://aip.baidubce.com/rest/2.0/image-classify/v1/realtime_search/similar/delete";
41 |
42 | static final String PRODUCT_ADD =
43 | "https://aip.baidubce.com/rest/2.0/image-classify/v1/realtime_search/product/add";
44 |
45 | static final String PRODUCT_SEARCH =
46 | "https://aip.baidubce.com/rest/2.0/image-classify/v1/realtime_search/product/search";
47 |
48 | static final String PRODUCT_UPDATE =
49 | "https://aip.baidubce.com/rest/2.0/image-classify/v1/realtime_search/product/update";
50 |
51 | static final String PRODUCT_DELETE =
52 | "https://aip.baidubce.com/rest/2.0/image-classify/v1/realtime_search/product/delete";
53 |
54 | }
--------------------------------------------------------------------------------
/src/main/java/com/baidu/aip/util/SignUtil.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2017 Baidu, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
5 | * the License. You may obtain a copy of the License at
6 | *
7 | * http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
10 | * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
11 | * specific language governing permissions and limitations under the License.
12 | */
13 | package com.baidu.aip.util;
14 |
15 | import com.baidu.aip.exception.AipException;
16 |
17 | import javax.crypto.Mac;
18 | import javax.crypto.spec.SecretKeySpec;
19 | import java.io.UnsupportedEncodingException;
20 | import java.security.MessageDigest;
21 | import java.security.NoSuchAlgorithmException;
22 |
23 | public class SignUtil {
24 | private static final char[] DIGITS;
25 |
26 | public static String hmacSha256(String key, String data) throws AipException {
27 | try {
28 | Mac mac = Mac.getInstance("HmacSHA256");
29 | SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(),
30 | mac.getAlgorithm());
31 | mac.init(signingKey);
32 | return encodeHex(mac.doFinal(data.getBytes()));
33 | } catch (Exception e) {
34 | e.printStackTrace();
35 | throw new AipException(-1, "Fail to generate HMAC-SHA256 signature");
36 | }
37 | }
38 |
39 | public static String md5(String data, String charset) {
40 | try {
41 | byte[] msg = data.getBytes(charset);
42 | MessageDigest md = MessageDigest.getInstance("MD5");
43 | return encodeHex(md.digest(msg));
44 | } catch (UnsupportedEncodingException e) {
45 | e.printStackTrace();
46 | } catch (NoSuchAlgorithmException e) {
47 | e.printStackTrace();
48 | }
49 | return null;
50 | }
51 |
52 | private static String encodeHex(byte[] data) {
53 | int l = data.length;
54 | char[] out = new char[l << 1];
55 | int i = 0;
56 |
57 | for (int j = 0; i < l; ++i) {
58 | out[j++] = DIGITS[(240 & data[i]) >>> 4];
59 | out[j++] = DIGITS[15 & data[i]];
60 | }
61 |
62 | return new String(out);
63 | }
64 |
65 | static {
66 | DIGITS = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
67 | }
68 | }
69 |
--------------------------------------------------------------------------------
/src/main/java/com/baidu/aip/auth/DevAuth.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2017 Baidu, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
5 | * the License. You may obtain a copy of the License at
6 | *
7 | * http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
10 | * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
11 | * specific language governing permissions and limitations under the License.
12 | */
13 | package com.baidu.aip.auth;
14 |
15 | import com.baidu.aip.http.AipHttpClient;
16 | import com.baidu.aip.http.AipRequest;
17 | import com.baidu.aip.http.AipResponse;
18 | import com.baidu.aip.util.AipClientConfiguration;
19 | import com.baidu.aip.util.AipClientConst;
20 | import com.baidu.aip.util.Util;
21 | import org.json.JSONObject;
22 |
23 | import java.net.URI;
24 | import java.net.URISyntaxException;
25 |
26 | public class DevAuth {
27 |
28 | /**
29 | * get access_token from openapi
30 | * @param apiKey API key from console
31 | * @param secretKey Secret Key from console
32 | * @param config network config settings
33 | * @return JsonObject of response from OAuth server
34 | */
35 | public static JSONObject oauth(String apiKey, String secretKey, AipClientConfiguration config) {
36 | try {
37 | AipRequest request = new AipRequest();
38 | request.setUri(new URI(AipClientConst.OAUTH_URL));
39 | request.addBody("grant_type", "client_credentials");
40 | request.addBody("client_id", apiKey);
41 | request.addBody("client_secret", secretKey);
42 | request.setConfig(config);
43 | int statusCode = 500;
44 | AipResponse response = null;
45 | // add retry
46 | int cnt = 0;
47 | while (statusCode == 500 && cnt < 3) {
48 | response = AipHttpClient.post(request);
49 | statusCode = response.getStatus();
50 | cnt++;
51 | }
52 | String res = response.getBodyStr();
53 | if (res != null && !res.equals("")) {
54 | return new JSONObject(res);
55 | } else {
56 | return Util.getGeneralError(statusCode, "Server response code: " + statusCode);
57 | }
58 | } catch (URISyntaxException e) {
59 | e.printStackTrace();
60 | }
61 | return Util.getGeneralError(-1, "unknown error");
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/src/main/java/com/baidu/aip/http/Headers.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2017 Baidu, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
5 | * the License. You may obtain a copy of the License at
6 | *
7 | * http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
10 | * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
11 | * specific language governing permissions and limitations under the License.
12 | */
13 | package com.baidu.aip.http;
14 |
15 | /**
16 | * Common BOS HTTP header values used throughout the BCE BOS Java client.
17 | */
18 | public interface Headers {
19 |
20 | /*
21 | * Standard HTTP Headers
22 | */
23 |
24 | public static final String AUTHORIZATION = "Authorization";
25 |
26 | public static final String CACHE_CONTROL = "Cache-Control";
27 |
28 | public static final String CONTENT_DISPOSITION = "Content-Disposition";
29 |
30 | public static final String CONTENT_ENCODING = "Content-Encoding";
31 |
32 | public static final String CONTENT_LENGTH = "Content-Length";
33 |
34 | public static final String CONTENT_MD5 = "Content-MD5";
35 |
36 | public static final String CONTENT_RANGE = "Content-Range";
37 |
38 | public static final String CONTENT_TYPE = "Content-Type";
39 |
40 | public static final String DATE = "Date";
41 |
42 | public static final String ETAG = "ETag";
43 |
44 | public static final String EXPIRES = "Expires";
45 |
46 | public static final String HOST = "Host";
47 |
48 | public static final String LAST_MODIFIED = "Last-Modified";
49 |
50 | public static final String RANGE = "Range";
51 |
52 | public static final String SERVER = "Server";
53 |
54 | public static final String TRANSFER_ENCODING = "Transfer-Encoding";
55 |
56 | public static final String USER_AGENT = "User-Agent";
57 |
58 |
59 | /*
60 | * BCE Common HTTP Headers
61 | */
62 |
63 | public static final String BCE_ACL = "x-bce-acl";
64 |
65 | public static final String BCE_CONTENT_SHA256 = "x-bce-content-sha256";
66 |
67 | public static final String BCE_COPY_METADATA_DIRECTIVE = "x-bce-metadata-directive";
68 |
69 | public static final String BCE_COPY_SOURCE = "x-bce-copy-source";
70 |
71 | public static final String BCE_COPY_SOURCE_IF_MATCH = "x-bce-copy-source-if-match";
72 |
73 | public static final String BCE_DATE = "x-bce-date";
74 |
75 | public static final String BCE_DEBUG_ID = "x-bce-debug-id";
76 |
77 | public static final String BCE_PREFIX = "x-bce-";
78 |
79 | public static final String BCE_REQUEST_ID = "x-bce-request-id";
80 |
81 | public static final String BCE_SECURITY_TOKEN = "x-bce-security-token";
82 |
83 | public static final String BCE_STORAGE_CLASS = "x-bce-storage-class";
84 |
85 | public static final String BCE_USER_METADATA_PREFIX = "x-bce-meta-";
86 |
87 | }
88 |
--------------------------------------------------------------------------------
/src/main/java/com/baidu/aip/face/MatchRequest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2017 Baidu, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
5 | * the License. You may obtain a copy of the License at
6 | *
7 | * http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
10 | * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
11 | * specific language governing permissions and limitations under the License.
12 | */
13 |
14 | package com.baidu.aip.face;
15 |
16 | import org.json.JSONObject;
17 |
18 | public class MatchRequest {
19 |
20 | private String image;
21 | private String imageType;
22 | private String faceType;
23 | private String qualityControl;
24 | private String livenessControl;
25 |
26 | public MatchRequest(String image, String imageType) {
27 | this.image = image;
28 | this.imageType = imageType;
29 | this.faceType = null;
30 | this.qualityControl = null;
31 | this.livenessControl = null;
32 | }
33 |
34 | public MatchRequest(String image, String imageType, String faceType,
35 | String qualityControl, String livenessControl) {
36 | this.image = image;
37 | this.imageType = imageType;
38 | this.faceType = faceType;
39 | this.qualityControl = qualityControl;
40 | this.livenessControl = livenessControl;
41 | }
42 |
43 | public JSONObject toJsonObject() {
44 | JSONObject obj = new JSONObject();
45 | obj.put("image", this.image);
46 | obj.put("image_type", this.imageType);
47 | if (this.faceType != null) {
48 | obj.put("face_type", this.faceType);
49 | }
50 | if (this.qualityControl != null) {
51 | obj.put("quality_control", this.qualityControl);
52 | }
53 | if (this.livenessControl != null) {
54 | obj.put("liveness_control", this.livenessControl);
55 | }
56 | return obj;
57 | }
58 |
59 | public String getImage() {
60 | return image;
61 | }
62 |
63 | public void setImage(String image) {
64 | this.image = image;
65 | }
66 |
67 | public String getImageType() {
68 | return imageType;
69 | }
70 |
71 | public void setImageType(String imageType) {
72 | this.imageType = imageType;
73 | }
74 |
75 | public String getFaceType() {
76 | return faceType;
77 | }
78 |
79 | public void setFaceType(String faceType) {
80 | this.faceType = faceType;
81 | }
82 |
83 | public String getQualityControl() {
84 | return qualityControl;
85 | }
86 |
87 | public void setQualityControl(String qualityControl) {
88 | this.qualityControl = qualityControl;
89 | }
90 |
91 | public String getLivenessControl() {
92 | return livenessControl;
93 | }
94 |
95 | public void setLivenessControl(String livenessControl) {
96 | this.livenessControl = livenessControl;
97 | }
98 | }
99 |
--------------------------------------------------------------------------------
/src/main/java/com/baidu/aip/face/FaceConsts.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2017 Baidu, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
5 | * the License. You may obtain a copy of the License at
6 | *
7 | * http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
10 | * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
11 | * specific language governing permissions and limitations under the License.
12 | */
13 |
14 | package com.baidu.aip.face;
15 |
16 | public class FaceConsts {
17 |
18 | static final String DETECT =
19 | "https://aip.baidubce.com/rest/2.0/face/v3/detect";
20 |
21 | static final String SEARCH =
22 | "https://aip.baidubce.com/rest/2.0/face/v3/search";
23 |
24 | static final String MULTI_SEARCH =
25 | "https://aip.baidubce.com/rest/2.0/face/v3/multi-search";
26 |
27 | static final String USER_ADD =
28 | "https://aip.baidubce.com/rest/2.0/face/v3/faceset/user/add";
29 |
30 | static final String USER_UPDATE =
31 | "https://aip.baidubce.com/rest/2.0/face/v3/faceset/user/update";
32 |
33 | static final String FACE_DELETE =
34 | "https://aip.baidubce.com/rest/2.0/face/v3/faceset/face/delete";
35 |
36 | static final String USER_GET =
37 | "https://aip.baidubce.com/rest/2.0/face/v3/faceset/user/get";
38 |
39 | static final String FACE_GETLIST =
40 | "https://aip.baidubce.com/rest/2.0/face/v3/faceset/face/getlist";
41 |
42 | static final String GROUP_GETUSERS =
43 | "https://aip.baidubce.com/rest/2.0/face/v3/faceset/group/getusers";
44 |
45 | static final String USER_COPY =
46 | "https://aip.baidubce.com/rest/2.0/face/v3/faceset/user/copy";
47 |
48 | static final String USER_DELETE =
49 | "https://aip.baidubce.com/rest/2.0/face/v3/faceset/user/delete";
50 |
51 | static final String GROUP_ADD =
52 | "https://aip.baidubce.com/rest/2.0/face/v3/faceset/group/add";
53 |
54 | static final String GROUP_DELETE =
55 | "https://aip.baidubce.com/rest/2.0/face/v3/faceset/group/delete";
56 |
57 | static final String GROUP_GETLIST =
58 | "https://aip.baidubce.com/rest/2.0/face/v3/faceset/group/getlist";
59 |
60 | static final String PERSON_VERIFY =
61 | "https://aip.baidubce.com/rest/2.0/face/v3/person/verify";
62 |
63 | static final String VIDEO_SESSIONCODE =
64 | "https://aip.baidubce.com/rest/2.0/face/v1/faceliveness/sessioncode";
65 |
66 | static final String MATCH = "https://aip.baidubce.com/rest/2.0/face/v3/match";
67 |
68 | static final String FACEVERIFY =
69 | "https://aip.baidubce.com/rest/2.0/face/v3/faceverify";
70 |
71 | static final String VIDEO_FACELIVENESS =
72 | "https://aip.baidubce.com/rest/2.0/face/v1/faceliveness/verify";
73 |
74 | static final String ID_MATCH =
75 | "https://aip.baidubce.com/rest/2.0/face/v3/person/idmatch";
76 |
77 | }
--------------------------------------------------------------------------------
/src/main/java/com/baidu/aip/easydl/AipEasyDL.java:
--------------------------------------------------------------------------------
1 | package com.baidu.aip.easydl;
2 |
3 | import com.baidu.aip.client.BaseClient;
4 | import com.baidu.aip.error.AipError;
5 | import com.baidu.aip.http.AipRequest;
6 | import com.baidu.aip.http.EBodyFormat;
7 | import com.baidu.aip.http.Headers;
8 | import com.baidu.aip.http.HttpCharacterEncoding;
9 | import com.baidu.aip.http.HttpContentType;
10 | import com.baidu.aip.util.Base64Util;
11 | import com.baidu.aip.util.Util;
12 | import org.json.JSONObject;
13 |
14 | import java.io.IOException;
15 | import java.util.HashMap;
16 |
17 | public class AipEasyDL extends BaseClient {
18 |
19 | public AipEasyDL(String appId, String apiKey, String secretKey) {
20 | super(appId, apiKey, secretKey);
21 | }
22 |
23 | /**
24 | * easyDL通用请求方法
25 | * @param url 服务的url
26 | * @param image 图片本地路径
27 | * @param options 可选参数
28 | * @return Json返回
29 | */
30 | public JSONObject sendImageRequest(String url, String image, HashMap options) {
31 | try {
32 | byte[] data = Util.readFileByBytes(image);
33 | return sendImageRequest(url, data, options);
34 | } catch (IOException e) {
35 | e.printStackTrace();
36 | return AipError.IMAGE_READ_ERROR.toJsonResult();
37 | }
38 | }
39 |
40 |
41 | /**
42 | * easyDL通用请求方法
43 | * @param url 服务的url
44 | * @param image 图片二进制数据
45 | * @param options 可选参数
46 | * @return Json返回
47 | */
48 | public JSONObject sendImageRequest(String url, byte[] image, HashMap options) {
49 | AipRequest request = new AipRequest();
50 | preOperation(request);
51 | String content = Base64Util.encode(image);
52 | request.addBody("image", content);
53 | if (options != null) {
54 | request.addBody(options);
55 | }
56 | request.setUri(url);
57 | request.addHeader(Headers.CONTENT_ENCODING,
58 | HttpCharacterEncoding.ENCODE_UTF8);
59 | request.addHeader(Headers.CONTENT_TYPE, HttpContentType.JSON_DATA);
60 | request.setBodyFormat(EBodyFormat.RAW_JSON);
61 | postOperation(request);
62 | return requestServer(request);
63 | }
64 |
65 | /**
66 | * easyDL通用请求方法
67 | * @param url 服务的url
68 | * @param file 图片本地路径
69 | * @param options 可选参数
70 | * @return Json返回
71 | */
72 | public JSONObject sendSoundRequest(String url, String file, HashMap options) {
73 | try {
74 | byte[] data = Util.readFileByBytes(file);
75 | return sendSoundRequest(url, data, options);
76 | } catch (IOException e) {
77 | e.printStackTrace();
78 | return AipError.IMAGE_READ_ERROR.toJsonResult();
79 | }
80 | }
81 |
82 |
83 | /**
84 | * easyDL通用请求方法
85 | * @param url 服务的url
86 | * @param data 图片二进制数据
87 | * @param options 可选参数
88 | * @return Json返回
89 | */
90 | public JSONObject sendSoundRequest(String url, byte[] data, HashMap options) {
91 | AipRequest request = new AipRequest();
92 | preOperation(request);
93 | String content = Base64Util.encode(data);
94 | request.addBody("sound", content);
95 | if (options != null) {
96 | request.addBody(options);
97 | }
98 | request.setUri(url);
99 | request.addHeader(Headers.CONTENT_ENCODING,
100 | HttpCharacterEncoding.ENCODE_UTF8);
101 | request.addHeader(Headers.CONTENT_TYPE, HttpContentType.JSON_DATA);
102 | request.setBodyFormat(EBodyFormat.RAW_JSON);
103 | postOperation(request);
104 | return requestServer(request);
105 | }
106 |
107 | }
108 |
--------------------------------------------------------------------------------
/src/main/java/com/baidu/aip/util/ImageUtil.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2017 Baidu, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
5 | * the License. You may obtain a copy of the License at
6 | *
7 | * http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
10 | * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
11 | * specific language governing permissions and limitations under the License.
12 | */
13 | package com.baidu.aip.util;
14 |
15 | import javax.imageio.ImageIO;
16 | import javax.imageio.ImageReader;
17 | import javax.imageio.stream.ImageInputStream;
18 | import javax.imageio.stream.MemoryCacheImageInputStream;
19 | import java.awt.image.BufferedImage;
20 | import java.io.ByteArrayInputStream;
21 | import java.io.File;
22 | import java.io.IOException;
23 | import java.util.HashMap;
24 | import java.util.Iterator;
25 |
26 | public class ImageUtil {
27 |
28 | public static String getImageFormatByFile(String filePath) {
29 | ImageInputStream input = null;
30 | try {
31 | input = ImageIO.createImageInputStream(new File(filePath));
32 | return getImageFormat(input);
33 | } catch (IOException e) {
34 | e.printStackTrace();
35 | } finally {
36 | if (input != null) {
37 | try {
38 | input.close();
39 | } catch (IOException e) {
40 | e.printStackTrace();
41 | }
42 | }
43 | }
44 | return "unknown";
45 | }
46 |
47 | public static String getImageFormatByBytes(byte[] content) {
48 | ImageInputStream input = null;
49 | try {
50 | input = new MemoryCacheImageInputStream(new ByteArrayInputStream(content));
51 | return getImageFormat(input);
52 | } finally {
53 | if (input != null) {
54 | try {
55 | input.close();
56 | } catch (IOException e) {
57 | e.printStackTrace();
58 | }
59 | }
60 | }
61 | }
62 |
63 | // this function will not close input, need caller to close it.
64 | public static String getImageFormat(ImageInputStream input) {
65 | Iterator readers = ImageIO.getImageReaders(input);
66 | String format = "unknown";
67 | if (readers.hasNext()) {
68 | ImageReader reader = readers.next();
69 | try {
70 | format = reader.getFormatName();
71 | } catch (IOException e) {
72 | e.printStackTrace();
73 | } finally {
74 | reader.dispose();
75 | }
76 | }
77 |
78 | return format;
79 | }
80 |
81 |
82 | public static HashMap getImageInfoByFile(String filePath) {
83 | ImageInputStream input;
84 | try {
85 | input = ImageIO.createImageInputStream(new File(filePath));
86 | return getImageInfo(input);
87 | } catch (IOException e) {
88 | e.printStackTrace();
89 | }
90 | return null;
91 | }
92 |
93 | public static HashMap getImageInfoByBytes(byte[] content) {
94 | ImageInputStream input = new MemoryCacheImageInputStream(new ByteArrayInputStream(content));
95 | return getImageInfo(input);
96 | }
97 |
98 | // this function will not close input, need caller to close it.
99 | public static HashMap getImageInfo(ImageInputStream input) {
100 | HashMap map = new HashMap(2);
101 |
102 | BufferedImage buff = null;
103 | try {
104 | buff = ImageIO.read(input);
105 | map.put("width", buff.getWidth());
106 | map.put("height", buff.getHeight());
107 | return map;
108 | } catch (IOException e) {
109 | e.printStackTrace();
110 | } catch (Exception e) {
111 | e.printStackTrace();
112 | }
113 |
114 | return null;
115 | }
116 |
117 |
118 | }
119 |
--------------------------------------------------------------------------------
/src/main/java/com/baidu/aip/http/AipHttpClient.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2017 Baidu, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
5 | * the License. You may obtain a copy of the License at
6 | *
7 | * http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
10 | * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
11 | * specific language governing permissions and limitations under the License.
12 | */
13 | package com.baidu.aip.http;
14 |
15 | import java.io.ByteArrayOutputStream;
16 | import java.io.DataOutputStream;
17 | import java.io.IOException;
18 | import java.io.InputStream;
19 | import java.io.UnsupportedEncodingException;
20 | import java.net.HttpURLConnection;
21 | import java.net.MalformedURLException;
22 | import java.net.Proxy;
23 | import java.net.URL;
24 | import java.util.HashMap;
25 | import java.util.Map;
26 |
27 | public class AipHttpClient {
28 |
29 |
30 | /**
31 | * post方式请求服务器(https协议)
32 | *
33 | * @param request 请求内容
34 | * @return AipResponse
35 | */
36 | public static AipResponse post(AipRequest request) {
37 | String url;
38 | String charset = request.getContentEncoding();
39 | String content = request.getBodyStr();
40 | HashMap header = request.getHeaders();
41 | AipResponse response = new AipResponse();
42 |
43 | DataOutputStream out = null;
44 | InputStream is = null;
45 | try {
46 | if (request.getParams().isEmpty()) {
47 | url = request.getUri().toString();
48 | }
49 | else {
50 | url = String.format("%s?%s", request.getUri().toString(), request.getParamStr());
51 | }
52 |
53 | URL console = new URL(url);
54 | Proxy proxy = request.getConfig() == null ? Proxy.NO_PROXY : request.getConfig().getProxy();
55 | HttpURLConnection conn = (HttpURLConnection) console.openConnection(proxy);
56 |
57 | // set timeout
58 | if (request.getConfig() != null) {
59 | conn.setConnectTimeout(request.getConfig().getConnectionTimeoutMillis());
60 | conn.setReadTimeout(request.getConfig().getSocketTimeoutMillis());
61 | }
62 | conn.setDoOutput(true);
63 | // 添加header
64 | for (Map.Entry entry : header.entrySet()) {
65 | conn.setRequestProperty(entry.getKey(), entry.getValue());
66 | }
67 |
68 | conn.connect();
69 | out = new DataOutputStream(conn.getOutputStream());
70 | out.write(content.getBytes(charset));
71 | out.flush();
72 | int statusCode = conn.getResponseCode();
73 | response.setHeader(conn.getHeaderFields());
74 | response.setStatus(statusCode);
75 | response.setCharset(charset);
76 | if (statusCode != 200) {
77 | return response;
78 | }
79 |
80 | is = conn.getInputStream();
81 | if (is != null) {
82 | ByteArrayOutputStream outStream = new ByteArrayOutputStream();
83 | byte[] buffer = new byte[1024];
84 | int len = 0;
85 | while ((len = is.read(buffer)) != -1) {
86 | outStream.write(buffer, 0, len);
87 | }
88 | response.setBody(outStream.toByteArray());
89 | }
90 | return response;
91 | } catch (MalformedURLException e) {
92 | e.printStackTrace();
93 | } catch (UnsupportedEncodingException e) {
94 | e.printStackTrace();
95 | } catch (IOException e) {
96 | e.printStackTrace();
97 | } finally {
98 | if (out != null) {
99 | try {
100 | out.close();
101 | } catch (IOException e) {
102 | e.printStackTrace();
103 | }
104 | }
105 | if (is != null) {
106 | try {
107 | is.close();
108 | } catch (IOException e) {
109 | e.printStackTrace();
110 | }
111 | }
112 | }
113 | return response;
114 | }
115 |
116 | }
--------------------------------------------------------------------------------
/src/main/java/com/baidu/aip/ocr/OcrConsts.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2017 Baidu, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
5 | * the License. You may obtain a copy of the License at
6 | *
7 | * http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
10 | * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
11 | * specific language governing permissions and limitations under the License.
12 | */
13 |
14 | package com.baidu.aip.ocr;
15 |
16 | public class OcrConsts {
17 |
18 | static final String GENERAL_BASIC = "https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic";
19 |
20 | static final String ACCURATE_BASIC = "https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic";
21 |
22 | static final String GENERAL = "https://aip.baidubce.com/rest/2.0/ocr/v1/general";
23 |
24 | static final String ACCURATE = "https://aip.baidubce.com/rest/2.0/ocr/v1/accurate";
25 |
26 | static final String GENERAL_ENHANCED = "https://aip.baidubce.com/rest/2.0/ocr/v1/general_enhanced";
27 |
28 | static final String WEB_IMAGE = "https://aip.baidubce.com/rest/2.0/ocr/v1/webimage";
29 |
30 | static final String IDCARD = "https://aip.baidubce.com/rest/2.0/ocr/v1/idcard";
31 |
32 | static final String BANKCARD = "https://aip.baidubce.com/rest/2.0/ocr/v1/bankcard";
33 |
34 | static final String DRIVING_LICENSE = "https://aip.baidubce.com/rest/2.0/ocr/v1/driving_license";
35 |
36 | static final String VEHICLE_LICENSE = "https://aip.baidubce.com/rest/2.0/ocr/v1/vehicle_license";
37 |
38 | static final String LICENSE_PLATE = "https://aip.baidubce.com/rest/2.0/ocr/v1/license_plate";
39 |
40 | static final String BUSINESS_LICENSE = "https://aip.baidubce.com/rest/2.0/ocr/v1/business_license";
41 |
42 | static final String RECEIPT = "https://aip.baidubce.com/rest/2.0/ocr/v1/receipt";
43 |
44 | static final String TRAIN_TICKET = "https://aip.baidubce.com/rest/2.0/ocr/v1/train_ticket";
45 |
46 | static final String TAXI_RECEIPT = "https://aip.baidubce.com/rest/2.0/ocr/v1/taxi_receipt";
47 |
48 | static final String FORM = "https://aip.baidubce.com/rest/2.0/ocr/v1/form";
49 |
50 | static final String TABLE_RECOGNIZE = "https://aip.baidubce.com/rest/2.0/solution/v1/form_ocr/request";
51 |
52 | static final String TABLE_RESULT_GET = "https://aip.baidubce.com/rest/2.0/solution/v1/form_ocr/get_request_result";
53 |
54 | static final String VIN_CODE = "https://aip.baidubce.com/rest/2.0/ocr/v1/vin_code";
55 |
56 | static final String QUOTA_INVOICE = "https://aip.baidubce.com/rest/2.0/ocr/v1/quota_invoice";
57 |
58 | static final String HOUSEHOLD_REGISTER = "https://aip.baidubce.com/rest/2.0/ocr/v1/household_register";
59 |
60 | static final String HK_MACAU_EXITENTRYPERMIT = "https://aip.baidubce.com/rest/2.0/ocr/v1/HK_Macau_exitentrypermit";
61 |
62 | static final String TAIWAN_EXITENTRYPERMIT = "https://aip.baidubce.com/rest/2.0/ocr/v1/taiwan_exitentrypermit";
63 |
64 | static final String BIRTH_CERTIFICATE = "https://aip.baidubce.com/rest/2.0/ocr/v1/birth_certificate";
65 |
66 | static final String VEHICLE_INVOICE = "https://aip.baidubce.com/rest/2.0/ocr/v1/vehicle_invoice";
67 |
68 | static final String VEHICLE_CERTIFICATE = "https://aip.baidubce.com/rest/2.0/ocr/v1/vehicle_certificate";
69 |
70 | static final String INVOICE = "https://aip.baidubce.com/rest/2.0/ocr/v1/invoice";
71 |
72 | static final String AIR_TICKET = "https://aip.baidubce.com/rest/2.0/ocr/v1/air_ticket";
73 |
74 | static final String INSURANCE_DOCUMENTS = "https://aip.baidubce.com/rest/2.0/ocr/v1/insurance_documents";
75 |
76 | static final String VAT_INVOICE = "https://aip.baidubce.com/rest/2.0/ocr/v1/vat_invoice";
77 |
78 | static final String QRCODE = "https://aip.baidubce.com/rest/2.0/ocr/v1/qrcode";
79 |
80 | static final String NUMBERS = "https://aip.baidubce.com/rest/2.0/ocr/v1/numbers";
81 |
82 | static final String LOTTERY = "https://aip.baidubce.com/rest/2.0/ocr/v1/lottery";
83 |
84 | static final String PASSPORT = "https://aip.baidubce.com/rest/2.0/ocr/v1/passport";
85 |
86 | static final String BUSINESS_CARD = "https://aip.baidubce.com/rest/2.0/ocr/v1/business_card";
87 |
88 | static final String HANDWRITING = "https://aip.baidubce.com/rest/2.0/ocr/v1/handwriting";
89 |
90 | static final String CUSTOM = "https://aip.baidubce.com/rest/2.0/solution/v1/iocr/recognise";
91 |
92 | static final int ASYNC_TASK_STATUS_FINISHED = 3;
93 | }
--------------------------------------------------------------------------------
/src/main/java/com/baidu/aip/auth/CloudAuth.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2017 Baidu, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
5 | * the License. You may obtain a copy of the License at
6 | *
7 | * http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
10 | * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
11 | * specific language governing permissions and limitations under the License.
12 | */
13 | package com.baidu.aip.auth;
14 |
15 | import com.baidu.aip.http.AipRequest;
16 | import com.baidu.aip.util.AipClientConst;
17 | import com.baidu.aip.util.SignUtil;
18 | import com.baidu.aip.util.Util;
19 |
20 | import java.util.ArrayList;
21 | import java.util.HashMap;
22 | import java.util.Map;
23 | import java.util.TreeSet;
24 |
25 | public class CloudAuth {
26 |
27 | /**
28 | * @param request AipRequest Object
29 | * @param ak access key ID
30 | * @param sk secret access key
31 | * @param timestamp UTC timestamp
32 | * @return signed authorization header for cloud auth
33 | */
34 | public static String sign(AipRequest request, String ak, String sk, String timestamp) {
35 | HashMap headers = request.getHeaders();
36 | HashMap params = request.getParams();
37 | String httpMethod = request.getHttpMethod().toString();
38 | String path = request.getUri().getPath();
39 | // 1. 生成signingKey
40 | // 1.1 authString,格式为:bce-auth-v1/{accessKeyId}/{timestamp}/{expirationPeriodInSeconds}
41 | String authStringPrefix = String.format("bce-auth-v1/%s/%s/%d",
42 | ak, timestamp, AipClientConst.BCE_AUTH_EXPIRE_IN_SECONDS);
43 |
44 | try {
45 | // 1.2.使用authStringPrefix加上SK,用SHA-256生成sign key
46 | String signingKey = SignUtil.hmacSha256(sk, authStringPrefix);
47 |
48 | // 2. 生成规范化uri
49 | String canonicalUri = getCanonicalUri(path);
50 |
51 | // 3. 生成规范化query string
52 | String canonicalQuery = getCanonicalQuery(params);
53 |
54 | // 4. 生成规范化headers
55 | String canonicalHeaders = getCanonicalHeaders(headers);
56 |
57 | ArrayList canonicalRequest = new ArrayList();
58 | canonicalRequest.add(httpMethod);
59 | canonicalRequest.add(canonicalUri);
60 | canonicalRequest.add(canonicalQuery);
61 | canonicalRequest.add(canonicalHeaders);
62 |
63 | String signature = SignUtil.hmacSha256(signingKey, Util.mkString(canonicalRequest.iterator(), '\n'));
64 |
65 | return String.format("%s/%s/%s", authStringPrefix, "", signature);
66 | } catch (Exception e) {
67 | e.printStackTrace();
68 | return null;
69 | }
70 | }
71 |
72 | private static String getCanonicalUri(String path) {
73 | if (!path.startsWith("/")) {
74 | path = String.format("/%s", path);
75 | }
76 | return Util.uriEncode(path, false);
77 | }
78 |
79 | private static String getCanonicalQuery(HashMap params) {
80 | if (params.isEmpty()) {
81 | return "";
82 | }
83 |
84 | TreeSet querySet = new TreeSet();
85 | for (Map.Entry entry : params.entrySet()) {
86 | if (!entry.getKey().toLowerCase().equals("authorization")) {
87 | querySet.add(String.format("%s=%s",
88 | Util.uriEncode(entry.getKey(), true),
89 | Util.uriEncode(entry.getValue(), true)));
90 | }
91 | }
92 |
93 | return Util.mkString(querySet.iterator(), '&');
94 |
95 | }
96 |
97 | /*
98 | * 对部分header名称及参数进行编码,默认使用:
99 | * 1. host
100 | * 2. content-md5
101 | * 3. content-length
102 | * 4. content-type
103 | * 5. 所有以x-bce-开头的header项
104 | */
105 | private static String getCanonicalHeaders(HashMap headers) {
106 | if (headers.isEmpty()) {
107 | return "";
108 | }
109 | TreeSet headerSet = new TreeSet();
110 | for (Map.Entry entry : headers.entrySet()) {
111 | String key = entry.getKey().trim().toLowerCase();
112 | if (key.startsWith(AipClientConst.BCE_PREFIX)
113 | || AipClientConst.BCE_HEADER_TO_SIGN.contains(key)) {
114 | headerSet.add(String.format("%s:%s", Util.uriEncode(key, true),
115 | Util.uriEncode(entry.getValue().trim(), true)));
116 | }
117 | }
118 |
119 | return Util.mkString(headerSet.iterator(), '\n');
120 | }
121 |
122 | }
123 |
--------------------------------------------------------------------------------
/src/main/java/com/baidu/aip/util/Base64Util.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2017 Baidu, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
5 | * the License. You may obtain a copy of the License at
6 | *
7 | * http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
10 | * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
11 | * specific language governing permissions and limitations under the License.
12 | */
13 | package com.baidu.aip.util;
14 |
15 | public class Base64Util {
16 | private static final char[] ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
17 | .toCharArray();
18 |
19 | private static final char last2byte = (char) Integer
20 | .parseInt("00000011", 2);
21 | private static final char last4byte = (char) Integer
22 | .parseInt("00001111", 2);
23 | private static final char last6byte = (char) Integer
24 | .parseInt("00111111", 2);
25 | private static final char lead6byte = (char) Integer
26 | .parseInt("11111100", 2);
27 | private static final char lead4byte = (char) Integer
28 | .parseInt("11110000", 2);
29 | private static final char lead2byte = (char) Integer
30 | .parseInt("11000000", 2);
31 | private static final char[] encodeTable = new char[] { 'A', 'B', 'C', 'D',
32 | 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q',
33 | 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd',
34 | 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q',
35 | 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3',
36 | '4', '5', '6', '7', '8', '9', '+', '/' };
37 |
38 | private static int[] toInt = new int[128];
39 |
40 | static {
41 | for (int i = 0; i < ALPHABET.length; i++) {
42 | toInt[ALPHABET[i]] = i;
43 | }
44 | }
45 |
46 | /**
47 | * Base64 encoding.
48 | *
49 | * @param from
50 | * The src data.
51 | * @return cryto_str
52 | */
53 | public static String encode(byte[] from) {
54 | StringBuilder to = new StringBuilder((int) (from.length * 1.34) + 3);
55 | int num = 0;
56 | char currentByte = 0;
57 | for (int i = 0; i < from.length; i++) {
58 | num = num % 8;
59 | while (num < 8) {
60 | switch (num) {
61 | case 0:
62 | currentByte = (char) (from[i] & lead6byte);
63 | currentByte = (char) (currentByte >>> 2);
64 | break;
65 | case 2:
66 | currentByte = (char) (from[i] & last6byte);
67 | break;
68 | case 4:
69 | currentByte = (char) (from[i] & last4byte);
70 | currentByte = (char) (currentByte << 2);
71 | if ((i + 1) < from.length) {
72 | currentByte |= (from[i + 1] & lead2byte) >>> 6;
73 | }
74 | break;
75 | case 6:
76 | currentByte = (char) (from[i] & last2byte);
77 | currentByte = (char) (currentByte << 4);
78 | if ((i + 1) < from.length) {
79 | currentByte |= (from[i + 1] & lead4byte) >>> 4;
80 | }
81 | break;
82 | default:
83 | break;
84 | }
85 | to.append(encodeTable[currentByte]);
86 | num += 6;
87 | }
88 | }
89 | if (to.length() % 4 != 0) {
90 | for (int i = 4 - to.length() % 4; i > 0; i--) {
91 | to.append("=");
92 | }
93 | }
94 | return to.toString();
95 | }
96 |
97 | /**
98 | * Translates the specified Base64 string into a byte array.
99 | *
100 | * @param s the Base64 string (not null)
101 | * @return the byte array (not null)
102 | */
103 | public static byte[] decode(String s) {
104 | int delta = s.endsWith( "==" ) ? 2 : s.endsWith( "=" ) ? 1 : 0;
105 | byte[] buffer = new byte[s.length() * 3 / 4 - delta];
106 | int mask = 0xFF;
107 | int index = 0;
108 | for (int i = 0; i < s.length(); i += 4) {
109 | int c0 = toInt[s.charAt( i )];
110 | int c1 = toInt[s.charAt( i + 1)];
111 | buffer[index++] = (byte)(((c0 << 2) | (c1 >> 4)) & mask);
112 | if (index >= buffer.length) {
113 | return buffer;
114 | }
115 | int c2 = toInt[s.charAt( i + 2)];
116 | buffer[index++] = (byte)(((c1 << 4) | (c2 >> 2)) & mask);
117 | if (index >= buffer.length) {
118 | return buffer;
119 | }
120 | int c3 = toInt[s.charAt( i + 3 )];
121 | buffer[index++] = (byte)(((c2 << 6) | c3) & mask);
122 | }
123 | return buffer;
124 | }
125 | }
126 |
--------------------------------------------------------------------------------
/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 4.0.0
6 |
7 | com.baidu.aip
8 | java-sdk
9 | 4.12.0
10 | aip-java-sdk
11 | The AIP SDK for Java provides Java APIs for all of AI APIs.
12 | http://ai.baidu.com/sdk
13 |
14 |
15 |
16 | The Apache Software License, Version 2.0
17 | http://www.apache.org/licenses/LICENSE-2.0.txt
18 |
19 |
20 |
21 |
22 | https://github.com/Baidu-AIP/java-sdk.git
23 |
24 |
25 |
26 |
27 | aipe
28 | Baidu AIPE
29 | http://ai.baidu.com
30 |
31 | developer
32 |
33 |
34 |
35 |
36 |
37 |
38 | org.json
39 | json
40 | 20160810
41 |
42 |
43 | org.slf4j
44 | slf4j-api
45 | 1.7.25
46 |
47 |
48 | org.slf4j
49 | slf4j-simple
50 | 1.7.25
51 |
52 |
53 |
54 |
55 |
56 |
57 | org.apache.maven.plugins
58 | maven-compiler-plugin
59 | 2.3
60 |
61 | 1.6
62 | 1.6
63 | UTF-8
64 |
65 |
66 |
67 | org.apache.maven.plugins
68 | maven-source-plugin
69 | 2.2.1
70 |
71 |
72 | attach-sources
73 |
74 | jar-no-fork
75 |
76 |
77 |
78 |
79 |
80 | org.apache.maven.plugins
81 | maven-javadoc-plugin
82 | 2.9.1
83 |
84 |
85 | attach-javadocs
86 |
87 | jar
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 | ossrh
98 | https://oss.sonatype.org/content/repositories/snapshots
99 |
100 |
101 | ossrh
102 | https://oss.sonatype.org/service/local/staging/deploy/maven2/
103 |
104 |
105 |
106 |
107 | release
108 |
109 |
110 |
111 | org.sonatype.plugins
112 | nexus-staging-maven-plugin
113 | 1.6.7
114 | true
115 |
116 | ossrh
117 | https://oss.sonatype.org/
118 | true
119 |
120 |
121 |
122 | org.apache.maven.plugins
123 | maven-gpg-plugin
124 | 1.5
125 |
126 |
127 | sign-artifacts
128 | verify
129 |
130 | sign
131 |
132 |
133 |
134 |
135 |
136 |
137 |
138 |
139 |
140 |
141 |
--------------------------------------------------------------------------------
/src/main/java/com/baidu/aip/http/AipRequest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2017 Baidu, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
5 | * the License. You may obtain a copy of the License at
6 | *
7 | * http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
10 | * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
11 | * specific language governing permissions and limitations under the License.
12 | */
13 | package com.baidu.aip.http;
14 |
15 | import com.baidu.aip.util.AipClientConfiguration;
16 | import com.baidu.aip.util.Util;
17 | import org.json.JSONObject;
18 |
19 | import java.net.URI;
20 | import java.net.URISyntaxException;
21 | import java.util.ArrayList;
22 | import java.util.HashMap;
23 | import java.util.Map;
24 |
25 | public class AipRequest {
26 | private HashMap headers;
27 | private HashMap params;
28 | private HashMap body;
29 | private URI uri;
30 | private HttpMethodName httpMethod;
31 | private EBodyFormat bodyFormat;
32 | private String contentEncoding;
33 | private AipClientConfiguration config;
34 |
35 |
36 | public AipRequest() {
37 | headers = new HashMap();
38 | params = new HashMap();
39 | body = new HashMap();
40 | httpMethod = HttpMethodName.POST;
41 | bodyFormat = EBodyFormat.FORM_KV;
42 | contentEncoding = HttpCharacterEncoding.DEFAULT_ENCODING;
43 | config = null;
44 | }
45 |
46 | public AipRequest(HashMap header, HashMap bodyParams) {
47 | headers = header;
48 | params = bodyParams;
49 | }
50 |
51 | public String getContentEncoding() {
52 | return contentEncoding;
53 | }
54 |
55 | public void setContentEncoding(String contentEncoding) {
56 | this.contentEncoding = contentEncoding;
57 | }
58 |
59 | public EBodyFormat getBodyFormat() {
60 | return bodyFormat;
61 | }
62 |
63 | public void setBodyFormat(EBodyFormat bodyFormat) {
64 | this.bodyFormat = bodyFormat;
65 | }
66 |
67 | public void addHeader(String key, String value) {
68 | headers.put(key, value);
69 | if (key.equals(Headers.CONTENT_ENCODING)) {
70 | this.contentEncoding = value;
71 | }
72 | }
73 |
74 | public void addParam(String key, String value) {
75 | params.put(key, value);
76 | }
77 |
78 | public void addBody(String key, Object value) {
79 | body.put(key, value);
80 | }
81 |
82 | public void addBody(HashMap other) {
83 | if (other != null) {
84 | body.putAll(other);
85 | }
86 | }
87 |
88 | public HashMap getParams() {
89 | return params;
90 | }
91 |
92 | /**
93 | * get body content depending on bodyFormat
94 | * @return body content as String
95 | */
96 | public String getBodyStr() {
97 | ArrayList arr = new ArrayList();
98 | if (bodyFormat.equals(EBodyFormat.FORM_KV)) {
99 | for (Map.Entry entry : body.entrySet()) {
100 | if (entry.getValue() == null || entry.getValue().equals("")) {
101 | arr.add(Util.uriEncode(entry.getKey(), true));
102 | } else {
103 | arr.add(String.format("%s=%s", Util.uriEncode(entry.getKey(), true),
104 | Util.uriEncode(entry.getValue().toString(), true)));
105 | }
106 | }
107 | return Util.mkString(arr.iterator(), '&');
108 | }
109 | else if (bodyFormat.equals(EBodyFormat.RAW_JSON)) {
110 | JSONObject json = new JSONObject();
111 | for (Map.Entry entry : body.entrySet()) {
112 | json.put(entry.getKey(), entry.getValue());
113 | }
114 | return json.toString();
115 | }
116 | else if (bodyFormat.equals(EBodyFormat.RAW_JSON_ARRAY)) {
117 | return (String) body.get("body");
118 | }
119 | return "";
120 | }
121 |
122 | public String getParamStr() {
123 | StringBuffer buffer = new StringBuffer();
124 | for (Map.Entry entry : params.entrySet()) {
125 | buffer.append(String.format("%s=%s&", entry.getKey(), entry.getValue()));
126 | }
127 | if (buffer.length() > 0) {
128 | buffer.deleteCharAt(buffer.length() - 1);
129 | }
130 | return buffer.toString();
131 | }
132 |
133 | public HashMap getBody() {
134 | return body;
135 | }
136 |
137 | public void setBody(HashMap body) {
138 | this.body = body;
139 | }
140 |
141 | public void setParams(HashMap params) {
142 | this.params = params;
143 | }
144 |
145 | public HashMap getHeaders() {
146 | return headers;
147 | }
148 |
149 | public void setHeaders(HashMap headers) {
150 | this.headers = headers;
151 | }
152 |
153 | public URI getUri() {
154 | return uri;
155 | }
156 |
157 | public void setUri(URI uri) {
158 | this.uri = uri;
159 | }
160 |
161 | public void setUri(String url) {
162 | try {
163 | this.uri = new URI(url);
164 | } catch (URISyntaxException e) {
165 | e.printStackTrace();
166 | }
167 | }
168 |
169 | public HttpMethodName getHttpMethod() {
170 | return httpMethod;
171 | }
172 |
173 | public void setHttpMethod(HttpMethodName httpMethod) {
174 | this.httpMethod = httpMethod;
175 | }
176 |
177 | public AipClientConfiguration getConfig() {
178 | return config;
179 | }
180 |
181 | public void setConfig(AipClientConfiguration config) {
182 | this.config = config;
183 | }
184 | }
185 |
--------------------------------------------------------------------------------
/src/main/java/com/baidu/aip/kg/AipKnowledgeGraphic.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2017 Baidu, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
5 | * the License. You may obtain a copy of the License at
6 | *
7 | * http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
10 | * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
11 | * specific language governing permissions and limitations under the License.
12 | */
13 |
14 | package com.baidu.aip.kg;
15 |
16 | import com.baidu.aip.client.BaseClient;
17 | import com.baidu.aip.http.AipRequest;
18 | import org.json.JSONObject;
19 |
20 | import java.util.HashMap;
21 |
22 | public class AipKnowledgeGraphic extends BaseClient {
23 |
24 | public AipKnowledgeGraphic(String appId, String apiKey, String secretKey) {
25 | super(appId, apiKey, secretKey);
26 | }
27 |
28 | /**
29 | * 创建任务接口
30 | * 创建一个新的信息抽取任务
31 | *
32 | * @param name - 任务名字
33 | * @param templateContent - json string 解析模板内容
34 | * @param inputMappingFile - 抓取结果映射文件的路径
35 | * @param outputFile - 输出文件名字
36 | * @param urlPattern - url pattern
37 | * @param options - 可选参数对象,key: value都为string类型
38 | * options - options列表:
39 | * limit_count 限制解析数量limit_count为0时进行全量任务,limit_count>0时只解析limit_count数量的页面
40 | * @return JSONObject
41 | */
42 | public JSONObject createTask(String name, String templateContent, String inputMappingFile, String outputFile, String urlPattern, HashMap options) {
43 | AipRequest request = new AipRequest();
44 | preOperation(request);
45 |
46 | request.addBody("name", name);
47 |
48 | request.addBody("template_content", templateContent);
49 |
50 | request.addBody("input_mapping_file", inputMappingFile);
51 |
52 | request.addBody("output_file", outputFile);
53 |
54 | request.addBody("url_pattern", urlPattern);
55 | if (options != null) {
56 | request.addBody(options);
57 | }
58 | request.setUri(KnowledgeGraphicConsts.CREATE_TASK);
59 | postOperation(request);
60 | return requestServer(request);
61 | }
62 |
63 | /**
64 | * 更新任务接口
65 | * 更新任务配置,在任务重新启动后生效
66 | *
67 | * @param id - 任务ID
68 | * @param options - 可选参数对象,key: value都为string类型
69 | * options - options列表:
70 | * name 任务名字
71 | * template_content json string 解析模板内容
72 | * input_mapping_file 抓取结果映射文件的路径
73 | * url_pattern url pattern
74 | * output_file 输出文件名字
75 | * @return JSONObject
76 | */
77 | public JSONObject updateTask(int id, HashMap options) {
78 | AipRequest request = new AipRequest();
79 | preOperation(request);
80 |
81 | request.addBody("id", id);
82 | if (options != null) {
83 | request.addBody(options);
84 | }
85 | request.setUri(KnowledgeGraphicConsts.UPDATE_TASK);
86 | postOperation(request);
87 | return requestServer(request);
88 | }
89 |
90 | /**
91 | * 获取任务详情接口
92 | * 根据任务id获取单个任务的详细信息
93 | *
94 | * @param id - 任务ID
95 | * @param options - 可选参数对象,key: value都为string类型
96 | * options - options列表:
97 | * @return JSONObject
98 | */
99 | public JSONObject getTaskInfo(int id, HashMap options) {
100 | AipRequest request = new AipRequest();
101 | preOperation(request);
102 |
103 | request.addBody("id", id);
104 | if (options != null) {
105 | request.addBody(options);
106 | }
107 | request.setUri(KnowledgeGraphicConsts.TASK_INFO);
108 | postOperation(request);
109 | return requestServer(request);
110 | }
111 |
112 | /**
113 | * 以分页的方式查询当前用户所有的任务信息接口
114 | * 该请求用于菜品识别。即对于输入的一张图片(可正常解码,且长宽比适宜),输出图片的菜品名称、卡路里信息、置信度。
115 | *
116 | * @param options - 可选参数对象,key: value都为string类型
117 | * options - options列表:
118 | * id 任务ID,精确匹配
119 | * name 中缀模糊匹配,abc可以匹配abc,aaabc,abcde等
120 | * status 要筛选的任务状态
121 | * page 页码
122 | * per_page 页码
123 | * @return JSONObject
124 | */
125 | public JSONObject getUserTasks(HashMap options) {
126 | AipRequest request = new AipRequest();
127 | preOperation(request);
128 | if (options != null) {
129 | request.addBody(options);
130 | }
131 | request.setUri(KnowledgeGraphicConsts.TASK_QUERY);
132 | postOperation(request);
133 | return requestServer(request);
134 | }
135 |
136 | /**
137 | * 启动任务接口
138 | * 启动一个已经创建的信息抽取任务
139 | *
140 | * @param id - 任务ID
141 | * @param options - 可选参数对象,key: value都为string类型
142 | * options - options列表:
143 | * @return JSONObject
144 | */
145 | public JSONObject startTask(int id, HashMap options) {
146 | AipRequest request = new AipRequest();
147 | preOperation(request);
148 |
149 | request.addBody("id", id);
150 | if (options != null) {
151 | request.addBody(options);
152 | }
153 | request.setUri(KnowledgeGraphicConsts.TASK_START);
154 | postOperation(request);
155 | return requestServer(request);
156 | }
157 |
158 | /**
159 | * 查询任务状态接口
160 | * 查询指定的任务的最新执行状态
161 | *
162 | * @param id - 任务ID
163 | * @param options - 可选参数对象,key: value都为string类型
164 | * options - options列表:
165 | * @return JSONObject
166 | */
167 | public JSONObject getTaskStatus(int id, HashMap options) {
168 | AipRequest request = new AipRequest();
169 | preOperation(request);
170 |
171 | request.addBody("id", id);
172 | if (options != null) {
173 | request.addBody(options);
174 | }
175 | request.setUri(KnowledgeGraphicConsts.TASK_STATUS);
176 | postOperation(request);
177 | return requestServer(request);
178 | }
179 |
180 | }
--------------------------------------------------------------------------------
/src/main/java/com/baidu/aip/util/Util.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2017 Baidu, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
5 | * the License. You may obtain a copy of the License at
6 | *
7 | * http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
10 | * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
11 | * specific language governing permissions and limitations under the License.
12 | */
13 | package com.baidu.aip.util;
14 |
15 | import org.json.JSONObject;
16 |
17 | import java.io.BufferedInputStream;
18 | import java.io.BufferedOutputStream;
19 | import java.io.ByteArrayOutputStream;
20 | import java.io.DataOutputStream;
21 | import java.io.File;
22 | import java.io.FileInputStream;
23 | import java.io.FileNotFoundException;
24 | import java.io.FileOutputStream;
25 | import java.io.IOException;
26 | import java.io.UnsupportedEncodingException;
27 | import java.text.SimpleDateFormat;
28 | import java.util.BitSet;
29 | import java.util.Date;
30 | import java.util.Iterator;
31 | import java.util.TimeZone;
32 | import java.util.regex.Pattern;
33 |
34 | public class Util {
35 |
36 | private static BitSet URI_UNRESERVED_CHARACTERS = new BitSet();
37 | private static String[] PERCENT_ENCODED_STRINGS = new String[256];
38 |
39 |
40 | static {
41 | for (int i = 'a'; i <= 'z'; i++) {
42 | URI_UNRESERVED_CHARACTERS.set(i);
43 | }
44 | for (int i = 'A'; i <= 'Z'; i++) {
45 | URI_UNRESERVED_CHARACTERS.set(i);
46 | }
47 | for (int i = '0'; i <= '9'; i++) {
48 | URI_UNRESERVED_CHARACTERS.set(i);
49 | }
50 | URI_UNRESERVED_CHARACTERS.set('-');
51 | URI_UNRESERVED_CHARACTERS.set('.');
52 | URI_UNRESERVED_CHARACTERS.set('_');
53 | URI_UNRESERVED_CHARACTERS.set('~');
54 |
55 | for (int i = 0; i < PERCENT_ENCODED_STRINGS.length; ++i) {
56 | PERCENT_ENCODED_STRINGS[i] = String.format("%%%02X", i);
57 | }
58 |
59 | }
60 |
61 | public static String mkString(Iterator iter, char seprator) {
62 | if (!iter.hasNext()) {
63 | return "";
64 | }
65 | StringBuilder builder = new StringBuilder();
66 | while (iter.hasNext()) {
67 | String item = iter.next();
68 | builder.append(item);
69 | builder.append(seprator);
70 | }
71 |
72 | builder.deleteCharAt(builder.length() - 1); // remove last sep
73 | return builder.toString();
74 | }
75 |
76 |
77 | /**
78 | * Normalize a string for use in BCE web service APIs. The normalization algorithm is:
79 | *
80 | * - Convert the string into a UTF-8 byte array.
81 | * - Encode all octets into percent-encoding, except all URI unreserved characters per the RFC 3986.
82 | *
83 | *
84 | * All letters used in the percent-encoding are in uppercase.
85 | *
86 | * @param value the string to normalize.
87 | * @param encodeSlash if encode '/'
88 | * @return the normalized string.
89 | */
90 | public static String uriEncode(String value, boolean encodeSlash) {
91 | try {
92 | StringBuilder builder = new StringBuilder();
93 | for (byte b : value.getBytes(AipClientConst.DEFAULT_ENCODING)) {
94 | if (URI_UNRESERVED_CHARACTERS.get(b & 0xFF)) {
95 | builder.append((char) b);
96 | } else {
97 | builder.append(PERCENT_ENCODED_STRINGS[b & 0xFF]);
98 | }
99 | }
100 | String encodeString = builder.toString();
101 | if (!encodeSlash) {
102 | return encodeString.replace("%2F", "/");
103 | }
104 | return encodeString;
105 | } catch (UnsupportedEncodingException e) {
106 | throw new RuntimeException(e);
107 | }
108 | }
109 |
110 | public static String getCanonicalTime() {
111 | SimpleDateFormat utcDayFormat = new SimpleDateFormat("yyyy-MM-dd");
112 | SimpleDateFormat utcHourFormat = new SimpleDateFormat("hh:mm:ss");
113 | utcDayFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
114 | utcHourFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
115 | Date now = new Date();
116 | return String.format("%sT%sZ", utcDayFormat.format(now), utcHourFormat.format(now));
117 | }
118 |
119 | /**
120 | *
121 | * @param filePath 文件路径
122 | * @return file bytes
123 | * @throws IOException 读取文件错误
124 | */
125 |
126 | public static byte[] readFileByBytes(String filePath) throws IOException {
127 | File file = new File(filePath);
128 | if (!file.exists()) {
129 | throw new FileNotFoundException(filePath);
130 | }
131 |
132 | ByteArrayOutputStream bos = new ByteArrayOutputStream(((int) file.length()));
133 | BufferedInputStream in = null;
134 | try {
135 | in = new BufferedInputStream(new FileInputStream(file));
136 | int bufSize = 1024;
137 | byte[] buffer = new byte[bufSize];
138 | int len = 0;
139 | while (-1 != (len = in.read(buffer, 0, bufSize))) {
140 | bos.write(buffer, 0, len);
141 | }
142 | return bos.toByteArray();
143 | } finally {
144 | try {
145 | if (in != null) {
146 | in.close();
147 | }
148 | } catch (IOException e) {
149 | e.printStackTrace();
150 | }
151 | bos.close();
152 | }
153 | }
154 |
155 | public static void writeBytesToFileSystem(byte[] data, String output) throws IOException {
156 | DataOutputStream out = null;
157 | try {
158 | out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(output)));
159 | out.write(data);
160 | } finally {
161 | if (out != null) {
162 | out.close();
163 | }
164 | }
165 | }
166 |
167 | public static JSONObject getGeneralError(int errorCode, String errorMsg) {
168 | JSONObject json = new JSONObject();
169 | json.put("error_code", errorCode);
170 | json.put("error_msg", errorMsg);
171 | return json;
172 | }
173 |
174 | public static boolean isLiteral(String input) {
175 | Pattern pattern = Pattern.compile("[0-9a-zA-Z_]*");
176 | return pattern.matcher(input).matches();
177 | }
178 | }
179 |
--------------------------------------------------------------------------------
/src/main/java/com/baidu/aip/speech/AipSpeech.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2017 Baidu, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
5 | * the License. You may obtain a copy of the License at
6 | *
7 | * http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
10 | * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
11 | * specific language governing permissions and limitations under the License.
12 | */
13 | package com.baidu.aip.speech;
14 |
15 | import com.baidu.aip.client.BaseClient;
16 | import com.baidu.aip.error.AipError;
17 | import com.baidu.aip.http.*;
18 | import com.baidu.aip.util.AipClientConst;
19 | import com.baidu.aip.util.Base64Util;
20 | import com.baidu.aip.util.SignUtil;
21 | import com.baidu.aip.util.Util;
22 | import org.json.JSONException;
23 | import org.json.JSONObject;
24 |
25 | import java.io.IOException;
26 | import java.util.HashMap;
27 | import java.util.List;
28 | import java.util.Map;
29 |
30 | public class AipSpeech extends BaseClient {
31 |
32 | public AipSpeech(String appId, String apiKey, String secretKey) {
33 | super(appId, apiKey, secretKey);
34 | }
35 |
36 | public JSONObject asr(String path, String format, int rate, HashMap options) {
37 | try {
38 | byte[] imgData = Util.readFileByBytes(path);
39 | return asr(imgData, format, rate, options);
40 | } catch (IOException e) {
41 | e.printStackTrace();
42 | return AipError.IMAGE_READ_ERROR.toJsonResult();
43 | }
44 | }
45 |
46 | public JSONObject asr(byte[] data, String format, int rate, HashMap options) {
47 | AipRequest request = new AipRequest();
48 |
49 | preOperation(request); // get access token
50 | if (this.isBceKey.get()) {
51 | // get access token failed!
52 | return Util.getGeneralError(
53 | AipClientConst.OPENAPI_NO_ACCESS_ERROR_CODE,
54 | AipClientConst.OPENAPI_NO_ACCESS_ERROR_MSG);
55 | }
56 | // state.setState(EAuthState.STATE_TRUE_AIP_USER);
57 | String base64Content = Base64Util.encode(data);
58 | request.addBody("speech", base64Content);
59 | request.addBody("format", format);
60 | request.addBody("rate", rate);
61 | request.addBody("channel", 1);
62 | String cuid = SignUtil.md5(accessToken, "UTF-8");
63 | request.addBody("cuid", cuid);
64 | request.addBody("token", accessToken);
65 | request.addBody("len", data.length);
66 | if (options != null) {
67 | request.addBody(options);
68 | }
69 | // no post operation
70 |
71 | request.setUri(SpeechConsts.SPEECH_ASR_URL);
72 | request.setBodyFormat(EBodyFormat.RAW_JSON);
73 | request.addHeader(Headers.CONTENT_TYPE, HttpContentType.JSON_DATA);
74 |
75 | return requestServer(request);
76 | }
77 |
78 | public JSONObject asr(String url, String callback, String format, int rate, HashMap options) {
79 | AipRequest request = new AipRequest();
80 |
81 | preOperation(request); // get access token
82 | if (this.isBceKey.get()) {
83 | // get access token failed!
84 | return Util.getGeneralError(
85 | AipClientConst.OPENAPI_NO_ACCESS_ERROR_CODE,
86 | AipClientConst.OPENAPI_NO_ACCESS_ERROR_MSG);
87 | }
88 | request.addBody("url", url);
89 | request.addBody("format", format);
90 | request.addBody("rate", rate);
91 | request.addBody("channel", 1);
92 | String cuid = SignUtil.md5(accessToken, "UTF-8");
93 | request.addBody("cuid", cuid);
94 | request.addBody("token", accessToken);
95 | request.addBody("callback", callback);
96 | if (options != null) {
97 | request.addBody(options);
98 | }
99 | request.setUri(SpeechConsts.SPEECH_ASR_URL);
100 | request.setBodyFormat(EBodyFormat.RAW_JSON);
101 | request.addHeader(Headers.CONTENT_TYPE, HttpContentType.JSON_DATA);
102 |
103 | return requestServer(request);
104 | }
105 |
106 | public TtsResponse synthesis(String text, String lang, int ctp, HashMap options) {
107 | AipRequest request = new AipRequest();
108 | preOperation(request);
109 | if (this.isBceKey.get()) {
110 | // get access token failed!
111 | TtsResponse response = new TtsResponse();
112 | JSONObject msg = Util.getGeneralError(AipClientConst.OPENAPI_NO_ACCESS_ERROR_CODE,
113 | AipClientConst.OPENAPI_NO_ACCESS_ERROR_MSG);
114 | response.setResult(msg);
115 | return response;
116 | }
117 | request.addBody("tex", text);
118 | request.addBody("lan", lang);
119 | request.addBody("tok", accessToken);
120 | request.addBody("ctp", ctp);
121 | String cuid = SignUtil.md5(accessToken, "UTF-8");
122 | request.addBody("cuid", cuid);
123 | if (options != null) {
124 | request.addBody(options);
125 | }
126 | request.setUri(SpeechConsts.SPEECH_TTS_URL);
127 |
128 | TtsResponse response = new TtsResponse();
129 | AipResponse res = AipHttpClient.post(request);
130 | if (res == null) {
131 | response.setResult(Util.getGeneralError(-1,
132 | "null response from server"));
133 | return response;
134 | }
135 | Map> header = res.getHeader();
136 | if (header.containsKey("content-type")) {
137 | String contentType = res.getHeader().get("content-type").get(0);
138 | if (contentType.contains("json")) {
139 | String data = res.getBodyStr();
140 | JSONObject json = new JSONObject(data);
141 | response.setResult(json);
142 | }
143 | else {
144 | byte[] binData = res.getBody();
145 | response.setData(binData);
146 | }
147 | }
148 | else {
149 | LOGGER.error("synthesis get no content-type in header: " + header);
150 | LOGGER.info("synthesis response status: " + res.getStatus());
151 | try {
152 | JSONObject json = new JSONObject(res.getBodyStr());
153 | response.setResult(json);
154 | } catch (JSONException e) {
155 | response.setData(res.getBody());
156 | }
157 | }
158 | return response;
159 | }
160 | }
161 |
--------------------------------------------------------------------------------
/src/main/java/com/baidu/aip/imageprocess/AipImageProcess.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2017 Baidu, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
5 | * the License. You may obtain a copy of the License at
6 | *
7 | * http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
10 | * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
11 | * specific language governing permissions and limitations under the License.
12 | */
13 |
14 | package com.baidu.aip.imageprocess;
15 |
16 | import com.baidu.aip.client.BaseClient;
17 | import com.baidu.aip.error.AipError;
18 | import com.baidu.aip.http.AipRequest;
19 | import com.baidu.aip.util.Base64Util;
20 | import com.baidu.aip.util.Util;
21 | import org.json.JSONObject;
22 |
23 | import java.io.IOException;
24 | import java.util.HashMap;
25 |
26 | public class AipImageProcess extends BaseClient {
27 |
28 | public AipImageProcess(String appId, String apiKey, String secretKey) {
29 | super(appId, apiKey, secretKey);
30 | }
31 |
32 | /**
33 | * 图像无损放大接口
34 | * 输入一张图片,可以在尽量保持图像质量的条件下,将图像在长宽方向各放大两倍。
35 | *
36 | * @param image - 二进制图像数据
37 | * @param options - 可选参数对象,key: value都为string类型
38 | * options - options列表:
39 | * @return JSONObject
40 | */
41 | public JSONObject imageQualityEnhance(byte[] image, HashMap options) {
42 | AipRequest request = new AipRequest();
43 | preOperation(request);
44 |
45 | String base64Content = Base64Util.encode(image);
46 | request.addBody("image", base64Content);
47 | if (options != null) {
48 | request.addBody(options);
49 | }
50 | request.setUri(ImageProcessConsts.IMAGE_QUALITY_ENHANCE);
51 | postOperation(request);
52 | return requestServer(request);
53 | }
54 |
55 | /**
56 | * 图像无损放大接口
57 | * 输入一张图片,可以在尽量保持图像质量的条件下,将图像在长宽方向各放大两倍。
58 | *
59 | * @param image - 本地图片路径
60 | * @param options - 可选参数对象,key: value都为string类型
61 | * options - options列表:
62 | * @return JSONObject
63 | */
64 | public JSONObject imageQualityEnhance(String image, HashMap options) {
65 | try {
66 | byte[] data = Util.readFileByBytes(image);
67 | return imageQualityEnhance(data, options);
68 | } catch (IOException e) {
69 | e.printStackTrace();
70 | return AipError.IMAGE_READ_ERROR.toJsonResult();
71 | }
72 | }
73 |
74 | /**
75 | * 图像去雾接口
76 | * 对浓雾天气下拍摄,导致细节无法辨认的图像进行去雾处理,还原更清晰真实的图像。
77 | *
78 | * @param image - 二进制图像数据
79 | * @param options - 可选参数对象,key: value都为string类型
80 | * options - options列表:
81 | * @return JSONObject
82 | */
83 | public JSONObject dehaze(byte[] image, HashMap options) {
84 | AipRequest request = new AipRequest();
85 | preOperation(request);
86 |
87 | String base64Content = Base64Util.encode(image);
88 | request.addBody("image", base64Content);
89 | if (options != null) {
90 | request.addBody(options);
91 | }
92 | request.setUri(ImageProcessConsts.DEHAZE);
93 | postOperation(request);
94 | return requestServer(request);
95 | }
96 |
97 | /**
98 | * 图像去雾接口
99 | * 对浓雾天气下拍摄,导致细节无法辨认的图像进行去雾处理,还原更清晰真实的图像。
100 | *
101 | * @param image - 本地图片路径
102 | * @param options - 可选参数对象,key: value都为string类型
103 | * options - options列表:
104 | * @return JSONObject
105 | */
106 | public JSONObject dehaze(String image, HashMap options) {
107 | try {
108 | byte[] data = Util.readFileByBytes(image);
109 | return dehaze(data, options);
110 | } catch (IOException e) {
111 | e.printStackTrace();
112 | return AipError.IMAGE_READ_ERROR.toJsonResult();
113 | }
114 | }
115 |
116 | /**
117 | * 图像对比度增强接口
118 | * 调整过暗或者过亮图像的对比度,使图像更加鲜明。
119 | *
120 | * @param image - 二进制图像数据
121 | * @param options - 可选参数对象,key: value都为string类型
122 | * options - options列表:
123 | * @return JSONObject
124 | */
125 | public JSONObject contrastEnhance(byte[] image, HashMap options) {
126 | AipRequest request = new AipRequest();
127 | preOperation(request);
128 |
129 | String base64Content = Base64Util.encode(image);
130 | request.addBody("image", base64Content);
131 | if (options != null) {
132 | request.addBody(options);
133 | }
134 | request.setUri(ImageProcessConsts.CONTRAST_ENHANCE);
135 | postOperation(request);
136 | return requestServer(request);
137 | }
138 |
139 | /**
140 | * 图像对比度增强接口
141 | * 调整过暗或者过亮图像的对比度,使图像更加鲜明。
142 | *
143 | * @param image - 本地图片路径
144 | * @param options - 可选参数对象,key: value都为string类型
145 | * options - options列表:
146 | * @return JSONObject
147 | */
148 | public JSONObject contrastEnhance(String image, HashMap options) {
149 | try {
150 | byte[] data = Util.readFileByBytes(image);
151 | return contrastEnhance(data, options);
152 | } catch (IOException e) {
153 | e.printStackTrace();
154 | return AipError.IMAGE_READ_ERROR.toJsonResult();
155 | }
156 | }
157 |
158 | /**
159 | * 黑白图像上色接口
160 | * 智能识别黑白图像内容并填充色彩,使黑白图像变得鲜活。
161 | *
162 | * @param image - 二进制图像数据
163 | * @param options - 可选参数对象,key: value都为string类型
164 | * options - options列表:
165 | * @return JSONObject
166 | */
167 | public JSONObject colourize(byte[] image, HashMap options) {
168 | AipRequest request = new AipRequest();
169 | preOperation(request);
170 |
171 | String base64Content = Base64Util.encode(image);
172 | request.addBody("image", base64Content);
173 | if (options != null) {
174 | request.addBody(options);
175 | }
176 | request.setUri(ImageProcessConsts.COLOURIZE);
177 | postOperation(request);
178 | return requestServer(request);
179 | }
180 |
181 | /**
182 | * 黑白图像上色接口
183 | * 智能识别黑白图像内容并填充色彩,使黑白图像变得鲜活。
184 | *
185 | * @param image - 本地图片路径
186 | * @param options - 可选参数对象,key: value都为string类型
187 | * options - options列表:
188 | * @return JSONObject
189 | */
190 | public JSONObject colourize(String image, HashMap options) {
191 | try {
192 | byte[] data = Util.readFileByBytes(image);
193 | return colourize(data, options);
194 | } catch (IOException e) {
195 | e.printStackTrace();
196 | return AipError.IMAGE_READ_ERROR.toJsonResult();
197 | }
198 | }
199 |
200 | /**
201 | * 拉伸图像恢复接口
202 | * 自动识别过度拉伸的图像,将图像内容恢复成正常比例。
203 | *
204 | * @param image - 二进制图像数据
205 | * @param options - 可选参数对象,key: value都为string类型
206 | * options - options列表:
207 | * @return JSONObject
208 | */
209 | public JSONObject stretchRestore(byte[] image, HashMap options) {
210 | AipRequest request = new AipRequest();
211 | preOperation(request);
212 |
213 | String base64Content = Base64Util.encode(image);
214 | request.addBody("image", base64Content);
215 | if (options != null) {
216 | request.addBody(options);
217 | }
218 | request.setUri(ImageProcessConsts.STRETCH_RESTORE);
219 | postOperation(request);
220 | return requestServer(request);
221 | }
222 |
223 | /**
224 | * 拉伸图像恢复接口
225 | * 自动识别过度拉伸的图像,将图像内容恢复成正常比例。
226 | *
227 | * @param image - 本地图片路径
228 | * @param options - 可选参数对象,key: value都为string类型
229 | * options - options列表:
230 | * @return JSONObject
231 | */
232 | public JSONObject stretchRestore(String image, HashMap options) {
233 | try {
234 | byte[] data = Util.readFileByBytes(image);
235 | return stretchRestore(data, options);
236 | } catch (IOException e) {
237 | e.printStackTrace();
238 | return AipError.IMAGE_READ_ERROR.toJsonResult();
239 | }
240 | }
241 |
242 | }
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "{}"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright {yyyy} {name of copyright owner}
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/src/main/java/com/baidu/aip/client/BaseClient.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2017 Baidu, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
5 | * the License. You may obtain a copy of the License at
6 | *
7 | * http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
10 | * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
11 | * specific language governing permissions and limitations under the License.
12 | */
13 | package com.baidu.aip.client;
14 |
15 | import com.baidu.aip.auth.CloudAuth;
16 | import com.baidu.aip.auth.DevAuth;
17 | import com.baidu.aip.error.AipError;
18 | import com.baidu.aip.http.AipHttpClient;
19 | import com.baidu.aip.http.AipRequest;
20 | import com.baidu.aip.http.AipResponse;
21 | import com.baidu.aip.http.Headers;
22 | import com.baidu.aip.http.HttpContentType;
23 | import com.baidu.aip.http.HttpMethodName;
24 | import com.baidu.aip.util.AipClientConfiguration;
25 | import com.baidu.aip.util.AipClientConst;
26 | import com.baidu.aip.util.SignUtil;
27 | import com.baidu.aip.util.Util;
28 | import org.json.JSONException;
29 | import org.json.JSONObject;
30 | import org.slf4j.Logger;
31 | import org.slf4j.LoggerFactory;
32 |
33 | import java.io.UnsupportedEncodingException;
34 | import java.net.Proxy;
35 | import java.util.Calendar;
36 | import java.util.concurrent.atomic.AtomicBoolean;
37 |
38 | public abstract class BaseClient {
39 |
40 | protected String appId;
41 | protected String aipKey;
42 | protected String aipToken;
43 | protected String accessToken; // 不适用于使用公有云ak/sk的用户
44 | protected AtomicBoolean isAuthorized;
45 | protected AtomicBoolean isBceKey; // 是否为公有云用户
46 | protected Calendar expireDate;
47 | protected AuthState state;
48 | protected AipClientConfiguration config;
49 | protected static final Logger LOGGER = LoggerFactory.getLogger(BaseClient.class);
50 |
51 | class AuthState {
52 |
53 | private EAuthState state;
54 |
55 | public AuthState() {
56 | state = EAuthState.STATE_UNKNOWN;
57 | }
58 |
59 | public String toString() {
60 | return state.name();
61 | }
62 |
63 | public EAuthState getState() {
64 | return state;
65 | }
66 |
67 | public void setState(EAuthState state) {
68 | this.state = state;
69 | }
70 |
71 | public void transfer(boolean value) {
72 | switch (state) {
73 | case STATE_UNKNOWN: {
74 | if (value) {
75 | state = EAuthState.STATE_AIP_AUTH_OK;
76 | isBceKey.set(false);
77 | }
78 | else {
79 | state = EAuthState.STATE_TRUE_CLOUD_USER;
80 | isBceKey.set(true);
81 | }
82 | break;
83 | }
84 | case STATE_AIP_AUTH_OK: {
85 | if (value) {
86 | state = EAuthState.STATE_TRUE_AIP_USER;
87 | isBceKey.set(false);
88 | isAuthorized.set(true);
89 | }
90 | else {
91 | state = EAuthState.STATE_POSSIBLE_CLOUD_USER;
92 | isBceKey.set(true);
93 | }
94 | break;
95 | }
96 | case STATE_TRUE_AIP_USER:
97 | break;
98 | case STATE_POSSIBLE_CLOUD_USER: {
99 | if (value) {
100 | state = EAuthState.STATE_TRUE_CLOUD_USER;
101 | isBceKey.set(true);
102 | }
103 | else {
104 | state = EAuthState.STATE_TRUE_AIP_USER;
105 | isBceKey.set(false);
106 | isAuthorized.set(true);
107 | }
108 | break;
109 | }
110 | case STATE_TRUE_CLOUD_USER:
111 | break;
112 | default:
113 | break;
114 | }
115 | }
116 | }
117 |
118 | /*
119 | * BaseClient constructor, default as AIP user
120 | */
121 | protected BaseClient(String appId, String apiKey, String secretKey) {
122 | this.appId = appId;
123 | this.aipKey = apiKey;
124 | this.aipToken = secretKey;
125 | isAuthorized = new AtomicBoolean(false);
126 | isBceKey = new AtomicBoolean(false);
127 | accessToken = null;
128 | expireDate = null;
129 | state = new AuthState();
130 | }
131 |
132 | /**
133 | *
134 | * @param timeout 服务器建立连接的超时时间(单位:毫秒)
135 | */
136 | public void setConnectionTimeoutInMillis(int timeout) {
137 | if (config == null) {
138 | config = new AipClientConfiguration();
139 | }
140 | this.config.setConnectionTimeoutMillis(timeout);
141 | }
142 |
143 | /**
144 | *
145 | * @param timeout 通过打开的连接传输数据的超时时间(单位:毫秒)
146 | */
147 | public void setSocketTimeoutInMillis(int timeout) {
148 | if (config == null) {
149 | config = new AipClientConfiguration();
150 | }
151 | this.config.setSocketTimeoutMillis(timeout);
152 | }
153 |
154 | /**
155 | * 设置访问网络需要的http代理
156 | * @param host 代理服务器地址
157 | * @param port 代理服务器端口
158 | */
159 | public void setHttpProxy(String host, int port) {
160 | if (config == null) {
161 | config = new AipClientConfiguration();
162 | }
163 | this.config.setProxy(host, port, Proxy.Type.HTTP);
164 | }
165 |
166 | /**
167 | * 设置访问网络需要的socket代理
168 | * @param host 代理服务器地址
169 | * @param port 代理服务器端口
170 | */
171 | public void setSocketProxy(String host, int port) {
172 | if (config == null) {
173 | config = new AipClientConfiguration();
174 | }
175 | this.config.setProxy(host, port, Proxy.Type.SOCKS);
176 | }
177 |
178 | /**
179 | * get OAuth access token, synchronized function
180 | * @param config 网络连接设置
181 | */
182 | protected synchronized void getAccessToken(AipClientConfiguration config) {
183 | if (!needAuth()) {
184 | if (LOGGER.isDebugEnabled()) {
185 | LOGGER.debug(String.format("app[%s] no need to auth", this.appId));
186 | }
187 | return;
188 | }
189 | JSONObject res = DevAuth.oauth(aipKey, aipToken, config);
190 | if (res == null) {
191 | LOGGER.warn("oauth get null response");
192 | return;
193 | }
194 | if (!res.isNull("access_token")) {
195 | // openAPI认证成功
196 | state.transfer(true);
197 | accessToken = res.getString("access_token");
198 |
199 | LOGGER.info("get access_token success. current state: " + state.toString());
200 | Integer expireSec = res.getInt("expires_in");
201 | Calendar c = Calendar.getInstance();
202 | c.add(Calendar.SECOND, expireSec);
203 | expireDate = c;
204 | // isBceKey.set(false);
205 | // 验证接口权限
206 | String[] scope = res.getString("scope").split(" ");
207 | boolean hasRight = false;
208 | for (String str : scope) {
209 | if (AipClientConst.AI_ACCESS_RIGHT.contains(str)) {
210 | // 权限验证通过
211 | hasRight = true;
212 | break;
213 | }
214 | }
215 | state.transfer(hasRight);
216 | if (LOGGER.isDebugEnabled()) {
217 | LOGGER.debug("current state after check priviledge: " + state.toString());
218 | }
219 | }
220 | else if (!res.isNull("error_code")) {
221 | state.transfer(false);
222 | LOGGER.warn("oauth get error, current state: " + state.toString());
223 | }
224 | }
225 |
226 | /*
227 | * 需要重新获取access_token的条件:
228 | * 1. 是DEV用户,即 isBceKey为false
229 | * 2. isAuthorized为false,或isAuthorized为true,但当前时间晚于expireDate前一天
230 | */
231 | protected Boolean needAuth() {
232 | if (isBceKey.get()) {
233 | return false;
234 | }
235 | Calendar c = Calendar.getInstance();
236 | c.add(Calendar.DATE, 1);
237 | return !isAuthorized.get() || c.after(expireDate);
238 | }
239 |
240 | /*
241 | * 为DEV创建的用户填充body
242 | */
243 | protected void preOperation(AipRequest request) {
244 | if (needAuth()) {
245 | getAccessToken(config);
246 | }
247 |
248 | request.setHttpMethod(HttpMethodName.POST);
249 | request.addHeader(Headers.CONTENT_TYPE, HttpContentType.FORM_URLENCODE_DATA);
250 | request.addHeader("accept", "*/*");
251 | request.setConfig(config);
252 | }
253 |
254 | /*
255 | * 为公有云用户填充http header,传入的request中body¶m已经ready
256 | * 对于DEV用户,则将access_token放到url中
257 | */
258 | protected void postOperation(AipRequest request) {
259 | if (isBceKey.get()) {
260 | // add aipSdk param
261 | request.addParam("aipSdk", "java");
262 |
263 | String bodyStr = request.getBodyStr();
264 |
265 | try {
266 | int len = bodyStr.getBytes(request.getContentEncoding()).length;
267 | request.addHeader(Headers.CONTENT_LENGTH, Integer.toString(len));
268 | } catch (UnsupportedEncodingException e) {
269 | e.printStackTrace();
270 | }
271 |
272 | request.addHeader(Headers.CONTENT_MD5, SignUtil.md5(bodyStr, request.getContentEncoding()));
273 |
274 | String timestamp = Util.getCanonicalTime();
275 | request.addHeader(Headers.HOST, request.getUri().getHost());
276 | request.addHeader(Headers.BCE_DATE, timestamp);
277 | request.addHeader(Headers.AUTHORIZATION, CloudAuth.sign(request, this.aipKey, this.aipToken, timestamp));
278 | }
279 | else {
280 | request.addParam("aipSdk", "java");
281 | request.addParam("access_token", accessToken);
282 | }
283 | }
284 |
285 | /**
286 | * send request to server
287 | * @param request AipRequest object
288 | * @return JSONObject of server response
289 | */
290 | protected JSONObject requestServer(AipRequest request) {
291 | // 请求API
292 | AipResponse response = AipHttpClient.post(request);
293 | String resData = response.getBodyStr();
294 | Integer status = response.getStatus();
295 | if (status.equals(200) && !resData.equals("")) {
296 | try {
297 | JSONObject res = new JSONObject(resData);
298 | if (state.getState().equals(EAuthState.STATE_POSSIBLE_CLOUD_USER)) {
299 | boolean cloudAuthState = res.isNull("error_code")
300 | || res.getInt("error_code") != AipClientConst.IAM_ERROR_CODE;
301 | state.transfer(cloudAuthState);
302 | if (LOGGER.isDebugEnabled()) {
303 | LOGGER.debug("state after cloud auth: " + state.toString());
304 | }
305 | if (!cloudAuthState) {
306 | return Util.getGeneralError(
307 | AipClientConst.OPENAPI_NO_ACCESS_ERROR_CODE,
308 | AipClientConst.OPENAPI_NO_ACCESS_ERROR_MSG);
309 | }
310 | }
311 | return res;
312 | } catch (JSONException e) {
313 | return Util.getGeneralError(-1, resData);
314 | }
315 | }
316 | else {
317 | LOGGER.warn(String.format("call failed! response status: %d, data: %s", status, resData));
318 | return AipError.NET_TIMEOUT_ERROR.toJsonResult();
319 |
320 | }
321 | }
322 |
323 |
324 | // getters and setters for UT
325 | private void setAccessToken(String accessToken) {
326 | this.accessToken = accessToken;
327 | }
328 |
329 | private AtomicBoolean getIsAuthorized() {
330 | return isAuthorized;
331 | }
332 |
333 | private void setIsAuthorized(boolean isAuthorized) {
334 | this.isAuthorized.set(isAuthorized);
335 | }
336 |
337 | private AtomicBoolean getIsBceKey() {
338 | return isBceKey;
339 | }
340 |
341 | private void setIsBceKey(boolean isBceKey) {
342 | this.isBceKey.set(isBceKey);
343 | }
344 |
345 | private Calendar getExpireDate() {
346 | return expireDate;
347 | }
348 |
349 | private void setExpireDate(Calendar expireDate) {
350 | this.expireDate = expireDate;
351 | }
352 |
353 | }
354 |
--------------------------------------------------------------------------------
/src/main/java/com/baidu/aip/contentcensor/AipContentCensor.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2017 Baidu, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
5 | * the License. You may obtain a copy of the License at
6 | *
7 | * http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
10 | * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
11 | * specific language governing permissions and limitations under the License.
12 | */
13 | package com.baidu.aip.contentcensor;
14 |
15 | import com.baidu.aip.client.BaseClient;
16 | import com.baidu.aip.error.AipError;
17 | import com.baidu.aip.http.AipRequest;
18 | import com.baidu.aip.http.EBodyFormat;
19 | import com.baidu.aip.http.Headers;
20 | import com.baidu.aip.http.HttpContentType;
21 | import com.baidu.aip.util.Base64Util;
22 | import com.baidu.aip.util.ImageUtil;
23 | import com.baidu.aip.util.Util;
24 | import org.json.JSONArray;
25 | import org.json.JSONObject;
26 |
27 | import java.io.IOException;
28 | import java.util.ArrayList;
29 | import java.util.HashMap;
30 | import java.util.List;
31 | import java.util.Map;
32 |
33 | public class AipContentCensor extends BaseClient {
34 |
35 | public AipContentCensor(String appId, String aipKey, String aipToken) {
36 | super(appId, aipKey, aipToken);
37 | }
38 |
39 | /**
40 | * 色情识别接口
41 | * @param imgPath 本地图片路径
42 | * @return JSONObject
43 | */
44 | public JSONObject antiPorn(String imgPath) {
45 | try {
46 | byte[] imgData = Util.readFileByBytes(imgPath);
47 | return antiPorn(imgData);
48 | } catch (IOException e) {
49 | return AipError.IMAGE_READ_ERROR.toJsonResult();
50 | }
51 | }
52 |
53 | /**
54 | * 色情识别接口
55 | * @param imgData 图片二进制数据
56 | * @return JSONObject
57 | */
58 | public JSONObject antiPorn(byte[] imgData) {
59 | AipRequest request = new AipRequest();
60 | // check param
61 |
62 | JSONObject checkRet = checkParam(imgData);
63 | if (!"0".equals(checkRet.getString("error_code"))) {
64 | return checkRet;
65 | }
66 | preOperation(request);
67 | // add API params
68 | String base64Content = Base64Util.encode(imgData);
69 |
70 | request.addBody("image", base64Content);
71 | request.setUri(ContentCensorConsts.ANTI_PORN_URL);
72 | postOperation(request);
73 |
74 | return requestServer(request);
75 | }
76 |
77 | /**
78 | * GIF色情图像识别
79 | * @param imgPath 本地图片路径
80 | * @return JSONObject
81 | */
82 | public JSONObject antiPornGif(String imgPath) {
83 | try {
84 | byte[] imgData = Util.readFileByBytes(imgPath);
85 | return antiPornGif(imgData);
86 | } catch (IOException e) {
87 | return AipError.IMAGE_READ_ERROR.toJsonResult();
88 | }
89 | }
90 |
91 | /**
92 | * GIF色情图像识别
93 | * @param imgData 图片二进制数据
94 | * @return JSONObject
95 | */
96 | public JSONObject antiPornGif(byte[] imgData) {
97 | AipRequest request = new AipRequest();
98 | // check param
99 |
100 | JSONObject checkRet = checkImgFormat(imgData, "gif");
101 | if (!"0".equals(checkRet.getString("error_code"))) {
102 | return checkRet;
103 | }
104 |
105 | preOperation(request);
106 | // add API params
107 | String base64Content = Base64Util.encode(imgData);
108 | request.addBody("image", base64Content);
109 | request.setUri(ContentCensorConsts.ANTI_PORN_GIF_URL);
110 |
111 | postOperation(request);
112 |
113 | return requestServer(request);
114 | }
115 |
116 | /**
117 | * 暴恐图像识别
118 | * @param imgPath 本地图片路径
119 | * @return JSONObject
120 | */
121 | public JSONObject antiTerror(String imgPath) {
122 | try {
123 | byte[] imgData = Util.readFileByBytes(imgPath);
124 | return antiTerror(imgData);
125 | } catch (IOException e) {
126 | return AipError.IMAGE_READ_ERROR.toJsonResult();
127 | }
128 | }
129 |
130 | /**
131 | * 暴恐图像识别
132 | * @param imgData 图片二进制数据
133 | * @return JSONObject
134 | */
135 | public JSONObject antiTerror(byte[] imgData) {
136 | AipRequest request = new AipRequest();
137 |
138 | preOperation(request);
139 | // add API params
140 | String base64Content = Base64Util.encode(imgData);
141 |
142 | request.addBody("image", base64Content);
143 | request.setUri(ContentCensorConsts.ANTI_TERROR_URL);
144 | postOperation(request);
145 |
146 | return requestServer(request);
147 | }
148 |
149 | /**
150 | * 组合审核接口
151 | * @param imgPath 本地图片路径或url
152 | * @param type imgPath类型:FILE或URL
153 | * @param scenes 需要审核的服务类型
154 | * @param options 可选参数
155 | * @return JSONObject
156 | */
157 | public JSONObject imageCensorComb(String imgPath, EImgType type,
158 | List scenes, HashMap options) {
159 | if (type == EImgType.FILE) {
160 | try {
161 | byte[] imgData = Util.readFileByBytes(imgPath);
162 | return imageCensorComb(imgData, scenes, options);
163 | } catch (IOException e) {
164 | return AipError.IMAGE_READ_ERROR.toJsonResult();
165 | }
166 | }
167 |
168 | // url
169 | AipRequest request = new AipRequest();
170 |
171 | request.addBody("imgUrl", imgPath);
172 |
173 | return imageCensorCombHelper(request, scenes, options);
174 | }
175 |
176 | /**
177 | * 组合审核接口
178 | * @param imgData 图片二进制数据
179 | * @param scenes 需要审核的服务类型
180 | * @param options 可选参数
181 | * @return JSONObject
182 | */
183 | public JSONObject imageCensorComb(byte[] imgData, List scenes, HashMap options) {
184 | AipRequest request = new AipRequest();
185 |
186 | String base64Content = Base64Util.encode(imgData);
187 | request.addBody("image", base64Content);
188 |
189 | return imageCensorCombHelper(request, scenes, options);
190 | }
191 |
192 | private JSONObject imageCensorCombHelper(AipRequest request, List scenes, HashMap options) {
193 | preOperation(request);
194 | JSONArray obj = new JSONArray();
195 | for (String scene : scenes) {
196 | obj.put(scene);
197 | }
198 | request.addBody("scenes", obj);
199 |
200 | if (options != null) {
201 | for (Map.Entry entry : options.entrySet()) {
202 | request.addBody(entry.getKey(), entry.getValue());
203 | }
204 | }
205 | request.setUri(ContentCensorConsts.IMAGE_CENSOR_COMB_URL);
206 | request.setBodyFormat(EBodyFormat.RAW_JSON);
207 | request.addHeader(Headers.CONTENT_TYPE, HttpContentType.JSON_DATA);
208 | postOperation(request);
209 | return requestServer(request);
210 | }
211 |
212 | /**
213 | * 头像审核接口
214 | * @param imgPaths 本地图片路径或图片url列表
215 | * @param type imgPaths参数类型:FILE或URL
216 | * @param options 可选参数
217 | * @return JSONObject
218 | */
219 | public JSONObject faceAudit(List imgPaths, EImgType type,
220 | HashMap options) {
221 | if (type == EImgType.FILE) {
222 | try {
223 | byte[][] imgData = new byte[imgPaths.size()][];
224 | int idx = 0;
225 | for (String path : imgPaths) {
226 | imgData[idx] = Util.readFileByBytes(path);
227 | ++idx;
228 | }
229 | return faceAudit(imgData, options);
230 | } catch (IOException e) {
231 | e.printStackTrace();
232 | return AipError.IMAGE_READ_ERROR.toJsonResult();
233 | }
234 | }
235 |
236 | AipRequest request = new AipRequest();
237 | request.addBody("imgUrls", Util.mkString(imgPaths.iterator(), ','));
238 |
239 | return faceAuditHelper(request, options);
240 | }
241 |
242 | /**
243 | * 头像审核接口
244 | * @param imgData 图片二进制数据数组
245 | * @param options 可选参数
246 | * @return JSONObject
247 | */
248 | public JSONObject faceAudit(byte[][] imgData, HashMap options) {
249 | AipRequest request = new AipRequest();
250 | ArrayList buffer = new ArrayList();
251 | for (byte[] data : imgData) {
252 | String base64Str = Base64Util.encode(data);
253 | buffer.add(base64Str);
254 | }
255 | String imgDataAll = Util.mkString(buffer.iterator(), ',');
256 |
257 | request.addBody("images", imgDataAll);
258 | if (options != null) {
259 | for (Map.Entry entry : options.entrySet()) {
260 | request.addBody(entry.getKey(), entry.getValue());
261 | }
262 | }
263 |
264 | return faceAuditHelper(request, options);
265 | }
266 |
267 | private JSONObject faceAuditHelper(AipRequest request, HashMap options) {
268 | preOperation(request);
269 | request.setUri(ContentCensorConsts.FACE_AUDIT_URL);
270 | postOperation(request);
271 | return requestServer(request);
272 | }
273 |
274 | /**
275 | * 反馈接口
276 | * @param reportData 反馈图片识别结果好坏的json数组
277 | * @return JSONObject
278 | */
279 | public JSONObject report(JSONArray reportData) {
280 | AipRequest request = new AipRequest();
281 | preOperation(request);
282 | request.addBody("feedback", reportData);
283 | request.setUri(ContentCensorConsts.REPORT_URL);
284 | request.setBodyFormat(EBodyFormat.RAW_JSON);
285 | request.addHeader(Headers.CONTENT_TYPE, HttpContentType.JSON_DATA);
286 | postOperation(request);
287 | return requestServer(request);
288 | }
289 |
290 |
291 | /**
292 | * 图像审核接口
293 | * 本接口除了支持自定义配置外,还对返回结果进行了总体的包装,按照用户在控制台中配置的规则直接返回是否合规,如果不合规则指出具体不合规的内容。
294 | * @param image 本地图片路径或图片url
295 | * @param type image参数类型:FILE或URL
296 | * @param options 可选参数
297 | * @return JSONObject
298 | */
299 | public JSONObject imageCensorUserDefined(String image, EImgType type, HashMap options) {
300 | if (type == EImgType.FILE) {
301 | try {
302 | byte[] imgData = Util.readFileByBytes(image);
303 | return imageCensorUserDefined(imgData, options);
304 | } catch (IOException e) {
305 | return AipError.IMAGE_READ_ERROR.toJsonResult();
306 | }
307 | }
308 |
309 | // url
310 | AipRequest request = new AipRequest();
311 |
312 | request.addBody("imgUrl", image);
313 |
314 | return imageCensorUserDefinedHelper(request, options);
315 | }
316 |
317 | /**
318 | * 图像审核接口
319 | * 本接口除了支持自定义配置外,还对返回结果进行了总体的包装,按照用户在控制台中配置的规则直接返回是否合规,如果不合规则指出具体不合规的内容。
320 | * @param imgData 图片二进制数据
321 | * @param options 可选参数
322 | * @return JSONObject
323 | */
324 | public JSONObject imageCensorUserDefined(byte[] imgData, HashMap options) {
325 | AipRequest request = new AipRequest();
326 |
327 | String base64Content = Base64Util.encode(imgData);
328 | request.addBody("image", base64Content);
329 |
330 | return imageCensorUserDefinedHelper(request, options);
331 | }
332 |
333 | private JSONObject imageCensorUserDefinedHelper(AipRequest request, HashMap options) {
334 | preOperation(request);
335 |
336 | if (options != null) {
337 | for (Map.Entry entry : options.entrySet()) {
338 | request.addBody(entry.getKey(), entry.getValue());
339 | }
340 | }
341 | request.setUri(ContentCensorConsts.USER_DEFINED_IMAGE_URL);
342 | postOperation(request);
343 | return requestServer(request);
344 | }
345 |
346 | /**
347 | * 文本审核接口
348 | * 本接口除了支持自定义配置外,还对返回结果进行了总体的包装,按照用户在控制台中配置的规则直接返回是否合规,如果不合规则指出具体不合规的内容。
349 | * @param text 文本
350 | * @return JSONObject
351 | */
352 | public JSONObject textCensorUserDefined(String text) {
353 | AipRequest request = new AipRequest();
354 |
355 | request.addBody("text", text);
356 |
357 | return textCensorUserDefinedHelper(request, null);
358 | }
359 |
360 | private JSONObject textCensorUserDefinedHelper(AipRequest request, HashMap options) {
361 | preOperation(request);
362 |
363 | if (options != null) {
364 | for (Map.Entry entry : options.entrySet()) {
365 | request.addBody(entry.getKey(), entry.getValue());
366 | }
367 | }
368 | request.setUri(ContentCensorConsts.USER_DEFINED_TEXT_URL);
369 | postOperation(request);
370 | return requestServer(request);
371 | }
372 |
373 | public JSONObject antiSpam(String content, HashMap options) {
374 | AipRequest request = new AipRequest();
375 | preOperation(request);
376 |
377 | request.addBody("content", content);
378 | if (options != null) {
379 | request.addBody(options);
380 | }
381 |
382 | request.setUri(ContentCensorConsts.TXT_CENSOR_URL);
383 | postOperation(request);
384 | return requestServer(request);
385 | }
386 |
387 | private JSONObject checkParam(byte[] imgData) {
388 | // image format
389 | String format = ImageUtil.getImageFormatByBytes(imgData);
390 | if (!ContentCensorConsts.ANTIPORN_SUPPORT_IMAGE_FORMAT.contains(format)) {
391 | return AipError.UNSUPPORTED_IMAGE_FORMAT_ERROR.toJsonResult();
392 | }
393 |
394 | return AipError.SUCCESS.toJsonResult();
395 | }
396 |
397 | private JSONObject checkImgFormat(byte[] imgData, String format) {
398 | String realFormat = ImageUtil.getImageFormatByBytes(imgData);
399 | if (realFormat.equals(format)) {
400 | return AipError.SUCCESS.toJsonResult();
401 | }
402 | return AipError.UNSUPPORTED_IMAGE_FORMAT_ERROR.toJsonResult();
403 | }
404 | }
405 |
--------------------------------------------------------------------------------
/src/main/java/com/baidu/aip/nlp/AipNlp.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2017 Baidu, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
5 | * the License. You may obtain a copy of the License at
6 | *
7 | * http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
10 | * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
11 | * specific language governing permissions and limitations under the License.
12 | */
13 |
14 | package com.baidu.aip.nlp;
15 |
16 | import com.baidu.aip.client.BaseClient;
17 | import com.baidu.aip.http.AipRequest;
18 | import com.baidu.aip.http.EBodyFormat;
19 | import com.baidu.aip.http.Headers;
20 | import com.baidu.aip.http.HttpCharacterEncoding;
21 | import com.baidu.aip.http.HttpContentType;
22 | import org.json.JSONObject;
23 |
24 | import java.util.HashMap;
25 |
26 | public class AipNlp extends BaseClient {
27 |
28 | public AipNlp(String appId, String apiKey, String secretKey) {
29 | super(appId, apiKey, secretKey);
30 | }
31 |
32 | /**
33 | * 词法分析接口
34 | * 词法分析接口向用户提供分词、词性标注、专名识别三大功能;能够识别出文本串中的基本词汇(分词),对这些词汇进行重组、标注组合后词汇的词性,并进一步识别出命名实体。
35 | *
36 | * @param text - 待分析文本(目前仅支持GBK编码),长度不超过65536字节
37 | * @param options - 可选参数对象,key: value都为string类型
38 | * options - options列表:
39 | * @return JSONObject
40 | */
41 | public JSONObject lexer(String text, HashMap options) {
42 | AipRequest request = new AipRequest();
43 | preOperation(request);
44 |
45 | request.addBody("text", text);
46 |
47 | if (options != null) {
48 | request.addBody(options);
49 | }
50 | request.setUri(NlpConsts.LEXER);
51 | request.addHeader(Headers.CONTENT_ENCODING, HttpCharacterEncoding.ENCODE_GBK);
52 | request.addHeader(Headers.CONTENT_TYPE, HttpContentType.JSON_DATA);
53 | request.setBodyFormat(EBodyFormat.RAW_JSON);
54 | postOperation(request);
55 | return requestServer(request);
56 | }
57 |
58 | /**
59 | * 词法分析(定制版)接口
60 | * 词法分析接口向用户提供分词、词性标注、专名识别三大功能;能够识别出文本串中的基本词汇(分词),对这些词汇进行重组、标注组合后词汇的词性,并进一步识别出命名实体。
61 | *
62 | * @param text - 待分析文本(目前仅支持GBK编码),长度不超过65536字节
63 | * @param options - 可选参数对象,key: value都为string类型
64 | * options - options列表:
65 | * @return JSONObject
66 | */
67 | public JSONObject lexerCustom(String text, HashMap options) {
68 | AipRequest request = new AipRequest();
69 | preOperation(request);
70 |
71 | request.addBody("text", text);
72 |
73 | if (options != null) {
74 | request.addBody(options);
75 | }
76 | request.setUri(NlpConsts.LEXER_CUSTOM);
77 | request.addHeader(Headers.CONTENT_ENCODING, HttpCharacterEncoding.ENCODE_GBK);
78 | request.addHeader(Headers.CONTENT_TYPE, HttpContentType.JSON_DATA);
79 | request.setBodyFormat(EBodyFormat.RAW_JSON);
80 | postOperation(request);
81 | return requestServer(request);
82 | }
83 |
84 | /**
85 | * 依存句法分析接口
86 | * 依存句法分析接口可自动分析文本中的依存句法结构信息,利用句子中词与词之间的依存关系来表示词语的句法结构信息(如“主谓”、“动宾”、“定中”等结构关系),并用树状结构来表示整句的结构(如“主谓宾”、“定状补”等)。
87 | *
88 | * @param text - 待分析文本(目前仅支持GBK编码),长度不超过256字节
89 | * @param options - 可选参数对象,key: value都为string类型
90 | * options - options列表:
91 | * mode 模型选择。默认值为0,可选值mode=0(对应web模型);mode=1(对应query模型)
92 | * @return JSONObject
93 | */
94 | public JSONObject depParser(String text, HashMap options) {
95 | AipRequest request = new AipRequest();
96 | preOperation(request);
97 |
98 | request.addBody("text", text);
99 |
100 | if (options != null) {
101 | request.addBody(options);
102 | }
103 | request.setUri(NlpConsts.DEP_PARSER);
104 | request.addHeader(Headers.CONTENT_ENCODING, HttpCharacterEncoding.ENCODE_GBK);
105 | request.addHeader(Headers.CONTENT_TYPE, HttpContentType.JSON_DATA);
106 | request.setBodyFormat(EBodyFormat.RAW_JSON);
107 | postOperation(request);
108 | return requestServer(request);
109 | }
110 |
111 | /**
112 | * 词向量表示接口
113 | * 词向量表示接口提供中文词向量的查询功能。
114 | *
115 | * @param word - 文本内容(GBK编码),最大64字节
116 | * @param options - 可选参数对象,key: value都为string类型
117 | * options - options列表:
118 | * @return JSONObject
119 | */
120 | public JSONObject wordEmbedding(String word, HashMap options) {
121 | AipRequest request = new AipRequest();
122 | preOperation(request);
123 |
124 | request.addBody("word", word);
125 |
126 | if (options != null) {
127 | request.addBody(options);
128 | }
129 | request.setUri(NlpConsts.WORD_EMBEDDING);
130 | request.addHeader(Headers.CONTENT_ENCODING, HttpCharacterEncoding.ENCODE_GBK);
131 | request.addHeader(Headers.CONTENT_TYPE, HttpContentType.JSON_DATA);
132 | request.setBodyFormat(EBodyFormat.RAW_JSON);
133 | postOperation(request);
134 | return requestServer(request);
135 | }
136 |
137 | /**
138 | * DNN语言模型接口
139 | * 中文DNN语言模型接口用于输出切词结果并给出每个词在句子中的概率值,判断一句话是否符合语言表达习惯。
140 | *
141 | * @param text - 文本内容(GBK编码),最大512字节,不需要切词
142 | * @param options - 可选参数对象,key: value都为string类型
143 | * options - options列表:
144 | * @return JSONObject
145 | */
146 | public JSONObject dnnlmCn(String text, HashMap options) {
147 | AipRequest request = new AipRequest();
148 | preOperation(request);
149 |
150 | request.addBody("text", text);
151 |
152 | if (options != null) {
153 | request.addBody(options);
154 | }
155 | request.setUri(NlpConsts.DNNLM_CN);
156 | request.addHeader(Headers.CONTENT_ENCODING, HttpCharacterEncoding.ENCODE_GBK);
157 | request.addHeader(Headers.CONTENT_TYPE, HttpContentType.JSON_DATA);
158 | request.setBodyFormat(EBodyFormat.RAW_JSON);
159 | postOperation(request);
160 | return requestServer(request);
161 | }
162 |
163 | /**
164 | * 词义相似度接口
165 | * 输入两个词,得到两个词的相似度结果。
166 | *
167 | * @param word1 - 词1(GBK编码),最大64字节*
168 | * @param word2 - 词1(GBK编码),最大64字节
169 | * @param options - 可选参数对象,key: value都为string类型
170 | * options - options列表:
171 | * mode 预留字段,可选择不同的词义相似度模型。默认值为0,目前仅支持mode=0
172 | * @return JSONObject
173 | */
174 | public JSONObject wordSimEmbedding(String word1, String word2, HashMap options) {
175 | AipRequest request = new AipRequest();
176 | preOperation(request);
177 |
178 | request.addBody("word_1", word1);
179 |
180 | request.addBody("word_2", word2);
181 |
182 | if (options != null) {
183 | request.addBody(options);
184 | }
185 | request.setUri(NlpConsts.WORD_SIM_EMBEDDING);
186 | request.addHeader(Headers.CONTENT_ENCODING, HttpCharacterEncoding.ENCODE_GBK);
187 | request.addHeader(Headers.CONTENT_TYPE, HttpContentType.JSON_DATA);
188 | request.setBodyFormat(EBodyFormat.RAW_JSON);
189 | postOperation(request);
190 | return requestServer(request);
191 | }
192 |
193 | /**
194 | * 短文本相似度接口
195 | * 短文本相似度接口用来判断两个文本的相似度得分。
196 | *
197 | * @param text1 - 待比较文本1(GBK编码),最大512字节*
198 | * @param text2 - 待比较文本2(GBK编码),最大512字节
199 | * @param options - 可选参数对象,key: value都为string类型
200 | * options - options列表:
201 | * model 默认为"BOW",可选"BOW"、"CNN"与"GRNN"
202 | * @return JSONObject
203 | */
204 | public JSONObject simnet(String text1, String text2, HashMap options) {
205 | AipRequest request = new AipRequest();
206 | preOperation(request);
207 |
208 | request.addBody("text_1", text1);
209 |
210 | request.addBody("text_2", text2);
211 |
212 | if (options != null) {
213 | request.addBody(options);
214 | }
215 | request.setUri(NlpConsts.SIMNET);
216 | request.addHeader(Headers.CONTENT_ENCODING, HttpCharacterEncoding.ENCODE_GBK);
217 | request.addHeader(Headers.CONTENT_TYPE, HttpContentType.JSON_DATA);
218 | request.setBodyFormat(EBodyFormat.RAW_JSON);
219 | postOperation(request);
220 | return requestServer(request);
221 | }
222 |
223 | /**
224 | * 评论观点抽取接口
225 | * 评论观点抽取接口用来提取一条评论句子的关注点和评论观点,并输出评论观点标签及评论观点极性。
226 | *
227 | * @param text - 评论内容(GBK编码),最大10240字节
228 | * @param type - ESimnetType枚举类型,选择识别的垂类
229 | * @param options - 可选参数对象,key: value都为string类型
230 | * options - options列表:
231 | * type 评论行业类型,默认为4(餐饮美食)
232 | * @return JSONObject
233 | */
234 | public JSONObject commentTag(String text, ESimnetType type, HashMap options) {
235 | AipRequest request = new AipRequest();
236 | preOperation(request);
237 |
238 | request.addBody("text", text);
239 | request.addBody("type", type.ordinal());
240 | if (options != null) {
241 | request.addBody(options);
242 | }
243 | request.setUri(NlpConsts.COMMENT_TAG);
244 | request.addHeader(Headers.CONTENT_ENCODING, HttpCharacterEncoding.ENCODE_GBK);
245 | request.addHeader(Headers.CONTENT_TYPE, HttpContentType.JSON_DATA);
246 | request.setBodyFormat(EBodyFormat.RAW_JSON);
247 | postOperation(request);
248 | return requestServer(request);
249 | }
250 |
251 | /**
252 | * 情感倾向分析接口
253 | * 对包含主观观点信息的文本进行情感极性类别(积极、消极、中性)的判断,并给出相应的置信度。
254 | *
255 | * @param text - 文本内容(GBK编码),最大102400字节
256 | * @param options - 可选参数对象,key: value都为string类型
257 | * options - options列表:
258 | * @return JSONObject
259 | */
260 | public JSONObject sentimentClassify(String text, HashMap options) {
261 | AipRequest request = new AipRequest();
262 | preOperation(request);
263 |
264 | request.addBody("text", text);
265 |
266 | if (options != null) {
267 | request.addBody(options);
268 | }
269 | request.setUri(NlpConsts.SENTIMENT_CLASSIFY);
270 | request.addHeader(Headers.CONTENT_ENCODING, HttpCharacterEncoding.ENCODE_GBK);
271 | request.addHeader(Headers.CONTENT_TYPE, HttpContentType.JSON_DATA);
272 | request.setBodyFormat(EBodyFormat.RAW_JSON);
273 | postOperation(request);
274 | return requestServer(request);
275 | }
276 |
277 | /**
278 | * 文章标签接口
279 | * 文章标签服务能够针对网络各类媒体文章进行快速的内容理解,根据输入含有标题的文章,输出多个内容标签以及对应的置信度,用于个性化推荐、相似文章聚合、文本内容分析等场景。
280 | *
281 | * @param title - 篇章的标题,最大80字节*
282 | * @param content - 篇章的正文,最大65535字节
283 | * @param options - 可选参数对象,key: value都为string类型
284 | * options - options列表:
285 | * @return JSONObject
286 | */
287 | public JSONObject keyword(String title, String content, HashMap options) {
288 | AipRequest request = new AipRequest();
289 | preOperation(request);
290 |
291 | request.addBody("title", title);
292 |
293 | request.addBody("content", content);
294 |
295 | if (options != null) {
296 | request.addBody(options);
297 | }
298 | request.setUri(NlpConsts.KEYWORD);
299 | request.addHeader(Headers.CONTENT_ENCODING, HttpCharacterEncoding.ENCODE_GBK);
300 | request.addHeader(Headers.CONTENT_TYPE, HttpContentType.JSON_DATA);
301 | request.setBodyFormat(EBodyFormat.RAW_JSON);
302 | postOperation(request);
303 | return requestServer(request);
304 | }
305 |
306 | /**
307 | * 文章分类接口
308 | * 对文章按照内容类型进行自动分类,首批支持娱乐、体育、科技等26个主流内容类型,为文章聚类、文本内容分析等应用提供基础技术支持。
309 | *
310 | * @param title - 篇章的标题,最大80字节*
311 | * @param content - 篇章的正文,最大65535字节
312 | * @param options - 可选参数对象,key: value都为string类型
313 | * options - options列表:
314 | * @return JSONObject
315 | */
316 | public JSONObject topic(String title, String content, HashMap options) {
317 | AipRequest request = new AipRequest();
318 | preOperation(request);
319 |
320 | request.addBody("title", title);
321 |
322 | request.addBody("content", content);
323 |
324 | if (options != null) {
325 | request.addBody(options);
326 | }
327 | request.setUri(NlpConsts.TOPIC);
328 | request.addHeader(Headers.CONTENT_ENCODING, HttpCharacterEncoding.ENCODE_GBK);
329 | request.addHeader(Headers.CONTENT_TYPE, HttpContentType.JSON_DATA);
330 | request.setBodyFormat(EBodyFormat.RAW_JSON);
331 | postOperation(request);
332 | return requestServer(request);
333 | }
334 |
335 | /**
336 | * 文本纠错接口
337 | * 识别输入文本中有错误的片段,提示错误并给出正确的文本结果。支持短文本、长文本、语音等内容的错误识别,纠错是搜索引擎、语音识别、内容审查等功能更好运行的基础模块之一。
338 | *
339 | * @param text - 待纠错文本,输入限制511字节
340 | * @param options - 可选参数对象,key: value都为string类型
341 | * options - options列表:
342 | * @return JSONObject
343 | */
344 | public JSONObject ecnet(String text, HashMap options) {
345 | AipRequest request = new AipRequest();
346 | preOperation(request);
347 |
348 | request.addBody("text", text);
349 |
350 | if (options != null) {
351 | request.addBody(options);
352 | }
353 | request.setUri(NlpConsts.ECNET);
354 | request.addHeader(Headers.CONTENT_ENCODING, HttpCharacterEncoding.ENCODE_GBK);
355 | request.addHeader(Headers.CONTENT_TYPE, HttpContentType.JSON_DATA);
356 | request.setBodyFormat(EBodyFormat.RAW_JSON);
357 | postOperation(request);
358 | return requestServer(request);
359 | }
360 |
361 | /**
362 | * 对话情绪识别接口接口
363 | * 针对用户日常沟通文本背后所蕴含情绪的一种直观检测,可自动识别出当前会话者所表现出的情绪类别及其置信度,可以帮助企业更全面地把握产品服务质量、监控客户服务质量
364 | *
365 | * @param text - 待识别情感文本,输入限制512字节
366 | * @param options - 可选参数对象,key: value都为string类型
367 | * options - options列表:
368 | * scene default(默认项-不区分场景),talk(闲聊对话-如度秘聊天等),task(任务型对话-如导航对话等),customer_service(客服对话-如电信/银行客服等)
369 | * @return JSONObject
370 | */
371 | public JSONObject emotion(String text, HashMap options) {
372 | AipRequest request = new AipRequest();
373 | preOperation(request);
374 |
375 | request.addBody("text", text);
376 |
377 | if (options != null) {
378 | request.addBody(options);
379 | }
380 | request.setUri(NlpConsts.EMOTION);
381 | request.addHeader(Headers.CONTENT_ENCODING, HttpCharacterEncoding.ENCODE_GBK);
382 | request.addHeader(Headers.CONTENT_TYPE, HttpContentType.JSON_DATA);
383 | request.setBodyFormat(EBodyFormat.RAW_JSON);
384 | postOperation(request);
385 | return requestServer(request);
386 | }
387 |
388 | /**
389 | * 新闻摘要接口接口
390 | * 自动抽取新闻文本中的关键信息,进而生成指定长度的新闻摘要
391 | *
392 | * @param content - 字符串(限3000字符数以内)字符串仅支持GBK编码,长度需小于3000字符数(即6000字节),请输入前确认字符数没有超限,若字符数超长会返回错误。正文中如果包含段落信息,请使用"\n"分隔,段落信息算法中有重要的作用,请尽量保留*
393 | * @param maxSummaryLen - 此数值将作为摘要结果的最大长度。例如:原文长度1000字,本参数设置为150,则摘要结果的最大长度是150字;推荐最优区间:200-500字
394 | * @param options - 可选参数对象,key: value都为string类型
395 | * options - options列表:
396 | * title 字符串(限200字符数)字符串仅支持GBK编码,长度需小于200字符数(即400字节),请输入前确认字符数没有超限,若字符数超长会返回错误。标题在算法中具有重要的作用,若文章确无标题,输入参数的“标题”字段为空即可
397 | * @return JSONObject
398 | */
399 | public JSONObject newsSummary(String content, int maxSummaryLen, HashMap options) {
400 | AipRequest request = new AipRequest();
401 | preOperation(request);
402 |
403 | request.addBody("content", content);
404 |
405 | request.addBody("max_summary_len", maxSummaryLen);
406 |
407 | if (options != null) {
408 | request.addBody(options);
409 | }
410 | request.setUri(NlpConsts.NEWS_SUMMARY);
411 | request.addHeader(Headers.CONTENT_ENCODING, HttpCharacterEncoding.ENCODE_GBK);
412 | request.addHeader(Headers.CONTENT_TYPE, HttpContentType.JSON_DATA);
413 | request.setBodyFormat(EBodyFormat.RAW_JSON);
414 | postOperation(request);
415 | return requestServer(request);
416 | }
417 |
418 | }
--------------------------------------------------------------------------------
/src/main/java/com/baidu/aip/bodyanalysis/AipBodyAnalysis.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2017 Baidu, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
5 | * the License. You may obtain a copy of the License at
6 | *
7 | * http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
10 | * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
11 | * specific language governing permissions and limitations under the License.
12 | */
13 |
14 | package com.baidu.aip.bodyanalysis;
15 |
16 | import com.baidu.aip.client.BaseClient;
17 | import com.baidu.aip.error.AipError;
18 | import com.baidu.aip.http.AipRequest;
19 | import com.baidu.aip.util.Base64Util;
20 | import com.baidu.aip.util.Util;
21 | import org.json.JSONObject;
22 |
23 | import javax.imageio.ImageIO;
24 | import java.awt.Graphics2D;
25 | import java.awt.Image;
26 | import java.awt.image.BufferedImage;
27 | import java.io.ByteArrayInputStream;
28 | import java.io.File;
29 | import java.io.IOException;
30 | import java.io.InputStream;
31 | import java.util.HashMap;
32 |
33 | public class AipBodyAnalysis extends BaseClient {
34 |
35 | public AipBodyAnalysis(String appId, String apiKey, String secretKey) {
36 | super(appId, apiKey, secretKey);
37 | }
38 |
39 | /**
40 | * 人体关键点识别接口
41 | * 对于输入的一张图片(可正常解码,且长宽比适宜),**检测图片中的所有人体,输出每个人体的21个主要关键点,包含头顶、五官、脖颈、四肢等部位,同时输出人体的坐标信息和数量**。
42 | *
43 | * @param image - 二进制图像数据
44 | * @param options - 可选参数对象,key: value都为string类型
45 | * options - options列表:
46 | * @return JSONObject
47 | */
48 | public JSONObject bodyAnalysis(byte[] image, HashMap options) {
49 | AipRequest request = new AipRequest();
50 | preOperation(request);
51 |
52 | String base64Content = Base64Util.encode(image);
53 | request.addBody("image", base64Content);
54 | if (options != null) {
55 | request.addBody(options);
56 | }
57 | request.setUri(BodyAnalysisConsts.BODY_ANALYSIS);
58 | postOperation(request);
59 | return requestServer(request);
60 | }
61 |
62 | /**
63 | * 人体关键点识别接口
64 | * 对于输入的一张图片(可正常解码,且长宽比适宜),**检测图片中的所有人体,输出每个人体的21个主要关键点,包含头顶、五官、脖颈、四肢等部位,同时输出人体的坐标信息和数量**。
65 | *
66 | * @param image - 本地图片路径
67 | * @param options - 可选参数对象,key: value都为string类型
68 | * options - options列表:
69 | * @return JSONObject
70 | */
71 | public JSONObject bodyAnalysis(String image, HashMap options) {
72 | try {
73 | byte[] data = Util.readFileByBytes(image);
74 | return bodyAnalysis(data, options);
75 | } catch (IOException e) {
76 | e.printStackTrace();
77 | return AipError.IMAGE_READ_ERROR.toJsonResult();
78 | }
79 | }
80 |
81 | /**
82 | * 人体检测与属性识别接口
83 | * 对于输入的一张图片(可正常解码,且长宽比适宜),**检测图像中的所有人体并返回每个人体的矩形框位置,识别人体的静态属性和行为,共支持20余种属性,包括:性别、年龄阶段、衣着(含类别/颜色)、是否戴帽子、是否戴眼镜、是否背包、是否使用手机、身体朝向等**。
84 | *
85 | * @param image - 二进制图像数据
86 | * @param options - 可选参数对象,key: value都为string类型
87 | * options - options列表:
88 | * type gender,
age,
lower_wear,
upper_wear,
headwear,
glasses,
upper_color,
lower_color,
cellphone,
upper_wear_fg,
upper_wear_texture,
lower_wear_texture,
orientation,
umbrella,
bag,
smoke,
vehicle,
carrying_item,
upper_cut,
lower_cut,
occlusion,
is_human | 1)可选值说明:
gender-性别,
age-年龄阶段,
lower_wear-下身服饰,
upper_wear-上身服饰,
headwear-是否戴帽子,
glasses-是否戴眼镜,
upper_color-上身服饰颜色,
lower_color-下身服饰颜色,
cellphone-是否使用手机,
upper_wear_fg-上身服饰细分类,
upper_wear_texture-上身服饰纹理,
orientation-身体朝向,
umbrella-是否撑伞;
bag-背包,
smoke-是否吸烟,
vehicle-交通工具,
carrying_item-是否有手提物,
upper_cut-上方截断,
lower_cut-下方截断,
occlusion-遮挡,
is_human-是否是正常人体
2)type 参数值可以是可选值的组合,用逗号分隔;**如果无此参数默认输出全部21个属性**
89 | * @return JSONObject
90 | */
91 | public JSONObject bodyAttr(byte[] image, HashMap options) {
92 | AipRequest request = new AipRequest();
93 | preOperation(request);
94 |
95 | String base64Content = Base64Util.encode(image);
96 | request.addBody("image", base64Content);
97 | if (options != null) {
98 | request.addBody(options);
99 | }
100 | request.setUri(BodyAnalysisConsts.BODY_ATTR);
101 | postOperation(request);
102 | return requestServer(request);
103 | }
104 |
105 | /**
106 | * 人体检测与属性识别接口
107 | * 对于输入的一张图片(可正常解码,且长宽比适宜),**检测图像中的所有人体并返回每个人体的矩形框位置,识别人体的静态属性和行为,共支持20余种属性,包括:性别、年龄阶段、衣着(含类别/颜色)、是否戴帽子、是否戴眼镜、是否背包、是否使用手机、身体朝向等**。
108 | *
109 | * @param image - 本地图片路径
110 | * @param options - 可选参数对象,key: value都为string类型
111 | * options - options列表:
112 | * type gender,
age,
lower_wear,
upper_wear,
headwear,
glasses,
upper_color,
lower_color,
cellphone,
upper_wear_fg,
upper_wear_texture,
lower_wear_texture,
orientation,
umbrella,
bag,
smoke,
vehicle,
carrying_item,
upper_cut,
lower_cut,
occlusion,
is_human | 1)可选值说明:
gender-性别,
age-年龄阶段,
lower_wear-下身服饰,
upper_wear-上身服饰,
headwear-是否戴帽子,
glasses-是否戴眼镜,
upper_color-上身服饰颜色,
lower_color-下身服饰颜色,
cellphone-是否使用手机,
upper_wear_fg-上身服饰细分类,
upper_wear_texture-上身服饰纹理,
orientation-身体朝向,
umbrella-是否撑伞;
bag-背包,
smoke-是否吸烟,
vehicle-交通工具,
carrying_item-是否有手提物,
upper_cut-上方截断,
lower_cut-下方截断,
occlusion-遮挡,
is_human-是否是正常人体
2)type 参数值可以是可选值的组合,用逗号分隔;**如果无此参数默认输出全部21个属性**
113 | * @return JSONObject
114 | */
115 | public JSONObject bodyAttr(String image, HashMap options) {
116 | try {
117 | byte[] data = Util.readFileByBytes(image);
118 | return bodyAttr(data, options);
119 | } catch (IOException e) {
120 | e.printStackTrace();
121 | return AipError.IMAGE_READ_ERROR.toJsonResult();
122 | }
123 | }
124 |
125 | /**
126 | * 人流量统计接口
127 | * 对于输入的一张图片(可正常解码,且长宽比适宜),**识别和统计图像当中的人体个数(静态统计,暂不支持追踪和去重)**。
128 | *
129 | * @param image - 二进制图像数据
130 | * @param options - 可选参数对象,key: value都为string类型
131 | * options - options列表:
132 | * area 特定框选区域坐标,支持多个多边形区域,最多支持10个区域,如输入超过10个区域,截取前10个区域进行识别。
**此参数为空或无此参数、或area参数设置错误时,默认识别整个图片的人数** 。
area参数设置错误的示例:某个坐标超过原图大小,x、y坐标未成对出现等;注意:**设置了多个区域时,任意一个坐标设置错误,则认为area参数错误、失效**。
**area参数设置格式**:
1)多个区域用英文分号“;”分隔;
2)同一个区域内的坐标用英文逗号“,”分隔,默认尾点和首点相连做闭合。
示例:
1)单个多边形区域:x1,y1,x2,y2,x3,y3...xn,yn
2)多个多边形区域:xa1,ya1,xa2,ya2,xa3,ya3...xan,yan;xb1,yb1,xb2,yb2,xb3,yb3...xbn,ybn;..
133 | * show 是否输出渲染的图片,默认不返回,**选true时返回渲染后的图片(base64)**,其它无效值或为空则默认false
134 | * @return JSONObject
135 | */
136 | public JSONObject bodyNum(byte[] image, HashMap options) {
137 | AipRequest request = new AipRequest();
138 | preOperation(request);
139 |
140 | String base64Content = Base64Util.encode(image);
141 | request.addBody("image", base64Content);
142 | if (options != null) {
143 | request.addBody(options);
144 | }
145 | request.setUri(BodyAnalysisConsts.BODY_NUM);
146 | postOperation(request);
147 | return requestServer(request);
148 | }
149 |
150 | /**
151 | * 人流量统计接口
152 | * 对于输入的一张图片(可正常解码,且长宽比适宜),**识别和统计图像当中的人体个数(静态统计,暂不支持追踪和去重)**。
153 | *
154 | * @param image - 本地图片路径
155 | * @param options - 可选参数对象,key: value都为string类型
156 | * options - options列表:
157 | * area 特定框选区域坐标,支持多个多边形区域,最多支持10个区域,如输入超过10个区域,截取前10个区域进行识别。
**此参数为空或无此参数、或area参数设置错误时,默认识别整个图片的人数** 。
area参数设置错误的示例:某个坐标超过原图大小,x、y坐标未成对出现等;注意:**设置了多个区域时,任意一个坐标设置错误,则认为area参数错误、失效**。
**area参数设置格式**:
1)多个区域用英文分号“;”分隔;
2)同一个区域内的坐标用英文逗号“,”分隔,默认尾点和首点相连做闭合。
示例:
1)单个多边形区域:x1,y1,x2,y2,x3,y3...xn,yn
2)多个多边形区域:xa1,ya1,xa2,ya2,xa3,ya3...xan,yan;xb1,yb1,xb2,yb2,xb3,yb3...xbn,ybn;..
158 | * show 是否输出渲染的图片,默认不返回,**选true时返回渲染后的图片(base64)**,其它无效值或为空则默认false
159 | * @return JSONObject
160 | */
161 | public JSONObject bodyNum(String image, HashMap options) {
162 | try {
163 | byte[] data = Util.readFileByBytes(image);
164 | return bodyNum(data, options);
165 | } catch (IOException e) {
166 | e.printStackTrace();
167 | return AipError.IMAGE_READ_ERROR.toJsonResult();
168 | }
169 | }
170 |
171 | /**
172 | * 手势识别接口
173 | * 识别图片中的手势类型,返回手势名称、手势矩形框、概率分数,可识别24种常见手势,适用于手势特效、智能家居手势交互等场景**。支持的24类手势列表:拳头、OK、祈祷、作揖、作别、单手比心、点赞、Diss、我爱你、掌心向上、双手比心(3种)、数字(9种)、Rock、竖中指。
174 | *
175 | * @param image - 二进制图像数据
176 | * @param options - 可选参数对象,key: value都为string类型
177 | * options - options列表:
178 | * @return JSONObject
179 | */
180 | public JSONObject gesture(byte[] image, HashMap options) {
181 | AipRequest request = new AipRequest();
182 | preOperation(request);
183 |
184 | String base64Content = Base64Util.encode(image);
185 | request.addBody("image", base64Content);
186 | if (options != null) {
187 | request.addBody(options);
188 | }
189 | request.setUri(BodyAnalysisConsts.GESTURE);
190 | postOperation(request);
191 | return requestServer(request);
192 | }
193 |
194 | /**
195 | * 手势识别接口
196 | * 识别图片中的手势类型,返回手势名称、手势矩形框、概率分数,可识别24种常见手势,适用于手势特效、智能家居手势交互等场景**。支持的24类手势列表:拳头、OK、祈祷、作揖、作别、单手比心、点赞、Diss、我爱你、掌心向上、双手比心(3种)、数字(9种)、Rock、竖中指。
197 | *
198 | * @param image - 本地图片路径
199 | * @param options - 可选参数对象,key: value都为string类型
200 | * options - options列表:
201 | * @return JSONObject
202 | */
203 | public JSONObject gesture(String image, HashMap options) {
204 | try {
205 | byte[] data = Util.readFileByBytes(image);
206 | return gesture(data, options);
207 | } catch (IOException e) {
208 | e.printStackTrace();
209 | return AipError.IMAGE_READ_ERROR.toJsonResult();
210 | }
211 | }
212 |
213 | /**
214 | * 人像分割接口
215 | * 对于输入的一张图片(可正常解码,且长宽比适宜),**识别人体的轮廓范围,与背景进行分离,适用于拍照背景替换、照片合成、身体特效等场景。输入正常人像图片,返回分割后的二值结果图和分割类型(目前仅支持person)**
216 | *
217 | * @param image - 二进制图像数据
218 | * @param options - 可选参数对象,key: value都为string类型
219 | * options - options列表:
220 | * type 可以通过设置type参数,自主设置返回哪些结果图,避免造成带宽的浪费
1)可选值说明:
labelmap - 二值图像,需二次处理方能查看分割效果
scoremap - 人像前景灰度图
foreground - 人像前景抠图,透明背景
2)type 参数值可以是可选值的组合,用逗号分隔;如果无此参数默认输出全部3类结果图
221 | * @return JSONObject
222 | */
223 | public JSONObject bodySeg(byte[] image, HashMap options) {
224 | AipRequest request = new AipRequest();
225 | preOperation(request);
226 |
227 | String base64Content = Base64Util.encode(image);
228 | request.addBody("image", base64Content);
229 | if (options != null) {
230 | request.addBody(options);
231 | }
232 | request.setUri(BodyAnalysisConsts.BODY_SEG);
233 | postOperation(request);
234 | return requestServer(request);
235 | }
236 |
237 | /**
238 | * 人像分割接口
239 | * 对于输入的一张图片(可正常解码,且长宽比适宜),**识别人体的轮廓范围,与背景进行分离,适用于拍照背景替换、照片合成、身体特效等场景。输入正常人像图片,返回分割后的二值结果图和分割类型(目前仅支持person)**
240 | *
241 | * @param image - 本地图片路径
242 | * @param options - 可选参数对象,key: value都为string类型
243 | * options - options列表:
244 | * type 可以通过设置type参数,自主设置返回哪些结果图,避免造成带宽的浪费
1)可选值说明:
labelmap - 二值图像,需二次处理方能查看分割效果
scoremap - 人像前景灰度图
foreground - 人像前景抠图,透明背景
2)type 参数值可以是可选值的组合,用逗号分隔;如果无此参数默认输出全部3类结果图
245 | * @return JSONObject
246 | */
247 | public JSONObject bodySeg(String image, HashMap options) {
248 | try {
249 | byte[] data = Util.readFileByBytes(image);
250 | return bodySeg(data, options);
251 | } catch (IOException e) {
252 | e.printStackTrace();
253 | return AipError.IMAGE_READ_ERROR.toJsonResult();
254 | }
255 | }
256 |
257 | /**
258 | * 驾驶行为分析接口
259 | * 对于输入的一张车载监控图片(可正常解码,且长宽比适宜),**识别图像中是否有人体(驾驶员),若检测到至少1个人体,则进一步识别属性行为,可识别使用手机、抽烟、未系安全带、双手离开方向盘、视线未朝前方5种典型行为姿态**。
260 | *
261 | * @param image - 二进制图像数据
262 | * @param options - 可选参数对象,key: value都为string类型
263 | * options - options列表:
264 | * type smoke,cellphone,
not_buckling_up,
both_hands_leaving_wheel,
not_facing_front |识别的属性行为类别,英文逗号分隔,默认所有属性都识别;
smoke //吸烟,
cellphone //打手机 ,
not_buckling_up // 未系安全带,
both_hands_leaving_wheel // 双手离开方向盘,
not_facing_front // 视角未看前方
265 | * @return JSONObject
266 | */
267 | public JSONObject driverBehavior(byte[] image, HashMap options) {
268 | AipRequest request = new AipRequest();
269 | preOperation(request);
270 |
271 | String base64Content = Base64Util.encode(image);
272 | request.addBody("image", base64Content);
273 | if (options != null) {
274 | request.addBody(options);
275 | }
276 | request.setUri(BodyAnalysisConsts.DRIVER_BEHAVIOR);
277 | postOperation(request);
278 | return requestServer(request);
279 | }
280 |
281 | /**
282 | * 驾驶行为分析接口
283 | * 对于输入的一张车载监控图片(可正常解码,且长宽比适宜),**识别图像中是否有人体(驾驶员),若检测到至少1个人体,则进一步识别属性行为,可识别使用手机、抽烟、未系安全带、双手离开方向盘、视线未朝前方5种典型行为姿态**。
284 | *
285 | * @param image - 本地图片路径
286 | * @param options - 可选参数对象,key: value都为string类型
287 | * options - options列表:
288 | * type smoke,cellphone,
not_buckling_up,
both_hands_leaving_wheel,
not_facing_front |识别的属性行为类别,英文逗号分隔,默认所有属性都识别;
smoke //吸烟,
cellphone //打手机 ,
not_buckling_up // 未系安全带,
both_hands_leaving_wheel // 双手离开方向盘,
not_facing_front // 视角未看前方
289 | * @return JSONObject
290 | */
291 | public JSONObject driverBehavior(String image, HashMap options) {
292 | try {
293 | byte[] data = Util.readFileByBytes(image);
294 | return driverBehavior(data, options);
295 | } catch (IOException e) {
296 | e.printStackTrace();
297 | return AipError.IMAGE_READ_ERROR.toJsonResult();
298 | }
299 | }
300 |
301 | /**
302 | * 人流量统计-动态版接口
303 | * 统计图像中的人体个数和流动趋势,主要适用于**低空俯拍、出入口场景,以人体头肩为主要识别目标**
304 | *
305 | * @param image - 二进制图像数据
306 | * @param dynamic - true:动态人流量统计,返回总人数、跟踪ID、区域进出人数;
false:静态人数统计,返回总人数
307 | * @param options - 可选参数对象,key: value都为string类型
308 | * options - options列表:
309 | * case_id 当dynamic为True时,必填;任务ID(通过case_id区分不同视频流,自拟,不同序列间不可重复即可)
310 | * case_init 当dynamic为True时,必填;每个case的初始化信号,为true时对该case下的跟踪算法进行初始化,为false时重载该case的跟踪状态。当为false且读取不到相应case的信息时,直接重新初始化
311 | * show 否返回结果图(含统计值和跟踪框渲染),默认不返回,选true时返回渲染后的图片(base64),其它无效值或为空则默认false
312 | * area 当dynamic为True时,必填;静态人数统计时,只统计区域内的人,缺省时为全图统计。
动态人流量统计时,进出区域的人流会被统计。
逗号分隔,如‘x1,y1,x2,y2,x3,y3...xn,yn',按顺序依次给出每个顶点的xy坐标(默认尾点和首点相连),形成闭合多边形区域。
服务会做范围(顶点左边需在图像范围内)及个数校验(数组长度必须为偶数,且大于3个顶点)。只支持单个多边形区域,建议设置矩形框,即4个顶点。**坐标取值不能超过图像宽度和高度,比如1280的宽度,坐标值最小建议从1开始,最大到1279**。
313 | * @return JSONObject
314 | */
315 | public JSONObject bodyTracking(byte[] image, String dynamic, HashMap options) {
316 | AipRequest request = new AipRequest();
317 | preOperation(request);
318 |
319 | String base64Content = Base64Util.encode(image);
320 | request.addBody("image", base64Content);
321 |
322 | request.addBody("dynamic", dynamic);
323 | if (options != null) {
324 | request.addBody(options);
325 | }
326 | request.setUri(BodyAnalysisConsts.BODY_TRACKING);
327 | postOperation(request);
328 | return requestServer(request);
329 | }
330 |
331 | /**
332 | * 人流量统计-动态版接口
333 | * 统计图像中的人体个数和流动趋势,主要适用于**低空俯拍、出入口场景,以人体头肩为主要识别目标**
334 | *
335 | * @param image - 本地图片路径
336 | * @param dynamic - true:动态人流量统计,返回总人数、跟踪ID、区域进出人数;
false:静态人数统计,返回总人数
337 | * @param options - 可选参数对象,key: value都为string类型
338 | * options - options列表:
339 | * case_id 当dynamic为True时,必填;任务ID(通过case_id区分不同视频流,自拟,不同序列间不可重复即可)
340 | * case_init 当dynamic为True时,必填;每个case的初始化信号,为true时对该case下的跟踪算法进行初始化,为false时重载该case的跟踪状态。当为false且读取不到相应case的信息时,直接重新初始化
341 | * show 否返回结果图(含统计值和跟踪框渲染),默认不返回,选true时返回渲染后的图片(base64),其它无效值或为空则默认false
342 | * area 当dynamic为True时,必填;静态人数统计时,只统计区域内的人,缺省时为全图统计。
动态人流量统计时,进出区域的人流会被统计。
逗号分隔,如‘x1,y1,x2,y2,x3,y3...xn,yn',按顺序依次给出每个顶点的xy坐标(默认尾点和首点相连),形成闭合多边形区域。
服务会做范围(顶点左边需在图像范围内)及个数校验(数组长度必须为偶数,且大于3个顶点)。只支持单个多边形区域,建议设置矩形框,即4个顶点。**坐标取值不能超过图像宽度和高度,比如1280的宽度,坐标值最小建议从1开始,最大到1279**。
343 | * @return JSONObject
344 | */
345 | public JSONObject bodyTracking(String image, String dynamic, HashMap options) {
346 | try {
347 | byte[] data = Util.readFileByBytes(image);
348 | return bodyTracking(data, dynamic, options);
349 | } catch (IOException e) {
350 | e.printStackTrace();
351 | return AipError.IMAGE_READ_ERROR.toJsonResult();
352 | }
353 | }
354 |
355 | public static BufferedImage resize(BufferedImage img, int newW, int newH) {
356 | Image tmp = img.getScaledInstance(newW, newH, Image.SCALE_SMOOTH);
357 | BufferedImage dimg = new BufferedImage(newW, newH, BufferedImage.TYPE_INT_ARGB);
358 |
359 | Graphics2D g2d = dimg.createGraphics();
360 | g2d.drawImage(tmp, 0, 0, null);
361 | g2d.dispose();
362 |
363 | return dimg;
364 | }
365 |
366 | /**
367 | * 针对人像分割接口,将返回的二值图转化为灰度图,存储为jpg格式
368 | * @param labelmapBase64 人像分割接口返回的二值图base64
369 | * @param realWidth 图片原始宽度
370 | * @param realHeight 图片原始高度
371 | * @param outPath 灰度图输出路径
372 | */
373 | public static void convert(String labelmapBase64, int realWidth, int realHeight, String outPath) {
374 | try {
375 |
376 | byte[] bytes = Base64Util.decode(labelmapBase64);
377 | InputStream is = new ByteArrayInputStream(bytes);
378 | BufferedImage image = ImageIO.read(is);
379 | BufferedImage newImage = resize(image, realWidth, realHeight);
380 | BufferedImage grayImage = new BufferedImage(realWidth, realHeight, BufferedImage.TYPE_BYTE_GRAY);
381 | for (int i = 0 ; i < realWidth ; i++) {
382 | for (int j = 0 ; j < realHeight; j++) {
383 | int rgb = newImage.getRGB(i, j);
384 | grayImage.setRGB(i, j, rgb * 255); // 将像素存入缓冲区
385 | }
386 | }
387 | File newFile = new File(outPath);
388 | ImageIO.write(grayImage, "jpg", newFile);
389 | } catch (IOException e) {
390 | e.printStackTrace();
391 | }
392 | }
393 |
394 | }
--------------------------------------------------------------------------------
/src/main/java/com/baidu/aip/face/AipFace.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2017 Baidu, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
5 | * the License. You may obtain a copy of the License at
6 | *
7 | * http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
10 | * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
11 | * specific language governing permissions and limitations under the License.
12 | */
13 |
14 | package com.baidu.aip.face;
15 |
16 | import com.baidu.aip.client.BaseClient;
17 | import com.baidu.aip.error.AipError;
18 | import com.baidu.aip.http.AipRequest;
19 | import com.baidu.aip.http.EBodyFormat;
20 | import com.baidu.aip.util.Base64Util;
21 | import com.baidu.aip.util.Util;
22 | import org.json.JSONObject;
23 | import org.json.JSONArray;
24 |
25 | import java.io.IOException;
26 | import java.util.HashMap;
27 | import java.util.List;
28 |
29 | public class AipFace extends BaseClient {
30 |
31 | public AipFace(String appId, String apiKey, String secretKey) {
32 | super(appId, apiKey, secretKey);
33 | }
34 |
35 | /**
36 | * 人脸检测接口
37 | *
38 | * @param image - 图片信息(**总数据大小应小于10M**),图片上传方式根据image_type来判断
39 | * @param imageType - 图片类型
**BASE64**:图片的base64值,base64编码后的图片数据,编码后的图片大小不超过2M;
**URL**:图片的 URL地址( 可能由于网络等原因导致下载图片时间过长);
**FACE_TOKEN**: 人脸图片的唯一标识,调用人脸检测接口时,会为每个人脸图片赋予一个唯一的FACE_TOKEN,同一张图片多次检测得到的FACE_TOKEN是同一个。
40 | * @param options - 可选参数对象,key: value都为string类型
41 | * options - options列表:
42 | * face_field 包括**age,beauty,expression,face_shape,gender,glasses,landmark,landmark72,landmark150,race,quality,eye_status,emotion,face_type信息**
逗号分隔. 默认只返回face_token、人脸框、概率和旋转角度
43 | * max_face_num 最多处理人脸的数目,默认值为1,仅检测图片中面积最大的那个人脸;**最大值10**,检测图片中面积最大的几张人脸。
44 | * face_type 人脸的类型 **LIVE**表示生活照:通常为手机、相机拍摄的人像图片、或从网络获取的人像图片等**IDCARD**表示身份证芯片照:二代身份证内置芯片中的人像照片 **WATERMARK**表示带水印证件照:一般为带水印的小图,如公安网小图 **CERT**表示证件照片:如拍摄的身份证、工卡、护照、学生证等证件图片 默认**LIVE**
45 | * liveness_control 活体检测控制 **NONE**: 不进行控制 **LOW**:较低的活体要求(高通过率 低攻击拒绝率) **NORMAL**: 一般的活体要求(平衡的攻击拒绝率, 通过率) **HIGH**: 较高的活体要求(高攻击拒绝率 低通过率) **默认NONE**
46 | * @return JSONObject
47 | */
48 | public JSONObject detect(String image, String imageType, HashMap options) {
49 | AipRequest request = new AipRequest();
50 | preOperation(request);
51 |
52 | request.addBody("image", image);
53 |
54 | request.addBody("image_type", imageType);
55 | if (options != null) {
56 | request.addBody(options);
57 | }
58 | request.setUri(FaceConsts.DETECT);
59 | request.setBodyFormat(EBodyFormat.RAW_JSON);
60 | postOperation(request);
61 | return requestServer(request);
62 | }
63 |
64 | /**
65 | * 人脸搜索接口
66 | *
67 | * @param image - 图片信息(**总数据大小应小于10M**),图片上传方式根据image_type来判断
68 | * @param imageType - 图片类型
**BASE64**:图片的base64值,base64编码后的图片数据,编码后的图片大小不超过2M;
**URL**:图片的 URL地址( 可能由于网络等原因导致下载图片时间过长);
**FACE_TOKEN**: 人脸图片的唯一标识,调用人脸检测接口时,会为每个人脸图片赋予一个唯一的FACE_TOKEN,同一张图片多次检测得到的FACE_TOKEN是同一个。
69 | * @param groupIdList - 从指定的group中进行查找 用逗号分隔,**上限20个**
70 | * @param options - 可选参数对象,key: value都为string类型
71 | * options - options列表:
72 | * max_face_num 最多处理人脸的数目
**默认值为1(仅检测图片中面积最大的那个人脸)** **最大值10**
73 | * match_threshold 匹配阈值(设置阈值后,score低于此阈值的用户信息将不会返回) 最大100 最小0 默认80
**此阈值设置得越高,检索速度将会越快,推荐使用默认阈值`80`**
74 | * quality_control 图片质量控制 **NONE**: 不进行控制 **LOW**:较低的质量要求 **NORMAL**: 一般的质量要求 **HIGH**: 较高的质量要求 **默认 NONE**
75 | * liveness_control 活体检测控制 **NONE**: 不进行控制 **LOW**:较低的活体要求(高通过率 低攻击拒绝率) **NORMAL**: 一般的活体要求(平衡的攻击拒绝率, 通过率) **HIGH**: 较高的活体要求(高攻击拒绝率 低通过率) **默认NONE**
76 | * user_id 当需要对特定用户进行比对时,指定user_id进行比对。即人脸认证功能。
77 | * max_user_num 查找后返回的用户数量。返回相似度最高的几个用户,默认为1,最多返回50个。
78 | * @return JSONObject
79 | */
80 | public JSONObject search(String image, String imageType, String groupIdList, HashMap options) {
81 | AipRequest request = new AipRequest();
82 | preOperation(request);
83 |
84 | request.addBody("image", image);
85 |
86 | request.addBody("image_type", imageType);
87 |
88 | request.addBody("group_id_list", groupIdList);
89 | if (options != null) {
90 | request.addBody(options);
91 | }
92 | request.setUri(FaceConsts.SEARCH);
93 | request.setBodyFormat(EBodyFormat.RAW_JSON);
94 | postOperation(request);
95 | return requestServer(request);
96 | }
97 |
98 | /**
99 | * 人脸搜索 M:N 识别接口
100 | *
101 | * @param image - 图片信息(**总数据大小应小于10M**),图片上传方式根据image_type来判断
102 | * @param imageType - 图片类型
**BASE64**:图片的base64值,base64编码后的图片数据,编码后的图片大小不超过2M;
**URL**:图片的 URL地址( 可能由于网络等原因导致下载图片时间过长);
**FACE_TOKEN**: 人脸图片的唯一标识,调用人脸检测接口时,会为每个人脸图片赋予一个唯一的FACE_TOKEN,同一张图片多次检测得到的FACE_TOKEN是同一个。
103 | * @param groupIdList - 从指定的group中进行查找 用逗号分隔,**上限20个**
104 | * @param options - 可选参数对象,key: value都为string类型
105 | * options - options列表:
106 | * max_face_num 最多处理人脸的数目
**默认值为1(仅检测图片中面积最大的那个人脸)** **最大值10**
107 | * match_threshold 匹配阈值(设置阈值后,score低于此阈值的用户信息将不会返回) 最大100 最小0 默认80
**此阈值设置得越高,检索速度将会越快,推荐使用默认阈值`80`**
108 | * quality_control 图片质量控制 **NONE**: 不进行控制 **LOW**:较低的质量要求 **NORMAL**: 一般的质量要求 **HIGH**: 较高的质量要求 **默认 NONE**
109 | * liveness_control 活体检测控制 **NONE**: 不进行控制 **LOW**:较低的活体要求(高通过率 低攻击拒绝率) **NORMAL**: 一般的活体要求(平衡的攻击拒绝率, 通过率) **HIGH**: 较高的活体要求(高攻击拒绝率 低通过率) **默认NONE**
110 | * max_user_num 查找后返回的用户数量。返回相似度最高的几个用户,默认为1,最多返回50个。
111 | * @return JSONObject
112 | */
113 | public JSONObject multiSearch(String image, String imageType, String groupIdList, HashMap options) {
114 | AipRequest request = new AipRequest();
115 | preOperation(request);
116 |
117 | request.addBody("image", image);
118 |
119 | request.addBody("image_type", imageType);
120 |
121 | request.addBody("group_id_list", groupIdList);
122 | if (options != null) {
123 | request.addBody(options);
124 | }
125 | request.setUri(FaceConsts.MULTI_SEARCH);
126 | request.setBodyFormat(EBodyFormat.RAW_JSON);
127 | postOperation(request);
128 | return requestServer(request);
129 | }
130 |
131 | /**
132 | * 人脸注册接口
133 | *
134 | * @param image - 图片信息(总数据大小应小于10M),图片上传方式根据image_type来判断。注:组内每个uid下的人脸图片数目上限为20张
135 | * @param imageType - 图片类型
**BASE64**:图片的base64值,base64编码后的图片数据,编码后的图片大小不超过2M;
**URL**:图片的 URL地址( 可能由于网络等原因导致下载图片时间过长);
**FACE_TOKEN**: 人脸图片的唯一标识,调用人脸检测接口时,会为每个人脸图片赋予一个唯一的FACE_TOKEN,同一张图片多次检测得到的FACE_TOKEN是同一个。
136 | * @param groupId - 用户组id(由数字、字母、下划线组成),长度限制128B
137 | * @param userId - 用户id(由数字、字母、下划线组成),长度限制128B
138 | * @param options - 可选参数对象,key: value都为string类型
139 | * options - options列表:
140 | * user_info 用户资料,长度限制256B
141 | * quality_control 图片质量控制 **NONE**: 不进行控制 **LOW**:较低的质量要求 **NORMAL**: 一般的质量要求 **HIGH**: 较高的质量要求 **默认 NONE**
142 | * liveness_control 活体检测控制 **NONE**: 不进行控制 **LOW**:较低的活体要求(高通过率 低攻击拒绝率) **NORMAL**: 一般的活体要求(平衡的攻击拒绝率, 通过率) **HIGH**: 较高的活体要求(高攻击拒绝率 低通过率) **默认NONE**
143 | * action_type 操作方式 APPEND: 当user_id在库中已经存在时,对此user_id重复注册时,新注册的图片默认会追加到该user_id下,REPLACE : 当对此user_id重复注册时,则会用新图替换库中该user_id下所有图片,默认使用APPEND
144 | * @return JSONObject
145 | */
146 | public JSONObject addUser(String image, String imageType, String groupId, String userId, HashMap options) {
147 | AipRequest request = new AipRequest();
148 | preOperation(request);
149 |
150 | request.addBody("image", image);
151 |
152 | request.addBody("image_type", imageType);
153 |
154 | request.addBody("group_id", groupId);
155 |
156 | request.addBody("user_id", userId);
157 | if (options != null) {
158 | request.addBody(options);
159 | }
160 | request.setUri(FaceConsts.USER_ADD);
161 | request.setBodyFormat(EBodyFormat.RAW_JSON);
162 | postOperation(request);
163 | return requestServer(request);
164 | }
165 |
166 | /**
167 | * 人脸更新接口
168 | *
169 | * @param image - 图片信息(**总数据大小应小于10M**),图片上传方式根据image_type来判断
170 | * @param imageType - 图片类型
**BASE64**:图片的base64值,base64编码后的图片数据,编码后的图片大小不超过2M;
**URL**:图片的 URL地址( 可能由于网络等原因导致下载图片时间过长);
**FACE_TOKEN**: 人脸图片的唯一标识,调用人脸检测接口时,会为每个人脸图片赋予一个唯一的FACE_TOKEN,同一张图片多次检测得到的FACE_TOKEN是同一个。
171 | * @param groupId - 更新指定groupid下uid对应的信息
172 | * @param userId - 用户id(由数字、字母、下划线组成),长度限制128B
173 | * @param options - 可选参数对象,key: value都为string类型
174 | * options - options列表:
175 | * user_info 用户资料,长度限制256B
176 | * quality_control 图片质量控制 **NONE**: 不进行控制 **LOW**:较低的质量要求 **NORMAL**: 一般的质量要求 **HIGH**: 较高的质量要求 **默认 NONE**
177 | * liveness_control 活体检测控制 **NONE**: 不进行控制 **LOW**:较低的活体要求(高通过率 低攻击拒绝率) **NORMAL**: 一般的活体要求(平衡的攻击拒绝率, 通过率) **HIGH**: 较高的活体要求(高攻击拒绝率 低通过率) **默认NONE**
178 | * action_type 操作方式 APPEND: 当user_id在库中已经存在时,对此user_id重复注册时,新注册的图片默认会追加到该user_id下,REPLACE : 当对此user_id重复注册时,则会用新图替换库中该user_id下所有图片,默认使用APPEND
179 | * @return JSONObject
180 | */
181 | public JSONObject updateUser(String image, String imageType, String groupId, String userId, HashMap options) {
182 | AipRequest request = new AipRequest();
183 | preOperation(request);
184 |
185 | request.addBody("image", image);
186 |
187 | request.addBody("image_type", imageType);
188 |
189 | request.addBody("group_id", groupId);
190 |
191 | request.addBody("user_id", userId);
192 | if (options != null) {
193 | request.addBody(options);
194 | }
195 | request.setUri(FaceConsts.USER_UPDATE);
196 | request.setBodyFormat(EBodyFormat.RAW_JSON);
197 | postOperation(request);
198 | return requestServer(request);
199 | }
200 |
201 | /**
202 | * 人脸删除接口
203 | *
204 | * @param userId - 用户id(由数字、字母、下划线组成),长度限制128B
205 | * @param groupId - 用户组id(由数字、字母、下划线组成),长度限制128B
206 | * @param faceToken - 需要删除的人脸图片token,(由数字、字母、下划线组成)长度限制64B
207 | * @param options - 可选参数对象,key: value都为string类型
208 | * options - options列表:
209 | * @return JSONObject
210 | */
211 | public JSONObject faceDelete(String userId, String groupId, String faceToken, HashMap options) {
212 | AipRequest request = new AipRequest();
213 | preOperation(request);
214 |
215 | request.addBody("user_id", userId);
216 |
217 | request.addBody("group_id", groupId);
218 |
219 | request.addBody("face_token", faceToken);
220 | if (options != null) {
221 | request.addBody(options);
222 | }
223 | request.setUri(FaceConsts.FACE_DELETE);
224 | request.setBodyFormat(EBodyFormat.RAW_JSON);
225 | postOperation(request);
226 | return requestServer(request);
227 | }
228 |
229 | /**
230 | * 用户信息查询接口
231 | *
232 | * @param userId - 用户id(由数字、字母、下划线组成),长度限制128B
233 | * @param groupId - 用户组id(由数字、字母、下划线组成),长度限制128B
234 | * @param options - 可选参数对象,key: value都为string类型
235 | * options - options列表:
236 | * @return JSONObject
237 | */
238 | public JSONObject getUser(String userId, String groupId, HashMap options) {
239 | AipRequest request = new AipRequest();
240 | preOperation(request);
241 |
242 | request.addBody("user_id", userId);
243 |
244 | request.addBody("group_id", groupId);
245 | if (options != null) {
246 | request.addBody(options);
247 | }
248 | request.setUri(FaceConsts.USER_GET);
249 | request.setBodyFormat(EBodyFormat.RAW_JSON);
250 | postOperation(request);
251 | return requestServer(request);
252 | }
253 |
254 | /**
255 | * 获取用户人脸列表接口
256 | *
257 | * @param userId - 用户id(由数字、字母、下划线组成),长度限制128B
258 | * @param groupId - 用户组id(由数字、字母、下划线组成),长度限制128B
259 | * @param options - 可选参数对象,key: value都为string类型
260 | * options - options列表:
261 | * @return JSONObject
262 | */
263 | public JSONObject faceGetlist(String userId, String groupId, HashMap options) {
264 | AipRequest request = new AipRequest();
265 | preOperation(request);
266 |
267 | request.addBody("user_id", userId);
268 |
269 | request.addBody("group_id", groupId);
270 | if (options != null) {
271 | request.addBody(options);
272 | }
273 | request.setUri(FaceConsts.FACE_GETLIST);
274 | request.setBodyFormat(EBodyFormat.RAW_JSON);
275 | postOperation(request);
276 | return requestServer(request);
277 | }
278 |
279 | /**
280 | * 获取用户列表接口
281 | *
282 | * @param groupId - 用户组id(由数字、字母、下划线组成),长度限制128B
283 | * @param options - 可选参数对象,key: value都为string类型
284 | * options - options列表:
285 | * start 默认值0,起始序号
286 | * length 返回数量,默认值100,最大值1000
287 | * @return JSONObject
288 | */
289 | public JSONObject getGroupUsers(String groupId, HashMap options) {
290 | AipRequest request = new AipRequest();
291 | preOperation(request);
292 |
293 | request.addBody("group_id", groupId);
294 | if (options != null) {
295 | request.addBody(options);
296 | }
297 | request.setUri(FaceConsts.GROUP_GETUSERS);
298 | request.setBodyFormat(EBodyFormat.RAW_JSON);
299 | postOperation(request);
300 | return requestServer(request);
301 | }
302 |
303 | /**
304 | * 复制用户接口
305 | *
306 | * @param userId - 用户id(由数字、字母、下划线组成),长度限制128B
307 | * @param options - 可选参数对象,key: value都为string类型
308 | * options - options列表:
309 | * src_group_id 从指定组里复制信息
310 | * dst_group_id 需要添加用户的组id
311 | * @return JSONObject
312 | */
313 | public JSONObject userCopy(String userId, HashMap options) {
314 | AipRequest request = new AipRequest();
315 | preOperation(request);
316 |
317 | request.addBody("user_id", userId);
318 | if (options != null) {
319 | request.addBody(options);
320 | }
321 | request.setUri(FaceConsts.USER_COPY);
322 | request.setBodyFormat(EBodyFormat.RAW_JSON);
323 | postOperation(request);
324 | return requestServer(request);
325 | }
326 |
327 | /**
328 | * 删除用户接口
329 | *
330 | * @param groupId - 用户组id(由数字、字母、下划线组成),长度限制128B
331 | * @param userId - 用户id(由数字、字母、下划线组成),长度限制128B
332 | * @param options - 可选参数对象,key: value都为string类型
333 | * options - options列表:
334 | * @return JSONObject
335 | */
336 | public JSONObject deleteUser(String groupId, String userId, HashMap options) {
337 | AipRequest request = new AipRequest();
338 | preOperation(request);
339 |
340 | request.addBody("group_id", groupId);
341 |
342 | request.addBody("user_id", userId);
343 | if (options != null) {
344 | request.addBody(options);
345 | }
346 | request.setUri(FaceConsts.USER_DELETE);
347 | request.setBodyFormat(EBodyFormat.RAW_JSON);
348 | postOperation(request);
349 | return requestServer(request);
350 | }
351 |
352 | /**
353 | * 创建用户组接口
354 | *
355 | * @param groupId - 用户组id(由数字、字母、下划线组成),长度限制128B
356 | * @param options - 可选参数对象,key: value都为string类型
357 | * options - options列表:
358 | * @return JSONObject
359 | */
360 | public JSONObject groupAdd(String groupId, HashMap options) {
361 | AipRequest request = new AipRequest();
362 | preOperation(request);
363 |
364 | request.addBody("group_id", groupId);
365 | if (options != null) {
366 | request.addBody(options);
367 | }
368 | request.setUri(FaceConsts.GROUP_ADD);
369 | request.setBodyFormat(EBodyFormat.RAW_JSON);
370 | postOperation(request);
371 | return requestServer(request);
372 | }
373 |
374 | /**
375 | * 删除用户组接口
376 | *
377 | * @param groupId - 用户组id(由数字、字母、下划线组成),长度限制128B
378 | * @param options - 可选参数对象,key: value都为string类型
379 | * options - options列表:
380 | * @return JSONObject
381 | */
382 | public JSONObject groupDelete(String groupId, HashMap options) {
383 | AipRequest request = new AipRequest();
384 | preOperation(request);
385 |
386 | request.addBody("group_id", groupId);
387 | if (options != null) {
388 | request.addBody(options);
389 | }
390 | request.setUri(FaceConsts.GROUP_DELETE);
391 | request.setBodyFormat(EBodyFormat.RAW_JSON);
392 | postOperation(request);
393 | return requestServer(request);
394 | }
395 |
396 | /**
397 | * 组列表查询接口
398 | *
399 | * @param options - 可选参数对象,key: value都为string类型
400 | * options - options列表:
401 | * start 默认值0,起始序号
402 | * length 返回数量,默认值100,最大值1000
403 | * @return JSONObject
404 | */
405 | public JSONObject getGroupList(HashMap options) {
406 | AipRequest request = new AipRequest();
407 | preOperation(request);
408 | if (options != null) {
409 | request.addBody(options);
410 | }
411 | request.setUri(FaceConsts.GROUP_GETLIST);
412 | request.setBodyFormat(EBodyFormat.RAW_JSON);
413 | postOperation(request);
414 | return requestServer(request);
415 | }
416 |
417 | /**
418 | * 身份验证接口
419 | *
420 | * @param image - 图片信息(**总数据大小应小于10M**),图片上传方式根据image_type来判断
421 | * @param imageType - 图片类型
**BASE64**:图片的base64值,base64编码后的图片数据,编码后的图片大小不超过2M;
**URL**:图片的 URL地址( 可能由于网络等原因导致下载图片时间过长);
**FACE_TOKEN**: 人脸图片的唯一标识,调用人脸检测接口时,会为每个人脸图片赋予一个唯一的FACE_TOKEN,同一张图片多次检测得到的FACE_TOKEN是同一个。
422 | * @param idCardNumber - 身份证号(真实身份证号号码)
423 | * @param name - utf8,姓名(真实姓名,和身份证号匹配)
424 | * @param options - 可选参数对象,key: value都为string类型
425 | * options - options列表:
426 | * quality_control 图片质量控制 **NONE**: 不进行控制 **LOW**:较低的质量要求 **NORMAL**: 一般的质量要求 **HIGH**: 较高的质量要求 **默认 NONE**
427 | * liveness_control 活体检测控制 **NONE**: 不进行控制 **LOW**:较低的活体要求(高通过率 低攻击拒绝率) **NORMAL**: 一般的活体要求(平衡的攻击拒绝率, 通过率) **HIGH**: 较高的活体要求(高攻击拒绝率 低通过率) **默认NONE**
428 | * @return JSONObject
429 | */
430 | public JSONObject personVerify(String image, String imageType, String idCardNumber, String name, HashMap options) {
431 | AipRequest request = new AipRequest();
432 | preOperation(request);
433 |
434 | request.addBody("image", image);
435 |
436 | request.addBody("image_type", imageType);
437 |
438 | request.addBody("id_card_number", idCardNumber);
439 |
440 | request.addBody("name", name);
441 | if (options != null) {
442 | request.addBody(options);
443 | }
444 | request.setUri(FaceConsts.PERSON_VERIFY);
445 | request.setBodyFormat(EBodyFormat.RAW_JSON);
446 | postOperation(request);
447 | return requestServer(request);
448 | }
449 |
450 | /**
451 | * 语音校验码接口接口
452 | *
453 | * @param options - 可选参数对象,key: value都为string类型
454 | * options - options列表:
455 | * appid 百度云创建应用时的唯一标识ID
456 | * @return JSONObject
457 | */
458 | public JSONObject videoSessioncode(HashMap options) {
459 | AipRequest request = new AipRequest();
460 | preOperation(request);
461 | if (options != null) {
462 | request.addBody(options);
463 | }
464 | request.setUri(FaceConsts.VIDEO_SESSIONCODE);
465 | request.setBodyFormat(EBodyFormat.RAW_JSON);
466 | postOperation(request);
467 | return requestServer(request);
468 | }
469 |
470 | /**
471 | * 视频活体检测接口接口
472 | *
473 | * @param sessionId - 语音校验码会话id,使用此接口的前提是已经调用了语音校验码接口
474 | * @param video - 二进制图像数据
475 | * @param options - 可选参数对象,key: value都为string类型
476 | * options - options列表:
477 | * @return JSONObject
478 | */
479 | public JSONObject videoFaceliveness(String sessionId, byte[] video, HashMap options) {
480 | AipRequest request = new AipRequest();
481 | preOperation(request);
482 |
483 | request.addBody("session_id", sessionId);
484 |
485 | String base64Content = Base64Util.encode(video);
486 | request.addBody("video_base64", base64Content);
487 | if (options != null) {
488 | request.addBody(options);
489 | }
490 | request.setUri(FaceConsts.VIDEO_FACELIVENESS);
491 | postOperation(request);
492 | return requestServer(request);
493 | }
494 |
495 | /**
496 | * 视频活体检测接口接口
497 | *
498 | * @param sessionId - 语音校验码会话id,使用此接口的前提是已经调用了语音校验码接口
499 | * @param video - 本地图片路径
500 | * @param options - 可选参数对象,key: value都为string类型
501 | * options - options列表:
502 | * @return JSONObject
503 | */
504 | public JSONObject videoFaceliveness(String sessionId, String video, HashMap options) {
505 | try {
506 | byte[] data = Util.readFileByBytes(video);
507 | return videoFaceliveness(sessionId, data, options);
508 | } catch (IOException e) {
509 | e.printStackTrace();
510 | return AipError.IMAGE_READ_ERROR.toJsonResult();
511 | }
512 | }
513 |
514 |
515 | /**
516 | * 人脸对比接口
517 | * 两张人脸图片相似度对比:比对两张图片中人脸的相似度,并返回相似度分值
518 | *
519 | * @param input - 请求参数array
520 | * image: 必须,图片信息(**总数据大小应小于10M**),图片上传方式根据image_type来判断
521 | * imageType: 必须,图片类型 **BASE64**:图片的base64值,base64编码后的图片数据,需urlencode,编码后的图片大小不超过2M;**URL**:图片的 URL地址( 可能由于网络等原因导致下载图片时间过长)**;FACE_TOKEN**: 人脸图片的唯一标识,调用人脸检测接口时,会为每个人脸图片赋予一个唯一的FACE_TOKEN,同一张图片多次检测得到的FACE_TOKEN是同一个
522 | * faceType: 可选,人脸的类型 LIVE表示生活照:通常为手机、相机拍摄的人像图片、或从网络获取的人像图片等 IDCARD表示身份证芯片照:二代身份证内置芯片中的人像照片 WATERMARK表示带水印证件照:一般为带水印的小图,如公安网小图 CERT表示证件照片:如拍摄的身份证、工卡、护照、学生证等证件图片 默认LIVE
523 | * qualityControl: 可选,质量控制 NONE: 不进行控制 LOW:较低的质量要求 NORMAL: 一般的质量要求 HIGH: 较高的质量要求 默认NONE
524 | * livenessControl: 可选,活体控制 NONE: 不进行控制 LOW:较低的活体要求(高通过率 低攻击拒绝率) NORMAL: 一般的活体要求(平衡的攻击拒绝率, 通过率) HIGH: 较高的活体要求(高攻击拒绝率 低通过率) 默认NONE
525 | * @return JSONObject
526 | */
527 | public JSONObject match(List input) {
528 | AipRequest request = new AipRequest();
529 |
530 | preOperation(request);
531 | JSONArray arr = new JSONArray();
532 | for (MatchRequest req : input) {
533 | arr.put(req.toJsonObject());
534 | }
535 | request.addBody("body", arr.toString());
536 | request.setBodyFormat(EBodyFormat.RAW_JSON_ARRAY);
537 | request.setUri(FaceConsts.MATCH);
538 | postOperation(request);
539 | return requestServer(request);
540 | }
541 |
542 | /**
543 | * 在线活体检测接口
544 | *
545 | *
546 | * @param input - 请求参数array
547 | * image: 必须,图片信息(**总数据大小应小于10M**),图片上传方式根据image_type来判断
548 | * imageType: 必须 图片类型 **BASE64**:图片的base64值,base64编码后的图片数据,需urlencode,编码后的图片大小不超过2M;**URL**:图片的 URL地址( 可能由于网络等原因导致下载图片时间过长)**;FACE_TOKEN**: 人脸图片的唯一标识,调用人脸检测接口时,会为每个人脸图片赋予一个唯一的FACE_TOKEN,同一张图片多次检测得到的FACE_TOKEN是同一个
549 | * face_field:可选 包括age,beauty,expression,faceshape,gender,glasses,landmark,race,quality,facetype,parsing信息,逗号分隔,默认只返回face_token、活体数、人脸框、概率和旋转角度。
550 | * @return JSONObject
551 | */
552 | public JSONObject faceverify(List input) {
553 | AipRequest request = new AipRequest();
554 |
555 | preOperation(request);
556 | JSONArray arr = new JSONArray();
557 | for (FaceVerifyRequest req : input) {
558 | arr.put(req.toJsonObject());
559 | }
560 | request.addBody("body", arr.toString());
561 | request.setBodyFormat(EBodyFormat.RAW_JSON_ARRAY);
562 | request.setUri(FaceConsts.FACEVERIFY);
563 | postOperation(request);
564 | return requestServer(request);
565 | }
566 |
567 | /**
568 | * 身份证与名字比对接口
569 | */
570 | public JSONObject idMatch(String idCardNum, String name, HashMap options) {
571 | AipRequest request = new AipRequest();
572 |
573 | preOperation(request);
574 | request.addBody("id_card_number", idCardNum);
575 | request.addBody("name", name);
576 | if (options != null) {
577 | request.addBody(options);
578 | }
579 | request.setUri(FaceConsts.ID_MATCH);
580 | request.setBodyFormat(EBodyFormat.RAW_JSON);
581 | postOperation(request);
582 | return requestServer(request);
583 |
584 | }
585 |
586 | }
--------------------------------------------------------------------------------