Просмотр исходного кода

上传json接口update前计算分数

AnlaAnla 3 месяцев назад
Родитель
Сommit
57f1494c39
5 измененных файлов с 103 добавлено и 9 удалено
  1. 1 0
      .idea/encodings.xml
  2. 6 4
      Test/img_data_insert.py
  3. 3 3
      Test/test01.py
  4. 89 2
      app/api/images.py
  5. 4 0
      app/core/config.py

+ 1 - 0
.idea/encodings.xml

@@ -1,6 +1,7 @@
 <?xml version="1.0" encoding="UTF-8"?>
 <?xml version="1.0" encoding="UTF-8"?>
 <project version="4">
 <project version="4">
   <component name="Encoding">
   <component name="Encoding">
+    <file url="file://$PROJECT_DIR$/Test/img_data_insert.py" charset="UTF-8" />
     <file url="file://$PROJECT_DIR$/Test/test01.py" charset="GBK" />
     <file url="file://$PROJECT_DIR$/Test/test01.py" charset="GBK" />
     <file url="file://$PROJECT_DIR$/app/api/cards.py" charset="UTF-8" />
     <file url="file://$PROJECT_DIR$/app/api/cards.py" charset="UTF-8" />
     <file url="file://$PROJECT_DIR$/app/api/images.py" charset="UTF-8" />
     <file url="file://$PROJECT_DIR$/app/api/images.py" charset="UTF-8" />

+ 6 - 4
Test/img_data_insert.py

