image.py 11 KB

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