layout_parsing.py 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. # copyright (c) 2024 PaddlePaddle Authors. All Rights Reserve.
  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 os
  15. import re
  16. import uuid
  17. from typing import Final, List, Literal, Optional, Tuple
  18. from urllib.parse import parse_qs, urlparse
  19. import cv2
  20. import numpy as np
  21. from fastapi import FastAPI, HTTPException
  22. from numpy.typing import ArrayLike
  23. from pydantic import BaseModel, Field
  24. from typing_extensions import Annotated, TypeAlias, assert_never
  25. from .....utils import logging
  26. from ...layout_parsing import LayoutParsingPipeline
  27. from .. import file_storage
  28. from .. import utils as serving_utils
  29. from ..app import AppConfig, create_app
  30. from ..models import Response, ResultResponse
  31. _DEFAULT_MAX_IMG_SIZE: Final[Tuple[int, int]] = (2000, 2000)
  32. _DEFAULT_MAX_NUM_IMGS: Final[int] = 10
  33. FileType: TypeAlias = Literal[0, 1]
  34. class InferenceParams(BaseModel):
  35. maxLongSide: Optional[Annotated[int, Field(gt=0)]] = None
  36. class InferRequest(BaseModel):
  37. file: str
  38. fileType: Optional[FileType] = None
  39. useImgOrientationCls: bool = True
  40. useImgUnwrapping: bool = True
  41. useSealTextDet: bool = True
  42. inferenceParams: Optional[InferenceParams] = None
  43. BoundingBox: TypeAlias = Annotated[List[float], Field(min_length=4, max_length=4)]
  44. class LayoutElement(BaseModel):
  45. bbox: BoundingBox
  46. label: str
  47. text: str
  48. layoutType: Literal["single", "double"]
  49. image: Optional[str] = None
  50. class LayoutParsingResult(BaseModel):
  51. layoutElements: List[LayoutElement]
  52. class InferResult(BaseModel):
  53. layoutParsingResults: List[LayoutParsingResult]
  54. def _generate_request_id() -> str:
  55. return str(uuid.uuid4())
  56. def _infer_file_type(url: str) -> FileType:
  57. # Is it more reliable to guess the file type based on the response headers?
  58. SUPPORTED_IMG_EXTS: Final[List[str]] = [".jpg", ".jpeg", ".png"]
  59. url_parts = urlparse(url)
  60. ext = os.path.splitext(url_parts.path)[1]
  61. # HACK: The support for BOS URLs with query params is implementation-based,
  62. # not interface-based.
  63. is_bos_url = (
  64. re.fullmatch(r"(?:bj|bd|su|gz|cd|hkg|fwh|fsh)\.bcebos\.com", url_parts.netloc)
  65. is not None
  66. )
  67. if is_bos_url and url_parts.query:
  68. params = parse_qs(url_parts.query)
  69. if (
  70. "responseContentDisposition" not in params
  71. or len(params["responseContentDisposition"]) != 1
  72. ):
  73. raise ValueError("`responseContentDisposition` not found")
  74. match_ = re.match(
  75. r"attachment;filename=(.*)", params["responseContentDisposition"][0]
  76. )
  77. if not match_ or not match_.groups()[0] is not None:
  78. raise ValueError(
  79. "Failed to extract the filename from `responseContentDisposition`"
  80. )
  81. ext = os.path.splitext(match_.groups()[0])[1]
  82. ext = ext.lower()
  83. if ext == ".pdf":
  84. return 0
  85. elif ext in SUPPORTED_IMG_EXTS:
  86. return 1
  87. else:
  88. raise ValueError("Unsupported file type")
  89. def _bytes_to_arrays(
  90. file_bytes: bytes,
  91. file_type: FileType,
  92. *,
  93. max_img_size: Tuple[int, int],
  94. max_num_imgs: int,
  95. ) -> List[np.ndarray]:
  96. if file_type == 0:
  97. images = serving_utils.read_pdf(
  98. file_bytes, resize=True, max_num_imgs=max_num_imgs
  99. )
  100. elif file_type == 1:
  101. images = [serving_utils.image_bytes_to_array(file_bytes)]
  102. else:
  103. assert_never(file_type)
  104. h, w = images[0].shape[0:2]
  105. if w > max_img_size[1] or h > max_img_size[0]:
  106. if w / h > max_img_size[0] / max_img_size[1]:
  107. factor = max_img_size[0] / w
  108. else:
  109. factor = max_img_size[1] / h
  110. images = [cv2.resize(img, (int(factor * w), int(factor * h))) for img in images]
  111. return images
  112. def _postprocess_image(
  113. img: ArrayLike,
  114. request_id: str,
  115. filename: str,
  116. file_storage_config: file_storage.FileStorageConfig,
  117. ) -> str:
  118. key = f"{request_id}/{filename}"
  119. ext = os.path.splitext(filename)[1]
  120. img = np.asarray(img)
  121. _, encoded_img = cv2.imencode(ext, img)
  122. encoded_img = encoded_img.tobytes()
  123. return file_storage.postprocess_file(
  124. encoded_img, config=file_storage_config, key=key
  125. )
  126. def create_pipeline_app(
  127. pipeline: LayoutParsingPipeline, app_config: AppConfig
  128. ) -> FastAPI:
  129. app, ctx = create_app(
  130. pipeline=pipeline, app_config=app_config, app_aiohttp_session=True
  131. )
  132. if "file_storage_config" in ctx.extra:
  133. ctx.extra["file_storage_config"] = file_storage.parse_file_storage_config(
  134. ctx.extra["file_storage_config"]
  135. )
  136. else:
  137. ctx.extra["file_storage_config"] = file_storage.InMemoryStorageConfig()
  138. ctx.extra.setdefault("max_img_size", _DEFAULT_MAX_IMG_SIZE)
  139. ctx.extra.setdefault("max_num_imgs", _DEFAULT_MAX_NUM_IMGS)
  140. @app.post(
  141. "/layout-parsing",
  142. operation_id="infer",
  143. responses={422: {"model": Response}},
  144. response_model_exclude_none=True,
  145. )
  146. async def _infer(
  147. request: InferRequest,
  148. ) -> ResultResponse[InferResult]:
  149. pipeline = ctx.pipeline
  150. aiohttp_session = ctx.aiohttp_session
  151. request_id = _generate_request_id()
  152. if request.fileType is None:
  153. if serving_utils.is_url(request.file):
  154. try:
  155. file_type = _infer_file_type(request.file)
  156. except Exception as e:
  157. logging.exception(e)
  158. raise HTTPException(
  159. status_code=422,
  160. detail="The file type cannot be inferred from the URL. Please specify the file type explicitly.",
  161. )
  162. else:
  163. raise HTTPException(status_code=422, detail="Unknown file type")
  164. else:
  165. file_type = request.fileType
  166. if request.inferenceParams:
  167. max_long_side = request.inferenceParams.maxLongSide
  168. if max_long_side:
  169. raise HTTPException(
  170. status_code=422,
  171. detail="`max_long_side` is currently not supported.",
  172. )
  173. try:
  174. file_bytes = await serving_utils.get_raw_bytes(
  175. request.file, aiohttp_session
  176. )
  177. images = await serving_utils.call_async(
  178. _bytes_to_arrays,
  179. file_bytes,
  180. file_type,
  181. max_img_size=ctx.extra["max_img_size"],
  182. max_num_imgs=ctx.extra["max_num_imgs"],
  183. )
  184. result = await pipeline.infer(
  185. images,
  186. use_doc_image_ori_cls_model=request.useImgOrientationCls,
  187. use_doc_image_unwarp_model=request.useImgUnwrapping,
  188. use_seal_text_det_model=request.useSealTextDet,
  189. )
  190. layout_parsing_results: List[LayoutParsingResult] = []
  191. for i, item in enumerate(result):
  192. layout_elements: List[LayoutElement] = []
  193. for j, subitem in enumerate(
  194. item["layout_parsing_result"]["parsing_result"]
  195. ):
  196. dyn_keys = subitem.keys() - {"input_path", "layout_bbox", "layout"}
  197. if len(dyn_keys) != 1:
  198. raise RuntimeError(f"Unexpected result: {subitem}")
  199. label = next(iter(dyn_keys))
  200. if label in ("image", "figure", "img", "fig"):
  201. image_ = await serving_utils.call_async(
  202. _postprocess_image,
  203. subitem[label]["img"],
  204. request_id=request_id,
  205. filename=f"image_{i}_{j}.jpg",
  206. file_storage_config=ctx.extra["file_storage_config"],
  207. )
  208. text = subitem[label]["image_text"]
  209. else:
  210. image_ = None
  211. text = subitem[label]
  212. layout_elements.append(
  213. LayoutElement(
  214. bbox=subitem["layout_bbox"],
  215. label=label,
  216. text=text,
  217. layoutType=subitem["layout"],
  218. image=image_,
  219. )
  220. )
  221. layout_parsing_results.append(
  222. LayoutParsingResult(layoutElements=layout_elements)
  223. )
  224. return ResultResponse(
  225. logId=serving_utils.generate_log_id(),
  226. errorCode=0,
  227. errorMsg="Success",
  228. result=InferResult(
  229. layoutParsingResults=layout_parsing_results,
  230. ),
  231. )
  232. except Exception as e:
  233. logging.exception(e)
  234. raise HTTPException(status_code=500, detail="Internal server error")
  235. return app