utils.py 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  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. import base64
  16. import io
  17. import mimetypes
  18. import re
  19. import tempfile
  20. import uuid
  21. from functools import partial
  22. from typing import Awaitable, Callable, List, Optional, Tuple, TypeVar, Union, overload
  23. from urllib.parse import parse_qs, urlparse
  24. import numpy as np
  25. import pandas as pd
  26. import requests
  27. from PIL import Image
  28. from typing_extensions import Literal, ParamSpec, TypeAlias, assert_never
  29. from ....utils.deps import function_requires_deps, is_dep_available
  30. from .models import ImageInfo, PDFInfo, PDFPageInfo
  31. if is_dep_available("aiohttp"):
  32. import aiohttp
  33. if is_dep_available("opencv-contrib-python"):
  34. import cv2
  35. if is_dep_available("filetype"):
  36. import filetype
  37. if is_dep_available("pypdfium2"):
  38. import pypdfium2 as pdfium
  39. if is_dep_available("yarl"):
  40. import yarl
  41. __all__ = [
  42. "FileType",
  43. "generate_log_id",
  44. "is_url",
  45. "infer_file_type",
  46. "infer_file_ext",
  47. "image_bytes_to_array",
  48. "image_bytes_to_image",
  49. "image_to_bytes",
  50. "image_array_to_bytes",
  51. "csv_bytes_to_data_frame",
  52. "data_frame_to_bytes",
  53. "base64_encode",
  54. "read_pdf",
  55. "file_to_images",
  56. "get_image_info",
  57. "write_to_temp_file",
  58. "get_raw_bytes",
  59. "get_raw_bytes_async",
  60. "call_async",
  61. ]
  62. FileType: TypeAlias = Literal["IMAGE", "PDF", "VIDEO", "AUDIO"]
  63. P = ParamSpec("P")
  64. R = TypeVar("R")
  65. def generate_log_id() -> str:
  66. return str(uuid.uuid4())
  67. # TODO:
  68. # 1. Use Pydantic to validate the URL and Base64-encoded string types for both
  69. # input and output data instead of handling this manually.
  70. # 2. Define a `File` type for global use; this will be part of the contract.
  71. # 3. Consider using two separate fields instead of a union of URL and Base64,
  72. # even though they are both strings. Backward compatibility should be
  73. # maintained.
  74. def is_url(s: str) -> bool:
  75. if not (s.startswith("http://") or s.startswith("https://")):
  76. # Quick rejection
  77. return False
  78. result = urlparse(s)
  79. return all([result.scheme, result.netloc]) and result.scheme in ("http", "https")
  80. def infer_file_type(url: str) -> Optional[FileType]:
  81. url_parts = urlparse(url)
  82. filename = url_parts.path.split("/")[-1]
  83. file_type = mimetypes.guess_type(filename)[0]
  84. if file_type is None:
  85. # HACK: The support for BOS URLs with query params is implementation-based,
  86. # not interface-based.
  87. is_bos_url = re.fullmatch(r"\w+\.bcebos\.com", url_parts.netloc) is not None
  88. if is_bos_url and url_parts.query:
  89. params = parse_qs(url_parts.query)
  90. if (
  91. "responseContentDisposition" in params
  92. and len(params["responseContentDisposition"]) == 1
  93. ):
  94. match_ = re.match(
  95. r"attachment;filename=(.*)", params["responseContentDisposition"][0]
  96. )
  97. if match_:
  98. file_type = mimetypes.guess_type(match_.group(1))[0]
  99. if file_type is None:
  100. return None
  101. if file_type.startswith("image/"):
  102. return "IMAGE"
  103. elif file_type == "application/pdf":
  104. return "PDF"
  105. elif file_type.startswith("video/"):
  106. return "VIDEO"
  107. elif file_type.startswith("audio/"):
  108. return "AUDIO"
  109. else:
  110. return None
  111. @function_requires_deps("filetype")
  112. def infer_file_ext(file: str) -> Optional[str]:
  113. if is_url(file):
  114. url_parts = urlparse(file)
  115. filename = url_parts.path.split("/")[-1]
  116. mime_type = mimetypes.guess_type(filename)[0]
  117. if mime_type is None:
  118. return None
  119. return mimetypes.guess_extension(mime_type)
  120. else:
  121. bytes_ = base64.b64decode(file)
  122. return "." + filetype.guess_extension(bytes_)
  123. @function_requires_deps("opencv-contrib-python")
  124. def image_bytes_to_array(data: bytes) -> np.ndarray:
  125. return cv2.imdecode(np.frombuffer(data, np.uint8), cv2.IMREAD_COLOR)
  126. def image_bytes_to_image(data: bytes) -> Image.Image:
  127. return Image.open(io.BytesIO(data))
  128. def image_to_bytes(image: Image.Image, format: str = "JPEG") -> bytes:
  129. with io.BytesIO() as f:
  130. image.save(f, format=format)
  131. img_bytes = f.getvalue()
  132. return img_bytes
  133. @function_requires_deps("opencv-contrib-python")
  134. def image_array_to_bytes(image: np.ndarray, ext: str = ".jpg") -> bytes:
  135. image = cv2.imencode(ext, image)[1]
  136. return image.tobytes()
  137. def csv_bytes_to_data_frame(data: bytes) -> pd.DataFrame:
  138. with io.StringIO(data.decode("utf-8")) as f:
  139. df = pd.read_csv(f)
  140. return df
  141. def data_frame_to_bytes(df: pd.DataFrame) -> bytes:
  142. return df.to_csv().encode("utf-8")
  143. def base64_encode(data: bytes) -> str:
  144. return base64.b64encode(data).decode("ascii")
  145. @function_requires_deps("pypdfium2", "opencv-contrib-python")
  146. def read_pdf(
  147. bytes_: bytes, max_num_imgs: Optional[int] = None
  148. ) -> Tuple[List[np.ndarray], PDFInfo]:
  149. images: List[np.ndarray] = []
  150. page_info_list: List[PDFPageInfo] = []
  151. doc = pdfium.PdfDocument(bytes_)
  152. for page in doc:
  153. if max_num_imgs is not None and len(images) >= max_num_imgs:
  154. break
  155. # TODO: Do not always use zoom=2.0
  156. zoom = 2.0
  157. deg = 0
  158. image = page.render(scale=zoom, rotation=deg).to_pil()
  159. image = image.convert("RGB")
  160. image = np.array(image)
  161. image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
  162. images.append(image)
  163. page_info = PDFPageInfo(
  164. width=image.shape[1],
  165. height=image.shape[0],
  166. )
  167. page_info_list.append(page_info)
  168. pdf_info = PDFInfo(
  169. numPages=len(page_info_list),
  170. pages=page_info_list,
  171. )
  172. return images, pdf_info
  173. @overload
  174. def file_to_images(
  175. file_bytes: bytes,
  176. file_type: Literal["IMAGE"],
  177. *,
  178. max_num_imgs: Optional[int] = ...,
  179. ) -> Tuple[List[np.ndarray], ImageInfo]: ...
  180. @overload
  181. def file_to_images(
  182. file_bytes: bytes,
  183. file_type: Literal["PDF"],
  184. *,
  185. max_num_imgs: Optional[int] = ...,
  186. ) -> Tuple[List[np.ndarray], PDFInfo]: ...
  187. @overload
  188. def file_to_images(
  189. file_bytes: bytes,
  190. file_type: Literal["IMAGE", "PDF"],
  191. *,
  192. max_num_imgs: Optional[int] = ...,
  193. ) -> Union[Tuple[List[np.ndarray], ImageInfo], Tuple[List[np.ndarray], PDFInfo]]: ...
  194. def file_to_images(
  195. file_bytes: bytes,
  196. file_type: Literal["IMAGE", "PDF"],
  197. *,
  198. max_num_imgs: Optional[int] = None,
  199. ) -> Union[Tuple[List[np.ndarray], ImageInfo], Tuple[List[np.ndarray], PDFInfo]]:
  200. if file_type == "IMAGE":
  201. images = [image_bytes_to_array(file_bytes)]
  202. data_info = get_image_info(images[0])
  203. elif file_type == "PDF":
  204. images, data_info = read_pdf(file_bytes, max_num_imgs=max_num_imgs)
  205. else:
  206. assert_never(file_type)
  207. return images, data_info
  208. def get_image_info(image: np.ndarray) -> ImageInfo:
  209. return ImageInfo(width=image.shape[1], height=image.shape[0])
  210. def write_to_temp_file(file_bytes: bytes, suffix: str) -> str:
  211. with tempfile.NamedTemporaryFile("wb", suffix=suffix, delete=False) as f:
  212. f.write(file_bytes)
  213. return f.name
  214. def get_raw_bytes(file: str) -> bytes:
  215. if is_url(file):
  216. resp = requests.get(file, timeout=5)
  217. resp.raise_for_status()
  218. return resp.content
  219. else:
  220. return base64.b64decode(file)
  221. @function_requires_deps("aiohttp", "yarl")
  222. async def get_raw_bytes_async(file: str, session: "aiohttp.ClientSession") -> bytes:
  223. if is_url(file):
  224. async with session.get(yarl.URL(file, encoded=True)) as resp:
  225. return await resp.read()
  226. else:
  227. return base64.b64decode(file)
  228. def call_async(
  229. func: Callable[P, R], /, *args: P.args, **kwargs: P.kwargs
  230. ) -> Awaitable[R]:
  231. return asyncio.get_running_loop().run_in_executor(
  232. None, partial(func, *args, **kwargs)
  233. )