utils.py 8.2 KB

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