crud_card.py 24 KB

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