Commit 59312ac5 by 徐甲彬

增加百度文字识别接口,并整合统一图片扫描接口

1 parent 2fb7eb7f
/*****************************************
* *
* @dookay.com Internet make it happen *
* ----------- ----------------------- *
* dddd ddddd Internet make it happen *
* o o o Internet make it happen *
* k k k Internet make it happen *
* a a a Internet make it happen *
* yyyy yyyyy Internet make it happen *
* ----------- ----------------------- *
* Code is far away from bug with the *
* animal protecting *
* 神兽保佑,代码无bug  *
* *
****************************************/
package com.dookay.cihai.core.aip;
import com.dookay.cihai.core.aip.enums.ImageInputTypeEnum;
import com.dookay.cihai.core.aip.enums.ScanResultTypeEnum;
import com.dookay.cihai.core.aip.model.GeneralRecognitionResult;
import com.dookay.cihai.core.aip.model.ImageResult;
import com.dookay.cihai.core.aip.model.ScanResult;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.Arrays;
import java.util.Collections;
/**
*
* @author Luxor
* @version v0.0.1
* @since 2017/12/7
*/
@Component
@Slf4j
public class AipDefaultClient {
@Autowired
private AipImageClassifyClient aipImageClassifyClient;
@Autowired
private AipOcrClient aipOcrClient;
/**
* 图片扫描
* @param
* @author luxor
* @date 2017/12/7
*/
public ScanResult scan(String imageBase64) throws JSONException {
ScanResult result = new ScanResult();
GeneralRecognitionResult generalRecognitionResult = aipOcrClient.generalRecognition(imageBase64, ImageInputTypeEnum.BASE64);
if(generalRecognitionResult.getWordsResultNum()>0){
result.setType(ScanResultTypeEnum.WORDS.getValue());
result.setWordsList(generalRecognitionResult.getWordsResult());
}else{
result.setType(ScanResultTypeEnum.PICTURE.getValue());
ImageResult imageResult = aipImageClassifyClient.getImageResult(imageBase64);
result.setWordsList(Collections.singletonList(imageResult.getName()));
}
return result;
}
}
......@@ -18,8 +18,6 @@ package com.dookay.cihai.core.aip;
import com.alibaba.fastjson.JSON;
import com.baidu.aip.imageclassify.AipImageClassify;
import com.baidu.aip.util.Base64Util;
import com.dookay.cihai.core.aip.config.AipProperties;
import com.dookay.cihai.core.aip.enums.ImageInputTypeEnum;
import com.dookay.cihai.core.aip.model.ImageResult;
import com.dookay.coral.common.core.exception.ServiceException;
......@@ -28,14 +26,10 @@ import org.codehaus.plexus.util.StringUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.Base64Utils;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.*;
/**
* 图片识别客户端
......@@ -53,7 +47,7 @@ public class AipImageClassifyClient {
public static final String SECRET_KEY = "YUGcqkGioxrceK4CgD3wB90vmmG7KzRf";
/**
* 获取动物图片识别结果列表,可能会有多个结果
* 获取动物图片识别结果列表,会有多个结果
* @param
* @author luxor
* @date 2017/12/7
......@@ -72,12 +66,11 @@ public class AipImageClassifyClient {
log.info(image);
}
// 调用接口
return parseResult(res);
}
/**
* 获取动物图片识别结果列表,可能会有多个结果
* 获取植物图片识别结果列表,会有多个结果
* @param
* @author luxor
* @date 2017/12/7
......@@ -96,7 +89,6 @@ public class AipImageClassifyClient {
log.info(image);
}
// 调用接口
return parseResult(res);
}
......@@ -135,15 +127,13 @@ public class AipImageClassifyClient {
if(StringUtils.isBlank(imageBase64)){
return new ImageResult();
}
String image = imageBase64.replace("data:image/png;base64,","")
.replace("data:image/jpg;base64,","")
.replace("data:image/jpeg;base64,","");
String image = AipUtils.fixImage(imageBase64);
log.info("image:"+image);
List<ImageResult> imageResultList = this.getAnimalDetect(image,ImageInputTypeEnum.BASE64);
List<ImageResult> imageResultList2 = this.getPlantDetect(image,ImageInputTypeEnum.BASE64);
imageResultList.addAll(imageResultList2);
log.info(JSON.toJSONString(imageResultList));
return imageResultList.stream().filter(x->x.getScore()<0.99).sorted(Comparator.comparing(ImageResult::getScore).reversed()).findFirst().orElse(new ImageResult());
return imageResultList.stream().filter(x-> !Objects.equals(x.getName(), "非动物")).sorted(Comparator.comparing(ImageResult::getScore).reversed()).findFirst().orElse(new ImageResult());
}
}
/*****************************************
* *
* @dookay.com Internet make it happen *
* ----------- ----------------------- *
* dddd ddddd Internet make it happen *
* o o o Internet make it happen *
* k k k Internet make it happen *
* a a a Internet make it happen *
* yyyy yyyyy Internet make it happen *
* ----------- ----------------------- *
* Code is far away from bug with the *
* animal protecting *
* 神兽保佑,代码无bug  *
* *
****************************************/
package com.dookay.cihai.core.aip;
import com.baidu.aip.ocr.AipOcr;
import com.dookay.cihai.core.aip.enums.ImageInputTypeEnum;
import com.dookay.cihai.core.aip.model.GeneralRecognitionResult;
import com.dookay.cihai.core.aip.model.ImageResult;
import com.dookay.coral.common.core.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.stereotype.Component;
import org.springframework.util.Base64Utils;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* 图文文字识别客户端
* @author Luxor
* @version v0.0.1
* @since 2017/12/7
*/
@Component
@Slf4j
public class AipOcrClient {
//设置APPID/AK/SK
public static final String APP_ID = "10492789";
public static final String API_KEY = "MfnPaNqkmPyyU6GecceDmkFt";
public static final String SECRET_KEY = "f7saVfLEXKC6AG6TU3CEfG0iUCXXY2kn";
/**
* 通用文字识别
* @param
* @param image
* @author luxor
* @date 2017/12/7
*/
public GeneralRecognitionResult generalRecognition(String image, ImageInputTypeEnum typeEnum) throws JSONException {
// 初始化一个AipOcr
AipOcr client = new AipOcr(APP_ID, API_KEY, SECRET_KEY);
// 自定义参数定义
HashMap<String, String> options = new HashMap<String, String>();
options.put("detect_direction", "true");
options.put("language_type", "CHN_ENG");
//调用接口
JSONObject res;
// 参数为本地图片路径
if(typeEnum == ImageInputTypeEnum.PATH){
res = client.basicGeneral(image, options);
}else{
image = AipUtils.fixImage(image);
byte[] file = Base64Utils.decodeFromString(image);
res = client.basicGeneral(file, options);
log.info(image);
}
return parseResult(res);
}
/**
* 解析结果
* @param
* @author luxor
* @date 2017/12/7
*/
private GeneralRecognitionResult parseResult(JSONObject res) throws JSONException {
if(res.has("error_code")){
log.info("图像识别错误:"+res.toString(2));
throw new ServiceException("图像识别错误:"+res.toString(2));
}else{
GeneralRecognitionResult result = new GeneralRecognitionResult();
result.setWordsResultNum(res.getInt("words_result_num"));
List<String> wordsList = new ArrayList<>();
JSONArray jsonArray = res.getJSONArray("words_result");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
wordsList.add(jsonObject.getString("words"));
}
result.setWordsResult(wordsList);
return result;
}
}
}
/*****************************************
* *
* @dookay.com Internet make it happen *
* ----------- ----------------------- *
* dddd ddddd Internet make it happen *
* o o o Internet make it happen *
* k k k Internet make it happen *
* a a a Internet make it happen *
* yyyy yyyyy Internet make it happen *
* ----------- ----------------------- *
* Code is far away from bug with the *
* animal protecting *
* 神兽保佑,代码无bug  *
* *
****************************************/
package com.dookay.cihai.core.aip;
import java.io.*;
import java.util.Base64;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
/**
* @author Luxor
* @version v0.0.1
* @since 2017/12/7
*/
public class AipUtils {
/**
* 读取txt文件的内容
* @param file 想要读取的文件对象
* @return 返回文件内容
* @author luxor
* @date 2017/12/7
*/
public static String txt2String(File file){
StringBuilder result = new StringBuilder();
try{
BufferedReader br = new BufferedReader(new FileReader(file));//构造一个BufferedReader类来读取文件
String s = null;
while((s = br.readLine())!=null){//使用readLine方法,一次读一行
result.append(s);
}
br.close();
}catch(Exception e){
e.printStackTrace();
}
return result.toString();
}
/**
* @param
* @author luxor
* @date 2017/12/7
*/
public static String fixImage(String imageBase64){
return imageBase64.replace("data:image/png;base64,","")
.replace("data:image/jpg;base64,","")
.replace("data:image/jpeg;base64,","");
}
/**
* 文件转base64字符串
* @param file
* @return
* @author luxor
* @date 2017/12/7
*/
public static String encodeBase64File( File file) throws Exception {
FileInputStream inputFile = new FileInputStream(file);
byte[] buffer = new byte[(int) file.length()];
inputFile.read(buffer);
inputFile.close();
return new BASE64Encoder().encode(buffer);
}
}
/*****************************************
* *
* @dookay.com Internet make it happen *
* ----------- ----------------------- *
* dddd ddddd Internet make it happen *
* o o o Internet make it happen *
* k k k Internet make it happen *
* a a a Internet make it happen *
* yyyy yyyyy Internet make it happen *
* ----------- ----------------------- *
* Code is far away from bug with the *
* animal protecting *
* 神兽保佑,代码无bug  *
* *
****************************************/
package com.dookay.cihai.core.aip.enums;
import com.dookay.coral.common.core.enums.IEnum;
/**
* @author Luxor
* @version v0.0.1
* @since 2017/12/7
*/
public enum ScanResultTypeEnum implements IEnum {
PICTURE(1, "图片"),
WORDS(2,"文字");
private int value;
private String description;
ScanResultTypeEnum(int value, String description) {
this.value = value;
this.description = description;
}
@Override
public int getValue() {
return value;
}
@Override
public String getDescription() {
return description;
}
public static ScanResultTypeEnum valueOf(Integer value) {
ScanResultTypeEnum[] values = ScanResultTypeEnum.values();
for (ScanResultTypeEnum item : values) {
if (item.value == value) {
return item;
}
}
return null;
}
}
/*****************************************
* *
* @dookay.com Internet make it happen *
* ----------- ----------------------- *
* dddd ddddd Internet make it happen *
* o o o Internet make it happen *
* k k k Internet make it happen *
* a a a Internet make it happen *
* yyyy yyyyy Internet make it happen *
* ----------- ----------------------- *
* Code is far away from bug with the *
* animal protecting *
* 神兽保佑,代码无bug  *
* *
****************************************/
package com.dookay.cihai.core.aip.model;
import lombok.Data;
import java.util.List;
/**
* @author Luxor
* @version v0.0.1
* @since 2017/12/7
*/
@Data
public class GeneralRecognitionResult {
/*识别结果数,表示words_result的元素个数*/
private Integer wordsResultNum;
/*识别结果字符串数字*/
private List<String> wordsResult;
}
/*****************************************
* *
* @dookay.com Internet make it happen *
* ----------- ----------------------- *
* dddd ddddd Internet make it happen *
* o o o Internet make it happen *
* k k k Internet make it happen *
* a a a Internet make it happen *
* yyyy yyyyy Internet make it happen *
* ----------- ----------------------- *
* Code is far away from bug with the *
* animal protecting *
* 神兽保佑,代码无bug  *
* *
****************************************/
package com.dookay.cihai.core.aip.model;
import lombok.Data;
import java.util.List;
/**
* 图像扫描结果
* @author Luxor
* @version v0.0.1
* @since 2017/12/7
*/
@Data
public class ScanResult {
/*图像、文字*/
private Integer type;
/*结果文字列表*/
private List<String> wordsList;
}
package com.dookay.cihai.core.aip;
import com.alibaba.fastjson.JSON;
import com.dookay.cihai.core.CihaiCoreApplicationTests;
import com.dookay.cihai.core.aip.model.ScanResult;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ResourceUtils;
import java.io.File;
/**
* @author Luxor
* @version v0.0.1
* @since 2017/12/7
*/
@Slf4j
public class AipDefaultClientTest extends CihaiCoreApplicationTests {
@Autowired
private AipDefaultClient aipDefaultClient;
@Test
public void scan() throws Exception {
File file = ResourceUtils.getFile("classpath:daxiang.txt");
String image = AipUtils.txt2String(file);
ScanResult result = aipDefaultClient.scan(image);
log.info(JSON.toJSONString(result));
}
}
\ No newline at end of file
......@@ -8,11 +8,7 @@ import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ResourceUtils;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import static org.junit.Assert.*;
/**
* @author Luxor
......@@ -26,32 +22,13 @@ public class AipImageClassifyClientTest extends CihaiCoreApplicationTests {
@Test
public void getImageResult() throws Exception {
File file = ResourceUtils.getFile("classpath:daxiang.txt");
System.out.println(txt2String(file));
String image = txt2String(file);
File file = ResourceUtils.getFile("classpath:mudan.txt");
System.out.println(AipUtils.txt2String(file));
String image = AipUtils.txt2String(file);
log.info(image);
ImageResult imageResult = aipImageClassifyClient.getImageResult(image);
Boolean flag = imageResult.getScore()<0.99;
log.info(JSON.toJSONString(imageResult));
}
/**
* 读取txt文件的内容
* @param file 想要读取的文件对象
* @return 返回文件内容
*/
public static String txt2String(File file){
StringBuilder result = new StringBuilder();
try{
BufferedReader br = new BufferedReader(new FileReader(file));//构造一个BufferedReader类来读取文件
String s = null;
while((s = br.readLine())!=null){//使用readLine方法,一次读一行
result.append(s);
}
br.close();
}catch(Exception e){
e.printStackTrace();
}
return result.toString();
}
}
\ No newline at end of file
package com.dookay.cihai.core.aip;
import com.alibaba.fastjson.JSON;
import com.dookay.cihai.core.CihaiCoreApplicationTests;
import com.dookay.cihai.core.aip.enums.ImageInputTypeEnum;
import com.dookay.cihai.core.aip.model.GeneralRecognitionResult;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ResourceUtils;
import java.io.*;
import static org.junit.Assert.*;
/**
* @author Luxor
* @version v0.0.1
* @since 2017/12/7
*/
@Slf4j
public class AipOcrClientTest extends CihaiCoreApplicationTests {
@Autowired
private AipOcrClient aipOcrClient;
@Test
public void generalRecognition() throws Exception {
File file = ResourceUtils.getFile("classpath:wenzi.txt");
String image = AipUtils.txt2String(file);
GeneralRecognitionResult result = aipOcrClient.generalRecognition(image, ImageInputTypeEnum.BASE64);
log.info(JSON.toJSONString(result));
}
@Test
public void generalRecognition2() throws Exception {
File file = ResourceUtils.getFile("classpath:daxiang.txt");
String image = AipUtils.txt2String(file);
GeneralRecognitionResult result = aipOcrClient.generalRecognition(image, ImageInputTypeEnum.BASE64);
log.info(JSON.toJSONString(result));
}
/**
* 读取txt文件的内容
* @param file 想要读取的文件对象
* @return 返回文件内容
*/
public static String txt2String(File file){
StringBuilder result = new StringBuilder();
try{
BufferedReader br = new BufferedReader(new FileReader(file));//构造一个BufferedReader类来读取文件
String s = null;
while((s = br.readLine())!=null){//使用readLine方法,一次读一行
result.append(s);
}
br.close();
}catch(Exception e){
e.printStackTrace();
}
return result.toString();
}
}
\ No newline at end of file
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!