crud_card.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  1. from typing import Optional, List, Dict, Any
  2. from datetime import date
  3. from mysql.connector.pooling import PooledMySQLConnection
  4. import json
  5. from datetime import datetime
  6. import copy
  7. from app.core.config import settings
  8. from app.utils.scheme import CardImageResponse, CardType, SortBy, SortOrder, ImageType
  9. from app.utils.card_score_calculate import calculate_scores_from_images
  10. from app.core.logger import get_logger
  11. logger = get_logger(__name__)
  12. # 定义灰度图固定的 detection_json 结构
  13. EMPTY_DETECTION_JSON = {
  14. "result": {
  15. "center_result": {},
  16. "defect_result": {
  17. "defects": []
  18. }
  19. }
  20. }
  21. def update_card_scores_and_status(db_conn: PooledMySQLConnection, card_id: int):
  22. """
  23. 更新cards表中的分数和状态。注意:只基于 card_images 表(主4张图)计算。
  24. """
  25. with db_conn.cursor(dictionary=True) as cursor:
  26. # 1. 获取所有关联图片 (主表)
  27. query_images = f"SELECT * FROM {settings.DB_IMAGE_TABLE_NAME} WHERE card_id = %s"
  28. cursor.execute(query_images, (card_id,))
  29. image_records = cursor.fetchall()
  30. images = [CardImageResponse.model_validate(row) for row in image_records]
  31. # 2. 计算分数和状态
  32. scores_data = calculate_scores_from_images(images)
  33. # 3. 更新 cards 表
  34. query_update_card = (
  35. f"UPDATE {settings.DB_CARD_TABLE_NAME} SET "
  36. "detection_score = %s, modified_score = %s, is_edited = %s, updated_at = NOW() "
  37. "WHERE id = %s"
  38. )
  39. params = (
  40. scores_data["detection_score"],
  41. scores_data["modified_score"],
  42. scores_data["is_edited"],
  43. card_id,
  44. )
  45. cursor.execute(query_update_card, params)
  46. db_conn.commit()
  47. def _construct_gray_image_json(gray_type: str, ring_image_data: Optional[Dict[str, Any]]) -> Dict[str, Any]:
  48. """
  49. 内部辅助:构建辅助图(灰度图/融合图)的 modified_json
  50. gray_type: front_gray / back_gray / front_fusion / back_fusion
  51. ring_image_data: 对应的 ring 图的数据库原始字典数据 (包含 detection_json/modified_json 字段)
  52. """
  53. if not ring_image_data:
  54. return None
  55. # 获取 Ring 图最新的 JSON (优先取 modified, 没有则取 detection)
  56. source_json = ring_image_data.get('modified_json')
  57. if not source_json:
  58. source_json = ring_image_data.get('detection_json')
  59. # 解析 JSON 字符串
  60. if isinstance(source_json, str):
  61. try:
  62. source_json = json.loads(source_json)
  63. except:
  64. return None
  65. if not source_json:
  66. return None
  67. # 开始筛选 defects
  68. defects = source_json.get("result", {}).get("defect_result", {}).get("defects", [])
  69. filtered_defects = []
  70. for defect in defects:
  71. # 判断当前缺陷是否属于当前这张辅助图
  72. # 如果是融合图,就找 fusion_id;如果是灰度图,就找 gray_id
  73. is_fusion = gray_type in ("front_fusion", "back_fusion")
  74. key_to_check = "fusion_id" if is_fusion else "gray_id"
  75. if key_to_check in defect:
  76. filtered_defects.append(defect)
  77. # 即使没有缺陷,也最好返回一个空的结构,不要返回 None
  78. # 不然前端可能会觉得没这个字段或者解析报错
  79. gray_modified_json = copy.deepcopy(EMPTY_DETECTION_JSON)
  80. gray_modified_json["result"]["defect_result"]["defects"] = filtered_defects
  81. # 还可以把 Ring 图的宽高带过来,防止前端报错
  82. gray_modified_json["result"]["imageHeight"] = source_json.get("result", {}).get("imageHeight", 0)
  83. gray_modified_json["result"]["imageWidth"] = source_json.get("result", {}).get("imageWidth", 0)
  84. return gray_modified_json
  85. def get_card_with_details(db_conn: PooledMySQLConnection, card_id: int) -> Optional[Dict[str, Any]]:
  86. """获取单个卡牌的完整信息,包含主图和灰度图。"""
  87. with db_conn.cursor(dictionary=True) as cursor:
  88. # 1. 获取卡牌信息
  89. query_card = f"SELECT * FROM {settings.DB_CARD_TABLE_NAME} WHERE id = %s"
  90. cursor.execute(query_card, (card_id,))
  91. card_data = cursor.fetchone()
  92. if not card_data:
  93. return None
  94. # 2. 获取主图片 (Card Images)
  95. query_images = f"SELECT * FROM {settings.DB_IMAGE_TABLE_NAME} WHERE card_id = %s"
  96. cursor.execute(query_images, (card_id,))
  97. main_image_records = cursor.fetchall()
  98. # 3. 获取灰度图片 (Gray Images)
  99. query_gray = f"SELECT * FROM {settings.DB_GRAY_IMAGE_TABLE_NAME} WHERE card_id = %s"
  100. cursor.execute(query_gray, (card_id,))
  101. gray_image_records = cursor.fetchall()
  102. # 4. 寻找 Ring 图的数据,用于辅助构建灰度图 JSON
  103. # 建立映射: ImageType -> Record Dict
  104. main_images_map = {rec['image_type']: rec for rec in main_image_records}
  105. final_images_list = []
  106. # 处理主图片,补充全路径
  107. for row in main_image_records:
  108. row['image_path'] = settings.get_full_url(row.get('image_path'))
  109. row['detection_image_path'] = settings.get_full_url(row.get('detection_image_path'))
  110. row['modified_image_path'] = settings.get_full_url(row.get('modified_image_path'))
  111. final_images_list.append(CardImageResponse.model_validate(row))
  112. # 处理 card_gray_images:真灰度图 + ring/stripe 等辅助图(导入时可能落在此表)
  113. for row in gray_image_records:
  114. g_type = row['image_type']
  115. # 主表已有同类型时跳过,避免 images 列表重复
  116. if g_type in main_images_map:
  117. continue
  118. fusion_type = None
  119. if g_type.startswith("front_") and g_type != ImageType.front_gray.value:
  120. fusion_type = ImageType.front_fusion.value
  121. elif g_type.startswith("back_") and g_type != ImageType.back_gray.value:
  122. fusion_type = ImageType.back_fusion.value
  123. if g_type in (ImageType.front_gray.value, ImageType.back_gray.value):
  124. target_ring_type = (
  125. ImageType.front_ring.value
  126. if g_type == ImageType.front_gray.value
  127. else ImageType.back_ring.value
  128. )
  129. virtual_detection_json = copy.deepcopy(EMPTY_DETECTION_JSON)
  130. ring_data = main_images_map.get(target_ring_type)
  131. virtual_modified_json = _construct_gray_image_json(g_type, ring_data)
  132. elif fusion_type and fusion_type in main_images_map:
  133. # ring / stripe 等在辅助表时,JSON 与融合图共用
  134. fusion_row = main_images_map[fusion_type]
  135. virtual_detection_json = fusion_row.get("detection_json") or copy.deepcopy(EMPTY_DETECTION_JSON)
  136. if isinstance(virtual_detection_json, str):
  137. virtual_detection_json = json.loads(virtual_detection_json)
  138. virtual_modified_json = fusion_row.get("modified_json")
  139. if isinstance(virtual_modified_json, str):
  140. virtual_modified_json = json.loads(virtual_modified_json)
  141. else:
  142. virtual_detection_json = copy.deepcopy(EMPTY_DETECTION_JSON)
  143. virtual_modified_json = None
  144. gray_image_dict = {
  145. "id": row['id'],
  146. "card_id": row['card_id'],
  147. "image_type": g_type,
  148. "image_path": settings.get_full_url(row['image_path']),
  149. "created_at": row['created_at'],
  150. "updated_at": row['updated_at'],
  151. "detection_json": virtual_detection_json,
  152. "modified_json": virtual_modified_json,
  153. "image_name": None,
  154. "detection_image_path": None,
  155. "modified_image_path": None,
  156. "is_edited": False,
  157. }
  158. final_images_list.append(CardImageResponse.model_validate(gray_image_dict))
  159. # 5. 获取分数详情 (只基于主图片计算)
  160. # 过滤掉灰度图进行分数计算,防止干扰逻辑
  161. main_images_objs = [img for img in final_images_list if
  162. img.image_type not in [ImageType.front_gray.value, ImageType.back_gray.value, ImageType.front_fusion.value, ImageType.back_fusion.value]]
  163. score_details = calculate_scores_from_images(main_images_objs)
  164. # 6. 对图片列表进行自定义排序(14 类:每面 fusion / gray / ring / stripe1-4)
  165. sort_priority = {
  166. ImageType.back_fusion.value: 0,
  167. ImageType.front_fusion.value: 1,
  168. ImageType.front_gray.value: 2,
  169. ImageType.back_gray.value: 3,
  170. ImageType.front_ring.value: 4,
  171. ImageType.back_ring.value: 5,
  172. ImageType.front_stripe1.value: 6,
  173. ImageType.front_stripe2.value: 7,
  174. ImageType.front_stripe3.value: 8,
  175. ImageType.front_stripe4.value: 9,
  176. ImageType.back_stripe1.value: 10,
  177. ImageType.back_stripe2.value: 11,
  178. ImageType.back_stripe3.value: 12,
  179. ImageType.back_stripe4.value: 13,
  180. ImageType.front_coaxial.value: 14,
  181. ImageType.back_coaxial.value: 15,
  182. }
  183. final_images_list.sort(key=lambda x: sort_priority.get(x.image_type, 999))
  184. card_data.update({
  185. "images": final_images_list, # 包含所有图片
  186. "detection_score": score_details["detection_score"],
  187. "modified_score": score_details["modified_score"],
  188. "detection_score_detail": score_details["detection_score_detail"],
  189. "modified_score_detail": score_details["modified_score_detail"]
  190. })
  191. return card_data
  192. def get_card_list_with_images(
  193. db_conn: PooledMySQLConnection,
  194. card_id: Optional[int],
  195. card_name: Optional[str],
  196. card_type: Optional[CardType],
  197. is_edited: Optional[bool],
  198. min_detect_score: Optional[float],
  199. max_detect_score: Optional[float],
  200. min_mod_score: Optional[float],
  201. max_mod_score: Optional[float],
  202. created_start: Optional[date],
  203. created_end: Optional[date],
  204. updated_start: Optional[date],
  205. updated_end: Optional[date],
  206. sort_by: SortBy,
  207. sort_order: SortOrder,
  208. skip: int,
  209. limit: int
  210. ) -> List[Dict[str, Any]]:
  211. # 此函数逻辑主要是列表展示,不需要复杂的 JSON 构造,
  212. # 只需要把灰度图的路径也带出来即可。
  213. with db_conn.cursor(dictionary=True) as cursor:
  214. query = f"SELECT * FROM {settings.DB_CARD_TABLE_NAME}"
  215. conditions = []
  216. params = []
  217. if card_id is not None: conditions.append("id = %s"); params.append(card_id)
  218. if card_name: conditions.append("card_name LIKE %s"); params.append(f"%{card_name}%")
  219. if card_type: conditions.append("card_type = %s"); params.append(card_type.value)
  220. if is_edited is not None: conditions.append("is_edited = %s"); params.append(is_edited)
  221. if min_detect_score is not None: conditions.append("detection_score >= %s"); params.append(min_detect_score)
  222. if max_detect_score is not None: conditions.append("detection_score <= %s"); params.append(max_detect_score)
  223. if min_mod_score is not None: conditions.append("modified_score >= %s"); params.append(min_mod_score)
  224. if max_mod_score is not None: conditions.append("modified_score <= %s"); params.append(max_mod_score)
  225. if created_start: conditions.append("DATE(created_at) >= %s"); params.append(created_start)
  226. if created_end: conditions.append("DATE(created_at) <= %s"); params.append(created_end)
  227. if updated_start: conditions.append("DATE(updated_at) >= %s"); params.append(updated_start)
  228. if updated_end: conditions.append("DATE(updated_at) <= %s"); params.append(updated_end)
  229. if conditions: query += " WHERE " + " AND ".join(conditions)
  230. query += f" ORDER BY {sort_by.value} {sort_order.value}, id DESC"
  231. query += " LIMIT %s OFFSET %s"
  232. params.extend([limit, skip])
  233. cursor.execute(query, tuple(params))
  234. cards = cursor.fetchall()
  235. if not cards:
  236. return []
  237. card_ids = [card['id'] for card in cards]
  238. format_strings = ','.join(['%s'] * len(card_ids))
  239. # 1. 查询主图片
  240. image_query = (
  241. f"SELECT id, card_id, image_type, image_path, detection_image_path, modified_image_path "
  242. f"FROM {settings.DB_IMAGE_TABLE_NAME} WHERE card_id IN ({format_strings})"
  243. )
  244. cursor.execute(image_query, tuple(card_ids))
  245. images = cursor.fetchall()
  246. # 2. 查询灰度图片
  247. gray_query = (
  248. f"SELECT id, card_id, image_type, image_path "
  249. f"FROM {settings.DB_GRAY_IMAGE_TABLE_NAME} WHERE card_id IN ({format_strings})"
  250. )
  251. cursor.execute(gray_query, tuple(card_ids))
  252. gray_images = cursor.fetchall()
  253. # 分组
  254. images_by_card_id = {}
  255. for img in images:
  256. cid = img['card_id']
  257. if cid not in images_by_card_id: images_by_card_id[cid] = []
  258. images_by_card_id[cid].append(img)
  259. for g_img in gray_images:
  260. cid = g_img['card_id']
  261. if cid not in images_by_card_id: images_by_card_id[cid] = []
  262. # 补齐字段结构以便前端统一处理
  263. g_img['detection_image_path'] = None
  264. g_img['modified_image_path'] = None
  265. images_by_card_id[cid].append(g_img)
  266. # 附加到卡牌
  267. for card in cards:
  268. card['image_path_list'] = {}
  269. card['detection_image_path_list'] = {}
  270. card['modified_image_path_list'] = {}
  271. related_images = images_by_card_id.get(card['id'], [])
  272. for image_data in related_images:
  273. image_type = image_data['image_type']
  274. if image_type:
  275. card['image_path_list'][image_type] = settings.get_full_url(image_data.get('image_path'))
  276. card['detection_image_path_list'][image_type] = settings.get_full_url(
  277. image_data.get('detection_image_path'))
  278. card['modified_image_path_list'][image_type] = settings.get_full_url(
  279. image_data.get('modified_image_path'))
  280. return cards
  281. def get_card_list_and_count(
  282. db_conn: PooledMySQLConnection,
  283. card_id: Optional[int],
  284. cardNo: Optional[str],
  285. card_name: Optional[str],
  286. card_type: Optional[CardType],
  287. is_edited: Optional[bool],
  288. review_state: Optional[int],
  289. min_detect_score: Optional[float],
  290. max_detect_score: Optional[float],
  291. min_mod_score: Optional[float],
  292. max_mod_score: Optional[float],
  293. created_start: Optional[date],
  294. created_end: Optional[date],
  295. updated_start: Optional[date],
  296. updated_end: Optional[date],
  297. sort_by: SortBy,
  298. sort_order: SortOrder,
  299. skip: int,
  300. limit: int,
  301. permission_user_id: Optional[str] = None,
  302. bound_user_id: Optional[str] = None
  303. ) -> Dict[str, Any]:
  304. with db_conn.cursor(dictionary=True) as cursor:
  305. conditions = []
  306. params = []
  307. if card_id is not None: conditions.append("id = %s"); params.append(card_id)
  308. if cardNo: conditions.append("cardNo LIKE %s"); params.append(f"%{cardNo}%")
  309. if card_name: conditions.append("card_name LIKE %s"); params.append(f"%{card_name}%")
  310. if card_type: conditions.append("card_type = %s"); params.append(card_type.value)
  311. if is_edited is not None: conditions.append("is_edited = %s"); params.append(is_edited)
  312. if review_state is not None: conditions.append("review_state = %s"); params.append(review_state)
  313. if min_detect_score is not None: conditions.append("detection_score >= %s"); params.append(min_detect_score)
  314. if max_detect_score is not None: conditions.append("detection_score <= %s"); params.append(max_detect_score)
  315. if min_mod_score is not None: conditions.append("modified_score >= %s"); params.append(min_mod_score)
  316. if max_mod_score is not None: conditions.append("modified_score <= %s"); params.append(max_mod_score)
  317. if created_start: conditions.append("DATE(created_at) >= %s"); params.append(created_start)
  318. if created_end: conditions.append("DATE(created_at) <= %s"); params.append(created_end)
  319. if updated_start: conditions.append("DATE(updated_at) >= %s"); params.append(updated_start)
  320. if updated_end: conditions.append("DATE(updated_at) <= %s"); params.append(updated_end)
  321. if permission_user_id is not None:
  322. conditions.append(
  323. f"id IN (SELECT card_id FROM `{settings.DB_USER_CARD_TABLE_NAME}` WHERE user_id = %s)"
  324. )
  325. params.append(permission_user_id)
  326. where_clause = ""
  327. if conditions: where_clause = " WHERE " + " AND ".join(conditions)
  328. # Count
  329. count_query = f"SELECT COUNT(*) as total FROM {settings.DB_CARD_TABLE_NAME}" + where_clause
  330. cursor.execute(count_query, tuple(params))
  331. total_count = cursor.fetchone()['total']
  332. # List
  333. data_query = f"SELECT * FROM {settings.DB_CARD_TABLE_NAME}" + where_clause
  334. data_query += f" ORDER BY {sort_by.value} {sort_order.value}, id DESC"
  335. data_query += " LIMIT %s OFFSET %s"
  336. data_params = params.copy()
  337. data_params.extend([limit, skip])
  338. cursor.execute(data_query, tuple(data_params))
  339. cards = cursor.fetchall()
  340. if cards:
  341. card_ids = [card['id'] for card in cards]
  342. format_strings = ','.join(['%s'] * len(card_ids))
  343. bound_card_ids = set()
  344. if bound_user_id is not None:
  345. # 只标记当前页卡片是否绑定到指定外部用户,不影响原有列表筛选逻辑。
  346. bound_query = (
  347. f"SELECT card_id FROM `{settings.DB_USER_CARD_TABLE_NAME}` "
  348. f"WHERE user_id = %s AND card_id IN ({format_strings})"
  349. )
  350. cursor.execute(bound_query, tuple([bound_user_id] + card_ids))
  351. bound_card_ids = {row['card_id'] for row in cursor.fetchall()}
  352. # 主图
  353. image_query = (
  354. f"SELECT id, card_id, image_type, image_path, detection_image_path, modified_image_path "
  355. f"FROM {settings.DB_IMAGE_TABLE_NAME} WHERE card_id IN ({format_strings})"
  356. )
  357. cursor.execute(image_query, tuple(card_ids))
  358. images = cursor.fetchall()
  359. # [NEW] 灰度图
  360. gray_query = (
  361. f"SELECT id, card_id, image_type, image_path "
  362. f"FROM {settings.DB_GRAY_IMAGE_TABLE_NAME} WHERE card_id IN ({format_strings})"
  363. )
  364. cursor.execute(gray_query, tuple(card_ids))
  365. gray_images = cursor.fetchall()
  366. images_by_card_id = {}
  367. for img in images:
  368. cid = img['card_id']
  369. if cid not in images_by_card_id: images_by_card_id[cid] = []
  370. images_by_card_id[cid].append(img)
  371. # 混入灰度图
  372. for g_img in gray_images:
  373. cid = g_img['card_id']
  374. if cid not in images_by_card_id: images_by_card_id[cid] = []
  375. g_img['detection_image_path'] = None
  376. g_img['modified_image_path'] = None
  377. images_by_card_id[cid].append(g_img)
  378. for card in cards:
  379. card['is_bound'] = card['id'] in bound_card_ids
  380. card['image_path_list'] = {}
  381. card['detection_image_path_list'] = {}
  382. card['modified_image_path_list'] = {}
  383. related_images = images_by_card_id.get(card['id'], [])
  384. for image_data in related_images:
  385. image_type = image_data['image_type']
  386. if image_type:
  387. card['image_path_list'][image_type] = settings.get_full_url(image_data.get('image_path'))
  388. card['detection_image_path_list'][image_type] = settings.get_full_url(
  389. image_data.get('detection_image_path'))
  390. card['modified_image_path_list'][image_type] = settings.get_full_url(
  391. image_data.get('modified_image_path'))
  392. return {
  393. "total": total_count,
  394. "list": cards
  395. }