chatterer 0.1.7__py3-none-any.whl → 0.1.9__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
chatterer/utils/image.py CHANGED
@@ -1,284 +1,288 @@
1
- from __future__ import annotations
2
-
3
- import re
4
- from base64 import b64encode
5
- from io import BytesIO
6
- from pathlib import Path
7
- from traceback import print_exc
8
- from typing import (
9
- Awaitable,
10
- ClassVar,
11
- Literal,
12
- NotRequired,
13
- Optional,
14
- Self,
15
- Sequence,
16
- TypeAlias,
17
- TypedDict,
18
- TypeGuard,
19
- cast,
20
- get_args,
21
- overload,
22
- )
23
- from urllib.parse import urlparse
24
-
25
- import requests
26
- from aiohttp import ClientSession
27
- from PIL.Image import Resampling
28
- from PIL.Image import open as image_open
29
- from pydantic import BaseModel
30
-
31
- ImageType: TypeAlias = Literal["jpeg", "jpg", "png", "gif", "webp", "bmp"]
32
-
33
-
34
- class ImageProcessingConfig(TypedDict):
35
- """
36
- 이미지 필터링/변환 시 사용할 설정.
37
- - formats: (Sequence[str]) 허용할 이미지 포맷(소문자, 예: ["jpeg", "png", "webp"]).
38
- - max_size_mb: (float) 이미지 용량 상한(MB). 초과 시 제외.
39
- - min_largest_side: (int) 가로나 세로 중 가장 큰 변의 최소 크기. 미만 시 제외.
40
- - resize_if_min_side_exceeds: (int) 가로나 세로 중 작은 변이 이 값 이상이면 리스케일.
41
- - resize_target_for_min_side: (int) 리스케일시, '가장 작은 변'을 이 값으로 줄임(비율 유지는 Lanczos).
42
- """
43
-
44
- formats: Sequence[ImageType]
45
- max_size_mb: NotRequired[float]
46
- min_largest_side: NotRequired[int]
47
- resize_if_min_side_exceeds: NotRequired[int]
48
- resize_target_for_min_side: NotRequired[int]
49
-
50
-
51
- def get_default_image_processing_config() -> ImageProcessingConfig:
52
- return {
53
- "max_size_mb": 5,
54
- "min_largest_side": 200,
55
- "resize_if_min_side_exceeds": 2000,
56
- "resize_target_for_min_side": 1000,
57
- "formats": ["png", "jpeg", "gif", "bmp", "webp"],
58
- }
59
-
60
-
61
- class Base64Image(BaseModel):
62
- ext: ImageType
63
- data: str
64
-
65
- IMAGE_TYPES: ClassVar[tuple[str, ...]] = tuple(map(str, get_args(ImageType)))
66
- IMAGE_PATTERN: ClassVar[re.Pattern[str]] = re.compile(
67
- rf"data:image/({'|'.join(IMAGE_TYPES)});base64,[A-Za-z0-9+/]+={0, 2}$"
68
- )
69
-
70
- def __hash__(self) -> int:
71
- return hash((self.ext, self.data))
72
-
73
- def model_post_init(self, __context: object) -> None:
74
- if self.ext == "jpg":
75
- self.ext = "jpeg"
76
-
77
- @classmethod
78
- def from_string(cls, data: str) -> Optional[Self]:
79
- match = cls.IMAGE_PATTERN.fullmatch(data)
80
- if not match:
81
- return None
82
- return cls(ext=cast(ImageType, match.group(1)), data=match.group(2))
83
-
84
- @overload
85
- @classmethod
86
- def from_url_or_path(
87
- cls,
88
- url_or_path: str,
89
- *,
90
- headers: dict[str, str] = ...,
91
- config: ImageProcessingConfig = ...,
92
- return_coro: Literal[True],
93
- ) -> Awaitable[Optional[Self]]: ...
94
-
95
- @overload
96
- @classmethod
97
- def from_url_or_path(
98
- cls,
99
- url_or_path: str,
100
- *,
101
- headers: dict[str, str] = ...,
102
- config: ImageProcessingConfig = ...,
103
- return_coro: Literal[False] = False,
104
- ) -> Optional[Self]: ...
105
-
106
- @classmethod
107
- def from_url_or_path(
108
- cls,
109
- url_or_path: str,
110
- *,
111
- headers: dict[str, str] = {},
112
- config: ImageProcessingConfig = get_default_image_processing_config(),
113
- return_coro: bool = False,
114
- ) -> Optional[Self] | Awaitable[Optional[Self]]:
115
- """Return a Base64Image instance from a URL or local file path."""
116
- if maybe_base64 := cls.from_string(url_or_path):
117
- return maybe_base64
118
- elif _is_remote_url(url_or_path):
119
- if return_coro:
120
- return cls._afetch_remote_image(url_or_path, headers, config)
121
- return cls._fetch_remote_image(url_or_path, headers, config)
122
- return cls._process_local_image(Path(url_or_path), config)
123
-
124
- @property
125
- def data_uri(self) -> str:
126
- return f"data:image/{self.ext.replace('jpg', 'jpeg')};base64,{self.data}"
127
-
128
- @property
129
- def data_uri_content(self) -> dict[Literal["type", "image_url"], Literal["image_url"] | dict[Literal["url"], str]]:
130
- return {"type": "image_url", "image_url": {"url": self.data_uri}}
131
-
132
- @staticmethod
133
- def _verify_ext(ext: str, allowed_types: Sequence[ImageType]) -> TypeGuard[ImageType]:
134
- return ext in allowed_types
135
-
136
- @classmethod
137
- def _fetch_remote_image(cls, url: str, headers: dict[str, str], config: ImageProcessingConfig) -> Optional[Self]:
138
- image_bytes = _get_image_bytes(image_url=url.strip(), headers=headers)
139
- if not image_bytes:
140
- return None
141
- return cls._convert_image_into_base64(image_bytes, config)
142
-
143
- @classmethod
144
- async def _afetch_remote_image(
145
- cls, url: str, headers: dict[str, str], config: ImageProcessingConfig
146
- ) -> Optional[Self]:
147
- image_bytes = await _aget_image_bytes(image_url=url.strip(), headers=headers)
148
- if not image_bytes:
149
- return None
150
- return cls._convert_image_into_base64(image_bytes, config)
151
-
152
- @classmethod
153
- def _convert_image_into_base64(cls, image_data: bytes, config: Optional[ImageProcessingConfig]) -> Optional[Self]:
154
- """
155
- Retrieve an image in bytes and return a base64-encoded data URL,
156
- applying dynamic rules from 'config'.
157
- """
158
- if not config:
159
- # config 없으면 그냥 기존 헤더만 보고 돌려주는 간단 로직
160
- return cls._simple_base64_encode(image_data)
161
-
162
- # 1) 용량 검사
163
- max_size_mb = config.get("max_size_mb", float("inf"))
164
- image_size_mb = len(image_data) / (1024 * 1024)
165
- if image_size_mb > max_size_mb:
166
- print(f"Image too large: {image_size_mb:.2f} MB > {max_size_mb} MB")
167
- return None
168
-
169
- # 2) Pillow로 이미지 열기
170
- try:
171
- with image_open(BytesIO(image_data)) as im:
172
- w, h = im.size
173
- # 가장
174
- largest_side = max(w, h)
175
- # 가장 작은
176
- smallest_side = min(w, h)
177
-
178
- # min_largest_side 기준
179
- min_largest_side = config.get("min_largest_side", 1)
180
- if largest_side < min_largest_side:
181
- print(f"Image too small: {largest_side} < {min_largest_side}")
182
- return None
183
-
184
- # resize 로직
185
- resize_if_min_side_exceeds = config.get("resize_if_min_side_exceeds", float("inf"))
186
- if smallest_side >= resize_if_min_side_exceeds:
187
- # resize_target_for_min_side 로 축소
188
- resize_target = config.get("resize_target_for_min_side", 1000)
189
- ratio = resize_target / float(smallest_side)
190
- new_w = int(w * ratio)
191
- new_h = int(h * ratio)
192
- im = im.resize((new_w, new_h), Resampling.LANCZOS)
193
-
194
- # 포맷 제한
195
- # PIL이 인식한 포맷이 대문자(JPEG)일 수 있으므로 소문자로
196
- pil_format: str = (im.format or "").lower()
197
- allowed_formats: Sequence[ImageType] = config.get("formats", [])
198
- if not cls._verify_ext(pil_format, allowed_formats):
199
- print(f"Invalid format: {pil_format} not in {allowed_formats}")
200
- return None
201
-
202
- # 다시 bytes 로 저장
203
- output_buffer = BytesIO()
204
- im.save(output_buffer, format=pil_format.upper()) # PIL에 맞춰서 대문자로
205
- output_buffer.seek(0)
206
- final_bytes = output_buffer.read()
207
-
208
- except Exception:
209
- print_exc()
210
- return None
211
-
212
- # 최종 base64 인코딩
213
- encoded_data = b64encode(final_bytes).decode("utf-8")
214
- return cls(ext=pil_format, data=encoded_data)
215
-
216
- @classmethod
217
- def _simple_base64_encode(cls, image_data: bytes) -> Optional[Self]:
218
- """
219
- Retrieve an image URL and return a base64-encoded data URL.
220
- """
221
- ext = _detect_image_type(image_data)
222
- if not ext:
223
- return
224
- return cls(ext=ext, data=b64encode(image_data).decode("utf-8"))
225
-
226
- @classmethod
227
- def _process_local_image(cls, path: Path, config: ImageProcessingConfig) -> Optional[Self]:
228
- """로컬 파일이 존재하고 유효한 이미지 포맷이면 Base64 데이터 URL을 반환, 아니면 None."""
229
- if not path.is_file():
230
- return None
231
- ext = path.suffix.lower().removeprefix(".")
232
- if not cls._verify_ext(ext, config["formats"]):
233
- return None
234
- return cls(ext=ext, data=b64encode(path.read_bytes()).decode("ascii"))
235
-
236
-
237
- def _is_remote_url(path: str) -> bool:
238
- parsed = urlparse(path)
239
- return bool(parsed.scheme and parsed.netloc)
240
-
241
-
242
- def _detect_image_type(image_data: bytes) -> Optional[ImageType]:
243
- """
244
- Detect the image format based on the image binary signature (header).
245
- Only JPEG, PNG, GIF, WEBP, and BMP are handled as examples.
246
- If the format is not recognized, return None.
247
- """
248
- # JPEG: 시작 바이트가 FF D8 FF
249
- if image_data.startswith(b"\xff\xd8\xff"):
250
- return "jpeg"
251
- # PNG: 시작 바이트가 89 50 4E 47 0D 0A 1A 0A
252
- elif image_data.startswith(b"\x89PNG\r\n\x1a\n"):
253
- return "png"
254
- # GIF: 시작 바이트가 GIF87a 또는 GIF89a
255
- elif image_data.startswith(b"GIF87a") or image_data.startswith(b"GIF89a"):
256
- return "gif"
257
- # WEBP: 시작 바이트가 RIFF....WEBP
258
- elif image_data.startswith(b"RIFF") and image_data[8:12] == b"WEBP":
259
- return "webp"
260
- # BMP: 시작 바이트가 BM
261
- elif image_data.startswith(b"BM"):
262
- return "bmp"
263
-
264
-
265
- def _get_image_bytes(image_url: str, headers: dict[str, str]) -> Optional[bytes]:
266
- try:
267
- with requests.Session() as session:
268
- response = session.get(image_url, headers={k: str(v) for k, v in headers.items()})
269
- if not response.ok:
270
- return
271
- return bytes(response.content or b"")
272
- except Exception:
273
- return
274
-
275
-
276
- async def _aget_image_bytes(image_url: str, headers: dict[str, str]) -> Optional[bytes]:
277
- try:
278
- async with ClientSession() as session:
279
- async with session.get(image_url, headers={k: str(v) for k, v in headers.items()}) as response:
280
- if not response.ok:
281
- return
282
- return await response.read()
283
- except Exception:
284
- return
1
+ from __future__ import annotations
2
+
3
+ import re
4
+ from base64 import b64encode
5
+ from io import BytesIO
6
+ from pathlib import Path
7
+ from traceback import print_exc
8
+ from typing import (
9
+ Awaitable,
10
+ ClassVar,
11
+ Literal,
12
+ NotRequired,
13
+ Optional,
14
+ Self,
15
+ Sequence,
16
+ TypeAlias,
17
+ TypedDict,
18
+ TypeGuard,
19
+ cast,
20
+ get_args,
21
+ overload,
22
+ )
23
+ from urllib.parse import urlparse
24
+
25
+ import requests
26
+ from aiohttp import ClientSession
27
+ from PIL.Image import Resampling
28
+ from PIL.Image import open as image_open
29
+ from pydantic import BaseModel
30
+
31
+ ImageType: TypeAlias = Literal["jpeg", "jpg", "png", "gif", "webp", "bmp"]
32
+
33
+
34
+ class ImageProcessingConfig(TypedDict):
35
+ """
36
+ 이미지 필터링/변환 시 사용할 설정.
37
+ - formats: (Sequence[str]) 허용할 이미지 포맷(소문자, 예: ["jpeg", "png", "webp"]).
38
+ - max_size_mb: (float) 이미지 용량 상한(MB). 초과 시 제외.
39
+ - min_largest_side: (int) 가로나 세로 중 가장 큰 변의 최소 크기. 미만 시 제외.
40
+ - resize_if_min_side_exceeds: (int) 가로나 세로 중 작은 변이 이 값 이상이면 리스케일.
41
+ - resize_target_for_min_side: (int) 리스케일시, '가장 작은 변'을 이 값으로 줄임(비율 유지는 Lanczos).
42
+ """
43
+
44
+ formats: Sequence[ImageType]
45
+ max_size_mb: NotRequired[float]
46
+ min_largest_side: NotRequired[int]
47
+ resize_if_min_side_exceeds: NotRequired[int]
48
+ resize_target_for_min_side: NotRequired[int]
49
+
50
+
51
+ def get_default_image_processing_config() -> ImageProcessingConfig:
52
+ return {
53
+ "max_size_mb": 5,
54
+ "min_largest_side": 200,
55
+ "resize_if_min_side_exceeds": 2000,
56
+ "resize_target_for_min_side": 1000,
57
+ "formats": ["png", "jpeg", "gif", "bmp", "webp"],
58
+ }
59
+
60
+
61
+ class Base64Image(BaseModel):
62
+ ext: ImageType
63
+ data: str
64
+
65
+ IMAGE_TYPES: ClassVar[tuple[str, ...]] = tuple(map(str, get_args(ImageType)))
66
+ IMAGE_PATTERN: ClassVar[re.Pattern[str]] = re.compile(
67
+ rf"data:image/({'|'.join(IMAGE_TYPES)});base64,[A-Za-z0-9+/]+={0, 2}$"
68
+ )
69
+
70
+ def __hash__(self) -> int:
71
+ return hash((self.ext, self.data))
72
+
73
+ def model_post_init(self, __context: object) -> None:
74
+ if self.ext == "jpg":
75
+ self.ext = "jpeg"
76
+
77
+ @classmethod
78
+ def from_string(cls, data: str) -> Optional[Self]:
79
+ match = cls.IMAGE_PATTERN.fullmatch(data)
80
+ if not match:
81
+ return None
82
+ return cls(ext=cast(ImageType, match.group(1)), data=match.group(2))
83
+
84
+ @classmethod
85
+ def from_bytes(cls, data: bytes, ext: ImageType) -> Self:
86
+ return cls(ext=ext, data=b64encode(data).decode("utf-8"))
87
+
88
+ @overload
89
+ @classmethod
90
+ def from_url_or_path(
91
+ cls,
92
+ url_or_path: str,
93
+ *,
94
+ headers: dict[str, str] = ...,
95
+ config: ImageProcessingConfig = ...,
96
+ return_coro: Literal[True],
97
+ ) -> Awaitable[Optional[Self]]: ...
98
+
99
+ @overload
100
+ @classmethod
101
+ def from_url_or_path(
102
+ cls,
103
+ url_or_path: str,
104
+ *,
105
+ headers: dict[str, str] = ...,
106
+ config: ImageProcessingConfig = ...,
107
+ return_coro: Literal[False] = False,
108
+ ) -> Optional[Self]: ...
109
+
110
+ @classmethod
111
+ def from_url_or_path(
112
+ cls,
113
+ url_or_path: str,
114
+ *,
115
+ headers: dict[str, str] = {},
116
+ config: ImageProcessingConfig = get_default_image_processing_config(),
117
+ return_coro: bool = False,
118
+ ) -> Optional[Self] | Awaitable[Optional[Self]]:
119
+ """Return a Base64Image instance from a URL or local file path."""
120
+ if maybe_base64 := cls.from_string(url_or_path):
121
+ return maybe_base64
122
+ elif _is_remote_url(url_or_path):
123
+ if return_coro:
124
+ return cls._afetch_remote_image(url_or_path, headers, config)
125
+ return cls._fetch_remote_image(url_or_path, headers, config)
126
+ return cls._process_local_image(Path(url_or_path), config)
127
+
128
+ @property
129
+ def data_uri(self) -> str:
130
+ return f"data:image/{self.ext.replace('jpg', 'jpeg')};base64,{self.data}"
131
+
132
+ @property
133
+ def data_uri_content(self) -> dict[Literal["type", "image_url"], Literal["image_url"] | dict[Literal["url"], str]]:
134
+ return {"type": "image_url", "image_url": {"url": self.data_uri}}
135
+
136
+ @staticmethod
137
+ def _verify_ext(ext: str, allowed_types: Sequence[ImageType]) -> TypeGuard[ImageType]:
138
+ return ext in allowed_types
139
+
140
+ @classmethod
141
+ def _fetch_remote_image(cls, url: str, headers: dict[str, str], config: ImageProcessingConfig) -> Optional[Self]:
142
+ image_bytes = _get_image_bytes(image_url=url.strip(), headers=headers)
143
+ if not image_bytes:
144
+ return None
145
+ return cls._convert_image_into_base64(image_bytes, config)
146
+
147
+ @classmethod
148
+ async def _afetch_remote_image(
149
+ cls, url: str, headers: dict[str, str], config: ImageProcessingConfig
150
+ ) -> Optional[Self]:
151
+ image_bytes = await _aget_image_bytes(image_url=url.strip(), headers=headers)
152
+ if not image_bytes:
153
+ return None
154
+ return cls._convert_image_into_base64(image_bytes, config)
155
+
156
+ @classmethod
157
+ def _convert_image_into_base64(cls, image_data: bytes, config: Optional[ImageProcessingConfig]) -> Optional[Self]:
158
+ """
159
+ Retrieve an image in bytes and return a base64-encoded data URL,
160
+ applying dynamic rules from 'config'.
161
+ """
162
+ if not config:
163
+ # config 없으면 그냥 기존 헤더만 보고 돌려주는 간단 로직
164
+ return cls._simple_base64_encode(image_data)
165
+
166
+ # 1) 용량 검사
167
+ max_size_mb = config.get("max_size_mb", float("inf"))
168
+ image_size_mb = len(image_data) / (1024 * 1024)
169
+ if image_size_mb > max_size_mb:
170
+ print(f"Image too large: {image_size_mb:.2f} MB > {max_size_mb} MB")
171
+ return None
172
+
173
+ # 2) Pillow로 이미지 열기
174
+ try:
175
+ with image_open(BytesIO(image_data)) as im:
176
+ w, h = im.size
177
+ # 가장 큰 변
178
+ largest_side = max(w, h)
179
+ # 가장 작은
180
+ smallest_side = min(w, h)
181
+
182
+ # min_largest_side 기준
183
+ min_largest_side = config.get("min_largest_side", 1)
184
+ if largest_side < min_largest_side:
185
+ print(f"Image too small: {largest_side} < {min_largest_side}")
186
+ return None
187
+
188
+ # resize 로직
189
+ resize_if_min_side_exceeds = config.get("resize_if_min_side_exceeds", float("inf"))
190
+ if smallest_side >= resize_if_min_side_exceeds:
191
+ # resize_target_for_min_side 축소
192
+ resize_target = config.get("resize_target_for_min_side", 1000)
193
+ ratio = resize_target / float(smallest_side)
194
+ new_w = int(w * ratio)
195
+ new_h = int(h * ratio)
196
+ im = im.resize((new_w, new_h), Resampling.LANCZOS)
197
+
198
+ # 포맷 제한
199
+ # PIL이 인식한 포맷이 대문자(JPEG)일 수 있으므로 소문자로
200
+ pil_format: str = (im.format or "").lower()
201
+ allowed_formats: Sequence[ImageType] = config.get("formats", [])
202
+ if not cls._verify_ext(pil_format, allowed_formats):
203
+ print(f"Invalid format: {pil_format} not in {allowed_formats}")
204
+ return None
205
+
206
+ # 다시 bytes 로 저장
207
+ output_buffer = BytesIO()
208
+ im.save(output_buffer, format=pil_format.upper()) # PIL에 맞춰서 대문자로
209
+ output_buffer.seek(0)
210
+ final_bytes = output_buffer.read()
211
+
212
+ except Exception:
213
+ print_exc()
214
+ return None
215
+
216
+ # 최종 base64 인코딩
217
+ encoded_data = b64encode(final_bytes).decode("utf-8")
218
+ return cls(ext=pil_format, data=encoded_data)
219
+
220
+ @classmethod
221
+ def _simple_base64_encode(cls, image_data: bytes) -> Optional[Self]:
222
+ """
223
+ Retrieve an image URL and return a base64-encoded data URL.
224
+ """
225
+ ext = _detect_image_type(image_data)
226
+ if not ext:
227
+ return
228
+ return cls(ext=ext, data=b64encode(image_data).decode("utf-8"))
229
+
230
+ @classmethod
231
+ def _process_local_image(cls, path: Path, config: ImageProcessingConfig) -> Optional[Self]:
232
+ """로컬 파일이 존재하고 유효한 이미지 포맷이면 Base64 데이터 URL을 반환, 아니면 None."""
233
+ if not path.is_file():
234
+ return None
235
+ ext = path.suffix.lower().removeprefix(".")
236
+ if not cls._verify_ext(ext, config["formats"]):
237
+ return None
238
+ return cls(ext=ext, data=b64encode(path.read_bytes()).decode("ascii"))
239
+
240
+
241
+ def _is_remote_url(path: str) -> bool:
242
+ parsed = urlparse(path)
243
+ return bool(parsed.scheme and parsed.netloc)
244
+
245
+
246
+ def _detect_image_type(image_data: bytes) -> Optional[ImageType]:
247
+ """
248
+ Detect the image format based on the image binary signature (header).
249
+ Only JPEG, PNG, GIF, WEBP, and BMP are handled as examples.
250
+ If the format is not recognized, return None.
251
+ """
252
+ # JPEG: 시작 바이트가 FF D8 FF
253
+ if image_data.startswith(b"\xff\xd8\xff"):
254
+ return "jpeg"
255
+ # PNG: 시작 바이트가 89 50 4E 47 0D 0A 1A 0A
256
+ elif image_data.startswith(b"\x89PNG\r\n\x1a\n"):
257
+ return "png"
258
+ # GIF: 시작 바이트가 GIF87a 또는 GIF89a
259
+ elif image_data.startswith(b"GIF87a") or image_data.startswith(b"GIF89a"):
260
+ return "gif"
261
+ # WEBP: 시작 바이트가 RIFF....WEBP
262
+ elif image_data.startswith(b"RIFF") and image_data[8:12] == b"WEBP":
263
+ return "webp"
264
+ # BMP: 시작 바이트가 BM
265
+ elif image_data.startswith(b"BM"):
266
+ return "bmp"
267
+
268
+
269
+ def _get_image_bytes(image_url: str, headers: dict[str, str]) -> Optional[bytes]:
270
+ try:
271
+ with requests.Session() as session:
272
+ response = session.get(image_url, headers={k: str(v) for k, v in headers.items()})
273
+ if not response.ok:
274
+ return
275
+ return bytes(response.content or b"")
276
+ except Exception:
277
+ return
278
+
279
+
280
+ async def _aget_image_bytes(image_url: str, headers: dict[str, str]) -> Optional[bytes]:
281
+ try:
282
+ async with ClientSession() as session:
283
+ async with session.get(image_url, headers={k: str(v) for k, v in headers.items()}) as response:
284
+ if not response.ok:
285
+ return
286
+ return await response.read()
287
+ except Exception:
288
+ return