Commit cafaf74a authored by huangcb's avatar huangcb

新增天壤智能OCR组件

parent a29bca25
......@@ -123,6 +123,10 @@
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
</dependency>
</dependencies>
<dependencyManagement>
......
package com.esv.freight.file.common.component;
import com.alibaba.fastjson.JSONObject;
import com.esv.freight.file.common.constants.TianRangOcrConstants;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Random;
import java.util.UUID;
/**
* @description: 天壤OCR组件
* @project: freight-file-service
* @name: com.esv.freight.file.common.component.TianRangOcrComponent
* @author: 黄朝斌
* @email: huangchaobin@esvtek.com
* @createTime: 2020/06/28 11:16
* @version:1.0
*/
@Component
@Slf4j
public class TianRangOcrComponent {
/**
* description 图片文件OCR
* param [ocrType, bytes]
* return java.lang.String
* author HuangChaobin
* createTime 2020/06/28 14:14
**/
public String ocr(int ocrType, byte[] bytes) {
// 创建临时文件
File temp;
try {
temp = this.createTmpFile(bytes);
} catch (IOException e) {
log.error("创建临时文件失败:{}", e.getMessage(), e);
return null;
}
// 构造Http请求内容
CloseableHttpClient http = HttpClients.createDefault();
HttpPost post = new HttpPost(TianRangOcrConstants.BASE_URL + "/public/api/esvtek/ai/" + ocrType);
try {
this.setPostUri(post, ocrType);
FileBody fileBody = new FileBody(temp);
MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create();
multipartEntity.addPart(TianRangOcrConstants.MEDIA_ID, fileBody);
post.setEntity(multipartEntity.build());
} catch (Exception e) {
log.error("构造OCR Http请求内容失败:{}", e.getMessage(), e);
return null;
} finally {
temp.deleteOnExit();
}
// 执行Http请求
String result = null;
try {
long startTime = System.currentTimeMillis();
HttpResponse response = http.execute(post);
long endTime = System.currentTimeMillis();
log.info("ocr http request spend time {} ms", endTime - startTime);
result = EntityUtils.toString(response.getEntity());
log.info("ocr result: {}", result);
} catch (IOException e) {
log.error("OCR Http请求失败:{}", e.getMessage(), e);
}
return result;
}
/**
* description 获取OCR数据
* param [result]
* return com.alibaba.fastjson.JSONObject
* author HuangChaobin
* createTime 2020/06/28 14:21
**/
public JSONObject getOcrData(String result) {
if (null == result) {
return null;
}
JSONObject resultJson = JSONObject.parseObject(result);
if (TianRangOcrConstants.SUCCESS_CODE == resultJson.getIntValue("code")) {
return resultJson.getJSONObject("data");
} else {
return null;
}
}
private void setPostUri(HttpPost post, int ocrType) throws URISyntaxException {
String nonce = this.generateNonce(6);
Long timestamp = System.currentTimeMillis();
StringBuffer sb = new StringBuffer();
sb.append("POST");
sb.append("\n");
sb.append("/public/api/esvtek/ai/" + ocrType);
sb.append("\n");
sb.append("appkey=");
sb.append(TianRangOcrConstants.APP_KEY);
sb.append("&nonce=");
sb.append(nonce);
sb.append("&timestamp=");
sb.append(timestamp);
String sign = this.sha256_HMAC(sb.toString(), TianRangOcrConstants.APP_SECRET);
URI uri = new URIBuilder(post.getURI()).
addParameter("appkey", TianRangOcrConstants.APP_KEY).
addParameter("timestamp", String.valueOf(timestamp)).
addParameter("nonce", nonce).
addParameter("signature", sign).
build();
post.setURI(uri);
}
/**
* description 创建临时文件
* param [bytes]
* return java.io.File
* author HuangChaobin
* createTime 2020/06/28 13:42
**/
private File createTmpFile(byte[] bytes) throws IOException {
File temp = File.createTempFile(UUID.randomUUID().toString(), ".jpg");
FileOutputStream fos = new FileOutputStream(temp);
BufferedOutputStream bos = new BufferedOutputStream(fos);
bos.write(bytes);
return temp;
}
/**
* sha256_HMAC加密
* @param message 消息
* @param secret 秘钥
* @return 加密后字符串
*/
private String sha256_HMAC(String message, String secret) {
String hash = "";
try {
Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(), "HmacSHA256");
sha256_HMAC.init(secret_key);
byte[] bytes = sha256_HMAC.doFinal(message.getBytes());
hash = byteArrayToHexString(bytes);
} catch (Exception e) {
log.error("Error HmacSHA256 =========== {}", e.getMessage(), e);
}
return hash;
}
/**
* 将加密后的字节数组转换成字符串
*
* @param b 字节数组
* @return 字符串
*/
private String byteArrayToHexString(byte[] b) {
StringBuilder hs = new StringBuilder();
String sTmp;
for (int n = 0; b != null && n < b.length; n++) {
sTmp = Integer.toHexString(b[n] & 0XFF);
if (1 == sTmp.length()) {
hs.append('0');
}
hs.append(sTmp);
}
return hs.toString().toLowerCase();
}
/**
* description 生成随机数
* param [len]
* return java.lang.String
* author HuangChaobin
* createTime 2020/06/28 13:48
**/
private String generateNonce(int len) {
String letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
Random random = new Random();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < len; i++) {
int number = random.nextInt(62);
sb.append(letters.charAt(number));
}
return sb.toString();
}
}
package com.esv.freight.file.common.constants;
/**
* @description: 天壤OCR常量
* @project: freight-file-service
* @name: com.esv.freight.file.common.constants.TianRangOcrConstants
* @author: 黄朝斌
* @email: huangchaobin@esvtek.com
* @createTime: 2020/06/28 11:16
* @version:1.0
*/
public class TianRangOcrConstants {
public static final String APP_KEY = "1e29453c9850449b8ed3fa407d28a5f9";
public static final String APP_SECRET = "65e78c4f46004d4293b2a16af34c153c";
public static final String BASE_URL = "http://ts.tianrang.com";
public static final int SUCCESS_CODE = 0;
/**
* 营业执照
*/
public static final int BUSINESS_LICENCE = 1;
/**
* 身份证
*/
public static final int ID_CARD = 11;
/**
* 驾驶证
*/
public static final int JIASHIZHENG = 12;
/**
* 行驶证
*/
public static final int XINGSHIZHENG = 13;
/**
* 道路运输证
*/
public static final int DAOLU_YUNSHU = 23;
/**
* 道路运输经营许可证
*/
public static final int DAOLU_JINGYING = 24;
/**
* 道路运输从业资格证
*/
public static final int DAOLU_CONGYE = 25;
public static final String MEDIA_ID = "media_id";
}
package com.esv.freight.file.common.util;
import lombok.extern.slf4j.Slf4j;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* @description: InputStream工具类
* @project: freight-file-service
* @name: com.esv.freight.file.common.util.InputStreamUtils
* @author: 黄朝斌
* @email: huangchaobin@esvtek.com
* @createTime: 2020/06/28 15:10
* @version:1.0
*/
@Slf4j
public class InputStreamUtils {
/**
* description byte数组转InputStream
* param [bytes]
* return java.io.InputStream
* author Administrator
* createTime 2020/05/21 19:14
**/
public static InputStream byte2InputStream(byte[] bytes) {
return new ByteArrayInputStream(bytes);
}
/**
* description InputStream转byte数组
* param [inputStream]
* return byte[]
* author Administrator
* createTime 2020/05/21 19:15
**/
public static byte[] inputStream2byte(InputStream inputStream) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byte[] buff = new byte[100];
int rc = 0;
try {
while ((rc = inputStream.read(buff, 0, 100)) > 0) {
byteArrayOutputStream.write(buff, 0, rc);
}
} catch (IOException e) {
log.error(e.getMessage(), e);
}
return byteArrayOutputStream.toByteArray();
}
}
package com.esv.freight.file.common.component;
import com.esv.freight.file.common.constants.TianRangOcrConstants;
import com.esv.freight.file.common.util.InputStreamUtils;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
/**
* @description:
* @project: freight-file-service
* @name: com.esv.freight.file.common.component.TianRangOcrComponentTest
* @author: 黄朝斌
* @email: huangchaobin@esvtek.com
* @createTime: 2020/06/28 15:04
* @version:1.0
*/
@RunWith(SpringRunner.class)
@SpringBootTest
@Slf4j
public class TianRangOcrComponentTest {
@Autowired
private TianRangOcrComponent tianRangOcrComponent;
@Test
public void a1_ocr_collection_test() throws Exception {
ID_CARD_front_test();
ID_CARD_back_test();
JIASHIZHENG_test();
XINGSHIZHENG_test();
BUSINESS_LICENCE_test();
DAOLU_YUNSHU_test();
DAOLU_JINGYING_test();
DAOLU_CONGYE_test();
}
public void ID_CARD_front_test() throws Exception {
log.info("---------- 身份证正面 ----------");
// 构造数据
String filepath = "E:\\SVN\\04.项目库\\05.网络货运平台\\天壤智能-测试\\黄朝斌_身份证_头像.jpg";
File file = new File(filepath);
InputStream input = new FileInputStream(file);
byte[] bytes = InputStreamUtils.inputStream2byte(input);
String result = tianRangOcrComponent.ocr(TianRangOcrConstants.ID_CARD, bytes);
log.info(result);
log.info("---------- 身份证正面 ----------");
}
public void ID_CARD_back_test() throws Exception {
log.info("---------- 身份证背面 ----------");
// 构造数据
String filepath = "E:\\SVN\\04.项目库\\05.网络货运平台\\天壤智能-测试\\黄朝斌_身份证_国徽.jpg";
File file = new File(filepath);
InputStream input = new FileInputStream(file);
byte[] bytes = InputStreamUtils.inputStream2byte(input);
String result = tianRangOcrComponent.ocr(TianRangOcrConstants.ID_CARD, bytes);
log.info(result);
log.info("---------- 身份证背面 ----------");
}
public void JIASHIZHENG_test() throws Exception {
log.info("---------- 驾驶证 ----------");
// 构造数据
String filepath = "E:\\SVN\\04.项目库\\05.网络货运平台\\天壤智能-测试\\黄朝斌_驾驶证.jpg";
File file = new File(filepath);
InputStream input = new FileInputStream(file);
byte[] bytes = InputStreamUtils.inputStream2byte(input);
String result = tianRangOcrComponent.ocr(TianRangOcrConstants.JIASHIZHENG, bytes);
log.info(result);
log.info("---------- 驾驶证 ----------");
}
public void XINGSHIZHENG_test() throws Exception {
log.info("---------- 行驶证 ----------");
// 构造数据
String filepath = "E:\\SVN\\04.项目库\\05.网络货运平台\\天壤智能-测试\\黄朝斌_行驶证.jpg";
File file = new File(filepath);
InputStream input = new FileInputStream(file);
byte[] bytes = InputStreamUtils.inputStream2byte(input);
String result = tianRangOcrComponent.ocr(TianRangOcrConstants.XINGSHIZHENG, bytes);
log.info(result);
log.info("---------- 行驶证 ----------");
}
public void BUSINESS_LICENCE_test() throws Exception {
log.info("---------- 营业执照 ----------");
// 构造数据
String filepath = "E:\\SVN\\04.项目库\\05.网络货运平台\\天壤智能-测试\\苏州英思唯智能科技有限公司-营业执照.jpg";
File file = new File(filepath);
InputStream input = new FileInputStream(file);
byte[] bytes = InputStreamUtils.inputStream2byte(input);
String result = tianRangOcrComponent.ocr(TianRangOcrConstants.BUSINESS_LICENCE, bytes);
log.info(result);
log.info("---------- 营业执照 ----------");
}
public void DAOLU_YUNSHU_test() throws Exception {
log.info("---------- 道路运输证 ----------");
// 构造数据
String filepath = "E:\\SVN\\04.项目库\\05.网络货运平台\\天壤智能-测试\\道路运输证.jpg";
File file = new File(filepath);
InputStream input = new FileInputStream(file);
byte[] bytes = InputStreamUtils.inputStream2byte(input);
String result = tianRangOcrComponent.ocr(TianRangOcrConstants.DAOLU_YUNSHU, bytes);
log.info(result);
log.info("---------- 道路运输证 ----------");
}
public void DAOLU_JINGYING_test() throws Exception {
log.info("---------- 道路运输经营许可证 ----------");
// 构造数据
String filepath = "E:\\SVN\\04.项目库\\05.网络货运平台\\天壤智能-测试\\道路运输经营许可证.jpg";
File file = new File(filepath);
InputStream input = new FileInputStream(file);
byte[] bytes = InputStreamUtils.inputStream2byte(input);
String result = tianRangOcrComponent.ocr(TianRangOcrConstants.DAOLU_JINGYING, bytes);
log.info(result);
log.info("---------- 道路运输经营许可证 ----------");
}
public void DAOLU_CONGYE_test() throws Exception {
log.info("---------- 道路运输从业资格证 ----------");
// 构造数据
String filepath = "E:\\SVN\\04.项目库\\05.网络货运平台\\天壤智能-测试\\道路运输从业资格证.jpeg";
File file = new File(filepath);
InputStream input = new FileInputStream(file);
byte[] bytes = InputStreamUtils.inputStream2byte(input);
String result = tianRangOcrComponent.ocr(TianRangOcrConstants.DAOLU_CONGYE, bytes);
log.info(result);
log.info("---------- 道路运输从业资格证 ----------");
}
}
......@@ -49,12 +49,12 @@ public class UploadControllerTest extends BaseTestController {
JSONObject reqJson = new JSONObject();
// 构造数据
String filepath = "D:\\test\\苏州英思唯智能科技有限公司沈阳分公司.png";
String filepath = "D:\\test\\路上飞-签名.PNG";
File file = new File(filepath);
InputStream input = new FileInputStream(file);
reqJson.put("fileType", "image");
reqJson.put("fileData", Base64.getEncoder().encodeToString(IOUtils.toByteArray(input)));
reqJson.put("fileName", "苏州英思唯智能科技有限公司沈阳分公司-公章");
reqJson.put("fileName", "路上飞-签名.PNG");
MvcResult mvcResult = this.getMockMvc().perform(MockMvcRequestBuilders.post(url)
.contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment