pp_shituv2.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  1. # Copyright (c) 2024 PaddlePaddle Authors. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import asyncio
  15. from operator import attrgetter
  16. from typing import Any, Dict, List
  17. from .....utils.deps import function_requires_deps, is_dep_available
  18. from ....pipelines.components import IndexData
  19. from ...infra import utils as serving_utils
  20. from ...infra.config import AppConfig
  21. from ...infra.models import AIStudioResultResponse
  22. from ...schemas import pp_shituv2 as schema
  23. from .._app import create_app, primary_operation
  24. from ._common import image_recognition as ir_common
  25. if is_dep_available("fastapi"):
  26. from fastapi import FastAPI
  27. @function_requires_deps("fastapi")
  28. def create_pipeline_app(pipeline: Any, app_config: AppConfig) -> "FastAPI":
  29. app, ctx = create_app(
  30. pipeline=pipeline, app_config=app_config, app_aiohttp_session=True
  31. )
  32. ir_common.update_app_context(ctx)
  33. @primary_operation(
  34. app,
  35. schema.BUILD_INDEX_ENDPOINT,
  36. "buildIndex",
  37. )
  38. async def _build_index(
  39. request: schema.BuildIndexRequest,
  40. ) -> AIStudioResultResponse[schema.BuildIndexResult]:
  41. pipeline = ctx.pipeline
  42. aiohttp_session = ctx.aiohttp_session
  43. file_bytes_list = await asyncio.gather(
  44. *(
  45. serving_utils.get_raw_bytes_async(img, aiohttp_session)
  46. for img in map(attrgetter("image"), request.imageLabelPairs)
  47. )
  48. )
  49. images = [serving_utils.image_bytes_to_array(item) for item in file_bytes_list]
  50. labels = [pair.label for pair in request.imageLabelPairs]
  51. # TODO: Support specifying `index_type` and `metric_type` in the
  52. # request
  53. index_data = await pipeline.call(
  54. pipeline.pipeline.build_index,
  55. images,
  56. labels,
  57. index_type="Flat",
  58. metric_type="IP",
  59. )
  60. index_storage = ctx.extra["index_storage"]
  61. index_key = ir_common.generate_index_key()
  62. index_data_bytes = index_data.to_bytes()
  63. await serving_utils.call_async(index_storage.set, index_key, index_data_bytes)
  64. return AIStudioResultResponse[schema.BuildIndexResult](
  65. logId=serving_utils.generate_log_id(),
  66. result=schema.BuildIndexResult(
  67. indexKey=index_key, imageCount=len(index_data.id_map)
  68. ),
  69. )
  70. @primary_operation(
  71. app,
  72. schema.ADD_IMAGES_TO_INDEX_ENDPOINT,
  73. "addImagesToIndex",
  74. )
  75. async def _add_images_to_index(
  76. request: schema.AddImagesToIndexRequest,
  77. ) -> AIStudioResultResponse[schema.AddImagesToIndexResult]:
  78. pipeline = ctx.pipeline
  79. aiohttp_session = ctx.aiohttp_session
  80. file_bytes_list = await asyncio.gather(
  81. *(
  82. serving_utils.get_raw_bytes_async(img, aiohttp_session)
  83. for img in map(attrgetter("image"), request.imageLabelPairs)
  84. )
  85. )
  86. images = [serving_utils.image_bytes_to_array(item) for item in file_bytes_list]
  87. labels = [pair.label for pair in request.imageLabelPairs]
  88. index_storage = ctx.extra["index_storage"]
  89. index_data_bytes = await serving_utils.call_async(
  90. index_storage.get, request.indexKey
  91. )
  92. index_data = IndexData.from_bytes(index_data_bytes)
  93. index_data = await pipeline.call(
  94. pipeline.pipeline.append_index, images, labels, index_data
  95. )
  96. index_data_bytes = index_data.to_bytes()
  97. await serving_utils.call_async(
  98. index_storage.set, request.indexKey, index_data_bytes
  99. )
  100. return AIStudioResultResponse[schema.AddImagesToIndexResult](
  101. logId=serving_utils.generate_log_id(),
  102. result=schema.AddImagesToIndexResult(imageCount=len(index_data.id_map)),
  103. )
  104. @primary_operation(
  105. app,
  106. schema.REMOVE_IMAGES_FROM_INDEX_ENDPOINT,
  107. "removeImagesFromIndex",
  108. )
  109. async def _remove_images_from_index(
  110. request: schema.RemoveImagesFromIndexRequest,
  111. ) -> AIStudioResultResponse[schema.RemoveImagesFromIndexResult]:
  112. pipeline = ctx.pipeline
  113. index_storage = ctx.extra["index_storage"]
  114. index_data_bytes = await serving_utils.call_async(
  115. index_storage.get, request.indexKey
  116. )
  117. index_data = IndexData.from_bytes(index_data_bytes)
  118. index_data = await pipeline.call(
  119. pipeline.pipeline.remove_index, request.ids, index_data
  120. )
  121. index_data_bytes = index_data.to_bytes()
  122. await serving_utils.call_async(
  123. index_storage.set, request.indexKey, index_data_bytes
  124. )
  125. return AIStudioResultResponse[schema.RemoveImagesFromIndexResult](
  126. logId=serving_utils.generate_log_id(),
  127. result=schema.RemoveImagesFromIndexResult(
  128. imageCount=len(index_data.id_map)
  129. ),
  130. )
  131. @primary_operation(
  132. app,
  133. schema.INFER_ENDPOINT,
  134. "infer",
  135. )
  136. async def _infer(
  137. request: schema.InferRequest,
  138. ) -> AIStudioResultResponse[schema.InferResult]:
  139. pipeline = ctx.pipeline
  140. aiohttp_session = ctx.aiohttp_session
  141. visualize_enabled = (
  142. request.visualize if request.visualize is not None else ctx.config.visualize
  143. )
  144. image_bytes = await serving_utils.get_raw_bytes_async(
  145. request.image, aiohttp_session
  146. )
  147. image = serving_utils.image_bytes_to_array(image_bytes)
  148. if request.indexKey is not None:
  149. index_storage = ctx.extra["index_storage"]
  150. index_data_bytes = await serving_utils.call_async(
  151. index_storage.get, request.indexKey
  152. )
  153. index_data = IndexData.from_bytes(index_data_bytes)
  154. else:
  155. index_data = None
  156. result = list(
  157. await pipeline.call(
  158. pipeline.pipeline.predict,
  159. image,
  160. index=index_data,
  161. det_threshold=request.detThreshold,
  162. rec_threshold=request.recThreshold,
  163. hamming_radius=request.hammingRadius,
  164. topk=request.topk,
  165. )
  166. )[0]
  167. objs: List[Dict[str, Any]] = []
  168. for obj in result["boxes"]:
  169. rec_results: List[Dict[str, Any]] = []
  170. if obj["rec_scores"] != [None]:
  171. for label, score in zip(obj["labels"], obj["rec_scores"]):
  172. rec_results.append(
  173. dict(
  174. label=label,
  175. score=score,
  176. )
  177. )
  178. objs.append(
  179. dict(
  180. bbox=obj["coordinate"],
  181. recResults=rec_results,
  182. score=obj["det_score"],
  183. )
  184. )
  185. if visualize_enabled:
  186. output_image_base64 = serving_utils.base64_encode(
  187. serving_utils.image_to_bytes(result.img["res"])
  188. )
  189. else:
  190. output_image_base64 = None
  191. return AIStudioResultResponse[schema.InferResult](
  192. logId=serving_utils.generate_log_id(),
  193. result=schema.InferResult(detectedObjects=objs, image=output_image_base64),
  194. )
  195. return app