cards.py 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. from datetime import datetime
  2. import os
  3. from typing import Optional, List
  4. from fastapi import APIRouter, Depends, HTTPException, Query
  5. from mysql.connector.pooling import PooledMySQLConnection
  6. from app.core.config import settings
  7. from app.core.logger import get_logger
  8. from app.core.database_loader import get_db_connection
  9. from app.utils.scheme import CardDetailResponse, CardImageResponse, CardListDetailResponse
  10. logger = get_logger(__name__)
  11. router = APIRouter()
  12. db_dependency = Depends(get_db_connection)
  13. @router.post("/created", response_model=CardDetailResponse, status_code=201, summary="创建一个新的卡牌记录")
  14. def create_card(
  15. card_name: Optional[str] = Query(None, summary="卡牌的名称"),
  16. db_conn: PooledMySQLConnection = db_dependency
  17. ):
  18. """创建一个新的卡牌实体,此时它不关联任何图片。"""
  19. cursor = None
  20. try:
  21. cursor = db_conn.cursor()
  22. query = f"INSERT INTO {settings.DB_CARD_TABLE_NAME} (card_name) VALUES (%s)"
  23. cursor.execute(query, (card_name,))
  24. db_conn.commit()
  25. new_id = cursor.lastrowid
  26. logger.info(f"新卡牌已创建, ID: {new_id}")
  27. # 返回刚创建的空卡牌信息
  28. return CardDetailResponse(
  29. id=new_id,
  30. card_name=card_name,
  31. created_at=datetime.now(),
  32. updated_at=datetime.now(),
  33. images=[]
  34. )
  35. except Exception as e:
  36. db_conn.rollback()
  37. logger.error(f"创建卡牌失败: {e}")
  38. raise HTTPException(status_code=500, detail="数据库插入失败。")
  39. finally:
  40. if cursor:
  41. cursor.close()
  42. @router.get("/query/{id}", response_model=CardDetailResponse, summary="获取指定卡牌的详细信息")
  43. def get_card_details(id: int, db_conn: PooledMySQLConnection = db_dependency):
  44. """获取卡牌元数据以及所有与之关联的图片信息。"""
  45. cursor = None
  46. try:
  47. cursor = db_conn.cursor(dictionary=True)
  48. # 1. 获取卡牌信息
  49. query_card = f"SELECT * FROM {settings.DB_CARD_TABLE_NAME} WHERE id = %s"
  50. cursor.execute(query_card, (id,))
  51. card_data = cursor.fetchone()
  52. if not card_data:
  53. raise HTTPException(status_code=404, detail=f"ID为 {id} 的卡牌未找到。")
  54. # 2. 获取所有关联的图片信息
  55. query_images = f"SELECT * FROM {settings.DB_IMAGE_TABLE_NAME} WHERE card_id = %s"
  56. cursor.execute(query_images, (id,))
  57. image_records = cursor.fetchall()
  58. images = [CardImageResponse.model_validate(row) for row in image_records]
  59. # 计算总分数(只有当图片数量为 4 时才计算)
  60. # 初始化
  61. card_data["detection_score"] = None
  62. card_data["modified_score"] = None
  63. if len(images) == 4:
  64. try:
  65. # ---------- detection_score ----------
  66. detection_score = 10.0
  67. for img in images:
  68. try:
  69. add_val = img.detection_json.get("result", {}).get("_used_compute_deduct_score", 0)
  70. detection_score += float(add_val or 0)
  71. except Exception as e:
  72. logger.warning(f"解析 detection_json 分数失败 (image_id={img.id}): {e}")
  73. card_data["detection_score"] = detection_score
  74. # ---------- modified_score ----------
  75. all_modified_none = all(img.modified_json is None for img in images)
  76. if not all_modified_none:
  77. modified_score = 10.0
  78. for img in images:
  79. src = img.modified_json if img.modified_json is not None else img.detection_json
  80. try:
  81. add_val = src.get("result", {}).get("_used_compute_deduct_score", 0)
  82. modified_score += float(add_val or 0)
  83. except Exception as e:
  84. logger.warning(f"解析 modified_json 分数失败 (image_id={img.id}): {e}")
  85. card_data["modified_score"] = modified_score
  86. else:
  87. card_data["modified_score"] = None
  88. except Exception as e:
  89. logger.error(f"计算分数过程异常: {e}")
  90. # 组合成最终响应
  91. card_response = CardDetailResponse.model_validate(card_data)
  92. card_response.images = images
  93. return card_response
  94. except Exception as e:
  95. logger.error(f"查询卡牌详情失败 ({id}): {e}")
  96. if isinstance(e, HTTPException): raise e
  97. raise HTTPException(status_code=500, detail="数据库查询失败。")
  98. finally:
  99. if cursor:
  100. cursor.close()
  101. @router.get("/card_list", response_model=List[CardListDetailResponse], summary="获取卡牌列表")
  102. def list_cards_detailed(
  103. start_id: Optional[int] = Query(None, description="筛选条件:起始 card_id"),
  104. end_id: Optional[int] = Query(None, description="筛选条件:结束 card_id"),
  105. skip: int = Query(0, ge=0, description="分页:跳过的记录数"),
  106. limit: int = Query(100, ge=1, le=1000, description="分页:每页的记录数"),
  107. db_conn: PooledMySQLConnection = db_dependency
  108. ):
  109. """
  110. 获取卡牌的基础信息列表,支持按 id 范围筛选和分页。
  111. """
  112. cursor = None
  113. try:
  114. cursor = db_conn.cursor(dictionary=True)
  115. base_query = f"SELECT id, card_name, created_at, updated_at FROM {settings.DB_CARD_TABLE_NAME}"
  116. conditions = []
  117. params = []
  118. if start_id is not None:
  119. conditions.append("id >= %s")
  120. params.append(start_id)
  121. if end_id is not None:
  122. conditions.append("id <= %s")
  123. params.append(end_id)
  124. if conditions:
  125. base_query += " WHERE " + " AND ".join(conditions)
  126. base_query += " ORDER BY id DESC LIMIT %s OFFSET %s"
  127. params.extend([limit, skip])
  128. cursor.execute(base_query, tuple(params))
  129. results = cursor.fetchall()
  130. return [CardListDetailResponse.model_validate(row) for row in results]
  131. except Exception as e:
  132. logger.error(f"查询卡牌列表失败: {e}")
  133. raise HTTPException(status_code=500, detail="获取数据列表失败。")
  134. finally:
  135. if cursor:
  136. cursor.close()
  137. @router.delete("/delete/{id}", status_code=200, summary="删除卡牌及其所有关联图片")
  138. def delete_card(id: int, db_conn: PooledMySQLConnection = db_dependency):
  139. """
  140. 删除一张卡牌及其所有关联的图片记录和物理文件。
  141. 利用了数据库的 ON DELETE CASCADE 特性。
  142. """
  143. cursor = None
  144. try:
  145. cursor = db_conn.cursor()
  146. # 1. 查询所有关联图片的物理文件路径,以便稍后删除
  147. query_paths = f"SELECT image_path FROM {settings.DB_IMAGE_TABLE_NAME} WHERE card_id = %s"
  148. cursor.execute(query_paths, (id,))
  149. image_paths_to_delete = [row[0] for row in cursor.fetchall()]
  150. # 2. 删除卡牌记录。数据库会自动级联删除 card_images 表中的相关记录
  151. query_delete_card = f"DELETE FROM {settings.DB_CARD_TABLE_NAME} WHERE id = %s"
  152. cursor.execute(query_delete_card, (id,))
  153. if cursor.rowcount == 0:
  154. raise HTTPException(status_code=404, detail=f"ID为 {id} 的卡牌未找到。")
  155. # 3. 删除物理文件
  156. for path in image_paths_to_delete:
  157. absolute_path = settings.BASE_PATH / path.lstrip('/\\')
  158. if os.path.exists(absolute_path):
  159. try:
  160. os.remove(absolute_path)
  161. logger.info(f"图片文件已删除: {absolute_path}")
  162. except OSError as e:
  163. logger.error(f"删除文件失败 {absolute_path}: {e}")
  164. db_conn.commit()
  165. logger.info(f"ID {id} 的卡牌和关联数据已成功删除。")
  166. return {"message": f"成功删除卡牌 ID {id} 及其所有关联数据"}
  167. except Exception as e:
  168. db_conn.rollback()
  169. logger.error(f"删除卡牌失败 ({id}): {e}")
  170. if isinstance(e, HTTPException): raise e
  171. raise HTTPException(status_code=500, detail="删除卡牌失败。")
  172. finally:
  173. if cursor:
  174. cursor.close()