This commit is contained in:
caramelteawithmint
2026-11-20 13:05:30 +03:00
parent f856651e57
commit a306a68aa4
11 changed files with 268 additions and 132 deletions
+26 -15
View File
@@ -2,30 +2,35 @@ import asyncio
import io
import json
import logging
from datetime import datetime, timezone
import hashlib
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
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
@@ -33,14 +38,13 @@ def generate_variants(img: Image.Image):
crop = crop.resize((512, 512), Image.Resampling.LANCZOS)
variants["crop"] = crop
# 3. Optimized (просто оригинал в JPEG с качеством 85)
# 3. Optimized (просто оригинал в JPEG)
opt = img.convert("RGB")
buf = io.BytesIO()
opt.save(buf, format="JPEG", quality=85)
variants["optimized"] = Image.open(buf)
variants["optimized"] = opt
return variants
async def process_message(message: aio_pika.IncomingMessage):
async with message.process():
data = json.loads(message.body)
@@ -68,15 +72,12 @@ async def process_message(message: aio_pika.IncomingMessage):
with conn.cursor() as cur:
for name, var_img in variants.items():
buf = io.BytesIO()
# Всегда сохраняем как JPEG (так требует контракт)
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_img.save(buf, format="JPEG", quality=85)
var_bytes = buf.getvalue()
sha256 = __import__("hashlib").sha256(var_bytes).hexdigest()
sha256 = hashlib.sha256(var_bytes).hexdigest()
var_key = f"chats/{att_id}/variants/{name}"
upload_fileobj(io.BytesIO(var_bytes), var_key, ct)
@@ -104,13 +105,22 @@ async def process_message(message: aio_pika.IncomingMessage):
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)
raise e
async def main():
init_pool()
settings = get_settings()
connection = await aio_pika.connect_robust(settings.broker_url)
# Ждем, пока брокер станет доступен
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)
@@ -119,5 +129,6 @@ async def main():
await queue.consume(process_message)
await asyncio.Future()
if __name__ == "__main__":
asyncio.run(main())