chatterer 0.1.10__py3-none-any.whl → 0.1.12__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/__init__.py +60 -60
- chatterer/language_model.py +577 -580
- chatterer/messages.py +9 -9
- chatterer/strategies/__init__.py +13 -13
- chatterer/strategies/atom_of_thoughts.py +975 -975
- chatterer/strategies/base.py +14 -14
- chatterer/tools/__init__.py +28 -28
- chatterer/tools/citation_chunking/__init__.py +3 -3
- chatterer/tools/citation_chunking/chunks.py +53 -53
- chatterer/tools/citation_chunking/citation_chunker.py +118 -118
- chatterer/tools/citation_chunking/citations.py +285 -285
- chatterer/tools/citation_chunking/prompt.py +157 -157
- chatterer/tools/citation_chunking/reference.py +26 -26
- chatterer/tools/citation_chunking/utils.py +138 -138
- chatterer/tools/convert_to_text.py +463 -463
- chatterer/tools/webpage_to_markdown/__init__.py +4 -4
- chatterer/tools/webpage_to_markdown/playwright_bot.py +649 -649
- chatterer/tools/webpage_to_markdown/utils.py +334 -329
- chatterer/tools/youtube.py +146 -132
- chatterer/utils/__init__.py +15 -15
- chatterer/utils/code_agent.py +138 -138
- chatterer/utils/image.py +291 -288
- {chatterer-0.1.10.dist-info → chatterer-0.1.12.dist-info}/METADATA +170 -170
- chatterer-0.1.12.dist-info/RECORD +27 -0
- {chatterer-0.1.10.dist-info → chatterer-0.1.12.dist-info}/WHEEL +1 -1
- chatterer-0.1.10.dist-info/RECORD +0 -27
- {chatterer-0.1.10.dist-info → chatterer-0.1.12.dist-info}/top_level.txt +0 -0
@@ -1,329 +1,334 @@
|
|
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
|
-
|
281
|
-
|
282
|
-
|
283
|
-
|
284
|
-
|
285
|
-
|
286
|
-
|
287
|
-
|
288
|
-
|
289
|
-
|
290
|
-
|
291
|
-
|
292
|
-
|
293
|
-
|
294
|
-
|
295
|
-
|
296
|
-
|
297
|
-
|
298
|
-
|
299
|
-
|
300
|
-
|
301
|
-
|
302
|
-
|
303
|
-
|
304
|
-
|
305
|
-
|
306
|
-
|
307
|
-
|
308
|
-
|
309
|
-
|
310
|
-
|
311
|
-
|
312
|
-
markdown_link,
|
313
|
-
|
314
|
-
|
315
|
-
|
316
|
-
|
317
|
-
|
318
|
-
|
319
|
-
|
320
|
-
|
321
|
-
|
322
|
-
|
323
|
-
|
324
|
-
|
325
|
-
|
326
|
-
|
327
|
-
|
328
|
-
|
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
|
+
image_matches.setdefault(None, []).append(markdown_link)
|
281
|
+
continue
|
282
|
+
image_matches.setdefault(image_data, []).append(markdown_link)
|
283
|
+
return image_matches
|
284
|
+
|
285
|
+
|
286
|
+
async def aget_image_url_and_markdown_links(
|
287
|
+
markdown_text: str, headers: dict[str, str], config: ImageProcessingConfig
|
288
|
+
) -> dict[Optional[Base64Image], list[MarkdownLink]]:
|
289
|
+
image_matches: dict[Optional[Base64Image], list[MarkdownLink]] = {}
|
290
|
+
for markdown_link in MarkdownLink.from_markdown(markdown_text=markdown_text, referer_url=headers.get("Referer")):
|
291
|
+
if markdown_link.type == "link":
|
292
|
+
image_matches.setdefault(None, []).append(markdown_link)
|
293
|
+
continue
|
294
|
+
image_data = await Base64Image.from_url_or_path(
|
295
|
+
markdown_link.url, headers=headers, config=config, return_coro=True
|
296
|
+
)
|
297
|
+
if not image_data:
|
298
|
+
image_matches.setdefault(None, []).append(markdown_link)
|
299
|
+
continue
|
300
|
+
image_matches.setdefault(image_data, []).append(markdown_link)
|
301
|
+
return image_matches
|
302
|
+
|
303
|
+
|
304
|
+
def replace_images(
|
305
|
+
markdown_text: str, image_description_and_references: ImageDescriptionAndReferences, description_format: str
|
306
|
+
) -> str:
|
307
|
+
replacements: list[tuple[MarkdownLink, str]] = []
|
308
|
+
for image_description, markdown_links in image_description_and_references.items():
|
309
|
+
for markdown_link in markdown_links:
|
310
|
+
if image_description is None:
|
311
|
+
if markdown_link.type == "link":
|
312
|
+
replacements.append((markdown_link, markdown_link.link_markdown))
|
313
|
+
elif markdown_link.type == "image":
|
314
|
+
replacements.append((markdown_link, f""))
|
315
|
+
else:
|
316
|
+
replacements.append((
|
317
|
+
markdown_link,
|
318
|
+
description_format.format(
|
319
|
+
image_summary=image_description.replace("\n", " "),
|
320
|
+
inline_text=markdown_link.inline_text,
|
321
|
+
**markdown_link._asdict(),
|
322
|
+
),
|
323
|
+
))
|
324
|
+
|
325
|
+
return MarkdownLink.replace(markdown_text, replacements)
|
326
|
+
|
327
|
+
|
328
|
+
ImageDataAndReferences = dict[Optional[str], list[MarkdownLink]]
|
329
|
+
ImageDescriptionAndReferences = NewType("ImageDescriptionAndReferences", ImageDataAndReferences)
|
330
|
+
WaitUntil: TypeAlias = Literal["commit", "domcontentloaded", "load", "networkidle"]
|
331
|
+
|
332
|
+
DEFAULT_UA: str = (
|
333
|
+
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36"
|
334
|
+
)
|