formate_xy.py 31 KB

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