import asyncio import io import json import logging import hashlib import aio_pika from PIL import Image 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 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() # Если картинка имеет прозрачность (RGBA), конвертируем в RGB для JPEG if thumb.mode in ("RGBA", "P"): thumb = thumb.convert("RGB") thumb.thumbnail((256, 256)) variants["thumbnail"] = thumb # 2. Crop (квадрат 512x512 по центру) crop = img.copy() if crop.mode in ("RGBA", "P"): crop = crop.convert("RGB") 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) opt = img.convert("RGB") variants["optimized"] = opt 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() # Всегда сохраняем как JPEG (так требует контракт) ct = "image/jpeg" var_img.save(buf, format="JPEG", quality=85) var_bytes = buf.getvalue() sha256 = 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 async def main(): init_pool() settings = get_settings() # Ждем, пока брокер станет доступен while True: try: connection = await aio_pika.connect_robust(settings.broker_url) break # если подключились - выходим из цикла except Exception as e: logger.warning(f"Broker not ready, waiting 5 seconds... ({e})") await asyncio.sleep(5) 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())