formate_xy.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  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 _process_defects_for_json(card_id: int, img_id: int, img_path: str, json_data: dict, side: str, all_images: list = None):
  28. if not json_data or "result" not in json_data:
  29. return
  30. defect_result = json_data["result"].get("defect_result", {})
  31. defects = defect_result.get("defects", [])
  32. is_fusion = side in ("front_fusion", "back_fusion")
  33. side_prefix = "front_" if side.startswith("front_") else "back_"
  34. defect_detail_list = []
  35. for idx, defect in enumerate(defects, start=1):
  36. min_rect = defect.get("min_rect")
  37. defect_img_url = ""
  38. location_str = ""
  39. defect_img_url_list = []
  40. if min_rect and len(min_rect) == 3:
  41. center_x, center_y = min_rect[0]
  42. location_str = f"{int(center_x)},{int(center_y)}"
  43. # 使用坐标哈希作为缓存文件名,避免重复裁剪
  44. rect_str = str(min_rect)
  45. rect_hash = hashlib.md5(rect_str.encode('utf-8')).hexdigest()[:8]
  46. filename = f"xy_{card_id}_{img_id}_{idx}_{rect_hash}.jpg"
  47. out_rel_path = f"/DefectImage/{filename}"
  48. out_object_name = f"{settings.MINIO_BASE_PREFIX}{out_rel_path}"
  49. try:
  50. # 检查 MinIO 中是否已有该截图,有则直接使用
  51. minio_client.stat_object(settings.MINIO_BUCKET, out_object_name)
  52. defect_img_url = settings.get_full_url(out_rel_path)
  53. except Exception:
  54. # 不存在或异常,则执行裁剪并上传
  55. defect_img_url = crop_defect_image(img_path, min_rect, filename)
  56. # 把同面的其他类型图在同样位置截图(不论是不是融合图都截)
  57. if all_images:
  58. same_side_images = [img for img in all_images if getattr(img, 'image_type', '').startswith(side_prefix)]
  59. for s_img in same_side_images:
  60. s_img_type = getattr(s_img, 'image_type', '')
  61. s_img_path = getattr(s_img, 'image_path', '')
  62. s_img_id = getattr(s_img, 'id', 0)
  63. s_filename = f"xy_{card_id}_{s_img_id}_{idx}_{rect_hash}.jpg"
  64. s_out_rel_path = f"/DefectImage/{s_filename}"
  65. s_out_object_name = f"{settings.MINIO_BASE_PREFIX}{s_out_rel_path}"
  66. s_url = ""
  67. try:
  68. minio_client.stat_object(settings.MINIO_BUCKET, s_out_object_name)
  69. s_url = settings.get_full_url(s_out_rel_path)
  70. except Exception:
  71. if s_img_path:
  72. s_url = crop_defect_image(s_img_path, min_rect, s_filename)
  73. if s_url:
  74. defect_img_url_list.append({
  75. "image_type": s_img_type,
  76. "url": s_url
  77. })
  78. # 1. 给每条缺陷带上 defectImgUrl
  79. defect["defectImgUrl"] = defect_img_url
  80. defect["defectImgUrls"] = defect_img_url_list
  81. # 2. 组装 defectDetailList 元素
  82. raw_type = f"{defect.get('defect_type', '')}".upper().strip()
  83. type_str_map = {
  84. "CORNER": "CORNER",
  85. "EDGE": "SIDE",
  86. "FACE": "SURFACE"
  87. }
  88. type_str = type_str_map.get(raw_type, raw_type)
  89. detail_item = {
  90. "id": defect.get("id", idx),
  91. "side": side,
  92. "location": location_str,
  93. "type": type_str,
  94. "defectImgUrl": defect_img_url,
  95. "label": defect.get("label", ""),
  96. "actual_area": defect.get("actual_area", 0),
  97. "defectImgUrls": defect_img_url_list
  98. }
  99. defect_detail_list.append(detail_item)
  100. defect_result["defectDetailList"] = defect_detail_list
  101. def _process_images_to_xy_format(card_data: dict):
  102. """
  103. 内部辅助函数:遍历卡牌数据中的图片,将 JSON 格式转换为前端需要的 XY 格式。
  104. 直接修改传入的 card_data 字典。
  105. """
  106. card_id = card_data.get("id")
  107. all_images = card_data.get("images", [])
  108. if all_images:
  109. for img in all_images:
  110. d_internal = img.detection_json
  111. if d_internal and isinstance(d_internal, str):
  112. d_internal = json.loads(d_internal)
  113. if d_internal:
  114. _process_defects_for_json(card_id, img.id, img.image_path, d_internal, img.image_type, all_images)
  115. img.detection_json = convert_internal_to_xy_format(d_internal)
  116. else:
  117. img.detection_json = convert_internal_to_xy_format({})
  118. m_internal = img.modified_json
  119. if m_internal and isinstance(m_internal, str):
  120. m_internal = json.loads(m_internal)
  121. if m_internal:
  122. _process_defects_for_json(card_id, img.id, img.image_path, m_internal, img.image_type, all_images)
  123. img.modified_json = convert_internal_to_xy_format(m_internal)
  124. else:
  125. m_fallback = copy.deepcopy(d_internal) if d_internal else {}
  126. img.modified_json = convert_internal_to_xy_format(m_fallback)
  127. return card_data
  128. @router.get("/query", response_model=CardDetailResponse, summary="获取卡牌详细信息(格式化xy), 支持前后翻页 [用户调用]")
  129. def get_card_details(
  130. card_id: int = Query(..., description="基准卡牌ID"),
  131. mode: QueryMode = Query(QueryMode.current, description="查询模式: current(当前), next(下一个), prev(上一个)"),
  132. db_conn: PooledMySQLConnection = db_dependency
  133. ):
  134. """
  135. 获取卡牌元数据以及所有与之关联的图片信息,并将坐标转换为 xy 格式。
  136. 同时返回上一张和下一张卡牌的ID。
  137. - **current**: 查询 card_id 对应的卡牌。
  138. - **next**: 查询 ID 比 card_id 大的第一张卡牌。
  139. - **prev**: 查询 ID 比 card_id 小的第一张卡牌。
  140. """
  141. target_id = card_id
  142. cursor = None
  143. try:
  144. cursor = db_conn.cursor(dictionary=True)
  145. # 1. 如果是查询上一个或下一个,先计算目标ID
  146. if mode != QueryMode.current:
  147. if mode == QueryMode.next:
  148. query_target = (f"SELECT id FROM {settings.DB_CARD_TABLE_NAME} "
  149. f"WHERE id > %s ORDER BY id ASC LIMIT 1")
  150. else: # mode == QueryMode.prev
  151. query_target = (f"SELECT id FROM {settings.DB_CARD_TABLE_NAME} "
  152. f"WHERE id < %s ORDER BY id DESC LIMIT 1")
  153. cursor.execute(query_target, (card_id,))
  154. row = cursor.fetchone()
  155. if not row:
  156. msg = "没有下一张" if mode == QueryMode.next else "没有上一张"
  157. raise HTTPException(status_code=200, detail=msg)
  158. target_id = row['id']
  159. # 2. 获取目标卡牌的详细数据 (Dict 格式)
  160. card_data = crud_card.get_card_with_details(db_conn, target_id)
  161. if not card_data:
  162. raise HTTPException(status_code=404, detail=f"ID为 {target_id} 的卡牌未找到。")
  163. # 3. 补充当前目标卡牌的 id_prev 和 id_next
  164. # 注意:这里需要重新获取 cursor,或者使用 cursor (非 dict 模式可能更方便取值,但 dict 模式也行)
  165. # 这里为了简单直接用 raw SQL
  166. # 查询上一个ID
  167. sql_prev = f"SELECT id FROM {settings.DB_CARD_TABLE_NAME} WHERE id < %s ORDER BY id DESC LIMIT 1"
  168. cursor.execute(sql_prev, (target_id,))
  169. row_prev = cursor.fetchone()
  170. card_data['id_prev'] = row_prev['id'] if row_prev else None
  171. # 查询下一个ID
  172. sql_next = f"SELECT id FROM {settings.DB_CARD_TABLE_NAME} WHERE id > %s ORDER BY id ASC LIMIT 1"
  173. cursor.execute(sql_next, (target_id,))
  174. row_next = cursor.fetchone()
  175. card_data['id_next'] = row_next['id'] if row_next else None
  176. # 4. 遍历图片,转换格式 (使用抽取出的辅助函数)
  177. _process_images_to_xy_format(card_data)
  178. # 5. 验证并返回
  179. return CardDetailResponse.model_validate(card_data)
  180. except HTTPException:
  181. raise
  182. except Exception as e:
  183. logger.error(f"查询卡牌详情失败 (Mode: {mode}, BaseID: {card_id}): {e}")
  184. raise HTTPException(status_code=500, detail="数据库查询失败")
  185. finally:
  186. if cursor:
  187. cursor.close()
  188. @router.put("/update/json/{id}", status_code=200, summary="接收xy格式, 还原后重计算分数并保存 [用户调用]")
  189. async def update_image_modified_json(
  190. id: int,
  191. new_json_data: dict = Body(..., description="前端传来的包含xy对象格式的JSON"),
  192. current_user: dict = Depends(get_current_user),
  193. db_conn: PooledMySQLConnection = db_dependency
  194. ):
  195. """
  196. 接收前端传来的特殊格式 JSON (points 为对象列表)。
  197. 1. 将格式还原为后端标准格式 (points 为 [[x,y]])。
  198. 2. 根据 id 获取 image_type。
  199. 3. 调用外部接口重新计算分数。
  200. 4. 更新 modified_json。
  201. """
  202. card_id_to_update = None
  203. cursor = None
  204. # *** 1. 格式还原 ***
  205. # 将前端的 xy dict 格式转回 [[x,y]],并丢弃 points 里的 id
  206. internal_json_payload = convert_xy_to_internal_format(new_json_data)
  207. try:
  208. cursor = db_conn.cursor(dictionary=True)
  209. # 2. 获取图片信息
  210. cursor.execute(f"SELECT image_type, card_id FROM {settings.DB_IMAGE_TABLE_NAME} WHERE id = %s", (id,))
  211. row = cursor.fetchone()
  212. if not row:
  213. raise HTTPException(status_code=404, detail=f"ID为 {id} 的图片未找到。")
  214. card_id_to_update = row["card_id"]
  215. check_card_permission(db_conn, current_user, card_id_to_update)
  216. image_type = row["image_type"]
  217. score_type = IMAGE_TYPE_TO_SCORE_TYPE.get(image_type)
  218. if not score_type:
  219. raise HTTPException(status_code=400, detail=f"未知的 image_type: {image_type}")
  220. logger.info(f"开始计算分数 (ID: {id}, Type: {score_type})")
  221. # 3. 调用远程计算接口 (使用还原后的 JSON)
  222. try:
  223. response = await run_in_threadpool(
  224. lambda: requests.post(
  225. settings.SCORE_RECALCULATE_ENDPOINT,
  226. params={"score_type": score_type},
  227. json=internal_json_payload, # 传递还原后的数据
  228. timeout=20
  229. )
  230. )
  231. except Exception as e:
  232. raise HTTPException(status_code=500, detail=f"调用分数计算服务失败: {e}")
  233. if response.status_code != 200:
  234. logger.error(f"分数计算接口返回错误: {response.status_code}, {response.text}")
  235. raise HTTPException(status_code=response.status_code,
  236. detail=f"分数计算接口返回错误: {response.text}")
  237. logger.info("分数计算完成")
  238. # 获取计算服务返回的结果(这个结果通常已经是标准的 internal 格式,带有分数和面积)
  239. final_json_data = response.json()
  240. # 4. 保存结果到数据库
  241. recalculated_json_str = json.dumps(final_json_data, ensure_ascii=False)
  242. update_query = (f"UPDATE {settings.DB_IMAGE_TABLE_NAME} "
  243. f"SET modified_json = %s, is_edited = TRUE "
  244. f"WHERE id = %s")
  245. cursor.execute(update_query, (recalculated_json_str, id))
  246. db_conn.commit()
  247. logger.info(f"图片ID {id} 的 modified_json 已更新并重新计算。")
  248. # 更新对应的 cards 的分数状态
  249. try:
  250. crud_card.update_card_scores_and_status(db_conn, card_id_to_update)
  251. logger.info(f"卡牌 {card_id_to_update} 的分数和状态已更新。")
  252. except Exception as score_update_e:
  253. logger.error(f"更新卡牌 {card_id_to_update} 分数失败: {score_update_e}")
  254. # 更新卡牌审核状态
  255. try:
  256. with db_conn.cursor() as cursor:
  257. review_state = 2
  258. # 更新指定 card_id 的 review_state 字段
  259. query_update = f"UPDATE {settings.DB_CARD_TABLE_NAME} SET review_state = %s WHERE id = %s"
  260. cursor.execute(query_update, (review_state, card_id_to_update))
  261. if cursor.rowcount == 0:
  262. raise HTTPException(status_code=404, detail=f"ID为 {card_id_to_update} 的卡牌未找到。")
  263. db_conn.commit()
  264. logger.info(f"卡牌 ID {card_id_to_update} 的审核状态已成功修改为 {review_state}。")
  265. except Exception as e:
  266. db_conn.rollback()
  267. logger.error(f"修改卡牌 {id} 审核状态失败: {e}")
  268. if isinstance(e, HTTPException):
  269. raise e
  270. raise HTTPException(status_code=500, detail="修改审核状态失败,数据库操作错误。")
  271. return {
  272. "detail": f"成功更新图片ID {id} 的JSON数据",
  273. "image_type": image_type,
  274. "score_type": score_type
  275. }
  276. except HTTPException:
  277. db_conn.rollback()
  278. raise
  279. except Exception as e:
  280. db_conn.rollback()
  281. logger.error(f"更新JSON失败 ({id}): {e}")
  282. raise HTTPException(status_code=500, detail=f"更新JSON数据失败: {e}")
  283. finally:
  284. if cursor:
  285. cursor.close()
  286. # 处理灰度如
  287. @router.put("/update/json_gray/{id}", status_code=200, summary="[灰度] 接收xy格式, 合并至Ring图重计算并保存 [用户调用]")
  288. async def update_gray_image_json(
  289. id: int,
  290. new_json_data: dict = Body(..., description="前端传来的灰度图编辑后的JSON(xy格式)"),
  291. current_user: dict = Depends(get_current_user),
  292. db_conn: PooledMySQLConnection = db_dependency
  293. ):
  294. """
  295. 针对灰度图 (front_gray/back_gray) 的保存逻辑。
  296. """
  297. cursor = None
  298. # 1. 格式还原
  299. internal_gray_json = convert_xy_to_internal_format(new_json_data)
  300. gray_defects = internal_gray_json.get("result", {}).get("defect_result", {}).get("defects", [])
  301. try:
  302. cursor = db_conn.cursor(dictionary=True)
  303. # 2. 获取灰度图信息
  304. # 注意:灰度图存在 card_gray_images 表中
  305. cursor.execute(f"SELECT card_id, image_type FROM {settings.DB_GRAY_IMAGE_TABLE_NAME} WHERE id = %s", (id,))
  306. gray_row = cursor.fetchone()
  307. if not gray_row:
  308. raise HTTPException(status_code=404, detail=f"ID为 {id} 的灰度图未找到。")
  309. card_id = gray_row['card_id']
  310. check_card_permission(db_conn, current_user, card_id)
  311. gray_image_type = gray_row['image_type']
  312. # 3. 确定目标 Ring 图类型
  313. target_ring_type = None
  314. if gray_image_type == ImageType.front_gray.value:
  315. target_ring_type = ImageType.front_ring.value
  316. elif gray_image_type == ImageType.back_gray.value:
  317. target_ring_type = ImageType.back_ring.value
  318. else:
  319. raise HTTPException(status_code=400, detail=f"不支持的灰度图类型: {gray_image_type}")
  320. # 4. 获取目标 Ring 图数据 (Card Images 表)
  321. cursor.execute(
  322. f"SELECT id, detection_json, modified_json FROM {settings.DB_IMAGE_TABLE_NAME} "
  323. f"WHERE card_id = %s AND image_type = %s",
  324. (card_id, target_ring_type)
  325. )
  326. ring_row = cursor.fetchone()
  327. if not ring_row:
  328. raise HTTPException(status_code=404, detail=f"未找到对应的 Ring 图 ({target_ring_type}),无法应用修改。")
  329. ring_image_id = ring_row['id']
  330. # 优先使用 modified_json,如果没有则使用 detection_json
  331. source_json_str = ring_row['modified_json'] if ring_row['modified_json'] else ring_row['detection_json']
  332. if isinstance(source_json_str, str):
  333. ring_json_data = json.loads(source_json_str)
  334. else:
  335. ring_json_data = source_json_str
  336. # 5. 合并逻辑 (Merge Logic)
  337. # 确保路径存在
  338. if "result" not in ring_json_data: ring_json_data["result"] = {}
  339. if "defect_result" not in ring_json_data["result"]: ring_json_data["result"]["defect_result"] = {}
  340. if "defects" not in ring_json_data["result"]["defect_result"]: ring_json_data["result"]["defect_result"][
  341. "defects"] = []
  342. ring_defects = ring_json_data["result"]["defect_result"]["defects"]
  343. # 遍历灰度图传来的新缺陷列表
  344. for new_defect in gray_defects:
  345. gray_id = new_defect.get("gray_id")
  346. # 只有带有 gray_id 的才进行特殊合并处理 (理论上前端编辑的都应该有,或者新生成的)
  347. # 如果没有 gray_id,视作普通新缺陷直接添加
  348. if not gray_id:
  349. ring_defects.append(new_defect)
  350. continue
  351. # 在 Ring 图现有的缺陷中寻找匹配的 gray_id
  352. match_index = -1
  353. for i, old_defect in enumerate(ring_defects):
  354. if old_defect.get("gray_id") == gray_id:
  355. match_index = i
  356. break
  357. if match_index != -1:
  358. # 存在:替换 (Replace)
  359. ring_defects[match_index] = new_defect
  360. else:
  361. # 不存在:添加 (Append)
  362. ring_defects.append(new_defect)
  363. # 6. 调用计算服务 (对 Ring 图数据进行重算)
  364. score_type = IMAGE_TYPE_TO_SCORE_TYPE.get(target_ring_type) # e.g., 'front_ring'
  365. logger.info(f"开始重计算 Ring 图分数 (GrayID: {id} -> RingID: {ring_image_id}, Type: {score_type})")
  366. try:
  367. response = await run_in_threadpool(
  368. lambda: requests.post(
  369. settings.SCORE_RECALCULATE_ENDPOINT,
  370. params={"score_type": score_type},
  371. json=ring_json_data, # 发送合并后的 Ring 数据
  372. timeout=20
  373. )
  374. )
  375. except Exception as e:
  376. raise HTTPException(status_code=500, detail=f"调用分数计算服务失败: {e}")
  377. if response.status_code != 200:
  378. logger.error(f"分数计算接口返回错误: {response.text}")
  379. raise HTTPException(status_code=response.status_code,
  380. detail=f"分数计算接口返回错误: {response.text}")
  381. final_ring_json = response.json()
  382. # 7. 保存结果到数据库 (保存到 Ring 图记录)
  383. final_json_str = json.dumps(final_ring_json, ensure_ascii=False)
  384. update_query = (
  385. f"UPDATE {settings.DB_IMAGE_TABLE_NAME} "
  386. f"SET modified_json = %s, is_edited = TRUE "
  387. f"WHERE id = %s"
  388. )
  389. cursor.execute(update_query, (final_json_str, ring_image_id))
  390. db_conn.commit()
  391. logger.info(f"Ring 图 {ring_image_id} 已根据灰度图 {id} 的修改进行了更新。")
  392. # 8. 更新卡牌总分状态
  393. try:
  394. crud_card.update_card_scores_and_status(db_conn, card_id)
  395. except Exception as e:
  396. logger.error(f"更新卡牌 {card_id} 分数状态失败: {e}")
  397. # 更新卡牌审核状态
  398. try:
  399. with db_conn.cursor() as cursor:
  400. review_state = 2
  401. # 更新指定 card_id 的 review_state 字段
  402. # 注意:MySQL 在 “值未变化” 的情况下 rowcount 可能为 0,但这不代表记录不存在。
  403. query_update = f"UPDATE {settings.DB_CARD_TABLE_NAME} SET review_state = %s WHERE id = %s"
  404. cursor.execute(query_update, (review_state, card_id))
  405. if cursor.rowcount == 0:
  406. cursor.execute(f"SELECT 1 FROM {settings.DB_CARD_TABLE_NAME} WHERE id = %s LIMIT 1", (card_id,))
  407. if not cursor.fetchone():
  408. raise HTTPException(status_code=404, detail=f"ID为 {card_id} 的卡牌未找到。")
  409. db_conn.commit()
  410. logger.info(f"卡牌 ID {card_id} 的审核状态已成功修改为 {review_state}。")
  411. except Exception as e:
  412. db_conn.rollback()
  413. logger.error(f"修改卡牌 {id} 审核状态失败: {e}")
  414. if isinstance(e, HTTPException):
  415. raise e
  416. raise HTTPException(status_code=500, detail="修改审核状态失败,数据库操作错误。")
  417. return {
  418. "detail": f"成功应用灰度图修改到 {target_ring_type}",
  419. "target_ring_id": ring_image_id,
  420. "gray_id": id
  421. }
  422. except HTTPException:
  423. db_conn.rollback()
  424. raise
  425. except Exception as e:
  426. db_conn.rollback()
  427. logger.error(f"灰度图更新失败 ({id}): {e}")
  428. raise HTTPException(status_code=500, detail=f"系统内部错误: {e}")
  429. finally:
  430. if cursor:
  431. cursor.close()