image.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. from __future__ import annotations
  2. import os
  3. import re
  4. import time
  5. import uuid
  6. from io import BytesIO
  7. import base64
  8. import asyncio
  9. from aiohttp import ClientSession, ClientError
  10. try:
  11. from PIL.Image import open as open_image, new as new_image
  12. from PIL.Image import FLIP_LEFT_RIGHT, ROTATE_180, ROTATE_270, ROTATE_90
  13. has_requirements = True
  14. except ImportError:
  15. has_requirements = False
  16. from .typing import ImageType, Union, Image, Optional, Cookies
  17. from .errors import MissingRequirementsError
  18. from .providers.response import ResponseType
  19. from .requests.aiohttp import get_connector
  20. from . import debug
  21. ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif', 'webp', 'svg'}
  22. EXTENSIONS_MAP: dict[str, str] = {
  23. "image/png": "png",
  24. "image/jpeg": "jpg",
  25. "image/gif": "gif",
  26. "image/webp": "webp",
  27. }
  28. # Define the directory for generated images
  29. images_dir = "./generated_images"
  30. def fix_url(url: str) -> str:
  31. """ replace ' ' by '+' (to be markdown compliant)"""
  32. return url.replace(" ","+")
  33. def fix_title(title: str) -> str:
  34. if title:
  35. return title.replace("\n", "").replace('"', '')
  36. return ""
  37. def to_image(image: ImageType, is_svg: bool = False) -> Image:
  38. """
  39. Converts the input image to a PIL Image object.
  40. Args:
  41. image (Union[str, bytes, Image]): The input image.
  42. Returns:
  43. Image: The converted PIL Image object.
  44. """
  45. if not has_requirements:
  46. raise MissingRequirementsError('Install "pillow" package for images')
  47. if isinstance(image, str):
  48. is_data_uri_an_image(image)
  49. image = extract_data_uri(image)
  50. if is_svg:
  51. try:
  52. import cairosvg
  53. except ImportError:
  54. raise MissingRequirementsError('Install "cairosvg" package for svg images')
  55. if not isinstance(image, bytes):
  56. image = image.read()
  57. buffer = BytesIO()
  58. cairosvg.svg2png(image, write_to=buffer)
  59. return open_image(buffer)
  60. if isinstance(image, bytes):
  61. is_accepted_format(image)
  62. return open_image(BytesIO(image))
  63. elif not isinstance(image, Image):
  64. image = open_image(image)
  65. image.load()
  66. return image
  67. return image
  68. def is_allowed_extension(filename: str) -> bool:
  69. """
  70. Checks if the given filename has an allowed extension.
  71. Args:
  72. filename (str): The filename to check.
  73. Returns:
  74. bool: True if the extension is allowed, False otherwise.
  75. """
  76. return '.' in filename and \
  77. filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
  78. def is_data_uri_an_image(data_uri: str) -> bool:
  79. """
  80. Checks if the given data URI represents an image.
  81. Args:
  82. data_uri (str): The data URI to check.
  83. Raises:
  84. ValueError: If the data URI is invalid or the image format is not allowed.
  85. """
  86. # Check if the data URI starts with 'data:image' and contains an image format (e.g., jpeg, png, gif)
  87. if not re.match(r'data:image/(\w+);base64,', data_uri):
  88. raise ValueError("Invalid data URI image.")
  89. # Extract the image format from the data URI
  90. image_format = re.match(r'data:image/(\w+);base64,', data_uri).group(1).lower()
  91. # Check if the image format is one of the allowed formats (jpg, jpeg, png, gif)
  92. if image_format not in ALLOWED_EXTENSIONS and image_format != "svg+xml":
  93. raise ValueError("Invalid image format (from mime file type).")
  94. def is_accepted_format(binary_data: bytes) -> str:
  95. """
  96. Checks if the given binary data represents an image with an accepted format.
  97. Args:
  98. binary_data (bytes): The binary data to check.
  99. Raises:
  100. ValueError: If the image format is not allowed.
  101. """
  102. if binary_data.startswith(b'\xFF\xD8\xFF'):
  103. return "image/jpeg"
  104. elif binary_data.startswith(b'\x89PNG\r\n\x1a\n'):
  105. return "image/png"
  106. elif binary_data.startswith(b'GIF87a') or binary_data.startswith(b'GIF89a'):
  107. return "image/gif"
  108. elif binary_data.startswith(b'\x89JFIF') or binary_data.startswith(b'JFIF\x00'):
  109. return "image/jpeg"
  110. elif binary_data.startswith(b'\xFF\xD8'):
  111. return "image/jpeg"
  112. elif binary_data.startswith(b'RIFF') and binary_data[8:12] == b'WEBP':
  113. return "image/webp"
  114. else:
  115. raise ValueError("Invalid image format (from magic code).")
  116. def extract_data_uri(data_uri: str) -> bytes:
  117. """
  118. Extracts the binary data from the given data URI.
  119. Args:
  120. data_uri (str): The data URI.
  121. Returns:
  122. bytes: The extracted binary data.
  123. """
  124. data = data_uri.split(",")[-1]
  125. data = base64.b64decode(data)
  126. return data
  127. def get_orientation(image: Image) -> int:
  128. """
  129. Gets the orientation of the given image.
  130. Args:
  131. image (Image): The image.
  132. Returns:
  133. int: The orientation value.
  134. """
  135. exif_data = image.getexif() if hasattr(image, 'getexif') else image._getexif()
  136. if exif_data is not None:
  137. orientation = exif_data.get(274) # 274 corresponds to the orientation tag in EXIF
  138. if orientation is not None:
  139. return orientation
  140. def process_image(image: Image, new_width: int, new_height: int) -> Image:
  141. """
  142. Processes the given image by adjusting its orientation and resizing it.
  143. Args:
  144. image (Image): The image to process.
  145. new_width (int): The new width of the image.
  146. new_height (int): The new height of the image.
  147. Returns:
  148. Image: The processed image.
  149. """
  150. # Fix orientation
  151. orientation = get_orientation(image)
  152. if orientation:
  153. if orientation > 4:
  154. image = image.transpose(FLIP_LEFT_RIGHT)
  155. if orientation in [3, 4]:
  156. image = image.transpose(ROTATE_180)
  157. if orientation in [5, 6]:
  158. image = image.transpose(ROTATE_270)
  159. if orientation in [7, 8]:
  160. image = image.transpose(ROTATE_90)
  161. # Resize image
  162. image.thumbnail((new_width, new_height))
  163. # Remove transparency
  164. if image.mode == "RGBA":
  165. image.load()
  166. white = new_image('RGB', image.size, (255, 255, 255))
  167. white.paste(image, mask=image.split()[-1])
  168. return white
  169. # Convert to RGB for jpg format
  170. elif image.mode != "RGB":
  171. image = image.convert("RGB")
  172. return image
  173. def to_base64_jpg(image: Image, compression_rate: float) -> str:
  174. """
  175. Converts the given image to a base64-encoded string.
  176. Args:
  177. image (Image.Image): The image to convert.
  178. compression_rate (float): The compression rate (0.0 to 1.0).
  179. Returns:
  180. str: The base64-encoded image.
  181. """
  182. output_buffer = BytesIO()
  183. image.save(output_buffer, format="JPEG", quality=int(compression_rate * 100))
  184. return base64.b64encode(output_buffer.getvalue()).decode()
  185. def format_images_markdown(images: Union[str, list], alt: str, preview: Union[str, list] = None) -> str:
  186. """
  187. Formats the given images as a markdown string.
  188. Args:
  189. images: The images to format.
  190. alt (str): The alt for the images.
  191. preview (str, optional): The preview URL format. Defaults to "{image}?w=200&h=200".
  192. Returns:
  193. str: The formatted markdown string.
  194. """
  195. if isinstance(images, list) and len(images) == 1:
  196. images = images[0]
  197. if isinstance(images, str):
  198. result = f"[![{fix_title(alt)}]({fix_url(preview.replace('{image}', images) if preview else images)})]({fix_url(images)})"
  199. else:
  200. if not isinstance(preview, list):
  201. preview = [preview.replace('{image}', image) if preview else image for image in images]
  202. result = "\n".join(
  203. f"[![#{idx+1} {fix_title(alt)}]({fix_url(preview[idx])})]({fix_url(image)})"
  204. for idx, image in enumerate(images)
  205. )
  206. start_flag = "<!-- generated images start -->\n"
  207. end_flag = "<!-- generated images end -->\n"
  208. return f"\n{start_flag}{result}\n{end_flag}\n"
  209. def to_bytes(image: ImageType) -> bytes:
  210. """
  211. Converts the given image to bytes.
  212. Args:
  213. image (ImageType): The image to convert.
  214. Returns:
  215. bytes: The image as bytes.
  216. """
  217. if isinstance(image, bytes):
  218. return image
  219. elif isinstance(image, str):
  220. is_data_uri_an_image(image)
  221. return extract_data_uri(image)
  222. elif isinstance(image, Image):
  223. bytes_io = BytesIO()
  224. image.save(bytes_io, image.format)
  225. image.seek(0)
  226. return bytes_io.getvalue()
  227. else:
  228. image.seek(0)
  229. return image.read()
  230. def to_data_uri(image: ImageType) -> str:
  231. if not isinstance(image, str):
  232. data = to_bytes(image)
  233. data_base64 = base64.b64encode(data).decode()
  234. return f"data:{is_accepted_format(data)};base64,{data_base64}"
  235. return image
  236. # Function to ensure the images directory exists
  237. def ensure_images_dir():
  238. os.makedirs(images_dir, exist_ok=True)
  239. async def copy_images(
  240. images: list[str],
  241. cookies: Optional[Cookies] = None,
  242. proxy: Optional[str] = None
  243. ) -> list[str]:
  244. ensure_images_dir()
  245. async with ClientSession(
  246. connector=get_connector(proxy=proxy),
  247. cookies=cookies
  248. ) as session:
  249. async def copy_image(image: str) -> str:
  250. target = os.path.join(images_dir, f"{int(time.time())}_{str(uuid.uuid4())}")
  251. if image.startswith("data:"):
  252. with open(target, "wb") as f:
  253. f.write(extract_data_uri(image))
  254. else:
  255. try:
  256. async with session.get(image) as response:
  257. response.raise_for_status()
  258. with open(target, "wb") as f:
  259. async for chunk in response.content.iter_chunked(4096):
  260. f.write(chunk)
  261. except ClientError as e:
  262. debug.log(f"copy_images failed: {e.__class__.__name__}: {e}")
  263. return image
  264. with open(target, "rb") as f:
  265. extension = is_accepted_format(f.read(12)).split("/")[-1]
  266. extension = "jpg" if extension == "jpeg" else extension
  267. new_target = f"{target}.{extension}"
  268. os.rename(target, new_target)
  269. return f"/images/{os.path.basename(new_target)}"
  270. return await asyncio.gather(*[copy_image(image) for image in images])
  271. class ImageResponse(ResponseType):
  272. def __init__(
  273. self,
  274. images: Union[str, list],
  275. alt: str,
  276. options: dict = {}
  277. ):
  278. self.images = images
  279. self.alt = alt
  280. self.options = options
  281. def __str__(self) -> str:
  282. return format_images_markdown(self.images, self.alt, self.get("preview"))
  283. def get(self, key: str):
  284. return self.options.get(key)
  285. def get_list(self) -> list[str]:
  286. return [self.images] if isinstance(self.images, str) else self.images
  287. class ImagePreview(ImageResponse):
  288. def __str__(self):
  289. return ""
  290. def to_string(self):
  291. return super().__str__()
  292. class ImageDataResponse():
  293. def __init__(
  294. self,
  295. images: Union[str, list],
  296. alt: str,
  297. ):
  298. self.images = images
  299. self.alt = alt
  300. def get_list(self) -> list[str]:
  301. return [self.images] if isinstance(self.images, str) else self.images
  302. class ImageRequest:
  303. def __init__(
  304. self,
  305. options: dict = {}
  306. ):
  307. self.options = options
  308. def get(self, key: str):
  309. return self.options.get(key)