utils.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  1. import base64
  2. import os
  3. from io import BytesIO
  4. from typing import Tuple, Union
  5. import librosa
  6. import numpy as np
  7. import soundfile
  8. from PIL import Image
  9. from aphrodite.common.connections import global_http_connection
  10. from aphrodite.multimodal.base import MultiModalDataDict
  11. APHRODITE_IMAGE_FETCH_TIMEOUT = int(
  12. os.getenv("APHRODITE_IMAGE_FETCH_TIMEOUT", 10))
  13. APHRODITE_AUDIO_FETCH_TIMEOUT = int(
  14. os.getenv("APHRODITE_AUDIO_FETCH_TIMEOUT", 10))
  15. def _load_image_from_bytes(b: bytes):
  16. image = Image.open(BytesIO(b))
  17. image.load()
  18. return image
  19. def _load_image_from_data_url(image_url: str):
  20. # Only split once and assume the second part is the base64 encoded image
  21. _, image_base64 = image_url.split(",", 1)
  22. return load_image_from_base64(image_base64)
  23. def fetch_image(image_url: str, *, image_mode: str = "RGB") -> Image.Image:
  24. """
  25. Load a PIL image from a HTTP or base64 data URL.
  26. By default, the image is converted into RGB format.
  27. """
  28. if image_url.startswith('http'):
  29. image_raw = global_http_connection.get_bytes(
  30. image_url, timeout=APHRODITE_IMAGE_FETCH_TIMEOUT)
  31. image = _load_image_from_bytes(image_raw)
  32. elif image_url.startswith('data:image'):
  33. image = _load_image_from_data_url(image_url)
  34. else:
  35. raise ValueError("Invalid 'image_url': A valid 'image_url' must start "
  36. "with either 'data:image' or 'http'.")
  37. return image.convert(image_mode)
  38. async def async_fetch_image(image_url: str,
  39. *,
  40. image_mode: str = "RGB") -> Image.Image:
  41. """
  42. Asynchronously load a PIL image from a HTTP or base64 data URL.
  43. By default, the image is converted into RGB format.
  44. """
  45. if image_url.startswith('http'):
  46. image_raw = await global_http_connection.async_get_bytes(
  47. image_url, timeout=APHRODITE_IMAGE_FETCH_TIMEOUT)
  48. image = _load_image_from_bytes(image_raw)
  49. elif image_url.startswith('data:image'):
  50. image = _load_image_from_data_url(image_url)
  51. else:
  52. raise ValueError("Invalid 'image_url': A valid 'image_url' must start "
  53. "with either 'data:image' or 'http'.")
  54. return image.convert(image_mode)
  55. def fetch_audio(audio_url: str) -> Tuple[np.ndarray, Union[int, float]]:
  56. """
  57. Load audio from a URL.
  58. """
  59. if audio_url.startswith("http"):
  60. audio_bytes = global_http_connection.get_bytes(
  61. audio_url, timeout=APHRODITE_AUDIO_FETCH_TIMEOUT)
  62. elif audio_url.startswith("data:audio"):
  63. _, audio_base64 = audio_url.split(",", 1)
  64. audio_bytes = base64.b64decode(audio_base64)
  65. else:
  66. raise ValueError("Invalid 'audio_url': A valid 'audio_url' must start "
  67. "with either 'data:audio' or 'http'.")
  68. return librosa.load(BytesIO(audio_bytes), sr=None)
  69. async def async_fetch_audio(
  70. audio_url: str) -> Tuple[np.ndarray, Union[int, float]]:
  71. """
  72. Asynchronously fetch audio from a URL.
  73. """
  74. if audio_url.startswith("http"):
  75. audio_bytes = await global_http_connection.async_get_bytes(
  76. audio_url, timeout=APHRODITE_AUDIO_FETCH_TIMEOUT)
  77. elif audio_url.startswith("data:audio"):
  78. _, audio_base64 = audio_url.split(",", 1)
  79. audio_bytes = base64.b64decode(audio_base64)
  80. else:
  81. raise ValueError("Invalid 'audio_url': A valid 'audio_url' must start "
  82. "with either 'data:audio' or 'http'.")
  83. return librosa.load(BytesIO(audio_bytes), sr=None)
  84. async def async_get_and_parse_audio(audio_url: str) -> MultiModalDataDict:
  85. audio, sr = await async_fetch_audio(audio_url)
  86. return {"audio": (audio, sr)}
  87. async def async_get_and_parse_image(image_url: str) -> MultiModalDataDict:
  88. image = await async_fetch_image(image_url)
  89. return {"image": image}
  90. def encode_audio_base64(
  91. audio: np.ndarray,
  92. sampling_rate: int,
  93. ) -> str:
  94. """Encode audio as base64."""
  95. buffered = BytesIO()
  96. soundfile.write(buffered, audio, sampling_rate, format="WAV")
  97. return base64.b64encode(buffered.getvalue()).decode('utf-8')
  98. def encode_image_base64(
  99. image: Image.Image,
  100. *,
  101. image_mode: str = "RGB",
  102. format: str = "JPEG",
  103. ) -> str:
  104. """
  105. Encode a pillow image to base64 format.
  106. By default, the image is converted into RGB format before being encoded.
  107. """
  108. buffered = BytesIO()
  109. image = image.convert(image_mode)
  110. image.save(buffered, format)
  111. return base64.b64encode(buffered.getvalue()).decode('utf-8')
  112. def load_image_from_base64(image: Union[bytes, str]) -> Image.Image:
  113. """Load image from base64 format."""
  114. return _load_image_from_bytes(base64.b64decode(image))
  115. def rescale_image_size(image: Image.Image,
  116. size_factor: float,
  117. transpose: int = -1) -> Image.Image:
  118. """Rescale the dimensions of an image by a constant factor."""
  119. new_width = int(image.width * size_factor)
  120. new_height = int(image.height * size_factor)
  121. image = image.resize((new_width, new_height))
  122. if transpose >= 0:
  123. image = image.transpose(Image.Transpose(transpose))
  124. return image