img_score_and_insert.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  1. import asyncio
  2. import aiohttp
  3. import aiofiles
  4. import json
  5. import os
  6. from typing import Dict, Any, Tuple
  7. from datetime import datetime
  8. # --- 配置区域 ---
  9. # 1. 服务 URL
  10. INFERENCE_SERVICE_URL = "http://192.168.31.243:7744"
  11. STORAGE_SERVICE_URL = "http://192.168.31.243:7745"
  12. # 2. 要处理的卡片信息
  13. formate_time = datetime.now().strftime("%Y-%m-%d_%H:%M")
  14. CARD_NAME = f"卡 {formate_time}"
  15. # 3. 四张卡片图片的本地路径
  16. front_face_img_path = r"C:\Code\ML\Image\Card\_250915_many_capture_img\_250919_1500_no_reflect_nature_defect\15_front_coaxial_1_0.jpg"
  17. front_edge_img_path = r"C:\Code\ML\Image\Card\_250915_many_capture_img\_250919_1500_no_reflect_nature_defect\15_front_ring_0_1.jpg"
  18. back_face_img_path = r"C:\Code\ML\Image\Card\_250915_many_capture_img\_250919_1500_no_reflect_nature_defect\15_back_coaxial_1_0.jpg"
  19. back_edge_img_path = r"C:\Code\ML\Image\Card\_250915_many_capture_img\_250919_1500_no_reflect_nature_defect\15_back_ring_0_1.jpg"
  20. IMAGE_PATHS = [
  21. front_edge_img_path,
  22. front_face_img_path,
  23. back_edge_img_path,
  24. back_face_img_path
  25. ]
  26. # 4. 推理服务需要的 score_type 参数
  27. SCORE_TYPES = [
  28. "front_corner_edge",
  29. "front_face",
  30. "back_corner_edge",
  31. "back_face"
  32. ]
  33. SCORE_TO_IMAGE_TYPE_MAP = {
  34. "front_corner_edge": "front_edge",
  35. "front_face": "front_face",
  36. "back_corner_edge": "back_edge",
  37. "back_face": "back_face"
  38. }
  39. # --- 脚本主逻辑 ---
  40. async def call_api_with_file(
  41. session: aiohttp.ClientSession,
  42. url: str,
  43. file_path: str,
  44. params: Dict[str, Any] = None,
  45. form_fields: Dict[str, Any] = None
  46. ) -> Tuple[int, bytes]:
  47. """通用的文件上传API调用函数 (从文件路径读取)"""
  48. form_data = aiohttp.FormData()
  49. if form_fields:
  50. for key, value in form_fields.items():
  51. form_data.add_field(key, str(value))
  52. async with aiofiles.open(file_path, 'rb') as f:
  53. content = await f.read()
  54. form_data.add_field(
  55. 'file',
  56. content,
  57. filename=os.path.basename(file_path),
  58. content_type='image/jpeg'
  59. )
  60. try:
  61. async with session.post(url, data=form_data, params=params) as response:
  62. response_content = await response.read()
  63. if not response.ok:
  64. print(f"错误: 调用 {url} 失败, 状态码: {response.status}")
  65. print(f" 错误详情: {response_content.decode(errors='ignore')}")
  66. return response.status, response_content
  67. except aiohttp.ClientConnectorError as e:
  68. print(f"错误: 无法连接到服务 {url} - {e}")
  69. return 503, b"Connection Error"
  70. async def process_single_image(
  71. session: aiohttp.ClientSession,
  72. image_path: str,
  73. score_type: str
  74. ) -> Dict[str, Any]:
  75. """处理单张图片:获取转正图和分数JSON"""
  76. print(f" 正在处理图片: {image_path} (类型: {score_type})")
  77. # 1. 获取转正后的图片
  78. rectify_url = f"{INFERENCE_SERVICE_URL}/api/card_inference/card_rectify_and_center"
  79. rectify_status, rectified_image_bytes = await call_api_with_file(
  80. session, url=rectify_url, file_path=image_path
  81. )
  82. if rectify_status >= 300:
  83. raise Exception(f"获取转正图失败: {image_path}")
  84. print(f" -> 已成功获取转正图")
  85. # 2. 获取分数JSON
  86. score_url = f"{INFERENCE_SERVICE_URL}/api/card_score/score_inference"
  87. score_params = {
  88. "score_type": score_type,
  89. "is_reflect_card": "false"
  90. }
  91. score_status, score_json_bytes = await call_api_with_file(
  92. session,
  93. url=score_url,
  94. file_path=image_path,
  95. params=score_params
  96. )
  97. if score_status >= 300:
  98. raise Exception(f"获取分数JSON失败: {image_path}")
  99. score_json = json.loads(score_json_bytes)
  100. print(f" -> 已成功获取分数JSON")
  101. return {
  102. "score_type": score_type,
  103. "rectified_image": rectified_image_bytes,
  104. "score_json": score_json
  105. }
  106. async def create_card_set(session: aiohttp.ClientSession, card_name: str) -> int:
  107. """创建一个新的卡组并返回其ID"""
  108. url = f"{STORAGE_SERVICE_URL}/api/cards/created"
  109. params = {'card_name': card_name}
  110. print(f"\n[步骤 2] 正在创建卡组,名称: '{card_name}'...")
  111. try:
  112. async with session.post(url, params=params) as response:
  113. if response.ok:
  114. data = await response.json()
  115. card_id = data.get('id')
  116. if card_id is not None:
  117. print(f" -> 成功创建卡组, ID: {card_id}")
  118. return card_id
  119. else:
  120. raise Exception("创建卡组API的响应中未找到'id'字段")
  121. else:
  122. error_text = await response.text()
  123. raise Exception(f"创建卡组失败, 状态码: {response.status}, 详情: {error_text}")
  124. except aiohttp.ClientConnectorError as e:
  125. raise Exception(f"无法连接到存储服务 {url} - {e}")
  126. # 【修改点】: 修正此函数
  127. async def upload_processed_data(
  128. session: aiohttp.ClientSession,
  129. card_id: int,
  130. processed_data: Dict[str, Any]
  131. ):
  132. """上传单张转正图和对应的JSON到存储服务"""
  133. score_type = processed_data['score_type']
  134. image_type_for_storage = SCORE_TO_IMAGE_TYPE_MAP[score_type]
  135. print(f" 正在上传图片, 类型: {image_type_for_storage}...")
  136. url = f"{STORAGE_SERVICE_URL}/api/images/insert/{card_id}"
  137. # 直接构建FormData,因为图片数据已经在内存中 (processed_data['rectified_image'])
  138. form_data = aiohttp.FormData()
  139. form_data.add_field('image_type', image_type_for_storage)
  140. form_data.add_field('json_data_str', json.dumps(processed_data['score_json'], ensure_ascii=False))
  141. form_data.add_field(
  142. 'image',
  143. processed_data['rectified_image'],
  144. filename='rectified.jpg',
  145. content_type='image/jpeg'
  146. )
  147. try:
  148. async with session.post(url, data=form_data) as response:
  149. if response.status == 201:
  150. print(f" -> 成功上传并关联图片: {image_type_for_storage}")
  151. else:
  152. error_text = await response.text()
  153. print(
  154. f" -> 错误: 上传失败! 类型: {image_type_for_storage}, 状态码: {response.status}, 详情: {error_text}")
  155. except aiohttp.ClientConnectorError as e:
  156. print(f" -> 错误: 无法连接到存储服务 {url} - {e}")
  157. async def main():
  158. """主执行函数"""
  159. async with aiohttp.ClientSession() as session:
  160. # 步骤 1: 并发处理所有图片, 获取转正图和分数
  161. print("[步骤 1] 开始并发处理所有图片...")
  162. process_tasks = []
  163. for path, s_type in zip(IMAGE_PATHS, SCORE_TYPES):
  164. if not os.path.exists(path):
  165. print(f"错误:文件不存在,请检查路径配置: {path}")
  166. return
  167. task = asyncio.create_task(process_single_image(session, path, s_type))
  168. process_tasks.append(task)
  169. try:
  170. processed_results = await asyncio.gather(*process_tasks)
  171. print(" -> 所有图片处理完成!")
  172. except Exception as e:
  173. print(f"\n在处理图片过程中发生错误: {e}")
  174. return
  175. # 步骤 2: 创建卡组
  176. try:
  177. card_id = await create_card_set(session, CARD_NAME)
  178. except Exception as e:
  179. print(f"\n创建卡组时发生严重错误: {e}")
  180. return
  181. # 步骤 3: 并发上传所有处理好的数据
  182. print(f"\n[步骤 3] 开始为卡组ID {card_id} 并发上传图片和数据...")
  183. upload_tasks = []
  184. for result in processed_results:
  185. task = asyncio.create_task(upload_processed_data(session, card_id, result))
  186. upload_tasks.append(task)
  187. await asyncio.gather(*upload_tasks)
  188. print(" -> 所有数据上传完成!")
  189. print("\n====================")
  190. print("所有流程执行完毕!")
  191. print("====================")
  192. if __name__ == "__main__":
  193. if len(IMAGE_PATHS) != 4 or len(SCORE_TYPES) != 4:
  194. print("错误: IMAGE_PATHS 和 SCORE_TYPES 列表的长度必须为4,请检查配置。")
  195. else:
  196. # 在 Windows 上使用 ProactorEventLoop 可能会更稳定
  197. if os.name == 'nt':
  198. asyncio.set_event_loop_policy(asyncio.WindowsProactorEventLoopPolicy())
  199. asyncio.run(main())