wlzboy
3 天以前 40a8157440e3b906da8f52e07d939d78c3f4c313
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
package com.ruoyi.system.controller;
 
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.image.ImageCompressUtil;
import com.ruoyi.system.utils.AliOCRUtil;
import com.ruoyi.system.utils.BaiduOCRUtil;
import com.ruoyi.system.utils.TencentOCRUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
 
import java.io.File;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
 
/**
 * OCR识别Controller
 * 支持阿里云OCR和百度OCR服务
 * @author ruoyi
 */
@RestController
@RequestMapping("/system/ocr")
public class OCRController extends BaseController {
 
    @Autowired
    private AliOCRUtil aliOCRUtil;
 
    // 支持的OCR识别类型
    private static final List<String> SUPPORTED_TYPES = Arrays.asList("General", "Invoice", "IdCard", "HandWriting");
 
    /**
     * 上传图片并进行OCR识别
     * @param file 上传的图片文件
     * @param type 识别类型(General-通用, Invoice-发票, IdCard-身份证, HandWriting-手写体)
     * @param provider OCR服务提供商(ali-阿里云, baidu-百度)
     * @return OCR识别结果
     */
    @PostMapping(value = "/recognize", consumes = "multipart/form-data")
    public AjaxResult recognizeImage(@RequestParam("file") MultipartFile file,
                                      @RequestParam(value = "type", defaultValue = "General") String type,
                                      @RequestParam(value = "provider", defaultValue = "ali") String provider,
                                      @RequestParam(value = "itemNames", required = false) String[] itemNames) {
        try {
            if (file.isEmpty()) {
                return error("上传图片不能为空");
            }
 
            // 验证识别类型
            if (!SUPPORTED_TYPES.contains(type)) {
                return error("不支持的识别类型: " + type + ", 支持的类型: " + String.join(",", SUPPORTED_TYPES));
            }
 
            // 智能压缩图片(自动处理超过3MB的图片)
            File tempFile = ImageCompressUtil.compressForOCR(file);
 
            // 根据提供商调用不同的OCR服务
            JSONObject ocrResult;
            if ("baidu".equalsIgnoreCase(provider)) {
                // 百度OCR只支持部分类型
                if ("General".equals(type)) {
                    ocrResult = BaiduOCRUtil.generalRecognize(tempFile);
                } else if ("HandWriting".equals(type)) {
                    ocrResult = BaiduOCRUtil.handwritingRecognize(tempFile);
                } else {
                    ocrResult = BaiduOCRUtil.generalRecognize(tempFile); // 默认使用通用识别
                }
            } else if ("tencent".equalsIgnoreCase(provider)) {
                // 腾讯云OCR只支持部分类型
                if ("General".equals(type)) {
                    ocrResult = TencentOCRUtil.generalRecognize(tempFile);
                } else if ("HandWriting".equals(type)) {
                    ocrResult = TencentOCRUtil.handwritingRecognize(tempFile.getAbsolutePath(), itemNames);
                } else {
                    ocrResult = TencentOCRUtil.generalRecognize(tempFile); // 默认使用通用识别
                }
            } else {
                // 阿里云OCR
                ocrResult = AliOCRUtil.recognizeTextByFile(tempFile, type);
            }
 
            // 删除临时文件
            tempFile.delete();
 
            // 构建返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("ocrResult", ocrResult);
            result.put("fileName", file.getOriginalFilename());
            result.put("originalSize", file.getSize());
            result.put("processedSize", tempFile.length());
            result.put("compressed", file.getSize() > tempFile.length());
            result.put("type", type);
            result.put("provider", provider);
 
            if (ocrResult.getBooleanValue("success")) {
                return success(result);
            } else {
                return error("OCR识别失败: " + ocrResult.getString("error"));
            }
 
        } catch (Exception e) {
            logger.error("OCR识别异常", e);
            return error("OCR识别异常: " + e.getMessage());
        }
    }
 
