feat(backend): sanitize and re-encode all input before the model
Browse filesNever trust the client. Decode, validate, downscale, and re-encode every
image server-side to a known JPEG (≤896px), cap count (4) and source size
(12MB), and clean/cap the fragment (strip control chars, 600 chars). Bad
input raises InputError, which the API returns as a clean 400 instead of
letting it reach or crash the model. Adds Pillow to runtime deps.
- app.py +4 -1
- backend/__init__.py +2 -1
- backend/oracle.py +6 -2
- backend/sanitize.py +106 -0
- requirements.txt +1 -0
app.py
CHANGED
|
@@ -22,7 +22,7 @@ from pydantic import BaseModel, Field
|
|
| 22 |
|
| 23 |
import gradio as gr
|
| 24 |
|
| 25 |
-
from backend import OracleError, interpret
|
| 26 |
from backend.providers import get_provider
|
| 27 |
|
| 28 |
load_dotenv()
|
|
@@ -60,6 +60,9 @@ async def api_interpret(moment: Moment):
|
|
| 60 |
try:
|
| 61 |
result = interpret(moment.images, moment.fragment, provider=_provider())
|
| 62 |
return result
|
|
|
|
|
|
|
|
|
|
| 63 |
except OracleError as exc:
|
| 64 |
# The reel slipped — a model/parse problem the user can retry past.
|
| 65 |
return JSONResponse({"error": str(exc)}, status_code=422)
|
|
|
|
| 22 |
|
| 23 |
import gradio as gr
|
| 24 |
|
| 25 |
+
from backend import InputError, OracleError, interpret
|
| 26 |
from backend.providers import get_provider
|
| 27 |
|
| 28 |
load_dotenv()
|
|
|
|
| 60 |
try:
|
| 61 |
result = interpret(moment.images, moment.fragment, provider=_provider())
|
| 62 |
return result
|
| 63 |
+
except InputError as exc:
|
| 64 |
+
# Bad/oversized/unsupported input — rejected before reaching the model.
|
| 65 |
+
return JSONResponse({"error": str(exc)}, status_code=400)
|
| 66 |
except OracleError as exc:
|
| 67 |
# The reel slipped — a model/parse problem the user can retry past.
|
| 68 |
return JSONResponse({"error": str(exc)}, status_code=422)
|
backend/__init__.py
CHANGED
|
@@ -2,5 +2,6 @@
|
|
| 2 |
|
| 3 |
from .oracle import OracleError, interpret
|
| 4 |
from .providers import get_provider
|
|
|
|
| 5 |
|
| 6 |
-
__all__ = ["interpret", "OracleError", "get_provider"]
|
|
|
|
| 2 |
|
| 3 |
from .oracle import OracleError, interpret
|
| 4 |
from .providers import get_provider
|
| 5 |
+
from .sanitize import InputError
|
| 6 |
|
| 7 |
+
__all__ = ["interpret", "OracleError", "InputError", "get_provider"]
|
backend/oracle.py
CHANGED
|
@@ -17,6 +17,7 @@ from typing import Any
|
|
| 17 |
|
| 18 |
from .prompt import closing_instruction, fragment_lead, system_prompt
|
| 19 |
from .providers import Provider, get_provider
|
|
|
|
| 20 |
|
| 21 |
MAX_IMAGES = 4
|
| 22 |
MAX_TOKENS = 2048
|
|
@@ -149,8 +150,11 @@ def interpret(
|
|
| 149 |
photo" rule, retry once with the refined prompt and a hotter temperature,
|
| 150 |
then keep whichever pass is stronger.
|
| 151 |
"""
|
| 152 |
-
|
| 153 |
-
|
|
|
|
|
|
|
|
|
|
| 154 |
provider = provider or get_provider()
|
| 155 |
content = _build_content(images, fragment)
|
| 156 |
|
|
|
|
| 17 |
|
| 18 |
from .prompt import closing_instruction, fragment_lead, system_prompt
|
| 19 |
from .providers import Provider, get_provider
|
| 20 |
+
from .sanitize import sanitize_fragment, sanitize_images
|
| 21 |
|
| 22 |
MAX_IMAGES = 4
|
| 23 |
MAX_TOKENS = 2048
|
|
|
|
| 150 |
photo" rule, retry once with the refined prompt and a hotter temperature,
|
| 151 |
then keep whichever pass is stronger.
|
| 152 |
"""
|
| 153 |
+
# Guardrails first: decode/validate/re-encode images and clean the fragment
|
| 154 |
+
# before anything reaches the model. InputError propagates to a clean 4xx.
|
| 155 |
+
images = sanitize_images(images)
|
| 156 |
+
fragment = sanitize_fragment(fragment)
|
| 157 |
+
|
| 158 |
provider = provider or get_provider()
|
| 159 |
content = _build_content(images, fragment)
|
| 160 |
|
backend/sanitize.py
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Guardrails on everything that reaches the model.
|
| 2 |
+
|
| 3 |
+
We never trust the client. The browser already shrinks images, but a direct
|
| 4 |
+
POST to /api/interpret could carry anything — so we decode, validate, and
|
| 5 |
+
re-encode every image server-side to a known-safe size and format, and we cap
|
| 6 |
+
and clean the fragment. Bad input raises InputError, which the API turns into a
|
| 7 |
+
clean 4xx instead of letting it reach (or crash) the model.
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
from __future__ import annotations
|
| 11 |
+
|
| 12 |
+
import base64
|
| 13 |
+
import binascii
|
| 14 |
+
import io
|
| 15 |
+
import re
|
| 16 |
+
|
| 17 |
+
from PIL import Image, UnidentifiedImageError
|
| 18 |
+
|
| 19 |
+
MAX_IMAGES = 4
|
| 20 |
+
# Reject a single source image larger than this (decoded bytes) before we touch it.
|
| 21 |
+
MAX_SOURCE_BYTES = 12 * 1024 * 1024 # 12 MB
|
| 22 |
+
# What we hand the model: longest edge and JPEG quality after re-encoding.
|
| 23 |
+
TARGET_MAX_DIM = 896
|
| 24 |
+
JPEG_QUALITY = 72
|
| 25 |
+
# A fragment is a line or two, not an essay.
|
| 26 |
+
MAX_FRAGMENT_CHARS = 600
|
| 27 |
+
|
| 28 |
+
_DATA_URL_RE = re.compile(r"^data:(?P<mime>[\w.+-]+/[\w.+-]+)?;base64,(?P<data>.+)$", re.DOTALL)
|
| 29 |
+
# Control chars except tab/newline/carriage-return.
|
| 30 |
+
_CONTROL_RE = re.compile(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]")
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class InputError(Exception):
|
| 34 |
+
"""User-supplied input that we refuse to forward to the model."""
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def sanitize_fragment(text: str) -> str:
|
| 38 |
+
"""Trim, strip control characters, collapse runaway whitespace, and cap length."""
|
| 39 |
+
if not text:
|
| 40 |
+
return ""
|
| 41 |
+
if not isinstance(text, str):
|
| 42 |
+
raise InputError("Fragment must be text.")
|
| 43 |
+
cleaned = _CONTROL_RE.sub("", text).strip()
|
| 44 |
+
# Collapse 3+ blank lines / long whitespace runs that bloat the prompt.
|
| 45 |
+
cleaned = re.sub(r"[ \t]{2,}", " ", cleaned)
|
| 46 |
+
cleaned = re.sub(r"\n{3,}", "\n\n", cleaned)
|
| 47 |
+
if len(cleaned) > MAX_FRAGMENT_CHARS:
|
| 48 |
+
cleaned = cleaned[:MAX_FRAGMENT_CHARS].rstrip() + "…"
|
| 49 |
+
return cleaned
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def _decode(one: str) -> bytes:
|
| 53 |
+
"""Accept a data URL or raw base64 and return the decoded bytes."""
|
| 54 |
+
if not isinstance(one, str) or not one.strip():
|
| 55 |
+
raise InputError("Empty image entry.")
|
| 56 |
+
m = _DATA_URL_RE.match(one.strip())
|
| 57 |
+
payload = m.group("data") if m else one.strip()
|
| 58 |
+
try:
|
| 59 |
+
raw = base64.b64decode(payload, validate=True)
|
| 60 |
+
except (binascii.Error, ValueError) as exc:
|
| 61 |
+
raise InputError("An image wasn't valid base64.") from exc
|
| 62 |
+
if not raw:
|
| 63 |
+
raise InputError("An image decoded to nothing.")
|
| 64 |
+
if len(raw) > MAX_SOURCE_BYTES:
|
| 65 |
+
raise InputError("An image is too large (max 12 MB).")
|
| 66 |
+
return raw
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def _reencode(raw: bytes) -> str:
|
| 70 |
+
"""Open, normalize, downscale, and re-encode to a JPEG data URL we control."""
|
| 71 |
+
try:
|
| 72 |
+
img = Image.open(io.BytesIO(raw))
|
| 73 |
+
img.load()
|
| 74 |
+
except (UnidentifiedImageError, OSError) as exc:
|
| 75 |
+
raise InputError("An image couldn't be read.") from exc
|
| 76 |
+
|
| 77 |
+
# Flatten transparency/odd modes onto black, matching the cinematic ground.
|
| 78 |
+
if img.mode not in ("RGB", "L"):
|
| 79 |
+
img = img.convert("RGBA") if "A" in img.mode else img.convert("RGB")
|
| 80 |
+
if img.mode == "RGBA":
|
| 81 |
+
bg = Image.new("RGB", img.size, (12, 9, 7))
|
| 82 |
+
bg.paste(img, mask=img.split()[-1])
|
| 83 |
+
img = bg
|
| 84 |
+
if img.mode != "RGB":
|
| 85 |
+
img = img.convert("RGB")
|
| 86 |
+
|
| 87 |
+
w, h = img.size
|
| 88 |
+
if max(w, h) > TARGET_MAX_DIM:
|
| 89 |
+
if w >= h:
|
| 90 |
+
img = img.resize((TARGET_MAX_DIM, round(h * TARGET_MAX_DIM / w)))
|
| 91 |
+
else:
|
| 92 |
+
img = img.resize((round(w * TARGET_MAX_DIM / h), TARGET_MAX_DIM))
|
| 93 |
+
|
| 94 |
+
buf = io.BytesIO()
|
| 95 |
+
img.save(buf, format="JPEG", quality=JPEG_QUALITY)
|
| 96 |
+
b64 = base64.b64encode(buf.getvalue()).decode()
|
| 97 |
+
return f"data:image/jpeg;base64,{b64}"
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def sanitize_images(images: list[str]) -> list[str]:
|
| 101 |
+
"""Validate, downscale, and re-encode each image. Returns safe JPEG data URLs."""
|
| 102 |
+
if not isinstance(images, list) or not images:
|
| 103 |
+
raise InputError("Bring at least one image.")
|
| 104 |
+
if len(images) > MAX_IMAGES:
|
| 105 |
+
raise InputError(f"Up to {MAX_IMAGES} images, please.")
|
| 106 |
+
return [_reencode(_decode(one)) for one in images]
|
requirements.txt
CHANGED
|
@@ -2,6 +2,7 @@
|
|
| 2 |
gradio==6.18.0
|
| 3 |
openai>=1.40
|
| 4 |
python-dotenv>=1.0
|
|
|
|
| 5 |
|
| 6 |
# --- hf_local provider (in-process model on ZeroGPU) — uncomment when needed ---
|
| 7 |
# transformers>=4.49
|
|
|
|
| 2 |
gradio==6.18.0
|
| 3 |
openai>=1.40
|
| 4 |
python-dotenv>=1.0
|
| 5 |
+
pillow>=10.0 # server-side image validation + re-encode (sanitize.py)
|
| 6 |
|
| 7 |
# --- hf_local provider (in-process model on ZeroGPU) — uncomment when needed ---
|
| 8 |
# transformers>=4.49
|