From 11367c6c868c0ecab32fd3cdaddef6f40c5e2815 Mon Sep 17 00:00:00 2001 From: Kirill Kirilenko Date: Sun, 1 Mar 2026 22:55:53 +0300 Subject: [PATCH] =?UTF-8?q?=D0=9A=D0=BE=D0=BD=D0=B2=D0=B5=D1=80=D1=82?= =?UTF-8?q?=D0=B0=D1=86=D0=B8=D1=8F=20=D0=B2=20JPEG=20=D0=B2=D1=8B=D0=B4?= =?UTF-8?q?=D0=B5=D0=BB=D0=B5=D0=BD=D0=B0=20=D0=B2=20=D0=BE=D1=82=D0=B4?= =?UTF-8?q?=D0=B5=D0=BB=D1=8C=D0=BD=D1=83=D1=8E=20=D1=84=D1=83=D0=BD=D0=BA?= =?UTF-8?q?=D1=86=D0=B8=D1=8E.=20=D0=9A=D0=B0=D1=87=D0=B5=D1=81=D1=82?= =?UTF-8?q?=D0=B2=D0=BE=20=D1=81=D0=B6=D0=B0=D1=82=D0=B8=D1=8F=20JPEG=20?= =?UTF-8?q?=D1=83=D0=B2=D0=B5=D0=BB=D0=B8=D1=87=D0=B5=D0=BD=D0=BE=20=D0=B4?= =?UTF-8?q?=D0=BE=2095.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ai_agent.py | 26 ++++++++++++-------------- 1 file changed, 12 insertions(+), 14 deletions(-) diff --git a/ai_agent.py b/ai_agent.py index 93f3992..8259faa 100644 --- a/ai_agent.py +++ b/ai_agent.py @@ -92,6 +92,13 @@ def _get_resolution_for_aspect_ratio(aspect_ratio: str) -> Tuple[int, int]: return aspect_ratio_resolution_map.get(aspect_ratio, (1280, 1024)) +def _convert_image_to_jpeg(image: bytes) -> bytes: + img = Image.open(BytesIO(image)).convert("RGB") + output = BytesIO() + img.save(output, format='JPEG', quality=95, optimize=True) + return output.getvalue() + + class AiAgent: def __init__(self, openrouter_token: str, openrouter_model: str, @@ -307,14 +314,10 @@ class AiAgent: async with aiohttp.ClientSession() as session: async with session.get(image_url) as response: if response.status == 200: - image_bytes = await response.read() + image = await response.read() if not image_url.endswith(".jpg"): - image = Image.open(BytesIO(image_bytes)).convert("RGB") - output = BytesIO() - image.save(output, format="JPEG", quality=80, optimize=True) - image_bytes = output.getvalue() - - return Ok(image_bytes) + image = _convert_image_to_jpeg(image) + return Ok(image) else: raise RuntimeError(f"Не удалось загрузить изображение ({response.status}).") @@ -362,13 +365,8 @@ class AiAgent: try: outputs = await self.replicate_client.async_run(REPLICATE_MODEL, input=arguments) - image_bytes = await outputs[0].aread() - - image = Image.open(BytesIO(image_bytes)).convert("RGB") - output = BytesIO() - image.save(output, format="JPEG", quality=80, optimize=True) - image_bytes = output.getvalue() - return Ok(image_bytes) + image = _convert_image_to_jpeg(await outputs[0].aread()) + return Ok(image) except Exception as e: print(f"Ошибка генерации изображения: {e}") return Err(str(e))