import os
from paddleocr import PaddleOCR
from core.back import IdCardStraight
from core.direction  import *
import json

# 初始化ocr模型和后处理模型
ocr = PaddleOCR(use_angle_cls=True, rec_model_dir="./idcard_rec_infer/",
                det_model_dir="./idcard_det_infer/", cls_model_dir="idcard_cls_infer",
                rec_algorithm='CRNN',
                ocr_version='PP-OCRv2',
                rec_char_dict_path="./ppocr_keys_v1.txt", lang="ch", use_gpu=False)

# 定义文件路径
img_path = "back.jpeg"
image=cv2.imread(img_path)
angle = detect_angle(image)
print("------------------")
print(angle)
print("------------------")

# 获取模型检测结果
result = ocr.ocr(img_path, cls=True)
scores = [line[1][1] for line in result]
sc=[]
for i in range(2,4):
    sc.append(scores[i])
#scores = [line[1][1] for line in result]
print("------------------")
scores2=sum(scores)/len(scores)
print(sc)
print(scores2)
print("------------------")
# 将检测到的文字放到一个列表中
txts = [line[1][0] for line in result]
#print("......................................")
#print(txts)
#print("......................................")
# 将结果送入到后处理模型中
postprocessing = IdCardStraight(txts)
id_result = postprocessing.run()
result=id_result.encode('utf-8').decode('unicode_escape')
result = json.loads(result)

data={}
data["confidence"]="null"
data["orientation"]="null"
data["expiry_data"]={"text":"null","confidence":"null"}
data["isauthor"]={"text":"null","confidence":"null"}
data["confidence"]=scores2
data["orientation"]=angle
data["expiry_data"]={"text":result["Data"]["FrontResult"]["data"],"confidence":sc[0]}
data["isauthor"]={"text":result["Data"]["FrontResult"]["isauthor"],"confidence":sc[1]}
print(data)
