formate_xy.py 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015
  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. 将 14 类新版 image_type 归一到 score_recalculate 接口接受的 score_type。
  31. 新版 stitch 导入后,同一面的 fusion/ring/stripe 共用该面 JSON;
  32. 编辑重算时按正反面统一归到 front_ring / back_ring。
  33. """
  34. image_type_to_recalc_score_type = {
  35. ImageType.front_fusion.value: ImageType.front_ring.value,
  36. ImageType.front_ring.value: ImageType.front_ring.value,
  37. ImageType.front_gray.value: ImageType.front_ring.value,
  38. ImageType.front_stripe1.value: ImageType.front_ring.value,
  39. ImageType.front_stripe2.value: ImageType.front_ring.value,
  40. ImageType.front_stripe3.value: ImageType.front_ring.value,
  41. ImageType.front_stripe4.value: ImageType.front_ring.value,
  42. ImageType.back_fusion.value: ImageType.back_ring.value,
  43. ImageType.back_ring.value: ImageType.back_ring.value,
  44. ImageType.back_gray.value: ImageType.back_ring.value,
  45. ImageType.back_stripe1.value: ImageType.back_ring.value,
  46. ImageType.back_stripe2.value: ImageType.back_ring.value,
  47. ImageType.back_stripe3.value: ImageType.back_ring.value,
  48. ImageType.back_stripe4.value: ImageType.back_ring.value,
  49. # 兼容历史同轴光数据
  50. ImageType.front_coaxial.value: ImageType.front_coaxial.value,
  51. ImageType.back_coaxial.value: ImageType.back_coaxial.value,
  52. }
  53. return image_type_to_recalc_score_type.get(image_type)
  54. def _is_center_box_shapes_empty(center_result: dict) -> bool:
  55. """
  56. 判断 center_result 中 inner/outer box 的 shapes 是否都为空。
  57. 前端某些场景会传空 shapes,直接下发给算分服务可能触发其内部越界。
  58. """
  59. if not isinstance(center_result, dict):
  60. return True
  61. box_result = center_result.get("box_result", {})
  62. if not isinstance(box_result, dict):
  63. return True
  64. inner_shapes = box_result.get("inner_box", {}).get("shapes", [])
  65. outer_shapes = box_result.get("outer_box", {}).get("shapes", [])
  66. return not inner_shapes and not outer_shapes
  67. def _normalize_center_result(center_result: dict) -> dict:
  68. """
  69. 兜底补齐算分服务依赖的 center_result 结构,避免 KeyError: 'box_result'。
  70. """
  71. normalized = center_result if isinstance(center_result, dict) else {}
  72. box_result = normalized.get("box_result")
  73. if not isinstance(box_result, dict):
  74. box_result = {}
  75. normalized["box_result"] = box_result
  76. inner_box = box_result.get("inner_box")
  77. if not isinstance(inner_box, dict):
  78. inner_box = {}
  79. box_result["inner_box"] = inner_box
  80. if not isinstance(inner_box.get("shapes"), list):
  81. inner_box["shapes"] = []
  82. outer_box = box_result.get("outer_box")
  83. if not isinstance(outer_box, dict):
  84. outer_box = {}
  85. box_result["outer_box"] = outer_box
  86. if not isinstance(outer_box.get("shapes"), list):
  87. outer_box["shapes"] = []
  88. return normalized
  89. def _prepare_recalculate_payload(edited_json: dict, source_json: dict) -> dict:
  90. """
  91. 以数据库里的原始 JSON 为底稿,合并前端编辑结果,得到更稳定的重算入参。
  92. 当前仅明确覆盖 defects;center_result 只有在前端传了非空 shapes 时才覆盖。
  93. 对前端标记为删除(edit_type=del)的缺陷,在这里直接过滤,避免重算后再次写回 modified_json。
  94. """
  95. base = copy.deepcopy(source_json) if isinstance(source_json, dict) else {}
  96. incoming = edited_json if isinstance(edited_json, dict) else {}
  97. if "id" in incoming:
  98. base["id"] = incoming["id"]
  99. if "imageWidth" in incoming:
  100. base["imageWidth"] = incoming["imageWidth"]
  101. if "imageHeight" in incoming:
  102. base["imageHeight"] = incoming["imageHeight"]
  103. base.setdefault("result", {})
  104. incoming_result = incoming.get("result", {})
  105. if not isinstance(incoming_result, dict):
  106. incoming_result = {}
  107. # defects 使用前端编辑结果覆盖;前端标记删除的项不参与重算,也不写回 modified_json
  108. incoming_defects = (
  109. incoming_result.get("defect_result", {}).get("defects", [])
  110. if isinstance(incoming_result.get("defect_result", {}), dict)
  111. else []
  112. )
  113. base["result"].setdefault("defect_result", {})
  114. filtered_defects = []
  115. if isinstance(incoming_defects, list):
  116. filtered_defects = [
  117. defect for defect in incoming_defects
  118. if not (isinstance(defect, dict) and defect.get("edit_type") == "del")
  119. ]
  120. base["result"]["defect_result"]["defects"] = filtered_defects
  121. # center_result 仅在前端有有效 shapes 时覆盖;否则沿用底稿
  122. incoming_center = incoming_result.get("center_result")
  123. if isinstance(incoming_center, dict) and not _is_center_box_shapes_empty(incoming_center):
  124. base["result"]["center_result"] = incoming_center
  125. elif "center_result" not in base["result"]:
  126. base["result"]["center_result"] = incoming_center if isinstance(incoming_center, dict) else {}
  127. base["result"]["center_result"] = _normalize_center_result(base["result"].get("center_result"))
  128. return base
  129. _GRAY_IMAGE_TYPES = frozenset({
  130. ImageType.front_gray.value,
  131. ImageType.back_gray.value,
  132. })
  133. # 以融合图 JSON 中的缺陷为准,在同面下列类型原图上裁图(含灰度图)
  134. _FRONT_DEFECT_URL_TARGET_TYPES = [
  135. ImageType.front_fusion.value,
  136. ImageType.front_ring.value,
  137. ImageType.front_gray.value,
  138. ImageType.front_stripe1.value,
  139. ImageType.front_stripe2.value,
  140. ImageType.front_stripe3.value,
  141. ImageType.front_stripe4.value,
  142. ImageType.front_coaxial.value, # 兼容历史同轴光
  143. ]
  144. _BACK_DEFECT_URL_TARGET_TYPES = [
  145. ImageType.back_fusion.value,
  146. ImageType.back_ring.value,
  147. ImageType.back_gray.value,
  148. ImageType.back_stripe1.value,
  149. ImageType.back_stripe2.value,
  150. ImageType.back_stripe3.value,
  151. ImageType.back_stripe4.value,
  152. ImageType.back_coaxial.value,
  153. ]
  154. _DEFECT_URL_TARGET_TYPES_BY_SIDE = {
  155. "front": _FRONT_DEFECT_URL_TARGET_TYPES,
  156. "back": _BACK_DEFECT_URL_TARGET_TYPES,
  157. }
  158. # ring / stripe 等可能落在 card_gray_images,裁图时需与主表合并
  159. _ALL_DEFECT_URL_TARGET_TYPES = frozenset(
  160. _FRONT_DEFECT_URL_TARGET_TYPES + _BACK_DEFECT_URL_TARGET_TYPES
  161. )
  162. def _is_gray_image_type(image_type: str) -> bool:
  163. return image_type in _GRAY_IMAGE_TYPES
  164. def _side_key_from_image_type(image_type: str) -> str:
  165. if image_type.startswith("front_"):
  166. return "front"
  167. if image_type.startswith("back_"):
  168. return "back"
  169. return ""
  170. def _defect_rect_hash(min_rect) -> str:
  171. if not min_rect or len(min_rect) != 3:
  172. return ""
  173. rect_str = str(min_rect)
  174. return hashlib.md5(rect_str.encode("utf-8")).hexdigest()[:8]
  175. def _resolve_fusion_images_by_side(all_images: list) -> dict:
  176. """每面仅以融合图 JSON 作为缺陷与裁图坐标来源。"""
  177. type_to_img = {getattr(img, "image_type", ""): img for img in all_images}
  178. return {
  179. "front": type_to_img.get(ImageType.front_fusion.value),
  180. "back": type_to_img.get(ImageType.back_fusion.value),
  181. }
  182. class _DefectCropImageRef:
  183. """裁图用的轻量图片引用(主表 Pydantic 或灰度辅助表行均可)。"""
  184. __slots__ = ("id", "image_type", "image_path")
  185. def __init__(self, image_id: int, image_type: str, image_path: str):
  186. self.id = image_id
  187. self.image_type = image_type
  188. self.image_path = image_path
  189. def _build_defect_crop_pool_by_type(
  190. card_id: int,
  191. all_images: list,
  192. db_conn: PooledMySQLConnection = None,
  193. ) -> dict:
  194. """
  195. 合并主表 card_images 与辅助表 card_gray_images 中的裁图目标。
  196. 同类型主表优先;ring/stripe 导入在灰度表时也能被 defectImgUrls 用到。
  197. """
  198. pool: dict = {}
  199. for img in all_images or []:
  200. image_type = getattr(img, "image_type", "")
  201. if image_type not in _ALL_DEFECT_URL_TARGET_TYPES:
  202. continue
  203. pool[image_type] = img
  204. if db_conn is not None:
  205. cursor = None
  206. try:
  207. cursor = db_conn.cursor(dictionary=True)
  208. cursor.execute(
  209. f"SELECT id, image_type, image_path FROM {settings.DB_GRAY_IMAGE_TABLE_NAME} "
  210. f"WHERE card_id = %s",
  211. (card_id,),
  212. )
  213. for row in cursor.fetchall():
  214. image_type = row.get("image_type") or ""
  215. if image_type not in _ALL_DEFECT_URL_TARGET_TYPES:
  216. continue
  217. if image_type in pool:
  218. continue
  219. pool[image_type] = _DefectCropImageRef(
  220. row["id"],
  221. image_type,
  222. settings.get_full_url(row.get("image_path")),
  223. )
  224. finally:
  225. if cursor:
  226. cursor.close()
  227. return pool
  228. def _defect_url_target_type_list(crop_pool_by_type: dict, side_key: str) -> list:
  229. """同面裁图类型列表;若已有 stripe 则不再使用历史 coaxial。"""
  230. target_types = list(_DEFECT_URL_TARGET_TYPES_BY_SIDE.get(side_key, []))
  231. has_stripe = any(
  232. t.startswith(f"{side_key}_stripe") and t in crop_pool_by_type
  233. for t in target_types
  234. )
  235. if has_stripe:
  236. coaxial = ImageType.front_coaxial.value if side_key == "front" else ImageType.back_coaxial.value
  237. target_types = [t for t in target_types if t != coaxial]
  238. return target_types
  239. def _defect_url_target_images(crop_pool_by_type: dict, side_key: str) -> list:
  240. """按固定类型顺序返回同面需生成 defectImgUrls 的图片(含灰度图)。"""
  241. targets = []
  242. for image_type in _defect_url_target_type_list(crop_pool_by_type, side_key):
  243. img = crop_pool_by_type.get(image_type)
  244. if img is not None:
  245. targets.append(img)
  246. return targets
  247. def _sanitize_defects_for_recalculate(defects: list):
  248. """
  249. 清理前端展示/编辑辅助字段,减少算分服务解析失败概率。
  250. """
  251. if not isinstance(defects, list):
  252. return
  253. for d in defects:
  254. if not isinstance(d, dict):
  255. continue
  256. if d.get("label") == "slight_scratch":
  257. d["label"] = "scratch"
  258. d.pop("defectImgUrl", None)
  259. d.pop("defectImgUrls", None)
  260. d.pop("gray_id", None)
  261. d.pop("fusion_id", None)
  262. d.pop("edit_type", None)
  263. d.pop("severity_level", None)
  264. d.pop("new_score", None)
  265. def _generate_defect_img_urls_for_json(
  266. card_id: int,
  267. fusion_img_id: int,
  268. json_data: dict,
  269. side_key: str,
  270. crop_pool_by_type: dict,
  271. generate_related_images: bool = True,
  272. ) -> dict:
  273. """
  274. 以融合图 JSON 中的缺陷 min_rect 为准,在同面各目标类型原图上裁图,
  275. 生成 defectImgUrls 并返回 rect_hash -> urls 缓存,供同面其它图复用。
  276. """
  277. start_time = perf_counter()
  278. url_cache_by_rect = {}
  279. if not json_data or "result" not in json_data:
  280. logger.info(
  281. "耗时埋点 _generate_defect_img_urls: card_id=%s fusion_image_id=%s side=%s defects=0 elapsed_ms=%.2f",
  282. card_id, fusion_img_id, side_key, (perf_counter() - start_time) * 1000,
  283. )
  284. return url_cache_by_rect
  285. defect_result = json_data["result"].get("defect_result", {})
  286. defects = defect_result.get("defects", [])
  287. crop_target_images = _defect_url_target_images(crop_pool_by_type, side_key)
  288. target_types = _defect_url_target_type_list(crop_pool_by_type, side_key)
  289. missing_types = [t for t in target_types if t not in crop_pool_by_type]
  290. if missing_types:
  291. logger.info(
  292. "defectImgUrls 裁图目标缺失: card_id=%s side=%s missing=%s",
  293. card_id, side_key, ",".join(missing_types),
  294. )
  295. for idx, defect in enumerate(defects, start=1):
  296. min_rect = defect.get("min_rect")
  297. defect_img_url_list = []
  298. rect_hash = _defect_rect_hash(min_rect)
  299. if min_rect and len(min_rect) == 3 and generate_related_images and crop_target_images:
  300. for s_img in crop_target_images:
  301. s_img_type = getattr(s_img, "image_type", "")
  302. s_img_path = getattr(s_img, "image_path", "")
  303. s_img_id = getattr(s_img, "id", 0)
  304. # _ln:带 points 连线的裁图版本,与旧缓存文件名区分
  305. s_filename = f"xy_{card_id}_{s_img_id}_{idx}_{rect_hash}_ln.jpg"
  306. s_out_rel_path = f"/DefectImage/{s_filename}"
  307. s_out_object_name = f"{settings.MINIO_BASE_PREFIX}{s_out_rel_path}"
  308. defect_points = defect.get("points")
  309. s_url = ""
  310. try:
  311. minio_client.stat_object(settings.MINIO_BUCKET, s_out_object_name)
  312. s_url = settings.get_full_url(s_out_rel_path)
  313. except Exception:
  314. if s_img_path:
  315. s_url = crop_defect_image(
  316. s_img_path, min_rect, s_filename, points=defect_points,
  317. )
  318. if s_url:
  319. defect_img_url_list.append({
  320. "image_type": s_img_type,
  321. "url": s_url,
  322. })
  323. defect["defectImgUrls"] = defect_img_url_list
  324. if rect_hash:
  325. url_cache_by_rect[rect_hash] = copy.deepcopy(defect_img_url_list)
  326. logger.info(
  327. "耗时埋点 _generate_defect_img_urls: card_id=%s fusion_image_id=%s side=%s "
  328. "defects=%s target_types=%s elapsed_ms=%.2f",
  329. card_id,
  330. fusion_img_id,
  331. side_key,
  332. len(defects),
  333. len(crop_target_images),
  334. (perf_counter() - start_time) * 1000,
  335. )
  336. return url_cache_by_rect
  337. def _apply_defect_img_urls_from_cache(json_data: dict, url_cache_by_rect: dict):
  338. """同面非 canonical 图:按 min_rect 哈希复用已生成的 defectImgUrls,不再访问 MinIO。"""
  339. if not json_data or "result" not in json_data or not url_cache_by_rect:
  340. return
  341. defects = json_data["result"].get("defect_result", {}).get("defects", [])
  342. for defect in defects:
  343. if not isinstance(defect, dict):
  344. continue
  345. rect_hash = _defect_rect_hash(defect.get("min_rect"))
  346. defect["defectImgUrls"] = copy.deepcopy(url_cache_by_rect.get(rect_hash, []))
  347. def _process_images_to_xy_format(
  348. card_data: dict,
  349. generate_related_images: bool = True,
  350. db_conn: PooledMySQLConnection = None,
  351. ):
  352. """
  353. 内部辅助函数:遍历卡牌数据中的图片,将 JSON 格式转换为前端需要的 XY 格式。
  354. 每面仅以融合图 JSON 生成一次 defectImgUrls(含 fusion/ring/gray/stripe 等同面类型),
  355. 再拷贝到同面其它图;裁切图会绘制缺陷 points 连线。
  356. 直接修改传入的 card_data 字典。
  357. """
  358. start_time = perf_counter()
  359. card_id = card_data.get("id")
  360. all_images = card_data.get("images", [])
  361. fusion_by_side = _resolve_fusion_images_by_side(all_images) if all_images else {}
  362. crop_pool_by_type = _build_defect_crop_pool_by_type(
  363. card_id, all_images, db_conn=db_conn,
  364. )
  365. detection_url_cache_by_side = {}
  366. modified_url_cache_by_side = {}
  367. if all_images:
  368. parsed_json_by_img_id = {}
  369. for img in all_images:
  370. d_internal = img.detection_json
  371. if isinstance(d_internal, str):
  372. d_internal = json.loads(d_internal) if d_internal else None
  373. m_internal = img.modified_json
  374. if isinstance(m_internal, str):
  375. m_internal = json.loads(m_internal) if m_internal else None
  376. parsed_json_by_img_id[img.id] = {
  377. "detection": d_internal,
  378. "modified": m_internal,
  379. }
  380. if generate_related_images:
  381. for side_key, fusion_img in fusion_by_side.items():
  382. if not fusion_img:
  383. continue
  384. parsed = parsed_json_by_img_id.get(fusion_img.id, {})
  385. d_internal = parsed.get("detection")
  386. if d_internal:
  387. detection_url_cache_by_side[side_key] = _generate_defect_img_urls_for_json(
  388. card_id,
  389. fusion_img.id,
  390. d_internal,
  391. side_key,
  392. crop_pool_by_type,
  393. generate_related_images=True,
  394. )
  395. m_internal = parsed.get("modified")
  396. if m_internal:
  397. modified_url_cache_by_side[side_key] = _generate_defect_img_urls_for_json(
  398. card_id,
  399. fusion_img.id,
  400. m_internal,
  401. side_key,
  402. crop_pool_by_type,
  403. generate_related_images=True,
  404. )
  405. for img in all_images:
  406. side_key = _side_key_from_image_type(img.image_type)
  407. parsed = parsed_json_by_img_id.get(img.id, {})
  408. d_internal = parsed.get("detection")
  409. m_internal = parsed.get("modified")
  410. if d_internal:
  411. if side_key and detection_url_cache_by_side.get(side_key):
  412. _apply_defect_img_urls_from_cache(
  413. d_internal, detection_url_cache_by_side[side_key],
  414. )
  415. img.detection_json = convert_internal_to_xy_format(d_internal)
  416. else:
  417. img.detection_json = convert_internal_to_xy_format({})
  418. if m_internal:
  419. if side_key and modified_url_cache_by_side.get(side_key):
  420. _apply_defect_img_urls_from_cache(
  421. m_internal, modified_url_cache_by_side[side_key],
  422. )
  423. img.modified_json = convert_internal_to_xy_format(m_internal)
  424. else:
  425. m_fallback = copy.deepcopy(d_internal) if d_internal else {}
  426. img.modified_json = convert_internal_to_xy_format(m_fallback)
  427. logger.info(
  428. "耗时埋点 _process_images_to_xy_format: card_id=%s image_count=%s elapsed_ms=%.2f",
  429. card_id, len(all_images), (perf_counter() - start_time) * 1000
  430. )
  431. return card_data
  432. def pregenerate_defect_images_for_card(db_conn: PooledMySQLConnection, card_id: int) -> int:
  433. """
  434. 导入阶段预生成缺陷裁图:以融合图 JSON 为准,按面在同面各类型原图上裁图并写入 MinIO。
  435. 查询接口 get_card_details 命中已存在的裁图后即可直接拼 URL,无需再实时裁图。
  436. 返回本次涉及裁图的缺陷数量(仅用于日志/统计)。
  437. """
  438. start_time = perf_counter()
  439. card_data = crud_card.get_card_with_details(db_conn, card_id)
  440. if not card_data:
  441. logger.warning("预生成缺陷裁图跳过:card_id=%s 未找到卡牌", card_id)
  442. return 0
  443. all_images = card_data.get("images", [])
  444. if not all_images:
  445. return 0
  446. fusion_by_side = _resolve_fusion_images_by_side(all_images)
  447. crop_pool_by_type = _build_defect_crop_pool_by_type(card_id, all_images, db_conn=db_conn)
  448. total_defects = 0
  449. for side_key, fusion_img in fusion_by_side.items():
  450. if not fusion_img:
  451. continue
  452. for json_field in ("detection_json", "modified_json"):
  453. raw_json = getattr(fusion_img, json_field, None)
  454. if isinstance(raw_json, str):
  455. raw_json = json.loads(raw_json) if raw_json else None
  456. if not raw_json:
  457. continue
  458. # 复制一份,避免污染 Pydantic 对象;只关心裁图副作用(写入 MinIO)
  459. cache = _generate_defect_img_urls_for_json(
  460. card_id,
  461. fusion_img.id,
  462. copy.deepcopy(raw_json),
  463. side_key,
  464. crop_pool_by_type,
  465. generate_related_images=True,
  466. )
  467. total_defects += len(cache)
  468. logger.info(
  469. "预生成缺陷裁图完成: card_id=%s defects=%s elapsed_ms=%.2f",
  470. card_id, total_defects, (perf_counter() - start_time) * 1000,
  471. )
  472. return total_defects
  473. @router.get("/query", response_model=CardDetailResponse, summary="获取卡牌详细信息(格式化xy), 支持前后翻页 [用户调用]")
  474. def get_card_details(
  475. card_id: int = Query(..., description="基准卡牌ID"),
  476. mode: QueryMode = Query(QueryMode.current, description="查询模式: current(当前), next(下一个), prev(上一个)"),
  477. db_conn: PooledMySQLConnection = db_dependency
  478. ):
  479. """
  480. 获取卡牌元数据以及所有与之关联的图片信息,并将坐标转换为 xy 格式。
  481. 同时返回上一张和下一张卡牌的ID。
  482. - **current**: 查询 card_id 对应的卡牌。
  483. - **next**: 查询 ID 比 card_id 大的第一张卡牌。
  484. - **prev**: 查询 ID 比 card_id 小的第一张卡牌。
  485. """
  486. target_id = card_id
  487. cursor = None
  488. start_time = perf_counter()
  489. try:
  490. cursor = db_conn.cursor(dictionary=True)
  491. # 1. 如果是查询上一个或下一个,先计算目标ID
  492. if mode != QueryMode.current:
  493. if mode == QueryMode.next:
  494. query_target = (f"SELECT id FROM {settings.DB_CARD_TABLE_NAME} "
  495. f"WHERE id > %s ORDER BY id ASC LIMIT 1")
  496. else: # mode == QueryMode.prev
  497. query_target = (f"SELECT id FROM {settings.DB_CARD_TABLE_NAME} "
  498. f"WHERE id < %s ORDER BY id DESC LIMIT 1")
  499. cursor.execute(query_target, (card_id,))
  500. row = cursor.fetchone()
  501. if not row:
  502. msg = "没有下一张" if mode == QueryMode.next else "没有上一张"
  503. # 边界场景返回 404,避免与 response_model=CardDetailResponse 冲突
  504. raise HTTPException(status_code=404, detail=msg)
  505. target_id = row['id']
  506. # 2. 获取目标卡牌的详细数据 (Dict 格式)
  507. card_data = crud_card.get_card_with_details(db_conn, target_id)
  508. if not card_data:
  509. raise HTTPException(status_code=404, detail=f"ID为 {target_id} 的卡牌未找到。")
  510. # 3. 补充当前目标卡牌的 id_prev 和 id_next
  511. # 注意:这里需要重新获取 cursor,或者使用 cursor (非 dict 模式可能更方便取值,但 dict 模式也行)
  512. # 这里为了简单直接用 raw SQL
  513. # 查询上一个ID
  514. sql_prev = f"SELECT id FROM {settings.DB_CARD_TABLE_NAME} WHERE id < %s ORDER BY id DESC LIMIT 1"
  515. cursor.execute(sql_prev, (target_id,))
  516. row_prev = cursor.fetchone()
  517. card_data['id_prev'] = row_prev['id'] if row_prev else None
  518. # 查询下一个ID
  519. sql_next = f"SELECT id FROM {settings.DB_CARD_TABLE_NAME} WHERE id > %s ORDER BY id ASC LIMIT 1"
  520. cursor.execute(sql_next, (target_id,))
  521. row_next = cursor.fetchone()
  522. card_data['id_next'] = row_next['id'] if row_next else None
  523. # 4. 遍历图片,转换格式 (使用抽取出的辅助函数)
  524. _process_images_to_xy_format(
  525. card_data,
  526. generate_related_images=True,
  527. db_conn=db_conn,
  528. )
  529. # 5. 将 images 从 Pydantic 对象转为 dict,避免 model_validate 重复验证导致类型异常
  530. if "images" in card_data:
  531. card_data["images"] = [
  532. img.model_dump() if hasattr(img, 'model_dump') else img
  533. for img in card_data["images"]
  534. ]
  535. # 6. 验证并返回
  536. return CardDetailResponse.model_validate(card_data)
  537. except HTTPException:
  538. raise
  539. except Exception as e:
  540. logger.error(f"查询卡牌详情失败 (Mode: {mode}, BaseID: {card_id}): {e}")
  541. raise HTTPException(status_code=500, detail="数据库查询失败")
  542. finally:
  543. logger.info(
  544. "耗时埋点 get_card_details: base_card_id=%s target_card_id=%s mode=%s elapsed_ms=%.2f",
  545. card_id, target_id, mode, (perf_counter() - start_time) * 1000
  546. )
  547. if cursor:
  548. cursor.close()
  549. @router.put("/update/json/{id}", status_code=200, summary="接收xy格式, 还原后重计算分数并保存 [用户调用]")
  550. async def update_image_modified_json(
  551. id: int,
  552. new_json_data: dict = Body(..., description="前端传来的包含xy对象格式的JSON"),
  553. current_user: dict = Depends(get_current_user),
  554. db_conn: PooledMySQLConnection = db_dependency
  555. ):
  556. """
  557. 接收前端传来的特殊格式 JSON (points 为对象列表)。
  558. 1. 将格式还原为后端标准格式 (points 为 [[x,y]])。
  559. 2. 根据 id 获取 image_type。
  560. 3. 调用外部接口重新计算分数。
  561. 4. 更新 modified_json。
  562. """
  563. card_id_to_update = None
  564. cursor = None
  565. # *** 1. 格式还原 ***
  566. # 将前端的 xy dict 格式转回 [[x,y]]
  567. internal_json_payload = convert_xy_to_internal_format(new_json_data)
  568. try:
  569. cursor = db_conn.cursor(dictionary=True)
  570. # 2. 获取图片信息
  571. cursor.execute(
  572. f"SELECT image_type, card_id, detection_json, modified_json "
  573. f"FROM {settings.DB_IMAGE_TABLE_NAME} WHERE id = %s",
  574. (id,)
  575. )
  576. row = cursor.fetchone()
  577. if not row:
  578. raise HTTPException(status_code=404, detail=f"ID为 {id} 的图片未找到。")
  579. card_id_to_update = row["card_id"]
  580. check_card_permission(db_conn, current_user, card_id_to_update)
  581. image_type = row["image_type"]
  582. # score_recalculate 接口只接受 coaxial / ring 类型的 score_type,
  583. # 融合图/灰度图/调光图都按正反面归到对应 ring。
  584. score_type = _resolve_recalc_score_type(image_type)
  585. if not score_type:
  586. raise HTTPException(status_code=400, detail=f"未知的 image_type: {image_type}")
  587. # 3. 准备重算 payload:以库内原始 JSON 为底稿,仅覆盖编辑后的 defects
  588. # 对 fusion 图,score_type 会映射到 ring;此时底稿也应优先使用 ring 图 JSON,
  589. # 否则 fusion 图常见的空框结构会导致算分服务在 ring 逻辑下越界。
  590. source_json_str = row["modified_json"] if row["modified_json"] else row["detection_json"]
  591. if image_type in (ImageType.front_fusion.value, ImageType.back_fusion.value):
  592. target_ring_type = (
  593. ImageType.front_ring.value
  594. if image_type == ImageType.front_fusion.value
  595. else ImageType.back_ring.value
  596. )
  597. cursor.execute(
  598. f"SELECT detection_json, modified_json FROM {settings.DB_IMAGE_TABLE_NAME} "
  599. f"WHERE card_id = %s AND image_type = %s LIMIT 1",
  600. (card_id_to_update, target_ring_type)
  601. )
  602. ring_row = cursor.fetchone()
  603. if ring_row:
  604. source_json_str = ring_row["modified_json"] if ring_row["modified_json"] else ring_row["detection_json"]
  605. else:
  606. logger.warning(
  607. "fusion图重算未找到对应ring底稿,回退到当前图: image_id=%s card_id=%s image_type=%s target_ring_type=%s",
  608. id, card_id_to_update, image_type, target_ring_type
  609. )
  610. if isinstance(source_json_str, str):
  611. source_json_data = json.loads(source_json_str)
  612. else:
  613. source_json_data = source_json_str if isinstance(source_json_str, dict) else {}
  614. payload_for_recalculate = _prepare_recalculate_payload(internal_json_payload, source_json_data)
  615. _defects = payload_for_recalculate.get("result", {}).get("defect_result", {}).get("defects", [])
  616. _sanitize_defects_for_recalculate(_defects)
  617. logger.info(f"开始计算分数 (ID: {id}, Type: {score_type})")
  618. # 4. 调用远程计算接口
  619. try:
  620. response = await run_in_threadpool(
  621. lambda: requests.post(
  622. settings.SCORE_RECALCULATE_ENDPOINT,
  623. params={"score_type": score_type},
  624. json=payload_for_recalculate,
  625. timeout=20
  626. )
  627. )
  628. except Exception as e:
  629. logger.error(
  630. "调用分数计算服务失败(update/json): image_id=%s card_id=%s score_type=%s endpoint=%s error=%s",
  631. id, card_id_to_update, score_type, settings.SCORE_RECALCULATE_ENDPOINT, e,
  632. exc_info=True
  633. )
  634. raise HTTPException(status_code=500, detail=f"调用分数计算服务失败: {e}")
  635. if response.status_code != 200:
  636. logger.error(
  637. "分数计算接口返回错误(update/json): image_id=%s card_id=%s score_type=%s endpoint=%s status=%s body=%s",
  638. id, card_id_to_update, score_type, settings.SCORE_RECALCULATE_ENDPOINT, response.status_code, response.text
  639. )
  640. raise HTTPException(status_code=response.status_code,
  641. detail=f"分数计算接口返回错误: {response.text}")
  642. logger.info("分数计算完成")
  643. # 获取计算服务返回的结果(这个结果通常已经是标准的 internal 格式,带有分数和面积)
  644. final_json_data = response.json()
  645. # 5. 保存结果到数据库
  646. recalculated_json_str = json.dumps(final_json_data, ensure_ascii=False)
  647. update_query = (f"UPDATE {settings.DB_IMAGE_TABLE_NAME} "
  648. f"SET modified_json = %s, is_edited = TRUE "
  649. f"WHERE id = %s")
  650. cursor.execute(update_query, (recalculated_json_str, id))
  651. db_conn.commit()
  652. logger.info(f"图片ID {id} 的 modified_json 已更新并重新计算。")
  653. # 更新对应的 cards 的分数状态
  654. try:
  655. crud_card.update_card_scores_and_status(db_conn, card_id_to_update)
  656. logger.info(f"卡牌 {card_id_to_update} 的分数和状态已更新。")
  657. except Exception as score_update_e:
  658. logger.error(f"更新卡牌 {card_id_to_update} 分数失败: {score_update_e}")
  659. # 更新卡牌审核状态
  660. try:
  661. with db_conn.cursor() as cursor:
  662. review_state = 2
  663. # 更新指定 card_id 的 review_state 字段
  664. # 注意:MySQL 在“值未变化”时 rowcount 可能为 0,这不代表记录不存在。
  665. query_update = f"UPDATE {settings.DB_CARD_TABLE_NAME} SET review_state = %s WHERE id = %s"
  666. cursor.execute(query_update, (review_state, card_id_to_update))
  667. if cursor.rowcount == 0:
  668. cursor.execute(f"SELECT 1 FROM {settings.DB_CARD_TABLE_NAME} WHERE id = %s LIMIT 1",
  669. (card_id_to_update,))
  670. if not cursor.fetchone():
  671. raise HTTPException(status_code=404, detail=f"ID为 {card_id_to_update} 的卡牌未找到。")
  672. db_conn.commit()
  673. logger.info(f"卡牌 ID {card_id_to_update} 的审核状态已成功修改为 {review_state}。")
  674. except Exception as e:
  675. db_conn.rollback()
  676. logger.error(f"修改卡牌 {id} 审核状态失败: {e}")
  677. if isinstance(e, HTTPException):
  678. raise e
  679. raise HTTPException(status_code=500, detail="修改审核状态失败,数据库操作错误。")
  680. return {
  681. "detail": f"成功更新图片ID {id} 的JSON数据",
  682. "image_type": image_type,
  683. "score_type": score_type
  684. }
  685. except HTTPException:
  686. db_conn.rollback()
  687. raise
  688. except Exception as e:
  689. db_conn.rollback()
  690. logger.error(f"更新JSON失败 ({id}): {e}")
  691. raise HTTPException(status_code=500, detail=f"更新JSON数据失败: {e}")
  692. finally:
  693. if cursor:
  694. cursor.close()
  695. # 处理灰度如
  696. @router.put("/update/json_gray/{id}", status_code=200, summary="[灰度] 接收xy格式, 合并至Ring图重计算并保存 [用户调用]")
  697. async def update_gray_image_json(
  698. id: int,
  699. new_json_data: dict = Body(..., description="前端传来的灰度图编辑后的JSON(xy格式)"),
  700. current_user: dict = Depends(get_current_user),
  701. db_conn: PooledMySQLConnection = db_dependency
  702. ):
  703. """
  704. 针对灰度图 (front_gray/back_gray) 的保存逻辑。
  705. """
  706. cursor = None
  707. # 1. 格式还原
  708. internal_gray_json = convert_xy_to_internal_format(new_json_data)
  709. gray_defects = internal_gray_json.get("result", {}).get("defect_result", {}).get("defects", [])
  710. # 丢弃前端展示用的辅助字段,防止传给算分服务导致报错
  711. for d in gray_defects:
  712. if d.get("label") == "slight_scratch":
  713. d["label"] = "scratch"
  714. d.pop("defectImgUrl", None)
  715. d.pop("defectImgUrls", None)
  716. try:
  717. cursor = db_conn.cursor(dictionary=True)
  718. # 2. 获取辅助图(灰度图/融合图)信息
  719. # 以前只查 card_gray_images,现在融合图是在 card_images 表里
  720. # 先查 card_gray_images
  721. cursor.execute(f"SELECT card_id, image_type FROM {settings.DB_GRAY_IMAGE_TABLE_NAME} WHERE id = %s", (id,))
  722. gray_row = cursor.fetchone()
  723. if not gray_row:
  724. # 如果灰度表没找到,去主表找找看是不是融合图
  725. 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,))
  726. gray_row = cursor.fetchone()
  727. if not gray_row:
  728. raise HTTPException(status_code=404, detail=f"ID为 {id} 的辅助图未找到。")
  729. card_id = gray_row['card_id']
  730. check_card_permission(db_conn, current_user, card_id)
  731. gray_image_type = gray_row['image_type']
  732. # 3. 确定目标 Ring 图类型
  733. target_ring_type = None
  734. if gray_image_type in (ImageType.front_gray.value, ImageType.front_fusion.value):
  735. target_ring_type = ImageType.front_ring.value
  736. elif gray_image_type in (ImageType.back_gray.value, ImageType.back_fusion.value):
  737. target_ring_type = ImageType.back_ring.value
  738. else:
  739. raise HTTPException(status_code=400, detail=f"不支持的辅助图类型: {gray_image_type}")
  740. # 4. 获取目标 Ring 图数据 (Card Images 表)
  741. cursor.execute(
  742. f"SELECT id, detection_json, modified_json FROM {settings.DB_IMAGE_TABLE_NAME} "
  743. f"WHERE card_id = %s AND image_type = %s",
  744. (card_id, target_ring_type)
  745. )
  746. ring_row = cursor.fetchone()
  747. if not ring_row:
  748. raise HTTPException(status_code=404, detail=f"未找到对应的 Ring 图 ({target_ring_type}),无法应用修改。")
  749. ring_image_id = ring_row['id']
  750. # 优先使用 modified_json,如果没有则使用 detection_json
  751. source_json_str = ring_row['modified_json'] if ring_row['modified_json'] else ring_row['detection_json']
  752. if isinstance(source_json_str, str):
  753. ring_json_data = json.loads(source_json_str)
  754. else:
  755. ring_json_data = source_json_str
  756. # 5. 合并逻辑 (Merge Logic)
  757. # 确保路径存在
  758. if "result" not in ring_json_data: ring_json_data["result"] = {}
  759. if "defect_result" not in ring_json_data["result"]: ring_json_data["result"]["defect_result"] = {}
  760. if "defects" not in ring_json_data["result"]["defect_result"]: ring_json_data["result"]["defect_result"][
  761. "defects"] = []
  762. ring_defects = ring_json_data["result"]["defect_result"]["defects"]
  763. # 遍历灰度图传来的新缺陷列表
  764. for new_defect in gray_defects:
  765. is_fusion = gray_image_type in (ImageType.front_fusion.value, ImageType.back_fusion.value)
  766. key_to_check = "fusion_id" if is_fusion else "gray_id"
  767. identifier = new_defect.get(key_to_check)
  768. # 只有带有对应标识的才进行特殊合并处理
  769. # 如果没有,视作普通新缺陷直接添加
  770. if not identifier:
  771. ring_defects.append(new_defect)
  772. continue
  773. # 在 Ring 图现有的缺陷中寻找匹配的标识
  774. match_index = -1
  775. for i, old_defect in enumerate(ring_defects):
  776. if old_defect.get(key_to_check) == identifier:
  777. match_index = i
  778. break
  779. if match_index != -1:
  780. # 存在:替换 (Replace)
  781. ring_defects[match_index] = new_defect
  782. else:
  783. # 不存在:添加 (Append)
  784. ring_defects.append(new_defect)
  785. # 6. 调用计算服务 (对 Ring 图数据进行重算)
  786. # score_recalculate 接口接受 ring 类型,直接用目标 ring 类型即可
  787. score_type = _resolve_recalc_score_type(target_ring_type)
  788. logger.info(f"开始重计算 Ring 图分数 (GrayID: {id} -> RingID: {ring_image_id}, Type: {score_type})")
  789. try:
  790. response = await run_in_threadpool(
  791. lambda: requests.post(
  792. settings.SCORE_RECALCULATE_ENDPOINT,
  793. params={"score_type": score_type},
  794. json=ring_json_data, # 发送合并后的 Ring 数据
  795. timeout=20
  796. )
  797. )
  798. except Exception as e:
  799. logger.error(
  800. "调用分数计算服务失败(update/json_gray): gray_id=%s ring_id=%s card_id=%s score_type=%s endpoint=%s error=%s",
  801. id, ring_image_id, card_id, score_type, settings.SCORE_RECALCULATE_ENDPOINT, e,
  802. exc_info=True
  803. )
  804. raise HTTPException(status_code=500, detail=f"调用分数计算服务失败: {e}")
  805. if response.status_code != 200:
  806. logger.error(
  807. "分数计算接口返回错误(update/json_gray): gray_id=%s ring_id=%s card_id=%s score_type=%s endpoint=%s status=%s body=%s",
  808. id, ring_image_id, card_id, score_type, settings.SCORE_RECALCULATE_ENDPOINT, response.status_code, response.text
  809. )
  810. raise HTTPException(status_code=response.status_code,
  811. detail=f"分数计算接口返回错误: {response.text}")
  812. final_ring_json = response.json()
  813. # 7. 保存结果到数据库 (保存到 Ring 图记录)
  814. final_json_str = json.dumps(final_ring_json, ensure_ascii=False)
  815. update_query = (
  816. f"UPDATE {settings.DB_IMAGE_TABLE_NAME} "
  817. f"SET modified_json = %s, is_edited = TRUE "
  818. f"WHERE id = %s"
  819. )
  820. cursor.execute(update_query, (final_json_str, ring_image_id))
  821. db_conn.commit()
  822. logger.info(f"Ring 图 {ring_image_id} 已根据灰度图 {id} 的修改进行了更新。")
  823. # 8. 更新卡牌总分状态
  824. try:
  825. crud_card.update_card_scores_and_status(db_conn, card_id)
  826. except Exception as e:
  827. logger.error(f"更新卡牌 {card_id} 分数状态失败: {e}")
  828. # 更新卡牌审核状态
  829. try:
  830. with db_conn.cursor() as cursor:
  831. review_state = 2
  832. # 更新指定 card_id 的 review_state 字段
  833. # 注意:MySQL 在 “值未变化” 的情况下 rowcount 可能为 0,但这不代表记录不存在。
  834. query_update = f"UPDATE {settings.DB_CARD_TABLE_NAME} SET review_state = %s WHERE id = %s"
  835. cursor.execute(query_update, (review_state, card_id))
  836. if cursor.rowcount == 0:
  837. cursor.execute(f"SELECT 1 FROM {settings.DB_CARD_TABLE_NAME} WHERE id = %s LIMIT 1", (card_id,))
  838. if not cursor.fetchone():
  839. raise HTTPException(status_code=404, detail=f"ID为 {card_id} 的卡牌未找到。")
  840. db_conn.commit()
  841. logger.info(f"卡牌 ID {card_id} 的审核状态已成功修改为 {review_state}。")
  842. except Exception as e:
  843. db_conn.rollback()
  844. logger.error(f"修改卡牌 {id} 审核状态失败: {e}")
  845. if isinstance(e, HTTPException):
  846. raise e
  847. raise HTTPException(status_code=500, detail="修改审核状态失败,数据库操作错误。")
  848. return {
  849. "detail": f"成功应用灰度图修改到 {target_ring_type}",
  850. "target_ring_id": ring_image_id,
  851. "gray_id": id
  852. }
  853. except HTTPException:
  854. db_conn.rollback()
  855. raise
  856. except Exception as e:
  857. db_conn.rollback()
  858. logger.error(f"灰度图更新失败 ({id}): {e}")
  859. raise HTTPException(status_code=500, detail=f"系统内部错误: {e}")
  860. finally:
  861. if cursor:
  862. cursor.close()