1
0

crud_card.py 20 KB

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