img_score_and_insert.py 8.5 KB

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