Add files using upload-large-folder tool
Browse files- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/markdown_it/_compat.py +1 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/markdown_it/main.py +351 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/markdown_it/parser_block.py +113 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/markdown_it/parser_core.py +46 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/markdown_it/parser_inline.py +215 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/markdown_it/py.typed +1 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/markdown_it/renderer.py +356 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/markdown_it/ruler.py +275 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/markdown_it/tree.py +333 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/markdown_it/utils.py +194 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/colpali/__init__.py +28 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/colpali/modular_colpali.py +296 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_2x8gpu_50ep_lr4e3_ema0p9999_elfopt_not5_bottleneck128_unfixed_norm_stateprobadd_selfcond_ce_fast_20260610_020108/step_153000.pt +3 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_2x8gpu_50ep_lr4e3_ema0p9999_elfopt_not5_bottleneck128_unfixed_norm_stateprobadd_selfcond_ce_fast_20260610_020108/step_169000.pt +3 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_2x8gpu_50ep_lr4e3_ema0p9999_elfopt_not5_bottleneck128_unfixed_norm_stateprobadd_selfcond_ce_fast_20260610_020108/step_188000.pt +3 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_2x8gpu_50ep_lr4e3_ema0p9999_elfopt_not5_bottleneck128_unfixed_norm_stateprobadd_selfcond_ce_fast_20260610_020108/step_247000.pt +3 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_2x8gpu_50ep_lr4e3_ema0p9999_elfopt_not5_bottleneck128_unfixed_norm_stateprobadd_selfcond_ce_fast_20260610_020108/step_272000.pt +3 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_2x8gpu_50ep_lr4e3_ema0p9999_elfopt_not5_bottleneck128_unfixed_norm_stateprobadd_selfcond_ce_fast_20260610_020108/step_287000.pt +3 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_2x8gpu_50ep_lr4e3_ema0p9999_elfopt_not5_bottleneck128_unfixed_norm_stateprobadd_selfcond_ce_fast_20260610_020108/step_288000.pt +3 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_2x8gpu_50ep_lr4e3_ema0p9999_elfopt_not5_bottleneck128_unfixed_norm_stateprobadd_selfcond_ce_fast_20260610_020108/step_297000.pt +3 -0
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/markdown_it/_compat.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/markdown_it/main.py
ADDED
|
@@ -0,0 +1,351 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from collections.abc import Callable, Generator, Iterable, Mapping, MutableMapping
|
| 4 |
+
from contextlib import contextmanager
|
| 5 |
+
from typing import Any, Literal, overload
|
| 6 |
+
|
| 7 |
+
from . import helpers, presets
|
| 8 |
+
from .common import normalize_url, utils
|
| 9 |
+
from .parser_block import ParserBlock
|
| 10 |
+
from .parser_core import ParserCore
|
| 11 |
+
from .parser_inline import ParserInline
|
| 12 |
+
from .renderer import RendererHTML, RendererProtocol
|
| 13 |
+
from .rules_core.state_core import StateCore
|
| 14 |
+
from .token import Token
|
| 15 |
+
from .utils import EnvType, OptionsDict, OptionsType, PresetType
|
| 16 |
+
|
| 17 |
+
try:
|
| 18 |
+
import linkify_it
|
| 19 |
+
except ModuleNotFoundError:
|
| 20 |
+
linkify_it = None
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
_PRESETS: dict[str, PresetType] = {
|
| 24 |
+
"default": presets.default.make(),
|
| 25 |
+
"js-default": presets.js_default.make(),
|
| 26 |
+
"zero": presets.zero.make(),
|
| 27 |
+
"commonmark": presets.commonmark.make(),
|
| 28 |
+
"gfm-like": presets.gfm_like.make(),
|
| 29 |
+
"gfm-like2": presets.gfm_like2.make(),
|
| 30 |
+
}
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class MarkdownIt:
|
| 34 |
+
def __init__(
|
| 35 |
+
self,
|
| 36 |
+
config: str | PresetType = "commonmark",
|
| 37 |
+
options_update: Mapping[str, Any] | None = None,
|
| 38 |
+
*,
|
| 39 |
+
renderer_cls: Callable[[MarkdownIt], RendererProtocol] = RendererHTML,
|
| 40 |
+
):
|
| 41 |
+
"""Main parser class
|
| 42 |
+
|
| 43 |
+
:param config: name of configuration to load or a pre-defined dictionary
|
| 44 |
+
:param options_update: dictionary that will be merged into ``config["options"]``
|
| 45 |
+
:param renderer_cls: the class to load as the renderer:
|
| 46 |
+
``self.renderer = renderer_cls(self)
|
| 47 |
+
"""
|
| 48 |
+
# add modules
|
| 49 |
+
self.utils = utils
|
| 50 |
+
self.helpers = helpers
|
| 51 |
+
|
| 52 |
+
# initialise classes
|
| 53 |
+
self.inline = ParserInline()
|
| 54 |
+
self.block = ParserBlock()
|
| 55 |
+
self.core = ParserCore()
|
| 56 |
+
self.renderer = renderer_cls(self)
|
| 57 |
+
self.linkify = linkify_it.LinkifyIt() if linkify_it else None
|
| 58 |
+
|
| 59 |
+
# set the configuration
|
| 60 |
+
if options_update and not isinstance(options_update, Mapping):
|
| 61 |
+
# catch signature change where renderer_cls was not used as a key-word
|
| 62 |
+
raise TypeError(
|
| 63 |
+
f"options_update should be a mapping: {options_update}"
|
| 64 |
+
"\n(Perhaps you intended this to be the renderer_cls?)"
|
| 65 |
+
)
|
| 66 |
+
self.configure(config, options_update=options_update)
|
| 67 |
+
|
| 68 |
+
def __repr__(self) -> str:
|
| 69 |
+
return f"{self.__class__.__module__}.{self.__class__.__name__}()"
|
| 70 |
+
|
| 71 |
+
@overload
|
| 72 |
+
def __getitem__(self, name: Literal["inline"]) -> ParserInline: ...
|
| 73 |
+
|
| 74 |
+
@overload
|
| 75 |
+
def __getitem__(self, name: Literal["block"]) -> ParserBlock: ...
|
| 76 |
+
|
| 77 |
+
@overload
|
| 78 |
+
def __getitem__(self, name: Literal["core"]) -> ParserCore: ...
|
| 79 |
+
|
| 80 |
+
@overload
|
| 81 |
+
def __getitem__(self, name: Literal["renderer"]) -> RendererProtocol: ...
|
| 82 |
+
|
| 83 |
+
@overload
|
| 84 |
+
def __getitem__(self, name: str) -> Any: ...
|
| 85 |
+
|
| 86 |
+
def __getitem__(self, name: str) -> Any:
|
| 87 |
+
return {
|
| 88 |
+
"inline": self.inline,
|
| 89 |
+
"block": self.block,
|
| 90 |
+
"core": self.core,
|
| 91 |
+
"renderer": self.renderer,
|
| 92 |
+
}[name]
|
| 93 |
+
|
| 94 |
+
def set(self, options: OptionsType) -> None:
|
| 95 |
+
"""Set parser options (in the same format as in constructor).
|
| 96 |
+
Probably, you will never need it, but you can change options after constructor call.
|
| 97 |
+
|
| 98 |
+
__Note:__ To achieve the best possible performance, don't modify a
|
| 99 |
+
`markdown-it` instance options on the fly. If you need multiple configurations
|
| 100 |
+
it's best to create multiple instances and initialize each with separate config.
|
| 101 |
+
"""
|
| 102 |
+
self.options = OptionsDict(options)
|
| 103 |
+
|
| 104 |
+
def configure(
|
| 105 |
+
self, presets: str | PresetType, options_update: Mapping[str, Any] | None = None
|
| 106 |
+
) -> MarkdownIt:
|
| 107 |
+
"""Batch load of all options and component settings.
|
| 108 |
+
This is an internal method, and you probably will not need it.
|
| 109 |
+
But if you will - see available presets and data structure
|
| 110 |
+
[here](https://github.com/markdown-it/markdown-it/tree/master/lib/presets)
|
| 111 |
+
|
| 112 |
+
We strongly recommend to use presets instead of direct config loads.
|
| 113 |
+
That will give better compatibility with next versions.
|
| 114 |
+
"""
|
| 115 |
+
if isinstance(presets, str):
|
| 116 |
+
if presets not in _PRESETS:
|
| 117 |
+
raise KeyError(f"Wrong `markdown-it` preset '{presets}', check name")
|
| 118 |
+
config = _PRESETS[presets]
|
| 119 |
+
else:
|
| 120 |
+
config = presets
|
| 121 |
+
|
| 122 |
+
if not config:
|
| 123 |
+
raise ValueError("Wrong `markdown-it` config, can't be empty")
|
| 124 |
+
|
| 125 |
+
options = config.get("options", {}) or {}
|
| 126 |
+
if options_update:
|
| 127 |
+
options = {**options, **options_update} # type: ignore
|
| 128 |
+
|
| 129 |
+
self.set(options)
|
| 130 |
+
|
| 131 |
+
if "components" in config:
|
| 132 |
+
for name, component in config["components"].items():
|
| 133 |
+
rules = component.get("rules", None)
|
| 134 |
+
if rules:
|
| 135 |
+
self[name].ruler.enableOnly(rules)
|
| 136 |
+
rules2 = component.get("rules2", None)
|
| 137 |
+
if rules2:
|
| 138 |
+
self[name].ruler2.enableOnly(rules2)
|
| 139 |
+
|
| 140 |
+
return self
|
| 141 |
+
|
| 142 |
+
def get_all_rules(self) -> dict[str, list[str]]:
|
| 143 |
+
"""Return the names of all active rules."""
|
| 144 |
+
rules = {
|
| 145 |
+
chain: self[chain].ruler.get_all_rules()
|
| 146 |
+
for chain in ["core", "block", "inline"]
|
| 147 |
+
}
|
| 148 |
+
rules["inline2"] = self.inline.ruler2.get_all_rules()
|
| 149 |
+
return rules
|
| 150 |
+
|
| 151 |
+
def get_active_rules(self) -> dict[str, list[str]]:
|
| 152 |
+
"""Return the names of all active rules."""
|
| 153 |
+
rules = {
|
| 154 |
+
chain: self[chain].ruler.get_active_rules()
|
| 155 |
+
for chain in ["core", "block", "inline"]
|
| 156 |
+
}
|
| 157 |
+
rules["inline2"] = self.inline.ruler2.get_active_rules()
|
| 158 |
+
return rules
|
| 159 |
+
|
| 160 |
+
def enable(
|
| 161 |
+
self, names: str | Iterable[str], ignoreInvalid: bool = False
|
| 162 |
+
) -> MarkdownIt:
|
| 163 |
+
"""Enable list or rules. (chainable)
|
| 164 |
+
|
| 165 |
+
:param names: rule name or list of rule names to enable.
|
| 166 |
+
:param ignoreInvalid: set `true` to ignore errors when rule not found.
|
| 167 |
+
|
| 168 |
+
It will automatically find appropriate components,
|
| 169 |
+
containing rules with given names. If rule not found, and `ignoreInvalid`
|
| 170 |
+
not set - throws exception.
|
| 171 |
+
|
| 172 |
+
Example::
|
| 173 |
+
|
| 174 |
+
md = MarkdownIt().enable(['sub', 'sup']).disable('smartquotes')
|
| 175 |
+
|
| 176 |
+
"""
|
| 177 |
+
result = []
|
| 178 |
+
|
| 179 |
+
if isinstance(names, str):
|
| 180 |
+
names = [names]
|
| 181 |
+
|
| 182 |
+
for chain in ["core", "block", "inline"]:
|
| 183 |
+
result.extend(self[chain].ruler.enable(names, True))
|
| 184 |
+
result.extend(self.inline.ruler2.enable(names, True))
|
| 185 |
+
|
| 186 |
+
missed = [name for name in names if name not in result]
|
| 187 |
+
if missed and not ignoreInvalid:
|
| 188 |
+
raise ValueError(f"MarkdownIt. Failed to enable unknown rule(s): {missed}")
|
| 189 |
+
|
| 190 |
+
return self
|
| 191 |
+
|
| 192 |
+
def disable(
|
| 193 |
+
self, names: str | Iterable[str], ignoreInvalid: bool = False
|
| 194 |
+
) -> MarkdownIt:
|
| 195 |
+
"""The same as [[MarkdownIt.enable]], but turn specified rules off. (chainable)
|
| 196 |
+
|
| 197 |
+
:param names: rule name or list of rule names to disable.
|
| 198 |
+
:param ignoreInvalid: set `true` to ignore errors when rule not found.
|
| 199 |
+
|
| 200 |
+
"""
|
| 201 |
+
result = []
|
| 202 |
+
|
| 203 |
+
if isinstance(names, str):
|
| 204 |
+
names = [names]
|
| 205 |
+
|
| 206 |
+
for chain in ["core", "block", "inline"]:
|
| 207 |
+
result.extend(self[chain].ruler.disable(names, True))
|
| 208 |
+
result.extend(self.inline.ruler2.disable(names, True))
|
| 209 |
+
|
| 210 |
+
missed = [name for name in names if name not in result]
|
| 211 |
+
if missed and not ignoreInvalid:
|
| 212 |
+
raise ValueError(f"MarkdownIt. Failed to disable unknown rule(s): {missed}")
|
| 213 |
+
return self
|
| 214 |
+
|
| 215 |
+
@contextmanager
|
| 216 |
+
def reset_rules(self) -> Generator[None, None, None]:
|
| 217 |
+
"""A context manager, that will reset the current enabled rules on exit."""
|
| 218 |
+
chain_rules = self.get_active_rules()
|
| 219 |
+
yield
|
| 220 |
+
for chain, rules in chain_rules.items():
|
| 221 |
+
if chain != "inline2":
|
| 222 |
+
self[chain].ruler.enableOnly(rules)
|
| 223 |
+
self.inline.ruler2.enableOnly(chain_rules["inline2"])
|
| 224 |
+
|
| 225 |
+
def add_render_rule(
|
| 226 |
+
self, name: str, function: Callable[..., Any], fmt: str = "html"
|
| 227 |
+
) -> None:
|
| 228 |
+
"""Add a rule for rendering a particular Token type.
|
| 229 |
+
|
| 230 |
+
Only applied when ``renderer.__output__ == fmt``
|
| 231 |
+
"""
|
| 232 |
+
if self.renderer.__output__ == fmt:
|
| 233 |
+
self.renderer.rules[name] = function.__get__(self.renderer) # type: ignore
|
| 234 |
+
|
| 235 |
+
def use(
|
| 236 |
+
self, plugin: Callable[..., None], *params: Any, **options: Any
|
| 237 |
+
) -> MarkdownIt:
|
| 238 |
+
"""Load specified plugin with given params into current parser instance. (chainable)
|
| 239 |
+
|
| 240 |
+
It's just a sugar to call `plugin(md, params)` with curring.
|
| 241 |
+
|
| 242 |
+
Example::
|
| 243 |
+
|
| 244 |
+
def func(tokens, idx):
|
| 245 |
+
tokens[idx].content = tokens[idx].content.replace('foo', 'bar')
|
| 246 |
+
md = MarkdownIt().use(plugin, 'foo_replace', 'text', func)
|
| 247 |
+
|
| 248 |
+
"""
|
| 249 |
+
plugin(self, *params, **options)
|
| 250 |
+
return self
|
| 251 |
+
|
| 252 |
+
def parse(self, src: str, env: EnvType | None = None) -> list[Token]:
|
| 253 |
+
"""Parse the source string to a token stream
|
| 254 |
+
|
| 255 |
+
:param src: source string
|
| 256 |
+
:param env: environment sandbox
|
| 257 |
+
|
| 258 |
+
Parse input string and return list of block tokens (special token type
|
| 259 |
+
"inline" will contain list of inline tokens).
|
| 260 |
+
|
| 261 |
+
`env` is used to pass data between "distributed" rules and return additional
|
| 262 |
+
metadata like reference info, needed for the renderer. It also can be used to
|
| 263 |
+
inject data in specific cases. Usually, you will be ok to pass `{}`,
|
| 264 |
+
and then pass updated object to renderer.
|
| 265 |
+
"""
|
| 266 |
+
env = {} if env is None else env
|
| 267 |
+
if not isinstance(env, MutableMapping):
|
| 268 |
+
raise TypeError(f"Input data should be a MutableMapping, not {type(env)}")
|
| 269 |
+
if not isinstance(src, str):
|
| 270 |
+
raise TypeError(f"Input data should be a string, not {type(src)}")
|
| 271 |
+
state = StateCore(src, self, env)
|
| 272 |
+
self.core.process(state)
|
| 273 |
+
return state.tokens
|
| 274 |
+
|
| 275 |
+
def render(self, src: str, env: EnvType | None = None) -> Any:
|
| 276 |
+
"""Render markdown string into html. It does all magic for you :).
|
| 277 |
+
|
| 278 |
+
:param src: source string
|
| 279 |
+
:param env: environment sandbox
|
| 280 |
+
:returns: The output of the loaded renderer
|
| 281 |
+
|
| 282 |
+
`env` can be used to inject additional metadata (`{}` by default).
|
| 283 |
+
But you will not need it with high probability. See also comment
|
| 284 |
+
in [[MarkdownIt.parse]].
|
| 285 |
+
"""
|
| 286 |
+
env = {} if env is None else env
|
| 287 |
+
return self.renderer.render(self.parse(src, env), self.options, env)
|
| 288 |
+
|
| 289 |
+
def parseInline(self, src: str, env: EnvType | None = None) -> list[Token]:
|
| 290 |
+
"""The same as [[MarkdownIt.parse]] but skip all block rules.
|
| 291 |
+
|
| 292 |
+
:param src: source string
|
| 293 |
+
:param env: environment sandbox
|
| 294 |
+
|
| 295 |
+
It returns the
|
| 296 |
+
block tokens list with the single `inline` element, containing parsed inline
|
| 297 |
+
tokens in `children` property. Also updates `env` object.
|
| 298 |
+
"""
|
| 299 |
+
env = {} if env is None else env
|
| 300 |
+
if not isinstance(env, MutableMapping):
|
| 301 |
+
raise TypeError(f"Input data should be an MutableMapping, not {type(env)}")
|
| 302 |
+
if not isinstance(src, str):
|
| 303 |
+
raise TypeError(f"Input data should be a string, not {type(src)}")
|
| 304 |
+
state = StateCore(src, self, env)
|
| 305 |
+
state.inlineMode = True
|
| 306 |
+
self.core.process(state)
|
| 307 |
+
return state.tokens
|
| 308 |
+
|
| 309 |
+
def renderInline(self, src: str, env: EnvType | None = None) -> Any:
|
| 310 |
+
"""Similar to [[MarkdownIt.render]] but for single paragraph content.
|
| 311 |
+
|
| 312 |
+
:param src: source string
|
| 313 |
+
:param env: environment sandbox
|
| 314 |
+
|
| 315 |
+
Similar to [[MarkdownIt.render]] but for single paragraph content. Result
|
| 316 |
+
will NOT be wrapped into `<p>` tags.
|
| 317 |
+
"""
|
| 318 |
+
env = {} if env is None else env
|
| 319 |
+
return self.renderer.render(self.parseInline(src, env), self.options, env)
|
| 320 |
+
|
| 321 |
+
# link methods
|
| 322 |
+
|
| 323 |
+
def validateLink(self, url: str) -> bool:
|
| 324 |
+
"""Validate if the URL link is allowed in output.
|
| 325 |
+
|
| 326 |
+
This validator can prohibit more than really needed to prevent XSS.
|
| 327 |
+
It's a tradeoff to keep code simple and to be secure by default.
|
| 328 |
+
|
| 329 |
+
Note: the url should be normalized at this point, and existing entities decoded.
|
| 330 |
+
"""
|
| 331 |
+
return normalize_url.validateLink(url)
|
| 332 |
+
|
| 333 |
+
def normalizeLink(self, url: str) -> str:
|
| 334 |
+
"""Normalize destination URLs in links
|
| 335 |
+
|
| 336 |
+
::
|
| 337 |
+
|
| 338 |
+
[label]: destination 'title'
|
| 339 |
+
^^^^^^^^^^^
|
| 340 |
+
"""
|
| 341 |
+
return normalize_url.normalizeLink(url)
|
| 342 |
+
|
| 343 |
+
def normalizeLinkText(self, link: str) -> str:
|
| 344 |
+
"""Normalize autolink content
|
| 345 |
+
|
| 346 |
+
::
|
| 347 |
+
|
| 348 |
+
<destination>
|
| 349 |
+
~~~~~~~~~~~
|
| 350 |
+
"""
|
| 351 |
+
return normalize_url.normalizeLinkText(link)
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/markdown_it/parser_block.py
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Block-level tokenizer."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from collections.abc import Callable
|
| 6 |
+
import logging
|
| 7 |
+
from typing import TYPE_CHECKING
|
| 8 |
+
|
| 9 |
+
from . import rules_block
|
| 10 |
+
from .ruler import Ruler
|
| 11 |
+
from .rules_block.state_block import StateBlock
|
| 12 |
+
from .token import Token
|
| 13 |
+
from .utils import EnvType
|
| 14 |
+
|
| 15 |
+
if TYPE_CHECKING:
|
| 16 |
+
from markdown_it import MarkdownIt
|
| 17 |
+
|
| 18 |
+
LOGGER = logging.getLogger(__name__)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
RuleFuncBlockType = Callable[[StateBlock, int, int, bool], bool]
|
| 22 |
+
"""(state: StateBlock, startLine: int, endLine: int, silent: bool) -> matched: bool)
|
| 23 |
+
|
| 24 |
+
`silent` disables token generation, useful for lookahead.
|
| 25 |
+
"""
|
| 26 |
+
|
| 27 |
+
_rules: list[tuple[str, RuleFuncBlockType, list[str]]] = [
|
| 28 |
+
# First 2 params - rule name & source. Secondary array - list of rules,
|
| 29 |
+
# which can be terminated by this one.
|
| 30 |
+
("table", rules_block.table, ["paragraph", "reference"]),
|
| 31 |
+
("code", rules_block.code, []),
|
| 32 |
+
("fence", rules_block.fence, ["paragraph", "reference", "blockquote", "list"]),
|
| 33 |
+
(
|
| 34 |
+
"blockquote",
|
| 35 |
+
rules_block.blockquote,
|
| 36 |
+
["paragraph", "reference", "blockquote", "list"],
|
| 37 |
+
),
|
| 38 |
+
("hr", rules_block.hr, ["paragraph", "reference", "blockquote", "list"]),
|
| 39 |
+
("list", rules_block.list_block, ["paragraph", "reference", "blockquote"]),
|
| 40 |
+
("reference", rules_block.reference, []),
|
| 41 |
+
("html_block", rules_block.html_block, ["paragraph", "reference", "blockquote"]),
|
| 42 |
+
("heading", rules_block.heading, ["paragraph", "reference", "blockquote"]),
|
| 43 |
+
("lheading", rules_block.lheading, []),
|
| 44 |
+
("paragraph", rules_block.paragraph, []),
|
| 45 |
+
]
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
class ParserBlock:
|
| 49 |
+
"""
|
| 50 |
+
ParserBlock#ruler -> Ruler
|
| 51 |
+
|
| 52 |
+
[[Ruler]] instance. Keep configuration of block rules.
|
| 53 |
+
"""
|
| 54 |
+
|
| 55 |
+
def __init__(self) -> None:
|
| 56 |
+
self.ruler = Ruler[RuleFuncBlockType]()
|
| 57 |
+
for name, rule, alt in _rules:
|
| 58 |
+
self.ruler.push(name, rule, {"alt": alt})
|
| 59 |
+
|
| 60 |
+
def tokenize(self, state: StateBlock, startLine: int, endLine: int) -> None:
|
| 61 |
+
"""Generate tokens for input range."""
|
| 62 |
+
rules = self.ruler.getRules("")
|
| 63 |
+
line = startLine
|
| 64 |
+
maxNesting = state.md.options.maxNesting
|
| 65 |
+
hasEmptyLines = False
|
| 66 |
+
|
| 67 |
+
while line < endLine:
|
| 68 |
+
state.line = line = state.skipEmptyLines(line)
|
| 69 |
+
if line >= endLine:
|
| 70 |
+
break
|
| 71 |
+
if state.sCount[line] < state.blkIndent:
|
| 72 |
+
# Termination condition for nested calls.
|
| 73 |
+
# Nested calls currently used for blockquotes & lists
|
| 74 |
+
break
|
| 75 |
+
if state.level >= maxNesting:
|
| 76 |
+
# If nesting level exceeded - skip tail to the end.
|
| 77 |
+
# That's not ordinary situation and we should not care about content.
|
| 78 |
+
state.line = endLine
|
| 79 |
+
break
|
| 80 |
+
|
| 81 |
+
# Try all possible rules.
|
| 82 |
+
# On success, rule should:
|
| 83 |
+
# - update `state.line`
|
| 84 |
+
# - update `state.tokens`
|
| 85 |
+
# - return True
|
| 86 |
+
for rule in rules:
|
| 87 |
+
if rule(state, line, endLine, False):
|
| 88 |
+
break
|
| 89 |
+
|
| 90 |
+
# set state.tight if we had an empty line before current tag
|
| 91 |
+
# i.e. latest empty line should not count
|
| 92 |
+
state.tight = not hasEmptyLines
|
| 93 |
+
|
| 94 |
+
line = state.line
|
| 95 |
+
|
| 96 |
+
# paragraph might "eat" one newline after it in nested lists
|
| 97 |
+
if (line - 1) < endLine and state.isEmpty(line - 1):
|
| 98 |
+
hasEmptyLines = True
|
| 99 |
+
|
| 100 |
+
if line < endLine and state.isEmpty(line):
|
| 101 |
+
hasEmptyLines = True
|
| 102 |
+
line += 1
|
| 103 |
+
state.line = line
|
| 104 |
+
|
| 105 |
+
def parse(
|
| 106 |
+
self, src: str, md: MarkdownIt, env: EnvType, outTokens: list[Token]
|
| 107 |
+
) -> list[Token] | None:
|
| 108 |
+
"""Process input string and push block tokens into `outTokens`."""
|
| 109 |
+
if not src:
|
| 110 |
+
return None
|
| 111 |
+
state = StateBlock(src, md, env, outTokens)
|
| 112 |
+
self.tokenize(state, state.line, state.lineMax)
|
| 113 |
+
return state.tokens
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/markdown_it/parser_core.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
* class Core
|
| 3 |
+
*
|
| 4 |
+
* Top-level rules executor. Glues block/inline parsers and does intermediate
|
| 5 |
+
* transformations.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
from collections.abc import Callable
|
| 11 |
+
|
| 12 |
+
from .ruler import Ruler
|
| 13 |
+
from .rules_core import (
|
| 14 |
+
block,
|
| 15 |
+
inline,
|
| 16 |
+
linkify,
|
| 17 |
+
normalize,
|
| 18 |
+
replace,
|
| 19 |
+
smartquotes,
|
| 20 |
+
text_join,
|
| 21 |
+
)
|
| 22 |
+
from .rules_core.state_core import StateCore
|
| 23 |
+
|
| 24 |
+
RuleFuncCoreType = Callable[[StateCore], None]
|
| 25 |
+
|
| 26 |
+
_rules: list[tuple[str, RuleFuncCoreType]] = [
|
| 27 |
+
("normalize", normalize),
|
| 28 |
+
("block", block),
|
| 29 |
+
("inline", inline),
|
| 30 |
+
("linkify", linkify),
|
| 31 |
+
("replacements", replace),
|
| 32 |
+
("smartquotes", smartquotes),
|
| 33 |
+
("text_join", text_join),
|
| 34 |
+
]
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
class ParserCore:
|
| 38 |
+
def __init__(self) -> None:
|
| 39 |
+
self.ruler = Ruler[RuleFuncCoreType]()
|
| 40 |
+
for name, rule in _rules:
|
| 41 |
+
self.ruler.push(name, rule)
|
| 42 |
+
|
| 43 |
+
def process(self, state: StateCore) -> None:
|
| 44 |
+
"""Executes core chain rules."""
|
| 45 |
+
for rule in self.ruler.getRules(""):
|
| 46 |
+
rule(state)
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/markdown_it/parser_inline.py
ADDED
|
@@ -0,0 +1,215 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Tokenizes paragraph content."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from collections.abc import Callable
|
| 6 |
+
import functools
|
| 7 |
+
import re
|
| 8 |
+
from typing import TYPE_CHECKING
|
| 9 |
+
|
| 10 |
+
from . import rules_inline
|
| 11 |
+
from .ruler import Ruler
|
| 12 |
+
from .rules_inline.state_inline import StateInline
|
| 13 |
+
from .token import Token
|
| 14 |
+
from .utils import EnvType
|
| 15 |
+
|
| 16 |
+
if TYPE_CHECKING:
|
| 17 |
+
from markdown_it import MarkdownIt
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
# Default set of characters that terminate a text token and allow inline rules to fire.
|
| 21 |
+
# '{}$%@~+=:' reserved for extensions.
|
| 22 |
+
# Note: Don't confuse with "Markdown ASCII Punctuation" chars.
|
| 23 |
+
# http://spec.commonmark.org/0.15/#ascii-punctuation-character
|
| 24 |
+
_DEFAULT_TERMINATORS: frozenset[str] = frozenset(
|
| 25 |
+
{
|
| 26 |
+
"\n",
|
| 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 |
+
# Lazily compiled regex for the default terminator set. The @cache ensures it is
|
| 54 |
+
# compiled at most once (on first ParserInline instantiation) and shared across all
|
| 55 |
+
# instances that have not added extra chars, keeping __init__ cost near zero.
|
| 56 |
+
@functools.cache
|
| 57 |
+
def _default_terminator_re() -> re.Pattern[str]:
|
| 58 |
+
return re.compile("[" + re.escape("".join(_DEFAULT_TERMINATORS)) + "]")
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
# Parser rules
|
| 62 |
+
RuleFuncInlineType = Callable[[StateInline, bool], bool]
|
| 63 |
+
"""(state: StateInline, silent: bool) -> matched: bool)
|
| 64 |
+
|
| 65 |
+
`silent` disables token generation, useful for lookahead.
|
| 66 |
+
"""
|
| 67 |
+
_rules: list[tuple[str, RuleFuncInlineType]] = [
|
| 68 |
+
("text", rules_inline.text),
|
| 69 |
+
("linkify", rules_inline.linkify),
|
| 70 |
+
("newline", rules_inline.newline),
|
| 71 |
+
("escape", rules_inline.escape),
|
| 72 |
+
("backticks", rules_inline.backtick),
|
| 73 |
+
("strikethrough", rules_inline.strikethrough.tokenize),
|
| 74 |
+
("emphasis", rules_inline.emphasis.tokenize),
|
| 75 |
+
("link", rules_inline.link),
|
| 76 |
+
("image", rules_inline.image),
|
| 77 |
+
("autolink", rules_inline.autolink),
|
| 78 |
+
("html_inline", rules_inline.html_inline),
|
| 79 |
+
("entity", rules_inline.entity),
|
| 80 |
+
]
|
| 81 |
+
|
| 82 |
+
# Note `rule2` ruleset was created specifically for emphasis/strikethrough
|
| 83 |
+
# post-processing and may be changed in the future.
|
| 84 |
+
#
|
| 85 |
+
# Don't use this for anything except pairs (plugins working with `balance_pairs`).
|
| 86 |
+
#
|
| 87 |
+
RuleFuncInline2Type = Callable[[StateInline], None]
|
| 88 |
+
_rules2: list[tuple[str, RuleFuncInline2Type]] = [
|
| 89 |
+
("balance_pairs", rules_inline.link_pairs),
|
| 90 |
+
("strikethrough", rules_inline.strikethrough.postProcess),
|
| 91 |
+
("emphasis", rules_inline.emphasis.postProcess),
|
| 92 |
+
# rules for pairs separate '**' into its own text tokens, which may be left unused,
|
| 93 |
+
# rule below merges unused segments back with the rest of the text
|
| 94 |
+
("fragments_join", rules_inline.fragments_join),
|
| 95 |
+
]
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
class ParserInline:
|
| 99 |
+
def __init__(self) -> None:
|
| 100 |
+
self.ruler = Ruler[RuleFuncInlineType]()
|
| 101 |
+
for name, rule in _rules:
|
| 102 |
+
self.ruler.push(name, rule)
|
| 103 |
+
# Second ruler used for post-processing (e.g. in emphasis-like rules)
|
| 104 |
+
self.ruler2 = Ruler[RuleFuncInline2Type]()
|
| 105 |
+
for name, rule2 in _rules2:
|
| 106 |
+
self.ruler2.push(name, rule2)
|
| 107 |
+
# Characters that stop the text rule, allowing other inline rules to fire.
|
| 108 |
+
# _extra_terminator_chars is only allocated when add_terminator_char() is called
|
| 109 |
+
# with a char outside the defaults, keeping __init__ allocation-free.
|
| 110 |
+
self._extra_terminator_chars: set[str] = set()
|
| 111 |
+
# Pre-compiled regex shared with all default instances (no copy in the common path).
|
| 112 |
+
self.terminator_re: re.Pattern[str] = _default_terminator_re()
|
| 113 |
+
|
| 114 |
+
def add_terminator_char(self, ch: str) -> None:
|
| 115 |
+
"""Register a character that stops the ``text`` rule, allowing inline rules to fire.
|
| 116 |
+
|
| 117 |
+
This lets plugins declare which characters their inline rules react to,
|
| 118 |
+
mirroring the ``MARKER`` mechanism in the Rust markdown-it implementation.
|
| 119 |
+
|
| 120 |
+
:param ch: A single character to add to the terminator set.
|
| 121 |
+
"""
|
| 122 |
+
if ch not in _DEFAULT_TERMINATORS and ch not in self._extra_terminator_chars:
|
| 123 |
+
self._extra_terminator_chars.add(ch)
|
| 124 |
+
self.terminator_re = re.compile(
|
| 125 |
+
"["
|
| 126 |
+
+ re.escape(
|
| 127 |
+
"".join(_DEFAULT_TERMINATORS | self._extra_terminator_chars)
|
| 128 |
+
)
|
| 129 |
+
+ "]"
|
| 130 |
+
)
|
| 131 |
+
|
| 132 |
+
def skipToken(self, state: StateInline) -> None:
|
| 133 |
+
"""Skip single token by running all rules in validation mode;
|
| 134 |
+
returns `True` if any rule reported success
|
| 135 |
+
"""
|
| 136 |
+
ok = False
|
| 137 |
+
pos = state.pos
|
| 138 |
+
rules = self.ruler.getRules("")
|
| 139 |
+
maxNesting = state.md.options["maxNesting"]
|
| 140 |
+
cache = state.cache
|
| 141 |
+
|
| 142 |
+
if pos in cache:
|
| 143 |
+
state.pos = cache[pos]
|
| 144 |
+
return
|
| 145 |
+
|
| 146 |
+
if state.level < maxNesting:
|
| 147 |
+
for rule in rules:
|
| 148 |
+
# Increment state.level and decrement it later to limit recursion.
|
| 149 |
+
# It's harmless to do here, because no tokens are created.
|
| 150 |
+
# But ideally, we'd need a separate private state variable for this purpose.
|
| 151 |
+
state.level += 1
|
| 152 |
+
ok = rule(state, True)
|
| 153 |
+
state.level -= 1
|
| 154 |
+
if ok:
|
| 155 |
+
break
|
| 156 |
+
else:
|
| 157 |
+
# Too much nesting, just skip until the end of the paragraph.
|
| 158 |
+
#
|
| 159 |
+
# NOTE: this will cause links to behave incorrectly in the following case,
|
| 160 |
+
# when an amount of `[` is exactly equal to `maxNesting + 1`:
|
| 161 |
+
#
|
| 162 |
+
# [[[[[[[[[[[[[[[[[[[[[foo]()
|
| 163 |
+
#
|
| 164 |
+
# TODO: remove this workaround when CM standard will allow nested links
|
| 165 |
+
# (we can replace it by preventing links from being parsed in
|
| 166 |
+
# validation mode)
|
| 167 |
+
#
|
| 168 |
+
state.pos = state.posMax
|
| 169 |
+
|
| 170 |
+
if not ok:
|
| 171 |
+
state.pos += 1
|
| 172 |
+
cache[pos] = state.pos
|
| 173 |
+
|
| 174 |
+
def tokenize(self, state: StateInline) -> None:
|
| 175 |
+
"""Generate tokens for input range."""
|
| 176 |
+
ok = False
|
| 177 |
+
rules = self.ruler.getRules("")
|
| 178 |
+
end = state.posMax
|
| 179 |
+
maxNesting = state.md.options["maxNesting"]
|
| 180 |
+
|
| 181 |
+
while state.pos < end:
|
| 182 |
+
# Try all possible rules.
|
| 183 |
+
# On success, rule should:
|
| 184 |
+
#
|
| 185 |
+
# - update `state.pos`
|
| 186 |
+
# - update `state.tokens`
|
| 187 |
+
# - return true
|
| 188 |
+
|
| 189 |
+
if state.level < maxNesting:
|
| 190 |
+
for rule in rules:
|
| 191 |
+
ok = rule(state, False)
|
| 192 |
+
if ok:
|
| 193 |
+
break
|
| 194 |
+
|
| 195 |
+
if ok:
|
| 196 |
+
if state.pos >= end:
|
| 197 |
+
break
|
| 198 |
+
continue
|
| 199 |
+
|
| 200 |
+
state.pending += state.src[state.pos]
|
| 201 |
+
state.pos += 1
|
| 202 |
+
|
| 203 |
+
if state.pending:
|
| 204 |
+
state.pushPending()
|
| 205 |
+
|
| 206 |
+
def parse(
|
| 207 |
+
self, src: str, md: MarkdownIt, env: EnvType, tokens: list[Token]
|
| 208 |
+
) -> list[Token]:
|
| 209 |
+
"""Process input string and push inline tokens into `tokens`"""
|
| 210 |
+
state = StateInline(src, md, env, tokens)
|
| 211 |
+
self.tokenize(state)
|
| 212 |
+
rules2 = self.ruler2.getRules("")
|
| 213 |
+
for rule in rules2:
|
| 214 |
+
rule(state)
|
| 215 |
+
return state.tokens
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/markdown_it/py.typed
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
# Marker file for PEP 561
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/markdown_it/renderer.py
ADDED
|
@@ -0,0 +1,356 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
class Renderer
|
| 3 |
+
|
| 4 |
+
Generates HTML from parsed token stream. Each instance has independent
|
| 5 |
+
copy of rules. Those can be rewritten with ease. Also, you can add new
|
| 6 |
+
rules if you create plugin and adds new token types.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
from collections.abc import Sequence
|
| 12 |
+
import inspect
|
| 13 |
+
from typing import Any, ClassVar, Protocol
|
| 14 |
+
|
| 15 |
+
from .common.utils import escapeHtml, unescapeAll
|
| 16 |
+
from .token import Token
|
| 17 |
+
from .utils import EnvType, OptionsDict
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class RendererProtocol(Protocol):
|
| 21 |
+
__output__: ClassVar[str]
|
| 22 |
+
|
| 23 |
+
def render(
|
| 24 |
+
self, tokens: Sequence[Token], options: OptionsDict, env: EnvType
|
| 25 |
+
) -> Any: ...
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class RendererHTML(RendererProtocol):
|
| 29 |
+
"""Contains render rules for tokens. Can be updated and extended.
|
| 30 |
+
|
| 31 |
+
Example:
|
| 32 |
+
|
| 33 |
+
Each rule is called as independent static function with fixed signature:
|
| 34 |
+
|
| 35 |
+
::
|
| 36 |
+
|
| 37 |
+
class Renderer:
|
| 38 |
+
def token_type_name(self, tokens, idx, options, env) {
|
| 39 |
+
# ...
|
| 40 |
+
return renderedHTML
|
| 41 |
+
|
| 42 |
+
::
|
| 43 |
+
|
| 44 |
+
class CustomRenderer(RendererHTML):
|
| 45 |
+
def strong_open(self, tokens, idx, options, env):
|
| 46 |
+
return '<b>'
|
| 47 |
+
def strong_close(self, tokens, idx, options, env):
|
| 48 |
+
return '</b>'
|
| 49 |
+
|
| 50 |
+
md = MarkdownIt(renderer_cls=CustomRenderer)
|
| 51 |
+
|
| 52 |
+
result = md.render(...)
|
| 53 |
+
|
| 54 |
+
See https://github.com/markdown-it/markdown-it/blob/master/lib/renderer.js
|
| 55 |
+
for more details and examples.
|
| 56 |
+
"""
|
| 57 |
+
|
| 58 |
+
__output__ = "html"
|
| 59 |
+
|
| 60 |
+
def __init__(self, parser: Any = None):
|
| 61 |
+
self.rules = {
|
| 62 |
+
k: v
|
| 63 |
+
for k, v in inspect.getmembers(self, predicate=inspect.ismethod)
|
| 64 |
+
if not (k.startswith("render") or k.startswith("_"))
|
| 65 |
+
}
|
| 66 |
+
|
| 67 |
+
def render(
|
| 68 |
+
self, tokens: Sequence[Token], options: OptionsDict, env: EnvType
|
| 69 |
+
) -> str:
|
| 70 |
+
"""Takes token stream and generates HTML.
|
| 71 |
+
|
| 72 |
+
:param tokens: list on block tokens to render
|
| 73 |
+
:param options: params of parser instance
|
| 74 |
+
:param env: additional data from parsed input
|
| 75 |
+
|
| 76 |
+
"""
|
| 77 |
+
result = ""
|
| 78 |
+
|
| 79 |
+
for i, token in enumerate(tokens):
|
| 80 |
+
if token.type == "inline":
|
| 81 |
+
if token.children:
|
| 82 |
+
result += self.renderInline(token.children, options, env)
|
| 83 |
+
elif token.type in self.rules:
|
| 84 |
+
result += self.rules[token.type](tokens, i, options, env)
|
| 85 |
+
else:
|
| 86 |
+
result += self.renderToken(tokens, i, options, env)
|
| 87 |
+
|
| 88 |
+
return result
|
| 89 |
+
|
| 90 |
+
def renderInline(
|
| 91 |
+
self, tokens: Sequence[Token], options: OptionsDict, env: EnvType
|
| 92 |
+
) -> str:
|
| 93 |
+
"""The same as ``render``, but for single token of `inline` type.
|
| 94 |
+
|
| 95 |
+
:param tokens: list on block tokens to render
|
| 96 |
+
:param options: params of parser instance
|
| 97 |
+
:param env: additional data from parsed input (references, for example)
|
| 98 |
+
"""
|
| 99 |
+
result = ""
|
| 100 |
+
|
| 101 |
+
for i, token in enumerate(tokens):
|
| 102 |
+
if token.type in self.rules:
|
| 103 |
+
result += self.rules[token.type](tokens, i, options, env)
|
| 104 |
+
else:
|
| 105 |
+
result += self.renderToken(tokens, i, options, env)
|
| 106 |
+
|
| 107 |
+
return result
|
| 108 |
+
|
| 109 |
+
def renderToken(
|
| 110 |
+
self,
|
| 111 |
+
tokens: Sequence[Token],
|
| 112 |
+
idx: int,
|
| 113 |
+
options: OptionsDict,
|
| 114 |
+
env: EnvType,
|
| 115 |
+
) -> str:
|
| 116 |
+
"""Default token renderer.
|
| 117 |
+
|
| 118 |
+
Can be overridden by custom function
|
| 119 |
+
|
| 120 |
+
:param idx: token index to render
|
| 121 |
+
:param options: params of parser instance
|
| 122 |
+
"""
|
| 123 |
+
result = ""
|
| 124 |
+
needLf = False
|
| 125 |
+
token = tokens[idx]
|
| 126 |
+
|
| 127 |
+
# Tight list paragraphs
|
| 128 |
+
if token.hidden:
|
| 129 |
+
return ""
|
| 130 |
+
|
| 131 |
+
# Insert a newline between hidden paragraph and subsequent opening
|
| 132 |
+
# block-level tag.
|
| 133 |
+
#
|
| 134 |
+
# For example, here we should insert a newline before blockquote:
|
| 135 |
+
# - a
|
| 136 |
+
# >
|
| 137 |
+
#
|
| 138 |
+
if token.block and token.nesting != -1 and idx and tokens[idx - 1].hidden:
|
| 139 |
+
result += "\n"
|
| 140 |
+
|
| 141 |
+
# Add token name, e.g. `<img`
|
| 142 |
+
result += ("</" if token.nesting == -1 else "<") + token.tag
|
| 143 |
+
|
| 144 |
+
# Encode attributes, e.g. `<img src="foo"`
|
| 145 |
+
result += self.renderAttrs(token)
|
| 146 |
+
|
| 147 |
+
# Add a slash for self-closing tags, e.g. `<img src="foo" /`
|
| 148 |
+
if token.nesting == 0 and options["xhtmlOut"]:
|
| 149 |
+
result += " /"
|
| 150 |
+
|
| 151 |
+
# Check if we need to add a newline after this tag
|
| 152 |
+
if token.block:
|
| 153 |
+
needLf = True
|
| 154 |
+
|
| 155 |
+
if token.nesting == 1 and (idx + 1 < len(tokens)):
|
| 156 |
+
nextToken = tokens[idx + 1]
|
| 157 |
+
|
| 158 |
+
if nextToken.type == "inline" or nextToken.hidden:
|
| 159 |
+
# Block-level tag containing an inline tag.
|
| 160 |
+
#
|
| 161 |
+
needLf = False
|
| 162 |
+
|
| 163 |
+
elif nextToken.nesting == -1 and nextToken.tag == token.tag:
|
| 164 |
+
# Opening tag + closing tag of the same type. E.g. `<li></li>`.
|
| 165 |
+
#
|
| 166 |
+
needLf = False
|
| 167 |
+
|
| 168 |
+
result += ">\n" if needLf else ">"
|
| 169 |
+
|
| 170 |
+
return result
|
| 171 |
+
|
| 172 |
+
@staticmethod
|
| 173 |
+
def renderAttrs(token: Token) -> str:
|
| 174 |
+
"""Render token attributes to string."""
|
| 175 |
+
result = ""
|
| 176 |
+
|
| 177 |
+
for key, value in token.attrItems():
|
| 178 |
+
result += " " + escapeHtml(key) + '="' + escapeHtml(str(value)) + '"'
|
| 179 |
+
|
| 180 |
+
return result
|
| 181 |
+
|
| 182 |
+
def renderInlineAsText(
|
| 183 |
+
self,
|
| 184 |
+
tokens: Sequence[Token] | None,
|
| 185 |
+
options: OptionsDict,
|
| 186 |
+
env: EnvType,
|
| 187 |
+
) -> str:
|
| 188 |
+
"""Special kludge for image `alt` attributes to conform CommonMark spec.
|
| 189 |
+
|
| 190 |
+
Don't try to use it! Spec requires to show `alt` content with stripped markup,
|
| 191 |
+
instead of simple escaping.
|
| 192 |
+
|
| 193 |
+
:param tokens: list on block tokens to render
|
| 194 |
+
:param options: params of parser instance
|
| 195 |
+
:param env: additional data from parsed input
|
| 196 |
+
"""
|
| 197 |
+
result = ""
|
| 198 |
+
|
| 199 |
+
for token in tokens or []:
|
| 200 |
+
if token.type == "text":
|
| 201 |
+
result += token.content
|
| 202 |
+
elif token.type == "image":
|
| 203 |
+
if token.children:
|
| 204 |
+
result += self.renderInlineAsText(token.children, options, env)
|
| 205 |
+
elif token.type == "softbreak":
|
| 206 |
+
result += "\n"
|
| 207 |
+
|
| 208 |
+
return result
|
| 209 |
+
|
| 210 |
+
###################################################
|
| 211 |
+
|
| 212 |
+
def list_item_open(
|
| 213 |
+
self,
|
| 214 |
+
tokens: Sequence[Token],
|
| 215 |
+
idx: int,
|
| 216 |
+
options: OptionsDict,
|
| 217 |
+
env: EnvType,
|
| 218 |
+
) -> str:
|
| 219 |
+
token = tokens[idx]
|
| 220 |
+
result = self.renderToken(tokens, idx, options, env)
|
| 221 |
+
if token.meta and "checked" in token.meta:
|
| 222 |
+
checked_attr = ' checked=""' if token.meta["checked"] else ""
|
| 223 |
+
disabled_attr = (
|
| 224 |
+
"" if options.get("tasklists_editable", False) else ' disabled=""'
|
| 225 |
+
)
|
| 226 |
+
result += (
|
| 227 |
+
'<input class="task-list-item-checkbox"'
|
| 228 |
+
f'{disabled_attr} type="checkbox"{checked_attr}> '
|
| 229 |
+
)
|
| 230 |
+
return result
|
| 231 |
+
|
| 232 |
+
def code_inline(
|
| 233 |
+
self, tokens: Sequence[Token], idx: int, options: OptionsDict, env: EnvType
|
| 234 |
+
) -> str:
|
| 235 |
+
token = tokens[idx]
|
| 236 |
+
return (
|
| 237 |
+
"<code"
|
| 238 |
+
+ self.renderAttrs(token)
|
| 239 |
+
+ ">"
|
| 240 |
+
+ escapeHtml(tokens[idx].content)
|
| 241 |
+
+ "</code>"
|
| 242 |
+
)
|
| 243 |
+
|
| 244 |
+
def code_block(
|
| 245 |
+
self,
|
| 246 |
+
tokens: Sequence[Token],
|
| 247 |
+
idx: int,
|
| 248 |
+
options: OptionsDict,
|
| 249 |
+
env: EnvType,
|
| 250 |
+
) -> str:
|
| 251 |
+
token = tokens[idx]
|
| 252 |
+
|
| 253 |
+
return (
|
| 254 |
+
"<pre"
|
| 255 |
+
+ self.renderAttrs(token)
|
| 256 |
+
+ "><code>"
|
| 257 |
+
+ escapeHtml(tokens[idx].content)
|
| 258 |
+
+ "</code></pre>\n"
|
| 259 |
+
)
|
| 260 |
+
|
| 261 |
+
def fence(
|
| 262 |
+
self,
|
| 263 |
+
tokens: Sequence[Token],
|
| 264 |
+
idx: int,
|
| 265 |
+
options: OptionsDict,
|
| 266 |
+
env: EnvType,
|
| 267 |
+
) -> str:
|
| 268 |
+
token = tokens[idx]
|
| 269 |
+
info = unescapeAll(token.info).strip() if token.info else ""
|
| 270 |
+
langName = ""
|
| 271 |
+
langAttrs = ""
|
| 272 |
+
|
| 273 |
+
if info:
|
| 274 |
+
arr = info.split(maxsplit=1)
|
| 275 |
+
langName = arr[0]
|
| 276 |
+
if len(arr) == 2:
|
| 277 |
+
langAttrs = arr[1]
|
| 278 |
+
|
| 279 |
+
if options.highlight:
|
| 280 |
+
highlighted = options.highlight(
|
| 281 |
+
token.content, langName, langAttrs
|
| 282 |
+
) or escapeHtml(token.content)
|
| 283 |
+
else:
|
| 284 |
+
highlighted = escapeHtml(token.content)
|
| 285 |
+
|
| 286 |
+
if highlighted.startswith("<pre"):
|
| 287 |
+
return highlighted + "\n"
|
| 288 |
+
|
| 289 |
+
# If language exists, inject class gently, without modifying original token.
|
| 290 |
+
# May be, one day we will add .deepClone() for token and simplify this part, but
|
| 291 |
+
# now we prefer to keep things local.
|
| 292 |
+
if info:
|
| 293 |
+
# Fake token just to render attributes
|
| 294 |
+
tmpToken = Token(type="", tag="", nesting=0, attrs=token.attrs.copy())
|
| 295 |
+
tmpToken.attrJoin("class", options.langPrefix + langName)
|
| 296 |
+
|
| 297 |
+
return (
|
| 298 |
+
"<pre><code"
|
| 299 |
+
+ self.renderAttrs(tmpToken)
|
| 300 |
+
+ ">"
|
| 301 |
+
+ highlighted
|
| 302 |
+
+ "</code></pre>\n"
|
| 303 |
+
)
|
| 304 |
+
|
| 305 |
+
return (
|
| 306 |
+
"<pre><code"
|
| 307 |
+
+ self.renderAttrs(token)
|
| 308 |
+
+ ">"
|
| 309 |
+
+ highlighted
|
| 310 |
+
+ "</code></pre>\n"
|
| 311 |
+
)
|
| 312 |
+
|
| 313 |
+
def image(
|
| 314 |
+
self,
|
| 315 |
+
tokens: Sequence[Token],
|
| 316 |
+
idx: int,
|
| 317 |
+
options: OptionsDict,
|
| 318 |
+
env: EnvType,
|
| 319 |
+
) -> str:
|
| 320 |
+
token = tokens[idx]
|
| 321 |
+
|
| 322 |
+
# "alt" attr MUST be set, even if empty. Because it's mandatory and
|
| 323 |
+
# should be placed on proper position for tests.
|
| 324 |
+
if token.children:
|
| 325 |
+
token.attrSet("alt", self.renderInlineAsText(token.children, options, env))
|
| 326 |
+
else:
|
| 327 |
+
token.attrSet("alt", "")
|
| 328 |
+
|
| 329 |
+
return self.renderToken(tokens, idx, options, env)
|
| 330 |
+
|
| 331 |
+
def hardbreak(
|
| 332 |
+
self, tokens: Sequence[Token], idx: int, options: OptionsDict, env: EnvType
|
| 333 |
+
) -> str:
|
| 334 |
+
return "<br />\n" if options.xhtmlOut else "<br>\n"
|
| 335 |
+
|
| 336 |
+
def softbreak(
|
| 337 |
+
self, tokens: Sequence[Token], idx: int, options: OptionsDict, env: EnvType
|
| 338 |
+
) -> str:
|
| 339 |
+
return (
|
| 340 |
+
("<br />\n" if options.xhtmlOut else "<br>\n") if options.breaks else "\n"
|
| 341 |
+
)
|
| 342 |
+
|
| 343 |
+
def text(
|
| 344 |
+
self, tokens: Sequence[Token], idx: int, options: OptionsDict, env: EnvType
|
| 345 |
+
) -> str:
|
| 346 |
+
return escapeHtml(tokens[idx].content)
|
| 347 |
+
|
| 348 |
+
def html_block(
|
| 349 |
+
self, tokens: Sequence[Token], idx: int, options: OptionsDict, env: EnvType
|
| 350 |
+
) -> str:
|
| 351 |
+
return tokens[idx].content
|
| 352 |
+
|
| 353 |
+
def html_inline(
|
| 354 |
+
self, tokens: Sequence[Token], idx: int, options: OptionsDict, env: EnvType
|
| 355 |
+
) -> str:
|
| 356 |
+
return tokens[idx].content
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/markdown_it/ruler.py
ADDED
|
@@ -0,0 +1,275 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
class Ruler
|
| 3 |
+
|
| 4 |
+
Helper class, used by [[MarkdownIt#core]], [[MarkdownIt#block]] and
|
| 5 |
+
[[MarkdownIt#inline]] to manage sequences of functions (rules):
|
| 6 |
+
|
| 7 |
+
- keep rules in defined order
|
| 8 |
+
- assign the name to each rule
|
| 9 |
+
- enable/disable rules
|
| 10 |
+
- add/replace rules
|
| 11 |
+
- allow assign rules to additional named chains (in the same)
|
| 12 |
+
- caching lists of active rules
|
| 13 |
+
|
| 14 |
+
You will not need use this class directly until write plugins. For simple
|
| 15 |
+
rules control use [[MarkdownIt.disable]], [[MarkdownIt.enable]] and
|
| 16 |
+
[[MarkdownIt.use]].
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
from __future__ import annotations
|
| 20 |
+
|
| 21 |
+
from collections.abc import Iterable
|
| 22 |
+
from dataclasses import dataclass, field
|
| 23 |
+
from typing import TYPE_CHECKING, Generic, TypedDict, TypeVar
|
| 24 |
+
import warnings
|
| 25 |
+
|
| 26 |
+
from .utils import EnvType
|
| 27 |
+
|
| 28 |
+
if TYPE_CHECKING:
|
| 29 |
+
from markdown_it import MarkdownIt
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class StateBase:
|
| 33 |
+
def __init__(self, src: str, md: MarkdownIt, env: EnvType):
|
| 34 |
+
self.src = src
|
| 35 |
+
self.env = env
|
| 36 |
+
self.md = md
|
| 37 |
+
|
| 38 |
+
@property
|
| 39 |
+
def src(self) -> str:
|
| 40 |
+
return self._src
|
| 41 |
+
|
| 42 |
+
@src.setter
|
| 43 |
+
def src(self, value: str) -> None:
|
| 44 |
+
self._src = value
|
| 45 |
+
self._srcCharCode: tuple[int, ...] | None = None
|
| 46 |
+
|
| 47 |
+
@property
|
| 48 |
+
def srcCharCode(self) -> tuple[int, ...]:
|
| 49 |
+
warnings.warn(
|
| 50 |
+
"StateBase.srcCharCode is deprecated. Use StateBase.src instead.",
|
| 51 |
+
DeprecationWarning,
|
| 52 |
+
stacklevel=2,
|
| 53 |
+
)
|
| 54 |
+
if self._srcCharCode is None:
|
| 55 |
+
self._srcCharCode = tuple(ord(c) for c in self._src)
|
| 56 |
+
return self._srcCharCode
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
class RuleOptionsType(TypedDict, total=False):
|
| 60 |
+
alt: list[str]
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
RuleFuncTv = TypeVar("RuleFuncTv")
|
| 64 |
+
"""A rule function, whose signature is dependent on the state type."""
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
@dataclass(slots=True)
|
| 68 |
+
class Rule(Generic[RuleFuncTv]):
|
| 69 |
+
name: str
|
| 70 |
+
enabled: bool
|
| 71 |
+
fn: RuleFuncTv = field(repr=False)
|
| 72 |
+
alt: list[str]
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
class Ruler(Generic[RuleFuncTv]):
|
| 76 |
+
def __init__(self) -> None:
|
| 77 |
+
# List of added rules.
|
| 78 |
+
self.__rules__: list[Rule[RuleFuncTv]] = []
|
| 79 |
+
# Cached rule chains.
|
| 80 |
+
# First level - chain name, '' for default.
|
| 81 |
+
# Second level - diginal anchor for fast filtering by charcodes.
|
| 82 |
+
self.__cache__: dict[str, list[RuleFuncTv]] | None = None
|
| 83 |
+
|
| 84 |
+
def __find__(self, name: str) -> int:
|
| 85 |
+
"""Find rule index by name"""
|
| 86 |
+
for i, rule in enumerate(self.__rules__):
|
| 87 |
+
if rule.name == name:
|
| 88 |
+
return i
|
| 89 |
+
return -1
|
| 90 |
+
|
| 91 |
+
def __compile__(self) -> None:
|
| 92 |
+
"""Build rules lookup cache"""
|
| 93 |
+
chains = {""}
|
| 94 |
+
# collect unique names
|
| 95 |
+
for rule in self.__rules__:
|
| 96 |
+
if not rule.enabled:
|
| 97 |
+
continue
|
| 98 |
+
for name in rule.alt:
|
| 99 |
+
chains.add(name)
|
| 100 |
+
self.__cache__ = {}
|
| 101 |
+
for chain in chains:
|
| 102 |
+
self.__cache__[chain] = []
|
| 103 |
+
for rule in self.__rules__:
|
| 104 |
+
if not rule.enabled:
|
| 105 |
+
continue
|
| 106 |
+
if chain and (chain not in rule.alt):
|
| 107 |
+
continue
|
| 108 |
+
self.__cache__[chain].append(rule.fn)
|
| 109 |
+
|
| 110 |
+
def at(
|
| 111 |
+
self, ruleName: str, fn: RuleFuncTv, options: RuleOptionsType | None = None
|
| 112 |
+
) -> None:
|
| 113 |
+
"""Replace rule by name with new function & options.
|
| 114 |
+
|
| 115 |
+
:param ruleName: rule name to replace.
|
| 116 |
+
:param fn: new rule function.
|
| 117 |
+
:param options: new rule options (not mandatory).
|
| 118 |
+
:raises: KeyError if name not found
|
| 119 |
+
"""
|
| 120 |
+
index = self.__find__(ruleName)
|
| 121 |
+
options = options or {}
|
| 122 |
+
if index == -1:
|
| 123 |
+
raise KeyError(f"Parser rule not found: {ruleName}")
|
| 124 |
+
self.__rules__[index].fn = fn
|
| 125 |
+
self.__rules__[index].alt = options.get("alt", [])
|
| 126 |
+
self.__cache__ = None
|
| 127 |
+
|
| 128 |
+
def before(
|
| 129 |
+
self,
|
| 130 |
+
beforeName: str,
|
| 131 |
+
ruleName: str,
|
| 132 |
+
fn: RuleFuncTv,
|
| 133 |
+
options: RuleOptionsType | None = None,
|
| 134 |
+
) -> None:
|
| 135 |
+
"""Add new rule to chain before one with given name.
|
| 136 |
+
|
| 137 |
+
:param beforeName: new rule will be added before this one.
|
| 138 |
+
:param ruleName: new rule will be added before this one.
|
| 139 |
+
:param fn: new rule function.
|
| 140 |
+
:param options: new rule options (not mandatory).
|
| 141 |
+
:raises: KeyError if name not found
|
| 142 |
+
"""
|
| 143 |
+
index = self.__find__(beforeName)
|
| 144 |
+
options = options or {}
|
| 145 |
+
if index == -1:
|
| 146 |
+
raise KeyError(f"Parser rule not found: {beforeName}")
|
| 147 |
+
self.__rules__.insert(
|
| 148 |
+
index, Rule[RuleFuncTv](ruleName, True, fn, options.get("alt", []))
|
| 149 |
+
)
|
| 150 |
+
self.__cache__ = None
|
| 151 |
+
|
| 152 |
+
def after(
|
| 153 |
+
self,
|
| 154 |
+
afterName: str,
|
| 155 |
+
ruleName: str,
|
| 156 |
+
fn: RuleFuncTv,
|
| 157 |
+
options: RuleOptionsType | None = None,
|
| 158 |
+
) -> None:
|
| 159 |
+
"""Add new rule to chain after one with given name.
|
| 160 |
+
|
| 161 |
+
:param afterName: new rule will be added after this one.
|
| 162 |
+
:param ruleName: new rule will be added after this one.
|
| 163 |
+
:param fn: new rule function.
|
| 164 |
+
:param options: new rule options (not mandatory).
|
| 165 |
+
:raises: KeyError if name not found
|
| 166 |
+
"""
|
| 167 |
+
index = self.__find__(afterName)
|
| 168 |
+
options = options or {}
|
| 169 |
+
if index == -1:
|
| 170 |
+
raise KeyError(f"Parser rule not found: {afterName}")
|
| 171 |
+
self.__rules__.insert(
|
| 172 |
+
index + 1, Rule[RuleFuncTv](ruleName, True, fn, options.get("alt", []))
|
| 173 |
+
)
|
| 174 |
+
self.__cache__ = None
|
| 175 |
+
|
| 176 |
+
def push(
|
| 177 |
+
self, ruleName: str, fn: RuleFuncTv, options: RuleOptionsType | None = None
|
| 178 |
+
) -> None:
|
| 179 |
+
"""Push new rule to the end of chain.
|
| 180 |
+
|
| 181 |
+
:param ruleName: new rule will be added to the end of chain.
|
| 182 |
+
:param fn: new rule function.
|
| 183 |
+
:param options: new rule options (not mandatory).
|
| 184 |
+
|
| 185 |
+
"""
|
| 186 |
+
self.__rules__.append(
|
| 187 |
+
Rule[RuleFuncTv](ruleName, True, fn, (options or {}).get("alt", []))
|
| 188 |
+
)
|
| 189 |
+
self.__cache__ = None
|
| 190 |
+
|
| 191 |
+
def enable(
|
| 192 |
+
self, names: str | Iterable[str], ignoreInvalid: bool = False
|
| 193 |
+
) -> list[str]:
|
| 194 |
+
"""Enable rules with given names.
|
| 195 |
+
|
| 196 |
+
:param names: name or list of rule names to enable.
|
| 197 |
+
:param ignoreInvalid: ignore errors when rule not found
|
| 198 |
+
:raises: KeyError if name not found and not ignoreInvalid
|
| 199 |
+
:return: list of found rule names
|
| 200 |
+
"""
|
| 201 |
+
if isinstance(names, str):
|
| 202 |
+
names = [names]
|
| 203 |
+
result: list[str] = []
|
| 204 |
+
for name in names:
|
| 205 |
+
idx = self.__find__(name)
|
| 206 |
+
if (idx < 0) and ignoreInvalid:
|
| 207 |
+
continue
|
| 208 |
+
if (idx < 0) and not ignoreInvalid:
|
| 209 |
+
raise KeyError(f"Rules manager: invalid rule name {name}")
|
| 210 |
+
self.__rules__[idx].enabled = True
|
| 211 |
+
result.append(name)
|
| 212 |
+
self.__cache__ = None
|
| 213 |
+
return result
|
| 214 |
+
|
| 215 |
+
def enableOnly(
|
| 216 |
+
self, names: str | Iterable[str], ignoreInvalid: bool = False
|
| 217 |
+
) -> list[str]:
|
| 218 |
+
"""Enable rules with given names, and disable everything else.
|
| 219 |
+
|
| 220 |
+
:param names: name or list of rule names to enable.
|
| 221 |
+
:param ignoreInvalid: ignore errors when rule not found
|
| 222 |
+
:raises: KeyError if name not found and not ignoreInvalid
|
| 223 |
+
:return: list of found rule names
|
| 224 |
+
"""
|
| 225 |
+
if isinstance(names, str):
|
| 226 |
+
names = [names]
|
| 227 |
+
for rule in self.__rules__:
|
| 228 |
+
rule.enabled = False
|
| 229 |
+
return self.enable(names, ignoreInvalid)
|
| 230 |
+
|
| 231 |
+
def disable(
|
| 232 |
+
self, names: str | Iterable[str], ignoreInvalid: bool = False
|
| 233 |
+
) -> list[str]:
|
| 234 |
+
"""Disable rules with given names.
|
| 235 |
+
|
| 236 |
+
:param names: name or list of rule names to enable.
|
| 237 |
+
:param ignoreInvalid: ignore errors when rule not found
|
| 238 |
+
:raises: KeyError if name not found and not ignoreInvalid
|
| 239 |
+
:return: list of found rule names
|
| 240 |
+
"""
|
| 241 |
+
if isinstance(names, str):
|
| 242 |
+
names = [names]
|
| 243 |
+
result = []
|
| 244 |
+
for name in names:
|
| 245 |
+
idx = self.__find__(name)
|
| 246 |
+
if (idx < 0) and ignoreInvalid:
|
| 247 |
+
continue
|
| 248 |
+
if (idx < 0) and not ignoreInvalid:
|
| 249 |
+
raise KeyError(f"Rules manager: invalid rule name {name}")
|
| 250 |
+
self.__rules__[idx].enabled = False
|
| 251 |
+
result.append(name)
|
| 252 |
+
self.__cache__ = None
|
| 253 |
+
return result
|
| 254 |
+
|
| 255 |
+
def getRules(self, chainName: str = "") -> list[RuleFuncTv]:
|
| 256 |
+
"""Return array of active functions (rules) for given chain name.
|
| 257 |
+
It analyzes rules configuration, compiles caches if not exists and returns result.
|
| 258 |
+
|
| 259 |
+
Default chain name is `''` (empty string). It can't be skipped.
|
| 260 |
+
That's done intentionally, to keep signature monomorphic for high speed.
|
| 261 |
+
|
| 262 |
+
"""
|
| 263 |
+
if self.__cache__ is None:
|
| 264 |
+
self.__compile__()
|
| 265 |
+
assert self.__cache__ is not None
|
| 266 |
+
# Chain can be empty, if rules disabled. But we still have to return Array.
|
| 267 |
+
return self.__cache__.get(chainName, []) or []
|
| 268 |
+
|
| 269 |
+
def get_all_rules(self) -> list[str]:
|
| 270 |
+
"""Return all available rule names."""
|
| 271 |
+
return [r.name for r in self.__rules__]
|
| 272 |
+
|
| 273 |
+
def get_active_rules(self) -> list[str]:
|
| 274 |
+
"""Return the active rule names."""
|
| 275 |
+
return [r.name for r in self.__rules__ if r.enabled]
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/markdown_it/tree.py
ADDED
|
@@ -0,0 +1,333 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""A tree representation of a linear markdown-it token stream.
|
| 2 |
+
|
| 3 |
+
This module is not part of upstream JavaScript markdown-it.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
from __future__ import annotations
|
| 7 |
+
|
| 8 |
+
from collections.abc import Generator, Sequence
|
| 9 |
+
import textwrap
|
| 10 |
+
from typing import Any, NamedTuple, TypeVar, overload
|
| 11 |
+
|
| 12 |
+
from .token import Token
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class _NesterTokens(NamedTuple):
|
| 16 |
+
opening: Token
|
| 17 |
+
closing: Token
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
_NodeType = TypeVar("_NodeType", bound="SyntaxTreeNode")
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class SyntaxTreeNode:
|
| 24 |
+
"""A Markdown syntax tree node.
|
| 25 |
+
|
| 26 |
+
A class that can be used to construct a tree representation of a linear
|
| 27 |
+
`markdown-it-py` token stream.
|
| 28 |
+
|
| 29 |
+
Each node in the tree represents either:
|
| 30 |
+
- root of the Markdown document
|
| 31 |
+
- a single unnested `Token`
|
| 32 |
+
- a `Token` "_open" and "_close" token pair, and the tokens nested in
|
| 33 |
+
between
|
| 34 |
+
"""
|
| 35 |
+
|
| 36 |
+
def __init__(
|
| 37 |
+
self, tokens: Sequence[Token] = (), *, create_root: bool = True
|
| 38 |
+
) -> None:
|
| 39 |
+
"""Initialize a `SyntaxTreeNode` from a token stream.
|
| 40 |
+
|
| 41 |
+
If `create_root` is True, create a root node for the document.
|
| 42 |
+
"""
|
| 43 |
+
# Only nodes representing an unnested token have self.token
|
| 44 |
+
self.token: Token | None = None
|
| 45 |
+
|
| 46 |
+
# Only containers have nester tokens
|
| 47 |
+
self.nester_tokens: _NesterTokens | None = None
|
| 48 |
+
|
| 49 |
+
# Root node does not have self.parent
|
| 50 |
+
self._parent: Any = None
|
| 51 |
+
|
| 52 |
+
# Empty list unless a non-empty container, or unnested token that has
|
| 53 |
+
# children (i.e. inline or img)
|
| 54 |
+
self._children: list[Any] = []
|
| 55 |
+
|
| 56 |
+
if create_root:
|
| 57 |
+
self._set_children_from_tokens(tokens)
|
| 58 |
+
return
|
| 59 |
+
|
| 60 |
+
if not tokens:
|
| 61 |
+
raise ValueError(
|
| 62 |
+
"Can only create root from empty token sequence."
|
| 63 |
+
" Set `create_root=True`."
|
| 64 |
+
)
|
| 65 |
+
elif len(tokens) == 1:
|
| 66 |
+
inline_token = tokens[0]
|
| 67 |
+
if inline_token.nesting:
|
| 68 |
+
raise ValueError(
|
| 69 |
+
"Unequal nesting level at the start and end of token stream."
|
| 70 |
+
)
|
| 71 |
+
self.token = inline_token
|
| 72 |
+
if inline_token.children:
|
| 73 |
+
self._set_children_from_tokens(inline_token.children)
|
| 74 |
+
else:
|
| 75 |
+
self.nester_tokens = _NesterTokens(tokens[0], tokens[-1])
|
| 76 |
+
self._set_children_from_tokens(tokens[1:-1])
|
| 77 |
+
|
| 78 |
+
def __repr__(self) -> str:
|
| 79 |
+
return f"{type(self).__name__}({self.type})"
|
| 80 |
+
|
| 81 |
+
@overload
|
| 82 |
+
def __getitem__(self: _NodeType, item: int) -> _NodeType: ...
|
| 83 |
+
|
| 84 |
+
@overload
|
| 85 |
+
def __getitem__(self: _NodeType, item: slice) -> list[_NodeType]: ...
|
| 86 |
+
|
| 87 |
+
def __getitem__(self: _NodeType, item: int | slice) -> _NodeType | list[_NodeType]:
|
| 88 |
+
return self.children[item]
|
| 89 |
+
|
| 90 |
+
def to_tokens(self: _NodeType) -> list[Token]:
|
| 91 |
+
"""Recover the linear token stream."""
|
| 92 |
+
|
| 93 |
+
def recursive_collect_tokens(node: _NodeType, token_list: list[Token]) -> None:
|
| 94 |
+
if node.type == "root":
|
| 95 |
+
for child in node.children:
|
| 96 |
+
recursive_collect_tokens(child, token_list)
|
| 97 |
+
elif node.token:
|
| 98 |
+
token_list.append(node.token)
|
| 99 |
+
else:
|
| 100 |
+
assert node.nester_tokens
|
| 101 |
+
token_list.append(node.nester_tokens.opening)
|
| 102 |
+
for child in node.children:
|
| 103 |
+
recursive_collect_tokens(child, token_list)
|
| 104 |
+
token_list.append(node.nester_tokens.closing)
|
| 105 |
+
|
| 106 |
+
tokens: list[Token] = []
|
| 107 |
+
recursive_collect_tokens(self, tokens)
|
| 108 |
+
return tokens
|
| 109 |
+
|
| 110 |
+
@property
|
| 111 |
+
def children(self: _NodeType) -> list[_NodeType]:
|
| 112 |
+
return self._children
|
| 113 |
+
|
| 114 |
+
@children.setter
|
| 115 |
+
def children(self: _NodeType, value: list[_NodeType]) -> None:
|
| 116 |
+
self._children = value
|
| 117 |
+
|
| 118 |
+
@property
|
| 119 |
+
def parent(self: _NodeType) -> _NodeType | None:
|
| 120 |
+
return self._parent # type: ignore
|
| 121 |
+
|
| 122 |
+
@parent.setter
|
| 123 |
+
def parent(self: _NodeType, value: _NodeType | None) -> None:
|
| 124 |
+
self._parent = value
|
| 125 |
+
|
| 126 |
+
@property
|
| 127 |
+
def is_root(self) -> bool:
|
| 128 |
+
"""Is the node a special root node?"""
|
| 129 |
+
return not (self.token or self.nester_tokens)
|
| 130 |
+
|
| 131 |
+
@property
|
| 132 |
+
def is_nested(self) -> bool:
|
| 133 |
+
"""Is this node nested?.
|
| 134 |
+
|
| 135 |
+
Returns `True` if the node represents a `Token` pair and tokens in the
|
| 136 |
+
sequence between them, where `Token.nesting` of the first `Token` in
|
| 137 |
+
the pair is 1 and nesting of the other `Token` is -1.
|
| 138 |
+
"""
|
| 139 |
+
return bool(self.nester_tokens)
|
| 140 |
+
|
| 141 |
+
@property
|
| 142 |
+
def siblings(self: _NodeType) -> Sequence[_NodeType]:
|
| 143 |
+
"""Get siblings of the node.
|
| 144 |
+
|
| 145 |
+
Gets the whole group of siblings, including self.
|
| 146 |
+
"""
|
| 147 |
+
if not self.parent:
|
| 148 |
+
return [self]
|
| 149 |
+
return self.parent.children
|
| 150 |
+
|
| 151 |
+
@property
|
| 152 |
+
def type(self) -> str:
|
| 153 |
+
"""Get a string type of the represented syntax.
|
| 154 |
+
|
| 155 |
+
- "root" for root nodes
|
| 156 |
+
- `Token.type` if the node represents an unnested token
|
| 157 |
+
- `Token.type` of the opening token, with "_open" suffix stripped, if
|
| 158 |
+
the node represents a nester token pair
|
| 159 |
+
"""
|
| 160 |
+
if self.is_root:
|
| 161 |
+
return "root"
|
| 162 |
+
if self.token:
|
| 163 |
+
return self.token.type
|
| 164 |
+
assert self.nester_tokens
|
| 165 |
+
return self.nester_tokens.opening.type.removesuffix("_open")
|
| 166 |
+
|
| 167 |
+
@property
|
| 168 |
+
def next_sibling(self: _NodeType) -> _NodeType | None:
|
| 169 |
+
"""Get the next node in the sequence of siblings.
|
| 170 |
+
|
| 171 |
+
Returns `None` if this is the last sibling.
|
| 172 |
+
"""
|
| 173 |
+
self_index = self.siblings.index(self)
|
| 174 |
+
if self_index + 1 < len(self.siblings):
|
| 175 |
+
return self.siblings[self_index + 1]
|
| 176 |
+
return None
|
| 177 |
+
|
| 178 |
+
@property
|
| 179 |
+
def previous_sibling(self: _NodeType) -> _NodeType | None:
|
| 180 |
+
"""Get the previous node in the sequence of siblings.
|
| 181 |
+
|
| 182 |
+
Returns `None` if this is the first sibling.
|
| 183 |
+
"""
|
| 184 |
+
self_index = self.siblings.index(self)
|
| 185 |
+
if self_index - 1 >= 0:
|
| 186 |
+
return self.siblings[self_index - 1]
|
| 187 |
+
return None
|
| 188 |
+
|
| 189 |
+
def _add_child(
|
| 190 |
+
self,
|
| 191 |
+
tokens: Sequence[Token],
|
| 192 |
+
) -> None:
|
| 193 |
+
"""Make a child node for `self`."""
|
| 194 |
+
child = type(self)(tokens, create_root=False)
|
| 195 |
+
child.parent = self
|
| 196 |
+
self.children.append(child)
|
| 197 |
+
|
| 198 |
+
def _set_children_from_tokens(self, tokens: Sequence[Token]) -> None:
|
| 199 |
+
"""Convert the token stream to a tree structure and set the resulting
|
| 200 |
+
nodes as children of `self`."""
|
| 201 |
+
reversed_tokens = list(reversed(tokens))
|
| 202 |
+
while reversed_tokens:
|
| 203 |
+
token = reversed_tokens.pop()
|
| 204 |
+
|
| 205 |
+
if not token.nesting:
|
| 206 |
+
self._add_child([token])
|
| 207 |
+
continue
|
| 208 |
+
if token.nesting != 1:
|
| 209 |
+
raise ValueError("Invalid token nesting")
|
| 210 |
+
|
| 211 |
+
nested_tokens = [token]
|
| 212 |
+
nesting = 1
|
| 213 |
+
while reversed_tokens and nesting:
|
| 214 |
+
token = reversed_tokens.pop()
|
| 215 |
+
nested_tokens.append(token)
|
| 216 |
+
nesting += token.nesting
|
| 217 |
+
if nesting:
|
| 218 |
+
raise ValueError(f"unclosed tokens starting {nested_tokens[0]}")
|
| 219 |
+
|
| 220 |
+
self._add_child(nested_tokens)
|
| 221 |
+
|
| 222 |
+
def pretty(
|
| 223 |
+
self, *, indent: int = 2, show_text: bool = False, _current: int = 0
|
| 224 |
+
) -> str:
|
| 225 |
+
"""Create an XML style string of the tree."""
|
| 226 |
+
prefix = " " * _current
|
| 227 |
+
text = prefix + f"<{self.type}"
|
| 228 |
+
if not self.is_root and self.attrs:
|
| 229 |
+
text += " " + " ".join(f"{k}={v!r}" for k, v in self.attrs.items())
|
| 230 |
+
text += ">"
|
| 231 |
+
if (
|
| 232 |
+
show_text
|
| 233 |
+
and not self.is_root
|
| 234 |
+
and self.type in ("text", "text_special")
|
| 235 |
+
and self.content
|
| 236 |
+
):
|
| 237 |
+
text += "\n" + textwrap.indent(self.content, prefix + " " * indent)
|
| 238 |
+
for child in self.children:
|
| 239 |
+
text += "\n" + child.pretty(
|
| 240 |
+
indent=indent, show_text=show_text, _current=_current + indent
|
| 241 |
+
)
|
| 242 |
+
return text
|
| 243 |
+
|
| 244 |
+
def walk(
|
| 245 |
+
self: _NodeType, *, include_self: bool = True
|
| 246 |
+
) -> Generator[_NodeType, None, None]:
|
| 247 |
+
"""Recursively yield all descendant nodes in the tree starting at self.
|
| 248 |
+
|
| 249 |
+
The order mimics the order of the underlying linear token
|
| 250 |
+
stream (i.e. depth first).
|
| 251 |
+
"""
|
| 252 |
+
if include_self:
|
| 253 |
+
yield self
|
| 254 |
+
for child in self.children:
|
| 255 |
+
yield from child.walk(include_self=True)
|
| 256 |
+
|
| 257 |
+
# NOTE:
|
| 258 |
+
# The values of the properties defined below directly map to properties
|
| 259 |
+
# of the underlying `Token`s. A root node does not translate to a `Token`
|
| 260 |
+
# object, so calling these property getters on a root node will raise an
|
| 261 |
+
# `AttributeError`.
|
| 262 |
+
#
|
| 263 |
+
# There is no mapping for `Token.nesting` because the `is_nested` property
|
| 264 |
+
# provides that data, and can be called on any node type, including root.
|
| 265 |
+
|
| 266 |
+
def _attribute_token(self) -> Token:
|
| 267 |
+
"""Return the `Token` that is used as the data source for the
|
| 268 |
+
properties defined below."""
|
| 269 |
+
if self.token:
|
| 270 |
+
return self.token
|
| 271 |
+
if self.nester_tokens:
|
| 272 |
+
return self.nester_tokens.opening
|
| 273 |
+
raise AttributeError("Root node does not have the accessed attribute")
|
| 274 |
+
|
| 275 |
+
@property
|
| 276 |
+
def tag(self) -> str:
|
| 277 |
+
"""html tag name, e.g. \"p\""""
|
| 278 |
+
return self._attribute_token().tag
|
| 279 |
+
|
| 280 |
+
@property
|
| 281 |
+
def attrs(self) -> dict[str, str | int | float]:
|
| 282 |
+
"""Html attributes."""
|
| 283 |
+
return self._attribute_token().attrs
|
| 284 |
+
|
| 285 |
+
def attrGet(self, name: str) -> None | str | int | float:
|
| 286 |
+
"""Get the value of attribute `name`, or null if it does not exist."""
|
| 287 |
+
return self._attribute_token().attrGet(name)
|
| 288 |
+
|
| 289 |
+
@property
|
| 290 |
+
def map(self) -> tuple[int, int] | None:
|
| 291 |
+
"""Source map info. Format: `tuple[ line_begin, line_end ]`"""
|
| 292 |
+
map_ = self._attribute_token().map
|
| 293 |
+
if map_:
|
| 294 |
+
# Type ignore because `Token`s attribute types are not perfect
|
| 295 |
+
return tuple(map_) # type: ignore
|
| 296 |
+
return None
|
| 297 |
+
|
| 298 |
+
@property
|
| 299 |
+
def level(self) -> int:
|
| 300 |
+
"""nesting level, the same as `state.level`"""
|
| 301 |
+
return self._attribute_token().level
|
| 302 |
+
|
| 303 |
+
@property
|
| 304 |
+
def content(self) -> str:
|
| 305 |
+
"""In a case of self-closing tag (code, html, fence, etc.), it
|
| 306 |
+
has contents of this tag."""
|
| 307 |
+
return self._attribute_token().content
|
| 308 |
+
|
| 309 |
+
@property
|
| 310 |
+
def markup(self) -> str:
|
| 311 |
+
"""'*' or '_' for emphasis, fence string for fence, etc."""
|
| 312 |
+
return self._attribute_token().markup
|
| 313 |
+
|
| 314 |
+
@property
|
| 315 |
+
def info(self) -> str:
|
| 316 |
+
"""fence infostring"""
|
| 317 |
+
return self._attribute_token().info
|
| 318 |
+
|
| 319 |
+
@property
|
| 320 |
+
def meta(self) -> dict[Any, Any]:
|
| 321 |
+
"""A place for plugins to store an arbitrary data."""
|
| 322 |
+
return self._attribute_token().meta
|
| 323 |
+
|
| 324 |
+
@property
|
| 325 |
+
def block(self) -> bool:
|
| 326 |
+
"""True for block-level tokens, false for inline tokens."""
|
| 327 |
+
return self._attribute_token().block
|
| 328 |
+
|
| 329 |
+
@property
|
| 330 |
+
def hidden(self) -> bool:
|
| 331 |
+
"""If it's true, ignore this element when rendering.
|
| 332 |
+
Used for tight lists to hide paragraphs."""
|
| 333 |
+
return self._attribute_token().hidden
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/markdown_it/utils.py
ADDED
|
@@ -0,0 +1,194 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from collections.abc import Callable, Iterable, MutableMapping
|
| 4 |
+
from collections.abc import MutableMapping as MutableMappingABC
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
from typing import TYPE_CHECKING, Any, TypedDict, cast
|
| 7 |
+
|
| 8 |
+
if TYPE_CHECKING:
|
| 9 |
+
from typing_extensions import NotRequired
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
EnvType = MutableMapping[str, Any] # note: could use TypeAlias in python 3.10
|
| 13 |
+
"""Type for the environment sandbox used in parsing and rendering,
|
| 14 |
+
which stores mutable variables for use by plugins and rules.
|
| 15 |
+
"""
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class OptionsType(TypedDict):
|
| 19 |
+
"""Options for parsing."""
|
| 20 |
+
|
| 21 |
+
maxNesting: int
|
| 22 |
+
"""Internal protection, recursion limit."""
|
| 23 |
+
html: bool
|
| 24 |
+
"""Enable HTML tags in source."""
|
| 25 |
+
linkify: bool
|
| 26 |
+
"""Enable autoconversion of URL-like texts to links."""
|
| 27 |
+
typographer: bool
|
| 28 |
+
"""Enable smartquotes and replacements."""
|
| 29 |
+
quotes: str
|
| 30 |
+
"""Quote characters."""
|
| 31 |
+
xhtmlOut: bool
|
| 32 |
+
"""Use '/' to close single tags (<br />)."""
|
| 33 |
+
breaks: bool
|
| 34 |
+
"""Convert newlines in paragraphs into <br>."""
|
| 35 |
+
langPrefix: str
|
| 36 |
+
"""CSS language prefix for fenced blocks."""
|
| 37 |
+
highlight: Callable[[str, str, str], str] | None
|
| 38 |
+
"""Highlighter function: (content, lang, attrs) -> str."""
|
| 39 |
+
store_labels: NotRequired[bool]
|
| 40 |
+
"""Store link label in link/image token's metadata (under Token.meta['label']).
|
| 41 |
+
|
| 42 |
+
This is a Python only option, and is intended for the use of round-trip parsing.
|
| 43 |
+
"""
|
| 44 |
+
tasklists: NotRequired[bool]
|
| 45 |
+
"""Enable GFM task list checkbox detection in list items."""
|
| 46 |
+
alerts: NotRequired[bool]
|
| 47 |
+
"""Enable GitHub-style alert detection in blockquotes."""
|
| 48 |
+
tasklists_editable: NotRequired[bool]
|
| 49 |
+
"""When True, rendered task list checkboxes are interactive (no disabled attribute)."""
|
| 50 |
+
strikethrough_single_tilde: NotRequired[bool]
|
| 51 |
+
"""Allow single tilde ``~text~`` for strikethrough in addition to double."""
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
class PresetType(TypedDict):
|
| 55 |
+
"""Preset configuration for markdown-it."""
|
| 56 |
+
|
| 57 |
+
options: OptionsType
|
| 58 |
+
"""Options for parsing."""
|
| 59 |
+
components: MutableMapping[str, MutableMapping[str, list[str]]]
|
| 60 |
+
"""Components for parsing and rendering."""
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
class OptionsDict(MutableMappingABC): # type: ignore
|
| 64 |
+
"""A dictionary, with attribute access to core markdownit configuration options."""
|
| 65 |
+
|
| 66 |
+
# Note: ideally we would probably just remove attribute access entirely,
|
| 67 |
+
# but we keep it for backwards compatibility.
|
| 68 |
+
|
| 69 |
+
def __init__(self, options: OptionsType) -> None:
|
| 70 |
+
self._options = cast(OptionsType, dict(options))
|
| 71 |
+
|
| 72 |
+
def __getitem__(self, key: str) -> Any:
|
| 73 |
+
return self._options[key] # type: ignore[literal-required]
|
| 74 |
+
|
| 75 |
+
def __setitem__(self, key: str, value: Any) -> None:
|
| 76 |
+
self._options[key] = value # type: ignore[literal-required]
|
| 77 |
+
|
| 78 |
+
def __delitem__(self, key: str) -> None:
|
| 79 |
+
del self._options[key] # type: ignore
|
| 80 |
+
|
| 81 |
+
def __iter__(self) -> Iterable[str]: # type: ignore
|
| 82 |
+
return iter(self._options)
|
| 83 |
+
|
| 84 |
+
def __len__(self) -> int:
|
| 85 |
+
return len(self._options)
|
| 86 |
+
|
| 87 |
+
def __repr__(self) -> str:
|
| 88 |
+
return repr(self._options)
|
| 89 |
+
|
| 90 |
+
def __str__(self) -> str:
|
| 91 |
+
return str(self._options)
|
| 92 |
+
|
| 93 |
+
@property
|
| 94 |
+
def maxNesting(self) -> int:
|
| 95 |
+
"""Internal protection, recursion limit."""
|
| 96 |
+
return self._options["maxNesting"]
|
| 97 |
+
|
| 98 |
+
@maxNesting.setter
|
| 99 |
+
def maxNesting(self, value: int) -> None:
|
| 100 |
+
self._options["maxNesting"] = value
|
| 101 |
+
|
| 102 |
+
@property
|
| 103 |
+
def html(self) -> bool:
|
| 104 |
+
"""Enable HTML tags in source."""
|
| 105 |
+
return self._options["html"]
|
| 106 |
+
|
| 107 |
+
@html.setter
|
| 108 |
+
def html(self, value: bool) -> None:
|
| 109 |
+
self._options["html"] = value
|
| 110 |
+
|
| 111 |
+
@property
|
| 112 |
+
def linkify(self) -> bool:
|
| 113 |
+
"""Enable autoconversion of URL-like texts to links."""
|
| 114 |
+
return self._options["linkify"]
|
| 115 |
+
|
| 116 |
+
@linkify.setter
|
| 117 |
+
def linkify(self, value: bool) -> None:
|
| 118 |
+
self._options["linkify"] = value
|
| 119 |
+
|
| 120 |
+
@property
|
| 121 |
+
def typographer(self) -> bool:
|
| 122 |
+
"""Enable smartquotes and replacements."""
|
| 123 |
+
return self._options["typographer"]
|
| 124 |
+
|
| 125 |
+
@typographer.setter
|
| 126 |
+
def typographer(self, value: bool) -> None:
|
| 127 |
+
self._options["typographer"] = value
|
| 128 |
+
|
| 129 |
+
@property
|
| 130 |
+
def quotes(self) -> str:
|
| 131 |
+
"""Quote characters."""
|
| 132 |
+
return self._options["quotes"]
|
| 133 |
+
|
| 134 |
+
@quotes.setter
|
| 135 |
+
def quotes(self, value: str) -> None:
|
| 136 |
+
self._options["quotes"] = value
|
| 137 |
+
|
| 138 |
+
@property
|
| 139 |
+
def xhtmlOut(self) -> bool:
|
| 140 |
+
"""Use '/' to close single tags (<br />)."""
|
| 141 |
+
return self._options["xhtmlOut"]
|
| 142 |
+
|
| 143 |
+
@xhtmlOut.setter
|
| 144 |
+
def xhtmlOut(self, value: bool) -> None:
|
| 145 |
+
self._options["xhtmlOut"] = value
|
| 146 |
+
|
| 147 |
+
@property
|
| 148 |
+
def breaks(self) -> bool:
|
| 149 |
+
"""Convert newlines in paragraphs into <br>."""
|
| 150 |
+
return self._options["breaks"]
|
| 151 |
+
|
| 152 |
+
@breaks.setter
|
| 153 |
+
def breaks(self, value: bool) -> None:
|
| 154 |
+
self._options["breaks"] = value
|
| 155 |
+
|
| 156 |
+
@property
|
| 157 |
+
def langPrefix(self) -> str:
|
| 158 |
+
"""CSS language prefix for fenced blocks."""
|
| 159 |
+
return self._options["langPrefix"]
|
| 160 |
+
|
| 161 |
+
@langPrefix.setter
|
| 162 |
+
def langPrefix(self, value: str) -> None:
|
| 163 |
+
self._options["langPrefix"] = value
|
| 164 |
+
|
| 165 |
+
@property
|
| 166 |
+
def highlight(self) -> Callable[[str, str, str], str] | None:
|
| 167 |
+
"""Highlighter function: (content, langName, langAttrs) -> escaped HTML."""
|
| 168 |
+
return self._options["highlight"]
|
| 169 |
+
|
| 170 |
+
@highlight.setter
|
| 171 |
+
def highlight(self, value: Callable[[str, str, str], str] | None) -> None:
|
| 172 |
+
self._options["highlight"] = value
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
def read_fixture_file(path: str | Path) -> list[list[Any]]:
|
| 176 |
+
text = Path(path).read_text(encoding="utf-8")
|
| 177 |
+
tests = []
|
| 178 |
+
section = 0
|
| 179 |
+
last_pos = 0
|
| 180 |
+
lines = text.splitlines(keepends=True)
|
| 181 |
+
for i in range(len(lines)):
|
| 182 |
+
if lines[i].rstrip() == ".":
|
| 183 |
+
if section == 0:
|
| 184 |
+
tests.append([i, lines[i - 1].strip()])
|
| 185 |
+
section = 1
|
| 186 |
+
elif section == 1:
|
| 187 |
+
tests[-1].append("".join(lines[last_pos + 1 : i]))
|
| 188 |
+
section = 2
|
| 189 |
+
elif section == 2:
|
| 190 |
+
tests[-1].append("".join(lines[last_pos + 1 : i]))
|
| 191 |
+
section = 0
|
| 192 |
+
|
| 193 |
+
last_pos = i
|
| 194 |
+
return tests
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/colpali/__init__.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from typing import TYPE_CHECKING
|
| 15 |
+
|
| 16 |
+
from ...utils import _LazyModule
|
| 17 |
+
from ...utils.import_utils import define_import_structure
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
if TYPE_CHECKING:
|
| 21 |
+
from .configuration_colpali import *
|
| 22 |
+
from .modeling_colpali import *
|
| 23 |
+
from .processing_colpali import *
|
| 24 |
+
else:
|
| 25 |
+
import sys
|
| 26 |
+
|
| 27 |
+
_file = globals()["__file__"]
|
| 28 |
+
sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/colpali/modular_colpali.py
ADDED
|
@@ -0,0 +1,296 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 The HuggingFace Inc. team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
from typing import Optional, Union
|
| 17 |
+
|
| 18 |
+
from transformers.models.paligemma.processing_paligemma import IMAGE_TOKEN, PaliGemmaProcessor, build_string_from_input
|
| 19 |
+
|
| 20 |
+
from ...feature_extraction_utils import BatchFeature
|
| 21 |
+
from ...image_utils import ImageInput, make_flat_list_of_images
|
| 22 |
+
from ...processing_utils import ProcessingKwargs, Unpack
|
| 23 |
+
from ...tokenization_utils_base import PreTokenizedInput, TextInput
|
| 24 |
+
from ...utils import is_torch_available, logging
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
if is_torch_available():
|
| 28 |
+
import torch
|
| 29 |
+
|
| 30 |
+
logger = logging.get_logger(__name__)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class ColPaliProcessorKwargs(ProcessingKwargs, total=False):
|
| 34 |
+
_defaults = {
|
| 35 |
+
"text_kwargs": {
|
| 36 |
+
"padding": "longest",
|
| 37 |
+
},
|
| 38 |
+
"images_kwargs": {
|
| 39 |
+
"data_format": "channels_first",
|
| 40 |
+
"do_convert_rgb": True,
|
| 41 |
+
},
|
| 42 |
+
"common_kwargs": {"return_tensors": "pt"},
|
| 43 |
+
}
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
class ColPaliProcessor(PaliGemmaProcessor):
|
| 47 |
+
def __init__(
|
| 48 |
+
self,
|
| 49 |
+
image_processor=None,
|
| 50 |
+
tokenizer=None,
|
| 51 |
+
chat_template=None,
|
| 52 |
+
visual_prompt_prefix: str = "Describe the image.",
|
| 53 |
+
query_prefix: str = "Question: ",
|
| 54 |
+
):
|
| 55 |
+
r"""
|
| 56 |
+
visual_prompt_prefix (`str`, *optional*, defaults to `"Describe the image."`):
|
| 57 |
+
A string that gets tokenized and prepended to the image tokens.
|
| 58 |
+
query_prefix (`str`, *optional*, defaults to `"Question: "`):
|
| 59 |
+
A prefix to be used for the query.
|
| 60 |
+
"""
|
| 61 |
+
self.visual_prompt_prefix = visual_prompt_prefix
|
| 62 |
+
self.query_prefix = query_prefix
|
| 63 |
+
super().__init__(image_processor=image_processor, tokenizer=tokenizer, chat_template=chat_template)
|
| 64 |
+
|
| 65 |
+
@property
|
| 66 |
+
def query_augmentation_token(self) -> str:
|
| 67 |
+
"""
|
| 68 |
+
Return the query augmentation token.
|
| 69 |
+
|
| 70 |
+
Query augmentation buffers are used as reasoning buffers during inference.
|
| 71 |
+
"""
|
| 72 |
+
return self.tokenizer.pad_token
|
| 73 |
+
|
| 74 |
+
def __call__(
|
| 75 |
+
self,
|
| 76 |
+
images: ImageInput | None = None,
|
| 77 |
+
text: TextInput | PreTokenizedInput | list[TextInput] | list[PreTokenizedInput] = None,
|
| 78 |
+
**kwargs: Unpack[ColPaliProcessorKwargs],
|
| 79 |
+
) -> BatchFeature:
|
| 80 |
+
r"""
|
| 81 |
+
Returns:
|
| 82 |
+
[`BatchFeature`]: A [`BatchFeature`] with the following fields:
|
| 83 |
+
|
| 84 |
+
- **input_ids** -- List of token ids to be fed to a model.
|
| 85 |
+
- **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
|
| 86 |
+
`return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
|
| 87 |
+
`None`).
|
| 88 |
+
- **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
|
| 89 |
+
"""
|
| 90 |
+
output_kwargs = self._merge_kwargs(
|
| 91 |
+
ColPaliProcessorKwargs,
|
| 92 |
+
tokenizer_init_kwargs=self.tokenizer.init_kwargs,
|
| 93 |
+
**kwargs,
|
| 94 |
+
)
|
| 95 |
+
suffix = output_kwargs["text_kwargs"].pop("suffix", None)
|
| 96 |
+
|
| 97 |
+
return_token_type_ids = True
|
| 98 |
+
|
| 99 |
+
if text is None and images is None:
|
| 100 |
+
raise ValueError("Either text or images must be provided")
|
| 101 |
+
if text is not None and images is not None:
|
| 102 |
+
raise ValueError("Only one of text or images can be processed at a time")
|
| 103 |
+
|
| 104 |
+
if images is not None:
|
| 105 |
+
images = self.image_processor.fetch_images(images)
|
| 106 |
+
images = make_flat_list_of_images(images)
|
| 107 |
+
texts_doc = [self.visual_prompt_prefix] * len(images)
|
| 108 |
+
images = [self.image_processor.process_image(image) for image in images]
|
| 109 |
+
|
| 110 |
+
input_strings = [
|
| 111 |
+
build_string_from_input(
|
| 112 |
+
prompt=prompt,
|
| 113 |
+
bos_token=self.tokenizer.bos_token,
|
| 114 |
+
image_seq_len=self.image_seq_length,
|
| 115 |
+
image_token=IMAGE_TOKEN,
|
| 116 |
+
num_images=len(image_list) if isinstance(image_list, list) else 1,
|
| 117 |
+
)
|
| 118 |
+
for prompt, image_list in zip(texts_doc, images)
|
| 119 |
+
]
|
| 120 |
+
pixel_values = self.image_processor(images, **output_kwargs["images_kwargs"])["pixel_values"]
|
| 121 |
+
|
| 122 |
+
# max_length has to account for the image tokens
|
| 123 |
+
if output_kwargs["text_kwargs"].get("max_length", None) is not None:
|
| 124 |
+
output_kwargs["text_kwargs"]["max_length"] += self.image_seq_length
|
| 125 |
+
|
| 126 |
+
inputs = self.tokenizer(
|
| 127 |
+
input_strings,
|
| 128 |
+
return_token_type_ids=return_token_type_ids,
|
| 129 |
+
**output_kwargs["text_kwargs"],
|
| 130 |
+
)
|
| 131 |
+
|
| 132 |
+
return_data = {**inputs, "pixel_values": pixel_values}
|
| 133 |
+
|
| 134 |
+
if return_token_type_ids:
|
| 135 |
+
labels = inputs["input_ids"].masked_fill(inputs["token_type_ids"] == 0, -100)
|
| 136 |
+
return_data.update({"labels": labels})
|
| 137 |
+
|
| 138 |
+
return BatchFeature(data=return_data)
|
| 139 |
+
|
| 140 |
+
elif text is not None:
|
| 141 |
+
if isinstance(text, str):
|
| 142 |
+
text = [text]
|
| 143 |
+
elif not (isinstance(text, list) and isinstance(text[0], str)):
|
| 144 |
+
raise ValueError("Text must be a string or a list of strings")
|
| 145 |
+
|
| 146 |
+
if suffix is None:
|
| 147 |
+
suffix = self.query_augmentation_token * 10
|
| 148 |
+
|
| 149 |
+
texts_query: list[str] = []
|
| 150 |
+
for query in text:
|
| 151 |
+
query = self.tokenizer.bos_token + self.query_prefix + query + suffix + "\n"
|
| 152 |
+
texts_query.append(query)
|
| 153 |
+
|
| 154 |
+
output_kwargs["text_kwargs"]["max_length"] = output_kwargs["text_kwargs"].get("max_length", 50)
|
| 155 |
+
|
| 156 |
+
batch_query = self.tokenizer(
|
| 157 |
+
texts_query,
|
| 158 |
+
return_token_type_ids=return_token_type_ids,
|
| 159 |
+
**output_kwargs["text_kwargs"],
|
| 160 |
+
)
|
| 161 |
+
|
| 162 |
+
return batch_query
|
| 163 |
+
|
| 164 |
+
def process_images(
|
| 165 |
+
self,
|
| 166 |
+
images: ImageInput | None = None,
|
| 167 |
+
**kwargs: Unpack[ColPaliProcessorKwargs],
|
| 168 |
+
) -> BatchFeature:
|
| 169 |
+
"""
|
| 170 |
+
Prepare for the model one or several image(s). This method is a wrapper around the `__call__` method of the ColPaliProcessor's
|
| 171 |
+
[`ColPaliProcessor.__call__`].
|
| 172 |
+
|
| 173 |
+
This method forwards the `images` and `kwargs` arguments to the image processor.
|
| 174 |
+
|
| 175 |
+
Args:
|
| 176 |
+
images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `list[PIL.Image.Image]`, `list[np.ndarray]`, `list[torch.Tensor]`):
|
| 177 |
+
The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
|
| 178 |
+
tensor. In case of a NumPy array/PyTorch tensor, each image should be of shape (C, H, W), where C is a
|
| 179 |
+
number of channels, H and W are image height and width.
|
| 180 |
+
return_tensors (`str` or [`~utils.TensorType`], *optional*):
|
| 181 |
+
If set, will return tensors of a particular framework. Acceptable values are:
|
| 182 |
+
|
| 183 |
+
- `'pt'`: Return PyTorch `torch.Tensor` objects.
|
| 184 |
+
- `'np'`: Return NumPy `np.ndarray` objects.
|
| 185 |
+
|
| 186 |
+
Returns:
|
| 187 |
+
[`BatchFeature`]: A [`BatchFeature`] with the following fields:
|
| 188 |
+
|
| 189 |
+
- **input_ids** -- List of token ids to be fed to a model.
|
| 190 |
+
- **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
|
| 191 |
+
`return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
|
| 192 |
+
`None`).
|
| 193 |
+
- **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
|
| 194 |
+
"""
|
| 195 |
+
return self.__call__(images=images, **kwargs)
|
| 196 |
+
|
| 197 |
+
def process_queries(
|
| 198 |
+
self,
|
| 199 |
+
text: TextInput | list[TextInput],
|
| 200 |
+
**kwargs: Unpack[ColPaliProcessorKwargs],
|
| 201 |
+
) -> BatchFeature:
|
| 202 |
+
"""
|
| 203 |
+
Prepare for the model one or several texts. This method is a wrapper around the `__call__` method of the ColPaliProcessor's
|
| 204 |
+
[`ColPaliProcessor.__call__`].
|
| 205 |
+
|
| 206 |
+
This method forwards the `text` and `kwargs` arguments to the tokenizer.
|
| 207 |
+
|
| 208 |
+
Args:
|
| 209 |
+
text (`str`, `list[str]`, `list[list[str]]`):
|
| 210 |
+
The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
|
| 211 |
+
(pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
|
| 212 |
+
`is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
|
| 213 |
+
return_tensors (`str` or [`~utils.TensorType`], *optional*):
|
| 214 |
+
If set, will return tensors of a particular framework. Acceptable values are:
|
| 215 |
+
|
| 216 |
+
- `'pt'`: Return PyTorch `torch.Tensor` objects.
|
| 217 |
+
- `'np'`: Return NumPy `np.ndarray` objects.
|
| 218 |
+
|
| 219 |
+
Returns:
|
| 220 |
+
[`BatchFeature`]: A [`BatchFeature`] with the following fields:
|
| 221 |
+
|
| 222 |
+
- **input_ids** -- List of token ids to be fed to a model.
|
| 223 |
+
- **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
|
| 224 |
+
`return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
|
| 225 |
+
`None`).
|
| 226 |
+
"""
|
| 227 |
+
return self.__call__(text=text, **kwargs)
|
| 228 |
+
|
| 229 |
+
def score_retrieval(
|
| 230 |
+
self,
|
| 231 |
+
query_embeddings: Union["torch.Tensor", list["torch.Tensor"]],
|
| 232 |
+
passage_embeddings: Union["torch.Tensor", list["torch.Tensor"]],
|
| 233 |
+
batch_size: int = 128,
|
| 234 |
+
output_dtype: Optional["torch.dtype"] = None,
|
| 235 |
+
output_device: Union["torch.device", str] = "cpu",
|
| 236 |
+
) -> "torch.Tensor":
|
| 237 |
+
"""
|
| 238 |
+
Compute the late-interaction/MaxSim score (ColBERT-like) for the given multi-vector
|
| 239 |
+
query embeddings (`qs`) and passage embeddings (`ps`). For ColPali, a passage is the
|
| 240 |
+
image of a document page.
|
| 241 |
+
|
| 242 |
+
Because the embedding tensors are multi-vector and can thus have different shapes, they
|
| 243 |
+
should be fed as:
|
| 244 |
+
(1) a list of tensors, where the i-th tensor is of shape (sequence_length_i, embedding_dim)
|
| 245 |
+
(2) a single tensor of shape (n_passages, max_sequence_length, embedding_dim) -> usually
|
| 246 |
+
obtained by padding the list of tensors.
|
| 247 |
+
|
| 248 |
+
Args:
|
| 249 |
+
query_embeddings (`Union[torch.Tensor, list[torch.Tensor]`): Query embeddings.
|
| 250 |
+
passage_embeddings (`Union[torch.Tensor, list[torch.Tensor]`): Passage embeddings.
|
| 251 |
+
batch_size (`int`, *optional*, defaults to 128): Batch size for computing scores.
|
| 252 |
+
output_dtype (`torch.dtype`, *optional*, defaults to `torch.float32`): The dtype of the output tensor.
|
| 253 |
+
If `None`, the dtype of the input embeddings is used.
|
| 254 |
+
output_device (`torch.device` or `str`, *optional*, defaults to "cpu"): The device of the output tensor.
|
| 255 |
+
|
| 256 |
+
Returns:
|
| 257 |
+
`torch.Tensor`: A tensor of shape `(n_queries, n_passages)` containing the scores. The score
|
| 258 |
+
tensor is saved on the "cpu" device.
|
| 259 |
+
"""
|
| 260 |
+
|
| 261 |
+
if len(query_embeddings) == 0:
|
| 262 |
+
raise ValueError("No queries provided")
|
| 263 |
+
if len(passage_embeddings) == 0:
|
| 264 |
+
raise ValueError("No passages provided")
|
| 265 |
+
|
| 266 |
+
if query_embeddings[0].device != passage_embeddings[0].device:
|
| 267 |
+
raise ValueError("Queries and passages must be on the same device")
|
| 268 |
+
|
| 269 |
+
if query_embeddings[0].dtype != passage_embeddings[0].dtype:
|
| 270 |
+
raise ValueError("Queries and passages must have the same dtype")
|
| 271 |
+
|
| 272 |
+
if output_dtype is None:
|
| 273 |
+
output_dtype = query_embeddings[0].dtype
|
| 274 |
+
|
| 275 |
+
scores: list[torch.Tensor] = []
|
| 276 |
+
|
| 277 |
+
for i in range(0, len(query_embeddings), batch_size):
|
| 278 |
+
batch_scores: list[torch.Tensor] = []
|
| 279 |
+
batch_queries = torch.nn.utils.rnn.pad_sequence(
|
| 280 |
+
query_embeddings[i : i + batch_size], batch_first=True, padding_value=0
|
| 281 |
+
)
|
| 282 |
+
for j in range(0, len(passage_embeddings), batch_size):
|
| 283 |
+
batch_passages = torch.nn.utils.rnn.pad_sequence(
|
| 284 |
+
passage_embeddings[j : j + batch_size], batch_first=True, padding_value=0
|
| 285 |
+
)
|
| 286 |
+
batch_scores.append(
|
| 287 |
+
torch.einsum("bnd,csd->bcns", batch_queries, batch_passages).max(dim=3)[0].sum(dim=2)
|
| 288 |
+
)
|
| 289 |
+
scores.append(torch.cat(batch_scores, dim=1).to(output_dtype).to(output_device))
|
| 290 |
+
|
| 291 |
+
return torch.cat(scores, dim=0)
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
__all__ = [
|
| 295 |
+
"ColPaliProcessor",
|
| 296 |
+
]
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_2x8gpu_50ep_lr4e3_ema0p9999_elfopt_not5_bottleneck128_unfixed_norm_stateprobadd_selfcond_ce_fast_20260610_020108/step_153000.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:376ea08cb78c6b4dea29f2f53d9e3b10a1d371423435d41f7cd8c3d9f9cfaf2c
|
| 3 |
+
size 927700322
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_2x8gpu_50ep_lr4e3_ema0p9999_elfopt_not5_bottleneck128_unfixed_norm_stateprobadd_selfcond_ce_fast_20260610_020108/step_169000.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:b839d0620ef827b475afe6ac6662ebb2cdcb40e2d4c6802d6b4804a6c2134835
|
| 3 |
+
size 927700322
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_2x8gpu_50ep_lr4e3_ema0p9999_elfopt_not5_bottleneck128_unfixed_norm_stateprobadd_selfcond_ce_fast_20260610_020108/step_188000.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:a2fd16d59df0b5ba62c3caa8616d1ae7b68184ff6811d2e12f90b0bef05e7816
|
| 3 |
+
size 927700322
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_2x8gpu_50ep_lr4e3_ema0p9999_elfopt_not5_bottleneck128_unfixed_norm_stateprobadd_selfcond_ce_fast_20260610_020108/step_247000.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:23fd91ac84c75cac68c682ff0df325b91300c8b01d7974af2ad4af2cd5f1563b
|
| 3 |
+
size 927700322
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_2x8gpu_50ep_lr4e3_ema0p9999_elfopt_not5_bottleneck128_unfixed_norm_stateprobadd_selfcond_ce_fast_20260610_020108/step_272000.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:f8ff1d2e5dfb136a4d48f240a4bfb4600ea7173c966140dd7103a84bacf75569
|
| 3 |
+
size 927700322
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_2x8gpu_50ep_lr4e3_ema0p9999_elfopt_not5_bottleneck128_unfixed_norm_stateprobadd_selfcond_ce_fast_20260610_020108/step_287000.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:c78056d738b731e543940b219e7a6658fab4ef2a0c92cfc22eeece99c427c6cb
|
| 3 |
+
size 927700322
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_2x8gpu_50ep_lr4e3_ema0p9999_elfopt_not5_bottleneck128_unfixed_norm_stateprobadd_selfcond_ce_fast_20260610_020108/step_288000.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:3b7eb15fda77f5faf8da57859d476b4f6d9782fe40903bdb45da4dd024952a90
|
| 3 |
+
size 927700322
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/runs/owt_t5_elftokenized_full_len1024_C1_to_1024_pow1_d768_l12_h12_gbs512_2x8gpu_50ep_lr4e3_ema0p9999_elfopt_not5_bottleneck128_unfixed_norm_stateprobadd_selfcond_ce_fast_20260610_020108/step_297000.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:ddffefa4e58da82402f0f2a270c92cee36aebdebb680e53a17d8ef2568e6f36d
|
| 3 |
+
size 927700322
|