Przeglądaj źródła

refactor anchor

Zhang Li 2 lat temu
rodzic
commit
60b8ec9de5

+ 7 - 1
README.md

@@ -30,5 +30,11 @@ python server.py --port 8080
 ## 单元测试
 
 ```shell
- python -m unittest discover testing '*_test.py' -v
+python -m unittest discover testing '*_test.py' -v
+ 
+# pytest
+cd testing
+python -m pytest test_bank.py -vv
+# test group convex
+python -m pytest test_bank.py -m convex -vv
 ```

+ 125 - 0
core/anchor.py

@@ -0,0 +1,125 @@
+import re
+from dataclasses import dataclass
+from enum import Enum
+from typing import Tuple, List
+
+import cv2
+import numpy as np
+from paddleocr import PaddleOCR
+
+from core.line_parser import LineParser
+
+
+class Direction(Enum):
+    TOP = 0
+    RIGHT = 1
+    BOTTOM = 2
+    LEFT = 3
+
+
+class OcrAnchor(object):
+    # 输入识别anchor的名字, 如身份证号
+    def __init__(self, name: str, d: List[Direction]):
+        self.name = name
+        # anchor位置
+        self.direction = d
+
+        def t_func(anchor, c, is_horizontal):
+            if is_horizontal:
+                return 0 if anchor[1] < c[1] else 2
+            else:
+                return 1 if anchor[0] > c[0] else 3
+
+        def l_func(anchor, c, is_horizontal):
+            if is_horizontal:
+                return 0 if anchor[0] < c[0] else 2
+            else:
+                return 1 if anchor[1] < c[1] else 3
+
+        def b_func(anchor, c, is_horizontal):
+            if is_horizontal:
+                return 0 if anchor[1] > c[1] else 2
+            else:
+                return 1 if anchor[0] < c[0] else 3
+
+        def r_func(anchor, c, is_horizontal):
+            if is_horizontal:
+                return 0 if anchor[0] > c[0] else 2
+            else:
+                return 1 if anchor[1] > c[1] else 3
+
+        self.direction_funcs = {
+            Direction.TOP: t_func,
+            Direction.BOTTOM: b_func,
+            Direction.LEFT: l_func,
+            Direction.RIGHT: r_func,
+        }
+
+    # 获取中心区域坐标 -> (x, y)
+    def get_rec_area(self, res) -> Tuple[float, float]:
+        """获得整张身份证的识别区域, 返回识别区域的中心点"""
+        boxes = []
+        for row in res:
+            for r in row:
+                boxes.extend(r.box)
+        boxes = np.stack(boxes)
+        l, t = np.min(boxes, 0)
+        r, b = np.max(boxes, 0)
+        # 识别区域的box
+        # big_box = [[l, t], [r, t], [r, b], [l, b]]
+        # w, h = (r - l, b - t)
+        return (l + r) / 2, (t + b) / 2
+
+    # 判断是否是 锚点
+    def is_anchor(self, txt, box) -> bool:
+        pass
+
+    # 找 锚点 -> 锚点坐标
+    def find_anchor(self, res) -> Tuple[bool, float, float]:
+        """
+        寻找锚点 中心点坐标
+        """
+        for row in res:
+            for r in row:
+                txt = r.txt.replace('-', '').replace(' ', '')
+                box = r.box
+                if self.is_anchor(txt, box):
+                    l, t = np.min(box, 0)
+                    r, b = np.max(box, 0)
+                    return True, (l + r) / 2, (t + b) / 2
+        return False, 0., 0.
+
+    # 定位 锚点 -> 角度
+    # -> 锚点(x, y)  pic(x, y) is_horizontal
+    def locate_anchor(self, res, is_horizontal) -> int:
+        found, id_cx, id_cy = self.find_anchor(res)
+
+        # 如果识别不到身份证号
+        if not found: raise Exception(f'识别不到anchor{self.name}')
+        cx, cy = self.get_rec_area(res)
+        # print(f'id_cx: {id_cx}, id_cy: {id_cy}')
+        # print(f'cx: {cx}, cy: {cy}')
+        pre = None
+        for d in self.direction:
+            f = self.direction_funcs.get(d, None)
+            angle = f((id_cx, id_cy), (cx, cy), is_horizontal)
+            if pre is None:
+                pre = angle
+            else:
+                if angle != pre:
+                    raise Exception('angle is not compatiable')
+        return pre
+
+
+class BankCardAnchor(OcrAnchor):
+    def __init__(self, name: str, d: List[Direction]):
+        super(BankCardAnchor, self).__init__(name, d)
+
+    def is_anchor(self, txt, box) -> bool:
+        txts = re.findall('\d{10,20}', txt)
+        if len(txts) > 0:
+            return True
+        return False
+
+    def locate_anchor(self, res, is_horizontal) -> int:
+        return super(BankCardAnchor, self).locate_anchor(res, is_horizontal)

