images.py 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. """Préparation des images avant l'envoi à Claude (redimensionnement et compression)."""
  2. from __future__ import annotations
  3. import io
  4. import logging
  5. from PIL import Image, ImageOps, UnidentifiedImageError
  6. from .errors import UserFacingError
  7. from .media import ImageData
  8. logger = logging.getLogger("chatbot.images")
  9. # Claude redimensionne lui-même toute image dont le grand côté dépasse ~1568 px :
  10. # envoyer plus grand ne lui apporte rien.
  11. MAX_DIMENSION = 1568
  12. # Limite de l'API : 5 Mo une fois encodé en base64, soit environ 3,75 Mo bruts.
  13. API_MAX_BYTES = 3_750_000
  14. # Protection contre les images piégées (des milliards de pixels qui saturent la mémoire).
  15. Image.MAX_IMAGE_PIXELS = 80_000_000
  16. _DIRECT_FORMATS = {"JPEG": "image/jpeg", "PNG": "image/png", "GIF": "image/gif", "WEBP": "image/webp"}
  17. # Formats sans perte (captures d'écran, dessins…) : PNG essayé avant le JPEG.
  18. _LOSSLESS_FORMATS = {"PNG", "GIF", "BMP", "TIFF"}
  19. _PNG_MODES = ("L", "RGB") # modes sans transparence enregistrables tels quels en PNG
  20. class ImageError(UserFacingError):
  21. """Image illisible ou impossible à préparer, avec un message affichable sur Discord."""
  22. def prepare_image(data: bytes) -> ImageData:
  23. """Renvoie une image acceptée par l'API, en la réduisant ou la convertissant si besoin.
  24. Fonction bloquante (calculs sur l'image) : à appeler via asyncio.to_thread.
  25. """
  26. try:
  27. img = Image.open(io.BytesIO(data))
  28. img.load()
  29. except Image.DecompressionBombError:
  30. raise ImageError("Cette image est beaucoup trop grande (en pixels) pour que je puisse la lire.")
  31. except (UnidentifiedImageError, OSError, ValueError):
  32. raise ImageError("Je n'arrive pas à lire cette image. Formats conseillés : JPEG, PNG, GIF ou WebP.")
  33. fmt = (img.format or "").upper()
  34. if fmt in _DIRECT_FORMATS and len(data) <= API_MAX_BYTES and max(img.size) <= MAX_DIMENSION:
  35. return ImageData(media_type=_DIRECT_FORMATS[fmt], data=data) # déjà parfaite : envoyée telle quelle
  36. original_size, original_dims = len(data), img.size
  37. img.seek(0) # GIF ou WebP animé : première image uniquement
  38. img = ImageOps.exif_transpose(img) # respecte l'orientation des photos de téléphone
  39. if img.mode in ("1", "P"): # sinon réduite au plus proche voisin, qui abîme le texte
  40. img = img.convert("RGBA" if "transparency" in img.info else "RGB")
  41. img.thumbnail((MAX_DIMENSION, MAX_DIMENSION), Image.Resampling.LANCZOS)
  42. has_alpha = img.mode in ("RGBA", "LA", "PA") or (img.mode == "P" and "transparency" in img.info)
  43. result: ImageData | None = None
  44. # PNG si la taille le permet : garde la transparence, et le texte net des captures d'écran
  45. # (le JPEG le brouille). Les photos, déjà en JPEG, passent directement au JPEG.
  46. if has_alpha or fmt in _LOSSLESS_FORMATS:
  47. if has_alpha:
  48. png = _encode(img.convert("RGBA"), "PNG", optimize=True)
  49. else:
  50. png = _encode(img if img.mode in _PNG_MODES else img.convert("RGB"), "PNG", optimize=True)
  51. if len(png) <= API_MAX_BYTES:
  52. result = ImageData("image/png", png)
  53. elif has_alpha: # sinon fond blanc + JPEG
  54. background = Image.new("RGB", img.size, "white")
  55. background.paste(img.convert("RGBA"), mask=img.convert("RGBA").getchannel("A"))
  56. img = background
  57. if result is None:
  58. rgb = img.convert("RGB")
  59. for quality in (85, 75, 60, 45):
  60. jpeg = _encode(rgb, "JPEG", quality=quality, optimize=True)
  61. if len(jpeg) <= API_MAX_BYTES:
  62. result = ImageData("image/jpeg", jpeg)
  63. break
  64. else:
  65. raise ImageError("Je n'ai pas réussi à compresser suffisamment cette image.")
  66. logger.info("Image adaptée : %s %dx%d (%.1f Mo) → %s %dx%d (%.1f Mo)",
  67. fmt or "?", *original_dims, original_size / 1e6,
  68. result.media_type, *img.size, len(result.data) / 1e6)
  69. return result
  70. def _encode(img: Image.Image, fmt: str, **options) -> bytes:
  71. buffer = io.BytesIO()
  72. img.save(buffer, format=fmt, **options)
  73. return buffer.getvalue()