    /**
     * 通过图片URL进行OCR识别
     * @param imageUrl 图片URL地址
     * @param type 识别类型(General-通用, Invoice-发票, IdCard-身份证, HandWriting-手写体)
     * @param provider OCR服务提供商(ali-阿里云, baidu-百度)
     * @return OCR识别结果
     */
    @GetMapping("/recognizeByUrl")
    public AjaxResult recognizeByUrl(@RequestParam("imageUrl") String imageUrl,
                                      @RequestParam(value = "type", defaultValue = "General") String type,
                                      @RequestParam(value = "provider", defaultValue = "ali") String provider,
                                      @RequestParam(value = "itemNames", required = false) String[] itemNames) {
        try {
            // 验证识别类型
            if (!SUPPORTED_TYPES.contains(type)) {
                return error("不支持的识别类型: " + type + ", 支持的类型: " + String.join(",", SUPPORTED_TYPES));
            }
 
            // 根据提供商调用不同的OCR服务
            JSONObject ocrResult;
            if ("baidu".equalsIgnoreCase(provider)) {
                // 百度OCR只支持部分类型
                if ("General".equals(type)) {
                    ocrResult = BaiduOCRUtil.generalRecognize(imageUrl);
                } else if ("HandWriting".equals(type)) {
                    ocrResult = BaiduOCRUtil.handwritingRecognize(imageUrl);
                } else {
                    ocrResult = BaiduOCRUtil.generalRecognize(imageUrl); // 默认使用通用识别
                }
            } else if ("tencent".equalsIgnoreCase(provider)) {
                // 腾讯云OCR只支持部分类型
                if ("General".equals(type)) {
                    ocrResult = TencentOCRUtil.generalRecognize(imageUrl);
                } else if ("HandWriting".equals(type)) {
                    ocrResult = TencentOCRUtil.handwritingRecognize(imageUrl, itemNames);
                } else {
                    ocrResult = TencentOCRUtil.generalRecognize(imageUrl); // 默认使用通用识别
                }
            } else {
                // 阿里云OCR
                ocrResult = AliOCRUtil.recognizeTextByUrl(imageUrl, type);
            }
 
            // 构建返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("ocrResult", ocrResult);
            result.put("imageUrl", imageUrl);
            result.put("type", type);
            result.put("provider", provider);
 
            if (ocrResult.getBooleanValue("success")) {
                return success(result);
            } else {
                return error("OCR识别失败: " + ocrResult.getString("error"));
            }
 
        } catch (Exception e) {
            logger.error("OCR识别异常", e);
            return error("OCR识别异常: " + e.getMessage());
        }
    }
 
    /**
     * 获取支持的OCR识别类型列表
     * @return 识别类型列表
     */
    @GetMapping("/types")
    public AjaxResult getSupportedTypes() {
        Map<String, Object> result = new HashMap<>();
        result.put("types", SUPPORTED_TYPES);
        
        List<Map<String, String>> typeList = SUPPORTED_TYPES.stream().map(type -> {
            Map<String, String> typeInfo = new HashMap<>();
            typeInfo.put("value", type);
            
            // 根据类型设置显示名称
            switch (type) {
                case "General":
                    typeInfo.put("label", "通用文字识别");
                    break;
                case "Invoice":
                    typeInfo.put("label", "发票识别");
                    break;
                case "IdCard":
                    typeInfo.put("label", "身份证识别");
                    break;
                case "HandWriting":
                    typeInfo.put("label", "手写体识别");
                    break;
                default:
                    typeInfo.put("label", type);
                    break;
            }
            return typeInfo;
        }).collect(Collectors.toList());
        
        result.put("typeList", typeList);
        return success(result);
    }
 