+ 37 - 159
core/direction.py

@@ -1,163 +1,41 @@
-import math
+from core.anchor import *
+from dataclasses import dataclass
+from paddleocr import PaddleOCR
 
-import cv2
 import numpy as np
-from pathlib import Path
 
-BASE_DIR = Path(__file__).parent.parent
-logo_path = str(BASE_DIR/'logo.png')
-print(f'logo_path: {logo_path}')
-template_img = cv2.imread(logo_path)
-template_img = cv2.cvtColor(template_img, cv2.COLOR_BGR2RGB)
-
-
-def format_img(img, max_height=480):
-    max_width = img.shape[1] * max_height // img.shape[0]
-    return cv2.resize(img, (max_width, max_height))
-
-
-def search_best(des1, copy_target, sift):
-    (kp2, des2) = sift.detectAndCompute(copy_target, None)
-    bf = cv2.BFMatcher()
-    matches1 = bf.knnMatch(des1, des2, k=2)
-    ratio1 = 0.5
-    good1 = []
-    for m1, n1 in matches1:
-        # 如果最接近和次接近的比值大于一个既定的值,那么我们保留这个最接近的值,认为它和其匹配的点为good_match
-        if m1.distance < ratio1 * n1.distance:
-            good1.append(m1)
-    goodx = [(m1, m1.distance / n1.distance, m1.distance, n1.distance) for m1, n1 in matches1]
-    goodx = sorted(goodx, key=lambda x: x[1])
-    for gx, _, _, _ in goodx:
-        if len(good1) >= 20: break
-        if gx not in good1:
-            good1.append(gx)
-    return [[p] for p in good1], kp2
-
-
-def transform2stardard(ori_logo, ori_target):
-    sift = cv2.xfeatures2d.SIFT_create()
-    copy_logo = ori_logo.copy()
-    (kp1, des1) = sift.detectAndCompute(copy_logo, None)
-    match_pairs = []
-    angle_rotate = {-1: 0, cv2.ROTATE_90_CLOCKWISE: 90}  # ,cv2.ROTATE_180:180}
-    for rotate in angle_rotate.keys():
-        copy_target = cv2.rotate(ori_target, rotate) if rotate != -1 else ori_target.copy()
-        goodx, kpx = search_best(des1, copy_target, sift)
-        match_pairs.append((goodx, rotate, kpx))
-        if len(goodx) >= 20:
-            break
-
-    max_match = max(match_pairs, key=lambda y: len(y[0]))
-    good1 = max_match[0]
-    kp2 = max_match[2]
-
-    copy_target = cv2.rotate(ori_target, max_match[1]) if max_match[1] != -1 else ori_target.copy()
-    if len(good1) > 4:
-        ptsA = np.float32([kp1[m[0].queryIdx].pt for m in good1]).reshape(-1, 1, 2)
-        ptsB = np.float32([kp2[m[0].trainIdx].pt for m in good1]).reshape(-1, 1, 2)
-        ransacReprojThreshold = min(max(4, int(len(good1))), 20)
-        # RANSAC算法选择其中最优的四个点
-        H, status = cv2.findHomography(ptsA, ptsB, cv2.RANSAC, ransacReprojThreshold)
-        imgout = cv2.warpPerspective(copy_target, H, (copy_logo.shape[1], copy_logo.shape[0]),
-                                     flags=cv2.INTER_LINEAR + cv2.WARP_INVERSE_MAP)
-        angle = math.atan2(H[1, 0], H[0, 0]) * 180 / math.pi - angle_rotate[max_match[1]]
-        print(f'------------angle: {angle}')
-        return imgout, angle
-        # return np.hstack((format_img(ori_target.copy()),
-        #                   cv2.putText(img=format_img(imgout.copy()), text='{}=>{}'.format(int(angle), tag),
-        #                               org=(20, 70), fontFace=cv2.FONT_HERSHEY_TRIPLEX, fontScale=3, color=(0, 0, 255),
-        #                               thickness=3)))
-    else:
-        return None, None
-
-
-def detect_angle(img):
-    img_copy = np.copy(img)
-    imgout, angle = transform2stardard(template_img, img)
-    if imgout is not None:
-        angle = np.argmin(np.abs(np.array([0, 90, 180, -180, -90]) - angle))
-        if angle == 2 or angle == 3:
-            angle = 2
-        if angle == 4:
-            angle = 3
-        # return format_img(imgout), int(angle)
-        return img_copy, int(angle)
-    else:
-        raise Exception('无法识别方向, 请把银行卡摆放正确')
-
-
-# @dataclass
-# class AngleDetector(object):
-#     ocr: PaddleOCR
-#
-#     def detect_angle(self, img, result) -> int:
-#         wc = 0
-#         hc = 0
-#         count_0 = 0
-#         count_180 = 0
-#         angle = 0
-#         print(result)
-#         for res in result:
-#             txt = res[1][0]
-#             if '银行' not in txt: continue
-#             a = np.array(res[0])
-#             l, t = np.min(a, axis=0).tolist()
-#             r, b = np.max(a, axis=0).tolist()
-#             l, t, r, b = list(map(int, [l, t, r, b]))
-#             if b - t > r - l:
-#                 hc += 1
-#             else:
-#                 wc += 1
-#             imgb = img[t:b, l:r, :]
-#             r = self.ocr.ocr(imgb, det=False, rec=False, cls=True)
-#             print(f'ocr angle: {r}')
-#             if int(r[0][0]) == 180:
-#                 count_180 += 1
-#             else:
-#                 count_0 += 1
-#         if hc >= wc:
-#             if count_0 >= count_180:
-#                 angle = 90
-#             else:
-#                 angle = 270
-#         else:
-#             if count_0 > count_180:
-#                 angle = 0
-#             else:
-#                 angle = 180
-#
-#         return angle
-
-def detect_angle2(image):
-    mask = np.zeros(image.shape, dtype=np.uint8)
-    gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
-    blur = cv2.GaussianBlur(gray, (3, 3), 0)
-    adaptive = cv2.adaptiveThreshold(blur, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 15, 4)
-
-    cnts = cv2.findContours(adaptive, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
-    cnts = cnts[0] if len(cnts) == 2 else cnts[1]
-
-    for c in cnts:
-        area = cv2.contourArea(c)
-        if area < 45000 and area > 20:
-            cv2.drawContours(mask, [c], -1, (255, 255, 255), -1)
-
-    mask = cv2.cvtColor(mask, cv2.COLOR_BGR2GRAY)
-    h, w = mask.shape
-
-    # Horizontal
-    if w > h:
-        left = mask[0:h, 0:0 + w // 2]
-        right = mask[0:h, w // 2:]
-        left_pixels = cv2.countNonZero(left)
-        right_pixels = cv2.countNonZero(right)
-        return 0 if left_pixels >= right_pixels else 180
-    # Vertical
-    else:
-        top = mask[0:h // 2, 0:w]
-        bottom = mask[h // 2:, 0:w]
-        top_pixels = cv2.countNonZero(top)
-        bottom_pixels = cv2.countNonZero(bottom)
-        return 90 if bottom_pixels >= top_pixels else 270
 
+def detect_angle(result, ocr_anchor: OcrAnchor):
+    lp = LineParser(result)
+    res = lp.parse()
+    print('------ angle ocr -------')
+    print(res)
+    print('------ angle ocr -------')
+    is_horizontal = lp.is_horizontal
+    return ocr_anchor.locate_anchor(res, is_horizontal)
+
+
+@dataclass
+class AngleDetector(object):
+    """
+    角度检测器
+    """
+    ocr: PaddleOCR
+
+    def detect_angle(self, img):
+        ocr_anchor = BankCardAnchor('银行卡号', [Direction.BOTTOM])
+
+        result = self.ocr.ocr(img, cls=True)
+
+        try:
+            angle = detect_angle(result, ocr_anchor)
+            return angle, result
+
+        except Exception as e:
+            print(e)
+            # 如果第一次识别不到,旋转90度再识别
+            img = cv2.rotate(img, cv2.ROTATE_90_CLOCKWISE)
+            result = self.ocr.ocr(img, cls=True)
+            angle = detect_angle(result, ocr_anchor)
+            # 旋转90度之后要重新计算角度
+            return (angle - 1 + 4) % 4, result

+ 21 - 21
core/ocr.py

@@ -1,36 +1,38 @@
 from dataclasses import dataclass
 
-from core.line_parser import LineParser
-from core.parser import *
-from core.direction import *
 import numpy as np
 from paddleocr import PaddleOCR
 
+from core.direction import *
+from core.line_parser import LineParser
+from core.parser import *
+
 
 @dataclass
 class BankOcr:
     ocr: PaddleOCR
-    # angle_detector: AngleDetector
+    angle_detector: AngleDetector
 
     def predict(self, image: np.ndarray):
-        image, angle = self._pre_process(image)
-        _, _, result = self._ocr(image)
-        # angle = self.angle_detector.detect_angle(image, result)
+        image, angle, result = self._pre_process(image)
+        print(f'---------- detect angle: {angle} 角度 --------')
+        if angle != 0:
+            # 角度不为0需要重新识别,字面
+            _, _, result = self._ocr(image)
         return self._post_process(result, angle)
 
     def _pre_process(self, image: np.ndarray):
-        img, angle = detect_angle(image)
-        print(f'angle: {angle}')
-        if angle == 0:
-            pass
-        elif angle == 1:
-            img = cv2.rotate(img, cv2.ROTATE_90_COUNTERCLOCKWISE)
-        elif angle == 2:
-            img = cv2.rotate(img, cv2.ROTATE_180)
-        else:
-            img = cv2.rotate(img, cv2.ROTATE_90_CLOCKWISE)
-
-        return img, angle
+        angle, result = self.angle_detector.detect_angle(image)
+
+        if angle == 1:
+            image = cv2.rotate(image, cv2.ROTATE_90_COUNTERCLOCKWISE)
+        print(angle)  # 逆时针
+        if angle == 2:
+            image = cv2.rotate(image, cv2.ROTATE_180)
+        if angle == 3:
+            image = cv2.rotate(image, cv2.ROTATE_90_CLOCKWISE)
+
+        return image, angle, result
 
     def _ocr(self, image):
         # 获取模型检测结果
@@ -45,7 +47,6 @@ class BankOcr:
         txts = [line[1][0] for line in result]
         return txts, confs, result
 
-
     def _post_process(self, raw_result, angle: int):
 
         # 把测试图片 喂给 OCR 返回给 self.raw_results
@@ -60,4 +61,3 @@ class BankOcr:
             "orientation": angle,
             "number": content["number"].to_dict(),
         }
-

+ 7 - 7
docker-compose.yml

@@ -10,12 +10,12 @@ services:
     tty: true
     working_dir: /workspace
     ports:
-      - '18080:8080'
-      - '18222:22'
+      - '18081:8080'
+      - '18223:22'
     volumes:
       - ./:/workspace
-#    deploy:
-#      resources:
-#        reservations:
-#          devices:
-#            - capabilities: [gpu]
+    deploy:
+      resources:
+        reservations:
+          devices:
+            - capabilities: [gpu]

+ 3 - 0
environment.yml

@@ -15,6 +15,8 @@ dependencies:
       - paddlehub
       - fastapi
       - uvicorn
+      - zhon
+      - pytest
       - jinja2
       - aiofiles
       - python-multipart
@@ -25,3 +27,4 @@ dependencies:
       - paddlepaddle  # gpu==2.3.0.post110
       - -f https://www.paddlepaddle.org.cn/whl/linux/mkl/avx/stable.html
 prefix: /opt/conda/envs/py38
+

+ 4 - 3
server.py

@@ -6,8 +6,8 @@ from fastapi.middleware.cors import CORSMiddleware
 from paddleocr import PaddleOCR
 from pydantic import BaseModel
 
-from core.direction import detect_angle
 from core.ocr import BankOcr
+from core.direction import AngleDetector
 from sx_utils.sximage import *
 from sx_utils.sxtime import sxtimeit
 from sx_utils.sxweb import web_try
@@ -64,7 +64,8 @@ ocr = PaddleOCR(use_angle_cls=True,
 #                 warmup=True)
 
 
-m = BankOcr(ocr)
+ad = AngleDetector(ocr)
+m = BankOcr(ocr, ad)
 
 
 @app.get("/ping")
@@ -104,7 +105,7 @@ def detect(request: Request, id_card: IdCardInfo):
 @web_try()
 def detect(request: Request, id_card: IdCardInfo):
     image = base64_to_np(id_card.image)
-    _, angle = detect_angle(image)
+    angle, _ = ad.detect_angle(image)
     res = {'orientation': angle, 'fn': id_card.fn}
     print(res)
     return res

+ 3 - 1
sx_utils/sximage.py

@@ -5,5 +5,7 @@ import cv2
 def base64_to_np(img_data):
     color_image_flag = 1
     img_data = img_data.split(',',1)[-1]
-    return cv2.imdecode(np.fromstring(b64decode(img_data), dtype=np.uint8), color_image_flag)
+    img = cv2.imdecode(np.fromstring(b64decode(img_data), dtype=np.uint8), color_image_flag)
+    # img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
+    return img
 

+ 1 - 12
testing/101_error_test.py

@@ -4,18 +4,7 @@ from pathlib import Path
 
 import requests
 
-url = 'http://192.168.199.208:18080'
-# url = 'http://aihub-test.digitalyili.com/aiSquare/openApi/reasoning-services/rlocrxm'
-#
-# header = {
-#     'Authorization': 'Bearer 9679c2b3-b90b-4029-a3c7-f347b4d242f7'
-# }
-def send_request(image_path):
-    with open(image_path, 'rb') as f:
-        img_str: str = base64.encodebytes(f.read()).decode('utf-8')
-        r = requests.post(f'{url}/ocr_system/bankcard', json={'image': img_str})
-        print(r.json())
-        return r.json()
+from testing.utils import *
 
 
 class TestBank101(unittest.TestCase):

+ 1 - 14
testing/all_test.py

@@ -3,20 +3,7 @@ import unittest
 from pathlib import Path
 
 import requests
-
-url = 'http://192.168.199.107:28080'
-
-
-# url = 'http://aihub-test.digitalyili.com/aiSquare/openApi/reasoning-services/rlocrxm'
-# header = {
-#     'Authorization': 'Bearer 9679c2b3-b90b-4029-a3c7-f347b4d242f7'
-# }
-def send_request(image_path):
-    with open(image_path, 'rb') as f:
-        img_str: str = base64.encodebytes(f.read()).decode('utf-8')
-        r = requests.post(f'{url}/ocr_system/bankcard', json={'image': img_str})
-        print(r.json())
-        return r.json()
+from testing.utils import send_request
 
 
 class TestBankCardConvex(unittest.TestCase):

+ 1 - 15
testing/number_test.py

@@ -3,21 +3,7 @@ import unittest
 from pathlib import Path
 
 import requests
-
-url = 'http://192.168.199.249:18080'
-
-
-# url = 'http://aihub-test.digitalyili.com/aiSquare/openApi/reasoning-services/rlocrxm'
-# header = {
-#     'Authorization': 'Bearer 9679c2b3-b90b-4029-a3c7-f347b4d242f7'
-# }
-def send_request(image_path):
-    with open(image_path, 'rb') as f:
-        img_str: str = base64.encodebytes(f.read()).decode('utf-8')
-        r = requests.post(f'{url}/ocr_system/bankcard', json={'image': img_str})
-        # r = requests.post(f'{url}/yhksb/bankcard', json={'image': img_str})
-        print(r.json())
-        return r.json()
+from testing.utils import *
 
 
 class TestBankCardOcr(unittest.TestCase):

+ 1 - 17
testing/orientation_test.py

@@ -1,21 +1,5 @@
-import base64
 import unittest
-
-import requests
-
-url = 'http://192.168.199.249:18080'
-
-
-# url = 'http://aihub-test.digitalyili.com/aiSquare/openApi/reasoning-services/rlocrxm'
-# header = {
-#     'Authorization': 'Bearer 9679c2b3-b90b-4029-a3c7-f347b4d242f7'
-# }
-def send_request(image_path):
-    with open(image_path, 'rb') as f:
-        img_str: str = base64.encodebytes(f.read()).decode('utf-8')
-        r = requests.post(f'{url}/ocr_system/orientation', json={'image': img_str, 'fn': image_path})
-        print(r.json())
-        return r.json()
+from testing.utils import *
 
 
 class TestBankCardOcr(unittest.TestCase):

+ 4 - 0
testing/pytest.ini

@@ -0,0 +1,4 @@
+[pytest]
+makers =
+    convex: group1.
+    print: group2.

+ 77 - 0
testing/test_bank.py

@@ -0,0 +1,77 @@
+from pathlib import Path
+
+import pytest
+
+from testing.utils import send_request
+
+
+def helper(image_path, sta, orient, card_no):
+    root = Path(__file__).parent
+    image_path = str(root / image_path)
+    r = send_request(image_path)
+    assert sta, r['status']
+    assert orient, r['result']['orientation']
+    assert card_no, r['result']['number']['text']
+
+
+def get_from_request(image_path):
+    root = Path(__file__).parent
+    image_path = str(root / image_path)
+    r = send_request(image_path)
+    if r['status'] == '000':
+        return r['status'], r['result']['orientation'], r['result']['number']['text']
+    return '101', 0, ''
+
+
+@pytest.mark.convex
+@pytest.mark.parametrize(
+    "p, status, t, no",
+    [
+        ('../images/all/convex/back_mess.jpg', '000', 0, '6222521510000593'),
+        ('../images/all/convex/convex_0.jpg', '000', 0, '6258091767775765'),
+        ('../images/all/convex/back_mess.jpg', '000', 0, '6222521510000593'),
+        ('../images/all/convex/convex_0.jpg', '000', 0, '6258091767775765'),
+        ('../images/all/convex/convex_0.jpg', '000', 1, '6217991910056756013'),
+        ('../images/all/convex/convex_180.jpg', '000', 2, '6214835715794218'),
+        ('../images/all/convex/convex_270.jpg', '000', 3, '6222081211001840619'),
+        ('../images/all/convex/mohu1.jpg', '000', 0, '6212261602020022770'),
+        ('../images/all/convex/mohu2.jpg', '000', 1, '6215581504002751986'),
+        ('../images/all/convex/small.jpg', '000', 0, '6217981910002853676'),
+        ('../images/all/convex/tilt1.jpg', '000', 3, '6215590613003222324'),
+        ('../images/all/convex/tilt2.jpg', '000', 0, '623061571509189093'),
+
+    ]
+)
+def test_convex(p, status, t, no):
+    assert get_from_request(p) == (status, t, no)
+
+
+def test_01():
+    image_path = '../images/all/convex/back_mess.jpg'
+    assert get_from_request(image_path) == ('000', 0, '6222521510000593')
+
+
+def test_02():
+    image_path = '../images/all/convex/convex_0.jpg'
+    assert get_from_request(image_path) == ('000', 0, '6258091767775765')
+
+
+@pytest.mark.print
+@pytest.mark.parametrize(
+    "p, status, t, no",
+    [
+        ('../images/all/print/front_0.jpg', '000', 0, '6216638405000213022'),
+        ('../images/all/print/front_90.jpg', '000', 1, '6216618401001365345'),
+        ('../images/all/print/front_180.png', '000', 2, '6230522590019175070'),
+        ('../images/all/print/front_270.png', '000', 3, '6228480329658828572'),
+        ('../images/all/print/long.jpg', '000', 0, '6217991910038919747'),
+        ('../images/all/print/mohu1.jpg', '000', 1, '6217000416004100998'),
+        ('../images/all/print/mohu2.jpg', '000', 0, '6217000870003035904'),
+        ('../images/all/print/small1.jpg', '000', 0, '6222020602005624997'),
+        ('../images/all/print/small2.png', '000', 0, '6222020602015798211'),
+        ('../images/all/print/special.jpg', '000', 0, '6259760610567202'),
+        ('../images/all/print/small2.png', '000', 0, '6222020602015798211'),
+    ]
+)
+def test_print(p, status, t, no):
+    assert get_from_request(p) == (status, t, no)

+ 1 - 13
testing/true_test.py

@@ -4,19 +4,7 @@ from pathlib import Path
 
 import requests
 
-url = 'http://192.168.199.249:18080'
-
-
-# url = 'http://aihub-test.digitalyili.com/aiSquare/openApi/reasoning-services/rlocrxm'
-# header = {
-#     'Authorization': 'Bearer 9679c2b3-b90b-4029-a3c7-f347b4d242f7'
-# }
-def send_request(image_path):
-    with open(image_path, 'rb') as f:
-        img_str: str = base64.encodebytes(f.read()).decode('utf-8')
-        r = requests.post(f'{url}/ocr_system/bankcard', json={'image': img_str})
-        print(r.json())
-        return r.json()
+from testing.utils import send_request
 
 
 class TestBankCardOcr(unittest.TestCase):

+ 18 - 0
testing/utils.py

@@ -0,0 +1,18 @@
+import base64
+
+import requests
+
+
+url = 'http://192.168.13.54:18081'
+
+
+# url = 'http://aihub-test.digitalyili.com/aiSquare/openApi/reasoning-services/rlocrxm'
+# header = {
+#     'Authorization': 'Bearer 9679c2b3-b90b-4029-a3c7-f347b4d242f7'
+# }
+def send_request(image_path):
+    with open(image_path, 'rb') as f:
+        img_str: str = base64.encodebytes(f.read()).decode('utf-8')
+        r = requests.post(f'{url}/ocr_system/bankcard', json={'image': img_str})
+        print(r.json())
+        return r.json()