Files
mtusi2026lab5/worker/main.py
T
2026-11-20 11:53:35 +03:00

123 lines
5.1 KiB
Python

import asyncio
import io
import json
import logging
from datetime import datetime, timezone
import aio_pika
from PIL import Image
import psycopg
from psycopg.rows import dict_row
from src.app.config import get_settings
from src.app.db import init_pool, transaction
from src.app.s3 import get_s3_client, download_fileobj, upload_fileobj
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("worker")
def generate_variants(img: Image.Image):
variants = {}
# 1. Thumbnail (макс 256x256, сохраняем пропорции)
thumb = img.copy()
thumb.thumbnail((256, 256))
variants["thumbnail"] = thumb
# 2. Crop (квадрат 512x512 по центру)
crop = img.copy()
min_dim = min(crop.size)
left = (crop.width - min_dim) // 2
top = (crop.height - min_dim) // 2
crop = crop.crop((left, top, left + min_dim, top + min_dim))
crop = crop.resize((512, 512), Image.Resampling.LANCZOS)
variants["crop"] = crop
# 3. Optimized (просто оригинал в JPEG с качеством 85)
opt = img.convert("RGB")
buf = io.BytesIO()
opt.save(buf, format="JPEG", quality=85)
variants["optimized"] = Image.open(buf)
return variants
async def process_message(message: aio_pika.IncomingMessage):
async with message.process():
data = json.loads(message.body)
att_id = data["attachment_id"]
obj_key = data["object_key"]
logger.info(f"Processing attachment {att_id}")
try:
# 1. Обновляем статус на processing
with transaction() as conn:
with conn.cursor() as cur:
cur.execute("UPDATE attachments SET status='processing', updated_at=now() WHERE id=%s", (att_id,))
# 2. Качаем из S3
body = download_fileobj(obj_key)
img = Image.open(body)
img.load() # принудительная загрузка в память для обнаружения битых файлов
# 3. Генерируем варианты
variants = generate_variants(img)
# 4. Сохраняем в S3 и БД
with transaction() as conn:
with conn.cursor() as cur:
for name, var_img in variants.items():
buf = io.BytesIO()
ct = "image/jpeg"
if name == "thumbnail":
var_img.save(buf, format="PNG")
ct = "image/png"
else:
var_img.save(buf, format="JPEG", quality=85)
var_bytes = buf.getvalue()
sha256 = __import__("hashlib").sha256(var_bytes).hexdigest()
var_key = f"chats/{att_id}/variants/{name}"
upload_fileobj(io.BytesIO(var_bytes), var_key, ct)
cur.execute(
"""
INSERT INTO attachment_variants (attachment_id, name, content_type, size_bytes, width, height, sha256, object_key)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
ON CONFLICT (attachment_id, name) DO UPDATE SET
content_type = EXCLUDED.content_type,
size_bytes = EXCLUDED.size_bytes,
width = EXCLUDED.width,
height = EXCLUDED.height,
sha256 = EXCLUDED.sha256,
object_key = EXCLUDED.object_key
""",
(att_id, name, ct, len(var_bytes), var_img.width, var_img.height, sha256, var_key)
)
cur.execute("UPDATE attachments SET status='ready', error_code=NULL, updated_at=now() WHERE id=%s", (att_id,))
logger.info(f"Successfully processed {att_id}")
except Exception as e:
logger.error(f"Error processing {att_id}: {e}")
with transaction() as conn:
with conn.cursor() as cur:
cur.execute("UPDATE attachments SET status='failed', error_code=%s, updated_at=now() WHERE id=%s", ("processing_error", att_id))
raise e # Пробрасываем ошибку, чтобы RabbitMQ не удалил сообщение (at-least-once)
async def main():
init_pool()
settings = get_settings()
connection = await aio_pika.connect_robust(settings.broker_url)
async with connection:
channel = await connection.channel()
await channel.set_qos(prefetch_count=1)
queue = await channel.declare_queue(settings.broker_queue, durable=True)
logger.info("Worker started, waiting for messages...")
await queue.consume(process_message)
await asyncio.Future()
if __name__ == "__main__":
asyncio.run(main())