    /**
     * 获取支持的OCR服务提供商列表
     * @return OCR服务提供商列表
     */
    @GetMapping("/providers")
    public AjaxResult getSupportedProviders() {
        Map<String, Object> result = new HashMap<>();
        List<Map<String, String>> providerList = Arrays.asList(
            createProviderInfo("ali", "阿里云OCR", true),
            createProviderInfo("baidu", "百度OCR", true),
            createProviderInfo("tencent", "腾讯云OCR", true)
        );
        result.put("providers", providerList);
        return success(result);
    }
 
    /**
     * 提取OCR结果中的目标字段
     * @param ocrResult OCR原始结果
     * @return 提取的字段信息
     */
    @PostMapping("/extractFields")
    public AjaxResult extractFields(@RequestBody JSONObject ocrResult) {
        try {
            // 检查是否为百度OCR结果
            String provider = ocrResult.getString("provider");
            Map<String, String> extracted;
            if ("baidu".equalsIgnoreCase(provider)) {
                extracted = BaiduOCRUtil.extractTargetFields(ocrResult);
            } else if ("tencent".equalsIgnoreCase(provider)) {
                extracted = TencentOCRUtil.extractTargetFields(ocrResult);
            } else {
                extracted = AliOCRUtil.extractTargetFields(ocrResult);
            }
            return success(extracted);
        } catch (Exception e) {
            logger.error("字段提取异常", e);
            return error("字段提取异常: " + e.getMessage());
        }
    }
 
    /**
     * 腾讯云手写体识别(支持自定义字段提取)
     * @param file 上传的图片文件
     * @param itemNames 需要提取的字段名称数组
     * @return 识别结果 Map,key为字段名,value为识别内容
     */
    @PostMapping(value = "/tencent/handwriting", consumes = "multipart/form-data")
    public AjaxResult tencentHandwritingRecognize(@RequestParam("file") MultipartFile file,
                                                   @RequestParam(value = "itemNames", required = false) String[] itemNames) {
        try {
            if (file.isEmpty()) {
                return error("上传图片不能为空");
            }
 
            // 智能压缩图片(自动处理超过3MB的图片)
            File tempFile = ImageCompressUtil.compressForOCR(file);
 
            // 调用腾讯云手写体识别
            Map<String, String> resultMap = TencentOCRUtil.handwritingRecognizeWith(tempFile.getAbsolutePath(), itemNames);
 
            // 删除临时文件
            tempFile.delete();
 
            // 检查是否有错误
            if (resultMap.containsKey("error")) {
                return error("腾讯云OCR手写体识别失败: " + resultMap.get("error"));
            }
 
            // 构建返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("fileName", file.getOriginalFilename());
            result.put("type", "HandWriting");
            result.put("provider", "tencent");
            result.put("fields", resultMap);
            result.put("fieldCount", resultMap.size());
 
            return success(result);
 
        } catch (Exception e) {
            logger.error("腾讯云OCR手写体识别异常", e);
            return error("腾讯云OCR手写体识别异常: " + e.getMessage());
        }
    }
 
    /**
     * 腾讯云手写体识别通过URL(支持自定义字段提取)
     * @param imageUrl 图片URL地址
     * @param itemNames 需要提取的字段名称数组
     * @return 识别结果 Map,key为字段名,value为识别内容
     */
    @GetMapping("/tencent/handwritingByUrl")
    public AjaxResult tencentHandwritingRecognizeByUrl(@RequestParam("imageUrl") String imageUrl,
                                                        @RequestParam(value = "itemNames", required = false) String[] itemNames) {
        try {
            // 调用腾讯云手写体识别
            Map<String, String> resultMap = TencentOCRUtil.handwritingRecognizeWith(imageUrl, itemNames);
 
            // 检查是否有错误
            if (resultMap.containsKey("error")) {
                return error("腾讯云OCR手写体识别失败: " + resultMap.get("error"));
            }
 
            // 构建返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("imageUrl", imageUrl);
            result.put("type", "HandWriting");
            result.put("provider", "tencent");
            result.put("fields", resultMap);
            result.put("fieldCount", resultMap.size());
 
            return success(result);
 
        } catch (Exception e) {
            logger.error("腾讯云OCR手写体识别异常", e);
            return error("腾讯云OCR手写体识别异常: " + e.getMessage());
        }
    }
 
