# SPDX-License-Identifier: Apache-2.0 """Decoding of request media (untrusted bytes): images (PNG / JPEG / WebP / BMP / GIF via Pillow, bounded pixel count), audio (WAV PCM 8/16/24/32-bit or IEEE float via the standard library; FLAC / OGG / MP3 when ``soundfile`` is installed; raw little-endian float32 PCM), video (a list of frames; a container file when PyAV is installed). Standard library + numpy + Pillow (+ optional soundfile / av).""" from __future__ import annotations import base64 import binascii import io import struct from typing import Any, Dict, List, Optional, Tuple import numpy as np MAX_IMAGE_PIXELS = 64_000_000 # decompression-bomb guard (8000 x 8000) MAX_AUDIO_SECONDS_IN = 600.0 # longer uploads are refused before decoding (the model uses 30 s) class MediaError(ValueError): pass def b64bytes(s: str, what: str) -> bytes: if not isinstance(s, str): raise MediaError(f"{what}: expected a base64 string") if s.startswith("data:"): if "," not in s: raise MediaError(f"{what}: malformed data URL") s = s.split(",", 1)[1] try: return base64.b64decode(s, validate=False) except (binascii.Error, ValueError) as e: raise MediaError(f"{what}: invalid base64 ({e})") from None def decode_image(data: bytes): """-> RGB PIL image (transparency composited onto white, as the official processor does).""" from PIL import Image Image.MAX_IMAGE_PIXELS = MAX_IMAGE_PIXELS try: im = Image.open(io.BytesIO(data)) if im.width * im.height > MAX_IMAGE_PIXELS: raise MediaError(f"image has {im.width}x{im.height} pixels (> {MAX_IMAGE_PIXELS})") im.load() from .preprocess.image import to_rgb_pil return to_rgb_pil(im) except MediaError: raise except Exception as e: # noqa: BLE001 -- PIL raises many types on corrupt input raise MediaError(f"cannot decode image: {type(e).__name__}: {e}") from None def _wav(data: bytes) -> Tuple[np.ndarray, int]: """Minimal RIFF/WAVE reader: PCM 8/16/24/32-bit and IEEE float 32/64, any channel count (mixed to mono).""" if len(data) < 12 or data[:4] != b"RIFF" or data[8:12] != b"WAVE": raise MediaError("not a RIFF/WAVE file") pos, fmt, raw = 12, None, None while pos + 8 <= len(data): cid, size = data[pos:pos + 4], struct.unpack("= 26: tag = struct.unpack("= 1 << 23, v - (1 << 24), v) x = v.astype(np.float32) / float(1 << 23) elif bits == 32: x = np.frombuffer(raw[: len(raw) // 4 * 4], " Tuple[np.ndarray, int]: """-> (mono float32 waveform, sampling rate).""" if fmt == "pcm_f32le": if not sampling_rate: raise MediaError("raw pcm_f32le audio needs sampling_rate") x = np.frombuffer(data[: len(data) // 4 * 4], " MAX_AUDIO_SECONDS_IN * sr: raise MediaError(f"audio longer than {MAX_AUDIO_SECONDS_IN:g} s") if not np.isfinite(x).all(): raise MediaError("audio contains NaN / inf") return x, int(sr) def decode_video_file(data: bytes, max_frames_decoded: int = 3600) -> Dict[str, Any]: """Container file (mp4 / webm / ...) -> dict(frames, fps, duration); needs PyAV.""" try: import av except ImportError: raise MediaError("video files need PyAV (not installed): send decoded frames instead " "({'type': 'video', 'frames': [base64 images], 'fps': ...})") from None try: c = av.open(io.BytesIO(data)) st = c.streams.video[0] fps = float(st.average_rate) if st.average_rate else None frames = [] for fr in c.decode(st): frames.append(fr.to_ndarray(format="rgb24")) if len(frames) >= max_frames_decoded: break c.close() except Exception as e: # noqa: BLE001 raise MediaError(f"cannot decode video: {type(e).__name__}: {e}") from None if not frames: raise MediaError("video has no frames") dur = len(frames) / fps if fps else None return {"frames": frames, "fps": fps, "duration": dur} def decode_frames(frames: List[str], what: str = "video") -> List[np.ndarray]: out = [] shape = None for i, f in enumerate(frames): im = np.asarray(decode_image(b64bytes(f, f"{what} frame {i}")), dtype=np.uint8) if shape is None: shape = im.shape elif im.shape != shape: raise MediaError(f"{what} frame {i} is {im.shape[1]}x{im.shape[0]}, frame 0 is {shape[1]}x{shape[0]}") out.append(im) if not out: raise MediaError(f"{what} has no frames") return out