Quellcode durchsuchen

试图计算总分

AnlaAnla vor 1 Monat
Ursprung
Commit
6f5cdb96b9
5 geänderte Dateien mit 123 neuen und 3 gelöschten Zeilen
  1. 90 0
      Test/img_data_insert.py
  2. 2 2
      Test/test01.py
  3. 29 0
      app/api/cards.py
  4. 1 1
      app/api/images.py
  5. 1 0
      app/utils/scheme.py

+ 90 - 0
Test/img_data_insert.py

@@ -0,0 +1,90 @@
+import requests
+import json
+
+
+def upload_image_with_json(
+        url: str,
+        image_path: str,
+        image_type: str = "front_face",
+        image_name: str = "未命名",
+        json_path: str = ''
+):
+    """
+    向指定接口上传图片及附带的 JSON 数据。
+
+    参数:
+        url (str): 接口 URL,例如 http://127.0.0.1:7745/api/images/insert/6
+        image_path (str): 图片文件路径
+        image_type (str): 图片类型,例如 'front_face'
+        image_name (str): 图片名称
+        json_data (str | dict | None): JSON 内容,可以是字符串、字典或 None
+
+    返回:
+        requests.Response: 服务器响应对象
+    """
+    with open(json_path, "r", encoding="utf-8") as f:
+        json_data_str = f.read()
+
+    files = {
+        "image": (image_path, open(image_path, "rb"), "image/gif")
+    }
+
+    data = {
+        "image_type": image_type,
+        "image_name": image_name,
+        "json_data_str": json_data_str
+    }
+
+    headers = {
+        "accept": "application/json"
+    }
+
+    # 发送 POST 请求
+    response = requests.post(url, headers=headers, files=files, data=data)
+
+    return response
+
+
+def send4img():
+    send_url = "http://127.0.0.1:7745/api/images/insert/7"
+    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_edge_img_path = r"C:\Code\ML\Project\CheckCardBoxAndDefectServer\_temp_work\test\正面边角\rectify_center_img.jpg"
+    front_edge_json_path = r"C:\Code\ML\Project\CheckCardBoxAndDefectServer\_temp_work\test\正面边角\front_corner_edge_score.json"
+
+    back_face_img_path = r"C:\Code\ML\Project\CheckCardBoxAndDefectServer\_temp_work\test\背面面\rectify_center_img.jpg"
+    back_face_json_path = r"C:\Code\ML\Project\CheckCardBoxAndDefectServer\_temp_work\test\背面面\back_face_score.json"
+
+    back_edge_img_path = r"C:\Code\ML\Project\CheckCardBoxAndDefectServer\_temp_work\test\背面边角\rectify_center_img.jpg"
+    back_edge_json_path = r"C:\Code\ML\Project\CheckCardBoxAndDefectServer\_temp_work\test\背面边角\back_corner_edge_score.json"
+
+    data = {"front_face": {"image": front_face_img_path, "json_data": front_face_json_path},
+            "front_edge": {"image": front_edge_img_path, "json_data": front_edge_json_path},
+            "back_face": {"image": back_face_img_path, "json_data": back_face_json_path},
+            "back_edge": {"image": back_edge_img_path, "json_data": back_edge_json_path}}
+
+    for k, v in data.items():
+        resp = upload_image_with_json(
+            url=send_url,
+            image_path=v['image'],
+            image_type=k,
+            image_name="",
+            json_path=v['json_data']
+        )
+        print(f"{k} Status:", resp.status_code)
+        print("Response:", resp.text)
+
+
+if __name__ == "__main__":
+    send4img()
+    # resp = upload_image_with_json(
+    #     url="http://127.0.0.1:7745/api/images/insert/6",
+    #     image_path="v2-28c2dced87172b004d40eedc38e7889a_b.gif",
+    #     image_type="front_face",
+    #     image_name="星海",
+    #     json_data={"2343": "阿萨"}
+    # )
+    #
+    # print("Status:", resp.status_code)
+    # print("Response:", resp.text)

+ 2 - 2
Test/test01.py

@@ -1,7 +1,7 @@
 import requests
 
-# base_url = 'http://127.0.0.1:7745/api/cards/query/1'
-base_url = 'http://192.168.31.243:7745/api/cards/query/4'
+base_url = 'http://127.0.0.1:7745/api/cards/query/7'
+# base_url = 'http://192.168.31.243:7745/api/cards/query/4'
 
 
 def send(url):

+ 29 - 0
app/api/cards.py

@@ -66,6 +66,35 @@ def get_card_details(id: int, db_conn: PooledMySQLConnection = db_dependency):
         image_records = cursor.fetchall()
         images = [CardImageResponse.model_validate(row) for row in image_records]
 
+        # 计算总分数(只有当图片数量为 4 时才计算)
+        card_data['score'] = None
+        if len(images) == 4:
+            try:
+                final_score = 10
+                for img in images:
+                    # 优先使用 modified_json,否则使用 detection_json
+                    src = img.modified_json if img.modified_json is not None else img.detection_json
+
+                    # src 可能为 None 或者不是 dict;做稳健检查
+                    if not isinstance(src, dict):
+                        logger.warning(f"图片 {img.id} 的 JSON 数据格式异常: {type(src)}")
+                        add_score = 0
+                    else:
+                        # 取嵌套键值:result -> _used_compute_deduct_score
+                        add_score = 0
+                        try:
+                            add_val = src.get("result", {}).get("_used_compute_deduct_score", 0)
+                            add_score = float(add_val) if add_val is not None else 0
+                        except Exception as e:
+                            logger.warning(f"从图片 {img.id} 的 JSON 中解析分数失败: {e}")
+                            add_score = 0
+
+                    final_score += add_score
+
+                card_data['score'] = final_score
+            except Exception as e:
+                logger.error(f"计算分数过程异常: {e}")
+
         # 组合成最终响应
         card_response = CardDetailResponse.model_validate(card_data)
         card_response.images = images

+ 1 - 1
app/api/images.py

@@ -70,7 +70,7 @@ async def upload_image_for_card(
             "VALUES (%s, %s, %s, %s, %s)"
         )
         params = (
-        card_id, image_type.value, image_name, relative_path, json.dumps(detection_json, ensure_ascii=False))
+            card_id, image_type.value, image_name, relative_path, json.dumps(detection_json, ensure_ascii=False))
 
         cursor.execute(query_insert_image, params)
         new_id = cursor.lastrowid

+ 1 - 0
app/utils/scheme.py

@@ -41,6 +41,7 @@ class CardDetailResponse(BaseModel):
     card_name: Optional[str] = None
     created_at: datetime
     updated_at: datetime
+    score: Optional[float] = None
     images: List[CardImageResponse] = []
 
     class Config: