Files
mtusi2026lab5/bench/make_images.py
T
ricoromaandClaude Opus 5.5 d667fa3c57 feat: limit accepted attachment work and add queue overload bench
Reject uploads with 429 at [uploads] max_unfinished_jobs, counted by the existing partial indexes in the membership block. Add the bench_queue profile, hypotheses H1-H9 and the fifth failure-stand API.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 07:30:08 +03:00

162 lines
4.5 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Файлы классов профиля очереди (design change `track1-queue-overload`,
решение 5): `s`, `m`, `lj`, `lp`, детерминированно от зерна.
Только в контейнере `mtusi-bench-images` на образе стенда: Pillow образа и та же
его версия, что у процесса обработки; `src` не импортируется. На stdout — JSON с
размерами, пикселями и SHA-256; файл больше лимита контракта — код 1.
python make_images.py <зерно> <каталог>
"""
import hashlib
import io
import json
import random
import sys
from pathlib import Path
from PIL import Image, ImageChops
from uploads import png_noise
MAX_BYTES = 10_485_760
MAX_PIXELS = 40_000_000
LARGE = (8000, 5000)
SMALL = (1600, 1200)
NOISE_HEIGHT = 3409
CELLS_LOW = 64
CELLS_HIGH = 512
FINE_DIVISOR = 6
TILE = 512
AMPLITUDE = 24
POSTERIZE_MASK = 0xF0
def noise_l(width: int, height: int, seed: int) -> Image.Image:
data = random.Random(seed).randbytes(width * height)
return Image.frombytes("L", (width, height), data)
def clouds(
width: int,
height: int,
seed: int,
cells: int = CELLS_LOW,
) -> Image.Image:
"""Гладкое поле из шума низкого разрешения: низкие частоты фото."""
return noise_l(cells, max(2, cells * height // width), seed).resize(
(width, height),
Image.Resampling.BICUBIC,
)
def detail_tile(
width: int,
height: int,
seed: int,
amplitude: int,
) -> Image.Image:
"""Плитка шума амплитуды `amplitude`, повторённая на всё поле."""
tile = noise_l(TILE, TILE, seed).point(lambda v: v * amplitude // 255)
field = Image.new("L", (width, height))
for y in range(0, height, TILE):
for x in range(0, width, TILE):
field.paste(tile, (x, y))
return field
def bands(
width: int,
height: int,
seed: int,
amplitude: int,
) -> list[Image.Image]:
out = []
for number in range(3):
band = ImageChops.add(
clouds(width, height, seed + number),
clouds(
width,
height,
seed + 10 + number,
cells=CELLS_HIGH,
).point(lambda v: v // FINE_DIVISOR),
)
if amplitude:
band = ImageChops.add(
band,
detail_tile(width, height, seed + 20 + number, amplitude),
)
out.append(band)
return out
def jpeg(image: Image.Image, quality: int) -> bytes:
out = io.BytesIO()
image.save(out, format="JPEG", quality=quality, subsampling="4:2:0")
return out.getvalue()
def build_s(seed: int) -> bytes:
return jpeg(Image.merge("RGB", bands(*SMALL, seed, AMPLITUDE)), 85)
def build_lj(seed: int) -> bytes:
return jpeg(Image.merge("RGB", bands(*LARGE, seed + 200, AMPLITUDE)), 88)
def build_lp(seed: int) -> bytes:
colour = [
band.point(lambda v: v & POSTERIZE_MASK)
for band in bands(*LARGE, seed + 200, 0)
]
alpha = clouds(*LARGE, seed + 300).point(
lambda v: (128 + v // 2) & POSTERIZE_MASK,
)
out = io.BytesIO()
Image.merge("RGBA", (*colour, alpha)).save(
out,
format="PNG",
compress_level=6,
)
return out.getvalue()
def build_m(seed: int) -> bytes:
return png_noise(NOISE_HEIGHT, seed + NOISE_HEIGHT)
BUILDERS = {
"s": (build_s, "s.jpg", "image/jpeg"),
"m": (build_m, "m.png", "image/png"),
"lj": (build_lj, "lj.jpg", "image/jpeg"),
"lp": (build_lp, "lp.png", "image/png"),
}
def main() -> int:
seed, directory = int(sys.argv[1]), Path(sys.argv[2])
report = {}
code = 0
for name, (build, filename, media) in BUILDERS.items():
data = build(seed)
with Image.open(io.BytesIO(data)) as image:
width, height = image.size
(directory / filename).write_bytes(data)
report[name] = {
"file": filename,
"media_type": media,
"bytes": len(data),
"width": width,
"height": height,
"sha256": hashlib.sha256(data).hexdigest(),
}
if len(data) > MAX_BYTES or width * height > MAX_PIXELS:
print(f"{name}: over the contract limit", file=sys.stderr)
code = 1
print(json.dumps(report))
return code
if __name__ == "__main__":
sys.exit(main())