img_score_and_insert2.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. import asyncio
  2. import aiohttp
  3. import aiofiles
  4. import json
  5. import os
  6. from typing import Dict, Any, Tuple, List
  7. from datetime import datetime
  8. # --- 配置区域 (可根据需要修改) ---
  9. INFERENCE_SERVICE_URL = "http://192.168.77.78:7744"
  10. STORAGE_SERVICE_URL = "http://192.168.77.78:7745"
  11. # 固定的处理类型映射
  12. SCORE_TYPES = [
  13. "front_corner_edge",
  14. "front_face",
  15. "back_corner_edge",
  16. "back_face"
  17. ]
  18. SCORE_TO_IMAGE_TYPE_MAP = {
  19. "front_corner_edge": "front_edge",
  20. "front_face": "front_face",
  21. "back_corner_edge": "back_edge",
  22. "back_face": "back_face"
  23. }
  24. # --- 辅助功能函数 (内部逻辑) ---
  25. async def call_api_with_file(
  26. session: aiohttp.ClientSession,
  27. url: str,
  28. file_path: str,
  29. params: Dict[str, Any] = None,
  30. form_fields: Dict[str, Any] = None
  31. ) -> Tuple[int, bytes]:
  32. """通用的文件上传API调用函数"""
  33. form_data = aiohttp.FormData()
  34. if form_fields:
  35. for key, value in form_fields.items():
  36. form_data.add_field(key, str(value))
  37. async with aiofiles.open(file_path, 'rb') as f:
  38. content = await f.read()
  39. form_data.add_field(
  40. 'file',
  41. content,
  42. filename=os.path.basename(file_path),
  43. content_type='image/jpeg'
  44. )
  45. try:
  46. async with session.post(url, data=form_data, params=params) as response:
  47. response_content = await response.read()
  48. if not response.ok:
  49. print(f"错误: 调用 {url} 失败, 状态码: {response.status}")
  50. return response.status, response_content
  51. except aiohttp.ClientConnectorError as e:
  52. print(f"错误: 无法连接到服务 {url} - {e}")
  53. return 503, b"Connection Error"
  54. async def process_single_image(
  55. session: aiohttp.ClientSession,
  56. image_path: str,
  57. score_type: str,
  58. is_reflect_card: str
  59. ) -> Dict[str, Any]:
  60. """处理单张图片:获取转正图和分数JSON"""
  61. print(f" 正在处理图片: {os.path.basename(image_path)} ({score_type})")
  62. # 1. 获取转正后的图片
  63. rectify_url = f"{INFERENCE_SERVICE_URL}/api/card_inference/card_rectify_and_center"
  64. rectify_status, rectified_image_bytes = await call_api_with_file(
  65. session, url=rectify_url, file_path=image_path
  66. )
  67. if rectify_status >= 300:
  68. raise Exception(f"获取转正图失败: {image_path}")
  69. # 2. 获取分数JSON
  70. score_url = f"{INFERENCE_SERVICE_URL}/api/card_score/score_inference"
  71. score_params = {
  72. "score_type": score_type,
  73. "is_reflect_card": is_reflect_card
  74. }
  75. score_status, score_json_bytes = await call_api_with_file(
  76. session,
  77. url=score_url,
  78. file_path=image_path,
  79. params=score_params
  80. )
  81. if score_status >= 300:
  82. raise Exception(f"获取分数JSON失败: {image_path}")
  83. score_json = json.loads(score_json_bytes)
  84. return {
  85. "score_type": score_type,
  86. "rectified_image": rectified_image_bytes,
  87. "score_json": score_json
  88. }
  89. async def create_card_set(session: aiohttp.ClientSession, card_name: str) -> int:
  90. """创建一个新的卡组并返回其ID"""
  91. url = f"{STORAGE_SERVICE_URL}/api/cards/created"
  92. params = {'card_name': card_name}
  93. print(f"\n[步骤 2] 创建卡组: '{card_name}'")
  94. try:
  95. async with session.post(url, params=params) as response:
  96. if response.ok:
  97. data = await response.json()
  98. card_id = data.get('id')
  99. if card_id is not None:
  100. print(f" -> 成功创建卡组 ID: {card_id}")
  101. return card_id
  102. raise Exception("响应中未找到 'id' 字段")
  103. else:
  104. raise Exception(f"状态码: {response.status}")
  105. except Exception as e:
  106. raise Exception(f"创建卡组失败: {e}")
  107. async def upload_processed_data(
  108. session: aiohttp.ClientSession,
  109. card_id: int,
  110. processed_data: Dict[str, Any]
  111. ):
  112. """上传单张转正图和对应的JSON"""
  113. score_type = processed_data['score_type']
  114. image_type = SCORE_TO_IMAGE_TYPE_MAP[score_type]
  115. url = f"{STORAGE_SERVICE_URL}/api/images/insert/{card_id}"
  116. form_data = aiohttp.FormData()
  117. form_data.add_field('image_type', image_type)
  118. form_data.add_field('json_data_str', json.dumps(processed_data['score_json'], ensure_ascii=False))
  119. form_data.add_field(
  120. 'image',
  121. processed_data['rectified_image'],
  122. filename='rectified.jpg',
  123. content_type='image/jpeg'
  124. )
  125. try:
  126. async with session.post(url, data=form_data) as response:
  127. if response.status == 201:
  128. print(f" -> 上传成功: {image_type}")
  129. else:
  130. print(f" -> 上传失败 ({image_type}): {response.status}")
  131. except Exception as e:
  132. print(f" -> 上传异常 ({image_type}): {e}")
  133. # --- 核心 API 函数 ---
  134. async def process_card_images(
  135. is_reflect: bool,
  136. front_face_path: str,
  137. front_edge_path: str,
  138. back_face_path: str,
  139. back_edge_path: str
  140. ) -> int:
  141. """
  142. 核心异步处理函数。
  143. :return: 成功创建的 card_id,如果失败返回 -1
  144. """
  145. # 0. 数据准备
  146. is_reflect_str = "true" if is_reflect else "false"
  147. # 注意:这里的顺序必须与全局 SCORE_TYPES 列表的顺序一一对应
  148. # SCORE_TYPES = ["front_corner_edge", "front_face", "back_corner_edge", "back_face"]
  149. path_list = [
  150. front_edge_path, # 对应 front_corner_edge
  151. front_face_path, # 对应 front_face
  152. back_edge_path, # 对应 back_corner_edge
  153. back_face_path # 对应 back_face
  154. ]
  155. # 检查路径是否存在
  156. for p in path_list:
  157. if not os.path.exists(p):
  158. print(f"错误: 文件路径不存在 -> {p}")
  159. return -1
  160. # 生成卡片名称
  161. card_name = f"卡 {datetime.now().strftime('%Y-%m-%d_%H:%M:%S')}"
  162. async with aiohttp.ClientSession() as session:
  163. try:
  164. # 步骤 1: 并发处理图片 (转正 + 评分)
  165. print(f"--- 开始处理: {card_name} ---")
  166. print("[步骤 1] 并发图像处理...")
  167. process_tasks = []
  168. for path, s_type in zip(path_list, SCORE_TYPES):
  169. task = process_single_image(session, path, s_type, is_reflect_str)
  170. process_tasks.append(task)
  171. processed_results = await asyncio.gather(*process_tasks)
  172. # 步骤 2: 创建卡组
  173. card_id = await create_card_set(session, card_name)
  174. # 步骤 3: 并发上传结果
  175. print(f"\n[步骤 3] 上传数据到卡组 {card_id}...")
  176. upload_tasks = []
  177. for result in processed_results:
  178. task = upload_processed_data(session, card_id, result)
  179. upload_tasks.append(task)
  180. await asyncio.gather(*upload_tasks)
  181. print(f"--- 流程完成,卡组ID: {card_id} ---\n")
  182. return card_id
  183. except Exception as e:
  184. print(f"\n流程执行中发生错误: {e}")
  185. return -1
  186. # --- 同步封装函数 (方便直接调用) ---
  187. def run_card_processing_sync(
  188. is_reflect: bool,
  189. front_face_path: str,
  190. front_edge_path: str,
  191. back_face_path: str,
  192. back_edge_path: str
  193. ):
  194. """
  195. 同步包装函数,会自动处理 EventLoop。
  196. 如果你的代码不是异步的,直接调用这个函数即可。
  197. """
  198. if os.name == 'nt':
  199. asyncio.set_event_loop_policy(asyncio.WindowsProactorEventLoopPolicy())
  200. return asyncio.run(process_card_images(
  201. is_reflect,
  202. front_face_path,
  203. front_edge_path,
  204. back_face_path,
  205. back_edge_path
  206. ))
  207. # --- 使用示例 ---
  208. if __name__ == "__main__":
  209. # 准备参数
  210. # !!!!!🪸是否反光
  211. my_is_reflect = True
  212. for img_num in range(10, 15):
  213. base_path = r"C:\Code\ML\Image\Card\_2025_1119_many_img\reflect2"
  214. p1 = os.path.join(base_path, f"{img_num}_front_coaxial_1_0.jpg")
  215. p2 = os.path.join(base_path, f"{img_num}_front_ring_0_1.jpg")
  216. p3 = os.path.join(base_path, f"{img_num}_back_coaxial_1_0.jpg")
  217. p4 = os.path.join(base_path, f"{img_num}_back_ring_0_1.jpg")
  218. # 调用函数
  219. print("开始调用函数...")
  220. final_card_id = run_card_processing_sync(
  221. is_reflect=my_is_reflect,
  222. front_face_path=p1,
  223. front_edge_path=p2,
  224. back_face_path=p3,
  225. back_edge_path=p4
  226. )
  227. if final_card_id != -1:
  228. print(f"调用成功,生成的卡片ID是: {final_card_id}")
  229. else:
  230. print("调用失败")