included rabbitmq as broker

This commit is contained in:
2026-11-10 07:01:17 +03:00
parent 0a70358829
commit 2b9fb3f375
49 changed files with 3072 additions and 287 deletions
+70 -25
View File
@@ -1,34 +1,79 @@
"""Заготовки преобразований lab5, без доступа к БД, брокеру и HTTP.
Pipeline запускается внутри ограниченного процесса worker. Исходные bytes
не перекодируются; варианты удаляют метаданные по документированной политике.
Значения качества JPEG/WebP предстоит выбрать и зафиксировать в REPORT.md.
"""
"""Thumbnail, crop и WebP; один ограниченный процесс, последовательная обработка."""
import hashlib
from pathlib import Path
from PIL import Image, ImageOps
def create_thumbnail(source: Path, destination: Path) -> None:
"""Создать JPEG, вписанный в 256×256 без увеличения.
Применить EXIF orientation, alpha положить на белый; округлять размеры
вниз, минимум 1 px. Публичный fixture 320×200 должен дать 256×160.
"""
raise NotImplementedError("Lab5: thumbnail ещё не реализован")
from app.core.image_processing import ImageSettings
from app.domain.image_validation import decode_image
from app.schemas.attachment import PipelineResult, Variant
def create_crop(source: Path, destination: Path) -> None:
"""Создать центрированный квадрат JPEG 128×128; увеличение допустимо.
Учитывать EXIF orientation и прозрачность по той же политике, что thumbnail.
"""
raise NotImplementedError("Lab5: crop ещё не реализован")
def fitted_size(size: tuple[int, int], maximum: int) -> tuple[int, int]:
"""Вписать без увеличения, округляя вниз, минимум один пиксель."""
longest = max(size)
result = size
if longest > maximum:
result = (max(1, size[0] * maximum // longest), max(1, size[1] * maximum // longest))
return result
def create_optimized(source: Path, destination: Path) -> None:
"""Создать WebP, вписанный в 1280×1280 без увеличения.
def describe_variant(name: str, content_type: str, path: Path, size: tuple[int, int]) -> Variant:
checksum = hashlib.sha256()
with path.open("rb") as source:
for chunk in iter(lambda: source.read(65536), b""):
checksum.update(chunk)
return Variant(
name=name, content_type=content_type, size_bytes=path.stat().st_size,
width=size[0], height=size[1], sha256=checksum.hexdigest(),
)
Удалить метаданные и применить описанную политику качества. Уменьшение
размера любого маленького исходника не гарантируется контрактом.
"""
raise NotImplementedError("Lab5: optimized ещё не реализован")
def save_jpeg(image: Image.Image, destination: Path, quality: int) -> None:
"""Белая подложка и новый image без EXIF/ICC/XMP/текстовых метаданных."""
with Image.new("RGB", image.size, "white") as clean:
with image.getchannel("A") as alpha:
clean.paste(image, mask=alpha)
clean.save(destination, format="JPEG", quality=quality, exif=b"")
def create_thumbnail(image: Image.Image, destination: Path, quality: int) -> Variant:
size = fitted_size(image.size, 256)
with image.resize(size, Image.Resampling.LANCZOS) as resized:
save_jpeg(resized, destination, quality)
return describe_variant("thumbnail", "image/jpeg", destination, size)
def create_crop(image: Image.Image, destination: Path, quality: int) -> Variant:
"""Центрированный JPEG 128×128; маленький исходник допускает увеличение."""
with ImageOps.fit(image, (128, 128), method=Image.Resampling.LANCZOS, centering=(0.5, 0.5)) as crop:
save_jpeg(crop, destination, quality)
return describe_variant("crop", "image/jpeg", destination, (128, 128))
def create_optimized(image: Image.Image, destination: Path, settings: ImageSettings) -> Variant:
"""WebP ≤1280×1280 без увеличения; alpha сохраняется, метаданные удаляются."""
size = fitted_size(image.size, 1280)
with image.resize(size, Image.Resampling.LANCZOS) as resized:
with Image.new("RGBA", size) as clean:
clean.paste(resized)
clean.save(
destination, format="WEBP", lossless=False,
quality=settings.webp_quality, method=settings.webp_method,
exif=b"", icc_profile=b"", xmp=b"",
)
return describe_variant("optimized", "image/webp", destination, size)
def create_variants(source: Path, directory: Path, content_type: str, max_pixels: int, settings: ImageSettings) -> PipelineResult:
decode_image(source, content_type, max_pixels)
with Image.open(source, formats=["PNG", "JPEG"]) as image:
ImageOps.exif_transpose(image, in_place=True)
with image.convert("RGBA") as pixels:
variants = [
create_thumbnail(pixels, directory / "thumbnail.jpg", settings.jpeg_quality),
create_crop(pixels, directory / "crop.jpg", settings.jpeg_quality),
create_optimized(pixels, directory / "optimized.webp", settings),
]
return PipelineResult(variants=variants)