chatterer 0.1.5__py3-none-any.whl → 0.1.7__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.
@@ -0,0 +1,329 @@
1
+ from __future__ import annotations
2
+
3
+ import os.path
4
+ import re
5
+ from pathlib import Path
6
+ from typing import (
7
+ ClassVar,
8
+ Literal,
9
+ NamedTuple,
10
+ NewType,
11
+ NotRequired,
12
+ Optional,
13
+ Self,
14
+ Sequence,
15
+ TypeAlias,
16
+ TypedDict,
17
+ TypeGuard,
18
+ cast,
19
+ )
20
+ from urllib.parse import urljoin, urlparse
21
+
22
+ import mistune
23
+ import playwright.sync_api
24
+ from pydantic import BaseModel, Field
25
+
26
+ from ...utils.image import Base64Image, ImageProcessingConfig
27
+
28
+
29
+ class SelectedLineRanges(BaseModel):
30
+ line_ranges: list[str] = Field(description="List of inclusive line ranges, e.g., ['1-3', '5-5', '7-10']")
31
+
32
+
33
+ class PlaywrightLaunchOptions(TypedDict):
34
+ executable_path: NotRequired[str | Path]
35
+ channel: NotRequired[str]
36
+ args: NotRequired[Sequence[str]]
37
+ ignore_default_args: NotRequired[bool | Sequence[str]]
38
+ handle_sigint: NotRequired[bool]
39
+ handle_sigterm: NotRequired[bool]
40
+ handle_sighup: NotRequired[bool]
41
+ timeout: NotRequired[float]
42
+ env: NotRequired[dict[str, str | float | bool]]
43
+ headless: NotRequired[bool]
44
+ devtools: NotRequired[bool]
45
+ proxy: NotRequired[playwright.sync_api.ProxySettings]
46
+ downloads_path: NotRequired[str | Path]
47
+ slow_mo: NotRequired[float]
48
+ traces_dir: NotRequired[str | Path]
49
+ chromium_sandbox: NotRequired[bool]
50
+ firefox_user_prefs: NotRequired[dict[str, str | float | bool]]
51
+
52
+
53
+ class PlaywrightPersistencyOptions(TypedDict):
54
+ user_data_dir: NotRequired[str | Path]
55
+ storage_state: NotRequired[playwright.sync_api.StorageState]
56
+
57
+
58
+ class PlaywrightOptions(PlaywrightLaunchOptions, PlaywrightPersistencyOptions): ...
59
+
60
+
61
+ def get_default_playwright_launch_options() -> PlaywrightLaunchOptions:
62
+ return {"headless": True}
63
+
64
+
65
+ class _TrackingInlineState(mistune.InlineState):
66
+ meta_offset: int = 0 # Where in the original text does self.src start?
67
+
68
+ def copy(self) -> Self:
69
+ new_state = self.__class__(self.env)
70
+ new_state.src = self.src
71
+ new_state.tokens = []
72
+ new_state.in_image = self.in_image
73
+ new_state.in_link = self.in_link
74
+ new_state.in_emphasis = self.in_emphasis
75
+ new_state.in_strong = self.in_strong
76
+ new_state.meta_offset = self.meta_offset
77
+ return new_state
78
+
79
+
80
+ class MarkdownLink(NamedTuple):
81
+ type: Literal["link", "image"]
82
+ url: str
83
+ text: str
84
+ title: Optional[str]
85
+ pos: int
86
+ end_pos: int
87
+
88
+ @classmethod
89
+ def from_markdown(cls, markdown_text: str, referer_url: Optional[str]) -> list[Self]:
90
+ """
91
+ The main function that returns the list of MarkdownLink for the input text.
92
+ For simplicity, we do a "pure inline parse" of the entire text
93
+ instead of letting the block parser break it up. That ensures that
94
+ link tokens cover the global positions of the entire input.
95
+ """
96
+ md = mistune.Markdown(inline=_TrackingInlineParser())
97
+ # Create an inline state that references the full text.
98
+ state = _TrackingInlineState({})
99
+ state.src = markdown_text
100
+
101
+ # Instead of calling md.parse, we can directly run the inline parser on
102
+ # the entire text, so that positions match the entire input:
103
+ md.inline.parse(state)
104
+
105
+ # Now gather all the link info from the tokens.
106
+ return cls._extract_links(tokens=state.tokens, referer_url=referer_url)
107
+
108
+ @property
109
+ def inline_text(self) -> str:
110
+ return self.text.replace("\n", " ").strip()
111
+
112
+ @property
113
+ def inline_title(self) -> str:
114
+ return self.title.replace("\n", " ").strip() if self.title else ""
115
+
116
+ @property
117
+ def link_markdown(self) -> str:
118
+ if self.title:
119
+ return f'[{self.inline_text}]({self.url} "{self.inline_title}")'
120
+ return f"[{self.inline_text}]({self.url})"
121
+
122
+ @classmethod
123
+ def replace(cls, text: str, replacements: list[tuple[Self, str]]) -> str:
124
+ for self, replacement in sorted(replacements, key=lambda x: x[0].pos, reverse=True):
125
+ text = text[: self.pos] + replacement + text[self.end_pos :]
126
+ return text
127
+
128
+ @classmethod
129
+ def _extract_links(cls, tokens: list[dict[str, object]], referer_url: Optional[str]) -> list[Self]:
130
+ results: list[Self] = []
131
+ for token in tokens:
132
+ if (
133
+ (type := token.get("type")) in ("link", "image")
134
+ and "global_pos" in token
135
+ and "attrs" in token
136
+ and _attrs_typeguard(attrs := token["attrs"])
137
+ and "url" in attrs
138
+ and _url_typeguard(url := attrs["url"])
139
+ and _global_pos_typeguard(global_pos := token["global_pos"])
140
+ ):
141
+ if referer_url:
142
+ url = _to_absolute_path(path=url, referer=referer_url)
143
+ children: object | None = token.get("children")
144
+ if _children_typeguard(children):
145
+ text = _extract_text(children)
146
+ else:
147
+ text = ""
148
+
149
+ if "title" in attrs:
150
+ title = str(attrs["title"])
151
+ else:
152
+ title = None
153
+
154
+ start, end = global_pos
155
+ results.append(cls(type, url, text, title, start, end))
156
+ if "children" in token and _children_typeguard(children := token["children"]):
157
+ results.extend(cls._extract_links(children, referer_url))
158
+
159
+ return results
160
+
161
+
162
+ class _TrackingInlineParser(mistune.InlineParser):
163
+ state_cls: ClassVar = _TrackingInlineState
164
+
165
+ def parse_link( # pyright: ignore[reportIncompatibleMethodOverride]
166
+ self, m: re.Match[str], state: _TrackingInlineState
167
+ ) -> Optional[int]:
168
+ """
169
+ Mistune calls parse_link with a match object for the link syntax
170
+ and the current inline state. If we successfully parse the link,
171
+ super().parse_link(...) returns the new position *within self.src*.
172
+ We add that to state.meta_offset for the global position.
173
+
174
+ Because parse_link in mistune might return None or an int, we only
175
+ record positions if we get an int back (meaning success).
176
+ """
177
+ offset = state.meta_offset
178
+ new_pos: int | None = super().parse_link(m, state)
179
+ if new_pos is not None:
180
+ # We have successfully parsed a link.
181
+ # The link token we just added should be the last token in state.tokens:
182
+ if state.tokens:
183
+ token = state.tokens[-1]
184
+ # The local end is new_pos in the substring.
185
+ # So the global start/end in the *original* text is offset + local positions.
186
+ token["global_pos"] = (offset + m.start(), offset + new_pos)
187
+ return new_pos
188
+
189
+
190
+ # --------------------------------------------------------------------
191
+ # Type Guards & Helper to gather plain text from nested tokens (for the link text).
192
+ # --------------------------------------------------------------------
193
+ def _children_typeguard(obj: object) -> TypeGuard[list[dict[str, object]]]:
194
+ if not isinstance(obj, list):
195
+ return False
196
+ return all(isinstance(i, dict) for i in cast(list[object], obj))
197
+
198
+
199
+ def _attrs_typeguard(obj: object) -> TypeGuard[dict[str, object]]:
200
+ if not isinstance(obj, dict):
201
+ return False
202
+ return all(isinstance(k, str) for k in cast(dict[object, object], obj))
203
+
204
+
205
+ def _global_pos_typeguard(obj: object) -> TypeGuard[tuple[int, int]]:
206
+ if not isinstance(obj, tuple):
207
+ return False
208
+ obj = cast(tuple[object, ...], obj)
209
+ if len(obj) != 2:
210
+ return False
211
+ return all(isinstance(i, int) for i in obj)
212
+
213
+
214
+ def _url_typeguard(obj: object) -> TypeGuard[str]:
215
+ return isinstance(obj, str)
216
+
217
+
218
+ def _extract_text(tokens: list[dict[str, object]]) -> str:
219
+ parts: list[str] = []
220
+ for t in tokens:
221
+ if t.get("type") == "text":
222
+ parts.append(str(t.get("raw", "")))
223
+ elif "children" in t:
224
+ children: object = t["children"]
225
+ if not _children_typeguard(children):
226
+ continue
227
+ parts.append(_extract_text(children))
228
+ return "".join(parts)
229
+
230
+
231
+ def _to_absolute_path(path: str, referer: str) -> str:
232
+ """
233
+ path : 변환할 경로(상대/절대 경로 혹은 URL일 수도 있음)
234
+ referer : 기준이 되는 절대경로(혹은 URL)
235
+ """
236
+ # referer가 URL인지 파일 경로인지 먼저 판별
237
+ ref_parsed = urlparse(referer)
238
+ is_referer_url = bool(ref_parsed.scheme and ref_parsed.netloc)
239
+
240
+ if is_referer_url:
241
+ # referer가 URL이라면,
242
+ # 1) path 자체가 이미 절대 URL인지 확인
243
+ parsed = urlparse(path)
244
+ if parsed.scheme and parsed.netloc:
245
+ # path가 이미 완전한 URL (예: http://, https:// 등)
246
+ return path
247
+ else:
248
+ # 그렇지 않다면(슬래시로 시작 포함), urljoin을 써서 referer + path 로 합침
249
+ return urljoin(referer, path)
250
+ else:
251
+ # referer가 로컬 경로라면,
252
+ # path가 로컬 파일 시스템에서의 절대경로인지 판단
253
+ if os.path.isabs(path):
254
+ return path
255
+ else:
256
+ # 파일이면 referer의 디렉토리만 추출
257
+ if not os.path.isdir(referer):
258
+ referer_dir = os.path.dirname(referer)
259
+ else:
260
+ referer_dir = referer
261
+
262
+ combined = os.path.join(referer_dir, path)
263
+ return os.path.abspath(combined)
264
+
265
+
266
+ # =======================
267
+
268
+
269
+ def get_image_url_and_markdown_links(
270
+ markdown_text: str, headers: dict[str, str], config: ImageProcessingConfig
271
+ ) -> dict[Optional[Base64Image], list[MarkdownLink]]:
272
+ image_matches: dict[Optional[Base64Image], list[MarkdownLink]] = {}
273
+ for markdown_link in MarkdownLink.from_markdown(markdown_text=markdown_text, referer_url=headers.get("Referer")):
274
+ if markdown_link.type == "link":
275
+ image_matches.setdefault(None, []).append(markdown_link)
276
+ continue
277
+
278
+ image_data = Base64Image.from_url_or_path(markdown_link.url, headers=headers, config=config)
279
+ if not image_data:
280
+ continue
281
+ image_matches.setdefault(image_data, []).append(markdown_link)
282
+ return image_matches
283
+
284
+
285
+ async def aget_image_url_and_markdown_links(
286
+ markdown_text: str, headers: dict[str, str], config: ImageProcessingConfig
287
+ ) -> dict[Optional[Base64Image], list[MarkdownLink]]:
288
+ image_matches: dict[Optional[Base64Image], list[MarkdownLink]] = {}
289
+ for markdown_link in MarkdownLink.from_markdown(markdown_text=markdown_text, referer_url=headers.get("Referer")):
290
+ if markdown_link.type == "link":
291
+ image_matches.setdefault(None, []).append(markdown_link)
292
+ continue
293
+ image_data = await Base64Image.from_url_or_path(
294
+ markdown_link.url, headers=headers, config=config, return_coro=True
295
+ )
296
+ if not image_data:
297
+ continue
298
+ image_matches.setdefault(image_data, []).append(markdown_link)
299
+ return image_matches
300
+
301
+
302
+ def replace_images(
303
+ markdown_text: str, image_description_and_references: ImageDescriptionAndReferences, description_format: str
304
+ ) -> str:
305
+ replacements: list[tuple[MarkdownLink, str]] = []
306
+ for image_description, markdown_links in image_description_and_references.items():
307
+ for markdown_link in markdown_links:
308
+ if image_description is None:
309
+ replacements.append((markdown_link, markdown_link.link_markdown))
310
+ else:
311
+ replacements.append((
312
+ markdown_link,
313
+ description_format.format(
314
+ image_summary=image_description.replace("\n", " "),
315
+ inline_text=markdown_link.inline_text,
316
+ **markdown_link._asdict(),
317
+ ),
318
+ ))
319
+
320
+ return MarkdownLink.replace(markdown_text, replacements)
321
+
322
+
323
+ ImageDataAndReferences = dict[Optional[str], list[MarkdownLink]]
324
+ ImageDescriptionAndReferences = NewType("ImageDescriptionAndReferences", ImageDataAndReferences)
325
+ WaitUntil: TypeAlias = Literal["commit", "domcontentloaded", "load", "networkidle"]
326
+
327
+ DEFAULT_UA: str = (
328
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36"
329
+ )
@@ -0,0 +1,284 @@
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