Добавлена возможность пересылки сообщений в личных чатах. Обновлены зависимости. Добавлен requirements.txt. Исправлены предупреждения PyCharm 2026.1.
39 lines
1.2 KiB
Python
39 lines
1.2 KiB
Python
from base64 import b64encode
|
|
from io import BytesIO
|
|
from PIL import Image
|
|
from typing import Dict, List, Optional
|
|
|
|
|
|
def serialize_message_content(text: Optional[str], image: Optional[bytes] = None) -> List[Dict]:
|
|
content = []
|
|
if text is not None:
|
|
content.append({"type": "text", "text": text})
|
|
if image is not None:
|
|
content.append({"type": "image_url", "detail": "high", "image_url": {"url": encode_image(image)}})
|
|
return content
|
|
|
|
|
|
def encode_image(image: bytes) -> str:
|
|
encoded_image = b64encode(image).decode('utf-8')
|
|
return f"data:image/jpeg;base64,{encoded_image}"
|
|
|
|
|
|
def compress_image(image: bytes, max_side: Optional[int] = None) -> bytes:
|
|
img = Image.open(BytesIO(image)).convert("RGB")
|
|
|
|
if max_side is not None and (img.width > max_side or img.height > max_side):
|
|
scale = min(max_side / img.width, max_side / img.height)
|
|
new_width = int(img.width * scale)
|
|
new_height = int(img.height * scale)
|
|
img = img.resize((new_width, new_height), Image.Resampling.LANCZOS)
|
|
|
|
output = BytesIO()
|
|
img.save(output, format='JPEG', quality=87, optimize=True)
|
|
return output.getvalue()
|
|
|
|
|
|
__all__ = [
|
|
"serialize_message_content",
|
|
"compress_image",
|
|
"encode_image"
|
|
]
|