convert_MD.py 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. import re
  2. from itertools import chain
  3. from pathlib import Path
  4. import numpy as np
  5. import pandas as pd
  6. import json
  7. from mdutils.mdutils import MdUtils
  8. import requests
  9. from YQ_OCR.config import keyDict
  10. url = 'http://192.168.199.107:18087'
  11. url_path = '/ocr_system/identify'
  12. imgs_path = '/Users/zeke/work/sx/OCR/image_data/样签图片'
  13. # 1. xlsx -> 正确json文件(写入厂家信息)
  14. # 2. 发送图片(带正确json文件)
  15. # 3. 把返回的json 和正确的json 进行对比(有key--用返回结果与正确结果比对,无key--用正确结果与返回结果比对)
  16. # 编辑距离
  17. def Levenshtein_Distance(str1, str2):
  18. matrix = [[i + j for j in range(len(str2) + 1)] for i in range(len(str1) + 1)]
  19. for i in range(1, len(str1) + 1):
  20. for j in range(1, len(str2) + 1):
  21. d = 0 if (str1[i - 1] == str2[j - 1]) else 1
  22. matrix[i][j] = min(matrix[i - 1][j] + 1, matrix[i][j - 1] + 1, matrix[i - 1][j - 1] + d)
  23. return matrix[len(str1)][len(str2)]
  24. # 发送请求 带正确答案参数
  25. def send_request(img_path: Path, img_json: str):
  26. file = {'file': (img_path.name, open(img_path, 'rb'), img_path)}
  27. payload = {'docDataStr': img_json}
  28. r = requests.post(url + url_path, files=file, data=payload)
  29. return r.json()
  30. # 处理返回结果
  31. def _parse_result(r): # sourcery skip: dict-comprehension
  32. if r['status'] == '000':
  33. result = r['result']
  34. res = {}
  35. for field in keyDict:
  36. if field in result:
  37. res[field] = result[field]
  38. res['noKeyList'] = result['noKeyList']
  39. res['logoList'] = result['logoList']
  40. logoFileName = [log['logoFileName'] for log in res['logoList']]
  41. res['logoList'] = logoFileName
  42. return res
  43. elif r['status'] == '101':
  44. return "101"
  45. # 比较两个json文件 并在md文件中写入对比结果
  46. def evaluate_one(xlsx_dict, res_dict):
  47. true_num = 0
  48. for key_yes in res_dict:
  49. if type(res_dict[key_yes]) is str:
  50. if Levenshtein_Distance(res_dict[key_yes], xlsx_dict[key_yes]) == 0:
  51. table_result.extend([key_yes, xlsx_dict[key_yes], res_dict[key_yes], '✅'])
  52. true_num += 1
  53. else:
  54. table_result.extend([key_yes, xlsx_dict[key_yes], res_dict[key_yes], '❌'])
  55. key_no_dict = {}
  56. for key_no_xlsx in xlsx_dict['noKeyList']:
  57. key_no_dict[key_no_xlsx] = []
  58. for key_no_res in res_dict['noKeyList']:
  59. key_no_dict[key_no_xlsx].append((Levenshtein_Distance(key_no_xlsx, key_no_res), key_no_res))
  60. sort_NoKey = sorted(key_no_dict[key_no_xlsx], key=lambda x: x[0])
  61. NoKey_min_distance = sort_NoKey[0][0]
  62. if NoKey_min_distance == 0:
  63. table_result.extend(['无key值', key_no_xlsx, sort_NoKey[0][1], '✅'])
  64. true_num += 1
  65. else:
  66. table_result.extend(['无key值', key_no_xlsx, sort_NoKey[0][1], '❌'])
  67. rate = true_num / (len(table_result) / 4)
  68. all_rate.append(rate)
  69. statistics = f'共{len(table_result) // 4}个字段,正确{true_num}个,错误{len(table_result) // 4 - true_num}个'
  70. return "{:.2f}%".format(rate * 100), statistics
  71. # 打开正确的json文件
  72. def open_true_json(j_path):
  73. with j_path.open('r') as f:
  74. j_dict = json.load(f)
  75. j_json_str = json.dumps(j_dict, ensure_ascii=False)
  76. return j_dict, j_json_str
  77. if __name__ == '__main__':
  78. img_paths = chain(*[Path(imgs_path).rglob(f'*.{ext}') for ext in ['jpg', 'png', 'jpeg', 'PNG', 'JPG', 'JPEG']])
  79. all_rate = []
  80. for img_path in img_paths:
  81. print(img_path)
  82. # json result
  83. true_d, true_json = open_true_json(img_path.with_suffix('.json'))
  84. result = send_request(img_path, true_json)
  85. res_d = _parse_result(result)
  86. # md
  87. md_file_path = img_path.parent / (img_path.with_suffix('.md'))
  88. MD = MdUtils(file_name=str(md_file_path))
  89. table_result = ['key值', '正确答案', 'ocr返回答案', '是否正确']
  90. rate, statistics = evaluate_one(true_d, res_d)
  91. MD.new_header(level=1, title='测试结果')
  92. MD.new_header(level=2, title=f'正确率:{rate}')
  93. MD.new_header(level=3, title=statistics)
  94. print(f'正确率:{rate}')
  95. MD.new_table(columns=4, rows=len(table_result) // 4, text=table_result, text_align='center')
  96. MD.create_md_file()
  97. print('-------------------------------')
  98. all_rate = "{:.2f}%".format(np.mean(all_rate) * 100)
  99. print(f'总体正确率:{all_rate}')