Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- miniconda3/lib/python3.13/site-packages/rich-14.2.0.dist-info/INSTALLER +1 -0
- miniconda3/lib/python3.13/site-packages/rich-14.2.0.dist-info/METADATA +474 -0
- miniconda3/lib/python3.13/site-packages/rich-14.2.0.dist-info/RECORD +164 -0
- miniconda3/lib/python3.13/site-packages/rich-14.2.0.dist-info/REQUESTED +0 -0
- miniconda3/lib/python3.13/site-packages/rich-14.2.0.dist-info/WHEEL +4 -0
- miniconda3/lib/python3.13/site-packages/rich-14.2.0.dist-info/direct_url.json +1 -0
- miniconda3/lib/python3.13/site-packages/rich-14.2.0.dist-info/licenses/LICENSE +19 -0
- miniconda3/lib/python3.13/site-packages/rich/box.py +474 -0
- miniconda3/lib/python3.13/site-packages/rich/cells.py +174 -0
- miniconda3/lib/python3.13/site-packages/rich/color.py +621 -0
- miniconda3/lib/python3.13/site-packages/rich/color_triplet.py +38 -0
- miniconda3/lib/python3.13/site-packages/rich/columns.py +187 -0
- miniconda3/lib/python3.13/site-packages/rich/console.py +0 -0
- miniconda3/lib/python3.13/site-packages/rich/constrain.py +37 -0
- miniconda3/lib/python3.13/site-packages/rich/containers.py +167 -0
- miniconda3/lib/python3.13/site-packages/rich/control.py +219 -0
- miniconda3/lib/python3.13/site-packages/rich/default_styles.py +193 -0
- miniconda3/lib/python3.13/site-packages/rich/diagnose.py +39 -0
- miniconda3/lib/python3.13/site-packages/rich/emoji.py +91 -0
- miniconda3/lib/python3.13/site-packages/rich/errors.py +34 -0
- miniconda3/lib/python3.13/site-packages/rich/file_proxy.py +57 -0
- miniconda3/lib/python3.13/site-packages/rich/filesize.py +88 -0
- miniconda3/lib/python3.13/site-packages/rich/highlighter.py +232 -0
- miniconda3/lib/python3.13/site-packages/rich/json.py +139 -0
- miniconda3/lib/python3.13/site-packages/rich/jupyter.py +101 -0
- miniconda3/lib/python3.13/site-packages/rich/layout.py +442 -0
- miniconda3/lib/python3.13/site-packages/rich/live.py +400 -0
- miniconda3/lib/python3.13/site-packages/rich/live_render.py +106 -0
- miniconda3/lib/python3.13/site-packages/rich/logging.py +297 -0
- miniconda3/lib/python3.13/site-packages/rich/markdown.py +779 -0
- miniconda3/lib/python3.13/site-packages/rich/markup.py +251 -0
- miniconda3/lib/python3.13/site-packages/rich/measure.py +151 -0
- miniconda3/lib/python3.13/site-packages/rich/padding.py +141 -0
- miniconda3/lib/python3.13/site-packages/rich/pager.py +34 -0
- miniconda3/lib/python3.13/site-packages/rich/palette.py +100 -0
- miniconda3/lib/python3.13/site-packages/rich/panel.py +317 -0
- miniconda3/lib/python3.13/site-packages/rich/pretty.py +1016 -0
- miniconda3/lib/python3.13/site-packages/rich/progress.py +1715 -0
- miniconda3/lib/python3.13/site-packages/rich/progress_bar.py +223 -0
- miniconda3/lib/python3.13/site-packages/rich/prompt.py +400 -0
- miniconda3/lib/python3.13/site-packages/rich/protocol.py +42 -0
- miniconda3/lib/python3.13/site-packages/rich/py.typed +0 -0
- miniconda3/lib/python3.13/site-packages/rich/region.py +10 -0
- miniconda3/lib/python3.13/site-packages/rich/repr.py +149 -0
- miniconda3/lib/python3.13/site-packages/rich/rule.py +130 -0
- miniconda3/lib/python3.13/site-packages/rich/scope.py +86 -0
- miniconda3/lib/python3.13/site-packages/rich/screen.py +54 -0
- miniconda3/lib/python3.13/site-packages/rich/segment.py +752 -0
- miniconda3/lib/python3.13/site-packages/rich/spinner.py +132 -0
- miniconda3/lib/python3.13/site-packages/rich/status.py +131 -0
miniconda3/lib/python3.13/site-packages/rich-14.2.0.dist-info/INSTALLER
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
conda
|
miniconda3/lib/python3.13/site-packages/rich-14.2.0.dist-info/METADATA
ADDED
|
@@ -0,0 +1,474 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Metadata-Version: 2.4
|
| 2 |
+
Name: rich
|
| 3 |
+
Version: 14.2.0
|
| 4 |
+
Summary: Render rich text, tables, progress bars, syntax highlighting, markdown and more to the terminal
|
| 5 |
+
License: MIT
|
| 6 |
+
License-File: LICENSE
|
| 7 |
+
Author: Will McGugan
|
| 8 |
+
Author-email: willmcgugan@gmail.com
|
| 9 |
+
Requires-Python: >=3.8.0
|
| 10 |
+
Classifier: Development Status :: 5 - Production/Stable
|
| 11 |
+
Classifier: Environment :: Console
|
| 12 |
+
Classifier: Framework :: IPython
|
| 13 |
+
Classifier: Intended Audience :: Developers
|
| 14 |
+
Classifier: License :: OSI Approved :: MIT License
|
| 15 |
+
Classifier: Operating System :: MacOS
|
| 16 |
+
Classifier: Operating System :: Microsoft :: Windows
|
| 17 |
+
Classifier: Operating System :: POSIX :: Linux
|
| 18 |
+
Classifier: Programming Language :: Python :: 3
|
| 19 |
+
Classifier: Programming Language :: Python :: 3.8
|
| 20 |
+
Classifier: Programming Language :: Python :: 3.9
|
| 21 |
+
Classifier: Programming Language :: Python :: 3.10
|
| 22 |
+
Classifier: Programming Language :: Python :: 3.11
|
| 23 |
+
Classifier: Programming Language :: Python :: 3.12
|
| 24 |
+
Classifier: Programming Language :: Python :: 3.13
|
| 25 |
+
Classifier: Programming Language :: Python :: 3.14
|
| 26 |
+
Classifier: Typing :: Typed
|
| 27 |
+
Provides-Extra: jupyter
|
| 28 |
+
Requires-Dist: ipywidgets (>=7.5.1,<9) ; extra == "jupyter"
|
| 29 |
+
Requires-Dist: markdown-it-py (>=2.2.0)
|
| 30 |
+
Requires-Dist: pygments (>=2.13.0,<3.0.0)
|
| 31 |
+
Project-URL: Documentation, https://rich.readthedocs.io/en/latest/
|
| 32 |
+
Project-URL: Homepage, https://github.com/Textualize/rich
|
| 33 |
+
Description-Content-Type: text/markdown
|
| 34 |
+
|
| 35 |
+
[](https://pypi.org/project/rich/) [](https://badge.fury.io/py/rich)
|
| 36 |
+
|
| 37 |
+
[](https://pepy.tech/project/rich)
|
| 38 |
+
[](https://codecov.io/gh/Textualize/rich)
|
| 39 |
+
[](https://www.willmcgugan.com/tag/rich/)
|
| 40 |
+
[](https://twitter.com/willmcgugan)
|
| 41 |
+
|
| 42 |
+

|
| 43 |
+
|
| 44 |
+
[English readme](https://github.com/textualize/rich/blob/master/README.md)
|
| 45 |
+
• [简体中文 readme](https://github.com/textualize/rich/blob/master/README.cn.md)
|
| 46 |
+
• [正體中文 readme](https://github.com/textualize/rich/blob/master/README.zh-tw.md)
|
| 47 |
+
• [Lengua española readme](https://github.com/textualize/rich/blob/master/README.es.md)
|
| 48 |
+
• [Deutsche readme](https://github.com/textualize/rich/blob/master/README.de.md)
|
| 49 |
+
• [Läs på svenska](https://github.com/textualize/rich/blob/master/README.sv.md)
|
| 50 |
+
• [日本語 readme](https://github.com/textualize/rich/blob/master/README.ja.md)
|
| 51 |
+
• [한국어 readme](https://github.com/textualize/rich/blob/master/README.kr.md)
|
| 52 |
+
• [Français readme](https://github.com/textualize/rich/blob/master/README.fr.md)
|
| 53 |
+
• [Schwizerdütsch readme](https://github.com/textualize/rich/blob/master/README.de-ch.md)
|
| 54 |
+
• [हिन्दी readme](https://github.com/textualize/rich/blob/master/README.hi.md)
|
| 55 |
+
• [Português brasileiro readme](https://github.com/textualize/rich/blob/master/README.pt-br.md)
|
| 56 |
+
• [Italian readme](https://github.com/textualize/rich/blob/master/README.it.md)
|
| 57 |
+
• [Русский readme](https://github.com/textualize/rich/blob/master/README.ru.md)
|
| 58 |
+
• [Indonesian readme](https://github.com/textualize/rich/blob/master/README.id.md)
|
| 59 |
+
• [فارسی readme](https://github.com/textualize/rich/blob/master/README.fa.md)
|
| 60 |
+
• [Türkçe readme](https://github.com/textualize/rich/blob/master/README.tr.md)
|
| 61 |
+
• [Polskie readme](https://github.com/textualize/rich/blob/master/README.pl.md)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
Rich is a Python library for _rich_ text and beautiful formatting in the terminal.
|
| 65 |
+
|
| 66 |
+
The [Rich API](https://rich.readthedocs.io/en/latest/) makes it easy to add color and style to terminal output. Rich can also render pretty tables, progress bars, markdown, syntax highlighted source code, tracebacks, and more — out of the box.
|
| 67 |
+
|
| 68 |
+

|
| 69 |
+
|
| 70 |
+
For a video introduction to Rich see [calmcode.io](https://calmcode.io/rich/introduction.html) by [@fishnets88](https://twitter.com/fishnets88).
|
| 71 |
+
|
| 72 |
+
See what [people are saying about Rich](https://www.willmcgugan.com/blog/pages/post/rich-tweets/).
|
| 73 |
+
|
| 74 |
+
## Compatibility
|
| 75 |
+
|
| 76 |
+
Rich works with Linux, macOS and Windows. True color / emoji works with new Windows Terminal, classic terminal is limited to 16 colors. Rich requires Python 3.8 or later.
|
| 77 |
+
|
| 78 |
+
Rich works with [Jupyter notebooks](https://jupyter.org/) with no additional configuration required.
|
| 79 |
+
|
| 80 |
+
## Installing
|
| 81 |
+
|
| 82 |
+
Install with `pip` or your favorite PyPI package manager.
|
| 83 |
+
|
| 84 |
+
```sh
|
| 85 |
+
python -m pip install rich
|
| 86 |
+
```
|
| 87 |
+
|
| 88 |
+
Run the following to test Rich output on your terminal:
|
| 89 |
+
|
| 90 |
+
```sh
|
| 91 |
+
python -m rich
|
| 92 |
+
```
|
| 93 |
+
|
| 94 |
+
## Rich Print
|
| 95 |
+
|
| 96 |
+
To effortlessly add rich output to your application, you can import the [rich print](https://rich.readthedocs.io/en/latest/introduction.html#quick-start) method, which has the same signature as the builtin Python function. Try this:
|
| 97 |
+
|
| 98 |
+
```python
|
| 99 |
+
from rich import print
|
| 100 |
+
|
| 101 |
+
print("Hello, [bold magenta]World[/bold magenta]!", ":vampire:", locals())
|
| 102 |
+
```
|
| 103 |
+
|
| 104 |
+

|
| 105 |
+
|
| 106 |
+
## Rich REPL
|
| 107 |
+
|
| 108 |
+
Rich can be installed in the Python REPL, so that any data structures will be pretty printed and highlighted.
|
| 109 |
+
|
| 110 |
+
```python
|
| 111 |
+
>>> from rich import pretty
|
| 112 |
+
>>> pretty.install()
|
| 113 |
+
```
|
| 114 |
+
|
| 115 |
+

|
| 116 |
+
|
| 117 |
+
## Using the Console
|
| 118 |
+
|
| 119 |
+
For more control over rich terminal content, import and construct a [Console](https://rich.readthedocs.io/en/latest/reference/console.html#rich.console.Console) object.
|
| 120 |
+
|
| 121 |
+
```python
|
| 122 |
+
from rich.console import Console
|
| 123 |
+
|
| 124 |
+
console = Console()
|
| 125 |
+
```
|
| 126 |
+
|
| 127 |
+
The Console object has a `print` method which has an intentionally similar interface to the builtin `print` function. Here's an example of use:
|
| 128 |
+
|
| 129 |
+
```python
|
| 130 |
+
console.print("Hello", "World!")
|
| 131 |
+
```
|
| 132 |
+
|
| 133 |
+
As you might expect, this will print `"Hello World!"` to the terminal. Note that unlike the builtin `print` function, Rich will word-wrap your text to fit within the terminal width.
|
| 134 |
+
|
| 135 |
+
There are a few ways of adding color and style to your output. You can set a style for the entire output by adding a `style` keyword argument. Here's an example:
|
| 136 |
+
|
| 137 |
+
```python
|
| 138 |
+
console.print("Hello", "World!", style="bold red")
|
| 139 |
+
```
|
| 140 |
+
|
| 141 |
+
The output will be something like the following:
|
| 142 |
+
|
| 143 |
+

|
| 144 |
+
|
| 145 |
+
That's fine for styling a line of text at a time. For more finely grained styling, Rich renders a special markup which is similar in syntax to [bbcode](https://en.wikipedia.org/wiki/BBCode). Here's an example:
|
| 146 |
+
|
| 147 |
+
```python
|
| 148 |
+
console.print("Where there is a [bold cyan]Will[/bold cyan] there [u]is[/u] a [i]way[/i].")
|
| 149 |
+
```
|
| 150 |
+
|
| 151 |
+

|
| 152 |
+
|
| 153 |
+
You can use a Console object to generate sophisticated output with minimal effort. See the [Console API](https://rich.readthedocs.io/en/latest/console.html) docs for details.
|
| 154 |
+
|
| 155 |
+
## Rich Inspect
|
| 156 |
+
|
| 157 |
+
Rich has an [inspect](https://rich.readthedocs.io/en/latest/reference/init.html?highlight=inspect#rich.inspect) function which can produce a report on any Python object, such as class, instance, or builtin.
|
| 158 |
+
|
| 159 |
+
```python
|
| 160 |
+
>>> my_list = ["foo", "bar"]
|
| 161 |
+
>>> from rich import inspect
|
| 162 |
+
>>> inspect(my_list, methods=True)
|
| 163 |
+
```
|
| 164 |
+
|
| 165 |
+

|
| 166 |
+
|
| 167 |
+
See the [inspect docs](https://rich.readthedocs.io/en/latest/reference/init.html#rich.inspect) for details.
|
| 168 |
+
|
| 169 |
+
# Rich Library
|
| 170 |
+
|
| 171 |
+
Rich contains a number of builtin _renderables_ you can use to create elegant output in your CLI and help you debug your code.
|
| 172 |
+
|
| 173 |
+
Click the following headings for details:
|
| 174 |
+
|
| 175 |
+
<details>
|
| 176 |
+
<summary>Log</summary>
|
| 177 |
+
|
| 178 |
+
The Console object has a `log()` method which has a similar interface to `print()`, but also renders a column for the current time and the file and line which made the call. By default Rich will do syntax highlighting for Python structures and for repr strings. If you log a collection (i.e. a dict or a list) Rich will pretty print it so that it fits in the available space. Here's an example of some of these features.
|
| 179 |
+
|
| 180 |
+
```python
|
| 181 |
+
from rich.console import Console
|
| 182 |
+
console = Console()
|
| 183 |
+
|
| 184 |
+
test_data = [
|
| 185 |
+
{"jsonrpc": "2.0", "method": "sum", "params": [None, 1, 2, 4, False, True], "id": "1",},
|
| 186 |
+
{"jsonrpc": "2.0", "method": "notify_hello", "params": [7]},
|
| 187 |
+
{"jsonrpc": "2.0", "method": "subtract", "params": [42, 23], "id": "2"},
|
| 188 |
+
]
|
| 189 |
+
|
| 190 |
+
def test_log():
|
| 191 |
+
enabled = False
|
| 192 |
+
context = {
|
| 193 |
+
"foo": "bar",
|
| 194 |
+
}
|
| 195 |
+
movies = ["Deadpool", "Rise of the Skywalker"]
|
| 196 |
+
console.log("Hello from", console, "!")
|
| 197 |
+
console.log(test_data, log_locals=True)
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
test_log()
|
| 201 |
+
```
|
| 202 |
+
|
| 203 |
+
The above produces the following output:
|
| 204 |
+
|
| 205 |
+

|
| 206 |
+
|
| 207 |
+
Note the `log_locals` argument, which outputs a table containing the local variables where the log method was called.
|
| 208 |
+
|
| 209 |
+
The log method could be used for logging to the terminal for long running applications such as servers, but is also a very nice debugging aid.
|
| 210 |
+
|
| 211 |
+
</details>
|
| 212 |
+
<details>
|
| 213 |
+
<summary>Logging Handler</summary>
|
| 214 |
+
|
| 215 |
+
You can also use the builtin [Handler class](https://rich.readthedocs.io/en/latest/logging.html) to format and colorize output from Python's logging module. Here's an example of the output:
|
| 216 |
+
|
| 217 |
+

|
| 218 |
+
|
| 219 |
+
</details>
|
| 220 |
+
|
| 221 |
+
<details>
|
| 222 |
+
<summary>Emoji</summary>
|
| 223 |
+
|
| 224 |
+
To insert an emoji in to console output place the name between two colons. Here's an example:
|
| 225 |
+
|
| 226 |
+
```python
|
| 227 |
+
>>> console.print(":smiley: :vampire: :pile_of_poo: :thumbs_up: :raccoon:")
|
| 228 |
+
😃 🧛 💩 👍 🦝
|
| 229 |
+
```
|
| 230 |
+
|
| 231 |
+
Please use this feature wisely.
|
| 232 |
+
|
| 233 |
+
</details>
|
| 234 |
+
|
| 235 |
+
<details>
|
| 236 |
+
<summary>Tables</summary>
|
| 237 |
+
|
| 238 |
+
Rich can render flexible [tables](https://rich.readthedocs.io/en/latest/tables.html) with unicode box characters. There is a large variety of formatting options for borders, styles, cell alignment etc.
|
| 239 |
+
|
| 240 |
+

|
| 241 |
+
|
| 242 |
+
The animation above was generated with [table_movie.py](https://github.com/textualize/rich/blob/master/examples/table_movie.py) in the examples directory.
|
| 243 |
+
|
| 244 |
+
Here's a simpler table example:
|
| 245 |
+
|
| 246 |
+
```python
|
| 247 |
+
from rich.console import Console
|
| 248 |
+
from rich.table import Table
|
| 249 |
+
|
| 250 |
+
console = Console()
|
| 251 |
+
|
| 252 |
+
table = Table(show_header=True, header_style="bold magenta")
|
| 253 |
+
table.add_column("Date", style="dim", width=12)
|
| 254 |
+
table.add_column("Title")
|
| 255 |
+
table.add_column("Production Budget", justify="right")
|
| 256 |
+
table.add_column("Box Office", justify="right")
|
| 257 |
+
table.add_row(
|
| 258 |
+
"Dec 20, 2019", "Star Wars: The Rise of Skywalker", "$275,000,000", "$375,126,118"
|
| 259 |
+
)
|
| 260 |
+
table.add_row(
|
| 261 |
+
"May 25, 2018",
|
| 262 |
+
"[red]Solo[/red]: A Star Wars Story",
|
| 263 |
+
"$275,000,000",
|
| 264 |
+
"$393,151,347",
|
| 265 |
+
)
|
| 266 |
+
table.add_row(
|
| 267 |
+
"Dec 15, 2017",
|
| 268 |
+
"Star Wars Ep. VIII: The Last Jedi",
|
| 269 |
+
"$262,000,000",
|
| 270 |
+
"[bold]$1,332,539,889[/bold]",
|
| 271 |
+
)
|
| 272 |
+
|
| 273 |
+
console.print(table)
|
| 274 |
+
```
|
| 275 |
+
|
| 276 |
+
This produces the following output:
|
| 277 |
+
|
| 278 |
+

|
| 279 |
+
|
| 280 |
+
Note that console markup is rendered in the same way as `print()` and `log()`. In fact, anything that is renderable by Rich may be included in the headers / rows (even other tables).
|
| 281 |
+
|
| 282 |
+
The `Table` class is smart enough to resize columns to fit the available width of the terminal, wrapping text as required. Here's the same example, with the terminal made smaller than the table above:
|
| 283 |
+
|
| 284 |
+

|
| 285 |
+
|
| 286 |
+
</details>
|
| 287 |
+
|
| 288 |
+
<details>
|
| 289 |
+
<summary>Progress Bars</summary>
|
| 290 |
+
|
| 291 |
+
Rich can render multiple flicker-free [progress](https://rich.readthedocs.io/en/latest/progress.html) bars to track long-running tasks.
|
| 292 |
+
|
| 293 |
+
For basic usage, wrap any sequence in the `track` function and iterate over the result. Here's an example:
|
| 294 |
+
|
| 295 |
+
```python
|
| 296 |
+
from rich.progress import track
|
| 297 |
+
|
| 298 |
+
for step in track(range(100)):
|
| 299 |
+
do_step(step)
|
| 300 |
+
```
|
| 301 |
+
|
| 302 |
+
It's not much harder to add multiple progress bars. Here's an example taken from the docs:
|
| 303 |
+
|
| 304 |
+

|
| 305 |
+
|
| 306 |
+
The columns may be configured to show any details you want. Built-in columns include percentage complete, file size, file speed, and time remaining. Here's another example showing a download in progress:
|
| 307 |
+
|
| 308 |
+

|
| 309 |
+
|
| 310 |
+
To try this out yourself, see [examples/downloader.py](https://github.com/textualize/rich/blob/master/examples/downloader.py) which can download multiple URLs simultaneously while displaying progress.
|
| 311 |
+
|
| 312 |
+
</details>
|
| 313 |
+
|
| 314 |
+
<details>
|
| 315 |
+
<summary>Status</summary>
|
| 316 |
+
|
| 317 |
+
For situations where it is hard to calculate progress, you can use the [status](https://rich.readthedocs.io/en/latest/reference/console.html#rich.console.Console.status) method which will display a 'spinner' animation and message. The animation won't prevent you from using the console as normal. Here's an example:
|
| 318 |
+
|
| 319 |
+
```python
|
| 320 |
+
from time import sleep
|
| 321 |
+
from rich.console import Console
|
| 322 |
+
|
| 323 |
+
console = Console()
|
| 324 |
+
tasks = [f"task {n}" for n in range(1, 11)]
|
| 325 |
+
|
| 326 |
+
with console.status("[bold green]Working on tasks...") as status:
|
| 327 |
+
while tasks:
|
| 328 |
+
task = tasks.pop(0)
|
| 329 |
+
sleep(1)
|
| 330 |
+
console.log(f"{task} complete")
|
| 331 |
+
```
|
| 332 |
+
|
| 333 |
+
This generates the following output in the terminal.
|
| 334 |
+
|
| 335 |
+

|
| 336 |
+
|
| 337 |
+
The spinner animations were borrowed from [cli-spinners](https://www.npmjs.com/package/cli-spinners). You can select a spinner by specifying the `spinner` parameter. Run the following command to see the available values:
|
| 338 |
+
|
| 339 |
+
```
|
| 340 |
+
python -m rich.spinner
|
| 341 |
+
```
|
| 342 |
+
|
| 343 |
+
The above command generates the following output in the terminal:
|
| 344 |
+
|
| 345 |
+

|
| 346 |
+
|
| 347 |
+
</details>
|
| 348 |
+
|
| 349 |
+
<details>
|
| 350 |
+
<summary>Tree</summary>
|
| 351 |
+
|
| 352 |
+
Rich can render a [tree](https://rich.readthedocs.io/en/latest/tree.html) with guide lines. A tree is ideal for displaying a file structure, or any other hierarchical data.
|
| 353 |
+
|
| 354 |
+
The labels of the tree can be simple text or anything else Rich can render. Run the following for a demonstration:
|
| 355 |
+
|
| 356 |
+
```
|
| 357 |
+
python -m rich.tree
|
| 358 |
+
```
|
| 359 |
+
|
| 360 |
+
This generates the following output:
|
| 361 |
+
|
| 362 |
+

|
| 363 |
+
|
| 364 |
+
See the [tree.py](https://github.com/textualize/rich/blob/master/examples/tree.py) example for a script that displays a tree view of any directory, similar to the linux `tree` command.
|
| 365 |
+
|
| 366 |
+
</details>
|
| 367 |
+
|
| 368 |
+
<details>
|
| 369 |
+
<summary>Columns</summary>
|
| 370 |
+
|
| 371 |
+
Rich can render content in neat [columns](https://rich.readthedocs.io/en/latest/columns.html) with equal or optimal width. Here's a very basic clone of the (MacOS / Linux) `ls` command which displays a directory listing in columns:
|
| 372 |
+
|
| 373 |
+
```python
|
| 374 |
+
import os
|
| 375 |
+
import sys
|
| 376 |
+
|
| 377 |
+
from rich import print
|
| 378 |
+
from rich.columns import Columns
|
| 379 |
+
|
| 380 |
+
directory = os.listdir(sys.argv[1])
|
| 381 |
+
print(Columns(directory))
|
| 382 |
+
```
|
| 383 |
+
|
| 384 |
+
The following screenshot is the output from the [columns example](https://github.com/textualize/rich/blob/master/examples/columns.py) which displays data pulled from an API in columns:
|
| 385 |
+
|
| 386 |
+

|
| 387 |
+
|
| 388 |
+
</details>
|
| 389 |
+
|
| 390 |
+
<details>
|
| 391 |
+
<summary>Markdown</summary>
|
| 392 |
+
|
| 393 |
+
Rich can render [markdown](https://rich.readthedocs.io/en/latest/markdown.html) and does a reasonable job of translating the formatting to the terminal.
|
| 394 |
+
|
| 395 |
+
To render markdown import the `Markdown` class and construct it with a string containing markdown code. Then print it to the console. Here's an example:
|
| 396 |
+
|
| 397 |
+
```python
|
| 398 |
+
from rich.console import Console
|
| 399 |
+
from rich.markdown import Markdown
|
| 400 |
+
|
| 401 |
+
console = Console()
|
| 402 |
+
with open("README.md") as readme:
|
| 403 |
+
markdown = Markdown(readme.read())
|
| 404 |
+
console.print(markdown)
|
| 405 |
+
```
|
| 406 |
+
|
| 407 |
+
This will produce output something like the following:
|
| 408 |
+
|
| 409 |
+

|
| 410 |
+
|
| 411 |
+
</details>
|
| 412 |
+
|
| 413 |
+
<details>
|
| 414 |
+
<summary>Syntax Highlighting</summary>
|
| 415 |
+
|
| 416 |
+
Rich uses the [pygments](https://pygments.org/) library to implement [syntax highlighting](https://rich.readthedocs.io/en/latest/syntax.html). Usage is similar to rendering markdown; construct a `Syntax` object and print it to the console. Here's an example:
|
| 417 |
+
|
| 418 |
+
```python
|
| 419 |
+
from rich.console import Console
|
| 420 |
+
from rich.syntax import Syntax
|
| 421 |
+
|
| 422 |
+
my_code = '''
|
| 423 |
+
def iter_first_last(values: Iterable[T]) -> Iterable[Tuple[bool, bool, T]]:
|
| 424 |
+
"""Iterate and generate a tuple with a flag for first and last value."""
|
| 425 |
+
iter_values = iter(values)
|
| 426 |
+
try:
|
| 427 |
+
previous_value = next(iter_values)
|
| 428 |
+
except StopIteration:
|
| 429 |
+
return
|
| 430 |
+
first = True
|
| 431 |
+
for value in iter_values:
|
| 432 |
+
yield first, False, previous_value
|
| 433 |
+
first = False
|
| 434 |
+
previous_value = value
|
| 435 |
+
yield first, True, previous_value
|
| 436 |
+
'''
|
| 437 |
+
syntax = Syntax(my_code, "python", theme="monokai", line_numbers=True)
|
| 438 |
+
console = Console()
|
| 439 |
+
console.print(syntax)
|
| 440 |
+
```
|
| 441 |
+
|
| 442 |
+
This will produce the following output:
|
| 443 |
+
|
| 444 |
+

|
| 445 |
+
|
| 446 |
+
</details>
|
| 447 |
+
|
| 448 |
+
<details>
|
| 449 |
+
<summary>Tracebacks</summary>
|
| 450 |
+
|
| 451 |
+
Rich can render [beautiful tracebacks](https://rich.readthedocs.io/en/latest/traceback.html) which are easier to read and show more code than standard Python tracebacks. You can set Rich as the default traceback handler so all uncaught exceptions will be rendered by Rich.
|
| 452 |
+
|
| 453 |
+
Here's what it looks like on OSX (similar on Linux):
|
| 454 |
+
|
| 455 |
+

|
| 456 |
+
|
| 457 |
+
</details>
|
| 458 |
+
|
| 459 |
+
All Rich renderables make use of the [Console Protocol](https://rich.readthedocs.io/en/latest/protocol.html), which you can also use to implement your own Rich content.
|
| 460 |
+
|
| 461 |
+
# Rich CLI
|
| 462 |
+
|
| 463 |
+
|
| 464 |
+
See also [Rich CLI](https://github.com/textualize/rich-cli) for a command line application powered by Rich. Syntax highlight code, render markdown, display CSVs in tables, and more, directly from the command prompt.
|
| 465 |
+
|
| 466 |
+
|
| 467 |
+

|
| 468 |
+
|
| 469 |
+
# Textual
|
| 470 |
+
|
| 471 |
+
See also Rich's sister project, [Textual](https://github.com/Textualize/textual), which you can use to build sophisticated User Interfaces in the terminal.
|
| 472 |
+
|
| 473 |
+

|
| 474 |
+
|
miniconda3/lib/python3.13/site-packages/rich-14.2.0.dist-info/RECORD
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
rich-14.2.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
|
| 2 |
+
rich-14.2.0.dist-info/METADATA,sha256=P9KUodSKDwH6jWLfyhI08Vewa90oansDMtj_H5oUS98,18279
|
| 3 |
+
rich-14.2.0.dist-info/RECORD,,
|
| 4 |
+
rich-14.2.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 5 |
+
rich-14.2.0.dist-info/WHEEL,sha256=M5asmiAlL6HEcOq52Yi5mmk9KmTVjY2RDPtO4p9DMrc,88
|
| 6 |
+
rich-14.2.0.dist-info/direct_url.json,sha256=o5ImHplym0xCdC-tY1Thxct-IsFIgoIIJm9zSyC2ZRI,94
|
| 7 |
+
rich-14.2.0.dist-info/licenses/LICENSE,sha256=3u18F6QxgVgZCj6iOcyHmlpQJxzruYrnAl9I--WNyhU,1056
|
| 8 |
+
rich/__init__.py,sha256=lh2WcoIOJp5M5_lbAsSUMGv8oiJeumROazHH_AYMS8I,6066
|
| 9 |
+
rich/__main__.py,sha256=YoXaPBcb-LeQMDj9jhZejCSY0DK4gP57uOlngbPxf4k,7752
|
| 10 |
+
rich/__pycache__/__init__.cpython-313.pyc,,
|
| 11 |
+
rich/__pycache__/__main__.cpython-313.pyc,,
|
| 12 |
+
rich/__pycache__/_cell_widths.cpython-313.pyc,,
|
| 13 |
+
rich/__pycache__/_emoji_codes.cpython-313.pyc,,
|
| 14 |
+
rich/__pycache__/_emoji_replace.cpython-313.pyc,,
|
| 15 |
+
rich/__pycache__/_export_format.cpython-313.pyc,,
|
| 16 |
+
rich/__pycache__/_extension.cpython-313.pyc,,
|
| 17 |
+
rich/__pycache__/_fileno.cpython-313.pyc,,
|
| 18 |
+
rich/__pycache__/_inspect.cpython-313.pyc,,
|
| 19 |
+
rich/__pycache__/_log_render.cpython-313.pyc,,
|
| 20 |
+
rich/__pycache__/_loop.cpython-313.pyc,,
|
| 21 |
+
rich/__pycache__/_null_file.cpython-313.pyc,,
|
| 22 |
+
rich/__pycache__/_palettes.cpython-313.pyc,,
|
| 23 |
+
rich/__pycache__/_pick.cpython-313.pyc,,
|
| 24 |
+
rich/__pycache__/_ratio.cpython-313.pyc,,
|
| 25 |
+
rich/__pycache__/_spinners.cpython-313.pyc,,
|
| 26 |
+
rich/__pycache__/_stack.cpython-313.pyc,,
|
| 27 |
+
rich/__pycache__/_timer.cpython-313.pyc,,
|
| 28 |
+
rich/__pycache__/_win32_console.cpython-313.pyc,,
|
| 29 |
+
rich/__pycache__/_windows.cpython-313.pyc,,
|
| 30 |
+
rich/__pycache__/_windows_renderer.cpython-313.pyc,,
|
| 31 |
+
rich/__pycache__/_wrap.cpython-313.pyc,,
|
| 32 |
+
rich/__pycache__/abc.cpython-313.pyc,,
|
| 33 |
+
rich/__pycache__/align.cpython-313.pyc,,
|
| 34 |
+
rich/__pycache__/ansi.cpython-313.pyc,,
|
| 35 |
+
rich/__pycache__/bar.cpython-313.pyc,,
|
| 36 |
+
rich/__pycache__/box.cpython-313.pyc,,
|
| 37 |
+
rich/__pycache__/cells.cpython-313.pyc,,
|
| 38 |
+
rich/__pycache__/color.cpython-313.pyc,,
|
| 39 |
+
rich/__pycache__/color_triplet.cpython-313.pyc,,
|
| 40 |
+
rich/__pycache__/columns.cpython-313.pyc,,
|
| 41 |
+
rich/__pycache__/console.cpython-313.pyc,,
|
| 42 |
+
rich/__pycache__/constrain.cpython-313.pyc,,
|
| 43 |
+
rich/__pycache__/containers.cpython-313.pyc,,
|
| 44 |
+
rich/__pycache__/control.cpython-313.pyc,,
|
| 45 |
+
rich/__pycache__/default_styles.cpython-313.pyc,,
|
| 46 |
+
rich/__pycache__/diagnose.cpython-313.pyc,,
|
| 47 |
+
rich/__pycache__/emoji.cpython-313.pyc,,
|
| 48 |
+
rich/__pycache__/errors.cpython-313.pyc,,
|
| 49 |
+
rich/__pycache__/file_proxy.cpython-313.pyc,,
|
| 50 |
+
rich/__pycache__/filesize.cpython-313.pyc,,
|
| 51 |
+
rich/__pycache__/highlighter.cpython-313.pyc,,
|
| 52 |
+
rich/__pycache__/json.cpython-313.pyc,,
|
| 53 |
+
rich/__pycache__/jupyter.cpython-313.pyc,,
|
| 54 |
+
rich/__pycache__/layout.cpython-313.pyc,,
|
| 55 |
+
rich/__pycache__/live.cpython-313.pyc,,
|
| 56 |
+
rich/__pycache__/live_render.cpython-313.pyc,,
|
| 57 |
+
rich/__pycache__/logging.cpython-313.pyc,,
|
| 58 |
+
rich/__pycache__/markdown.cpython-313.pyc,,
|
| 59 |
+
rich/__pycache__/markup.cpython-313.pyc,,
|
| 60 |
+
rich/__pycache__/measure.cpython-313.pyc,,
|
| 61 |
+
rich/__pycache__/padding.cpython-313.pyc,,
|
| 62 |
+
rich/__pycache__/pager.cpython-313.pyc,,
|
| 63 |
+
rich/__pycache__/palette.cpython-313.pyc,,
|
| 64 |
+
rich/__pycache__/panel.cpython-313.pyc,,
|
| 65 |
+
rich/__pycache__/pretty.cpython-313.pyc,,
|
| 66 |
+
rich/__pycache__/progress.cpython-313.pyc,,
|
| 67 |
+
rich/__pycache__/progress_bar.cpython-313.pyc,,
|
| 68 |
+
rich/__pycache__/prompt.cpython-313.pyc,,
|
| 69 |
+
rich/__pycache__/protocol.cpython-313.pyc,,
|
| 70 |
+
rich/__pycache__/region.cpython-313.pyc,,
|
| 71 |
+
rich/__pycache__/repr.cpython-313.pyc,,
|
| 72 |
+
rich/__pycache__/rule.cpython-313.pyc,,
|
| 73 |
+
rich/__pycache__/scope.cpython-313.pyc,,
|
| 74 |
+
rich/__pycache__/screen.cpython-313.pyc,,
|
| 75 |
+
rich/__pycache__/segment.cpython-313.pyc,,
|
| 76 |
+
rich/__pycache__/spinner.cpython-313.pyc,,
|
| 77 |
+
rich/__pycache__/status.cpython-313.pyc,,
|
| 78 |
+
rich/__pycache__/style.cpython-313.pyc,,
|
| 79 |
+
rich/__pycache__/styled.cpython-313.pyc,,
|
| 80 |
+
rich/__pycache__/syntax.cpython-313.pyc,,
|
| 81 |
+
rich/__pycache__/table.cpython-313.pyc,,
|
| 82 |
+
rich/__pycache__/terminal_theme.cpython-313.pyc,,
|
| 83 |
+
rich/__pycache__/text.cpython-313.pyc,,
|
| 84 |
+
rich/__pycache__/theme.cpython-313.pyc,,
|
| 85 |
+
rich/__pycache__/themes.cpython-313.pyc,,
|
| 86 |
+
rich/__pycache__/traceback.cpython-313.pyc,,
|
| 87 |
+
rich/__pycache__/tree.cpython-313.pyc,,
|
| 88 |
+
rich/_cell_widths.py,sha256=fbmeyetEdHjzE_Vx2l1uK7tnPOhMs2X1lJfO3vsKDpA,10209
|
| 89 |
+
rich/_emoji_codes.py,sha256=hu1VL9nbVdppJrVoijVshRlcRRe_v3dju3Mmd2sKZdY,140235
|
| 90 |
+
rich/_emoji_replace.py,sha256=n-kcetsEUx2ZUmhQrfeMNc-teeGhpuSQ5F8VPBsyvDo,1064
|
| 91 |
+
rich/_export_format.py,sha256=RI08pSrm5tBSzPMvnbTqbD9WIalaOoN5d4M1RTmLq1Y,2128
|
| 92 |
+
rich/_extension.py,sha256=G66PkbH_QdTJh6jD-J228O76CmAnr2hLQv72CgPPuzE,241
|
| 93 |
+
rich/_fileno.py,sha256=HWZxP5C2ajMbHryvAQZseflVfQoGzsKOHzKGsLD8ynQ,799
|
| 94 |
+
rich/_inspect.py,sha256=ROT0PLC2GMWialWZkqJIjmYq7INRijQQkoSokWTaAiI,9656
|
| 95 |
+
rich/_log_render.py,sha256=xBKCxqiO4FZk8eG56f8crFdrmJxFrJsQE3V3F-fFekc,3213
|
| 96 |
+
rich/_loop.py,sha256=hV_6CLdoPm0va22Wpw4zKqM0RYsz3TZxXj0PoS-9eDQ,1236
|
| 97 |
+
rich/_null_file.py,sha256=ADGKp1yt-k70FMKV6tnqCqecB-rSJzp-WQsD7LPL-kg,1394
|
| 98 |
+
rich/_palettes.py,sha256=cdev1JQKZ0JvlguV9ipHgznTdnvlIzUFDBb0It2PzjI,7063
|
| 99 |
+
rich/_pick.py,sha256=evDt8QN4lF5CiwrUIXlOJCntitBCOsI3ZLPEIAVRLJU,423
|
| 100 |
+
rich/_ratio.py,sha256=IOtl78sQCYZsmHyxhe45krkb68u9xVz7zFsXVJD-b2Y,5325
|
| 101 |
+
rich/_spinners.py,sha256=U2r1_g_1zSjsjiUdAESc2iAMc3i4ri_S8PYP6kQ5z1I,19919
|
| 102 |
+
rich/_stack.py,sha256=-C8OK7rxn3sIUdVwxZBBpeHhIzX0eI-VM3MemYfaXm0,351
|
| 103 |
+
rich/_timer.py,sha256=zelxbT6oPFZnNrwWPpc1ktUeAT-Vc4fuFcRZLQGLtMI,417
|
| 104 |
+
rich/_win32_console.py,sha256=o2QN_IRx10biGP3Ap1neaqX8FBGlUKSmWM6Kw4OSg-U,22719
|
| 105 |
+
rich/_windows.py,sha256=is3WpbHMj8WaTHYB11hc6lP2t4hlvt4TViTlHSmjsi0,1901
|
| 106 |
+
rich/_windows_renderer.py,sha256=d799xOnxLbCCCzGu9-U7YLmIQkxtxQIBFQQ6iu4veSc,2759
|
| 107 |
+
rich/_wrap.py,sha256=FlSsom5EX0LVkA3KWy34yHnCfLtqX-ZIepXKh-70rpc,3404
|
| 108 |
+
rich/abc.py,sha256=dALMOGfKVNeAbvqq66IpTQxQUerxD7AE4FKwqd0eQKk,878
|
| 109 |
+
rich/align.py,sha256=ADa5ty1Eh_Yf68Iay3FgKyjUXgjrc4TyqBDww9FeAAs,10288
|
| 110 |
+
rich/ansi.py,sha256=Avs1LHbSdcyOvDOdpELZUoULcBiYewY76eNBp6uFBhs,6921
|
| 111 |
+
rich/bar.py,sha256=ldbVHOzKJOnflVNuv1xS7g6dLX2E3wMnXkdPbpzJTcs,3263
|
| 112 |
+
rich/box.py,sha256=SSolg8_pzHzY9QvJQo-qp0tbPsnj8O_2W4hmi1l-Zo0,10650
|
| 113 |
+
rich/cells.py,sha256=KrQkj5-LghCCpJLSNQIyAZjndc4bnEqOEmi5YuZ9UCY,5130
|
| 114 |
+
rich/color.py,sha256=3HSULVDj7qQkXUdFWv78JOiSZzfy5y1nkcYhna296V0,18211
|
| 115 |
+
rich/color_triplet.py,sha256=3lhQkdJbvWPoLDO-AnYImAWmJvV5dlgYNCVZ97ORaN4,1054
|
| 116 |
+
rich/columns.py,sha256=HUX0KcMm9dsKNi11fTbiM_h2iDtl8ySCaVcxlalEzq8,7131
|
| 117 |
+
rich/console.py,sha256=rgyfKfmSnJHiGxVnv-wyGGIHPoJFgbOoiYPeyJXUclU,100789
|
| 118 |
+
rich/constrain.py,sha256=1VIPuC8AgtKWrcncQrjBdYqA3JVWysu6jZo1rrh7c7Q,1288
|
| 119 |
+
rich/containers.py,sha256=c_56TxcedGYqDepHBMTuZdUIijitAQgnox-Qde0Z1qo,5502
|
| 120 |
+
rich/control.py,sha256=HnsraFTzBaUQDzKJWXsfPv-PPmgGypSgSv7oANackqs,6475
|
| 121 |
+
rich/default_styles.py,sha256=j9eZgSn7bqnymxYzYp8h-0OGTRy2ZOj-PfY9toqp0Rw,8221
|
| 122 |
+
rich/diagnose.py,sha256=1RWnQoppPXjC_49AB4vtV048DK3ksQSq671C83Y6f-g,977
|
| 123 |
+
rich/emoji.py,sha256=_bTf1Y3JqiMk6Nfn4V_YOhq1wAPAHNODhGLJj95R3uI,2343
|
| 124 |
+
rich/errors.py,sha256=5pP3Kc5d4QJ_c0KFsxrfyhjiPVe7J1zOqSFbFAzcV-Y,642
|
| 125 |
+
rich/file_proxy.py,sha256=Tl9THMDZ-Pk5Wm8sI1gGg_U5DhusmxD-FZ0fUbcU0W0,1683
|
| 126 |
+
rich/filesize.py,sha256=_iz9lIpRgvW7MNSeCZnLg-HwzbP4GETg543WqD8SFs0,2484
|
| 127 |
+
rich/highlighter.py,sha256=G_sn-8DKjM1sEjLG_oc4ovkWmiUpWvj8bXi0yed2LnY,9586
|
| 128 |
+
rich/json.py,sha256=omC2WHTgURxEosna1ftoSJCne2EX7MDuQtCdswS3qsk,5019
|
| 129 |
+
rich/jupyter.py,sha256=G9pOJmR4ESIFYSd4MKGqmHqCtstx0oRWpyeTgv54-Xc,3228
|
| 130 |
+
rich/layout.py,sha256=WR8PCSroYnteIT3zawxQ3k3ad1sQO5wGG1SZOoeBuBM,13944
|
| 131 |
+
rich/live.py,sha256=tF3ukAAJZ_N2ZbGclqZ-iwLoIoZ8f0HHUz79jAyJqj8,15180
|
| 132 |
+
rich/live_render.py,sha256=It_39YdzrBm8o3LL0kaGorPFg-BfZWAcrBjLjFokbx4,3521
|
| 133 |
+
rich/logging.py,sha256=UL6TZNlaptYKHNhQ45LREy-29Pl-tQsBh7q3HSnWIAA,12456
|
| 134 |
+
rich/markdown.py,sha256=R6X_1TMxUy3j3p0fkbmP3AYj8vt9Q72jr4Rz6tdtSU8,25846
|
| 135 |
+
rich/markup.py,sha256=btpr271BLhiCR1jNglRnv2BpIzVcNefYwSMeW9teDbc,8427
|
| 136 |
+
rich/measure.py,sha256=HmrIJX8sWRTHbgh8MxEay_83VkqNW_70s8aKP5ZcYI8,5305
|
| 137 |
+
rich/padding.py,sha256=h8XnIivLrNtlxI3vQPKHXh4hAwjOJqZx0slM0z3g1_M,4896
|
| 138 |
+
rich/pager.py,sha256=SO_ETBFKbg3n_AgOzXm41Sv36YxXAyI3_R-KOY2_uSc,828
|
| 139 |
+
rich/palette.py,sha256=Ar6ZUrYHiFt6-Rr2k-k9F8V7hxgJYHNdqjk2vVXsLgc,3288
|
| 140 |
+
rich/panel.py,sha256=9sQl00hPIqH5G2gALQo4NepFwpP0k9wT-s_gOms5pIc,11157
|
| 141 |
+
rich/pretty.py,sha256=eQs437AksYaCB2qO_d-z6e0DF_t5F1KfXfa1Hi-Ya0E,36355
|
| 142 |
+
rich/progress.py,sha256=CUc2lkU-X59mVdGfjMCBkZeiGPL3uxdONjhNJF2T7wY,60408
|
| 143 |
+
rich/progress_bar.py,sha256=mZTPpJUwcfcdgQCTTz3kyY-fc79ddLwtx6Ghhxfo064,8162
|
| 144 |
+
rich/prompt.py,sha256=k0CUIW-3I55jGk8U3O1WiEhdF6yXa2EiWeRqRhuJXWA,12435
|
| 145 |
+
rich/protocol.py,sha256=Wt-2HZd67OYiopUkCTOz7lM38vyo5r3HEQZ9TOPDl5Q,1367
|
| 146 |
+
rich/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 147 |
+
rich/region.py,sha256=rNT9xZrVZTYIXZC0NYn41CJQwYNbR-KecPOxTgQvB8Y,166
|
| 148 |
+
rich/repr.py,sha256=HIsurPLZK9Gray75l3_vQx7S27AzTpAj4ChXSfe1Fes,4419
|
| 149 |
+
rich/rule.py,sha256=umO21Wjw0FcYAeTB3UumNLCsDWhejzxnjlf2VwiXiDI,4590
|
| 150 |
+
rich/scope.py,sha256=lf6Qet_e4JOY34lwhYSAG-NBXYKBcYu6t_igv_JoGog,2831
|
| 151 |
+
rich/screen.py,sha256=rL_j2wX-4SeuIOI2oOlc418QP9EAvD59GInUmEAE6jQ,1579
|
| 152 |
+
rich/segment.py,sha256=7gOdwSPrzu0a2gRmxBDtu3u2S8iG5s9l7wlB58dKMy0,24707
|
| 153 |
+
rich/spinner.py,sha256=onIhpKlljRHppTZasxO8kXgtYyCHUkpSgKglRJ3o51g,4214
|
| 154 |
+
rich/status.py,sha256=kkPph3YeAZBo-X-4wPp8gTqZyU466NLwZBA4PZTTewo,4424
|
| 155 |
+
rich/style.py,sha256=W9Ccy8Py8lNICtlfcp-ryzMTuQaGxAU3av7-g5fHu0s,26990
|
| 156 |
+
rich/styled.py,sha256=wljVsVTXbABMMZvkzkO43ZEk_-irzEtvUiQ-sNnikQ8,1234
|
| 157 |
+
rich/syntax.py,sha256=5ZBNxjIj3C1FC92vLwBVN-C5YAdKjPHfH6SqCzFaOYE,36263
|
| 158 |
+
rich/table.py,sha256=52hmoLoHpeJEomznWvW8Ce2m1w62HuQDSGmaG6fYyqI,40025
|
| 159 |
+
rich/terminal_theme.py,sha256=1j5-ufJfnvlAo5Qsi_ACZiXDmwMXzqgmFByObT9-yJY,3370
|
| 160 |
+
rich/text.py,sha256=v-vCOG8gS_D5QDhOhU19478-yEJGAXKVi8iYCCk7O_M,47540
|
| 161 |
+
rich/theme.py,sha256=oNyhXhGagtDlbDye3tVu3esWOWk0vNkuxFw-_unlaK0,3771
|
| 162 |
+
rich/themes.py,sha256=0xgTLozfabebYtcJtDdC5QkX5IVUEaviqDUJJh4YVFk,102
|
| 163 |
+
rich/traceback.py,sha256=MtNMwDaDOH35HRbeB_Kx2ReMjfPfRC8IfRUZPMuKFPE,35789
|
| 164 |
+
rich/tree.py,sha256=QoOwg424FkdwGfR8K0tZ6Q7qtzWNAUP_m4sFaYuG6nw,9391
|
miniconda3/lib/python3.13/site-packages/rich-14.2.0.dist-info/REQUESTED
ADDED
|
File without changes
|
miniconda3/lib/python3.13/site-packages/rich-14.2.0.dist-info/WHEEL
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Wheel-Version: 1.0
|
| 2 |
+
Generator: poetry-core 2.2.0
|
| 3 |
+
Root-Is-Purelib: true
|
| 4 |
+
Tag: py3-none-any
|
miniconda3/lib/python3.13/site-packages/rich-14.2.0.dist-info/direct_url.json
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
{"dir_info": {}, "url": "file:///home/task_176037557612320/conda-bld/rich_1760375632000/work"}
|
miniconda3/lib/python3.13/site-packages/rich-14.2.0.dist-info/licenses/LICENSE
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Copyright (c) 2020 Will McGugan
|
| 2 |
+
|
| 3 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 4 |
+
of this software and associated documentation files (the "Software"), to deal
|
| 5 |
+
in the Software without restriction, including without limitation the rights
|
| 6 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 7 |
+
copies of the Software, and to permit persons to whom the Software is
|
| 8 |
+
furnished to do so, subject to the following conditions:
|
| 9 |
+
|
| 10 |
+
The above copyright notice and this permission notice shall be included in all
|
| 11 |
+
copies or substantial portions of the Software.
|
| 12 |
+
|
| 13 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 14 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 15 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 16 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 17 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 18 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 19 |
+
SOFTWARE.
|
miniconda3/lib/python3.13/site-packages/rich/box.py
ADDED
|
@@ -0,0 +1,474 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import TYPE_CHECKING, Iterable, List, Literal
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
from ._loop import loop_last
|
| 5 |
+
|
| 6 |
+
if TYPE_CHECKING:
|
| 7 |
+
from rich.console import ConsoleOptions
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class Box:
|
| 11 |
+
"""Defines characters to render boxes.
|
| 12 |
+
|
| 13 |
+
┌─┬┐ top
|
| 14 |
+
│ ││ head
|
| 15 |
+
├─┼┤ head_row
|
| 16 |
+
│ ││ mid
|
| 17 |
+
├─┼┤ row
|
| 18 |
+
├─┼┤ foot_row
|
| 19 |
+
│ ││ foot
|
| 20 |
+
└─┴┘ bottom
|
| 21 |
+
|
| 22 |
+
Args:
|
| 23 |
+
box (str): Characters making up box.
|
| 24 |
+
ascii (bool, optional): True if this box uses ascii characters only. Default is False.
|
| 25 |
+
"""
|
| 26 |
+
|
| 27 |
+
def __init__(self, box: str, *, ascii: bool = False) -> None:
|
| 28 |
+
self._box = box
|
| 29 |
+
self.ascii = ascii
|
| 30 |
+
line1, line2, line3, line4, line5, line6, line7, line8 = box.splitlines()
|
| 31 |
+
# top
|
| 32 |
+
self.top_left, self.top, self.top_divider, self.top_right = iter(line1)
|
| 33 |
+
# head
|
| 34 |
+
self.head_left, _, self.head_vertical, self.head_right = iter(line2)
|
| 35 |
+
# head_row
|
| 36 |
+
(
|
| 37 |
+
self.head_row_left,
|
| 38 |
+
self.head_row_horizontal,
|
| 39 |
+
self.head_row_cross,
|
| 40 |
+
self.head_row_right,
|
| 41 |
+
) = iter(line3)
|
| 42 |
+
|
| 43 |
+
# mid
|
| 44 |
+
self.mid_left, _, self.mid_vertical, self.mid_right = iter(line4)
|
| 45 |
+
# row
|
| 46 |
+
self.row_left, self.row_horizontal, self.row_cross, self.row_right = iter(line5)
|
| 47 |
+
# foot_row
|
| 48 |
+
(
|
| 49 |
+
self.foot_row_left,
|
| 50 |
+
self.foot_row_horizontal,
|
| 51 |
+
self.foot_row_cross,
|
| 52 |
+
self.foot_row_right,
|
| 53 |
+
) = iter(line6)
|
| 54 |
+
# foot
|
| 55 |
+
self.foot_left, _, self.foot_vertical, self.foot_right = iter(line7)
|
| 56 |
+
# bottom
|
| 57 |
+
self.bottom_left, self.bottom, self.bottom_divider, self.bottom_right = iter(
|
| 58 |
+
line8
|
| 59 |
+
)
|
| 60 |
+
|
| 61 |
+
def __repr__(self) -> str:
|
| 62 |
+
return "Box(...)"
|
| 63 |
+
|
| 64 |
+
def __str__(self) -> str:
|
| 65 |
+
return self._box
|
| 66 |
+
|
| 67 |
+
def substitute(self, options: "ConsoleOptions", safe: bool = True) -> "Box":
|
| 68 |
+
"""Substitute this box for another if it won't render due to platform issues.
|
| 69 |
+
|
| 70 |
+
Args:
|
| 71 |
+
options (ConsoleOptions): Console options used in rendering.
|
| 72 |
+
safe (bool, optional): Substitute this for another Box if there are known problems
|
| 73 |
+
displaying on the platform (currently only relevant on Windows). Default is True.
|
| 74 |
+
|
| 75 |
+
Returns:
|
| 76 |
+
Box: A different Box or the same Box.
|
| 77 |
+
"""
|
| 78 |
+
box = self
|
| 79 |
+
if options.legacy_windows and safe:
|
| 80 |
+
box = LEGACY_WINDOWS_SUBSTITUTIONS.get(box, box)
|
| 81 |
+
if options.ascii_only and not box.ascii:
|
| 82 |
+
box = ASCII
|
| 83 |
+
return box
|
| 84 |
+
|
| 85 |
+
def get_plain_headed_box(self) -> "Box":
|
| 86 |
+
"""If this box uses special characters for the borders of the header, then
|
| 87 |
+
return the equivalent box that does not.
|
| 88 |
+
|
| 89 |
+
Returns:
|
| 90 |
+
Box: The most similar Box that doesn't use header-specific box characters.
|
| 91 |
+
If the current Box already satisfies this criterion, then it's returned.
|
| 92 |
+
"""
|
| 93 |
+
return PLAIN_HEADED_SUBSTITUTIONS.get(self, self)
|
| 94 |
+
|
| 95 |
+
def get_top(self, widths: Iterable[int]) -> str:
|
| 96 |
+
"""Get the top of a simple box.
|
| 97 |
+
|
| 98 |
+
Args:
|
| 99 |
+
widths (List[int]): Widths of columns.
|
| 100 |
+
|
| 101 |
+
Returns:
|
| 102 |
+
str: A string of box characters.
|
| 103 |
+
"""
|
| 104 |
+
|
| 105 |
+
parts: List[str] = []
|
| 106 |
+
append = parts.append
|
| 107 |
+
append(self.top_left)
|
| 108 |
+
for last, width in loop_last(widths):
|
| 109 |
+
append(self.top * width)
|
| 110 |
+
if not last:
|
| 111 |
+
append(self.top_divider)
|
| 112 |
+
append(self.top_right)
|
| 113 |
+
return "".join(parts)
|
| 114 |
+
|
| 115 |
+
def get_row(
|
| 116 |
+
self,
|
| 117 |
+
widths: Iterable[int],
|
| 118 |
+
level: Literal["head", "row", "foot", "mid"] = "row",
|
| 119 |
+
edge: bool = True,
|
| 120 |
+
) -> str:
|
| 121 |
+
"""Get the top of a simple box.
|
| 122 |
+
|
| 123 |
+
Args:
|
| 124 |
+
width (List[int]): Widths of columns.
|
| 125 |
+
|
| 126 |
+
Returns:
|
| 127 |
+
str: A string of box characters.
|
| 128 |
+
"""
|
| 129 |
+
if level == "head":
|
| 130 |
+
left = self.head_row_left
|
| 131 |
+
horizontal = self.head_row_horizontal
|
| 132 |
+
cross = self.head_row_cross
|
| 133 |
+
right = self.head_row_right
|
| 134 |
+
elif level == "row":
|
| 135 |
+
left = self.row_left
|
| 136 |
+
horizontal = self.row_horizontal
|
| 137 |
+
cross = self.row_cross
|
| 138 |
+
right = self.row_right
|
| 139 |
+
elif level == "mid":
|
| 140 |
+
left = self.mid_left
|
| 141 |
+
horizontal = " "
|
| 142 |
+
cross = self.mid_vertical
|
| 143 |
+
right = self.mid_right
|
| 144 |
+
elif level == "foot":
|
| 145 |
+
left = self.foot_row_left
|
| 146 |
+
horizontal = self.foot_row_horizontal
|
| 147 |
+
cross = self.foot_row_cross
|
| 148 |
+
right = self.foot_row_right
|
| 149 |
+
else:
|
| 150 |
+
raise ValueError("level must be 'head', 'row' or 'foot'")
|
| 151 |
+
|
| 152 |
+
parts: List[str] = []
|
| 153 |
+
append = parts.append
|
| 154 |
+
if edge:
|
| 155 |
+
append(left)
|
| 156 |
+
for last, width in loop_last(widths):
|
| 157 |
+
append(horizontal * width)
|
| 158 |
+
if not last:
|
| 159 |
+
append(cross)
|
| 160 |
+
if edge:
|
| 161 |
+
append(right)
|
| 162 |
+
return "".join(parts)
|
| 163 |
+
|
| 164 |
+
def get_bottom(self, widths: Iterable[int]) -> str:
|
| 165 |
+
"""Get the bottom of a simple box.
|
| 166 |
+
|
| 167 |
+
Args:
|
| 168 |
+
widths (List[int]): Widths of columns.
|
| 169 |
+
|
| 170 |
+
Returns:
|
| 171 |
+
str: A string of box characters.
|
| 172 |
+
"""
|
| 173 |
+
|
| 174 |
+
parts: List[str] = []
|
| 175 |
+
append = parts.append
|
| 176 |
+
append(self.bottom_left)
|
| 177 |
+
for last, width in loop_last(widths):
|
| 178 |
+
append(self.bottom * width)
|
| 179 |
+
if not last:
|
| 180 |
+
append(self.bottom_divider)
|
| 181 |
+
append(self.bottom_right)
|
| 182 |
+
return "".join(parts)
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
# fmt: off
|
| 186 |
+
ASCII: Box = Box(
|
| 187 |
+
"+--+\n"
|
| 188 |
+
"| ||\n"
|
| 189 |
+
"|-+|\n"
|
| 190 |
+
"| ||\n"
|
| 191 |
+
"|-+|\n"
|
| 192 |
+
"|-+|\n"
|
| 193 |
+
"| ||\n"
|
| 194 |
+
"+--+\n",
|
| 195 |
+
ascii=True,
|
| 196 |
+
)
|
| 197 |
+
|
| 198 |
+
ASCII2: Box = Box(
|
| 199 |
+
"+-++\n"
|
| 200 |
+
"| ||\n"
|
| 201 |
+
"+-++\n"
|
| 202 |
+
"| ||\n"
|
| 203 |
+
"+-++\n"
|
| 204 |
+
"+-++\n"
|
| 205 |
+
"| ||\n"
|
| 206 |
+
"+-++\n",
|
| 207 |
+
ascii=True,
|
| 208 |
+
)
|
| 209 |
+
|
| 210 |
+
ASCII_DOUBLE_HEAD: Box = Box(
|
| 211 |
+
"+-++\n"
|
| 212 |
+
"| ||\n"
|
| 213 |
+
"+=++\n"
|
| 214 |
+
"| ||\n"
|
| 215 |
+
"+-++\n"
|
| 216 |
+
"+-++\n"
|
| 217 |
+
"| ||\n"
|
| 218 |
+
"+-++\n",
|
| 219 |
+
ascii=True,
|
| 220 |
+
)
|
| 221 |
+
|
| 222 |
+
SQUARE: Box = Box(
|
| 223 |
+
"┌─┬┐\n"
|
| 224 |
+
"│ ││\n"
|
| 225 |
+
"├─┼┤\n"
|
| 226 |
+
"│ ││\n"
|
| 227 |
+
"├─┼┤\n"
|
| 228 |
+
"├─┼┤\n"
|
| 229 |
+
"│ ││\n"
|
| 230 |
+
"└─┴┘\n"
|
| 231 |
+
)
|
| 232 |
+
|
| 233 |
+
SQUARE_DOUBLE_HEAD: Box = Box(
|
| 234 |
+
"┌─┬┐\n"
|
| 235 |
+
"│ ││\n"
|
| 236 |
+
"╞═╪╡\n"
|
| 237 |
+
"│ ││\n"
|
| 238 |
+
"├─┼┤\n"
|
| 239 |
+
"├─┼┤\n"
|
| 240 |
+
"│ ││\n"
|
| 241 |
+
"└─┴┘\n"
|
| 242 |
+
)
|
| 243 |
+
|
| 244 |
+
MINIMAL: Box = Box(
|
| 245 |
+
" ╷ \n"
|
| 246 |
+
" │ \n"
|
| 247 |
+
"╶─┼╴\n"
|
| 248 |
+
" │ \n"
|
| 249 |
+
"╶─┼╴\n"
|
| 250 |
+
"╶─┼╴\n"
|
| 251 |
+
" │ \n"
|
| 252 |
+
" ╵ \n"
|
| 253 |
+
)
|
| 254 |
+
|
| 255 |
+
|
| 256 |
+
MINIMAL_HEAVY_HEAD: Box = Box(
|
| 257 |
+
" ╷ \n"
|
| 258 |
+
" │ \n"
|
| 259 |
+
"╺━┿╸\n"
|
| 260 |
+
" │ \n"
|
| 261 |
+
"╶─┼╴\n"
|
| 262 |
+
"╶─┼╴\n"
|
| 263 |
+
" │ \n"
|
| 264 |
+
" ╵ \n"
|
| 265 |
+
)
|
| 266 |
+
|
| 267 |
+
MINIMAL_DOUBLE_HEAD: Box = Box(
|
| 268 |
+
" ╷ \n"
|
| 269 |
+
" │ \n"
|
| 270 |
+
" ═╪ \n"
|
| 271 |
+
" │ \n"
|
| 272 |
+
" ─┼ \n"
|
| 273 |
+
" ─┼ \n"
|
| 274 |
+
" │ \n"
|
| 275 |
+
" ╵ \n"
|
| 276 |
+
)
|
| 277 |
+
|
| 278 |
+
|
| 279 |
+
SIMPLE: Box = Box(
|
| 280 |
+
" \n"
|
| 281 |
+
" \n"
|
| 282 |
+
" ── \n"
|
| 283 |
+
" \n"
|
| 284 |
+
" \n"
|
| 285 |
+
" ── \n"
|
| 286 |
+
" \n"
|
| 287 |
+
" \n"
|
| 288 |
+
)
|
| 289 |
+
|
| 290 |
+
SIMPLE_HEAD: Box = Box(
|
| 291 |
+
" \n"
|
| 292 |
+
" \n"
|
| 293 |
+
" ── \n"
|
| 294 |
+
" \n"
|
| 295 |
+
" \n"
|
| 296 |
+
" \n"
|
| 297 |
+
" \n"
|
| 298 |
+
" \n"
|
| 299 |
+
)
|
| 300 |
+
|
| 301 |
+
|
| 302 |
+
SIMPLE_HEAVY: Box = Box(
|
| 303 |
+
" \n"
|
| 304 |
+
" \n"
|
| 305 |
+
" ━━ \n"
|
| 306 |
+
" \n"
|
| 307 |
+
" \n"
|
| 308 |
+
" ━━ \n"
|
| 309 |
+
" \n"
|
| 310 |
+
" \n"
|
| 311 |
+
)
|
| 312 |
+
|
| 313 |
+
|
| 314 |
+
HORIZONTALS: Box = Box(
|
| 315 |
+
" ── \n"
|
| 316 |
+
" \n"
|
| 317 |
+
" ── \n"
|
| 318 |
+
" \n"
|
| 319 |
+
" ── \n"
|
| 320 |
+
" ── \n"
|
| 321 |
+
" \n"
|
| 322 |
+
" ── \n"
|
| 323 |
+
)
|
| 324 |
+
|
| 325 |
+
ROUNDED: Box = Box(
|
| 326 |
+
"╭─┬╮\n"
|
| 327 |
+
"│ ││\n"
|
| 328 |
+
"├─┼┤\n"
|
| 329 |
+
"│ ││\n"
|
| 330 |
+
"├─┼┤\n"
|
| 331 |
+
"├─┼┤\n"
|
| 332 |
+
"│ ││\n"
|
| 333 |
+
"╰─┴╯\n"
|
| 334 |
+
)
|
| 335 |
+
|
| 336 |
+
HEAVY: Box = Box(
|
| 337 |
+
"┏━┳┓\n"
|
| 338 |
+
"┃ ┃┃\n"
|
| 339 |
+
"┣━╋┫\n"
|
| 340 |
+
"┃ ┃┃\n"
|
| 341 |
+
"┣━╋┫\n"
|
| 342 |
+
"┣━╋┫\n"
|
| 343 |
+
"┃ ┃┃\n"
|
| 344 |
+
"┗━┻┛\n"
|
| 345 |
+
)
|
| 346 |
+
|
| 347 |
+
HEAVY_EDGE: Box = Box(
|
| 348 |
+
"┏━┯┓\n"
|
| 349 |
+
"┃ │┃\n"
|
| 350 |
+
"┠─┼┨\n"
|
| 351 |
+
"┃ │┃\n"
|
| 352 |
+
"┠─┼┨\n"
|
| 353 |
+
"┠─┼┨\n"
|
| 354 |
+
"┃ │┃\n"
|
| 355 |
+
"┗━┷┛\n"
|
| 356 |
+
)
|
| 357 |
+
|
| 358 |
+
HEAVY_HEAD: Box = Box(
|
| 359 |
+
"┏━┳┓\n"
|
| 360 |
+
"┃ ┃┃\n"
|
| 361 |
+
"┡━╇┩\n"
|
| 362 |
+
"│ ││\n"
|
| 363 |
+
"├─┼┤\n"
|
| 364 |
+
"├─┼┤\n"
|
| 365 |
+
"│ ││\n"
|
| 366 |
+
"└─┴┘\n"
|
| 367 |
+
)
|
| 368 |
+
|
| 369 |
+
DOUBLE: Box = Box(
|
| 370 |
+
"╔═╦╗\n"
|
| 371 |
+
"║ ║║\n"
|
| 372 |
+
"╠═╬╣\n"
|
| 373 |
+
"║ ║║\n"
|
| 374 |
+
"╠═╬╣\n"
|
| 375 |
+
"╠═╬╣\n"
|
| 376 |
+
"║ ║║\n"
|
| 377 |
+
"╚═╩╝\n"
|
| 378 |
+
)
|
| 379 |
+
|
| 380 |
+
DOUBLE_EDGE: Box = Box(
|
| 381 |
+
"╔═╤╗\n"
|
| 382 |
+
"║ │║\n"
|
| 383 |
+
"╟─┼╢\n"
|
| 384 |
+
"║ │║\n"
|
| 385 |
+
"╟─┼╢\n"
|
| 386 |
+
"╟─┼╢\n"
|
| 387 |
+
"║ │║\n"
|
| 388 |
+
"╚═╧╝\n"
|
| 389 |
+
)
|
| 390 |
+
|
| 391 |
+
MARKDOWN: Box = Box(
|
| 392 |
+
" \n"
|
| 393 |
+
"| ||\n"
|
| 394 |
+
"|-||\n"
|
| 395 |
+
"| ||\n"
|
| 396 |
+
"|-||\n"
|
| 397 |
+
"|-||\n"
|
| 398 |
+
"| ||\n"
|
| 399 |
+
" \n",
|
| 400 |
+
ascii=True,
|
| 401 |
+
)
|
| 402 |
+
# fmt: on
|
| 403 |
+
|
| 404 |
+
# Map Boxes that don't render with raster fonts on to equivalent that do
|
| 405 |
+
LEGACY_WINDOWS_SUBSTITUTIONS = {
|
| 406 |
+
ROUNDED: SQUARE,
|
| 407 |
+
MINIMAL_HEAVY_HEAD: MINIMAL,
|
| 408 |
+
SIMPLE_HEAVY: SIMPLE,
|
| 409 |
+
HEAVY: SQUARE,
|
| 410 |
+
HEAVY_EDGE: SQUARE,
|
| 411 |
+
HEAVY_HEAD: SQUARE,
|
| 412 |
+
}
|
| 413 |
+
|
| 414 |
+
# Map headed boxes to their headerless equivalents
|
| 415 |
+
PLAIN_HEADED_SUBSTITUTIONS = {
|
| 416 |
+
HEAVY_HEAD: SQUARE,
|
| 417 |
+
SQUARE_DOUBLE_HEAD: SQUARE,
|
| 418 |
+
MINIMAL_DOUBLE_HEAD: MINIMAL,
|
| 419 |
+
MINIMAL_HEAVY_HEAD: MINIMAL,
|
| 420 |
+
ASCII_DOUBLE_HEAD: ASCII2,
|
| 421 |
+
}
|
| 422 |
+
|
| 423 |
+
|
| 424 |
+
if __name__ == "__main__": # pragma: no cover
|
| 425 |
+
from rich.columns import Columns
|
| 426 |
+
from rich.panel import Panel
|
| 427 |
+
|
| 428 |
+
from . import box as box
|
| 429 |
+
from .console import Console
|
| 430 |
+
from .table import Table
|
| 431 |
+
from .text import Text
|
| 432 |
+
|
| 433 |
+
console = Console(record=True)
|
| 434 |
+
|
| 435 |
+
BOXES = [
|
| 436 |
+
"ASCII",
|
| 437 |
+
"ASCII2",
|
| 438 |
+
"ASCII_DOUBLE_HEAD",
|
| 439 |
+
"SQUARE",
|
| 440 |
+
"SQUARE_DOUBLE_HEAD",
|
| 441 |
+
"MINIMAL",
|
| 442 |
+
"MINIMAL_HEAVY_HEAD",
|
| 443 |
+
"MINIMAL_DOUBLE_HEAD",
|
| 444 |
+
"SIMPLE",
|
| 445 |
+
"SIMPLE_HEAD",
|
| 446 |
+
"SIMPLE_HEAVY",
|
| 447 |
+
"HORIZONTALS",
|
| 448 |
+
"ROUNDED",
|
| 449 |
+
"HEAVY",
|
| 450 |
+
"HEAVY_EDGE",
|
| 451 |
+
"HEAVY_HEAD",
|
| 452 |
+
"DOUBLE",
|
| 453 |
+
"DOUBLE_EDGE",
|
| 454 |
+
"MARKDOWN",
|
| 455 |
+
]
|
| 456 |
+
|
| 457 |
+
console.print(Panel("[bold green]Box Constants", style="green"), justify="center")
|
| 458 |
+
console.print()
|
| 459 |
+
|
| 460 |
+
columns = Columns(expand=True, padding=2)
|
| 461 |
+
for box_name in sorted(BOXES):
|
| 462 |
+
table = Table(
|
| 463 |
+
show_footer=True, style="dim", border_style="not dim", expand=True
|
| 464 |
+
)
|
| 465 |
+
table.add_column("Header 1", "Footer 1")
|
| 466 |
+
table.add_column("Header 2", "Footer 2")
|
| 467 |
+
table.add_row("Cell", "Cell")
|
| 468 |
+
table.add_row("Cell", "Cell")
|
| 469 |
+
table.box = getattr(box, box_name)
|
| 470 |
+
table.title = Text(f"box.{box_name}", style="magenta")
|
| 471 |
+
columns.add_renderable(table)
|
| 472 |
+
console.print(columns)
|
| 473 |
+
|
| 474 |
+
# console.save_svg("box.svg")
|
miniconda3/lib/python3.13/site-packages/rich/cells.py
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from functools import lru_cache
|
| 4 |
+
from typing import Callable
|
| 5 |
+
|
| 6 |
+
from ._cell_widths import CELL_WIDTHS
|
| 7 |
+
|
| 8 |
+
# Ranges of unicode ordinals that produce a 1-cell wide character
|
| 9 |
+
# This is non-exhaustive, but covers most common Western characters
|
| 10 |
+
_SINGLE_CELL_UNICODE_RANGES: list[tuple[int, int]] = [
|
| 11 |
+
(0x20, 0x7E), # Latin (excluding non-printable)
|
| 12 |
+
(0xA0, 0xAC),
|
| 13 |
+
(0xAE, 0x002FF),
|
| 14 |
+
(0x00370, 0x00482), # Greek / Cyrillic
|
| 15 |
+
(0x02500, 0x025FC), # Box drawing, box elements, geometric shapes
|
| 16 |
+
(0x02800, 0x028FF), # Braille
|
| 17 |
+
]
|
| 18 |
+
|
| 19 |
+
# A set of characters that are a single cell wide
|
| 20 |
+
_SINGLE_CELLS = frozenset(
|
| 21 |
+
[
|
| 22 |
+
character
|
| 23 |
+
for _start, _end in _SINGLE_CELL_UNICODE_RANGES
|
| 24 |
+
for character in map(chr, range(_start, _end + 1))
|
| 25 |
+
]
|
| 26 |
+
)
|
| 27 |
+
|
| 28 |
+
# When called with a string this will return True if all
|
| 29 |
+
# characters are single-cell, otherwise False
|
| 30 |
+
_is_single_cell_widths: Callable[[str], bool] = _SINGLE_CELLS.issuperset
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
@lru_cache(4096)
|
| 34 |
+
def cached_cell_len(text: str) -> int:
|
| 35 |
+
"""Get the number of cells required to display text.
|
| 36 |
+
|
| 37 |
+
This method always caches, which may use up a lot of memory. It is recommended to use
|
| 38 |
+
`cell_len` over this method.
|
| 39 |
+
|
| 40 |
+
Args:
|
| 41 |
+
text (str): Text to display.
|
| 42 |
+
|
| 43 |
+
Returns:
|
| 44 |
+
int: Get the number of cells required to display text.
|
| 45 |
+
"""
|
| 46 |
+
if _is_single_cell_widths(text):
|
| 47 |
+
return len(text)
|
| 48 |
+
return sum(map(get_character_cell_size, text))
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def cell_len(text: str, _cell_len: Callable[[str], int] = cached_cell_len) -> int:
|
| 52 |
+
"""Get the number of cells required to display text.
|
| 53 |
+
|
| 54 |
+
Args:
|
| 55 |
+
text (str): Text to display.
|
| 56 |
+
|
| 57 |
+
Returns:
|
| 58 |
+
int: Get the number of cells required to display text.
|
| 59 |
+
"""
|
| 60 |
+
if len(text) < 512:
|
| 61 |
+
return _cell_len(text)
|
| 62 |
+
if _is_single_cell_widths(text):
|
| 63 |
+
return len(text)
|
| 64 |
+
return sum(map(get_character_cell_size, text))
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
@lru_cache(maxsize=4096)
|
| 68 |
+
def get_character_cell_size(character: str) -> int:
|
| 69 |
+
"""Get the cell size of a character.
|
| 70 |
+
|
| 71 |
+
Args:
|
| 72 |
+
character (str): A single character.
|
| 73 |
+
|
| 74 |
+
Returns:
|
| 75 |
+
int: Number of cells (0, 1 or 2) occupied by that character.
|
| 76 |
+
"""
|
| 77 |
+
codepoint = ord(character)
|
| 78 |
+
_table = CELL_WIDTHS
|
| 79 |
+
lower_bound = 0
|
| 80 |
+
upper_bound = len(_table) - 1
|
| 81 |
+
index = (lower_bound + upper_bound) // 2
|
| 82 |
+
while True:
|
| 83 |
+
start, end, width = _table[index]
|
| 84 |
+
if codepoint < start:
|
| 85 |
+
upper_bound = index - 1
|
| 86 |
+
elif codepoint > end:
|
| 87 |
+
lower_bound = index + 1
|
| 88 |
+
else:
|
| 89 |
+
return 0 if width == -1 else width
|
| 90 |
+
if upper_bound < lower_bound:
|
| 91 |
+
break
|
| 92 |
+
index = (lower_bound + upper_bound) // 2
|
| 93 |
+
return 1
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def set_cell_size(text: str, total: int) -> str:
|
| 97 |
+
"""Set the length of a string to fit within given number of cells."""
|
| 98 |
+
|
| 99 |
+
if _is_single_cell_widths(text):
|
| 100 |
+
size = len(text)
|
| 101 |
+
if size < total:
|
| 102 |
+
return text + " " * (total - size)
|
| 103 |
+
return text[:total]
|
| 104 |
+
|
| 105 |
+
if total <= 0:
|
| 106 |
+
return ""
|
| 107 |
+
cell_size = cell_len(text)
|
| 108 |
+
if cell_size == total:
|
| 109 |
+
return text
|
| 110 |
+
if cell_size < total:
|
| 111 |
+
return text + " " * (total - cell_size)
|
| 112 |
+
|
| 113 |
+
start = 0
|
| 114 |
+
end = len(text)
|
| 115 |
+
|
| 116 |
+
# Binary search until we find the right size
|
| 117 |
+
while True:
|
| 118 |
+
pos = (start + end) // 2
|
| 119 |
+
before = text[: pos + 1]
|
| 120 |
+
before_len = cell_len(before)
|
| 121 |
+
if before_len == total + 1 and cell_len(before[-1]) == 2:
|
| 122 |
+
return before[:-1] + " "
|
| 123 |
+
if before_len == total:
|
| 124 |
+
return before
|
| 125 |
+
if before_len > total:
|
| 126 |
+
end = pos
|
| 127 |
+
else:
|
| 128 |
+
start = pos
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def chop_cells(
|
| 132 |
+
text: str,
|
| 133 |
+
width: int,
|
| 134 |
+
) -> list[str]:
|
| 135 |
+
"""Split text into lines such that each line fits within the available (cell) width.
|
| 136 |
+
|
| 137 |
+
Args:
|
| 138 |
+
text: The text to fold such that it fits in the given width.
|
| 139 |
+
width: The width available (number of cells).
|
| 140 |
+
|
| 141 |
+
Returns:
|
| 142 |
+
A list of strings such that each string in the list has cell width
|
| 143 |
+
less than or equal to the available width.
|
| 144 |
+
"""
|
| 145 |
+
_get_character_cell_size = get_character_cell_size
|
| 146 |
+
lines: list[list[str]] = [[]]
|
| 147 |
+
|
| 148 |
+
append_new_line = lines.append
|
| 149 |
+
append_to_last_line = lines[-1].append
|
| 150 |
+
|
| 151 |
+
total_width = 0
|
| 152 |
+
|
| 153 |
+
for character in text:
|
| 154 |
+
cell_width = _get_character_cell_size(character)
|
| 155 |
+
char_doesnt_fit = total_width + cell_width > width
|
| 156 |
+
|
| 157 |
+
if char_doesnt_fit:
|
| 158 |
+
append_new_line([character])
|
| 159 |
+
append_to_last_line = lines[-1].append
|
| 160 |
+
total_width = cell_width
|
| 161 |
+
else:
|
| 162 |
+
append_to_last_line(character)
|
| 163 |
+
total_width += cell_width
|
| 164 |
+
|
| 165 |
+
return ["".join(line) for line in lines]
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
if __name__ == "__main__": # pragma: no cover
|
| 169 |
+
print(get_character_cell_size("😽"))
|
| 170 |
+
for line in chop_cells("""这是对亚洲语言支持的测试。面对模棱两可的想法,拒绝猜测的诱惑。""", 8):
|
| 171 |
+
print(line)
|
| 172 |
+
for n in range(80, 1, -1):
|
| 173 |
+
print(set_cell_size("""这是对亚洲语言支持的测试。面对模棱两可的想法,拒绝猜测的诱惑。""", n) + "|")
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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import re
|
| 2 |
+
import sys
|
| 3 |
+
from colorsys import rgb_to_hls
|
| 4 |
+
from enum import IntEnum
|
| 5 |
+
from functools import lru_cache
|
| 6 |
+
from typing import TYPE_CHECKING, NamedTuple, Optional, Tuple
|
| 7 |
+
|
| 8 |
+
from ._palettes import EIGHT_BIT_PALETTE, STANDARD_PALETTE, WINDOWS_PALETTE
|
| 9 |
+
from .color_triplet import ColorTriplet
|
| 10 |
+
from .repr import Result, rich_repr
|
| 11 |
+
from .terminal_theme import DEFAULT_TERMINAL_THEME
|
| 12 |
+
|
| 13 |
+
if TYPE_CHECKING: # pragma: no cover
|
| 14 |
+
from .terminal_theme import TerminalTheme
|
| 15 |
+
from .text import Text
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
WINDOWS = sys.platform == "win32"
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class ColorSystem(IntEnum):
|
| 22 |
+
"""One of the 3 color system supported by terminals."""
|
| 23 |
+
|
| 24 |
+
STANDARD = 1
|
| 25 |
+
EIGHT_BIT = 2
|
| 26 |
+
TRUECOLOR = 3
|
| 27 |
+
WINDOWS = 4
|
| 28 |
+
|
| 29 |
+
def __repr__(self) -> str:
|
| 30 |
+
return f"ColorSystem.{self.name}"
|
| 31 |
+
|
| 32 |
+
def __str__(self) -> str:
|
| 33 |
+
return repr(self)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class ColorType(IntEnum):
|
| 37 |
+
"""Type of color stored in Color class."""
|
| 38 |
+
|
| 39 |
+
DEFAULT = 0
|
| 40 |
+
STANDARD = 1
|
| 41 |
+
EIGHT_BIT = 2
|
| 42 |
+
TRUECOLOR = 3
|
| 43 |
+
WINDOWS = 4
|
| 44 |
+
|
| 45 |
+
def __repr__(self) -> str:
|
| 46 |
+
return f"ColorType.{self.name}"
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
ANSI_COLOR_NAMES = {
|
| 50 |
+
"black": 0,
|
| 51 |
+
"red": 1,
|
| 52 |
+
"green": 2,
|
| 53 |
+
"yellow": 3,
|
| 54 |
+
"blue": 4,
|
| 55 |
+
"magenta": 5,
|
| 56 |
+
"cyan": 6,
|
| 57 |
+
"white": 7,
|
| 58 |
+
"bright_black": 8,
|
| 59 |
+
"bright_red": 9,
|
| 60 |
+
"bright_green": 10,
|
| 61 |
+
"bright_yellow": 11,
|
| 62 |
+
"bright_blue": 12,
|
| 63 |
+
"bright_magenta": 13,
|
| 64 |
+
"bright_cyan": 14,
|
| 65 |
+
"bright_white": 15,
|
| 66 |
+
"grey0": 16,
|
| 67 |
+
"gray0": 16,
|
| 68 |
+
"navy_blue": 17,
|
| 69 |
+
"dark_blue": 18,
|
| 70 |
+
"blue3": 20,
|
| 71 |
+
"blue1": 21,
|
| 72 |
+
"dark_green": 22,
|
| 73 |
+
"deep_sky_blue4": 25,
|
| 74 |
+
"dodger_blue3": 26,
|
| 75 |
+
"dodger_blue2": 27,
|
| 76 |
+
"green4": 28,
|
| 77 |
+
"spring_green4": 29,
|
| 78 |
+
"turquoise4": 30,
|
| 79 |
+
"deep_sky_blue3": 32,
|
| 80 |
+
"dodger_blue1": 33,
|
| 81 |
+
"green3": 40,
|
| 82 |
+
"spring_green3": 41,
|
| 83 |
+
"dark_cyan": 36,
|
| 84 |
+
"light_sea_green": 37,
|
| 85 |
+
"deep_sky_blue2": 38,
|
| 86 |
+
"deep_sky_blue1": 39,
|
| 87 |
+
"spring_green2": 47,
|
| 88 |
+
"cyan3": 43,
|
| 89 |
+
"dark_turquoise": 44,
|
| 90 |
+
"turquoise2": 45,
|
| 91 |
+
"green1": 46,
|
| 92 |
+
"spring_green1": 48,
|
| 93 |
+
"medium_spring_green": 49,
|
| 94 |
+
"cyan2": 50,
|
| 95 |
+
"cyan1": 51,
|
| 96 |
+
"dark_red": 88,
|
| 97 |
+
"deep_pink4": 125,
|
| 98 |
+
"purple4": 55,
|
| 99 |
+
"purple3": 56,
|
| 100 |
+
"blue_violet": 57,
|
| 101 |
+
"orange4": 94,
|
| 102 |
+
"grey37": 59,
|
| 103 |
+
"gray37": 59,
|
| 104 |
+
"medium_purple4": 60,
|
| 105 |
+
"slate_blue3": 62,
|
| 106 |
+
"royal_blue1": 63,
|
| 107 |
+
"chartreuse4": 64,
|
| 108 |
+
"dark_sea_green4": 71,
|
| 109 |
+
"pale_turquoise4": 66,
|
| 110 |
+
"steel_blue": 67,
|
| 111 |
+
"steel_blue3": 68,
|
| 112 |
+
"cornflower_blue": 69,
|
| 113 |
+
"chartreuse3": 76,
|
| 114 |
+
"cadet_blue": 73,
|
| 115 |
+
"sky_blue3": 74,
|
| 116 |
+
"steel_blue1": 81,
|
| 117 |
+
"pale_green3": 114,
|
| 118 |
+
"sea_green3": 78,
|
| 119 |
+
"aquamarine3": 79,
|
| 120 |
+
"medium_turquoise": 80,
|
| 121 |
+
"chartreuse2": 112,
|
| 122 |
+
"sea_green2": 83,
|
| 123 |
+
"sea_green1": 85,
|
| 124 |
+
"aquamarine1": 122,
|
| 125 |
+
"dark_slate_gray2": 87,
|
| 126 |
+
"dark_magenta": 91,
|
| 127 |
+
"dark_violet": 128,
|
| 128 |
+
"purple": 129,
|
| 129 |
+
"light_pink4": 95,
|
| 130 |
+
"plum4": 96,
|
| 131 |
+
"medium_purple3": 98,
|
| 132 |
+
"slate_blue1": 99,
|
| 133 |
+
"yellow4": 106,
|
| 134 |
+
"wheat4": 101,
|
| 135 |
+
"grey53": 102,
|
| 136 |
+
"gray53": 102,
|
| 137 |
+
"light_slate_grey": 103,
|
| 138 |
+
"light_slate_gray": 103,
|
| 139 |
+
"medium_purple": 104,
|
| 140 |
+
"light_slate_blue": 105,
|
| 141 |
+
"dark_olive_green3": 149,
|
| 142 |
+
"dark_sea_green": 108,
|
| 143 |
+
"light_sky_blue3": 110,
|
| 144 |
+
"sky_blue2": 111,
|
| 145 |
+
"dark_sea_green3": 150,
|
| 146 |
+
"dark_slate_gray3": 116,
|
| 147 |
+
"sky_blue1": 117,
|
| 148 |
+
"chartreuse1": 118,
|
| 149 |
+
"light_green": 120,
|
| 150 |
+
"pale_green1": 156,
|
| 151 |
+
"dark_slate_gray1": 123,
|
| 152 |
+
"red3": 160,
|
| 153 |
+
"medium_violet_red": 126,
|
| 154 |
+
"magenta3": 164,
|
| 155 |
+
"dark_orange3": 166,
|
| 156 |
+
"indian_red": 167,
|
| 157 |
+
"hot_pink3": 168,
|
| 158 |
+
"medium_orchid3": 133,
|
| 159 |
+
"medium_orchid": 134,
|
| 160 |
+
"medium_purple2": 140,
|
| 161 |
+
"dark_goldenrod": 136,
|
| 162 |
+
"light_salmon3": 173,
|
| 163 |
+
"rosy_brown": 138,
|
| 164 |
+
"grey63": 139,
|
| 165 |
+
"gray63": 139,
|
| 166 |
+
"medium_purple1": 141,
|
| 167 |
+
"gold3": 178,
|
| 168 |
+
"dark_khaki": 143,
|
| 169 |
+
"navajo_white3": 144,
|
| 170 |
+
"grey69": 145,
|
| 171 |
+
"gray69": 145,
|
| 172 |
+
"light_steel_blue3": 146,
|
| 173 |
+
"light_steel_blue": 147,
|
| 174 |
+
"yellow3": 184,
|
| 175 |
+
"dark_sea_green2": 157,
|
| 176 |
+
"light_cyan3": 152,
|
| 177 |
+
"light_sky_blue1": 153,
|
| 178 |
+
"green_yellow": 154,
|
| 179 |
+
"dark_olive_green2": 155,
|
| 180 |
+
"dark_sea_green1": 193,
|
| 181 |
+
"pale_turquoise1": 159,
|
| 182 |
+
"deep_pink3": 162,
|
| 183 |
+
"magenta2": 200,
|
| 184 |
+
"hot_pink2": 169,
|
| 185 |
+
"orchid": 170,
|
| 186 |
+
"medium_orchid1": 207,
|
| 187 |
+
"orange3": 172,
|
| 188 |
+
"light_pink3": 174,
|
| 189 |
+
"pink3": 175,
|
| 190 |
+
"plum3": 176,
|
| 191 |
+
"violet": 177,
|
| 192 |
+
"light_goldenrod3": 179,
|
| 193 |
+
"tan": 180,
|
| 194 |
+
"misty_rose3": 181,
|
| 195 |
+
"thistle3": 182,
|
| 196 |
+
"plum2": 183,
|
| 197 |
+
"khaki3": 185,
|
| 198 |
+
"light_goldenrod2": 222,
|
| 199 |
+
"light_yellow3": 187,
|
| 200 |
+
"grey84": 188,
|
| 201 |
+
"gray84": 188,
|
| 202 |
+
"light_steel_blue1": 189,
|
| 203 |
+
"yellow2": 190,
|
| 204 |
+
"dark_olive_green1": 192,
|
| 205 |
+
"honeydew2": 194,
|
| 206 |
+
"light_cyan1": 195,
|
| 207 |
+
"red1": 196,
|
| 208 |
+
"deep_pink2": 197,
|
| 209 |
+
"deep_pink1": 199,
|
| 210 |
+
"magenta1": 201,
|
| 211 |
+
"orange_red1": 202,
|
| 212 |
+
"indian_red1": 204,
|
| 213 |
+
"hot_pink": 206,
|
| 214 |
+
"dark_orange": 208,
|
| 215 |
+
"salmon1": 209,
|
| 216 |
+
"light_coral": 210,
|
| 217 |
+
"pale_violet_red1": 211,
|
| 218 |
+
"orchid2": 212,
|
| 219 |
+
"orchid1": 213,
|
| 220 |
+
"orange1": 214,
|
| 221 |
+
"sandy_brown": 215,
|
| 222 |
+
"light_salmon1": 216,
|
| 223 |
+
"light_pink1": 217,
|
| 224 |
+
"pink1": 218,
|
| 225 |
+
"plum1": 219,
|
| 226 |
+
"gold1": 220,
|
| 227 |
+
"navajo_white1": 223,
|
| 228 |
+
"misty_rose1": 224,
|
| 229 |
+
"thistle1": 225,
|
| 230 |
+
"yellow1": 226,
|
| 231 |
+
"light_goldenrod1": 227,
|
| 232 |
+
"khaki1": 228,
|
| 233 |
+
"wheat1": 229,
|
| 234 |
+
"cornsilk1": 230,
|
| 235 |
+
"grey100": 231,
|
| 236 |
+
"gray100": 231,
|
| 237 |
+
"grey3": 232,
|
| 238 |
+
"gray3": 232,
|
| 239 |
+
"grey7": 233,
|
| 240 |
+
"gray7": 233,
|
| 241 |
+
"grey11": 234,
|
| 242 |
+
"gray11": 234,
|
| 243 |
+
"grey15": 235,
|
| 244 |
+
"gray15": 235,
|
| 245 |
+
"grey19": 236,
|
| 246 |
+
"gray19": 236,
|
| 247 |
+
"grey23": 237,
|
| 248 |
+
"gray23": 237,
|
| 249 |
+
"grey27": 238,
|
| 250 |
+
"gray27": 238,
|
| 251 |
+
"grey30": 239,
|
| 252 |
+
"gray30": 239,
|
| 253 |
+
"grey35": 240,
|
| 254 |
+
"gray35": 240,
|
| 255 |
+
"grey39": 241,
|
| 256 |
+
"gray39": 241,
|
| 257 |
+
"grey42": 242,
|
| 258 |
+
"gray42": 242,
|
| 259 |
+
"grey46": 243,
|
| 260 |
+
"gray46": 243,
|
| 261 |
+
"grey50": 244,
|
| 262 |
+
"gray50": 244,
|
| 263 |
+
"grey54": 245,
|
| 264 |
+
"gray54": 245,
|
| 265 |
+
"grey58": 246,
|
| 266 |
+
"gray58": 246,
|
| 267 |
+
"grey62": 247,
|
| 268 |
+
"gray62": 247,
|
| 269 |
+
"grey66": 248,
|
| 270 |
+
"gray66": 248,
|
| 271 |
+
"grey70": 249,
|
| 272 |
+
"gray70": 249,
|
| 273 |
+
"grey74": 250,
|
| 274 |
+
"gray74": 250,
|
| 275 |
+
"grey78": 251,
|
| 276 |
+
"gray78": 251,
|
| 277 |
+
"grey82": 252,
|
| 278 |
+
"gray82": 252,
|
| 279 |
+
"grey85": 253,
|
| 280 |
+
"gray85": 253,
|
| 281 |
+
"grey89": 254,
|
| 282 |
+
"gray89": 254,
|
| 283 |
+
"grey93": 255,
|
| 284 |
+
"gray93": 255,
|
| 285 |
+
}
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
class ColorParseError(Exception):
|
| 289 |
+
"""The color could not be parsed."""
|
| 290 |
+
|
| 291 |
+
|
| 292 |
+
RE_COLOR = re.compile(
|
| 293 |
+
r"""^
|
| 294 |
+
\#([0-9a-f]{6})$|
|
| 295 |
+
color\(([0-9]{1,3})\)$|
|
| 296 |
+
rgb\(([\d\s,]+)\)$
|
| 297 |
+
""",
|
| 298 |
+
re.VERBOSE,
|
| 299 |
+
)
|
| 300 |
+
|
| 301 |
+
|
| 302 |
+
@rich_repr
|
| 303 |
+
class Color(NamedTuple):
|
| 304 |
+
"""Terminal color definition."""
|
| 305 |
+
|
| 306 |
+
name: str
|
| 307 |
+
"""The name of the color (typically the input to Color.parse)."""
|
| 308 |
+
type: ColorType
|
| 309 |
+
"""The type of the color."""
|
| 310 |
+
number: Optional[int] = None
|
| 311 |
+
"""The color number, if a standard color, or None."""
|
| 312 |
+
triplet: Optional[ColorTriplet] = None
|
| 313 |
+
"""A triplet of color components, if an RGB color."""
|
| 314 |
+
|
| 315 |
+
def __rich__(self) -> "Text":
|
| 316 |
+
"""Displays the actual color if Rich printed."""
|
| 317 |
+
from .style import Style
|
| 318 |
+
from .text import Text
|
| 319 |
+
|
| 320 |
+
return Text.assemble(
|
| 321 |
+
f"<color {self.name!r} ({self.type.name.lower()})",
|
| 322 |
+
("⬤", Style(color=self)),
|
| 323 |
+
" >",
|
| 324 |
+
)
|
| 325 |
+
|
| 326 |
+
def __rich_repr__(self) -> Result:
|
| 327 |
+
yield self.name
|
| 328 |
+
yield self.type
|
| 329 |
+
yield "number", self.number, None
|
| 330 |
+
yield "triplet", self.triplet, None
|
| 331 |
+
|
| 332 |
+
@property
|
| 333 |
+
def system(self) -> ColorSystem:
|
| 334 |
+
"""Get the native color system for this color."""
|
| 335 |
+
if self.type == ColorType.DEFAULT:
|
| 336 |
+
return ColorSystem.STANDARD
|
| 337 |
+
return ColorSystem(int(self.type))
|
| 338 |
+
|
| 339 |
+
@property
|
| 340 |
+
def is_system_defined(self) -> bool:
|
| 341 |
+
"""Check if the color is ultimately defined by the system."""
|
| 342 |
+
return self.system not in (ColorSystem.EIGHT_BIT, ColorSystem.TRUECOLOR)
|
| 343 |
+
|
| 344 |
+
@property
|
| 345 |
+
def is_default(self) -> bool:
|
| 346 |
+
"""Check if the color is a default color."""
|
| 347 |
+
return self.type == ColorType.DEFAULT
|
| 348 |
+
|
| 349 |
+
def get_truecolor(
|
| 350 |
+
self, theme: Optional["TerminalTheme"] = None, foreground: bool = True
|
| 351 |
+
) -> ColorTriplet:
|
| 352 |
+
"""Get an equivalent color triplet for this color.
|
| 353 |
+
|
| 354 |
+
Args:
|
| 355 |
+
theme (TerminalTheme, optional): Optional terminal theme, or None to use default. Defaults to None.
|
| 356 |
+
foreground (bool, optional): True for a foreground color, or False for background. Defaults to True.
|
| 357 |
+
|
| 358 |
+
Returns:
|
| 359 |
+
ColorTriplet: A color triplet containing RGB components.
|
| 360 |
+
"""
|
| 361 |
+
|
| 362 |
+
if theme is None:
|
| 363 |
+
theme = DEFAULT_TERMINAL_THEME
|
| 364 |
+
if self.type == ColorType.TRUECOLOR:
|
| 365 |
+
assert self.triplet is not None
|
| 366 |
+
return self.triplet
|
| 367 |
+
elif self.type == ColorType.EIGHT_BIT:
|
| 368 |
+
assert self.number is not None
|
| 369 |
+
return EIGHT_BIT_PALETTE[self.number]
|
| 370 |
+
elif self.type == ColorType.STANDARD:
|
| 371 |
+
assert self.number is not None
|
| 372 |
+
return theme.ansi_colors[self.number]
|
| 373 |
+
elif self.type == ColorType.WINDOWS:
|
| 374 |
+
assert self.number is not None
|
| 375 |
+
return WINDOWS_PALETTE[self.number]
|
| 376 |
+
else: # self.type == ColorType.DEFAULT:
|
| 377 |
+
assert self.number is None
|
| 378 |
+
return theme.foreground_color if foreground else theme.background_color
|
| 379 |
+
|
| 380 |
+
@classmethod
|
| 381 |
+
def from_ansi(cls, number: int) -> "Color":
|
| 382 |
+
"""Create a Color number from it's 8-bit ansi number.
|
| 383 |
+
|
| 384 |
+
Args:
|
| 385 |
+
number (int): A number between 0-255 inclusive.
|
| 386 |
+
|
| 387 |
+
Returns:
|
| 388 |
+
Color: A new Color instance.
|
| 389 |
+
"""
|
| 390 |
+
return cls(
|
| 391 |
+
name=f"color({number})",
|
| 392 |
+
type=(ColorType.STANDARD if number < 16 else ColorType.EIGHT_BIT),
|
| 393 |
+
number=number,
|
| 394 |
+
)
|
| 395 |
+
|
| 396 |
+
@classmethod
|
| 397 |
+
def from_triplet(cls, triplet: "ColorTriplet") -> "Color":
|
| 398 |
+
"""Create a truecolor RGB color from a triplet of values.
|
| 399 |
+
|
| 400 |
+
Args:
|
| 401 |
+
triplet (ColorTriplet): A color triplet containing red, green and blue components.
|
| 402 |
+
|
| 403 |
+
Returns:
|
| 404 |
+
Color: A new color object.
|
| 405 |
+
"""
|
| 406 |
+
return cls(name=triplet.hex, type=ColorType.TRUECOLOR, triplet=triplet)
|
| 407 |
+
|
| 408 |
+
@classmethod
|
| 409 |
+
def from_rgb(cls, red: float, green: float, blue: float) -> "Color":
|
| 410 |
+
"""Create a truecolor from three color components in the range(0->255).
|
| 411 |
+
|
| 412 |
+
Args:
|
| 413 |
+
red (float): Red component in range 0-255.
|
| 414 |
+
green (float): Green component in range 0-255.
|
| 415 |
+
blue (float): Blue component in range 0-255.
|
| 416 |
+
|
| 417 |
+
Returns:
|
| 418 |
+
Color: A new color object.
|
| 419 |
+
"""
|
| 420 |
+
return cls.from_triplet(ColorTriplet(int(red), int(green), int(blue)))
|
| 421 |
+
|
| 422 |
+
@classmethod
|
| 423 |
+
def default(cls) -> "Color":
|
| 424 |
+
"""Get a Color instance representing the default color.
|
| 425 |
+
|
| 426 |
+
Returns:
|
| 427 |
+
Color: Default color.
|
| 428 |
+
"""
|
| 429 |
+
return cls(name="default", type=ColorType.DEFAULT)
|
| 430 |
+
|
| 431 |
+
@classmethod
|
| 432 |
+
@lru_cache(maxsize=1024)
|
| 433 |
+
def parse(cls, color: str) -> "Color":
|
| 434 |
+
"""Parse a color definition."""
|
| 435 |
+
original_color = color
|
| 436 |
+
color = color.lower().strip()
|
| 437 |
+
|
| 438 |
+
if color == "default":
|
| 439 |
+
return cls(color, type=ColorType.DEFAULT)
|
| 440 |
+
|
| 441 |
+
color_number = ANSI_COLOR_NAMES.get(color)
|
| 442 |
+
if color_number is not None:
|
| 443 |
+
return cls(
|
| 444 |
+
color,
|
| 445 |
+
type=(ColorType.STANDARD if color_number < 16 else ColorType.EIGHT_BIT),
|
| 446 |
+
number=color_number,
|
| 447 |
+
)
|
| 448 |
+
|
| 449 |
+
color_match = RE_COLOR.match(color)
|
| 450 |
+
if color_match is None:
|
| 451 |
+
raise ColorParseError(f"{original_color!r} is not a valid color")
|
| 452 |
+
|
| 453 |
+
color_24, color_8, color_rgb = color_match.groups()
|
| 454 |
+
if color_24:
|
| 455 |
+
triplet = ColorTriplet(
|
| 456 |
+
int(color_24[0:2], 16), int(color_24[2:4], 16), int(color_24[4:6], 16)
|
| 457 |
+
)
|
| 458 |
+
return cls(color, ColorType.TRUECOLOR, triplet=triplet)
|
| 459 |
+
|
| 460 |
+
elif color_8:
|
| 461 |
+
number = int(color_8)
|
| 462 |
+
if number > 255:
|
| 463 |
+
raise ColorParseError(f"color number must be <= 255 in {color!r}")
|
| 464 |
+
return cls(
|
| 465 |
+
color,
|
| 466 |
+
type=(ColorType.STANDARD if number < 16 else ColorType.EIGHT_BIT),
|
| 467 |
+
number=number,
|
| 468 |
+
)
|
| 469 |
+
|
| 470 |
+
else: # color_rgb:
|
| 471 |
+
components = color_rgb.split(",")
|
| 472 |
+
if len(components) != 3:
|
| 473 |
+
raise ColorParseError(
|
| 474 |
+
f"expected three components in {original_color!r}"
|
| 475 |
+
)
|
| 476 |
+
red, green, blue = components
|
| 477 |
+
triplet = ColorTriplet(int(red), int(green), int(blue))
|
| 478 |
+
if not all(component <= 255 for component in triplet):
|
| 479 |
+
raise ColorParseError(
|
| 480 |
+
f"color components must be <= 255 in {original_color!r}"
|
| 481 |
+
)
|
| 482 |
+
return cls(color, ColorType.TRUECOLOR, triplet=triplet)
|
| 483 |
+
|
| 484 |
+
@lru_cache(maxsize=1024)
|
| 485 |
+
def get_ansi_codes(self, foreground: bool = True) -> Tuple[str, ...]:
|
| 486 |
+
"""Get the ANSI escape codes for this color."""
|
| 487 |
+
_type = self.type
|
| 488 |
+
if _type == ColorType.DEFAULT:
|
| 489 |
+
return ("39" if foreground else "49",)
|
| 490 |
+
|
| 491 |
+
elif _type == ColorType.WINDOWS:
|
| 492 |
+
number = self.number
|
| 493 |
+
assert number is not None
|
| 494 |
+
fore, back = (30, 40) if number < 8 else (82, 92)
|
| 495 |
+
return (str(fore + number if foreground else back + number),)
|
| 496 |
+
|
| 497 |
+
elif _type == ColorType.STANDARD:
|
| 498 |
+
number = self.number
|
| 499 |
+
assert number is not None
|
| 500 |
+
fore, back = (30, 40) if number < 8 else (82, 92)
|
| 501 |
+
return (str(fore + number if foreground else back + number),)
|
| 502 |
+
|
| 503 |
+
elif _type == ColorType.EIGHT_BIT:
|
| 504 |
+
assert self.number is not None
|
| 505 |
+
return ("38" if foreground else "48", "5", str(self.number))
|
| 506 |
+
|
| 507 |
+
else: # self.standard == ColorStandard.TRUECOLOR:
|
| 508 |
+
assert self.triplet is not None
|
| 509 |
+
red, green, blue = self.triplet
|
| 510 |
+
return ("38" if foreground else "48", "2", str(red), str(green), str(blue))
|
| 511 |
+
|
| 512 |
+
@lru_cache(maxsize=1024)
|
| 513 |
+
def downgrade(self, system: ColorSystem) -> "Color":
|
| 514 |
+
"""Downgrade a color system to a system with fewer colors."""
|
| 515 |
+
|
| 516 |
+
if self.type in (ColorType.DEFAULT, system):
|
| 517 |
+
return self
|
| 518 |
+
# Convert to 8-bit color from truecolor color
|
| 519 |
+
if system == ColorSystem.EIGHT_BIT and self.system == ColorSystem.TRUECOLOR:
|
| 520 |
+
assert self.triplet is not None
|
| 521 |
+
_h, l, s = rgb_to_hls(*self.triplet.normalized)
|
| 522 |
+
# If saturation is under 15% assume it is grayscale
|
| 523 |
+
if s < 0.15:
|
| 524 |
+
gray = round(l * 25.0)
|
| 525 |
+
if gray == 0:
|
| 526 |
+
color_number = 16
|
| 527 |
+
elif gray == 25:
|
| 528 |
+
color_number = 231
|
| 529 |
+
else:
|
| 530 |
+
color_number = 231 + gray
|
| 531 |
+
return Color(self.name, ColorType.EIGHT_BIT, number=color_number)
|
| 532 |
+
|
| 533 |
+
red, green, blue = self.triplet
|
| 534 |
+
six_red = red / 95 if red < 95 else 1 + (red - 95) / 40
|
| 535 |
+
six_green = green / 95 if green < 95 else 1 + (green - 95) / 40
|
| 536 |
+
six_blue = blue / 95 if blue < 95 else 1 + (blue - 95) / 40
|
| 537 |
+
|
| 538 |
+
color_number = (
|
| 539 |
+
16 + 36 * round(six_red) + 6 * round(six_green) + round(six_blue)
|
| 540 |
+
)
|
| 541 |
+
return Color(self.name, ColorType.EIGHT_BIT, number=color_number)
|
| 542 |
+
|
| 543 |
+
# Convert to standard from truecolor or 8-bit
|
| 544 |
+
elif system == ColorSystem.STANDARD:
|
| 545 |
+
if self.system == ColorSystem.TRUECOLOR:
|
| 546 |
+
assert self.triplet is not None
|
| 547 |
+
triplet = self.triplet
|
| 548 |
+
else: # self.system == ColorSystem.EIGHT_BIT
|
| 549 |
+
assert self.number is not None
|
| 550 |
+
triplet = ColorTriplet(*EIGHT_BIT_PALETTE[self.number])
|
| 551 |
+
|
| 552 |
+
color_number = STANDARD_PALETTE.match(triplet)
|
| 553 |
+
return Color(self.name, ColorType.STANDARD, number=color_number)
|
| 554 |
+
|
| 555 |
+
elif system == ColorSystem.WINDOWS:
|
| 556 |
+
if self.system == ColorSystem.TRUECOLOR:
|
| 557 |
+
assert self.triplet is not None
|
| 558 |
+
triplet = self.triplet
|
| 559 |
+
else: # self.system == ColorSystem.EIGHT_BIT
|
| 560 |
+
assert self.number is not None
|
| 561 |
+
if self.number < 16:
|
| 562 |
+
return Color(self.name, ColorType.WINDOWS, number=self.number)
|
| 563 |
+
triplet = ColorTriplet(*EIGHT_BIT_PALETTE[self.number])
|
| 564 |
+
|
| 565 |
+
color_number = WINDOWS_PALETTE.match(triplet)
|
| 566 |
+
return Color(self.name, ColorType.WINDOWS, number=color_number)
|
| 567 |
+
|
| 568 |
+
return self
|
| 569 |
+
|
| 570 |
+
|
| 571 |
+
def parse_rgb_hex(hex_color: str) -> ColorTriplet:
|
| 572 |
+
"""Parse six hex characters in to RGB triplet."""
|
| 573 |
+
assert len(hex_color) == 6, "must be 6 characters"
|
| 574 |
+
color = ColorTriplet(
|
| 575 |
+
int(hex_color[0:2], 16), int(hex_color[2:4], 16), int(hex_color[4:6], 16)
|
| 576 |
+
)
|
| 577 |
+
return color
|
| 578 |
+
|
| 579 |
+
|
| 580 |
+
def blend_rgb(
|
| 581 |
+
color1: ColorTriplet, color2: ColorTriplet, cross_fade: float = 0.5
|
| 582 |
+
) -> ColorTriplet:
|
| 583 |
+
"""Blend one RGB color in to another."""
|
| 584 |
+
r1, g1, b1 = color1
|
| 585 |
+
r2, g2, b2 = color2
|
| 586 |
+
new_color = ColorTriplet(
|
| 587 |
+
int(r1 + (r2 - r1) * cross_fade),
|
| 588 |
+
int(g1 + (g2 - g1) * cross_fade),
|
| 589 |
+
int(b1 + (b2 - b1) * cross_fade),
|
| 590 |
+
)
|
| 591 |
+
return new_color
|
| 592 |
+
|
| 593 |
+
|
| 594 |
+
if __name__ == "__main__": # pragma: no cover
|
| 595 |
+
from .console import Console
|
| 596 |
+
from .table import Table
|
| 597 |
+
from .text import Text
|
| 598 |
+
|
| 599 |
+
console = Console()
|
| 600 |
+
|
| 601 |
+
table = Table(show_footer=False, show_edge=True)
|
| 602 |
+
table.add_column("Color", width=10, overflow="ellipsis")
|
| 603 |
+
table.add_column("Number", justify="right", style="yellow")
|
| 604 |
+
table.add_column("Name", style="green")
|
| 605 |
+
table.add_column("Hex", style="blue")
|
| 606 |
+
table.add_column("RGB", style="magenta")
|
| 607 |
+
|
| 608 |
+
colors = sorted((v, k) for k, v in ANSI_COLOR_NAMES.items())
|
| 609 |
+
for color_number, name in colors:
|
| 610 |
+
if "grey" in name:
|
| 611 |
+
continue
|
| 612 |
+
color_cell = Text(" " * 10, style=f"on {name}")
|
| 613 |
+
if color_number < 16:
|
| 614 |
+
table.add_row(color_cell, f"{color_number}", Text(f'"{name}"'))
|
| 615 |
+
else:
|
| 616 |
+
color = EIGHT_BIT_PALETTE[color_number] # type: ignore[has-type]
|
| 617 |
+
table.add_row(
|
| 618 |
+
color_cell, str(color_number), Text(f'"{name}"'), color.hex, color.rgb
|
| 619 |
+
)
|
| 620 |
+
|
| 621 |
+
console.print(table)
|
miniconda3/lib/python3.13/site-packages/rich/color_triplet.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import NamedTuple, Tuple
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
class ColorTriplet(NamedTuple):
|
| 5 |
+
"""The red, green, and blue components of a color."""
|
| 6 |
+
|
| 7 |
+
red: int
|
| 8 |
+
"""Red component in 0 to 255 range."""
|
| 9 |
+
green: int
|
| 10 |
+
"""Green component in 0 to 255 range."""
|
| 11 |
+
blue: int
|
| 12 |
+
"""Blue component in 0 to 255 range."""
|
| 13 |
+
|
| 14 |
+
@property
|
| 15 |
+
def hex(self) -> str:
|
| 16 |
+
"""get the color triplet in CSS style."""
|
| 17 |
+
red, green, blue = self
|
| 18 |
+
return f"#{red:02x}{green:02x}{blue:02x}"
|
| 19 |
+
|
| 20 |
+
@property
|
| 21 |
+
def rgb(self) -> str:
|
| 22 |
+
"""The color in RGB format.
|
| 23 |
+
|
| 24 |
+
Returns:
|
| 25 |
+
str: An rgb color, e.g. ``"rgb(100,23,255)"``.
|
| 26 |
+
"""
|
| 27 |
+
red, green, blue = self
|
| 28 |
+
return f"rgb({red},{green},{blue})"
|
| 29 |
+
|
| 30 |
+
@property
|
| 31 |
+
def normalized(self) -> Tuple[float, float, float]:
|
| 32 |
+
"""Convert components into floats between 0 and 1.
|
| 33 |
+
|
| 34 |
+
Returns:
|
| 35 |
+
Tuple[float, float, float]: A tuple of three normalized colour components.
|
| 36 |
+
"""
|
| 37 |
+
red, green, blue = self
|
| 38 |
+
return red / 255.0, green / 255.0, blue / 255.0
|
miniconda3/lib/python3.13/site-packages/rich/columns.py
ADDED
|
@@ -0,0 +1,187 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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import itemgetter
|
| 4 |
+
from typing import Dict, Iterable, List, Optional, Tuple
|
| 5 |
+
|
| 6 |
+
from .align import Align, AlignMethod
|
| 7 |
+
from .console import Console, ConsoleOptions, RenderableType, RenderResult
|
| 8 |
+
from .constrain import Constrain
|
| 9 |
+
from .measure import Measurement
|
| 10 |
+
from .padding import Padding, PaddingDimensions
|
| 11 |
+
from .table import Table
|
| 12 |
+
from .text import TextType
|
| 13 |
+
from .jupyter import JupyterMixin
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class Columns(JupyterMixin):
|
| 17 |
+
"""Display renderables in neat columns.
|
| 18 |
+
|
| 19 |
+
Args:
|
| 20 |
+
renderables (Iterable[RenderableType]): Any number of Rich renderables (including str).
|
| 21 |
+
width (int, optional): The desired width of the columns, or None to auto detect. Defaults to None.
|
| 22 |
+
padding (PaddingDimensions, optional): Optional padding around cells. Defaults to (0, 1).
|
| 23 |
+
expand (bool, optional): Expand columns to full width. Defaults to False.
|
| 24 |
+
equal (bool, optional): Arrange in to equal sized columns. Defaults to False.
|
| 25 |
+
column_first (bool, optional): Align items from top to bottom (rather than left to right). Defaults to False.
|
| 26 |
+
right_to_left (bool, optional): Start column from right hand side. Defaults to False.
|
| 27 |
+
align (str, optional): Align value ("left", "right", or "center") or None for default. Defaults to None.
|
| 28 |
+
title (TextType, optional): Optional title for Columns.
|
| 29 |
+
"""
|
| 30 |
+
|
| 31 |
+
def __init__(
|
| 32 |
+
self,
|
| 33 |
+
renderables: Optional[Iterable[RenderableType]] = None,
|
| 34 |
+
padding: PaddingDimensions = (0, 1),
|
| 35 |
+
*,
|
| 36 |
+
width: Optional[int] = None,
|
| 37 |
+
expand: bool = False,
|
| 38 |
+
equal: bool = False,
|
| 39 |
+
column_first: bool = False,
|
| 40 |
+
right_to_left: bool = False,
|
| 41 |
+
align: Optional[AlignMethod] = None,
|
| 42 |
+
title: Optional[TextType] = None,
|
| 43 |
+
) -> None:
|
| 44 |
+
self.renderables = list(renderables or [])
|
| 45 |
+
self.width = width
|
| 46 |
+
self.padding = padding
|
| 47 |
+
self.expand = expand
|
| 48 |
+
self.equal = equal
|
| 49 |
+
self.column_first = column_first
|
| 50 |
+
self.right_to_left = right_to_left
|
| 51 |
+
self.align: Optional[AlignMethod] = align
|
| 52 |
+
self.title = title
|
| 53 |
+
|
| 54 |
+
def add_renderable(self, renderable: RenderableType) -> None:
|
| 55 |
+
"""Add a renderable to the columns.
|
| 56 |
+
|
| 57 |
+
Args:
|
| 58 |
+
renderable (RenderableType): Any renderable object.
|
| 59 |
+
"""
|
| 60 |
+
self.renderables.append(renderable)
|
| 61 |
+
|
| 62 |
+
def __rich_console__(
|
| 63 |
+
self, console: Console, options: ConsoleOptions
|
| 64 |
+
) -> RenderResult:
|
| 65 |
+
render_str = console.render_str
|
| 66 |
+
renderables = [
|
| 67 |
+
render_str(renderable) if isinstance(renderable, str) else renderable
|
| 68 |
+
for renderable in self.renderables
|
| 69 |
+
]
|
| 70 |
+
if not renderables:
|
| 71 |
+
return
|
| 72 |
+
_top, right, _bottom, left = Padding.unpack(self.padding)
|
| 73 |
+
width_padding = max(left, right)
|
| 74 |
+
max_width = options.max_width
|
| 75 |
+
widths: Dict[int, int] = defaultdict(int)
|
| 76 |
+
column_count = len(renderables)
|
| 77 |
+
|
| 78 |
+
get_measurement = Measurement.get
|
| 79 |
+
renderable_widths = [
|
| 80 |
+
get_measurement(console, options, renderable).maximum
|
| 81 |
+
for renderable in renderables
|
| 82 |
+
]
|
| 83 |
+
if self.equal:
|
| 84 |
+
renderable_widths = [max(renderable_widths)] * len(renderable_widths)
|
| 85 |
+
|
| 86 |
+
def iter_renderables(
|
| 87 |
+
column_count: int,
|
| 88 |
+
) -> Iterable[Tuple[int, Optional[RenderableType]]]:
|
| 89 |
+
item_count = len(renderables)
|
| 90 |
+
if self.column_first:
|
| 91 |
+
width_renderables = list(zip(renderable_widths, renderables))
|
| 92 |
+
|
| 93 |
+
column_lengths: List[int] = [item_count // column_count] * column_count
|
| 94 |
+
for col_no in range(item_count % column_count):
|
| 95 |
+
column_lengths[col_no] += 1
|
| 96 |
+
|
| 97 |
+
row_count = (item_count + column_count - 1) // column_count
|
| 98 |
+
cells = [[-1] * column_count for _ in range(row_count)]
|
| 99 |
+
row = col = 0
|
| 100 |
+
for index in range(item_count):
|
| 101 |
+
cells[row][col] = index
|
| 102 |
+
column_lengths[col] -= 1
|
| 103 |
+
if column_lengths[col]:
|
| 104 |
+
row += 1
|
| 105 |
+
else:
|
| 106 |
+
col += 1
|
| 107 |
+
row = 0
|
| 108 |
+
for index in chain.from_iterable(cells):
|
| 109 |
+
if index == -1:
|
| 110 |
+
break
|
| 111 |
+
yield width_renderables[index]
|
| 112 |
+
else:
|
| 113 |
+
yield from zip(renderable_widths, renderables)
|
| 114 |
+
# Pad odd elements with spaces
|
| 115 |
+
if item_count % column_count:
|
| 116 |
+
for _ in range(column_count - (item_count % column_count)):
|
| 117 |
+
yield 0, None
|
| 118 |
+
|
| 119 |
+
table = Table.grid(padding=self.padding, collapse_padding=True, pad_edge=False)
|
| 120 |
+
table.expand = self.expand
|
| 121 |
+
table.title = self.title
|
| 122 |
+
|
| 123 |
+
if self.width is not None:
|
| 124 |
+
column_count = (max_width) // (self.width + width_padding)
|
| 125 |
+
for _ in range(column_count):
|
| 126 |
+
table.add_column(width=self.width)
|
| 127 |
+
else:
|
| 128 |
+
while column_count > 1:
|
| 129 |
+
widths.clear()
|
| 130 |
+
column_no = 0
|
| 131 |
+
for renderable_width, _ in iter_renderables(column_count):
|
| 132 |
+
widths[column_no] = max(widths[column_no], renderable_width)
|
| 133 |
+
total_width = sum(widths.values()) + width_padding * (
|
| 134 |
+
len(widths) - 1
|
| 135 |
+
)
|
| 136 |
+
if total_width > max_width:
|
| 137 |
+
column_count = len(widths) - 1
|
| 138 |
+
break
|
| 139 |
+
else:
|
| 140 |
+
column_no = (column_no + 1) % column_count
|
| 141 |
+
else:
|
| 142 |
+
break
|
| 143 |
+
|
| 144 |
+
get_renderable = itemgetter(1)
|
| 145 |
+
_renderables = [
|
| 146 |
+
get_renderable(_renderable)
|
| 147 |
+
for _renderable in iter_renderables(column_count)
|
| 148 |
+
]
|
| 149 |
+
if self.equal:
|
| 150 |
+
_renderables = [
|
| 151 |
+
None
|
| 152 |
+
if renderable is None
|
| 153 |
+
else Constrain(renderable, renderable_widths[0])
|
| 154 |
+
for renderable in _renderables
|
| 155 |
+
]
|
| 156 |
+
if self.align:
|
| 157 |
+
align = self.align
|
| 158 |
+
_Align = Align
|
| 159 |
+
_renderables = [
|
| 160 |
+
None if renderable is None else _Align(renderable, align)
|
| 161 |
+
for renderable in _renderables
|
| 162 |
+
]
|
| 163 |
+
|
| 164 |
+
right_to_left = self.right_to_left
|
| 165 |
+
add_row = table.add_row
|
| 166 |
+
for start in range(0, len(_renderables), column_count):
|
| 167 |
+
row = _renderables[start : start + column_count]
|
| 168 |
+
if right_to_left:
|
| 169 |
+
row = row[::-1]
|
| 170 |
+
add_row(*row)
|
| 171 |
+
yield table
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
if __name__ == "__main__": # pragma: no cover
|
| 175 |
+
import os
|
| 176 |
+
|
| 177 |
+
console = Console()
|
| 178 |
+
|
| 179 |
+
files = [f"{i} {s}" for i, s in enumerate(sorted(os.listdir()))]
|
| 180 |
+
columns = Columns(files, padding=(0, 1), expand=False, equal=False)
|
| 181 |
+
console.print(columns)
|
| 182 |
+
console.rule()
|
| 183 |
+
columns.column_first = True
|
| 184 |
+
console.print(columns)
|
| 185 |
+
columns.right_to_left = True
|
| 186 |
+
console.rule()
|
| 187 |
+
console.print(columns)
|
miniconda3/lib/python3.13/site-packages/rich/console.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
miniconda3/lib/python3.13/site-packages/rich/constrain.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Optional, TYPE_CHECKING
|
| 2 |
+
|
| 3 |
+
from .jupyter import JupyterMixin
|
| 4 |
+
from .measure import Measurement
|
| 5 |
+
|
| 6 |
+
if TYPE_CHECKING:
|
| 7 |
+
from .console import Console, ConsoleOptions, RenderableType, RenderResult
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class Constrain(JupyterMixin):
|
| 11 |
+
"""Constrain the width of a renderable to a given number of characters.
|
| 12 |
+
|
| 13 |
+
Args:
|
| 14 |
+
renderable (RenderableType): A renderable object.
|
| 15 |
+
width (int, optional): The maximum width (in characters) to render. Defaults to 80.
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
def __init__(self, renderable: "RenderableType", width: Optional[int] = 80) -> None:
|
| 19 |
+
self.renderable = renderable
|
| 20 |
+
self.width = width
|
| 21 |
+
|
| 22 |
+
def __rich_console__(
|
| 23 |
+
self, console: "Console", options: "ConsoleOptions"
|
| 24 |
+
) -> "RenderResult":
|
| 25 |
+
if self.width is None:
|
| 26 |
+
yield self.renderable
|
| 27 |
+
else:
|
| 28 |
+
child_options = options.update_width(min(self.width, options.max_width))
|
| 29 |
+
yield from console.render(self.renderable, child_options)
|
| 30 |
+
|
| 31 |
+
def __rich_measure__(
|
| 32 |
+
self, console: "Console", options: "ConsoleOptions"
|
| 33 |
+
) -> "Measurement":
|
| 34 |
+
if self.width is not None:
|
| 35 |
+
options = options.update_width(self.width)
|
| 36 |
+
measurement = Measurement.get(console, options, self.renderable)
|
| 37 |
+
return measurement
|
miniconda3/lib/python3.13/site-packages/rich/containers.py
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 4 |
+
Iterable,
|
| 5 |
+
Iterator,
|
| 6 |
+
List,
|
| 7 |
+
Optional,
|
| 8 |
+
TypeVar,
|
| 9 |
+
Union,
|
| 10 |
+
overload,
|
| 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 cells available 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)
|
miniconda3/lib/python3.13/site-packages/rich/control.py
ADDED
|
@@ -0,0 +1,219 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import time
|
| 2 |
+
from typing import TYPE_CHECKING, Callable, Dict, Iterable, List, Union, Final
|
| 3 |
+
|
| 4 |
+
from .segment import ControlCode, ControlType, Segment
|
| 5 |
+
|
| 6 |
+
if TYPE_CHECKING:
|
| 7 |
+
from .console import Console, ConsoleOptions, RenderResult
|
| 8 |
+
|
| 9 |
+
STRIP_CONTROL_CODES: Final = [
|
| 10 |
+
7, # Bell
|
| 11 |
+
8, # Backspace
|
| 12 |
+
11, # Vertical tab
|
| 13 |
+
12, # Form feed
|
| 14 |
+
13, # Carriage return
|
| 15 |
+
]
|
| 16 |
+
_CONTROL_STRIP_TRANSLATE: Final = {
|
| 17 |
+
_codepoint: None for _codepoint in STRIP_CONTROL_CODES
|
| 18 |
+
}
|
| 19 |
+
|
| 20 |
+
CONTROL_ESCAPE: Final = {
|
| 21 |
+
7: "\\a",
|
| 22 |
+
8: "\\b",
|
| 23 |
+
11: "\\v",
|
| 24 |
+
12: "\\f",
|
| 25 |
+
13: "\\r",
|
| 26 |
+
}
|
| 27 |
+
|
| 28 |
+
CONTROL_CODES_FORMAT: Dict[int, Callable[..., str]] = {
|
| 29 |
+
ControlType.BELL: lambda: "\x07",
|
| 30 |
+
ControlType.CARRIAGE_RETURN: lambda: "\r",
|
| 31 |
+
ControlType.HOME: lambda: "\x1b[H",
|
| 32 |
+
ControlType.CLEAR: lambda: "\x1b[2J",
|
| 33 |
+
ControlType.ENABLE_ALT_SCREEN: lambda: "\x1b[?1049h",
|
| 34 |
+
ControlType.DISABLE_ALT_SCREEN: lambda: "\x1b[?1049l",
|
| 35 |
+
ControlType.SHOW_CURSOR: lambda: "\x1b[?25h",
|
| 36 |
+
ControlType.HIDE_CURSOR: lambda: "\x1b[?25l",
|
| 37 |
+
ControlType.CURSOR_UP: lambda param: f"\x1b[{param}A",
|
| 38 |
+
ControlType.CURSOR_DOWN: lambda param: f"\x1b[{param}B",
|
| 39 |
+
ControlType.CURSOR_FORWARD: lambda param: f"\x1b[{param}C",
|
| 40 |
+
ControlType.CURSOR_BACKWARD: lambda param: f"\x1b[{param}D",
|
| 41 |
+
ControlType.CURSOR_MOVE_TO_COLUMN: lambda param: f"\x1b[{param+1}G",
|
| 42 |
+
ControlType.ERASE_IN_LINE: lambda param: f"\x1b[{param}K",
|
| 43 |
+
ControlType.CURSOR_MOVE_TO: lambda x, y: f"\x1b[{y+1};{x+1}H",
|
| 44 |
+
ControlType.SET_WINDOW_TITLE: lambda title: f"\x1b]0;{title}\x07",
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
class Control:
|
| 49 |
+
"""A renderable that inserts a control code (non printable but may move cursor).
|
| 50 |
+
|
| 51 |
+
Args:
|
| 52 |
+
*codes (str): Positional arguments are either a :class:`~rich.segment.ControlType` enum or a
|
| 53 |
+
tuple of ControlType and an integer parameter
|
| 54 |
+
"""
|
| 55 |
+
|
| 56 |
+
__slots__ = ["segment"]
|
| 57 |
+
|
| 58 |
+
def __init__(self, *codes: Union[ControlType, ControlCode]) -> None:
|
| 59 |
+
control_codes: List[ControlCode] = [
|
| 60 |
+
(code,) if isinstance(code, ControlType) else code for code in codes
|
| 61 |
+
]
|
| 62 |
+
_format_map = CONTROL_CODES_FORMAT
|
| 63 |
+
rendered_codes = "".join(
|
| 64 |
+
_format_map[code](*parameters) for code, *parameters in control_codes
|
| 65 |
+
)
|
| 66 |
+
self.segment = Segment(rendered_codes, None, control_codes)
|
| 67 |
+
|
| 68 |
+
@classmethod
|
| 69 |
+
def bell(cls) -> "Control":
|
| 70 |
+
"""Ring the 'bell'."""
|
| 71 |
+
return cls(ControlType.BELL)
|
| 72 |
+
|
| 73 |
+
@classmethod
|
| 74 |
+
def home(cls) -> "Control":
|
| 75 |
+
"""Move cursor to 'home' position."""
|
| 76 |
+
return cls(ControlType.HOME)
|
| 77 |
+
|
| 78 |
+
@classmethod
|
| 79 |
+
def move(cls, x: int = 0, y: int = 0) -> "Control":
|
| 80 |
+
"""Move cursor relative to current position.
|
| 81 |
+
|
| 82 |
+
Args:
|
| 83 |
+
x (int): X offset.
|
| 84 |
+
y (int): Y offset.
|
| 85 |
+
|
| 86 |
+
Returns:
|
| 87 |
+
~Control: Control object.
|
| 88 |
+
|
| 89 |
+
"""
|
| 90 |
+
|
| 91 |
+
def get_codes() -> Iterable[ControlCode]:
|
| 92 |
+
control = ControlType
|
| 93 |
+
if x:
|
| 94 |
+
yield (
|
| 95 |
+
control.CURSOR_FORWARD if x > 0 else control.CURSOR_BACKWARD,
|
| 96 |
+
abs(x),
|
| 97 |
+
)
|
| 98 |
+
if y:
|
| 99 |
+
yield (
|
| 100 |
+
control.CURSOR_DOWN if y > 0 else control.CURSOR_UP,
|
| 101 |
+
abs(y),
|
| 102 |
+
)
|
| 103 |
+
|
| 104 |
+
control = cls(*get_codes())
|
| 105 |
+
return control
|
| 106 |
+
|
| 107 |
+
@classmethod
|
| 108 |
+
def move_to_column(cls, x: int, y: int = 0) -> "Control":
|
| 109 |
+
"""Move to the given column, optionally add offset to row.
|
| 110 |
+
|
| 111 |
+
Returns:
|
| 112 |
+
x (int): absolute x (column)
|
| 113 |
+
y (int): optional y offset (row)
|
| 114 |
+
|
| 115 |
+
Returns:
|
| 116 |
+
~Control: Control object.
|
| 117 |
+
"""
|
| 118 |
+
|
| 119 |
+
return (
|
| 120 |
+
cls(
|
| 121 |
+
(ControlType.CURSOR_MOVE_TO_COLUMN, x),
|
| 122 |
+
(
|
| 123 |
+
ControlType.CURSOR_DOWN if y > 0 else ControlType.CURSOR_UP,
|
| 124 |
+
abs(y),
|
| 125 |
+
),
|
| 126 |
+
)
|
| 127 |
+
if y
|
| 128 |
+
else cls((ControlType.CURSOR_MOVE_TO_COLUMN, x))
|
| 129 |
+
)
|
| 130 |
+
|
| 131 |
+
@classmethod
|
| 132 |
+
def move_to(cls, x: int, y: int) -> "Control":
|
| 133 |
+
"""Move cursor to absolute position.
|
| 134 |
+
|
| 135 |
+
Args:
|
| 136 |
+
x (int): x offset (column)
|
| 137 |
+
y (int): y offset (row)
|
| 138 |
+
|
| 139 |
+
Returns:
|
| 140 |
+
~Control: Control object.
|
| 141 |
+
"""
|
| 142 |
+
return cls((ControlType.CURSOR_MOVE_TO, x, y))
|
| 143 |
+
|
| 144 |
+
@classmethod
|
| 145 |
+
def clear(cls) -> "Control":
|
| 146 |
+
"""Clear the screen."""
|
| 147 |
+
return cls(ControlType.CLEAR)
|
| 148 |
+
|
| 149 |
+
@classmethod
|
| 150 |
+
def show_cursor(cls, show: bool) -> "Control":
|
| 151 |
+
"""Show or hide the cursor."""
|
| 152 |
+
return cls(ControlType.SHOW_CURSOR if show else ControlType.HIDE_CURSOR)
|
| 153 |
+
|
| 154 |
+
@classmethod
|
| 155 |
+
def alt_screen(cls, enable: bool) -> "Control":
|
| 156 |
+
"""Enable or disable alt screen."""
|
| 157 |
+
if enable:
|
| 158 |
+
return cls(ControlType.ENABLE_ALT_SCREEN, ControlType.HOME)
|
| 159 |
+
else:
|
| 160 |
+
return cls(ControlType.DISABLE_ALT_SCREEN)
|
| 161 |
+
|
| 162 |
+
@classmethod
|
| 163 |
+
def title(cls, title: str) -> "Control":
|
| 164 |
+
"""Set the terminal window title
|
| 165 |
+
|
| 166 |
+
Args:
|
| 167 |
+
title (str): The new terminal window title
|
| 168 |
+
"""
|
| 169 |
+
return cls((ControlType.SET_WINDOW_TITLE, title))
|
| 170 |
+
|
| 171 |
+
def __str__(self) -> str:
|
| 172 |
+
return self.segment.text
|
| 173 |
+
|
| 174 |
+
def __rich_console__(
|
| 175 |
+
self, console: "Console", options: "ConsoleOptions"
|
| 176 |
+
) -> "RenderResult":
|
| 177 |
+
if self.segment.text:
|
| 178 |
+
yield self.segment
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
def strip_control_codes(
|
| 182 |
+
text: str, _translate_table: Dict[int, None] = _CONTROL_STRIP_TRANSLATE
|
| 183 |
+
) -> str:
|
| 184 |
+
"""Remove control codes from text.
|
| 185 |
+
|
| 186 |
+
Args:
|
| 187 |
+
text (str): A string possibly contain control codes.
|
| 188 |
+
|
| 189 |
+
Returns:
|
| 190 |
+
str: String with control codes removed.
|
| 191 |
+
"""
|
| 192 |
+
return text.translate(_translate_table)
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
def escape_control_codes(
|
| 196 |
+
text: str,
|
| 197 |
+
_translate_table: Dict[int, str] = CONTROL_ESCAPE,
|
| 198 |
+
) -> str:
|
| 199 |
+
"""Replace control codes with their "escaped" equivalent in the given text.
|
| 200 |
+
(e.g. "\b" becomes "\\b")
|
| 201 |
+
|
| 202 |
+
Args:
|
| 203 |
+
text (str): A string possibly containing control codes.
|
| 204 |
+
|
| 205 |
+
Returns:
|
| 206 |
+
str: String with control codes replaced with their escaped version.
|
| 207 |
+
"""
|
| 208 |
+
return text.translate(_translate_table)
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
if __name__ == "__main__": # pragma: no cover
|
| 212 |
+
from rich.console import Console
|
| 213 |
+
|
| 214 |
+
console = Console()
|
| 215 |
+
console.print("Look at the title of your terminal window ^")
|
| 216 |
+
# console.print(Control((ControlType.SET_WINDOW_TITLE, "Hello, world!")))
|
| 217 |
+
for i in range(10):
|
| 218 |
+
console.set_window_title("🚀 Loading" + "." * i)
|
| 219 |
+
time.sleep(0.5)
|
miniconda3/lib/python3.13/site-packages/rich/default_styles.py
ADDED
|
@@ -0,0 +1,193 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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="yellow"),
|
| 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 |
+
"traceback.error_range": Style(underline=True, bold=True),
|
| 124 |
+
"traceback.note": Style(color="green", bold=True),
|
| 125 |
+
"traceback.group.border": Style(color="magenta"),
|
| 126 |
+
"bar.back": Style(color="grey23"),
|
| 127 |
+
"bar.complete": Style(color="rgb(249,38,114)"),
|
| 128 |
+
"bar.finished": Style(color="rgb(114,156,31)"),
|
| 129 |
+
"bar.pulse": Style(color="rgb(249,38,114)"),
|
| 130 |
+
"progress.description": Style.null(),
|
| 131 |
+
"progress.filesize": Style(color="green"),
|
| 132 |
+
"progress.filesize.total": Style(color="green"),
|
| 133 |
+
"progress.download": Style(color="green"),
|
| 134 |
+
"progress.elapsed": Style(color="yellow"),
|
| 135 |
+
"progress.percentage": Style(color="magenta"),
|
| 136 |
+
"progress.remaining": Style(color="cyan"),
|
| 137 |
+
"progress.data.speed": Style(color="red"),
|
| 138 |
+
"progress.spinner": Style(color="green"),
|
| 139 |
+
"status.spinner": Style(color="green"),
|
| 140 |
+
"tree": Style(),
|
| 141 |
+
"tree.line": Style(),
|
| 142 |
+
"markdown.paragraph": Style(),
|
| 143 |
+
"markdown.text": Style(),
|
| 144 |
+
"markdown.em": Style(italic=True),
|
| 145 |
+
"markdown.emph": Style(italic=True), # For commonmark backwards compatibility
|
| 146 |
+
"markdown.strong": Style(bold=True),
|
| 147 |
+
"markdown.code": Style(bold=True, color="cyan", bgcolor="black"),
|
| 148 |
+
"markdown.code_block": Style(color="cyan", bgcolor="black"),
|
| 149 |
+
"markdown.block_quote": Style(color="magenta"),
|
| 150 |
+
"markdown.list": Style(color="cyan"),
|
| 151 |
+
"markdown.item": Style(),
|
| 152 |
+
"markdown.item.bullet": Style(color="yellow", bold=True),
|
| 153 |
+
"markdown.item.number": Style(color="yellow", bold=True),
|
| 154 |
+
"markdown.hr": Style(color="yellow"),
|
| 155 |
+
"markdown.h1.border": Style(),
|
| 156 |
+
"markdown.h1": Style(bold=True),
|
| 157 |
+
"markdown.h2": Style(bold=True, underline=True),
|
| 158 |
+
"markdown.h3": Style(bold=True),
|
| 159 |
+
"markdown.h4": Style(bold=True, dim=True),
|
| 160 |
+
"markdown.h5": Style(underline=True),
|
| 161 |
+
"markdown.h6": Style(italic=True),
|
| 162 |
+
"markdown.h7": Style(italic=True, dim=True),
|
| 163 |
+
"markdown.link": Style(color="bright_blue"),
|
| 164 |
+
"markdown.link_url": Style(color="blue", underline=True),
|
| 165 |
+
"markdown.s": Style(strike=True),
|
| 166 |
+
"iso8601.date": Style(color="blue"),
|
| 167 |
+
"iso8601.time": Style(color="magenta"),
|
| 168 |
+
"iso8601.timezone": Style(color="yellow"),
|
| 169 |
+
}
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
if __name__ == "__main__": # pragma: no cover
|
| 173 |
+
import argparse
|
| 174 |
+
import io
|
| 175 |
+
|
| 176 |
+
from rich.console import Console
|
| 177 |
+
from rich.table import Table
|
| 178 |
+
from rich.text import Text
|
| 179 |
+
|
| 180 |
+
parser = argparse.ArgumentParser()
|
| 181 |
+
parser.add_argument("--html", action="store_true", help="Export as HTML table")
|
| 182 |
+
args = parser.parse_args()
|
| 183 |
+
html: bool = args.html
|
| 184 |
+
console = Console(record=True, width=70, file=io.StringIO()) if html else Console()
|
| 185 |
+
|
| 186 |
+
table = Table("Name", "Styling")
|
| 187 |
+
|
| 188 |
+
for style_name, style in DEFAULT_STYLES.items():
|
| 189 |
+
table.add_row(Text(style_name, style=style), str(style))
|
| 190 |
+
|
| 191 |
+
console.print(table)
|
| 192 |
+
if html:
|
| 193 |
+
print(console.export_html(inline_styles=True))
|
miniconda3/lib/python3.13/site-packages/rich/diagnose.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import platform
|
| 3 |
+
|
| 4 |
+
from rich import inspect
|
| 5 |
+
from rich.console import Console, get_windows_console_features
|
| 6 |
+
from rich.panel import Panel
|
| 7 |
+
from rich.pretty import Pretty
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def report() -> None: # pragma: no cover
|
| 11 |
+
"""Print a report to the terminal with debugging information"""
|
| 12 |
+
console = Console()
|
| 13 |
+
inspect(console)
|
| 14 |
+
features = get_windows_console_features()
|
| 15 |
+
inspect(features)
|
| 16 |
+
|
| 17 |
+
env_names = (
|
| 18 |
+
"CLICOLOR",
|
| 19 |
+
"COLORTERM",
|
| 20 |
+
"COLUMNS",
|
| 21 |
+
"JPY_PARENT_PID",
|
| 22 |
+
"JUPYTER_COLUMNS",
|
| 23 |
+
"JUPYTER_LINES",
|
| 24 |
+
"LINES",
|
| 25 |
+
"NO_COLOR",
|
| 26 |
+
"TERM_PROGRAM",
|
| 27 |
+
"TERM",
|
| 28 |
+
"TTY_COMPATIBLE",
|
| 29 |
+
"TTY_INTERACTIVE",
|
| 30 |
+
"VSCODE_VERBOSE_LOGGING",
|
| 31 |
+
)
|
| 32 |
+
env = {name: os.getenv(name) for name in env_names}
|
| 33 |
+
console.print(Panel.fit((Pretty(env)), title="[b]Environment Variables"))
|
| 34 |
+
|
| 35 |
+
console.print(f'platform="{platform.system()}"')
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
if __name__ == "__main__": # pragma: no cover
|
| 39 |
+
report()
|
miniconda3/lib/python3.13/site-packages/rich/emoji.py
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sys
|
| 2 |
+
from typing import TYPE_CHECKING, Optional, Union, Literal
|
| 3 |
+
|
| 4 |
+
from .jupyter import JupyterMixin
|
| 5 |
+
from .segment import Segment
|
| 6 |
+
from .style import Style
|
| 7 |
+
from ._emoji_codes import EMOJI
|
| 8 |
+
from ._emoji_replace import _emoji_replace
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
if TYPE_CHECKING:
|
| 12 |
+
from .console import Console, ConsoleOptions, RenderResult
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
EmojiVariant = Literal["emoji", "text"]
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class NoEmoji(Exception):
|
| 19 |
+
"""No emoji by that name."""
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class Emoji(JupyterMixin):
|
| 23 |
+
__slots__ = ["name", "style", "_char", "variant"]
|
| 24 |
+
|
| 25 |
+
VARIANTS = {"text": "\uFE0E", "emoji": "\uFE0F"}
|
| 26 |
+
|
| 27 |
+
def __init__(
|
| 28 |
+
self,
|
| 29 |
+
name: str,
|
| 30 |
+
style: Union[str, Style] = "none",
|
| 31 |
+
variant: Optional[EmojiVariant] = None,
|
| 32 |
+
) -> None:
|
| 33 |
+
"""A single emoji character.
|
| 34 |
+
|
| 35 |
+
Args:
|
| 36 |
+
name (str): Name of emoji.
|
| 37 |
+
style (Union[str, Style], optional): Optional style. Defaults to None.
|
| 38 |
+
|
| 39 |
+
Raises:
|
| 40 |
+
NoEmoji: If the emoji doesn't exist.
|
| 41 |
+
"""
|
| 42 |
+
self.name = name
|
| 43 |
+
self.style = style
|
| 44 |
+
self.variant = variant
|
| 45 |
+
try:
|
| 46 |
+
self._char = EMOJI[name]
|
| 47 |
+
except KeyError:
|
| 48 |
+
raise NoEmoji(f"No emoji called {name!r}")
|
| 49 |
+
if variant is not None:
|
| 50 |
+
self._char += self.VARIANTS.get(variant, "")
|
| 51 |
+
|
| 52 |
+
@classmethod
|
| 53 |
+
def replace(cls, text: str) -> str:
|
| 54 |
+
"""Replace emoji markup with corresponding unicode characters.
|
| 55 |
+
|
| 56 |
+
Args:
|
| 57 |
+
text (str): A string with emojis codes, e.g. "Hello :smiley:!"
|
| 58 |
+
|
| 59 |
+
Returns:
|
| 60 |
+
str: A string with emoji codes replaces with actual emoji.
|
| 61 |
+
"""
|
| 62 |
+
return _emoji_replace(text)
|
| 63 |
+
|
| 64 |
+
def __repr__(self) -> str:
|
| 65 |
+
return f"<emoji {self.name!r}>"
|
| 66 |
+
|
| 67 |
+
def __str__(self) -> str:
|
| 68 |
+
return self._char
|
| 69 |
+
|
| 70 |
+
def __rich_console__(
|
| 71 |
+
self, console: "Console", options: "ConsoleOptions"
|
| 72 |
+
) -> "RenderResult":
|
| 73 |
+
yield Segment(self._char, console.get_style(self.style))
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
if __name__ == "__main__": # pragma: no cover
|
| 77 |
+
import sys
|
| 78 |
+
|
| 79 |
+
from rich.columns import Columns
|
| 80 |
+
from rich.console import Console
|
| 81 |
+
|
| 82 |
+
console = Console(record=True)
|
| 83 |
+
|
| 84 |
+
columns = Columns(
|
| 85 |
+
(f":{name}: {name}" for name in sorted(EMOJI.keys()) if "\u200D" not in name),
|
| 86 |
+
column_first=True,
|
| 87 |
+
)
|
| 88 |
+
|
| 89 |
+
console.print(columns)
|
| 90 |
+
if len(sys.argv) > 1:
|
| 91 |
+
console.save_html(sys.argv[1])
|
miniconda3/lib/python3.13/site-packages/rich/errors.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
class ConsoleError(Exception):
|
| 2 |
+
"""An error in console operation."""
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
class StyleError(Exception):
|
| 6 |
+
"""An error in styles."""
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class StyleSyntaxError(ConsoleError):
|
| 10 |
+
"""Style was badly formatted."""
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class MissingStyle(StyleError):
|
| 14 |
+
"""No such style."""
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class StyleStackError(ConsoleError):
|
| 18 |
+
"""Style stack is invalid."""
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class NotRenderableError(ConsoleError):
|
| 22 |
+
"""Object is not renderable."""
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class MarkupError(ConsoleError):
|
| 26 |
+
"""Markup was badly formatted."""
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class LiveError(ConsoleError):
|
| 30 |
+
"""Error related to Live display."""
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class NoAltScreen(ConsoleError):
|
| 34 |
+
"""Alt screen mode was required."""
|
miniconda3/lib/python3.13/site-packages/rich/file_proxy.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import io
|
| 2 |
+
from typing import IO, TYPE_CHECKING, Any, List
|
| 3 |
+
|
| 4 |
+
from .ansi import AnsiDecoder
|
| 5 |
+
from .text import Text
|
| 6 |
+
|
| 7 |
+
if TYPE_CHECKING:
|
| 8 |
+
from .console import Console
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class FileProxy(io.TextIOBase):
|
| 12 |
+
"""Wraps a file (e.g. sys.stdout) and redirects writes to a console."""
|
| 13 |
+
|
| 14 |
+
def __init__(self, console: "Console", file: IO[str]) -> None:
|
| 15 |
+
self.__console = console
|
| 16 |
+
self.__file = file
|
| 17 |
+
self.__buffer: List[str] = []
|
| 18 |
+
self.__ansi_decoder = AnsiDecoder()
|
| 19 |
+
|
| 20 |
+
@property
|
| 21 |
+
def rich_proxied_file(self) -> IO[str]:
|
| 22 |
+
"""Get proxied file."""
|
| 23 |
+
return self.__file
|
| 24 |
+
|
| 25 |
+
def __getattr__(self, name: str) -> Any:
|
| 26 |
+
return getattr(self.__file, name)
|
| 27 |
+
|
| 28 |
+
def write(self, text: str) -> int:
|
| 29 |
+
if not isinstance(text, str):
|
| 30 |
+
raise TypeError(f"write() argument must be str, not {type(text).__name__}")
|
| 31 |
+
buffer = self.__buffer
|
| 32 |
+
lines: List[str] = []
|
| 33 |
+
while text:
|
| 34 |
+
line, new_line, text = text.partition("\n")
|
| 35 |
+
if new_line:
|
| 36 |
+
lines.append("".join(buffer) + line)
|
| 37 |
+
buffer.clear()
|
| 38 |
+
else:
|
| 39 |
+
buffer.append(line)
|
| 40 |
+
break
|
| 41 |
+
if lines:
|
| 42 |
+
console = self.__console
|
| 43 |
+
with console:
|
| 44 |
+
output = Text("\n").join(
|
| 45 |
+
self.__ansi_decoder.decode_line(line) for line in lines
|
| 46 |
+
)
|
| 47 |
+
console.print(output)
|
| 48 |
+
return len(text)
|
| 49 |
+
|
| 50 |
+
def flush(self) -> None:
|
| 51 |
+
output = "".join(self.__buffer)
|
| 52 |
+
if output:
|
| 53 |
+
self.__console.print(output)
|
| 54 |
+
del self.__buffer[:]
|
| 55 |
+
|
| 56 |
+
def fileno(self) -> int:
|
| 57 |
+
return self.__file.fileno()
|
miniconda3/lib/python3.13/site-packages/rich/filesize.py
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Functions for reporting filesizes. Borrowed from https://github.com/PyFilesystem/pyfilesystem2
|
| 2 |
+
|
| 3 |
+
The functions declared in this module should cover the different
|
| 4 |
+
use cases needed to generate a string representation of a file size
|
| 5 |
+
using several different units. Since there are many standards regarding
|
| 6 |
+
file size units, three different functions have been implemented.
|
| 7 |
+
|
| 8 |
+
See Also:
|
| 9 |
+
* `Wikipedia: Binary prefix <https://en.wikipedia.org/wiki/Binary_prefix>`_
|
| 10 |
+
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
__all__ = ["decimal"]
|
| 14 |
+
|
| 15 |
+
from typing import Iterable, List, Optional, Tuple
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def _to_str(
|
| 19 |
+
size: int,
|
| 20 |
+
suffixes: Iterable[str],
|
| 21 |
+
base: int,
|
| 22 |
+
*,
|
| 23 |
+
precision: Optional[int] = 1,
|
| 24 |
+
separator: Optional[str] = " ",
|
| 25 |
+
) -> str:
|
| 26 |
+
if size == 1:
|
| 27 |
+
return "1 byte"
|
| 28 |
+
elif size < base:
|
| 29 |
+
return f"{size:,} bytes"
|
| 30 |
+
|
| 31 |
+
for i, suffix in enumerate(suffixes, 2): # noqa: B007
|
| 32 |
+
unit = base**i
|
| 33 |
+
if size < unit:
|
| 34 |
+
break
|
| 35 |
+
return "{:,.{precision}f}{separator}{}".format(
|
| 36 |
+
(base * size / unit),
|
| 37 |
+
suffix,
|
| 38 |
+
precision=precision,
|
| 39 |
+
separator=separator,
|
| 40 |
+
)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def pick_unit_and_suffix(size: int, suffixes: List[str], base: int) -> Tuple[int, str]:
|
| 44 |
+
"""Pick a suffix and base for the given size."""
|
| 45 |
+
for i, suffix in enumerate(suffixes):
|
| 46 |
+
unit = base**i
|
| 47 |
+
if size < unit * base:
|
| 48 |
+
break
|
| 49 |
+
return unit, suffix
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def decimal(
|
| 53 |
+
size: int,
|
| 54 |
+
*,
|
| 55 |
+
precision: Optional[int] = 1,
|
| 56 |
+
separator: Optional[str] = " ",
|
| 57 |
+
) -> str:
|
| 58 |
+
"""Convert a filesize in to a string (powers of 1000, SI prefixes).
|
| 59 |
+
|
| 60 |
+
In this convention, ``1000 B = 1 kB``.
|
| 61 |
+
|
| 62 |
+
This is typically the format used to advertise the storage
|
| 63 |
+
capacity of USB flash drives and the like (*256 MB* meaning
|
| 64 |
+
actually a storage capacity of more than *256 000 000 B*),
|
| 65 |
+
or used by **Mac OS X** since v10.6 to report file sizes.
|
| 66 |
+
|
| 67 |
+
Arguments:
|
| 68 |
+
int (size): A file size.
|
| 69 |
+
int (precision): The number of decimal places to include (default = 1).
|
| 70 |
+
str (separator): The string to separate the value from the units (default = " ").
|
| 71 |
+
|
| 72 |
+
Returns:
|
| 73 |
+
`str`: A string containing a abbreviated file size and units.
|
| 74 |
+
|
| 75 |
+
Example:
|
| 76 |
+
>>> filesize.decimal(30000)
|
| 77 |
+
'30.0 kB'
|
| 78 |
+
>>> filesize.decimal(30000, precision=2, separator="")
|
| 79 |
+
'30.00kB'
|
| 80 |
+
|
| 81 |
+
"""
|
| 82 |
+
return _to_str(
|
| 83 |
+
size,
|
| 84 |
+
("kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"),
|
| 85 |
+
1000,
|
| 86 |
+
precision=precision,
|
| 87 |
+
separator=separator,
|
| 88 |
+
)
|
miniconda3/lib/python3.13/site-packages/rich/highlighter.py
ADDED
|
@@ -0,0 +1,232 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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|
+
|
| 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)
|
miniconda3/lib/python3.13/site-packages/rich/json.py
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
import argparse
|
| 107 |
+
import sys
|
| 108 |
+
|
| 109 |
+
parser = argparse.ArgumentParser(description="Pretty print json")
|
| 110 |
+
parser.add_argument(
|
| 111 |
+
"path",
|
| 112 |
+
metavar="PATH",
|
| 113 |
+
help="path to file, or - for stdin",
|
| 114 |
+
)
|
| 115 |
+
parser.add_argument(
|
| 116 |
+
"-i",
|
| 117 |
+
"--indent",
|
| 118 |
+
metavar="SPACES",
|
| 119 |
+
type=int,
|
| 120 |
+
help="Number of spaces in an indent",
|
| 121 |
+
default=2,
|
| 122 |
+
)
|
| 123 |
+
args = parser.parse_args()
|
| 124 |
+
|
| 125 |
+
from rich.console import Console
|
| 126 |
+
|
| 127 |
+
console = Console()
|
| 128 |
+
error_console = Console(stderr=True)
|
| 129 |
+
|
| 130 |
+
try:
|
| 131 |
+
if args.path == "-":
|
| 132 |
+
json_data = sys.stdin.read()
|
| 133 |
+
else:
|
| 134 |
+
json_data = Path(args.path).read_text()
|
| 135 |
+
except Exception as error:
|
| 136 |
+
error_console.print(f"Unable to read {args.path!r}; {error}")
|
| 137 |
+
sys.exit(-1)
|
| 138 |
+
|
| 139 |
+
console.print(JSON(json_data, indent=args.indent), soft_wrap=True)
|
miniconda3/lib/python3.13/site-packages/rich/jupyter.py
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Sequence
|
| 2 |
+
|
| 3 |
+
if TYPE_CHECKING:
|
| 4 |
+
from rich.console import ConsoleRenderable
|
| 5 |
+
|
| 6 |
+
from . import get_console
|
| 7 |
+
from .segment import Segment
|
| 8 |
+
from .terminal_theme import DEFAULT_TERMINAL_THEME
|
| 9 |
+
|
| 10 |
+
if TYPE_CHECKING:
|
| 11 |
+
from rich.console import ConsoleRenderable
|
| 12 |
+
|
| 13 |
+
JUPYTER_HTML_FORMAT = """\
|
| 14 |
+
<pre style="white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace">{code}</pre>
|
| 15 |
+
"""
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class JupyterRenderable:
|
| 19 |
+
"""A shim to write html to Jupyter notebook."""
|
| 20 |
+
|
| 21 |
+
def __init__(self, html: str, text: str) -> None:
|
| 22 |
+
self.html = html
|
| 23 |
+
self.text = text
|
| 24 |
+
|
| 25 |
+
def _repr_mimebundle_(
|
| 26 |
+
self, include: Sequence[str], exclude: Sequence[str], **kwargs: Any
|
| 27 |
+
) -> Dict[str, str]:
|
| 28 |
+
data = {"text/plain": self.text, "text/html": self.html}
|
| 29 |
+
if include:
|
| 30 |
+
data = {k: v for (k, v) in data.items() if k in include}
|
| 31 |
+
if exclude:
|
| 32 |
+
data = {k: v for (k, v) in data.items() if k not in exclude}
|
| 33 |
+
return data
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class JupyterMixin:
|
| 37 |
+
"""Add to an Rich renderable to make it render in Jupyter notebook."""
|
| 38 |
+
|
| 39 |
+
__slots__ = ()
|
| 40 |
+
|
| 41 |
+
def _repr_mimebundle_(
|
| 42 |
+
self: "ConsoleRenderable",
|
| 43 |
+
include: Sequence[str],
|
| 44 |
+
exclude: Sequence[str],
|
| 45 |
+
**kwargs: Any,
|
| 46 |
+
) -> Dict[str, str]:
|
| 47 |
+
console = get_console()
|
| 48 |
+
segments = list(console.render(self, console.options))
|
| 49 |
+
html = _render_segments(segments)
|
| 50 |
+
text = console._render_buffer(segments)
|
| 51 |
+
data = {"text/plain": text, "text/html": html}
|
| 52 |
+
if include:
|
| 53 |
+
data = {k: v for (k, v) in data.items() if k in include}
|
| 54 |
+
if exclude:
|
| 55 |
+
data = {k: v for (k, v) in data.items() if k not in exclude}
|
| 56 |
+
return data
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def _render_segments(segments: Iterable[Segment]) -> str:
|
| 60 |
+
def escape(text: str) -> str:
|
| 61 |
+
"""Escape html."""
|
| 62 |
+
return text.replace("&", "&").replace("<", "<").replace(">", ">")
|
| 63 |
+
|
| 64 |
+
fragments: List[str] = []
|
| 65 |
+
append_fragment = fragments.append
|
| 66 |
+
theme = DEFAULT_TERMINAL_THEME
|
| 67 |
+
for text, style, control in Segment.simplify(segments):
|
| 68 |
+
if control:
|
| 69 |
+
continue
|
| 70 |
+
text = escape(text)
|
| 71 |
+
if style:
|
| 72 |
+
rule = style.get_html_style(theme)
|
| 73 |
+
text = f'<span style="{rule}">{text}</span>' if rule else text
|
| 74 |
+
if style.link:
|
| 75 |
+
text = f'<a href="{style.link}" target="_blank">{text}</a>'
|
| 76 |
+
append_fragment(text)
|
| 77 |
+
|
| 78 |
+
code = "".join(fragments)
|
| 79 |
+
html = JUPYTER_HTML_FORMAT.format(code=code)
|
| 80 |
+
|
| 81 |
+
return html
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def display(segments: Iterable[Segment], text: str) -> None:
|
| 85 |
+
"""Render segments to Jupyter."""
|
| 86 |
+
html = _render_segments(segments)
|
| 87 |
+
jupyter_renderable = JupyterRenderable(html, text)
|
| 88 |
+
try:
|
| 89 |
+
from IPython.display import display as ipython_display
|
| 90 |
+
|
| 91 |
+
ipython_display(jupyter_renderable)
|
| 92 |
+
except ModuleNotFoundError:
|
| 93 |
+
# Handle the case where the Console has force_jupyter=True,
|
| 94 |
+
# but IPython is not installed.
|
| 95 |
+
pass
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def print(*args: Any, **kwargs: Any) -> None:
|
| 99 |
+
"""Proxy for Console print."""
|
| 100 |
+
console = get_console()
|
| 101 |
+
return console.print(*args, **kwargs)
|
miniconda3/lib/python3.13/site-packages/rich/layout.py
ADDED
|
@@ -0,0 +1,442 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from abc import ABC, abstractmethod
|
| 2 |
+
from itertools import islice
|
| 3 |
+
from operator import itemgetter
|
| 4 |
+
from threading import RLock
|
| 5 |
+
from typing import (
|
| 6 |
+
TYPE_CHECKING,
|
| 7 |
+
Dict,
|
| 8 |
+
Iterable,
|
| 9 |
+
List,
|
| 10 |
+
NamedTuple,
|
| 11 |
+
Optional,
|
| 12 |
+
Sequence,
|
| 13 |
+
Tuple,
|
| 14 |
+
Union,
|
| 15 |
+
)
|
| 16 |
+
|
| 17 |
+
from ._ratio import ratio_resolve
|
| 18 |
+
from .align import Align
|
| 19 |
+
from .console import Console, ConsoleOptions, RenderableType, RenderResult
|
| 20 |
+
from .highlighter import ReprHighlighter
|
| 21 |
+
from .panel import Panel
|
| 22 |
+
from .pretty import Pretty
|
| 23 |
+
from .region import Region
|
| 24 |
+
from .repr import Result, rich_repr
|
| 25 |
+
from .segment import Segment
|
| 26 |
+
from .style import StyleType
|
| 27 |
+
|
| 28 |
+
if TYPE_CHECKING:
|
| 29 |
+
from rich.tree import Tree
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class LayoutRender(NamedTuple):
|
| 33 |
+
"""An individual layout render."""
|
| 34 |
+
|
| 35 |
+
region: Region
|
| 36 |
+
render: List[List[Segment]]
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
RegionMap = Dict["Layout", Region]
|
| 40 |
+
RenderMap = Dict["Layout", LayoutRender]
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class LayoutError(Exception):
|
| 44 |
+
"""Layout related error."""
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
class NoSplitter(LayoutError):
|
| 48 |
+
"""Requested splitter does not exist."""
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
class _Placeholder:
|
| 52 |
+
"""An internal renderable used as a Layout placeholder."""
|
| 53 |
+
|
| 54 |
+
highlighter = ReprHighlighter()
|
| 55 |
+
|
| 56 |
+
def __init__(self, layout: "Layout", style: StyleType = "") -> None:
|
| 57 |
+
self.layout = layout
|
| 58 |
+
self.style = style
|
| 59 |
+
|
| 60 |
+
def __rich_console__(
|
| 61 |
+
self, console: Console, options: ConsoleOptions
|
| 62 |
+
) -> RenderResult:
|
| 63 |
+
width = options.max_width
|
| 64 |
+
height = options.height or options.size.height
|
| 65 |
+
layout = self.layout
|
| 66 |
+
title = (
|
| 67 |
+
f"{layout.name!r} ({width} x {height})"
|
| 68 |
+
if layout.name
|
| 69 |
+
else f"({width} x {height})"
|
| 70 |
+
)
|
| 71 |
+
yield Panel(
|
| 72 |
+
Align.center(Pretty(layout), vertical="middle"),
|
| 73 |
+
style=self.style,
|
| 74 |
+
title=self.highlighter(title),
|
| 75 |
+
border_style="blue",
|
| 76 |
+
height=height,
|
| 77 |
+
)
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
class Splitter(ABC):
|
| 81 |
+
"""Base class for a splitter."""
|
| 82 |
+
|
| 83 |
+
name: str = ""
|
| 84 |
+
|
| 85 |
+
@abstractmethod
|
| 86 |
+
def get_tree_icon(self) -> str:
|
| 87 |
+
"""Get the icon (emoji) used in layout.tree"""
|
| 88 |
+
|
| 89 |
+
@abstractmethod
|
| 90 |
+
def divide(
|
| 91 |
+
self, children: Sequence["Layout"], region: Region
|
| 92 |
+
) -> Iterable[Tuple["Layout", Region]]:
|
| 93 |
+
"""Divide a region amongst several child layouts.
|
| 94 |
+
|
| 95 |
+
Args:
|
| 96 |
+
children (Sequence(Layout)): A number of child layouts.
|
| 97 |
+
region (Region): A rectangular region to divide.
|
| 98 |
+
"""
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
class RowSplitter(Splitter):
|
| 102 |
+
"""Split a layout region in to rows."""
|
| 103 |
+
|
| 104 |
+
name = "row"
|
| 105 |
+
|
| 106 |
+
def get_tree_icon(self) -> str:
|
| 107 |
+
return "[layout.tree.row]⬌"
|
| 108 |
+
|
| 109 |
+
def divide(
|
| 110 |
+
self, children: Sequence["Layout"], region: Region
|
| 111 |
+
) -> Iterable[Tuple["Layout", Region]]:
|
| 112 |
+
x, y, width, height = region
|
| 113 |
+
render_widths = ratio_resolve(width, children)
|
| 114 |
+
offset = 0
|
| 115 |
+
_Region = Region
|
| 116 |
+
for child, child_width in zip(children, render_widths):
|
| 117 |
+
yield child, _Region(x + offset, y, child_width, height)
|
| 118 |
+
offset += child_width
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
class ColumnSplitter(Splitter):
|
| 122 |
+
"""Split a layout region in to columns."""
|
| 123 |
+
|
| 124 |
+
name = "column"
|
| 125 |
+
|
| 126 |
+
def get_tree_icon(self) -> str:
|
| 127 |
+
return "[layout.tree.column]⬍"
|
| 128 |
+
|
| 129 |
+
def divide(
|
| 130 |
+
self, children: Sequence["Layout"], region: Region
|
| 131 |
+
) -> Iterable[Tuple["Layout", Region]]:
|
| 132 |
+
x, y, width, height = region
|
| 133 |
+
render_heights = ratio_resolve(height, children)
|
| 134 |
+
offset = 0
|
| 135 |
+
_Region = Region
|
| 136 |
+
for child, child_height in zip(children, render_heights):
|
| 137 |
+
yield child, _Region(x, y + offset, width, child_height)
|
| 138 |
+
offset += child_height
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
@rich_repr
|
| 142 |
+
class Layout:
|
| 143 |
+
"""A renderable to divide a fixed height in to rows or columns.
|
| 144 |
+
|
| 145 |
+
Args:
|
| 146 |
+
renderable (RenderableType, optional): Renderable content, or None for placeholder. Defaults to None.
|
| 147 |
+
name (str, optional): Optional identifier for Layout. Defaults to None.
|
| 148 |
+
size (int, optional): Optional fixed size of layout. Defaults to None.
|
| 149 |
+
minimum_size (int, optional): Minimum size of layout. Defaults to 1.
|
| 150 |
+
ratio (int, optional): Optional ratio for flexible layout. Defaults to 1.
|
| 151 |
+
visible (bool, optional): Visibility of layout. Defaults to True.
|
| 152 |
+
"""
|
| 153 |
+
|
| 154 |
+
splitters = {"row": RowSplitter, "column": ColumnSplitter}
|
| 155 |
+
|
| 156 |
+
def __init__(
|
| 157 |
+
self,
|
| 158 |
+
renderable: Optional[RenderableType] = None,
|
| 159 |
+
*,
|
| 160 |
+
name: Optional[str] = None,
|
| 161 |
+
size: Optional[int] = None,
|
| 162 |
+
minimum_size: int = 1,
|
| 163 |
+
ratio: int = 1,
|
| 164 |
+
visible: bool = True,
|
| 165 |
+
) -> None:
|
| 166 |
+
self._renderable = renderable or _Placeholder(self)
|
| 167 |
+
self.size = size
|
| 168 |
+
self.minimum_size = minimum_size
|
| 169 |
+
self.ratio = ratio
|
| 170 |
+
self.name = name
|
| 171 |
+
self.visible = visible
|
| 172 |
+
self.splitter: Splitter = self.splitters["column"]()
|
| 173 |
+
self._children: List[Layout] = []
|
| 174 |
+
self._render_map: RenderMap = {}
|
| 175 |
+
self._lock = RLock()
|
| 176 |
+
|
| 177 |
+
def __rich_repr__(self) -> Result:
|
| 178 |
+
yield "name", self.name, None
|
| 179 |
+
yield "size", self.size, None
|
| 180 |
+
yield "minimum_size", self.minimum_size, 1
|
| 181 |
+
yield "ratio", self.ratio, 1
|
| 182 |
+
|
| 183 |
+
@property
|
| 184 |
+
def renderable(self) -> RenderableType:
|
| 185 |
+
"""Layout renderable."""
|
| 186 |
+
return self if self._children else self._renderable
|
| 187 |
+
|
| 188 |
+
@property
|
| 189 |
+
def children(self) -> List["Layout"]:
|
| 190 |
+
"""Gets (visible) layout children."""
|
| 191 |
+
return [child for child in self._children if child.visible]
|
| 192 |
+
|
| 193 |
+
@property
|
| 194 |
+
def map(self) -> RenderMap:
|
| 195 |
+
"""Get a map of the last render."""
|
| 196 |
+
return self._render_map
|
| 197 |
+
|
| 198 |
+
def get(self, name: str) -> Optional["Layout"]:
|
| 199 |
+
"""Get a named layout, or None if it doesn't exist.
|
| 200 |
+
|
| 201 |
+
Args:
|
| 202 |
+
name (str): Name of layout.
|
| 203 |
+
|
| 204 |
+
Returns:
|
| 205 |
+
Optional[Layout]: Layout instance or None if no layout was found.
|
| 206 |
+
"""
|
| 207 |
+
if self.name == name:
|
| 208 |
+
return self
|
| 209 |
+
else:
|
| 210 |
+
for child in self._children:
|
| 211 |
+
named_layout = child.get(name)
|
| 212 |
+
if named_layout is not None:
|
| 213 |
+
return named_layout
|
| 214 |
+
return None
|
| 215 |
+
|
| 216 |
+
def __getitem__(self, name: str) -> "Layout":
|
| 217 |
+
layout = self.get(name)
|
| 218 |
+
if layout is None:
|
| 219 |
+
raise KeyError(f"No layout with name {name!r}")
|
| 220 |
+
return layout
|
| 221 |
+
|
| 222 |
+
@property
|
| 223 |
+
def tree(self) -> "Tree":
|
| 224 |
+
"""Get a tree renderable to show layout structure."""
|
| 225 |
+
from rich.styled import Styled
|
| 226 |
+
from rich.table import Table
|
| 227 |
+
from rich.tree import Tree
|
| 228 |
+
|
| 229 |
+
def summary(layout: "Layout") -> Table:
|
| 230 |
+
icon = layout.splitter.get_tree_icon()
|
| 231 |
+
|
| 232 |
+
table = Table.grid(padding=(0, 1, 0, 0))
|
| 233 |
+
|
| 234 |
+
text: RenderableType = (
|
| 235 |
+
Pretty(layout) if layout.visible else Styled(Pretty(layout), "dim")
|
| 236 |
+
)
|
| 237 |
+
table.add_row(icon, text)
|
| 238 |
+
_summary = table
|
| 239 |
+
return _summary
|
| 240 |
+
|
| 241 |
+
layout = self
|
| 242 |
+
tree = Tree(
|
| 243 |
+
summary(layout),
|
| 244 |
+
guide_style=f"layout.tree.{layout.splitter.name}",
|
| 245 |
+
highlight=True,
|
| 246 |
+
)
|
| 247 |
+
|
| 248 |
+
def recurse(tree: "Tree", layout: "Layout") -> None:
|
| 249 |
+
for child in layout._children:
|
| 250 |
+
recurse(
|
| 251 |
+
tree.add(
|
| 252 |
+
summary(child),
|
| 253 |
+
guide_style=f"layout.tree.{child.splitter.name}",
|
| 254 |
+
),
|
| 255 |
+
child,
|
| 256 |
+
)
|
| 257 |
+
|
| 258 |
+
recurse(tree, self)
|
| 259 |
+
return tree
|
| 260 |
+
|
| 261 |
+
def split(
|
| 262 |
+
self,
|
| 263 |
+
*layouts: Union["Layout", RenderableType],
|
| 264 |
+
splitter: Union[Splitter, str] = "column",
|
| 265 |
+
) -> None:
|
| 266 |
+
"""Split the layout in to multiple sub-layouts.
|
| 267 |
+
|
| 268 |
+
Args:
|
| 269 |
+
*layouts (Layout): Positional arguments should be (sub) Layout instances.
|
| 270 |
+
splitter (Union[Splitter, str]): Splitter instance or name of splitter.
|
| 271 |
+
"""
|
| 272 |
+
_layouts = [
|
| 273 |
+
layout if isinstance(layout, Layout) else Layout(layout)
|
| 274 |
+
for layout in layouts
|
| 275 |
+
]
|
| 276 |
+
try:
|
| 277 |
+
self.splitter = (
|
| 278 |
+
splitter
|
| 279 |
+
if isinstance(splitter, Splitter)
|
| 280 |
+
else self.splitters[splitter]()
|
| 281 |
+
)
|
| 282 |
+
except KeyError:
|
| 283 |
+
raise NoSplitter(f"No splitter called {splitter!r}")
|
| 284 |
+
self._children[:] = _layouts
|
| 285 |
+
|
| 286 |
+
def add_split(self, *layouts: Union["Layout", RenderableType]) -> None:
|
| 287 |
+
"""Add a new layout(s) to existing split.
|
| 288 |
+
|
| 289 |
+
Args:
|
| 290 |
+
*layouts (Union[Layout, RenderableType]): Positional arguments should be renderables or (sub) Layout instances.
|
| 291 |
+
|
| 292 |
+
"""
|
| 293 |
+
_layouts = (
|
| 294 |
+
layout if isinstance(layout, Layout) else Layout(layout)
|
| 295 |
+
for layout in layouts
|
| 296 |
+
)
|
| 297 |
+
self._children.extend(_layouts)
|
| 298 |
+
|
| 299 |
+
def split_row(self, *layouts: Union["Layout", RenderableType]) -> None:
|
| 300 |
+
"""Split the layout in to a row (layouts side by side).
|
| 301 |
+
|
| 302 |
+
Args:
|
| 303 |
+
*layouts (Layout): Positional arguments should be (sub) Layout instances.
|
| 304 |
+
"""
|
| 305 |
+
self.split(*layouts, splitter="row")
|
| 306 |
+
|
| 307 |
+
def split_column(self, *layouts: Union["Layout", RenderableType]) -> None:
|
| 308 |
+
"""Split the layout in to a column (layouts stacked on top of each other).
|
| 309 |
+
|
| 310 |
+
Args:
|
| 311 |
+
*layouts (Layout): Positional arguments should be (sub) Layout instances.
|
| 312 |
+
"""
|
| 313 |
+
self.split(*layouts, splitter="column")
|
| 314 |
+
|
| 315 |
+
def unsplit(self) -> None:
|
| 316 |
+
"""Reset splits to initial state."""
|
| 317 |
+
del self._children[:]
|
| 318 |
+
|
| 319 |
+
def update(self, renderable: RenderableType) -> None:
|
| 320 |
+
"""Update renderable.
|
| 321 |
+
|
| 322 |
+
Args:
|
| 323 |
+
renderable (RenderableType): New renderable object.
|
| 324 |
+
"""
|
| 325 |
+
with self._lock:
|
| 326 |
+
self._renderable = renderable
|
| 327 |
+
|
| 328 |
+
def refresh_screen(self, console: "Console", layout_name: str) -> None:
|
| 329 |
+
"""Refresh a sub-layout.
|
| 330 |
+
|
| 331 |
+
Args:
|
| 332 |
+
console (Console): Console instance where Layout is to be rendered.
|
| 333 |
+
layout_name (str): Name of layout.
|
| 334 |
+
"""
|
| 335 |
+
with self._lock:
|
| 336 |
+
layout = self[layout_name]
|
| 337 |
+
region, _lines = self._render_map[layout]
|
| 338 |
+
(x, y, width, height) = region
|
| 339 |
+
lines = console.render_lines(
|
| 340 |
+
layout, console.options.update_dimensions(width, height)
|
| 341 |
+
)
|
| 342 |
+
self._render_map[layout] = LayoutRender(region, lines)
|
| 343 |
+
console.update_screen_lines(lines, x, y)
|
| 344 |
+
|
| 345 |
+
def _make_region_map(self, width: int, height: int) -> RegionMap:
|
| 346 |
+
"""Create a dict that maps layout on to Region."""
|
| 347 |
+
stack: List[Tuple[Layout, Region]] = [(self, Region(0, 0, width, height))]
|
| 348 |
+
push = stack.append
|
| 349 |
+
pop = stack.pop
|
| 350 |
+
layout_regions: List[Tuple[Layout, Region]] = []
|
| 351 |
+
append_layout_region = layout_regions.append
|
| 352 |
+
while stack:
|
| 353 |
+
append_layout_region(pop())
|
| 354 |
+
layout, region = layout_regions[-1]
|
| 355 |
+
children = layout.children
|
| 356 |
+
if children:
|
| 357 |
+
for child_and_region in layout.splitter.divide(children, region):
|
| 358 |
+
push(child_and_region)
|
| 359 |
+
|
| 360 |
+
region_map = {
|
| 361 |
+
layout: region
|
| 362 |
+
for layout, region in sorted(layout_regions, key=itemgetter(1))
|
| 363 |
+
}
|
| 364 |
+
return region_map
|
| 365 |
+
|
| 366 |
+
def render(self, console: Console, options: ConsoleOptions) -> RenderMap:
|
| 367 |
+
"""Render the sub_layouts.
|
| 368 |
+
|
| 369 |
+
Args:
|
| 370 |
+
console (Console): Console instance.
|
| 371 |
+
options (ConsoleOptions): Console options.
|
| 372 |
+
|
| 373 |
+
Returns:
|
| 374 |
+
RenderMap: A dict that maps Layout on to a tuple of Region, lines
|
| 375 |
+
"""
|
| 376 |
+
render_width = options.max_width
|
| 377 |
+
render_height = options.height or console.height
|
| 378 |
+
region_map = self._make_region_map(render_width, render_height)
|
| 379 |
+
layout_regions = [
|
| 380 |
+
(layout, region)
|
| 381 |
+
for layout, region in region_map.items()
|
| 382 |
+
if not layout.children
|
| 383 |
+
]
|
| 384 |
+
render_map: Dict["Layout", "LayoutRender"] = {}
|
| 385 |
+
render_lines = console.render_lines
|
| 386 |
+
update_dimensions = options.update_dimensions
|
| 387 |
+
|
| 388 |
+
for layout, region in layout_regions:
|
| 389 |
+
lines = render_lines(
|
| 390 |
+
layout.renderable, update_dimensions(region.width, region.height)
|
| 391 |
+
)
|
| 392 |
+
render_map[layout] = LayoutRender(region, lines)
|
| 393 |
+
return render_map
|
| 394 |
+
|
| 395 |
+
def __rich_console__(
|
| 396 |
+
self, console: Console, options: ConsoleOptions
|
| 397 |
+
) -> RenderResult:
|
| 398 |
+
with self._lock:
|
| 399 |
+
width = options.max_width or console.width
|
| 400 |
+
height = options.height or console.height
|
| 401 |
+
render_map = self.render(console, options.update_dimensions(width, height))
|
| 402 |
+
self._render_map = render_map
|
| 403 |
+
layout_lines: List[List[Segment]] = [[] for _ in range(height)]
|
| 404 |
+
_islice = islice
|
| 405 |
+
for region, lines in render_map.values():
|
| 406 |
+
_x, y, _layout_width, layout_height = region
|
| 407 |
+
for row, line in zip(
|
| 408 |
+
_islice(layout_lines, y, y + layout_height), lines
|
| 409 |
+
):
|
| 410 |
+
row.extend(line)
|
| 411 |
+
|
| 412 |
+
new_line = Segment.line()
|
| 413 |
+
for layout_row in layout_lines:
|
| 414 |
+
yield from layout_row
|
| 415 |
+
yield new_line
|
| 416 |
+
|
| 417 |
+
|
| 418 |
+
if __name__ == "__main__":
|
| 419 |
+
from rich.console import Console
|
| 420 |
+
|
| 421 |
+
console = Console()
|
| 422 |
+
layout = Layout()
|
| 423 |
+
|
| 424 |
+
layout.split_column(
|
| 425 |
+
Layout(name="header", size=3),
|
| 426 |
+
Layout(ratio=1, name="main"),
|
| 427 |
+
Layout(size=10, name="footer"),
|
| 428 |
+
)
|
| 429 |
+
|
| 430 |
+
layout["main"].split_row(Layout(name="side"), Layout(name="body", ratio=2))
|
| 431 |
+
|
| 432 |
+
layout["body"].split_row(Layout(name="content", ratio=2), Layout(name="s2"))
|
| 433 |
+
|
| 434 |
+
layout["s2"].split_column(
|
| 435 |
+
Layout(name="top"), Layout(name="middle"), Layout(name="bottom")
|
| 436 |
+
)
|
| 437 |
+
|
| 438 |
+
layout["side"].split_column(Layout(layout.tree, name="left1"), Layout(name="left2"))
|
| 439 |
+
|
| 440 |
+
layout["content"].update("foo")
|
| 441 |
+
|
| 442 |
+
console.print(layout)
|
miniconda3/lib/python3.13/site-packages/rich/live.py
ADDED
|
@@ -0,0 +1,400 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import sys
|
| 4 |
+
from threading import Event, RLock, Thread
|
| 5 |
+
from types import TracebackType
|
| 6 |
+
from typing import IO, TYPE_CHECKING, Any, Callable, List, Optional, TextIO, Type, cast
|
| 7 |
+
|
| 8 |
+
from . import get_console
|
| 9 |
+
from .console import Console, ConsoleRenderable, Group, RenderableType, RenderHook
|
| 10 |
+
from .control import Control
|
| 11 |
+
from .file_proxy import FileProxy
|
| 12 |
+
from .jupyter import JupyterMixin
|
| 13 |
+
from .live_render import LiveRender, VerticalOverflowMethod
|
| 14 |
+
from .screen import Screen
|
| 15 |
+
from .text import Text
|
| 16 |
+
|
| 17 |
+
if TYPE_CHECKING:
|
| 18 |
+
# Can be replaced with `from typing import Self` in Python 3.11+
|
| 19 |
+
from typing_extensions import Self # pragma: no cover
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class _RefreshThread(Thread):
|
| 23 |
+
"""A thread that calls refresh() at regular intervals."""
|
| 24 |
+
|
| 25 |
+
def __init__(self, live: "Live", refresh_per_second: float) -> None:
|
| 26 |
+
self.live = live
|
| 27 |
+
self.refresh_per_second = refresh_per_second
|
| 28 |
+
self.done = Event()
|
| 29 |
+
super().__init__(daemon=True)
|
| 30 |
+
|
| 31 |
+
def stop(self) -> None:
|
| 32 |
+
self.done.set()
|
| 33 |
+
|
| 34 |
+
def run(self) -> None:
|
| 35 |
+
while not self.done.wait(1 / self.refresh_per_second):
|
| 36 |
+
with self.live._lock:
|
| 37 |
+
if not self.done.is_set():
|
| 38 |
+
self.live.refresh()
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class Live(JupyterMixin, RenderHook):
|
| 42 |
+
"""Renders an auto-updating live display of any given renderable.
|
| 43 |
+
|
| 44 |
+
Args:
|
| 45 |
+
renderable (RenderableType, optional): The renderable to live display. Defaults to displaying nothing.
|
| 46 |
+
console (Console, optional): Optional Console instance. Defaults to an internal Console instance writing to stdout.
|
| 47 |
+
screen (bool, optional): Enable alternate screen mode. Defaults to False.
|
| 48 |
+
auto_refresh (bool, optional): Enable auto refresh. If disabled, you will need to call `refresh()` or `update()` with refresh flag. Defaults to True
|
| 49 |
+
refresh_per_second (float, optional): Number of times per second to refresh the live display. Defaults to 4.
|
| 50 |
+
transient (bool, optional): Clear the renderable on exit (has no effect when screen=True). Defaults to False.
|
| 51 |
+
redirect_stdout (bool, optional): Enable redirection of stdout, so ``print`` may be used. Defaults to True.
|
| 52 |
+
redirect_stderr (bool, optional): Enable redirection of stderr. Defaults to True.
|
| 53 |
+
vertical_overflow (VerticalOverflowMethod, optional): How to handle renderable when it is too tall for the console. Defaults to "ellipsis".
|
| 54 |
+
get_renderable (Callable[[], RenderableType], optional): Optional callable to get renderable. Defaults to None.
|
| 55 |
+
"""
|
| 56 |
+
|
| 57 |
+
def __init__(
|
| 58 |
+
self,
|
| 59 |
+
renderable: Optional[RenderableType] = None,
|
| 60 |
+
*,
|
| 61 |
+
console: Optional[Console] = None,
|
| 62 |
+
screen: bool = False,
|
| 63 |
+
auto_refresh: bool = True,
|
| 64 |
+
refresh_per_second: float = 4,
|
| 65 |
+
transient: bool = False,
|
| 66 |
+
redirect_stdout: bool = True,
|
| 67 |
+
redirect_stderr: bool = True,
|
| 68 |
+
vertical_overflow: VerticalOverflowMethod = "ellipsis",
|
| 69 |
+
get_renderable: Optional[Callable[[], RenderableType]] = None,
|
| 70 |
+
) -> None:
|
| 71 |
+
assert refresh_per_second > 0, "refresh_per_second must be > 0"
|
| 72 |
+
self._renderable = renderable
|
| 73 |
+
self.console = console if console is not None else get_console()
|
| 74 |
+
self._screen = screen
|
| 75 |
+
self._alt_screen = False
|
| 76 |
+
|
| 77 |
+
self._redirect_stdout = redirect_stdout
|
| 78 |
+
self._redirect_stderr = redirect_stderr
|
| 79 |
+
self._restore_stdout: Optional[IO[str]] = None
|
| 80 |
+
self._restore_stderr: Optional[IO[str]] = None
|
| 81 |
+
|
| 82 |
+
self._lock = RLock()
|
| 83 |
+
self.ipy_widget: Optional[Any] = None
|
| 84 |
+
self.auto_refresh = auto_refresh
|
| 85 |
+
self._started: bool = False
|
| 86 |
+
self.transient = True if screen else transient
|
| 87 |
+
|
| 88 |
+
self._refresh_thread: Optional[_RefreshThread] = None
|
| 89 |
+
self.refresh_per_second = refresh_per_second
|
| 90 |
+
|
| 91 |
+
self.vertical_overflow = vertical_overflow
|
| 92 |
+
self._get_renderable = get_renderable
|
| 93 |
+
self._live_render = LiveRender(
|
| 94 |
+
self.get_renderable(), vertical_overflow=vertical_overflow
|
| 95 |
+
)
|
| 96 |
+
self._nested = False
|
| 97 |
+
|
| 98 |
+
@property
|
| 99 |
+
def is_started(self) -> bool:
|
| 100 |
+
"""Check if live display has been started."""
|
| 101 |
+
return self._started
|
| 102 |
+
|
| 103 |
+
def get_renderable(self) -> RenderableType:
|
| 104 |
+
renderable = (
|
| 105 |
+
self._get_renderable()
|
| 106 |
+
if self._get_renderable is not None
|
| 107 |
+
else self._renderable
|
| 108 |
+
)
|
| 109 |
+
return renderable or ""
|
| 110 |
+
|
| 111 |
+
def start(self, refresh: bool = False) -> None:
|
| 112 |
+
"""Start live rendering display.
|
| 113 |
+
|
| 114 |
+
Args:
|
| 115 |
+
refresh (bool, optional): Also refresh. Defaults to False.
|
| 116 |
+
"""
|
| 117 |
+
with self._lock:
|
| 118 |
+
if self._started:
|
| 119 |
+
return
|
| 120 |
+
self._started = True
|
| 121 |
+
|
| 122 |
+
if not self.console.set_live(self):
|
| 123 |
+
self._nested = True
|
| 124 |
+
return
|
| 125 |
+
|
| 126 |
+
if self._screen:
|
| 127 |
+
self._alt_screen = self.console.set_alt_screen(True)
|
| 128 |
+
self.console.show_cursor(False)
|
| 129 |
+
self._enable_redirect_io()
|
| 130 |
+
self.console.push_render_hook(self)
|
| 131 |
+
if refresh:
|
| 132 |
+
try:
|
| 133 |
+
self.refresh()
|
| 134 |
+
except Exception:
|
| 135 |
+
# If refresh fails, we want to stop the redirection of sys.stderr,
|
| 136 |
+
# so the error stacktrace is properly displayed in the terminal.
|
| 137 |
+
# (or, if the code that calls Rich captures the exception and wants to display something,
|
| 138 |
+
# let this be displayed in the terminal).
|
| 139 |
+
self.stop()
|
| 140 |
+
raise
|
| 141 |
+
if self.auto_refresh:
|
| 142 |
+
self._refresh_thread = _RefreshThread(self, self.refresh_per_second)
|
| 143 |
+
self._refresh_thread.start()
|
| 144 |
+
|
| 145 |
+
def stop(self) -> None:
|
| 146 |
+
"""Stop live rendering display."""
|
| 147 |
+
with self._lock:
|
| 148 |
+
if not self._started:
|
| 149 |
+
return
|
| 150 |
+
self._started = False
|
| 151 |
+
self.console.clear_live()
|
| 152 |
+
if self._nested:
|
| 153 |
+
if not self.transient:
|
| 154 |
+
self.console.print(self.renderable)
|
| 155 |
+
return
|
| 156 |
+
|
| 157 |
+
if self.auto_refresh and self._refresh_thread is not None:
|
| 158 |
+
self._refresh_thread.stop()
|
| 159 |
+
self._refresh_thread = None
|
| 160 |
+
# allow it to fully render on the last even if overflow
|
| 161 |
+
self.vertical_overflow = "visible"
|
| 162 |
+
with self.console:
|
| 163 |
+
try:
|
| 164 |
+
if not self._alt_screen and not self.console.is_jupyter:
|
| 165 |
+
self.refresh()
|
| 166 |
+
finally:
|
| 167 |
+
self._disable_redirect_io()
|
| 168 |
+
self.console.pop_render_hook()
|
| 169 |
+
if not self._alt_screen and self.console.is_terminal:
|
| 170 |
+
self.console.line()
|
| 171 |
+
self.console.show_cursor(True)
|
| 172 |
+
if self._alt_screen:
|
| 173 |
+
self.console.set_alt_screen(False)
|
| 174 |
+
if self.transient and not self._alt_screen:
|
| 175 |
+
self.console.control(self._live_render.restore_cursor())
|
| 176 |
+
if self.ipy_widget is not None and self.transient:
|
| 177 |
+
self.ipy_widget.close() # pragma: no cover
|
| 178 |
+
|
| 179 |
+
def __enter__(self) -> Self:
|
| 180 |
+
self.start(refresh=self._renderable is not None)
|
| 181 |
+
return self
|
| 182 |
+
|
| 183 |
+
def __exit__(
|
| 184 |
+
self,
|
| 185 |
+
exc_type: Optional[Type[BaseException]],
|
| 186 |
+
exc_val: Optional[BaseException],
|
| 187 |
+
exc_tb: Optional[TracebackType],
|
| 188 |
+
) -> None:
|
| 189 |
+
self.stop()
|
| 190 |
+
|
| 191 |
+
def _enable_redirect_io(self) -> None:
|
| 192 |
+
"""Enable redirecting of stdout / stderr."""
|
| 193 |
+
if self.console.is_terminal or self.console.is_jupyter:
|
| 194 |
+
if self._redirect_stdout and not isinstance(sys.stdout, FileProxy):
|
| 195 |
+
self._restore_stdout = sys.stdout
|
| 196 |
+
sys.stdout = cast("TextIO", FileProxy(self.console, sys.stdout))
|
| 197 |
+
if self._redirect_stderr and not isinstance(sys.stderr, FileProxy):
|
| 198 |
+
self._restore_stderr = sys.stderr
|
| 199 |
+
sys.stderr = cast("TextIO", FileProxy(self.console, sys.stderr))
|
| 200 |
+
|
| 201 |
+
def _disable_redirect_io(self) -> None:
|
| 202 |
+
"""Disable redirecting of stdout / stderr."""
|
| 203 |
+
if self._restore_stdout:
|
| 204 |
+
sys.stdout = cast("TextIO", self._restore_stdout)
|
| 205 |
+
self._restore_stdout = None
|
| 206 |
+
if self._restore_stderr:
|
| 207 |
+
sys.stderr = cast("TextIO", self._restore_stderr)
|
| 208 |
+
self._restore_stderr = None
|
| 209 |
+
|
| 210 |
+
@property
|
| 211 |
+
def renderable(self) -> RenderableType:
|
| 212 |
+
"""Get the renderable that is being displayed
|
| 213 |
+
|
| 214 |
+
Returns:
|
| 215 |
+
RenderableType: Displayed renderable.
|
| 216 |
+
"""
|
| 217 |
+
live_stack = self.console._live_stack
|
| 218 |
+
renderable: RenderableType
|
| 219 |
+
if live_stack and self is live_stack[0]:
|
| 220 |
+
# The first Live instance will render everything in the Live stack
|
| 221 |
+
renderable = Group(*[live.get_renderable() for live in live_stack])
|
| 222 |
+
else:
|
| 223 |
+
renderable = self.get_renderable()
|
| 224 |
+
return Screen(renderable) if self._alt_screen else renderable
|
| 225 |
+
|
| 226 |
+
def update(self, renderable: RenderableType, *, refresh: bool = False) -> None:
|
| 227 |
+
"""Update the renderable that is being displayed
|
| 228 |
+
|
| 229 |
+
Args:
|
| 230 |
+
renderable (RenderableType): New renderable to use.
|
| 231 |
+
refresh (bool, optional): Refresh the display. Defaults to False.
|
| 232 |
+
"""
|
| 233 |
+
if isinstance(renderable, str):
|
| 234 |
+
renderable = self.console.render_str(renderable)
|
| 235 |
+
with self._lock:
|
| 236 |
+
self._renderable = renderable
|
| 237 |
+
if refresh:
|
| 238 |
+
self.refresh()
|
| 239 |
+
|
| 240 |
+
def refresh(self) -> None:
|
| 241 |
+
"""Update the display of the Live Render."""
|
| 242 |
+
with self._lock:
|
| 243 |
+
self._live_render.set_renderable(self.renderable)
|
| 244 |
+
if self._nested:
|
| 245 |
+
if self.console._live_stack:
|
| 246 |
+
self.console._live_stack[0].refresh()
|
| 247 |
+
return
|
| 248 |
+
|
| 249 |
+
if self.console.is_jupyter: # pragma: no cover
|
| 250 |
+
try:
|
| 251 |
+
from IPython.display import display
|
| 252 |
+
from ipywidgets import Output
|
| 253 |
+
except ImportError:
|
| 254 |
+
import warnings
|
| 255 |
+
|
| 256 |
+
warnings.warn('install "ipywidgets" for Jupyter support')
|
| 257 |
+
else:
|
| 258 |
+
if self.ipy_widget is None:
|
| 259 |
+
self.ipy_widget = Output()
|
| 260 |
+
display(self.ipy_widget)
|
| 261 |
+
|
| 262 |
+
with self.ipy_widget:
|
| 263 |
+
self.ipy_widget.clear_output(wait=True)
|
| 264 |
+
self.console.print(self._live_render.renderable)
|
| 265 |
+
elif self.console.is_terminal and not self.console.is_dumb_terminal:
|
| 266 |
+
with self.console:
|
| 267 |
+
self.console.print(Control())
|
| 268 |
+
elif (
|
| 269 |
+
not self._started and not self.transient
|
| 270 |
+
): # if it is finished allow files or dumb-terminals to see final result
|
| 271 |
+
with self.console:
|
| 272 |
+
self.console.print(Control())
|
| 273 |
+
|
| 274 |
+
def process_renderables(
|
| 275 |
+
self, renderables: List[ConsoleRenderable]
|
| 276 |
+
) -> List[ConsoleRenderable]:
|
| 277 |
+
"""Process renderables to restore cursor and display progress."""
|
| 278 |
+
self._live_render.vertical_overflow = self.vertical_overflow
|
| 279 |
+
if self.console.is_interactive:
|
| 280 |
+
# lock needs acquiring as user can modify live_render renderable at any time unlike in Progress.
|
| 281 |
+
with self._lock:
|
| 282 |
+
reset = (
|
| 283 |
+
Control.home()
|
| 284 |
+
if self._alt_screen
|
| 285 |
+
else self._live_render.position_cursor()
|
| 286 |
+
)
|
| 287 |
+
renderables = [reset, *renderables, self._live_render]
|
| 288 |
+
elif (
|
| 289 |
+
not self._started and not self.transient
|
| 290 |
+
): # if it is finished render the final output for files or dumb_terminals
|
| 291 |
+
renderables = [*renderables, self._live_render]
|
| 292 |
+
|
| 293 |
+
return renderables
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
if __name__ == "__main__": # pragma: no cover
|
| 297 |
+
import random
|
| 298 |
+
import time
|
| 299 |
+
from itertools import cycle
|
| 300 |
+
from typing import Dict, List, Tuple
|
| 301 |
+
|
| 302 |
+
from .align import Align
|
| 303 |
+
from .console import Console
|
| 304 |
+
from .live import Live as Live
|
| 305 |
+
from .panel import Panel
|
| 306 |
+
from .rule import Rule
|
| 307 |
+
from .syntax import Syntax
|
| 308 |
+
from .table import Table
|
| 309 |
+
|
| 310 |
+
console = Console()
|
| 311 |
+
|
| 312 |
+
syntax = Syntax(
|
| 313 |
+
'''def loop_last(values: Iterable[T]) -> Iterable[Tuple[bool, T]]:
|
| 314 |
+
"""Iterate and generate a tuple with a flag for last value."""
|
| 315 |
+
iter_values = iter(values)
|
| 316 |
+
try:
|
| 317 |
+
previous_value = next(iter_values)
|
| 318 |
+
except StopIteration:
|
| 319 |
+
return
|
| 320 |
+
for value in iter_values:
|
| 321 |
+
yield False, previous_value
|
| 322 |
+
previous_value = value
|
| 323 |
+
yield True, previous_value''',
|
| 324 |
+
"python",
|
| 325 |
+
line_numbers=True,
|
| 326 |
+
)
|
| 327 |
+
|
| 328 |
+
table = Table("foo", "bar", "baz")
|
| 329 |
+
table.add_row("1", "2", "3")
|
| 330 |
+
|
| 331 |
+
progress_renderables = [
|
| 332 |
+
"You can make the terminal shorter and taller to see the live table hide"
|
| 333 |
+
"Text may be printed while the progress bars are rendering.",
|
| 334 |
+
Panel("In fact, [i]any[/i] renderable will work"),
|
| 335 |
+
"Such as [magenta]tables[/]...",
|
| 336 |
+
table,
|
| 337 |
+
"Pretty printed structures...",
|
| 338 |
+
{"type": "example", "text": "Pretty printed"},
|
| 339 |
+
"Syntax...",
|
| 340 |
+
syntax,
|
| 341 |
+
Rule("Give it a try!"),
|
| 342 |
+
]
|
| 343 |
+
|
| 344 |
+
examples = cycle(progress_renderables)
|
| 345 |
+
|
| 346 |
+
exchanges = [
|
| 347 |
+
"SGD",
|
| 348 |
+
"MYR",
|
| 349 |
+
"EUR",
|
| 350 |
+
"USD",
|
| 351 |
+
"AUD",
|
| 352 |
+
"JPY",
|
| 353 |
+
"CNH",
|
| 354 |
+
"HKD",
|
| 355 |
+
"CAD",
|
| 356 |
+
"INR",
|
| 357 |
+
"DKK",
|
| 358 |
+
"GBP",
|
| 359 |
+
"RUB",
|
| 360 |
+
"NZD",
|
| 361 |
+
"MXN",
|
| 362 |
+
"IDR",
|
| 363 |
+
"TWD",
|
| 364 |
+
"THB",
|
| 365 |
+
"VND",
|
| 366 |
+
]
|
| 367 |
+
with Live(console=console) as live_table:
|
| 368 |
+
exchange_rate_dict: Dict[Tuple[str, str], float] = {}
|
| 369 |
+
|
| 370 |
+
for index in range(100):
|
| 371 |
+
select_exchange = exchanges[index % len(exchanges)]
|
| 372 |
+
|
| 373 |
+
for exchange in exchanges:
|
| 374 |
+
if exchange == select_exchange:
|
| 375 |
+
continue
|
| 376 |
+
time.sleep(0.4)
|
| 377 |
+
if random.randint(0, 10) < 1:
|
| 378 |
+
console.log(next(examples))
|
| 379 |
+
exchange_rate_dict[(select_exchange, exchange)] = 200 / (
|
| 380 |
+
(random.random() * 320) + 1
|
| 381 |
+
)
|
| 382 |
+
if len(exchange_rate_dict) > len(exchanges) - 1:
|
| 383 |
+
exchange_rate_dict.pop(list(exchange_rate_dict.keys())[0])
|
| 384 |
+
table = Table(title="Exchange Rates")
|
| 385 |
+
|
| 386 |
+
table.add_column("Source Currency")
|
| 387 |
+
table.add_column("Destination Currency")
|
| 388 |
+
table.add_column("Exchange Rate")
|
| 389 |
+
|
| 390 |
+
for (source, dest), exchange_rate in exchange_rate_dict.items():
|
| 391 |
+
table.add_row(
|
| 392 |
+
source,
|
| 393 |
+
dest,
|
| 394 |
+
Text(
|
| 395 |
+
f"{exchange_rate:.4f}",
|
| 396 |
+
style="red" if exchange_rate < 1.0 else "green",
|
| 397 |
+
),
|
| 398 |
+
)
|
| 399 |
+
|
| 400 |
+
live_table.update(Align.center(table))
|
miniconda3/lib/python3.13/site-packages/rich/live_render.py
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Optional, Tuple, Literal
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
from ._loop import loop_last
|
| 5 |
+
from .console import Console, ConsoleOptions, RenderableType, RenderResult
|
| 6 |
+
from .control import Control
|
| 7 |
+
from .segment import ControlType, Segment
|
| 8 |
+
from .style import StyleType
|
| 9 |
+
from .text import Text
|
| 10 |
+
|
| 11 |
+
VerticalOverflowMethod = Literal["crop", "ellipsis", "visible"]
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class LiveRender:
|
| 15 |
+
"""Creates a renderable that may be updated.
|
| 16 |
+
|
| 17 |
+
Args:
|
| 18 |
+
renderable (RenderableType): Any renderable object.
|
| 19 |
+
style (StyleType, optional): An optional style to apply to the renderable. Defaults to "".
|
| 20 |
+
"""
|
| 21 |
+
|
| 22 |
+
def __init__(
|
| 23 |
+
self,
|
| 24 |
+
renderable: RenderableType,
|
| 25 |
+
style: StyleType = "",
|
| 26 |
+
vertical_overflow: VerticalOverflowMethod = "ellipsis",
|
| 27 |
+
) -> None:
|
| 28 |
+
self.renderable = renderable
|
| 29 |
+
self.style = style
|
| 30 |
+
self.vertical_overflow = vertical_overflow
|
| 31 |
+
self._shape: Optional[Tuple[int, int]] = None
|
| 32 |
+
|
| 33 |
+
def set_renderable(self, renderable: RenderableType) -> None:
|
| 34 |
+
"""Set a new renderable.
|
| 35 |
+
|
| 36 |
+
Args:
|
| 37 |
+
renderable (RenderableType): Any renderable object, including str.
|
| 38 |
+
"""
|
| 39 |
+
self.renderable = renderable
|
| 40 |
+
|
| 41 |
+
def position_cursor(self) -> Control:
|
| 42 |
+
"""Get control codes to move cursor to beginning of live render.
|
| 43 |
+
|
| 44 |
+
Returns:
|
| 45 |
+
Control: A control instance that may be printed.
|
| 46 |
+
"""
|
| 47 |
+
if self._shape is not None:
|
| 48 |
+
_, height = self._shape
|
| 49 |
+
return Control(
|
| 50 |
+
ControlType.CARRIAGE_RETURN,
|
| 51 |
+
(ControlType.ERASE_IN_LINE, 2),
|
| 52 |
+
*(
|
| 53 |
+
(
|
| 54 |
+
(ControlType.CURSOR_UP, 1),
|
| 55 |
+
(ControlType.ERASE_IN_LINE, 2),
|
| 56 |
+
)
|
| 57 |
+
* (height - 1)
|
| 58 |
+
)
|
| 59 |
+
)
|
| 60 |
+
return Control()
|
| 61 |
+
|
| 62 |
+
def restore_cursor(self) -> Control:
|
| 63 |
+
"""Get control codes to clear the render and restore the cursor to its previous position.
|
| 64 |
+
|
| 65 |
+
Returns:
|
| 66 |
+
Control: A Control instance that may be printed.
|
| 67 |
+
"""
|
| 68 |
+
if self._shape is not None:
|
| 69 |
+
_, height = self._shape
|
| 70 |
+
return Control(
|
| 71 |
+
ControlType.CARRIAGE_RETURN,
|
| 72 |
+
*((ControlType.CURSOR_UP, 1), (ControlType.ERASE_IN_LINE, 2)) * height
|
| 73 |
+
)
|
| 74 |
+
return Control()
|
| 75 |
+
|
| 76 |
+
def __rich_console__(
|
| 77 |
+
self, console: Console, options: ConsoleOptions
|
| 78 |
+
) -> RenderResult:
|
| 79 |
+
renderable = self.renderable
|
| 80 |
+
style = console.get_style(self.style)
|
| 81 |
+
lines = console.render_lines(renderable, options, style=style, pad=False)
|
| 82 |
+
shape = Segment.get_shape(lines)
|
| 83 |
+
|
| 84 |
+
_, height = shape
|
| 85 |
+
if height > options.size.height:
|
| 86 |
+
if self.vertical_overflow == "crop":
|
| 87 |
+
lines = lines[: options.size.height]
|
| 88 |
+
shape = Segment.get_shape(lines)
|
| 89 |
+
elif self.vertical_overflow == "ellipsis":
|
| 90 |
+
lines = lines[: (options.size.height - 1)]
|
| 91 |
+
overflow_text = Text(
|
| 92 |
+
"...",
|
| 93 |
+
overflow="crop",
|
| 94 |
+
justify="center",
|
| 95 |
+
end="",
|
| 96 |
+
style="live.ellipsis",
|
| 97 |
+
)
|
| 98 |
+
lines.append(list(console.render(overflow_text)))
|
| 99 |
+
shape = Segment.get_shape(lines)
|
| 100 |
+
self._shape = shape
|
| 101 |
+
|
| 102 |
+
new_line = Segment.line()
|
| 103 |
+
for last, line in loop_last(lines):
|
| 104 |
+
yield from line
|
| 105 |
+
if not last:
|
| 106 |
+
yield new_line
|
miniconda3/lib/python3.13/site-packages/rich/logging.py
ADDED
|
@@ -0,0 +1,297 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
from datetime import datetime
|
| 3 |
+
from logging import Handler, LogRecord
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
from types import ModuleType
|
| 6 |
+
from typing import ClassVar, Iterable, List, Optional, Type, Union
|
| 7 |
+
|
| 8 |
+
from rich._null_file import NullFile
|
| 9 |
+
|
| 10 |
+
from . import get_console
|
| 11 |
+
from ._log_render import FormatTimeCallable, LogRender
|
| 12 |
+
from .console import Console, ConsoleRenderable
|
| 13 |
+
from .highlighter import Highlighter, ReprHighlighter
|
| 14 |
+
from .text import Text
|
| 15 |
+
from .traceback import Traceback
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class RichHandler(Handler):
|
| 19 |
+
"""A logging handler that renders output with Rich. The time / level / message and file are displayed in columns.
|
| 20 |
+
The level is color coded, and the message is syntax highlighted.
|
| 21 |
+
|
| 22 |
+
Note:
|
| 23 |
+
Be careful when enabling console markup in log messages if you have configured logging for libraries not
|
| 24 |
+
under your control. If a dependency writes messages containing square brackets, it may not produce the intended output.
|
| 25 |
+
|
| 26 |
+
Args:
|
| 27 |
+
level (Union[int, str], optional): Log level. Defaults to logging.NOTSET.
|
| 28 |
+
console (:class:`~rich.console.Console`, optional): Optional console instance to write logs.
|
| 29 |
+
Default will use a global console instance writing to stdout.
|
| 30 |
+
show_time (bool, optional): Show a column for the time. Defaults to True.
|
| 31 |
+
omit_repeated_times (bool, optional): Omit repetition of the same time. Defaults to True.
|
| 32 |
+
show_level (bool, optional): Show a column for the level. Defaults to True.
|
| 33 |
+
show_path (bool, optional): Show the path to the original log call. Defaults to True.
|
| 34 |
+
enable_link_path (bool, optional): Enable terminal link of path column to file. Defaults to True.
|
| 35 |
+
highlighter (Highlighter, optional): Highlighter to style log messages, or None to use ReprHighlighter. Defaults to None.
|
| 36 |
+
markup (bool, optional): Enable console markup in log messages. Defaults to False.
|
| 37 |
+
rich_tracebacks (bool, optional): Enable rich tracebacks with syntax highlighting and formatting. Defaults to False.
|
| 38 |
+
tracebacks_width (Optional[int], optional): Number of characters used to render tracebacks, or None for full width. Defaults to None.
|
| 39 |
+
tracebacks_code_width (int, optional): Number of code characters used to render tracebacks, or None for full width. Defaults to 88.
|
| 40 |
+
tracebacks_extra_lines (int, optional): Additional lines of code to render tracebacks, or None for full width. Defaults to None.
|
| 41 |
+
tracebacks_theme (str, optional): Override pygments theme used in traceback.
|
| 42 |
+
tracebacks_word_wrap (bool, optional): Enable word wrapping of long tracebacks lines. Defaults to True.
|
| 43 |
+
tracebacks_show_locals (bool, optional): Enable display of locals in tracebacks. Defaults to False.
|
| 44 |
+
tracebacks_suppress (Sequence[Union[str, ModuleType]]): Optional sequence of modules or paths to exclude from traceback.
|
| 45 |
+
tracebacks_max_frames (int, optional): Optional maximum number of frames returned by traceback.
|
| 46 |
+
locals_max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation.
|
| 47 |
+
Defaults to 10.
|
| 48 |
+
locals_max_string (int, optional): Maximum length of string before truncating, or None to disable. Defaults to 80.
|
| 49 |
+
log_time_format (Union[str, TimeFormatterCallable], optional): If ``log_time`` is enabled, either string for strftime or callable that formats the time. Defaults to "[%x %X] ".
|
| 50 |
+
keywords (List[str], optional): List of words to highlight instead of ``RichHandler.KEYWORDS``.
|
| 51 |
+
"""
|
| 52 |
+
|
| 53 |
+
KEYWORDS: ClassVar[Optional[List[str]]] = [
|
| 54 |
+
"GET",
|
| 55 |
+
"POST",
|
| 56 |
+
"HEAD",
|
| 57 |
+
"PUT",
|
| 58 |
+
"DELETE",
|
| 59 |
+
"OPTIONS",
|
| 60 |
+
"TRACE",
|
| 61 |
+
"PATCH",
|
| 62 |
+
]
|
| 63 |
+
HIGHLIGHTER_CLASS: ClassVar[Type[Highlighter]] = ReprHighlighter
|
| 64 |
+
|
| 65 |
+
def __init__(
|
| 66 |
+
self,
|
| 67 |
+
level: Union[int, str] = logging.NOTSET,
|
| 68 |
+
console: Optional[Console] = None,
|
| 69 |
+
*,
|
| 70 |
+
show_time: bool = True,
|
| 71 |
+
omit_repeated_times: bool = True,
|
| 72 |
+
show_level: bool = True,
|
| 73 |
+
show_path: bool = True,
|
| 74 |
+
enable_link_path: bool = True,
|
| 75 |
+
highlighter: Optional[Highlighter] = None,
|
| 76 |
+
markup: bool = False,
|
| 77 |
+
rich_tracebacks: bool = False,
|
| 78 |
+
tracebacks_width: Optional[int] = None,
|
| 79 |
+
tracebacks_code_width: Optional[int] = 88,
|
| 80 |
+
tracebacks_extra_lines: int = 3,
|
| 81 |
+
tracebacks_theme: Optional[str] = None,
|
| 82 |
+
tracebacks_word_wrap: bool = True,
|
| 83 |
+
tracebacks_show_locals: bool = False,
|
| 84 |
+
tracebacks_suppress: Iterable[Union[str, ModuleType]] = (),
|
| 85 |
+
tracebacks_max_frames: int = 100,
|
| 86 |
+
locals_max_length: int = 10,
|
| 87 |
+
locals_max_string: int = 80,
|
| 88 |
+
log_time_format: Union[str, FormatTimeCallable] = "[%x %X]",
|
| 89 |
+
keywords: Optional[List[str]] = None,
|
| 90 |
+
) -> None:
|
| 91 |
+
super().__init__(level=level)
|
| 92 |
+
self.console = console or get_console()
|
| 93 |
+
self.highlighter = highlighter or self.HIGHLIGHTER_CLASS()
|
| 94 |
+
self._log_render = LogRender(
|
| 95 |
+
show_time=show_time,
|
| 96 |
+
show_level=show_level,
|
| 97 |
+
show_path=show_path,
|
| 98 |
+
time_format=log_time_format,
|
| 99 |
+
omit_repeated_times=omit_repeated_times,
|
| 100 |
+
level_width=None,
|
| 101 |
+
)
|
| 102 |
+
self.enable_link_path = enable_link_path
|
| 103 |
+
self.markup = markup
|
| 104 |
+
self.rich_tracebacks = rich_tracebacks
|
| 105 |
+
self.tracebacks_width = tracebacks_width
|
| 106 |
+
self.tracebacks_extra_lines = tracebacks_extra_lines
|
| 107 |
+
self.tracebacks_theme = tracebacks_theme
|
| 108 |
+
self.tracebacks_word_wrap = tracebacks_word_wrap
|
| 109 |
+
self.tracebacks_show_locals = tracebacks_show_locals
|
| 110 |
+
self.tracebacks_suppress = tracebacks_suppress
|
| 111 |
+
self.tracebacks_max_frames = tracebacks_max_frames
|
| 112 |
+
self.tracebacks_code_width = tracebacks_code_width
|
| 113 |
+
self.locals_max_length = locals_max_length
|
| 114 |
+
self.locals_max_string = locals_max_string
|
| 115 |
+
self.keywords = keywords
|
| 116 |
+
|
| 117 |
+
def get_level_text(self, record: LogRecord) -> Text:
|
| 118 |
+
"""Get the level name from the record.
|
| 119 |
+
|
| 120 |
+
Args:
|
| 121 |
+
record (LogRecord): LogRecord instance.
|
| 122 |
+
|
| 123 |
+
Returns:
|
| 124 |
+
Text: A tuple of the style and level name.
|
| 125 |
+
"""
|
| 126 |
+
level_name = record.levelname
|
| 127 |
+
level_text = Text.styled(
|
| 128 |
+
level_name.ljust(8), f"logging.level.{level_name.lower()}"
|
| 129 |
+
)
|
| 130 |
+
return level_text
|
| 131 |
+
|
| 132 |
+
def emit(self, record: LogRecord) -> None:
|
| 133 |
+
"""Invoked by logging."""
|
| 134 |
+
message = self.format(record)
|
| 135 |
+
traceback = None
|
| 136 |
+
if (
|
| 137 |
+
self.rich_tracebacks
|
| 138 |
+
and record.exc_info
|
| 139 |
+
and record.exc_info != (None, None, None)
|
| 140 |
+
):
|
| 141 |
+
exc_type, exc_value, exc_traceback = record.exc_info
|
| 142 |
+
assert exc_type is not None
|
| 143 |
+
assert exc_value is not None
|
| 144 |
+
traceback = Traceback.from_exception(
|
| 145 |
+
exc_type,
|
| 146 |
+
exc_value,
|
| 147 |
+
exc_traceback,
|
| 148 |
+
width=self.tracebacks_width,
|
| 149 |
+
code_width=self.tracebacks_code_width,
|
| 150 |
+
extra_lines=self.tracebacks_extra_lines,
|
| 151 |
+
theme=self.tracebacks_theme,
|
| 152 |
+
word_wrap=self.tracebacks_word_wrap,
|
| 153 |
+
show_locals=self.tracebacks_show_locals,
|
| 154 |
+
locals_max_length=self.locals_max_length,
|
| 155 |
+
locals_max_string=self.locals_max_string,
|
| 156 |
+
suppress=self.tracebacks_suppress,
|
| 157 |
+
max_frames=self.tracebacks_max_frames,
|
| 158 |
+
)
|
| 159 |
+
message = record.getMessage()
|
| 160 |
+
if self.formatter:
|
| 161 |
+
record.message = record.getMessage()
|
| 162 |
+
formatter = self.formatter
|
| 163 |
+
if hasattr(formatter, "usesTime") and formatter.usesTime():
|
| 164 |
+
record.asctime = formatter.formatTime(record, formatter.datefmt)
|
| 165 |
+
message = formatter.formatMessage(record)
|
| 166 |
+
|
| 167 |
+
message_renderable = self.render_message(record, message)
|
| 168 |
+
log_renderable = self.render(
|
| 169 |
+
record=record, traceback=traceback, message_renderable=message_renderable
|
| 170 |
+
)
|
| 171 |
+
if isinstance(self.console.file, NullFile):
|
| 172 |
+
# Handles pythonw, where stdout/stderr are null, and we return NullFile
|
| 173 |
+
# instance from Console.file. In this case, we still want to make a log record
|
| 174 |
+
# even though we won't be writing anything to a file.
|
| 175 |
+
self.handleError(record)
|
| 176 |
+
else:
|
| 177 |
+
try:
|
| 178 |
+
self.console.print(log_renderable)
|
| 179 |
+
except Exception:
|
| 180 |
+
self.handleError(record)
|
| 181 |
+
|
| 182 |
+
def render_message(self, record: LogRecord, message: str) -> "ConsoleRenderable":
|
| 183 |
+
"""Render message text in to Text.
|
| 184 |
+
|
| 185 |
+
Args:
|
| 186 |
+
record (LogRecord): logging Record.
|
| 187 |
+
message (str): String containing log message.
|
| 188 |
+
|
| 189 |
+
Returns:
|
| 190 |
+
ConsoleRenderable: Renderable to display log message.
|
| 191 |
+
"""
|
| 192 |
+
use_markup = getattr(record, "markup", self.markup)
|
| 193 |
+
message_text = Text.from_markup(message) if use_markup else Text(message)
|
| 194 |
+
|
| 195 |
+
highlighter = getattr(record, "highlighter", self.highlighter)
|
| 196 |
+
if highlighter:
|
| 197 |
+
message_text = highlighter(message_text)
|
| 198 |
+
|
| 199 |
+
if self.keywords is None:
|
| 200 |
+
self.keywords = self.KEYWORDS
|
| 201 |
+
|
| 202 |
+
if self.keywords:
|
| 203 |
+
message_text.highlight_words(self.keywords, "logging.keyword")
|
| 204 |
+
|
| 205 |
+
return message_text
|
| 206 |
+
|
| 207 |
+
def render(
|
| 208 |
+
self,
|
| 209 |
+
*,
|
| 210 |
+
record: LogRecord,
|
| 211 |
+
traceback: Optional[Traceback],
|
| 212 |
+
message_renderable: "ConsoleRenderable",
|
| 213 |
+
) -> "ConsoleRenderable":
|
| 214 |
+
"""Render log for display.
|
| 215 |
+
|
| 216 |
+
Args:
|
| 217 |
+
record (LogRecord): logging Record.
|
| 218 |
+
traceback (Optional[Traceback]): Traceback instance or None for no Traceback.
|
| 219 |
+
message_renderable (ConsoleRenderable): Renderable (typically Text) containing log message contents.
|
| 220 |
+
|
| 221 |
+
Returns:
|
| 222 |
+
ConsoleRenderable: Renderable to display log.
|
| 223 |
+
"""
|
| 224 |
+
path = Path(record.pathname).name
|
| 225 |
+
level = self.get_level_text(record)
|
| 226 |
+
time_format = None if self.formatter is None else self.formatter.datefmt
|
| 227 |
+
log_time = datetime.fromtimestamp(record.created)
|
| 228 |
+
|
| 229 |
+
log_renderable = self._log_render(
|
| 230 |
+
self.console,
|
| 231 |
+
[message_renderable] if not traceback else [message_renderable, traceback],
|
| 232 |
+
log_time=log_time,
|
| 233 |
+
time_format=time_format,
|
| 234 |
+
level=level,
|
| 235 |
+
path=path,
|
| 236 |
+
line_no=record.lineno,
|
| 237 |
+
link_path=record.pathname if self.enable_link_path else None,
|
| 238 |
+
)
|
| 239 |
+
return log_renderable
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
if __name__ == "__main__": # pragma: no cover
|
| 243 |
+
from time import sleep
|
| 244 |
+
|
| 245 |
+
FORMAT = "%(message)s"
|
| 246 |
+
# FORMAT = "%(asctime)-15s - %(levelname)s - %(message)s"
|
| 247 |
+
logging.basicConfig(
|
| 248 |
+
level="NOTSET",
|
| 249 |
+
format=FORMAT,
|
| 250 |
+
datefmt="[%X]",
|
| 251 |
+
handlers=[RichHandler(rich_tracebacks=True, tracebacks_show_locals=True)],
|
| 252 |
+
)
|
| 253 |
+
log = logging.getLogger("rich")
|
| 254 |
+
|
| 255 |
+
log.info("Server starting...")
|
| 256 |
+
log.info("Listening on http://127.0.0.1:8080")
|
| 257 |
+
sleep(1)
|
| 258 |
+
|
| 259 |
+
log.info("GET /index.html 200 1298")
|
| 260 |
+
log.info("GET /imgs/backgrounds/back1.jpg 200 54386")
|
| 261 |
+
log.info("GET /css/styles.css 200 54386")
|
| 262 |
+
log.warning("GET /favicon.ico 404 242")
|
| 263 |
+
sleep(1)
|
| 264 |
+
|
| 265 |
+
log.debug(
|
| 266 |
+
"JSONRPC request\n--> %r\n<-- %r",
|
| 267 |
+
{
|
| 268 |
+
"version": "1.1",
|
| 269 |
+
"method": "confirmFruitPurchase",
|
| 270 |
+
"params": [["apple", "orange", "mangoes", "pomelo"], 1.123],
|
| 271 |
+
"id": "194521489",
|
| 272 |
+
},
|
| 273 |
+
{"version": "1.1", "result": True, "error": None, "id": "194521489"},
|
| 274 |
+
)
|
| 275 |
+
log.debug(
|
| 276 |
+
"Loading configuration file /adasd/asdasd/qeqwe/qwrqwrqwr/sdgsdgsdg/werwerwer/dfgerert/ertertert/ertetert/werwerwer"
|
| 277 |
+
)
|
| 278 |
+
log.error("Unable to find 'pomelo' in database!")
|
| 279 |
+
log.info("POST /jsonrpc/ 200 65532")
|
| 280 |
+
log.info("POST /admin/ 401 42234")
|
| 281 |
+
log.warning("password was rejected for admin site.")
|
| 282 |
+
|
| 283 |
+
def divide() -> None:
|
| 284 |
+
number = 1
|
| 285 |
+
divisor = 0
|
| 286 |
+
foos = ["foo"] * 100
|
| 287 |
+
log.debug("in divide")
|
| 288 |
+
try:
|
| 289 |
+
number / divisor
|
| 290 |
+
except:
|
| 291 |
+
log.exception("An error of some kind occurred!")
|
| 292 |
+
|
| 293 |
+
divide()
|
| 294 |
+
sleep(1)
|
| 295 |
+
log.critical("Out of memory!")
|
| 296 |
+
log.info("Server exited with code=-1")
|
| 297 |
+
log.info("[bold]EXITING...[/bold]", extra=dict(markup=True))
|
miniconda3/lib/python3.13/site-packages/rich/markdown.py
ADDED
|
@@ -0,0 +1,779 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import sys
|
| 4 |
+
from typing import ClassVar, Iterable, get_args
|
| 5 |
+
|
| 6 |
+
from markdown_it import MarkdownIt
|
| 7 |
+
from markdown_it.token import Token
|
| 8 |
+
|
| 9 |
+
from rich.table import Table
|
| 10 |
+
|
| 11 |
+
from . import box
|
| 12 |
+
from ._loop import loop_first
|
| 13 |
+
from ._stack import Stack
|
| 14 |
+
from .console import Console, ConsoleOptions, JustifyMethod, RenderResult
|
| 15 |
+
from .containers import Renderables
|
| 16 |
+
from .jupyter import JupyterMixin
|
| 17 |
+
from .panel import Panel
|
| 18 |
+
from .rule import Rule
|
| 19 |
+
from .segment import Segment
|
| 20 |
+
from .style import Style, StyleStack
|
| 21 |
+
from .syntax import Syntax
|
| 22 |
+
from .text import Text, TextType
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class MarkdownElement:
|
| 26 |
+
new_line: ClassVar[bool] = True
|
| 27 |
+
|
| 28 |
+
@classmethod
|
| 29 |
+
def create(cls, markdown: Markdown, token: Token) -> MarkdownElement:
|
| 30 |
+
"""Factory to create markdown element,
|
| 31 |
+
|
| 32 |
+
Args:
|
| 33 |
+
markdown (Markdown): The parent Markdown object.
|
| 34 |
+
token (Token): A node from markdown-it.
|
| 35 |
+
|
| 36 |
+
Returns:
|
| 37 |
+
MarkdownElement: A new markdown element
|
| 38 |
+
"""
|
| 39 |
+
return cls()
|
| 40 |
+
|
| 41 |
+
def on_enter(self, context: MarkdownContext) -> None:
|
| 42 |
+
"""Called when the node is entered.
|
| 43 |
+
|
| 44 |
+
Args:
|
| 45 |
+
context (MarkdownContext): The markdown context.
|
| 46 |
+
"""
|
| 47 |
+
|
| 48 |
+
def on_text(self, context: MarkdownContext, text: TextType) -> None:
|
| 49 |
+
"""Called when text is parsed.
|
| 50 |
+
|
| 51 |
+
Args:
|
| 52 |
+
context (MarkdownContext): The markdown context.
|
| 53 |
+
"""
|
| 54 |
+
|
| 55 |
+
def on_leave(self, context: MarkdownContext) -> None:
|
| 56 |
+
"""Called when the parser leaves the element.
|
| 57 |
+
|
| 58 |
+
Args:
|
| 59 |
+
context (MarkdownContext): [description]
|
| 60 |
+
"""
|
| 61 |
+
|
| 62 |
+
def on_child_close(self, context: MarkdownContext, child: MarkdownElement) -> bool:
|
| 63 |
+
"""Called when a child element is closed.
|
| 64 |
+
|
| 65 |
+
This method allows a parent element to take over rendering of its children.
|
| 66 |
+
|
| 67 |
+
Args:
|
| 68 |
+
context (MarkdownContext): The markdown context.
|
| 69 |
+
child (MarkdownElement): The child markdown element.
|
| 70 |
+
|
| 71 |
+
Returns:
|
| 72 |
+
bool: Return True to render the element, or False to not render the element.
|
| 73 |
+
"""
|
| 74 |
+
return True
|
| 75 |
+
|
| 76 |
+
def __rich_console__(
|
| 77 |
+
self, console: Console, options: ConsoleOptions
|
| 78 |
+
) -> RenderResult:
|
| 79 |
+
return ()
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
class UnknownElement(MarkdownElement):
|
| 83 |
+
"""An unknown element.
|
| 84 |
+
|
| 85 |
+
Hopefully there will be no unknown elements, and we will have a MarkdownElement for
|
| 86 |
+
everything in the document.
|
| 87 |
+
|
| 88 |
+
"""
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
class TextElement(MarkdownElement):
|
| 92 |
+
"""Base class for elements that render text."""
|
| 93 |
+
|
| 94 |
+
style_name = "none"
|
| 95 |
+
|
| 96 |
+
def on_enter(self, context: MarkdownContext) -> None:
|
| 97 |
+
self.style = context.enter_style(self.style_name)
|
| 98 |
+
self.text = Text(justify="left")
|
| 99 |
+
|
| 100 |
+
def on_text(self, context: MarkdownContext, text: TextType) -> None:
|
| 101 |
+
self.text.append(text, context.current_style if isinstance(text, str) else None)
|
| 102 |
+
|
| 103 |
+
def on_leave(self, context: MarkdownContext) -> None:
|
| 104 |
+
context.leave_style()
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
class Paragraph(TextElement):
|
| 108 |
+
"""A Paragraph."""
|
| 109 |
+
|
| 110 |
+
style_name = "markdown.paragraph"
|
| 111 |
+
justify: JustifyMethod
|
| 112 |
+
|
| 113 |
+
@classmethod
|
| 114 |
+
def create(cls, markdown: Markdown, token: Token) -> Paragraph:
|
| 115 |
+
return cls(justify=markdown.justify or "left")
|
| 116 |
+
|
| 117 |
+
def __init__(self, justify: JustifyMethod) -> None:
|
| 118 |
+
self.justify = justify
|
| 119 |
+
|
| 120 |
+
def __rich_console__(
|
| 121 |
+
self, console: Console, options: ConsoleOptions
|
| 122 |
+
) -> RenderResult:
|
| 123 |
+
self.text.justify = self.justify
|
| 124 |
+
yield self.text
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
class Heading(TextElement):
|
| 128 |
+
"""A heading."""
|
| 129 |
+
|
| 130 |
+
@classmethod
|
| 131 |
+
def create(cls, markdown: Markdown, token: Token) -> Heading:
|
| 132 |
+
return cls(token.tag)
|
| 133 |
+
|
| 134 |
+
def on_enter(self, context: MarkdownContext) -> None:
|
| 135 |
+
self.text = Text()
|
| 136 |
+
context.enter_style(self.style_name)
|
| 137 |
+
|
| 138 |
+
def __init__(self, tag: str) -> None:
|
| 139 |
+
self.tag = tag
|
| 140 |
+
self.style_name = f"markdown.{tag}"
|
| 141 |
+
super().__init__()
|
| 142 |
+
|
| 143 |
+
def __rich_console__(
|
| 144 |
+
self, console: Console, options: ConsoleOptions
|
| 145 |
+
) -> RenderResult:
|
| 146 |
+
text = self.text
|
| 147 |
+
text.justify = "center"
|
| 148 |
+
if self.tag == "h1":
|
| 149 |
+
# Draw a border around h1s
|
| 150 |
+
yield Panel(
|
| 151 |
+
text,
|
| 152 |
+
box=box.HEAVY,
|
| 153 |
+
style="markdown.h1.border",
|
| 154 |
+
)
|
| 155 |
+
else:
|
| 156 |
+
# Styled text for h2 and beyond
|
| 157 |
+
if self.tag == "h2":
|
| 158 |
+
yield Text("")
|
| 159 |
+
yield text
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
class CodeBlock(TextElement):
|
| 163 |
+
"""A code block with syntax highlighting."""
|
| 164 |
+
|
| 165 |
+
style_name = "markdown.code_block"
|
| 166 |
+
|
| 167 |
+
@classmethod
|
| 168 |
+
def create(cls, markdown: Markdown, token: Token) -> CodeBlock:
|
| 169 |
+
node_info = token.info or ""
|
| 170 |
+
lexer_name = node_info.partition(" ")[0]
|
| 171 |
+
return cls(lexer_name or "text", markdown.code_theme)
|
| 172 |
+
|
| 173 |
+
def __init__(self, lexer_name: str, theme: str) -> None:
|
| 174 |
+
self.lexer_name = lexer_name
|
| 175 |
+
self.theme = theme
|
| 176 |
+
|
| 177 |
+
def __rich_console__(
|
| 178 |
+
self, console: Console, options: ConsoleOptions
|
| 179 |
+
) -> RenderResult:
|
| 180 |
+
code = str(self.text).rstrip()
|
| 181 |
+
syntax = Syntax(
|
| 182 |
+
code, self.lexer_name, theme=self.theme, word_wrap=True, padding=1
|
| 183 |
+
)
|
| 184 |
+
yield syntax
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
class BlockQuote(TextElement):
|
| 188 |
+
"""A block quote."""
|
| 189 |
+
|
| 190 |
+
style_name = "markdown.block_quote"
|
| 191 |
+
|
| 192 |
+
def __init__(self) -> None:
|
| 193 |
+
self.elements: Renderables = Renderables()
|
| 194 |
+
|
| 195 |
+
def on_child_close(self, context: MarkdownContext, child: MarkdownElement) -> bool:
|
| 196 |
+
self.elements.append(child)
|
| 197 |
+
return False
|
| 198 |
+
|
| 199 |
+
def __rich_console__(
|
| 200 |
+
self, console: Console, options: ConsoleOptions
|
| 201 |
+
) -> RenderResult:
|
| 202 |
+
render_options = options.update(width=options.max_width - 4)
|
| 203 |
+
lines = console.render_lines(self.elements, render_options, style=self.style)
|
| 204 |
+
style = self.style
|
| 205 |
+
new_line = Segment("\n")
|
| 206 |
+
padding = Segment("▌ ", style)
|
| 207 |
+
for line in lines:
|
| 208 |
+
yield padding
|
| 209 |
+
yield from line
|
| 210 |
+
yield new_line
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
class HorizontalRule(MarkdownElement):
|
| 214 |
+
"""A horizontal rule to divide sections."""
|
| 215 |
+
|
| 216 |
+
new_line = False
|
| 217 |
+
|
| 218 |
+
def __rich_console__(
|
| 219 |
+
self, console: Console, options: ConsoleOptions
|
| 220 |
+
) -> RenderResult:
|
| 221 |
+
style = console.get_style("markdown.hr", default="none")
|
| 222 |
+
yield Rule(style=style)
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
class TableElement(MarkdownElement):
|
| 226 |
+
"""MarkdownElement corresponding to `table_open`."""
|
| 227 |
+
|
| 228 |
+
def __init__(self) -> None:
|
| 229 |
+
self.header: TableHeaderElement | None = None
|
| 230 |
+
self.body: TableBodyElement | None = None
|
| 231 |
+
|
| 232 |
+
def on_child_close(self, context: MarkdownContext, child: MarkdownElement) -> bool:
|
| 233 |
+
if isinstance(child, TableHeaderElement):
|
| 234 |
+
self.header = child
|
| 235 |
+
elif isinstance(child, TableBodyElement):
|
| 236 |
+
self.body = child
|
| 237 |
+
else:
|
| 238 |
+
raise RuntimeError("Couldn't process markdown table.")
|
| 239 |
+
return False
|
| 240 |
+
|
| 241 |
+
def __rich_console__(
|
| 242 |
+
self, console: Console, options: ConsoleOptions
|
| 243 |
+
) -> RenderResult:
|
| 244 |
+
table = Table(box=box.SIMPLE_HEAVY)
|
| 245 |
+
|
| 246 |
+
if self.header is not None and self.header.row is not None:
|
| 247 |
+
for column in self.header.row.cells:
|
| 248 |
+
table.add_column(column.content)
|
| 249 |
+
|
| 250 |
+
if self.body is not None:
|
| 251 |
+
for row in self.body.rows:
|
| 252 |
+
row_content = [element.content for element in row.cells]
|
| 253 |
+
table.add_row(*row_content)
|
| 254 |
+
|
| 255 |
+
yield table
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
class TableHeaderElement(MarkdownElement):
|
| 259 |
+
"""MarkdownElement corresponding to `thead_open` and `thead_close`."""
|
| 260 |
+
|
| 261 |
+
def __init__(self) -> None:
|
| 262 |
+
self.row: TableRowElement | None = None
|
| 263 |
+
|
| 264 |
+
def on_child_close(self, context: MarkdownContext, child: MarkdownElement) -> bool:
|
| 265 |
+
assert isinstance(child, TableRowElement)
|
| 266 |
+
self.row = child
|
| 267 |
+
return False
|
| 268 |
+
|
| 269 |
+
|
| 270 |
+
class TableBodyElement(MarkdownElement):
|
| 271 |
+
"""MarkdownElement corresponding to `tbody_open` and `tbody_close`."""
|
| 272 |
+
|
| 273 |
+
def __init__(self) -> None:
|
| 274 |
+
self.rows: list[TableRowElement] = []
|
| 275 |
+
|
| 276 |
+
def on_child_close(self, context: MarkdownContext, child: MarkdownElement) -> bool:
|
| 277 |
+
assert isinstance(child, TableRowElement)
|
| 278 |
+
self.rows.append(child)
|
| 279 |
+
return False
|
| 280 |
+
|
| 281 |
+
|
| 282 |
+
class TableRowElement(MarkdownElement):
|
| 283 |
+
"""MarkdownElement corresponding to `tr_open` and `tr_close`."""
|
| 284 |
+
|
| 285 |
+
def __init__(self) -> None:
|
| 286 |
+
self.cells: list[TableDataElement] = []
|
| 287 |
+
|
| 288 |
+
def on_child_close(self, context: MarkdownContext, child: MarkdownElement) -> bool:
|
| 289 |
+
assert isinstance(child, TableDataElement)
|
| 290 |
+
self.cells.append(child)
|
| 291 |
+
return False
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
class TableDataElement(MarkdownElement):
|
| 295 |
+
"""MarkdownElement corresponding to `td_open` and `td_close`
|
| 296 |
+
and `th_open` and `th_close`."""
|
| 297 |
+
|
| 298 |
+
@classmethod
|
| 299 |
+
def create(cls, markdown: Markdown, token: Token) -> MarkdownElement:
|
| 300 |
+
style = str(token.attrs.get("style")) or ""
|
| 301 |
+
|
| 302 |
+
justify: JustifyMethod
|
| 303 |
+
if "text-align:right" in style:
|
| 304 |
+
justify = "right"
|
| 305 |
+
elif "text-align:center" in style:
|
| 306 |
+
justify = "center"
|
| 307 |
+
elif "text-align:left" in style:
|
| 308 |
+
justify = "left"
|
| 309 |
+
else:
|
| 310 |
+
justify = "default"
|
| 311 |
+
|
| 312 |
+
assert justify in get_args(JustifyMethod)
|
| 313 |
+
return cls(justify=justify)
|
| 314 |
+
|
| 315 |
+
def __init__(self, justify: JustifyMethod) -> None:
|
| 316 |
+
self.content: Text = Text("", justify=justify)
|
| 317 |
+
self.justify = justify
|
| 318 |
+
|
| 319 |
+
def on_text(self, context: MarkdownContext, text: TextType) -> None:
|
| 320 |
+
text = Text(text) if isinstance(text, str) else text
|
| 321 |
+
text.stylize(context.current_style)
|
| 322 |
+
self.content.append_text(text)
|
| 323 |
+
|
| 324 |
+
|
| 325 |
+
class ListElement(MarkdownElement):
|
| 326 |
+
"""A list element."""
|
| 327 |
+
|
| 328 |
+
@classmethod
|
| 329 |
+
def create(cls, markdown: Markdown, token: Token) -> ListElement:
|
| 330 |
+
return cls(token.type, int(token.attrs.get("start", 1)))
|
| 331 |
+
|
| 332 |
+
def __init__(self, list_type: str, list_start: int | None) -> None:
|
| 333 |
+
self.items: list[ListItem] = []
|
| 334 |
+
self.list_type = list_type
|
| 335 |
+
self.list_start = list_start
|
| 336 |
+
|
| 337 |
+
def on_child_close(self, context: MarkdownContext, child: MarkdownElement) -> bool:
|
| 338 |
+
assert isinstance(child, ListItem)
|
| 339 |
+
self.items.append(child)
|
| 340 |
+
return False
|
| 341 |
+
|
| 342 |
+
def __rich_console__(
|
| 343 |
+
self, console: Console, options: ConsoleOptions
|
| 344 |
+
) -> RenderResult:
|
| 345 |
+
if self.list_type == "bullet_list_open":
|
| 346 |
+
for item in self.items:
|
| 347 |
+
yield from item.render_bullet(console, options)
|
| 348 |
+
else:
|
| 349 |
+
number = 1 if self.list_start is None else self.list_start
|
| 350 |
+
last_number = number + len(self.items)
|
| 351 |
+
for index, item in enumerate(self.items):
|
| 352 |
+
yield from item.render_number(
|
| 353 |
+
console, options, number + index, last_number
|
| 354 |
+
)
|
| 355 |
+
|
| 356 |
+
|
| 357 |
+
class ListItem(TextElement):
|
| 358 |
+
"""An item in a list."""
|
| 359 |
+
|
| 360 |
+
style_name = "markdown.item"
|
| 361 |
+
|
| 362 |
+
def __init__(self) -> None:
|
| 363 |
+
self.elements: Renderables = Renderables()
|
| 364 |
+
|
| 365 |
+
def on_child_close(self, context: MarkdownContext, child: MarkdownElement) -> bool:
|
| 366 |
+
self.elements.append(child)
|
| 367 |
+
return False
|
| 368 |
+
|
| 369 |
+
def render_bullet(self, console: Console, options: ConsoleOptions) -> RenderResult:
|
| 370 |
+
render_options = options.update(width=options.max_width - 3)
|
| 371 |
+
lines = console.render_lines(self.elements, render_options, style=self.style)
|
| 372 |
+
bullet_style = console.get_style("markdown.item.bullet", default="none")
|
| 373 |
+
|
| 374 |
+
bullet = Segment(" • ", bullet_style)
|
| 375 |
+
padding = Segment(" " * 3, bullet_style)
|
| 376 |
+
new_line = Segment("\n")
|
| 377 |
+
for first, line in loop_first(lines):
|
| 378 |
+
yield bullet if first else padding
|
| 379 |
+
yield from line
|
| 380 |
+
yield new_line
|
| 381 |
+
|
| 382 |
+
def render_number(
|
| 383 |
+
self, console: Console, options: ConsoleOptions, number: int, last_number: int
|
| 384 |
+
) -> RenderResult:
|
| 385 |
+
number_width = len(str(last_number)) + 2
|
| 386 |
+
render_options = options.update(width=options.max_width - number_width)
|
| 387 |
+
lines = console.render_lines(self.elements, render_options, style=self.style)
|
| 388 |
+
number_style = console.get_style("markdown.item.number", default="none")
|
| 389 |
+
|
| 390 |
+
new_line = Segment("\n")
|
| 391 |
+
padding = Segment(" " * number_width, number_style)
|
| 392 |
+
numeral = Segment(f"{number}".rjust(number_width - 1) + " ", number_style)
|
| 393 |
+
for first, line in loop_first(lines):
|
| 394 |
+
yield numeral if first else padding
|
| 395 |
+
yield from line
|
| 396 |
+
yield new_line
|
| 397 |
+
|
| 398 |
+
|
| 399 |
+
class Link(TextElement):
|
| 400 |
+
@classmethod
|
| 401 |
+
def create(cls, markdown: Markdown, token: Token) -> MarkdownElement:
|
| 402 |
+
url = token.attrs.get("href", "#")
|
| 403 |
+
return cls(token.content, str(url))
|
| 404 |
+
|
| 405 |
+
def __init__(self, text: str, href: str):
|
| 406 |
+
self.text = Text(text)
|
| 407 |
+
self.href = href
|
| 408 |
+
|
| 409 |
+
|
| 410 |
+
class ImageItem(TextElement):
|
| 411 |
+
"""Renders a placeholder for an image."""
|
| 412 |
+
|
| 413 |
+
new_line = False
|
| 414 |
+
|
| 415 |
+
@classmethod
|
| 416 |
+
def create(cls, markdown: Markdown, token: Token) -> MarkdownElement:
|
| 417 |
+
"""Factory to create markdown element,
|
| 418 |
+
|
| 419 |
+
Args:
|
| 420 |
+
markdown (Markdown): The parent Markdown object.
|
| 421 |
+
token (Any): A token from markdown-it.
|
| 422 |
+
|
| 423 |
+
Returns:
|
| 424 |
+
MarkdownElement: A new markdown element
|
| 425 |
+
"""
|
| 426 |
+
return cls(str(token.attrs.get("src", "")), markdown.hyperlinks)
|
| 427 |
+
|
| 428 |
+
def __init__(self, destination: str, hyperlinks: bool) -> None:
|
| 429 |
+
self.destination = destination
|
| 430 |
+
self.hyperlinks = hyperlinks
|
| 431 |
+
self.link: str | None = None
|
| 432 |
+
super().__init__()
|
| 433 |
+
|
| 434 |
+
def on_enter(self, context: MarkdownContext) -> None:
|
| 435 |
+
self.link = context.current_style.link
|
| 436 |
+
self.text = Text(justify="left")
|
| 437 |
+
super().on_enter(context)
|
| 438 |
+
|
| 439 |
+
def __rich_console__(
|
| 440 |
+
self, console: Console, options: ConsoleOptions
|
| 441 |
+
) -> RenderResult:
|
| 442 |
+
link_style = Style(link=self.link or self.destination or None)
|
| 443 |
+
title = self.text or Text(self.destination.strip("/").rsplit("/", 1)[-1])
|
| 444 |
+
if self.hyperlinks:
|
| 445 |
+
title.stylize(link_style)
|
| 446 |
+
text = Text.assemble("🌆 ", title, " ", end="")
|
| 447 |
+
yield text
|
| 448 |
+
|
| 449 |
+
|
| 450 |
+
class MarkdownContext:
|
| 451 |
+
"""Manages the console render state."""
|
| 452 |
+
|
| 453 |
+
def __init__(
|
| 454 |
+
self,
|
| 455 |
+
console: Console,
|
| 456 |
+
options: ConsoleOptions,
|
| 457 |
+
style: Style,
|
| 458 |
+
inline_code_lexer: str | None = None,
|
| 459 |
+
inline_code_theme: str = "monokai",
|
| 460 |
+
) -> None:
|
| 461 |
+
self.console = console
|
| 462 |
+
self.options = options
|
| 463 |
+
self.style_stack: StyleStack = StyleStack(style)
|
| 464 |
+
self.stack: Stack[MarkdownElement] = Stack()
|
| 465 |
+
|
| 466 |
+
self._syntax: Syntax | None = None
|
| 467 |
+
if inline_code_lexer is not None:
|
| 468 |
+
self._syntax = Syntax("", inline_code_lexer, theme=inline_code_theme)
|
| 469 |
+
|
| 470 |
+
@property
|
| 471 |
+
def current_style(self) -> Style:
|
| 472 |
+
"""Current style which is the product of all styles on the stack."""
|
| 473 |
+
return self.style_stack.current
|
| 474 |
+
|
| 475 |
+
def on_text(self, text: str, node_type: str) -> None:
|
| 476 |
+
"""Called when the parser visits text."""
|
| 477 |
+
if node_type in {"fence", "code_inline"} and self._syntax is not None:
|
| 478 |
+
highlight_text = self._syntax.highlight(text)
|
| 479 |
+
highlight_text.rstrip()
|
| 480 |
+
self.stack.top.on_text(
|
| 481 |
+
self, Text.assemble(highlight_text, style=self.style_stack.current)
|
| 482 |
+
)
|
| 483 |
+
else:
|
| 484 |
+
self.stack.top.on_text(self, text)
|
| 485 |
+
|
| 486 |
+
def enter_style(self, style_name: str | Style) -> Style:
|
| 487 |
+
"""Enter a style context."""
|
| 488 |
+
style = self.console.get_style(style_name, default="none")
|
| 489 |
+
self.style_stack.push(style)
|
| 490 |
+
return self.current_style
|
| 491 |
+
|
| 492 |
+
def leave_style(self) -> Style:
|
| 493 |
+
"""Leave a style context."""
|
| 494 |
+
style = self.style_stack.pop()
|
| 495 |
+
return style
|
| 496 |
+
|
| 497 |
+
|
| 498 |
+
class Markdown(JupyterMixin):
|
| 499 |
+
"""A Markdown renderable.
|
| 500 |
+
|
| 501 |
+
Args:
|
| 502 |
+
markup (str): A string containing markdown.
|
| 503 |
+
code_theme (str, optional): Pygments theme for code blocks. Defaults to "monokai". See https://pygments.org/styles/ for code themes.
|
| 504 |
+
justify (JustifyMethod, optional): Justify value for paragraphs. Defaults to None.
|
| 505 |
+
style (Union[str, Style], optional): Optional style to apply to markdown.
|
| 506 |
+
hyperlinks (bool, optional): Enable hyperlinks. Defaults to ``True``.
|
| 507 |
+
inline_code_lexer: (str, optional): Lexer to use if inline code highlighting is
|
| 508 |
+
enabled. Defaults to None.
|
| 509 |
+
inline_code_theme: (Optional[str], optional): Pygments theme for inline code
|
| 510 |
+
highlighting, or None for no highlighting. Defaults to None.
|
| 511 |
+
"""
|
| 512 |
+
|
| 513 |
+
elements: ClassVar[dict[str, type[MarkdownElement]]] = {
|
| 514 |
+
"paragraph_open": Paragraph,
|
| 515 |
+
"heading_open": Heading,
|
| 516 |
+
"fence": CodeBlock,
|
| 517 |
+
"code_block": CodeBlock,
|
| 518 |
+
"blockquote_open": BlockQuote,
|
| 519 |
+
"hr": HorizontalRule,
|
| 520 |
+
"bullet_list_open": ListElement,
|
| 521 |
+
"ordered_list_open": ListElement,
|
| 522 |
+
"list_item_open": ListItem,
|
| 523 |
+
"image": ImageItem,
|
| 524 |
+
"table_open": TableElement,
|
| 525 |
+
"tbody_open": TableBodyElement,
|
| 526 |
+
"thead_open": TableHeaderElement,
|
| 527 |
+
"tr_open": TableRowElement,
|
| 528 |
+
"td_open": TableDataElement,
|
| 529 |
+
"th_open": TableDataElement,
|
| 530 |
+
}
|
| 531 |
+
|
| 532 |
+
inlines = {"em", "strong", "code", "s"}
|
| 533 |
+
|
| 534 |
+
def __init__(
|
| 535 |
+
self,
|
| 536 |
+
markup: str,
|
| 537 |
+
code_theme: str = "monokai",
|
| 538 |
+
justify: JustifyMethod | None = None,
|
| 539 |
+
style: str | Style = "none",
|
| 540 |
+
hyperlinks: bool = True,
|
| 541 |
+
inline_code_lexer: str | None = None,
|
| 542 |
+
inline_code_theme: str | None = None,
|
| 543 |
+
) -> None:
|
| 544 |
+
parser = MarkdownIt().enable("strikethrough").enable("table")
|
| 545 |
+
self.markup = markup
|
| 546 |
+
self.parsed = parser.parse(markup)
|
| 547 |
+
self.code_theme = code_theme
|
| 548 |
+
self.justify: JustifyMethod | None = justify
|
| 549 |
+
self.style = style
|
| 550 |
+
self.hyperlinks = hyperlinks
|
| 551 |
+
self.inline_code_lexer = inline_code_lexer
|
| 552 |
+
self.inline_code_theme = inline_code_theme or code_theme
|
| 553 |
+
|
| 554 |
+
def _flatten_tokens(self, tokens: Iterable[Token]) -> Iterable[Token]:
|
| 555 |
+
"""Flattens the token stream."""
|
| 556 |
+
for token in tokens:
|
| 557 |
+
is_fence = token.type == "fence"
|
| 558 |
+
is_image = token.tag == "img"
|
| 559 |
+
if token.children and not (is_image or is_fence):
|
| 560 |
+
yield from self._flatten_tokens(token.children)
|
| 561 |
+
else:
|
| 562 |
+
yield token
|
| 563 |
+
|
| 564 |
+
def __rich_console__(
|
| 565 |
+
self, console: Console, options: ConsoleOptions
|
| 566 |
+
) -> RenderResult:
|
| 567 |
+
"""Render markdown to the console."""
|
| 568 |
+
style = console.get_style(self.style, default="none")
|
| 569 |
+
options = options.update(height=None)
|
| 570 |
+
context = MarkdownContext(
|
| 571 |
+
console,
|
| 572 |
+
options,
|
| 573 |
+
style,
|
| 574 |
+
inline_code_lexer=self.inline_code_lexer,
|
| 575 |
+
inline_code_theme=self.inline_code_theme,
|
| 576 |
+
)
|
| 577 |
+
tokens = self.parsed
|
| 578 |
+
inline_style_tags = self.inlines
|
| 579 |
+
new_line = False
|
| 580 |
+
_new_line_segment = Segment.line()
|
| 581 |
+
|
| 582 |
+
for token in self._flatten_tokens(tokens):
|
| 583 |
+
node_type = token.type
|
| 584 |
+
tag = token.tag
|
| 585 |
+
|
| 586 |
+
entering = token.nesting == 1
|
| 587 |
+
exiting = token.nesting == -1
|
| 588 |
+
self_closing = token.nesting == 0
|
| 589 |
+
|
| 590 |
+
if node_type == "text":
|
| 591 |
+
context.on_text(token.content, node_type)
|
| 592 |
+
elif node_type == "hardbreak":
|
| 593 |
+
context.on_text("\n", node_type)
|
| 594 |
+
elif node_type == "softbreak":
|
| 595 |
+
context.on_text(" ", node_type)
|
| 596 |
+
elif node_type == "link_open":
|
| 597 |
+
href = str(token.attrs.get("href", ""))
|
| 598 |
+
if self.hyperlinks:
|
| 599 |
+
link_style = console.get_style("markdown.link_url", default="none")
|
| 600 |
+
link_style += Style(link=href)
|
| 601 |
+
context.enter_style(link_style)
|
| 602 |
+
else:
|
| 603 |
+
context.stack.push(Link.create(self, token))
|
| 604 |
+
elif node_type == "link_close":
|
| 605 |
+
if self.hyperlinks:
|
| 606 |
+
context.leave_style()
|
| 607 |
+
else:
|
| 608 |
+
element = context.stack.pop()
|
| 609 |
+
assert isinstance(element, Link)
|
| 610 |
+
link_style = console.get_style("markdown.link", default="none")
|
| 611 |
+
context.enter_style(link_style)
|
| 612 |
+
context.on_text(element.text.plain, node_type)
|
| 613 |
+
context.leave_style()
|
| 614 |
+
context.on_text(" (", node_type)
|
| 615 |
+
link_url_style = console.get_style(
|
| 616 |
+
"markdown.link_url", default="none"
|
| 617 |
+
)
|
| 618 |
+
context.enter_style(link_url_style)
|
| 619 |
+
context.on_text(element.href, node_type)
|
| 620 |
+
context.leave_style()
|
| 621 |
+
context.on_text(")", node_type)
|
| 622 |
+
elif (
|
| 623 |
+
tag in inline_style_tags
|
| 624 |
+
and node_type != "fence"
|
| 625 |
+
and node_type != "code_block"
|
| 626 |
+
):
|
| 627 |
+
if entering:
|
| 628 |
+
# If it's an opening inline token e.g. strong, em, etc.
|
| 629 |
+
# Then we move into a style context i.e. push to stack.
|
| 630 |
+
context.enter_style(f"markdown.{tag}")
|
| 631 |
+
elif exiting:
|
| 632 |
+
# If it's a closing inline style, then we pop the style
|
| 633 |
+
# off of the stack, to move out of the context of it...
|
| 634 |
+
context.leave_style()
|
| 635 |
+
else:
|
| 636 |
+
# If it's a self-closing inline style e.g. `code_inline`
|
| 637 |
+
context.enter_style(f"markdown.{tag}")
|
| 638 |
+
if token.content:
|
| 639 |
+
context.on_text(token.content, node_type)
|
| 640 |
+
context.leave_style()
|
| 641 |
+
else:
|
| 642 |
+
# Map the markdown tag -> MarkdownElement renderable
|
| 643 |
+
element_class = self.elements.get(token.type) or UnknownElement
|
| 644 |
+
element = element_class.create(self, token)
|
| 645 |
+
|
| 646 |
+
if entering or self_closing:
|
| 647 |
+
context.stack.push(element)
|
| 648 |
+
element.on_enter(context)
|
| 649 |
+
|
| 650 |
+
if exiting: # CLOSING tag
|
| 651 |
+
element = context.stack.pop()
|
| 652 |
+
|
| 653 |
+
should_render = not context.stack or (
|
| 654 |
+
context.stack
|
| 655 |
+
and context.stack.top.on_child_close(context, element)
|
| 656 |
+
)
|
| 657 |
+
|
| 658 |
+
if should_render:
|
| 659 |
+
if new_line:
|
| 660 |
+
yield _new_line_segment
|
| 661 |
+
|
| 662 |
+
yield from console.render(element, context.options)
|
| 663 |
+
elif self_closing: # SELF-CLOSING tags (e.g. text, code, image)
|
| 664 |
+
context.stack.pop()
|
| 665 |
+
text = token.content
|
| 666 |
+
if text is not None:
|
| 667 |
+
element.on_text(context, text)
|
| 668 |
+
|
| 669 |
+
should_render = (
|
| 670 |
+
not context.stack
|
| 671 |
+
or context.stack
|
| 672 |
+
and context.stack.top.on_child_close(context, element)
|
| 673 |
+
)
|
| 674 |
+
if should_render:
|
| 675 |
+
if new_line and node_type != "inline":
|
| 676 |
+
yield _new_line_segment
|
| 677 |
+
yield from console.render(element, context.options)
|
| 678 |
+
|
| 679 |
+
if exiting or self_closing:
|
| 680 |
+
element.on_leave(context)
|
| 681 |
+
new_line = element.new_line
|
| 682 |
+
|
| 683 |
+
|
| 684 |
+
if __name__ == "__main__": # pragma: no cover
|
| 685 |
+
import argparse
|
| 686 |
+
import sys
|
| 687 |
+
|
| 688 |
+
parser = argparse.ArgumentParser(
|
| 689 |
+
description="Render Markdown to the console with Rich"
|
| 690 |
+
)
|
| 691 |
+
parser.add_argument(
|
| 692 |
+
"path",
|
| 693 |
+
metavar="PATH",
|
| 694 |
+
help="path to markdown file, or - for stdin",
|
| 695 |
+
)
|
| 696 |
+
parser.add_argument(
|
| 697 |
+
"-c",
|
| 698 |
+
"--force-color",
|
| 699 |
+
dest="force_color",
|
| 700 |
+
action="store_true",
|
| 701 |
+
default=None,
|
| 702 |
+
help="force color for non-terminals",
|
| 703 |
+
)
|
| 704 |
+
parser.add_argument(
|
| 705 |
+
"-t",
|
| 706 |
+
"--code-theme",
|
| 707 |
+
dest="code_theme",
|
| 708 |
+
default="monokai",
|
| 709 |
+
help="pygments code theme",
|
| 710 |
+
)
|
| 711 |
+
parser.add_argument(
|
| 712 |
+
"-i",
|
| 713 |
+
"--inline-code-lexer",
|
| 714 |
+
dest="inline_code_lexer",
|
| 715 |
+
default=None,
|
| 716 |
+
help="inline_code_lexer",
|
| 717 |
+
)
|
| 718 |
+
parser.add_argument(
|
| 719 |
+
"-y",
|
| 720 |
+
"--hyperlinks",
|
| 721 |
+
dest="hyperlinks",
|
| 722 |
+
action="store_true",
|
| 723 |
+
help="enable hyperlinks",
|
| 724 |
+
)
|
| 725 |
+
parser.add_argument(
|
| 726 |
+
"-w",
|
| 727 |
+
"--width",
|
| 728 |
+
type=int,
|
| 729 |
+
dest="width",
|
| 730 |
+
default=None,
|
| 731 |
+
help="width of output (default will auto-detect)",
|
| 732 |
+
)
|
| 733 |
+
parser.add_argument(
|
| 734 |
+
"-j",
|
| 735 |
+
"--justify",
|
| 736 |
+
dest="justify",
|
| 737 |
+
action="store_true",
|
| 738 |
+
help="enable full text justify",
|
| 739 |
+
)
|
| 740 |
+
parser.add_argument(
|
| 741 |
+
"-p",
|
| 742 |
+
"--page",
|
| 743 |
+
dest="page",
|
| 744 |
+
action="store_true",
|
| 745 |
+
help="use pager to scroll output",
|
| 746 |
+
)
|
| 747 |
+
args = parser.parse_args()
|
| 748 |
+
|
| 749 |
+
from rich.console import Console
|
| 750 |
+
|
| 751 |
+
if args.path == "-":
|
| 752 |
+
markdown_body = sys.stdin.read()
|
| 753 |
+
else:
|
| 754 |
+
with open(args.path, encoding="utf-8") as markdown_file:
|
| 755 |
+
markdown_body = markdown_file.read()
|
| 756 |
+
|
| 757 |
+
markdown = Markdown(
|
| 758 |
+
markdown_body,
|
| 759 |
+
justify="full" if args.justify else "left",
|
| 760 |
+
code_theme=args.code_theme,
|
| 761 |
+
hyperlinks=args.hyperlinks,
|
| 762 |
+
inline_code_lexer=args.inline_code_lexer,
|
| 763 |
+
)
|
| 764 |
+
if args.page:
|
| 765 |
+
import io
|
| 766 |
+
import pydoc
|
| 767 |
+
|
| 768 |
+
fileio = io.StringIO()
|
| 769 |
+
console = Console(
|
| 770 |
+
file=fileio, force_terminal=args.force_color, width=args.width
|
| 771 |
+
)
|
| 772 |
+
console.print(markdown)
|
| 773 |
+
pydoc.pager(fileio.getvalue())
|
| 774 |
+
|
| 775 |
+
else:
|
| 776 |
+
console = Console(
|
| 777 |
+
force_terminal=args.force_color, width=args.width, record=True
|
| 778 |
+
)
|
| 779 |
+
console.print(markdown)
|
miniconda3/lib/python3.13/site-packages/rich/markup.py
ADDED
|
@@ -0,0 +1,251 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import re
|
| 2 |
+
from ast import literal_eval
|
| 3 |
+
from operator import attrgetter
|
| 4 |
+
from typing import Callable, Iterable, List, Match, NamedTuple, Optional, Tuple, Union
|
| 5 |
+
|
| 6 |
+
from ._emoji_replace import _emoji_replace
|
| 7 |
+
from .emoji import EmojiVariant
|
| 8 |
+
from .errors import MarkupError
|
| 9 |
+
from .style import Style
|
| 10 |
+
from .text import Span, Text
|
| 11 |
+
|
| 12 |
+
RE_TAGS = re.compile(
|
| 13 |
+
r"""((\\*)\[([a-z#/@][^[]*?)])""",
|
| 14 |
+
re.VERBOSE,
|
| 15 |
+
)
|
| 16 |
+
|
| 17 |
+
RE_HANDLER = re.compile(r"^([\w.]*?)(\(.*?\))?$")
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class Tag(NamedTuple):
|
| 21 |
+
"""A tag in console markup."""
|
| 22 |
+
|
| 23 |
+
name: str
|
| 24 |
+
"""The tag name. e.g. 'bold'."""
|
| 25 |
+
parameters: Optional[str]
|
| 26 |
+
"""Any additional parameters after the name."""
|
| 27 |
+
|
| 28 |
+
def __str__(self) -> str:
|
| 29 |
+
return (
|
| 30 |
+
self.name if self.parameters is None else f"{self.name} {self.parameters}"
|
| 31 |
+
)
|
| 32 |
+
|
| 33 |
+
@property
|
| 34 |
+
def markup(self) -> str:
|
| 35 |
+
"""Get the string representation of this tag."""
|
| 36 |
+
return (
|
| 37 |
+
f"[{self.name}]"
|
| 38 |
+
if self.parameters is None
|
| 39 |
+
else f"[{self.name}={self.parameters}]"
|
| 40 |
+
)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
_ReStringMatch = Match[str] # regex match object
|
| 44 |
+
_ReSubCallable = Callable[[_ReStringMatch], str] # Callable invoked by re.sub
|
| 45 |
+
_EscapeSubMethod = Callable[[_ReSubCallable, str], str] # Sub method of a compiled re
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def escape(
|
| 49 |
+
markup: str,
|
| 50 |
+
_escape: _EscapeSubMethod = re.compile(r"(\\*)(\[[a-z#/@][^[]*?])").sub,
|
| 51 |
+
) -> str:
|
| 52 |
+
"""Escapes text so that it won't be interpreted as markup.
|
| 53 |
+
|
| 54 |
+
Args:
|
| 55 |
+
markup (str): Content to be inserted in to markup.
|
| 56 |
+
|
| 57 |
+
Returns:
|
| 58 |
+
str: Markup with square brackets escaped.
|
| 59 |
+
"""
|
| 60 |
+
|
| 61 |
+
def escape_backslashes(match: Match[str]) -> str:
|
| 62 |
+
"""Called by re.sub replace matches."""
|
| 63 |
+
backslashes, text = match.groups()
|
| 64 |
+
return f"{backslashes}{backslashes}\\{text}"
|
| 65 |
+
|
| 66 |
+
markup = _escape(escape_backslashes, markup)
|
| 67 |
+
if markup.endswith("\\") and not markup.endswith("\\\\"):
|
| 68 |
+
return markup + "\\"
|
| 69 |
+
|
| 70 |
+
return markup
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def _parse(markup: str) -> Iterable[Tuple[int, Optional[str], Optional[Tag]]]:
|
| 74 |
+
"""Parse markup in to an iterable of tuples of (position, text, tag).
|
| 75 |
+
|
| 76 |
+
Args:
|
| 77 |
+
markup (str): A string containing console markup
|
| 78 |
+
|
| 79 |
+
"""
|
| 80 |
+
position = 0
|
| 81 |
+
_divmod = divmod
|
| 82 |
+
_Tag = Tag
|
| 83 |
+
for match in RE_TAGS.finditer(markup):
|
| 84 |
+
full_text, escapes, tag_text = match.groups()
|
| 85 |
+
start, end = match.span()
|
| 86 |
+
if start > position:
|
| 87 |
+
yield start, markup[position:start], None
|
| 88 |
+
if escapes:
|
| 89 |
+
backslashes, escaped = _divmod(len(escapes), 2)
|
| 90 |
+
if backslashes:
|
| 91 |
+
# Literal backslashes
|
| 92 |
+
yield start, "\\" * backslashes, None
|
| 93 |
+
start += backslashes * 2
|
| 94 |
+
if escaped:
|
| 95 |
+
# Escape of tag
|
| 96 |
+
yield start, full_text[len(escapes) :], None
|
| 97 |
+
position = end
|
| 98 |
+
continue
|
| 99 |
+
text, equals, parameters = tag_text.partition("=")
|
| 100 |
+
yield start, None, _Tag(text, parameters if equals else None)
|
| 101 |
+
position = end
|
| 102 |
+
if position < len(markup):
|
| 103 |
+
yield position, markup[position:], None
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def render(
|
| 107 |
+
markup: str,
|
| 108 |
+
style: Union[str, Style] = "",
|
| 109 |
+
emoji: bool = True,
|
| 110 |
+
emoji_variant: Optional[EmojiVariant] = None,
|
| 111 |
+
) -> Text:
|
| 112 |
+
"""Render console markup in to a Text instance.
|
| 113 |
+
|
| 114 |
+
Args:
|
| 115 |
+
markup (str): A string containing console markup.
|
| 116 |
+
style: (Union[str, Style]): The style to use.
|
| 117 |
+
emoji (bool, optional): Also render emoji code. Defaults to True.
|
| 118 |
+
emoji_variant (str, optional): Optional emoji variant, either "text" or "emoji". Defaults to None.
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
Raises:
|
| 122 |
+
MarkupError: If there is a syntax error in the markup.
|
| 123 |
+
|
| 124 |
+
Returns:
|
| 125 |
+
Text: A test instance.
|
| 126 |
+
"""
|
| 127 |
+
emoji_replace = _emoji_replace
|
| 128 |
+
if "[" not in markup:
|
| 129 |
+
return Text(
|
| 130 |
+
emoji_replace(markup, default_variant=emoji_variant) if emoji else markup,
|
| 131 |
+
style=style,
|
| 132 |
+
)
|
| 133 |
+
text = Text(style=style)
|
| 134 |
+
append = text.append
|
| 135 |
+
normalize = Style.normalize
|
| 136 |
+
|
| 137 |
+
style_stack: List[Tuple[int, Tag]] = []
|
| 138 |
+
pop = style_stack.pop
|
| 139 |
+
|
| 140 |
+
spans: List[Span] = []
|
| 141 |
+
append_span = spans.append
|
| 142 |
+
|
| 143 |
+
_Span = Span
|
| 144 |
+
_Tag = Tag
|
| 145 |
+
|
| 146 |
+
def pop_style(style_name: str) -> Tuple[int, Tag]:
|
| 147 |
+
"""Pop tag matching given style name."""
|
| 148 |
+
for index, (_, tag) in enumerate(reversed(style_stack), 1):
|
| 149 |
+
if tag.name == style_name:
|
| 150 |
+
return pop(-index)
|
| 151 |
+
raise KeyError(style_name)
|
| 152 |
+
|
| 153 |
+
for position, plain_text, tag in _parse(markup):
|
| 154 |
+
if plain_text is not None:
|
| 155 |
+
# Handle open brace escapes, where the brace is not part of a tag.
|
| 156 |
+
plain_text = plain_text.replace("\\[", "[")
|
| 157 |
+
append(emoji_replace(plain_text) if emoji else plain_text)
|
| 158 |
+
elif tag is not None:
|
| 159 |
+
if tag.name.startswith("/"): # Closing tag
|
| 160 |
+
style_name = tag.name[1:].strip()
|
| 161 |
+
|
| 162 |
+
if style_name: # explicit close
|
| 163 |
+
style_name = normalize(style_name)
|
| 164 |
+
try:
|
| 165 |
+
start, open_tag = pop_style(style_name)
|
| 166 |
+
except KeyError:
|
| 167 |
+
raise MarkupError(
|
| 168 |
+
f"closing tag '{tag.markup}' at position {position} doesn't match any open tag"
|
| 169 |
+
) from None
|
| 170 |
+
else: # implicit close
|
| 171 |
+
try:
|
| 172 |
+
start, open_tag = pop()
|
| 173 |
+
except IndexError:
|
| 174 |
+
raise MarkupError(
|
| 175 |
+
f"closing tag '[/]' at position {position} has nothing to close"
|
| 176 |
+
) from None
|
| 177 |
+
|
| 178 |
+
if open_tag.name.startswith("@"):
|
| 179 |
+
if open_tag.parameters:
|
| 180 |
+
handler_name = ""
|
| 181 |
+
parameters = open_tag.parameters.strip()
|
| 182 |
+
handler_match = RE_HANDLER.match(parameters)
|
| 183 |
+
if handler_match is not None:
|
| 184 |
+
handler_name, match_parameters = handler_match.groups()
|
| 185 |
+
parameters = (
|
| 186 |
+
"()" if match_parameters is None else match_parameters
|
| 187 |
+
)
|
| 188 |
+
|
| 189 |
+
try:
|
| 190 |
+
meta_params = literal_eval(parameters)
|
| 191 |
+
except SyntaxError as error:
|
| 192 |
+
raise MarkupError(
|
| 193 |
+
f"error parsing {parameters!r} in {open_tag.parameters!r}; {error.msg}"
|
| 194 |
+
)
|
| 195 |
+
except Exception as error:
|
| 196 |
+
raise MarkupError(
|
| 197 |
+
f"error parsing {open_tag.parameters!r}; {error}"
|
| 198 |
+
) from None
|
| 199 |
+
|
| 200 |
+
if handler_name:
|
| 201 |
+
meta_params = (
|
| 202 |
+
handler_name,
|
| 203 |
+
meta_params
|
| 204 |
+
if isinstance(meta_params, tuple)
|
| 205 |
+
else (meta_params,),
|
| 206 |
+
)
|
| 207 |
+
|
| 208 |
+
else:
|
| 209 |
+
meta_params = ()
|
| 210 |
+
|
| 211 |
+
append_span(
|
| 212 |
+
_Span(
|
| 213 |
+
start, len(text), Style(meta={open_tag.name: meta_params})
|
| 214 |
+
)
|
| 215 |
+
)
|
| 216 |
+
else:
|
| 217 |
+
append_span(_Span(start, len(text), str(open_tag)))
|
| 218 |
+
|
| 219 |
+
else: # Opening tag
|
| 220 |
+
normalized_tag = _Tag(normalize(tag.name), tag.parameters)
|
| 221 |
+
style_stack.append((len(text), normalized_tag))
|
| 222 |
+
|
| 223 |
+
text_length = len(text)
|
| 224 |
+
while style_stack:
|
| 225 |
+
start, tag = style_stack.pop()
|
| 226 |
+
style = str(tag)
|
| 227 |
+
if style:
|
| 228 |
+
append_span(_Span(start, text_length, style))
|
| 229 |
+
|
| 230 |
+
text.spans = sorted(spans[::-1], key=attrgetter("start"))
|
| 231 |
+
return text
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
if __name__ == "__main__": # pragma: no cover
|
| 235 |
+
MARKUP = [
|
| 236 |
+
"[red]Hello World[/red]",
|
| 237 |
+
"[magenta]Hello [b]World[/b]",
|
| 238 |
+
"[bold]Bold[italic] bold and italic [/bold]italic[/italic]",
|
| 239 |
+
"Click [link=https://www.willmcgugan.com]here[/link] to visit my Blog",
|
| 240 |
+
":warning-emoji: [bold red blink] DANGER![/]",
|
| 241 |
+
]
|
| 242 |
+
|
| 243 |
+
from rich import print
|
| 244 |
+
from rich.table import Table
|
| 245 |
+
|
| 246 |
+
grid = Table("Markup", "Result", padding=(0, 1))
|
| 247 |
+
|
| 248 |
+
for markup in MARKUP:
|
| 249 |
+
grid.add_row(Text(markup), markup)
|
| 250 |
+
|
| 251 |
+
print(grid)
|
miniconda3/lib/python3.13/site-packages/rich/measure.py
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from operator import itemgetter
|
| 2 |
+
from typing import TYPE_CHECKING, Callable, NamedTuple, Optional, Sequence
|
| 3 |
+
|
| 4 |
+
from . import errors
|
| 5 |
+
from .protocol import is_renderable, rich_cast
|
| 6 |
+
|
| 7 |
+
if TYPE_CHECKING:
|
| 8 |
+
from .console import Console, ConsoleOptions, RenderableType
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class Measurement(NamedTuple):
|
| 12 |
+
"""Stores the minimum and maximum widths (in characters) required to render an object."""
|
| 13 |
+
|
| 14 |
+
minimum: int
|
| 15 |
+
"""Minimum number of cells required to render."""
|
| 16 |
+
maximum: int
|
| 17 |
+
"""Maximum number of cells required to render."""
|
| 18 |
+
|
| 19 |
+
@property
|
| 20 |
+
def span(self) -> int:
|
| 21 |
+
"""Get difference between maximum and minimum."""
|
| 22 |
+
return self.maximum - self.minimum
|
| 23 |
+
|
| 24 |
+
def normalize(self) -> "Measurement":
|
| 25 |
+
"""Get measurement that ensures that minimum <= maximum and minimum >= 0
|
| 26 |
+
|
| 27 |
+
Returns:
|
| 28 |
+
Measurement: A normalized measurement.
|
| 29 |
+
"""
|
| 30 |
+
minimum, maximum = self
|
| 31 |
+
minimum = min(max(0, minimum), maximum)
|
| 32 |
+
return Measurement(max(0, minimum), max(0, max(minimum, maximum)))
|
| 33 |
+
|
| 34 |
+
def with_maximum(self, width: int) -> "Measurement":
|
| 35 |
+
"""Get a RenderableWith where the widths are <= width.
|
| 36 |
+
|
| 37 |
+
Args:
|
| 38 |
+
width (int): Maximum desired width.
|
| 39 |
+
|
| 40 |
+
Returns:
|
| 41 |
+
Measurement: New Measurement object.
|
| 42 |
+
"""
|
| 43 |
+
minimum, maximum = self
|
| 44 |
+
return Measurement(min(minimum, width), min(maximum, width))
|
| 45 |
+
|
| 46 |
+
def with_minimum(self, width: int) -> "Measurement":
|
| 47 |
+
"""Get a RenderableWith where the widths are >= width.
|
| 48 |
+
|
| 49 |
+
Args:
|
| 50 |
+
width (int): Minimum desired width.
|
| 51 |
+
|
| 52 |
+
Returns:
|
| 53 |
+
Measurement: New Measurement object.
|
| 54 |
+
"""
|
| 55 |
+
minimum, maximum = self
|
| 56 |
+
width = max(0, width)
|
| 57 |
+
return Measurement(max(minimum, width), max(maximum, width))
|
| 58 |
+
|
| 59 |
+
def clamp(
|
| 60 |
+
self, min_width: Optional[int] = None, max_width: Optional[int] = None
|
| 61 |
+
) -> "Measurement":
|
| 62 |
+
"""Clamp a measurement within the specified range.
|
| 63 |
+
|
| 64 |
+
Args:
|
| 65 |
+
min_width (int): Minimum desired width, or ``None`` for no minimum. Defaults to None.
|
| 66 |
+
max_width (int): Maximum desired width, or ``None`` for no maximum. Defaults to None.
|
| 67 |
+
|
| 68 |
+
Returns:
|
| 69 |
+
Measurement: New Measurement object.
|
| 70 |
+
"""
|
| 71 |
+
measurement = self
|
| 72 |
+
if min_width is not None:
|
| 73 |
+
measurement = measurement.with_minimum(min_width)
|
| 74 |
+
if max_width is not None:
|
| 75 |
+
measurement = measurement.with_maximum(max_width)
|
| 76 |
+
return measurement
|
| 77 |
+
|
| 78 |
+
@classmethod
|
| 79 |
+
def get(
|
| 80 |
+
cls, console: "Console", options: "ConsoleOptions", renderable: "RenderableType"
|
| 81 |
+
) -> "Measurement":
|
| 82 |
+
"""Get a measurement for a renderable.
|
| 83 |
+
|
| 84 |
+
Args:
|
| 85 |
+
console (~rich.console.Console): Console instance.
|
| 86 |
+
options (~rich.console.ConsoleOptions): Console options.
|
| 87 |
+
renderable (RenderableType): An object that may be rendered with Rich.
|
| 88 |
+
|
| 89 |
+
Raises:
|
| 90 |
+
errors.NotRenderableError: If the object is not renderable.
|
| 91 |
+
|
| 92 |
+
Returns:
|
| 93 |
+
Measurement: Measurement object containing range of character widths required to render the object.
|
| 94 |
+
"""
|
| 95 |
+
_max_width = options.max_width
|
| 96 |
+
if _max_width < 1:
|
| 97 |
+
return Measurement(0, 0)
|
| 98 |
+
if isinstance(renderable, str):
|
| 99 |
+
renderable = console.render_str(
|
| 100 |
+
renderable, markup=options.markup, highlight=False
|
| 101 |
+
)
|
| 102 |
+
renderable = rich_cast(renderable)
|
| 103 |
+
if is_renderable(renderable):
|
| 104 |
+
get_console_width: Optional[
|
| 105 |
+
Callable[["Console", "ConsoleOptions"], "Measurement"]
|
| 106 |
+
] = getattr(renderable, "__rich_measure__", None)
|
| 107 |
+
if get_console_width is not None:
|
| 108 |
+
render_width = (
|
| 109 |
+
get_console_width(console, options)
|
| 110 |
+
.normalize()
|
| 111 |
+
.with_maximum(_max_width)
|
| 112 |
+
)
|
| 113 |
+
if render_width.maximum < 1:
|
| 114 |
+
return Measurement(0, 0)
|
| 115 |
+
return render_width.normalize()
|
| 116 |
+
else:
|
| 117 |
+
return Measurement(0, _max_width)
|
| 118 |
+
else:
|
| 119 |
+
raise errors.NotRenderableError(
|
| 120 |
+
f"Unable to get render width for {renderable!r}; "
|
| 121 |
+
"a str, Segment, or object with __rich_console__ method is required"
|
| 122 |
+
)
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def measure_renderables(
|
| 126 |
+
console: "Console",
|
| 127 |
+
options: "ConsoleOptions",
|
| 128 |
+
renderables: Sequence["RenderableType"],
|
| 129 |
+
) -> "Measurement":
|
| 130 |
+
"""Get a measurement that would fit a number of renderables.
|
| 131 |
+
|
| 132 |
+
Args:
|
| 133 |
+
console (~rich.console.Console): Console instance.
|
| 134 |
+
options (~rich.console.ConsoleOptions): Console options.
|
| 135 |
+
renderables (Iterable[RenderableType]): One or more renderable objects.
|
| 136 |
+
|
| 137 |
+
Returns:
|
| 138 |
+
Measurement: Measurement object containing range of character widths required to
|
| 139 |
+
contain all given renderables.
|
| 140 |
+
"""
|
| 141 |
+
if not renderables:
|
| 142 |
+
return Measurement(0, 0)
|
| 143 |
+
get_measurement = Measurement.get
|
| 144 |
+
measurements = [
|
| 145 |
+
get_measurement(console, options, renderable) for renderable in renderables
|
| 146 |
+
]
|
| 147 |
+
measured_width = Measurement(
|
| 148 |
+
max(measurements, key=itemgetter(0)).minimum,
|
| 149 |
+
max(measurements, key=itemgetter(1)).maximum,
|
| 150 |
+
)
|
| 151 |
+
return measured_width
|
miniconda3/lib/python3.13/site-packages/rich/padding.py
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
|
|
|
|
|
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from .jupyter import JupyterMixin
|
| 12 |
+
from .measure import Measurement
|
| 13 |
+
from .segment import Segment
|
| 14 |
+
from .style import Style
|
| 15 |
+
|
| 16 |
+
PaddingDimensions = Union[int, Tuple[int], Tuple[int, int], Tuple[int, int, int, int]]
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class Padding(JupyterMixin):
|
| 20 |
+
"""Draw space around content.
|
| 21 |
+
|
| 22 |
+
Example:
|
| 23 |
+
>>> print(Padding("Hello", (2, 4), style="on blue"))
|
| 24 |
+
|
| 25 |
+
Args:
|
| 26 |
+
renderable (RenderableType): String or other renderable.
|
| 27 |
+
pad (Union[int, Tuple[int]]): Padding for top, right, bottom, and left borders.
|
| 28 |
+
May be specified with 1, 2, or 4 integers (CSS style).
|
| 29 |
+
style (Union[str, Style], optional): Style for padding characters. Defaults to "none".
|
| 30 |
+
expand (bool, optional): Expand padding to fit available width. Defaults to True.
|
| 31 |
+
"""
|
| 32 |
+
|
| 33 |
+
def __init__(
|
| 34 |
+
self,
|
| 35 |
+
renderable: "RenderableType",
|
| 36 |
+
pad: "PaddingDimensions" = (0, 0, 0, 0),
|
| 37 |
+
*,
|
| 38 |
+
style: Union[str, Style] = "none",
|
| 39 |
+
expand: bool = True,
|
| 40 |
+
):
|
| 41 |
+
self.renderable = renderable
|
| 42 |
+
self.top, self.right, self.bottom, self.left = self.unpack(pad)
|
| 43 |
+
self.style = style
|
| 44 |
+
self.expand = expand
|
| 45 |
+
|
| 46 |
+
@classmethod
|
| 47 |
+
def indent(cls, renderable: "RenderableType", level: int) -> "Padding":
|
| 48 |
+
"""Make padding instance to render an indent.
|
| 49 |
+
|
| 50 |
+
Args:
|
| 51 |
+
renderable (RenderableType): String or other renderable.
|
| 52 |
+
level (int): Number of characters to indent.
|
| 53 |
+
|
| 54 |
+
Returns:
|
| 55 |
+
Padding: A Padding instance.
|
| 56 |
+
"""
|
| 57 |
+
|
| 58 |
+
return Padding(renderable, pad=(0, 0, 0, level), expand=False)
|
| 59 |
+
|
| 60 |
+
@staticmethod
|
| 61 |
+
def unpack(pad: "PaddingDimensions") -> Tuple[int, int, int, int]:
|
| 62 |
+
"""Unpack padding specified in CSS style."""
|
| 63 |
+
if isinstance(pad, int):
|
| 64 |
+
return (pad, pad, pad, pad)
|
| 65 |
+
if len(pad) == 1:
|
| 66 |
+
_pad = pad[0]
|
| 67 |
+
return (_pad, _pad, _pad, _pad)
|
| 68 |
+
if len(pad) == 2:
|
| 69 |
+
pad_top, pad_right = pad
|
| 70 |
+
return (pad_top, pad_right, pad_top, pad_right)
|
| 71 |
+
if len(pad) == 4:
|
| 72 |
+
top, right, bottom, left = pad
|
| 73 |
+
return (top, right, bottom, left)
|
| 74 |
+
raise ValueError(f"1, 2 or 4 integers required for padding; {len(pad)} given")
|
| 75 |
+
|
| 76 |
+
def __repr__(self) -> str:
|
| 77 |
+
return f"Padding({self.renderable!r}, ({self.top},{self.right},{self.bottom},{self.left}))"
|
| 78 |
+
|
| 79 |
+
def __rich_console__(
|
| 80 |
+
self, console: "Console", options: "ConsoleOptions"
|
| 81 |
+
) -> "RenderResult":
|
| 82 |
+
style = console.get_style(self.style)
|
| 83 |
+
if self.expand:
|
| 84 |
+
width = options.max_width
|
| 85 |
+
else:
|
| 86 |
+
width = min(
|
| 87 |
+
Measurement.get(console, options, self.renderable).maximum
|
| 88 |
+
+ self.left
|
| 89 |
+
+ self.right,
|
| 90 |
+
options.max_width,
|
| 91 |
+
)
|
| 92 |
+
render_options = options.update_width(width - self.left - self.right)
|
| 93 |
+
if render_options.height is not None:
|
| 94 |
+
render_options = render_options.update_height(
|
| 95 |
+
height=render_options.height - self.top - self.bottom
|
| 96 |
+
)
|
| 97 |
+
lines = console.render_lines(
|
| 98 |
+
self.renderable, render_options, style=style, pad=True
|
| 99 |
+
)
|
| 100 |
+
_Segment = Segment
|
| 101 |
+
|
| 102 |
+
left = _Segment(" " * self.left, style) if self.left else None
|
| 103 |
+
right = (
|
| 104 |
+
[_Segment(f'{" " * self.right}', style), _Segment.line()]
|
| 105 |
+
if self.right
|
| 106 |
+
else [_Segment.line()]
|
| 107 |
+
)
|
| 108 |
+
blank_line: Optional[List[Segment]] = None
|
| 109 |
+
if self.top:
|
| 110 |
+
blank_line = [_Segment(f'{" " * width}\n', style)]
|
| 111 |
+
yield from blank_line * self.top
|
| 112 |
+
if left:
|
| 113 |
+
for line in lines:
|
| 114 |
+
yield left
|
| 115 |
+
yield from line
|
| 116 |
+
yield from right
|
| 117 |
+
else:
|
| 118 |
+
for line in lines:
|
| 119 |
+
yield from line
|
| 120 |
+
yield from right
|
| 121 |
+
if self.bottom:
|
| 122 |
+
blank_line = blank_line or [_Segment(f'{" " * width}\n', style)]
|
| 123 |
+
yield from blank_line * self.bottom
|
| 124 |
+
|
| 125 |
+
def __rich_measure__(
|
| 126 |
+
self, console: "Console", options: "ConsoleOptions"
|
| 127 |
+
) -> "Measurement":
|
| 128 |
+
max_width = options.max_width
|
| 129 |
+
extra_width = self.left + self.right
|
| 130 |
+
if max_width - extra_width < 1:
|
| 131 |
+
return Measurement(max_width, max_width)
|
| 132 |
+
measure_min, measure_max = Measurement.get(console, options, self.renderable)
|
| 133 |
+
measurement = Measurement(measure_min + extra_width, measure_max + extra_width)
|
| 134 |
+
measurement = measurement.with_maximum(max_width)
|
| 135 |
+
return measurement
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
if __name__ == "__main__": # pragma: no cover
|
| 139 |
+
from rich import print
|
| 140 |
+
|
| 141 |
+
print(Padding("Hello, World", (2, 4), style="on blue"))
|
miniconda3/lib/python3.13/site-packages/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())
|
miniconda3/lib/python3.13/site-packages/rich/palette.py
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from math import sqrt
|
| 2 |
+
from functools import lru_cache
|
| 3 |
+
from typing import Sequence, Tuple, TYPE_CHECKING
|
| 4 |
+
|
| 5 |
+
from .color_triplet import ColorTriplet
|
| 6 |
+
|
| 7 |
+
if TYPE_CHECKING:
|
| 8 |
+
from rich.table import Table
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class Palette:
|
| 12 |
+
"""A palette of available colors."""
|
| 13 |
+
|
| 14 |
+
def __init__(self, colors: Sequence[Tuple[int, int, int]]):
|
| 15 |
+
self._colors = colors
|
| 16 |
+
|
| 17 |
+
def __getitem__(self, number: int) -> ColorTriplet:
|
| 18 |
+
return ColorTriplet(*self._colors[number])
|
| 19 |
+
|
| 20 |
+
def __rich__(self) -> "Table":
|
| 21 |
+
from rich.color import Color
|
| 22 |
+
from rich.style import Style
|
| 23 |
+
from rich.text import Text
|
| 24 |
+
from rich.table import Table
|
| 25 |
+
|
| 26 |
+
table = Table(
|
| 27 |
+
"index",
|
| 28 |
+
"RGB",
|
| 29 |
+
"Color",
|
| 30 |
+
title="Palette",
|
| 31 |
+
caption=f"{len(self._colors)} colors",
|
| 32 |
+
highlight=True,
|
| 33 |
+
caption_justify="right",
|
| 34 |
+
)
|
| 35 |
+
for index, color in enumerate(self._colors):
|
| 36 |
+
table.add_row(
|
| 37 |
+
str(index),
|
| 38 |
+
repr(color),
|
| 39 |
+
Text(" " * 16, style=Style(bgcolor=Color.from_rgb(*color))),
|
| 40 |
+
)
|
| 41 |
+
return table
|
| 42 |
+
|
| 43 |
+
# This is somewhat inefficient and needs caching
|
| 44 |
+
@lru_cache(maxsize=1024)
|
| 45 |
+
def match(self, color: Tuple[int, int, int]) -> int:
|
| 46 |
+
"""Find a color from a palette that most closely matches a given color.
|
| 47 |
+
|
| 48 |
+
Args:
|
| 49 |
+
color (Tuple[int, int, int]): RGB components in range 0 > 255.
|
| 50 |
+
|
| 51 |
+
Returns:
|
| 52 |
+
int: Index of closes matching color.
|
| 53 |
+
"""
|
| 54 |
+
red1, green1, blue1 = color
|
| 55 |
+
_sqrt = sqrt
|
| 56 |
+
get_color = self._colors.__getitem__
|
| 57 |
+
|
| 58 |
+
def get_color_distance(index: int) -> float:
|
| 59 |
+
"""Get the distance to a color."""
|
| 60 |
+
red2, green2, blue2 = get_color(index)
|
| 61 |
+
red_mean = (red1 + red2) // 2
|
| 62 |
+
red = red1 - red2
|
| 63 |
+
green = green1 - green2
|
| 64 |
+
blue = blue1 - blue2
|
| 65 |
+
return _sqrt(
|
| 66 |
+
(((512 + red_mean) * red * red) >> 8)
|
| 67 |
+
+ 4 * green * green
|
| 68 |
+
+ (((767 - red_mean) * blue * blue) >> 8)
|
| 69 |
+
)
|
| 70 |
+
|
| 71 |
+
min_index = min(range(len(self._colors)), key=get_color_distance)
|
| 72 |
+
return min_index
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
if __name__ == "__main__": # pragma: no cover
|
| 76 |
+
import colorsys
|
| 77 |
+
from typing import Iterable
|
| 78 |
+
from rich.color import Color
|
| 79 |
+
from rich.console import Console, ConsoleOptions
|
| 80 |
+
from rich.segment import Segment
|
| 81 |
+
from rich.style import Style
|
| 82 |
+
|
| 83 |
+
class ColorBox:
|
| 84 |
+
def __rich_console__(
|
| 85 |
+
self, console: Console, options: ConsoleOptions
|
| 86 |
+
) -> Iterable[Segment]:
|
| 87 |
+
height = console.size.height - 3
|
| 88 |
+
for y in range(0, height):
|
| 89 |
+
for x in range(options.max_width):
|
| 90 |
+
h = x / options.max_width
|
| 91 |
+
l = y / (height + 1)
|
| 92 |
+
r1, g1, b1 = colorsys.hls_to_rgb(h, l, 1.0)
|
| 93 |
+
r2, g2, b2 = colorsys.hls_to_rgb(h, l + (1 / height / 2), 1.0)
|
| 94 |
+
bgcolor = Color.from_rgb(r1 * 255, g1 * 255, b1 * 255)
|
| 95 |
+
color = Color.from_rgb(r2 * 255, g2 * 255, b2 * 255)
|
| 96 |
+
yield Segment("▄", Style(color=color, bgcolor=bgcolor))
|
| 97 |
+
yield Segment.line()
|
| 98 |
+
|
| 99 |
+
console = Console()
|
| 100 |
+
console.print(ColorBox())
|
miniconda3/lib/python3.13/site-packages/rich/panel.py
ADDED
|
@@ -0,0 +1,317 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import TYPE_CHECKING, Optional
|
| 2 |
+
|
| 3 |
+
from .align import AlignMethod
|
| 4 |
+
from .box import ROUNDED, Box
|
| 5 |
+
from .cells import cell_len
|
| 6 |
+
from .jupyter import JupyterMixin
|
| 7 |
+
from .measure import Measurement, measure_renderables
|
| 8 |
+
from .padding import Padding, PaddingDimensions
|
| 9 |
+
from .segment import Segment
|
| 10 |
+
from .style import Style, StyleType
|
| 11 |
+
from .text import Text, TextType
|
| 12 |
+
|
| 13 |
+
if TYPE_CHECKING:
|
| 14 |
+
from .console import Console, ConsoleOptions, RenderableType, RenderResult
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class Panel(JupyterMixin):
|
| 18 |
+
"""A console renderable that draws a border around its contents.
|
| 19 |
+
|
| 20 |
+
Example:
|
| 21 |
+
>>> console.print(Panel("Hello, World!"))
|
| 22 |
+
|
| 23 |
+
Args:
|
| 24 |
+
renderable (RenderableType): A console renderable object.
|
| 25 |
+
box (Box): A Box instance that defines the look of the border (see :ref:`appendix_box`. Defaults to box.ROUNDED.
|
| 26 |
+
title (Optional[TextType], optional): Optional title displayed in panel header. Defaults to None.
|
| 27 |
+
title_align (AlignMethod, optional): Alignment of title. Defaults to "center".
|
| 28 |
+
subtitle (Optional[TextType], optional): Optional subtitle displayed in panel footer. Defaults to None.
|
| 29 |
+
subtitle_align (AlignMethod, optional): Alignment of subtitle. Defaults to "center".
|
| 30 |
+
safe_box (bool, optional): Disable box characters that don't display on windows legacy terminal with *raster* fonts. Defaults to True.
|
| 31 |
+
expand (bool, optional): If True the panel will stretch to fill the console width, otherwise it will be sized to fit the contents. Defaults to True.
|
| 32 |
+
style (str, optional): The style of the panel (border and contents). Defaults to "none".
|
| 33 |
+
border_style (str, optional): The style of the border. Defaults to "none".
|
| 34 |
+
width (Optional[int], optional): Optional width of panel. Defaults to None to auto-detect.
|
| 35 |
+
height (Optional[int], optional): Optional height of panel. Defaults to None to auto-detect.
|
| 36 |
+
padding (Optional[PaddingDimensions]): Optional padding around renderable. Defaults to 0.
|
| 37 |
+
highlight (bool, optional): Enable automatic highlighting of panel title (if str). Defaults to False.
|
| 38 |
+
"""
|
| 39 |
+
|
| 40 |
+
def __init__(
|
| 41 |
+
self,
|
| 42 |
+
renderable: "RenderableType",
|
| 43 |
+
box: Box = ROUNDED,
|
| 44 |
+
*,
|
| 45 |
+
title: Optional[TextType] = None,
|
| 46 |
+
title_align: AlignMethod = "center",
|
| 47 |
+
subtitle: Optional[TextType] = None,
|
| 48 |
+
subtitle_align: AlignMethod = "center",
|
| 49 |
+
safe_box: Optional[bool] = None,
|
| 50 |
+
expand: bool = True,
|
| 51 |
+
style: StyleType = "none",
|
| 52 |
+
border_style: StyleType = "none",
|
| 53 |
+
width: Optional[int] = None,
|
| 54 |
+
height: Optional[int] = None,
|
| 55 |
+
padding: PaddingDimensions = (0, 1),
|
| 56 |
+
highlight: bool = False,
|
| 57 |
+
) -> None:
|
| 58 |
+
self.renderable = renderable
|
| 59 |
+
self.box = box
|
| 60 |
+
self.title = title
|
| 61 |
+
self.title_align: AlignMethod = title_align
|
| 62 |
+
self.subtitle = subtitle
|
| 63 |
+
self.subtitle_align = subtitle_align
|
| 64 |
+
self.safe_box = safe_box
|
| 65 |
+
self.expand = expand
|
| 66 |
+
self.style = style
|
| 67 |
+
self.border_style = border_style
|
| 68 |
+
self.width = width
|
| 69 |
+
self.height = height
|
| 70 |
+
self.padding = padding
|
| 71 |
+
self.highlight = highlight
|
| 72 |
+
|
| 73 |
+
@classmethod
|
| 74 |
+
def fit(
|
| 75 |
+
cls,
|
| 76 |
+
renderable: "RenderableType",
|
| 77 |
+
box: Box = ROUNDED,
|
| 78 |
+
*,
|
| 79 |
+
title: Optional[TextType] = None,
|
| 80 |
+
title_align: AlignMethod = "center",
|
| 81 |
+
subtitle: Optional[TextType] = None,
|
| 82 |
+
subtitle_align: AlignMethod = "center",
|
| 83 |
+
safe_box: Optional[bool] = None,
|
| 84 |
+
style: StyleType = "none",
|
| 85 |
+
border_style: StyleType = "none",
|
| 86 |
+
width: Optional[int] = None,
|
| 87 |
+
height: Optional[int] = None,
|
| 88 |
+
padding: PaddingDimensions = (0, 1),
|
| 89 |
+
highlight: bool = False,
|
| 90 |
+
) -> "Panel":
|
| 91 |
+
"""An alternative constructor that sets expand=False."""
|
| 92 |
+
return cls(
|
| 93 |
+
renderable,
|
| 94 |
+
box,
|
| 95 |
+
title=title,
|
| 96 |
+
title_align=title_align,
|
| 97 |
+
subtitle=subtitle,
|
| 98 |
+
subtitle_align=subtitle_align,
|
| 99 |
+
safe_box=safe_box,
|
| 100 |
+
style=style,
|
| 101 |
+
border_style=border_style,
|
| 102 |
+
width=width,
|
| 103 |
+
height=height,
|
| 104 |
+
padding=padding,
|
| 105 |
+
highlight=highlight,
|
| 106 |
+
expand=False,
|
| 107 |
+
)
|
| 108 |
+
|
| 109 |
+
@property
|
| 110 |
+
def _title(self) -> Optional[Text]:
|
| 111 |
+
if self.title:
|
| 112 |
+
title_text = (
|
| 113 |
+
Text.from_markup(self.title)
|
| 114 |
+
if isinstance(self.title, str)
|
| 115 |
+
else self.title.copy()
|
| 116 |
+
)
|
| 117 |
+
title_text.end = ""
|
| 118 |
+
title_text.plain = title_text.plain.replace("\n", " ")
|
| 119 |
+
title_text.no_wrap = True
|
| 120 |
+
title_text.expand_tabs()
|
| 121 |
+
title_text.pad(1)
|
| 122 |
+
return title_text
|
| 123 |
+
return None
|
| 124 |
+
|
| 125 |
+
@property
|
| 126 |
+
def _subtitle(self) -> Optional[Text]:
|
| 127 |
+
if self.subtitle:
|
| 128 |
+
subtitle_text = (
|
| 129 |
+
Text.from_markup(self.subtitle)
|
| 130 |
+
if isinstance(self.subtitle, str)
|
| 131 |
+
else self.subtitle.copy()
|
| 132 |
+
)
|
| 133 |
+
subtitle_text.end = ""
|
| 134 |
+
subtitle_text.plain = subtitle_text.plain.replace("\n", " ")
|
| 135 |
+
subtitle_text.no_wrap = True
|
| 136 |
+
subtitle_text.expand_tabs()
|
| 137 |
+
subtitle_text.pad(1)
|
| 138 |
+
return subtitle_text
|
| 139 |
+
return None
|
| 140 |
+
|
| 141 |
+
def __rich_console__(
|
| 142 |
+
self, console: "Console", options: "ConsoleOptions"
|
| 143 |
+
) -> "RenderResult":
|
| 144 |
+
_padding = Padding.unpack(self.padding)
|
| 145 |
+
renderable = (
|
| 146 |
+
Padding(self.renderable, _padding) if any(_padding) else self.renderable
|
| 147 |
+
)
|
| 148 |
+
style = console.get_style(self.style)
|
| 149 |
+
border_style = style + console.get_style(self.border_style)
|
| 150 |
+
width = (
|
| 151 |
+
options.max_width
|
| 152 |
+
if self.width is None
|
| 153 |
+
else min(options.max_width, self.width)
|
| 154 |
+
)
|
| 155 |
+
|
| 156 |
+
safe_box: bool = console.safe_box if self.safe_box is None else self.safe_box
|
| 157 |
+
box = self.box.substitute(options, safe=safe_box)
|
| 158 |
+
|
| 159 |
+
def align_text(
|
| 160 |
+
text: Text, width: int, align: str, character: str, style: Style
|
| 161 |
+
) -> Text:
|
| 162 |
+
"""Gets new aligned text.
|
| 163 |
+
|
| 164 |
+
Args:
|
| 165 |
+
text (Text): Title or subtitle text.
|
| 166 |
+
width (int): Desired width.
|
| 167 |
+
align (str): Alignment.
|
| 168 |
+
character (str): Character for alignment.
|
| 169 |
+
style (Style): Border style
|
| 170 |
+
|
| 171 |
+
Returns:
|
| 172 |
+
Text: New text instance
|
| 173 |
+
"""
|
| 174 |
+
text = text.copy()
|
| 175 |
+
text.truncate(width)
|
| 176 |
+
excess_space = width - cell_len(text.plain)
|
| 177 |
+
if text.style:
|
| 178 |
+
text.stylize(console.get_style(text.style))
|
| 179 |
+
|
| 180 |
+
if excess_space:
|
| 181 |
+
if align == "left":
|
| 182 |
+
return Text.assemble(
|
| 183 |
+
text,
|
| 184 |
+
(character * excess_space, style),
|
| 185 |
+
no_wrap=True,
|
| 186 |
+
end="",
|
| 187 |
+
)
|
| 188 |
+
elif align == "center":
|
| 189 |
+
left = excess_space // 2
|
| 190 |
+
return Text.assemble(
|
| 191 |
+
(character * left, style),
|
| 192 |
+
text,
|
| 193 |
+
(character * (excess_space - left), style),
|
| 194 |
+
no_wrap=True,
|
| 195 |
+
end="",
|
| 196 |
+
)
|
| 197 |
+
else:
|
| 198 |
+
return Text.assemble(
|
| 199 |
+
(character * excess_space, style),
|
| 200 |
+
text,
|
| 201 |
+
no_wrap=True,
|
| 202 |
+
end="",
|
| 203 |
+
)
|
| 204 |
+
return text
|
| 205 |
+
|
| 206 |
+
title_text = self._title
|
| 207 |
+
if title_text is not None:
|
| 208 |
+
title_text.stylize_before(border_style)
|
| 209 |
+
|
| 210 |
+
child_width = (
|
| 211 |
+
width - 2
|
| 212 |
+
if self.expand
|
| 213 |
+
else console.measure(
|
| 214 |
+
renderable, options=options.update_width(width - 2)
|
| 215 |
+
).maximum
|
| 216 |
+
)
|
| 217 |
+
child_height = self.height or options.height or None
|
| 218 |
+
if child_height:
|
| 219 |
+
child_height -= 2
|
| 220 |
+
if title_text is not None:
|
| 221 |
+
child_width = min(
|
| 222 |
+
options.max_width - 2, max(child_width, title_text.cell_len + 2)
|
| 223 |
+
)
|
| 224 |
+
|
| 225 |
+
width = child_width + 2
|
| 226 |
+
child_options = options.update(
|
| 227 |
+
width=child_width, height=child_height, highlight=self.highlight
|
| 228 |
+
)
|
| 229 |
+
lines = console.render_lines(renderable, child_options, style=style)
|
| 230 |
+
|
| 231 |
+
line_start = Segment(box.mid_left, border_style)
|
| 232 |
+
line_end = Segment(f"{box.mid_right}", border_style)
|
| 233 |
+
new_line = Segment.line()
|
| 234 |
+
if title_text is None or width <= 4:
|
| 235 |
+
yield Segment(box.get_top([width - 2]), border_style)
|
| 236 |
+
else:
|
| 237 |
+
title_text = align_text(
|
| 238 |
+
title_text,
|
| 239 |
+
width - 4,
|
| 240 |
+
self.title_align,
|
| 241 |
+
box.top,
|
| 242 |
+
border_style,
|
| 243 |
+
)
|
| 244 |
+
yield Segment(box.top_left + box.top, border_style)
|
| 245 |
+
yield from console.render(title_text, child_options.update_width(width - 4))
|
| 246 |
+
yield Segment(box.top + box.top_right, border_style)
|
| 247 |
+
|
| 248 |
+
yield new_line
|
| 249 |
+
for line in lines:
|
| 250 |
+
yield line_start
|
| 251 |
+
yield from line
|
| 252 |
+
yield line_end
|
| 253 |
+
yield new_line
|
| 254 |
+
|
| 255 |
+
subtitle_text = self._subtitle
|
| 256 |
+
if subtitle_text is not None:
|
| 257 |
+
subtitle_text.stylize_before(border_style)
|
| 258 |
+
|
| 259 |
+
if subtitle_text is None or width <= 4:
|
| 260 |
+
yield Segment(box.get_bottom([width - 2]), border_style)
|
| 261 |
+
else:
|
| 262 |
+
subtitle_text = align_text(
|
| 263 |
+
subtitle_text,
|
| 264 |
+
width - 4,
|
| 265 |
+
self.subtitle_align,
|
| 266 |
+
box.bottom,
|
| 267 |
+
border_style,
|
| 268 |
+
)
|
| 269 |
+
yield Segment(box.bottom_left + box.bottom, border_style)
|
| 270 |
+
yield from console.render(
|
| 271 |
+
subtitle_text, child_options.update_width(width - 4)
|
| 272 |
+
)
|
| 273 |
+
yield Segment(box.bottom + box.bottom_right, border_style)
|
| 274 |
+
|
| 275 |
+
yield new_line
|
| 276 |
+
|
| 277 |
+
def __rich_measure__(
|
| 278 |
+
self, console: "Console", options: "ConsoleOptions"
|
| 279 |
+
) -> "Measurement":
|
| 280 |
+
_title = self._title
|
| 281 |
+
_, right, _, left = Padding.unpack(self.padding)
|
| 282 |
+
padding = left + right
|
| 283 |
+
renderables = [self.renderable, _title] if _title else [self.renderable]
|
| 284 |
+
|
| 285 |
+
if self.width is None:
|
| 286 |
+
width = (
|
| 287 |
+
measure_renderables(
|
| 288 |
+
console,
|
| 289 |
+
options.update_width(options.max_width - padding - 2),
|
| 290 |
+
renderables,
|
| 291 |
+
).maximum
|
| 292 |
+
+ padding
|
| 293 |
+
+ 2
|
| 294 |
+
)
|
| 295 |
+
else:
|
| 296 |
+
width = self.width
|
| 297 |
+
return Measurement(width, width)
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
if __name__ == "__main__": # pragma: no cover
|
| 301 |
+
from .console import Console
|
| 302 |
+
|
| 303 |
+
c = Console()
|
| 304 |
+
|
| 305 |
+
from .box import DOUBLE, ROUNDED
|
| 306 |
+
from .padding import Padding
|
| 307 |
+
|
| 308 |
+
p = Panel(
|
| 309 |
+
"Hello, World!",
|
| 310 |
+
title="rich.Panel",
|
| 311 |
+
style="white on blue",
|
| 312 |
+
box=DOUBLE,
|
| 313 |
+
padding=1,
|
| 314 |
+
)
|
| 315 |
+
|
| 316 |
+
c.print()
|
| 317 |
+
c.print(p)
|
miniconda3/lib/python3.13/site-packages/rich/pretty.py
ADDED
|
@@ -0,0 +1,1016 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import builtins
|
| 2 |
+
import collections
|
| 3 |
+
import dataclasses
|
| 4 |
+
import inspect
|
| 5 |
+
import os
|
| 6 |
+
import reprlib
|
| 7 |
+
import sys
|
| 8 |
+
from array import array
|
| 9 |
+
from collections import Counter, UserDict, UserList, defaultdict, deque
|
| 10 |
+
from dataclasses import dataclass, fields, is_dataclass
|
| 11 |
+
from inspect import isclass
|
| 12 |
+
from itertools import islice
|
| 13 |
+
from types import MappingProxyType
|
| 14 |
+
from typing import (
|
| 15 |
+
TYPE_CHECKING,
|
| 16 |
+
Any,
|
| 17 |
+
Callable,
|
| 18 |
+
DefaultDict,
|
| 19 |
+
Deque,
|
| 20 |
+
Dict,
|
| 21 |
+
Iterable,
|
| 22 |
+
List,
|
| 23 |
+
Optional,
|
| 24 |
+
Sequence,
|
| 25 |
+
Set,
|
| 26 |
+
Tuple,
|
| 27 |
+
Union,
|
| 28 |
+
)
|
| 29 |
+
|
| 30 |
+
from rich.repr import RichReprResult
|
| 31 |
+
|
| 32 |
+
try:
|
| 33 |
+
import attr as _attr_module
|
| 34 |
+
|
| 35 |
+
_has_attrs = hasattr(_attr_module, "ib")
|
| 36 |
+
except ImportError: # pragma: no cover
|
| 37 |
+
_has_attrs = False
|
| 38 |
+
|
| 39 |
+
from . import get_console
|
| 40 |
+
from ._loop import loop_last
|
| 41 |
+
from ._pick import pick_bool
|
| 42 |
+
from .abc import RichRenderable
|
| 43 |
+
from .cells import cell_len
|
| 44 |
+
from .highlighter import ReprHighlighter
|
| 45 |
+
from .jupyter import JupyterMixin, JupyterRenderable
|
| 46 |
+
from .measure import Measurement
|
| 47 |
+
from .text import Text
|
| 48 |
+
|
| 49 |
+
if TYPE_CHECKING:
|
| 50 |
+
from .console import (
|
| 51 |
+
Console,
|
| 52 |
+
ConsoleOptions,
|
| 53 |
+
HighlighterType,
|
| 54 |
+
JustifyMethod,
|
| 55 |
+
OverflowMethod,
|
| 56 |
+
RenderResult,
|
| 57 |
+
)
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def _is_attr_object(obj: Any) -> bool:
|
| 61 |
+
"""Check if an object was created with attrs module."""
|
| 62 |
+
return _has_attrs and _attr_module.has(type(obj))
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def _get_attr_fields(obj: Any) -> Sequence["_attr_module.Attribute[Any]"]:
|
| 66 |
+
"""Get fields for an attrs object."""
|
| 67 |
+
return _attr_module.fields(type(obj)) if _has_attrs else []
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def _is_dataclass_repr(obj: object) -> bool:
|
| 71 |
+
"""Check if an instance of a dataclass contains the default repr.
|
| 72 |
+
|
| 73 |
+
Args:
|
| 74 |
+
obj (object): A dataclass instance.
|
| 75 |
+
|
| 76 |
+
Returns:
|
| 77 |
+
bool: True if the default repr is used, False if there is a custom repr.
|
| 78 |
+
"""
|
| 79 |
+
# Digging in to a lot of internals here
|
| 80 |
+
# Catching all exceptions in case something is missing on a non CPython implementation
|
| 81 |
+
try:
|
| 82 |
+
return obj.__repr__.__code__.co_filename in (
|
| 83 |
+
dataclasses.__file__,
|
| 84 |
+
reprlib.__file__,
|
| 85 |
+
)
|
| 86 |
+
except Exception: # pragma: no coverage
|
| 87 |
+
return False
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
_dummy_namedtuple = collections.namedtuple("_dummy_namedtuple", [])
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def _has_default_namedtuple_repr(obj: object) -> bool:
|
| 94 |
+
"""Check if an instance of namedtuple contains the default repr
|
| 95 |
+
|
| 96 |
+
Args:
|
| 97 |
+
obj (object): A namedtuple
|
| 98 |
+
|
| 99 |
+
Returns:
|
| 100 |
+
bool: True if the default repr is used, False if there's a custom repr.
|
| 101 |
+
"""
|
| 102 |
+
obj_file = None
|
| 103 |
+
try:
|
| 104 |
+
obj_file = inspect.getfile(obj.__repr__)
|
| 105 |
+
except (OSError, TypeError):
|
| 106 |
+
# OSError handles case where object is defined in __main__ scope, e.g. REPL - no filename available.
|
| 107 |
+
# TypeError trapped defensively, in case of object without filename slips through.
|
| 108 |
+
pass
|
| 109 |
+
default_repr_file = inspect.getfile(_dummy_namedtuple.__repr__)
|
| 110 |
+
return obj_file == default_repr_file
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def _ipy_display_hook(
|
| 114 |
+
value: Any,
|
| 115 |
+
console: Optional["Console"] = None,
|
| 116 |
+
overflow: "OverflowMethod" = "ignore",
|
| 117 |
+
crop: bool = False,
|
| 118 |
+
indent_guides: bool = False,
|
| 119 |
+
max_length: Optional[int] = None,
|
| 120 |
+
max_string: Optional[int] = None,
|
| 121 |
+
max_depth: Optional[int] = None,
|
| 122 |
+
expand_all: bool = False,
|
| 123 |
+
) -> Union[str, None]:
|
| 124 |
+
# needed here to prevent circular import:
|
| 125 |
+
from .console import ConsoleRenderable
|
| 126 |
+
|
| 127 |
+
# always skip rich generated jupyter renderables or None values
|
| 128 |
+
if _safe_isinstance(value, JupyterRenderable) or value is None:
|
| 129 |
+
return None
|
| 130 |
+
|
| 131 |
+
console = console or get_console()
|
| 132 |
+
|
| 133 |
+
with console.capture() as capture:
|
| 134 |
+
# certain renderables should start on a new line
|
| 135 |
+
if _safe_isinstance(value, ConsoleRenderable):
|
| 136 |
+
console.line()
|
| 137 |
+
console.print(
|
| 138 |
+
(
|
| 139 |
+
value
|
| 140 |
+
if _safe_isinstance(value, RichRenderable)
|
| 141 |
+
else Pretty(
|
| 142 |
+
value,
|
| 143 |
+
overflow=overflow,
|
| 144 |
+
indent_guides=indent_guides,
|
| 145 |
+
max_length=max_length,
|
| 146 |
+
max_string=max_string,
|
| 147 |
+
max_depth=max_depth,
|
| 148 |
+
expand_all=expand_all,
|
| 149 |
+
margin=12,
|
| 150 |
+
)
|
| 151 |
+
),
|
| 152 |
+
crop=crop,
|
| 153 |
+
new_line_start=True,
|
| 154 |
+
end="",
|
| 155 |
+
)
|
| 156 |
+
# strip trailing newline, not usually part of a text repr
|
| 157 |
+
# I'm not sure if this should be prevented at a lower level
|
| 158 |
+
return capture.get().rstrip("\n")
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def _safe_isinstance(
|
| 162 |
+
obj: object, class_or_tuple: Union[type, Tuple[type, ...]]
|
| 163 |
+
) -> bool:
|
| 164 |
+
"""isinstance can fail in rare cases, for example types with no __class__"""
|
| 165 |
+
try:
|
| 166 |
+
return isinstance(obj, class_or_tuple)
|
| 167 |
+
except Exception:
|
| 168 |
+
return False
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
def install(
|
| 172 |
+
console: Optional["Console"] = None,
|
| 173 |
+
overflow: "OverflowMethod" = "ignore",
|
| 174 |
+
crop: bool = False,
|
| 175 |
+
indent_guides: bool = False,
|
| 176 |
+
max_length: Optional[int] = None,
|
| 177 |
+
max_string: Optional[int] = None,
|
| 178 |
+
max_depth: Optional[int] = None,
|
| 179 |
+
expand_all: bool = False,
|
| 180 |
+
) -> None:
|
| 181 |
+
"""Install automatic pretty printing in the Python REPL.
|
| 182 |
+
|
| 183 |
+
Args:
|
| 184 |
+
console (Console, optional): Console instance or ``None`` to use global console. Defaults to None.
|
| 185 |
+
overflow (Optional[OverflowMethod], optional): Overflow method. Defaults to "ignore".
|
| 186 |
+
crop (Optional[bool], optional): Enable cropping of long lines. Defaults to False.
|
| 187 |
+
indent_guides (bool, optional): Enable indentation guides. Defaults to False.
|
| 188 |
+
max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation.
|
| 189 |
+
Defaults to None.
|
| 190 |
+
max_string (int, optional): Maximum length of string before truncating, or None to disable. Defaults to None.
|
| 191 |
+
max_depth (int, optional): Maximum depth of nested data structures, or None for no maximum. Defaults to None.
|
| 192 |
+
expand_all (bool, optional): Expand all containers. Defaults to False.
|
| 193 |
+
max_frames (int): Maximum number of frames to show in a traceback, 0 for no maximum. Defaults to 100.
|
| 194 |
+
"""
|
| 195 |
+
from rich import get_console
|
| 196 |
+
|
| 197 |
+
console = console or get_console()
|
| 198 |
+
assert console is not None
|
| 199 |
+
|
| 200 |
+
def display_hook(value: Any) -> None:
|
| 201 |
+
"""Replacement sys.displayhook which prettifies objects with Rich."""
|
| 202 |
+
if value is not None:
|
| 203 |
+
assert console is not None
|
| 204 |
+
builtins._ = None # type: ignore[attr-defined]
|
| 205 |
+
console.print(
|
| 206 |
+
(
|
| 207 |
+
value
|
| 208 |
+
if _safe_isinstance(value, RichRenderable)
|
| 209 |
+
else Pretty(
|
| 210 |
+
value,
|
| 211 |
+
overflow=overflow,
|
| 212 |
+
indent_guides=indent_guides,
|
| 213 |
+
max_length=max_length,
|
| 214 |
+
max_string=max_string,
|
| 215 |
+
max_depth=max_depth,
|
| 216 |
+
expand_all=expand_all,
|
| 217 |
+
)
|
| 218 |
+
),
|
| 219 |
+
crop=crop,
|
| 220 |
+
)
|
| 221 |
+
builtins._ = value # type: ignore[attr-defined]
|
| 222 |
+
|
| 223 |
+
try:
|
| 224 |
+
ip = get_ipython() # type: ignore[name-defined]
|
| 225 |
+
except NameError:
|
| 226 |
+
sys.displayhook = display_hook
|
| 227 |
+
else:
|
| 228 |
+
from IPython.core.formatters import BaseFormatter
|
| 229 |
+
|
| 230 |
+
class RichFormatter(BaseFormatter): # type: ignore[misc]
|
| 231 |
+
pprint: bool = True
|
| 232 |
+
|
| 233 |
+
def __call__(self, value: Any) -> Any:
|
| 234 |
+
if self.pprint:
|
| 235 |
+
return _ipy_display_hook(
|
| 236 |
+
value,
|
| 237 |
+
console=get_console(),
|
| 238 |
+
overflow=overflow,
|
| 239 |
+
indent_guides=indent_guides,
|
| 240 |
+
max_length=max_length,
|
| 241 |
+
max_string=max_string,
|
| 242 |
+
max_depth=max_depth,
|
| 243 |
+
expand_all=expand_all,
|
| 244 |
+
)
|
| 245 |
+
else:
|
| 246 |
+
return repr(value)
|
| 247 |
+
|
| 248 |
+
# replace plain text formatter with rich formatter
|
| 249 |
+
rich_formatter = RichFormatter()
|
| 250 |
+
ip.display_formatter.formatters["text/plain"] = rich_formatter
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
class Pretty(JupyterMixin):
|
| 254 |
+
"""A rich renderable that pretty prints an object.
|
| 255 |
+
|
| 256 |
+
Args:
|
| 257 |
+
_object (Any): An object to pretty print.
|
| 258 |
+
highlighter (HighlighterType, optional): Highlighter object to apply to result, or None for ReprHighlighter. Defaults to None.
|
| 259 |
+
indent_size (int, optional): Number of spaces in indent. Defaults to 4.
|
| 260 |
+
justify (JustifyMethod, optional): Justify method, or None for default. Defaults to None.
|
| 261 |
+
overflow (OverflowMethod, optional): Overflow method, or None for default. Defaults to None.
|
| 262 |
+
no_wrap (Optional[bool], optional): Disable word wrapping. Defaults to False.
|
| 263 |
+
indent_guides (bool, optional): Enable indentation guides. Defaults to False.
|
| 264 |
+
max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation.
|
| 265 |
+
Defaults to None.
|
| 266 |
+
max_string (int, optional): Maximum length of string before truncating, or None to disable. Defaults to None.
|
| 267 |
+
max_depth (int, optional): Maximum depth of nested data structures, or None for no maximum. Defaults to None.
|
| 268 |
+
expand_all (bool, optional): Expand all containers. Defaults to False.
|
| 269 |
+
margin (int, optional): Subtrace a margin from width to force containers to expand earlier. Defaults to 0.
|
| 270 |
+
insert_line (bool, optional): Insert a new line if the output has multiple new lines. Defaults to False.
|
| 271 |
+
"""
|
| 272 |
+
|
| 273 |
+
def __init__(
|
| 274 |
+
self,
|
| 275 |
+
_object: Any,
|
| 276 |
+
highlighter: Optional["HighlighterType"] = None,
|
| 277 |
+
*,
|
| 278 |
+
indent_size: int = 4,
|
| 279 |
+
justify: Optional["JustifyMethod"] = None,
|
| 280 |
+
overflow: Optional["OverflowMethod"] = None,
|
| 281 |
+
no_wrap: Optional[bool] = False,
|
| 282 |
+
indent_guides: bool = False,
|
| 283 |
+
max_length: Optional[int] = None,
|
| 284 |
+
max_string: Optional[int] = None,
|
| 285 |
+
max_depth: Optional[int] = None,
|
| 286 |
+
expand_all: bool = False,
|
| 287 |
+
margin: int = 0,
|
| 288 |
+
insert_line: bool = False,
|
| 289 |
+
) -> None:
|
| 290 |
+
self._object = _object
|
| 291 |
+
self.highlighter = highlighter or ReprHighlighter()
|
| 292 |
+
self.indent_size = indent_size
|
| 293 |
+
self.justify: Optional["JustifyMethod"] = justify
|
| 294 |
+
self.overflow: Optional["OverflowMethod"] = overflow
|
| 295 |
+
self.no_wrap = no_wrap
|
| 296 |
+
self.indent_guides = indent_guides
|
| 297 |
+
self.max_length = max_length
|
| 298 |
+
self.max_string = max_string
|
| 299 |
+
self.max_depth = max_depth
|
| 300 |
+
self.expand_all = expand_all
|
| 301 |
+
self.margin = margin
|
| 302 |
+
self.insert_line = insert_line
|
| 303 |
+
|
| 304 |
+
def __rich_console__(
|
| 305 |
+
self, console: "Console", options: "ConsoleOptions"
|
| 306 |
+
) -> "RenderResult":
|
| 307 |
+
pretty_str = pretty_repr(
|
| 308 |
+
self._object,
|
| 309 |
+
max_width=options.max_width - self.margin,
|
| 310 |
+
indent_size=self.indent_size,
|
| 311 |
+
max_length=self.max_length,
|
| 312 |
+
max_string=self.max_string,
|
| 313 |
+
max_depth=self.max_depth,
|
| 314 |
+
expand_all=self.expand_all,
|
| 315 |
+
)
|
| 316 |
+
pretty_text = Text.from_ansi(
|
| 317 |
+
pretty_str,
|
| 318 |
+
justify=self.justify or options.justify,
|
| 319 |
+
overflow=self.overflow or options.overflow,
|
| 320 |
+
no_wrap=pick_bool(self.no_wrap, options.no_wrap),
|
| 321 |
+
style="pretty",
|
| 322 |
+
)
|
| 323 |
+
pretty_text = (
|
| 324 |
+
self.highlighter(pretty_text)
|
| 325 |
+
if pretty_text
|
| 326 |
+
else Text(
|
| 327 |
+
f"{type(self._object)}.__repr__ returned empty string",
|
| 328 |
+
style="dim italic",
|
| 329 |
+
)
|
| 330 |
+
)
|
| 331 |
+
if self.indent_guides and not options.ascii_only:
|
| 332 |
+
pretty_text = pretty_text.with_indent_guides(
|
| 333 |
+
self.indent_size, style="repr.indent"
|
| 334 |
+
)
|
| 335 |
+
if self.insert_line and "\n" in pretty_text:
|
| 336 |
+
yield ""
|
| 337 |
+
yield pretty_text
|
| 338 |
+
|
| 339 |
+
def __rich_measure__(
|
| 340 |
+
self, console: "Console", options: "ConsoleOptions"
|
| 341 |
+
) -> "Measurement":
|
| 342 |
+
pretty_str = pretty_repr(
|
| 343 |
+
self._object,
|
| 344 |
+
max_width=options.max_width,
|
| 345 |
+
indent_size=self.indent_size,
|
| 346 |
+
max_length=self.max_length,
|
| 347 |
+
max_string=self.max_string,
|
| 348 |
+
max_depth=self.max_depth,
|
| 349 |
+
expand_all=self.expand_all,
|
| 350 |
+
)
|
| 351 |
+
text_width = (
|
| 352 |
+
max(cell_len(line) for line in pretty_str.splitlines()) if pretty_str else 0
|
| 353 |
+
)
|
| 354 |
+
return Measurement(text_width, text_width)
|
| 355 |
+
|
| 356 |
+
|
| 357 |
+
def _get_braces_for_defaultdict(_object: DefaultDict[Any, Any]) -> Tuple[str, str, str]:
|
| 358 |
+
return (
|
| 359 |
+
f"defaultdict({_object.default_factory!r}, {{",
|
| 360 |
+
"})",
|
| 361 |
+
f"defaultdict({_object.default_factory!r}, {{}})",
|
| 362 |
+
)
|
| 363 |
+
|
| 364 |
+
|
| 365 |
+
def _get_braces_for_deque(_object: Deque[Any]) -> Tuple[str, str, str]:
|
| 366 |
+
if _object.maxlen is None:
|
| 367 |
+
return ("deque([", "])", "deque()")
|
| 368 |
+
return (
|
| 369 |
+
"deque([",
|
| 370 |
+
f"], maxlen={_object.maxlen})",
|
| 371 |
+
f"deque(maxlen={_object.maxlen})",
|
| 372 |
+
)
|
| 373 |
+
|
| 374 |
+
|
| 375 |
+
def _get_braces_for_array(_object: "array[Any]") -> Tuple[str, str, str]:
|
| 376 |
+
return (f"array({_object.typecode!r}, [", "])", f"array({_object.typecode!r})")
|
| 377 |
+
|
| 378 |
+
|
| 379 |
+
_BRACES: Dict[type, Callable[[Any], Tuple[str, str, str]]] = {
|
| 380 |
+
os._Environ: lambda _object: ("environ({", "})", "environ({})"),
|
| 381 |
+
array: _get_braces_for_array,
|
| 382 |
+
defaultdict: _get_braces_for_defaultdict,
|
| 383 |
+
Counter: lambda _object: ("Counter({", "})", "Counter()"),
|
| 384 |
+
deque: _get_braces_for_deque,
|
| 385 |
+
dict: lambda _object: ("{", "}", "{}"),
|
| 386 |
+
UserDict: lambda _object: ("{", "}", "{}"),
|
| 387 |
+
frozenset: lambda _object: ("frozenset({", "})", "frozenset()"),
|
| 388 |
+
list: lambda _object: ("[", "]", "[]"),
|
| 389 |
+
UserList: lambda _object: ("[", "]", "[]"),
|
| 390 |
+
set: lambda _object: ("{", "}", "set()"),
|
| 391 |
+
tuple: lambda _object: ("(", ")", "()"),
|
| 392 |
+
MappingProxyType: lambda _object: ("mappingproxy({", "})", "mappingproxy({})"),
|
| 393 |
+
}
|
| 394 |
+
_CONTAINERS = tuple(_BRACES.keys())
|
| 395 |
+
_MAPPING_CONTAINERS = (dict, os._Environ, MappingProxyType, UserDict)
|
| 396 |
+
|
| 397 |
+
|
| 398 |
+
def is_expandable(obj: Any) -> bool:
|
| 399 |
+
"""Check if an object may be expanded by pretty print."""
|
| 400 |
+
return (
|
| 401 |
+
_safe_isinstance(obj, _CONTAINERS)
|
| 402 |
+
or (is_dataclass(obj))
|
| 403 |
+
or (hasattr(obj, "__rich_repr__"))
|
| 404 |
+
or _is_attr_object(obj)
|
| 405 |
+
) and not isclass(obj)
|
| 406 |
+
|
| 407 |
+
|
| 408 |
+
@dataclass
|
| 409 |
+
class Node:
|
| 410 |
+
"""A node in a repr tree. May be atomic or a container."""
|
| 411 |
+
|
| 412 |
+
key_repr: str = ""
|
| 413 |
+
value_repr: str = ""
|
| 414 |
+
open_brace: str = ""
|
| 415 |
+
close_brace: str = ""
|
| 416 |
+
empty: str = ""
|
| 417 |
+
last: bool = False
|
| 418 |
+
is_tuple: bool = False
|
| 419 |
+
is_namedtuple: bool = False
|
| 420 |
+
children: Optional[List["Node"]] = None
|
| 421 |
+
key_separator: str = ": "
|
| 422 |
+
separator: str = ", "
|
| 423 |
+
|
| 424 |
+
def iter_tokens(self) -> Iterable[str]:
|
| 425 |
+
"""Generate tokens for this node."""
|
| 426 |
+
if self.key_repr:
|
| 427 |
+
yield self.key_repr
|
| 428 |
+
yield self.key_separator
|
| 429 |
+
if self.value_repr:
|
| 430 |
+
yield self.value_repr
|
| 431 |
+
elif self.children is not None:
|
| 432 |
+
if self.children:
|
| 433 |
+
yield self.open_brace
|
| 434 |
+
if self.is_tuple and not self.is_namedtuple and len(self.children) == 1:
|
| 435 |
+
yield from self.children[0].iter_tokens()
|
| 436 |
+
yield ","
|
| 437 |
+
else:
|
| 438 |
+
for child in self.children:
|
| 439 |
+
yield from child.iter_tokens()
|
| 440 |
+
if not child.last:
|
| 441 |
+
yield self.separator
|
| 442 |
+
yield self.close_brace
|
| 443 |
+
else:
|
| 444 |
+
yield self.empty
|
| 445 |
+
|
| 446 |
+
def check_length(self, start_length: int, max_length: int) -> bool:
|
| 447 |
+
"""Check the length fits within a limit.
|
| 448 |
+
|
| 449 |
+
Args:
|
| 450 |
+
start_length (int): Starting length of the line (indent, prefix, suffix).
|
| 451 |
+
max_length (int): Maximum length.
|
| 452 |
+
|
| 453 |
+
Returns:
|
| 454 |
+
bool: True if the node can be rendered within max length, otherwise False.
|
| 455 |
+
"""
|
| 456 |
+
total_length = start_length
|
| 457 |
+
for token in self.iter_tokens():
|
| 458 |
+
total_length += cell_len(token)
|
| 459 |
+
if total_length > max_length:
|
| 460 |
+
return False
|
| 461 |
+
return True
|
| 462 |
+
|
| 463 |
+
def __str__(self) -> str:
|
| 464 |
+
repr_text = "".join(self.iter_tokens())
|
| 465 |
+
return repr_text
|
| 466 |
+
|
| 467 |
+
def render(
|
| 468 |
+
self, max_width: int = 80, indent_size: int = 4, expand_all: bool = False
|
| 469 |
+
) -> str:
|
| 470 |
+
"""Render the node to a pretty repr.
|
| 471 |
+
|
| 472 |
+
Args:
|
| 473 |
+
max_width (int, optional): Maximum width of the repr. Defaults to 80.
|
| 474 |
+
indent_size (int, optional): Size of indents. Defaults to 4.
|
| 475 |
+
expand_all (bool, optional): Expand all levels. Defaults to False.
|
| 476 |
+
|
| 477 |
+
Returns:
|
| 478 |
+
str: A repr string of the original object.
|
| 479 |
+
"""
|
| 480 |
+
lines = [_Line(node=self, is_root=True)]
|
| 481 |
+
line_no = 0
|
| 482 |
+
while line_no < len(lines):
|
| 483 |
+
line = lines[line_no]
|
| 484 |
+
if line.expandable and not line.expanded:
|
| 485 |
+
if expand_all or not line.check_length(max_width):
|
| 486 |
+
lines[line_no : line_no + 1] = line.expand(indent_size)
|
| 487 |
+
line_no += 1
|
| 488 |
+
|
| 489 |
+
repr_str = "\n".join(str(line) for line in lines)
|
| 490 |
+
return repr_str
|
| 491 |
+
|
| 492 |
+
|
| 493 |
+
@dataclass
|
| 494 |
+
class _Line:
|
| 495 |
+
"""A line in repr output."""
|
| 496 |
+
|
| 497 |
+
parent: Optional["_Line"] = None
|
| 498 |
+
is_root: bool = False
|
| 499 |
+
node: Optional[Node] = None
|
| 500 |
+
text: str = ""
|
| 501 |
+
suffix: str = ""
|
| 502 |
+
whitespace: str = ""
|
| 503 |
+
expanded: bool = False
|
| 504 |
+
last: bool = False
|
| 505 |
+
|
| 506 |
+
@property
|
| 507 |
+
def expandable(self) -> bool:
|
| 508 |
+
"""Check if the line may be expanded."""
|
| 509 |
+
return bool(self.node is not None and self.node.children)
|
| 510 |
+
|
| 511 |
+
def check_length(self, max_length: int) -> bool:
|
| 512 |
+
"""Check this line fits within a given number of cells."""
|
| 513 |
+
start_length = (
|
| 514 |
+
len(self.whitespace) + cell_len(self.text) + cell_len(self.suffix)
|
| 515 |
+
)
|
| 516 |
+
assert self.node is not None
|
| 517 |
+
return self.node.check_length(start_length, max_length)
|
| 518 |
+
|
| 519 |
+
def expand(self, indent_size: int) -> Iterable["_Line"]:
|
| 520 |
+
"""Expand this line by adding children on their own line."""
|
| 521 |
+
node = self.node
|
| 522 |
+
assert node is not None
|
| 523 |
+
whitespace = self.whitespace
|
| 524 |
+
assert node.children
|
| 525 |
+
if node.key_repr:
|
| 526 |
+
new_line = yield _Line(
|
| 527 |
+
text=f"{node.key_repr}{node.key_separator}{node.open_brace}",
|
| 528 |
+
whitespace=whitespace,
|
| 529 |
+
)
|
| 530 |
+
else:
|
| 531 |
+
new_line = yield _Line(text=node.open_brace, whitespace=whitespace)
|
| 532 |
+
child_whitespace = self.whitespace + " " * indent_size
|
| 533 |
+
tuple_of_one = node.is_tuple and len(node.children) == 1
|
| 534 |
+
for last, child in loop_last(node.children):
|
| 535 |
+
separator = "," if tuple_of_one else node.separator
|
| 536 |
+
line = _Line(
|
| 537 |
+
parent=new_line,
|
| 538 |
+
node=child,
|
| 539 |
+
whitespace=child_whitespace,
|
| 540 |
+
suffix=separator,
|
| 541 |
+
last=last and not tuple_of_one,
|
| 542 |
+
)
|
| 543 |
+
yield line
|
| 544 |
+
|
| 545 |
+
yield _Line(
|
| 546 |
+
text=node.close_brace,
|
| 547 |
+
whitespace=whitespace,
|
| 548 |
+
suffix=self.suffix,
|
| 549 |
+
last=self.last,
|
| 550 |
+
)
|
| 551 |
+
|
| 552 |
+
def __str__(self) -> str:
|
| 553 |
+
if self.last:
|
| 554 |
+
return f"{self.whitespace}{self.text}{self.node or ''}"
|
| 555 |
+
else:
|
| 556 |
+
return (
|
| 557 |
+
f"{self.whitespace}{self.text}{self.node or ''}{self.suffix.rstrip()}"
|
| 558 |
+
)
|
| 559 |
+
|
| 560 |
+
|
| 561 |
+
def _is_namedtuple(obj: Any) -> bool:
|
| 562 |
+
"""Checks if an object is most likely a namedtuple. It is possible
|
| 563 |
+
to craft an object that passes this check and isn't a namedtuple, but
|
| 564 |
+
there is only a minuscule chance of this happening unintentionally.
|
| 565 |
+
|
| 566 |
+
Args:
|
| 567 |
+
obj (Any): The object to test
|
| 568 |
+
|
| 569 |
+
Returns:
|
| 570 |
+
bool: True if the object is a namedtuple. False otherwise.
|
| 571 |
+
"""
|
| 572 |
+
try:
|
| 573 |
+
fields = getattr(obj, "_fields", None)
|
| 574 |
+
except Exception:
|
| 575 |
+
# Being very defensive - if we cannot get the attr then its not a namedtuple
|
| 576 |
+
return False
|
| 577 |
+
return isinstance(obj, tuple) and isinstance(fields, tuple)
|
| 578 |
+
|
| 579 |
+
|
| 580 |
+
def traverse(
|
| 581 |
+
_object: Any,
|
| 582 |
+
max_length: Optional[int] = None,
|
| 583 |
+
max_string: Optional[int] = None,
|
| 584 |
+
max_depth: Optional[int] = None,
|
| 585 |
+
) -> Node:
|
| 586 |
+
"""Traverse object and generate a tree.
|
| 587 |
+
|
| 588 |
+
Args:
|
| 589 |
+
_object (Any): Object to be traversed.
|
| 590 |
+
max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation.
|
| 591 |
+
Defaults to None.
|
| 592 |
+
max_string (int, optional): Maximum length of string before truncating, or None to disable truncating.
|
| 593 |
+
Defaults to None.
|
| 594 |
+
max_depth (int, optional): Maximum depth of data structures, or None for no maximum.
|
| 595 |
+
Defaults to None.
|
| 596 |
+
|
| 597 |
+
Returns:
|
| 598 |
+
Node: The root of a tree structure which can be used to render a pretty repr.
|
| 599 |
+
"""
|
| 600 |
+
|
| 601 |
+
def to_repr(obj: Any) -> str:
|
| 602 |
+
"""Get repr string for an object, but catch errors."""
|
| 603 |
+
if (
|
| 604 |
+
max_string is not None
|
| 605 |
+
and _safe_isinstance(obj, (bytes, str))
|
| 606 |
+
and len(obj) > max_string
|
| 607 |
+
):
|
| 608 |
+
truncated = len(obj) - max_string
|
| 609 |
+
obj_repr = f"{obj[:max_string]!r}+{truncated}"
|
| 610 |
+
else:
|
| 611 |
+
try:
|
| 612 |
+
obj_repr = repr(obj)
|
| 613 |
+
except Exception as error:
|
| 614 |
+
obj_repr = f"<repr-error {str(error)!r}>"
|
| 615 |
+
return obj_repr
|
| 616 |
+
|
| 617 |
+
visited_ids: Set[int] = set()
|
| 618 |
+
push_visited = visited_ids.add
|
| 619 |
+
pop_visited = visited_ids.remove
|
| 620 |
+
|
| 621 |
+
def _traverse(obj: Any, root: bool = False, depth: int = 0) -> Node:
|
| 622 |
+
"""Walk the object depth first."""
|
| 623 |
+
|
| 624 |
+
obj_id = id(obj)
|
| 625 |
+
if obj_id in visited_ids:
|
| 626 |
+
# Recursion detected
|
| 627 |
+
return Node(value_repr="...")
|
| 628 |
+
|
| 629 |
+
obj_type = type(obj)
|
| 630 |
+
children: List[Node]
|
| 631 |
+
reached_max_depth = max_depth is not None and depth >= max_depth
|
| 632 |
+
|
| 633 |
+
def iter_rich_args(rich_args: Any) -> Iterable[Union[Any, Tuple[str, Any]]]:
|
| 634 |
+
for arg in rich_args:
|
| 635 |
+
if _safe_isinstance(arg, tuple):
|
| 636 |
+
if len(arg) == 3:
|
| 637 |
+
key, child, default = arg
|
| 638 |
+
if default == child:
|
| 639 |
+
continue
|
| 640 |
+
yield key, child
|
| 641 |
+
elif len(arg) == 2:
|
| 642 |
+
key, child = arg
|
| 643 |
+
yield key, child
|
| 644 |
+
elif len(arg) == 1:
|
| 645 |
+
yield arg[0]
|
| 646 |
+
else:
|
| 647 |
+
yield arg
|
| 648 |
+
|
| 649 |
+
try:
|
| 650 |
+
fake_attributes = hasattr(
|
| 651 |
+
obj, "awehoi234_wdfjwljet234_234wdfoijsdfmmnxpi492"
|
| 652 |
+
)
|
| 653 |
+
except Exception:
|
| 654 |
+
fake_attributes = False
|
| 655 |
+
|
| 656 |
+
rich_repr_result: Optional[RichReprResult] = None
|
| 657 |
+
if not fake_attributes:
|
| 658 |
+
try:
|
| 659 |
+
if hasattr(obj, "__rich_repr__") and not isclass(obj):
|
| 660 |
+
rich_repr_result = obj.__rich_repr__()
|
| 661 |
+
except Exception:
|
| 662 |
+
pass
|
| 663 |
+
|
| 664 |
+
if rich_repr_result is not None:
|
| 665 |
+
push_visited(obj_id)
|
| 666 |
+
angular = getattr(obj.__rich_repr__, "angular", False)
|
| 667 |
+
args = list(iter_rich_args(rich_repr_result))
|
| 668 |
+
class_name = obj.__class__.__name__
|
| 669 |
+
|
| 670 |
+
if args:
|
| 671 |
+
children = []
|
| 672 |
+
append = children.append
|
| 673 |
+
|
| 674 |
+
if reached_max_depth:
|
| 675 |
+
if angular:
|
| 676 |
+
node = Node(value_repr=f"<{class_name}...>")
|
| 677 |
+
else:
|
| 678 |
+
node = Node(value_repr=f"{class_name}(...)")
|
| 679 |
+
else:
|
| 680 |
+
if angular:
|
| 681 |
+
node = Node(
|
| 682 |
+
open_brace=f"<{class_name} ",
|
| 683 |
+
close_brace=">",
|
| 684 |
+
children=children,
|
| 685 |
+
last=root,
|
| 686 |
+
separator=" ",
|
| 687 |
+
)
|
| 688 |
+
else:
|
| 689 |
+
node = Node(
|
| 690 |
+
open_brace=f"{class_name}(",
|
| 691 |
+
close_brace=")",
|
| 692 |
+
children=children,
|
| 693 |
+
last=root,
|
| 694 |
+
)
|
| 695 |
+
for last, arg in loop_last(args):
|
| 696 |
+
if _safe_isinstance(arg, tuple):
|
| 697 |
+
key, child = arg
|
| 698 |
+
child_node = _traverse(child, depth=depth + 1)
|
| 699 |
+
child_node.last = last
|
| 700 |
+
child_node.key_repr = key
|
| 701 |
+
child_node.key_separator = "="
|
| 702 |
+
append(child_node)
|
| 703 |
+
else:
|
| 704 |
+
child_node = _traverse(arg, depth=depth + 1)
|
| 705 |
+
child_node.last = last
|
| 706 |
+
append(child_node)
|
| 707 |
+
else:
|
| 708 |
+
node = Node(
|
| 709 |
+
value_repr=f"<{class_name}>" if angular else f"{class_name}()",
|
| 710 |
+
children=[],
|
| 711 |
+
last=root,
|
| 712 |
+
)
|
| 713 |
+
pop_visited(obj_id)
|
| 714 |
+
elif _is_attr_object(obj) and not fake_attributes:
|
| 715 |
+
push_visited(obj_id)
|
| 716 |
+
children = []
|
| 717 |
+
append = children.append
|
| 718 |
+
|
| 719 |
+
attr_fields = _get_attr_fields(obj)
|
| 720 |
+
if attr_fields:
|
| 721 |
+
if reached_max_depth:
|
| 722 |
+
node = Node(value_repr=f"{obj.__class__.__name__}(...)")
|
| 723 |
+
else:
|
| 724 |
+
node = Node(
|
| 725 |
+
open_brace=f"{obj.__class__.__name__}(",
|
| 726 |
+
close_brace=")",
|
| 727 |
+
children=children,
|
| 728 |
+
last=root,
|
| 729 |
+
)
|
| 730 |
+
|
| 731 |
+
def iter_attrs() -> (
|
| 732 |
+
Iterable[Tuple[str, Any, Optional[Callable[[Any], str]]]]
|
| 733 |
+
):
|
| 734 |
+
"""Iterate over attr fields and values."""
|
| 735 |
+
for attr in attr_fields:
|
| 736 |
+
if attr.repr:
|
| 737 |
+
try:
|
| 738 |
+
value = getattr(obj, attr.name)
|
| 739 |
+
except Exception as error:
|
| 740 |
+
# Can happen, albeit rarely
|
| 741 |
+
yield (attr.name, error, None)
|
| 742 |
+
else:
|
| 743 |
+
yield (
|
| 744 |
+
attr.name,
|
| 745 |
+
value,
|
| 746 |
+
attr.repr if callable(attr.repr) else None,
|
| 747 |
+
)
|
| 748 |
+
|
| 749 |
+
for last, (name, value, repr_callable) in loop_last(iter_attrs()):
|
| 750 |
+
if repr_callable:
|
| 751 |
+
child_node = Node(value_repr=str(repr_callable(value)))
|
| 752 |
+
else:
|
| 753 |
+
child_node = _traverse(value, depth=depth + 1)
|
| 754 |
+
child_node.last = last
|
| 755 |
+
child_node.key_repr = name
|
| 756 |
+
child_node.key_separator = "="
|
| 757 |
+
append(child_node)
|
| 758 |
+
else:
|
| 759 |
+
node = Node(
|
| 760 |
+
value_repr=f"{obj.__class__.__name__}()", children=[], last=root
|
| 761 |
+
)
|
| 762 |
+
pop_visited(obj_id)
|
| 763 |
+
elif (
|
| 764 |
+
is_dataclass(obj)
|
| 765 |
+
and not _safe_isinstance(obj, type)
|
| 766 |
+
and not fake_attributes
|
| 767 |
+
and _is_dataclass_repr(obj)
|
| 768 |
+
):
|
| 769 |
+
push_visited(obj_id)
|
| 770 |
+
children = []
|
| 771 |
+
append = children.append
|
| 772 |
+
if reached_max_depth:
|
| 773 |
+
node = Node(value_repr=f"{obj.__class__.__name__}(...)")
|
| 774 |
+
else:
|
| 775 |
+
node = Node(
|
| 776 |
+
open_brace=f"{obj.__class__.__name__}(",
|
| 777 |
+
close_brace=")",
|
| 778 |
+
children=children,
|
| 779 |
+
last=root,
|
| 780 |
+
empty=f"{obj.__class__.__name__}()",
|
| 781 |
+
)
|
| 782 |
+
|
| 783 |
+
for last, field in loop_last(
|
| 784 |
+
field
|
| 785 |
+
for field in fields(obj)
|
| 786 |
+
if field.repr and hasattr(obj, field.name)
|
| 787 |
+
):
|
| 788 |
+
child_node = _traverse(getattr(obj, field.name), depth=depth + 1)
|
| 789 |
+
child_node.key_repr = field.name
|
| 790 |
+
child_node.last = last
|
| 791 |
+
child_node.key_separator = "="
|
| 792 |
+
append(child_node)
|
| 793 |
+
|
| 794 |
+
pop_visited(obj_id)
|
| 795 |
+
elif _is_namedtuple(obj) and _has_default_namedtuple_repr(obj):
|
| 796 |
+
push_visited(obj_id)
|
| 797 |
+
class_name = obj.__class__.__name__
|
| 798 |
+
if reached_max_depth:
|
| 799 |
+
# If we've reached the max depth, we still show the class name, but not its contents
|
| 800 |
+
node = Node(
|
| 801 |
+
value_repr=f"{class_name}(...)",
|
| 802 |
+
)
|
| 803 |
+
else:
|
| 804 |
+
children = []
|
| 805 |
+
append = children.append
|
| 806 |
+
node = Node(
|
| 807 |
+
open_brace=f"{class_name}(",
|
| 808 |
+
close_brace=")",
|
| 809 |
+
children=children,
|
| 810 |
+
empty=f"{class_name}()",
|
| 811 |
+
)
|
| 812 |
+
for last, (key, value) in loop_last(obj._asdict().items()):
|
| 813 |
+
child_node = _traverse(value, depth=depth + 1)
|
| 814 |
+
child_node.key_repr = key
|
| 815 |
+
child_node.last = last
|
| 816 |
+
child_node.key_separator = "="
|
| 817 |
+
append(child_node)
|
| 818 |
+
pop_visited(obj_id)
|
| 819 |
+
elif _safe_isinstance(obj, _CONTAINERS):
|
| 820 |
+
for container_type in _CONTAINERS:
|
| 821 |
+
if _safe_isinstance(obj, container_type):
|
| 822 |
+
obj_type = container_type
|
| 823 |
+
break
|
| 824 |
+
|
| 825 |
+
push_visited(obj_id)
|
| 826 |
+
|
| 827 |
+
open_brace, close_brace, empty = _BRACES[obj_type](obj)
|
| 828 |
+
|
| 829 |
+
if reached_max_depth:
|
| 830 |
+
node = Node(value_repr=f"{open_brace}...{close_brace}")
|
| 831 |
+
elif obj_type.__repr__ != type(obj).__repr__:
|
| 832 |
+
node = Node(value_repr=to_repr(obj), last=root)
|
| 833 |
+
elif obj:
|
| 834 |
+
children = []
|
| 835 |
+
node = Node(
|
| 836 |
+
open_brace=open_brace,
|
| 837 |
+
close_brace=close_brace,
|
| 838 |
+
children=children,
|
| 839 |
+
last=root,
|
| 840 |
+
)
|
| 841 |
+
append = children.append
|
| 842 |
+
num_items = len(obj)
|
| 843 |
+
last_item_index = num_items - 1
|
| 844 |
+
|
| 845 |
+
if _safe_isinstance(obj, _MAPPING_CONTAINERS):
|
| 846 |
+
iter_items = iter(obj.items())
|
| 847 |
+
if max_length is not None:
|
| 848 |
+
iter_items = islice(iter_items, max_length)
|
| 849 |
+
for index, (key, child) in enumerate(iter_items):
|
| 850 |
+
child_node = _traverse(child, depth=depth + 1)
|
| 851 |
+
child_node.key_repr = to_repr(key)
|
| 852 |
+
child_node.last = index == last_item_index
|
| 853 |
+
append(child_node)
|
| 854 |
+
else:
|
| 855 |
+
iter_values = iter(obj)
|
| 856 |
+
if max_length is not None:
|
| 857 |
+
iter_values = islice(iter_values, max_length)
|
| 858 |
+
for index, child in enumerate(iter_values):
|
| 859 |
+
child_node = _traverse(child, depth=depth + 1)
|
| 860 |
+
child_node.last = index == last_item_index
|
| 861 |
+
append(child_node)
|
| 862 |
+
if max_length is not None and num_items > max_length:
|
| 863 |
+
append(Node(value_repr=f"... +{num_items - max_length}", last=True))
|
| 864 |
+
else:
|
| 865 |
+
node = Node(empty=empty, children=[], last=root)
|
| 866 |
+
|
| 867 |
+
pop_visited(obj_id)
|
| 868 |
+
else:
|
| 869 |
+
node = Node(value_repr=to_repr(obj), last=root)
|
| 870 |
+
node.is_tuple = type(obj) == tuple
|
| 871 |
+
node.is_namedtuple = _is_namedtuple(obj)
|
| 872 |
+
return node
|
| 873 |
+
|
| 874 |
+
node = _traverse(_object, root=True)
|
| 875 |
+
return node
|
| 876 |
+
|
| 877 |
+
|
| 878 |
+
def pretty_repr(
|
| 879 |
+
_object: Any,
|
| 880 |
+
*,
|
| 881 |
+
max_width: int = 80,
|
| 882 |
+
indent_size: int = 4,
|
| 883 |
+
max_length: Optional[int] = None,
|
| 884 |
+
max_string: Optional[int] = None,
|
| 885 |
+
max_depth: Optional[int] = None,
|
| 886 |
+
expand_all: bool = False,
|
| 887 |
+
) -> str:
|
| 888 |
+
"""Prettify repr string by expanding on to new lines to fit within a given width.
|
| 889 |
+
|
| 890 |
+
Args:
|
| 891 |
+
_object (Any): Object to repr.
|
| 892 |
+
max_width (int, optional): Desired maximum width of repr string. Defaults to 80.
|
| 893 |
+
indent_size (int, optional): Number of spaces to indent. Defaults to 4.
|
| 894 |
+
max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation.
|
| 895 |
+
Defaults to None.
|
| 896 |
+
max_string (int, optional): Maximum length of string before truncating, or None to disable truncating.
|
| 897 |
+
Defaults to None.
|
| 898 |
+
max_depth (int, optional): Maximum depth of nested data structure, or None for no depth.
|
| 899 |
+
Defaults to None.
|
| 900 |
+
expand_all (bool, optional): Expand all containers regardless of available width. Defaults to False.
|
| 901 |
+
|
| 902 |
+
Returns:
|
| 903 |
+
str: A possibly multi-line representation of the object.
|
| 904 |
+
"""
|
| 905 |
+
|
| 906 |
+
if _safe_isinstance(_object, Node):
|
| 907 |
+
node = _object
|
| 908 |
+
else:
|
| 909 |
+
node = traverse(
|
| 910 |
+
_object, max_length=max_length, max_string=max_string, max_depth=max_depth
|
| 911 |
+
)
|
| 912 |
+
repr_str: str = node.render(
|
| 913 |
+
max_width=max_width, indent_size=indent_size, expand_all=expand_all
|
| 914 |
+
)
|
| 915 |
+
return repr_str
|
| 916 |
+
|
| 917 |
+
|
| 918 |
+
def pprint(
|
| 919 |
+
_object: Any,
|
| 920 |
+
*,
|
| 921 |
+
console: Optional["Console"] = None,
|
| 922 |
+
indent_guides: bool = True,
|
| 923 |
+
max_length: Optional[int] = None,
|
| 924 |
+
max_string: Optional[int] = None,
|
| 925 |
+
max_depth: Optional[int] = None,
|
| 926 |
+
expand_all: bool = False,
|
| 927 |
+
) -> None:
|
| 928 |
+
"""A convenience function for pretty printing.
|
| 929 |
+
|
| 930 |
+
Args:
|
| 931 |
+
_object (Any): Object to pretty print.
|
| 932 |
+
console (Console, optional): Console instance, or None to use default. Defaults to None.
|
| 933 |
+
max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation.
|
| 934 |
+
Defaults to None.
|
| 935 |
+
max_string (int, optional): Maximum length of strings before truncating, or None to disable. Defaults to None.
|
| 936 |
+
max_depth (int, optional): Maximum depth for nested data structures, or None for unlimited depth. Defaults to None.
|
| 937 |
+
indent_guides (bool, optional): Enable indentation guides. Defaults to True.
|
| 938 |
+
expand_all (bool, optional): Expand all containers. Defaults to False.
|
| 939 |
+
"""
|
| 940 |
+
_console = get_console() if console is None else console
|
| 941 |
+
_console.print(
|
| 942 |
+
Pretty(
|
| 943 |
+
_object,
|
| 944 |
+
max_length=max_length,
|
| 945 |
+
max_string=max_string,
|
| 946 |
+
max_depth=max_depth,
|
| 947 |
+
indent_guides=indent_guides,
|
| 948 |
+
expand_all=expand_all,
|
| 949 |
+
overflow="ignore",
|
| 950 |
+
),
|
| 951 |
+
soft_wrap=True,
|
| 952 |
+
)
|
| 953 |
+
|
| 954 |
+
|
| 955 |
+
if __name__ == "__main__": # pragma: no cover
|
| 956 |
+
|
| 957 |
+
class BrokenRepr:
|
| 958 |
+
def __repr__(self) -> str:
|
| 959 |
+
1 / 0
|
| 960 |
+
return "this will fail"
|
| 961 |
+
|
| 962 |
+
from typing import NamedTuple
|
| 963 |
+
|
| 964 |
+
class StockKeepingUnit(NamedTuple):
|
| 965 |
+
name: str
|
| 966 |
+
description: str
|
| 967 |
+
price: float
|
| 968 |
+
category: str
|
| 969 |
+
reviews: List[str]
|
| 970 |
+
|
| 971 |
+
d = defaultdict(int)
|
| 972 |
+
d["foo"] = 5
|
| 973 |
+
data = {
|
| 974 |
+
"foo": [
|
| 975 |
+
1,
|
| 976 |
+
"Hello World!",
|
| 977 |
+
100.123,
|
| 978 |
+
323.232,
|
| 979 |
+
432324.0,
|
| 980 |
+
{5, 6, 7, (1, 2, 3, 4), 8},
|
| 981 |
+
],
|
| 982 |
+
"bar": frozenset({1, 2, 3}),
|
| 983 |
+
"defaultdict": defaultdict(
|
| 984 |
+
list, {"crumble": ["apple", "rhubarb", "butter", "sugar", "flour"]}
|
| 985 |
+
),
|
| 986 |
+
"counter": Counter(
|
| 987 |
+
[
|
| 988 |
+
"apple",
|
| 989 |
+
"orange",
|
| 990 |
+
"pear",
|
| 991 |
+
"kumquat",
|
| 992 |
+
"kumquat",
|
| 993 |
+
"durian" * 100,
|
| 994 |
+
]
|
| 995 |
+
),
|
| 996 |
+
"atomic": (False, True, None),
|
| 997 |
+
"namedtuple": StockKeepingUnit(
|
| 998 |
+
"Sparkling British Spring Water",
|
| 999 |
+
"Carbonated spring water",
|
| 1000 |
+
0.9,
|
| 1001 |
+
"water",
|
| 1002 |
+
["its amazing!", "its terrible!"],
|
| 1003 |
+
),
|
| 1004 |
+
"Broken": BrokenRepr(),
|
| 1005 |
+
}
|
| 1006 |
+
data["foo"].append(data) # type: ignore[attr-defined]
|
| 1007 |
+
|
| 1008 |
+
from rich import print
|
| 1009 |
+
|
| 1010 |
+
print(Pretty(data, indent_guides=True, max_string=20))
|
| 1011 |
+
|
| 1012 |
+
class Thing:
|
| 1013 |
+
def __repr__(self) -> str:
|
| 1014 |
+
return "Hello\x1b[38;5;239m World!"
|
| 1015 |
+
|
| 1016 |
+
print(Pretty(Thing()))
|
miniconda3/lib/python3.13/site-packages/rich/progress.py
ADDED
|
@@ -0,0 +1,1715 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import io
|
| 4 |
+
import typing
|
| 5 |
+
import warnings
|
| 6 |
+
from abc import ABC, abstractmethod
|
| 7 |
+
from collections import deque
|
| 8 |
+
from dataclasses import dataclass, field
|
| 9 |
+
from datetime import timedelta
|
| 10 |
+
from io import RawIOBase, UnsupportedOperation
|
| 11 |
+
from math import ceil
|
| 12 |
+
from mmap import mmap
|
| 13 |
+
from operator import length_hint
|
| 14 |
+
from os import PathLike, stat
|
| 15 |
+
from threading import Event, RLock, Thread
|
| 16 |
+
from types import TracebackType
|
| 17 |
+
from typing import (
|
| 18 |
+
TYPE_CHECKING,
|
| 19 |
+
Any,
|
| 20 |
+
BinaryIO,
|
| 21 |
+
Callable,
|
| 22 |
+
ContextManager,
|
| 23 |
+
Deque,
|
| 24 |
+
Dict,
|
| 25 |
+
Generic,
|
| 26 |
+
Iterable,
|
| 27 |
+
List,
|
| 28 |
+
Literal,
|
| 29 |
+
NamedTuple,
|
| 30 |
+
NewType,
|
| 31 |
+
Optional,
|
| 32 |
+
TextIO,
|
| 33 |
+
Tuple,
|
| 34 |
+
Type,
|
| 35 |
+
TypeVar,
|
| 36 |
+
Union,
|
| 37 |
+
)
|
| 38 |
+
|
| 39 |
+
if TYPE_CHECKING:
|
| 40 |
+
# Can be replaced with `from typing import Self` in Python 3.11+
|
| 41 |
+
from typing_extensions import Self # pragma: no cover
|
| 42 |
+
|
| 43 |
+
from . import filesize, get_console
|
| 44 |
+
from .console import Console, Group, JustifyMethod, RenderableType
|
| 45 |
+
from .highlighter import Highlighter
|
| 46 |
+
from .jupyter import JupyterMixin
|
| 47 |
+
from .live import Live
|
| 48 |
+
from .progress_bar import ProgressBar
|
| 49 |
+
from .spinner import Spinner
|
| 50 |
+
from .style import StyleType
|
| 51 |
+
from .table import Column, Table
|
| 52 |
+
from .text import Text, TextType
|
| 53 |
+
|
| 54 |
+
TaskID = NewType("TaskID", int)
|
| 55 |
+
|
| 56 |
+
ProgressType = TypeVar("ProgressType")
|
| 57 |
+
|
| 58 |
+
GetTimeCallable = Callable[[], float]
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
_I = typing.TypeVar("_I", TextIO, BinaryIO)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
class _TrackThread(Thread):
|
| 65 |
+
"""A thread to periodically update progress."""
|
| 66 |
+
|
| 67 |
+
def __init__(self, progress: "Progress", task_id: "TaskID", update_period: float):
|
| 68 |
+
self.progress = progress
|
| 69 |
+
self.task_id = task_id
|
| 70 |
+
self.update_period = update_period
|
| 71 |
+
self.done = Event()
|
| 72 |
+
|
| 73 |
+
self.completed = 0
|
| 74 |
+
super().__init__(daemon=True)
|
| 75 |
+
|
| 76 |
+
def run(self) -> None:
|
| 77 |
+
task_id = self.task_id
|
| 78 |
+
advance = self.progress.advance
|
| 79 |
+
update_period = self.update_period
|
| 80 |
+
last_completed = 0
|
| 81 |
+
wait = self.done.wait
|
| 82 |
+
while not wait(update_period) and self.progress.live.is_started:
|
| 83 |
+
completed = self.completed
|
| 84 |
+
if last_completed != completed:
|
| 85 |
+
advance(task_id, completed - last_completed)
|
| 86 |
+
last_completed = completed
|
| 87 |
+
|
| 88 |
+
self.progress.update(self.task_id, completed=self.completed, refresh=True)
|
| 89 |
+
|
| 90 |
+
def __enter__(self) -> "_TrackThread":
|
| 91 |
+
self.start()
|
| 92 |
+
return self
|
| 93 |
+
|
| 94 |
+
def __exit__(
|
| 95 |
+
self,
|
| 96 |
+
exc_type: Optional[Type[BaseException]],
|
| 97 |
+
exc_val: Optional[BaseException],
|
| 98 |
+
exc_tb: Optional[TracebackType],
|
| 99 |
+
) -> None:
|
| 100 |
+
self.done.set()
|
| 101 |
+
self.join()
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def track(
|
| 105 |
+
sequence: Iterable[ProgressType],
|
| 106 |
+
description: str = "Working...",
|
| 107 |
+
total: Optional[float] = None,
|
| 108 |
+
completed: int = 0,
|
| 109 |
+
auto_refresh: bool = True,
|
| 110 |
+
console: Optional[Console] = None,
|
| 111 |
+
transient: bool = False,
|
| 112 |
+
get_time: Optional[Callable[[], float]] = None,
|
| 113 |
+
refresh_per_second: float = 10,
|
| 114 |
+
style: StyleType = "bar.back",
|
| 115 |
+
complete_style: StyleType = "bar.complete",
|
| 116 |
+
finished_style: StyleType = "bar.finished",
|
| 117 |
+
pulse_style: StyleType = "bar.pulse",
|
| 118 |
+
update_period: float = 0.1,
|
| 119 |
+
disable: bool = False,
|
| 120 |
+
show_speed: bool = True,
|
| 121 |
+
) -> Iterable[ProgressType]:
|
| 122 |
+
"""Track progress by iterating over a sequence.
|
| 123 |
+
|
| 124 |
+
You can also track progress of an iterable, which might require that you additionally specify ``total``.
|
| 125 |
+
|
| 126 |
+
Args:
|
| 127 |
+
sequence (Iterable[ProgressType]): Values you wish to iterate over and track progress.
|
| 128 |
+
description (str, optional): Description of task show next to progress bar. Defaults to "Working".
|
| 129 |
+
total: (float, optional): Total number of steps. Default is len(sequence).
|
| 130 |
+
completed (int, optional): Number of steps completed so far. Defaults to 0.
|
| 131 |
+
auto_refresh (bool, optional): Automatic refresh, disable to force a refresh after each iteration. Default is True.
|
| 132 |
+
transient: (bool, optional): Clear the progress on exit. Defaults to False.
|
| 133 |
+
console (Console, optional): Console to write to. Default creates internal Console instance.
|
| 134 |
+
refresh_per_second (float): Number of times per second to refresh the progress information. Defaults to 10.
|
| 135 |
+
style (StyleType, optional): Style for the bar background. Defaults to "bar.back".
|
| 136 |
+
complete_style (StyleType, optional): Style for the completed bar. Defaults to "bar.complete".
|
| 137 |
+
finished_style (StyleType, optional): Style for a finished bar. Defaults to "bar.finished".
|
| 138 |
+
pulse_style (StyleType, optional): Style for pulsing bars. Defaults to "bar.pulse".
|
| 139 |
+
update_period (float, optional): Minimum time (in seconds) between calls to update(). Defaults to 0.1.
|
| 140 |
+
disable (bool, optional): Disable display of progress.
|
| 141 |
+
show_speed (bool, optional): Show speed if total isn't known. Defaults to True.
|
| 142 |
+
Returns:
|
| 143 |
+
Iterable[ProgressType]: An iterable of the values in the sequence.
|
| 144 |
+
|
| 145 |
+
"""
|
| 146 |
+
|
| 147 |
+
columns: List["ProgressColumn"] = (
|
| 148 |
+
[TextColumn("[progress.description]{task.description}")] if description else []
|
| 149 |
+
)
|
| 150 |
+
columns.extend(
|
| 151 |
+
(
|
| 152 |
+
BarColumn(
|
| 153 |
+
style=style,
|
| 154 |
+
complete_style=complete_style,
|
| 155 |
+
finished_style=finished_style,
|
| 156 |
+
pulse_style=pulse_style,
|
| 157 |
+
),
|
| 158 |
+
TaskProgressColumn(show_speed=show_speed),
|
| 159 |
+
TimeRemainingColumn(elapsed_when_finished=True),
|
| 160 |
+
)
|
| 161 |
+
)
|
| 162 |
+
progress = Progress(
|
| 163 |
+
*columns,
|
| 164 |
+
auto_refresh=auto_refresh,
|
| 165 |
+
console=console,
|
| 166 |
+
transient=transient,
|
| 167 |
+
get_time=get_time,
|
| 168 |
+
refresh_per_second=refresh_per_second or 10,
|
| 169 |
+
disable=disable,
|
| 170 |
+
)
|
| 171 |
+
|
| 172 |
+
with progress:
|
| 173 |
+
yield from progress.track(
|
| 174 |
+
sequence,
|
| 175 |
+
total=total,
|
| 176 |
+
completed=completed,
|
| 177 |
+
description=description,
|
| 178 |
+
update_period=update_period,
|
| 179 |
+
)
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
class _Reader(RawIOBase, BinaryIO):
|
| 183 |
+
"""A reader that tracks progress while it's being read from."""
|
| 184 |
+
|
| 185 |
+
def __init__(
|
| 186 |
+
self,
|
| 187 |
+
handle: BinaryIO,
|
| 188 |
+
progress: "Progress",
|
| 189 |
+
task: TaskID,
|
| 190 |
+
close_handle: bool = True,
|
| 191 |
+
) -> None:
|
| 192 |
+
self.handle = handle
|
| 193 |
+
self.progress = progress
|
| 194 |
+
self.task = task
|
| 195 |
+
self.close_handle = close_handle
|
| 196 |
+
self._closed = False
|
| 197 |
+
|
| 198 |
+
def __enter__(self) -> "_Reader":
|
| 199 |
+
self.handle.__enter__()
|
| 200 |
+
return self
|
| 201 |
+
|
| 202 |
+
def __exit__(
|
| 203 |
+
self,
|
| 204 |
+
exc_type: Optional[Type[BaseException]],
|
| 205 |
+
exc_val: Optional[BaseException],
|
| 206 |
+
exc_tb: Optional[TracebackType],
|
| 207 |
+
) -> None:
|
| 208 |
+
self.close()
|
| 209 |
+
|
| 210 |
+
def __iter__(self) -> BinaryIO:
|
| 211 |
+
return self
|
| 212 |
+
|
| 213 |
+
def __next__(self) -> bytes:
|
| 214 |
+
line = next(self.handle)
|
| 215 |
+
self.progress.advance(self.task, advance=len(line))
|
| 216 |
+
return line
|
| 217 |
+
|
| 218 |
+
@property
|
| 219 |
+
def closed(self) -> bool:
|
| 220 |
+
return self._closed
|
| 221 |
+
|
| 222 |
+
def fileno(self) -> int:
|
| 223 |
+
return self.handle.fileno()
|
| 224 |
+
|
| 225 |
+
def isatty(self) -> bool:
|
| 226 |
+
return self.handle.isatty()
|
| 227 |
+
|
| 228 |
+
@property
|
| 229 |
+
def mode(self) -> str:
|
| 230 |
+
return self.handle.mode
|
| 231 |
+
|
| 232 |
+
@property
|
| 233 |
+
def name(self) -> str:
|
| 234 |
+
return self.handle.name
|
| 235 |
+
|
| 236 |
+
def readable(self) -> bool:
|
| 237 |
+
return self.handle.readable()
|
| 238 |
+
|
| 239 |
+
def seekable(self) -> bool:
|
| 240 |
+
return self.handle.seekable()
|
| 241 |
+
|
| 242 |
+
def writable(self) -> bool:
|
| 243 |
+
return False
|
| 244 |
+
|
| 245 |
+
def read(self, size: int = -1) -> bytes:
|
| 246 |
+
block = self.handle.read(size)
|
| 247 |
+
self.progress.advance(self.task, advance=len(block))
|
| 248 |
+
return block
|
| 249 |
+
|
| 250 |
+
def readinto(self, b: Union[bytearray, memoryview, mmap]): # type: ignore[no-untyped-def, override]
|
| 251 |
+
n = self.handle.readinto(b) # type: ignore[attr-defined]
|
| 252 |
+
self.progress.advance(self.task, advance=n)
|
| 253 |
+
return n
|
| 254 |
+
|
| 255 |
+
def readline(self, size: int = -1) -> bytes: # type: ignore[override]
|
| 256 |
+
line = self.handle.readline(size)
|
| 257 |
+
self.progress.advance(self.task, advance=len(line))
|
| 258 |
+
return line
|
| 259 |
+
|
| 260 |
+
def readlines(self, hint: int = -1) -> List[bytes]:
|
| 261 |
+
lines = self.handle.readlines(hint)
|
| 262 |
+
self.progress.advance(self.task, advance=sum(map(len, lines)))
|
| 263 |
+
return lines
|
| 264 |
+
|
| 265 |
+
def close(self) -> None:
|
| 266 |
+
if self.close_handle:
|
| 267 |
+
self.handle.close()
|
| 268 |
+
self._closed = True
|
| 269 |
+
|
| 270 |
+
def seek(self, offset: int, whence: int = 0) -> int:
|
| 271 |
+
pos = self.handle.seek(offset, whence)
|
| 272 |
+
self.progress.update(self.task, completed=pos)
|
| 273 |
+
return pos
|
| 274 |
+
|
| 275 |
+
def tell(self) -> int:
|
| 276 |
+
return self.handle.tell()
|
| 277 |
+
|
| 278 |
+
def write(self, s: Any) -> int:
|
| 279 |
+
raise UnsupportedOperation("write")
|
| 280 |
+
|
| 281 |
+
def writelines(self, lines: Iterable[Any]) -> None:
|
| 282 |
+
raise UnsupportedOperation("writelines")
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
class _ReadContext(ContextManager[_I], Generic[_I]):
|
| 286 |
+
"""A utility class to handle a context for both a reader and a progress."""
|
| 287 |
+
|
| 288 |
+
def __init__(self, progress: "Progress", reader: _I) -> None:
|
| 289 |
+
self.progress = progress
|
| 290 |
+
self.reader: _I = reader
|
| 291 |
+
|
| 292 |
+
def __enter__(self) -> _I:
|
| 293 |
+
self.progress.start()
|
| 294 |
+
return self.reader.__enter__()
|
| 295 |
+
|
| 296 |
+
def __exit__(
|
| 297 |
+
self,
|
| 298 |
+
exc_type: Optional[Type[BaseException]],
|
| 299 |
+
exc_val: Optional[BaseException],
|
| 300 |
+
exc_tb: Optional[TracebackType],
|
| 301 |
+
) -> None:
|
| 302 |
+
self.progress.stop()
|
| 303 |
+
self.reader.__exit__(exc_type, exc_val, exc_tb)
|
| 304 |
+
|
| 305 |
+
|
| 306 |
+
def wrap_file(
|
| 307 |
+
file: BinaryIO,
|
| 308 |
+
total: int,
|
| 309 |
+
*,
|
| 310 |
+
description: str = "Reading...",
|
| 311 |
+
auto_refresh: bool = True,
|
| 312 |
+
console: Optional[Console] = None,
|
| 313 |
+
transient: bool = False,
|
| 314 |
+
get_time: Optional[Callable[[], float]] = None,
|
| 315 |
+
refresh_per_second: float = 10,
|
| 316 |
+
style: StyleType = "bar.back",
|
| 317 |
+
complete_style: StyleType = "bar.complete",
|
| 318 |
+
finished_style: StyleType = "bar.finished",
|
| 319 |
+
pulse_style: StyleType = "bar.pulse",
|
| 320 |
+
disable: bool = False,
|
| 321 |
+
) -> ContextManager[BinaryIO]:
|
| 322 |
+
"""Read bytes from a file while tracking progress.
|
| 323 |
+
|
| 324 |
+
Args:
|
| 325 |
+
file (Union[str, PathLike[str], BinaryIO]): The path to the file to read, or a file-like object in binary mode.
|
| 326 |
+
total (int): Total number of bytes to read.
|
| 327 |
+
description (str, optional): Description of task show next to progress bar. Defaults to "Reading".
|
| 328 |
+
auto_refresh (bool, optional): Automatic refresh, disable to force a refresh after each iteration. Default is True.
|
| 329 |
+
transient: (bool, optional): Clear the progress on exit. Defaults to False.
|
| 330 |
+
console (Console, optional): Console to write to. Default creates internal Console instance.
|
| 331 |
+
refresh_per_second (float): Number of times per second to refresh the progress information. Defaults to 10.
|
| 332 |
+
style (StyleType, optional): Style for the bar background. Defaults to "bar.back".
|
| 333 |
+
complete_style (StyleType, optional): Style for the completed bar. Defaults to "bar.complete".
|
| 334 |
+
finished_style (StyleType, optional): Style for a finished bar. Defaults to "bar.finished".
|
| 335 |
+
pulse_style (StyleType, optional): Style for pulsing bars. Defaults to "bar.pulse".
|
| 336 |
+
disable (bool, optional): Disable display of progress.
|
| 337 |
+
Returns:
|
| 338 |
+
ContextManager[BinaryIO]: A context manager yielding a progress reader.
|
| 339 |
+
|
| 340 |
+
"""
|
| 341 |
+
|
| 342 |
+
columns: List["ProgressColumn"] = (
|
| 343 |
+
[TextColumn("[progress.description]{task.description}")] if description else []
|
| 344 |
+
)
|
| 345 |
+
columns.extend(
|
| 346 |
+
(
|
| 347 |
+
BarColumn(
|
| 348 |
+
style=style,
|
| 349 |
+
complete_style=complete_style,
|
| 350 |
+
finished_style=finished_style,
|
| 351 |
+
pulse_style=pulse_style,
|
| 352 |
+
),
|
| 353 |
+
DownloadColumn(),
|
| 354 |
+
TimeRemainingColumn(),
|
| 355 |
+
)
|
| 356 |
+
)
|
| 357 |
+
progress = Progress(
|
| 358 |
+
*columns,
|
| 359 |
+
auto_refresh=auto_refresh,
|
| 360 |
+
console=console,
|
| 361 |
+
transient=transient,
|
| 362 |
+
get_time=get_time,
|
| 363 |
+
refresh_per_second=refresh_per_second or 10,
|
| 364 |
+
disable=disable,
|
| 365 |
+
)
|
| 366 |
+
|
| 367 |
+
reader = progress.wrap_file(file, total=total, description=description)
|
| 368 |
+
return _ReadContext(progress, reader)
|
| 369 |
+
|
| 370 |
+
|
| 371 |
+
@typing.overload
|
| 372 |
+
def open(
|
| 373 |
+
file: Union[str, "PathLike[str]", bytes],
|
| 374 |
+
mode: Union[Literal["rt"], Literal["r"]],
|
| 375 |
+
buffering: int = -1,
|
| 376 |
+
encoding: Optional[str] = None,
|
| 377 |
+
errors: Optional[str] = None,
|
| 378 |
+
newline: Optional[str] = None,
|
| 379 |
+
*,
|
| 380 |
+
total: Optional[int] = None,
|
| 381 |
+
description: str = "Reading...",
|
| 382 |
+
auto_refresh: bool = True,
|
| 383 |
+
console: Optional[Console] = None,
|
| 384 |
+
transient: bool = False,
|
| 385 |
+
get_time: Optional[Callable[[], float]] = None,
|
| 386 |
+
refresh_per_second: float = 10,
|
| 387 |
+
style: StyleType = "bar.back",
|
| 388 |
+
complete_style: StyleType = "bar.complete",
|
| 389 |
+
finished_style: StyleType = "bar.finished",
|
| 390 |
+
pulse_style: StyleType = "bar.pulse",
|
| 391 |
+
disable: bool = False,
|
| 392 |
+
) -> ContextManager[TextIO]:
|
| 393 |
+
pass
|
| 394 |
+
|
| 395 |
+
|
| 396 |
+
@typing.overload
|
| 397 |
+
def open(
|
| 398 |
+
file: Union[str, "PathLike[str]", bytes],
|
| 399 |
+
mode: Literal["rb"],
|
| 400 |
+
buffering: int = -1,
|
| 401 |
+
encoding: Optional[str] = None,
|
| 402 |
+
errors: Optional[str] = None,
|
| 403 |
+
newline: Optional[str] = None,
|
| 404 |
+
*,
|
| 405 |
+
total: Optional[int] = None,
|
| 406 |
+
description: str = "Reading...",
|
| 407 |
+
auto_refresh: bool = True,
|
| 408 |
+
console: Optional[Console] = None,
|
| 409 |
+
transient: bool = False,
|
| 410 |
+
get_time: Optional[Callable[[], float]] = None,
|
| 411 |
+
refresh_per_second: float = 10,
|
| 412 |
+
style: StyleType = "bar.back",
|
| 413 |
+
complete_style: StyleType = "bar.complete",
|
| 414 |
+
finished_style: StyleType = "bar.finished",
|
| 415 |
+
pulse_style: StyleType = "bar.pulse",
|
| 416 |
+
disable: bool = False,
|
| 417 |
+
) -> ContextManager[BinaryIO]:
|
| 418 |
+
pass
|
| 419 |
+
|
| 420 |
+
|
| 421 |
+
def open(
|
| 422 |
+
file: Union[str, "PathLike[str]", bytes],
|
| 423 |
+
mode: Union[Literal["rb"], Literal["rt"], Literal["r"]] = "r",
|
| 424 |
+
buffering: int = -1,
|
| 425 |
+
encoding: Optional[str] = None,
|
| 426 |
+
errors: Optional[str] = None,
|
| 427 |
+
newline: Optional[str] = None,
|
| 428 |
+
*,
|
| 429 |
+
total: Optional[int] = None,
|
| 430 |
+
description: str = "Reading...",
|
| 431 |
+
auto_refresh: bool = True,
|
| 432 |
+
console: Optional[Console] = None,
|
| 433 |
+
transient: bool = False,
|
| 434 |
+
get_time: Optional[Callable[[], float]] = None,
|
| 435 |
+
refresh_per_second: float = 10,
|
| 436 |
+
style: StyleType = "bar.back",
|
| 437 |
+
complete_style: StyleType = "bar.complete",
|
| 438 |
+
finished_style: StyleType = "bar.finished",
|
| 439 |
+
pulse_style: StyleType = "bar.pulse",
|
| 440 |
+
disable: bool = False,
|
| 441 |
+
) -> Union[ContextManager[BinaryIO], ContextManager[TextIO]]:
|
| 442 |
+
"""Read bytes from a file while tracking progress.
|
| 443 |
+
|
| 444 |
+
Args:
|
| 445 |
+
path (Union[str, PathLike[str], BinaryIO]): The path to the file to read, or a file-like object in binary mode.
|
| 446 |
+
mode (str): The mode to use to open the file. Only supports "r", "rb" or "rt".
|
| 447 |
+
buffering (int): The buffering strategy to use, see :func:`io.open`.
|
| 448 |
+
encoding (str, optional): The encoding to use when reading in text mode, see :func:`io.open`.
|
| 449 |
+
errors (str, optional): The error handling strategy for decoding errors, see :func:`io.open`.
|
| 450 |
+
newline (str, optional): The strategy for handling newlines in text mode, see :func:`io.open`
|
| 451 |
+
total: (int, optional): Total number of bytes to read. Must be provided if reading from a file handle. Default for a path is os.stat(file).st_size.
|
| 452 |
+
description (str, optional): Description of task show next to progress bar. Defaults to "Reading".
|
| 453 |
+
auto_refresh (bool, optional): Automatic refresh, disable to force a refresh after each iteration. Default is True.
|
| 454 |
+
transient: (bool, optional): Clear the progress on exit. Defaults to False.
|
| 455 |
+
console (Console, optional): Console to write to. Default creates internal Console instance.
|
| 456 |
+
refresh_per_second (float): Number of times per second to refresh the progress information. Defaults to 10.
|
| 457 |
+
style (StyleType, optional): Style for the bar background. Defaults to "bar.back".
|
| 458 |
+
complete_style (StyleType, optional): Style for the completed bar. Defaults to "bar.complete".
|
| 459 |
+
finished_style (StyleType, optional): Style for a finished bar. Defaults to "bar.finished".
|
| 460 |
+
pulse_style (StyleType, optional): Style for pulsing bars. Defaults to "bar.pulse".
|
| 461 |
+
disable (bool, optional): Disable display of progress.
|
| 462 |
+
encoding (str, optional): The encoding to use when reading in text mode.
|
| 463 |
+
|
| 464 |
+
Returns:
|
| 465 |
+
ContextManager[BinaryIO]: A context manager yielding a progress reader.
|
| 466 |
+
|
| 467 |
+
"""
|
| 468 |
+
|
| 469 |
+
columns: List["ProgressColumn"] = (
|
| 470 |
+
[TextColumn("[progress.description]{task.description}")] if description else []
|
| 471 |
+
)
|
| 472 |
+
columns.extend(
|
| 473 |
+
(
|
| 474 |
+
BarColumn(
|
| 475 |
+
style=style,
|
| 476 |
+
complete_style=complete_style,
|
| 477 |
+
finished_style=finished_style,
|
| 478 |
+
pulse_style=pulse_style,
|
| 479 |
+
),
|
| 480 |
+
DownloadColumn(),
|
| 481 |
+
TimeRemainingColumn(),
|
| 482 |
+
)
|
| 483 |
+
)
|
| 484 |
+
progress = Progress(
|
| 485 |
+
*columns,
|
| 486 |
+
auto_refresh=auto_refresh,
|
| 487 |
+
console=console,
|
| 488 |
+
transient=transient,
|
| 489 |
+
get_time=get_time,
|
| 490 |
+
refresh_per_second=refresh_per_second or 10,
|
| 491 |
+
disable=disable,
|
| 492 |
+
)
|
| 493 |
+
|
| 494 |
+
reader = progress.open(
|
| 495 |
+
file,
|
| 496 |
+
mode=mode,
|
| 497 |
+
buffering=buffering,
|
| 498 |
+
encoding=encoding,
|
| 499 |
+
errors=errors,
|
| 500 |
+
newline=newline,
|
| 501 |
+
total=total,
|
| 502 |
+
description=description,
|
| 503 |
+
)
|
| 504 |
+
return _ReadContext(progress, reader) # type: ignore[return-value, type-var]
|
| 505 |
+
|
| 506 |
+
|
| 507 |
+
class ProgressColumn(ABC):
|
| 508 |
+
"""Base class for a widget to use in progress display."""
|
| 509 |
+
|
| 510 |
+
max_refresh: Optional[float] = None
|
| 511 |
+
|
| 512 |
+
def __init__(self, table_column: Optional[Column] = None) -> None:
|
| 513 |
+
self._table_column = table_column
|
| 514 |
+
self._renderable_cache: Dict[TaskID, Tuple[float, RenderableType]] = {}
|
| 515 |
+
self._update_time: Optional[float] = None
|
| 516 |
+
|
| 517 |
+
def get_table_column(self) -> Column:
|
| 518 |
+
"""Get a table column, used to build tasks table."""
|
| 519 |
+
return self._table_column or Column()
|
| 520 |
+
|
| 521 |
+
def __call__(self, task: "Task") -> RenderableType:
|
| 522 |
+
"""Called by the Progress object to return a renderable for the given task.
|
| 523 |
+
|
| 524 |
+
Args:
|
| 525 |
+
task (Task): An object containing information regarding the task.
|
| 526 |
+
|
| 527 |
+
Returns:
|
| 528 |
+
RenderableType: Anything renderable (including str).
|
| 529 |
+
"""
|
| 530 |
+
current_time = task.get_time()
|
| 531 |
+
if self.max_refresh is not None and not task.completed:
|
| 532 |
+
try:
|
| 533 |
+
timestamp, renderable = self._renderable_cache[task.id]
|
| 534 |
+
except KeyError:
|
| 535 |
+
pass
|
| 536 |
+
else:
|
| 537 |
+
if timestamp + self.max_refresh > current_time:
|
| 538 |
+
return renderable
|
| 539 |
+
|
| 540 |
+
renderable = self.render(task)
|
| 541 |
+
self._renderable_cache[task.id] = (current_time, renderable)
|
| 542 |
+
return renderable
|
| 543 |
+
|
| 544 |
+
@abstractmethod
|
| 545 |
+
def render(self, task: "Task") -> RenderableType:
|
| 546 |
+
"""Should return a renderable object."""
|
| 547 |
+
|
| 548 |
+
|
| 549 |
+
class RenderableColumn(ProgressColumn):
|
| 550 |
+
"""A column to insert an arbitrary column.
|
| 551 |
+
|
| 552 |
+
Args:
|
| 553 |
+
renderable (RenderableType, optional): Any renderable. Defaults to empty string.
|
| 554 |
+
"""
|
| 555 |
+
|
| 556 |
+
def __init__(
|
| 557 |
+
self, renderable: RenderableType = "", *, table_column: Optional[Column] = None
|
| 558 |
+
):
|
| 559 |
+
self.renderable = renderable
|
| 560 |
+
super().__init__(table_column=table_column)
|
| 561 |
+
|
| 562 |
+
def render(self, task: "Task") -> RenderableType:
|
| 563 |
+
return self.renderable
|
| 564 |
+
|
| 565 |
+
|
| 566 |
+
class SpinnerColumn(ProgressColumn):
|
| 567 |
+
"""A column with a 'spinner' animation.
|
| 568 |
+
|
| 569 |
+
Args:
|
| 570 |
+
spinner_name (str, optional): Name of spinner animation. Defaults to "dots".
|
| 571 |
+
style (StyleType, optional): Style of spinner. Defaults to "progress.spinner".
|
| 572 |
+
speed (float, optional): Speed factor of spinner. Defaults to 1.0.
|
| 573 |
+
finished_text (TextType, optional): Text used when task is finished. Defaults to " ".
|
| 574 |
+
"""
|
| 575 |
+
|
| 576 |
+
def __init__(
|
| 577 |
+
self,
|
| 578 |
+
spinner_name: str = "dots",
|
| 579 |
+
style: Optional[StyleType] = "progress.spinner",
|
| 580 |
+
speed: float = 1.0,
|
| 581 |
+
finished_text: TextType = " ",
|
| 582 |
+
table_column: Optional[Column] = None,
|
| 583 |
+
):
|
| 584 |
+
self.spinner = Spinner(spinner_name, style=style, speed=speed)
|
| 585 |
+
self.finished_text = (
|
| 586 |
+
Text.from_markup(finished_text)
|
| 587 |
+
if isinstance(finished_text, str)
|
| 588 |
+
else finished_text
|
| 589 |
+
)
|
| 590 |
+
super().__init__(table_column=table_column)
|
| 591 |
+
|
| 592 |
+
def set_spinner(
|
| 593 |
+
self,
|
| 594 |
+
spinner_name: str,
|
| 595 |
+
spinner_style: Optional[StyleType] = "progress.spinner",
|
| 596 |
+
speed: float = 1.0,
|
| 597 |
+
) -> None:
|
| 598 |
+
"""Set a new spinner.
|
| 599 |
+
|
| 600 |
+
Args:
|
| 601 |
+
spinner_name (str): Spinner name, see python -m rich.spinner.
|
| 602 |
+
spinner_style (Optional[StyleType], optional): Spinner style. Defaults to "progress.spinner".
|
| 603 |
+
speed (float, optional): Speed factor of spinner. Defaults to 1.0.
|
| 604 |
+
"""
|
| 605 |
+
self.spinner = Spinner(spinner_name, style=spinner_style, speed=speed)
|
| 606 |
+
|
| 607 |
+
def render(self, task: "Task") -> RenderableType:
|
| 608 |
+
text = (
|
| 609 |
+
self.finished_text
|
| 610 |
+
if task.finished
|
| 611 |
+
else self.spinner.render(task.get_time())
|
| 612 |
+
)
|
| 613 |
+
return text
|
| 614 |
+
|
| 615 |
+
|
| 616 |
+
class TextColumn(ProgressColumn):
|
| 617 |
+
"""A column containing text."""
|
| 618 |
+
|
| 619 |
+
def __init__(
|
| 620 |
+
self,
|
| 621 |
+
text_format: str,
|
| 622 |
+
style: StyleType = "none",
|
| 623 |
+
justify: JustifyMethod = "left",
|
| 624 |
+
markup: bool = True,
|
| 625 |
+
highlighter: Optional[Highlighter] = None,
|
| 626 |
+
table_column: Optional[Column] = None,
|
| 627 |
+
) -> None:
|
| 628 |
+
self.text_format = text_format
|
| 629 |
+
self.justify: JustifyMethod = justify
|
| 630 |
+
self.style = style
|
| 631 |
+
self.markup = markup
|
| 632 |
+
self.highlighter = highlighter
|
| 633 |
+
super().__init__(table_column=table_column or Column(no_wrap=True))
|
| 634 |
+
|
| 635 |
+
def render(self, task: "Task") -> Text:
|
| 636 |
+
_text = self.text_format.format(task=task)
|
| 637 |
+
if self.markup:
|
| 638 |
+
text = Text.from_markup(_text, style=self.style, justify=self.justify)
|
| 639 |
+
else:
|
| 640 |
+
text = Text(_text, style=self.style, justify=self.justify)
|
| 641 |
+
if self.highlighter:
|
| 642 |
+
self.highlighter.highlight(text)
|
| 643 |
+
return text
|
| 644 |
+
|
| 645 |
+
|
| 646 |
+
class BarColumn(ProgressColumn):
|
| 647 |
+
"""Renders a visual progress bar.
|
| 648 |
+
|
| 649 |
+
Args:
|
| 650 |
+
bar_width (Optional[int], optional): Width of bar or None for full width. Defaults to 40.
|
| 651 |
+
style (StyleType, optional): Style for the bar background. Defaults to "bar.back".
|
| 652 |
+
complete_style (StyleType, optional): Style for the completed bar. Defaults to "bar.complete".
|
| 653 |
+
finished_style (StyleType, optional): Style for a finished bar. Defaults to "bar.finished".
|
| 654 |
+
pulse_style (StyleType, optional): Style for pulsing bars. Defaults to "bar.pulse".
|
| 655 |
+
"""
|
| 656 |
+
|
| 657 |
+
def __init__(
|
| 658 |
+
self,
|
| 659 |
+
bar_width: Optional[int] = 40,
|
| 660 |
+
style: StyleType = "bar.back",
|
| 661 |
+
complete_style: StyleType = "bar.complete",
|
| 662 |
+
finished_style: StyleType = "bar.finished",
|
| 663 |
+
pulse_style: StyleType = "bar.pulse",
|
| 664 |
+
table_column: Optional[Column] = None,
|
| 665 |
+
) -> None:
|
| 666 |
+
self.bar_width = bar_width
|
| 667 |
+
self.style = style
|
| 668 |
+
self.complete_style = complete_style
|
| 669 |
+
self.finished_style = finished_style
|
| 670 |
+
self.pulse_style = pulse_style
|
| 671 |
+
super().__init__(table_column=table_column)
|
| 672 |
+
|
| 673 |
+
def render(self, task: "Task") -> ProgressBar:
|
| 674 |
+
"""Gets a progress bar widget for a task."""
|
| 675 |
+
return ProgressBar(
|
| 676 |
+
total=max(0, task.total) if task.total is not None else None,
|
| 677 |
+
completed=max(0, task.completed),
|
| 678 |
+
width=None if self.bar_width is None else max(1, self.bar_width),
|
| 679 |
+
pulse=not task.started,
|
| 680 |
+
animation_time=task.get_time(),
|
| 681 |
+
style=self.style,
|
| 682 |
+
complete_style=self.complete_style,
|
| 683 |
+
finished_style=self.finished_style,
|
| 684 |
+
pulse_style=self.pulse_style,
|
| 685 |
+
)
|
| 686 |
+
|
| 687 |
+
|
| 688 |
+
class TimeElapsedColumn(ProgressColumn):
|
| 689 |
+
"""Renders time elapsed."""
|
| 690 |
+
|
| 691 |
+
def render(self, task: "Task") -> Text:
|
| 692 |
+
"""Show time elapsed."""
|
| 693 |
+
elapsed = task.finished_time if task.finished else task.elapsed
|
| 694 |
+
if elapsed is None:
|
| 695 |
+
return Text("-:--:--", style="progress.elapsed")
|
| 696 |
+
delta = timedelta(seconds=max(0, int(elapsed)))
|
| 697 |
+
return Text(str(delta), style="progress.elapsed")
|
| 698 |
+
|
| 699 |
+
|
| 700 |
+
class TaskProgressColumn(TextColumn):
|
| 701 |
+
"""Show task progress as a percentage.
|
| 702 |
+
|
| 703 |
+
Args:
|
| 704 |
+
text_format (str, optional): Format for percentage display. Defaults to "[progress.percentage]{task.percentage:>3.0f}%".
|
| 705 |
+
text_format_no_percentage (str, optional): Format if percentage is unknown. Defaults to "".
|
| 706 |
+
style (StyleType, optional): Style of output. Defaults to "none".
|
| 707 |
+
justify (JustifyMethod, optional): Text justification. Defaults to "left".
|
| 708 |
+
markup (bool, optional): Enable markup. Defaults to True.
|
| 709 |
+
highlighter (Optional[Highlighter], optional): Highlighter to apply to output. Defaults to None.
|
| 710 |
+
table_column (Optional[Column], optional): Table Column to use. Defaults to None.
|
| 711 |
+
show_speed (bool, optional): Show speed if total is unknown. Defaults to False.
|
| 712 |
+
"""
|
| 713 |
+
|
| 714 |
+
def __init__(
|
| 715 |
+
self,
|
| 716 |
+
text_format: str = "[progress.percentage]{task.percentage:>3.0f}%",
|
| 717 |
+
text_format_no_percentage: str = "",
|
| 718 |
+
style: StyleType = "none",
|
| 719 |
+
justify: JustifyMethod = "left",
|
| 720 |
+
markup: bool = True,
|
| 721 |
+
highlighter: Optional[Highlighter] = None,
|
| 722 |
+
table_column: Optional[Column] = None,
|
| 723 |
+
show_speed: bool = False,
|
| 724 |
+
) -> None:
|
| 725 |
+
self.text_format_no_percentage = text_format_no_percentage
|
| 726 |
+
self.show_speed = show_speed
|
| 727 |
+
super().__init__(
|
| 728 |
+
text_format=text_format,
|
| 729 |
+
style=style,
|
| 730 |
+
justify=justify,
|
| 731 |
+
markup=markup,
|
| 732 |
+
highlighter=highlighter,
|
| 733 |
+
table_column=table_column,
|
| 734 |
+
)
|
| 735 |
+
|
| 736 |
+
@classmethod
|
| 737 |
+
def render_speed(cls, speed: Optional[float]) -> Text:
|
| 738 |
+
"""Render the speed in iterations per second.
|
| 739 |
+
|
| 740 |
+
Args:
|
| 741 |
+
task (Task): A Task object.
|
| 742 |
+
|
| 743 |
+
Returns:
|
| 744 |
+
Text: Text object containing the task speed.
|
| 745 |
+
"""
|
| 746 |
+
if speed is None:
|
| 747 |
+
return Text("", style="progress.percentage")
|
| 748 |
+
unit, suffix = filesize.pick_unit_and_suffix(
|
| 749 |
+
int(speed),
|
| 750 |
+
["", "×10³", "×10⁶", "×10⁹", "×10¹²"],
|
| 751 |
+
1000,
|
| 752 |
+
)
|
| 753 |
+
data_speed = speed / unit
|
| 754 |
+
return Text(f"{data_speed:.1f}{suffix} it/s", style="progress.percentage")
|
| 755 |
+
|
| 756 |
+
def render(self, task: "Task") -> Text:
|
| 757 |
+
if task.total is None and self.show_speed:
|
| 758 |
+
return self.render_speed(task.finished_speed or task.speed)
|
| 759 |
+
text_format = (
|
| 760 |
+
self.text_format_no_percentage if task.total is None else self.text_format
|
| 761 |
+
)
|
| 762 |
+
_text = text_format.format(task=task)
|
| 763 |
+
if self.markup:
|
| 764 |
+
text = Text.from_markup(_text, style=self.style, justify=self.justify)
|
| 765 |
+
else:
|
| 766 |
+
text = Text(_text, style=self.style, justify=self.justify)
|
| 767 |
+
if self.highlighter:
|
| 768 |
+
self.highlighter.highlight(text)
|
| 769 |
+
return text
|
| 770 |
+
|
| 771 |
+
|
| 772 |
+
class TimeRemainingColumn(ProgressColumn):
|
| 773 |
+
"""Renders estimated time remaining.
|
| 774 |
+
|
| 775 |
+
Args:
|
| 776 |
+
compact (bool, optional): Render MM:SS when time remaining is less than an hour. Defaults to False.
|
| 777 |
+
elapsed_when_finished (bool, optional): Render time elapsed when the task is finished. Defaults to False.
|
| 778 |
+
"""
|
| 779 |
+
|
| 780 |
+
# Only refresh twice a second to prevent jitter
|
| 781 |
+
max_refresh = 0.5
|
| 782 |
+
|
| 783 |
+
def __init__(
|
| 784 |
+
self,
|
| 785 |
+
compact: bool = False,
|
| 786 |
+
elapsed_when_finished: bool = False,
|
| 787 |
+
table_column: Optional[Column] = None,
|
| 788 |
+
):
|
| 789 |
+
self.compact = compact
|
| 790 |
+
self.elapsed_when_finished = elapsed_when_finished
|
| 791 |
+
super().__init__(table_column=table_column)
|
| 792 |
+
|
| 793 |
+
def render(self, task: "Task") -> Text:
|
| 794 |
+
"""Show time remaining."""
|
| 795 |
+
if self.elapsed_when_finished and task.finished:
|
| 796 |
+
task_time = task.finished_time
|
| 797 |
+
style = "progress.elapsed"
|
| 798 |
+
else:
|
| 799 |
+
task_time = task.time_remaining
|
| 800 |
+
style = "progress.remaining"
|
| 801 |
+
|
| 802 |
+
if task.total is None:
|
| 803 |
+
return Text("", style=style)
|
| 804 |
+
|
| 805 |
+
if task_time is None:
|
| 806 |
+
return Text("--:--" if self.compact else "-:--:--", style=style)
|
| 807 |
+
|
| 808 |
+
# Based on https://github.com/tqdm/tqdm/blob/master/tqdm/std.py
|
| 809 |
+
minutes, seconds = divmod(int(task_time), 60)
|
| 810 |
+
hours, minutes = divmod(minutes, 60)
|
| 811 |
+
|
| 812 |
+
if self.compact and not hours:
|
| 813 |
+
formatted = f"{minutes:02d}:{seconds:02d}"
|
| 814 |
+
else:
|
| 815 |
+
formatted = f"{hours:d}:{minutes:02d}:{seconds:02d}"
|
| 816 |
+
|
| 817 |
+
return Text(formatted, style=style)
|
| 818 |
+
|
| 819 |
+
|
| 820 |
+
class FileSizeColumn(ProgressColumn):
|
| 821 |
+
"""Renders completed filesize."""
|
| 822 |
+
|
| 823 |
+
def render(self, task: "Task") -> Text:
|
| 824 |
+
"""Show data completed."""
|
| 825 |
+
data_size = filesize.decimal(int(task.completed))
|
| 826 |
+
return Text(data_size, style="progress.filesize")
|
| 827 |
+
|
| 828 |
+
|
| 829 |
+
class TotalFileSizeColumn(ProgressColumn):
|
| 830 |
+
"""Renders total filesize."""
|
| 831 |
+
|
| 832 |
+
def render(self, task: "Task") -> Text:
|
| 833 |
+
"""Show data completed."""
|
| 834 |
+
data_size = filesize.decimal(int(task.total)) if task.total is not None else ""
|
| 835 |
+
return Text(data_size, style="progress.filesize.total")
|
| 836 |
+
|
| 837 |
+
|
| 838 |
+
class MofNCompleteColumn(ProgressColumn):
|
| 839 |
+
"""Renders completed count/total, e.g. ' 10/1000'.
|
| 840 |
+
|
| 841 |
+
Best for bounded tasks with int quantities.
|
| 842 |
+
|
| 843 |
+
Space pads the completed count so that progress length does not change as task progresses
|
| 844 |
+
past powers of 10.
|
| 845 |
+
|
| 846 |
+
Args:
|
| 847 |
+
separator (str, optional): Text to separate completed and total values. Defaults to "/".
|
| 848 |
+
"""
|
| 849 |
+
|
| 850 |
+
def __init__(self, separator: str = "/", table_column: Optional[Column] = None):
|
| 851 |
+
self.separator = separator
|
| 852 |
+
super().__init__(table_column=table_column)
|
| 853 |
+
|
| 854 |
+
def render(self, task: "Task") -> Text:
|
| 855 |
+
"""Show completed/total."""
|
| 856 |
+
completed = int(task.completed)
|
| 857 |
+
total = int(task.total) if task.total is not None else "?"
|
| 858 |
+
total_width = len(str(total))
|
| 859 |
+
return Text(
|
| 860 |
+
f"{completed:{total_width}d}{self.separator}{total}",
|
| 861 |
+
style="progress.download",
|
| 862 |
+
)
|
| 863 |
+
|
| 864 |
+
|
| 865 |
+
class DownloadColumn(ProgressColumn):
|
| 866 |
+
"""Renders file size downloaded and total, e.g. '0.5/2.3 GB'.
|
| 867 |
+
|
| 868 |
+
Args:
|
| 869 |
+
binary_units (bool, optional): Use binary units, KiB, MiB etc. Defaults to False.
|
| 870 |
+
"""
|
| 871 |
+
|
| 872 |
+
def __init__(
|
| 873 |
+
self, binary_units: bool = False, table_column: Optional[Column] = None
|
| 874 |
+
) -> None:
|
| 875 |
+
self.binary_units = binary_units
|
| 876 |
+
super().__init__(table_column=table_column)
|
| 877 |
+
|
| 878 |
+
def render(self, task: "Task") -> Text:
|
| 879 |
+
"""Calculate common unit for completed and total."""
|
| 880 |
+
completed = int(task.completed)
|
| 881 |
+
|
| 882 |
+
unit_and_suffix_calculation_base = (
|
| 883 |
+
int(task.total) if task.total is not None else completed
|
| 884 |
+
)
|
| 885 |
+
if self.binary_units:
|
| 886 |
+
unit, suffix = filesize.pick_unit_and_suffix(
|
| 887 |
+
unit_and_suffix_calculation_base,
|
| 888 |
+
["bytes", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"],
|
| 889 |
+
1024,
|
| 890 |
+
)
|
| 891 |
+
else:
|
| 892 |
+
unit, suffix = filesize.pick_unit_and_suffix(
|
| 893 |
+
unit_and_suffix_calculation_base,
|
| 894 |
+
["bytes", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"],
|
| 895 |
+
1000,
|
| 896 |
+
)
|
| 897 |
+
precision = 0 if unit == 1 else 1
|
| 898 |
+
|
| 899 |
+
completed_ratio = completed / unit
|
| 900 |
+
completed_str = f"{completed_ratio:,.{precision}f}"
|
| 901 |
+
|
| 902 |
+
if task.total is not None:
|
| 903 |
+
total = int(task.total)
|
| 904 |
+
total_ratio = total / unit
|
| 905 |
+
total_str = f"{total_ratio:,.{precision}f}"
|
| 906 |
+
else:
|
| 907 |
+
total_str = "?"
|
| 908 |
+
|
| 909 |
+
download_status = f"{completed_str}/{total_str} {suffix}"
|
| 910 |
+
download_text = Text(download_status, style="progress.download")
|
| 911 |
+
return download_text
|
| 912 |
+
|
| 913 |
+
|
| 914 |
+
class TransferSpeedColumn(ProgressColumn):
|
| 915 |
+
"""Renders human readable transfer speed."""
|
| 916 |
+
|
| 917 |
+
def render(self, task: "Task") -> Text:
|
| 918 |
+
"""Show data transfer speed."""
|
| 919 |
+
speed = task.finished_speed or task.speed
|
| 920 |
+
if speed is None:
|
| 921 |
+
return Text("?", style="progress.data.speed")
|
| 922 |
+
data_speed = filesize.decimal(int(speed))
|
| 923 |
+
return Text(f"{data_speed}/s", style="progress.data.speed")
|
| 924 |
+
|
| 925 |
+
|
| 926 |
+
class ProgressSample(NamedTuple):
|
| 927 |
+
"""Sample of progress for a given time."""
|
| 928 |
+
|
| 929 |
+
timestamp: float
|
| 930 |
+
"""Timestamp of sample."""
|
| 931 |
+
completed: float
|
| 932 |
+
"""Number of steps completed."""
|
| 933 |
+
|
| 934 |
+
|
| 935 |
+
@dataclass
|
| 936 |
+
class Task:
|
| 937 |
+
"""Information regarding a progress task.
|
| 938 |
+
|
| 939 |
+
This object should be considered read-only outside of the :class:`~Progress` class.
|
| 940 |
+
|
| 941 |
+
"""
|
| 942 |
+
|
| 943 |
+
id: TaskID
|
| 944 |
+
"""Task ID associated with this task (used in Progress methods)."""
|
| 945 |
+
|
| 946 |
+
description: str
|
| 947 |
+
"""str: Description of the task."""
|
| 948 |
+
|
| 949 |
+
total: Optional[float]
|
| 950 |
+
"""Optional[float]: Total number of steps in this task."""
|
| 951 |
+
|
| 952 |
+
completed: float
|
| 953 |
+
"""float: Number of steps completed"""
|
| 954 |
+
|
| 955 |
+
_get_time: GetTimeCallable
|
| 956 |
+
"""Callable to get the current time."""
|
| 957 |
+
|
| 958 |
+
finished_time: Optional[float] = None
|
| 959 |
+
"""float: Time task was finished."""
|
| 960 |
+
|
| 961 |
+
visible: bool = True
|
| 962 |
+
"""bool: Indicates if this task is visible in the progress display."""
|
| 963 |
+
|
| 964 |
+
fields: Dict[str, Any] = field(default_factory=dict)
|
| 965 |
+
"""dict: Arbitrary fields passed in via Progress.update."""
|
| 966 |
+
|
| 967 |
+
start_time: Optional[float] = field(default=None, init=False, repr=False)
|
| 968 |
+
"""Optional[float]: Time this task was started, or None if not started."""
|
| 969 |
+
|
| 970 |
+
stop_time: Optional[float] = field(default=None, init=False, repr=False)
|
| 971 |
+
"""Optional[float]: Time this task was stopped, or None if not stopped."""
|
| 972 |
+
|
| 973 |
+
finished_speed: Optional[float] = None
|
| 974 |
+
"""Optional[float]: The last speed for a finished task."""
|
| 975 |
+
|
| 976 |
+
_progress: Deque[ProgressSample] = field(
|
| 977 |
+
default_factory=lambda: deque(maxlen=1000), init=False, repr=False
|
| 978 |
+
)
|
| 979 |
+
|
| 980 |
+
_lock: RLock = field(repr=False, default_factory=RLock)
|
| 981 |
+
"""Thread lock."""
|
| 982 |
+
|
| 983 |
+
def get_time(self) -> float:
|
| 984 |
+
"""float: Get the current time, in seconds."""
|
| 985 |
+
return self._get_time()
|
| 986 |
+
|
| 987 |
+
@property
|
| 988 |
+
def started(self) -> bool:
|
| 989 |
+
"""bool: Check if the task as started."""
|
| 990 |
+
return self.start_time is not None
|
| 991 |
+
|
| 992 |
+
@property
|
| 993 |
+
def remaining(self) -> Optional[float]:
|
| 994 |
+
"""Optional[float]: Get the number of steps remaining, if a non-None total was set."""
|
| 995 |
+
if self.total is None:
|
| 996 |
+
return None
|
| 997 |
+
return self.total - self.completed
|
| 998 |
+
|
| 999 |
+
@property
|
| 1000 |
+
def elapsed(self) -> Optional[float]:
|
| 1001 |
+
"""Optional[float]: Time elapsed since task was started, or ``None`` if the task hasn't started."""
|
| 1002 |
+
if self.start_time is None:
|
| 1003 |
+
return None
|
| 1004 |
+
if self.stop_time is not None:
|
| 1005 |
+
return self.stop_time - self.start_time
|
| 1006 |
+
return self.get_time() - self.start_time
|
| 1007 |
+
|
| 1008 |
+
@property
|
| 1009 |
+
def finished(self) -> bool:
|
| 1010 |
+
"""Check if the task has finished."""
|
| 1011 |
+
return self.finished_time is not None
|
| 1012 |
+
|
| 1013 |
+
@property
|
| 1014 |
+
def percentage(self) -> float:
|
| 1015 |
+
"""float: Get progress of task as a percentage. If a None total was set, returns 0"""
|
| 1016 |
+
if not self.total:
|
| 1017 |
+
return 0.0
|
| 1018 |
+
completed = (self.completed / self.total) * 100.0
|
| 1019 |
+
completed = min(100.0, max(0.0, completed))
|
| 1020 |
+
return completed
|
| 1021 |
+
|
| 1022 |
+
@property
|
| 1023 |
+
def speed(self) -> Optional[float]:
|
| 1024 |
+
"""Optional[float]: Get the estimated speed in steps per second."""
|
| 1025 |
+
if self.start_time is None:
|
| 1026 |
+
return None
|
| 1027 |
+
with self._lock:
|
| 1028 |
+
progress = self._progress
|
| 1029 |
+
if not progress:
|
| 1030 |
+
return None
|
| 1031 |
+
total_time = progress[-1].timestamp - progress[0].timestamp
|
| 1032 |
+
if total_time == 0:
|
| 1033 |
+
return None
|
| 1034 |
+
iter_progress = iter(progress)
|
| 1035 |
+
next(iter_progress)
|
| 1036 |
+
total_completed = sum(sample.completed for sample in iter_progress)
|
| 1037 |
+
speed = total_completed / total_time
|
| 1038 |
+
return speed
|
| 1039 |
+
|
| 1040 |
+
@property
|
| 1041 |
+
def time_remaining(self) -> Optional[float]:
|
| 1042 |
+
"""Optional[float]: Get estimated time to completion, or ``None`` if no data."""
|
| 1043 |
+
if self.finished:
|
| 1044 |
+
return 0.0
|
| 1045 |
+
speed = self.speed
|
| 1046 |
+
if not speed:
|
| 1047 |
+
return None
|
| 1048 |
+
remaining = self.remaining
|
| 1049 |
+
if remaining is None:
|
| 1050 |
+
return None
|
| 1051 |
+
estimate = ceil(remaining / speed)
|
| 1052 |
+
return estimate
|
| 1053 |
+
|
| 1054 |
+
def _reset(self) -> None:
|
| 1055 |
+
"""Reset progress."""
|
| 1056 |
+
self._progress.clear()
|
| 1057 |
+
self.finished_time = None
|
| 1058 |
+
self.finished_speed = None
|
| 1059 |
+
|
| 1060 |
+
|
| 1061 |
+
class Progress(JupyterMixin):
|
| 1062 |
+
"""Renders an auto-updating progress bar(s).
|
| 1063 |
+
|
| 1064 |
+
Args:
|
| 1065 |
+
console (Console, optional): Optional Console instance. Defaults to an internal Console instance writing to stdout.
|
| 1066 |
+
auto_refresh (bool, optional): Enable auto refresh. If disabled, you will need to call `refresh()`.
|
| 1067 |
+
refresh_per_second (Optional[float], optional): Number of times per second to refresh the progress information or None to use default (10). Defaults to None.
|
| 1068 |
+
speed_estimate_period: (float, optional): Period (in seconds) used to calculate the speed estimate. Defaults to 30.
|
| 1069 |
+
transient: (bool, optional): Clear the progress on exit. Defaults to False.
|
| 1070 |
+
redirect_stdout: (bool, optional): Enable redirection of stdout, so ``print`` may be used. Defaults to True.
|
| 1071 |
+
redirect_stderr: (bool, optional): Enable redirection of stderr. Defaults to True.
|
| 1072 |
+
get_time: (Callable, optional): A callable that gets the current time, or None to use Console.get_time. Defaults to None.
|
| 1073 |
+
disable (bool, optional): Disable progress display. Defaults to False
|
| 1074 |
+
expand (bool, optional): Expand tasks table to fit width. Defaults to False.
|
| 1075 |
+
"""
|
| 1076 |
+
|
| 1077 |
+
def __init__(
|
| 1078 |
+
self,
|
| 1079 |
+
*columns: Union[str, ProgressColumn],
|
| 1080 |
+
console: Optional[Console] = None,
|
| 1081 |
+
auto_refresh: bool = True,
|
| 1082 |
+
refresh_per_second: float = 10,
|
| 1083 |
+
speed_estimate_period: float = 30.0,
|
| 1084 |
+
transient: bool = False,
|
| 1085 |
+
redirect_stdout: bool = True,
|
| 1086 |
+
redirect_stderr: bool = True,
|
| 1087 |
+
get_time: Optional[GetTimeCallable] = None,
|
| 1088 |
+
disable: bool = False,
|
| 1089 |
+
expand: bool = False,
|
| 1090 |
+
) -> None:
|
| 1091 |
+
assert refresh_per_second > 0, "refresh_per_second must be > 0"
|
| 1092 |
+
self._lock = RLock()
|
| 1093 |
+
self.columns = columns or self.get_default_columns()
|
| 1094 |
+
self.speed_estimate_period = speed_estimate_period
|
| 1095 |
+
|
| 1096 |
+
self.disable = disable
|
| 1097 |
+
self.expand = expand
|
| 1098 |
+
self._tasks: Dict[TaskID, Task] = {}
|
| 1099 |
+
self._task_index: TaskID = TaskID(0)
|
| 1100 |
+
self.live = Live(
|
| 1101 |
+
console=console or get_console(),
|
| 1102 |
+
auto_refresh=auto_refresh,
|
| 1103 |
+
refresh_per_second=refresh_per_second,
|
| 1104 |
+
transient=transient,
|
| 1105 |
+
redirect_stdout=redirect_stdout,
|
| 1106 |
+
redirect_stderr=redirect_stderr,
|
| 1107 |
+
get_renderable=self.get_renderable,
|
| 1108 |
+
)
|
| 1109 |
+
self.get_time = get_time or self.console.get_time
|
| 1110 |
+
self.print = self.console.print
|
| 1111 |
+
self.log = self.console.log
|
| 1112 |
+
|
| 1113 |
+
@classmethod
|
| 1114 |
+
def get_default_columns(cls) -> Tuple[ProgressColumn, ...]:
|
| 1115 |
+
"""Get the default columns used for a new Progress instance:
|
| 1116 |
+
- a text column for the description (TextColumn)
|
| 1117 |
+
- the bar itself (BarColumn)
|
| 1118 |
+
- a text column showing completion percentage (TextColumn)
|
| 1119 |
+
- an estimated-time-remaining column (TimeRemainingColumn)
|
| 1120 |
+
If the Progress instance is created without passing a columns argument,
|
| 1121 |
+
the default columns defined here will be used.
|
| 1122 |
+
|
| 1123 |
+
You can also create a Progress instance using custom columns before
|
| 1124 |
+
and/or after the defaults, as in this example:
|
| 1125 |
+
|
| 1126 |
+
progress = Progress(
|
| 1127 |
+
SpinnerColumn(),
|
| 1128 |
+
*Progress.get_default_columns(),
|
| 1129 |
+
"Elapsed:",
|
| 1130 |
+
TimeElapsedColumn(),
|
| 1131 |
+
)
|
| 1132 |
+
|
| 1133 |
+
This code shows the creation of a Progress display, containing
|
| 1134 |
+
a spinner to the left, the default columns, and a labeled elapsed
|
| 1135 |
+
time column.
|
| 1136 |
+
"""
|
| 1137 |
+
return (
|
| 1138 |
+
TextColumn("[progress.description]{task.description}"),
|
| 1139 |
+
BarColumn(),
|
| 1140 |
+
TaskProgressColumn(),
|
| 1141 |
+
TimeRemainingColumn(),
|
| 1142 |
+
)
|
| 1143 |
+
|
| 1144 |
+
@property
|
| 1145 |
+
def console(self) -> Console:
|
| 1146 |
+
return self.live.console
|
| 1147 |
+
|
| 1148 |
+
@property
|
| 1149 |
+
def tasks(self) -> List[Task]:
|
| 1150 |
+
"""Get a list of Task instances."""
|
| 1151 |
+
with self._lock:
|
| 1152 |
+
return list(self._tasks.values())
|
| 1153 |
+
|
| 1154 |
+
@property
|
| 1155 |
+
def task_ids(self) -> List[TaskID]:
|
| 1156 |
+
"""A list of task IDs."""
|
| 1157 |
+
with self._lock:
|
| 1158 |
+
return list(self._tasks.keys())
|
| 1159 |
+
|
| 1160 |
+
@property
|
| 1161 |
+
def finished(self) -> bool:
|
| 1162 |
+
"""Check if all tasks have been completed."""
|
| 1163 |
+
with self._lock:
|
| 1164 |
+
if not self._tasks:
|
| 1165 |
+
return True
|
| 1166 |
+
return all(task.finished for task in self._tasks.values())
|
| 1167 |
+
|
| 1168 |
+
def start(self) -> None:
|
| 1169 |
+
"""Start the progress display."""
|
| 1170 |
+
if not self.disable:
|
| 1171 |
+
self.live.start(refresh=True)
|
| 1172 |
+
|
| 1173 |
+
def stop(self) -> None:
|
| 1174 |
+
"""Stop the progress display."""
|
| 1175 |
+
self.live.stop()
|
| 1176 |
+
if not self.console.is_interactive and not self.console.is_jupyter:
|
| 1177 |
+
self.console.print()
|
| 1178 |
+
|
| 1179 |
+
def __enter__(self) -> Self:
|
| 1180 |
+
self.start()
|
| 1181 |
+
return self
|
| 1182 |
+
|
| 1183 |
+
def __exit__(
|
| 1184 |
+
self,
|
| 1185 |
+
exc_type: Optional[Type[BaseException]],
|
| 1186 |
+
exc_val: Optional[BaseException],
|
| 1187 |
+
exc_tb: Optional[TracebackType],
|
| 1188 |
+
) -> None:
|
| 1189 |
+
self.stop()
|
| 1190 |
+
|
| 1191 |
+
def track(
|
| 1192 |
+
self,
|
| 1193 |
+
sequence: Iterable[ProgressType],
|
| 1194 |
+
total: Optional[float] = None,
|
| 1195 |
+
completed: int = 0,
|
| 1196 |
+
task_id: Optional[TaskID] = None,
|
| 1197 |
+
description: str = "Working...",
|
| 1198 |
+
update_period: float = 0.1,
|
| 1199 |
+
) -> Iterable[ProgressType]:
|
| 1200 |
+
"""Track progress by iterating over a sequence.
|
| 1201 |
+
|
| 1202 |
+
You can also track progress of an iterable, which might require that you additionally specify ``total``.
|
| 1203 |
+
|
| 1204 |
+
Args:
|
| 1205 |
+
sequence (Iterable[ProgressType]): Values you want to iterate over and track progress.
|
| 1206 |
+
total: (float, optional): Total number of steps. Default is len(sequence).
|
| 1207 |
+
completed (int, optional): Number of steps completed so far. Defaults to 0.
|
| 1208 |
+
task_id: (TaskID): Task to track. Default is new task.
|
| 1209 |
+
description: (str, optional): Description of task, if new task is created.
|
| 1210 |
+
update_period (float, optional): Minimum time (in seconds) between calls to update(). Defaults to 0.1.
|
| 1211 |
+
|
| 1212 |
+
Returns:
|
| 1213 |
+
Iterable[ProgressType]: An iterable of values taken from the provided sequence.
|
| 1214 |
+
"""
|
| 1215 |
+
if total is None:
|
| 1216 |
+
total = float(length_hint(sequence)) or None
|
| 1217 |
+
|
| 1218 |
+
if task_id is None:
|
| 1219 |
+
task_id = self.add_task(description, total=total, completed=completed)
|
| 1220 |
+
else:
|
| 1221 |
+
self.update(task_id, total=total, completed=completed)
|
| 1222 |
+
|
| 1223 |
+
if self.live.auto_refresh:
|
| 1224 |
+
with _TrackThread(self, task_id, update_period) as track_thread:
|
| 1225 |
+
for value in sequence:
|
| 1226 |
+
yield value
|
| 1227 |
+
track_thread.completed += 1
|
| 1228 |
+
else:
|
| 1229 |
+
advance = self.advance
|
| 1230 |
+
refresh = self.refresh
|
| 1231 |
+
for value in sequence:
|
| 1232 |
+
yield value
|
| 1233 |
+
advance(task_id, 1)
|
| 1234 |
+
refresh()
|
| 1235 |
+
|
| 1236 |
+
def wrap_file(
|
| 1237 |
+
self,
|
| 1238 |
+
file: BinaryIO,
|
| 1239 |
+
total: Optional[int] = None,
|
| 1240 |
+
*,
|
| 1241 |
+
task_id: Optional[TaskID] = None,
|
| 1242 |
+
description: str = "Reading...",
|
| 1243 |
+
) -> BinaryIO:
|
| 1244 |
+
"""Track progress file reading from a binary file.
|
| 1245 |
+
|
| 1246 |
+
Args:
|
| 1247 |
+
file (BinaryIO): A file-like object opened in binary mode.
|
| 1248 |
+
total (int, optional): Total number of bytes to read. This must be provided unless a task with a total is also given.
|
| 1249 |
+
task_id (TaskID): Task to track. Default is new task.
|
| 1250 |
+
description (str, optional): Description of task, if new task is created.
|
| 1251 |
+
|
| 1252 |
+
Returns:
|
| 1253 |
+
BinaryIO: A readable file-like object in binary mode.
|
| 1254 |
+
|
| 1255 |
+
Raises:
|
| 1256 |
+
ValueError: When no total value can be extracted from the arguments or the task.
|
| 1257 |
+
"""
|
| 1258 |
+
# attempt to recover the total from the task
|
| 1259 |
+
total_bytes: Optional[float] = None
|
| 1260 |
+
if total is not None:
|
| 1261 |
+
total_bytes = total
|
| 1262 |
+
elif task_id is not None:
|
| 1263 |
+
with self._lock:
|
| 1264 |
+
total_bytes = self._tasks[task_id].total
|
| 1265 |
+
if total_bytes is None:
|
| 1266 |
+
raise ValueError(
|
| 1267 |
+
f"unable to get the total number of bytes, please specify 'total'"
|
| 1268 |
+
)
|
| 1269 |
+
|
| 1270 |
+
# update total of task or create new task
|
| 1271 |
+
if task_id is None:
|
| 1272 |
+
task_id = self.add_task(description, total=total_bytes)
|
| 1273 |
+
else:
|
| 1274 |
+
self.update(task_id, total=total_bytes)
|
| 1275 |
+
|
| 1276 |
+
return _Reader(file, self, task_id, close_handle=False)
|
| 1277 |
+
|
| 1278 |
+
@typing.overload
|
| 1279 |
+
def open(
|
| 1280 |
+
self,
|
| 1281 |
+
file: Union[str, "PathLike[str]", bytes],
|
| 1282 |
+
mode: Literal["rb"],
|
| 1283 |
+
buffering: int = -1,
|
| 1284 |
+
encoding: Optional[str] = None,
|
| 1285 |
+
errors: Optional[str] = None,
|
| 1286 |
+
newline: Optional[str] = None,
|
| 1287 |
+
*,
|
| 1288 |
+
total: Optional[int] = None,
|
| 1289 |
+
task_id: Optional[TaskID] = None,
|
| 1290 |
+
description: str = "Reading...",
|
| 1291 |
+
) -> BinaryIO:
|
| 1292 |
+
pass
|
| 1293 |
+
|
| 1294 |
+
@typing.overload
|
| 1295 |
+
def open(
|
| 1296 |
+
self,
|
| 1297 |
+
file: Union[str, "PathLike[str]", bytes],
|
| 1298 |
+
mode: Union[Literal["r"], Literal["rt"]],
|
| 1299 |
+
buffering: int = -1,
|
| 1300 |
+
encoding: Optional[str] = None,
|
| 1301 |
+
errors: Optional[str] = None,
|
| 1302 |
+
newline: Optional[str] = None,
|
| 1303 |
+
*,
|
| 1304 |
+
total: Optional[int] = None,
|
| 1305 |
+
task_id: Optional[TaskID] = None,
|
| 1306 |
+
description: str = "Reading...",
|
| 1307 |
+
) -> TextIO:
|
| 1308 |
+
pass
|
| 1309 |
+
|
| 1310 |
+
def open(
|
| 1311 |
+
self,
|
| 1312 |
+
file: Union[str, "PathLike[str]", bytes],
|
| 1313 |
+
mode: Union[Literal["rb"], Literal["rt"], Literal["r"]] = "r",
|
| 1314 |
+
buffering: int = -1,
|
| 1315 |
+
encoding: Optional[str] = None,
|
| 1316 |
+
errors: Optional[str] = None,
|
| 1317 |
+
newline: Optional[str] = None,
|
| 1318 |
+
*,
|
| 1319 |
+
total: Optional[int] = None,
|
| 1320 |
+
task_id: Optional[TaskID] = None,
|
| 1321 |
+
description: str = "Reading...",
|
| 1322 |
+
) -> Union[BinaryIO, TextIO]:
|
| 1323 |
+
"""Track progress while reading from a binary file.
|
| 1324 |
+
|
| 1325 |
+
Args:
|
| 1326 |
+
path (Union[str, PathLike[str]]): The path to the file to read.
|
| 1327 |
+
mode (str): The mode to use to open the file. Only supports "r", "rb" or "rt".
|
| 1328 |
+
buffering (int): The buffering strategy to use, see :func:`io.open`.
|
| 1329 |
+
encoding (str, optional): The encoding to use when reading in text mode, see :func:`io.open`.
|
| 1330 |
+
errors (str, optional): The error handling strategy for decoding errors, see :func:`io.open`.
|
| 1331 |
+
newline (str, optional): The strategy for handling newlines in text mode, see :func:`io.open`.
|
| 1332 |
+
total (int, optional): Total number of bytes to read. If none given, os.stat(path).st_size is used.
|
| 1333 |
+
task_id (TaskID): Task to track. Default is new task.
|
| 1334 |
+
description (str, optional): Description of task, if new task is created.
|
| 1335 |
+
|
| 1336 |
+
Returns:
|
| 1337 |
+
BinaryIO: A readable file-like object in binary mode.
|
| 1338 |
+
|
| 1339 |
+
Raises:
|
| 1340 |
+
ValueError: When an invalid mode is given.
|
| 1341 |
+
"""
|
| 1342 |
+
# normalize the mode (always rb, rt)
|
| 1343 |
+
_mode = "".join(sorted(mode, reverse=False))
|
| 1344 |
+
if _mode not in ("br", "rt", "r"):
|
| 1345 |
+
raise ValueError(f"invalid mode {mode!r}")
|
| 1346 |
+
|
| 1347 |
+
# patch buffering to provide the same behaviour as the builtin `open`
|
| 1348 |
+
line_buffering = buffering == 1
|
| 1349 |
+
if _mode == "br" and buffering == 1:
|
| 1350 |
+
warnings.warn(
|
| 1351 |
+
"line buffering (buffering=1) isn't supported in binary mode, the default buffer size will be used",
|
| 1352 |
+
RuntimeWarning,
|
| 1353 |
+
)
|
| 1354 |
+
buffering = -1
|
| 1355 |
+
elif _mode in ("rt", "r"):
|
| 1356 |
+
if buffering == 0:
|
| 1357 |
+
raise ValueError("can't have unbuffered text I/O")
|
| 1358 |
+
elif buffering == 1:
|
| 1359 |
+
buffering = -1
|
| 1360 |
+
|
| 1361 |
+
# attempt to get the total with `os.stat`
|
| 1362 |
+
if total is None:
|
| 1363 |
+
total = stat(file).st_size
|
| 1364 |
+
|
| 1365 |
+
# update total of task or create new task
|
| 1366 |
+
if task_id is None:
|
| 1367 |
+
task_id = self.add_task(description, total=total)
|
| 1368 |
+
else:
|
| 1369 |
+
self.update(task_id, total=total)
|
| 1370 |
+
|
| 1371 |
+
# open the file in binary mode,
|
| 1372 |
+
handle = io.open(file, "rb", buffering=buffering)
|
| 1373 |
+
reader = _Reader(handle, self, task_id, close_handle=True)
|
| 1374 |
+
|
| 1375 |
+
# wrap the reader in a `TextIOWrapper` if text mode
|
| 1376 |
+
if mode in ("r", "rt"):
|
| 1377 |
+
return io.TextIOWrapper(
|
| 1378 |
+
reader,
|
| 1379 |
+
encoding=encoding,
|
| 1380 |
+
errors=errors,
|
| 1381 |
+
newline=newline,
|
| 1382 |
+
line_buffering=line_buffering,
|
| 1383 |
+
)
|
| 1384 |
+
|
| 1385 |
+
return reader
|
| 1386 |
+
|
| 1387 |
+
def start_task(self, task_id: TaskID) -> None:
|
| 1388 |
+
"""Start a task.
|
| 1389 |
+
|
| 1390 |
+
Starts a task (used when calculating elapsed time). You may need to call this manually,
|
| 1391 |
+
if you called ``add_task`` with ``start=False``.
|
| 1392 |
+
|
| 1393 |
+
Args:
|
| 1394 |
+
task_id (TaskID): ID of task.
|
| 1395 |
+
"""
|
| 1396 |
+
with self._lock:
|
| 1397 |
+
task = self._tasks[task_id]
|
| 1398 |
+
if task.start_time is None:
|
| 1399 |
+
task.start_time = self.get_time()
|
| 1400 |
+
|
| 1401 |
+
def stop_task(self, task_id: TaskID) -> None:
|
| 1402 |
+
"""Stop a task.
|
| 1403 |
+
|
| 1404 |
+
This will freeze the elapsed time on the task.
|
| 1405 |
+
|
| 1406 |
+
Args:
|
| 1407 |
+
task_id (TaskID): ID of task.
|
| 1408 |
+
"""
|
| 1409 |
+
with self._lock:
|
| 1410 |
+
task = self._tasks[task_id]
|
| 1411 |
+
current_time = self.get_time()
|
| 1412 |
+
if task.start_time is None:
|
| 1413 |
+
task.start_time = current_time
|
| 1414 |
+
task.stop_time = current_time
|
| 1415 |
+
|
| 1416 |
+
def update(
|
| 1417 |
+
self,
|
| 1418 |
+
task_id: TaskID,
|
| 1419 |
+
*,
|
| 1420 |
+
total: Optional[float] = None,
|
| 1421 |
+
completed: Optional[float] = None,
|
| 1422 |
+
advance: Optional[float] = None,
|
| 1423 |
+
description: Optional[str] = None,
|
| 1424 |
+
visible: Optional[bool] = None,
|
| 1425 |
+
refresh: bool = False,
|
| 1426 |
+
**fields: Any,
|
| 1427 |
+
) -> None:
|
| 1428 |
+
"""Update information associated with a task.
|
| 1429 |
+
|
| 1430 |
+
Args:
|
| 1431 |
+
task_id (TaskID): Task id (returned by add_task).
|
| 1432 |
+
total (float, optional): Updates task.total if not None.
|
| 1433 |
+
completed (float, optional): Updates task.completed if not None.
|
| 1434 |
+
advance (float, optional): Add a value to task.completed if not None.
|
| 1435 |
+
description (str, optional): Change task description if not None.
|
| 1436 |
+
visible (bool, optional): Set visible flag if not None.
|
| 1437 |
+
refresh (bool): Force a refresh of progress information. Default is False.
|
| 1438 |
+
**fields (Any): Additional data fields required for rendering.
|
| 1439 |
+
"""
|
| 1440 |
+
with self._lock:
|
| 1441 |
+
task = self._tasks[task_id]
|
| 1442 |
+
completed_start = task.completed
|
| 1443 |
+
|
| 1444 |
+
if total is not None and total != task.total:
|
| 1445 |
+
task.total = total
|
| 1446 |
+
task._reset()
|
| 1447 |
+
if advance is not None:
|
| 1448 |
+
task.completed += advance
|
| 1449 |
+
if completed is not None:
|
| 1450 |
+
task.completed = completed
|
| 1451 |
+
if description is not None:
|
| 1452 |
+
task.description = description
|
| 1453 |
+
if visible is not None:
|
| 1454 |
+
task.visible = visible
|
| 1455 |
+
task.fields.update(fields)
|
| 1456 |
+
update_completed = task.completed - completed_start
|
| 1457 |
+
|
| 1458 |
+
current_time = self.get_time()
|
| 1459 |
+
old_sample_time = current_time - self.speed_estimate_period
|
| 1460 |
+
_progress = task._progress
|
| 1461 |
+
|
| 1462 |
+
popleft = _progress.popleft
|
| 1463 |
+
while _progress and _progress[0].timestamp < old_sample_time:
|
| 1464 |
+
popleft()
|
| 1465 |
+
if update_completed > 0:
|
| 1466 |
+
_progress.append(ProgressSample(current_time, update_completed))
|
| 1467 |
+
if (
|
| 1468 |
+
task.total is not None
|
| 1469 |
+
and task.completed >= task.total
|
| 1470 |
+
and task.finished_time is None
|
| 1471 |
+
):
|
| 1472 |
+
task.finished_time = task.elapsed
|
| 1473 |
+
|
| 1474 |
+
if refresh:
|
| 1475 |
+
self.refresh()
|
| 1476 |
+
|
| 1477 |
+
def reset(
|
| 1478 |
+
self,
|
| 1479 |
+
task_id: TaskID,
|
| 1480 |
+
*,
|
| 1481 |
+
start: bool = True,
|
| 1482 |
+
total: Optional[float] = None,
|
| 1483 |
+
completed: int = 0,
|
| 1484 |
+
visible: Optional[bool] = None,
|
| 1485 |
+
description: Optional[str] = None,
|
| 1486 |
+
**fields: Any,
|
| 1487 |
+
) -> None:
|
| 1488 |
+
"""Reset a task so completed is 0 and the clock is reset.
|
| 1489 |
+
|
| 1490 |
+
Args:
|
| 1491 |
+
task_id (TaskID): ID of task.
|
| 1492 |
+
start (bool, optional): Start the task after reset. Defaults to True.
|
| 1493 |
+
total (float, optional): New total steps in task, or None to use current total. Defaults to None.
|
| 1494 |
+
completed (int, optional): Number of steps completed. Defaults to 0.
|
| 1495 |
+
visible (bool, optional): Enable display of the task. Defaults to True.
|
| 1496 |
+
description (str, optional): Change task description if not None. Defaults to None.
|
| 1497 |
+
**fields (str): Additional data fields required for rendering.
|
| 1498 |
+
"""
|
| 1499 |
+
current_time = self.get_time()
|
| 1500 |
+
with self._lock:
|
| 1501 |
+
task = self._tasks[task_id]
|
| 1502 |
+
task._reset()
|
| 1503 |
+
task.start_time = current_time if start else None
|
| 1504 |
+
if total is not None:
|
| 1505 |
+
task.total = total
|
| 1506 |
+
task.completed = completed
|
| 1507 |
+
if visible is not None:
|
| 1508 |
+
task.visible = visible
|
| 1509 |
+
if fields:
|
| 1510 |
+
task.fields = fields
|
| 1511 |
+
if description is not None:
|
| 1512 |
+
task.description = description
|
| 1513 |
+
task.finished_time = None
|
| 1514 |
+
self.refresh()
|
| 1515 |
+
|
| 1516 |
+
def advance(self, task_id: TaskID, advance: float = 1) -> None:
|
| 1517 |
+
"""Advance task by a number of steps.
|
| 1518 |
+
|
| 1519 |
+
Args:
|
| 1520 |
+
task_id (TaskID): ID of task.
|
| 1521 |
+
advance (float): Number of steps to advance. Default is 1.
|
| 1522 |
+
"""
|
| 1523 |
+
current_time = self.get_time()
|
| 1524 |
+
with self._lock:
|
| 1525 |
+
task = self._tasks[task_id]
|
| 1526 |
+
completed_start = task.completed
|
| 1527 |
+
task.completed += advance
|
| 1528 |
+
update_completed = task.completed - completed_start
|
| 1529 |
+
old_sample_time = current_time - self.speed_estimate_period
|
| 1530 |
+
_progress = task._progress
|
| 1531 |
+
|
| 1532 |
+
popleft = _progress.popleft
|
| 1533 |
+
while _progress and _progress[0].timestamp < old_sample_time:
|
| 1534 |
+
popleft()
|
| 1535 |
+
while len(_progress) > 1000:
|
| 1536 |
+
popleft()
|
| 1537 |
+
_progress.append(ProgressSample(current_time, update_completed))
|
| 1538 |
+
if (
|
| 1539 |
+
task.total is not None
|
| 1540 |
+
and task.completed >= task.total
|
| 1541 |
+
and task.finished_time is None
|
| 1542 |
+
):
|
| 1543 |
+
task.finished_time = task.elapsed
|
| 1544 |
+
task.finished_speed = task.speed
|
| 1545 |
+
|
| 1546 |
+
def refresh(self) -> None:
|
| 1547 |
+
"""Refresh (render) the progress information."""
|
| 1548 |
+
if not self.disable and self.live.is_started:
|
| 1549 |
+
self.live.refresh()
|
| 1550 |
+
|
| 1551 |
+
def get_renderable(self) -> RenderableType:
|
| 1552 |
+
"""Get a renderable for the progress display."""
|
| 1553 |
+
renderable = Group(*self.get_renderables())
|
| 1554 |
+
return renderable
|
| 1555 |
+
|
| 1556 |
+
def get_renderables(self) -> Iterable[RenderableType]:
|
| 1557 |
+
"""Get a number of renderables for the progress display."""
|
| 1558 |
+
table = self.make_tasks_table(self.tasks)
|
| 1559 |
+
yield table
|
| 1560 |
+
|
| 1561 |
+
def make_tasks_table(self, tasks: Iterable[Task]) -> Table:
|
| 1562 |
+
"""Get a table to render the Progress display.
|
| 1563 |
+
|
| 1564 |
+
Args:
|
| 1565 |
+
tasks (Iterable[Task]): An iterable of Task instances, one per row of the table.
|
| 1566 |
+
|
| 1567 |
+
Returns:
|
| 1568 |
+
Table: A table instance.
|
| 1569 |
+
"""
|
| 1570 |
+
table_columns = (
|
| 1571 |
+
(
|
| 1572 |
+
Column(no_wrap=True)
|
| 1573 |
+
if isinstance(_column, str)
|
| 1574 |
+
else _column.get_table_column().copy()
|
| 1575 |
+
)
|
| 1576 |
+
for _column in self.columns
|
| 1577 |
+
)
|
| 1578 |
+
table = Table.grid(*table_columns, padding=(0, 1), expand=self.expand)
|
| 1579 |
+
|
| 1580 |
+
for task in tasks:
|
| 1581 |
+
if task.visible:
|
| 1582 |
+
table.add_row(
|
| 1583 |
+
*(
|
| 1584 |
+
(
|
| 1585 |
+
column.format(task=task)
|
| 1586 |
+
if isinstance(column, str)
|
| 1587 |
+
else column(task)
|
| 1588 |
+
)
|
| 1589 |
+
for column in self.columns
|
| 1590 |
+
)
|
| 1591 |
+
)
|
| 1592 |
+
return table
|
| 1593 |
+
|
| 1594 |
+
def __rich__(self) -> RenderableType:
|
| 1595 |
+
"""Makes the Progress class itself renderable."""
|
| 1596 |
+
with self._lock:
|
| 1597 |
+
return self.get_renderable()
|
| 1598 |
+
|
| 1599 |
+
def add_task(
|
| 1600 |
+
self,
|
| 1601 |
+
description: str,
|
| 1602 |
+
start: bool = True,
|
| 1603 |
+
total: Optional[float] = 100.0,
|
| 1604 |
+
completed: int = 0,
|
| 1605 |
+
visible: bool = True,
|
| 1606 |
+
**fields: Any,
|
| 1607 |
+
) -> TaskID:
|
| 1608 |
+
"""Add a new 'task' to the Progress display.
|
| 1609 |
+
|
| 1610 |
+
Args:
|
| 1611 |
+
description (str): A description of the task.
|
| 1612 |
+
start (bool, optional): Start the task immediately (to calculate elapsed time). If set to False,
|
| 1613 |
+
you will need to call `start` manually. Defaults to True.
|
| 1614 |
+
total (float, optional): Number of total steps in the progress if known.
|
| 1615 |
+
Set to None to render a pulsing animation. Defaults to 100.
|
| 1616 |
+
completed (int, optional): Number of steps completed so far. Defaults to 0.
|
| 1617 |
+
visible (bool, optional): Enable display of the task. Defaults to True.
|
| 1618 |
+
**fields (str): Additional data fields required for rendering.
|
| 1619 |
+
|
| 1620 |
+
Returns:
|
| 1621 |
+
TaskID: An ID you can use when calling `update`.
|
| 1622 |
+
"""
|
| 1623 |
+
with self._lock:
|
| 1624 |
+
task = Task(
|
| 1625 |
+
self._task_index,
|
| 1626 |
+
description,
|
| 1627 |
+
total,
|
| 1628 |
+
completed,
|
| 1629 |
+
visible=visible,
|
| 1630 |
+
fields=fields,
|
| 1631 |
+
_get_time=self.get_time,
|
| 1632 |
+
_lock=self._lock,
|
| 1633 |
+
)
|
| 1634 |
+
self._tasks[self._task_index] = task
|
| 1635 |
+
if start:
|
| 1636 |
+
self.start_task(self._task_index)
|
| 1637 |
+
new_task_index = self._task_index
|
| 1638 |
+
self._task_index = TaskID(int(self._task_index) + 1)
|
| 1639 |
+
self.refresh()
|
| 1640 |
+
return new_task_index
|
| 1641 |
+
|
| 1642 |
+
def remove_task(self, task_id: TaskID) -> None:
|
| 1643 |
+
"""Delete a task if it exists.
|
| 1644 |
+
|
| 1645 |
+
Args:
|
| 1646 |
+
task_id (TaskID): A task ID.
|
| 1647 |
+
|
| 1648 |
+
"""
|
| 1649 |
+
with self._lock:
|
| 1650 |
+
del self._tasks[task_id]
|
| 1651 |
+
|
| 1652 |
+
|
| 1653 |
+
if __name__ == "__main__": # pragma: no coverage
|
| 1654 |
+
import random
|
| 1655 |
+
import time
|
| 1656 |
+
|
| 1657 |
+
from .panel import Panel
|
| 1658 |
+
from .rule import Rule
|
| 1659 |
+
from .syntax import Syntax
|
| 1660 |
+
from .table import Table
|
| 1661 |
+
|
| 1662 |
+
syntax = Syntax(
|
| 1663 |
+
'''def loop_last(values: Iterable[T]) -> Iterable[Tuple[bool, T]]:
|
| 1664 |
+
"""Iterate and generate a tuple with a flag for last value."""
|
| 1665 |
+
iter_values = iter(values)
|
| 1666 |
+
try:
|
| 1667 |
+
previous_value = next(iter_values)
|
| 1668 |
+
except StopIteration:
|
| 1669 |
+
return
|
| 1670 |
+
for value in iter_values:
|
| 1671 |
+
yield False, previous_value
|
| 1672 |
+
previous_value = value
|
| 1673 |
+
yield True, previous_value''',
|
| 1674 |
+
"python",
|
| 1675 |
+
line_numbers=True,
|
| 1676 |
+
)
|
| 1677 |
+
|
| 1678 |
+
table = Table("foo", "bar", "baz")
|
| 1679 |
+
table.add_row("1", "2", "3")
|
| 1680 |
+
|
| 1681 |
+
progress_renderables = [
|
| 1682 |
+
"Text may be printed while the progress bars are rendering.",
|
| 1683 |
+
Panel("In fact, [i]any[/i] renderable will work"),
|
| 1684 |
+
"Such as [magenta]tables[/]...",
|
| 1685 |
+
table,
|
| 1686 |
+
"Pretty printed structures...",
|
| 1687 |
+
{"type": "example", "text": "Pretty printed"},
|
| 1688 |
+
"Syntax...",
|
| 1689 |
+
syntax,
|
| 1690 |
+
Rule("Give it a try!"),
|
| 1691 |
+
]
|
| 1692 |
+
|
| 1693 |
+
from itertools import cycle
|
| 1694 |
+
|
| 1695 |
+
examples = cycle(progress_renderables)
|
| 1696 |
+
|
| 1697 |
+
console = Console(record=True)
|
| 1698 |
+
|
| 1699 |
+
with Progress(
|
| 1700 |
+
SpinnerColumn(),
|
| 1701 |
+
*Progress.get_default_columns(),
|
| 1702 |
+
TimeElapsedColumn(),
|
| 1703 |
+
console=console,
|
| 1704 |
+
transient=False,
|
| 1705 |
+
) as progress:
|
| 1706 |
+
task1 = progress.add_task("[red]Downloading", total=1000)
|
| 1707 |
+
task2 = progress.add_task("[green]Processing", total=1000)
|
| 1708 |
+
task3 = progress.add_task("[yellow]Thinking", total=None)
|
| 1709 |
+
|
| 1710 |
+
while not progress.finished:
|
| 1711 |
+
progress.update(task1, advance=0.5)
|
| 1712 |
+
progress.update(task2, advance=0.3)
|
| 1713 |
+
time.sleep(0.01)
|
| 1714 |
+
if random.randint(0, 100) < 1:
|
| 1715 |
+
progress.log(next(examples))
|
miniconda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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
from functools import lru_cache
|
| 3 |
+
from time import monotonic
|
| 4 |
+
from typing import Iterable, List, Optional
|
| 5 |
+
|
| 6 |
+
from .color import Color, blend_rgb
|
| 7 |
+
from .color_triplet import ColorTriplet
|
| 8 |
+
from .console import Console, ConsoleOptions, RenderResult
|
| 9 |
+
from .jupyter import JupyterMixin
|
| 10 |
+
from .measure import Measurement
|
| 11 |
+
from .segment import Segment
|
| 12 |
+
from .style import Style, StyleType
|
| 13 |
+
|
| 14 |
+
# Number of characters before 'pulse' animation repeats
|
| 15 |
+
PULSE_SIZE = 20
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class ProgressBar(JupyterMixin):
|
| 19 |
+
"""Renders a (progress) bar. Used by rich.progress.
|
| 20 |
+
|
| 21 |
+
Args:
|
| 22 |
+
total (float, optional): Number of steps in the bar. Defaults to 100. Set to None to render a pulsing animation.
|
| 23 |
+
completed (float, optional): Number of steps completed. Defaults to 0.
|
| 24 |
+
width (int, optional): Width of the bar, or ``None`` for maximum width. Defaults to None.
|
| 25 |
+
pulse (bool, optional): Enable pulse effect. Defaults to False. Will pulse if a None total was passed.
|
| 26 |
+
style (StyleType, optional): Style for the bar background. Defaults to "bar.back".
|
| 27 |
+
complete_style (StyleType, optional): Style for the completed bar. Defaults to "bar.complete".
|
| 28 |
+
finished_style (StyleType, optional): Style for a finished bar. Defaults to "bar.finished".
|
| 29 |
+
pulse_style (StyleType, optional): Style for pulsing bars. Defaults to "bar.pulse".
|
| 30 |
+
animation_time (Optional[float], optional): Time in seconds to use for animation, or None to use system time.
|
| 31 |
+
"""
|
| 32 |
+
|
| 33 |
+
def __init__(
|
| 34 |
+
self,
|
| 35 |
+
total: Optional[float] = 100.0,
|
| 36 |
+
completed: float = 0,
|
| 37 |
+
width: Optional[int] = None,
|
| 38 |
+
pulse: bool = False,
|
| 39 |
+
style: StyleType = "bar.back",
|
| 40 |
+
complete_style: StyleType = "bar.complete",
|
| 41 |
+
finished_style: StyleType = "bar.finished",
|
| 42 |
+
pulse_style: StyleType = "bar.pulse",
|
| 43 |
+
animation_time: Optional[float] = None,
|
| 44 |
+
):
|
| 45 |
+
self.total = total
|
| 46 |
+
self.completed = completed
|
| 47 |
+
self.width = width
|
| 48 |
+
self.pulse = pulse
|
| 49 |
+
self.style = style
|
| 50 |
+
self.complete_style = complete_style
|
| 51 |
+
self.finished_style = finished_style
|
| 52 |
+
self.pulse_style = pulse_style
|
| 53 |
+
self.animation_time = animation_time
|
| 54 |
+
|
| 55 |
+
self._pulse_segments: Optional[List[Segment]] = None
|
| 56 |
+
|
| 57 |
+
def __repr__(self) -> str:
|
| 58 |
+
return f"<Bar {self.completed!r} of {self.total!r}>"
|
| 59 |
+
|
| 60 |
+
@property
|
| 61 |
+
def percentage_completed(self) -> Optional[float]:
|
| 62 |
+
"""Calculate percentage complete."""
|
| 63 |
+
if self.total is None:
|
| 64 |
+
return None
|
| 65 |
+
completed = (self.completed / self.total) * 100.0
|
| 66 |
+
completed = min(100, max(0.0, completed))
|
| 67 |
+
return completed
|
| 68 |
+
|
| 69 |
+
@lru_cache(maxsize=16)
|
| 70 |
+
def _get_pulse_segments(
|
| 71 |
+
self,
|
| 72 |
+
fore_style: Style,
|
| 73 |
+
back_style: Style,
|
| 74 |
+
color_system: str,
|
| 75 |
+
no_color: bool,
|
| 76 |
+
ascii: bool = False,
|
| 77 |
+
) -> List[Segment]:
|
| 78 |
+
"""Get a list of segments to render a pulse animation.
|
| 79 |
+
|
| 80 |
+
Returns:
|
| 81 |
+
List[Segment]: A list of segments, one segment per character.
|
| 82 |
+
"""
|
| 83 |
+
bar = "-" if ascii else "━"
|
| 84 |
+
segments: List[Segment] = []
|
| 85 |
+
if color_system not in ("standard", "eight_bit", "truecolor") or no_color:
|
| 86 |
+
segments += [Segment(bar, fore_style)] * (PULSE_SIZE // 2)
|
| 87 |
+
segments += [Segment(" " if no_color else bar, back_style)] * (
|
| 88 |
+
PULSE_SIZE - (PULSE_SIZE // 2)
|
| 89 |
+
)
|
| 90 |
+
return segments
|
| 91 |
+
|
| 92 |
+
append = segments.append
|
| 93 |
+
fore_color = (
|
| 94 |
+
fore_style.color.get_truecolor()
|
| 95 |
+
if fore_style.color
|
| 96 |
+
else ColorTriplet(255, 0, 255)
|
| 97 |
+
)
|
| 98 |
+
back_color = (
|
| 99 |
+
back_style.color.get_truecolor()
|
| 100 |
+
if back_style.color
|
| 101 |
+
else ColorTriplet(0, 0, 0)
|
| 102 |
+
)
|
| 103 |
+
cos = math.cos
|
| 104 |
+
pi = math.pi
|
| 105 |
+
_Segment = Segment
|
| 106 |
+
_Style = Style
|
| 107 |
+
from_triplet = Color.from_triplet
|
| 108 |
+
|
| 109 |
+
for index in range(PULSE_SIZE):
|
| 110 |
+
position = index / PULSE_SIZE
|
| 111 |
+
fade = 0.5 + cos(position * pi * 2) / 2.0
|
| 112 |
+
color = blend_rgb(fore_color, back_color, cross_fade=fade)
|
| 113 |
+
append(_Segment(bar, _Style(color=from_triplet(color))))
|
| 114 |
+
return segments
|
| 115 |
+
|
| 116 |
+
def update(self, completed: float, total: Optional[float] = None) -> None:
|
| 117 |
+
"""Update progress with new values.
|
| 118 |
+
|
| 119 |
+
Args:
|
| 120 |
+
completed (float): Number of steps completed.
|
| 121 |
+
total (float, optional): Total number of steps, or ``None`` to not change. Defaults to None.
|
| 122 |
+
"""
|
| 123 |
+
self.completed = completed
|
| 124 |
+
self.total = total if total is not None else self.total
|
| 125 |
+
|
| 126 |
+
def _render_pulse(
|
| 127 |
+
self, console: Console, width: int, ascii: bool = False
|
| 128 |
+
) -> Iterable[Segment]:
|
| 129 |
+
"""Renders the pulse animation.
|
| 130 |
+
|
| 131 |
+
Args:
|
| 132 |
+
console (Console): Console instance.
|
| 133 |
+
width (int): Width in characters of pulse animation.
|
| 134 |
+
|
| 135 |
+
Returns:
|
| 136 |
+
RenderResult: [description]
|
| 137 |
+
|
| 138 |
+
Yields:
|
| 139 |
+
Iterator[Segment]: Segments to render pulse
|
| 140 |
+
"""
|
| 141 |
+
fore_style = console.get_style(self.pulse_style, default="white")
|
| 142 |
+
back_style = console.get_style(self.style, default="black")
|
| 143 |
+
|
| 144 |
+
pulse_segments = self._get_pulse_segments(
|
| 145 |
+
fore_style, back_style, console.color_system, console.no_color, ascii=ascii
|
| 146 |
+
)
|
| 147 |
+
segment_count = len(pulse_segments)
|
| 148 |
+
current_time = (
|
| 149 |
+
monotonic() if self.animation_time is None else self.animation_time
|
| 150 |
+
)
|
| 151 |
+
segments = pulse_segments * (int(width / segment_count) + 2)
|
| 152 |
+
offset = int(-current_time * 15) % segment_count
|
| 153 |
+
segments = segments[offset : offset + width]
|
| 154 |
+
yield from segments
|
| 155 |
+
|
| 156 |
+
def __rich_console__(
|
| 157 |
+
self, console: Console, options: ConsoleOptions
|
| 158 |
+
) -> RenderResult:
|
| 159 |
+
width = min(self.width or options.max_width, options.max_width)
|
| 160 |
+
ascii = options.legacy_windows or options.ascii_only
|
| 161 |
+
should_pulse = self.pulse or self.total is None
|
| 162 |
+
if should_pulse:
|
| 163 |
+
yield from self._render_pulse(console, width, ascii=ascii)
|
| 164 |
+
return
|
| 165 |
+
|
| 166 |
+
completed: Optional[float] = (
|
| 167 |
+
min(self.total, max(0, self.completed)) if self.total is not None else None
|
| 168 |
+
)
|
| 169 |
+
|
| 170 |
+
bar = "-" if ascii else "━"
|
| 171 |
+
half_bar_right = " " if ascii else "╸"
|
| 172 |
+
half_bar_left = " " if ascii else "╺"
|
| 173 |
+
complete_halves = (
|
| 174 |
+
int(width * 2 * completed / self.total)
|
| 175 |
+
if self.total and completed is not None
|
| 176 |
+
else width * 2
|
| 177 |
+
)
|
| 178 |
+
bar_count = complete_halves // 2
|
| 179 |
+
half_bar_count = complete_halves % 2
|
| 180 |
+
style = console.get_style(self.style)
|
| 181 |
+
is_finished = self.total is None or self.completed >= self.total
|
| 182 |
+
complete_style = console.get_style(
|
| 183 |
+
self.finished_style if is_finished else self.complete_style
|
| 184 |
+
)
|
| 185 |
+
_Segment = Segment
|
| 186 |
+
if bar_count:
|
| 187 |
+
yield _Segment(bar * bar_count, complete_style)
|
| 188 |
+
if half_bar_count:
|
| 189 |
+
yield _Segment(half_bar_right * half_bar_count, complete_style)
|
| 190 |
+
|
| 191 |
+
if not console.no_color:
|
| 192 |
+
remaining_bars = width - bar_count - half_bar_count
|
| 193 |
+
if remaining_bars and console.color_system is not None:
|
| 194 |
+
if not half_bar_count and bar_count:
|
| 195 |
+
yield _Segment(half_bar_left, style)
|
| 196 |
+
remaining_bars -= 1
|
| 197 |
+
if remaining_bars:
|
| 198 |
+
yield _Segment(bar * remaining_bars, style)
|
| 199 |
+
|
| 200 |
+
def __rich_measure__(
|
| 201 |
+
self, console: Console, options: ConsoleOptions
|
| 202 |
+
) -> Measurement:
|
| 203 |
+
return (
|
| 204 |
+
Measurement(self.width, self.width)
|
| 205 |
+
if self.width is not None
|
| 206 |
+
else Measurement(4, options.max_width)
|
| 207 |
+
)
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
if __name__ == "__main__": # pragma: no cover
|
| 211 |
+
console = Console()
|
| 212 |
+
bar = ProgressBar(width=50, total=100)
|
| 213 |
+
|
| 214 |
+
import time
|
| 215 |
+
|
| 216 |
+
console.show_cursor(False)
|
| 217 |
+
for n in range(0, 101, 1):
|
| 218 |
+
bar.update(n)
|
| 219 |
+
console.print(bar)
|
| 220 |
+
console.file.write("\r")
|
| 221 |
+
time.sleep(0.05)
|
| 222 |
+
console.show_cursor(True)
|
| 223 |
+
console.print()
|
miniconda3/lib/python3.13/site-packages/rich/prompt.py
ADDED
|
@@ -0,0 +1,400 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Any, Generic, List, Optional, TextIO, TypeVar, Union, overload
|
| 2 |
+
|
| 3 |
+
from . import get_console
|
| 4 |
+
from .console import Console
|
| 5 |
+
from .text import Text, TextType
|
| 6 |
+
|
| 7 |
+
PromptType = TypeVar("PromptType")
|
| 8 |
+
DefaultType = TypeVar("DefaultType")
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class PromptError(Exception):
|
| 12 |
+
"""Exception base class for prompt related errors."""
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class InvalidResponse(PromptError):
|
| 16 |
+
"""Exception to indicate a response was invalid. Raise this within process_response() to indicate an error
|
| 17 |
+
and provide an error message.
|
| 18 |
+
|
| 19 |
+
Args:
|
| 20 |
+
message (Union[str, Text]): Error message.
|
| 21 |
+
"""
|
| 22 |
+
|
| 23 |
+
def __init__(self, message: TextType) -> None:
|
| 24 |
+
self.message = message
|
| 25 |
+
|
| 26 |
+
def __rich__(self) -> TextType:
|
| 27 |
+
return self.message
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class PromptBase(Generic[PromptType]):
|
| 31 |
+
"""Ask the user for input until a valid response is received. This is the base class, see one of
|
| 32 |
+
the concrete classes for examples.
|
| 33 |
+
|
| 34 |
+
Args:
|
| 35 |
+
prompt (TextType, optional): Prompt text. Defaults to "".
|
| 36 |
+
console (Console, optional): A Console instance or None to use global console. Defaults to None.
|
| 37 |
+
password (bool, optional): Enable password input. Defaults to False.
|
| 38 |
+
choices (List[str], optional): A list of valid choices. Defaults to None.
|
| 39 |
+
case_sensitive (bool, optional): Matching of choices should be case-sensitive. Defaults to True.
|
| 40 |
+
show_default (bool, optional): Show default in prompt. Defaults to True.
|
| 41 |
+
show_choices (bool, optional): Show choices in prompt. Defaults to True.
|
| 42 |
+
"""
|
| 43 |
+
|
| 44 |
+
response_type: type = str
|
| 45 |
+
|
| 46 |
+
validate_error_message = "[prompt.invalid]Please enter a valid value"
|
| 47 |
+
illegal_choice_message = (
|
| 48 |
+
"[prompt.invalid.choice]Please select one of the available options"
|
| 49 |
+
)
|
| 50 |
+
prompt_suffix = ": "
|
| 51 |
+
|
| 52 |
+
choices: Optional[List[str]] = None
|
| 53 |
+
|
| 54 |
+
def __init__(
|
| 55 |
+
self,
|
| 56 |
+
prompt: TextType = "",
|
| 57 |
+
*,
|
| 58 |
+
console: Optional[Console] = None,
|
| 59 |
+
password: bool = False,
|
| 60 |
+
choices: Optional[List[str]] = None,
|
| 61 |
+
case_sensitive: bool = True,
|
| 62 |
+
show_default: bool = True,
|
| 63 |
+
show_choices: bool = True,
|
| 64 |
+
) -> None:
|
| 65 |
+
self.console = console or get_console()
|
| 66 |
+
self.prompt = (
|
| 67 |
+
Text.from_markup(prompt, style="prompt")
|
| 68 |
+
if isinstance(prompt, str)
|
| 69 |
+
else prompt
|
| 70 |
+
)
|
| 71 |
+
self.password = password
|
| 72 |
+
if choices is not None:
|
| 73 |
+
self.choices = choices
|
| 74 |
+
self.case_sensitive = case_sensitive
|
| 75 |
+
self.show_default = show_default
|
| 76 |
+
self.show_choices = show_choices
|
| 77 |
+
|
| 78 |
+
@classmethod
|
| 79 |
+
@overload
|
| 80 |
+
def ask(
|
| 81 |
+
cls,
|
| 82 |
+
prompt: TextType = "",
|
| 83 |
+
*,
|
| 84 |
+
console: Optional[Console] = None,
|
| 85 |
+
password: bool = False,
|
| 86 |
+
choices: Optional[List[str]] = None,
|
| 87 |
+
case_sensitive: bool = True,
|
| 88 |
+
show_default: bool = True,
|
| 89 |
+
show_choices: bool = True,
|
| 90 |
+
default: DefaultType,
|
| 91 |
+
stream: Optional[TextIO] = None,
|
| 92 |
+
) -> Union[DefaultType, PromptType]:
|
| 93 |
+
...
|
| 94 |
+
|
| 95 |
+
@classmethod
|
| 96 |
+
@overload
|
| 97 |
+
def ask(
|
| 98 |
+
cls,
|
| 99 |
+
prompt: TextType = "",
|
| 100 |
+
*,
|
| 101 |
+
console: Optional[Console] = None,
|
| 102 |
+
password: bool = False,
|
| 103 |
+
choices: Optional[List[str]] = None,
|
| 104 |
+
case_sensitive: bool = True,
|
| 105 |
+
show_default: bool = True,
|
| 106 |
+
show_choices: bool = True,
|
| 107 |
+
stream: Optional[TextIO] = None,
|
| 108 |
+
) -> PromptType:
|
| 109 |
+
...
|
| 110 |
+
|
| 111 |
+
@classmethod
|
| 112 |
+
def ask(
|
| 113 |
+
cls,
|
| 114 |
+
prompt: TextType = "",
|
| 115 |
+
*,
|
| 116 |
+
console: Optional[Console] = None,
|
| 117 |
+
password: bool = False,
|
| 118 |
+
choices: Optional[List[str]] = None,
|
| 119 |
+
case_sensitive: bool = True,
|
| 120 |
+
show_default: bool = True,
|
| 121 |
+
show_choices: bool = True,
|
| 122 |
+
default: Any = ...,
|
| 123 |
+
stream: Optional[TextIO] = None,
|
| 124 |
+
) -> Any:
|
| 125 |
+
"""Shortcut to construct and run a prompt loop and return the result.
|
| 126 |
+
|
| 127 |
+
Example:
|
| 128 |
+
>>> filename = Prompt.ask("Enter a filename")
|
| 129 |
+
|
| 130 |
+
Args:
|
| 131 |
+
prompt (TextType, optional): Prompt text. Defaults to "".
|
| 132 |
+
console (Console, optional): A Console instance or None to use global console. Defaults to None.
|
| 133 |
+
password (bool, optional): Enable password input. Defaults to False.
|
| 134 |
+
choices (List[str], optional): A list of valid choices. Defaults to None.
|
| 135 |
+
case_sensitive (bool, optional): Matching of choices should be case-sensitive. Defaults to True.
|
| 136 |
+
show_default (bool, optional): Show default in prompt. Defaults to True.
|
| 137 |
+
show_choices (bool, optional): Show choices in prompt. Defaults to True.
|
| 138 |
+
stream (TextIO, optional): Optional text file open for reading to get input. Defaults to None.
|
| 139 |
+
"""
|
| 140 |
+
_prompt = cls(
|
| 141 |
+
prompt,
|
| 142 |
+
console=console,
|
| 143 |
+
password=password,
|
| 144 |
+
choices=choices,
|
| 145 |
+
case_sensitive=case_sensitive,
|
| 146 |
+
show_default=show_default,
|
| 147 |
+
show_choices=show_choices,
|
| 148 |
+
)
|
| 149 |
+
return _prompt(default=default, stream=stream)
|
| 150 |
+
|
| 151 |
+
def render_default(self, default: DefaultType) -> Text:
|
| 152 |
+
"""Turn the supplied default in to a Text instance.
|
| 153 |
+
|
| 154 |
+
Args:
|
| 155 |
+
default (DefaultType): Default value.
|
| 156 |
+
|
| 157 |
+
Returns:
|
| 158 |
+
Text: Text containing rendering of default value.
|
| 159 |
+
"""
|
| 160 |
+
return Text(f"({default})", "prompt.default")
|
| 161 |
+
|
| 162 |
+
def make_prompt(self, default: DefaultType) -> Text:
|
| 163 |
+
"""Make prompt text.
|
| 164 |
+
|
| 165 |
+
Args:
|
| 166 |
+
default (DefaultType): Default value.
|
| 167 |
+
|
| 168 |
+
Returns:
|
| 169 |
+
Text: Text to display in prompt.
|
| 170 |
+
"""
|
| 171 |
+
prompt = self.prompt.copy()
|
| 172 |
+
prompt.end = ""
|
| 173 |
+
|
| 174 |
+
if self.show_choices and self.choices:
|
| 175 |
+
_choices = "/".join(self.choices)
|
| 176 |
+
choices = f"[{_choices}]"
|
| 177 |
+
prompt.append(" ")
|
| 178 |
+
prompt.append(choices, "prompt.choices")
|
| 179 |
+
|
| 180 |
+
if (
|
| 181 |
+
default != ...
|
| 182 |
+
and self.show_default
|
| 183 |
+
and isinstance(default, (str, self.response_type))
|
| 184 |
+
):
|
| 185 |
+
prompt.append(" ")
|
| 186 |
+
_default = self.render_default(default)
|
| 187 |
+
prompt.append(_default)
|
| 188 |
+
|
| 189 |
+
prompt.append(self.prompt_suffix)
|
| 190 |
+
|
| 191 |
+
return prompt
|
| 192 |
+
|
| 193 |
+
@classmethod
|
| 194 |
+
def get_input(
|
| 195 |
+
cls,
|
| 196 |
+
console: Console,
|
| 197 |
+
prompt: TextType,
|
| 198 |
+
password: bool,
|
| 199 |
+
stream: Optional[TextIO] = None,
|
| 200 |
+
) -> str:
|
| 201 |
+
"""Get input from user.
|
| 202 |
+
|
| 203 |
+
Args:
|
| 204 |
+
console (Console): Console instance.
|
| 205 |
+
prompt (TextType): Prompt text.
|
| 206 |
+
password (bool): Enable password entry.
|
| 207 |
+
|
| 208 |
+
Returns:
|
| 209 |
+
str: String from user.
|
| 210 |
+
"""
|
| 211 |
+
return console.input(prompt, password=password, stream=stream)
|
| 212 |
+
|
| 213 |
+
def check_choice(self, value: str) -> bool:
|
| 214 |
+
"""Check value is in the list of valid choices.
|
| 215 |
+
|
| 216 |
+
Args:
|
| 217 |
+
value (str): Value entered by user.
|
| 218 |
+
|
| 219 |
+
Returns:
|
| 220 |
+
bool: True if choice was valid, otherwise False.
|
| 221 |
+
"""
|
| 222 |
+
assert self.choices is not None
|
| 223 |
+
if self.case_sensitive:
|
| 224 |
+
return value.strip() in self.choices
|
| 225 |
+
return value.strip().lower() in [choice.lower() for choice in self.choices]
|
| 226 |
+
|
| 227 |
+
def process_response(self, value: str) -> PromptType:
|
| 228 |
+
"""Process response from user, convert to prompt type.
|
| 229 |
+
|
| 230 |
+
Args:
|
| 231 |
+
value (str): String typed by user.
|
| 232 |
+
|
| 233 |
+
Raises:
|
| 234 |
+
InvalidResponse: If ``value`` is invalid.
|
| 235 |
+
|
| 236 |
+
Returns:
|
| 237 |
+
PromptType: The value to be returned from ask method.
|
| 238 |
+
"""
|
| 239 |
+
value = value.strip()
|
| 240 |
+
try:
|
| 241 |
+
return_value: PromptType = self.response_type(value)
|
| 242 |
+
except ValueError:
|
| 243 |
+
raise InvalidResponse(self.validate_error_message)
|
| 244 |
+
|
| 245 |
+
if self.choices is not None:
|
| 246 |
+
if not self.check_choice(value):
|
| 247 |
+
raise InvalidResponse(self.illegal_choice_message)
|
| 248 |
+
|
| 249 |
+
if not self.case_sensitive:
|
| 250 |
+
# return the original choice, not the lower case version
|
| 251 |
+
return_value = self.response_type(
|
| 252 |
+
self.choices[
|
| 253 |
+
[choice.lower() for choice in self.choices].index(value.lower())
|
| 254 |
+
]
|
| 255 |
+
)
|
| 256 |
+
return return_value
|
| 257 |
+
|
| 258 |
+
def on_validate_error(self, value: str, error: InvalidResponse) -> None:
|
| 259 |
+
"""Called to handle validation error.
|
| 260 |
+
|
| 261 |
+
Args:
|
| 262 |
+
value (str): String entered by user.
|
| 263 |
+
error (InvalidResponse): Exception instance the initiated the error.
|
| 264 |
+
"""
|
| 265 |
+
self.console.print(error)
|
| 266 |
+
|
| 267 |
+
def pre_prompt(self) -> None:
|
| 268 |
+
"""Hook to display something before the prompt."""
|
| 269 |
+
|
| 270 |
+
@overload
|
| 271 |
+
def __call__(self, *, stream: Optional[TextIO] = None) -> PromptType:
|
| 272 |
+
...
|
| 273 |
+
|
| 274 |
+
@overload
|
| 275 |
+
def __call__(
|
| 276 |
+
self, *, default: DefaultType, stream: Optional[TextIO] = None
|
| 277 |
+
) -> Union[PromptType, DefaultType]:
|
| 278 |
+
...
|
| 279 |
+
|
| 280 |
+
def __call__(self, *, default: Any = ..., stream: Optional[TextIO] = None) -> Any:
|
| 281 |
+
"""Run the prompt loop.
|
| 282 |
+
|
| 283 |
+
Args:
|
| 284 |
+
default (Any, optional): Optional default value.
|
| 285 |
+
|
| 286 |
+
Returns:
|
| 287 |
+
PromptType: Processed value.
|
| 288 |
+
"""
|
| 289 |
+
while True:
|
| 290 |
+
self.pre_prompt()
|
| 291 |
+
prompt = self.make_prompt(default)
|
| 292 |
+
value = self.get_input(self.console, prompt, self.password, stream=stream)
|
| 293 |
+
if value == "" and default != ...:
|
| 294 |
+
return default
|
| 295 |
+
try:
|
| 296 |
+
return_value = self.process_response(value)
|
| 297 |
+
except InvalidResponse as error:
|
| 298 |
+
self.on_validate_error(value, error)
|
| 299 |
+
continue
|
| 300 |
+
else:
|
| 301 |
+
return return_value
|
| 302 |
+
|
| 303 |
+
|
| 304 |
+
class Prompt(PromptBase[str]):
|
| 305 |
+
"""A prompt that returns a str.
|
| 306 |
+
|
| 307 |
+
Example:
|
| 308 |
+
>>> name = Prompt.ask("Enter your name")
|
| 309 |
+
|
| 310 |
+
|
| 311 |
+
"""
|
| 312 |
+
|
| 313 |
+
response_type = str
|
| 314 |
+
|
| 315 |
+
|
| 316 |
+
class IntPrompt(PromptBase[int]):
|
| 317 |
+
"""A prompt that returns an integer.
|
| 318 |
+
|
| 319 |
+
Example:
|
| 320 |
+
>>> burrito_count = IntPrompt.ask("How many burritos do you want to order")
|
| 321 |
+
|
| 322 |
+
"""
|
| 323 |
+
|
| 324 |
+
response_type = int
|
| 325 |
+
validate_error_message = "[prompt.invalid]Please enter a valid integer number"
|
| 326 |
+
|
| 327 |
+
|
| 328 |
+
class FloatPrompt(PromptBase[float]):
|
| 329 |
+
"""A prompt that returns a float.
|
| 330 |
+
|
| 331 |
+
Example:
|
| 332 |
+
>>> temperature = FloatPrompt.ask("Enter desired temperature")
|
| 333 |
+
|
| 334 |
+
"""
|
| 335 |
+
|
| 336 |
+
response_type = float
|
| 337 |
+
validate_error_message = "[prompt.invalid]Please enter a number"
|
| 338 |
+
|
| 339 |
+
|
| 340 |
+
class Confirm(PromptBase[bool]):
|
| 341 |
+
"""A yes / no confirmation prompt.
|
| 342 |
+
|
| 343 |
+
Example:
|
| 344 |
+
>>> if Confirm.ask("Continue"):
|
| 345 |
+
run_job()
|
| 346 |
+
|
| 347 |
+
"""
|
| 348 |
+
|
| 349 |
+
response_type = bool
|
| 350 |
+
validate_error_message = "[prompt.invalid]Please enter Y or N"
|
| 351 |
+
choices: List[str] = ["y", "n"]
|
| 352 |
+
|
| 353 |
+
def render_default(self, default: DefaultType) -> Text:
|
| 354 |
+
"""Render the default as (y) or (n) rather than True/False."""
|
| 355 |
+
yes, no = self.choices
|
| 356 |
+
return Text(f"({yes})" if default else f"({no})", style="prompt.default")
|
| 357 |
+
|
| 358 |
+
def process_response(self, value: str) -> bool:
|
| 359 |
+
"""Convert choices to a bool."""
|
| 360 |
+
value = value.strip().lower()
|
| 361 |
+
if value not in self.choices:
|
| 362 |
+
raise InvalidResponse(self.validate_error_message)
|
| 363 |
+
return value == self.choices[0]
|
| 364 |
+
|
| 365 |
+
|
| 366 |
+
if __name__ == "__main__": # pragma: no cover
|
| 367 |
+
from rich import print
|
| 368 |
+
|
| 369 |
+
if Confirm.ask("Run [i]prompt[/i] tests?", default=True):
|
| 370 |
+
while True:
|
| 371 |
+
result = IntPrompt.ask(
|
| 372 |
+
":rocket: Enter a number between [b]1[/b] and [b]10[/b]", default=5
|
| 373 |
+
)
|
| 374 |
+
if result >= 1 and result <= 10:
|
| 375 |
+
break
|
| 376 |
+
print(":pile_of_poo: [prompt.invalid]Number must be between 1 and 10")
|
| 377 |
+
print(f"number={result}")
|
| 378 |
+
|
| 379 |
+
while True:
|
| 380 |
+
password = Prompt.ask(
|
| 381 |
+
"Please enter a password [cyan](must be at least 5 characters)",
|
| 382 |
+
password=True,
|
| 383 |
+
)
|
| 384 |
+
if len(password) >= 5:
|
| 385 |
+
break
|
| 386 |
+
print("[prompt.invalid]password too short")
|
| 387 |
+
print(f"password={password!r}")
|
| 388 |
+
|
| 389 |
+
fruit = Prompt.ask("Enter a fruit", choices=["apple", "orange", "pear"])
|
| 390 |
+
print(f"fruit={fruit!r}")
|
| 391 |
+
|
| 392 |
+
doggie = Prompt.ask(
|
| 393 |
+
"What's the best Dog? (Case INSENSITIVE)",
|
| 394 |
+
choices=["Border Terrier", "Collie", "Labradoodle"],
|
| 395 |
+
case_sensitive=False,
|
| 396 |
+
)
|
| 397 |
+
print(f"doggie={doggie!r}")
|
| 398 |
+
|
| 399 |
+
else:
|
| 400 |
+
print("[b]OK :loudly_crying_face:")
|
miniconda3/lib/python3.13/site-packages/rich/protocol.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Any, cast, Set, TYPE_CHECKING
|
| 2 |
+
from inspect import isclass
|
| 3 |
+
|
| 4 |
+
if TYPE_CHECKING:
|
| 5 |
+
from rich.console import RenderableType
|
| 6 |
+
|
| 7 |
+
_GIBBERISH = """aihwerij235234ljsdnp34ksodfipwoe234234jlskjdf"""
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def is_renderable(check_object: Any) -> bool:
|
| 11 |
+
"""Check if an object may be rendered by Rich."""
|
| 12 |
+
return (
|
| 13 |
+
isinstance(check_object, str)
|
| 14 |
+
or hasattr(check_object, "__rich__")
|
| 15 |
+
or hasattr(check_object, "__rich_console__")
|
| 16 |
+
)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def rich_cast(renderable: object) -> "RenderableType":
|
| 20 |
+
"""Cast an object to a renderable by calling __rich__ if present.
|
| 21 |
+
|
| 22 |
+
Args:
|
| 23 |
+
renderable (object): A potentially renderable object
|
| 24 |
+
|
| 25 |
+
Returns:
|
| 26 |
+
object: The result of recursively calling __rich__.
|
| 27 |
+
"""
|
| 28 |
+
from rich.console import RenderableType
|
| 29 |
+
|
| 30 |
+
rich_visited_set: Set[type] = set() # Prevent potential infinite loop
|
| 31 |
+
while hasattr(renderable, "__rich__") and not isclass(renderable):
|
| 32 |
+
# Detect object which claim to have all the attributes
|
| 33 |
+
if hasattr(renderable, _GIBBERISH):
|
| 34 |
+
return repr(renderable)
|
| 35 |
+
cast_method = getattr(renderable, "__rich__")
|
| 36 |
+
renderable = cast_method()
|
| 37 |
+
renderable_type = type(renderable)
|
| 38 |
+
if renderable_type in rich_visited_set:
|
| 39 |
+
break
|
| 40 |
+
rich_visited_set.add(renderable_type)
|
| 41 |
+
|
| 42 |
+
return cast(RenderableType, renderable)
|
miniconda3/lib/python3.13/site-packages/rich/py.typed
ADDED
|
File without changes
|
miniconda3/lib/python3.13/site-packages/rich/region.py
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import NamedTuple
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
class Region(NamedTuple):
|
| 5 |
+
"""Defines a rectangular region of the screen."""
|
| 6 |
+
|
| 7 |
+
x: int
|
| 8 |
+
y: int
|
| 9 |
+
width: int
|
| 10 |
+
height: int
|
miniconda3/lib/python3.13/site-packages/rich/repr.py
ADDED
|
@@ -0,0 +1,149 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import inspect
|
| 2 |
+
from functools import partial
|
| 3 |
+
from typing import (
|
| 4 |
+
Any,
|
| 5 |
+
Callable,
|
| 6 |
+
Iterable,
|
| 7 |
+
List,
|
| 8 |
+
Optional,
|
| 9 |
+
Tuple,
|
| 10 |
+
Type,
|
| 11 |
+
TypeVar,
|
| 12 |
+
Union,
|
| 13 |
+
overload,
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
T = TypeVar("T")
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
Result = Iterable[Union[Any, Tuple[Any], Tuple[str, Any], Tuple[str, Any, Any]]]
|
| 20 |
+
RichReprResult = Result
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class ReprError(Exception):
|
| 24 |
+
"""An error occurred when attempting to build a repr."""
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
@overload
|
| 28 |
+
def auto(cls: Optional[Type[T]]) -> Type[T]:
|
| 29 |
+
...
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
@overload
|
| 33 |
+
def auto(*, angular: bool = False) -> Callable[[Type[T]], Type[T]]:
|
| 34 |
+
...
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def auto(
|
| 38 |
+
cls: Optional[Type[T]] = None, *, angular: Optional[bool] = None
|
| 39 |
+
) -> Union[Type[T], Callable[[Type[T]], Type[T]]]:
|
| 40 |
+
"""Class decorator to create __repr__ from __rich_repr__"""
|
| 41 |
+
|
| 42 |
+
def do_replace(cls: Type[T], angular: Optional[bool] = None) -> Type[T]:
|
| 43 |
+
def auto_repr(self: T) -> str:
|
| 44 |
+
"""Create repr string from __rich_repr__"""
|
| 45 |
+
repr_str: List[str] = []
|
| 46 |
+
append = repr_str.append
|
| 47 |
+
|
| 48 |
+
angular: bool = getattr(self.__rich_repr__, "angular", False) # type: ignore[attr-defined]
|
| 49 |
+
for arg in self.__rich_repr__(): # type: ignore[attr-defined]
|
| 50 |
+
if isinstance(arg, tuple):
|
| 51 |
+
if len(arg) == 1:
|
| 52 |
+
append(repr(arg[0]))
|
| 53 |
+
else:
|
| 54 |
+
key, value, *default = arg
|
| 55 |
+
if key is None:
|
| 56 |
+
append(repr(value))
|
| 57 |
+
else:
|
| 58 |
+
if default and default[0] == value:
|
| 59 |
+
continue
|
| 60 |
+
append(f"{key}={value!r}")
|
| 61 |
+
else:
|
| 62 |
+
append(repr(arg))
|
| 63 |
+
if angular:
|
| 64 |
+
return f"<{self.__class__.__name__} {' '.join(repr_str)}>"
|
| 65 |
+
else:
|
| 66 |
+
return f"{self.__class__.__name__}({', '.join(repr_str)})"
|
| 67 |
+
|
| 68 |
+
def auto_rich_repr(self: Type[T]) -> Result:
|
| 69 |
+
"""Auto generate __rich_rep__ from signature of __init__"""
|
| 70 |
+
try:
|
| 71 |
+
signature = inspect.signature(self.__init__)
|
| 72 |
+
for name, param in signature.parameters.items():
|
| 73 |
+
if param.kind == param.POSITIONAL_ONLY:
|
| 74 |
+
yield getattr(self, name)
|
| 75 |
+
elif param.kind in (
|
| 76 |
+
param.POSITIONAL_OR_KEYWORD,
|
| 77 |
+
param.KEYWORD_ONLY,
|
| 78 |
+
):
|
| 79 |
+
if param.default is param.empty:
|
| 80 |
+
yield getattr(self, param.name)
|
| 81 |
+
else:
|
| 82 |
+
yield param.name, getattr(self, param.name), param.default
|
| 83 |
+
except Exception as error:
|
| 84 |
+
raise ReprError(
|
| 85 |
+
f"Failed to auto generate __rich_repr__; {error}"
|
| 86 |
+
) from None
|
| 87 |
+
|
| 88 |
+
if not hasattr(cls, "__rich_repr__"):
|
| 89 |
+
auto_rich_repr.__doc__ = "Build a rich repr"
|
| 90 |
+
cls.__rich_repr__ = auto_rich_repr # type: ignore[attr-defined]
|
| 91 |
+
|
| 92 |
+
auto_repr.__doc__ = "Return repr(self)"
|
| 93 |
+
cls.__repr__ = auto_repr # type: ignore[assignment]
|
| 94 |
+
if angular is not None:
|
| 95 |
+
cls.__rich_repr__.angular = angular # type: ignore[attr-defined]
|
| 96 |
+
return cls
|
| 97 |
+
|
| 98 |
+
if cls is None:
|
| 99 |
+
return partial(do_replace, angular=angular)
|
| 100 |
+
else:
|
| 101 |
+
return do_replace(cls, angular=angular)
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
@overload
|
| 105 |
+
def rich_repr(cls: Optional[Type[T]]) -> Type[T]:
|
| 106 |
+
...
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
@overload
|
| 110 |
+
def rich_repr(*, angular: bool = False) -> Callable[[Type[T]], Type[T]]:
|
| 111 |
+
...
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def rich_repr(
|
| 115 |
+
cls: Optional[Type[T]] = None, *, angular: bool = False
|
| 116 |
+
) -> Union[Type[T], Callable[[Type[T]], Type[T]]]:
|
| 117 |
+
if cls is None:
|
| 118 |
+
return auto(angular=angular)
|
| 119 |
+
else:
|
| 120 |
+
return auto(cls)
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
if __name__ == "__main__":
|
| 124 |
+
|
| 125 |
+
@auto
|
| 126 |
+
class Foo:
|
| 127 |
+
def __rich_repr__(self) -> Result:
|
| 128 |
+
yield "foo"
|
| 129 |
+
yield "bar", {"shopping": ["eggs", "ham", "pineapple"]}
|
| 130 |
+
yield "buy", "hand sanitizer"
|
| 131 |
+
|
| 132 |
+
foo = Foo()
|
| 133 |
+
from rich.console import Console
|
| 134 |
+
|
| 135 |
+
console = Console()
|
| 136 |
+
|
| 137 |
+
console.rule("Standard repr")
|
| 138 |
+
console.print(foo)
|
| 139 |
+
|
| 140 |
+
console.print(foo, width=60)
|
| 141 |
+
console.print(foo, width=30)
|
| 142 |
+
|
| 143 |
+
console.rule("Angular repr")
|
| 144 |
+
Foo.__rich_repr__.angular = True # type: ignore[attr-defined]
|
| 145 |
+
|
| 146 |
+
console.print(foo)
|
| 147 |
+
|
| 148 |
+
console.print(foo, width=60)
|
| 149 |
+
console.print(foo, width=30)
|
miniconda3/lib/python3.13/site-packages/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 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)
|
miniconda3/lib/python3.13/site-packages/rich/scope.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from collections.abc import Mapping
|
| 2 |
+
from typing import TYPE_CHECKING, Any, Optional, Tuple
|
| 3 |
+
|
| 4 |
+
from .highlighter import ReprHighlighter
|
| 5 |
+
from .panel import Panel
|
| 6 |
+
from .pretty import Pretty
|
| 7 |
+
from .table import Table
|
| 8 |
+
from .text import Text, TextType
|
| 9 |
+
|
| 10 |
+
if TYPE_CHECKING:
|
| 11 |
+
from .console import ConsoleRenderable
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def render_scope(
|
| 15 |
+
scope: "Mapping[str, Any]",
|
| 16 |
+
*,
|
| 17 |
+
title: Optional[TextType] = None,
|
| 18 |
+
sort_keys: bool = True,
|
| 19 |
+
indent_guides: bool = False,
|
| 20 |
+
max_length: Optional[int] = None,
|
| 21 |
+
max_string: Optional[int] = None,
|
| 22 |
+
) -> "ConsoleRenderable":
|
| 23 |
+
"""Render python variables in a given scope.
|
| 24 |
+
|
| 25 |
+
Args:
|
| 26 |
+
scope (Mapping): A mapping containing variable names and values.
|
| 27 |
+
title (str, optional): Optional title. Defaults to None.
|
| 28 |
+
sort_keys (bool, optional): Enable sorting of items. Defaults to True.
|
| 29 |
+
indent_guides (bool, optional): Enable indentation guides. Defaults to False.
|
| 30 |
+
max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation.
|
| 31 |
+
Defaults to None.
|
| 32 |
+
max_string (int, optional): Maximum length of string before truncating, or None to disable. Defaults to None.
|
| 33 |
+
|
| 34 |
+
Returns:
|
| 35 |
+
ConsoleRenderable: A renderable object.
|
| 36 |
+
"""
|
| 37 |
+
highlighter = ReprHighlighter()
|
| 38 |
+
items_table = Table.grid(padding=(0, 1), expand=False)
|
| 39 |
+
items_table.add_column(justify="right")
|
| 40 |
+
|
| 41 |
+
def sort_items(item: Tuple[str, Any]) -> Tuple[bool, str]:
|
| 42 |
+
"""Sort special variables first, then alphabetically."""
|
| 43 |
+
key, _ = item
|
| 44 |
+
return (not key.startswith("__"), key.lower())
|
| 45 |
+
|
| 46 |
+
items = sorted(scope.items(), key=sort_items) if sort_keys else scope.items()
|
| 47 |
+
for key, value in items:
|
| 48 |
+
key_text = Text.assemble(
|
| 49 |
+
(key, "scope.key.special" if key.startswith("__") else "scope.key"),
|
| 50 |
+
(" =", "scope.equals"),
|
| 51 |
+
)
|
| 52 |
+
items_table.add_row(
|
| 53 |
+
key_text,
|
| 54 |
+
Pretty(
|
| 55 |
+
value,
|
| 56 |
+
highlighter=highlighter,
|
| 57 |
+
indent_guides=indent_guides,
|
| 58 |
+
max_length=max_length,
|
| 59 |
+
max_string=max_string,
|
| 60 |
+
),
|
| 61 |
+
)
|
| 62 |
+
return Panel.fit(
|
| 63 |
+
items_table,
|
| 64 |
+
title=title,
|
| 65 |
+
border_style="scope.border",
|
| 66 |
+
padding=(0, 1),
|
| 67 |
+
)
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
if __name__ == "__main__": # pragma: no cover
|
| 71 |
+
from rich import print
|
| 72 |
+
|
| 73 |
+
print()
|
| 74 |
+
|
| 75 |
+
def test(foo: float, bar: float) -> None:
|
| 76 |
+
list_of_things = [1, 2, 3, None, 4, True, False, "Hello World"]
|
| 77 |
+
dict_of_things = {
|
| 78 |
+
"version": "1.1",
|
| 79 |
+
"method": "confirmFruitPurchase",
|
| 80 |
+
"params": [["apple", "orange", "mangoes", "pomelo"], 1.123],
|
| 81 |
+
"id": "194521489",
|
| 82 |
+
}
|
| 83 |
+
print(render_scope(locals(), title="[i]locals", sort_keys=False))
|
| 84 |
+
|
| 85 |
+
test(20.3423, 3.1427)
|
| 86 |
+
print()
|
miniconda3/lib/python3.13/site-packages/rich/screen.py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Optional, TYPE_CHECKING
|
| 2 |
+
|
| 3 |
+
from .segment import Segment
|
| 4 |
+
from .style import StyleType
|
| 5 |
+
from ._loop import loop_last
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
if TYPE_CHECKING:
|
| 9 |
+
from .console import (
|
| 10 |
+
Console,
|
| 11 |
+
ConsoleOptions,
|
| 12 |
+
RenderResult,
|
| 13 |
+
RenderableType,
|
| 14 |
+
Group,
|
| 15 |
+
)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class Screen:
|
| 19 |
+
"""A renderable that fills the terminal screen and crops excess.
|
| 20 |
+
|
| 21 |
+
Args:
|
| 22 |
+
renderable (RenderableType): Child renderable.
|
| 23 |
+
style (StyleType, optional): Optional background style. Defaults to None.
|
| 24 |
+
"""
|
| 25 |
+
|
| 26 |
+
renderable: "RenderableType"
|
| 27 |
+
|
| 28 |
+
def __init__(
|
| 29 |
+
self,
|
| 30 |
+
*renderables: "RenderableType",
|
| 31 |
+
style: Optional[StyleType] = None,
|
| 32 |
+
application_mode: bool = False,
|
| 33 |
+
) -> None:
|
| 34 |
+
from rich.console import Group
|
| 35 |
+
|
| 36 |
+
self.renderable = Group(*renderables)
|
| 37 |
+
self.style = style
|
| 38 |
+
self.application_mode = application_mode
|
| 39 |
+
|
| 40 |
+
def __rich_console__(
|
| 41 |
+
self, console: "Console", options: "ConsoleOptions"
|
| 42 |
+
) -> "RenderResult":
|
| 43 |
+
width, height = options.size
|
| 44 |
+
style = console.get_style(self.style) if self.style else None
|
| 45 |
+
render_options = options.update(width=width, height=height)
|
| 46 |
+
lines = console.render_lines(
|
| 47 |
+
self.renderable or "", render_options, style=style, pad=True
|
| 48 |
+
)
|
| 49 |
+
lines = Segment.set_shape(lines, width, height, style=style)
|
| 50 |
+
new_line = Segment("\n\r") if self.application_mode else Segment.line()
|
| 51 |
+
for last, line in loop_last(lines):
|
| 52 |
+
yield from line
|
| 53 |
+
if not last:
|
| 54 |
+
yield new_line
|
miniconda3/lib/python3.13/site-packages/rich/segment.py
ADDED
|
@@ -0,0 +1,752 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from enum import IntEnum
|
| 2 |
+
from functools import lru_cache
|
| 3 |
+
from itertools import filterfalse
|
| 4 |
+
from logging import getLogger
|
| 5 |
+
from operator import attrgetter
|
| 6 |
+
from typing import (
|
| 7 |
+
TYPE_CHECKING,
|
| 8 |
+
Dict,
|
| 9 |
+
Iterable,
|
| 10 |
+
List,
|
| 11 |
+
NamedTuple,
|
| 12 |
+
Optional,
|
| 13 |
+
Sequence,
|
| 14 |
+
Tuple,
|
| 15 |
+
Type,
|
| 16 |
+
Union,
|
| 17 |
+
)
|
| 18 |
+
|
| 19 |
+
from .cells import (
|
| 20 |
+
_is_single_cell_widths,
|
| 21 |
+
cached_cell_len,
|
| 22 |
+
cell_len,
|
| 23 |
+
get_character_cell_size,
|
| 24 |
+
set_cell_size,
|
| 25 |
+
)
|
| 26 |
+
from .repr import Result, rich_repr
|
| 27 |
+
from .style import Style
|
| 28 |
+
|
| 29 |
+
if TYPE_CHECKING:
|
| 30 |
+
from .console import Console, ConsoleOptions, RenderResult
|
| 31 |
+
|
| 32 |
+
log = getLogger("rich")
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class ControlType(IntEnum):
|
| 36 |
+
"""Non-printable control codes which typically translate to ANSI codes."""
|
| 37 |
+
|
| 38 |
+
BELL = 1
|
| 39 |
+
CARRIAGE_RETURN = 2
|
| 40 |
+
HOME = 3
|
| 41 |
+
CLEAR = 4
|
| 42 |
+
SHOW_CURSOR = 5
|
| 43 |
+
HIDE_CURSOR = 6
|
| 44 |
+
ENABLE_ALT_SCREEN = 7
|
| 45 |
+
DISABLE_ALT_SCREEN = 8
|
| 46 |
+
CURSOR_UP = 9
|
| 47 |
+
CURSOR_DOWN = 10
|
| 48 |
+
CURSOR_FORWARD = 11
|
| 49 |
+
CURSOR_BACKWARD = 12
|
| 50 |
+
CURSOR_MOVE_TO_COLUMN = 13
|
| 51 |
+
CURSOR_MOVE_TO = 14
|
| 52 |
+
ERASE_IN_LINE = 15
|
| 53 |
+
SET_WINDOW_TITLE = 16
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
ControlCode = Union[
|
| 57 |
+
Tuple[ControlType],
|
| 58 |
+
Tuple[ControlType, Union[int, str]],
|
| 59 |
+
Tuple[ControlType, int, int],
|
| 60 |
+
]
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
@rich_repr()
|
| 64 |
+
class Segment(NamedTuple):
|
| 65 |
+
"""A piece of text with associated style. Segments are produced by the Console render process and
|
| 66 |
+
are ultimately converted in to strings to be written to the terminal.
|
| 67 |
+
|
| 68 |
+
Args:
|
| 69 |
+
text (str): A piece of text.
|
| 70 |
+
style (:class:`~rich.style.Style`, optional): An optional style to apply to the text.
|
| 71 |
+
control (Tuple[ControlCode], optional): Optional sequence of control codes.
|
| 72 |
+
|
| 73 |
+
Attributes:
|
| 74 |
+
cell_length (int): The cell length of this Segment.
|
| 75 |
+
"""
|
| 76 |
+
|
| 77 |
+
text: str
|
| 78 |
+
style: Optional[Style] = None
|
| 79 |
+
control: Optional[Sequence[ControlCode]] = None
|
| 80 |
+
|
| 81 |
+
@property
|
| 82 |
+
def cell_length(self) -> int:
|
| 83 |
+
"""The number of terminal cells required to display self.text.
|
| 84 |
+
|
| 85 |
+
Returns:
|
| 86 |
+
int: A number of cells.
|
| 87 |
+
"""
|
| 88 |
+
text, _style, control = self
|
| 89 |
+
return 0 if control else cell_len(text)
|
| 90 |
+
|
| 91 |
+
def __rich_repr__(self) -> Result:
|
| 92 |
+
yield self.text
|
| 93 |
+
if self.control is None:
|
| 94 |
+
if self.style is not None:
|
| 95 |
+
yield self.style
|
| 96 |
+
else:
|
| 97 |
+
yield self.style
|
| 98 |
+
yield self.control
|
| 99 |
+
|
| 100 |
+
def __bool__(self) -> bool:
|
| 101 |
+
"""Check if the segment contains text."""
|
| 102 |
+
return bool(self.text)
|
| 103 |
+
|
| 104 |
+
@property
|
| 105 |
+
def is_control(self) -> bool:
|
| 106 |
+
"""Check if the segment contains control codes."""
|
| 107 |
+
return self.control is not None
|
| 108 |
+
|
| 109 |
+
@classmethod
|
| 110 |
+
@lru_cache(1024 * 16)
|
| 111 |
+
def _split_cells(cls, segment: "Segment", cut: int) -> Tuple["Segment", "Segment"]:
|
| 112 |
+
"""Split a segment in to two at a given cell position.
|
| 113 |
+
|
| 114 |
+
Note that splitting a double-width character, may result in that character turning
|
| 115 |
+
into two spaces.
|
| 116 |
+
|
| 117 |
+
Args:
|
| 118 |
+
segment (Segment): A segment to split.
|
| 119 |
+
cut (int): A cell position to cut on.
|
| 120 |
+
|
| 121 |
+
Returns:
|
| 122 |
+
A tuple of two segments.
|
| 123 |
+
"""
|
| 124 |
+
text, style, control = segment
|
| 125 |
+
_Segment = Segment
|
| 126 |
+
cell_length = segment.cell_length
|
| 127 |
+
if cut >= cell_length:
|
| 128 |
+
return segment, _Segment("", style, control)
|
| 129 |
+
|
| 130 |
+
cell_size = get_character_cell_size
|
| 131 |
+
|
| 132 |
+
pos = int((cut / cell_length) * len(text))
|
| 133 |
+
|
| 134 |
+
while True:
|
| 135 |
+
before = text[:pos]
|
| 136 |
+
cell_pos = cell_len(before)
|
| 137 |
+
out_by = cell_pos - cut
|
| 138 |
+
if not out_by:
|
| 139 |
+
return (
|
| 140 |
+
_Segment(before, style, control),
|
| 141 |
+
_Segment(text[pos:], style, control),
|
| 142 |
+
)
|
| 143 |
+
if out_by == -1 and cell_size(text[pos]) == 2:
|
| 144 |
+
return (
|
| 145 |
+
_Segment(text[:pos] + " ", style, control),
|
| 146 |
+
_Segment(" " + text[pos + 1 :], style, control),
|
| 147 |
+
)
|
| 148 |
+
if out_by == +1 and cell_size(text[pos - 1]) == 2:
|
| 149 |
+
return (
|
| 150 |
+
_Segment(text[: pos - 1] + " ", style, control),
|
| 151 |
+
_Segment(" " + text[pos:], style, control),
|
| 152 |
+
)
|
| 153 |
+
if cell_pos < cut:
|
| 154 |
+
pos += 1
|
| 155 |
+
else:
|
| 156 |
+
pos -= 1
|
| 157 |
+
|
| 158 |
+
def split_cells(self, cut: int) -> Tuple["Segment", "Segment"]:
|
| 159 |
+
"""Split segment in to two segments at the specified column.
|
| 160 |
+
|
| 161 |
+
If the cut point falls in the middle of a 2-cell wide character then it is replaced
|
| 162 |
+
by two spaces, to preserve the display width of the parent segment.
|
| 163 |
+
|
| 164 |
+
Args:
|
| 165 |
+
cut (int): Offset within the segment to cut.
|
| 166 |
+
|
| 167 |
+
Returns:
|
| 168 |
+
Tuple[Segment, Segment]: Two segments.
|
| 169 |
+
"""
|
| 170 |
+
text, style, control = self
|
| 171 |
+
assert cut >= 0
|
| 172 |
+
|
| 173 |
+
if _is_single_cell_widths(text):
|
| 174 |
+
# Fast path with all 1 cell characters
|
| 175 |
+
if cut >= len(text):
|
| 176 |
+
return self, Segment("", style, control)
|
| 177 |
+
return (
|
| 178 |
+
Segment(text[:cut], style, control),
|
| 179 |
+
Segment(text[cut:], style, control),
|
| 180 |
+
)
|
| 181 |
+
|
| 182 |
+
return self._split_cells(self, cut)
|
| 183 |
+
|
| 184 |
+
@classmethod
|
| 185 |
+
def line(cls) -> "Segment":
|
| 186 |
+
"""Make a new line segment."""
|
| 187 |
+
return cls("\n")
|
| 188 |
+
|
| 189 |
+
@classmethod
|
| 190 |
+
def apply_style(
|
| 191 |
+
cls,
|
| 192 |
+
segments: Iterable["Segment"],
|
| 193 |
+
style: Optional[Style] = None,
|
| 194 |
+
post_style: Optional[Style] = None,
|
| 195 |
+
) -> Iterable["Segment"]:
|
| 196 |
+
"""Apply style(s) to an iterable of segments.
|
| 197 |
+
|
| 198 |
+
Returns an iterable of segments where the style is replaced by ``style + segment.style + post_style``.
|
| 199 |
+
|
| 200 |
+
Args:
|
| 201 |
+
segments (Iterable[Segment]): Segments to process.
|
| 202 |
+
style (Style, optional): Base style. Defaults to None.
|
| 203 |
+
post_style (Style, optional): Style to apply on top of segment style. Defaults to None.
|
| 204 |
+
|
| 205 |
+
Returns:
|
| 206 |
+
Iterable[Segments]: A new iterable of segments (possibly the same iterable).
|
| 207 |
+
"""
|
| 208 |
+
result_segments = segments
|
| 209 |
+
if style:
|
| 210 |
+
apply = style.__add__
|
| 211 |
+
result_segments = (
|
| 212 |
+
cls(text, None if control else apply(_style), control)
|
| 213 |
+
for text, _style, control in result_segments
|
| 214 |
+
)
|
| 215 |
+
if post_style:
|
| 216 |
+
result_segments = (
|
| 217 |
+
cls(
|
| 218 |
+
text,
|
| 219 |
+
(
|
| 220 |
+
None
|
| 221 |
+
if control
|
| 222 |
+
else (_style + post_style if _style else post_style)
|
| 223 |
+
),
|
| 224 |
+
control,
|
| 225 |
+
)
|
| 226 |
+
for text, _style, control in result_segments
|
| 227 |
+
)
|
| 228 |
+
return result_segments
|
| 229 |
+
|
| 230 |
+
@classmethod
|
| 231 |
+
def filter_control(
|
| 232 |
+
cls, segments: Iterable["Segment"], is_control: bool = False
|
| 233 |
+
) -> Iterable["Segment"]:
|
| 234 |
+
"""Filter segments by ``is_control`` attribute.
|
| 235 |
+
|
| 236 |
+
Args:
|
| 237 |
+
segments (Iterable[Segment]): An iterable of Segment instances.
|
| 238 |
+
is_control (bool, optional): is_control flag to match in search.
|
| 239 |
+
|
| 240 |
+
Returns:
|
| 241 |
+
Iterable[Segment]: And iterable of Segment instances.
|
| 242 |
+
|
| 243 |
+
"""
|
| 244 |
+
if is_control:
|
| 245 |
+
return filter(attrgetter("control"), segments)
|
| 246 |
+
else:
|
| 247 |
+
return filterfalse(attrgetter("control"), segments)
|
| 248 |
+
|
| 249 |
+
@classmethod
|
| 250 |
+
def split_lines(cls, segments: Iterable["Segment"]) -> Iterable[List["Segment"]]:
|
| 251 |
+
"""Split a sequence of segments in to a list of lines.
|
| 252 |
+
|
| 253 |
+
Args:
|
| 254 |
+
segments (Iterable[Segment]): Segments potentially containing line feeds.
|
| 255 |
+
|
| 256 |
+
Yields:
|
| 257 |
+
Iterable[List[Segment]]: Iterable of segment lists, one per line.
|
| 258 |
+
"""
|
| 259 |
+
line: List[Segment] = []
|
| 260 |
+
append = line.append
|
| 261 |
+
|
| 262 |
+
for segment in segments:
|
| 263 |
+
if "\n" in segment.text and not segment.control:
|
| 264 |
+
text, style, _ = segment
|
| 265 |
+
while text:
|
| 266 |
+
_text, new_line, text = text.partition("\n")
|
| 267 |
+
if _text:
|
| 268 |
+
append(cls(_text, style))
|
| 269 |
+
if new_line:
|
| 270 |
+
yield line
|
| 271 |
+
line = []
|
| 272 |
+
append = line.append
|
| 273 |
+
else:
|
| 274 |
+
append(segment)
|
| 275 |
+
if line:
|
| 276 |
+
yield line
|
| 277 |
+
|
| 278 |
+
@classmethod
|
| 279 |
+
def split_and_crop_lines(
|
| 280 |
+
cls,
|
| 281 |
+
segments: Iterable["Segment"],
|
| 282 |
+
length: int,
|
| 283 |
+
style: Optional[Style] = None,
|
| 284 |
+
pad: bool = True,
|
| 285 |
+
include_new_lines: bool = True,
|
| 286 |
+
) -> Iterable[List["Segment"]]:
|
| 287 |
+
"""Split segments in to lines, and crop lines greater than a given length.
|
| 288 |
+
|
| 289 |
+
Args:
|
| 290 |
+
segments (Iterable[Segment]): An iterable of segments, probably
|
| 291 |
+
generated from console.render.
|
| 292 |
+
length (int): Desired line length.
|
| 293 |
+
style (Style, optional): Style to use for any padding.
|
| 294 |
+
pad (bool): Enable padding of lines that are less than `length`.
|
| 295 |
+
|
| 296 |
+
Returns:
|
| 297 |
+
Iterable[List[Segment]]: An iterable of lines of segments.
|
| 298 |
+
"""
|
| 299 |
+
line: List[Segment] = []
|
| 300 |
+
append = line.append
|
| 301 |
+
|
| 302 |
+
adjust_line_length = cls.adjust_line_length
|
| 303 |
+
new_line_segment = cls("\n")
|
| 304 |
+
|
| 305 |
+
for segment in segments:
|
| 306 |
+
if "\n" in segment.text and not segment.control:
|
| 307 |
+
text, segment_style, _ = segment
|
| 308 |
+
while text:
|
| 309 |
+
_text, new_line, text = text.partition("\n")
|
| 310 |
+
if _text:
|
| 311 |
+
append(cls(_text, segment_style))
|
| 312 |
+
if new_line:
|
| 313 |
+
cropped_line = adjust_line_length(
|
| 314 |
+
line, length, style=style, pad=pad
|
| 315 |
+
)
|
| 316 |
+
if include_new_lines:
|
| 317 |
+
cropped_line.append(new_line_segment)
|
| 318 |
+
yield cropped_line
|
| 319 |
+
line.clear()
|
| 320 |
+
else:
|
| 321 |
+
append(segment)
|
| 322 |
+
if line:
|
| 323 |
+
yield adjust_line_length(line, length, style=style, pad=pad)
|
| 324 |
+
|
| 325 |
+
@classmethod
|
| 326 |
+
def adjust_line_length(
|
| 327 |
+
cls,
|
| 328 |
+
line: List["Segment"],
|
| 329 |
+
length: int,
|
| 330 |
+
style: Optional[Style] = None,
|
| 331 |
+
pad: bool = True,
|
| 332 |
+
) -> List["Segment"]:
|
| 333 |
+
"""Adjust a line to a given width (cropping or padding as required).
|
| 334 |
+
|
| 335 |
+
Args:
|
| 336 |
+
segments (Iterable[Segment]): A list of segments in a single line.
|
| 337 |
+
length (int): The desired width of the line.
|
| 338 |
+
style (Style, optional): The style of padding if used (space on the end). Defaults to None.
|
| 339 |
+
pad (bool, optional): Pad lines with spaces if they are shorter than `length`. Defaults to True.
|
| 340 |
+
|
| 341 |
+
Returns:
|
| 342 |
+
List[Segment]: A line of segments with the desired length.
|
| 343 |
+
"""
|
| 344 |
+
line_length = sum(segment.cell_length for segment in line)
|
| 345 |
+
new_line: List[Segment]
|
| 346 |
+
|
| 347 |
+
if line_length < length:
|
| 348 |
+
if pad:
|
| 349 |
+
new_line = line + [cls(" " * (length - line_length), style)]
|
| 350 |
+
else:
|
| 351 |
+
new_line = line[:]
|
| 352 |
+
elif line_length > length:
|
| 353 |
+
new_line = []
|
| 354 |
+
append = new_line.append
|
| 355 |
+
line_length = 0
|
| 356 |
+
for segment in line:
|
| 357 |
+
segment_length = segment.cell_length
|
| 358 |
+
if line_length + segment_length < length or segment.control:
|
| 359 |
+
append(segment)
|
| 360 |
+
line_length += segment_length
|
| 361 |
+
else:
|
| 362 |
+
text, segment_style, _ = segment
|
| 363 |
+
text = set_cell_size(text, length - line_length)
|
| 364 |
+
append(cls(text, segment_style))
|
| 365 |
+
break
|
| 366 |
+
else:
|
| 367 |
+
new_line = line[:]
|
| 368 |
+
return new_line
|
| 369 |
+
|
| 370 |
+
@classmethod
|
| 371 |
+
def get_line_length(cls, line: List["Segment"]) -> int:
|
| 372 |
+
"""Get the length of list of segments.
|
| 373 |
+
|
| 374 |
+
Args:
|
| 375 |
+
line (List[Segment]): A line encoded as a list of Segments (assumes no '\\\\n' characters),
|
| 376 |
+
|
| 377 |
+
Returns:
|
| 378 |
+
int: The length of the line.
|
| 379 |
+
"""
|
| 380 |
+
_cell_len = cell_len
|
| 381 |
+
return sum(_cell_len(text) for text, style, control in line if not control)
|
| 382 |
+
|
| 383 |
+
@classmethod
|
| 384 |
+
def get_shape(cls, lines: List[List["Segment"]]) -> Tuple[int, int]:
|
| 385 |
+
"""Get the shape (enclosing rectangle) of a list of lines.
|
| 386 |
+
|
| 387 |
+
Args:
|
| 388 |
+
lines (List[List[Segment]]): A list of lines (no '\\\\n' characters).
|
| 389 |
+
|
| 390 |
+
Returns:
|
| 391 |
+
Tuple[int, int]: Width and height in characters.
|
| 392 |
+
"""
|
| 393 |
+
get_line_length = cls.get_line_length
|
| 394 |
+
max_width = max(get_line_length(line) for line in lines) if lines else 0
|
| 395 |
+
return (max_width, len(lines))
|
| 396 |
+
|
| 397 |
+
@classmethod
|
| 398 |
+
def set_shape(
|
| 399 |
+
cls,
|
| 400 |
+
lines: List[List["Segment"]],
|
| 401 |
+
width: int,
|
| 402 |
+
height: Optional[int] = None,
|
| 403 |
+
style: Optional[Style] = None,
|
| 404 |
+
new_lines: bool = False,
|
| 405 |
+
) -> List[List["Segment"]]:
|
| 406 |
+
"""Set the shape of a list of lines (enclosing rectangle).
|
| 407 |
+
|
| 408 |
+
Args:
|
| 409 |
+
lines (List[List[Segment]]): A list of lines.
|
| 410 |
+
width (int): Desired width.
|
| 411 |
+
height (int, optional): Desired height or None for no change.
|
| 412 |
+
style (Style, optional): Style of any padding added.
|
| 413 |
+
new_lines (bool, optional): Padded lines should include "\n". Defaults to False.
|
| 414 |
+
|
| 415 |
+
Returns:
|
| 416 |
+
List[List[Segment]]: New list of lines.
|
| 417 |
+
"""
|
| 418 |
+
_height = height or len(lines)
|
| 419 |
+
|
| 420 |
+
blank = (
|
| 421 |
+
[cls(" " * width + "\n", style)] if new_lines else [cls(" " * width, style)]
|
| 422 |
+
)
|
| 423 |
+
|
| 424 |
+
adjust_line_length = cls.adjust_line_length
|
| 425 |
+
shaped_lines = lines[:_height]
|
| 426 |
+
shaped_lines[:] = [
|
| 427 |
+
adjust_line_length(line, width, style=style) for line in lines
|
| 428 |
+
]
|
| 429 |
+
if len(shaped_lines) < _height:
|
| 430 |
+
shaped_lines.extend([blank] * (_height - len(shaped_lines)))
|
| 431 |
+
return shaped_lines
|
| 432 |
+
|
| 433 |
+
@classmethod
|
| 434 |
+
def align_top(
|
| 435 |
+
cls: Type["Segment"],
|
| 436 |
+
lines: List[List["Segment"]],
|
| 437 |
+
width: int,
|
| 438 |
+
height: int,
|
| 439 |
+
style: Style,
|
| 440 |
+
new_lines: bool = False,
|
| 441 |
+
) -> List[List["Segment"]]:
|
| 442 |
+
"""Aligns lines to top (adds extra lines to bottom as required).
|
| 443 |
+
|
| 444 |
+
Args:
|
| 445 |
+
lines (List[List[Segment]]): A list of lines.
|
| 446 |
+
width (int): Desired width.
|
| 447 |
+
height (int, optional): Desired height or None for no change.
|
| 448 |
+
style (Style): Style of any padding added.
|
| 449 |
+
new_lines (bool, optional): Padded lines should include "\n". Defaults to False.
|
| 450 |
+
|
| 451 |
+
Returns:
|
| 452 |
+
List[List[Segment]]: New list of lines.
|
| 453 |
+
"""
|
| 454 |
+
extra_lines = height - len(lines)
|
| 455 |
+
if not extra_lines:
|
| 456 |
+
return lines[:]
|
| 457 |
+
lines = lines[:height]
|
| 458 |
+
blank = cls(" " * width + "\n", style) if new_lines else cls(" " * width, style)
|
| 459 |
+
lines = lines + [[blank]] * extra_lines
|
| 460 |
+
return lines
|
| 461 |
+
|
| 462 |
+
@classmethod
|
| 463 |
+
def align_bottom(
|
| 464 |
+
cls: Type["Segment"],
|
| 465 |
+
lines: List[List["Segment"]],
|
| 466 |
+
width: int,
|
| 467 |
+
height: int,
|
| 468 |
+
style: Style,
|
| 469 |
+
new_lines: bool = False,
|
| 470 |
+
) -> List[List["Segment"]]:
|
| 471 |
+
"""Aligns render to bottom (adds extra lines above as required).
|
| 472 |
+
|
| 473 |
+
Args:
|
| 474 |
+
lines (List[List[Segment]]): A list of lines.
|
| 475 |
+
width (int): Desired width.
|
| 476 |
+
height (int, optional): Desired height or None for no change.
|
| 477 |
+
style (Style): Style of any padding added. Defaults to None.
|
| 478 |
+
new_lines (bool, optional): Padded lines should include "\n". Defaults to False.
|
| 479 |
+
|
| 480 |
+
Returns:
|
| 481 |
+
List[List[Segment]]: New list of lines.
|
| 482 |
+
"""
|
| 483 |
+
extra_lines = height - len(lines)
|
| 484 |
+
if not extra_lines:
|
| 485 |
+
return lines[:]
|
| 486 |
+
lines = lines[:height]
|
| 487 |
+
blank = cls(" " * width + "\n", style) if new_lines else cls(" " * width, style)
|
| 488 |
+
lines = [[blank]] * extra_lines + lines
|
| 489 |
+
return lines
|
| 490 |
+
|
| 491 |
+
@classmethod
|
| 492 |
+
def align_middle(
|
| 493 |
+
cls: Type["Segment"],
|
| 494 |
+
lines: List[List["Segment"]],
|
| 495 |
+
width: int,
|
| 496 |
+
height: int,
|
| 497 |
+
style: Style,
|
| 498 |
+
new_lines: bool = False,
|
| 499 |
+
) -> List[List["Segment"]]:
|
| 500 |
+
"""Aligns lines to middle (adds extra lines to above and below as required).
|
| 501 |
+
|
| 502 |
+
Args:
|
| 503 |
+
lines (List[List[Segment]]): A list of lines.
|
| 504 |
+
width (int): Desired width.
|
| 505 |
+
height (int, optional): Desired height or None for no change.
|
| 506 |
+
style (Style): Style of any padding added.
|
| 507 |
+
new_lines (bool, optional): Padded lines should include "\n". Defaults to False.
|
| 508 |
+
|
| 509 |
+
Returns:
|
| 510 |
+
List[List[Segment]]: New list of lines.
|
| 511 |
+
"""
|
| 512 |
+
extra_lines = height - len(lines)
|
| 513 |
+
if not extra_lines:
|
| 514 |
+
return lines[:]
|
| 515 |
+
lines = lines[:height]
|
| 516 |
+
blank = cls(" " * width + "\n", style) if new_lines else cls(" " * width, style)
|
| 517 |
+
top_lines = extra_lines // 2
|
| 518 |
+
bottom_lines = extra_lines - top_lines
|
| 519 |
+
lines = [[blank]] * top_lines + lines + [[blank]] * bottom_lines
|
| 520 |
+
return lines
|
| 521 |
+
|
| 522 |
+
@classmethod
|
| 523 |
+
def simplify(cls, segments: Iterable["Segment"]) -> Iterable["Segment"]:
|
| 524 |
+
"""Simplify an iterable of segments by combining contiguous segments with the same style.
|
| 525 |
+
|
| 526 |
+
Args:
|
| 527 |
+
segments (Iterable[Segment]): An iterable of segments.
|
| 528 |
+
|
| 529 |
+
Returns:
|
| 530 |
+
Iterable[Segment]: A possibly smaller iterable of segments that will render the same way.
|
| 531 |
+
"""
|
| 532 |
+
iter_segments = iter(segments)
|
| 533 |
+
try:
|
| 534 |
+
last_segment = next(iter_segments)
|
| 535 |
+
except StopIteration:
|
| 536 |
+
return
|
| 537 |
+
|
| 538 |
+
_Segment = Segment
|
| 539 |
+
for segment in iter_segments:
|
| 540 |
+
if last_segment.style == segment.style and not segment.control:
|
| 541 |
+
last_segment = _Segment(
|
| 542 |
+
last_segment.text + segment.text, last_segment.style
|
| 543 |
+
)
|
| 544 |
+
else:
|
| 545 |
+
yield last_segment
|
| 546 |
+
last_segment = segment
|
| 547 |
+
yield last_segment
|
| 548 |
+
|
| 549 |
+
@classmethod
|
| 550 |
+
def strip_links(cls, segments: Iterable["Segment"]) -> Iterable["Segment"]:
|
| 551 |
+
"""Remove all links from an iterable of styles.
|
| 552 |
+
|
| 553 |
+
Args:
|
| 554 |
+
segments (Iterable[Segment]): An iterable segments.
|
| 555 |
+
|
| 556 |
+
Yields:
|
| 557 |
+
Segment: Segments with link removed.
|
| 558 |
+
"""
|
| 559 |
+
for segment in segments:
|
| 560 |
+
if segment.control or segment.style is None:
|
| 561 |
+
yield segment
|
| 562 |
+
else:
|
| 563 |
+
text, style, _control = segment
|
| 564 |
+
yield cls(text, style.update_link(None) if style else None)
|
| 565 |
+
|
| 566 |
+
@classmethod
|
| 567 |
+
def strip_styles(cls, segments: Iterable["Segment"]) -> Iterable["Segment"]:
|
| 568 |
+
"""Remove all styles from an iterable of segments.
|
| 569 |
+
|
| 570 |
+
Args:
|
| 571 |
+
segments (Iterable[Segment]): An iterable segments.
|
| 572 |
+
|
| 573 |
+
Yields:
|
| 574 |
+
Segment: Segments with styles replace with None
|
| 575 |
+
"""
|
| 576 |
+
for text, _style, control in segments:
|
| 577 |
+
yield cls(text, None, control)
|
| 578 |
+
|
| 579 |
+
@classmethod
|
| 580 |
+
def remove_color(cls, segments: Iterable["Segment"]) -> Iterable["Segment"]:
|
| 581 |
+
"""Remove all color from an iterable of segments.
|
| 582 |
+
|
| 583 |
+
Args:
|
| 584 |
+
segments (Iterable[Segment]): An iterable segments.
|
| 585 |
+
|
| 586 |
+
Yields:
|
| 587 |
+
Segment: Segments with colorless style.
|
| 588 |
+
"""
|
| 589 |
+
|
| 590 |
+
cache: Dict[Style, Style] = {}
|
| 591 |
+
for text, style, control in segments:
|
| 592 |
+
if style:
|
| 593 |
+
colorless_style = cache.get(style)
|
| 594 |
+
if colorless_style is None:
|
| 595 |
+
colorless_style = style.without_color
|
| 596 |
+
cache[style] = colorless_style
|
| 597 |
+
yield cls(text, colorless_style, control)
|
| 598 |
+
else:
|
| 599 |
+
yield cls(text, None, control)
|
| 600 |
+
|
| 601 |
+
@classmethod
|
| 602 |
+
def divide(
|
| 603 |
+
cls, segments: Iterable["Segment"], cuts: Iterable[int]
|
| 604 |
+
) -> Iterable[List["Segment"]]:
|
| 605 |
+
"""Divides an iterable of segments in to portions.
|
| 606 |
+
|
| 607 |
+
Args:
|
| 608 |
+
cuts (Iterable[int]): Cell positions where to divide.
|
| 609 |
+
|
| 610 |
+
Yields:
|
| 611 |
+
[Iterable[List[Segment]]]: An iterable of Segments in List.
|
| 612 |
+
"""
|
| 613 |
+
split_segments: List["Segment"] = []
|
| 614 |
+
add_segment = split_segments.append
|
| 615 |
+
|
| 616 |
+
iter_cuts = iter(cuts)
|
| 617 |
+
|
| 618 |
+
while True:
|
| 619 |
+
cut = next(iter_cuts, -1)
|
| 620 |
+
if cut == -1:
|
| 621 |
+
return
|
| 622 |
+
if cut != 0:
|
| 623 |
+
break
|
| 624 |
+
yield []
|
| 625 |
+
pos = 0
|
| 626 |
+
|
| 627 |
+
segments_clear = split_segments.clear
|
| 628 |
+
segments_copy = split_segments.copy
|
| 629 |
+
|
| 630 |
+
_cell_len = cached_cell_len
|
| 631 |
+
for segment in segments:
|
| 632 |
+
text, _style, control = segment
|
| 633 |
+
while text:
|
| 634 |
+
end_pos = pos if control else pos + _cell_len(text)
|
| 635 |
+
if end_pos < cut:
|
| 636 |
+
add_segment(segment)
|
| 637 |
+
pos = end_pos
|
| 638 |
+
break
|
| 639 |
+
|
| 640 |
+
if end_pos == cut:
|
| 641 |
+
add_segment(segment)
|
| 642 |
+
yield segments_copy()
|
| 643 |
+
segments_clear()
|
| 644 |
+
pos = end_pos
|
| 645 |
+
|
| 646 |
+
cut = next(iter_cuts, -1)
|
| 647 |
+
if cut == -1:
|
| 648 |
+
if split_segments:
|
| 649 |
+
yield segments_copy()
|
| 650 |
+
return
|
| 651 |
+
|
| 652 |
+
break
|
| 653 |
+
|
| 654 |
+
else:
|
| 655 |
+
before, segment = segment.split_cells(cut - pos)
|
| 656 |
+
text, _style, control = segment
|
| 657 |
+
add_segment(before)
|
| 658 |
+
yield segments_copy()
|
| 659 |
+
segments_clear()
|
| 660 |
+
pos = cut
|
| 661 |
+
|
| 662 |
+
cut = next(iter_cuts, -1)
|
| 663 |
+
if cut == -1:
|
| 664 |
+
if split_segments:
|
| 665 |
+
yield segments_copy()
|
| 666 |
+
return
|
| 667 |
+
|
| 668 |
+
yield segments_copy()
|
| 669 |
+
|
| 670 |
+
|
| 671 |
+
class Segments:
|
| 672 |
+
"""A simple renderable to render an iterable of segments. This class may be useful if
|
| 673 |
+
you want to print segments outside of a __rich_console__ method.
|
| 674 |
+
|
| 675 |
+
Args:
|
| 676 |
+
segments (Iterable[Segment]): An iterable of segments.
|
| 677 |
+
new_lines (bool, optional): Add new lines between segments. Defaults to False.
|
| 678 |
+
"""
|
| 679 |
+
|
| 680 |
+
def __init__(self, segments: Iterable[Segment], new_lines: bool = False) -> None:
|
| 681 |
+
self.segments = list(segments)
|
| 682 |
+
self.new_lines = new_lines
|
| 683 |
+
|
| 684 |
+
def __rich_console__(
|
| 685 |
+
self, console: "Console", options: "ConsoleOptions"
|
| 686 |
+
) -> "RenderResult":
|
| 687 |
+
if self.new_lines:
|
| 688 |
+
line = Segment.line()
|
| 689 |
+
for segment in self.segments:
|
| 690 |
+
yield segment
|
| 691 |
+
yield line
|
| 692 |
+
else:
|
| 693 |
+
yield from self.segments
|
| 694 |
+
|
| 695 |
+
|
| 696 |
+
class SegmentLines:
|
| 697 |
+
def __init__(self, lines: Iterable[List[Segment]], new_lines: bool = False) -> None:
|
| 698 |
+
"""A simple renderable containing a number of lines of segments. May be used as an intermediate
|
| 699 |
+
in rendering process.
|
| 700 |
+
|
| 701 |
+
Args:
|
| 702 |
+
lines (Iterable[List[Segment]]): Lists of segments forming lines.
|
| 703 |
+
new_lines (bool, optional): Insert new lines after each line. Defaults to False.
|
| 704 |
+
"""
|
| 705 |
+
self.lines = list(lines)
|
| 706 |
+
self.new_lines = new_lines
|
| 707 |
+
|
| 708 |
+
def __rich_console__(
|
| 709 |
+
self, console: "Console", options: "ConsoleOptions"
|
| 710 |
+
) -> "RenderResult":
|
| 711 |
+
if self.new_lines:
|
| 712 |
+
new_line = Segment.line()
|
| 713 |
+
for line in self.lines:
|
| 714 |
+
yield from line
|
| 715 |
+
yield new_line
|
| 716 |
+
else:
|
| 717 |
+
for line in self.lines:
|
| 718 |
+
yield from line
|
| 719 |
+
|
| 720 |
+
|
| 721 |
+
if __name__ == "__main__": # pragma: no cover
|
| 722 |
+
from rich.console import Console
|
| 723 |
+
from rich.syntax import Syntax
|
| 724 |
+
from rich.text import Text
|
| 725 |
+
|
| 726 |
+
code = """from rich.console import Console
|
| 727 |
+
console = Console()
|
| 728 |
+
text = Text.from_markup("Hello, [bold magenta]World[/]!")
|
| 729 |
+
console.print(text)"""
|
| 730 |
+
|
| 731 |
+
text = Text.from_markup("Hello, [bold magenta]World[/]!")
|
| 732 |
+
|
| 733 |
+
console = Console()
|
| 734 |
+
|
| 735 |
+
console.rule("rich.Segment")
|
| 736 |
+
console.print(
|
| 737 |
+
"A Segment is the last step in the Rich render process before generating text with ANSI codes."
|
| 738 |
+
)
|
| 739 |
+
console.print("\nConsider the following code:\n")
|
| 740 |
+
console.print(Syntax(code, "python", line_numbers=True))
|
| 741 |
+
console.print()
|
| 742 |
+
console.print(
|
| 743 |
+
"When you call [b]print()[/b], Rich [i]renders[/i] the object in to the following:\n"
|
| 744 |
+
)
|
| 745 |
+
fragments = list(console.render(text))
|
| 746 |
+
console.print(fragments)
|
| 747 |
+
console.print()
|
| 748 |
+
console.print("The Segments are then processed to produce the following output:\n")
|
| 749 |
+
console.print(text)
|
| 750 |
+
console.print(
|
| 751 |
+
"\nYou will only need to know this if you are implementing your own Rich renderables."
|
| 752 |
+
)
|
miniconda3/lib/python3.13/site-packages/rich/spinner.py
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import TYPE_CHECKING, List, Optional, Union, cast
|
| 2 |
+
|
| 3 |
+
from ._spinners import SPINNERS
|
| 4 |
+
from .measure import Measurement
|
| 5 |
+
from .table import Table
|
| 6 |
+
from .text import Text
|
| 7 |
+
|
| 8 |
+
if TYPE_CHECKING:
|
| 9 |
+
from .console import Console, ConsoleOptions, RenderableType, RenderResult
|
| 10 |
+
from .style import StyleType
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class Spinner:
|
| 14 |
+
"""A spinner animation.
|
| 15 |
+
|
| 16 |
+
Args:
|
| 17 |
+
name (str): Name of spinner (run python -m rich.spinner).
|
| 18 |
+
text (RenderableType, optional): A renderable to display at the right of the spinner (str or Text typically). Defaults to "".
|
| 19 |
+
style (StyleType, optional): Style for spinner animation. Defaults to None.
|
| 20 |
+
speed (float, optional): Speed factor for animation. Defaults to 1.0.
|
| 21 |
+
|
| 22 |
+
Raises:
|
| 23 |
+
KeyError: If name isn't one of the supported spinner animations.
|
| 24 |
+
"""
|
| 25 |
+
|
| 26 |
+
def __init__(
|
| 27 |
+
self,
|
| 28 |
+
name: str,
|
| 29 |
+
text: "RenderableType" = "",
|
| 30 |
+
*,
|
| 31 |
+
style: Optional["StyleType"] = None,
|
| 32 |
+
speed: float = 1.0,
|
| 33 |
+
) -> None:
|
| 34 |
+
try:
|
| 35 |
+
spinner = SPINNERS[name]
|
| 36 |
+
except KeyError:
|
| 37 |
+
raise KeyError(f"no spinner called {name!r}")
|
| 38 |
+
self.text: "Union[RenderableType, Text]" = (
|
| 39 |
+
Text.from_markup(text) if isinstance(text, str) else text
|
| 40 |
+
)
|
| 41 |
+
self.name = name
|
| 42 |
+
self.frames = cast(List[str], spinner["frames"])[:]
|
| 43 |
+
self.interval = cast(float, spinner["interval"])
|
| 44 |
+
self.start_time: Optional[float] = None
|
| 45 |
+
self.style = style
|
| 46 |
+
self.speed = speed
|
| 47 |
+
self.frame_no_offset: float = 0.0
|
| 48 |
+
self._update_speed = 0.0
|
| 49 |
+
|
| 50 |
+
def __rich_console__(
|
| 51 |
+
self, console: "Console", options: "ConsoleOptions"
|
| 52 |
+
) -> "RenderResult":
|
| 53 |
+
yield self.render(console.get_time())
|
| 54 |
+
|
| 55 |
+
def __rich_measure__(
|
| 56 |
+
self, console: "Console", options: "ConsoleOptions"
|
| 57 |
+
) -> Measurement:
|
| 58 |
+
text = self.render(0)
|
| 59 |
+
return Measurement.get(console, options, text)
|
| 60 |
+
|
| 61 |
+
def render(self, time: float) -> "RenderableType":
|
| 62 |
+
"""Render the spinner for a given time.
|
| 63 |
+
|
| 64 |
+
Args:
|
| 65 |
+
time (float): Time in seconds.
|
| 66 |
+
|
| 67 |
+
Returns:
|
| 68 |
+
RenderableType: A renderable containing animation frame.
|
| 69 |
+
"""
|
| 70 |
+
if self.start_time is None:
|
| 71 |
+
self.start_time = time
|
| 72 |
+
|
| 73 |
+
frame_no = ((time - self.start_time) * self.speed) / (
|
| 74 |
+
self.interval / 1000.0
|
| 75 |
+
) + self.frame_no_offset
|
| 76 |
+
frame = Text(
|
| 77 |
+
self.frames[int(frame_no) % len(self.frames)], style=self.style or ""
|
| 78 |
+
)
|
| 79 |
+
|
| 80 |
+
if self._update_speed:
|
| 81 |
+
self.frame_no_offset = frame_no
|
| 82 |
+
self.start_time = time
|
| 83 |
+
self.speed = self._update_speed
|
| 84 |
+
self._update_speed = 0.0
|
| 85 |
+
|
| 86 |
+
if not self.text:
|
| 87 |
+
return frame
|
| 88 |
+
elif isinstance(self.text, (str, Text)):
|
| 89 |
+
return Text.assemble(frame, " ", self.text)
|
| 90 |
+
else:
|
| 91 |
+
table = Table.grid(padding=1)
|
| 92 |
+
table.add_row(frame, self.text)
|
| 93 |
+
return table
|
| 94 |
+
|
| 95 |
+
def update(
|
| 96 |
+
self,
|
| 97 |
+
*,
|
| 98 |
+
text: "RenderableType" = "",
|
| 99 |
+
style: Optional["StyleType"] = None,
|
| 100 |
+
speed: Optional[float] = None,
|
| 101 |
+
) -> None:
|
| 102 |
+
"""Updates attributes of a spinner after it has been started.
|
| 103 |
+
|
| 104 |
+
Args:
|
| 105 |
+
text (RenderableType, optional): A renderable to display at the right of the spinner (str or Text typically). Defaults to "".
|
| 106 |
+
style (StyleType, optional): Style for spinner animation. Defaults to None.
|
| 107 |
+
speed (float, optional): Speed factor for animation. Defaults to None.
|
| 108 |
+
"""
|
| 109 |
+
if text:
|
| 110 |
+
self.text = Text.from_markup(text) if isinstance(text, str) else text
|
| 111 |
+
if style:
|
| 112 |
+
self.style = style
|
| 113 |
+
if speed:
|
| 114 |
+
self._update_speed = speed
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
if __name__ == "__main__": # pragma: no cover
|
| 118 |
+
from time import sleep
|
| 119 |
+
|
| 120 |
+
from .console import Group
|
| 121 |
+
from .live import Live
|
| 122 |
+
|
| 123 |
+
all_spinners = Group(
|
| 124 |
+
*[
|
| 125 |
+
Spinner(spinner_name, text=Text(repr(spinner_name), style="green"))
|
| 126 |
+
for spinner_name in sorted(SPINNERS.keys())
|
| 127 |
+
]
|
| 128 |
+
)
|
| 129 |
+
|
| 130 |
+
with Live(all_spinners, refresh_per_second=20) as live:
|
| 131 |
+
while True:
|
| 132 |
+
sleep(0.1)
|
miniconda3/lib/python3.13/site-packages/rich/status.py
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from types import TracebackType
|
| 2 |
+
from typing import Optional, Type
|
| 3 |
+
|
| 4 |
+
from .console import Console, RenderableType
|
| 5 |
+
from .jupyter import JupyterMixin
|
| 6 |
+
from .live import Live
|
| 7 |
+
from .spinner import Spinner
|
| 8 |
+
from .style import StyleType
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class Status(JupyterMixin):
|
| 12 |
+
"""Displays a status indicator with a 'spinner' animation.
|
| 13 |
+
|
| 14 |
+
Args:
|
| 15 |
+
status (RenderableType): A status renderable (str or Text typically).
|
| 16 |
+
console (Console, optional): Console instance to use, or None for global console. Defaults to None.
|
| 17 |
+
spinner (str, optional): Name of spinner animation (see python -m rich.spinner). Defaults to "dots".
|
| 18 |
+
spinner_style (StyleType, optional): Style of spinner. Defaults to "status.spinner".
|
| 19 |
+
speed (float, optional): Speed factor for spinner animation. Defaults to 1.0.
|
| 20 |
+
refresh_per_second (float, optional): Number of refreshes per second. Defaults to 12.5.
|
| 21 |
+
"""
|
| 22 |
+
|
| 23 |
+
def __init__(
|
| 24 |
+
self,
|
| 25 |
+
status: RenderableType,
|
| 26 |
+
*,
|
| 27 |
+
console: Optional[Console] = None,
|
| 28 |
+
spinner: str = "dots",
|
| 29 |
+
spinner_style: StyleType = "status.spinner",
|
| 30 |
+
speed: float = 1.0,
|
| 31 |
+
refresh_per_second: float = 12.5,
|
| 32 |
+
):
|
| 33 |
+
self.status = status
|
| 34 |
+
self.spinner_style = spinner_style
|
| 35 |
+
self.speed = speed
|
| 36 |
+
self._spinner = Spinner(spinner, text=status, style=spinner_style, speed=speed)
|
| 37 |
+
self._live = Live(
|
| 38 |
+
self.renderable,
|
| 39 |
+
console=console,
|
| 40 |
+
refresh_per_second=refresh_per_second,
|
| 41 |
+
transient=True,
|
| 42 |
+
)
|
| 43 |
+
|
| 44 |
+
@property
|
| 45 |
+
def renderable(self) -> Spinner:
|
| 46 |
+
return self._spinner
|
| 47 |
+
|
| 48 |
+
@property
|
| 49 |
+
def console(self) -> "Console":
|
| 50 |
+
"""Get the Console used by the Status objects."""
|
| 51 |
+
return self._live.console
|
| 52 |
+
|
| 53 |
+
def update(
|
| 54 |
+
self,
|
| 55 |
+
status: Optional[RenderableType] = None,
|
| 56 |
+
*,
|
| 57 |
+
spinner: Optional[str] = None,
|
| 58 |
+
spinner_style: Optional[StyleType] = None,
|
| 59 |
+
speed: Optional[float] = None,
|
| 60 |
+
) -> None:
|
| 61 |
+
"""Update status.
|
| 62 |
+
|
| 63 |
+
Args:
|
| 64 |
+
status (Optional[RenderableType], optional): New status renderable or None for no change. Defaults to None.
|
| 65 |
+
spinner (Optional[str], optional): New spinner or None for no change. Defaults to None.
|
| 66 |
+
spinner_style (Optional[StyleType], optional): New spinner style or None for no change. Defaults to None.
|
| 67 |
+
speed (Optional[float], optional): Speed factor for spinner animation or None for no change. Defaults to None.
|
| 68 |
+
"""
|
| 69 |
+
if status is not None:
|
| 70 |
+
self.status = status
|
| 71 |
+
if spinner_style is not None:
|
| 72 |
+
self.spinner_style = spinner_style
|
| 73 |
+
if speed is not None:
|
| 74 |
+
self.speed = speed
|
| 75 |
+
if spinner is not None:
|
| 76 |
+
self._spinner = Spinner(
|
| 77 |
+
spinner, text=self.status, style=self.spinner_style, speed=self.speed
|
| 78 |
+
)
|
| 79 |
+
self._live.update(self.renderable, refresh=True)
|
| 80 |
+
else:
|
| 81 |
+
self._spinner.update(
|
| 82 |
+
text=self.status, style=self.spinner_style, speed=self.speed
|
| 83 |
+
)
|
| 84 |
+
|
| 85 |
+
def start(self) -> None:
|
| 86 |
+
"""Start the status animation."""
|
| 87 |
+
self._live.start()
|
| 88 |
+
|
| 89 |
+
def stop(self) -> None:
|
| 90 |
+
"""Stop the spinner animation."""
|
| 91 |
+
self._live.stop()
|
| 92 |
+
|
| 93 |
+
def __rich__(self) -> RenderableType:
|
| 94 |
+
return self.renderable
|
| 95 |
+
|
| 96 |
+
def __enter__(self) -> "Status":
|
| 97 |
+
self.start()
|
| 98 |
+
return self
|
| 99 |
+
|
| 100 |
+
def __exit__(
|
| 101 |
+
self,
|
| 102 |
+
exc_type: Optional[Type[BaseException]],
|
| 103 |
+
exc_val: Optional[BaseException],
|
| 104 |
+
exc_tb: Optional[TracebackType],
|
| 105 |
+
) -> None:
|
| 106 |
+
self.stop()
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
if __name__ == "__main__": # pragma: no cover
|
| 110 |
+
from time import sleep
|
| 111 |
+
|
| 112 |
+
from .console import Console
|
| 113 |
+
|
| 114 |
+
console = Console()
|
| 115 |
+
with console.status("[magenta]Covid detector booting up") as status:
|
| 116 |
+
sleep(3)
|
| 117 |
+
console.log("Importing advanced AI")
|
| 118 |
+
sleep(3)
|
| 119 |
+
console.log("Advanced Covid AI Ready")
|
| 120 |
+
sleep(3)
|
| 121 |
+
status.update(status="[bold blue] Scanning for Covid", spinner="earth")
|
| 122 |
+
sleep(3)
|
| 123 |
+
console.log("Found 10,000,000,000 copies of Covid32.exe")
|
| 124 |
+
sleep(3)
|
| 125 |
+
status.update(
|
| 126 |
+
status="[bold red]Moving Covid32.exe to Trash",
|
| 127 |
+
spinner="bouncingBall",
|
| 128 |
+
spinner_style="yellow",
|
| 129 |
+
)
|
| 130 |
+
sleep(5)
|
| 131 |
+
console.print("[bold green]Covid deleted successfully")
|