utils.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  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. async def async_get_and_parse_audio(audio_url: str) -> MultiModalDataDict:
  86. audio, sr = await async_fetch_audio(audio_url)
  87. return {"audio": (audio, sr)}
  88. async def async_get_and_parse_image(image_url: str) -> MultiModalDataDict:
  89. image = await async_fetch_image(image_url)
  90. return {"image": image}
  91. def encode_audio_base64(
  92. audio: np.ndarray,
  93. sampling_rate: int,
  94. ) -> str:
  95. """Encode audio as base64."""
  96. buffered = BytesIO()
  97. soundfile.write(buffered, audio, sampling_rate, format="WAV")
  98. return base64.b64encode(buffered.getvalue()).decode('utf-8')
  99. def encode_image_base64(
  100. image: Image.Image,
  101. *,
  102. image_mode: str = "RGB",
  103. format: str = "JPEG",
  104. ) -> str:
  105. """
  106. Encode a pillow image to base64 format.
  107. By default, the image is converted into RGB format before being encoded.
  108. """
  109. buffered = BytesIO()
  110. image = image.convert(image_mode)
  111. image.save(buffered, format)
  112. return base64.b64encode(buffered.getvalue()).decode('utf-8')
  113. def load_image_from_base64(image: Union[bytes, str]) -> Image.Image:
  114. """Load image from base64 format."""
  115. return _load_image_from_bytes(base64.b64decode(image))
  116. def rescale_image_size(image: Image.Image,
  117. size_factor: float,
  118. transpose: int = -1) -> Image.Image:
  119. """Rescale the dimensions of an image by a constant factor."""
  120. new_width = int(image.width * size_factor)
  121. new_height = int(image.height * size_factor)
  122. image = image.resize((new_width, new_height))
  123. if transpose >= 0:
  124. image = image.transpose(Image.Transpose(transpose))
  125. return image
  126. # Utilities for input processors
  127. _T = TypeVar("_T", str, int)
  128. def repeat_and_pad_token(
  129. token: _T,
  130. *,
  131. repeat_count: int = 1,
  132. pad_token_left: Optional[_T] = None,
  133. pad_token_right: Optional[_T] = None,
  134. ) -> List[_T]:
  135. replacement = [token] * repeat_count
  136. if pad_token_left is not None:
  137. replacement = [pad_token_left] + replacement
  138. if pad_token_right is not None:
  139. replacement = replacement + [pad_token_right]
  140. return replacement
  141. def repeat_and_pad_placeholder_tokens(
  142. tokenizer: AnyTokenizer,
  143. prompt: Optional[str],
  144. prompt_token_ids: List[int],
  145. *,
  146. placeholder_token_id: int,
  147. repeat_count: int = 1,
  148. pad_token_left: Optional[int] = None,
  149. pad_token_right: Optional[int] = None,
  150. ) -> Tuple[Optional[str], List[int]]:
  151. if prompt is None:
  152. new_prompt = None
  153. else:
  154. placeholder_token_str = tokenizer.decode(placeholder_token_id)
  155. pad_token_str_left = (None if pad_token_left is None else
  156. tokenizer.decode(pad_token_left))
  157. pad_token_str_right = (None if pad_token_right is None else
  158. tokenizer.decode(pad_token_right))
  159. replacement_str = "".join(
  160. repeat_and_pad_token(
  161. placeholder_token_str,
  162. repeat_count=repeat_count,
  163. pad_token_left=pad_token_str_left,
  164. pad_token_right=pad_token_str_right,
  165. ))
  166. placeholder_token_count = prompt.count(placeholder_token_str)
  167. # This is an arbitrary number to distinguish between the two cases
  168. if placeholder_token_count > 16:
  169. logger.warning(
  170. "Please follow the prompt format that is "
  171. "documented on HuggingFace which does not involve "
  172. "repeating %s tokens.", placeholder_token_str)
  173. elif placeholder_token_count > 1:
  174. logger.warning("Multiple multi-modal input is not supported yet, "
  175. "so any extra placeholder tokens will be treated "
  176. "as plain text.")
  177. # The image tokens are removed to be consistent with HuggingFace
  178. new_prompt = prompt.replace(placeholder_token_str, replacement_str, 1)
  179. new_token_ids: List[int] = []
  180. for i, token in enumerate(prompt_token_ids):
  181. if token == placeholder_token_id:
  182. replacement_ids = repeat_and_pad_token(
  183. placeholder_token_id,
  184. repeat_count=repeat_count,
  185. pad_token_left=pad_token_left,
  186. pad_token_right=pad_token_right,
  187. )
  188. new_token_ids.extend(replacement_ids)
  189. # No need to further scan the list since we only replace once
  190. new_token_ids.extend(prompt_token_ids[i + 1:])
  191. break
  192. else:
  193. new_token_ids.append(token)
  194. return new_prompt, new_token_ids