File size: 7,272 Bytes
9abace2 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 | """
Image Editing
Part of SOVEREIGN PYTHON LLM ENGINE
Edit images using PIL/Pillow.
"""
from typing import Any
from pathlib import Path
from dataclasses import dataclass
from io import BytesIO
@dataclass
class EditedImage:
"""Edited image result"""
image_bytes: bytes
format: str
size: tuple[int, int]
operations: list[str]
class ImageEditor:
"""
Image editing operations using Pillow.
Supports:
- Resize, crop, rotate
- Format conversion
- Filters and adjustments
- Watermarking
"""
def __init__(self):
try:
from PIL import Image
except ImportError:
raise ImportError("Pillow is required. Install: pip install Pillow")
async def resize(
self,
image_path: Path,
width: int,
height: int,
maintain_aspect: bool = True
) -> EditedImage:
"""
Resize image.
Args:
image_path: Input image
width: Target width
height: Target height
maintain_aspect: Maintain aspect ratio
Returns:
EditedImage
"""
from PIL import Image
import asyncio
def _sync_resize():
img = Image.open(image_path)
if maintain_aspect:
img.thumbnail((width, height), Image.Resampling.LANCZOS)
else:
img = img.resize((width, height), Image.Resampling.LANCZOS)
# Save to bytes
buffer = BytesIO()
img.save(buffer, format=img.format or "PNG")
buffer.seek(0)
return EditedImage(
image_bytes=buffer.read(),
format=img.format or "PNG",
size=img.size,
operations=["resize"]
)
return await asyncio.to_thread(_sync_resize)
async def crop(
self,
image_path: Path,
left: int,
top: int,
right: int,
bottom: int
) -> EditedImage:
"""
Crop image.
Args:
image_path: Input image
left, top, right, bottom: Crop box
Returns:
EditedImage
"""
from PIL import Image
import asyncio
def _sync_crop():
img = Image.open(image_path)
img = img.crop((left, top, right, bottom))
buffer = BytesIO()
img.save(buffer, format=img.format or "PNG")
buffer.seek(0)
return EditedImage(
image_bytes=buffer.read(),
format=img.format or "PNG",
size=img.size,
operations=["crop"]
)
return await asyncio.to_thread(_sync_crop)
async def rotate(
self,
image_path: Path,
angle: float,
expand: bool = True
) -> EditedImage:
"""
Rotate image.
Args:
image_path: Input image
angle: Rotation angle in degrees
expand: Expand image to fit rotated content
Returns:
EditedImage
"""
from PIL import Image
import asyncio
def _sync_rotate():
img = Image.open(image_path)
img = img.rotate(angle, expand=expand)
buffer = BytesIO()
img.save(buffer, format=img.format or "PNG")
buffer.seek(0)
return EditedImage(
image_bytes=buffer.read(),
format=img.format or "PNG",
size=img.size,
operations=["rotate"]
)
return await asyncio.to_thread(_sync_rotate)
async def convert_format(
self,
image_path: Path,
target_format: str
) -> EditedImage:
"""
Convert image format.
Args:
image_path: Input image
target_format: Target format ("PNG", "JPEG", "WEBP", etc.)
Returns:
EditedImage
"""
from PIL import Image
import asyncio
def _sync_convert():
img = Image.open(image_path)
# Convert RGBA to RGB if saving as JPEG
if target_format.upper() == "JPEG" and img.mode == "RGBA":
img = img.convert("RGB")
buffer = BytesIO()
img.save(buffer, format=target_format)
buffer.seek(0)
return EditedImage(
image_bytes=buffer.read(),
format=target_format,
size=img.size,
operations=["convert"]
)
return await asyncio.to_thread(_sync_convert)
async def apply_filter(
self,
image_path: Path,
filter_name: str
) -> EditedImage:
"""
Apply filter to image.
Args:
image_path: Input image
filter_name: Filter name ("blur", "sharpen", "contour", etc.)
Returns:
EditedImage
"""
from PIL import Image, ImageFilter
import asyncio
def _sync_filter():
img = Image.open(image_path)
# Map filter names
filters = {
"blur": ImageFilter.BLUR,
"sharpen": ImageFilter.SHARPEN,
"contour": ImageFilter.CONTOUR,
"detail": ImageFilter.DETAIL,
"edge_enhance": ImageFilter.EDGE_ENHANCE,
"smooth": ImageFilter.SMOOTH,
}
filter_obj = filters.get(filter_name.lower())
if not filter_obj:
raise ValueError(f"Unknown filter: {filter_name}")
img = img.filter(filter_obj)
buffer = BytesIO()
img.save(buffer, format=img.format or "PNG")
buffer.seek(0)
return EditedImage(
image_bytes=buffer.read(),
format=img.format or "PNG",
size=img.size,
operations=[f"filter:{filter_name}"]
)
return await asyncio.to_thread(_sync_filter)
# Tool registration helpers
async def resize_image_tool(
image_path: str,
width: int,
height: int,
output_path: str | None = None
) -> dict:
"""Resize image tool"""
editor = ImageEditor()
result = await editor.resize(Path(image_path), width, height)
if output_path:
Path(output_path).write_bytes(result.image_bytes)
return {
"size": result.size,
"format": result.format,
"operations": result.operations
}
async def convert_image_tool(
image_path: str,
target_format: str,
output_path: str | None = None
) -> dict:
"""Convert image format tool"""
editor = ImageEditor()
result = await editor.convert_format(Path(image_path), target_format)
if output_path:
Path(output_path).write_bytes(result.image_bytes)
return {
"format": result.format,
"size": result.size
}
|