Add files using upload-large-folder tool
Browse files- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35/lib/python3.12/site-packages/pip/_vendor/rich/_export_format.py +76 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35/lib/python3.12/site-packages/pip/_vendor/rich/_inspect.py +270 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35/lib/python3.12/site-packages/pip/_vendor/rich/_windows.py +72 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35/lib/python3.12/site-packages/pip/_vendor/rich/bar.py +94 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35/lib/python3.12/site-packages/pip/_vendor/rich/containers.py +167 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35/lib/python3.12/site-packages/pip/_vendor/rich/default_styles.py +190 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35/lib/python3.12/site-packages/pip/_vendor/rich/highlighter.py +232 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35/lib/python3.12/site-packages/pip/_vendor/rich/json.py +140 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35/lib/python3.12/site-packages/pip/_vendor/rich/live.py +375 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35/lib/python3.12/site-packages/pip/_vendor/rich/pager.py +34 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35/lib/python3.12/site-packages/pip/_vendor/rich/rule.py +130 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35/lib/python3.12/site-packages/pip/_vendor/rich/styled.py +42 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35/lib/python3.12/site-packages/pip/_vendor/rich/syntax.py +948 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35/lib/python3.12/site-packages/pip/_vendor/rich/terminal_theme.py +153 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/moonshine_streaming/configuration_moonshine_streaming.py +142 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/moonshine_streaming/modeling_moonshine_streaming.py +1121 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/moonshine_streaming/modular_moonshine_streaming.py +419 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/moonshine_streaming/processing_moonshine_streaming.py +114 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/paligemma/__init__.py +28 -0
- LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/paligemma/processing_paligemma.py +272 -0
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35/lib/python3.12/site-packages/pip/_vendor/rich/_export_format.py
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
CONSOLE_HTML_FORMAT = """\
|
| 2 |
+
<!DOCTYPE html>
|
| 3 |
+
<head>
|
| 4 |
+
<meta charset="UTF-8">
|
| 5 |
+
<style>
|
| 6 |
+
{stylesheet}
|
| 7 |
+
body {{
|
| 8 |
+
color: {foreground};
|
| 9 |
+
background-color: {background};
|
| 10 |
+
}}
|
| 11 |
+
</style>
|
| 12 |
+
</head>
|
| 13 |
+
<html>
|
| 14 |
+
<body>
|
| 15 |
+
<pre style="font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace"><code>{code}</code></pre>
|
| 16 |
+
</body>
|
| 17 |
+
</html>
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
CONSOLE_SVG_FORMAT = """\
|
| 21 |
+
<svg class="rich-terminal" viewBox="0 0 {width} {height}" xmlns="http://www.w3.org/2000/svg">
|
| 22 |
+
<!-- Generated with Rich https://www.textualize.io -->
|
| 23 |
+
<style>
|
| 24 |
+
|
| 25 |
+
@font-face {{
|
| 26 |
+
font-family: "Fira Code";
|
| 27 |
+
src: local("FiraCode-Regular"),
|
| 28 |
+
url("https://cdnjs.cloudflare.com/ajax/libs/firacode/6.2.0/woff2/FiraCode-Regular.woff2") format("woff2"),
|
| 29 |
+
url("https://cdnjs.cloudflare.com/ajax/libs/firacode/6.2.0/woff/FiraCode-Regular.woff") format("woff");
|
| 30 |
+
font-style: normal;
|
| 31 |
+
font-weight: 400;
|
| 32 |
+
}}
|
| 33 |
+
@font-face {{
|
| 34 |
+
font-family: "Fira Code";
|
| 35 |
+
src: local("FiraCode-Bold"),
|
| 36 |
+
url("https://cdnjs.cloudflare.com/ajax/libs/firacode/6.2.0/woff2/FiraCode-Bold.woff2") format("woff2"),
|
| 37 |
+
url("https://cdnjs.cloudflare.com/ajax/libs/firacode/6.2.0/woff/FiraCode-Bold.woff") format("woff");
|
| 38 |
+
font-style: bold;
|
| 39 |
+
font-weight: 700;
|
| 40 |
+
}}
|
| 41 |
+
|
| 42 |
+
.{unique_id}-matrix {{
|
| 43 |
+
font-family: Fira Code, monospace;
|
| 44 |
+
font-size: {char_height}px;
|
| 45 |
+
line-height: {line_height}px;
|
| 46 |
+
font-variant-east-asian: full-width;
|
| 47 |
+
}}
|
| 48 |
+
|
| 49 |
+
.{unique_id}-title {{
|
| 50 |
+
font-size: 18px;
|
| 51 |
+
font-weight: bold;
|
| 52 |
+
font-family: arial;
|
| 53 |
+
}}
|
| 54 |
+
|
| 55 |
+
{styles}
|
| 56 |
+
</style>
|
| 57 |
+
|
| 58 |
+
<defs>
|
| 59 |
+
<clipPath id="{unique_id}-clip-terminal">
|
| 60 |
+
<rect x="0" y="0" width="{terminal_width}" height="{terminal_height}" />
|
| 61 |
+
</clipPath>
|
| 62 |
+
{lines}
|
| 63 |
+
</defs>
|
| 64 |
+
|
| 65 |
+
{chrome}
|
| 66 |
+
<g transform="translate({terminal_x}, {terminal_y})" clip-path="url(#{unique_id}-clip-terminal)">
|
| 67 |
+
{backgrounds}
|
| 68 |
+
<g class="{unique_id}-matrix">
|
| 69 |
+
{matrix}
|
| 70 |
+
</g>
|
| 71 |
+
</g>
|
| 72 |
+
</svg>
|
| 73 |
+
"""
|
| 74 |
+
|
| 75 |
+
_SVG_FONT_FAMILY = "Rich Fira Code"
|
| 76 |
+
_SVG_CLASSES_PREFIX = "rich-svg"
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35/lib/python3.12/site-packages/pip/_vendor/rich/_inspect.py
ADDED
|
@@ -0,0 +1,270 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import absolute_import
|
| 2 |
+
|
| 3 |
+
import inspect
|
| 4 |
+
from inspect import cleandoc, getdoc, getfile, isclass, ismodule, signature
|
| 5 |
+
from typing import Any, Collection, Iterable, Optional, Tuple, Type, Union
|
| 6 |
+
|
| 7 |
+
from .console import Group, RenderableType
|
| 8 |
+
from .control import escape_control_codes
|
| 9 |
+
from .highlighter import ReprHighlighter
|
| 10 |
+
from .jupyter import JupyterMixin
|
| 11 |
+
from .panel import Panel
|
| 12 |
+
from .pretty import Pretty
|
| 13 |
+
from .table import Table
|
| 14 |
+
from .text import Text, TextType
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def _first_paragraph(doc: str) -> str:
|
| 18 |
+
"""Get the first paragraph from a docstring."""
|
| 19 |
+
paragraph, _, _ = doc.partition("\n\n")
|
| 20 |
+
return paragraph
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class Inspect(JupyterMixin):
|
| 24 |
+
"""A renderable to inspect any Python Object.
|
| 25 |
+
|
| 26 |
+
Args:
|
| 27 |
+
obj (Any): An object to inspect.
|
| 28 |
+
title (str, optional): Title to display over inspect result, or None use type. Defaults to None.
|
| 29 |
+
help (bool, optional): Show full help text rather than just first paragraph. Defaults to False.
|
| 30 |
+
methods (bool, optional): Enable inspection of callables. Defaults to False.
|
| 31 |
+
docs (bool, optional): Also render doc strings. Defaults to True.
|
| 32 |
+
private (bool, optional): Show private attributes (beginning with underscore). Defaults to False.
|
| 33 |
+
dunder (bool, optional): Show attributes starting with double underscore. Defaults to False.
|
| 34 |
+
sort (bool, optional): Sort attributes alphabetically. Defaults to True.
|
| 35 |
+
all (bool, optional): Show all attributes. Defaults to False.
|
| 36 |
+
value (bool, optional): Pretty print value of object. Defaults to True.
|
| 37 |
+
"""
|
| 38 |
+
|
| 39 |
+
def __init__(
|
| 40 |
+
self,
|
| 41 |
+
obj: Any,
|
| 42 |
+
*,
|
| 43 |
+
title: Optional[TextType] = None,
|
| 44 |
+
help: bool = False,
|
| 45 |
+
methods: bool = False,
|
| 46 |
+
docs: bool = True,
|
| 47 |
+
private: bool = False,
|
| 48 |
+
dunder: bool = False,
|
| 49 |
+
sort: bool = True,
|
| 50 |
+
all: bool = True,
|
| 51 |
+
value: bool = True,
|
| 52 |
+
) -> None:
|
| 53 |
+
self.highlighter = ReprHighlighter()
|
| 54 |
+
self.obj = obj
|
| 55 |
+
self.title = title or self._make_title(obj)
|
| 56 |
+
if all:
|
| 57 |
+
methods = private = dunder = True
|
| 58 |
+
self.help = help
|
| 59 |
+
self.methods = methods
|
| 60 |
+
self.docs = docs or help
|
| 61 |
+
self.private = private or dunder
|
| 62 |
+
self.dunder = dunder
|
| 63 |
+
self.sort = sort
|
| 64 |
+
self.value = value
|
| 65 |
+
|
| 66 |
+
def _make_title(self, obj: Any) -> Text:
|
| 67 |
+
"""Make a default title."""
|
| 68 |
+
title_str = (
|
| 69 |
+
str(obj)
|
| 70 |
+
if (isclass(obj) or callable(obj) or ismodule(obj))
|
| 71 |
+
else str(type(obj))
|
| 72 |
+
)
|
| 73 |
+
title_text = self.highlighter(title_str)
|
| 74 |
+
return title_text
|
| 75 |
+
|
| 76 |
+
def __rich__(self) -> Panel:
|
| 77 |
+
return Panel.fit(
|
| 78 |
+
Group(*self._render()),
|
| 79 |
+
title=self.title,
|
| 80 |
+
border_style="scope.border",
|
| 81 |
+
padding=(0, 1),
|
| 82 |
+
)
|
| 83 |
+
|
| 84 |
+
def _get_signature(self, name: str, obj: Any) -> Optional[Text]:
|
| 85 |
+
"""Get a signature for a callable."""
|
| 86 |
+
try:
|
| 87 |
+
_signature = str(signature(obj)) + ":"
|
| 88 |
+
except ValueError:
|
| 89 |
+
_signature = "(...)"
|
| 90 |
+
except TypeError:
|
| 91 |
+
return None
|
| 92 |
+
|
| 93 |
+
source_filename: Optional[str] = None
|
| 94 |
+
try:
|
| 95 |
+
source_filename = getfile(obj)
|
| 96 |
+
except (OSError, TypeError):
|
| 97 |
+
# OSError is raised if obj has no source file, e.g. when defined in REPL.
|
| 98 |
+
pass
|
| 99 |
+
|
| 100 |
+
callable_name = Text(name, style="inspect.callable")
|
| 101 |
+
if source_filename:
|
| 102 |
+
callable_name.stylize(f"link file://{source_filename}")
|
| 103 |
+
signature_text = self.highlighter(_signature)
|
| 104 |
+
|
| 105 |
+
qualname = name or getattr(obj, "__qualname__", name)
|
| 106 |
+
|
| 107 |
+
# If obj is a module, there may be classes (which are callable) to display
|
| 108 |
+
if inspect.isclass(obj):
|
| 109 |
+
prefix = "class"
|
| 110 |
+
elif inspect.iscoroutinefunction(obj):
|
| 111 |
+
prefix = "async def"
|
| 112 |
+
else:
|
| 113 |
+
prefix = "def"
|
| 114 |
+
|
| 115 |
+
qual_signature = Text.assemble(
|
| 116 |
+
(f"{prefix} ", f"inspect.{prefix.replace(' ', '_')}"),
|
| 117 |
+
(qualname, "inspect.callable"),
|
| 118 |
+
signature_text,
|
| 119 |
+
)
|
| 120 |
+
|
| 121 |
+
return qual_signature
|
| 122 |
+
|
| 123 |
+
def _render(self) -> Iterable[RenderableType]:
|
| 124 |
+
"""Render object."""
|
| 125 |
+
|
| 126 |
+
def sort_items(item: Tuple[str, Any]) -> Tuple[bool, str]:
|
| 127 |
+
key, (_error, value) = item
|
| 128 |
+
return (callable(value), key.strip("_").lower())
|
| 129 |
+
|
| 130 |
+
def safe_getattr(attr_name: str) -> Tuple[Any, Any]:
|
| 131 |
+
"""Get attribute or any exception."""
|
| 132 |
+
try:
|
| 133 |
+
return (None, getattr(obj, attr_name))
|
| 134 |
+
except Exception as error:
|
| 135 |
+
return (error, None)
|
| 136 |
+
|
| 137 |
+
obj = self.obj
|
| 138 |
+
keys = dir(obj)
|
| 139 |
+
total_items = len(keys)
|
| 140 |
+
if not self.dunder:
|
| 141 |
+
keys = [key for key in keys if not key.startswith("__")]
|
| 142 |
+
if not self.private:
|
| 143 |
+
keys = [key for key in keys if not key.startswith("_")]
|
| 144 |
+
not_shown_count = total_items - len(keys)
|
| 145 |
+
items = [(key, safe_getattr(key)) for key in keys]
|
| 146 |
+
if self.sort:
|
| 147 |
+
items.sort(key=sort_items)
|
| 148 |
+
|
| 149 |
+
items_table = Table.grid(padding=(0, 1), expand=False)
|
| 150 |
+
items_table.add_column(justify="right")
|
| 151 |
+
add_row = items_table.add_row
|
| 152 |
+
highlighter = self.highlighter
|
| 153 |
+
|
| 154 |
+
if callable(obj):
|
| 155 |
+
signature = self._get_signature("", obj)
|
| 156 |
+
if signature is not None:
|
| 157 |
+
yield signature
|
| 158 |
+
yield ""
|
| 159 |
+
|
| 160 |
+
if self.docs:
|
| 161 |
+
_doc = self._get_formatted_doc(obj)
|
| 162 |
+
if _doc is not None:
|
| 163 |
+
doc_text = Text(_doc, style="inspect.help")
|
| 164 |
+
doc_text = highlighter(doc_text)
|
| 165 |
+
yield doc_text
|
| 166 |
+
yield ""
|
| 167 |
+
|
| 168 |
+
if self.value and not (isclass(obj) or callable(obj) or ismodule(obj)):
|
| 169 |
+
yield Panel(
|
| 170 |
+
Pretty(obj, indent_guides=True, max_length=10, max_string=60),
|
| 171 |
+
border_style="inspect.value.border",
|
| 172 |
+
)
|
| 173 |
+
yield ""
|
| 174 |
+
|
| 175 |
+
for key, (error, value) in items:
|
| 176 |
+
key_text = Text.assemble(
|
| 177 |
+
(
|
| 178 |
+
key,
|
| 179 |
+
"inspect.attr.dunder" if key.startswith("__") else "inspect.attr",
|
| 180 |
+
),
|
| 181 |
+
(" =", "inspect.equals"),
|
| 182 |
+
)
|
| 183 |
+
if error is not None:
|
| 184 |
+
warning = key_text.copy()
|
| 185 |
+
warning.stylize("inspect.error")
|
| 186 |
+
add_row(warning, highlighter(repr(error)))
|
| 187 |
+
continue
|
| 188 |
+
|
| 189 |
+
if callable(value):
|
| 190 |
+
if not self.methods:
|
| 191 |
+
continue
|
| 192 |
+
|
| 193 |
+
_signature_text = self._get_signature(key, value)
|
| 194 |
+
if _signature_text is None:
|
| 195 |
+
add_row(key_text, Pretty(value, highlighter=highlighter))
|
| 196 |
+
else:
|
| 197 |
+
if self.docs:
|
| 198 |
+
docs = self._get_formatted_doc(value)
|
| 199 |
+
if docs is not None:
|
| 200 |
+
_signature_text.append("\n" if "\n" in docs else " ")
|
| 201 |
+
doc = highlighter(docs)
|
| 202 |
+
doc.stylize("inspect.doc")
|
| 203 |
+
_signature_text.append(doc)
|
| 204 |
+
|
| 205 |
+
add_row(key_text, _signature_text)
|
| 206 |
+
else:
|
| 207 |
+
add_row(key_text, Pretty(value, highlighter=highlighter))
|
| 208 |
+
if items_table.row_count:
|
| 209 |
+
yield items_table
|
| 210 |
+
elif not_shown_count:
|
| 211 |
+
yield Text.from_markup(
|
| 212 |
+
f"[b cyan]{not_shown_count}[/][i] attribute(s) not shown.[/i] "
|
| 213 |
+
f"Run [b][magenta]inspect[/]([not b]inspect[/])[/b] for options."
|
| 214 |
+
)
|
| 215 |
+
|
| 216 |
+
def _get_formatted_doc(self, object_: Any) -> Optional[str]:
|
| 217 |
+
"""
|
| 218 |
+
Extract the docstring of an object, process it and returns it.
|
| 219 |
+
The processing consists in cleaning up the doctring's indentation,
|
| 220 |
+
taking only its 1st paragraph if `self.help` is not True,
|
| 221 |
+
and escape its control codes.
|
| 222 |
+
|
| 223 |
+
Args:
|
| 224 |
+
object_ (Any): the object to get the docstring from.
|
| 225 |
+
|
| 226 |
+
Returns:
|
| 227 |
+
Optional[str]: the processed docstring, or None if no docstring was found.
|
| 228 |
+
"""
|
| 229 |
+
docs = getdoc(object_)
|
| 230 |
+
if docs is None:
|
| 231 |
+
return None
|
| 232 |
+
docs = cleandoc(docs).strip()
|
| 233 |
+
if not self.help:
|
| 234 |
+
docs = _first_paragraph(docs)
|
| 235 |
+
return escape_control_codes(docs)
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
def get_object_types_mro(obj: Union[object, Type[Any]]) -> Tuple[type, ...]:
|
| 239 |
+
"""Returns the MRO of an object's class, or of the object itself if it's a class."""
|
| 240 |
+
if not hasattr(obj, "__mro__"):
|
| 241 |
+
# N.B. we cannot use `if type(obj) is type` here because it doesn't work with
|
| 242 |
+
# some types of classes, such as the ones that use abc.ABCMeta.
|
| 243 |
+
obj = type(obj)
|
| 244 |
+
return getattr(obj, "__mro__", ())
|
| 245 |
+
|
| 246 |
+
|
| 247 |
+
def get_object_types_mro_as_strings(obj: object) -> Collection[str]:
|
| 248 |
+
"""
|
| 249 |
+
Returns the MRO of an object's class as full qualified names, or of the object itself if it's a class.
|
| 250 |
+
|
| 251 |
+
Examples:
|
| 252 |
+
`object_types_mro_as_strings(JSONDecoder)` will return `['json.decoder.JSONDecoder', 'builtins.object']`
|
| 253 |
+
"""
|
| 254 |
+
return [
|
| 255 |
+
f'{getattr(type_, "__module__", "")}.{getattr(type_, "__qualname__", "")}'
|
| 256 |
+
for type_ in get_object_types_mro(obj)
|
| 257 |
+
]
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
def is_object_one_of_types(
|
| 261 |
+
obj: object, fully_qualified_types_names: Collection[str]
|
| 262 |
+
) -> bool:
|
| 263 |
+
"""
|
| 264 |
+
Returns `True` if the given object's class (or the object itself, if it's a class) has one of the
|
| 265 |
+
fully qualified names in its MRO.
|
| 266 |
+
"""
|
| 267 |
+
for type_name in get_object_types_mro_as_strings(obj):
|
| 268 |
+
if type_name in fully_qualified_types_names:
|
| 269 |
+
return True
|
| 270 |
+
return False
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35/lib/python3.12/site-packages/pip/_vendor/rich/_windows.py
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sys
|
| 2 |
+
from dataclasses import dataclass
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
@dataclass
|
| 6 |
+
class WindowsConsoleFeatures:
|
| 7 |
+
"""Windows features available."""
|
| 8 |
+
|
| 9 |
+
vt: bool = False
|
| 10 |
+
"""The console supports VT codes."""
|
| 11 |
+
truecolor: bool = False
|
| 12 |
+
"""The console supports truecolor."""
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
try:
|
| 16 |
+
import ctypes
|
| 17 |
+
from ctypes import LibraryLoader
|
| 18 |
+
|
| 19 |
+
if sys.platform == "win32":
|
| 20 |
+
windll = LibraryLoader(ctypes.WinDLL)
|
| 21 |
+
else:
|
| 22 |
+
windll = None
|
| 23 |
+
raise ImportError("Not windows")
|
| 24 |
+
|
| 25 |
+
from pip._vendor.rich._win32_console import (
|
| 26 |
+
ENABLE_VIRTUAL_TERMINAL_PROCESSING,
|
| 27 |
+
GetConsoleMode,
|
| 28 |
+
GetStdHandle,
|
| 29 |
+
LegacyWindowsError,
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
except (AttributeError, ImportError, ValueError):
|
| 33 |
+
|
| 34 |
+
# Fallback if we can't load the Windows DLL
|
| 35 |
+
def get_windows_console_features() -> WindowsConsoleFeatures:
|
| 36 |
+
features = WindowsConsoleFeatures()
|
| 37 |
+
return features
|
| 38 |
+
|
| 39 |
+
else:
|
| 40 |
+
|
| 41 |
+
def get_windows_console_features() -> WindowsConsoleFeatures:
|
| 42 |
+
"""Get windows console features.
|
| 43 |
+
|
| 44 |
+
Returns:
|
| 45 |
+
WindowsConsoleFeatures: An instance of WindowsConsoleFeatures.
|
| 46 |
+
"""
|
| 47 |
+
handle = GetStdHandle()
|
| 48 |
+
try:
|
| 49 |
+
console_mode = GetConsoleMode(handle)
|
| 50 |
+
success = True
|
| 51 |
+
except LegacyWindowsError:
|
| 52 |
+
console_mode = 0
|
| 53 |
+
success = False
|
| 54 |
+
vt = bool(success and console_mode & ENABLE_VIRTUAL_TERMINAL_PROCESSING)
|
| 55 |
+
truecolor = False
|
| 56 |
+
if vt:
|
| 57 |
+
win_version = sys.getwindowsversion()
|
| 58 |
+
truecolor = win_version.major > 10 or (
|
| 59 |
+
win_version.major == 10 and win_version.build >= 15063
|
| 60 |
+
)
|
| 61 |
+
features = WindowsConsoleFeatures(vt=vt, truecolor=truecolor)
|
| 62 |
+
return features
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
if __name__ == "__main__":
|
| 66 |
+
import platform
|
| 67 |
+
|
| 68 |
+
features = get_windows_console_features()
|
| 69 |
+
from pip._vendor.rich import print
|
| 70 |
+
|
| 71 |
+
print(f'platform="{platform.system()}"')
|
| 72 |
+
print(repr(features))
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35/lib/python3.12/site-packages/pip/_vendor/rich/bar.py
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Optional, Union
|
| 2 |
+
|
| 3 |
+
from .color import Color
|
| 4 |
+
from .console import Console, ConsoleOptions, RenderResult
|
| 5 |
+
from .jupyter import JupyterMixin
|
| 6 |
+
from .measure import Measurement
|
| 7 |
+
from .segment import Segment
|
| 8 |
+
from .style import Style
|
| 9 |
+
|
| 10 |
+
# There are left-aligned characters for 1/8 to 7/8, but
|
| 11 |
+
# the right-aligned characters exist only for 1/8 and 4/8.
|
| 12 |
+
BEGIN_BLOCK_ELEMENTS = ["█", "█", "█", "▐", "▐", "▐", "▕", "▕"]
|
| 13 |
+
END_BLOCK_ELEMENTS = [" ", "▏", "▎", "▍", "▌", "▋", "▊", "▉"]
|
| 14 |
+
FULL_BLOCK = "█"
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class Bar(JupyterMixin):
|
| 18 |
+
"""Renders a solid block bar.
|
| 19 |
+
|
| 20 |
+
Args:
|
| 21 |
+
size (float): Value for the end of the bar.
|
| 22 |
+
begin (float): Begin point (between 0 and size, inclusive).
|
| 23 |
+
end (float): End point (between 0 and size, inclusive).
|
| 24 |
+
width (int, optional): Width of the bar, or ``None`` for maximum width. Defaults to None.
|
| 25 |
+
color (Union[Color, str], optional): Color of the bar. Defaults to "default".
|
| 26 |
+
bgcolor (Union[Color, str], optional): Color of bar background. Defaults to "default".
|
| 27 |
+
"""
|
| 28 |
+
|
| 29 |
+
def __init__(
|
| 30 |
+
self,
|
| 31 |
+
size: float,
|
| 32 |
+
begin: float,
|
| 33 |
+
end: float,
|
| 34 |
+
*,
|
| 35 |
+
width: Optional[int] = None,
|
| 36 |
+
color: Union[Color, str] = "default",
|
| 37 |
+
bgcolor: Union[Color, str] = "default",
|
| 38 |
+
):
|
| 39 |
+
self.size = size
|
| 40 |
+
self.begin = max(begin, 0)
|
| 41 |
+
self.end = min(end, size)
|
| 42 |
+
self.width = width
|
| 43 |
+
self.style = Style(color=color, bgcolor=bgcolor)
|
| 44 |
+
|
| 45 |
+
def __repr__(self) -> str:
|
| 46 |
+
return f"Bar({self.size}, {self.begin}, {self.end})"
|
| 47 |
+
|
| 48 |
+
def __rich_console__(
|
| 49 |
+
self, console: Console, options: ConsoleOptions
|
| 50 |
+
) -> RenderResult:
|
| 51 |
+
|
| 52 |
+
width = min(
|
| 53 |
+
self.width if self.width is not None else options.max_width,
|
| 54 |
+
options.max_width,
|
| 55 |
+
)
|
| 56 |
+
|
| 57 |
+
if self.begin >= self.end:
|
| 58 |
+
yield Segment(" " * width, self.style)
|
| 59 |
+
yield Segment.line()
|
| 60 |
+
return
|
| 61 |
+
|
| 62 |
+
prefix_complete_eights = int(width * 8 * self.begin / self.size)
|
| 63 |
+
prefix_bar_count = prefix_complete_eights // 8
|
| 64 |
+
prefix_eights_count = prefix_complete_eights % 8
|
| 65 |
+
|
| 66 |
+
body_complete_eights = int(width * 8 * self.end / self.size)
|
| 67 |
+
body_bar_count = body_complete_eights // 8
|
| 68 |
+
body_eights_count = body_complete_eights % 8
|
| 69 |
+
|
| 70 |
+
# When start and end fall into the same cell, we ideally should render
|
| 71 |
+
# a symbol that's "center-aligned", but there is no good symbol in Unicode.
|
| 72 |
+
# In this case, we fall back to right-aligned block symbol for simplicity.
|
| 73 |
+
|
| 74 |
+
prefix = " " * prefix_bar_count
|
| 75 |
+
if prefix_eights_count:
|
| 76 |
+
prefix += BEGIN_BLOCK_ELEMENTS[prefix_eights_count]
|
| 77 |
+
|
| 78 |
+
body = FULL_BLOCK * body_bar_count
|
| 79 |
+
if body_eights_count:
|
| 80 |
+
body += END_BLOCK_ELEMENTS[body_eights_count]
|
| 81 |
+
|
| 82 |
+
suffix = " " * (width - len(body))
|
| 83 |
+
|
| 84 |
+
yield Segment(prefix + body[len(prefix) :] + suffix, self.style)
|
| 85 |
+
yield Segment.line()
|
| 86 |
+
|
| 87 |
+
def __rich_measure__(
|
| 88 |
+
self, console: Console, options: ConsoleOptions
|
| 89 |
+
) -> Measurement:
|
| 90 |
+
return (
|
| 91 |
+
Measurement(self.width, self.width)
|
| 92 |
+
if self.width is not None
|
| 93 |
+
else Measurement(4, options.max_width)
|
| 94 |
+
)
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35/lib/python3.12/site-packages/pip/_vendor/rich/containers.py
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from itertools import zip_longest
|
| 2 |
+
from typing import (
|
| 3 |
+
Iterator,
|
| 4 |
+
Iterable,
|
| 5 |
+
List,
|
| 6 |
+
Optional,
|
| 7 |
+
Union,
|
| 8 |
+
overload,
|
| 9 |
+
TypeVar,
|
| 10 |
+
TYPE_CHECKING,
|
| 11 |
+
)
|
| 12 |
+
|
| 13 |
+
if TYPE_CHECKING:
|
| 14 |
+
from .console import (
|
| 15 |
+
Console,
|
| 16 |
+
ConsoleOptions,
|
| 17 |
+
JustifyMethod,
|
| 18 |
+
OverflowMethod,
|
| 19 |
+
RenderResult,
|
| 20 |
+
RenderableType,
|
| 21 |
+
)
|
| 22 |
+
from .text import Text
|
| 23 |
+
|
| 24 |
+
from .cells import cell_len
|
| 25 |
+
from .measure import Measurement
|
| 26 |
+
|
| 27 |
+
T = TypeVar("T")
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class Renderables:
|
| 31 |
+
"""A list subclass which renders its contents to the console."""
|
| 32 |
+
|
| 33 |
+
def __init__(
|
| 34 |
+
self, renderables: Optional[Iterable["RenderableType"]] = None
|
| 35 |
+
) -> None:
|
| 36 |
+
self._renderables: List["RenderableType"] = (
|
| 37 |
+
list(renderables) if renderables is not None else []
|
| 38 |
+
)
|
| 39 |
+
|
| 40 |
+
def __rich_console__(
|
| 41 |
+
self, console: "Console", options: "ConsoleOptions"
|
| 42 |
+
) -> "RenderResult":
|
| 43 |
+
"""Console render method to insert line-breaks."""
|
| 44 |
+
yield from self._renderables
|
| 45 |
+
|
| 46 |
+
def __rich_measure__(
|
| 47 |
+
self, console: "Console", options: "ConsoleOptions"
|
| 48 |
+
) -> "Measurement":
|
| 49 |
+
dimensions = [
|
| 50 |
+
Measurement.get(console, options, renderable)
|
| 51 |
+
for renderable in self._renderables
|
| 52 |
+
]
|
| 53 |
+
if not dimensions:
|
| 54 |
+
return Measurement(1, 1)
|
| 55 |
+
_min = max(dimension.minimum for dimension in dimensions)
|
| 56 |
+
_max = max(dimension.maximum for dimension in dimensions)
|
| 57 |
+
return Measurement(_min, _max)
|
| 58 |
+
|
| 59 |
+
def append(self, renderable: "RenderableType") -> None:
|
| 60 |
+
self._renderables.append(renderable)
|
| 61 |
+
|
| 62 |
+
def __iter__(self) -> Iterable["RenderableType"]:
|
| 63 |
+
return iter(self._renderables)
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
class Lines:
|
| 67 |
+
"""A list subclass which can render to the console."""
|
| 68 |
+
|
| 69 |
+
def __init__(self, lines: Iterable["Text"] = ()) -> None:
|
| 70 |
+
self._lines: List["Text"] = list(lines)
|
| 71 |
+
|
| 72 |
+
def __repr__(self) -> str:
|
| 73 |
+
return f"Lines({self._lines!r})"
|
| 74 |
+
|
| 75 |
+
def __iter__(self) -> Iterator["Text"]:
|
| 76 |
+
return iter(self._lines)
|
| 77 |
+
|
| 78 |
+
@overload
|
| 79 |
+
def __getitem__(self, index: int) -> "Text":
|
| 80 |
+
...
|
| 81 |
+
|
| 82 |
+
@overload
|
| 83 |
+
def __getitem__(self, index: slice) -> List["Text"]:
|
| 84 |
+
...
|
| 85 |
+
|
| 86 |
+
def __getitem__(self, index: Union[slice, int]) -> Union["Text", List["Text"]]:
|
| 87 |
+
return self._lines[index]
|
| 88 |
+
|
| 89 |
+
def __setitem__(self, index: int, value: "Text") -> "Lines":
|
| 90 |
+
self._lines[index] = value
|
| 91 |
+
return self
|
| 92 |
+
|
| 93 |
+
def __len__(self) -> int:
|
| 94 |
+
return self._lines.__len__()
|
| 95 |
+
|
| 96 |
+
def __rich_console__(
|
| 97 |
+
self, console: "Console", options: "ConsoleOptions"
|
| 98 |
+
) -> "RenderResult":
|
| 99 |
+
"""Console render method to insert line-breaks."""
|
| 100 |
+
yield from self._lines
|
| 101 |
+
|
| 102 |
+
def append(self, line: "Text") -> None:
|
| 103 |
+
self._lines.append(line)
|
| 104 |
+
|
| 105 |
+
def extend(self, lines: Iterable["Text"]) -> None:
|
| 106 |
+
self._lines.extend(lines)
|
| 107 |
+
|
| 108 |
+
def pop(self, index: int = -1) -> "Text":
|
| 109 |
+
return self._lines.pop(index)
|
| 110 |
+
|
| 111 |
+
def justify(
|
| 112 |
+
self,
|
| 113 |
+
console: "Console",
|
| 114 |
+
width: int,
|
| 115 |
+
justify: "JustifyMethod" = "left",
|
| 116 |
+
overflow: "OverflowMethod" = "fold",
|
| 117 |
+
) -> None:
|
| 118 |
+
"""Justify and overflow text to a given width.
|
| 119 |
+
|
| 120 |
+
Args:
|
| 121 |
+
console (Console): Console instance.
|
| 122 |
+
width (int): Number of characters per line.
|
| 123 |
+
justify (str, optional): Default justify method for text: "left", "center", "full" or "right". Defaults to "left".
|
| 124 |
+
overflow (str, optional): Default overflow for text: "crop", "fold", or "ellipsis". Defaults to "fold".
|
| 125 |
+
|
| 126 |
+
"""
|
| 127 |
+
from .text import Text
|
| 128 |
+
|
| 129 |
+
if justify == "left":
|
| 130 |
+
for line in self._lines:
|
| 131 |
+
line.truncate(width, overflow=overflow, pad=True)
|
| 132 |
+
elif justify == "center":
|
| 133 |
+
for line in self._lines:
|
| 134 |
+
line.rstrip()
|
| 135 |
+
line.truncate(width, overflow=overflow)
|
| 136 |
+
line.pad_left((width - cell_len(line.plain)) // 2)
|
| 137 |
+
line.pad_right(width - cell_len(line.plain))
|
| 138 |
+
elif justify == "right":
|
| 139 |
+
for line in self._lines:
|
| 140 |
+
line.rstrip()
|
| 141 |
+
line.truncate(width, overflow=overflow)
|
| 142 |
+
line.pad_left(width - cell_len(line.plain))
|
| 143 |
+
elif justify == "full":
|
| 144 |
+
for line_index, line in enumerate(self._lines):
|
| 145 |
+
if line_index == len(self._lines) - 1:
|
| 146 |
+
break
|
| 147 |
+
words = line.split(" ")
|
| 148 |
+
words_size = sum(cell_len(word.plain) for word in words)
|
| 149 |
+
num_spaces = len(words) - 1
|
| 150 |
+
spaces = [1 for _ in range(num_spaces)]
|
| 151 |
+
index = 0
|
| 152 |
+
if spaces:
|
| 153 |
+
while words_size + num_spaces < width:
|
| 154 |
+
spaces[len(spaces) - index - 1] += 1
|
| 155 |
+
num_spaces += 1
|
| 156 |
+
index = (index + 1) % len(spaces)
|
| 157 |
+
tokens: List[Text] = []
|
| 158 |
+
for index, (word, next_word) in enumerate(
|
| 159 |
+
zip_longest(words, words[1:])
|
| 160 |
+
):
|
| 161 |
+
tokens.append(word)
|
| 162 |
+
if index < len(spaces):
|
| 163 |
+
style = word.get_style_at_offset(console, -1)
|
| 164 |
+
next_style = next_word.get_style_at_offset(console, 0)
|
| 165 |
+
space_style = style if style == next_style else line.style
|
| 166 |
+
tokens.append(Text(" " * spaces[index], style=space_style))
|
| 167 |
+
self[line_index] = Text("").join(tokens)
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35/lib/python3.12/site-packages/pip/_vendor/rich/default_styles.py
ADDED
|
@@ -0,0 +1,190 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Dict
|
| 2 |
+
|
| 3 |
+
from .style import Style
|
| 4 |
+
|
| 5 |
+
DEFAULT_STYLES: Dict[str, Style] = {
|
| 6 |
+
"none": Style.null(),
|
| 7 |
+
"reset": Style(
|
| 8 |
+
color="default",
|
| 9 |
+
bgcolor="default",
|
| 10 |
+
dim=False,
|
| 11 |
+
bold=False,
|
| 12 |
+
italic=False,
|
| 13 |
+
underline=False,
|
| 14 |
+
blink=False,
|
| 15 |
+
blink2=False,
|
| 16 |
+
reverse=False,
|
| 17 |
+
conceal=False,
|
| 18 |
+
strike=False,
|
| 19 |
+
),
|
| 20 |
+
"dim": Style(dim=True),
|
| 21 |
+
"bright": Style(dim=False),
|
| 22 |
+
"bold": Style(bold=True),
|
| 23 |
+
"strong": Style(bold=True),
|
| 24 |
+
"code": Style(reverse=True, bold=True),
|
| 25 |
+
"italic": Style(italic=True),
|
| 26 |
+
"emphasize": Style(italic=True),
|
| 27 |
+
"underline": Style(underline=True),
|
| 28 |
+
"blink": Style(blink=True),
|
| 29 |
+
"blink2": Style(blink2=True),
|
| 30 |
+
"reverse": Style(reverse=True),
|
| 31 |
+
"strike": Style(strike=True),
|
| 32 |
+
"black": Style(color="black"),
|
| 33 |
+
"red": Style(color="red"),
|
| 34 |
+
"green": Style(color="green"),
|
| 35 |
+
"yellow": Style(color="yellow"),
|
| 36 |
+
"magenta": Style(color="magenta"),
|
| 37 |
+
"cyan": Style(color="cyan"),
|
| 38 |
+
"white": Style(color="white"),
|
| 39 |
+
"inspect.attr": Style(color="yellow", italic=True),
|
| 40 |
+
"inspect.attr.dunder": Style(color="yellow", italic=True, dim=True),
|
| 41 |
+
"inspect.callable": Style(bold=True, color="red"),
|
| 42 |
+
"inspect.async_def": Style(italic=True, color="bright_cyan"),
|
| 43 |
+
"inspect.def": Style(italic=True, color="bright_cyan"),
|
| 44 |
+
"inspect.class": Style(italic=True, color="bright_cyan"),
|
| 45 |
+
"inspect.error": Style(bold=True, color="red"),
|
| 46 |
+
"inspect.equals": Style(),
|
| 47 |
+
"inspect.help": Style(color="cyan"),
|
| 48 |
+
"inspect.doc": Style(dim=True),
|
| 49 |
+
"inspect.value.border": Style(color="green"),
|
| 50 |
+
"live.ellipsis": Style(bold=True, color="red"),
|
| 51 |
+
"layout.tree.row": Style(dim=False, color="red"),
|
| 52 |
+
"layout.tree.column": Style(dim=False, color="blue"),
|
| 53 |
+
"logging.keyword": Style(bold=True, color="yellow"),
|
| 54 |
+
"logging.level.notset": Style(dim=True),
|
| 55 |
+
"logging.level.debug": Style(color="green"),
|
| 56 |
+
"logging.level.info": Style(color="blue"),
|
| 57 |
+
"logging.level.warning": Style(color="red"),
|
| 58 |
+
"logging.level.error": Style(color="red", bold=True),
|
| 59 |
+
"logging.level.critical": Style(color="red", bold=True, reverse=True),
|
| 60 |
+
"log.level": Style.null(),
|
| 61 |
+
"log.time": Style(color="cyan", dim=True),
|
| 62 |
+
"log.message": Style.null(),
|
| 63 |
+
"log.path": Style(dim=True),
|
| 64 |
+
"repr.ellipsis": Style(color="yellow"),
|
| 65 |
+
"repr.indent": Style(color="green", dim=True),
|
| 66 |
+
"repr.error": Style(color="red", bold=True),
|
| 67 |
+
"repr.str": Style(color="green", italic=False, bold=False),
|
| 68 |
+
"repr.brace": Style(bold=True),
|
| 69 |
+
"repr.comma": Style(bold=True),
|
| 70 |
+
"repr.ipv4": Style(bold=True, color="bright_green"),
|
| 71 |
+
"repr.ipv6": Style(bold=True, color="bright_green"),
|
| 72 |
+
"repr.eui48": Style(bold=True, color="bright_green"),
|
| 73 |
+
"repr.eui64": Style(bold=True, color="bright_green"),
|
| 74 |
+
"repr.tag_start": Style(bold=True),
|
| 75 |
+
"repr.tag_name": Style(color="bright_magenta", bold=True),
|
| 76 |
+
"repr.tag_contents": Style(color="default"),
|
| 77 |
+
"repr.tag_end": Style(bold=True),
|
| 78 |
+
"repr.attrib_name": Style(color="yellow", italic=False),
|
| 79 |
+
"repr.attrib_equal": Style(bold=True),
|
| 80 |
+
"repr.attrib_value": Style(color="magenta", italic=False),
|
| 81 |
+
"repr.number": Style(color="cyan", bold=True, italic=False),
|
| 82 |
+
"repr.number_complex": Style(color="cyan", bold=True, italic=False), # same
|
| 83 |
+
"repr.bool_true": Style(color="bright_green", italic=True),
|
| 84 |
+
"repr.bool_false": Style(color="bright_red", italic=True),
|
| 85 |
+
"repr.none": Style(color="magenta", italic=True),
|
| 86 |
+
"repr.url": Style(underline=True, color="bright_blue", italic=False, bold=False),
|
| 87 |
+
"repr.uuid": Style(color="bright_yellow", bold=False),
|
| 88 |
+
"repr.call": Style(color="magenta", bold=True),
|
| 89 |
+
"repr.path": Style(color="magenta"),
|
| 90 |
+
"repr.filename": Style(color="bright_magenta"),
|
| 91 |
+
"rule.line": Style(color="bright_green"),
|
| 92 |
+
"rule.text": Style.null(),
|
| 93 |
+
"json.brace": Style(bold=True),
|
| 94 |
+
"json.bool_true": Style(color="bright_green", italic=True),
|
| 95 |
+
"json.bool_false": Style(color="bright_red", italic=True),
|
| 96 |
+
"json.null": Style(color="magenta", italic=True),
|
| 97 |
+
"json.number": Style(color="cyan", bold=True, italic=False),
|
| 98 |
+
"json.str": Style(color="green", italic=False, bold=False),
|
| 99 |
+
"json.key": Style(color="blue", bold=True),
|
| 100 |
+
"prompt": Style.null(),
|
| 101 |
+
"prompt.choices": Style(color="magenta", bold=True),
|
| 102 |
+
"prompt.default": Style(color="cyan", bold=True),
|
| 103 |
+
"prompt.invalid": Style(color="red"),
|
| 104 |
+
"prompt.invalid.choice": Style(color="red"),
|
| 105 |
+
"pretty": Style.null(),
|
| 106 |
+
"scope.border": Style(color="blue"),
|
| 107 |
+
"scope.key": Style(color="yellow", italic=True),
|
| 108 |
+
"scope.key.special": Style(color="yellow", italic=True, dim=True),
|
| 109 |
+
"scope.equals": Style(color="red"),
|
| 110 |
+
"table.header": Style(bold=True),
|
| 111 |
+
"table.footer": Style(bold=True),
|
| 112 |
+
"table.cell": Style.null(),
|
| 113 |
+
"table.title": Style(italic=True),
|
| 114 |
+
"table.caption": Style(italic=True, dim=True),
|
| 115 |
+
"traceback.error": Style(color="red", italic=True),
|
| 116 |
+
"traceback.border.syntax_error": Style(color="bright_red"),
|
| 117 |
+
"traceback.border": Style(color="red"),
|
| 118 |
+
"traceback.text": Style.null(),
|
| 119 |
+
"traceback.title": Style(color="red", bold=True),
|
| 120 |
+
"traceback.exc_type": Style(color="bright_red", bold=True),
|
| 121 |
+
"traceback.exc_value": Style.null(),
|
| 122 |
+
"traceback.offset": Style(color="bright_red", bold=True),
|
| 123 |
+
"bar.back": Style(color="grey23"),
|
| 124 |
+
"bar.complete": Style(color="rgb(249,38,114)"),
|
| 125 |
+
"bar.finished": Style(color="rgb(114,156,31)"),
|
| 126 |
+
"bar.pulse": Style(color="rgb(249,38,114)"),
|
| 127 |
+
"progress.description": Style.null(),
|
| 128 |
+
"progress.filesize": Style(color="green"),
|
| 129 |
+
"progress.filesize.total": Style(color="green"),
|
| 130 |
+
"progress.download": Style(color="green"),
|
| 131 |
+
"progress.elapsed": Style(color="yellow"),
|
| 132 |
+
"progress.percentage": Style(color="magenta"),
|
| 133 |
+
"progress.remaining": Style(color="cyan"),
|
| 134 |
+
"progress.data.speed": Style(color="red"),
|
| 135 |
+
"progress.spinner": Style(color="green"),
|
| 136 |
+
"status.spinner": Style(color="green"),
|
| 137 |
+
"tree": Style(),
|
| 138 |
+
"tree.line": Style(),
|
| 139 |
+
"markdown.paragraph": Style(),
|
| 140 |
+
"markdown.text": Style(),
|
| 141 |
+
"markdown.em": Style(italic=True),
|
| 142 |
+
"markdown.emph": Style(italic=True), # For commonmark backwards compatibility
|
| 143 |
+
"markdown.strong": Style(bold=True),
|
| 144 |
+
"markdown.code": Style(bold=True, color="cyan", bgcolor="black"),
|
| 145 |
+
"markdown.code_block": Style(color="cyan", bgcolor="black"),
|
| 146 |
+
"markdown.block_quote": Style(color="magenta"),
|
| 147 |
+
"markdown.list": Style(color="cyan"),
|
| 148 |
+
"markdown.item": Style(),
|
| 149 |
+
"markdown.item.bullet": Style(color="yellow", bold=True),
|
| 150 |
+
"markdown.item.number": Style(color="yellow", bold=True),
|
| 151 |
+
"markdown.hr": Style(color="yellow"),
|
| 152 |
+
"markdown.h1.border": Style(),
|
| 153 |
+
"markdown.h1": Style(bold=True),
|
| 154 |
+
"markdown.h2": Style(bold=True, underline=True),
|
| 155 |
+
"markdown.h3": Style(bold=True),
|
| 156 |
+
"markdown.h4": Style(bold=True, dim=True),
|
| 157 |
+
"markdown.h5": Style(underline=True),
|
| 158 |
+
"markdown.h6": Style(italic=True),
|
| 159 |
+
"markdown.h7": Style(italic=True, dim=True),
|
| 160 |
+
"markdown.link": Style(color="bright_blue"),
|
| 161 |
+
"markdown.link_url": Style(color="blue", underline=True),
|
| 162 |
+
"markdown.s": Style(strike=True),
|
| 163 |
+
"iso8601.date": Style(color="blue"),
|
| 164 |
+
"iso8601.time": Style(color="magenta"),
|
| 165 |
+
"iso8601.timezone": Style(color="yellow"),
|
| 166 |
+
}
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
if __name__ == "__main__": # pragma: no cover
|
| 170 |
+
import argparse
|
| 171 |
+
import io
|
| 172 |
+
|
| 173 |
+
from pip._vendor.rich.console import Console
|
| 174 |
+
from pip._vendor.rich.table import Table
|
| 175 |
+
from pip._vendor.rich.text import Text
|
| 176 |
+
|
| 177 |
+
parser = argparse.ArgumentParser()
|
| 178 |
+
parser.add_argument("--html", action="store_true", help="Export as HTML table")
|
| 179 |
+
args = parser.parse_args()
|
| 180 |
+
html: bool = args.html
|
| 181 |
+
console = Console(record=True, width=70, file=io.StringIO()) if html else Console()
|
| 182 |
+
|
| 183 |
+
table = Table("Name", "Styling")
|
| 184 |
+
|
| 185 |
+
for style_name, style in DEFAULT_STYLES.items():
|
| 186 |
+
table.add_row(Text(style_name, style=style), str(style))
|
| 187 |
+
|
| 188 |
+
console.print(table)
|
| 189 |
+
if html:
|
| 190 |
+
print(console.export_html(inline_styles=True))
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35/lib/python3.12/site-packages/pip/_vendor/rich/highlighter.py
ADDED
|
@@ -0,0 +1,232 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import re
|
| 2 |
+
from abc import ABC, abstractmethod
|
| 3 |
+
from typing import List, Union
|
| 4 |
+
|
| 5 |
+
from .text import Span, Text
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def _combine_regex(*regexes: str) -> str:
|
| 9 |
+
"""Combine a number of regexes in to a single regex.
|
| 10 |
+
|
| 11 |
+
Returns:
|
| 12 |
+
str: New regex with all regexes ORed together.
|
| 13 |
+
"""
|
| 14 |
+
return "|".join(regexes)
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class Highlighter(ABC):
|
| 18 |
+
"""Abstract base class for highlighters."""
|
| 19 |
+
|
| 20 |
+
def __call__(self, text: Union[str, Text]) -> Text:
|
| 21 |
+
"""Highlight a str or Text instance.
|
| 22 |
+
|
| 23 |
+
Args:
|
| 24 |
+
text (Union[str, ~Text]): Text to highlight.
|
| 25 |
+
|
| 26 |
+
Raises:
|
| 27 |
+
TypeError: If not called with text or str.
|
| 28 |
+
|
| 29 |
+
Returns:
|
| 30 |
+
Text: A test instance with highlighting applied.
|
| 31 |
+
"""
|
| 32 |
+
if isinstance(text, str):
|
| 33 |
+
highlight_text = Text(text)
|
| 34 |
+
elif isinstance(text, Text):
|
| 35 |
+
highlight_text = text.copy()
|
| 36 |
+
else:
|
| 37 |
+
raise TypeError(f"str or Text instance required, not {text!r}")
|
| 38 |
+
self.highlight(highlight_text)
|
| 39 |
+
return highlight_text
|
| 40 |
+
|
| 41 |
+
@abstractmethod
|
| 42 |
+
def highlight(self, text: Text) -> None:
|
| 43 |
+
"""Apply highlighting in place to text.
|
| 44 |
+
|
| 45 |
+
Args:
|
| 46 |
+
text (~Text): A text object highlight.
|
| 47 |
+
"""
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
class NullHighlighter(Highlighter):
|
| 51 |
+
"""A highlighter object that doesn't highlight.
|
| 52 |
+
|
| 53 |
+
May be used to disable highlighting entirely.
|
| 54 |
+
|
| 55 |
+
"""
|
| 56 |
+
|
| 57 |
+
def highlight(self, text: Text) -> None:
|
| 58 |
+
"""Nothing to do"""
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
class RegexHighlighter(Highlighter):
|
| 62 |
+
"""Applies highlighting from a list of regular expressions."""
|
| 63 |
+
|
| 64 |
+
highlights: List[str] = []
|
| 65 |
+
base_style: str = ""
|
| 66 |
+
|
| 67 |
+
def highlight(self, text: Text) -> None:
|
| 68 |
+
"""Highlight :class:`rich.text.Text` using regular expressions.
|
| 69 |
+
|
| 70 |
+
Args:
|
| 71 |
+
text (~Text): Text to highlighted.
|
| 72 |
+
|
| 73 |
+
"""
|
| 74 |
+
|
| 75 |
+
highlight_regex = text.highlight_regex
|
| 76 |
+
for re_highlight in self.highlights:
|
| 77 |
+
highlight_regex(re_highlight, style_prefix=self.base_style)
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
class ReprHighlighter(RegexHighlighter):
|
| 81 |
+
"""Highlights the text typically produced from ``__repr__`` methods."""
|
| 82 |
+
|
| 83 |
+
base_style = "repr."
|
| 84 |
+
highlights = [
|
| 85 |
+
r"(?P<tag_start><)(?P<tag_name>[-\w.:|]*)(?P<tag_contents>[\w\W]*)(?P<tag_end>>)",
|
| 86 |
+
r'(?P<attrib_name>[\w_]{1,50})=(?P<attrib_value>"?[\w_]+"?)?',
|
| 87 |
+
r"(?P<brace>[][{}()])",
|
| 88 |
+
_combine_regex(
|
| 89 |
+
r"(?P<ipv4>[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})",
|
| 90 |
+
r"(?P<ipv6>([A-Fa-f0-9]{1,4}::?){1,7}[A-Fa-f0-9]{1,4})",
|
| 91 |
+
r"(?P<eui64>(?:[0-9A-Fa-f]{1,2}-){7}[0-9A-Fa-f]{1,2}|(?:[0-9A-Fa-f]{1,2}:){7}[0-9A-Fa-f]{1,2}|(?:[0-9A-Fa-f]{4}\.){3}[0-9A-Fa-f]{4})",
|
| 92 |
+
r"(?P<eui48>(?:[0-9A-Fa-f]{1,2}-){5}[0-9A-Fa-f]{1,2}|(?:[0-9A-Fa-f]{1,2}:){5}[0-9A-Fa-f]{1,2}|(?:[0-9A-Fa-f]{4}\.){2}[0-9A-Fa-f]{4})",
|
| 93 |
+
r"(?P<uuid>[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12})",
|
| 94 |
+
r"(?P<call>[\w.]*?)\(",
|
| 95 |
+
r"\b(?P<bool_true>True)\b|\b(?P<bool_false>False)\b|\b(?P<none>None)\b",
|
| 96 |
+
r"(?P<ellipsis>\.\.\.)",
|
| 97 |
+
r"(?P<number_complex>(?<!\w)(?:\-?[0-9]+\.?[0-9]*(?:e[-+]?\d+?)?)(?:[-+](?:[0-9]+\.?[0-9]*(?:e[-+]?\d+)?))?j)",
|
| 98 |
+
r"(?P<number>(?<!\w)\-?[0-9]+\.?[0-9]*(e[-+]?\d+?)?\b|0x[0-9a-fA-F]*)",
|
| 99 |
+
r"(?P<path>\B(/[-\w._+]+)*\/)(?P<filename>[-\w._+]*)?",
|
| 100 |
+
r"(?<![\\\w])(?P<str>b?'''.*?(?<!\\)'''|b?'.*?(?<!\\)'|b?\"\"\".*?(?<!\\)\"\"\"|b?\".*?(?<!\\)\")",
|
| 101 |
+
r"(?P<url>(file|https|http|ws|wss)://[-0-9a-zA-Z$_+!`(),.?/;:&=%#]*)",
|
| 102 |
+
),
|
| 103 |
+
]
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
class JSONHighlighter(RegexHighlighter):
|
| 107 |
+
"""Highlights JSON"""
|
| 108 |
+
|
| 109 |
+
# Captures the start and end of JSON strings, handling escaped quotes
|
| 110 |
+
JSON_STR = r"(?<![\\\w])(?P<str>b?\".*?(?<!\\)\")"
|
| 111 |
+
JSON_WHITESPACE = {" ", "\n", "\r", "\t"}
|
| 112 |
+
|
| 113 |
+
base_style = "json."
|
| 114 |
+
highlights = [
|
| 115 |
+
_combine_regex(
|
| 116 |
+
r"(?P<brace>[\{\[\(\)\]\}])",
|
| 117 |
+
r"\b(?P<bool_true>true)\b|\b(?P<bool_false>false)\b|\b(?P<null>null)\b",
|
| 118 |
+
r"(?P<number>(?<!\w)\-?[0-9]+\.?[0-9]*(e[\-\+]?\d+?)?\b|0x[0-9a-fA-F]*)",
|
| 119 |
+
JSON_STR,
|
| 120 |
+
),
|
| 121 |
+
]
|
| 122 |
+
|
| 123 |
+
def highlight(self, text: Text) -> None:
|
| 124 |
+
super().highlight(text)
|
| 125 |
+
|
| 126 |
+
# Additional work to handle highlighting JSON keys
|
| 127 |
+
plain = text.plain
|
| 128 |
+
append = text.spans.append
|
| 129 |
+
whitespace = self.JSON_WHITESPACE
|
| 130 |
+
for match in re.finditer(self.JSON_STR, plain):
|
| 131 |
+
start, end = match.span()
|
| 132 |
+
cursor = end
|
| 133 |
+
while cursor < len(plain):
|
| 134 |
+
char = plain[cursor]
|
| 135 |
+
cursor += 1
|
| 136 |
+
if char == ":":
|
| 137 |
+
append(Span(start, end, "json.key"))
|
| 138 |
+
elif char in whitespace:
|
| 139 |
+
continue
|
| 140 |
+
break
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
class ISO8601Highlighter(RegexHighlighter):
|
| 144 |
+
"""Highlights the ISO8601 date time strings.
|
| 145 |
+
Regex reference: https://www.oreilly.com/library/view/regular-expressions-cookbook/9781449327453/ch04s07.html
|
| 146 |
+
"""
|
| 147 |
+
|
| 148 |
+
base_style = "iso8601."
|
| 149 |
+
highlights = [
|
| 150 |
+
#
|
| 151 |
+
# Dates
|
| 152 |
+
#
|
| 153 |
+
# Calendar month (e.g. 2008-08). The hyphen is required
|
| 154 |
+
r"^(?P<year>[0-9]{4})-(?P<month>1[0-2]|0[1-9])$",
|
| 155 |
+
# Calendar date w/o hyphens (e.g. 20080830)
|
| 156 |
+
r"^(?P<date>(?P<year>[0-9]{4})(?P<month>1[0-2]|0[1-9])(?P<day>3[01]|0[1-9]|[12][0-9]))$",
|
| 157 |
+
# Ordinal date (e.g. 2008-243). The hyphen is optional
|
| 158 |
+
r"^(?P<date>(?P<year>[0-9]{4})-?(?P<day>36[0-6]|3[0-5][0-9]|[12][0-9]{2}|0[1-9][0-9]|00[1-9]))$",
|
| 159 |
+
#
|
| 160 |
+
# Weeks
|
| 161 |
+
#
|
| 162 |
+
# Week of the year (e.g., 2008-W35). The hyphen is optional
|
| 163 |
+
r"^(?P<date>(?P<year>[0-9]{4})-?W(?P<week>5[0-3]|[1-4][0-9]|0[1-9]))$",
|
| 164 |
+
# Week date (e.g., 2008-W35-6). The hyphens are optional
|
| 165 |
+
r"^(?P<date>(?P<year>[0-9]{4})-?W(?P<week>5[0-3]|[1-4][0-9]|0[1-9])-?(?P<day>[1-7]))$",
|
| 166 |
+
#
|
| 167 |
+
# Times
|
| 168 |
+
#
|
| 169 |
+
# Hours and minutes (e.g., 17:21). The colon is optional
|
| 170 |
+
r"^(?P<time>(?P<hour>2[0-3]|[01][0-9]):?(?P<minute>[0-5][0-9]))$",
|
| 171 |
+
# Hours, minutes, and seconds w/o colons (e.g., 172159)
|
| 172 |
+
r"^(?P<time>(?P<hour>2[0-3]|[01][0-9])(?P<minute>[0-5][0-9])(?P<second>[0-5][0-9]))$",
|
| 173 |
+
# Time zone designator (e.g., Z, +07 or +07:00). The colons and the minutes are optional
|
| 174 |
+
r"^(?P<timezone>(Z|[+-](?:2[0-3]|[01][0-9])(?::?(?:[0-5][0-9]))?))$",
|
| 175 |
+
# Hours, minutes, and seconds with time zone designator (e.g., 17:21:59+07:00).
|
| 176 |
+
# All the colons are optional. The minutes in the time zone designator are also optional
|
| 177 |
+
r"^(?P<time>(?P<hour>2[0-3]|[01][0-9])(?P<minute>[0-5][0-9])(?P<second>[0-5][0-9]))(?P<timezone>Z|[+-](?:2[0-3]|[01][0-9])(?::?(?:[0-5][0-9]))?)$",
|
| 178 |
+
#
|
| 179 |
+
# Date and Time
|
| 180 |
+
#
|
| 181 |
+
# Calendar date with hours, minutes, and seconds (e.g., 2008-08-30 17:21:59 or 20080830 172159).
|
| 182 |
+
# A space is required between the date and the time. The hyphens and colons are optional.
|
| 183 |
+
# This regex matches dates and times that specify some hyphens or colons but omit others.
|
| 184 |
+
# This does not follow ISO 8601
|
| 185 |
+
r"^(?P<date>(?P<year>[0-9]{4})(?P<hyphen>-)?(?P<month>1[0-2]|0[1-9])(?(hyphen)-)(?P<day>3[01]|0[1-9]|[12][0-9])) (?P<time>(?P<hour>2[0-3]|[01][0-9])(?(hyphen):)(?P<minute>[0-5][0-9])(?(hyphen):)(?P<second>[0-5][0-9]))$",
|
| 186 |
+
#
|
| 187 |
+
# XML Schema dates and times
|
| 188 |
+
#
|
| 189 |
+
# Date, with optional time zone (e.g., 2008-08-30 or 2008-08-30+07:00).
|
| 190 |
+
# Hyphens are required. This is the XML Schema 'date' type
|
| 191 |
+
r"^(?P<date>(?P<year>-?(?:[1-9][0-9]*)?[0-9]{4})-(?P<month>1[0-2]|0[1-9])-(?P<day>3[01]|0[1-9]|[12][0-9]))(?P<timezone>Z|[+-](?:2[0-3]|[01][0-9]):[0-5][0-9])?$",
|
| 192 |
+
# Time, with optional fractional seconds and time zone (e.g., 01:45:36 or 01:45:36.123+07:00).
|
| 193 |
+
# There is no limit on the number of digits for the fractional seconds. This is the XML Schema 'time' type
|
| 194 |
+
r"^(?P<time>(?P<hour>2[0-3]|[01][0-9]):(?P<minute>[0-5][0-9]):(?P<second>[0-5][0-9])(?P<frac>\.[0-9]+)?)(?P<timezone>Z|[+-](?:2[0-3]|[01][0-9]):[0-5][0-9])?$",
|
| 195 |
+
# Date and time, with optional fractional seconds and time zone (e.g., 2008-08-30T01:45:36 or 2008-08-30T01:45:36.123Z).
|
| 196 |
+
# This is the XML Schema 'dateTime' type
|
| 197 |
+
r"^(?P<date>(?P<year>-?(?:[1-9][0-9]*)?[0-9]{4})-(?P<month>1[0-2]|0[1-9])-(?P<day>3[01]|0[1-9]|[12][0-9]))T(?P<time>(?P<hour>2[0-3]|[01][0-9]):(?P<minute>[0-5][0-9]):(?P<second>[0-5][0-9])(?P<ms>\.[0-9]+)?)(?P<timezone>Z|[+-](?:2[0-3]|[01][0-9]):[0-5][0-9])?$",
|
| 198 |
+
]
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
if __name__ == "__main__": # pragma: no cover
|
| 202 |
+
from .console import Console
|
| 203 |
+
|
| 204 |
+
console = Console()
|
| 205 |
+
console.print("[bold green]hello world![/bold green]")
|
| 206 |
+
console.print("'[bold green]hello world![/bold green]'")
|
| 207 |
+
|
| 208 |
+
console.print(" /foo")
|
| 209 |
+
console.print("/foo/")
|
| 210 |
+
console.print("/foo/bar")
|
| 211 |
+
console.print("foo/bar/baz")
|
| 212 |
+
|
| 213 |
+
console.print("/foo/bar/baz?foo=bar+egg&egg=baz")
|
| 214 |
+
console.print("/foo/bar/baz/")
|
| 215 |
+
console.print("/foo/bar/baz/egg")
|
| 216 |
+
console.print("/foo/bar/baz/egg.py")
|
| 217 |
+
console.print("/foo/bar/baz/egg.py word")
|
| 218 |
+
console.print(" /foo/bar/baz/egg.py word")
|
| 219 |
+
console.print("foo /foo/bar/baz/egg.py word")
|
| 220 |
+
console.print("foo /foo/bar/ba._++z/egg+.py word")
|
| 221 |
+
console.print("https://example.org?foo=bar#header")
|
| 222 |
+
|
| 223 |
+
console.print(1234567.34)
|
| 224 |
+
console.print(1 / 2)
|
| 225 |
+
console.print(-1 / 123123123123)
|
| 226 |
+
|
| 227 |
+
console.print(
|
| 228 |
+
"127.0.1.1 bar 192.168.1.4 2001:0db8:85a3:0000:0000:8a2e:0370:7334 foo"
|
| 229 |
+
)
|
| 230 |
+
import json
|
| 231 |
+
|
| 232 |
+
console.print_json(json.dumps(obj={"name": "apple", "count": 1}), indent=None)
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35/lib/python3.12/site-packages/pip/_vendor/rich/json.py
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pathlib import Path
|
| 2 |
+
from json import loads, dumps
|
| 3 |
+
from typing import Any, Callable, Optional, Union
|
| 4 |
+
|
| 5 |
+
from .text import Text
|
| 6 |
+
from .highlighter import JSONHighlighter, NullHighlighter
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class JSON:
|
| 10 |
+
"""A renderable which pretty prints JSON.
|
| 11 |
+
|
| 12 |
+
Args:
|
| 13 |
+
json (str): JSON encoded data.
|
| 14 |
+
indent (Union[None, int, str], optional): Number of characters to indent by. Defaults to 2.
|
| 15 |
+
highlight (bool, optional): Enable highlighting. Defaults to True.
|
| 16 |
+
skip_keys (bool, optional): Skip keys not of a basic type. Defaults to False.
|
| 17 |
+
ensure_ascii (bool, optional): Escape all non-ascii characters. Defaults to False.
|
| 18 |
+
check_circular (bool, optional): Check for circular references. Defaults to True.
|
| 19 |
+
allow_nan (bool, optional): Allow NaN and Infinity values. Defaults to True.
|
| 20 |
+
default (Callable, optional): A callable that converts values that can not be encoded
|
| 21 |
+
in to something that can be JSON encoded. Defaults to None.
|
| 22 |
+
sort_keys (bool, optional): Sort dictionary keys. Defaults to False.
|
| 23 |
+
"""
|
| 24 |
+
|
| 25 |
+
def __init__(
|
| 26 |
+
self,
|
| 27 |
+
json: str,
|
| 28 |
+
indent: Union[None, int, str] = 2,
|
| 29 |
+
highlight: bool = True,
|
| 30 |
+
skip_keys: bool = False,
|
| 31 |
+
ensure_ascii: bool = False,
|
| 32 |
+
check_circular: bool = True,
|
| 33 |
+
allow_nan: bool = True,
|
| 34 |
+
default: Optional[Callable[[Any], Any]] = None,
|
| 35 |
+
sort_keys: bool = False,
|
| 36 |
+
) -> None:
|
| 37 |
+
data = loads(json)
|
| 38 |
+
json = dumps(
|
| 39 |
+
data,
|
| 40 |
+
indent=indent,
|
| 41 |
+
skipkeys=skip_keys,
|
| 42 |
+
ensure_ascii=ensure_ascii,
|
| 43 |
+
check_circular=check_circular,
|
| 44 |
+
allow_nan=allow_nan,
|
| 45 |
+
default=default,
|
| 46 |
+
sort_keys=sort_keys,
|
| 47 |
+
)
|
| 48 |
+
highlighter = JSONHighlighter() if highlight else NullHighlighter()
|
| 49 |
+
self.text = highlighter(json)
|
| 50 |
+
self.text.no_wrap = True
|
| 51 |
+
self.text.overflow = None
|
| 52 |
+
|
| 53 |
+
@classmethod
|
| 54 |
+
def from_data(
|
| 55 |
+
cls,
|
| 56 |
+
data: Any,
|
| 57 |
+
indent: Union[None, int, str] = 2,
|
| 58 |
+
highlight: bool = True,
|
| 59 |
+
skip_keys: bool = False,
|
| 60 |
+
ensure_ascii: bool = False,
|
| 61 |
+
check_circular: bool = True,
|
| 62 |
+
allow_nan: bool = True,
|
| 63 |
+
default: Optional[Callable[[Any], Any]] = None,
|
| 64 |
+
sort_keys: bool = False,
|
| 65 |
+
) -> "JSON":
|
| 66 |
+
"""Encodes a JSON object from arbitrary data.
|
| 67 |
+
|
| 68 |
+
Args:
|
| 69 |
+
data (Any): An object that may be encoded in to JSON
|
| 70 |
+
indent (Union[None, int, str], optional): Number of characters to indent by. Defaults to 2.
|
| 71 |
+
highlight (bool, optional): Enable highlighting. Defaults to True.
|
| 72 |
+
default (Callable, optional): Optional callable which will be called for objects that cannot be serialized. Defaults to None.
|
| 73 |
+
skip_keys (bool, optional): Skip keys not of a basic type. Defaults to False.
|
| 74 |
+
ensure_ascii (bool, optional): Escape all non-ascii characters. Defaults to False.
|
| 75 |
+
check_circular (bool, optional): Check for circular references. Defaults to True.
|
| 76 |
+
allow_nan (bool, optional): Allow NaN and Infinity values. Defaults to True.
|
| 77 |
+
default (Callable, optional): A callable that converts values that can not be encoded
|
| 78 |
+
in to something that can be JSON encoded. Defaults to None.
|
| 79 |
+
sort_keys (bool, optional): Sort dictionary keys. Defaults to False.
|
| 80 |
+
|
| 81 |
+
Returns:
|
| 82 |
+
JSON: New JSON object from the given data.
|
| 83 |
+
"""
|
| 84 |
+
json_instance: "JSON" = cls.__new__(cls)
|
| 85 |
+
json = dumps(
|
| 86 |
+
data,
|
| 87 |
+
indent=indent,
|
| 88 |
+
skipkeys=skip_keys,
|
| 89 |
+
ensure_ascii=ensure_ascii,
|
| 90 |
+
check_circular=check_circular,
|
| 91 |
+
allow_nan=allow_nan,
|
| 92 |
+
default=default,
|
| 93 |
+
sort_keys=sort_keys,
|
| 94 |
+
)
|
| 95 |
+
highlighter = JSONHighlighter() if highlight else NullHighlighter()
|
| 96 |
+
json_instance.text = highlighter(json)
|
| 97 |
+
json_instance.text.no_wrap = True
|
| 98 |
+
json_instance.text.overflow = None
|
| 99 |
+
return json_instance
|
| 100 |
+
|
| 101 |
+
def __rich__(self) -> Text:
|
| 102 |
+
return self.text
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
if __name__ == "__main__":
|
| 106 |
+
|
| 107 |
+
import argparse
|
| 108 |
+
import sys
|
| 109 |
+
|
| 110 |
+
parser = argparse.ArgumentParser(description="Pretty print json")
|
| 111 |
+
parser.add_argument(
|
| 112 |
+
"path",
|
| 113 |
+
metavar="PATH",
|
| 114 |
+
help="path to file, or - for stdin",
|
| 115 |
+
)
|
| 116 |
+
parser.add_argument(
|
| 117 |
+
"-i",
|
| 118 |
+
"--indent",
|
| 119 |
+
metavar="SPACES",
|
| 120 |
+
type=int,
|
| 121 |
+
help="Number of spaces in an indent",
|
| 122 |
+
default=2,
|
| 123 |
+
)
|
| 124 |
+
args = parser.parse_args()
|
| 125 |
+
|
| 126 |
+
from pip._vendor.rich.console import Console
|
| 127 |
+
|
| 128 |
+
console = Console()
|
| 129 |
+
error_console = Console(stderr=True)
|
| 130 |
+
|
| 131 |
+
try:
|
| 132 |
+
if args.path == "-":
|
| 133 |
+
json_data = sys.stdin.read()
|
| 134 |
+
else:
|
| 135 |
+
json_data = Path(args.path).read_text()
|
| 136 |
+
except Exception as error:
|
| 137 |
+
error_console.print(f"Unable to read {args.path!r}; {error}")
|
| 138 |
+
sys.exit(-1)
|
| 139 |
+
|
| 140 |
+
console.print(JSON(json_data, indent=args.indent), soft_wrap=True)
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35/lib/python3.12/site-packages/pip/_vendor/rich/live.py
ADDED
|
@@ -0,0 +1,375 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sys
|
| 2 |
+
from threading import Event, RLock, Thread
|
| 3 |
+
from types import TracebackType
|
| 4 |
+
from typing import IO, Any, Callable, List, Optional, TextIO, Type, cast
|
| 5 |
+
|
| 6 |
+
from . import get_console
|
| 7 |
+
from .console import Console, ConsoleRenderable, RenderableType, RenderHook
|
| 8 |
+
from .control import Control
|
| 9 |
+
from .file_proxy import FileProxy
|
| 10 |
+
from .jupyter import JupyterMixin
|
| 11 |
+
from .live_render import LiveRender, VerticalOverflowMethod
|
| 12 |
+
from .screen import Screen
|
| 13 |
+
from .text import Text
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class _RefreshThread(Thread):
|
| 17 |
+
"""A thread that calls refresh() at regular intervals."""
|
| 18 |
+
|
| 19 |
+
def __init__(self, live: "Live", refresh_per_second: float) -> None:
|
| 20 |
+
self.live = live
|
| 21 |
+
self.refresh_per_second = refresh_per_second
|
| 22 |
+
self.done = Event()
|
| 23 |
+
super().__init__(daemon=True)
|
| 24 |
+
|
| 25 |
+
def stop(self) -> None:
|
| 26 |
+
self.done.set()
|
| 27 |
+
|
| 28 |
+
def run(self) -> None:
|
| 29 |
+
while not self.done.wait(1 / self.refresh_per_second):
|
| 30 |
+
with self.live._lock:
|
| 31 |
+
if not self.done.is_set():
|
| 32 |
+
self.live.refresh()
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class Live(JupyterMixin, RenderHook):
|
| 36 |
+
"""Renders an auto-updating live display of any given renderable.
|
| 37 |
+
|
| 38 |
+
Args:
|
| 39 |
+
renderable (RenderableType, optional): The renderable to live display. Defaults to displaying nothing.
|
| 40 |
+
console (Console, optional): Optional Console instance. Default will an internal Console instance writing to stdout.
|
| 41 |
+
screen (bool, optional): Enable alternate screen mode. Defaults to False.
|
| 42 |
+
auto_refresh (bool, optional): Enable auto refresh. If disabled, you will need to call `refresh()` or `update()` with refresh flag. Defaults to True
|
| 43 |
+
refresh_per_second (float, optional): Number of times per second to refresh the live display. Defaults to 4.
|
| 44 |
+
transient (bool, optional): Clear the renderable on exit (has no effect when screen=True). Defaults to False.
|
| 45 |
+
redirect_stdout (bool, optional): Enable redirection of stdout, so ``print`` may be used. Defaults to True.
|
| 46 |
+
redirect_stderr (bool, optional): Enable redirection of stderr. Defaults to True.
|
| 47 |
+
vertical_overflow (VerticalOverflowMethod, optional): How to handle renderable when it is too tall for the console. Defaults to "ellipsis".
|
| 48 |
+
get_renderable (Callable[[], RenderableType], optional): Optional callable to get renderable. Defaults to None.
|
| 49 |
+
"""
|
| 50 |
+
|
| 51 |
+
def __init__(
|
| 52 |
+
self,
|
| 53 |
+
renderable: Optional[RenderableType] = None,
|
| 54 |
+
*,
|
| 55 |
+
console: Optional[Console] = None,
|
| 56 |
+
screen: bool = False,
|
| 57 |
+
auto_refresh: bool = True,
|
| 58 |
+
refresh_per_second: float = 4,
|
| 59 |
+
transient: bool = False,
|
| 60 |
+
redirect_stdout: bool = True,
|
| 61 |
+
redirect_stderr: bool = True,
|
| 62 |
+
vertical_overflow: VerticalOverflowMethod = "ellipsis",
|
| 63 |
+
get_renderable: Optional[Callable[[], RenderableType]] = None,
|
| 64 |
+
) -> None:
|
| 65 |
+
assert refresh_per_second > 0, "refresh_per_second must be > 0"
|
| 66 |
+
self._renderable = renderable
|
| 67 |
+
self.console = console if console is not None else get_console()
|
| 68 |
+
self._screen = screen
|
| 69 |
+
self._alt_screen = False
|
| 70 |
+
|
| 71 |
+
self._redirect_stdout = redirect_stdout
|
| 72 |
+
self._redirect_stderr = redirect_stderr
|
| 73 |
+
self._restore_stdout: Optional[IO[str]] = None
|
| 74 |
+
self._restore_stderr: Optional[IO[str]] = None
|
| 75 |
+
|
| 76 |
+
self._lock = RLock()
|
| 77 |
+
self.ipy_widget: Optional[Any] = None
|
| 78 |
+
self.auto_refresh = auto_refresh
|
| 79 |
+
self._started: bool = False
|
| 80 |
+
self.transient = True if screen else transient
|
| 81 |
+
|
| 82 |
+
self._refresh_thread: Optional[_RefreshThread] = None
|
| 83 |
+
self.refresh_per_second = refresh_per_second
|
| 84 |
+
|
| 85 |
+
self.vertical_overflow = vertical_overflow
|
| 86 |
+
self._get_renderable = get_renderable
|
| 87 |
+
self._live_render = LiveRender(
|
| 88 |
+
self.get_renderable(), vertical_overflow=vertical_overflow
|
| 89 |
+
)
|
| 90 |
+
|
| 91 |
+
@property
|
| 92 |
+
def is_started(self) -> bool:
|
| 93 |
+
"""Check if live display has been started."""
|
| 94 |
+
return self._started
|
| 95 |
+
|
| 96 |
+
def get_renderable(self) -> RenderableType:
|
| 97 |
+
renderable = (
|
| 98 |
+
self._get_renderable()
|
| 99 |
+
if self._get_renderable is not None
|
| 100 |
+
else self._renderable
|
| 101 |
+
)
|
| 102 |
+
return renderable or ""
|
| 103 |
+
|
| 104 |
+
def start(self, refresh: bool = False) -> None:
|
| 105 |
+
"""Start live rendering display.
|
| 106 |
+
|
| 107 |
+
Args:
|
| 108 |
+
refresh (bool, optional): Also refresh. Defaults to False.
|
| 109 |
+
"""
|
| 110 |
+
with self._lock:
|
| 111 |
+
if self._started:
|
| 112 |
+
return
|
| 113 |
+
self.console.set_live(self)
|
| 114 |
+
self._started = True
|
| 115 |
+
if self._screen:
|
| 116 |
+
self._alt_screen = self.console.set_alt_screen(True)
|
| 117 |
+
self.console.show_cursor(False)
|
| 118 |
+
self._enable_redirect_io()
|
| 119 |
+
self.console.push_render_hook(self)
|
| 120 |
+
if refresh:
|
| 121 |
+
try:
|
| 122 |
+
self.refresh()
|
| 123 |
+
except Exception:
|
| 124 |
+
# If refresh fails, we want to stop the redirection of sys.stderr,
|
| 125 |
+
# so the error stacktrace is properly displayed in the terminal.
|
| 126 |
+
# (or, if the code that calls Rich captures the exception and wants to display something,
|
| 127 |
+
# let this be displayed in the terminal).
|
| 128 |
+
self.stop()
|
| 129 |
+
raise
|
| 130 |
+
if self.auto_refresh:
|
| 131 |
+
self._refresh_thread = _RefreshThread(self, self.refresh_per_second)
|
| 132 |
+
self._refresh_thread.start()
|
| 133 |
+
|
| 134 |
+
def stop(self) -> None:
|
| 135 |
+
"""Stop live rendering display."""
|
| 136 |
+
with self._lock:
|
| 137 |
+
if not self._started:
|
| 138 |
+
return
|
| 139 |
+
self.console.clear_live()
|
| 140 |
+
self._started = False
|
| 141 |
+
|
| 142 |
+
if self.auto_refresh and self._refresh_thread is not None:
|
| 143 |
+
self._refresh_thread.stop()
|
| 144 |
+
self._refresh_thread = None
|
| 145 |
+
# allow it to fully render on the last even if overflow
|
| 146 |
+
self.vertical_overflow = "visible"
|
| 147 |
+
with self.console:
|
| 148 |
+
try:
|
| 149 |
+
if not self._alt_screen and not self.console.is_jupyter:
|
| 150 |
+
self.refresh()
|
| 151 |
+
finally:
|
| 152 |
+
self._disable_redirect_io()
|
| 153 |
+
self.console.pop_render_hook()
|
| 154 |
+
if not self._alt_screen and self.console.is_terminal:
|
| 155 |
+
self.console.line()
|
| 156 |
+
self.console.show_cursor(True)
|
| 157 |
+
if self._alt_screen:
|
| 158 |
+
self.console.set_alt_screen(False)
|
| 159 |
+
|
| 160 |
+
if self.transient and not self._alt_screen:
|
| 161 |
+
self.console.control(self._live_render.restore_cursor())
|
| 162 |
+
if self.ipy_widget is not None and self.transient:
|
| 163 |
+
self.ipy_widget.close() # pragma: no cover
|
| 164 |
+
|
| 165 |
+
def __enter__(self) -> "Live":
|
| 166 |
+
self.start(refresh=self._renderable is not None)
|
| 167 |
+
return self
|
| 168 |
+
|
| 169 |
+
def __exit__(
|
| 170 |
+
self,
|
| 171 |
+
exc_type: Optional[Type[BaseException]],
|
| 172 |
+
exc_val: Optional[BaseException],
|
| 173 |
+
exc_tb: Optional[TracebackType],
|
| 174 |
+
) -> None:
|
| 175 |
+
self.stop()
|
| 176 |
+
|
| 177 |
+
def _enable_redirect_io(self) -> None:
|
| 178 |
+
"""Enable redirecting of stdout / stderr."""
|
| 179 |
+
if self.console.is_terminal or self.console.is_jupyter:
|
| 180 |
+
if self._redirect_stdout and not isinstance(sys.stdout, FileProxy):
|
| 181 |
+
self._restore_stdout = sys.stdout
|
| 182 |
+
sys.stdout = cast("TextIO", FileProxy(self.console, sys.stdout))
|
| 183 |
+
if self._redirect_stderr and not isinstance(sys.stderr, FileProxy):
|
| 184 |
+
self._restore_stderr = sys.stderr
|
| 185 |
+
sys.stderr = cast("TextIO", FileProxy(self.console, sys.stderr))
|
| 186 |
+
|
| 187 |
+
def _disable_redirect_io(self) -> None:
|
| 188 |
+
"""Disable redirecting of stdout / stderr."""
|
| 189 |
+
if self._restore_stdout:
|
| 190 |
+
sys.stdout = cast("TextIO", self._restore_stdout)
|
| 191 |
+
self._restore_stdout = None
|
| 192 |
+
if self._restore_stderr:
|
| 193 |
+
sys.stderr = cast("TextIO", self._restore_stderr)
|
| 194 |
+
self._restore_stderr = None
|
| 195 |
+
|
| 196 |
+
@property
|
| 197 |
+
def renderable(self) -> RenderableType:
|
| 198 |
+
"""Get the renderable that is being displayed
|
| 199 |
+
|
| 200 |
+
Returns:
|
| 201 |
+
RenderableType: Displayed renderable.
|
| 202 |
+
"""
|
| 203 |
+
renderable = self.get_renderable()
|
| 204 |
+
return Screen(renderable) if self._alt_screen else renderable
|
| 205 |
+
|
| 206 |
+
def update(self, renderable: RenderableType, *, refresh: bool = False) -> None:
|
| 207 |
+
"""Update the renderable that is being displayed
|
| 208 |
+
|
| 209 |
+
Args:
|
| 210 |
+
renderable (RenderableType): New renderable to use.
|
| 211 |
+
refresh (bool, optional): Refresh the display. Defaults to False.
|
| 212 |
+
"""
|
| 213 |
+
if isinstance(renderable, str):
|
| 214 |
+
renderable = self.console.render_str(renderable)
|
| 215 |
+
with self._lock:
|
| 216 |
+
self._renderable = renderable
|
| 217 |
+
if refresh:
|
| 218 |
+
self.refresh()
|
| 219 |
+
|
| 220 |
+
def refresh(self) -> None:
|
| 221 |
+
"""Update the display of the Live Render."""
|
| 222 |
+
with self._lock:
|
| 223 |
+
self._live_render.set_renderable(self.renderable)
|
| 224 |
+
if self.console.is_jupyter: # pragma: no cover
|
| 225 |
+
try:
|
| 226 |
+
from IPython.display import display
|
| 227 |
+
from ipywidgets import Output
|
| 228 |
+
except ImportError:
|
| 229 |
+
import warnings
|
| 230 |
+
|
| 231 |
+
warnings.warn('install "ipywidgets" for Jupyter support')
|
| 232 |
+
else:
|
| 233 |
+
if self.ipy_widget is None:
|
| 234 |
+
self.ipy_widget = Output()
|
| 235 |
+
display(self.ipy_widget)
|
| 236 |
+
|
| 237 |
+
with self.ipy_widget:
|
| 238 |
+
self.ipy_widget.clear_output(wait=True)
|
| 239 |
+
self.console.print(self._live_render.renderable)
|
| 240 |
+
elif self.console.is_terminal and not self.console.is_dumb_terminal:
|
| 241 |
+
with self.console:
|
| 242 |
+
self.console.print(Control())
|
| 243 |
+
elif (
|
| 244 |
+
not self._started and not self.transient
|
| 245 |
+
): # if it is finished allow files or dumb-terminals to see final result
|
| 246 |
+
with self.console:
|
| 247 |
+
self.console.print(Control())
|
| 248 |
+
|
| 249 |
+
def process_renderables(
|
| 250 |
+
self, renderables: List[ConsoleRenderable]
|
| 251 |
+
) -> List[ConsoleRenderable]:
|
| 252 |
+
"""Process renderables to restore cursor and display progress."""
|
| 253 |
+
self._live_render.vertical_overflow = self.vertical_overflow
|
| 254 |
+
if self.console.is_interactive:
|
| 255 |
+
# lock needs acquiring as user can modify live_render renderable at any time unlike in Progress.
|
| 256 |
+
with self._lock:
|
| 257 |
+
reset = (
|
| 258 |
+
Control.home()
|
| 259 |
+
if self._alt_screen
|
| 260 |
+
else self._live_render.position_cursor()
|
| 261 |
+
)
|
| 262 |
+
renderables = [reset, *renderables, self._live_render]
|
| 263 |
+
elif (
|
| 264 |
+
not self._started and not self.transient
|
| 265 |
+
): # if it is finished render the final output for files or dumb_terminals
|
| 266 |
+
renderables = [*renderables, self._live_render]
|
| 267 |
+
|
| 268 |
+
return renderables
|
| 269 |
+
|
| 270 |
+
|
| 271 |
+
if __name__ == "__main__": # pragma: no cover
|
| 272 |
+
import random
|
| 273 |
+
import time
|
| 274 |
+
from itertools import cycle
|
| 275 |
+
from typing import Dict, List, Tuple
|
| 276 |
+
|
| 277 |
+
from .align import Align
|
| 278 |
+
from .console import Console
|
| 279 |
+
from .live import Live as Live
|
| 280 |
+
from .panel import Panel
|
| 281 |
+
from .rule import Rule
|
| 282 |
+
from .syntax import Syntax
|
| 283 |
+
from .table import Table
|
| 284 |
+
|
| 285 |
+
console = Console()
|
| 286 |
+
|
| 287 |
+
syntax = Syntax(
|
| 288 |
+
'''def loop_last(values: Iterable[T]) -> Iterable[Tuple[bool, T]]:
|
| 289 |
+
"""Iterate and generate a tuple with a flag for last value."""
|
| 290 |
+
iter_values = iter(values)
|
| 291 |
+
try:
|
| 292 |
+
previous_value = next(iter_values)
|
| 293 |
+
except StopIteration:
|
| 294 |
+
return
|
| 295 |
+
for value in iter_values:
|
| 296 |
+
yield False, previous_value
|
| 297 |
+
previous_value = value
|
| 298 |
+
yield True, previous_value''',
|
| 299 |
+
"python",
|
| 300 |
+
line_numbers=True,
|
| 301 |
+
)
|
| 302 |
+
|
| 303 |
+
table = Table("foo", "bar", "baz")
|
| 304 |
+
table.add_row("1", "2", "3")
|
| 305 |
+
|
| 306 |
+
progress_renderables = [
|
| 307 |
+
"You can make the terminal shorter and taller to see the live table hide"
|
| 308 |
+
"Text may be printed while the progress bars are rendering.",
|
| 309 |
+
Panel("In fact, [i]any[/i] renderable will work"),
|
| 310 |
+
"Such as [magenta]tables[/]...",
|
| 311 |
+
table,
|
| 312 |
+
"Pretty printed structures...",
|
| 313 |
+
{"type": "example", "text": "Pretty printed"},
|
| 314 |
+
"Syntax...",
|
| 315 |
+
syntax,
|
| 316 |
+
Rule("Give it a try!"),
|
| 317 |
+
]
|
| 318 |
+
|
| 319 |
+
examples = cycle(progress_renderables)
|
| 320 |
+
|
| 321 |
+
exchanges = [
|
| 322 |
+
"SGD",
|
| 323 |
+
"MYR",
|
| 324 |
+
"EUR",
|
| 325 |
+
"USD",
|
| 326 |
+
"AUD",
|
| 327 |
+
"JPY",
|
| 328 |
+
"CNH",
|
| 329 |
+
"HKD",
|
| 330 |
+
"CAD",
|
| 331 |
+
"INR",
|
| 332 |
+
"DKK",
|
| 333 |
+
"GBP",
|
| 334 |
+
"RUB",
|
| 335 |
+
"NZD",
|
| 336 |
+
"MXN",
|
| 337 |
+
"IDR",
|
| 338 |
+
"TWD",
|
| 339 |
+
"THB",
|
| 340 |
+
"VND",
|
| 341 |
+
]
|
| 342 |
+
with Live(console=console) as live_table:
|
| 343 |
+
exchange_rate_dict: Dict[Tuple[str, str], float] = {}
|
| 344 |
+
|
| 345 |
+
for index in range(100):
|
| 346 |
+
select_exchange = exchanges[index % len(exchanges)]
|
| 347 |
+
|
| 348 |
+
for exchange in exchanges:
|
| 349 |
+
if exchange == select_exchange:
|
| 350 |
+
continue
|
| 351 |
+
time.sleep(0.4)
|
| 352 |
+
if random.randint(0, 10) < 1:
|
| 353 |
+
console.log(next(examples))
|
| 354 |
+
exchange_rate_dict[(select_exchange, exchange)] = 200 / (
|
| 355 |
+
(random.random() * 320) + 1
|
| 356 |
+
)
|
| 357 |
+
if len(exchange_rate_dict) > len(exchanges) - 1:
|
| 358 |
+
exchange_rate_dict.pop(list(exchange_rate_dict.keys())[0])
|
| 359 |
+
table = Table(title="Exchange Rates")
|
| 360 |
+
|
| 361 |
+
table.add_column("Source Currency")
|
| 362 |
+
table.add_column("Destination Currency")
|
| 363 |
+
table.add_column("Exchange Rate")
|
| 364 |
+
|
| 365 |
+
for ((source, dest), exchange_rate) in exchange_rate_dict.items():
|
| 366 |
+
table.add_row(
|
| 367 |
+
source,
|
| 368 |
+
dest,
|
| 369 |
+
Text(
|
| 370 |
+
f"{exchange_rate:.4f}",
|
| 371 |
+
style="red" if exchange_rate < 1.0 else "green",
|
| 372 |
+
),
|
| 373 |
+
)
|
| 374 |
+
|
| 375 |
+
live_table.update(Align.center(table))
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35/lib/python3.12/site-packages/pip/_vendor/rich/pager.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from abc import ABC, abstractmethod
|
| 2 |
+
from typing import Any
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
class Pager(ABC):
|
| 6 |
+
"""Base class for a pager."""
|
| 7 |
+
|
| 8 |
+
@abstractmethod
|
| 9 |
+
def show(self, content: str) -> None:
|
| 10 |
+
"""Show content in pager.
|
| 11 |
+
|
| 12 |
+
Args:
|
| 13 |
+
content (str): Content to be displayed.
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class SystemPager(Pager):
|
| 18 |
+
"""Uses the pager installed on the system."""
|
| 19 |
+
|
| 20 |
+
def _pager(self, content: str) -> Any: # pragma: no cover
|
| 21 |
+
return __import__("pydoc").pager(content)
|
| 22 |
+
|
| 23 |
+
def show(self, content: str) -> None:
|
| 24 |
+
"""Use the same pager used by pydoc."""
|
| 25 |
+
self._pager(content)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
if __name__ == "__main__": # pragma: no cover
|
| 29 |
+
from .__main__ import make_test_card
|
| 30 |
+
from .console import Console
|
| 31 |
+
|
| 32 |
+
console = Console()
|
| 33 |
+
with console.pager(styles=True):
|
| 34 |
+
console.print(make_test_card())
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35/lib/python3.12/site-packages/pip/_vendor/rich/rule.py
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Union
|
| 2 |
+
|
| 3 |
+
from .align import AlignMethod
|
| 4 |
+
from .cells import cell_len, set_cell_size
|
| 5 |
+
from .console import Console, ConsoleOptions, RenderResult
|
| 6 |
+
from .jupyter import JupyterMixin
|
| 7 |
+
from .measure import Measurement
|
| 8 |
+
from .style import Style
|
| 9 |
+
from .text import Text
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class Rule(JupyterMixin):
|
| 13 |
+
"""A console renderable to draw a horizontal rule (line).
|
| 14 |
+
|
| 15 |
+
Args:
|
| 16 |
+
title (Union[str, Text], optional): Text to render in the rule. Defaults to "".
|
| 17 |
+
characters (str, optional): Character(s) used to draw the line. Defaults to "─".
|
| 18 |
+
style (StyleType, optional): Style of Rule. Defaults to "rule.line".
|
| 19 |
+
end (str, optional): Character at end of Rule. defaults to "\\\\n"
|
| 20 |
+
align (str, optional): How to align the title, one of "left", "center", or "right". Defaults to "center".
|
| 21 |
+
"""
|
| 22 |
+
|
| 23 |
+
def __init__(
|
| 24 |
+
self,
|
| 25 |
+
title: Union[str, Text] = "",
|
| 26 |
+
*,
|
| 27 |
+
characters: str = "─",
|
| 28 |
+
style: Union[str, Style] = "rule.line",
|
| 29 |
+
end: str = "\n",
|
| 30 |
+
align: AlignMethod = "center",
|
| 31 |
+
) -> None:
|
| 32 |
+
if cell_len(characters) < 1:
|
| 33 |
+
raise ValueError(
|
| 34 |
+
"'characters' argument must have a cell width of at least 1"
|
| 35 |
+
)
|
| 36 |
+
if align not in ("left", "center", "right"):
|
| 37 |
+
raise ValueError(
|
| 38 |
+
f'invalid value for align, expected "left", "center", "right" (not {align!r})'
|
| 39 |
+
)
|
| 40 |
+
self.title = title
|
| 41 |
+
self.characters = characters
|
| 42 |
+
self.style = style
|
| 43 |
+
self.end = end
|
| 44 |
+
self.align = align
|
| 45 |
+
|
| 46 |
+
def __repr__(self) -> str:
|
| 47 |
+
return f"Rule({self.title!r}, {self.characters!r})"
|
| 48 |
+
|
| 49 |
+
def __rich_console__(
|
| 50 |
+
self, console: Console, options: ConsoleOptions
|
| 51 |
+
) -> RenderResult:
|
| 52 |
+
width = options.max_width
|
| 53 |
+
|
| 54 |
+
characters = (
|
| 55 |
+
"-"
|
| 56 |
+
if (options.ascii_only and not self.characters.isascii())
|
| 57 |
+
else self.characters
|
| 58 |
+
)
|
| 59 |
+
|
| 60 |
+
chars_len = cell_len(characters)
|
| 61 |
+
if not self.title:
|
| 62 |
+
yield self._rule_line(chars_len, width)
|
| 63 |
+
return
|
| 64 |
+
|
| 65 |
+
if isinstance(self.title, Text):
|
| 66 |
+
title_text = self.title
|
| 67 |
+
else:
|
| 68 |
+
title_text = console.render_str(self.title, style="rule.text")
|
| 69 |
+
|
| 70 |
+
title_text.plain = title_text.plain.replace("\n", " ")
|
| 71 |
+
title_text.expand_tabs()
|
| 72 |
+
|
| 73 |
+
required_space = 4 if self.align == "center" else 2
|
| 74 |
+
truncate_width = max(0, width - required_space)
|
| 75 |
+
if not truncate_width:
|
| 76 |
+
yield self._rule_line(chars_len, width)
|
| 77 |
+
return
|
| 78 |
+
|
| 79 |
+
rule_text = Text(end=self.end)
|
| 80 |
+
if self.align == "center":
|
| 81 |
+
title_text.truncate(truncate_width, overflow="ellipsis")
|
| 82 |
+
side_width = (width - cell_len(title_text.plain)) // 2
|
| 83 |
+
left = Text(characters * (side_width // chars_len + 1))
|
| 84 |
+
left.truncate(side_width - 1)
|
| 85 |
+
right_length = width - cell_len(left.plain) - cell_len(title_text.plain)
|
| 86 |
+
right = Text(characters * (side_width // chars_len + 1))
|
| 87 |
+
right.truncate(right_length)
|
| 88 |
+
rule_text.append(left.plain + " ", self.style)
|
| 89 |
+
rule_text.append(title_text)
|
| 90 |
+
rule_text.append(" " + right.plain, self.style)
|
| 91 |
+
elif self.align == "left":
|
| 92 |
+
title_text.truncate(truncate_width, overflow="ellipsis")
|
| 93 |
+
rule_text.append(title_text)
|
| 94 |
+
rule_text.append(" ")
|
| 95 |
+
rule_text.append(characters * (width - rule_text.cell_len), self.style)
|
| 96 |
+
elif self.align == "right":
|
| 97 |
+
title_text.truncate(truncate_width, overflow="ellipsis")
|
| 98 |
+
rule_text.append(characters * (width - title_text.cell_len - 1), self.style)
|
| 99 |
+
rule_text.append(" ")
|
| 100 |
+
rule_text.append(title_text)
|
| 101 |
+
|
| 102 |
+
rule_text.plain = set_cell_size(rule_text.plain, width)
|
| 103 |
+
yield rule_text
|
| 104 |
+
|
| 105 |
+
def _rule_line(self, chars_len: int, width: int) -> Text:
|
| 106 |
+
rule_text = Text(self.characters * ((width // chars_len) + 1), self.style)
|
| 107 |
+
rule_text.truncate(width)
|
| 108 |
+
rule_text.plain = set_cell_size(rule_text.plain, width)
|
| 109 |
+
return rule_text
|
| 110 |
+
|
| 111 |
+
def __rich_measure__(
|
| 112 |
+
self, console: Console, options: ConsoleOptions
|
| 113 |
+
) -> Measurement:
|
| 114 |
+
return Measurement(1, 1)
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
if __name__ == "__main__": # pragma: no cover
|
| 118 |
+
import sys
|
| 119 |
+
|
| 120 |
+
from pip._vendor.rich.console import Console
|
| 121 |
+
|
| 122 |
+
try:
|
| 123 |
+
text = sys.argv[1]
|
| 124 |
+
except IndexError:
|
| 125 |
+
text = "Hello, World"
|
| 126 |
+
console = Console()
|
| 127 |
+
console.print(Rule(title=text))
|
| 128 |
+
|
| 129 |
+
console = Console()
|
| 130 |
+
console.print(Rule("foo"), width=4)
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35/lib/python3.12/site-packages/pip/_vendor/rich/styled.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import TYPE_CHECKING
|
| 2 |
+
|
| 3 |
+
from .measure import Measurement
|
| 4 |
+
from .segment import Segment
|
| 5 |
+
from .style import StyleType
|
| 6 |
+
|
| 7 |
+
if TYPE_CHECKING:
|
| 8 |
+
from .console import Console, ConsoleOptions, RenderResult, RenderableType
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class Styled:
|
| 12 |
+
"""Apply a style to a renderable.
|
| 13 |
+
|
| 14 |
+
Args:
|
| 15 |
+
renderable (RenderableType): Any renderable.
|
| 16 |
+
style (StyleType): A style to apply across the entire renderable.
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
def __init__(self, renderable: "RenderableType", style: "StyleType") -> None:
|
| 20 |
+
self.renderable = renderable
|
| 21 |
+
self.style = style
|
| 22 |
+
|
| 23 |
+
def __rich_console__(
|
| 24 |
+
self, console: "Console", options: "ConsoleOptions"
|
| 25 |
+
) -> "RenderResult":
|
| 26 |
+
style = console.get_style(self.style)
|
| 27 |
+
rendered_segments = console.render(self.renderable, options)
|
| 28 |
+
segments = Segment.apply_style(rendered_segments, style)
|
| 29 |
+
return segments
|
| 30 |
+
|
| 31 |
+
def __rich_measure__(
|
| 32 |
+
self, console: "Console", options: "ConsoleOptions"
|
| 33 |
+
) -> Measurement:
|
| 34 |
+
return Measurement.get(console, options, self.renderable)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
if __name__ == "__main__": # pragma: no cover
|
| 38 |
+
from pip._vendor.rich import print
|
| 39 |
+
from pip._vendor.rich.panel import Panel
|
| 40 |
+
|
| 41 |
+
panel = Styled(Panel("hello"), "on blue")
|
| 42 |
+
print(panel)
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35/lib/python3.12/site-packages/pip/_vendor/rich/syntax.py
ADDED
|
@@ -0,0 +1,948 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os.path
|
| 2 |
+
import platform
|
| 3 |
+
import re
|
| 4 |
+
import sys
|
| 5 |
+
import textwrap
|
| 6 |
+
from abc import ABC, abstractmethod
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
from typing import (
|
| 9 |
+
Any,
|
| 10 |
+
Dict,
|
| 11 |
+
Iterable,
|
| 12 |
+
List,
|
| 13 |
+
NamedTuple,
|
| 14 |
+
Optional,
|
| 15 |
+
Sequence,
|
| 16 |
+
Set,
|
| 17 |
+
Tuple,
|
| 18 |
+
Type,
|
| 19 |
+
Union,
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
from pip._vendor.pygments.lexer import Lexer
|
| 23 |
+
from pip._vendor.pygments.lexers import get_lexer_by_name, guess_lexer_for_filename
|
| 24 |
+
from pip._vendor.pygments.style import Style as PygmentsStyle
|
| 25 |
+
from pip._vendor.pygments.styles import get_style_by_name
|
| 26 |
+
from pip._vendor.pygments.token import (
|
| 27 |
+
Comment,
|
| 28 |
+
Error,
|
| 29 |
+
Generic,
|
| 30 |
+
Keyword,
|
| 31 |
+
Name,
|
| 32 |
+
Number,
|
| 33 |
+
Operator,
|
| 34 |
+
String,
|
| 35 |
+
Token,
|
| 36 |
+
Whitespace,
|
| 37 |
+
)
|
| 38 |
+
from pip._vendor.pygments.util import ClassNotFound
|
| 39 |
+
|
| 40 |
+
from pip._vendor.rich.containers import Lines
|
| 41 |
+
from pip._vendor.rich.padding import Padding, PaddingDimensions
|
| 42 |
+
|
| 43 |
+
from ._loop import loop_first
|
| 44 |
+
from .cells import cell_len
|
| 45 |
+
from .color import Color, blend_rgb
|
| 46 |
+
from .console import Console, ConsoleOptions, JustifyMethod, RenderResult
|
| 47 |
+
from .jupyter import JupyterMixin
|
| 48 |
+
from .measure import Measurement
|
| 49 |
+
from .segment import Segment, Segments
|
| 50 |
+
from .style import Style, StyleType
|
| 51 |
+
from .text import Text
|
| 52 |
+
|
| 53 |
+
TokenType = Tuple[str, ...]
|
| 54 |
+
|
| 55 |
+
WINDOWS = platform.system() == "Windows"
|
| 56 |
+
DEFAULT_THEME = "monokai"
|
| 57 |
+
|
| 58 |
+
# The following styles are based on https://github.com/pygments/pygments/blob/master/pygments/formatters/terminal.py
|
| 59 |
+
# A few modifications were made
|
| 60 |
+
|
| 61 |
+
ANSI_LIGHT: Dict[TokenType, Style] = {
|
| 62 |
+
Token: Style(),
|
| 63 |
+
Whitespace: Style(color="white"),
|
| 64 |
+
Comment: Style(dim=True),
|
| 65 |
+
Comment.Preproc: Style(color="cyan"),
|
| 66 |
+
Keyword: Style(color="blue"),
|
| 67 |
+
Keyword.Type: Style(color="cyan"),
|
| 68 |
+
Operator.Word: Style(color="magenta"),
|
| 69 |
+
Name.Builtin: Style(color="cyan"),
|
| 70 |
+
Name.Function: Style(color="green"),
|
| 71 |
+
Name.Namespace: Style(color="cyan", underline=True),
|
| 72 |
+
Name.Class: Style(color="green", underline=True),
|
| 73 |
+
Name.Exception: Style(color="cyan"),
|
| 74 |
+
Name.Decorator: Style(color="magenta", bold=True),
|
| 75 |
+
Name.Variable: Style(color="red"),
|
| 76 |
+
Name.Constant: Style(color="red"),
|
| 77 |
+
Name.Attribute: Style(color="cyan"),
|
| 78 |
+
Name.Tag: Style(color="bright_blue"),
|
| 79 |
+
String: Style(color="yellow"),
|
| 80 |
+
Number: Style(color="blue"),
|
| 81 |
+
Generic.Deleted: Style(color="bright_red"),
|
| 82 |
+
Generic.Inserted: Style(color="green"),
|
| 83 |
+
Generic.Heading: Style(bold=True),
|
| 84 |
+
Generic.Subheading: Style(color="magenta", bold=True),
|
| 85 |
+
Generic.Prompt: Style(bold=True),
|
| 86 |
+
Generic.Error: Style(color="bright_red"),
|
| 87 |
+
Error: Style(color="red", underline=True),
|
| 88 |
+
}
|
| 89 |
+
|
| 90 |
+
ANSI_DARK: Dict[TokenType, Style] = {
|
| 91 |
+
Token: Style(),
|
| 92 |
+
Whitespace: Style(color="bright_black"),
|
| 93 |
+
Comment: Style(dim=True),
|
| 94 |
+
Comment.Preproc: Style(color="bright_cyan"),
|
| 95 |
+
Keyword: Style(color="bright_blue"),
|
| 96 |
+
Keyword.Type: Style(color="bright_cyan"),
|
| 97 |
+
Operator.Word: Style(color="bright_magenta"),
|
| 98 |
+
Name.Builtin: Style(color="bright_cyan"),
|
| 99 |
+
Name.Function: Style(color="bright_green"),
|
| 100 |
+
Name.Namespace: Style(color="bright_cyan", underline=True),
|
| 101 |
+
Name.Class: Style(color="bright_green", underline=True),
|
| 102 |
+
Name.Exception: Style(color="bright_cyan"),
|
| 103 |
+
Name.Decorator: Style(color="bright_magenta", bold=True),
|
| 104 |
+
Name.Variable: Style(color="bright_red"),
|
| 105 |
+
Name.Constant: Style(color="bright_red"),
|
| 106 |
+
Name.Attribute: Style(color="bright_cyan"),
|
| 107 |
+
Name.Tag: Style(color="bright_blue"),
|
| 108 |
+
String: Style(color="yellow"),
|
| 109 |
+
Number: Style(color="bright_blue"),
|
| 110 |
+
Generic.Deleted: Style(color="bright_red"),
|
| 111 |
+
Generic.Inserted: Style(color="bright_green"),
|
| 112 |
+
Generic.Heading: Style(bold=True),
|
| 113 |
+
Generic.Subheading: Style(color="bright_magenta", bold=True),
|
| 114 |
+
Generic.Prompt: Style(bold=True),
|
| 115 |
+
Generic.Error: Style(color="bright_red"),
|
| 116 |
+
Error: Style(color="red", underline=True),
|
| 117 |
+
}
|
| 118 |
+
|
| 119 |
+
RICH_SYNTAX_THEMES = {"ansi_light": ANSI_LIGHT, "ansi_dark": ANSI_DARK}
|
| 120 |
+
NUMBERS_COLUMN_DEFAULT_PADDING = 2
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
class SyntaxTheme(ABC):
|
| 124 |
+
"""Base class for a syntax theme."""
|
| 125 |
+
|
| 126 |
+
@abstractmethod
|
| 127 |
+
def get_style_for_token(self, token_type: TokenType) -> Style:
|
| 128 |
+
"""Get a style for a given Pygments token."""
|
| 129 |
+
raise NotImplementedError # pragma: no cover
|
| 130 |
+
|
| 131 |
+
@abstractmethod
|
| 132 |
+
def get_background_style(self) -> Style:
|
| 133 |
+
"""Get the background color."""
|
| 134 |
+
raise NotImplementedError # pragma: no cover
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
class PygmentsSyntaxTheme(SyntaxTheme):
|
| 138 |
+
"""Syntax theme that delegates to Pygments theme."""
|
| 139 |
+
|
| 140 |
+
def __init__(self, theme: Union[str, Type[PygmentsStyle]]) -> None:
|
| 141 |
+
self._style_cache: Dict[TokenType, Style] = {}
|
| 142 |
+
if isinstance(theme, str):
|
| 143 |
+
try:
|
| 144 |
+
self._pygments_style_class = get_style_by_name(theme)
|
| 145 |
+
except ClassNotFound:
|
| 146 |
+
self._pygments_style_class = get_style_by_name("default")
|
| 147 |
+
else:
|
| 148 |
+
self._pygments_style_class = theme
|
| 149 |
+
|
| 150 |
+
self._background_color = self._pygments_style_class.background_color
|
| 151 |
+
self._background_style = Style(bgcolor=self._background_color)
|
| 152 |
+
|
| 153 |
+
def get_style_for_token(self, token_type: TokenType) -> Style:
|
| 154 |
+
"""Get a style from a Pygments class."""
|
| 155 |
+
try:
|
| 156 |
+
return self._style_cache[token_type]
|
| 157 |
+
except KeyError:
|
| 158 |
+
try:
|
| 159 |
+
pygments_style = self._pygments_style_class.style_for_token(token_type)
|
| 160 |
+
except KeyError:
|
| 161 |
+
style = Style.null()
|
| 162 |
+
else:
|
| 163 |
+
color = pygments_style["color"]
|
| 164 |
+
bgcolor = pygments_style["bgcolor"]
|
| 165 |
+
style = Style(
|
| 166 |
+
color="#" + color if color else "#000000",
|
| 167 |
+
bgcolor="#" + bgcolor if bgcolor else self._background_color,
|
| 168 |
+
bold=pygments_style["bold"],
|
| 169 |
+
italic=pygments_style["italic"],
|
| 170 |
+
underline=pygments_style["underline"],
|
| 171 |
+
)
|
| 172 |
+
self._style_cache[token_type] = style
|
| 173 |
+
return style
|
| 174 |
+
|
| 175 |
+
def get_background_style(self) -> Style:
|
| 176 |
+
return self._background_style
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
class ANSISyntaxTheme(SyntaxTheme):
|
| 180 |
+
"""Syntax theme to use standard colors."""
|
| 181 |
+
|
| 182 |
+
def __init__(self, style_map: Dict[TokenType, Style]) -> None:
|
| 183 |
+
self.style_map = style_map
|
| 184 |
+
self._missing_style = Style.null()
|
| 185 |
+
self._background_style = Style.null()
|
| 186 |
+
self._style_cache: Dict[TokenType, Style] = {}
|
| 187 |
+
|
| 188 |
+
def get_style_for_token(self, token_type: TokenType) -> Style:
|
| 189 |
+
"""Look up style in the style map."""
|
| 190 |
+
try:
|
| 191 |
+
return self._style_cache[token_type]
|
| 192 |
+
except KeyError:
|
| 193 |
+
# Styles form a hierarchy
|
| 194 |
+
# We need to go from most to least specific
|
| 195 |
+
# e.g. ("foo", "bar", "baz") to ("foo", "bar") to ("foo",)
|
| 196 |
+
get_style = self.style_map.get
|
| 197 |
+
token = tuple(token_type)
|
| 198 |
+
style = self._missing_style
|
| 199 |
+
while token:
|
| 200 |
+
_style = get_style(token)
|
| 201 |
+
if _style is not None:
|
| 202 |
+
style = _style
|
| 203 |
+
break
|
| 204 |
+
token = token[:-1]
|
| 205 |
+
self._style_cache[token_type] = style
|
| 206 |
+
return style
|
| 207 |
+
|
| 208 |
+
def get_background_style(self) -> Style:
|
| 209 |
+
return self._background_style
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
SyntaxPosition = Tuple[int, int]
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
class _SyntaxHighlightRange(NamedTuple):
|
| 216 |
+
"""
|
| 217 |
+
A range to highlight in a Syntax object.
|
| 218 |
+
`start` and `end` are 2-integers tuples, where the first integer is the line number
|
| 219 |
+
(starting from 1) and the second integer is the column index (starting from 0).
|
| 220 |
+
"""
|
| 221 |
+
|
| 222 |
+
style: StyleType
|
| 223 |
+
start: SyntaxPosition
|
| 224 |
+
end: SyntaxPosition
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
class Syntax(JupyterMixin):
|
| 228 |
+
"""Construct a Syntax object to render syntax highlighted code.
|
| 229 |
+
|
| 230 |
+
Args:
|
| 231 |
+
code (str): Code to highlight.
|
| 232 |
+
lexer (Lexer | str): Lexer to use (see https://pygments.org/docs/lexers/)
|
| 233 |
+
theme (str, optional): Color theme, aka Pygments style (see https://pygments.org/docs/styles/#getting-a-list-of-available-styles). Defaults to "monokai".
|
| 234 |
+
dedent (bool, optional): Enable stripping of initial whitespace. Defaults to False.
|
| 235 |
+
line_numbers (bool, optional): Enable rendering of line numbers. Defaults to False.
|
| 236 |
+
start_line (int, optional): Starting number for line numbers. Defaults to 1.
|
| 237 |
+
line_range (Tuple[int | None, int | None], optional): If given should be a tuple of the start and end line to render.
|
| 238 |
+
A value of None in the tuple indicates the range is open in that direction.
|
| 239 |
+
highlight_lines (Set[int]): A set of line numbers to highlight.
|
| 240 |
+
code_width: Width of code to render (not including line numbers), or ``None`` to use all available width.
|
| 241 |
+
tab_size (int, optional): Size of tabs. Defaults to 4.
|
| 242 |
+
word_wrap (bool, optional): Enable word wrapping.
|
| 243 |
+
background_color (str, optional): Optional background color, or None to use theme color. Defaults to None.
|
| 244 |
+
indent_guides (bool, optional): Show indent guides. Defaults to False.
|
| 245 |
+
padding (PaddingDimensions): Padding to apply around the syntax. Defaults to 0 (no padding).
|
| 246 |
+
"""
|
| 247 |
+
|
| 248 |
+
_pygments_style_class: Type[PygmentsStyle]
|
| 249 |
+
_theme: SyntaxTheme
|
| 250 |
+
|
| 251 |
+
@classmethod
|
| 252 |
+
def get_theme(cls, name: Union[str, SyntaxTheme]) -> SyntaxTheme:
|
| 253 |
+
"""Get a syntax theme instance."""
|
| 254 |
+
if isinstance(name, SyntaxTheme):
|
| 255 |
+
return name
|
| 256 |
+
theme: SyntaxTheme
|
| 257 |
+
if name in RICH_SYNTAX_THEMES:
|
| 258 |
+
theme = ANSISyntaxTheme(RICH_SYNTAX_THEMES[name])
|
| 259 |
+
else:
|
| 260 |
+
theme = PygmentsSyntaxTheme(name)
|
| 261 |
+
return theme
|
| 262 |
+
|
| 263 |
+
def __init__(
|
| 264 |
+
self,
|
| 265 |
+
code: str,
|
| 266 |
+
lexer: Union[Lexer, str],
|
| 267 |
+
*,
|
| 268 |
+
theme: Union[str, SyntaxTheme] = DEFAULT_THEME,
|
| 269 |
+
dedent: bool = False,
|
| 270 |
+
line_numbers: bool = False,
|
| 271 |
+
start_line: int = 1,
|
| 272 |
+
line_range: Optional[Tuple[Optional[int], Optional[int]]] = None,
|
| 273 |
+
highlight_lines: Optional[Set[int]] = None,
|
| 274 |
+
code_width: Optional[int] = None,
|
| 275 |
+
tab_size: int = 4,
|
| 276 |
+
word_wrap: bool = False,
|
| 277 |
+
background_color: Optional[str] = None,
|
| 278 |
+
indent_guides: bool = False,
|
| 279 |
+
padding: PaddingDimensions = 0,
|
| 280 |
+
) -> None:
|
| 281 |
+
self.code = code
|
| 282 |
+
self._lexer = lexer
|
| 283 |
+
self.dedent = dedent
|
| 284 |
+
self.line_numbers = line_numbers
|
| 285 |
+
self.start_line = start_line
|
| 286 |
+
self.line_range = line_range
|
| 287 |
+
self.highlight_lines = highlight_lines or set()
|
| 288 |
+
self.code_width = code_width
|
| 289 |
+
self.tab_size = tab_size
|
| 290 |
+
self.word_wrap = word_wrap
|
| 291 |
+
self.background_color = background_color
|
| 292 |
+
self.background_style = (
|
| 293 |
+
Style(bgcolor=background_color) if background_color else Style()
|
| 294 |
+
)
|
| 295 |
+
self.indent_guides = indent_guides
|
| 296 |
+
self.padding = padding
|
| 297 |
+
|
| 298 |
+
self._theme = self.get_theme(theme)
|
| 299 |
+
self._stylized_ranges: List[_SyntaxHighlightRange] = []
|
| 300 |
+
|
| 301 |
+
@classmethod
|
| 302 |
+
def from_path(
|
| 303 |
+
cls,
|
| 304 |
+
path: str,
|
| 305 |
+
encoding: str = "utf-8",
|
| 306 |
+
lexer: Optional[Union[Lexer, str]] = None,
|
| 307 |
+
theme: Union[str, SyntaxTheme] = DEFAULT_THEME,
|
| 308 |
+
dedent: bool = False,
|
| 309 |
+
line_numbers: bool = False,
|
| 310 |
+
line_range: Optional[Tuple[int, int]] = None,
|
| 311 |
+
start_line: int = 1,
|
| 312 |
+
highlight_lines: Optional[Set[int]] = None,
|
| 313 |
+
code_width: Optional[int] = None,
|
| 314 |
+
tab_size: int = 4,
|
| 315 |
+
word_wrap: bool = False,
|
| 316 |
+
background_color: Optional[str] = None,
|
| 317 |
+
indent_guides: bool = False,
|
| 318 |
+
padding: PaddingDimensions = 0,
|
| 319 |
+
) -> "Syntax":
|
| 320 |
+
"""Construct a Syntax object from a file.
|
| 321 |
+
|
| 322 |
+
Args:
|
| 323 |
+
path (str): Path to file to highlight.
|
| 324 |
+
encoding (str): Encoding of file.
|
| 325 |
+
lexer (str | Lexer, optional): Lexer to use. If None, lexer will be auto-detected from path/file content.
|
| 326 |
+
theme (str, optional): Color theme, aka Pygments style (see https://pygments.org/docs/styles/#getting-a-list-of-available-styles). Defaults to "emacs".
|
| 327 |
+
dedent (bool, optional): Enable stripping of initial whitespace. Defaults to True.
|
| 328 |
+
line_numbers (bool, optional): Enable rendering of line numbers. Defaults to False.
|
| 329 |
+
start_line (int, optional): Starting number for line numbers. Defaults to 1.
|
| 330 |
+
line_range (Tuple[int, int], optional): If given should be a tuple of the start and end line to render.
|
| 331 |
+
highlight_lines (Set[int]): A set of line numbers to highlight.
|
| 332 |
+
code_width: Width of code to render (not including line numbers), or ``None`` to use all available width.
|
| 333 |
+
tab_size (int, optional): Size of tabs. Defaults to 4.
|
| 334 |
+
word_wrap (bool, optional): Enable word wrapping of code.
|
| 335 |
+
background_color (str, optional): Optional background color, or None to use theme color. Defaults to None.
|
| 336 |
+
indent_guides (bool, optional): Show indent guides. Defaults to False.
|
| 337 |
+
padding (PaddingDimensions): Padding to apply around the syntax. Defaults to 0 (no padding).
|
| 338 |
+
|
| 339 |
+
Returns:
|
| 340 |
+
[Syntax]: A Syntax object that may be printed to the console
|
| 341 |
+
"""
|
| 342 |
+
code = Path(path).read_text(encoding=encoding)
|
| 343 |
+
|
| 344 |
+
if not lexer:
|
| 345 |
+
lexer = cls.guess_lexer(path, code=code)
|
| 346 |
+
|
| 347 |
+
return cls(
|
| 348 |
+
code,
|
| 349 |
+
lexer,
|
| 350 |
+
theme=theme,
|
| 351 |
+
dedent=dedent,
|
| 352 |
+
line_numbers=line_numbers,
|
| 353 |
+
line_range=line_range,
|
| 354 |
+
start_line=start_line,
|
| 355 |
+
highlight_lines=highlight_lines,
|
| 356 |
+
code_width=code_width,
|
| 357 |
+
tab_size=tab_size,
|
| 358 |
+
word_wrap=word_wrap,
|
| 359 |
+
background_color=background_color,
|
| 360 |
+
indent_guides=indent_guides,
|
| 361 |
+
padding=padding,
|
| 362 |
+
)
|
| 363 |
+
|
| 364 |
+
@classmethod
|
| 365 |
+
def guess_lexer(cls, path: str, code: Optional[str] = None) -> str:
|
| 366 |
+
"""Guess the alias of the Pygments lexer to use based on a path and an optional string of code.
|
| 367 |
+
If code is supplied, it will use a combination of the code and the filename to determine the
|
| 368 |
+
best lexer to use. For example, if the file is ``index.html`` and the file contains Django
|
| 369 |
+
templating syntax, then "html+django" will be returned. If the file is ``index.html``, and no
|
| 370 |
+
templating language is used, the "html" lexer will be used. If no string of code
|
| 371 |
+
is supplied, the lexer will be chosen based on the file extension..
|
| 372 |
+
|
| 373 |
+
Args:
|
| 374 |
+
path (AnyStr): The path to the file containing the code you wish to know the lexer for.
|
| 375 |
+
code (str, optional): Optional string of code that will be used as a fallback if no lexer
|
| 376 |
+
is found for the supplied path.
|
| 377 |
+
|
| 378 |
+
Returns:
|
| 379 |
+
str: The name of the Pygments lexer that best matches the supplied path/code.
|
| 380 |
+
"""
|
| 381 |
+
lexer: Optional[Lexer] = None
|
| 382 |
+
lexer_name = "default"
|
| 383 |
+
if code:
|
| 384 |
+
try:
|
| 385 |
+
lexer = guess_lexer_for_filename(path, code)
|
| 386 |
+
except ClassNotFound:
|
| 387 |
+
pass
|
| 388 |
+
|
| 389 |
+
if not lexer:
|
| 390 |
+
try:
|
| 391 |
+
_, ext = os.path.splitext(path)
|
| 392 |
+
if ext:
|
| 393 |
+
extension = ext.lstrip(".").lower()
|
| 394 |
+
lexer = get_lexer_by_name(extension)
|
| 395 |
+
except ClassNotFound:
|
| 396 |
+
pass
|
| 397 |
+
|
| 398 |
+
if lexer:
|
| 399 |
+
if lexer.aliases:
|
| 400 |
+
lexer_name = lexer.aliases[0]
|
| 401 |
+
else:
|
| 402 |
+
lexer_name = lexer.name
|
| 403 |
+
|
| 404 |
+
return lexer_name
|
| 405 |
+
|
| 406 |
+
def _get_base_style(self) -> Style:
|
| 407 |
+
"""Get the base style."""
|
| 408 |
+
default_style = self._theme.get_background_style() + self.background_style
|
| 409 |
+
return default_style
|
| 410 |
+
|
| 411 |
+
def _get_token_color(self, token_type: TokenType) -> Optional[Color]:
|
| 412 |
+
"""Get a color (if any) for the given token.
|
| 413 |
+
|
| 414 |
+
Args:
|
| 415 |
+
token_type (TokenType): A token type tuple from Pygments.
|
| 416 |
+
|
| 417 |
+
Returns:
|
| 418 |
+
Optional[Color]: Color from theme, or None for no color.
|
| 419 |
+
"""
|
| 420 |
+
style = self._theme.get_style_for_token(token_type)
|
| 421 |
+
return style.color
|
| 422 |
+
|
| 423 |
+
@property
|
| 424 |
+
def lexer(self) -> Optional[Lexer]:
|
| 425 |
+
"""The lexer for this syntax, or None if no lexer was found.
|
| 426 |
+
|
| 427 |
+
Tries to find the lexer by name if a string was passed to the constructor.
|
| 428 |
+
"""
|
| 429 |
+
|
| 430 |
+
if isinstance(self._lexer, Lexer):
|
| 431 |
+
return self._lexer
|
| 432 |
+
try:
|
| 433 |
+
return get_lexer_by_name(
|
| 434 |
+
self._lexer,
|
| 435 |
+
stripnl=False,
|
| 436 |
+
ensurenl=True,
|
| 437 |
+
tabsize=self.tab_size,
|
| 438 |
+
)
|
| 439 |
+
except ClassNotFound:
|
| 440 |
+
return None
|
| 441 |
+
|
| 442 |
+
def highlight(
|
| 443 |
+
self,
|
| 444 |
+
code: str,
|
| 445 |
+
line_range: Optional[Tuple[Optional[int], Optional[int]]] = None,
|
| 446 |
+
) -> Text:
|
| 447 |
+
"""Highlight code and return a Text instance.
|
| 448 |
+
|
| 449 |
+
Args:
|
| 450 |
+
code (str): Code to highlight.
|
| 451 |
+
line_range(Tuple[int, int], optional): Optional line range to highlight.
|
| 452 |
+
|
| 453 |
+
Returns:
|
| 454 |
+
Text: A text instance containing highlighted syntax.
|
| 455 |
+
"""
|
| 456 |
+
|
| 457 |
+
base_style = self._get_base_style()
|
| 458 |
+
justify: JustifyMethod = (
|
| 459 |
+
"default" if base_style.transparent_background else "left"
|
| 460 |
+
)
|
| 461 |
+
|
| 462 |
+
text = Text(
|
| 463 |
+
justify=justify,
|
| 464 |
+
style=base_style,
|
| 465 |
+
tab_size=self.tab_size,
|
| 466 |
+
no_wrap=not self.word_wrap,
|
| 467 |
+
)
|
| 468 |
+
_get_theme_style = self._theme.get_style_for_token
|
| 469 |
+
|
| 470 |
+
lexer = self.lexer
|
| 471 |
+
|
| 472 |
+
if lexer is None:
|
| 473 |
+
text.append(code)
|
| 474 |
+
else:
|
| 475 |
+
if line_range:
|
| 476 |
+
# More complicated path to only stylize a portion of the code
|
| 477 |
+
# This speeds up further operations as there are less spans to process
|
| 478 |
+
line_start, line_end = line_range
|
| 479 |
+
|
| 480 |
+
def line_tokenize() -> Iterable[Tuple[Any, str]]:
|
| 481 |
+
"""Split tokens to one per line."""
|
| 482 |
+
assert lexer # required to make MyPy happy - we know lexer is not None at this point
|
| 483 |
+
|
| 484 |
+
for token_type, token in lexer.get_tokens(code):
|
| 485 |
+
while token:
|
| 486 |
+
line_token, new_line, token = token.partition("\n")
|
| 487 |
+
yield token_type, line_token + new_line
|
| 488 |
+
|
| 489 |
+
def tokens_to_spans() -> Iterable[Tuple[str, Optional[Style]]]:
|
| 490 |
+
"""Convert tokens to spans."""
|
| 491 |
+
tokens = iter(line_tokenize())
|
| 492 |
+
line_no = 0
|
| 493 |
+
_line_start = line_start - 1 if line_start else 0
|
| 494 |
+
|
| 495 |
+
# Skip over tokens until line start
|
| 496 |
+
while line_no < _line_start:
|
| 497 |
+
try:
|
| 498 |
+
_token_type, token = next(tokens)
|
| 499 |
+
except StopIteration:
|
| 500 |
+
break
|
| 501 |
+
yield (token, None)
|
| 502 |
+
if token.endswith("\n"):
|
| 503 |
+
line_no += 1
|
| 504 |
+
# Generate spans until line end
|
| 505 |
+
for token_type, token in tokens:
|
| 506 |
+
yield (token, _get_theme_style(token_type))
|
| 507 |
+
if token.endswith("\n"):
|
| 508 |
+
line_no += 1
|
| 509 |
+
if line_end and line_no >= line_end:
|
| 510 |
+
break
|
| 511 |
+
|
| 512 |
+
text.append_tokens(tokens_to_spans())
|
| 513 |
+
|
| 514 |
+
else:
|
| 515 |
+
text.append_tokens(
|
| 516 |
+
(token, _get_theme_style(token_type))
|
| 517 |
+
for token_type, token in lexer.get_tokens(code)
|
| 518 |
+
)
|
| 519 |
+
if self.background_color is not None:
|
| 520 |
+
text.stylize(f"on {self.background_color}")
|
| 521 |
+
|
| 522 |
+
if self._stylized_ranges:
|
| 523 |
+
self._apply_stylized_ranges(text)
|
| 524 |
+
|
| 525 |
+
return text
|
| 526 |
+
|
| 527 |
+
def stylize_range(
|
| 528 |
+
self, style: StyleType, start: SyntaxPosition, end: SyntaxPosition
|
| 529 |
+
) -> None:
|
| 530 |
+
"""
|
| 531 |
+
Adds a custom style on a part of the code, that will be applied to the syntax display when it's rendered.
|
| 532 |
+
Line numbers are 1-based, while column indexes are 0-based.
|
| 533 |
+
|
| 534 |
+
Args:
|
| 535 |
+
style (StyleType): The style to apply.
|
| 536 |
+
start (Tuple[int, int]): The start of the range, in the form `[line number, column index]`.
|
| 537 |
+
end (Tuple[int, int]): The end of the range, in the form `[line number, column index]`.
|
| 538 |
+
"""
|
| 539 |
+
self._stylized_ranges.append(_SyntaxHighlightRange(style, start, end))
|
| 540 |
+
|
| 541 |
+
def _get_line_numbers_color(self, blend: float = 0.3) -> Color:
|
| 542 |
+
background_style = self._theme.get_background_style() + self.background_style
|
| 543 |
+
background_color = background_style.bgcolor
|
| 544 |
+
if background_color is None or background_color.is_system_defined:
|
| 545 |
+
return Color.default()
|
| 546 |
+
foreground_color = self._get_token_color(Token.Text)
|
| 547 |
+
if foreground_color is None or foreground_color.is_system_defined:
|
| 548 |
+
return foreground_color or Color.default()
|
| 549 |
+
new_color = blend_rgb(
|
| 550 |
+
background_color.get_truecolor(),
|
| 551 |
+
foreground_color.get_truecolor(),
|
| 552 |
+
cross_fade=blend,
|
| 553 |
+
)
|
| 554 |
+
return Color.from_triplet(new_color)
|
| 555 |
+
|
| 556 |
+
@property
|
| 557 |
+
def _numbers_column_width(self) -> int:
|
| 558 |
+
"""Get the number of characters used to render the numbers column."""
|
| 559 |
+
column_width = 0
|
| 560 |
+
if self.line_numbers:
|
| 561 |
+
column_width = (
|
| 562 |
+
len(str(self.start_line + self.code.count("\n")))
|
| 563 |
+
+ NUMBERS_COLUMN_DEFAULT_PADDING
|
| 564 |
+
)
|
| 565 |
+
return column_width
|
| 566 |
+
|
| 567 |
+
def _get_number_styles(self, console: Console) -> Tuple[Style, Style, Style]:
|
| 568 |
+
"""Get background, number, and highlight styles for line numbers."""
|
| 569 |
+
background_style = self._get_base_style()
|
| 570 |
+
if background_style.transparent_background:
|
| 571 |
+
return Style.null(), Style(dim=True), Style.null()
|
| 572 |
+
if console.color_system in ("256", "truecolor"):
|
| 573 |
+
number_style = Style.chain(
|
| 574 |
+
background_style,
|
| 575 |
+
self._theme.get_style_for_token(Token.Text),
|
| 576 |
+
Style(color=self._get_line_numbers_color()),
|
| 577 |
+
self.background_style,
|
| 578 |
+
)
|
| 579 |
+
highlight_number_style = Style.chain(
|
| 580 |
+
background_style,
|
| 581 |
+
self._theme.get_style_for_token(Token.Text),
|
| 582 |
+
Style(bold=True, color=self._get_line_numbers_color(0.9)),
|
| 583 |
+
self.background_style,
|
| 584 |
+
)
|
| 585 |
+
else:
|
| 586 |
+
number_style = background_style + Style(dim=True)
|
| 587 |
+
highlight_number_style = background_style + Style(dim=False)
|
| 588 |
+
return background_style, number_style, highlight_number_style
|
| 589 |
+
|
| 590 |
+
def __rich_measure__(
|
| 591 |
+
self, console: "Console", options: "ConsoleOptions"
|
| 592 |
+
) -> "Measurement":
|
| 593 |
+
_, right, _, left = Padding.unpack(self.padding)
|
| 594 |
+
padding = left + right
|
| 595 |
+
if self.code_width is not None:
|
| 596 |
+
width = self.code_width + self._numbers_column_width + padding + 1
|
| 597 |
+
return Measurement(self._numbers_column_width, width)
|
| 598 |
+
lines = self.code.splitlines()
|
| 599 |
+
width = (
|
| 600 |
+
self._numbers_column_width
|
| 601 |
+
+ padding
|
| 602 |
+
+ (max(cell_len(line) for line in lines) if lines else 0)
|
| 603 |
+
)
|
| 604 |
+
if self.line_numbers:
|
| 605 |
+
width += 1
|
| 606 |
+
return Measurement(self._numbers_column_width, width)
|
| 607 |
+
|
| 608 |
+
def __rich_console__(
|
| 609 |
+
self, console: Console, options: ConsoleOptions
|
| 610 |
+
) -> RenderResult:
|
| 611 |
+
segments = Segments(self._get_syntax(console, options))
|
| 612 |
+
if self.padding:
|
| 613 |
+
yield Padding(
|
| 614 |
+
segments, style=self._theme.get_background_style(), pad=self.padding
|
| 615 |
+
)
|
| 616 |
+
else:
|
| 617 |
+
yield segments
|
| 618 |
+
|
| 619 |
+
def _get_syntax(
|
| 620 |
+
self,
|
| 621 |
+
console: Console,
|
| 622 |
+
options: ConsoleOptions,
|
| 623 |
+
) -> Iterable[Segment]:
|
| 624 |
+
"""
|
| 625 |
+
Get the Segments for the Syntax object, excluding any vertical/horizontal padding
|
| 626 |
+
"""
|
| 627 |
+
transparent_background = self._get_base_style().transparent_background
|
| 628 |
+
code_width = (
|
| 629 |
+
(
|
| 630 |
+
(options.max_width - self._numbers_column_width - 1)
|
| 631 |
+
if self.line_numbers
|
| 632 |
+
else options.max_width
|
| 633 |
+
)
|
| 634 |
+
if self.code_width is None
|
| 635 |
+
else self.code_width
|
| 636 |
+
)
|
| 637 |
+
|
| 638 |
+
ends_on_nl, processed_code = self._process_code(self.code)
|
| 639 |
+
text = self.highlight(processed_code, self.line_range)
|
| 640 |
+
|
| 641 |
+
if not self.line_numbers and not self.word_wrap and not self.line_range:
|
| 642 |
+
if not ends_on_nl:
|
| 643 |
+
text.remove_suffix("\n")
|
| 644 |
+
# Simple case of just rendering text
|
| 645 |
+
style = (
|
| 646 |
+
self._get_base_style()
|
| 647 |
+
+ self._theme.get_style_for_token(Comment)
|
| 648 |
+
+ Style(dim=True)
|
| 649 |
+
+ self.background_style
|
| 650 |
+
)
|
| 651 |
+
if self.indent_guides and not options.ascii_only:
|
| 652 |
+
text = text.with_indent_guides(self.tab_size, style=style)
|
| 653 |
+
text.overflow = "crop"
|
| 654 |
+
if style.transparent_background:
|
| 655 |
+
yield from console.render(
|
| 656 |
+
text, options=options.update(width=code_width)
|
| 657 |
+
)
|
| 658 |
+
else:
|
| 659 |
+
syntax_lines = console.render_lines(
|
| 660 |
+
text,
|
| 661 |
+
options.update(width=code_width, height=None, justify="left"),
|
| 662 |
+
style=self.background_style,
|
| 663 |
+
pad=True,
|
| 664 |
+
new_lines=True,
|
| 665 |
+
)
|
| 666 |
+
for syntax_line in syntax_lines:
|
| 667 |
+
yield from syntax_line
|
| 668 |
+
return
|
| 669 |
+
|
| 670 |
+
start_line, end_line = self.line_range or (None, None)
|
| 671 |
+
line_offset = 0
|
| 672 |
+
if start_line:
|
| 673 |
+
line_offset = max(0, start_line - 1)
|
| 674 |
+
lines: Union[List[Text], Lines] = text.split("\n", allow_blank=ends_on_nl)
|
| 675 |
+
if self.line_range:
|
| 676 |
+
if line_offset > len(lines):
|
| 677 |
+
return
|
| 678 |
+
lines = lines[line_offset:end_line]
|
| 679 |
+
|
| 680 |
+
if self.indent_guides and not options.ascii_only:
|
| 681 |
+
style = (
|
| 682 |
+
self._get_base_style()
|
| 683 |
+
+ self._theme.get_style_for_token(Comment)
|
| 684 |
+
+ Style(dim=True)
|
| 685 |
+
+ self.background_style
|
| 686 |
+
)
|
| 687 |
+
lines = (
|
| 688 |
+
Text("\n")
|
| 689 |
+
.join(lines)
|
| 690 |
+
.with_indent_guides(self.tab_size, style=style + Style(italic=False))
|
| 691 |
+
.split("\n", allow_blank=True)
|
| 692 |
+
)
|
| 693 |
+
|
| 694 |
+
numbers_column_width = self._numbers_column_width
|
| 695 |
+
render_options = options.update(width=code_width)
|
| 696 |
+
|
| 697 |
+
highlight_line = self.highlight_lines.__contains__
|
| 698 |
+
_Segment = Segment
|
| 699 |
+
new_line = _Segment("\n")
|
| 700 |
+
|
| 701 |
+
line_pointer = "> " if options.legacy_windows else "❱ "
|
| 702 |
+
|
| 703 |
+
(
|
| 704 |
+
background_style,
|
| 705 |
+
number_style,
|
| 706 |
+
highlight_number_style,
|
| 707 |
+
) = self._get_number_styles(console)
|
| 708 |
+
|
| 709 |
+
for line_no, line in enumerate(lines, self.start_line + line_offset):
|
| 710 |
+
if self.word_wrap:
|
| 711 |
+
wrapped_lines = console.render_lines(
|
| 712 |
+
line,
|
| 713 |
+
render_options.update(height=None, justify="left"),
|
| 714 |
+
style=background_style,
|
| 715 |
+
pad=not transparent_background,
|
| 716 |
+
)
|
| 717 |
+
else:
|
| 718 |
+
segments = list(line.render(console, end=""))
|
| 719 |
+
if options.no_wrap:
|
| 720 |
+
wrapped_lines = [segments]
|
| 721 |
+
else:
|
| 722 |
+
wrapped_lines = [
|
| 723 |
+
_Segment.adjust_line_length(
|
| 724 |
+
segments,
|
| 725 |
+
render_options.max_width,
|
| 726 |
+
style=background_style,
|
| 727 |
+
pad=not transparent_background,
|
| 728 |
+
)
|
| 729 |
+
]
|
| 730 |
+
|
| 731 |
+
if self.line_numbers:
|
| 732 |
+
wrapped_line_left_pad = _Segment(
|
| 733 |
+
" " * numbers_column_width + " ", background_style
|
| 734 |
+
)
|
| 735 |
+
for first, wrapped_line in loop_first(wrapped_lines):
|
| 736 |
+
if first:
|
| 737 |
+
line_column = str(line_no).rjust(numbers_column_width - 2) + " "
|
| 738 |
+
if highlight_line(line_no):
|
| 739 |
+
yield _Segment(line_pointer, Style(color="red"))
|
| 740 |
+
yield _Segment(line_column, highlight_number_style)
|
| 741 |
+
else:
|
| 742 |
+
yield _Segment(" ", highlight_number_style)
|
| 743 |
+
yield _Segment(line_column, number_style)
|
| 744 |
+
else:
|
| 745 |
+
yield wrapped_line_left_pad
|
| 746 |
+
yield from wrapped_line
|
| 747 |
+
yield new_line
|
| 748 |
+
else:
|
| 749 |
+
for wrapped_line in wrapped_lines:
|
| 750 |
+
yield from wrapped_line
|
| 751 |
+
yield new_line
|
| 752 |
+
|
| 753 |
+
def _apply_stylized_ranges(self, text: Text) -> None:
|
| 754 |
+
"""
|
| 755 |
+
Apply stylized ranges to a text instance,
|
| 756 |
+
using the given code to determine the right portion to apply the style to.
|
| 757 |
+
|
| 758 |
+
Args:
|
| 759 |
+
text (Text): Text instance to apply the style to.
|
| 760 |
+
"""
|
| 761 |
+
code = text.plain
|
| 762 |
+
newlines_offsets = [
|
| 763 |
+
# Let's add outer boundaries at each side of the list:
|
| 764 |
+
0,
|
| 765 |
+
# N.B. using "\n" here is much faster than using metacharacters such as "^" or "\Z":
|
| 766 |
+
*[
|
| 767 |
+
match.start() + 1
|
| 768 |
+
for match in re.finditer("\n", code, flags=re.MULTILINE)
|
| 769 |
+
],
|
| 770 |
+
len(code) + 1,
|
| 771 |
+
]
|
| 772 |
+
|
| 773 |
+
for stylized_range in self._stylized_ranges:
|
| 774 |
+
start = _get_code_index_for_syntax_position(
|
| 775 |
+
newlines_offsets, stylized_range.start
|
| 776 |
+
)
|
| 777 |
+
end = _get_code_index_for_syntax_position(
|
| 778 |
+
newlines_offsets, stylized_range.end
|
| 779 |
+
)
|
| 780 |
+
if start is not None and end is not None:
|
| 781 |
+
text.stylize(stylized_range.style, start, end)
|
| 782 |
+
|
| 783 |
+
def _process_code(self, code: str) -> Tuple[bool, str]:
|
| 784 |
+
"""
|
| 785 |
+
Applies various processing to a raw code string
|
| 786 |
+
(normalises it so it always ends with a line return, dedents it if necessary, etc.)
|
| 787 |
+
|
| 788 |
+
Args:
|
| 789 |
+
code (str): The raw code string to process
|
| 790 |
+
|
| 791 |
+
Returns:
|
| 792 |
+
Tuple[bool, str]: the boolean indicates whether the raw code ends with a line return,
|
| 793 |
+
while the string is the processed code.
|
| 794 |
+
"""
|
| 795 |
+
ends_on_nl = code.endswith("\n")
|
| 796 |
+
processed_code = code if ends_on_nl else code + "\n"
|
| 797 |
+
processed_code = (
|
| 798 |
+
textwrap.dedent(processed_code) if self.dedent else processed_code
|
| 799 |
+
)
|
| 800 |
+
processed_code = processed_code.expandtabs(self.tab_size)
|
| 801 |
+
return ends_on_nl, processed_code
|
| 802 |
+
|
| 803 |
+
|
| 804 |
+
def _get_code_index_for_syntax_position(
|
| 805 |
+
newlines_offsets: Sequence[int], position: SyntaxPosition
|
| 806 |
+
) -> Optional[int]:
|
| 807 |
+
"""
|
| 808 |
+
Returns the index of the code string for the given positions.
|
| 809 |
+
|
| 810 |
+
Args:
|
| 811 |
+
newlines_offsets (Sequence[int]): The offset of each newline character found in the code snippet.
|
| 812 |
+
position (SyntaxPosition): The position to search for.
|
| 813 |
+
|
| 814 |
+
Returns:
|
| 815 |
+
Optional[int]: The index of the code string for this position, or `None`
|
| 816 |
+
if the given position's line number is out of range (if it's the column that is out of range
|
| 817 |
+
we silently clamp its value so that it reaches the end of the line)
|
| 818 |
+
"""
|
| 819 |
+
lines_count = len(newlines_offsets)
|
| 820 |
+
|
| 821 |
+
line_number, column_index = position
|
| 822 |
+
if line_number > lines_count or len(newlines_offsets) < (line_number + 1):
|
| 823 |
+
return None # `line_number` is out of range
|
| 824 |
+
line_index = line_number - 1
|
| 825 |
+
line_length = newlines_offsets[line_index + 1] - newlines_offsets[line_index] - 1
|
| 826 |
+
# If `column_index` is out of range: let's silently clamp it:
|
| 827 |
+
column_index = min(line_length, column_index)
|
| 828 |
+
return newlines_offsets[line_index] + column_index
|
| 829 |
+
|
| 830 |
+
|
| 831 |
+
if __name__ == "__main__": # pragma: no cover
|
| 832 |
+
import argparse
|
| 833 |
+
import sys
|
| 834 |
+
|
| 835 |
+
parser = argparse.ArgumentParser(
|
| 836 |
+
description="Render syntax to the console with Rich"
|
| 837 |
+
)
|
| 838 |
+
parser.add_argument(
|
| 839 |
+
"path",
|
| 840 |
+
metavar="PATH",
|
| 841 |
+
help="path to file, or - for stdin",
|
| 842 |
+
)
|
| 843 |
+
parser.add_argument(
|
| 844 |
+
"-c",
|
| 845 |
+
"--force-color",
|
| 846 |
+
dest="force_color",
|
| 847 |
+
action="store_true",
|
| 848 |
+
default=None,
|
| 849 |
+
help="force color for non-terminals",
|
| 850 |
+
)
|
| 851 |
+
parser.add_argument(
|
| 852 |
+
"-i",
|
| 853 |
+
"--indent-guides",
|
| 854 |
+
dest="indent_guides",
|
| 855 |
+
action="store_true",
|
| 856 |
+
default=False,
|
| 857 |
+
help="display indent guides",
|
| 858 |
+
)
|
| 859 |
+
parser.add_argument(
|
| 860 |
+
"-l",
|
| 861 |
+
"--line-numbers",
|
| 862 |
+
dest="line_numbers",
|
| 863 |
+
action="store_true",
|
| 864 |
+
help="render line numbers",
|
| 865 |
+
)
|
| 866 |
+
parser.add_argument(
|
| 867 |
+
"-w",
|
| 868 |
+
"--width",
|
| 869 |
+
type=int,
|
| 870 |
+
dest="width",
|
| 871 |
+
default=None,
|
| 872 |
+
help="width of output (default will auto-detect)",
|
| 873 |
+
)
|
| 874 |
+
parser.add_argument(
|
| 875 |
+
"-r",
|
| 876 |
+
"--wrap",
|
| 877 |
+
dest="word_wrap",
|
| 878 |
+
action="store_true",
|
| 879 |
+
default=False,
|
| 880 |
+
help="word wrap long lines",
|
| 881 |
+
)
|
| 882 |
+
parser.add_argument(
|
| 883 |
+
"-s",
|
| 884 |
+
"--soft-wrap",
|
| 885 |
+
action="store_true",
|
| 886 |
+
dest="soft_wrap",
|
| 887 |
+
default=False,
|
| 888 |
+
help="enable soft wrapping mode",
|
| 889 |
+
)
|
| 890 |
+
parser.add_argument(
|
| 891 |
+
"-t", "--theme", dest="theme", default="monokai", help="pygments theme"
|
| 892 |
+
)
|
| 893 |
+
parser.add_argument(
|
| 894 |
+
"-b",
|
| 895 |
+
"--background-color",
|
| 896 |
+
dest="background_color",
|
| 897 |
+
default=None,
|
| 898 |
+
help="Override background color",
|
| 899 |
+
)
|
| 900 |
+
parser.add_argument(
|
| 901 |
+
"-x",
|
| 902 |
+
"--lexer",
|
| 903 |
+
default=None,
|
| 904 |
+
dest="lexer_name",
|
| 905 |
+
help="Lexer name",
|
| 906 |
+
)
|
| 907 |
+
parser.add_argument(
|
| 908 |
+
"-p", "--padding", type=int, default=0, dest="padding", help="Padding"
|
| 909 |
+
)
|
| 910 |
+
parser.add_argument(
|
| 911 |
+
"--highlight-line",
|
| 912 |
+
type=int,
|
| 913 |
+
default=None,
|
| 914 |
+
dest="highlight_line",
|
| 915 |
+
help="The line number (not index!) to highlight",
|
| 916 |
+
)
|
| 917 |
+
args = parser.parse_args()
|
| 918 |
+
|
| 919 |
+
from pip._vendor.rich.console import Console
|
| 920 |
+
|
| 921 |
+
console = Console(force_terminal=args.force_color, width=args.width)
|
| 922 |
+
|
| 923 |
+
if args.path == "-":
|
| 924 |
+
code = sys.stdin.read()
|
| 925 |
+
syntax = Syntax(
|
| 926 |
+
code=code,
|
| 927 |
+
lexer=args.lexer_name,
|
| 928 |
+
line_numbers=args.line_numbers,
|
| 929 |
+
word_wrap=args.word_wrap,
|
| 930 |
+
theme=args.theme,
|
| 931 |
+
background_color=args.background_color,
|
| 932 |
+
indent_guides=args.indent_guides,
|
| 933 |
+
padding=args.padding,
|
| 934 |
+
highlight_lines={args.highlight_line},
|
| 935 |
+
)
|
| 936 |
+
else:
|
| 937 |
+
syntax = Syntax.from_path(
|
| 938 |
+
args.path,
|
| 939 |
+
lexer=args.lexer_name,
|
| 940 |
+
line_numbers=args.line_numbers,
|
| 941 |
+
word_wrap=args.word_wrap,
|
| 942 |
+
theme=args.theme,
|
| 943 |
+
background_color=args.background_color,
|
| 944 |
+
indent_guides=args.indent_guides,
|
| 945 |
+
padding=args.padding,
|
| 946 |
+
highlight_lines={args.highlight_line},
|
| 947 |
+
)
|
| 948 |
+
console.print(syntax, soft_wrap=args.soft_wrap)
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35/lib/python3.12/site-packages/pip/_vendor/rich/terminal_theme.py
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import List, Optional, Tuple
|
| 2 |
+
|
| 3 |
+
from .color_triplet import ColorTriplet
|
| 4 |
+
from .palette import Palette
|
| 5 |
+
|
| 6 |
+
_ColorTuple = Tuple[int, int, int]
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class TerminalTheme:
|
| 10 |
+
"""A color theme used when exporting console content.
|
| 11 |
+
|
| 12 |
+
Args:
|
| 13 |
+
background (Tuple[int, int, int]): The background color.
|
| 14 |
+
foreground (Tuple[int, int, int]): The foreground (text) color.
|
| 15 |
+
normal (List[Tuple[int, int, int]]): A list of 8 normal intensity colors.
|
| 16 |
+
bright (List[Tuple[int, int, int]], optional): A list of 8 bright colors, or None
|
| 17 |
+
to repeat normal intensity. Defaults to None.
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
def __init__(
|
| 21 |
+
self,
|
| 22 |
+
background: _ColorTuple,
|
| 23 |
+
foreground: _ColorTuple,
|
| 24 |
+
normal: List[_ColorTuple],
|
| 25 |
+
bright: Optional[List[_ColorTuple]] = None,
|
| 26 |
+
) -> None:
|
| 27 |
+
self.background_color = ColorTriplet(*background)
|
| 28 |
+
self.foreground_color = ColorTriplet(*foreground)
|
| 29 |
+
self.ansi_colors = Palette(normal + (bright or normal))
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
DEFAULT_TERMINAL_THEME = TerminalTheme(
|
| 33 |
+
(255, 255, 255),
|
| 34 |
+
(0, 0, 0),
|
| 35 |
+
[
|
| 36 |
+
(0, 0, 0),
|
| 37 |
+
(128, 0, 0),
|
| 38 |
+
(0, 128, 0),
|
| 39 |
+
(128, 128, 0),
|
| 40 |
+
(0, 0, 128),
|
| 41 |
+
(128, 0, 128),
|
| 42 |
+
(0, 128, 128),
|
| 43 |
+
(192, 192, 192),
|
| 44 |
+
],
|
| 45 |
+
[
|
| 46 |
+
(128, 128, 128),
|
| 47 |
+
(255, 0, 0),
|
| 48 |
+
(0, 255, 0),
|
| 49 |
+
(255, 255, 0),
|
| 50 |
+
(0, 0, 255),
|
| 51 |
+
(255, 0, 255),
|
| 52 |
+
(0, 255, 255),
|
| 53 |
+
(255, 255, 255),
|
| 54 |
+
],
|
| 55 |
+
)
|
| 56 |
+
|
| 57 |
+
MONOKAI = TerminalTheme(
|
| 58 |
+
(12, 12, 12),
|
| 59 |
+
(217, 217, 217),
|
| 60 |
+
[
|
| 61 |
+
(26, 26, 26),
|
| 62 |
+
(244, 0, 95),
|
| 63 |
+
(152, 224, 36),
|
| 64 |
+
(253, 151, 31),
|
| 65 |
+
(157, 101, 255),
|
| 66 |
+
(244, 0, 95),
|
| 67 |
+
(88, 209, 235),
|
| 68 |
+
(196, 197, 181),
|
| 69 |
+
(98, 94, 76),
|
| 70 |
+
],
|
| 71 |
+
[
|
| 72 |
+
(244, 0, 95),
|
| 73 |
+
(152, 224, 36),
|
| 74 |
+
(224, 213, 97),
|
| 75 |
+
(157, 101, 255),
|
| 76 |
+
(244, 0, 95),
|
| 77 |
+
(88, 209, 235),
|
| 78 |
+
(246, 246, 239),
|
| 79 |
+
],
|
| 80 |
+
)
|
| 81 |
+
DIMMED_MONOKAI = TerminalTheme(
|
| 82 |
+
(25, 25, 25),
|
| 83 |
+
(185, 188, 186),
|
| 84 |
+
[
|
| 85 |
+
(58, 61, 67),
|
| 86 |
+
(190, 63, 72),
|
| 87 |
+
(135, 154, 59),
|
| 88 |
+
(197, 166, 53),
|
| 89 |
+
(79, 118, 161),
|
| 90 |
+
(133, 92, 141),
|
| 91 |
+
(87, 143, 164),
|
| 92 |
+
(185, 188, 186),
|
| 93 |
+
(136, 137, 135),
|
| 94 |
+
],
|
| 95 |
+
[
|
| 96 |
+
(251, 0, 31),
|
| 97 |
+
(15, 114, 47),
|
| 98 |
+
(196, 112, 51),
|
| 99 |
+
(24, 109, 227),
|
| 100 |
+
(251, 0, 103),
|
| 101 |
+
(46, 112, 109),
|
| 102 |
+
(253, 255, 185),
|
| 103 |
+
],
|
| 104 |
+
)
|
| 105 |
+
NIGHT_OWLISH = TerminalTheme(
|
| 106 |
+
(255, 255, 255),
|
| 107 |
+
(64, 63, 83),
|
| 108 |
+
[
|
| 109 |
+
(1, 22, 39),
|
| 110 |
+
(211, 66, 62),
|
| 111 |
+
(42, 162, 152),
|
| 112 |
+
(218, 170, 1),
|
| 113 |
+
(72, 118, 214),
|
| 114 |
+
(64, 63, 83),
|
| 115 |
+
(8, 145, 106),
|
| 116 |
+
(122, 129, 129),
|
| 117 |
+
(122, 129, 129),
|
| 118 |
+
],
|
| 119 |
+
[
|
| 120 |
+
(247, 110, 110),
|
| 121 |
+
(73, 208, 197),
|
| 122 |
+
(218, 194, 107),
|
| 123 |
+
(92, 167, 228),
|
| 124 |
+
(105, 112, 152),
|
| 125 |
+
(0, 201, 144),
|
| 126 |
+
(152, 159, 177),
|
| 127 |
+
],
|
| 128 |
+
)
|
| 129 |
+
|
| 130 |
+
SVG_EXPORT_THEME = TerminalTheme(
|
| 131 |
+
(41, 41, 41),
|
| 132 |
+
(197, 200, 198),
|
| 133 |
+
[
|
| 134 |
+
(75, 78, 85),
|
| 135 |
+
(204, 85, 90),
|
| 136 |
+
(152, 168, 75),
|
| 137 |
+
(208, 179, 68),
|
| 138 |
+
(96, 138, 177),
|
| 139 |
+
(152, 114, 159),
|
| 140 |
+
(104, 160, 179),
|
| 141 |
+
(197, 200, 198),
|
| 142 |
+
(154, 155, 153),
|
| 143 |
+
],
|
| 144 |
+
[
|
| 145 |
+
(255, 38, 39),
|
| 146 |
+
(0, 130, 61),
|
| 147 |
+
(208, 132, 66),
|
| 148 |
+
(25, 132, 233),
|
| 149 |
+
(255, 44, 122),
|
| 150 |
+
(57, 130, 128),
|
| 151 |
+
(253, 253, 197),
|
| 152 |
+
],
|
| 153 |
+
)
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/moonshine_streaming/configuration_moonshine_streaming.py
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2026 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 |
+
|
| 15 |
+
|
| 16 |
+
from huggingface_hub.dataclasses import strict
|
| 17 |
+
|
| 18 |
+
from ...configuration_utils import PreTrainedConfig
|
| 19 |
+
from ...modeling_rope_utils import RopeParameters
|
| 20 |
+
from ...utils import auto_docstring
|
| 21 |
+
from ..auto import CONFIG_MAPPING
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
@auto_docstring(checkpoint="UsefulSensors/moonshine-streaming-tiny")
|
| 25 |
+
@strict
|
| 26 |
+
class MoonshineStreamingEncoderConfig(PreTrainedConfig):
|
| 27 |
+
r"""
|
| 28 |
+
sample_rate (`int`, *optional*, defaults to 16000):
|
| 29 |
+
The sample rate of the audio input in Hz.
|
| 30 |
+
frame_ms (`float`, *optional*, defaults to 5.0):
|
| 31 |
+
The frame duration in milliseconds for audio processing.
|
| 32 |
+
sliding_windows (`list[tuple[int, int]]`, *optional*, defaults to `[(16, 4), (16, 4), (16, 0), (16, 0), (16, 4), (16, 4)]`):
|
| 33 |
+
List of sliding window configurations for each encoder layer. Each tuple contains (window_size, shift).
|
| 34 |
+
|
| 35 |
+
```python
|
| 36 |
+
>>> from transformers import MoonshineStreamingEncoder, MoonshineStreamingEncoderConfig
|
| 37 |
+
|
| 38 |
+
>>> # Initializing a Moonshine Streaming encoder configuration
|
| 39 |
+
>>> configuration = MoonshineStreamingEncoderConfig()
|
| 40 |
+
|
| 41 |
+
>>> # Initializing a model from the configuration
|
| 42 |
+
>>> model = MoonshineStreamingEncoder(configuration)
|
| 43 |
+
|
| 44 |
+
>>> # Accessing the model configuration
|
| 45 |
+
>>> configuration = model.config
|
| 46 |
+
```
|
| 47 |
+
"""
|
| 48 |
+
|
| 49 |
+
model_type = "moonshine_streaming_encoder"
|
| 50 |
+
|
| 51 |
+
hidden_size: int = 320
|
| 52 |
+
intermediate_size: int = 1280
|
| 53 |
+
hidden_act: str = "gelu"
|
| 54 |
+
num_hidden_layers: int = 6
|
| 55 |
+
num_attention_heads: int = 8
|
| 56 |
+
num_key_value_heads: int = 8
|
| 57 |
+
max_position_embeddings: int = 4096
|
| 58 |
+
attention_dropout: float | int = 0.0
|
| 59 |
+
attention_bias: bool = False
|
| 60 |
+
sample_rate: int = 16000
|
| 61 |
+
frame_ms: float = 5.0
|
| 62 |
+
sliding_windows: tuple[tuple[int, int], ...] | list[list[int, int]] = (
|
| 63 |
+
(16, 4),
|
| 64 |
+
(16, 4),
|
| 65 |
+
(16, 0),
|
| 66 |
+
(16, 0),
|
| 67 |
+
(16, 4),
|
| 68 |
+
(16, 4),
|
| 69 |
+
)
|
| 70 |
+
head_dim: int | None = None
|
| 71 |
+
|
| 72 |
+
def __post_init__(self, **kwargs):
|
| 73 |
+
self.head_dim = self.head_dim if self.head_dim is not None else self.hidden_size // self.num_attention_heads
|
| 74 |
+
self.sliding_windows = [list(window) for window in self.sliding_windows]
|
| 75 |
+
|
| 76 |
+
super().__post_init__(**kwargs)
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
@auto_docstring(checkpoint="UsefulSensors/moonshine-streaming-tiny")
|
| 80 |
+
@strict
|
| 81 |
+
class MoonshineStreamingConfig(PreTrainedConfig):
|
| 82 |
+
r"""
|
| 83 |
+
pad_head_dim_to_multiple_of (`int`, *optional*):
|
| 84 |
+
If set, the head dimension will be padded to a multiple of this value.
|
| 85 |
+
|
| 86 |
+
```python
|
| 87 |
+
>>> from transformers import MoonshineStreamingModel, MoonshineStreamingConfig
|
| 88 |
+
|
| 89 |
+
>>> # Initializing a Moonshine Streaming configuration
|
| 90 |
+
>>> configuration = MoonshineStreamingConfig()
|
| 91 |
+
|
| 92 |
+
>>> # Initializing a model from the configuration
|
| 93 |
+
>>> model = MoonshineStreamingModel(configuration)
|
| 94 |
+
|
| 95 |
+
>>> # Accessing the model configuration
|
| 96 |
+
>>> configuration = model.config
|
| 97 |
+
```
|
| 98 |
+
"""
|
| 99 |
+
|
| 100 |
+
model_type = "moonshine_streaming"
|
| 101 |
+
sub_configs = {"encoder_config": MoonshineStreamingEncoderConfig}
|
| 102 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
| 103 |
+
|
| 104 |
+
encoder_config: dict | MoonshineStreamingEncoderConfig | None = None
|
| 105 |
+
vocab_size: int = 32768
|
| 106 |
+
hidden_size: int = 320
|
| 107 |
+
intermediate_size: int = 1280
|
| 108 |
+
num_hidden_layers: int = 6
|
| 109 |
+
num_attention_heads: int = 8
|
| 110 |
+
hidden_act: str = "silu"
|
| 111 |
+
max_position_embeddings: int = 4096
|
| 112 |
+
use_cache: bool = True
|
| 113 |
+
pad_token_id: int | None = 0
|
| 114 |
+
bos_token_id: int | None = 1
|
| 115 |
+
eos_token_id: int | list[int] | None = 2
|
| 116 |
+
rope_parameters: RopeParameters | dict | None = None
|
| 117 |
+
attention_bias: bool = False
|
| 118 |
+
attention_dropout: float | int = 0.0
|
| 119 |
+
decoder_start_token_id: int | None = None
|
| 120 |
+
head_dim: int | None = None
|
| 121 |
+
pad_head_dim_to_multiple_of: int | None = None
|
| 122 |
+
tie_word_embeddings: bool = False
|
| 123 |
+
is_encoder_decoder: bool = True
|
| 124 |
+
|
| 125 |
+
def __post_init__(self, **kwargs):
|
| 126 |
+
if isinstance(self.encoder_config, dict):
|
| 127 |
+
self.encoder_config["model_type"] = self.encoder_config.get("model_type", "moonshine_streaming_encoder")
|
| 128 |
+
self.encoder_config = CONFIG_MAPPING[self.encoder_config["model_type"]](**self.encoder_config)
|
| 129 |
+
elif self.encoder_config is None:
|
| 130 |
+
self.encoder_config = CONFIG_MAPPING["moonshine_streaming_encoder"]()
|
| 131 |
+
|
| 132 |
+
if self.rope_parameters is None:
|
| 133 |
+
self.rope_parameters = {
|
| 134 |
+
"rope_type": "default",
|
| 135 |
+
"rope_theta": 10000.0,
|
| 136 |
+
"partial_rotary_factor": 0.8,
|
| 137 |
+
}
|
| 138 |
+
self.head_dim = self.head_dim if self.head_dim is not None else self.hidden_size // self.num_attention_heads
|
| 139 |
+
super().__post_init__(**kwargs)
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
__all__ = ["MoonshineStreamingConfig", "MoonshineStreamingEncoderConfig"]
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/moonshine_streaming/modeling_moonshine_streaming.py
ADDED
|
@@ -0,0 +1,1121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 2 |
+
# This file was automatically generated from src/transformers/models/moonshine_streaming/modular_moonshine_streaming.py.
|
| 3 |
+
# Do NOT edit this file manually as any edits will be overwritten by the generation of
|
| 4 |
+
# the file from the modular. If any change should be done, please apply the change to the
|
| 5 |
+
# modular_moonshine_streaming.py file directly. One of our CI enforces this.
|
| 6 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 7 |
+
# Copyright 2026 the HuggingFace Team. All rights reserved.
|
| 8 |
+
#
|
| 9 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 10 |
+
# you may not use this file except in compliance with the License.
|
| 11 |
+
# You may obtain a copy of the License at
|
| 12 |
+
#
|
| 13 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 14 |
+
#
|
| 15 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 16 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 17 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 18 |
+
# See the License for the specific language governing permissions and
|
| 19 |
+
# limitations under the License.
|
| 20 |
+
|
| 21 |
+
from collections.abc import Callable
|
| 22 |
+
from dataclasses import dataclass
|
| 23 |
+
from typing import Optional
|
| 24 |
+
|
| 25 |
+
import torch
|
| 26 |
+
import torch.nn as nn
|
| 27 |
+
from torch import Tensor
|
| 28 |
+
|
| 29 |
+
from ...activations import ACT2FN
|
| 30 |
+
from ...cache_utils import Cache, DynamicCache, EncoderDecoderCache
|
| 31 |
+
from ...generation import GenerationMixin
|
| 32 |
+
from ...integrations import use_kernelized_func
|
| 33 |
+
from ...masking_utils import create_bidirectional_mask, create_causal_mask
|
| 34 |
+
from ...modeling_flash_attention_utils import FlashAttentionKwargs
|
| 35 |
+
from ...modeling_layers import GradientCheckpointingLayer
|
| 36 |
+
from ...modeling_outputs import (
|
| 37 |
+
BaseModelOutput,
|
| 38 |
+
BaseModelOutputWithPast,
|
| 39 |
+
BaseModelOutputWithPastAndCrossAttentions,
|
| 40 |
+
Seq2SeqLMOutput,
|
| 41 |
+
Seq2SeqModelOutput,
|
| 42 |
+
)
|
| 43 |
+
from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
|
| 44 |
+
from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
|
| 45 |
+
from ...processing_utils import Unpack
|
| 46 |
+
from ...utils import TransformersKwargs, auto_docstring, can_return_tuple
|
| 47 |
+
from ...utils.generic import maybe_autocast, merge_with_config_defaults
|
| 48 |
+
from ...utils.output_capturing import OutputRecorder, capture_outputs
|
| 49 |
+
from .configuration_moonshine_streaming import MoonshineStreamingConfig, MoonshineStreamingEncoderConfig
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
@auto_docstring(
|
| 53 |
+
custom_intro="""
|
| 54 |
+
Extends [~modeling_outputs.BaseModelOutput] to include the output attention mask since sequence length is not preserved in the model's forward.
|
| 55 |
+
"""
|
| 56 |
+
)
|
| 57 |
+
@dataclass
|
| 58 |
+
class MoonshineStreamingEncoderModelOutput(BaseModelOutput):
|
| 59 |
+
r"""
|
| 60 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 61 |
+
Mask to avoid performing attention on padding token indices after sequence compression. Returned because the
|
| 62 |
+
sequence length may differ from the input sequence length. Mask values selected in `[0, 1]`:
|
| 63 |
+
|
| 64 |
+
- 1 for tokens that are **not masked**,
|
| 65 |
+
- 0 for tokens that are **masked**.
|
| 66 |
+
"""
|
| 67 |
+
|
| 68 |
+
attention_mask: torch.Tensor | None = None
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
class MoonshineStreamingFrameCMVN(nn.Module):
|
| 72 |
+
def __init__(self, eps: float = 1e-6):
|
| 73 |
+
super().__init__()
|
| 74 |
+
self.eps = eps
|
| 75 |
+
|
| 76 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 77 |
+
mean = x.mean(dim=-1, keepdim=True)
|
| 78 |
+
centered = x - mean
|
| 79 |
+
rms = (centered.pow(2).mean(dim=-1, keepdim=True) + self.eps).sqrt()
|
| 80 |
+
return centered / rms
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
class MoonshineStreamingAsinhCompression(nn.Module):
|
| 84 |
+
def __init__(self, k_init: float = 0.75):
|
| 85 |
+
super().__init__()
|
| 86 |
+
self.log_k = nn.Parameter(torch.log(torch.tensor(k_init)))
|
| 87 |
+
|
| 88 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 89 |
+
return torch.asinh(torch.exp(self.log_k) * x)
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
class MoonshineStreamingCausalConv1d(nn.Conv1d):
|
| 93 |
+
def __init__(
|
| 94 |
+
self,
|
| 95 |
+
in_channels: int,
|
| 96 |
+
out_channels: int,
|
| 97 |
+
kernel_size: int,
|
| 98 |
+
stride: int = 1,
|
| 99 |
+
dilation: int = 1,
|
| 100 |
+
bias: bool = True,
|
| 101 |
+
):
|
| 102 |
+
super().__init__(in_channels, out_channels, kernel_size, stride=stride, dilation=dilation, bias=bias)
|
| 103 |
+
self.left_pad = (kernel_size - 1) * dilation
|
| 104 |
+
|
| 105 |
+
def forward(self, x: torch.Tensor, mask: torch.Tensor | None = None) -> torch.Tensor:
|
| 106 |
+
x = nn.functional.pad(x, (self.left_pad, 0))
|
| 107 |
+
x = super().forward(x)
|
| 108 |
+
|
| 109 |
+
if mask is not None:
|
| 110 |
+
mask = nn.functional.pad(mask, (self.left_pad, 0))[:, None, :]
|
| 111 |
+
weight = torch.ones(1, 1, self.kernel_size[0], device=mask.device)
|
| 112 |
+
mask = nn.functional.conv1d(mask.float(), weight, stride=self.stride)
|
| 113 |
+
mask = mask > 0
|
| 114 |
+
x *= mask
|
| 115 |
+
|
| 116 |
+
if mask is not None:
|
| 117 |
+
mask = mask.squeeze(1)
|
| 118 |
+
return x, mask
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
class MoonshineStreamingLayerNorm(nn.Module):
|
| 122 |
+
def __init__(self, dim: int, unit_offset: bool = True, device=None, dtype=None):
|
| 123 |
+
super().__init__()
|
| 124 |
+
self.unit_offset = float(unit_offset)
|
| 125 |
+
self.ln = nn.LayerNorm(dim, elementwise_affine=False, device=device, dtype=dtype)
|
| 126 |
+
self.gamma = nn.Parameter(torch.ones(dim, device=device, dtype=dtype))
|
| 127 |
+
|
| 128 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 129 |
+
normed = self.ln(x)
|
| 130 |
+
gamma = self.gamma + self.unit_offset
|
| 131 |
+
return normed * gamma
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
class MoonshineStreamingEncoderMLP(nn.Module):
|
| 135 |
+
def __init__(self, config, hidden_act):
|
| 136 |
+
super().__init__()
|
| 137 |
+
self.config = config
|
| 138 |
+
self.activation_fn = ACT2FN[hidden_act]
|
| 139 |
+
self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
|
| 140 |
+
self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
|
| 141 |
+
|
| 142 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 143 |
+
hidden_states = self.fc1(hidden_states)
|
| 144 |
+
hidden_states = self.activation_fn(hidden_states)
|
| 145 |
+
hidden_states = self.fc2(hidden_states)
|
| 146 |
+
return hidden_states
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
| 150 |
+
"""
|
| 151 |
+
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
|
| 152 |
+
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
|
| 153 |
+
"""
|
| 154 |
+
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
|
| 155 |
+
if n_rep == 1:
|
| 156 |
+
return hidden_states
|
| 157 |
+
hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
|
| 158 |
+
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def eager_attention_forward(
|
| 162 |
+
module: nn.Module,
|
| 163 |
+
query: torch.Tensor,
|
| 164 |
+
key: torch.Tensor,
|
| 165 |
+
value: torch.Tensor,
|
| 166 |
+
attention_mask: torch.Tensor | None,
|
| 167 |
+
scaling: float,
|
| 168 |
+
dropout: float = 0.0,
|
| 169 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 170 |
+
):
|
| 171 |
+
key_states = repeat_kv(key, module.num_key_value_groups)
|
| 172 |
+
value_states = repeat_kv(value, module.num_key_value_groups)
|
| 173 |
+
|
| 174 |
+
attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
|
| 175 |
+
if attention_mask is not None:
|
| 176 |
+
attn_weights = attn_weights + attention_mask
|
| 177 |
+
|
| 178 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
|
| 179 |
+
attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
|
| 180 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
| 181 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
| 182 |
+
|
| 183 |
+
return attn_output, attn_weights
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
class MoonshineStreamingEncoderAttention(nn.Module):
|
| 187 |
+
def __init__(self, config: MoonshineStreamingConfig, layer_idx: int):
|
| 188 |
+
super().__init__()
|
| 189 |
+
self.config = config
|
| 190 |
+
self.layer_idx = layer_idx
|
| 191 |
+
self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
|
| 192 |
+
self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
|
| 193 |
+
self.scaling = self.head_dim**-0.5
|
| 194 |
+
self.attention_dropout = config.attention_dropout
|
| 195 |
+
self.is_causal = False
|
| 196 |
+
|
| 197 |
+
self.q_proj = nn.Linear(
|
| 198 |
+
config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
|
| 199 |
+
)
|
| 200 |
+
self.k_proj = nn.Linear(
|
| 201 |
+
config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
|
| 202 |
+
)
|
| 203 |
+
self.v_proj = nn.Linear(
|
| 204 |
+
config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
|
| 205 |
+
)
|
| 206 |
+
self.o_proj = nn.Linear(
|
| 207 |
+
config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
|
| 208 |
+
)
|
| 209 |
+
|
| 210 |
+
def forward(
|
| 211 |
+
self,
|
| 212 |
+
hidden_states: torch.Tensor,
|
| 213 |
+
attention_mask: torch.Tensor | None = None,
|
| 214 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 215 |
+
) -> tuple[torch.Tensor, torch.Tensor]:
|
| 216 |
+
input_shape = hidden_states.shape[:-1]
|
| 217 |
+
hidden_shape = (*input_shape, -1, self.head_dim)
|
| 218 |
+
|
| 219 |
+
query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 220 |
+
key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 221 |
+
value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 222 |
+
|
| 223 |
+
attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
|
| 224 |
+
self.config._attn_implementation, eager_attention_forward
|
| 225 |
+
)
|
| 226 |
+
|
| 227 |
+
attn_output, attn_weights = attention_interface(
|
| 228 |
+
self,
|
| 229 |
+
query_states,
|
| 230 |
+
key_states,
|
| 231 |
+
value_states,
|
| 232 |
+
attention_mask,
|
| 233 |
+
dropout=0.0 if not self.training else self.attention_dropout,
|
| 234 |
+
scaling=self.scaling,
|
| 235 |
+
**kwargs,
|
| 236 |
+
)
|
| 237 |
+
|
| 238 |
+
attn_output = attn_output.reshape(*input_shape, -1).contiguous()
|
| 239 |
+
attn_output = self.o_proj(attn_output)
|
| 240 |
+
return attn_output, attn_weights
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
class MoonshineStreamingEncoderLayer(GradientCheckpointingLayer):
|
| 244 |
+
def __init__(self, config: MoonshineStreamingConfig, layer_idx: int):
|
| 245 |
+
super().__init__()
|
| 246 |
+
self.hidden_size = config.hidden_size
|
| 247 |
+
self.self_attn = MoonshineStreamingEncoderAttention(config, layer_idx)
|
| 248 |
+
self.mlp = MoonshineStreamingEncoderMLP(config, config.hidden_act)
|
| 249 |
+
self.input_layernorm = MoonshineStreamingLayerNorm(config.hidden_size)
|
| 250 |
+
self.post_attention_layernorm = MoonshineStreamingLayerNorm(config.hidden_size)
|
| 251 |
+
|
| 252 |
+
def forward(
|
| 253 |
+
self,
|
| 254 |
+
hidden_states: torch.Tensor,
|
| 255 |
+
attention_mask: torch.Tensor | None = None,
|
| 256 |
+
position_ids: torch.LongTensor | None = None,
|
| 257 |
+
past_key_values: Cache | None = None,
|
| 258 |
+
use_cache: bool | None = False,
|
| 259 |
+
position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
|
| 260 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 261 |
+
) -> torch.Tensor:
|
| 262 |
+
residual = hidden_states
|
| 263 |
+
hidden_states = self.input_layernorm(hidden_states)
|
| 264 |
+
# Self Attention
|
| 265 |
+
hidden_states, _ = self.self_attn(
|
| 266 |
+
hidden_states=hidden_states,
|
| 267 |
+
attention_mask=attention_mask,
|
| 268 |
+
position_ids=position_ids,
|
| 269 |
+
past_key_values=past_key_values,
|
| 270 |
+
use_cache=use_cache,
|
| 271 |
+
position_embeddings=position_embeddings,
|
| 272 |
+
**kwargs,
|
| 273 |
+
)
|
| 274 |
+
hidden_states = residual + hidden_states
|
| 275 |
+
|
| 276 |
+
# Fully Connected
|
| 277 |
+
residual = hidden_states
|
| 278 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
| 279 |
+
hidden_states = self.mlp(hidden_states)
|
| 280 |
+
hidden_states = residual + hidden_states
|
| 281 |
+
return hidden_states
|
| 282 |
+
|
| 283 |
+
|
| 284 |
+
class MoonshineStreamingEncoderEmbedder(nn.Module):
|
| 285 |
+
def __init__(self, config):
|
| 286 |
+
super().__init__()
|
| 287 |
+
self.cmvn = MoonshineStreamingFrameCMVN()
|
| 288 |
+
self.comp = MoonshineStreamingAsinhCompression()
|
| 289 |
+
self.conv1 = MoonshineStreamingCausalConv1d(
|
| 290 |
+
config.hidden_size, config.hidden_size * 2, kernel_size=5, stride=2
|
| 291 |
+
)
|
| 292 |
+
self.conv2 = MoonshineStreamingCausalConv1d(
|
| 293 |
+
config.hidden_size * 2, config.hidden_size, kernel_size=5, stride=2
|
| 294 |
+
)
|
| 295 |
+
self.frame_len = int(round(config.sample_rate * config.frame_ms / 1000.0))
|
| 296 |
+
self.linear = nn.Linear(self.frame_len, config.hidden_size, bias=False)
|
| 297 |
+
|
| 298 |
+
def forward(self, input_values, padding_mask=None):
|
| 299 |
+
hidden_states = self.cmvn(input_values.reshape(input_values.shape[0], -1, self.frame_len))
|
| 300 |
+
hidden_states = self.comp(hidden_states)
|
| 301 |
+
hidden_states = nn.functional.silu(self.linear(hidden_states))
|
| 302 |
+
|
| 303 |
+
if padding_mask is not None:
|
| 304 |
+
num_frames = padding_mask.sum(-1) // self.frame_len
|
| 305 |
+
padding_mask = (
|
| 306 |
+
torch.arange(hidden_states.shape[1], device=padding_mask.device)[None, :] < num_frames[:, None]
|
| 307 |
+
)
|
| 308 |
+
hidden_states *= padding_mask[..., None]
|
| 309 |
+
|
| 310 |
+
hidden_states = hidden_states.transpose(1, 2)
|
| 311 |
+
hidden_states, padding_mask = self.conv1(hidden_states, padding_mask)
|
| 312 |
+
hidden_states = nn.functional.silu(hidden_states)
|
| 313 |
+
hidden_states, padding_mask = self.conv2(hidden_states, padding_mask)
|
| 314 |
+
hidden_states = hidden_states.transpose(1, 2)
|
| 315 |
+
return hidden_states, padding_mask
|
| 316 |
+
|
| 317 |
+
|
| 318 |
+
@auto_docstring
|
| 319 |
+
class MoonshineStreamingPreTrainedModel(PreTrainedModel):
|
| 320 |
+
config: MoonshineStreamingConfig
|
| 321 |
+
base_model_prefix = "model"
|
| 322 |
+
main_input_name = "input_values"
|
| 323 |
+
input_modalities = "audio"
|
| 324 |
+
supports_gradient_checkpointing = True
|
| 325 |
+
_no_split_modules = ["MoonshineStreamingEncoderLayer", "MoonshineStreamingDecoderLayer"]
|
| 326 |
+
_supports_flash_attn = True
|
| 327 |
+
_supports_sdpa = True
|
| 328 |
+
|
| 329 |
+
_can_compile_fullgraph = True
|
| 330 |
+
# TODO arthur, how do we separate when it cross / self coming from different layer?
|
| 331 |
+
|
| 332 |
+
def _get_feat_extract_output_lengths(self, input_lengths: torch.LongTensor) -> torch.LongTensor:
|
| 333 |
+
"""
|
| 334 |
+
Computes the output length of the convolutional layers
|
| 335 |
+
"""
|
| 336 |
+
frame_len = int(round(self.config.encoder_config.sample_rate * self.config.encoder_config.frame_ms / 1000.0))
|
| 337 |
+
output_lengths = input_lengths // frame_len
|
| 338 |
+
output_lengths = (output_lengths - 1) // 2 + 1
|
| 339 |
+
output_lengths = (output_lengths - 1) // 2 + 1
|
| 340 |
+
return output_lengths
|
| 341 |
+
|
| 342 |
+
def _init_weights(self, module: nn.Module):
|
| 343 |
+
if isinstance(module, MoonshineStreamingLayerNorm):
|
| 344 |
+
nn.init.constant_(module.gamma, 1.0 - module.unit_offset)
|
| 345 |
+
else:
|
| 346 |
+
super()._init_weights(module)
|
| 347 |
+
|
| 348 |
+
|
| 349 |
+
def sliding_window_mask_function(sliding_window: tuple[int, int]) -> Callable:
|
| 350 |
+
"""
|
| 351 |
+
This creates uni/bidirectional attention mask with sliding window.
|
| 352 |
+
"""
|
| 353 |
+
|
| 354 |
+
def inner_mask(batch_idx: int, head_idx: int, q_idx: int, kv_idx: int) -> bool:
|
| 355 |
+
left_window_size, right_window_size = sliding_window
|
| 356 |
+
|
| 357 |
+
dist = q_idx - kv_idx
|
| 358 |
+
left_mask = (dist >= 0) & (dist < left_window_size)
|
| 359 |
+
right_mask = (dist < 0) & (-dist < right_window_size)
|
| 360 |
+
return left_mask | right_mask
|
| 361 |
+
|
| 362 |
+
return inner_mask
|
| 363 |
+
|
| 364 |
+
|
| 365 |
+
class MoonshineStreamingEncoder(MoonshineStreamingPreTrainedModel):
|
| 366 |
+
config: MoonshineStreamingEncoderConfig
|
| 367 |
+
_can_record_outputs = {
|
| 368 |
+
"attentions": OutputRecorder(MoonshineStreamingEncoderAttention, index=1, layer_name="self_attn"),
|
| 369 |
+
"hidden_states": MoonshineStreamingEncoderLayer,
|
| 370 |
+
}
|
| 371 |
+
|
| 372 |
+
def __init__(self, config: MoonshineStreamingEncoderConfig):
|
| 373 |
+
super().__init__(config)
|
| 374 |
+
self.embedder = MoonshineStreamingEncoderEmbedder(config)
|
| 375 |
+
self.layers = nn.ModuleList(
|
| 376 |
+
[MoonshineStreamingEncoderLayer(config, idx) for idx in range(config.num_hidden_layers)]
|
| 377 |
+
)
|
| 378 |
+
self.final_norm = MoonshineStreamingLayerNorm(config.hidden_size)
|
| 379 |
+
self.gradient_checkpointing = False
|
| 380 |
+
|
| 381 |
+
self.post_init()
|
| 382 |
+
|
| 383 |
+
@merge_with_config_defaults
|
| 384 |
+
@capture_outputs
|
| 385 |
+
def forward(
|
| 386 |
+
self,
|
| 387 |
+
input_values: torch.FloatTensor,
|
| 388 |
+
attention_mask: torch.Tensor | None = None,
|
| 389 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 390 |
+
) -> BaseModelOutputWithPast:
|
| 391 |
+
r"""
|
| 392 |
+
Args:
|
| 393 |
+
input_values (`torch.FloatTensor` of shape `(batch_size, audio_length)`):
|
| 394 |
+
Float values of the raw speech waveform. Raw speech waveform can be
|
| 395 |
+
obtained by loading a `.flac` or `.wav` audio file into an array of type `list[float]`, a
|
| 396 |
+
`numpy.ndarray` or a `torch.Tensor`, *e.g.* via the torchcodec library (`pip install torchcodec`) or
|
| 397 |
+
the soundfile library (`pip install soundfile`). To prepare the array into
|
| 398 |
+
`input_values`, the [`AutoFeatureExtractor`] should be used for padding
|
| 399 |
+
and conversion into a tensor of type `torch.FloatTensor`.
|
| 400 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 401 |
+
Mask to avoid performing attention on padding indices in `input_values`. Mask values selected in `[0, 1]`:
|
| 402 |
+
- 1 for tokens that are **not masked**,
|
| 403 |
+
- 0 for tokens that are **masked**.
|
| 404 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 405 |
+
"""
|
| 406 |
+
inputs_embeds, attention_mask = self.embedder(input_values, padding_mask=attention_mask)
|
| 407 |
+
|
| 408 |
+
if attention_mask is not None:
|
| 409 |
+
mask_kwargs = {
|
| 410 |
+
"config": self.config,
|
| 411 |
+
"inputs_embeds": inputs_embeds,
|
| 412 |
+
"attention_mask": attention_mask,
|
| 413 |
+
}
|
| 414 |
+
per_layer_attention_mask = [
|
| 415 |
+
create_bidirectional_mask(
|
| 416 |
+
and_mask_function=sliding_window_mask_function(self.config.sliding_windows[layer_idx]),
|
| 417 |
+
**mask_kwargs,
|
| 418 |
+
)
|
| 419 |
+
for layer_idx in range(self.config.num_hidden_layers)
|
| 420 |
+
]
|
| 421 |
+
|
| 422 |
+
hidden_states = inputs_embeds
|
| 423 |
+
for layer_idx, encoder_layer in enumerate(self.layers):
|
| 424 |
+
hidden_states = encoder_layer(
|
| 425 |
+
hidden_states,
|
| 426 |
+
attention_mask=per_layer_attention_mask[layer_idx] if attention_mask is not None else None,
|
| 427 |
+
**kwargs,
|
| 428 |
+
)
|
| 429 |
+
|
| 430 |
+
hidden_states = self.final_norm(hidden_states)
|
| 431 |
+
|
| 432 |
+
return MoonshineStreamingEncoderModelOutput(last_hidden_state=hidden_states, attention_mask=attention_mask)
|
| 433 |
+
|
| 434 |
+
|
| 435 |
+
class MoonshinMoonshineStreamingDecoderMLP(nn.Module):
|
| 436 |
+
def __init__(self, config):
|
| 437 |
+
super().__init__()
|
| 438 |
+
self.config = config
|
| 439 |
+
self.hidden_size = config.hidden_size
|
| 440 |
+
self.intermediate_size = config.intermediate_size
|
| 441 |
+
self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
|
| 442 |
+
self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
|
| 443 |
+
self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.mlp_bias)
|
| 444 |
+
self.act_fn = ACT2FN[config.hidden_act]
|
| 445 |
+
|
| 446 |
+
def forward(self, x):
|
| 447 |
+
down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
|
| 448 |
+
return down_proj
|
| 449 |
+
|
| 450 |
+
|
| 451 |
+
class MoonshineStreamingDecoderMLP(nn.Module):
|
| 452 |
+
def __init__(self, config, hidden_act):
|
| 453 |
+
super().__init__()
|
| 454 |
+
self.config = config
|
| 455 |
+
self.activation_fn = ACT2FN[hidden_act]
|
| 456 |
+
self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size * 2)
|
| 457 |
+
self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
|
| 458 |
+
|
| 459 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 460 |
+
hidden_states = self.fc1(hidden_states)
|
| 461 |
+
hidden_states, gate = hidden_states.chunk(2, dim=-1)
|
| 462 |
+
hidden_states = self.activation_fn(gate) * hidden_states
|
| 463 |
+
hidden_states = self.fc2(hidden_states)
|
| 464 |
+
return hidden_states
|
| 465 |
+
|
| 466 |
+
|
| 467 |
+
class MoonshineStreamingRotaryEmbedding(nn.Module):
|
| 468 |
+
inv_freq: torch.Tensor # fix linting for `register_buffer`
|
| 469 |
+
|
| 470 |
+
def __init__(self, config: MoonshineStreamingConfig, device=None):
|
| 471 |
+
super().__init__()
|
| 472 |
+
self.max_seq_len_cached = config.max_position_embeddings
|
| 473 |
+
self.original_max_seq_len = config.max_position_embeddings
|
| 474 |
+
|
| 475 |
+
self.config = config
|
| 476 |
+
|
| 477 |
+
self.rope_type = self.config.rope_parameters["rope_type"]
|
| 478 |
+
rope_init_fn: Callable = self.compute_default_rope_parameters
|
| 479 |
+
if self.rope_type != "default":
|
| 480 |
+
rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
|
| 481 |
+
inv_freq, self.attention_scaling = rope_init_fn(self.config, device)
|
| 482 |
+
|
| 483 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
| 484 |
+
self.register_buffer("original_inv_freq", inv_freq.clone(), persistent=False)
|
| 485 |
+
|
| 486 |
+
@staticmethod
|
| 487 |
+
def compute_default_rope_parameters(
|
| 488 |
+
config: MoonshineStreamingConfig | None = None,
|
| 489 |
+
device: Optional["torch.device"] = None,
|
| 490 |
+
seq_len: int | None = None,
|
| 491 |
+
) -> tuple["torch.Tensor", float]:
|
| 492 |
+
"""
|
| 493 |
+
Computes the inverse frequencies according to the original RoPE implementation
|
| 494 |
+
Args:
|
| 495 |
+
config ([`~transformers.PreTrainedConfig`]):
|
| 496 |
+
The model configuration.
|
| 497 |
+
device (`torch.device`):
|
| 498 |
+
The device to use for initialization of the inverse frequencies.
|
| 499 |
+
seq_len (`int`, *optional*):
|
| 500 |
+
The current sequence length. Unused for this type of RoPE.
|
| 501 |
+
Returns:
|
| 502 |
+
Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
|
| 503 |
+
post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
|
| 504 |
+
"""
|
| 505 |
+
base = config.rope_parameters["rope_theta"]
|
| 506 |
+
partial_rotary_factor = config.rope_parameters.get("partial_rotary_factor", 1.0)
|
| 507 |
+
head_dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
|
| 508 |
+
dim = int(head_dim * partial_rotary_factor)
|
| 509 |
+
|
| 510 |
+
attention_factor = 1.0 # Unused in this type of RoPE
|
| 511 |
+
|
| 512 |
+
# Compute the inverse frequencies
|
| 513 |
+
inv_freq = 1.0 / (
|
| 514 |
+
base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)
|
| 515 |
+
)
|
| 516 |
+
return inv_freq, attention_factor
|
| 517 |
+
|
| 518 |
+
@torch.no_grad()
|
| 519 |
+
@dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
|
| 520 |
+
def forward(self, x, position_ids):
|
| 521 |
+
inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
|
| 522 |
+
position_ids_expanded = position_ids[:, None, :].float()
|
| 523 |
+
|
| 524 |
+
device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
|
| 525 |
+
with maybe_autocast(device_type=device_type, enabled=False): # Force float32
|
| 526 |
+
freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
|
| 527 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
| 528 |
+
cos = emb.cos() * self.attention_scaling
|
| 529 |
+
sin = emb.sin() * self.attention_scaling
|
| 530 |
+
|
| 531 |
+
return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
|
| 532 |
+
|
| 533 |
+
|
| 534 |
+
def rotate_half(x):
|
| 535 |
+
"""Rotates half the hidden dims of the input."""
|
| 536 |
+
x1 = x[..., 0::2]
|
| 537 |
+
x2 = x[..., 1::2]
|
| 538 |
+
return torch.stack((-x2, x1), dim=-1).flatten(-2)
|
| 539 |
+
|
| 540 |
+
|
| 541 |
+
def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1):
|
| 542 |
+
"""Applies Rotary Position Embedding to the query and key tensors.
|
| 543 |
+
|
| 544 |
+
Args:
|
| 545 |
+
q (`torch.Tensor`): The query tensor.
|
| 546 |
+
k (`torch.Tensor`): The key tensor.
|
| 547 |
+
cos (`torch.Tensor`): The cosine part of the rotary embedding.
|
| 548 |
+
sin (`torch.Tensor`): The sine part of the rotary embedding.
|
| 549 |
+
unsqueeze_dim (`int`, *optional*, defaults to 1):
|
| 550 |
+
The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
|
| 551 |
+
sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
|
| 552 |
+
that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
|
| 553 |
+
k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
|
| 554 |
+
cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
|
| 555 |
+
the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
|
| 556 |
+
Returns:
|
| 557 |
+
`tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
|
| 558 |
+
"""
|
| 559 |
+
cos = cos.unsqueeze(unsqueeze_dim)
|
| 560 |
+
sin = sin.unsqueeze(unsqueeze_dim)
|
| 561 |
+
|
| 562 |
+
# Interleave them instead of usual shape
|
| 563 |
+
cos = cos[..., : cos.shape[-1] // 2].repeat_interleave(2, dim=-1)
|
| 564 |
+
sin = sin[..., : sin.shape[-1] // 2].repeat_interleave(2, dim=-1)
|
| 565 |
+
|
| 566 |
+
# Keep half or full tensor for later concatenation
|
| 567 |
+
rotary_dim = cos.shape[-1]
|
| 568 |
+
q_rot, q_pass = q[..., :rotary_dim], q[..., rotary_dim:]
|
| 569 |
+
k_rot, k_pass = k[..., :rotary_dim], k[..., rotary_dim:]
|
| 570 |
+
|
| 571 |
+
# Apply rotary embeddings on the first half or full tensor
|
| 572 |
+
q_embed = (q_rot * cos) + (rotate_half(q_rot) * sin)
|
| 573 |
+
k_embed = (k_rot * cos) + (rotate_half(k_rot) * sin)
|
| 574 |
+
|
| 575 |
+
# Concatenate back to full shape
|
| 576 |
+
q_embed = torch.cat([q_embed, q_pass], dim=-1)
|
| 577 |
+
k_embed = torch.cat([k_embed, k_pass], dim=-1)
|
| 578 |
+
return q_embed, k_embed
|
| 579 |
+
|
| 580 |
+
|
| 581 |
+
@use_kernelized_func(apply_rotary_pos_emb)
|
| 582 |
+
class MoonshineStreamingAttention(nn.Module):
|
| 583 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
| 584 |
+
|
| 585 |
+
def __init__(
|
| 586 |
+
self,
|
| 587 |
+
config: MoonshineStreamingConfig,
|
| 588 |
+
layer_idx: int,
|
| 589 |
+
is_causal: bool,
|
| 590 |
+
num_attention_heads: int,
|
| 591 |
+
num_key_value_heads: int,
|
| 592 |
+
):
|
| 593 |
+
super().__init__()
|
| 594 |
+
config.update({"num_attention_heads": num_attention_heads, "num_key_value_heads": num_key_value_heads})
|
| 595 |
+
self.config = config
|
| 596 |
+
self.layer_idx = layer_idx
|
| 597 |
+
self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
|
| 598 |
+
self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
|
| 599 |
+
self.scaling = self.head_dim**-0.5
|
| 600 |
+
self.attention_dropout = config.attention_dropout
|
| 601 |
+
self.is_causal = is_causal
|
| 602 |
+
|
| 603 |
+
self.q_proj = nn.Linear(
|
| 604 |
+
config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
|
| 605 |
+
)
|
| 606 |
+
self.k_proj = nn.Linear(
|
| 607 |
+
config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
|
| 608 |
+
)
|
| 609 |
+
self.v_proj = nn.Linear(
|
| 610 |
+
config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
|
| 611 |
+
)
|
| 612 |
+
self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=False)
|
| 613 |
+
|
| 614 |
+
# Pad head dimension to the next specified multiple.
|
| 615 |
+
if self.config.pad_head_dim_to_multiple_of is not None:
|
| 616 |
+
target_multiple = self.config.pad_head_dim_to_multiple_of
|
| 617 |
+
target_head_dim = target_multiple * ((self.head_dim + target_multiple - 1) // target_multiple)
|
| 618 |
+
self.head_dim_padding = target_head_dim - self.head_dim
|
| 619 |
+
else:
|
| 620 |
+
self.head_dim_padding = 0
|
| 621 |
+
|
| 622 |
+
def forward(
|
| 623 |
+
self,
|
| 624 |
+
hidden_states: torch.Tensor,
|
| 625 |
+
position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
|
| 626 |
+
attention_mask: torch.Tensor | None = None,
|
| 627 |
+
past_key_values: Cache | None = None,
|
| 628 |
+
key_value_states: torch.Tensor | None = None,
|
| 629 |
+
**kwargs: Unpack[FlashAttentionKwargs],
|
| 630 |
+
) -> tuple[torch.Tensor, torch.Tensor | None, tuple[torch.Tensor] | None]:
|
| 631 |
+
bsz, q_len = hidden_states.shape[:-1]
|
| 632 |
+
|
| 633 |
+
query_states = (
|
| 634 |
+
self.q_proj(hidden_states).view(bsz, q_len, self.config.num_key_value_heads, self.head_dim).transpose(1, 2)
|
| 635 |
+
)
|
| 636 |
+
|
| 637 |
+
is_cross_attention = key_value_states is not None
|
| 638 |
+
if past_key_values is not None:
|
| 639 |
+
is_updated = past_key_values.is_updated.get(self.layer_idx)
|
| 640 |
+
if is_cross_attention:
|
| 641 |
+
# after the first generated id, we can subsequently re-use all key/value_states from cache
|
| 642 |
+
past_key_values.is_updated[self.layer_idx] = True
|
| 643 |
+
past_key_values = past_key_values.cross_attention_cache
|
| 644 |
+
else:
|
| 645 |
+
past_key_values = past_key_values.self_attention_cache
|
| 646 |
+
|
| 647 |
+
# use key_value_states if cross attention
|
| 648 |
+
current_states = key_value_states if key_value_states is not None else hidden_states
|
| 649 |
+
if is_cross_attention and past_key_values and is_updated:
|
| 650 |
+
key_states = past_key_values.layers[self.layer_idx].keys
|
| 651 |
+
value_states = past_key_values.layers[self.layer_idx].values
|
| 652 |
+
else:
|
| 653 |
+
key_states = (
|
| 654 |
+
self.k_proj(current_states)
|
| 655 |
+
.view(bsz, -1, self.config.num_key_value_heads, self.head_dim)
|
| 656 |
+
.transpose(1, 2)
|
| 657 |
+
)
|
| 658 |
+
value_states = (
|
| 659 |
+
self.v_proj(current_states)
|
| 660 |
+
.view(bsz, -1, self.config.num_key_value_heads, self.head_dim)
|
| 661 |
+
.transpose(1, 2)
|
| 662 |
+
)
|
| 663 |
+
if is_cross_attention and past_key_values is not None:
|
| 664 |
+
key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
|
| 665 |
+
|
| 666 |
+
if not is_cross_attention:
|
| 667 |
+
cos, sin = position_embeddings
|
| 668 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
| 669 |
+
|
| 670 |
+
if past_key_values is not None:
|
| 671 |
+
key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
|
| 672 |
+
|
| 673 |
+
attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
|
| 674 |
+
self.config._attn_implementation, eager_attention_forward
|
| 675 |
+
)
|
| 676 |
+
|
| 677 |
+
is_causal = self.is_causal and attention_mask is None and q_len > 1
|
| 678 |
+
|
| 679 |
+
if self.head_dim_padding > 0:
|
| 680 |
+
query_states = torch.nn.functional.pad(query_states, (0, self.head_dim_padding))
|
| 681 |
+
key_states = torch.nn.functional.pad(key_states, (0, self.head_dim_padding))
|
| 682 |
+
value_states = torch.nn.functional.pad(value_states, (0, self.head_dim_padding))
|
| 683 |
+
|
| 684 |
+
attn_output, attn_weights = attention_interface(
|
| 685 |
+
self,
|
| 686 |
+
query_states,
|
| 687 |
+
key_states,
|
| 688 |
+
value_states,
|
| 689 |
+
attention_mask,
|
| 690 |
+
dropout=0.0 if not self.training else self.attention_dropout,
|
| 691 |
+
scaling=self.scaling,
|
| 692 |
+
is_causal=is_causal,
|
| 693 |
+
**kwargs,
|
| 694 |
+
)
|
| 695 |
+
|
| 696 |
+
if self.head_dim_padding > 0:
|
| 697 |
+
attn_output = attn_output[..., : -self.head_dim_padding]
|
| 698 |
+
|
| 699 |
+
attn_output = attn_output.reshape(bsz, q_len, -1).contiguous()
|
| 700 |
+
attn_output = self.o_proj(attn_output)
|
| 701 |
+
return attn_output, attn_weights
|
| 702 |
+
|
| 703 |
+
|
| 704 |
+
class MoonshineStreamingDecoderLayer(GradientCheckpointingLayer):
|
| 705 |
+
def __init__(self, config: MoonshineStreamingConfig, layer_idx: int | None = None):
|
| 706 |
+
super().__init__()
|
| 707 |
+
self.hidden_size = config.hidden_size
|
| 708 |
+
|
| 709 |
+
self.self_attn = MoonshineStreamingAttention(
|
| 710 |
+
config=config,
|
| 711 |
+
layer_idx=layer_idx,
|
| 712 |
+
is_causal=True,
|
| 713 |
+
num_attention_heads=config.num_attention_heads,
|
| 714 |
+
num_key_value_heads=config.num_key_value_heads,
|
| 715 |
+
)
|
| 716 |
+
self.encoder_attn = MoonshineStreamingAttention(
|
| 717 |
+
config=config,
|
| 718 |
+
layer_idx=layer_idx,
|
| 719 |
+
is_causal=False,
|
| 720 |
+
num_attention_heads=config.num_attention_heads,
|
| 721 |
+
num_key_value_heads=config.num_key_value_heads,
|
| 722 |
+
)
|
| 723 |
+
|
| 724 |
+
self.mlp = MoonshineStreamingDecoderMLP(config, config.hidden_act)
|
| 725 |
+
self.input_layernorm = nn.LayerNorm(config.hidden_size, bias=False)
|
| 726 |
+
self.post_attention_layernorm = nn.LayerNorm(config.hidden_size, bias=False)
|
| 727 |
+
self.final_layernorm = nn.LayerNorm(config.hidden_size, bias=False)
|
| 728 |
+
|
| 729 |
+
def forward(
|
| 730 |
+
self,
|
| 731 |
+
hidden_states: torch.Tensor,
|
| 732 |
+
attention_mask: torch.Tensor | None = None,
|
| 733 |
+
encoder_hidden_states: torch.Tensor | None = None,
|
| 734 |
+
encoder_attention_mask: torch.Tensor | None = None,
|
| 735 |
+
position_ids: torch.LongTensor | None = None,
|
| 736 |
+
encoder_position_ids: torch.LongTensor | None = None,
|
| 737 |
+
past_key_values: Cache | None = None,
|
| 738 |
+
use_cache: bool | None = False,
|
| 739 |
+
position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
|
| 740 |
+
encoder_position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
|
| 741 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 742 |
+
) -> tuple[torch.FloatTensor, tuple[torch.FloatTensor, torch.FloatTensor] | None]:
|
| 743 |
+
residual = hidden_states
|
| 744 |
+
hidden_states = self.input_layernorm(hidden_states)
|
| 745 |
+
|
| 746 |
+
hidden_states, _ = self.self_attn(
|
| 747 |
+
hidden_states=hidden_states,
|
| 748 |
+
attention_mask=attention_mask,
|
| 749 |
+
position_ids=position_ids,
|
| 750 |
+
past_key_values=past_key_values,
|
| 751 |
+
use_cache=use_cache,
|
| 752 |
+
position_embeddings=position_embeddings,
|
| 753 |
+
**kwargs,
|
| 754 |
+
)
|
| 755 |
+
hidden_states = residual + hidden_states
|
| 756 |
+
|
| 757 |
+
if encoder_hidden_states is not None:
|
| 758 |
+
residual = hidden_states
|
| 759 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
| 760 |
+
hidden_states, _ = self.encoder_attn(
|
| 761 |
+
hidden_states=hidden_states,
|
| 762 |
+
key_value_states=encoder_hidden_states,
|
| 763 |
+
attention_mask=encoder_attention_mask,
|
| 764 |
+
past_key_values=past_key_values,
|
| 765 |
+
use_cache=use_cache,
|
| 766 |
+
)
|
| 767 |
+
hidden_states = residual + hidden_states
|
| 768 |
+
|
| 769 |
+
residual = hidden_states
|
| 770 |
+
hidden_states = self.final_layernorm(hidden_states)
|
| 771 |
+
hidden_states = self.mlp(hidden_states)
|
| 772 |
+
hidden_states = residual + hidden_states
|
| 773 |
+
return hidden_states
|
| 774 |
+
|
| 775 |
+
|
| 776 |
+
@auto_docstring
|
| 777 |
+
class MoonshineStreamingDecoder(MoonshineStreamingPreTrainedModel):
|
| 778 |
+
main_input_name = "input_ids"
|
| 779 |
+
_can_record_outputs = {
|
| 780 |
+
"attentions": OutputRecorder(MoonshineStreamingAttention, index=1, layer_name="self_attn"),
|
| 781 |
+
"hidden_states": MoonshineStreamingDecoderLayer,
|
| 782 |
+
"cross_attentions": OutputRecorder(MoonshineStreamingAttention, index=1, layer_name="encoder_attn"),
|
| 783 |
+
}
|
| 784 |
+
|
| 785 |
+
def __init__(self, config):
|
| 786 |
+
super().__init__(config)
|
| 787 |
+
self.padding_idx = config.pad_token_id
|
| 788 |
+
self.vocab_size = config.vocab_size
|
| 789 |
+
|
| 790 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
| 791 |
+
self.layers = nn.ModuleList(
|
| 792 |
+
[MoonshineStreamingDecoderLayer(config, idx) for idx in range(config.num_hidden_layers)]
|
| 793 |
+
)
|
| 794 |
+
self.norm = nn.LayerNorm(config.hidden_size, bias=False)
|
| 795 |
+
self.rotary_emb = MoonshineStreamingRotaryEmbedding(config=config)
|
| 796 |
+
self.gradient_checkpointing = False
|
| 797 |
+
self.pos_emb = nn.Embedding(self.config.max_position_embeddings, config.encoder_config.hidden_size)
|
| 798 |
+
|
| 799 |
+
if config.encoder_config.hidden_size != self.config.hidden_size:
|
| 800 |
+
self.proj = nn.Linear(config.encoder_config.hidden_size, self.config.hidden_size, bias=False)
|
| 801 |
+
else:
|
| 802 |
+
self.proj = nn.Identity()
|
| 803 |
+
|
| 804 |
+
# Initialize weights and apply final processing
|
| 805 |
+
self.post_init()
|
| 806 |
+
|
| 807 |
+
@merge_with_config_defaults
|
| 808 |
+
@capture_outputs
|
| 809 |
+
def forward(
|
| 810 |
+
self,
|
| 811 |
+
input_ids: torch.LongTensor | None = None,
|
| 812 |
+
attention_mask: torch.Tensor | None = None,
|
| 813 |
+
position_ids: torch.LongTensor | None = None,
|
| 814 |
+
past_key_values: Cache | None = None,
|
| 815 |
+
inputs_embeds: torch.FloatTensor | None = None,
|
| 816 |
+
use_cache: bool | None = None,
|
| 817 |
+
encoder_hidden_states: torch.FloatTensor | None = None,
|
| 818 |
+
encoder_attention_mask: torch.Tensor | None = None,
|
| 819 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 820 |
+
) -> tuple | BaseModelOutputWithPast:
|
| 821 |
+
r"""
|
| 822 |
+
encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, encoder_sequence_length, hidden_size)`, *optional*):
|
| 823 |
+
Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
|
| 824 |
+
of the decoder.
|
| 825 |
+
encoder_attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 826 |
+
Mask to avoid performing attention on padding indices in `encoder_hidden_states`. Mask values selected in `[0, 1]`:
|
| 827 |
+
- 1 for tokens that are **not masked**,
|
| 828 |
+
- 0 for tokens that are **masked**.
|
| 829 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 830 |
+
"""
|
| 831 |
+
position_embeddings = self.pos_emb(
|
| 832 |
+
torch.arange(encoder_hidden_states.shape[1], device=encoder_hidden_states.device)
|
| 833 |
+
)
|
| 834 |
+
encoder_hidden_states += position_embeddings.to(encoder_hidden_states.device)
|
| 835 |
+
encoder_hidden_states = self.proj(encoder_hidden_states)
|
| 836 |
+
if (input_ids is None) ^ (inputs_embeds is not None):
|
| 837 |
+
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
|
| 838 |
+
|
| 839 |
+
if inputs_embeds is None:
|
| 840 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
| 841 |
+
|
| 842 |
+
if use_cache and past_key_values is None:
|
| 843 |
+
past_key_values = EncoderDecoderCache(DynamicCache(config=self.config), DynamicCache(config=self.config))
|
| 844 |
+
|
| 845 |
+
if position_ids is None:
|
| 846 |
+
past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
|
| 847 |
+
position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device) + past_seen_tokens
|
| 848 |
+
position_ids = position_ids.unsqueeze(0)
|
| 849 |
+
|
| 850 |
+
causal_mask = create_causal_mask(
|
| 851 |
+
config=self.config,
|
| 852 |
+
inputs_embeds=inputs_embeds,
|
| 853 |
+
attention_mask=attention_mask,
|
| 854 |
+
past_key_values=past_key_values,
|
| 855 |
+
position_ids=position_ids,
|
| 856 |
+
)
|
| 857 |
+
encoder_attention_mask = create_bidirectional_mask(
|
| 858 |
+
config=self.config,
|
| 859 |
+
inputs_embeds=inputs_embeds,
|
| 860 |
+
attention_mask=encoder_attention_mask,
|
| 861 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 862 |
+
)
|
| 863 |
+
|
| 864 |
+
hidden_states = inputs_embeds
|
| 865 |
+
position_embeddings = self.rotary_emb(hidden_states, position_ids=position_ids)
|
| 866 |
+
|
| 867 |
+
for decoder_layer in self.layers:
|
| 868 |
+
hidden_states = decoder_layer(
|
| 869 |
+
hidden_states,
|
| 870 |
+
causal_mask,
|
| 871 |
+
encoder_hidden_states, # as a positional argument for gradient checkpointing
|
| 872 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 873 |
+
position_ids=position_ids,
|
| 874 |
+
past_key_values=past_key_values,
|
| 875 |
+
use_cache=use_cache,
|
| 876 |
+
position_embeddings=position_embeddings,
|
| 877 |
+
**kwargs,
|
| 878 |
+
)
|
| 879 |
+
|
| 880 |
+
hidden_states = self.norm(hidden_states)
|
| 881 |
+
|
| 882 |
+
return BaseModelOutputWithPastAndCrossAttentions(
|
| 883 |
+
last_hidden_state=hidden_states,
|
| 884 |
+
past_key_values=past_key_values if use_cache else None,
|
| 885 |
+
)
|
| 886 |
+
|
| 887 |
+
|
| 888 |
+
@auto_docstring
|
| 889 |
+
class MoonshineStreamingModel(MoonshineStreamingPreTrainedModel):
|
| 890 |
+
def __init__(self, config):
|
| 891 |
+
super().__init__(config)
|
| 892 |
+
self.encoder = MoonshineStreamingEncoder(config.encoder_config)
|
| 893 |
+
self.decoder = MoonshineStreamingDecoder(config)
|
| 894 |
+
# Initialize weights and apply final processing
|
| 895 |
+
self.post_init()
|
| 896 |
+
|
| 897 |
+
def get_input_embeddings(self):
|
| 898 |
+
return self.decoder.embed_tokens
|
| 899 |
+
|
| 900 |
+
def set_input_embeddings(self, value):
|
| 901 |
+
self.decoder.embed_tokens = value
|
| 902 |
+
|
| 903 |
+
def freeze_encoder(self):
|
| 904 |
+
"""
|
| 905 |
+
Calling this function will disable the gradient computation for the MoonshineStreaming encoder so that its parameters will
|
| 906 |
+
not be updated during training.
|
| 907 |
+
"""
|
| 908 |
+
self.encoder._freeze_parameters()
|
| 909 |
+
|
| 910 |
+
def _mask_input_features(self):
|
| 911 |
+
"""
|
| 912 |
+
Masks extracted features along time axis and/or along feature axis according to
|
| 913 |
+
[SpecAugment](https://huggingface.co/papers/1904.08779).
|
| 914 |
+
"""
|
| 915 |
+
raise AttributeError("Not needed for MoonshineStreaming")
|
| 916 |
+
|
| 917 |
+
@can_return_tuple
|
| 918 |
+
@auto_docstring
|
| 919 |
+
def forward(
|
| 920 |
+
self,
|
| 921 |
+
input_values: torch.FloatTensor | None = None,
|
| 922 |
+
attention_mask: torch.LongTensor | None = None,
|
| 923 |
+
decoder_input_ids: torch.LongTensor | None = None,
|
| 924 |
+
decoder_attention_mask: torch.LongTensor | None = None,
|
| 925 |
+
encoder_outputs: tuple[tuple[torch.FloatTensor]] | None = None,
|
| 926 |
+
past_key_values: EncoderDecoderCache | None = None,
|
| 927 |
+
decoder_inputs_embeds: tuple[torch.FloatTensor] | None = None,
|
| 928 |
+
decoder_position_ids: tuple[torch.LongTensor] | None = None,
|
| 929 |
+
use_cache: bool | None = None,
|
| 930 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 931 |
+
) -> Seq2SeqModelOutput:
|
| 932 |
+
r"""
|
| 933 |
+
input_values (`torch.FloatTensor` of shape `(batch_size, audio_length)`):
|
| 934 |
+
Float values of the raw speech waveform. Raw speech waveform can be
|
| 935 |
+
obtained by loading a `.flac` or `.wav` audio file into an array of type `list[float]`, a
|
| 936 |
+
`numpy.ndarray` or a `torch.Tensor`, *e.g.* via the torchcodec library (`pip install torchcodec`) or
|
| 937 |
+
the soundfile library (`pip install soundfile`). To prepare the array into
|
| 938 |
+
`input_values`, the [`AutoFeatureExtractor`] should be used for padding
|
| 939 |
+
and conversion into a tensor of type `torch.FloatTensor`.
|
| 940 |
+
decoder_position_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`):
|
| 941 |
+
Indices of positions of each input sequence tokens in the position embeddings.
|
| 942 |
+
Used to calculate the position embeddings up to `config.decoder_config.max_position_embeddings`
|
| 943 |
+
|
| 944 |
+
Example:
|
| 945 |
+
|
| 946 |
+
```python
|
| 947 |
+
>>> import torch
|
| 948 |
+
>>> from transformers import AutoFeatureExtractor, MoonshineStreamingModel
|
| 949 |
+
>>> from datasets import load_dataset
|
| 950 |
+
|
| 951 |
+
>>> model = MoonshineStreamingModel.from_pretrained("UsefulSensors/moonshine_streaming-tiny")
|
| 952 |
+
>>> feature_extractor = AutoFeatureExtractor.from_pretrained("UsefulSensors/moonshine_streaming-tiny")
|
| 953 |
+
>>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
|
| 954 |
+
>>> inputs = feature_extractor(ds[0]["audio"]["array"], return_tensors="pt")
|
| 955 |
+
>>> input_values = inputs.input_values
|
| 956 |
+
>>> decoder_input_ids = torch.tensor([[1, 1]]) * model.config.decoder_start_token_id
|
| 957 |
+
>>> last_hidden_state = model(input_values, decoder_input_ids=decoder_input_ids).last_hidden_state
|
| 958 |
+
>>> list(last_hidden_state.shape)
|
| 959 |
+
[1, 2, 288]
|
| 960 |
+
```
|
| 961 |
+
"""
|
| 962 |
+
if encoder_outputs is None:
|
| 963 |
+
encoder_outputs: BaseModelOutput = self.encoder(input_values, attention_mask=attention_mask, **kwargs)
|
| 964 |
+
|
| 965 |
+
decoder_outputs: BaseModelOutputWithPastAndCrossAttentions = self.decoder(
|
| 966 |
+
input_ids=decoder_input_ids,
|
| 967 |
+
attention_mask=decoder_attention_mask,
|
| 968 |
+
encoder_hidden_states=encoder_outputs.last_hidden_state,
|
| 969 |
+
encoder_attention_mask=encoder_outputs.attention_mask,
|
| 970 |
+
past_key_values=past_key_values,
|
| 971 |
+
inputs_embeds=decoder_inputs_embeds,
|
| 972 |
+
position_ids=decoder_position_ids,
|
| 973 |
+
use_cache=use_cache,
|
| 974 |
+
**kwargs,
|
| 975 |
+
)
|
| 976 |
+
|
| 977 |
+
return Seq2SeqModelOutput(
|
| 978 |
+
last_hidden_state=decoder_outputs.last_hidden_state,
|
| 979 |
+
past_key_values=decoder_outputs.past_key_values,
|
| 980 |
+
decoder_hidden_states=decoder_outputs.hidden_states,
|
| 981 |
+
decoder_attentions=decoder_outputs.attentions,
|
| 982 |
+
cross_attentions=decoder_outputs.cross_attentions,
|
| 983 |
+
encoder_last_hidden_state=encoder_outputs.last_hidden_state,
|
| 984 |
+
encoder_hidden_states=encoder_outputs.hidden_states,
|
| 985 |
+
encoder_attentions=encoder_outputs.attentions,
|
| 986 |
+
)
|
| 987 |
+
|
| 988 |
+
|
| 989 |
+
def shift_tokens_right(input_ids: torch.Tensor, pad_token_id: int, decoder_start_token_id: int):
|
| 990 |
+
"""
|
| 991 |
+
Shift input ids one token to the right.
|
| 992 |
+
"""
|
| 993 |
+
shifted_input_ids = input_ids.new_zeros(input_ids.shape)
|
| 994 |
+
shifted_input_ids[:, 1:] = input_ids[:, :-1].clone()
|
| 995 |
+
shifted_input_ids[:, 0] = decoder_start_token_id
|
| 996 |
+
|
| 997 |
+
if pad_token_id is None:
|
| 998 |
+
raise ValueError("self.model.config.pad_token_id has to be defined.")
|
| 999 |
+
# replace possible -100 values in labels by `pad_token_id`
|
| 1000 |
+
shifted_input_ids.masked_fill_(shifted_input_ids == -100, pad_token_id)
|
| 1001 |
+
|
| 1002 |
+
return shifted_input_ids
|
| 1003 |
+
|
| 1004 |
+
|
| 1005 |
+
@auto_docstring(
|
| 1006 |
+
custom_intro="""
|
| 1007 |
+
The MoonshineStreaming Model with a language modeling head. Can be used for automatic speech recognition.
|
| 1008 |
+
"""
|
| 1009 |
+
)
|
| 1010 |
+
class MoonshineStreamingForConditionalGeneration(MoonshineStreamingPreTrainedModel, GenerationMixin):
|
| 1011 |
+
_tied_weights_keys = {"proj_out.weight": "model.decoder.embed_tokens.weight"}
|
| 1012 |
+
|
| 1013 |
+
def __init__(self, config: MoonshineStreamingConfig):
|
| 1014 |
+
super().__init__(config)
|
| 1015 |
+
self.model = MoonshineStreamingModel(config)
|
| 1016 |
+
self.proj_out = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
| 1017 |
+
|
| 1018 |
+
# Initialize weights and apply final processing
|
| 1019 |
+
self.post_init()
|
| 1020 |
+
|
| 1021 |
+
def get_output_embeddings(self):
|
| 1022 |
+
return self.proj_out
|
| 1023 |
+
|
| 1024 |
+
def set_output_embeddings(self, new_embeddings):
|
| 1025 |
+
self.proj_out = new_embeddings
|
| 1026 |
+
|
| 1027 |
+
def get_input_embeddings(self) -> nn.Module:
|
| 1028 |
+
return self.model.get_input_embeddings()
|
| 1029 |
+
|
| 1030 |
+
@can_return_tuple
|
| 1031 |
+
@auto_docstring
|
| 1032 |
+
def forward(
|
| 1033 |
+
self,
|
| 1034 |
+
input_values: torch.FloatTensor | None = None,
|
| 1035 |
+
attention_mask: torch.LongTensor | None = None,
|
| 1036 |
+
decoder_input_ids: torch.LongTensor | None = None,
|
| 1037 |
+
decoder_attention_mask: torch.LongTensor | None = None,
|
| 1038 |
+
encoder_outputs: tuple[tuple[torch.FloatTensor]] | None = None,
|
| 1039 |
+
past_key_values: EncoderDecoderCache | None = None,
|
| 1040 |
+
decoder_inputs_embeds: tuple[torch.FloatTensor] | None = None,
|
| 1041 |
+
decoder_position_ids: tuple[torch.LongTensor] | None = None,
|
| 1042 |
+
use_cache: bool | None = None,
|
| 1043 |
+
labels: torch.LongTensor | None = None,
|
| 1044 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 1045 |
+
) -> Seq2SeqLMOutput:
|
| 1046 |
+
r"""
|
| 1047 |
+
input_values (`torch.FloatTensor` of shape `(batch_size, audio_length)`):
|
| 1048 |
+
Float values of the raw speech waveform. Raw speech waveform can be
|
| 1049 |
+
obtained by loading a `.flac` or `.wav` audio file into an array of type `list[float]`, a
|
| 1050 |
+
`numpy.ndarray` or a `torch.Tensor`, *e.g.* via the torchcodec library (`pip install torchcodec`) or
|
| 1051 |
+
the soundfile library (`pip install soundfile`). To prepare the array into
|
| 1052 |
+
`input_values`, the [`AutoFeatureExtractor`] should be used for padding
|
| 1053 |
+
and conversion into a tensor of type `torch.FloatTensor`.
|
| 1054 |
+
decoder_position_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`):
|
| 1055 |
+
Indices of positions of each input sequence tokens in the position embeddings.
|
| 1056 |
+
Used to calculate the position embeddings up to `config.decoder_config.max_position_embeddings`
|
| 1057 |
+
|
| 1058 |
+
Example:
|
| 1059 |
+
|
| 1060 |
+
```python
|
| 1061 |
+
>>> import torch
|
| 1062 |
+
>>> from transformers import AutoProcessor, MoonshineStreamingForConditionalGeneration
|
| 1063 |
+
>>> from datasets import load_dataset
|
| 1064 |
+
|
| 1065 |
+
>>> processor = AutoProcessor.from_pretrained("UsefulSensors/moonshine_streaming-tiny")
|
| 1066 |
+
>>> model = MoonshineStreamingForConditionalGeneration.from_pretrained("UsefulSensors/moonshine_streaming-tiny")
|
| 1067 |
+
|
| 1068 |
+
>>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
|
| 1069 |
+
|
| 1070 |
+
>>> inputs = processor(ds[0]["audio"]["array"], return_tensors="pt")
|
| 1071 |
+
>>> input_values = inputs.input_values
|
| 1072 |
+
|
| 1073 |
+
>>> generated_ids = model.generate(input_values, max_new_tokens=100)
|
| 1074 |
+
|
| 1075 |
+
>>> transcription = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
|
| 1076 |
+
>>> transcription
|
| 1077 |
+
'Mr. Quilter is the apostle of the middle classes, and we are glad to welcome his gospel.'
|
| 1078 |
+
```"""
|
| 1079 |
+
|
| 1080 |
+
if labels is not None:
|
| 1081 |
+
if decoder_input_ids is None and decoder_inputs_embeds is None:
|
| 1082 |
+
decoder_input_ids = shift_tokens_right(
|
| 1083 |
+
labels, self.config.pad_token_id, self.config.decoder_start_token_id
|
| 1084 |
+
)
|
| 1085 |
+
|
| 1086 |
+
outputs: Seq2SeqModelOutput = self.model(
|
| 1087 |
+
input_values,
|
| 1088 |
+
attention_mask=attention_mask,
|
| 1089 |
+
decoder_input_ids=decoder_input_ids,
|
| 1090 |
+
encoder_outputs=encoder_outputs,
|
| 1091 |
+
decoder_attention_mask=decoder_attention_mask,
|
| 1092 |
+
past_key_values=past_key_values,
|
| 1093 |
+
decoder_inputs_embeds=decoder_inputs_embeds,
|
| 1094 |
+
decoder_position_ids=decoder_position_ids,
|
| 1095 |
+
use_cache=use_cache,
|
| 1096 |
+
**kwargs,
|
| 1097 |
+
)
|
| 1098 |
+
logits = self.proj_out(outputs.last_hidden_state)
|
| 1099 |
+
|
| 1100 |
+
loss = None
|
| 1101 |
+
if labels is not None:
|
| 1102 |
+
loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size)
|
| 1103 |
+
|
| 1104 |
+
return Seq2SeqLMOutput(
|
| 1105 |
+
loss=loss,
|
| 1106 |
+
logits=logits,
|
| 1107 |
+
past_key_values=outputs.past_key_values,
|
| 1108 |
+
decoder_hidden_states=outputs.decoder_hidden_states,
|
| 1109 |
+
decoder_attentions=outputs.decoder_attentions,
|
| 1110 |
+
cross_attentions=outputs.cross_attentions,
|
| 1111 |
+
encoder_last_hidden_state=outputs.encoder_last_hidden_state,
|
| 1112 |
+
encoder_hidden_states=outputs.encoder_hidden_states,
|
| 1113 |
+
encoder_attentions=outputs.encoder_attentions,
|
| 1114 |
+
)
|
| 1115 |
+
|
| 1116 |
+
|
| 1117 |
+
__all__ = [
|
| 1118 |
+
"MoonshineStreamingPreTrainedModel",
|
| 1119 |
+
"MoonshineStreamingModel",
|
| 1120 |
+
"MoonshineStreamingForConditionalGeneration",
|
| 1121 |
+
]
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/moonshine_streaming/modular_moonshine_streaming.py
ADDED
|
@@ -0,0 +1,419 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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 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 |
+
from collections.abc import Callable
|
| 16 |
+
from dataclasses import dataclass
|
| 17 |
+
|
| 18 |
+
import torch
|
| 19 |
+
import torch.nn as nn
|
| 20 |
+
from torch import Tensor
|
| 21 |
+
|
| 22 |
+
from ...cache_utils import Cache
|
| 23 |
+
from ...masking_utils import create_bidirectional_mask
|
| 24 |
+
from ...modeling_outputs import (
|
| 25 |
+
BaseModelOutput,
|
| 26 |
+
BaseModelOutputWithPast,
|
| 27 |
+
)
|
| 28 |
+
from ...modeling_utils import ALL_ATTENTION_FUNCTIONS
|
| 29 |
+
from ...processing_utils import ProcessingKwargs, Unpack
|
| 30 |
+
from ...utils import TransformersKwargs, auto_docstring, logging
|
| 31 |
+
from ...utils.generic import merge_with_config_defaults
|
| 32 |
+
from ...utils.output_capturing import OutputRecorder, capture_outputs
|
| 33 |
+
from ..llama.modeling_llama import LlamaMLP, eager_attention_forward
|
| 34 |
+
from ..moonshine.modeling_moonshine import (
|
| 35 |
+
MoonshineDecoder,
|
| 36 |
+
MoonshineEncoderLayer,
|
| 37 |
+
MoonshineEncoderMLP,
|
| 38 |
+
MoonshineForConditionalGeneration,
|
| 39 |
+
MoonshineModel,
|
| 40 |
+
MoonshinePreTrainedModel,
|
| 41 |
+
)
|
| 42 |
+
from ..wav2vec2.processing_wav2vec2 import Wav2Vec2Processor
|
| 43 |
+
from .configuration_moonshine_streaming import MoonshineStreamingConfig, MoonshineStreamingEncoderConfig
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
logger = logging.get_logger(__name__)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
class MoonshineStreamingProcessorKwargs(ProcessingKwargs, total=False):
|
| 50 |
+
_defaults = {
|
| 51 |
+
"audio_kwargs": {
|
| 52 |
+
"pad_to_multiple_of": 80,
|
| 53 |
+
"padding": True,
|
| 54 |
+
},
|
| 55 |
+
"common_kwargs": {"return_tensors": "pt"},
|
| 56 |
+
}
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
class MoonshineStreamingProcessor(Wav2Vec2Processor): ...
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
@auto_docstring(
|
| 63 |
+
custom_intro="""
|
| 64 |
+
Extends [~modeling_outputs.BaseModelOutput] to include the output attention mask since sequence length is not preserved in the model's forward.
|
| 65 |
+
"""
|
| 66 |
+
)
|
| 67 |
+
@dataclass
|
| 68 |
+
class MoonshineStreamingEncoderModelOutput(BaseModelOutput):
|
| 69 |
+
r"""
|
| 70 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 71 |
+
Mask to avoid performing attention on padding token indices after sequence compression. Returned because the
|
| 72 |
+
sequence length may differ from the input sequence length. Mask values selected in `[0, 1]`:
|
| 73 |
+
|
| 74 |
+
- 1 for tokens that are **not masked**,
|
| 75 |
+
- 0 for tokens that are **masked**.
|
| 76 |
+
"""
|
| 77 |
+
|
| 78 |
+
attention_mask: torch.Tensor | None = None
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
class MoonshineStreamingFrameCMVN(nn.Module):
|
| 82 |
+
def __init__(self, eps: float = 1e-6):
|
| 83 |
+
super().__init__()
|
| 84 |
+
self.eps = eps
|
| 85 |
+
|
| 86 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 87 |
+
mean = x.mean(dim=-1, keepdim=True)
|
| 88 |
+
centered = x - mean
|
| 89 |
+
rms = (centered.pow(2).mean(dim=-1, keepdim=True) + self.eps).sqrt()
|
| 90 |
+
return centered / rms
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
class MoonshineStreamingAsinhCompression(nn.Module):
|
| 94 |
+
def __init__(self, k_init: float = 0.75):
|
| 95 |
+
super().__init__()
|
| 96 |
+
self.log_k = nn.Parameter(torch.log(torch.tensor(k_init)))
|
| 97 |
+
|
| 98 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 99 |
+
return torch.asinh(torch.exp(self.log_k) * x)
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
class MoonshineStreamingCausalConv1d(nn.Conv1d):
|
| 103 |
+
def __init__(
|
| 104 |
+
self,
|
| 105 |
+
in_channels: int,
|
| 106 |
+
out_channels: int,
|
| 107 |
+
kernel_size: int,
|
| 108 |
+
stride: int = 1,
|
| 109 |
+
dilation: int = 1,
|
| 110 |
+
bias: bool = True,
|
| 111 |
+
):
|
| 112 |
+
super().__init__(in_channels, out_channels, kernel_size, stride=stride, dilation=dilation, bias=bias)
|
| 113 |
+
self.left_pad = (kernel_size - 1) * dilation
|
| 114 |
+
|
| 115 |
+
def forward(self, x: torch.Tensor, mask: torch.Tensor | None = None) -> torch.Tensor:
|
| 116 |
+
x = nn.functional.pad(x, (self.left_pad, 0))
|
| 117 |
+
x = super().forward(x)
|
| 118 |
+
|
| 119 |
+
if mask is not None:
|
| 120 |
+
mask = nn.functional.pad(mask, (self.left_pad, 0))[:, None, :]
|
| 121 |
+
weight = torch.ones(1, 1, self.kernel_size[0], device=mask.device)
|
| 122 |
+
mask = nn.functional.conv1d(mask.float(), weight, stride=self.stride)
|
| 123 |
+
mask = mask > 0
|
| 124 |
+
x *= mask
|
| 125 |
+
|
| 126 |
+
if mask is not None:
|
| 127 |
+
mask = mask.squeeze(1)
|
| 128 |
+
return x, mask
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
class MoonshineStreamingLayerNorm(nn.Module):
|
| 132 |
+
def __init__(self, dim: int, unit_offset: bool = True, device=None, dtype=None):
|
| 133 |
+
super().__init__()
|
| 134 |
+
self.unit_offset = float(unit_offset)
|
| 135 |
+
self.ln = nn.LayerNorm(dim, elementwise_affine=False, device=device, dtype=dtype)
|
| 136 |
+
self.gamma = nn.Parameter(torch.ones(dim, device=device, dtype=dtype))
|
| 137 |
+
|
| 138 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 139 |
+
normed = self.ln(x)
|
| 140 |
+
gamma = self.gamma + self.unit_offset
|
| 141 |
+
return normed * gamma
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
class MoonshineStreamingEncoderMLP(MoonshineEncoderMLP): ...
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
class MoonshineStreamingEncoderAttention(nn.Module):
|
| 148 |
+
def __init__(self, config: MoonshineStreamingConfig, layer_idx: int):
|
| 149 |
+
super().__init__()
|
| 150 |
+
self.config = config
|
| 151 |
+
self.layer_idx = layer_idx
|
| 152 |
+
self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
|
| 153 |
+
self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
|
| 154 |
+
self.scaling = self.head_dim**-0.5
|
| 155 |
+
self.attention_dropout = config.attention_dropout
|
| 156 |
+
self.is_causal = False
|
| 157 |
+
|
| 158 |
+
self.q_proj = nn.Linear(
|
| 159 |
+
config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
|
| 160 |
+
)
|
| 161 |
+
self.k_proj = nn.Linear(
|
| 162 |
+
config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
|
| 163 |
+
)
|
| 164 |
+
self.v_proj = nn.Linear(
|
| 165 |
+
config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
|
| 166 |
+
)
|
| 167 |
+
self.o_proj = nn.Linear(
|
| 168 |
+
config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
|
| 169 |
+
)
|
| 170 |
+
|
| 171 |
+
def forward(
|
| 172 |
+
self,
|
| 173 |
+
hidden_states: torch.Tensor,
|
| 174 |
+
attention_mask: torch.Tensor | None = None,
|
| 175 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 176 |
+
) -> tuple[torch.Tensor, torch.Tensor]:
|
| 177 |
+
input_shape = hidden_states.shape[:-1]
|
| 178 |
+
hidden_shape = (*input_shape, -1, self.head_dim)
|
| 179 |
+
|
| 180 |
+
query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 181 |
+
key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 182 |
+
value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 183 |
+
|
| 184 |
+
attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
|
| 185 |
+
self.config._attn_implementation, eager_attention_forward
|
| 186 |
+
)
|
| 187 |
+
|
| 188 |
+
attn_output, attn_weights = attention_interface(
|
| 189 |
+
self,
|
| 190 |
+
query_states,
|
| 191 |
+
key_states,
|
| 192 |
+
value_states,
|
| 193 |
+
attention_mask,
|
| 194 |
+
dropout=0.0 if not self.training else self.attention_dropout,
|
| 195 |
+
scaling=self.scaling,
|
| 196 |
+
**kwargs,
|
| 197 |
+
)
|
| 198 |
+
|
| 199 |
+
attn_output = attn_output.reshape(*input_shape, -1).contiguous()
|
| 200 |
+
attn_output = self.o_proj(attn_output)
|
| 201 |
+
return attn_output, attn_weights
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
class MoonshineStreamingEncoderLayer(MoonshineEncoderLayer):
|
| 205 |
+
def __init__(self, config: MoonshineStreamingConfig, layer_idx: int):
|
| 206 |
+
super().__init__(config, layer_idx)
|
| 207 |
+
self.self_attn = MoonshineStreamingEncoderAttention(config, layer_idx)
|
| 208 |
+
self.mlp = MoonshineStreamingEncoderMLP(config, config.hidden_act)
|
| 209 |
+
self.input_layernorm = MoonshineStreamingLayerNorm(config.hidden_size)
|
| 210 |
+
self.post_attention_layernorm = MoonshineStreamingLayerNorm(config.hidden_size)
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
class MoonshineStreamingEncoderEmbedder(nn.Module):
|
| 214 |
+
def __init__(self, config):
|
| 215 |
+
super().__init__()
|
| 216 |
+
self.cmvn = MoonshineStreamingFrameCMVN()
|
| 217 |
+
self.comp = MoonshineStreamingAsinhCompression()
|
| 218 |
+
self.conv1 = MoonshineStreamingCausalConv1d(
|
| 219 |
+
config.hidden_size, config.hidden_size * 2, kernel_size=5, stride=2
|
| 220 |
+
)
|
| 221 |
+
self.conv2 = MoonshineStreamingCausalConv1d(
|
| 222 |
+
config.hidden_size * 2, config.hidden_size, kernel_size=5, stride=2
|
| 223 |
+
)
|
| 224 |
+
self.frame_len = int(round(config.sample_rate * config.frame_ms / 1000.0))
|
| 225 |
+
self.linear = nn.Linear(self.frame_len, config.hidden_size, bias=False)
|
| 226 |
+
|
| 227 |
+
def forward(self, input_values, padding_mask=None):
|
| 228 |
+
hidden_states = self.cmvn(input_values.reshape(input_values.shape[0], -1, self.frame_len))
|
| 229 |
+
hidden_states = self.comp(hidden_states)
|
| 230 |
+
hidden_states = nn.functional.silu(self.linear(hidden_states))
|
| 231 |
+
|
| 232 |
+
if padding_mask is not None:
|
| 233 |
+
num_frames = padding_mask.sum(-1) // self.frame_len
|
| 234 |
+
padding_mask = (
|
| 235 |
+
torch.arange(hidden_states.shape[1], device=padding_mask.device)[None, :] < num_frames[:, None]
|
| 236 |
+
)
|
| 237 |
+
hidden_states *= padding_mask[..., None]
|
| 238 |
+
|
| 239 |
+
hidden_states = hidden_states.transpose(1, 2)
|
| 240 |
+
hidden_states, padding_mask = self.conv1(hidden_states, padding_mask)
|
| 241 |
+
hidden_states = nn.functional.silu(hidden_states)
|
| 242 |
+
hidden_states, padding_mask = self.conv2(hidden_states, padding_mask)
|
| 243 |
+
hidden_states = hidden_states.transpose(1, 2)
|
| 244 |
+
return hidden_states, padding_mask
|
| 245 |
+
|
| 246 |
+
|
| 247 |
+
class MoonshineStreamingPreTrainedModel(MoonshinePreTrainedModel):
|
| 248 |
+
def _get_feat_extract_output_lengths(self, input_lengths: torch.LongTensor) -> torch.LongTensor:
|
| 249 |
+
frame_len = int(round(self.config.encoder_config.sample_rate * self.config.encoder_config.frame_ms / 1000.0))
|
| 250 |
+
output_lengths = input_lengths // frame_len
|
| 251 |
+
output_lengths = (output_lengths - 1) // 2 + 1
|
| 252 |
+
output_lengths = (output_lengths - 1) // 2 + 1
|
| 253 |
+
return output_lengths
|
| 254 |
+
|
| 255 |
+
def _init_weights(self, module: nn.Module):
|
| 256 |
+
if isinstance(module, MoonshineStreamingLayerNorm):
|
| 257 |
+
nn.init.constant_(module.gamma, 1.0 - module.unit_offset)
|
| 258 |
+
else:
|
| 259 |
+
super()._init_weights(module)
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
def sliding_window_mask_function(sliding_window: tuple[int, int]) -> Callable:
|
| 263 |
+
"""
|
| 264 |
+
This creates uni/bidirectional attention mask with sliding window.
|
| 265 |
+
"""
|
| 266 |
+
|
| 267 |
+
def inner_mask(batch_idx: int, head_idx: int, q_idx: int, kv_idx: int) -> bool:
|
| 268 |
+
left_window_size, right_window_size = sliding_window
|
| 269 |
+
|
| 270 |
+
dist = q_idx - kv_idx
|
| 271 |
+
left_mask = (dist >= 0) & (dist < left_window_size)
|
| 272 |
+
right_mask = (dist < 0) & (-dist < right_window_size)
|
| 273 |
+
return left_mask | right_mask
|
| 274 |
+
|
| 275 |
+
return inner_mask
|
| 276 |
+
|
| 277 |
+
|
| 278 |
+
class MoonshineStreamingEncoder(MoonshineStreamingPreTrainedModel):
|
| 279 |
+
config: MoonshineStreamingEncoderConfig
|
| 280 |
+
_can_record_outputs = {
|
| 281 |
+
"attentions": OutputRecorder(MoonshineStreamingEncoderAttention, index=1, layer_name="self_attn"),
|
| 282 |
+
"hidden_states": MoonshineStreamingEncoderLayer,
|
| 283 |
+
}
|
| 284 |
+
|
| 285 |
+
def __init__(self, config: MoonshineStreamingEncoderConfig):
|
| 286 |
+
super().__init__(config)
|
| 287 |
+
self.embedder = MoonshineStreamingEncoderEmbedder(config)
|
| 288 |
+
self.layers = nn.ModuleList(
|
| 289 |
+
[MoonshineStreamingEncoderLayer(config, idx) for idx in range(config.num_hidden_layers)]
|
| 290 |
+
)
|
| 291 |
+
self.final_norm = MoonshineStreamingLayerNorm(config.hidden_size)
|
| 292 |
+
self.gradient_checkpointing = False
|
| 293 |
+
|
| 294 |
+
self.post_init()
|
| 295 |
+
|
| 296 |
+
@merge_with_config_defaults
|
| 297 |
+
@capture_outputs
|
| 298 |
+
def forward(
|
| 299 |
+
self,
|
| 300 |
+
input_values: torch.FloatTensor,
|
| 301 |
+
attention_mask: torch.Tensor | None = None,
|
| 302 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 303 |
+
) -> BaseModelOutputWithPast:
|
| 304 |
+
r"""
|
| 305 |
+
Args:
|
| 306 |
+
input_values (`torch.FloatTensor` of shape `(batch_size, audio_length)`):
|
| 307 |
+
Float values of the raw speech waveform. Raw speech waveform can be
|
| 308 |
+
obtained by loading a `.flac` or `.wav` audio file into an array of type `list[float]`, a
|
| 309 |
+
`numpy.ndarray` or a `torch.Tensor`, *e.g.* via the torchcodec library (`pip install torchcodec`) or
|
| 310 |
+
the soundfile library (`pip install soundfile`). To prepare the array into
|
| 311 |
+
`input_values`, the [`AutoFeatureExtractor`] should be used for padding
|
| 312 |
+
and conversion into a tensor of type `torch.FloatTensor`.
|
| 313 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 314 |
+
Mask to avoid performing attention on padding indices in `input_values`. Mask values selected in `[0, 1]`:
|
| 315 |
+
- 1 for tokens that are **not masked**,
|
| 316 |
+
- 0 for tokens that are **masked**.
|
| 317 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 318 |
+
"""
|
| 319 |
+
inputs_embeds, attention_mask = self.embedder(input_values, padding_mask=attention_mask)
|
| 320 |
+
|
| 321 |
+
if attention_mask is not None:
|
| 322 |
+
mask_kwargs = {
|
| 323 |
+
"config": self.config,
|
| 324 |
+
"inputs_embeds": inputs_embeds,
|
| 325 |
+
"attention_mask": attention_mask,
|
| 326 |
+
}
|
| 327 |
+
per_layer_attention_mask = [
|
| 328 |
+
create_bidirectional_mask(
|
| 329 |
+
and_mask_function=sliding_window_mask_function(self.config.sliding_windows[layer_idx]),
|
| 330 |
+
**mask_kwargs,
|
| 331 |
+
)
|
| 332 |
+
for layer_idx in range(self.config.num_hidden_layers)
|
| 333 |
+
]
|
| 334 |
+
|
| 335 |
+
hidden_states = inputs_embeds
|
| 336 |
+
for layer_idx, encoder_layer in enumerate(self.layers):
|
| 337 |
+
hidden_states = encoder_layer(
|
| 338 |
+
hidden_states,
|
| 339 |
+
attention_mask=per_layer_attention_mask[layer_idx] if attention_mask is not None else None,
|
| 340 |
+
**kwargs,
|
| 341 |
+
)
|
| 342 |
+
|
| 343 |
+
hidden_states = self.final_norm(hidden_states)
|
| 344 |
+
|
| 345 |
+
return MoonshineStreamingEncoderModelOutput(last_hidden_state=hidden_states, attention_mask=attention_mask)
|
| 346 |
+
|
| 347 |
+
|
| 348 |
+
class MoonshinMoonshineStreamingDecoderMLP(LlamaMLP): ...
|
| 349 |
+
|
| 350 |
+
|
| 351 |
+
class MoonshineStreamingDecoder(MoonshineDecoder):
|
| 352 |
+
def __init__(self, config):
|
| 353 |
+
super().__init__(config)
|
| 354 |
+
self.pos_emb = nn.Embedding(self.config.max_position_embeddings, config.encoder_config.hidden_size)
|
| 355 |
+
|
| 356 |
+
if config.encoder_config.hidden_size != self.config.hidden_size:
|
| 357 |
+
self.proj = nn.Linear(config.encoder_config.hidden_size, self.config.hidden_size, bias=False)
|
| 358 |
+
else:
|
| 359 |
+
self.proj = nn.Identity()
|
| 360 |
+
|
| 361 |
+
@merge_with_config_defaults
|
| 362 |
+
@capture_outputs
|
| 363 |
+
def forward(
|
| 364 |
+
self,
|
| 365 |
+
input_ids: torch.LongTensor | None = None,
|
| 366 |
+
attention_mask: torch.Tensor | None = None,
|
| 367 |
+
position_ids: torch.LongTensor | None = None,
|
| 368 |
+
past_key_values: Cache | None = None,
|
| 369 |
+
inputs_embeds: torch.FloatTensor | None = None,
|
| 370 |
+
use_cache: bool | None = None,
|
| 371 |
+
encoder_hidden_states: torch.FloatTensor | None = None,
|
| 372 |
+
encoder_attention_mask: torch.Tensor | None = None,
|
| 373 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 374 |
+
) -> tuple | BaseModelOutputWithPast:
|
| 375 |
+
r"""
|
| 376 |
+
encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, encoder_sequence_length, hidden_size)`, *optional*):
|
| 377 |
+
Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
|
| 378 |
+
of the decoder.
|
| 379 |
+
encoder_attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 380 |
+
Mask to avoid performing attention on padding indices in `encoder_hidden_states`. Mask values selected in `[0, 1]`:
|
| 381 |
+
- 1 for tokens that are **not masked**,
|
| 382 |
+
- 0 for tokens that are **masked**.
|
| 383 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 384 |
+
"""
|
| 385 |
+
position_embeddings = self.pos_emb(
|
| 386 |
+
torch.arange(encoder_hidden_states.shape[1], device=encoder_hidden_states.device)
|
| 387 |
+
)
|
| 388 |
+
encoder_hidden_states += position_embeddings.to(encoder_hidden_states.device)
|
| 389 |
+
encoder_hidden_states = self.proj(encoder_hidden_states)
|
| 390 |
+
|
| 391 |
+
return super().forward(
|
| 392 |
+
input_ids=input_ids,
|
| 393 |
+
attention_mask=attention_mask,
|
| 394 |
+
position_ids=position_ids,
|
| 395 |
+
past_key_values=past_key_values,
|
| 396 |
+
inputs_embeds=inputs_embeds,
|
| 397 |
+
use_cache=use_cache,
|
| 398 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 399 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 400 |
+
**kwargs,
|
| 401 |
+
)
|
| 402 |
+
|
| 403 |
+
|
| 404 |
+
class MoonshineStreamingModel(MoonshineModel):
|
| 405 |
+
def __init__(self, config):
|
| 406 |
+
super().__init__(config)
|
| 407 |
+
self.encoder = MoonshineStreamingEncoder(config.encoder_config)
|
| 408 |
+
self.decoder = MoonshineStreamingDecoder(config)
|
| 409 |
+
|
| 410 |
+
|
| 411 |
+
class MoonshineStreamingForConditionalGeneration(MoonshineForConditionalGeneration): ...
|
| 412 |
+
|
| 413 |
+
|
| 414 |
+
__all__ = [
|
| 415 |
+
"MoonshineStreamingPreTrainedModel",
|
| 416 |
+
"MoonshineStreamingModel",
|
| 417 |
+
"MoonshineStreamingForConditionalGeneration",
|
| 418 |
+
"MoonshineStreamingProcessor",
|
| 419 |
+
]
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/moonshine_streaming/processing_moonshine_streaming.py
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 2 |
+
# This file was automatically generated from src/transformers/models/moonshine_streaming/modular_moonshine_streaming.py.
|
| 3 |
+
# Do NOT edit this file manually as any edits will be overwritten by the generation of
|
| 4 |
+
# the file from the modular. If any change should be done, please apply the change to the
|
| 5 |
+
# modular_moonshine_streaming.py file directly. One of our CI enforces this.
|
| 6 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 7 |
+
# Copyright 2026 the HuggingFace Team. All rights reserved.
|
| 8 |
+
#
|
| 9 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 10 |
+
# you may not use this file except in compliance with the License.
|
| 11 |
+
# You may obtain a copy of the License at
|
| 12 |
+
#
|
| 13 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 14 |
+
#
|
| 15 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 16 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 17 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 18 |
+
# See the License for the specific language governing permissions and
|
| 19 |
+
# limitations under the License.
|
| 20 |
+
|
| 21 |
+
from ...processing_utils import ProcessingKwargs, ProcessorMixin, Unpack
|
| 22 |
+
from ...tokenization_utils_base import AudioInput, PreTokenizedInput, TextInput
|
| 23 |
+
from ...utils import auto_docstring
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class MoonshineStreamingProcessorKwargs(ProcessingKwargs, total=False):
|
| 27 |
+
_defaults = {
|
| 28 |
+
"audio_kwargs": {
|
| 29 |
+
"pad_to_multiple_of": 80,
|
| 30 |
+
"padding": True,
|
| 31 |
+
},
|
| 32 |
+
"common_kwargs": {"return_tensors": "pt"},
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
@auto_docstring
|
| 37 |
+
class MoonshineStreamingProcessor(ProcessorMixin):
|
| 38 |
+
def __init__(self, feature_extractor, tokenizer):
|
| 39 |
+
super().__init__(feature_extractor, tokenizer)
|
| 40 |
+
|
| 41 |
+
@auto_docstring
|
| 42 |
+
def __call__(
|
| 43 |
+
self,
|
| 44 |
+
audio: AudioInput | None = None,
|
| 45 |
+
text: str | list[str] | TextInput | PreTokenizedInput | None = None,
|
| 46 |
+
**kwargs: Unpack[MoonshineStreamingProcessorKwargs],
|
| 47 |
+
):
|
| 48 |
+
r"""
|
| 49 |
+
Returns:
|
| 50 |
+
This method returns the results of each `call` method. If both are used, the output is a dictionary containing the results of both.
|
| 51 |
+
"""
|
| 52 |
+
if audio is None and text is None:
|
| 53 |
+
raise ValueError("You need to specify either an `audio` or `text` input to process.")
|
| 54 |
+
|
| 55 |
+
output_kwargs = self._merge_kwargs(
|
| 56 |
+
MoonshineStreamingProcessorKwargs,
|
| 57 |
+
tokenizer_init_kwargs=self.tokenizer.init_kwargs,
|
| 58 |
+
**kwargs,
|
| 59 |
+
)
|
| 60 |
+
|
| 61 |
+
if audio is not None:
|
| 62 |
+
inputs = self.feature_extractor(audio, **output_kwargs["audio_kwargs"])
|
| 63 |
+
if text is not None:
|
| 64 |
+
encodings = self.tokenizer(text, **output_kwargs["text_kwargs"])
|
| 65 |
+
|
| 66 |
+
if text is None:
|
| 67 |
+
return inputs
|
| 68 |
+
elif audio is None:
|
| 69 |
+
return encodings
|
| 70 |
+
else:
|
| 71 |
+
inputs["labels"] = encodings["input_ids"]
|
| 72 |
+
return inputs
|
| 73 |
+
|
| 74 |
+
def pad(self, *args, **kwargs):
|
| 75 |
+
"""
|
| 76 |
+
This method operates on batches of extracted features and/or tokenized text. It forwards all arguments to
|
| 77 |
+
[`MoonshineStreamingFeatureExtractor.pad`] and/or [`PreTrainedTokenizer.pad`] depending on the input modality and returns their outputs. If both modalities are passed, [`MoonshineStreamingFeatureExtractor.pad`] and [`PreTrainedTokenizer.pad`] are called.
|
| 78 |
+
|
| 79 |
+
Args:
|
| 80 |
+
input_features:
|
| 81 |
+
When the first argument is a dictionary containing a batch of tensors, or the `input_features` argument is present, it is passed to [`MoonshineStreamingFeatureExtractor.pad`].
|
| 82 |
+
labels:
|
| 83 |
+
When the `label` argument is present, it is passed to [`PreTrainedTokenizer.pad`].
|
| 84 |
+
|
| 85 |
+
Returns:
|
| 86 |
+
This method returns the results of each `pad` method. If both are used, the output is a dictionary containing the results of both.
|
| 87 |
+
"""
|
| 88 |
+
input_features = kwargs.pop("input_features", None)
|
| 89 |
+
labels = kwargs.pop("labels", None)
|
| 90 |
+
if len(args) > 0:
|
| 91 |
+
input_features = args[0]
|
| 92 |
+
args = args[1:]
|
| 93 |
+
|
| 94 |
+
if input_features is not None:
|
| 95 |
+
input_features = self.feature_extractor.pad(input_features, *args, **kwargs)
|
| 96 |
+
if labels is not None:
|
| 97 |
+
labels = self.tokenizer.pad(labels, **kwargs)
|
| 98 |
+
|
| 99 |
+
if labels is None:
|
| 100 |
+
return input_features
|
| 101 |
+
elif input_features is None:
|
| 102 |
+
return labels
|
| 103 |
+
else:
|
| 104 |
+
input_features["labels"] = labels["input_ids"]
|
| 105 |
+
return input_features
|
| 106 |
+
|
| 107 |
+
@property
|
| 108 |
+
def model_input_names(self):
|
| 109 |
+
# The processor doesn't return text ids and the model seems to not need them
|
| 110 |
+
feature_extractor_input_names = self.feature_extractor.model_input_names
|
| 111 |
+
return feature_extractor_input_names + ["labels"]
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
__all__ = ["MoonshineStreamingProcessor"]
|
LTA_openwebtext_dualt/mini_owt_logdirichlet/.venv_qwen35_uv/lib/python3.12/site-packages/transformers/models/paligemma/__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_paligemma import *
|
| 22 |
+
from .modeling_paligemma import *
|
| 23 |
+
from .processing_paligemma import *
|
| 24 |
+
else:
|
| 25 |
+
import sys
|
| 26 |
+
|
| 27 |
+
_file = globals()["__file__"]
|
| 28 |
+
sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_sp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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
Processor class for PaliGemma.
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
import numpy as np
|
| 19 |
+
|
| 20 |
+
from ...feature_extraction_utils import BatchFeature
|
| 21 |
+
from ...image_utils import ImageInput, is_valid_image
|
| 22 |
+
from ...processing_utils import (
|
| 23 |
+
MultiModalData,
|
| 24 |
+
ProcessingKwargs,
|
| 25 |
+
ProcessorMixin,
|
| 26 |
+
TextKwargs,
|
| 27 |
+
Unpack,
|
| 28 |
+
)
|
| 29 |
+
from ...tokenization_utils_base import AddedToken, PreTokenizedInput, TextInput
|
| 30 |
+
from ...utils import auto_docstring, logging
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
logger = logging.get_logger(__name__)
|
| 34 |
+
|
| 35 |
+
IMAGE_TOKEN = "<image>"
|
| 36 |
+
EXTRA_TOKENS = [f"<loc{i:0>4}>" for i in range(1024)] + [f"<seg{i:0>3}>" for i in range(128)]
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class PaliGemmaTextKwargs(TextKwargs):
|
| 40 |
+
"""
|
| 41 |
+
suffix (`str`, `list[str]`, `list[list[str]]`):
|
| 42 |
+
The suffixes or batch of suffixes to be encoded. Only necessary for finetuning. See https://github.com/google-research/big_vision/blob/main/big_vision/configs/proj/paligemma/README.md
|
| 43 |
+
for more information. If your prompt is "<image> What is on the image", the suffix corresponds to the expected prediction "a cow sitting on a bench".
|
| 44 |
+
"""
|
| 45 |
+
|
| 46 |
+
suffix: TextInput | PreTokenizedInput | list[TextInput] | list[PreTokenizedInput] | None
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
class PaliGemmaProcessorKwargs(ProcessingKwargs, total=False):
|
| 50 |
+
text_kwargs: PaliGemmaTextKwargs
|
| 51 |
+
_defaults = {
|
| 52 |
+
"text_kwargs": {
|
| 53 |
+
"padding": False,
|
| 54 |
+
"return_mm_token_type_ids": False,
|
| 55 |
+
},
|
| 56 |
+
"images_kwargs": {
|
| 57 |
+
"data_format": "channels_first",
|
| 58 |
+
},
|
| 59 |
+
}
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
# Copied from transformers.models.idefics2.processing_idefics2.is_url
|
| 63 |
+
def is_url(val) -> bool:
|
| 64 |
+
return isinstance(val, str) and val.startswith("http")
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
# Copied from transformers.models.idefics2.processing_idefics2.is_image_or_image_url
|
| 68 |
+
def is_image_or_image_url(elem):
|
| 69 |
+
return is_url(elem) or is_valid_image(elem)
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def _is_str_or_image(elem):
|
| 73 |
+
return isinstance(elem, (str)) or is_image_or_image_url(elem)
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def build_string_from_input(prompt, bos_token, image_seq_len, image_token, num_images):
|
| 77 |
+
"""
|
| 78 |
+
Builds a string from the input prompt and image tokens.
|
| 79 |
+
For example, for the call:
|
| 80 |
+
build_string_from_input(
|
| 81 |
+
prompt="Prefix str"
|
| 82 |
+
bos_token="<s>",
|
| 83 |
+
image_seq_len=3,
|
| 84 |
+
image_token="<im>",
|
| 85 |
+
)
|
| 86 |
+
The output will be:
|
| 87 |
+
"<im><im><im><s>Initial str"
|
| 88 |
+
Args:
|
| 89 |
+
prompt (`list[Union[str, ImageInput]]`): The input prompt.
|
| 90 |
+
bos_token (`str`): The beginning of sentence token.
|
| 91 |
+
image_seq_len (`int`): The length of the image sequence.
|
| 92 |
+
image_token (`str`): The image token.
|
| 93 |
+
num_images (`int`): Number of images in the prompt.
|
| 94 |
+
"""
|
| 95 |
+
return f"{image_token * image_seq_len * num_images}{bos_token}{prompt}\n"
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
@auto_docstring
|
| 99 |
+
class PaliGemmaProcessor(ProcessorMixin):
|
| 100 |
+
def __init__(
|
| 101 |
+
self,
|
| 102 |
+
image_processor=None,
|
| 103 |
+
tokenizer=None,
|
| 104 |
+
chat_template=None,
|
| 105 |
+
**kwargs,
|
| 106 |
+
):
|
| 107 |
+
if not hasattr(image_processor, "image_seq_length"):
|
| 108 |
+
raise ValueError("Image processor is missing an `image_seq_length` attribute.")
|
| 109 |
+
|
| 110 |
+
self.image_seq_length = image_processor.image_seq_length
|
| 111 |
+
|
| 112 |
+
if not hasattr(tokenizer, "image_token"):
|
| 113 |
+
image_token = AddedToken(IMAGE_TOKEN, normalized=False, special=True)
|
| 114 |
+
tokens_to_add = {"additional_special_tokens": [image_token]}
|
| 115 |
+
tokenizer.add_special_tokens(tokens_to_add)
|
| 116 |
+
self.image_token_id = tokenizer.convert_tokens_to_ids(IMAGE_TOKEN)
|
| 117 |
+
self.image_token = IMAGE_TOKEN
|
| 118 |
+
else:
|
| 119 |
+
self.image_token_id = tokenizer.image_token_id
|
| 120 |
+
self.image_token = tokenizer.image_token
|
| 121 |
+
|
| 122 |
+
tokenizer.add_tokens(EXTRA_TOKENS)
|
| 123 |
+
tokenizer.add_bos_token = False
|
| 124 |
+
tokenizer.add_eos_token = False
|
| 125 |
+
|
| 126 |
+
super().__init__(image_processor, tokenizer, chat_template=chat_template)
|
| 127 |
+
|
| 128 |
+
@auto_docstring
|
| 129 |
+
def __call__(
|
| 130 |
+
self,
|
| 131 |
+
images: ImageInput | None = None,
|
| 132 |
+
text: TextInput | PreTokenizedInput | list[TextInput] | list[PreTokenizedInput] = None,
|
| 133 |
+
**kwargs: Unpack[PaliGemmaProcessorKwargs],
|
| 134 |
+
) -> BatchFeature:
|
| 135 |
+
r"""
|
| 136 |
+
Returns:
|
| 137 |
+
[`BatchFeature`]: A [`BatchFeature`] with the following fields:
|
| 138 |
+
|
| 139 |
+
- **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`. If `suffix`
|
| 140 |
+
is provided, the `input_ids` will also contain the suffix input ids.
|
| 141 |
+
- **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
|
| 142 |
+
`return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
|
| 143 |
+
`None`).
|
| 144 |
+
- **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
|
| 145 |
+
- **labels** -- Labels compatible with training if `suffix` is not None
|
| 146 |
+
"""
|
| 147 |
+
|
| 148 |
+
output_kwargs = self._merge_kwargs(
|
| 149 |
+
PaliGemmaProcessorKwargs,
|
| 150 |
+
tokenizer_init_kwargs=self.tokenizer.init_kwargs,
|
| 151 |
+
**kwargs,
|
| 152 |
+
)
|
| 153 |
+
suffix = output_kwargs["text_kwargs"].pop("suffix", None)
|
| 154 |
+
|
| 155 |
+
return_token_type_ids = True
|
| 156 |
+
|
| 157 |
+
if images is None:
|
| 158 |
+
raise ValueError("`images` are expected as arguments to a `PaliGemmaProcessor` instance.")
|
| 159 |
+
if text is None:
|
| 160 |
+
logger.warning_once(
|
| 161 |
+
"You are using PaliGemma without a text prefix. It will perform as a picture-captioning model."
|
| 162 |
+
)
|
| 163 |
+
text = ""
|
| 164 |
+
|
| 165 |
+
if _is_str_or_image(text):
|
| 166 |
+
text = [text]
|
| 167 |
+
elif isinstance(text, list) and _is_str_or_image(text[0]):
|
| 168 |
+
pass
|
| 169 |
+
|
| 170 |
+
if text is not None and images is not None:
|
| 171 |
+
if not any(IMAGE_TOKEN in sample for sample in text):
|
| 172 |
+
logger.warning(
|
| 173 |
+
"You are passing both `text` and `images` to `PaliGemmaProcessor`. The processor expects special "
|
| 174 |
+
"image tokens in the text, as many tokens as there are images per each text. It is recommended to "
|
| 175 |
+
"add `<image>` tokens in the very beginning of your text. For this call, we will infer how many images "
|
| 176 |
+
"each text has and add special tokens."
|
| 177 |
+
)
|
| 178 |
+
|
| 179 |
+
if isinstance(text, list) and isinstance(images, list):
|
| 180 |
+
if len(images) != len(text):
|
| 181 |
+
raise ValueError(
|
| 182 |
+
f"Received {len(images)} images for {len(text)} prompts. Each prompt should be associated with an image or list of images."
|
| 183 |
+
)
|
| 184 |
+
|
| 185 |
+
# make a nested list of lists to be able to iterate over the images and text below
|
| 186 |
+
if is_valid_image(images):
|
| 187 |
+
images = [[images]]
|
| 188 |
+
elif isinstance(images, (list, tuple)) and is_valid_image(images[0]):
|
| 189 |
+
images = [[image] for image in images]
|
| 190 |
+
elif not (
|
| 191 |
+
isinstance(images, (list, tuple))
|
| 192 |
+
and isinstance(images[0], (list, tuple))
|
| 193 |
+
and is_valid_image(images[0][0])
|
| 194 |
+
):
|
| 195 |
+
raise ValueError("images must be an image, list of images or list of list of images")
|
| 196 |
+
|
| 197 |
+
input_strings = [
|
| 198 |
+
build_string_from_input(
|
| 199 |
+
prompt=prompt,
|
| 200 |
+
bos_token=self.tokenizer.bos_token,
|
| 201 |
+
image_seq_len=self.image_seq_length,
|
| 202 |
+
image_token=IMAGE_TOKEN,
|
| 203 |
+
num_images=len(image_list) if isinstance(image_list, list) else 1,
|
| 204 |
+
)
|
| 205 |
+
for prompt, image_list in zip(text, images)
|
| 206 |
+
]
|
| 207 |
+
else:
|
| 208 |
+
expanded_samples = []
|
| 209 |
+
for sample in text:
|
| 210 |
+
expanded_sample = sample.replace(IMAGE_TOKEN, IMAGE_TOKEN * self.image_seq_length)
|
| 211 |
+
bos_rfind_index = expanded_sample.rfind(IMAGE_TOKEN)
|
| 212 |
+
bos_index = bos_rfind_index + len(IMAGE_TOKEN) if bos_rfind_index != -1 else 0
|
| 213 |
+
expanded_sample = (
|
| 214 |
+
expanded_sample[:bos_index] + self.tokenizer.bos_token + expanded_sample[bos_index:]
|
| 215 |
+
)
|
| 216 |
+
expanded_samples.append(expanded_sample)
|
| 217 |
+
input_strings = [f"{sample}\n" for sample in expanded_samples]
|
| 218 |
+
|
| 219 |
+
if suffix is not None and _is_str_or_image(suffix):
|
| 220 |
+
suffix = [suffix]
|
| 221 |
+
if suffix is not None:
|
| 222 |
+
suffix = [sfx + self.tokenizer.eos_token for sfx in suffix]
|
| 223 |
+
pixel_values = self.image_processor(images, **output_kwargs["images_kwargs"])["pixel_values"]
|
| 224 |
+
|
| 225 |
+
return_tensors = output_kwargs["text_kwargs"].pop("return_tensors", None)
|
| 226 |
+
return_mm_token_type_ids = output_kwargs["text_kwargs"].pop("return_mm_token_type_ids", None)
|
| 227 |
+
inputs = self.tokenizer(
|
| 228 |
+
input_strings,
|
| 229 |
+
text_pair=suffix,
|
| 230 |
+
return_token_type_ids=return_token_type_ids,
|
| 231 |
+
**output_kwargs["text_kwargs"],
|
| 232 |
+
)
|
| 233 |
+
self._check_special_mm_tokens(input_strings, inputs, modalities=["image"])
|
| 234 |
+
|
| 235 |
+
return_data = {**inputs, "pixel_values": pixel_values}
|
| 236 |
+
|
| 237 |
+
# TODO: ideally we would control label generation separately, now that we always return token_type_ids.
|
| 238 |
+
if return_token_type_ids:
|
| 239 |
+
labels = np.array(inputs["input_ids"])
|
| 240 |
+
labels[np.array(inputs["token_type_ids"]) == 0] = -100
|
| 241 |
+
return_data.update({"labels": labels})
|
| 242 |
+
|
| 243 |
+
if return_mm_token_type_ids:
|
| 244 |
+
return_data["mm_token_type_ids"] = self.create_mm_token_type_ids(return_data["input_ids"])
|
| 245 |
+
return BatchFeature(data=return_data, tensor_type=return_tensors)
|
| 246 |
+
|
| 247 |
+
def _get_num_multimodal_tokens(self, image_sizes=None, **kwargs):
|
| 248 |
+
"""
|
| 249 |
+
Computes the number of placeholder tokens needed for multimodal inputs with the given sizes.
|
| 250 |
+
|
| 251 |
+
Args:
|
| 252 |
+
image_sizes (list[list[str]], *optional*):
|
| 253 |
+
The input sizes formatted as (height, width) per each image.
|
| 254 |
+
Returns:
|
| 255 |
+
`MultiModalData`: A `MultiModalData` object holding number of tokens per each of the provided
|
| 256 |
+
input modalities, along with other useful data.
|
| 257 |
+
"""
|
| 258 |
+
vision_data = {}
|
| 259 |
+
if image_sizes is not None:
|
| 260 |
+
num_image_tokens = [self.image_seq_length] * len(image_sizes)
|
| 261 |
+
num_image_patches = [1] * len(image_sizes)
|
| 262 |
+
vision_data.update({"num_image_tokens": num_image_tokens, "num_image_patches": num_image_patches})
|
| 263 |
+
return MultiModalData(**vision_data)
|
| 264 |
+
|
| 265 |
+
@property
|
| 266 |
+
def model_input_names(self):
|
| 267 |
+
tokenizer_input_names = self.tokenizer.model_input_names + ["token_type_ids", "labels"]
|
| 268 |
+
image_processor_input_names = self.image_processor.model_input_names
|
| 269 |
+
return list(tokenizer_input_names + image_processor_input_names)
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
__all__ = ["PaliGemmaProcessor"]
|