Skip to content

The agent that grows with you

fix(telegram): harden image pre-compression for salvage of #74893

Teknium333bf120a5d2
diff --git a/plugins/platforms/telegram/adapter.py b/plugins/platforms/telegram/adapter.py
index 5fa4dda7bba..2fd66268b83 100644
--- a/plugins/platforms/telegram/adapter.py
+++ b/plugins/platforms/telegram/adapter.py
@@ -4560,6 +4560,31 @@ class TelegramAdapter(BasePlatformAdapter):
"Bind-mount a host directory and emit the host-visible path in MEDIA: for gateway file delivery.)")
return error
+ @staticmethod
+ def _sniff_raster_format(image_path: str) -> Optional[str]:
+ """Identify convertible raster formats by magic bytes.
+
+ Replacement for stdlib ``imghdr`` (removed in Python 3.13). Returns
+ one of ``png``/``gif``/``webp``/``bmp``/``tiff`` or None.
+ """
+ try:
+ with open(image_path, "rb") as fh:
+ head = fh.read(16)
+ except OSError:
+ return None
+ if head.startswith(b"\x89PNG\r\n\x1a\n"):
+ return "png"
+ if head.startswith((b"GIF87a", b"GIF89a")):
+ # GIFs are excluded: converting flattens animations to one frame.
+ return None
+ if head.startswith(b"RIFF") and head[8:12] == b"WEBP":
+ return "webp"
+ if head.startswith(b"BM"):
+ return "bmp"
+ if head.startswith((b"II*\x00", b"MM\x00*")):
+ return "tiff"
+ return None
+
def _compress_image_to_jpeg(self, image_path: str) -> Optional[str]:
"""Pre-compress a large image to progressive JPEG before upload.
@@ -4572,9 +4597,7 @@ class TelegramAdapter(BasePlatformAdapter):
used as-is (already small / already JPEG / Pillow not available). The
caller is responsible for cleaning up the returned temp file.
"""
- import shutil
import tempfile
- import imghdr
try:
file_size = os.path.getsize(image_path)
@@ -4591,8 +4614,10 @@ class TelegramAdapter(BasePlatformAdapter):
if file_size < self._IMG_COMPRESS_THRESHOLD_BYTES:
return None
- # Only convert raster image formats (png, gif, webp, bmp, tiff)
- if imghdr.what(image_path) not in ("png", "gif", "webp", "bmp", "tiff"):
+ # Only convert raster image formats (png, gif, webp, bmp, tiff).
+ # Magic-byte sniff instead of the stdlib imghdr module, which was
+ # removed in Python 3.13.
+ if self._sniff_raster_format(image_path) is None:
return None
try:
@@ -4604,16 +4629,18 @@ class TelegramAdapter(BasePlatformAdapter):
try:
img = Image.open(image_path)
- if len(img.getbands()) == 4:
- img = img.convert("RGB")
- elif img.mode in ("RGBA", "LA", "P"):
- # Build white background for alpha-blended images
+ if img.mode in ("RGBA", "LA", "P"):
+ # Alpha-capable modes: composite onto a white background so
+ # transparency doesn't render as black in the JPEG.
background = Image.new("RGB", img.size, (255, 255, 255))
if img.mode == "P":
img = img.convert("RGBA")
- background.paste(img, mask=img.split()[-1])
+ if img.mode in ("RGBA", "LA"):
+ background.paste(img, mask=img.split()[-1])
+ else:
+ background.paste(img)
img = background
- elif img.mode not in ("RGB",):
+ elif img.mode != "RGB":
img = img.convert("RGB")
max_w, max_h = img.size
@@ -4624,11 +4651,9 @@ class TelegramAdapter(BasePlatformAdapter):
fd, tmp = tempfile.mkstemp(
suffix=".jpg",
- dir=os.path.join(DEFAULT_OUTPUT_DIR, "tmp"),
prefix="tg_compress_",
)
os.close(fd)
- os.makedirs(os.path.dirname(tmp), exist_ok=True)
img.save(
tmp,
diff --git a/tests/gateway/test_telegram_image_precompress.py b/tests/gateway/test_telegram_image_precompress.py
new file mode 100644
index 00000000000..3ed1faf057e
--- /dev/null
+++ b/tests/gateway/test_telegram_image_precompress.py
@@ -0,0 +1,115 @@
+"""Tests for Telegram large-image pre-compression (salvage of PR #74893).
+
+Behind slow HTTP proxies, raw PNGs > 1-2MB exceed PTB's media_write_timeout.
+``_compress_image_to_jpeg`` converts large raster images to progressive JPEG
+(resizing above 1600px) before upload. These tests exercise the real Pillow
+path with real file I/O — no mocks on the compression itself.
+"""
+
+import os
+import sys
+from pathlib import Path
+
+import pytest
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
+
+PIL = pytest.importorskip("PIL")
+from PIL import Image # noqa: E402
+
+from gateway.platforms.base import PlatformConfig # noqa: E402
+from plugins.platforms.telegram.adapter import TelegramAdapter # noqa: E402
+
+
+def _adapter():
+ return TelegramAdapter(PlatformConfig(enabled=True, token="***"))
+
+
+def _make_png(path, size=(2400, 1800), noisy=True, mode="RGB"):
+ """Write a PNG large enough to cross the 1MB compression threshold."""
+ if noisy:
+ # True random noise defeats PNG compression so the file exceeds 1MB.
+ nbytes = size[0] * size[1] * len(mode)
+ img = Image.frombytes(mode, size, os.urandom(nbytes))
+ else:
+ img = Image.new(mode, size)
+ img.save(path, "PNG")
+ return path
+
+
+class TestSniffRasterFormat:
+ def test_png_magic(self, tmp_path):
+ p = tmp_path / "x.png"
+ Image.new("RGB", (4, 4)).save(p, "PNG")
+ assert TelegramAdapter._sniff_raster_format(str(p)) == "png"
+
+ def test_webp_magic(self, tmp_path):
+ p = tmp_path / "x.webp"
+ Image.new("RGB", (4, 4)).save(p, "WEBP")
+ assert TelegramAdapter._sniff_raster_format(str(p)) == "webp"
+
+ def test_gif_excluded(self, tmp_path):
+ p = tmp_path / "x.gif"
+ Image.new("P", (4, 4)).save(p, "GIF")
+ assert TelegramAdapter._sniff_raster_format(str(p)) is None
+
+ def test_non_image(self, tmp_path):
+ p = tmp_path / "x.bin"
+ p.write_bytes(b"not an image at all")
+ assert TelegramAdapter._sniff_raster_format(str(p)) is None
+
+ def test_missing_file(self, tmp_path):
+ assert TelegramAdapter._sniff_raster_format(str(tmp_path / "nope.png")) is None
+
+
+class TestCompressImageToJpeg:
+ def test_large_png_is_compressed_and_resized(self, tmp_path):
+ adapter = _adapter()
+ src = _make_png(tmp_path / "big.png")
+ assert os.path.getsize(src) > adapter._IMG_COMPRESS_THRESHOLD_BYTES
+
+ out = adapter._compress_image_to_jpeg(str(src))
+ assert out is not None
+ try:
+ assert out.endswith(".jpg")
+ assert os.path.getsize(out) < os.path.getsize(src)
+ with Image.open(out) as jpg:
+ assert jpg.format == "JPEG"
+ assert max(jpg.size) <= adapter._IMG_MAX_DIMENSION
+ finally:
+ os.remove(out)
+
+ def test_small_png_is_left_alone(self, tmp_path):
+ adapter = _adapter()
+ src = tmp_path / "small.png"
+ Image.new("RGB", (32, 32)).save(src, "PNG")
+ assert adapter._compress_image_to_jpeg(str(src)) is None
+
+ def test_jpeg_is_left_alone(self, tmp_path):
+ adapter = _adapter()
+ src = tmp_path / "photo.jpg"
+ Image.new("RGB", (2000, 2000)).save(src, "JPEG")
+ assert adapter._compress_image_to_jpeg(str(src)) is None
+
+ def test_transparent_png_gets_white_background(self, tmp_path):
+ """RGBA must composite onto white, not collapse to a black background."""
+ adapter = _adapter()
+ src = tmp_path / "transparent.png"
+ img = Image.new("RGBA", (2000, 2000), (0, 0, 0, 0)) # fully transparent
+ img.save(src, "PNG")
+ # Fully-transparent flat PNG compresses tiny; force it over threshold
+ # by lowering the adapter threshold for this test.
+ adapter._IMG_COMPRESS_THRESHOLD_BYTES = 0
+
+ out = adapter._compress_image_to_jpeg(str(src))
+ assert out is not None
+ try:
+ with Image.open(out) as jpg:
+ # Transparent areas must render white (255), not black (0).
+ assert jpg.getpixel((10, 10))[0] > 200
+ finally:
+ os.remove(out)
+
+ def test_missing_file_returns_none(self, tmp_path):
+ adapter = _adapter()
+ assert adapter._compress_image_to_jpeg(str(tmp_path / "gone.png")) is None