import requests import json import os # --- 服务地址配置 --- # 第一个服务: 卡片评分/缺陷推理 SCORE_API_URL = 'http://127.0.0.1:7744/api/card_score/score_inference' # 第二个服务: 结果存储 STORAGE_API_URL = 'http://192.168.31.243:7745/api/image_data/insert' def process_and_store_card(image_path, score_type, is_reflect_card, img_name): """ 一个完整的处理流程函数: 1. 请求评分服务获取缺陷JSON。 2. 将图片和缺陷JSON一起请求存储服务。 :param image_path: 图片文件的本地路径。 :param score_type: 评分类型 (例如: 'back_face')。 :param is_reflect_card: 是否是反光卡 (布尔值: True 或 False)。 :param img_name: 存储时使用的图片名称。 :return: 成功时返回 True, 失败时返回 False。 """ # 检查图片文件是否存在 if not os.path.exists(image_path): print(f"错误: 图片文件未找到 -> {image_path}") return False print(f"--- 开始处理图片: {image_path} ---") # --- 步骤 1: 请求评分服务 --- print("步骤 1: 请求评分服务...") # 准备评分服务的参数 score_params = { 'score_type': score_type, 'is_reflect_card': str(is_reflect_card).lower() # API需要 'true' 或 'false' 字符串 } try: # 打开图片文件, 'rb' 表示二进制读取 with open(image_path, 'rb') as f: # 准备要上传的文件, 格式为: {'表单字段名': (文件名, 文件对象, MIME类型)} files_for_score = {'file': (os.path.basename(image_path), f, 'image/jpeg')} # 发送POST请求 response_score = requests.post( SCORE_API_URL, params=score_params, files=files_for_score, timeout=90 # 设置超时时间, 例如30秒 ) # 检查响应状态码 response_score.raise_for_status() # 如果状态码不是 2xx, 会抛出异常 # 解析返回的JSON结果 score_json_result = response_score.json() print("步骤 1: 成功获取评分结果。") # print("评分结果JSON:", json.dumps(score_json_result, indent=2, ensure_ascii=False)) except requests.exceptions.RequestException as e: print(f"错误: 请求评分服务失败 -> {e}") return False except json.JSONDecodeError: print("错误: 无法解析评分服务的JSON响应。") print("服务器原始响应:", response_score.text) return False # --- 步骤 2: 请求存储服务 --- print("\n步骤 2: 请求存储服务...") try: # 准备存储服务的表单数据 # 将上一步得到的JSON结果转换为字符串 json_data_str = json.dumps(score_json_result, ensure_ascii=False) storage_data = { 'json_data_str': json_data_str, 'img_name': img_name } # 重新打开图片文件进行第二次上传 # (因为上一个 `with` 语句块结束后文件已关闭) with open(image_path, 'rb') as f: # 准备要上传的文件, 注意这里的表单字段名是 'image' files_for_storage = {'image': (os.path.basename(image_path), f, 'image/jpeg')} # 发送POST请求 response_storage = requests.post( STORAGE_API_URL, data=storage_data, files=files_for_storage, timeout=30 ) # 检查响应状态码 response_storage.raise_for_status() print(f"步骤 2: 成功存储数据。服务器响应: {response_storage.json()}") except requests.exceptions.RequestException as e: print(f"错误: 请求存储服务失败 -> {e}") return False print(f"\n--- 图片 '{image_path}' 处理完成 ---") return True # --- 主程序入口 --- if __name__ == '__main__': # --- 在这里配置你要处理的图片信息 --- # 1. 图片的路径 # 注意: 如果你的图片路径包含中文, 确保文件是以 UTF-8 编码保存的 image_file_path = r"C:\Code\ML\Image\Card\_250917_1157_pokemon_no flecct01\37_front_0_1.jpg.jpg" # 2. 评分服务的参数 # ["front_corner_edge", "front_face", # "back_corner_edge", "back_face"] card_score_type = 'front_face' # 是否是闪光卡 card_is_reflect = False # 3. 存储服务的图片名称 card_img_name = '铁甲蛹的边角' # 调用主函数执行流程 process_and_store_card( image_path=image_file_path, score_type=card_score_type, is_reflect_card=card_is_reflect, img_name=card_img_name )