| 1 | from __future__ import annotations |
| 2 | |
| 3 | import os |
| 4 | from typing import Any |
| 5 | |
| 6 | from PIL import Image |
| 7 | |
| 8 | |
| 9 | def landscape_guard_requested(*, size: Any = None, aspect_ratio: Any = None, enforce_landscape: Any = True, allow_portrait: Any = False) -> bool: |
| 10 | if bool(allow_portrait): |
| 11 | return False |
| 12 | if bool(enforce_landscape): |
| 13 | return True |
| 14 | parsed = _parse_size(size) |
| 15 | if parsed and parsed[0] > parsed[1]: |
| 16 | return True |
| 17 | parsed_ratio = _parse_size(aspect_ratio) |
| 18 | return bool(parsed_ratio and parsed_ratio[0] > parsed_ratio[1]) |
| 19 | |
| 20 | |
| 21 | def ensure_not_portrait(image: Image.Image, *, tolerance: float | None = None) -> None: |
| 22 | width, height = image.size |
| 23 | if width <= 0 or height <= 0: |
| 24 | return |
| 25 | threshold = tolerance if tolerance is not None else _portrait_tolerance() |
| 26 | if height > width * threshold: |
| 27 | raise ValueError(f"Generated image is portrait-oriented ({width}x{height}); retrying for a landscape frame") |
| 28 | |
| 29 | |
| 30 | def _portrait_tolerance() -> float: |
| 31 | raw = os.environ.get("VIMAX_IMAGE_PORTRAIT_RETRY_TOLERANCE", "1.05") |
| 32 | try: |
| 33 | return max(1.0, float(raw)) |
| 34 | except ValueError: |
| 35 | return 1.05 |
| 36 | |
| 37 | |
| 38 | def _parse_size(size: Any) -> tuple[int, int] | None: |
| 39 | if not isinstance(size, str): |
| 40 | return None |
| 41 | normalized = size.lower() |
| 42 | separator = "x" if "x" in normalized else ":" if ":" in normalized else "" |
| 43 | if not separator: |
| 44 | return None |
| 45 | left, right = normalized.split(separator, 1) |
| 46 | try: |
| 47 | width = int(left.strip()) |
| 48 | height = int(right.strip()) |
| 49 | except ValueError: |
| 50 | return None |
| 51 | if width <= 0 or height <= 0: |
| 52 | return None |
| 53 | return width, height |
| 54 |