utils.py 9.0 KB

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