Administrator
2023-03-08 3cfa1332c0807a74b4ac5a2150500841f5299147
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
import json
import logging
import socketserver
from http.server import BaseHTTPRequestHandler
import cv2
 
import ths_industry_util
from ocr import ocr_util
from ocr.ocr_util import OcrUtil
 
 
class OCRServer(BaseHTTPRequestHandler):
    ocr_temp_data = {}
 
    def do_GET(self):
        path = self.path
        self.send_response(200)
        # 发给请求客户端的响应数据
        self.send_header('Content-type', 'application/json')
        self.end_headers()
        self.wfile.write("".encode())
 
    def do_POST(self):
        path = self.path
        params = self.__parse_request()
        params = params["data"]
        result_str = self.__process(params)
        self.__send_response(result_str)
 
    def __process(self, _str):
        return_str = ""
        try:
            data = ""
            try:
                data = json.loads(_str)
            except:
                raise Exception("json解析失败")
            type = data["type"]
            if type == 100:
                data = data["data"]
                matId = data["matId"]
                index = data["index"]
                maxIndex = data["maxIndex"]
                cols = data["width"]
                rows = data["height"]
                key = data["key"]
                datas = data["data"]
                if self.ocr_temp_data.get(matId) is None:
                    self.ocr_temp_data[matId] = []
                self.ocr_temp_data[matId].extend(datas)
                if maxIndex == index:
                    # 数据传输完成
                    datas = self.ocr_temp_data[matId]
                    if rows * cols == len(datas):
                        self.ocr_temp_data.pop(matId)
                        mat = cv2.numpy.zeros((rows, cols, 1), cv2.numpy.uint8)
                        for r in range(0, rows):
                            for c in range(0, cols):
                                mat[r][c] = [datas[r * cols + c]]
                        # cv2.imwrite("D:/test.png", mat)
                        ocr_results = ocr_util.OcrUtil.ocr_with_key(mat, key)
                        if not ocr_results:
                            # 多重识别,防止识别出错
                            ocr_results = ocr_util.OcrUtil.ocr_num(mat, key)
                        # 图像识别
                        return_str = json.dumps({"code": 0, "data": {"datas": ocr_results}})
                    else:
                        return_str = json.dumps({"code": 2, "msg": "数据出错"})
                else:
                    return_str = json.dumps({"code": 1, "msg": "数据尚未上传完"})
            elif type == 101:
                data = data["data"]
                matId = data["matId"]
                index = data["index"]
                maxIndex = data["maxIndex"]
                cols = data["width"]
                rows = data["height"]
                datas = data["data"]
                if self.ocr_temp_data.get(matId) is None:
                    self.ocr_temp_data[matId] = []
                self.ocr_temp_data[matId].extend(datas)
                if maxIndex == index:
                    # 数据传输完成
                    datas = self.ocr_temp_data[matId]
                    if rows * cols == len(datas):
                        self.ocr_temp_data.pop(matId)
                        mat = cv2.numpy.zeros((rows, cols, 1), cv2.numpy.uint8)
                        for r in range(0, rows):
                            for c in range(0, cols):
                                mat[r][c] = [datas[r * cols + c]]
                        # cv2.imwrite("D:/test.png", mat)
                        ocr_results = ocr_util.OcrUtil.ocr_with_key(mat, ".")
                        code_name = ""
                        for res in ocr_results:
                            code_name += res[0]
                        # TODO 根据代码名称获取代码
                        code = ths_industry_util.get_code_by_name(code_name)
                        # 图像识别
                        return_str = json.dumps({"code": 0, "data": {"code": code}})
                    else:
                        return_str = json.dumps({"code": 2, "msg": "数据出错"})
                else:
                    return_str = json.dumps({"code": 1, "msg": "数据尚未上传完"})
        except Exception as e:
            logging.exception(e)
            if str(e).__contains__("json解析失败"):
                logging.error("OCR数据JSON解析解析失败")
                return_str = json.dumps({"code": -1, "msg": str(e)})
        return return_str
 
    def __send_response(self, data):
        # 发给请求客户端的响应数据
        self.send_response(200)
        self.send_header('Content-type', 'application/json')
        self.end_headers()
        self.wfile.write(data.encode())
 
    def __parse_request(self):
        params = {}
        datas = self.rfile.read(int(self.headers['content-length']))
        _str = str(datas, encoding="gbk")
        # print(_str)
        start = 0
        while True:
            start = _str.find("Content-Disposition: form-data;", start + 1)
            if start <= 0:
                break
            name_start = start + len("Content-Disposition: form-data;")
            name_end = _str.find("\r\n\r\n", start)
 
            val_end = _str.find("------", name_end)
            key = _str[name_start:name_end].strip()[6:-1]
            val = _str[name_end:val_end].strip()
            params[key] = val
        return params
 
 
def run(addr, port):
    handler = OCRServer
    httpd = socketserver.TCPServer((addr, port), handler)
    print("HTTP server is at: http://%s:%d/" % (addr, port))
    httpd.serve_forever()