utils.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  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 os
  18. import re
  19. import uuid
  20. from functools import partial
  21. from typing import Awaitable, Callable, List, Literal, Optional, TypeVar, Final, Tuple
  22. from urllib.parse import parse_qs, urlparse
  23. import aiohttp
  24. import cv2
  25. import fitz
  26. import numpy as np
  27. import pandas as pd
  28. import yarl
  29. from PIL import Image
  30. from typing_extensions import ParamSpec, assert_never
  31. FileType = Literal["IMAGE", "PDF"]
  32. _P = ParamSpec("_P")
  33. _R = TypeVar("_R")
  34. def generate_log_id() -> str:
  35. return str(uuid.uuid4())
  36. def generate_request_id() -> str:
  37. return str(uuid.uuid4())
  38. def is_url(s: str) -> bool:
  39. if not (s.startswith("http://") or s.startswith("https://")):
  40. # Quick rejection
  41. return False
  42. result = urlparse(s)
  43. return all([result.scheme, result.netloc]) and result.scheme in ("http", "https")
  44. def infer_file_type(url: str) -> FileType:
  45. # Is it more reliable to guess the file type based on the response headers?
  46. SUPPORTED_IMG_EXTS: Final[List[str]] = [".jpg", ".jpeg", ".png"]
  47. url_parts = urlparse(url)
  48. ext = os.path.splitext(url_parts.path)[1]
  49. # HACK: The support for BOS URLs with query params is implementation-based,
  50. # not interface-based.
  51. is_bos_url = (
  52. re.fullmatch(r"(?:bj|bd|su|gz|cd|hkg|fwh|fsh)\.bcebos\.com", url_parts.netloc)
  53. is not None
  54. )
  55. if is_bos_url and url_parts.query:
  56. params = parse_qs(url_parts.query)
  57. if (
  58. "responseContentDisposition" not in params
  59. or len(params["responseContentDisposition"]) != 1
  60. ):
  61. raise ValueError("`responseContentDisposition` not found")
  62. match_ = re.match(
  63. r"attachment;filename=(.*)", params["responseContentDisposition"][0]
  64. )
  65. if not match_ or not match_.groups()[0] is not None:
  66. raise ValueError(
  67. "Failed to extract the filename from `responseContentDisposition`"
  68. )
  69. ext = os.path.splitext(match_.groups()[0])[1]
  70. ext = ext.lower()
  71. if ext == ".pdf":
  72. return "PDF"
  73. elif ext in SUPPORTED_IMG_EXTS:
  74. return "IMAGE"
  75. else:
  76. raise ValueError("Unsupported file type")
  77. async def get_raw_bytes(file: str, session: aiohttp.ClientSession) -> bytes:
  78. if is_url(file):
  79. async with session.get(yarl.URL(file, encoded=True)) as resp:
  80. return await resp.read()
  81. else:
  82. return base64.b64decode(file)
  83. def image_bytes_to_array(data: bytes) -> np.ndarray:
  84. return cv2.imdecode(np.frombuffer(data, np.uint8), cv2.IMREAD_COLOR)
  85. def image_to_base64(image: Image.Image) -> str:
  86. with io.BytesIO() as f:
  87. image.save(f, format="JPEG")
  88. image_base64 = base64.b64encode(f.getvalue()).decode("ascii")
  89. return image_base64
  90. def csv_bytes_to_data_frame(data: bytes) -> pd.DataFrame:
  91. with io.StringIO(data.decode("utf-8")) as f:
  92. df = pd.read_csv(f)
  93. return df
  94. def data_frame_to_base64(df: str) -> str:
  95. return base64.b64encode(df.to_csv().encode("utf-8")).decode("ascii")
  96. def read_pdf(
  97. bytes_: bytes, resize: bool = False, max_num_imgs: Optional[int] = None
  98. ) -> List[np.ndarray]:
  99. images: List[np.ndarray] = []
  100. img_size = None
  101. with fitz.open("pdf", bytes_) as doc:
  102. for page in doc:
  103. if max_num_imgs is not None and len(images) >= max_num_imgs:
  104. break
  105. # TODO: Do not always use zoom=2.0
  106. zoom = 2.0
  107. deg = 0
  108. mat = fitz.Matrix(zoom, zoom).prerotate(deg)
  109. pixmap = page.get_pixmap(matrix=mat, alpha=False)
  110. image = np.frombuffer(pixmap.samples, dtype=np.uint8).reshape(
  111. pixmap.h, pixmap.w, pixmap.n
  112. )
  113. image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
  114. if resize:
  115. if img_size is None:
  116. img_size = (image.shape[1], image.shape[0])
  117. else:
  118. if (image.shape[1], image.shape[0]) != img_size:
  119. image = cv2.resize(image, img_size)
  120. images.append(image)
  121. return images
  122. def file_to_images(
  123. file_bytes: bytes,
  124. file_type: Literal["IMAGE", "PDF"],
  125. *,
  126. max_img_size: Tuple[int, int],
  127. max_num_imgs: int,
  128. ) -> List[np.ndarray]:
  129. if file_type == "IMAGE":
  130. images = [image_bytes_to_array(file_bytes)]
  131. elif file_type == "PDF":
  132. images = read_pdf(file_bytes, resize=True, max_num_imgs=max_num_imgs)
  133. else:
  134. assert_never(file_type)
  135. h, w = images[0].shape[0:2]
  136. if w > max_img_size[1] or h > max_img_size[0]:
  137. if w / h > max_img_size[0] / max_img_size[1]:
  138. factor = max_img_size[0] / w
  139. else:
  140. factor = max_img_size[1] / h
  141. images = [cv2.resize(img, (int(factor * w), int(factor * h))) for img in images]
  142. return images
  143. def call_async(
  144. func: Callable[_P, _R], /, *args: _P.args, **kwargs: _P.kwargs
  145. ) -> Awaitable[_R]:
  146. return asyncio.get_running_loop().run_in_executor(
  147. None, partial(func, *args, **kwargs)
  148. )