images.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  1. import os
  2. import uuid
  3. import json
  4. import requests
  5. import io
  6. from app.core.minio_client import minio_client
  7. from typing import Optional, Dict, Any
  8. from fastapi import APIRouter, File, UploadFile, Depends, HTTPException, Form, Path
  9. from fastapi.concurrency import run_in_threadpool
  10. from fastapi.responses import JSONResponse, FileResponse
  11. from mysql.connector.pooling import PooledMySQLConnection
  12. from mysql.connector import IntegrityError
  13. from app.core.config import settings
  14. from app.core.logger import get_logger
  15. from app.utils.scheme import CardImageResponse, ImageJsonPairResponse, ResultImagePathType
  16. from app.utils.scheme import ImageType, IMAGE_TYPE_TO_SCORE_TYPE
  17. from app.core.database_loader import get_db_connection
  18. from app.crud import crud_card
  19. logger = get_logger(__name__)
  20. router = APIRouter()
  21. db_dependency = Depends(get_db_connection)
  22. @router.post("/insert/{card_id}", response_model=CardImageResponse, status_code=201,
  23. summary="为卡牌上传并关联一张主要图片")
  24. async def upload_image_for_card(
  25. card_id: int = Path(..., description="要关联的卡牌ID"),
  26. image_type: ImageType = Form(..., description="图片类型"),
  27. image: UploadFile = File(..., description="图片文件"),
  28. image_name: Optional[str] = Form(None, description="图片的可选名称"),
  29. json_data_str: str = Form(..., description="与图片关联的JSON字符串"),
  30. db_conn: PooledMySQLConnection = db_dependency
  31. ):
  32. """
  33. 上传一张主要图片 (coaxial/ring)。
  34. """
  35. # 校验:此接口只能传主图类型
  36. if image_type in [ImageType.front_gray, ImageType.back_gray]:
  37. raise HTTPException(status_code=400, detail="此接口不支持灰度图上传,请使用 /insert/gray/{card_id}")
  38. try:
  39. detection_json = json.loads(json_data_str)
  40. except json.JSONDecodeError:
  41. raise HTTPException(status_code=400, detail="JSON格式无效。")
  42. file_extension = os.path.splitext(image.filename)[1]
  43. unique_filename = f"{uuid.uuid4()}{file_extension}"
  44. relative_path = f"/Data/{unique_filename}"
  45. object_name = f"{settings.MINIO_BASE_PREFIX}{relative_path}"
  46. try:
  47. # 写入 MinIO 存储
  48. file_bytes = await image.read()
  49. minio_client.put_object(
  50. settings.MINIO_BUCKET,
  51. object_name,
  52. io.BytesIO(file_bytes),
  53. len(file_bytes),
  54. content_type=image.content_type or "image/jpeg"
  55. )
  56. except Exception as e:
  57. logger.error(f"保存图片到MinIO失败: {e}")
  58. raise HTTPException(status_code=500, detail="无法保存图片文件。")
  59. cursor = None
  60. try:
  61. cursor = db_conn.cursor()
  62. cursor.execute(f"SELECT id FROM {settings.DB_CARD_TABLE_NAME} WHERE id = %s", (card_id,))
  63. if not cursor.fetchone():
  64. raise HTTPException(status_code=404, detail=f"ID为 {card_id} 的卡牌不存在。")
  65. query_insert_image = (
  66. f"INSERT INTO {settings.DB_IMAGE_TABLE_NAME} "
  67. "(card_id, image_type, image_name, image_path, detection_json) "
  68. "VALUES (%s, %s, %s, %s, %s)"
  69. )
  70. params = (
  71. card_id, image_type.value, image_name, relative_path, json.dumps(detection_json, ensure_ascii=False))
  72. cursor.execute(query_insert_image, params)
  73. new_id = cursor.lastrowid
  74. db_conn.commit()
  75. logger.info(f"图片 {new_id} 已成功关联到卡牌 {card_id},类型为 {image_type.value}。")
  76. try:
  77. crud_card.update_card_scores_and_status(db_conn, card_id)
  78. except Exception as score_update_e:
  79. logger.error(f"更新卡牌 {card_id} 分数失败: {score_update_e}")
  80. cursor.execute(f"SELECT * FROM {settings.DB_IMAGE_TABLE_NAME} WHERE id = %s", (new_id,))
  81. new_image_data = cursor.fetchone()
  82. columns = [desc[0] for desc in cursor.description]
  83. row_dict = dict(zip(columns, new_image_data))
  84. # 返回完整url
  85. row_dict['image_path'] = settings.get_full_url(row_dict.get('image_path'))
  86. row_dict['detection_image_path'] = settings.get_full_url(row_dict.get('detection_image_path'))
  87. row_dict['modified_image_path'] = settings.get_full_url(row_dict.get('modified_image_path'))
  88. return CardImageResponse.model_validate(dict(zip(columns, new_image_data)))
  89. except IntegrityError as e:
  90. db_conn.rollback()
  91. # 清理已上传到 MinIO 的文件
  92. try:
  93. minio_client.remove_object(settings.MINIO_BUCKET, object_name)
  94. except:
  95. pass
  96. if e.errno == 1062:
  97. raise HTTPException(status_code=409, detail=f"卡牌ID {card_id} 已存在...")
  98. raise HTTPException(status_code=500, detail="数据库操作失败。")
  99. except Exception as e:
  100. db_conn.rollback()
  101. try:
  102. minio_client.remove_object(settings.MINIO_BUCKET, object_name)
  103. except:
  104. pass
  105. logger.error(f"关联图片到卡牌失败: {e}")
  106. if isinstance(e, HTTPException): raise e
  107. raise HTTPException(status_code=500, detail="数据库操作失败。")
  108. finally:
  109. if cursor: cursor.close()
  110. @router.post("/insert/gray/{card_id}", response_model=CardImageResponse, status_code=201,
  111. summary="[NEW] 为卡牌上传辅助灰度图")
  112. async def upload_gray_image_for_card(
  113. card_id: int = Path(..., description="要关联的卡牌ID"),
  114. image_type: ImageType = Form(..., description="图片类型 (必须是 front_gray 或 back_gray)"),
  115. image: UploadFile = File(..., description="灰度图片文件"),
  116. db_conn: PooledMySQLConnection = db_dependency
  117. ):
  118. """
  119. 上传辅助灰度图 (front_gray / back_gray)。
  120. 不需要 JSON 数据,不参与直接计算。
  121. """
  122. if image_type not in [ImageType.front_gray, ImageType.back_gray]:
  123. raise HTTPException(status_code=400, detail="此接口仅支持灰度图 (front_gray, back_gray)")
  124. # 1. 保存文件
  125. file_extension = os.path.splitext(image.filename)[1]
  126. unique_filename = f"gray_{uuid.uuid4()}{file_extension}" # 加个前缀区分
  127. relative_path = f"/Data/{unique_filename}"
  128. object_name = f"{settings.MINIO_BASE_PREFIX}{relative_path}"
  129. try:
  130. # 写入 MinIO 存储
  131. file_bytes = await image.read()
  132. minio_client.put_object(
  133. settings.MINIO_BUCKET,
  134. object_name,
  135. io.BytesIO(file_bytes),
  136. len(file_bytes),
  137. content_type=image.content_type or "image/jpeg"
  138. )
  139. except Exception as e:
  140. logger.error(f"保存图片到MinIO失败: {e}")
  141. raise HTTPException(status_code=500, detail="无法保存图片文件。")
  142. cursor = None
  143. try:
  144. cursor = db_conn.cursor()
  145. # 2. 检查卡牌存在
  146. cursor.execute(f"SELECT id FROM {settings.DB_CARD_TABLE_NAME} WHERE id = %s", (card_id,))
  147. if not cursor.fetchone():
  148. raise HTTPException(status_code=404, detail=f"ID为 {card_id} 的卡牌不存在。")
  149. # 3. 插入数据 (card_gray_images 表)
  150. query_insert = (
  151. f"INSERT INTO {settings.DB_GRAY_IMAGE_TABLE_NAME} "
  152. "(card_id, image_type, image_path) VALUES (%s, %s, %s)"
  153. )
  154. cursor.execute(query_insert, (card_id, image_type.value, relative_path))
  155. new_id = cursor.lastrowid
  156. db_conn.commit()
  157. logger.info(f"灰度图 {new_id} 已关联到卡牌 {card_id}, 类型 {image_type.value}")
  158. # 4. 构造返回 (模拟 CardImageResponse 结构)
  159. # 因为数据库里只有基础字段,这里要补全 Pydantic 模型需要的字段
  160. cursor.execute(f"SELECT * FROM {settings.DB_GRAY_IMAGE_TABLE_NAME} WHERE id = %s", (new_id,))
  161. new_data = cursor.fetchone() # tuple
  162. # 获取列名
  163. columns = [desc[0] for desc in cursor.description]
  164. row_dict = dict(zip(columns, new_data))
  165. # 补全空字段以符合 CardImageResponse
  166. from app.crud.crud_card import EMPTY_DETECTION_JSON
  167. response_dict = {
  168. **row_dict,
  169. "image_path": settings.get_full_url(row_dict.get('image_path')),
  170. "detection_json": EMPTY_DETECTION_JSON, # 默认死值
  171. "modified_json": None, # 刚上传还没有 modified
  172. "image_name": None,
  173. "detection_image_path": None,
  174. "modified_image_path": None,
  175. "is_edited": False
  176. }
  177. return CardImageResponse.model_validate(response_dict)
  178. except IntegrityError as e:
  179. db_conn.rollback()
  180. # 清理已上传到 MinIO 的文件
  181. try:
  182. minio_client.remove_object(settings.MINIO_BUCKET, object_name)
  183. except:
  184. pass
  185. if e.errno == 1062:
  186. raise HTTPException(status_code=409, detail=f"卡牌ID {card_id} 已存在...")
  187. raise HTTPException(status_code=500, detail="数据库操作失败。")
  188. except Exception as e:
  189. db_conn.rollback()
  190. try:
  191. minio_client.remove_object(settings.MINIO_BUCKET, object_name)
  192. except:
  193. pass
  194. logger.error(f"关联图片到卡牌失败: {e}")
  195. if isinstance(e, HTTPException): raise e
  196. raise HTTPException(status_code=500, detail="数据库操作失败。")
  197. finally:
  198. if cursor: cursor.close()
  199. @router.get("/jsons/{id}", response_model=ImageJsonPairResponse, summary="获取图片的原始和修改后JSON")
  200. def get_image_jsons(id: int, db_conn: PooledMySQLConnection = db_dependency):
  201. # 此接口主要用于主图,灰度图没有实体的 JSON 存储,暂不支持直接通过此 ID 查询 JSON
  202. # 如果前端通过 format_xy 里的 query 接口获取,已经能在 list 里拿到了。
  203. cursor = None
  204. try:
  205. cursor = db_conn.cursor(dictionary=True)
  206. query = f"SELECT id, detection_json, modified_json FROM {settings.DB_IMAGE_TABLE_NAME} WHERE id = %s"
  207. cursor.execute(query, (id,))
  208. result = cursor.fetchone()
  209. if not result:
  210. raise HTTPException(status_code=404, detail=f"ID为 {id} 的图片未找到 (仅支持查询主图)。")
  211. return ImageJsonPairResponse.model_validate(result)
  212. except Exception as e:
  213. logger.error(f"获取JSON对失败 ({id}): {e}")
  214. if isinstance(e, HTTPException): raise e
  215. raise HTTPException(status_code=500, detail="数据库查询失败。")
  216. finally:
  217. if cursor: cursor.close()