CardScorer.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. import json
  2. from typing import List, Dict, Any, Union
  3. from app.core.logger import get_logger
  4. logger = get_logger(__name__)
  5. class CardScorer:
  6. """
  7. 它从一个JSON配置文件加载评分规则,并根据输入的卡片数据计算分数。
  8. """
  9. def __init__(self, config_path: str):
  10. try:
  11. with open(config_path, 'r', encoding='utf-8') as f:
  12. self.config = json.load(f)
  13. self.base_score = self.config.get("base_score", 10.0)
  14. except FileNotFoundError:
  15. raise ValueError(f"配置文件未找到: {config_path}")
  16. except json.JSONDecodeError:
  17. raise ValueError(f"配置文件格式错误: {config_path}")
  18. def _get_score_from_tiers(self, value: float, rules: List[List[Any]]) -> float:
  19. """
  20. 一个通用的辅助函数,根据分层规则查找值对应的分数。
  21. """
  22. for tier in rules:
  23. threshold, score = tier
  24. if threshold == "inf" or value < threshold:
  25. return float(score)
  26. return 0.0 # 如果没有匹配的规则,不扣分
  27. def calculate_defect_score(self,
  28. card_defect_type: str,
  29. card_aspect: str,
  30. defect_data: Dict,
  31. is_write_score: bool = True) -> Union[float, dict]:
  32. """
  33. 一个通用的缺陷计分函数,用于计算角、边、表面的加权分数。
  34. card_defect_type: 'corner', 'edge', 'face'
  35. card_aspect: 为 front或 back
  36. is_write_score: 是否将分数写入json并返回
  37. """
  38. if card_defect_type != "corner" and card_defect_type != "edge" and card_defect_type != "face":
  39. raise TypeError("calculate_centering_score:card_type 只能为 'corner', 'edge', 'face'")
  40. if card_aspect != "front" and card_aspect != "back":
  41. raise TypeError("calculate_defect_score:card_type 只能为 front 或 back")
  42. aspect_config = self.config[card_defect_type]
  43. total_deduction = 0.0
  44. weighted_scores = {}
  45. # 1. 计算每种缺陷类型的总扣分
  46. for defect in defect_data['defects']:
  47. if defect['defect_type'] != card_defect_type:
  48. continue
  49. if card_defect_type == 'corner' or card_defect_type == 'edge':
  50. if defect['label'] in ['wear', 'wear_and_impact', 'wear_and_stain']:
  51. defect_type = "wear_area"
  52. elif defect['label'] in ['impact', 'damaged']:
  53. defect_type = "loss_area"
  54. else:
  55. logger.error(f"数据缺陷类型不存在: {defect['label']}")
  56. raise TypeError(f"数据缺陷类型不存在: {defect['label']}")
  57. else:
  58. if defect['label'] in ['wear', 'wear_and_impact', 'damaged']:
  59. defect_type = "wear_area"
  60. elif defect['label'] in ['scratch', 'scuff']:
  61. defect_type = "scratch_length"
  62. elif defect['label'] in ['pit', 'impact']:
  63. defect_type = "pit_area"
  64. elif defect['label'] in ['stain']:
  65. defect_type = "stain_area"
  66. else:
  67. logger.error(f"数据缺陷类型不存在: {defect['label']}")
  68. raise TypeError(f"数据缺陷类型不存在: {defect['label']}")
  69. rules = aspect_config['rules'][defect_type]
  70. # 对于划痕取长度, 其他取面积
  71. if defect_type == "scratch_length":
  72. area_mm = max(defect['width'], defect['height'])
  73. else:
  74. area_mm = defect['actual_area']
  75. # 累加所有同类型缺陷的扣分
  76. if defect_type not in weighted_scores.keys():
  77. weighted_scores[defect_type] = 0
  78. # 计算单个缺陷扣分
  79. the_score = self._get_score_from_tiers(area_mm, rules)
  80. print(f"[{card_defect_type}, {defect_type}]: {area_mm}, {the_score}")
  81. weighted_scores[defect_type] += the_score
  82. # 将分数写入json
  83. if is_write_score:
  84. if "score" not in defect:
  85. # 新建的时候
  86. logger.info(f"新建分数score: {the_score}")
  87. defect['score'] = the_score
  88. defect["new_score"] = None
  89. elif defect.get("new_score") is None:
  90. # 初次修改
  91. if defect["score"] != the_score:
  92. logger.info(f"初次修改 -> new_score: {the_score} (原score: {defect['score']})")
  93. defect["new_score"] = the_score
  94. elif "score" in defect and defect["new_score"] is not None:
  95. # 多次修改
  96. if defect["new_score"] != the_score:
  97. defect["score"] = defect["new_score"]
  98. defect["new_score"] = the_score
  99. else:
  100. defect['score'] = the_score
  101. defect["new_score"] = None
  102. # 2. 根据权重/系数计算最终扣分
  103. weights = aspect_config.get(f"{card_aspect}_weights") or aspect_config.get("coefficients")
  104. if not weights:
  105. raise ValueError(f"在配置中未找到 '{card_defect_type}' 的权重/系数")
  106. print(weighted_scores)
  107. for defect_type, score in weighted_scores.items():
  108. total_deduction += score * weights.get(defect_type, 1.0)
  109. final_weights = aspect_config["final_weights"][card_aspect]
  110. final_score = total_deduction * final_weights
  111. logger.info(f"final weights: {final_weights}, final score: {final_score}")
  112. if is_write_score:
  113. defect_data[f"{card_aspect}_{card_defect_type}_deduct_score"] = final_score
  114. return defect_data
  115. else:
  116. return final_score
  117. def calculate_centering_score(self,
  118. card_aspect: str,
  119. center_data: dict,
  120. is_write_score: bool = False) -> Union[float, dict]:
  121. """
  122. 计算居中度分数。
  123. card_type 为 front或 back
  124. is_write_score: 是否将分数写入json并返回
  125. """
  126. if card_aspect != "front" and card_aspect != "back":
  127. raise TypeError("calculate_centering_score:card_type 只能为 front 或 back")
  128. centering_config = self.config['centering'][card_aspect]
  129. rules = centering_config['rules']
  130. coefficients = centering_config['coefficients']
  131. center_left = center_data['box_result']['center_inference']['center_left']
  132. center_right = center_data['box_result']['center_inference']['center_right']
  133. center_top = center_data['box_result']['center_inference']['center_top']
  134. center_bottom = center_data['box_result']['center_inference']['center_bottom']
  135. # 将比例转换为用于查找规则的单个最大值
  136. h_lookup_val = max(center_left, center_right)
  137. v_lookup_val = max(center_top, center_bottom)
  138. h_deduction = self._get_score_from_tiers(h_lookup_val, rules) * coefficients['horizontal']
  139. v_deduction = self._get_score_from_tiers(v_lookup_val, rules) * coefficients['vertical']
  140. print(h_deduction, v_deduction)
  141. final_weight = self.config['centering']["final_weights"][card_aspect]
  142. final_score = (h_deduction + v_deduction) * final_weight
  143. logger.info(f"final weight: {final_weight}, final score: {final_score}")
  144. if is_write_score:
  145. center_data['deduct_score'] = final_score
  146. return center_data
  147. else:
  148. return final_score
  149. def formate_one_card_result(self, center_result: dict,
  150. defect_result: dict,
  151. card_defect_type: str,
  152. card_aspect: str):
  153. try:
  154. # 获取计算总分的权重
  155. card_config = self.config['card']['PSA']
  156. # 计算各部分的最后分数
  157. # 计算居中
  158. final_center_score = None
  159. if card_defect_type == "corner_edge":
  160. center_score = center_result['deduct_score']
  161. center_weight = card_config['center']
  162. final_center_score = center_score * center_weight
  163. corner_score = defect_result[f"{card_aspect}_corner_deduct_score"]
  164. edge_score = defect_result[f"{card_aspect}_edge_deduct_score"]
  165. corner_weight = card_config['corner']
  166. edge_weight = card_config['edge']
  167. final_defect_score = corner_score * corner_weight + edge_score * edge_weight
  168. _used_compute_deduct_score = final_center_score + final_defect_score
  169. card_score = self.base_score + final_center_score + final_defect_score
  170. else:
  171. face_score = defect_result[f"{card_aspect}_face_deduct_score"]
  172. face_weight = card_config['face']
  173. final_defect_score = face_score * face_weight
  174. _used_compute_deduct_score = final_defect_score
  175. card_score = self.base_score + final_defect_score
  176. except Exception as e:
  177. logger.error(f"formate_one_card_result 从json获取分数失败: {e}")
  178. raise e
  179. data = {
  180. "result": {
  181. "center_result": center_result,
  182. "defect_result": defect_result,
  183. "card_center_deduct_score": final_center_score,
  184. "card_defect_deduct_score": final_defect_score,
  185. "_used_compute_deduct_score": _used_compute_deduct_score,
  186. "card_score": card_score
  187. }
  188. }
  189. return data
  190. if __name__ == '__main__':
  191. # 1. 初始化评分器,加载规则
  192. scorer = CardScorer(r"C:\Code\ML\Project\CheckCardBoxAndDefectServer\app\core\scoring_config.json")
  193. # rulers = scorer.config['corners']['rules']['wear_area']
  194. #
  195. # score = scorer._get_score_from_tiers(0.06, rulers)
  196. # print(score)
  197. # print()
  198. # 居中分数
  199. center_data_path = r"C:\Code\ML\Project\CheckCardBoxAndDefectServer\_temp_work\pokemon_card_center-center_result.json"
  200. with open(center_data_path, 'r', encoding='utf-8') as f:
  201. center_data = json.load(f)
  202. center_data = scorer.calculate_centering_score("front", center_data, True)
  203. print(center_data)
  204. # 边角分数
  205. edge_corner_data_path = r"C:\Code\ML\Project\CheckCardBoxAndDefectServer\_temp_work\pokemon_front_corner_no_reflect_defect-corner_result.json"
  206. with open(edge_corner_data_path, 'r', encoding='utf-8') as f:
  207. edge_corner_data = json.load(f)
  208. corner_data = scorer.calculate_defect_score("corner", 'front', edge_corner_data, True)
  209. print(corner_data)
  210. score = scorer.calculate_defect_score("edge", 'front', edge_corner_data, True)
  211. print(score)
  212. # 面分数
  213. face_data_path = r"C:\Code\ML\Project\CheckCardBoxAndDefectServer\_temp_work\pokemon_front_face_no_reflect_defect-face_result.json"
  214. with open(face_data_path, 'r', encoding='utf-8') as f:
  215. face_data = json.load(f)
  216. score = scorer.calculate_defect_score("face", 'front', face_data, True)
  217. print(score)