utils.py 7.2 KB

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