    /**
     * 腾讯云手写体识别(支持多图片批量识别)
     * @param files 上传的图片文件数组
     * @param itemNames 需要提取的字段名称数组
     * @return 识别结果,合并所有图片的识别字段
     */
    @PostMapping(value = "/tencent/handwriting/batch", consumes = "multipart/form-data")
    public AjaxResult tencentHandwritingRecognizeBatch(@RequestParam("files") MultipartFile[] files,
                                                        @RequestParam(value = "itemNames", required = false) String[] itemNames) {
        try {
            if (files == null || files.length == 0) {
                return error("上传图片不能为空");
            }
 
            // 合并所有图片的识别结果
            Map<String, String> mergedResultMap = new HashMap<>();
            int successCount = 0;
            int failCount = 0;
            StringBuilder errorMessages = new StringBuilder();
 
            for (MultipartFile file : files) {
                if (file.isEmpty()) {
                    continue;
                }
 
                try {
                    // 智能压缩图片(自动处理超过3MB的图片)
                    File tempFile = ImageCompressUtil.compressForOCR(file);
 
                    // 调用腾讯云手写体识别
                    Map<String, String> resultMap = TencentOCRUtil.handwritingRecognizeWith(tempFile.getAbsolutePath(), itemNames);
 
                    // 删除临时文件
                    tempFile.delete();
 
                    // 检查是否有错误
                    if (resultMap.containsKey("error")) {
                        failCount++;
                        errorMessages.append(file.getOriginalFilename()).append(":").append(resultMap.get("error")).append("; ");
                        logger.warn("图片 {} 识别失败: {}", file.getOriginalFilename(), resultMap.get("error"));
                    } else {
                        // 合并识别结果(如果key已存在,不覆盖)
                        for (Map.Entry<String, String> entry : resultMap.entrySet()) {
                            if (!mergedResultMap.containsKey(entry.getKey()) || mergedResultMap.get(entry.getKey()).isEmpty()) {
                                mergedResultMap.put(entry.getKey(), entry.getValue());
                            }
                        }
                        successCount++;
                        logger.info("图片 {} 识别成功,提取 {} 个字段", file.getOriginalFilename(), resultMap.size());
                    }
                } catch (Exception e) {
                    failCount++;
                    errorMessages.append(file.getOriginalFilename()).append(":").append(e.getMessage()).append("; ");
                    logger.error("处理图片 {} 时发生异常", file.getOriginalFilename(), e);
                }
            }
 
            // 构建返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("type", "HandWriting");
            result.put("provider", "tencent");
            result.put("fields", mergedResultMap);
            result.put("fieldCount", mergedResultMap.size());
            result.put("totalImages", files.length);
            result.put("successCount", successCount);
            result.put("failCount", failCount);
            
            if (failCount > 0) {
                result.put("errors", errorMessages.toString());
            }
 
            if (successCount == 0) {
                return error("所有图片识别失败: " + errorMessages.toString());
            }
 
            return success(result);
 
        } catch (Exception e) {
            logger.error("腾讯云OCR手写体批量识别异常", e);
            return error("腾讯云OCR手写体批量识别异常: " + e.getMessage());
        }
    }
 
    /**
     * 创建服务提供商信息
     * @param value 服务提供商标识
     * @param label 服务提供商显示名称
     * @param available 是否可用
     * @return 服务提供商信息
     */
    private Map<String, String> createProviderInfo(String value, String label, boolean available) {
        Map<String, String> providerInfo = new HashMap<>();
        providerInfo.put("value", value);
        providerInfo.put("label", label);
        providerInfo.put("available", String.valueOf(available));
        return providerInfo;
    }
}