@@ -45,9 +45,7 @@ def upload_image_with_json(
     return response
     return response
 
 
 
 
-def send4img():
-    send_url = "http://192.168.31.243:7745/api/images/insert/1"
-
+def send4img(send_url):
 
 
     front_face_img_path = r"C:\Code\ML\Project\CheckCardBoxAndDefectServer\_temp_work\test\正面面\rectify_center_img.jpg"
     front_face_img_path = r"C:\Code\ML\Project\CheckCardBoxAndDefectServer\_temp_work\test\正面面\rectify_center_img.jpg"
     front_face_json_path = r"C:\Code\ML\Project\CheckCardBoxAndDefectServer\_temp_work\test\正面面\front_face_score.json"
     front_face_json_path = r"C:\Code\ML\Project\CheckCardBoxAndDefectServer\_temp_work\test\正面面\front_face_score.json"
@@ -79,7 +77,11 @@ def send4img():
 
 
 
 
 if __name__ == "__main__":
 if __name__ == "__main__":
-    send4img()
+    # send_url = "http://127.0.0.1:7745/api/images/insert/9"
+    send_url = "http://192.168.31.243:7745/api/images/insert/3"
+
+    send4img(send_url)
+
     # resp = upload_image_with_json(
     # resp = upload_image_with_json(
     #     url="http://127.0.0.1:7745/api/images/insert/6",
     #     url="http://127.0.0.1:7745/api/images/insert/6",
     #     image_path="v2-28c2dced87172b004d40eedc38e7889a_b.gif",
     #     image_path="v2-28c2dced87172b004d40eedc38e7889a_b.gif",

+ 3 - 3
Test/test01.py

@@ -1,7 +1,5 @@
 import requests
 import requests
 
 
-# base_url = 'http://127.0.0.1:7745/api/cards/query/7'
-base_url = 'http://192.168.31.243:7745/api/cards/query/1'
 
 
 
 
 def send(url):
 def send(url):
@@ -12,7 +10,7 @@ def send(url):
 
 
     try:
     try:
         # 发送 GET 请求
         # 发送 GET 请求
-        response = requests.get(base_url, headers=headers)
+        response = requests.get(url, headers=headers)
 
 
         # 检查响应状态码
         # 检查响应状态码
         response.raise_for_status()
         response.raise_for_status()
@@ -36,4 +34,6 @@ def send(url):
 
 
 
 
 if __name__ == '__main__':
 if __name__ == '__main__':
+    # base_url = 'http://127.0.0.1:7745/api/cards/query/9'
+    base_url = 'http://192.168.31.243:7745/api/cards/query/3'
     send(base_url)
     send(base_url)

+ 89 - 2
app/api/images.py

@@ -1,9 +1,11 @@
 import os
 import os
 import uuid
 import uuid
 import json
 import json
+import requests
 from typing import Optional, Dict, Any
 from typing import Optional, Dict, Any
 from enum import Enum
 from enum import Enum
 from fastapi import APIRouter, File, UploadFile, Depends, HTTPException, Form, Path
 from fastapi import APIRouter, File, UploadFile, Depends, HTTPException, Form, Path
+from fastapi.concurrency import run_in_threadpool
 from fastapi.responses import JSONResponse, FileResponse
 from fastapi.responses import JSONResponse, FileResponse
 from mysql.connector.pooling import PooledMySQLConnection
 from mysql.connector.pooling import PooledMySQLConnection
 from mysql.connector import IntegrityError
 from mysql.connector import IntegrityError
@@ -25,6 +27,15 @@ class ImageType(str, Enum):
     back_edge = "back_edge"
     back_edge = "back_edge"
 
 
 
 
+# "图片类型和计算分数分数类型映射表"
+IMAGE_TYPE_TO_SCORE_TYPE = {
+    "front_face": "front_face",
+    "back_face": "back_face",
+    "front_edge": "front_corner_edge",
+    "back_edge": "back_corner_edge",
+}
+
+
 @router.post("/insert/{card_id}", response_model=CardImageResponse, status_code=201,
 @router.post("/insert/{card_id}", response_model=CardImageResponse, status_code=201,
              summary="为卡牌上传并关联一张图片")
              summary="为卡牌上传并关联一张图片")
 async def upload_image_for_card(
 async def upload_image_for_card(
@@ -128,8 +139,84 @@ def get_image_jsons(id: int, db_conn: PooledMySQLConnection = db_dependency):
             cursor.close()
             cursor.close()
 
 
 
 
-@router.put("/update/json/{id}", status_code=200, summary="修改图片的 modified_json")
-def update_image_modified_json(
+@router.put("/update/json/{id}", status_code=200, summary="重新计算分数, 并修改图片的 modified_json")
+async def update_image_modified_json(
+        id: int,
+        new_json_data: dict,
+        db_conn: PooledMySQLConnection = db_dependency
+):
+    """
+    根据 id 获取 image_type, 调用外部接口重新计算分数, 并更新 modified_json。
+    updated_at 会自动更新
+    """
+    cursor = None
+    try:
+        cursor = db_conn.cursor(dictionary=True)
+
+        # 1️ 获取图片信息
+        cursor.execute(f"SELECT image_type FROM {settings.DB_IMAGE_TABLE_NAME} WHERE id = %s", (id,))
+        row = cursor.fetchone()
+        if not row:
+            raise HTTPException(status_code=404, detail=f"ID为 {id} 的图片未找到。")
+
+        image_type = row["image_type"]
+        score_type = IMAGE_TYPE_TO_SCORE_TYPE.get(image_type)
+        if not score_type:
+            raise HTTPException(status_code=400, detail=f"未知的 image_type: {image_type}")
+
+        # 2️ 调用远程计算接口
+        try:
+            params = {"score_type": score_type}
+            payload = new_json_data
+            response = await run_in_threadpool(
+                lambda: requests.post(
+                    settings.SCORE_RECALCULATE_ENDPOINT,
+                    params=params,
+                    json=payload,
+                    timeout=30
+                )
+            )
+        except Exception as e:
+            raise HTTPException(status_code=500, detail=f"调用分数计算服务失败: {e}")
+
+        if response.status_code != 200:
+            logger.error(f"分数计算接口返回错误: {response.status_code}, {response.text}")
+            raise HTTPException(status_code=response.status_code,
+                                detail=f"分数计算接口返回错误: {response.text}")
+
+        recalculated_json = response.json()
+
+        # 3️ 保存结果到数据库
+        recalculated_json_str = json.dumps(recalculated_json, ensure_ascii=False)
+        update_query = f"UPDATE {settings.DB_IMAGE_TABLE_NAME} SET modified_json = %s WHERE id = %s"
+        cursor.execute(update_query, (recalculated_json_str, id))
+
+        if cursor.rowcount == 0:
+            raise HTTPException(status_code=404, detail=f"未找到ID {id} 的记录。")
+
+        db_conn.commit()
+        logger.info(f"图片ID {id} 的 modified_json 已更新并重新计算。")
+
+        return {
+            "message": f"成功更新图片ID {id} 的JSON数据",
+            "image_type": image_type,
+            "score_type": score_type
+        }
+
+    except HTTPException:
+        db_conn.rollback()
+        raise
+    except Exception as e:
+        db_conn.rollback()
+        logger.error(f"更新JSON失败 ({id}): {e}")
+        raise HTTPException(status_code=500, detail=f"更新JSON数据失败: {e}")
+    finally:
+        if cursor:
+            cursor.close()
+
+
+@router.put("/_update/json/{id}", status_code=200, summary="修改图片的 modified_json")
+def _update_image_modified_json(
         id: int,
         id: int,
         new_json_data: Dict[str, Any],
         new_json_data: Dict[str, Any],
         db_conn: PooledMySQLConnection = db_dependency
         db_conn: PooledMySQLConnection = db_dependency

+ 4 - 0
app/core/config.py

@@ -15,6 +15,10 @@ class Settings:
     DATA_DIR = BASE_PATH / "Data"
     DATA_DIR = BASE_PATH / "Data"
     SCORE_CONFIG_PATH = BASE_PATH / "app/core/scoring_config.json"
     SCORE_CONFIG_PATH = BASE_PATH / "app/core/scoring_config.json"
 
 
+    # 分数计算接口url
+    SCORE_UPDATE_SERVER_URL = "http://127.0.0.1:7744"
+    SCORE_RECALCULATE_ENDPOINT = f"{SCORE_UPDATE_SERVER_URL}/api/card_score/score_recalculate"
+
     # --- 数据库配置 ---
     # --- 数据库配置 ---
     DB_NAME = 'card_score_database'
     DB_NAME = 'card_score_database'
     # 从 Config.json 读取的旧表名, 我们将不再使用它, 但保留以兼容旧文件
     # 从 Config.json 读取的旧表名, 我们将不再使用它, 但保留以兼容旧文件