utils.py 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. import base64
  2. from functools import lru_cache
  3. from io import BytesIO
  4. from typing import Any, List, Optional, Tuple, TypeVar, Union
  5. import librosa
  6. import numpy as np
  7. import numpy.typing as npt
  8. import soundfile
  9. from loguru import logger
  10. from PIL import Image
  11. from aphrodite.common.envs import (APHRODITE_AUDIO_FETCH_TIMEOUT,
  12. APHRODITE_IMAGE_FETCH_TIMEOUT)
  13. from aphrodite.connections import global_http_connection
  14. from aphrodite.multimodal.base import MultiModalDataDict
  15. from aphrodite.transformers_utils.tokenizer import AnyTokenizer, get_tokenizer
  16. cached_get_tokenizer = lru_cache(get_tokenizer)
  17. def _load_image_from_bytes(b: bytes):
  18. image = Image.open(BytesIO(b))
  19. image.load()
  20. return image
  21. def _load_image_from_data_url(image_url: str):
  22. # Only split once and assume the second part is the base64 encoded image
  23. _, image_base64 = image_url.split(",", 1)
  24. return load_image_from_base64(image_base64)
  25. def fetch_image(image_url: str, *, image_mode: str = "RGB") -> Image.Image:
  26. """
  27. Load a PIL image from a HTTP or base64 data URL.
  28. By default, the image is converted into RGB format.
  29. """
  30. if image_url.startswith('http'):
  31. image_raw = global_http_connection.get_bytes(
  32. image_url, timeout=APHRODITE_IMAGE_FETCH_TIMEOUT)
  33. image = _load_image_from_bytes(image_raw)
  34. elif image_url.startswith('data:image'):
  35. image = _load_image_from_data_url(image_url)
  36. else:
  37. raise ValueError("Invalid 'image_url': A valid 'image_url' must start "
  38. "with either 'data:image' or 'http'.")
  39. return image.convert(image_mode)
  40. async def async_fetch_image(image_url: str,
  41. *,
  42. image_mode: str = "RGB") -> Image.Image:
  43. """
  44. Asynchronously load a PIL image from a HTTP or base64 data URL.
  45. By default, the image is converted into RGB format.
  46. """
  47. if image_url.startswith('http'):
  48. image_raw = await global_http_connection.async_get_bytes(
  49. image_url, timeout=APHRODITE_IMAGE_FETCH_TIMEOUT)
  50. image = _load_image_from_bytes(image_raw)
  51. elif image_url.startswith('data:image'):
  52. image = _load_image_from_data_url(image_url)
  53. else:
  54. raise ValueError("Invalid 'image_url': A valid 'image_url' must start "
  55. "with either 'data:image' or 'http'.")
  56. return image.convert(image_mode)
  57. def fetch_audio(audio_url: str) -> Tuple[np.ndarray, Union[int, float]]:
  58. """
  59. Load audio from a URL.
  60. """
  61. if audio_url.startswith("http"):
  62. audio_bytes = global_http_connection.get_bytes(
  63. audio_url, timeout=APHRODITE_AUDIO_FETCH_TIMEOUT)
  64. elif audio_url.startswith("data:audio"):
  65. _, audio_base64 = audio_url.split(",", 1)
  66. audio_bytes = base64.b64decode(audio_base64)
  67. else:
  68. raise ValueError("Invalid 'audio_url': A valid 'audio_url' must start "
  69. "with either 'data:audio' or 'http'.")
  70. return librosa.load(BytesIO(audio_bytes), sr=None)
  71. async def async_fetch_audio(
  72. audio_url: str) -> Tuple[np.ndarray, Union[int, float]]:
  73. """
  74. Asynchronously fetch audio from a URL.
  75. """
  76. if audio_url.startswith("http"):
  77. audio_bytes = await global_http_connection.async_get_bytes(
  78. audio_url, timeout=APHRODITE_AUDIO_FETCH_TIMEOUT)
  79. elif audio_url.startswith("data:audio"):
  80. _, audio_base64 = audio_url.split(",", 1)
  81. audio_bytes = base64.b64decode(audio_base64)
  82. else:
  83. raise ValueError("Invalid 'audio_url': A valid 'audio_url' must start "
  84. "with either 'data:audio' or 'http'.")
  85. return librosa.load(BytesIO(audio_bytes), sr=None)
  86. async def async_get_and_parse_audio(audio_url: str) -> MultiModalDataDict:
  87. audio, sr = await async_fetch_audio(audio_url)
  88. return {"audio": (audio, sr)}
  89. async def async_get_and_parse_image(image_url: str) -> MultiModalDataDict:
  90. image = await async_fetch_image(image_url)
  91. return {"image": image}
  92. def encode_audio_base64(
  93. audio: np.ndarray,
  94. sampling_rate: int,
  95. ) -> str:
  96. """Encode audio as base64."""
  97. buffered = BytesIO()
  98. soundfile.write(buffered, audio, sampling_rate, format="WAV")
  99. return base64.b64encode(buffered.getvalue()).decode('utf-8')
  100. def encode_image_base64(
  101. image: Image.Image,
  102. *,
  103. image_mode: str = "RGB",
  104. format: str = "JPEG",
  105. ) -> str:
  106. """
  107. Encode a pillow image to base64 format.
  108. By default, the image is converted into RGB format before being encoded.
  109. """
  110. buffered = BytesIO()
  111. image = image.convert(image_mode)
  112. image.save(buffered, format)
  113. return base64.b64encode(buffered.getvalue()).decode('utf-8')
  114. def load_image_from_base64(image: Union[bytes, str]) -> Image.Image:
  115. """Load image from base64 format."""
  116. return _load_image_from_bytes(base64.b64decode(image))
  117. def rescale_image_size(image: Image.Image,
  118. size_factor: float,
  119. transpose: int = -1) -> Image.Image:
  120. """Rescale the dimensions of an image by a constant factor."""
  121. new_width = int(image.width * size_factor)
  122. new_height = int(image.height * size_factor)
  123. image = image.resize((new_width, new_height))
  124. if transpose >= 0:
  125. image = image.transpose(Image.Transpose(transpose))
  126. return image
  127. def try_import_video_packages() -> Any:
  128. try:
  129. import cv2
  130. except ImportError:
  131. raise ImportError(
  132. "Please install vllm[video] for video support.") from None
  133. return cv2
  134. def resize_video(frames: npt.NDArray, size: Tuple[int, int]) -> npt.NDArray:
  135. cv2 = try_import_video_packages()
  136. num_frames, _, _, channels = frames.shape
  137. new_height, new_width = size
  138. resized_frames = np.empty((num_frames, new_height, new_width, channels),
  139. dtype=frames.dtype)
  140. for i, frame in enumerate(frames):
  141. resized_frame = cv2.resize(frame, (new_width, new_height))
  142. resized_frames[i] = resized_frame
  143. return resized_frames
  144. def rescale_video_size(frames: npt.NDArray, size_factor: float) -> npt.NDArray:
  145. _, height, width, _ = frames.shape
  146. new_height = int(height * size_factor)
  147. new_width = int(width * size_factor)
  148. return resize_video(frames, (new_height, new_width))
  149. def sample_frames_from_video(frames: npt.NDArray,
  150. num_frames: int) -> npt.NDArray:
  151. total_frames = frames.shape[0]
  152. if num_frames == -1:
  153. return frames
  154. else:
  155. frame_indices = np.linspace(0, total_frames - 1, num_frames, dtype=int)
  156. sampled_frames = frames[frame_indices, ...]
  157. return sampled_frames
  158. # Utilities for input processors
  159. _T = TypeVar("_T", str, int)
  160. def repeat_and_pad_token(
  161. token: _T,
  162. *,
  163. repeat_count: int = 1,
  164. pad_token_left: Optional[_T] = None,
  165. pad_token_right: Optional[_T] = None,
  166. ) -> List[_T]:
  167. replacement = [token] * repeat_count
  168. if pad_token_left is not None:
  169. replacement = [pad_token_left] + replacement
  170. if pad_token_right is not None:
  171. replacement = replacement + [pad_token_right]
  172. return replacement
  173. def repeat_and_pad_placeholder_tokens(
  174. tokenizer: AnyTokenizer,
  175. prompt: Optional[str],
  176. prompt_token_ids: List[int],
  177. *,
  178. placeholder_token_id: int,
  179. repeat_count: int = 1,
  180. pad_token_left: Optional[int] = None,
  181. pad_token_right: Optional[int] = None,
  182. ) -> Tuple[Optional[str], List[int]]:
  183. if prompt is None:
  184. new_prompt = None
  185. else:
  186. placeholder_token_str = tokenizer.decode(placeholder_token_id)
  187. pad_token_str_left = (None if pad_token_left is None else
  188. tokenizer.decode(pad_token_left))
  189. pad_token_str_right = (None if pad_token_right is None else
  190. tokenizer.decode(pad_token_right))
  191. replacement_str = "".join(
  192. repeat_and_pad_token(
  193. placeholder_token_str,
  194. repeat_count=repeat_count,
  195. pad_token_left=pad_token_str_left,
  196. pad_token_right=pad_token_str_right,
  197. ))
  198. placeholder_token_count = prompt.count(placeholder_token_str)
  199. # This is an arbitrary number to distinguish between the two cases
  200. if placeholder_token_count > 16:
  201. logger.warning(
  202. "Please follow the prompt format that is "
  203. "documented on HuggingFace which does not involve "
  204. "repeating %s tokens.", placeholder_token_str)
  205. elif placeholder_token_count > 1:
  206. logger.warning("Multiple multi-modal input is not supported yet, "
  207. "so any extra placeholder tokens will be treated "
  208. "as plain text.")
  209. # The image tokens are removed to be consistent with HuggingFace
  210. new_prompt = prompt.replace(placeholder_token_str, replacement_str, 1)
  211. new_token_ids: List[int] = []
  212. for i, token in enumerate(prompt_token_ids):
  213. if token == placeholder_token_id:
  214. replacement_ids = repeat_and_pad_token(
  215. placeholder_token_id,
  216. repeat_count=repeat_count,
  217. pad_token_left=pad_token_left,
  218. pad_token_right=pad_token_right,
  219. )
  220. new_token_ids.extend(replacement_ids)
  221. # No need to further scan the list since we only replace once
  222. new_token_ids.extend(prompt_token_ids[i + 1:])
  223. break
  224. else:
  225. new_token_ids.append(token)
  226. return new_prompt, new_token_ids