Skip to content

The agent that grows with you

fix(telegram): attach real video geometry and a thumbnail so large uploads aren't square

Steve Hsu97051e419441
diff --git a/plugins/platforms/telegram/adapter.py b/plugins/platforms/telegram/adapter.py
index f367ea7eb65..4e6aceee668 100644
--- a/plugins/platforms/telegram/adapter.py
+++ b/plugins/platforms/telegram/adapter.py
@@ -217,6 +217,72 @@ def _probe_voice_duration_seconds(path: str) -> Optional[int]:
return None
+def _probe_video_geometry(path: str) -> Dict[str, int]:
+ """``{"width", "height", "duration"}`` for a local video; ``{}`` when ffprobe can't read it.
+
+ Telegram runs its own video processing only for uploads under roughly 10 MB; above that it
+ stores the file as an unprocessed ``320x320`` video with ``duration=0``, so the message must
+ carry the real geometry or clients draw a square tile for any aspect ratio.
+ """
+ try:
+ import shutil
+ import subprocess
+ if not shutil.which("ffprobe"):
+ return {}
+ proc = subprocess.run(
+ ["ffprobe", "-v", "error", "-select_streams", "v:0",
+ "-show_entries", "stream=width,height", "-show_entries", "format=duration",
+ "-of", "json", path],
+ capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=20)
+ if proc.returncode != 0:
+ return {}
+ blob = json.loads(proc.stdout or "{}")
+ streams = blob.get("streams") or []
+ if not streams:
+ return {}
+ geometry = {"width": int(streams[0]["width"]), "height": int(streams[0]["height"])}
+ duration = _coerce_duration_seconds((blob.get("format") or {}).get("duration"))
+ if duration:
+ geometry["duration"] = duration
+ return geometry
+ except Exception:
+ logger.debug("[Telegram] video geometry probe failed for %s", path, exc_info=True)
+ return {}
+
+
+def _video_thumbnail_jpeg(path: str, duration: Optional[int]) -> Optional[str]:
+ """Write a 320px-wide JPEG frame for Telegram's ``thumbnail`` field; None on failure.
+
+ Telegram keeps a supplied thumbnail for the uploads it did not process itself — without one the
+ chat shows a square placeholder tile until the video is opened.
+ """
+ out = None
+ try:
+ import shutil
+ import subprocess
+ import tempfile
+ if not shutil.which("ffmpeg"):
+ return None
+ seek = max(1, int((duration or 3) * 0.25))
+ fd, out = tempfile.mkstemp(suffix=".jpg", prefix="hermes-tg-thumb-")
+ os.close(fd)
+ proc = subprocess.run(
+ ["ffmpeg", "-y", "-ss", str(seek), "-i", path, "-frames:v", "1",
+ "-vf", "scale=320:-2", "-q:v", "6", out],
+ capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=30)
+ if proc.returncode != 0 or not os.path.getsize(out):
+ with contextlib.suppress(OSError):
+ os.remove(out)
+ return None
+ return out
+ except Exception:
+ logger.debug("[Telegram] video thumbnail extraction failed for %s", path, exc_info=True)
+ if out:
+ with contextlib.suppress(OSError):
+ os.remove(out)
+ return None
+
+
def telegram_deps_present() -> bool:
"""PASSIVE registry ``check_fn``: is python-telegram-bot importable? Never installs
(``check_telegram_requirements`` is the active ``ensure_deps_fn``).
@@ -5190,13 +5256,36 @@ class TelegramAdapter(BasePlatformAdapter):
async def send_video(
self, chat_id: str, video_path: str, caption: Optional[str] = None, reply_to: Optional[str] = None,
metadata: Optional[Dict[str, Any]] = None, **kwargs) -> SendResult:
- """Send a video natively as a Telegram video message."""
- return await self._send_local_file(
- "Video", video_path, chat_id, reply_to, metadata, "video",
- lambda f: {"video": f, "caption": self._caption_1024(caption)},
- lambda e: self._warn_then(
- "video", e, super(TelegramAdapter, self).send_video(chat_id, video_path, caption, reply_to, metadata=metadata),
- ))
+ """Send a video natively as a Telegram video message.
+
+ Real geometry and a JPEG thumbnail ride along explicitly. Telegram only runs its own video
+ processing for uploads under roughly 10 MB; larger files come back as an unprocessed
+ ``320x320`` video with ``duration=0`` and no thumbnail, which clients then draw as a square
+ tile whatever the true aspect ratio (portrait reels and 16:9 clips alike).
+ """
+ geometry = await asyncio.to_thread(_probe_video_geometry, video_path)
+ thumb_path = (
+ await asyncio.to_thread(_video_thumbnail_jpeg, video_path, geometry.get("duration"))
+ if geometry else None
+ )
+ try:
+ def build_kwargs(f):
+ payload = {"video": f, "caption": self._caption_1024(caption), **geometry}
+ if thumb_path:
+ # A path (not an open handle) so python-telegram-bot loads the bytes once and a
+ # retry after a stale topic anchor still has a thumbnail to send.
+ payload["thumbnail"] = thumb_path
+ return payload
+
+ return await self._send_local_file(
+ "Video", video_path, chat_id, reply_to, metadata, "video", build_kwargs,
+ lambda e: self._warn_then(
+ "video", e, super(TelegramAdapter, self).send_video(chat_id, video_path, caption, reply_to, metadata=metadata),
+ ))
+ finally:
+ if thumb_path:
+ with contextlib.suppress(OSError):
+ os.remove(thumb_path)
async def send_image(
self, chat_id: str, image_url: str, caption: Optional[str] = None, reply_to: Optional[str] = None,
diff --git a/tests/gateway/test_telegram_video_metadata.py b/tests/gateway/test_telegram_video_metadata.py
new file mode 100644
index 00000000000..7444abaa87f
--- /dev/null
+++ b/tests/gateway/test_telegram_video_metadata.py
@@ -0,0 +1,114 @@
+"""Telegram videos over ~10 MB must carry explicit geometry and a thumbnail.
+
+Telegram runs its own video processing only for small uploads: above roughly 10 MB the
+``sendVideo`` response comes back as ``width=320 height=320 duration=0`` with no thumbnail, and
+clients then draw the message as a square tile whatever the real aspect ratio. Measured on one
+6 s 2560x1440 clip: 4.9 MB and 9.8 MB keep ``2560x1440``, duration 7 and a 320x180 thumbnail;
+14.8 MB, 19.4 MB and 23.0 MB degrade to the square placeholder, while the same 23.0 MB file sent
+with ``width``/``height``/``duration`` plus a JPEG ``thumbnail`` comes back ``2560x1440`` with a
+320x180 thumbnail.
+
+``TelegramAdapter.send_video`` therefore probes the local file and forwards that metadata, so
+portrait reels and landscape clips stay correct at any size.
+
+These tests confirm:
+ 1. the probed geometry and thumbnail reach ``bot.send_video``,
+ 2. a file ffprobe/ffmpeg cannot read still sends, just without metadata,
+ 3. the temporary thumbnail is removed after the send,
+ 4. on a real file, the helpers report the true geometry and a same-aspect thumbnail.
+"""
+import contextlib
+import os
+import shutil
+import subprocess
+from unittest.mock import AsyncMock, MagicMock
+
+import pytest
+
+from gateway.config import PlatformConfig
+from plugins.platforms.telegram import adapter as telegram_mod
+from plugins.platforms.telegram.adapter import TelegramAdapter
+
+
+def _make_adapter() -> TelegramAdapter:
+ adapter = TelegramAdapter(PlatformConfig(enabled=True, token="***"))
+ adapter._bot = MagicMock()
+ adapter._bot.send_video = AsyncMock(return_value=MagicMock(message_id=7))
+ return adapter
+
+
+async def test_send_video_forwards_geometry_and_thumbnail(monkeypatch, tmp_path):
+ """A video Telegram will not process itself still advertises its real shape."""
+ thumb = tmp_path / "thumb.jpg"
+ thumb.write_bytes(b"\xff\xd8\xff\xe0" + b"\x00" * 32)
+ monkeypatch.setattr(
+ telegram_mod, "_probe_video_geometry",
+ lambda _p: {"width": 2560, "height": 1440, "duration": 98})
+ monkeypatch.setattr(telegram_mod, "_video_thumbnail_jpeg", lambda _p, _d: str(thumb))
+ video = tmp_path / "clip.mp4"
+ video.write_bytes(b"\x00" * 64)
+
+ adapter = _make_adapter()
+ result = await adapter.send_video("123", str(video))
+
+ assert result.success is True
+ adapter._bot.send_video.assert_awaited_once()
+ kwargs = adapter._bot.send_video.await_args.kwargs
+ assert (kwargs["width"], kwargs["height"], kwargs["duration"]) == (2560, 1440, 98)
+ assert kwargs["thumbnail"] == str(thumb)
+ assert not thumb.exists(), "the temporary thumbnail must not be left behind"
+
+
+async def test_send_video_without_probeable_media_omits_metadata(monkeypatch, tmp_path):
+ """Unreadable or non-media files must still deliver, with no geometry kwargs."""
+ monkeypatch.setattr(telegram_mod, "_probe_video_geometry", lambda _p: {})
+ video = tmp_path / "clip.bin"
+ video.write_bytes(b"\x00" * 16)
+
+ adapter = _make_adapter()
+ result = await adapter.send_video("123", str(video))
+
+ assert result.success is True
+ kwargs = adapter._bot.send_video.await_args.kwargs
+ assert "width" not in kwargs and "height" not in kwargs
+ assert "duration" not in kwargs and "thumbnail" not in kwargs
+
+
+def test_video_helpers_degrade_without_ffmpeg(monkeypatch, tmp_path):
+ """No ffprobe/ffmpeg on the host means no metadata, never a failed send."""
+ monkeypatch.setattr(shutil, "which", lambda _name: None)
+ missing = str(tmp_path / "clip.mp4")
+
+ assert telegram_mod._probe_video_geometry(missing) == {}
+ assert telegram_mod._video_thumbnail_jpeg(missing, 5) is None
+
+
+ not (shutil.which("ffmpeg") and shutil.which("ffprobe")),
+ reason="needs ffmpeg/ffprobe to synthesise a real clip",
+)
+def test_video_helpers_read_real_geometry(tmp_path):
+ """On a real 16:9 clip the helpers report the true size and a 16:9 thumbnail."""
+ clip = tmp_path / "clip.mp4"
+ subprocess.run(
+ ["ffmpeg", "-y", "-f", "lavfi", "-i", "testsrc=size=640x360:rate=10:duration=2",
+ "-c:v", "libx264", "-pix_fmt", "yuv420p", str(clip)],
+ capture_output=True, check=True)
+
+ geometry = telegram_mod._probe_video_geometry(str(clip))
+ assert (geometry["width"], geometry["height"]) == (640, 360)
+ assert geometry["duration"] == 2
+
+ thumb = telegram_mod._video_thumbnail_jpeg(str(clip), geometry["duration"])
+ assert thumb is not None
+ try:
+ probe = subprocess.run(
+ ["ffprobe", "-v", "error", "-select_streams", "v:0",
+ "-show_entries", "stream=width,height", "-of", "csv=p=0", thumb],
+ capture_output=True, text=True, check=True).stdout.strip()
+ assert probe == "320,180", "thumbnails keep the source aspect ratio"
+ finally:
+ with contextlib.suppress(OSError):
+ os.remove(thumb)
diff --git a/tests/tools/test_telegram_send_message_video_metadata.py b/tests/tools/test_telegram_send_message_video_metadata.py
new file mode 100644
index 00000000000..2b460496828
--- /dev/null
+++ b/tests/tools/test_telegram_send_message_video_metadata.py
@@ -0,0 +1,80 @@
+"""The standalone ``hermes send`` Telegram path must carry video metadata too.
+
+Same root cause as the gateway adapter path (see
+``tests/gateway/test_telegram_video_metadata.py``): Telegram stops processing a video upload once
+it is large enough, and the message then has no geometry and no thumbnail, so clients render a
+square tile whatever the real aspect ratio. ``_telegram_send_one_media`` feeds the same helpers.
+
+These tests confirm:
+ 1. a video send forwards the probed geometry and the JPEG thumbnail,
+ 2. the temporary thumbnail is removed afterwards,
+ 3. ``[[as_document]]`` (force_document) keeps sending as a document with no geometry kwargs.
+"""
+from types import SimpleNamespace
+from unittest.mock import AsyncMock
+
+import pytest
+
+from tools.send_message_senders import _telegram_send_one_media
+
+
+def _fake_bot(**methods) -> SimpleNamespace:
+ return SimpleNamespace(**{
+ name: AsyncMock(return_value=SimpleNamespace(message_id=1)) for name in methods
+ })
+
+
+async def _send(bot, path, *, force_document=False):
+ return await _telegram_send_one_media(
+ bot, "1", str(path), False, caption=None, parse_mode=None,
+ has_html=False, thread_kwargs={}, force_document=force_document)
+
+
+async def test_video_send_carries_geometry_and_thumbnail(monkeypatch, tmp_path):
+ thumb = tmp_path / "thumb.jpg"
+ thumb.write_bytes(b"\xff\xd8\xff\xe0" + b"\x00" * 16)
+ monkeypatch.setattr("plugins.platforms.telegram.adapter._probe_video_geometry",
+ lambda _p: {"width": 720, "height": 1280, "duration": 59})
+ monkeypatch.setattr("plugins.platforms.telegram.adapter._video_thumbnail_jpeg",
+ lambda _p, _d: str(thumb))
+ video = tmp_path / "clip.mp4"
+ video.write_bytes(b"\x00" * 32)
+ bot = _fake_bot(send_video=True)
+
+ await _send(bot, video)
+
+ bot.send_video.assert_awaited_once()
+ kwargs = bot.send_video.await_args.kwargs
+ assert (kwargs["width"], kwargs["height"], kwargs["duration"]) == (720, 1280, 59)
+ assert kwargs["thumbnail"] == str(thumb)
+ assert not thumb.exists(), "the temporary thumbnail must not be left behind"
+
+
+async def test_video_send_without_probeable_file_still_sends(monkeypatch, tmp_path):
+ monkeypatch.setattr("plugins.platforms.telegram.adapter._probe_video_geometry", lambda _p: {})
+ video = tmp_path / "clip.mp4"
+ video.write_bytes(b"\x00" * 16)
+ bot = _fake_bot(send_video=True)
+
+ await _send(bot, video)
+
+ kwargs = bot.send_video.await_args.kwargs
+ assert "width" not in kwargs and "thumbnail" not in kwargs
+
+
+async def test_non_video_extension_never_probes_geometry(monkeypatch, tmp_path):
+ called = []
+ monkeypatch.setattr("plugins.platforms.telegram.adapter._probe_video_geometry",
+ lambda p: called.append(p) or {"width": 720, "height": 1280, "duration": 59})
+ archive = tmp_path / "bundle.zip"
+ archive.write_bytes(b"PK\x03\x04" + b"\x00" * 16)
+ bot = _fake_bot(send_document=True)
+
+ await _send(bot, archive)
+
+ bot.send_document.assert_awaited_once()
+ assert "width" not in bot.send_document.await_args.kwargs
+ assert called == [], "only video extensions carry video geometry"
diff --git a/tools/send_message_senders.py b/tools/send_message_senders.py
index 1e1e3530172..81eae913b36 100644
--- a/tools/send_message_senders.py
+++ b/tools/send_message_senders.py
@@ -203,24 +203,43 @@ async def _telegram_send_one_media(bot, chat_id, media_path, is_voice, *, captio
duration = await asyncio.to_thread(_probe_voice_duration_seconds, media_path)
if duration is not None:
media_kwargs["duration"] = duration
- with open(media_path, "rb") as f:
- try:
- return await _telegram_send_media(bot, chat_id, f, ext, is_voice, force_document, **media_kwargs)
- except Exception as media_err:
- err_text = str(media_err).lower()
- if _is_telegram_thread_not_found(media_err) and media_kwargs.get("message_thread_id"):
- logger.warning("Thread %s not found for media send, retrying without message_thread_id",
- media_kwargs.pop("message_thread_id"))
- elif media_kwargs.get("parse_mode") and ("parse" in err_text or "caption" in err_text):
- logger.warning("Caption parse failed for media send, retrying plain: %s",
- _sanitize_error_text(media_err))
- media_kwargs.pop("parse_mode", None)
- if not has_html and media_kwargs.get("caption"):
- media_kwargs["caption"] = _strip_mdv2_safe(media_kwargs["caption"])
- else:
- raise
- f.seek(0)
- return await _telegram_send_media(bot, chat_id, f, ext, is_voice, force_document, **media_kwargs)
+ thumb_path = None
+ if ext in _VIDEO_EXTS:
+ # Telegram processes only small video uploads itself; past that the message carries no
+ # geometry and no thumbnail, so clients draw a square tile (see the adapter helpers).
+ # Keyed on the extension because ``_telegram_send_media`` routes every video extension to
+ # ``sendVideo`` regardless of ``force_document`` (which only forces images to documents).
+ with contextlib.suppress(Exception):
+ from plugins.platforms.telegram.adapter import _probe_video_geometry, _video_thumbnail_jpeg
+ geometry = await asyncio.to_thread(_probe_video_geometry, media_path)
+ if geometry:
+ media_kwargs.update(geometry)
+ thumb_path = await asyncio.to_thread(_video_thumbnail_jpeg, media_path, geometry.get("duration"))
+ if thumb_path:
+ media_kwargs["thumbnail"] = thumb_path
+ try:
+ with open(media_path, "rb") as f:
+ try:
+ return await _telegram_send_media(bot, chat_id, f, ext, is_voice, force_document, **media_kwargs)
+ except Exception as media_err:
+ err_text = str(media_err).lower()
+ if _is_telegram_thread_not_found(media_err) and media_kwargs.get("message_thread_id"):
+ logger.warning("Thread %s not found for media send, retrying without message_thread_id",
+ media_kwargs.pop("message_thread_id"))
+ elif media_kwargs.get("parse_mode") and ("parse" in err_text or "caption" in err_text):
+ logger.warning("Caption parse failed for media send, retrying plain: %s",
+ _sanitize_error_text(media_err))
+ media_kwargs.pop("parse_mode", None)
+ if not has_html and media_kwargs.get("caption"):
+ media_kwargs["caption"] = _strip_mdv2_safe(media_kwargs["caption"])
+ else:
+ raise
+ f.seek(0)
+ return await _telegram_send_media(bot, chat_id, f, ext, is_voice, force_document, **media_kwargs)
+ finally:
+ if thumb_path:
+ with contextlib.suppress(OSError):
+ os.remove(thumb_path)
def _telegram_format(message):