__init__.py 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  1. from __future__ import annotations
  2. import os
  3. import re
  4. import io
  5. import base64
  6. from io import BytesIO
  7. from pathlib import Path
  8. from typing import Optional
  9. try:
  10. from PIL.Image import open as open_image, new as new_image
  11. from PIL.Image import FLIP_LEFT_RIGHT, ROTATE_180, ROTATE_270, ROTATE_90
  12. has_requirements = True
  13. except ImportError:
  14. has_requirements = False
  15. from ..typing import ImageType, Union, Image
  16. from ..errors import MissingRequirementsError
  17. MEDIA_TYPE_MAP: dict[str, str] = {
  18. "image/png": "png",
  19. "image/jpeg": "jpg",
  20. "image/gif": "gif",
  21. "image/webp": "webp",
  22. }
  23. EXTENSIONS_MAP: dict[str, str] = {
  24. # Image
  25. "png": "image/png",
  26. "jpg": "image/jpeg",
  27. "jpeg": "image/jpeg",
  28. "gif": "image/gif",
  29. "webp": "image/webp",
  30. # Audio
  31. "wav": "audio/wav",
  32. "mp3": "audio/mpeg",
  33. "flac": "audio/flac",
  34. "opus": "audio/opus",
  35. "ogg": "audio/ogg",
  36. "m4a": "audio/m4a",
  37. # Video
  38. "mkv": "video/x-matroska",
  39. "webm": "video/webm",
  40. "mp4": "video/mp4",
  41. }
  42. def to_image(image: ImageType, is_svg: bool = False) -> Image:
  43. """
  44. Converts the input image to a PIL Image object.
  45. Args:
  46. image (Union[str, bytes, Image]): The input image.
  47. Returns:
  48. Image: The converted PIL Image object.
  49. """
  50. if not has_requirements:
  51. raise MissingRequirementsError('Install "pillow" package for images')
  52. if isinstance(image, str) and image.startswith("data:"):
  53. is_data_uri_an_image(image)
  54. image = extract_data_uri(image)
  55. if is_svg:
  56. try:
  57. import cairosvg
  58. except ImportError:
  59. raise MissingRequirementsError('Install "cairosvg" package for svg images')
  60. if not isinstance(image, bytes):
  61. image = image.read()
  62. buffer = BytesIO()
  63. cairosvg.svg2png(image, write_to=buffer)
  64. return open_image(buffer)
  65. if isinstance(image, bytes):
  66. is_accepted_format(image)
  67. return open_image(BytesIO(image))
  68. elif not isinstance(image, Image):
  69. image = open_image(image)
  70. image.load()
  71. return image
  72. return image
  73. def is_allowed_extension(filename: str) -> Optional[str]:
  74. """
  75. Checks if the given filename has an allowed extension.
  76. Args:
  77. filename (str): The filename to check.
  78. Returns:
  79. bool: True if the extension is allowed, False otherwise.
  80. """
  81. ext = os.path.splitext(filename)[1][1:].lower() if '.' in filename else None
  82. return EXTENSIONS_MAP[ext] if ext in EXTENSIONS_MAP else None
  83. def is_data_an_media(data, filename: str = None) -> str:
  84. content_type = is_data_an_audio(data, filename)
  85. if content_type is not None:
  86. return content_type
  87. if isinstance(data, bytes):
  88. return is_accepted_format(data)
  89. return is_data_uri_an_image(data)
  90. def is_data_an_audio(data_uri: str = None, filename: str = None) -> str:
  91. if filename:
  92. if filename.endswith(".wav"):
  93. return "audio/wav"
  94. elif filename.endswith(".mp3"):
  95. return "audio/mpeg"
  96. elif filename.endswith(".m4a"):
  97. return "audio/m4a"
  98. if isinstance(data_uri, str):
  99. audio_format = re.match(r'^data:(audio/\w+);base64,', data_uri)
  100. if audio_format:
  101. return audio_format.group(1)
  102. def is_data_uri_an_image(data_uri: str) -> bool:
  103. """
  104. Checks if the given data URI represents an image.
  105. Args:
  106. data_uri (str): The data URI to check.
  107. Raises:
  108. ValueError: If the data URI is invalid or the image format is not allowed.
  109. """
  110. # Check if the data URI starts with 'data:image' and contains an image format (e.g., jpeg, png, gif)
  111. if not re.match(r'data:image/(\w+);base64,', data_uri):
  112. raise ValueError("Invalid data URI image.")
  113. # Extract the image format from the data URI
  114. image_format = re.match(r'data:image/(\w+);base64,', data_uri).group(1).lower()
  115. # Check if the image format is one of the allowed formats (jpg, jpeg, png, gif)
  116. if image_format not in EXTENSIONS_MAP and image_format != "svg+xml":
  117. raise ValueError("Invalid image format (from mime file type).")
  118. def is_accepted_format(binary_data: bytes) -> str:
  119. """
  120. Checks if the given binary data represents an image with an accepted format.
  121. Args:
  122. binary_data (bytes): The binary data to check.
  123. Raises:
  124. ValueError: If the image format is not allowed.
  125. """
  126. if binary_data.startswith(b'\xFF\xD8\xFF'):
  127. return "image/jpeg"
  128. elif binary_data.startswith(b'\x89PNG\r\n\x1a\n'):
  129. return "image/png"
  130. elif binary_data.startswith(b'GIF87a') or binary_data.startswith(b'GIF89a'):
  131. return "image/gif"
  132. elif binary_data.startswith(b'\x89JFIF') or binary_data.startswith(b'JFIF\x00'):
  133. return "image/jpeg"
  134. elif binary_data.startswith(b'\xFF\xD8'):
  135. return "image/jpeg"
  136. elif binary_data.startswith(b'RIFF') and binary_data[8:12] == b'WEBP':
  137. return "image/webp"
  138. else:
  139. raise ValueError("Invalid image format (from magic code).")
  140. def extract_data_uri(data_uri: str) -> bytes:
  141. """
  142. Extracts the binary data from the given data URI.
  143. Args:
  144. data_uri (str): The data URI.
  145. Returns:
  146. bytes: The extracted binary data.
  147. """
  148. data = data_uri.split(",")[-1]
  149. data = base64.b64decode(data)
  150. return data
  151. def get_orientation(image: Image) -> int:
  152. """
  153. Gets the orientation of the given image.
  154. Args:
  155. image (Image): The image.
  156. Returns:
  157. int: The orientation value.
  158. """
  159. exif_data = image.getexif() if hasattr(image, 'getexif') else image._getexif()
  160. if exif_data is not None:
  161. orientation = exif_data.get(274) # 274 corresponds to the orientation tag in EXIF
  162. if orientation is not None:
  163. return orientation
  164. def process_image(image: Image, new_width: int, new_height: int) -> Image:
  165. """
  166. Processes the given image by adjusting its orientation and resizing it.
  167. Args:
  168. image (Image): The image to process.
  169. new_width (int): The new width of the image.
  170. new_height (int): The new height of the image.
  171. Returns:
  172. Image: The processed image.
  173. """
  174. # Fix orientation
  175. orientation = get_orientation(image)
  176. if orientation:
  177. if orientation > 4:
  178. image = image.transpose(FLIP_LEFT_RIGHT)
  179. if orientation in [3, 4]:
  180. image = image.transpose(ROTATE_180)
  181. if orientation in [5, 6]:
  182. image = image.transpose(ROTATE_270)
  183. if orientation in [7, 8]:
  184. image = image.transpose(ROTATE_90)
  185. # Resize image
  186. image.thumbnail((new_width, new_height))
  187. # Remove transparency
  188. if image.mode == "RGBA":
  189. image.load()
  190. white = new_image('RGB', image.size, (255, 255, 255))
  191. white.paste(image, mask=image.split()[-1])
  192. return white
  193. # Convert to RGB for jpg format
  194. elif image.mode != "RGB":
  195. image = image.convert("RGB")
  196. return image
  197. def to_bytes(image: ImageType) -> bytes:
  198. """
  199. Converts the given image to bytes.
  200. Args:
  201. image (ImageType): The image to convert.
  202. Returns:
  203. bytes: The image as bytes.
  204. """
  205. if isinstance(image, bytes):
  206. return image
  207. elif isinstance(image, str) and image.startswith("data:"):
  208. is_data_an_media(image)
  209. return extract_data_uri(image)
  210. elif isinstance(image, Image):
  211. bytes_io = BytesIO()
  212. image.save(bytes_io, image.format)
  213. image.seek(0)
  214. return bytes_io.getvalue()
  215. elif isinstance(image, (str, os.PathLike)):
  216. return Path(image).read_bytes()
  217. elif isinstance(image, Path):
  218. return image.read_bytes()
  219. else:
  220. try:
  221. image.seek(0)
  222. except (AttributeError, io.UnsupportedOperation):
  223. pass
  224. return image.read()
  225. def to_data_uri(image: ImageType, filename: str = None) -> str:
  226. if not isinstance(image, str):
  227. data = to_bytes(image)
  228. data_base64 = base64.b64encode(data).decode()
  229. return f"data:{is_data_an_media(data, filename)};base64,{data_base64}"
  230. return image
  231. def to_input_audio(audio: ImageType, filename: str = None) -> str:
  232. if not isinstance(audio, str):
  233. if filename is not None and (filename.endswith(".wav") or filename.endswith(".mp3")):
  234. return {
  235. "data": base64.b64encode(to_bytes(audio)).decode(),
  236. "format": "wav" if filename.endswith(".wav") else "mp3"
  237. }
  238. raise ValueError("Invalid input audio")
  239. audio = re.match(r'^data:audio/(\w+);base64,(.+?)', audio)
  240. if audio:
  241. return {
  242. "data": audio.group(2),
  243. "format": audio.group(1).replace("mpeg", "mp3")
  244. }
  245. raise ValueError("Invalid input audio")
  246. def use_aspect_ratio(extra_data: dict, aspect_ratio: str) -> Image:
  247. extra_data = {key: value for key, value in extra_data.items() if value is not None}
  248. if aspect_ratio == "1:1":
  249. extra_data = {
  250. "width": 1024,
  251. "height": 1024,
  252. **extra_data
  253. }
  254. elif aspect_ratio == "16:9":
  255. extra_data = {
  256. "width": 832,
  257. "height": 480,
  258. **extra_data
  259. }
  260. elif aspect_ratio == "9:16":
  261. extra_data = {
  262. "width": 480,
  263. "height": 832,
  264. **extra_data
  265. }
  266. return extra_data
  267. class ImageDataResponse():
  268. def __init__(
  269. self,
  270. images: Union[str, list],
  271. alt: str,
  272. ):
  273. self.images = images
  274. self.alt = alt
  275. def get_list(self) -> list[str]:
  276. return [self.images] if isinstance(self.images, str) else self.images
  277. class ImageRequest:
  278. def __init__(
  279. self,
  280. options: dict = {}
  281. ):
  282. self.options = options
  283. def get(self, key: str):
  284. return self.options.get(key)