formate_xy.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648
  1. import requests
  2. import json
  3. import copy
  4. from enum import Enum
  5. from fastapi import APIRouter, Depends, HTTPException, Query, Body
  6. from fastapi.concurrency import run_in_threadpool
  7. from mysql.connector.pooling import PooledMySQLConnection
  8. from app.core.config import settings
  9. from app.core.logger import get_logger
  10. from app.core.database_loader import get_db_connection
  11. from app.api.users import check_card_permission, get_current_user
  12. from app.utils.scheme import (
  13. CardDetailResponse, IMAGE_TYPE_TO_SCORE_TYPE, ImageType
  14. )
  15. from app.crud import crud_card
  16. from app.utils.xy_process import convert_internal_to_xy_format, convert_xy_to_internal_format
  17. import hashlib
  18. from app.core.minio_client import minio_client
  19. from app.utils.rating_report_utils import crop_defect_image
  20. logger = get_logger(__name__)
  21. router = APIRouter()
  22. db_dependency = Depends(get_db_connection)
  23. class QueryMode(str, Enum):
  24. current = "current"
  25. next = "next"
  26. prev = "prev"
  27. def _is_center_box_shapes_empty(center_result: dict) -> bool:
  28. """
  29. 判断 center_result 中 inner/outer box 的 shapes 是否都为空。
  30. 前端某些场景会传空 shapes,直接下发给算分服务可能触发其内部越界。
  31. """
  32. if not isinstance(center_result, dict):
  33. return True
  34. box_result = center_result.get("box_result", {})
  35. if not isinstance(box_result, dict):
  36. return True
  37. inner_shapes = box_result.get("inner_box", {}).get("shapes", [])
  38. outer_shapes = box_result.get("outer_box", {}).get("shapes", [])
  39. return not inner_shapes and not outer_shapes
  40. def _prepare_recalculate_payload(edited_json: dict, source_json: dict) -> dict:
  41. """
  42. 以数据库里的原始 JSON 为底稿,合并前端编辑结果,得到更稳定的重算入参。
  43. 当前仅明确覆盖 defects;center_result 只有在前端传了非空 shapes 时才覆盖。
  44. """
  45. base = copy.deepcopy(source_json) if isinstance(source_json, dict) else {}
  46. incoming = edited_json if isinstance(edited_json, dict) else {}
  47. if "id" in incoming:
  48. base["id"] = incoming["id"]
  49. if "imageWidth" in incoming:
  50. base["imageWidth"] = incoming["imageWidth"]
  51. if "imageHeight" in incoming:
  52. base["imageHeight"] = incoming["imageHeight"]
  53. base.setdefault("result", {})
  54. incoming_result = incoming.get("result", {})
  55. if not isinstance(incoming_result, dict):
  56. incoming_result = {}
  57. # defects 使用前端编辑结果覆盖
  58. incoming_defects = (
  59. incoming_result.get("defect_result", {}).get("defects", [])
  60. if isinstance(incoming_result.get("defect_result", {}), dict)
  61. else []
  62. )
  63. base["result"].setdefault("defect_result", {})
  64. base["result"]["defect_result"]["defects"] = incoming_defects if isinstance(incoming_defects, list) else []
  65. # center_result 仅在前端有有效 shapes 时覆盖;否则沿用底稿
  66. incoming_center = incoming_result.get("center_result")
  67. if isinstance(incoming_center, dict) and not _is_center_box_shapes_empty(incoming_center):
  68. base["result"]["center_result"] = incoming_center
  69. elif "center_result" not in base["result"]:
  70. base["result"]["center_result"] = incoming_center if isinstance(incoming_center, dict) else {}
  71. return base
  72. def _sanitize_defects_for_recalculate(defects: list):
  73. """
  74. 清理前端展示/编辑辅助字段,减少算分服务解析失败概率。
  75. """
  76. if not isinstance(defects, list):
  77. return
  78. for d in defects:
  79. if not isinstance(d, dict):
  80. continue
  81. if d.get("label") == "slight_scratch":
  82. d["label"] = "scratch"
  83. d.pop("defectImgUrl", None)
  84. d.pop("defectImgUrls", None)
  85. d.pop("gray_id", None)
  86. d.pop("fusion_id", None)
  87. d.pop("edit_type", None)
  88. d.pop("severity_level", None)
  89. d.pop("new_score", None)
  90. def _process_defects_for_json(card_id: int, img_id: int, img_path: str, json_data: dict, side: str, all_images: list = None):
  91. if not json_data or "result" not in json_data:
  92. return
  93. defect_result = json_data["result"].get("defect_result", {})
  94. defects = defect_result.get("defects", [])
  95. is_fusion = side in ("front_fusion", "back_fusion")
  96. side_prefix = "front_" if side.startswith("front_") else "back_"
  97. defect_detail_list = []
  98. for idx, defect in enumerate(defects, start=1):
  99. min_rect = defect.get("min_rect")
  100. defect_img_url = ""
  101. location_str = ""
  102. defect_img_url_list = []
  103. if min_rect and len(min_rect) == 3:
  104. center_x, center_y = min_rect[0]
  105. location_str = f"{int(center_x)},{int(center_y)}"
  106. # 使用坐标哈希作为缓存文件名,避免重复裁剪
  107. rect_str = str(min_rect)
  108. rect_hash = hashlib.md5(rect_str.encode('utf-8')).hexdigest()[:8]
  109. filename = f"xy_{card_id}_{img_id}_{idx}_{rect_hash}.jpg"
  110. out_rel_path = f"/DefectImage/{filename}"
  111. out_object_name = f"{settings.MINIO_BASE_PREFIX}{out_rel_path}"
  112. try:
  113. # 检查 MinIO 中是否已有该截图,有则直接使用
  114. minio_client.stat_object(settings.MINIO_BUCKET, out_object_name)
  115. defect_img_url = settings.get_full_url(out_rel_path)
  116. except Exception:
  117. # 不存在或异常,则执行裁剪并上传
  118. defect_img_url = crop_defect_image(img_path, min_rect, filename)
  119. # 把同面的其他类型图在同样位置截图(不论是不是融合图都截)
  120. if all_images:
  121. same_side_images = [img for img in all_images if getattr(img, 'image_type', '').startswith(side_prefix)]
  122. for s_img in same_side_images:
  123. s_img_type = getattr(s_img, 'image_type', '')
  124. s_img_path = getattr(s_img, 'image_path', '')
  125. s_img_id = getattr(s_img, 'id', 0)
  126. s_filename = f"xy_{card_id}_{s_img_id}_{idx}_{rect_hash}.jpg"
  127. s_out_rel_path = f"/DefectImage/{s_filename}"
  128. s_out_object_name = f"{settings.MINIO_BASE_PREFIX}{s_out_rel_path}"
  129. s_url = ""
  130. try:
  131. minio_client.stat_object(settings.MINIO_BUCKET, s_out_object_name)
  132. s_url = settings.get_full_url(s_out_rel_path)
  133. except Exception:
  134. if s_img_path:
  135. s_url = crop_defect_image(s_img_path, min_rect, s_filename)
  136. if s_url:
  137. defect_img_url_list.append({
  138. "image_type": s_img_type,
  139. "url": s_url
  140. })
  141. # 1. 给每条缺陷带上 defectImgUrl
  142. defect["defectImgUrl"] = defect_img_url
  143. defect["defectImgUrls"] = defect_img_url_list
  144. # 2. 组装 defectDetailList 元素
  145. raw_type = f"{defect.get('defect_type', '')}".upper().strip()
  146. type_str_map = {
  147. "CORNER": "CORNER",
  148. "EDGE": "SIDE",
  149. "FACE": "SURFACE"
  150. }
  151. type_str = type_str_map.get(raw_type, raw_type)
  152. detail_item = {
  153. "id": defect.get("id", idx),
  154. "side": side,
  155. "location": location_str,
  156. "type": type_str,
  157. "defectImgUrl": defect_img_url,
  158. "label": defect.get("label", ""),
  159. "actual_area": defect.get("actual_area", 0),
  160. "defectImgUrls": defect_img_url_list
  161. }
  162. defect_detail_list.append(detail_item)
  163. defect_result["defectDetailList"] = defect_detail_list
  164. def _process_images_to_xy_format(card_data: dict):
  165. """
  166. 内部辅助函数:遍历卡牌数据中的图片,将 JSON 格式转换为前端需要的 XY 格式。
  167. 直接修改传入的 card_data 字典。
  168. """
  169. card_id = card_data.get("id")
  170. all_images = card_data.get("images", [])
  171. if all_images:
  172. for img in all_images:
  173. d_internal = img.detection_json
  174. if isinstance(d_internal, str):
  175. d_internal = json.loads(d_internal)
  176. if d_internal:
  177. _process_defects_for_json(card_id, img.id, img.image_path, d_internal, img.image_type, all_images)
  178. img.detection_json = convert_internal_to_xy_format(d_internal)
  179. else:
  180. img.detection_json = convert_internal_to_xy_format({})
  181. m_internal = img.modified_json
  182. if isinstance(m_internal, str):
  183. m_internal = json.loads(m_internal)
  184. if m_internal:
  185. _process_defects_for_json(card_id, img.id, img.image_path, m_internal, img.image_type, all_images)
  186. img.modified_json = convert_internal_to_xy_format(m_internal)
  187. else:
  188. m_fallback = copy.deepcopy(d_internal) if d_internal else {}
  189. img.modified_json = convert_internal_to_xy_format(m_fallback)
  190. return card_data
  191. @router.get("/query", response_model=CardDetailResponse, summary="获取卡牌详细信息(格式化xy), 支持前后翻页 [用户调用]")
  192. def get_card_details(
  193. card_id: int = Query(..., description="基准卡牌ID"),
  194. mode: QueryMode = Query(QueryMode.current, description="查询模式: current(当前), next(下一个), prev(上一个)"),
  195. db_conn: PooledMySQLConnection = db_dependency
  196. ):
  197. """
  198. 获取卡牌元数据以及所有与之关联的图片信息,并将坐标转换为 xy 格式。
  199. 同时返回上一张和下一张卡牌的ID。
  200. - **current**: 查询 card_id 对应的卡牌。
  201. - **next**: 查询 ID 比 card_id 大的第一张卡牌。
  202. - **prev**: 查询 ID 比 card_id 小的第一张卡牌。
  203. """
  204. target_id = card_id
  205. cursor = None
  206. try:
  207. cursor = db_conn.cursor(dictionary=True)
  208. # 1. 如果是查询上一个或下一个,先计算目标ID
  209. if mode != QueryMode.current:
  210. if mode == QueryMode.next:
  211. query_target = (f"SELECT id FROM {settings.DB_CARD_TABLE_NAME} "
  212. f"WHERE id > %s ORDER BY id ASC LIMIT 1")
  213. else: # mode == QueryMode.prev
  214. query_target = (f"SELECT id FROM {settings.DB_CARD_TABLE_NAME} "
  215. f"WHERE id < %s ORDER BY id DESC LIMIT 1")
  216. cursor.execute(query_target, (card_id,))
  217. row = cursor.fetchone()
  218. if not row:
  219. msg = "没有下一张" if mode == QueryMode.next else "没有上一张"
  220. raise HTTPException(status_code=200, detail=msg)
  221. target_id = row['id']
  222. # 2. 获取目标卡牌的详细数据 (Dict 格式)
  223. card_data = crud_card.get_card_with_details(db_conn, target_id)
  224. if not card_data:
  225. raise HTTPException(status_code=404, detail=f"ID为 {target_id} 的卡牌未找到。")
  226. # 3. 补充当前目标卡牌的 id_prev 和 id_next
  227. # 注意:这里需要重新获取 cursor,或者使用 cursor (非 dict 模式可能更方便取值,但 dict 模式也行)
  228. # 这里为了简单直接用 raw SQL
  229. # 查询上一个ID
  230. sql_prev = f"SELECT id FROM {settings.DB_CARD_TABLE_NAME} WHERE id < %s ORDER BY id DESC LIMIT 1"
  231. cursor.execute(sql_prev, (target_id,))
  232. row_prev = cursor.fetchone()
  233. card_data['id_prev'] = row_prev['id'] if row_prev else None
  234. # 查询下一个ID
  235. sql_next = f"SELECT id FROM {settings.DB_CARD_TABLE_NAME} WHERE id > %s ORDER BY id ASC LIMIT 1"
  236. cursor.execute(sql_next, (target_id,))
  237. row_next = cursor.fetchone()
  238. card_data['id_next'] = row_next['id'] if row_next else None
  239. # 4. 遍历图片,转换格式 (使用抽取出的辅助函数)
  240. _process_images_to_xy_format(card_data)
  241. # 5. 将 images 从 Pydantic 对象转为 dict,避免 model_validate 重复验证导致类型异常
  242. if "images" in card_data:
  243. card_data["images"] = [
  244. img.model_dump() if hasattr(img, 'model_dump') else img
  245. for img in card_data["images"]
  246. ]
  247. # 6. 验证并返回
  248. return CardDetailResponse.model_validate(card_data)
  249. except HTTPException:
  250. raise
  251. except Exception as e:
  252. logger.error(f"查询卡牌详情失败 (Mode: {mode}, BaseID: {card_id}): {e}")
  253. raise HTTPException(status_code=500, detail="数据库查询失败")
  254. finally:
  255. if cursor:
  256. cursor.close()
  257. @router.put("/update/json/{id}", status_code=200, summary="接收xy格式, 还原后重计算分数并保存 [用户调用]")
  258. async def update_image_modified_json(
  259. id: int,
  260. new_json_data: dict = Body(..., description="前端传来的包含xy对象格式的JSON"),
  261. current_user: dict = Depends(get_current_user),
  262. db_conn: PooledMySQLConnection = db_dependency
  263. ):
  264. """
  265. 接收前端传来的特殊格式 JSON (points 为对象列表)。
  266. 1. 将格式还原为后端标准格式 (points 为 [[x,y]])。
  267. 2. 根据 id 获取 image_type。
  268. 3. 调用外部接口重新计算分数。
  269. 4. 更新 modified_json。
  270. """
  271. card_id_to_update = None
  272. cursor = None
  273. # *** 1. 格式还原 ***
  274. # 将前端的 xy dict 格式转回 [[x,y]]
  275. internal_json_payload = convert_xy_to_internal_format(new_json_data)
  276. try:
  277. cursor = db_conn.cursor(dictionary=True)
  278. # 2. 获取图片信息
  279. cursor.execute(
  280. f"SELECT image_type, card_id, detection_json, modified_json "
  281. f"FROM {settings.DB_IMAGE_TABLE_NAME} WHERE id = %s",
  282. (id,)
  283. )
  284. row = cursor.fetchone()
  285. if not row:
  286. raise HTTPException(status_code=404, detail=f"ID为 {id} 的图片未找到。")
  287. card_id_to_update = row["card_id"]
  288. check_card_permission(db_conn, current_user, card_id_to_update)
  289. image_type = row["image_type"]
  290. # 针对融合图,在调用外部服务算分时直接把它当成对应的 ring 图
  291. # 否则它在映射表里是 None,会导致报错
  292. target_score_type = image_type
  293. if image_type == ImageType.front_fusion.value:
  294. target_score_type = ImageType.front_ring.value
  295. elif image_type == ImageType.back_fusion.value:
  296. target_score_type = ImageType.back_ring.value
  297. score_type = IMAGE_TYPE_TO_SCORE_TYPE.get(target_score_type)
  298. if not score_type:
  299. raise HTTPException(status_code=400, detail=f"未知的 image_type: {image_type}")
  300. # 3. 准备重算 payload:以库内原始 JSON 为底稿,仅覆盖编辑后的 defects
  301. source_json_str = row["modified_json"] if row["modified_json"] else row["detection_json"]
  302. if isinstance(source_json_str, str):
  303. source_json_data = json.loads(source_json_str)
  304. else:
  305. source_json_data = source_json_str if isinstance(source_json_str, dict) else {}
  306. payload_for_recalculate = _prepare_recalculate_payload(internal_json_payload, source_json_data)
  307. _defects = payload_for_recalculate.get("result", {}).get("defect_result", {}).get("defects", [])
  308. _sanitize_defects_for_recalculate(_defects)
  309. logger.info(f"开始计算分数 (ID: {id}, Type: {score_type})")
  310. # 4. 调用远程计算接口
  311. try:
  312. response = await run_in_threadpool(
  313. lambda: requests.post(
  314. settings.SCORE_RECALCULATE_ENDPOINT,
  315. params={"score_type": score_type},
  316. json=payload_for_recalculate,
  317. timeout=20
  318. )
  319. )
  320. except Exception as e:
  321. raise HTTPException(status_code=500, detail=f"调用分数计算服务失败: {e}")
  322. if response.status_code != 200:
  323. logger.error(f"分数计算接口返回错误: {response.status_code}, {response.text}")
  324. raise HTTPException(status_code=response.status_code,
  325. detail=f"分数计算接口返回错误: {response.text}")
  326. logger.info("分数计算完成")
  327. # 获取计算服务返回的结果(这个结果通常已经是标准的 internal 格式,带有分数和面积)
  328. final_json_data = response.json()
  329. # 5. 保存结果到数据库
  330. recalculated_json_str = json.dumps(final_json_data, ensure_ascii=False)
  331. update_query = (f"UPDATE {settings.DB_IMAGE_TABLE_NAME} "
  332. f"SET modified_json = %s, is_edited = TRUE "
  333. f"WHERE id = %s")
  334. cursor.execute(update_query, (recalculated_json_str, id))
  335. db_conn.commit()
  336. logger.info(f"图片ID {id} 的 modified_json 已更新并重新计算。")
  337. # 更新对应的 cards 的分数状态
  338. try:
  339. crud_card.update_card_scores_and_status(db_conn, card_id_to_update)
  340. logger.info(f"卡牌 {card_id_to_update} 的分数和状态已更新。")
  341. except Exception as score_update_e:
  342. logger.error(f"更新卡牌 {card_id_to_update} 分数失败: {score_update_e}")
  343. # 更新卡牌审核状态
  344. try:
  345. with db_conn.cursor() as cursor:
  346. review_state = 2
  347. # 更新指定 card_id 的 review_state 字段
  348. query_update = f"UPDATE {settings.DB_CARD_TABLE_NAME} SET review_state = %s WHERE id = %s"
  349. cursor.execute(query_update, (review_state, card_id_to_update))
  350. if cursor.rowcount == 0:
  351. raise HTTPException(status_code=404, detail=f"ID为 {card_id_to_update} 的卡牌未找到。")
  352. db_conn.commit()
  353. logger.info(f"卡牌 ID {card_id_to_update} 的审核状态已成功修改为 {review_state}。")
  354. except Exception as e:
  355. db_conn.rollback()
  356. logger.error(f"修改卡牌 {id} 审核状态失败: {e}")
  357. if isinstance(e, HTTPException):
  358. raise e
  359. raise HTTPException(status_code=500, detail="修改审核状态失败,数据库操作错误。")
  360. return {
  361. "detail": f"成功更新图片ID {id} 的JSON数据",
  362. "image_type": image_type,
  363. "score_type": score_type
  364. }
  365. except HTTPException:
  366. db_conn.rollback()
  367. raise
  368. except Exception as e:
  369. db_conn.rollback()
  370. logger.error(f"更新JSON失败 ({id}): {e}")
  371. raise HTTPException(status_code=500, detail=f"更新JSON数据失败: {e}")
  372. finally:
  373. if cursor:
  374. cursor.close()
  375. # 处理灰度如
  376. @router.put("/update/json_gray/{id}", status_code=200, summary="[灰度] 接收xy格式, 合并至Ring图重计算并保存 [用户调用]")
  377. async def update_gray_image_json(
  378. id: int,
  379. new_json_data: dict = Body(..., description="前端传来的灰度图编辑后的JSON(xy格式)"),
  380. current_user: dict = Depends(get_current_user),
  381. db_conn: PooledMySQLConnection = db_dependency
  382. ):
  383. """
  384. 针对灰度图 (front_gray/back_gray) 的保存逻辑。
  385. """
  386. cursor = None
  387. # 1. 格式还原
  388. internal_gray_json = convert_xy_to_internal_format(new_json_data)
  389. gray_defects = internal_gray_json.get("result", {}).get("defect_result", {}).get("defects", [])
  390. # 丢弃前端展示用的辅助字段,防止传给算分服务导致报错
  391. for d in gray_defects:
  392. if d.get("label") == "slight_scratch":
  393. d["label"] = "scratch"
  394. d.pop("defectImgUrl", None)
  395. d.pop("defectImgUrls", None)
  396. try:
  397. cursor = db_conn.cursor(dictionary=True)
  398. # 2. 获取辅助图(灰度图/融合图)信息
  399. # 以前只查 card_gray_images,现在融合图是在 card_images 表里
  400. # 先查 card_gray_images
  401. cursor.execute(f"SELECT card_id, image_type FROM {settings.DB_GRAY_IMAGE_TABLE_NAME} WHERE id = %s", (id,))
  402. gray_row = cursor.fetchone()
  403. if not gray_row:
  404. # 如果灰度表没找到,去主表找找看是不是融合图
  405. cursor.execute(f"SELECT card_id, image_type FROM {settings.DB_IMAGE_TABLE_NAME} WHERE id = %s AND image_type IN ('front_fusion', 'back_fusion')", (id,))
  406. gray_row = cursor.fetchone()
  407. if not gray_row:
  408. raise HTTPException(status_code=404, detail=f"ID为 {id} 的辅助图未找到。")
  409. card_id = gray_row['card_id']
  410. check_card_permission(db_conn, current_user, card_id)
  411. gray_image_type = gray_row['image_type']
  412. # 3. 确定目标 Ring 图类型
  413. target_ring_type = None
  414. if gray_image_type in (ImageType.front_gray.value, ImageType.front_fusion.value):
  415. target_ring_type = ImageType.front_ring.value
  416. elif gray_image_type in (ImageType.back_gray.value, ImageType.back_fusion.value):
  417. target_ring_type = ImageType.back_ring.value
  418. else:
  419. raise HTTPException(status_code=400, detail=f"不支持的辅助图类型: {gray_image_type}")
  420. # 4. 获取目标 Ring 图数据 (Card Images 表)
  421. cursor.execute(
  422. f"SELECT id, detection_json, modified_json FROM {settings.DB_IMAGE_TABLE_NAME} "
  423. f"WHERE card_id = %s AND image_type = %s",
  424. (card_id, target_ring_type)
  425. )
  426. ring_row = cursor.fetchone()
  427. if not ring_row:
  428. raise HTTPException(status_code=404, detail=f"未找到对应的 Ring 图 ({target_ring_type}),无法应用修改。")
  429. ring_image_id = ring_row['id']
  430. # 优先使用 modified_json,如果没有则使用 detection_json
  431. source_json_str = ring_row['modified_json'] if ring_row['modified_json'] else ring_row['detection_json']
  432. if isinstance(source_json_str, str):
  433. ring_json_data = json.loads(source_json_str)
  434. else:
  435. ring_json_data = source_json_str
  436. # 5. 合并逻辑 (Merge Logic)
  437. # 确保路径存在
  438. if "result" not in ring_json_data: ring_json_data["result"] = {}
  439. if "defect_result" not in ring_json_data["result"]: ring_json_data["result"]["defect_result"] = {}
  440. if "defects" not in ring_json_data["result"]["defect_result"]: ring_json_data["result"]["defect_result"][
  441. "defects"] = []
  442. ring_defects = ring_json_data["result"]["defect_result"]["defects"]
  443. # 遍历灰度图传来的新缺陷列表
  444. for new_defect in gray_defects:
  445. is_fusion = gray_image_type in (ImageType.front_fusion.value, ImageType.back_fusion.value)
  446. key_to_check = "fusion_id" if is_fusion else "gray_id"
  447. identifier = new_defect.get(key_to_check)
  448. # 只有带有对应标识的才进行特殊合并处理
  449. # 如果没有,视作普通新缺陷直接添加
  450. if not identifier:
  451. ring_defects.append(new_defect)
  452. continue
  453. # 在 Ring 图现有的缺陷中寻找匹配的标识
  454. match_index = -1
  455. for i, old_defect in enumerate(ring_defects):
  456. if old_defect.get(key_to_check) == identifier:
  457. match_index = i
  458. break
  459. if match_index != -1:
  460. # 存在:替换 (Replace)
  461. ring_defects[match_index] = new_defect
  462. else:
  463. # 不存在:添加 (Append)
  464. ring_defects.append(new_defect)
  465. # 6. 调用计算服务 (对 Ring 图数据进行重算)
  466. score_type = IMAGE_TYPE_TO_SCORE_TYPE.get(target_ring_type) # e.g., 'front_ring'
  467. logger.info(f"开始重计算 Ring 图分数 (GrayID: {id} -> RingID: {ring_image_id}, Type: {score_type})")
  468. try:
  469. response = await run_in_threadpool(
  470. lambda: requests.post(
  471. settings.SCORE_RECALCULATE_ENDPOINT,
  472. params={"score_type": score_type},
  473. json=ring_json_data, # 发送合并后的 Ring 数据
  474. timeout=20
  475. )
  476. )
  477. except Exception as e:
  478. raise HTTPException(status_code=500, detail=f"调用分数计算服务失败: {e}")
  479. if response.status_code != 200:
  480. logger.error(f"分数计算接口返回错误: {response.text}")
  481. raise HTTPException(status_code=response.status_code,
  482. detail=f"分数计算接口返回错误: {response.text}")
  483. final_ring_json = response.json()
  484. # 7. 保存结果到数据库 (保存到 Ring 图记录)
  485. final_json_str = json.dumps(final_ring_json, ensure_ascii=False)
  486. update_query = (
  487. f"UPDATE {settings.DB_IMAGE_TABLE_NAME} "
  488. f"SET modified_json = %s, is_edited = TRUE "
  489. f"WHERE id = %s"
  490. )
  491. cursor.execute(update_query, (final_json_str, ring_image_id))
  492. db_conn.commit()
  493. logger.info(f"Ring 图 {ring_image_id} 已根据灰度图 {id} 的修改进行了更新。")
  494. # 8. 更新卡牌总分状态
  495. try:
  496. crud_card.update_card_scores_and_status(db_conn, card_id)
  497. except Exception as e:
  498. logger.error(f"更新卡牌 {card_id} 分数状态失败: {e}")
  499. # 更新卡牌审核状态
  500. try:
  501. with db_conn.cursor() as cursor:
  502. review_state = 2
  503. # 更新指定 card_id 的 review_state 字段
  504. # 注意:MySQL 在 “值未变化” 的情况下 rowcount 可能为 0,但这不代表记录不存在。
  505. query_update = f"UPDATE {settings.DB_CARD_TABLE_NAME} SET review_state = %s WHERE id = %s"
  506. cursor.execute(query_update, (review_state, card_id))
  507. if cursor.rowcount == 0:
  508. cursor.execute(f"SELECT 1 FROM {settings.DB_CARD_TABLE_NAME} WHERE id = %s LIMIT 1", (card_id,))
  509. if not cursor.fetchone():
  510. raise HTTPException(status_code=404, detail=f"ID为 {card_id} 的卡牌未找到。")
  511. db_conn.commit()
  512. logger.info(f"卡牌 ID {card_id} 的审核状态已成功修改为 {review_state}。")
  513. except Exception as e:
  514. db_conn.rollback()
  515. logger.error(f"修改卡牌 {id} 审核状态失败: {e}")
  516. if isinstance(e, HTTPException):
  517. raise e
  518. raise HTTPException(status_code=500, detail="修改审核状态失败,数据库操作错误。")
  519. return {
  520. "detail": f"成功应用灰度图修改到 {target_ring_type}",
  521. "target_ring_id": ring_image_id,
  522. "gray_id": id
  523. }
  524. except HTTPException:
  525. db_conn.rollback()
  526. raise
  527. except Exception as e:
  528. db_conn.rollback()
  529. logger.error(f"灰度图更新失败 ({id}): {e}")
  530. raise HTTPException(status_code=500, detail=f"系统内部错误: {e}")
  531. finally:
  532. if cursor:
  533. cursor.close()