From ae8d76a456b64c1c6c4ebf11b6ec33b7df217b1a Mon Sep 17 00:00:00 2001
From: Administrator <admin@example.com>
Date: 星期一, 18 八月 2025 13:43:46 +0800
Subject: [PATCH] bug修复

---
 ocr/ocr_server.py |  177 +++++++++++++++++++++++++++++++++++++++++-----------------
 1 files changed, 125 insertions(+), 52 deletions(-)

diff --git a/ocr/ocr_server.py b/ocr/ocr_server.py
index 4c7af8e..de90e47 100644
--- a/ocr/ocr_server.py
+++ b/ocr/ocr_server.py
@@ -1,64 +1,49 @@
+import base64
 import json
 import logging
 import socketserver
-import socket
+from http.server import BaseHTTPRequestHandler
+import numpy
 
-import cv2
-
+import constant
+from log_module.log import logger_system
+from utils import ths_industry_util
 from ocr import ocr_util
+from third_data import kpl_util
+from trade import bidding_money_manager
 
 
-class MyTCPServer(socketserver.TCPServer):
-    def __init__(self, server_address, RequestHandlerClass, bind_and_activate=True, pipe_juejin=None, pipe_ui=None):
-        self.pipe_juejin = pipe_juejin  # 澧炲姞鐨勫弬鏁�
-        self.pipe_ui = pipe_ui
-        socketserver.TCPServer.__init__(self, server_address, RequestHandlerClass, bind_and_activate=bind_and_activate)
-
-
-# 濡傛灉浣跨敤寮傛鐨勫舰寮忓垯闇�瑕佸啀閲嶅啓ThreadingTCPServer
-class MyThreadingTCPServer(socketserver.ThreadingMixIn, MyTCPServer): pass
-
-
-class MyBaseRequestHandle(socketserver.BaseRequestHandler):
+class OCRServer(BaseHTTPRequestHandler):
     ocr_temp_data = {}
 
-    def setup(self):
-        super().setup()
+    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 handle(self):
-        host = self.client_address[0]
-        super().handle()  # 鍙互涓嶈皟鐢ㄧ埗绫荤殑handler(),鏂规硶锛岀埗绫荤殑handler鏂规硶浠�涔堥兘娌″仛
-        # print("-------handler鏂规硶琚墽琛�----")
-        # print(self.server)
-        # print(self.request)  # 鏈嶅姟
-        # print("瀹㈡埛绔湴鍧�锛�", self.client_address)  # 瀹㈡埛绔湴鍧�
-        # print(self.__dict__)
-        # print("- " * 30)
-        # print(self.server.__dict__)
-        # print("- " * 30)
-        sk: socket.socket = self.request
-        # 璁剧疆闈為樆濉�
-        sk.setblocking(False)
-        data = bytes()
-        while True:
-            try:
-                temp_data = sk.recv(1024)
-                if not temp_data:
-                    break
-                data += temp_data
-            except Exception as e:
-                break
-        _str = str(data, encoding="gbk")
-        # print("OCR SERVER 鍐呭锛�", _str[0:20], "......", _str[-150:-1])
-        return_str = "OK"
+    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:
+                if type(_str) == str:
+                    data = json.loads(_str)
+                else:
+                    data = _str
+            except Exception as e1:
                 raise Exception("json瑙f瀽澶辫触")
-            type = data["type"]
-            if type == 100:
+            _type = data["type"]
+            if _type == 100:
                 data = data["data"]
                 matId = data["matId"]
                 index = data["index"]
@@ -75,23 +60,111 @@
                     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)
+                        mat = numpy.zeros((rows, cols, 1), 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)
+                        # cv2.imwrite(f"{constant.get_path_prefix()}/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 = numpy.zeros((rows, cols, 1), numpy.uint8)
+                        for r in range(0, rows):
+                            for c in range(0, cols):
+                                mat[r][c] = [datas[r * cols + c]]
+                        # cv2.imwrite(f"{constant.get_path_prefix()}/test.png", mat)
+                        ocr_results = ocr_util.OcrUtil.ocr_with_key(mat, ".")
+                        code_name = ""
+                        for res in ocr_results:
+                            code_name += res[0]
+                        # 鏍规嵁浠g爜鍚嶇О鑾峰彇浠g爜
+                        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": "鏁版嵁灏氭湭涓婁紶瀹�"})
+            elif _type == 201:
+                imgdata = base64.b64decode(data["img"])
+                results = ocr_util.OcrUtil.easy_ocr(imgdata)
+                # print(results)
+                kpl_datas = kpl_util.parse_kpl_datas(results)
+                if kpl_datas:
+                    bidding_money_manager.set_bidding_money(kpl_datas)
+                with open(f"{constant.get_path_prefix()}/kpl.png", mode="wb") as f:
+                    f.write(imgdata)
         except Exception as e:
+            logging.exception(e)
             if str(e).__contains__("json瑙f瀽澶辫触"):
                 logging.error("OCR鏁版嵁JSON瑙f瀽瑙f瀽澶辫触")
                 return_str = json.dumps({"code": -1, "msg": str(e)})
-        sk.send(return_str.encode())
+        return return_str
 
-    def finish(self):
-        super().finish()
+    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)
+        if _str.find("Content-Disposition: form-data;") > -1:
+            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
+        else:
+            params = json.loads(_str)
+        return params
+
+
+def run(addr, port):
+    handler = OCRServer
+    try:
+        httpd = socketserver.TCPServer((addr, port), handler)
+        # print("HTTP server is at: http://%s:%d/" % (addr, port))
+        httpd.serve_forever()
+    except Exception as e:
+        logger_system.exception(e)
+        logger_system.error(f"绔彛鏈嶅姟鍣細{port} 鍚姩澶辫触")
+
+
+if __name__ == "__main__":
+    str_={"id":"123"}
+    # print(type(str_)==str)
\ No newline at end of file

--
Gitblit v1.8.0