utils.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  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("PyMuPDF"):
  38. import fitz
  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 not match_:
  98. file_type = mimetypes.guess_type(match_.group(1))[0]
  99. if file_type is None:
  100. return None
  101. return None
  102. if file_type.startswith("image/"):
  103. return "IMAGE"
  104. elif file_type == "application/pdf":
  105. return "PDF"
  106. elif file_type.startswith("video/"):
  107. return "VIDEO"
  108. elif file_type.startswith("audio/"):
  109. return "AUDIO"
  110. else:
  111. return None
  112. @function_requires_deps("filetype")
  113. def infer_file_ext(file: str) -> Optional[str]:
  114. if is_url(file):
  115. url_parts = urlparse(file)
  116. filename = url_parts.path.split("/")[-1]
  117. mime_type = mimetypes.guess_type(filename)[0]
  118. if mime_type is None:
  119. return None
  120. return mimetypes.guess_extension(mime_type)
  121. else:
  122. bytes_ = base64.b64decode(file)
  123. return "." + filetype.guess_extension(bytes_)
  124. @function_requires_deps("opencv-contrib-python")
  125. def image_bytes_to_array(data: bytes) -> np.ndarray:
  126. return cv2.imdecode(np.frombuffer(data, np.uint8), cv2.IMREAD_COLOR)
  127. def image_bytes_to_image(data: bytes) -> Image.Image:
  128. return Image.open(io.BytesIO(data))
  129. def image_to_bytes(image: Image.Image, format: str = "JPEG") -> bytes:
  130. with io.BytesIO() as f:
  131. image.save(f, format=format)
  132. img_bytes = f.getvalue()
  133. return img_bytes
  134. @function_requires_deps("opencv-contrib-python")
  135. def image_array_to_bytes(image: np.ndarray, ext: str = ".jpg") -> bytes:
  136. image = cv2.imencode(ext, image)[1]
  137. return image.tobytes()
  138. def csv_bytes_to_data_frame(data: bytes) -> pd.DataFrame:
  139. with io.StringIO(data.decode("utf-8")) as f:
  140. df = pd.read_csv(f)
  141. return df
  142. def data_frame_to_bytes(df: pd.DataFrame) -> bytes:
  143. return df.to_csv().encode("utf-8")
  144. def base64_encode(data: bytes) -> str:
  145. return base64.b64encode(data).decode("ascii")
  146. @function_requires_deps("PyMuPDF", "opencv-contrib-python")
  147. def read_pdf(
  148. bytes_: bytes, max_num_imgs: Optional[int] = None
  149. ) -> Tuple[List[np.ndarray], PDFInfo]:
  150. images: List[np.ndarray] = []
  151. page_info_list: List[PDFPageInfo] = []
  152. with fitz.open("pdf", bytes_) as doc:
  153. for page in doc:
  154. if max_num_imgs is not None and len(images) >= max_num_imgs:
  155. break
  156. # TODO: Do not always use zoom=2.0
  157. zoom = 2.0
  158. deg = 0
  159. mat = fitz.Matrix(zoom, zoom).prerotate(deg)
  160. pixmap = page.get_pixmap(matrix=mat, alpha=False)
  161. image = np.frombuffer(pixmap.samples, dtype=np.uint8).reshape(
  162. pixmap.h, pixmap.w, pixmap.n
  163. )
  164. image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
  165. images.append(image)
  166. page_info = PDFPageInfo(
  167. width=pixmap.w,
  168. height=pixmap.h,
  169. )
  170. page_info_list.append(page_info)
  171. pdf_info = PDFInfo(
  172. numPages=len(page_info_list),
  173. pages=page_info_list,
  174. )
  175. return images, pdf_info
  176. @overload
  177. def file_to_images(
  178. file_bytes: bytes,
  179. file_type: Literal["IMAGE"],
  180. *,
  181. max_num_imgs: Optional[int] = ...,
  182. ) -> Tuple[List[np.ndarray], ImageInfo]: ...
  183. @overload
  184. def file_to_images(
  185. file_bytes: bytes,
  186. file_type: Literal["PDF"],
  187. *,
  188. max_num_imgs: Optional[int] = ...,
  189. ) -> Tuple[List[np.ndarray], PDFInfo]: ...
  190. @overload
  191. def file_to_images(
  192. file_bytes: bytes,
  193. file_type: Literal["IMAGE", "PDF"],
  194. *,
  195. max_num_imgs: Optional[int] = ...,
  196. ) -> Union[Tuple[List[np.ndarray], ImageInfo], Tuple[List[np.ndarray], PDFInfo]]: ...
  197. def file_to_images(
  198. file_bytes: bytes,
  199. file_type: Literal["IMAGE", "PDF"],
  200. *,
  201. max_num_imgs: Optional[int] = None,
  202. ) -> Union[Tuple[List[np.ndarray], ImageInfo], Tuple[List[np.ndarray], PDFInfo]]:
  203. if file_type == "IMAGE":
  204. images = [image_bytes_to_array(file_bytes)]
  205. data_info = get_image_info(images[0])
  206. elif file_type == "PDF":
  207. images, data_info = read_pdf(file_bytes, max_num_imgs=max_num_imgs)
  208. else:
  209. assert_never(file_type)
  210. return images, data_info
  211. def get_image_info(image: np.ndarray) -> ImageInfo:
  212. return ImageInfo(width=image.shape[1], height=image.shape[0])
  213. def write_to_temp_file(file_bytes: bytes, suffix: str) -> str:
  214. with tempfile.NamedTemporaryFile("wb", suffix=suffix, delete=False) as f:
  215. f.write(file_bytes)
  216. return f.name
  217. def get_raw_bytes(file: str) -> bytes:
  218. if is_url(file):
  219. resp = requests.get(file, timeout=5)
  220. resp.raise_for_status()
  221. return resp.content
  222. else:
  223. return base64.b64decode(file)
  224. @function_requires_deps("aiohttp", "yarl")
  225. async def get_raw_bytes_async(file: str, session: "aiohttp.ClientSession") -> bytes:
  226. if is_url(file):
  227. async with session.get(yarl.URL(file, encoded=True)) as resp:
  228. return await resp.read()
  229. else:
  230. return base64.b64decode(file)
  231. def call_async(
  232. func: Callable[P, R], /, *args: P.args, **kwargs: P.kwargs
  233. ) -> Awaitable[R]:
  234. return asyncio.get_running_loop().run_in_executor(
  235. None, partial(func, *args, **kwargs)
  236. )