ZTWHHH commited on
Commit
b57b437
·
verified ·
1 Parent(s): c2e3c48

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. llava/lib/python3.10/site-packages/pip/_vendor/rich/__main__.py +273 -0
  2. llava/lib/python3.10/site-packages/pip/_vendor/rich/_emoji_replace.py +32 -0
  3. llava/lib/python3.10/site-packages/pip/_vendor/rich/_log_render.py +94 -0
  4. llava/lib/python3.10/site-packages/pip/_vendor/rich/_loop.py +43 -0
  5. llava/lib/python3.10/site-packages/pip/_vendor/rich/_palettes.py +309 -0
  6. llava/lib/python3.10/site-packages/pip/_vendor/rich/_spinners.py +482 -0
  7. llava/lib/python3.10/site-packages/pip/_vendor/rich/_stack.py +16 -0
  8. llava/lib/python3.10/site-packages/pip/_vendor/rich/ansi.py +241 -0
  9. llava/lib/python3.10/site-packages/pip/_vendor/rich/console.py +0 -0
  10. llava/lib/python3.10/site-packages/pip/_vendor/rich/constrain.py +37 -0
  11. llava/lib/python3.10/site-packages/pip/_vendor/rich/containers.py +167 -0
  12. llava/lib/python3.10/site-packages/pip/_vendor/rich/diagnose.py +37 -0
  13. llava/lib/python3.10/site-packages/pip/_vendor/rich/file_proxy.py +57 -0
  14. llava/lib/python3.10/site-packages/pip/_vendor/rich/filesize.py +88 -0
  15. llava/lib/python3.10/site-packages/pip/_vendor/rich/logging.py +297 -0
  16. llava/lib/python3.10/site-packages/pip/_vendor/rich/markup.py +251 -0
  17. llava/lib/python3.10/site-packages/pip/_vendor/rich/progress.py +1715 -0
  18. llava/lib/python3.10/site-packages/pip/_vendor/rich/py.typed +0 -0
  19. llava/lib/python3.10/site-packages/pip/_vendor/rich/repr.py +149 -0
  20. llava/lib/python3.10/site-packages/pip/_vendor/rich/rule.py +130 -0
  21. llava/lib/python3.10/site-packages/pip/_vendor/rich/screen.py +54 -0
  22. llava/lib/python3.10/site-packages/pip/_vendor/rich/spinner.py +138 -0
  23. llava/lib/python3.10/site-packages/pip/_vendor/rich/syntax.py +966 -0
  24. llava/lib/python3.10/site-packages/pip/_vendor/rich/terminal_theme.py +153 -0
  25. llava/lib/python3.10/site-packages/pip/_vendor/rich/text.py +1361 -0
  26. llava/lib/python3.10/site-packages/pip/_vendor/rich/theme.py +115 -0
  27. llava/lib/python3.10/site-packages/pip/_vendor/rich/traceback.py +797 -0
  28. minigpt2/lib/python3.10/site-packages/imageio/config/__init__.py +16 -0
  29. minigpt2/lib/python3.10/site-packages/imageio/config/__pycache__/__init__.cpython-310.pyc +0 -0
  30. minigpt2/lib/python3.10/site-packages/imageio/config/__pycache__/extensions.cpython-310.pyc +0 -0
  31. minigpt2/lib/python3.10/site-packages/imageio/config/__pycache__/plugins.cpython-310.pyc +0 -0
  32. minigpt2/lib/python3.10/site-packages/imageio/config/extensions.py +2002 -0
  33. minigpt2/lib/python3.10/site-packages/imageio/config/extensions.pyi +24 -0
  34. minigpt2/lib/python3.10/site-packages/imageio/config/plugins.py +782 -0
  35. minigpt2/lib/python3.10/site-packages/imageio/config/plugins.pyi +28 -0
  36. minigpt2/lib/python3.10/site-packages/imageio/freeze.py +11 -0
  37. minigpt2/lib/python3.10/site-packages/imageio/plugins/__init__.py +103 -0
  38. minigpt2/lib/python3.10/site-packages/imageio/plugins/_bsdf.py +915 -0
  39. minigpt2/lib/python3.10/site-packages/imageio/plugins/_dicom.py +932 -0
  40. minigpt2/lib/python3.10/site-packages/imageio/plugins/_freeimage.py +1312 -0
  41. minigpt2/lib/python3.10/site-packages/imageio/plugins/_tifffile.py +0 -0
  42. minigpt2/lib/python3.10/site-packages/imageio/plugins/bsdf.py +324 -0
  43. minigpt2/lib/python3.10/site-packages/imageio/plugins/dicom.py +333 -0
  44. minigpt2/lib/python3.10/site-packages/imageio/plugins/feisem.py +95 -0
  45. minigpt2/lib/python3.10/site-packages/imageio/plugins/ffmpeg.py +729 -0
  46. minigpt2/lib/python3.10/site-packages/imageio/plugins/fits.py +126 -0
  47. minigpt2/lib/python3.10/site-packages/imageio/plugins/freeimage.py +404 -0
  48. minigpt2/lib/python3.10/site-packages/imageio/plugins/freeimagemulti.py +316 -0
  49. minigpt2/lib/python3.10/site-packages/imageio/plugins/gdal.py +71 -0
  50. minigpt2/lib/python3.10/site-packages/imageio/plugins/grab.py +105 -0
llava/lib/python3.10/site-packages/pip/_vendor/rich/__main__.py ADDED
@@ -0,0 +1,273 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import colorsys
2
+ import io
3
+ from time import process_time
4
+
5
+ from pip._vendor.rich import box
6
+ from pip._vendor.rich.color import Color
7
+ from pip._vendor.rich.console import Console, ConsoleOptions, Group, RenderableType, RenderResult
8
+ from pip._vendor.rich.markdown import Markdown
9
+ from pip._vendor.rich.measure import Measurement
10
+ from pip._vendor.rich.pretty import Pretty
11
+ from pip._vendor.rich.segment import Segment
12
+ from pip._vendor.rich.style import Style
13
+ from pip._vendor.rich.syntax import Syntax
14
+ from pip._vendor.rich.table import Table
15
+ from pip._vendor.rich.text import Text
16
+
17
+
18
+ class ColorBox:
19
+ def __rich_console__(
20
+ self, console: Console, options: ConsoleOptions
21
+ ) -> RenderResult:
22
+ for y in range(0, 5):
23
+ for x in range(options.max_width):
24
+ h = x / options.max_width
25
+ l = 0.1 + ((y / 5) * 0.7)
26
+ r1, g1, b1 = colorsys.hls_to_rgb(h, l, 1.0)
27
+ r2, g2, b2 = colorsys.hls_to_rgb(h, l + 0.7 / 10, 1.0)
28
+ bgcolor = Color.from_rgb(r1 * 255, g1 * 255, b1 * 255)
29
+ color = Color.from_rgb(r2 * 255, g2 * 255, b2 * 255)
30
+ yield Segment("▄", Style(color=color, bgcolor=bgcolor))
31
+ yield Segment.line()
32
+
33
+ def __rich_measure__(
34
+ self, console: "Console", options: ConsoleOptions
35
+ ) -> Measurement:
36
+ return Measurement(1, options.max_width)
37
+
38
+
39
+ def make_test_card() -> Table:
40
+ """Get a renderable that demonstrates a number of features."""
41
+ table = Table.grid(padding=1, pad_edge=True)
42
+ table.title = "Rich features"
43
+ table.add_column("Feature", no_wrap=True, justify="center", style="bold red")
44
+ table.add_column("Demonstration")
45
+
46
+ color_table = Table(
47
+ box=None,
48
+ expand=False,
49
+ show_header=False,
50
+ show_edge=False,
51
+ pad_edge=False,
52
+ )
53
+ color_table.add_row(
54
+ (
55
+ "✓ [bold green]4-bit color[/]\n"
56
+ "✓ [bold blue]8-bit color[/]\n"
57
+ "✓ [bold magenta]Truecolor (16.7 million)[/]\n"
58
+ "✓ [bold yellow]Dumb terminals[/]\n"
59
+ "✓ [bold cyan]Automatic color conversion"
60
+ ),
61
+ ColorBox(),
62
+ )
63
+
64
+ table.add_row("Colors", color_table)
65
+
66
+ table.add_row(
67
+ "Styles",
68
+ "All ansi styles: [bold]bold[/], [dim]dim[/], [italic]italic[/italic], [underline]underline[/], [strike]strikethrough[/], [reverse]reverse[/], and even [blink]blink[/].",
69
+ )
70
+
71
+ lorem = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque in metus sed sapien ultricies pretium a at justo. Maecenas luctus velit et auctor maximus."
72
+ lorem_table = Table.grid(padding=1, collapse_padding=True)
73
+ lorem_table.pad_edge = False
74
+ lorem_table.add_row(
75
+ Text(lorem, justify="left", style="green"),
76
+ Text(lorem, justify="center", style="yellow"),
77
+ Text(lorem, justify="right", style="blue"),
78
+ Text(lorem, justify="full", style="red"),
79
+ )
80
+ table.add_row(
81
+ "Text",
82
+ Group(
83
+ Text.from_markup(
84
+ """Word wrap text. Justify [green]left[/], [yellow]center[/], [blue]right[/] or [red]full[/].\n"""
85
+ ),
86
+ lorem_table,
87
+ ),
88
+ )
89
+
90
+ def comparison(renderable1: RenderableType, renderable2: RenderableType) -> Table:
91
+ table = Table(show_header=False, pad_edge=False, box=None, expand=True)
92
+ table.add_column("1", ratio=1)
93
+ table.add_column("2", ratio=1)
94
+ table.add_row(renderable1, renderable2)
95
+ return table
96
+
97
+ table.add_row(
98
+ "Asian\nlanguage\nsupport",
99
+ ":flag_for_china: 该库支持中文,日文和韩文文本!\n:flag_for_japan: ライブラリは中国語、日本語、韓国語のテキストをサポートしています\n:flag_for_south_korea: 이 라이브러리는 중국어, 일본어 및 한국어 텍스트를 지원합니다",
100
+ )
101
+
102
+ markup_example = (
103
+ "[bold magenta]Rich[/] supports a simple [i]bbcode[/i]-like [b]markup[/b] for [yellow]color[/], [underline]style[/], and emoji! "
104
+ ":+1: :apple: :ant: :bear: :baguette_bread: :bus: "
105
+ )
106
+ table.add_row("Markup", markup_example)
107
+
108
+ example_table = Table(
109
+ show_edge=False,
110
+ show_header=True,
111
+ expand=False,
112
+ row_styles=["none", "dim"],
113
+ box=box.SIMPLE,
114
+ )
115
+ example_table.add_column("[green]Date", style="green", no_wrap=True)
116
+ example_table.add_column("[blue]Title", style="blue")
117
+ example_table.add_column(
118
+ "[cyan]Production Budget",
119
+ style="cyan",
120
+ justify="right",
121
+ no_wrap=True,
122
+ )
123
+ example_table.add_column(
124
+ "[magenta]Box Office",
125
+ style="magenta",
126
+ justify="right",
127
+ no_wrap=True,
128
+ )
129
+ example_table.add_row(
130
+ "Dec 20, 2019",
131
+ "Star Wars: The Rise of Skywalker",
132
+ "$275,000,000",
133
+ "$375,126,118",
134
+ )
135
+ example_table.add_row(
136
+ "May 25, 2018",
137
+ "[b]Solo[/]: A Star Wars Story",
138
+ "$275,000,000",
139
+ "$393,151,347",
140
+ )
141
+ example_table.add_row(
142
+ "Dec 15, 2017",
143
+ "Star Wars Ep. VIII: The Last Jedi",
144
+ "$262,000,000",
145
+ "[bold]$1,332,539,889[/bold]",
146
+ )
147
+ example_table.add_row(
148
+ "May 19, 1999",
149
+ "Star Wars Ep. [b]I[/b]: [i]The phantom Menace",
150
+ "$115,000,000",
151
+ "$1,027,044,677",
152
+ )
153
+
154
+ table.add_row("Tables", example_table)
155
+
156
+ code = '''\
157
+ def iter_last(values: Iterable[T]) -> Iterable[Tuple[bool, T]]:
158
+ """Iterate and generate a tuple with a flag for last value."""
159
+ iter_values = iter(values)
160
+ try:
161
+ previous_value = next(iter_values)
162
+ except StopIteration:
163
+ return
164
+ for value in iter_values:
165
+ yield False, previous_value
166
+ previous_value = value
167
+ yield True, previous_value'''
168
+
169
+ pretty_data = {
170
+ "foo": [
171
+ 3.1427,
172
+ (
173
+ "Paul Atreides",
174
+ "Vladimir Harkonnen",
175
+ "Thufir Hawat",
176
+ ),
177
+ ],
178
+ "atomic": (False, True, None),
179
+ }
180
+ table.add_row(
181
+ "Syntax\nhighlighting\n&\npretty\nprinting",
182
+ comparison(
183
+ Syntax(code, "python3", line_numbers=True, indent_guides=True),
184
+ Pretty(pretty_data, indent_guides=True),
185
+ ),
186
+ )
187
+
188
+ markdown_example = """\
189
+ # Markdown
190
+
191
+ Supports much of the *markdown* __syntax__!
192
+
193
+ - Headers
194
+ - Basic formatting: **bold**, *italic*, `code`
195
+ - Block quotes
196
+ - Lists, and more...
197
+ """
198
+ table.add_row(
199
+ "Markdown", comparison("[cyan]" + markdown_example, Markdown(markdown_example))
200
+ )
201
+
202
+ table.add_row(
203
+ "+more!",
204
+ """Progress bars, columns, styled logging handler, tracebacks, etc...""",
205
+ )
206
+ return table
207
+
208
+
209
+ if __name__ == "__main__": # pragma: no cover
210
+ console = Console(
211
+ file=io.StringIO(),
212
+ force_terminal=True,
213
+ )
214
+ test_card = make_test_card()
215
+
216
+ # Print once to warm cache
217
+ start = process_time()
218
+ console.print(test_card)
219
+ pre_cache_taken = round((process_time() - start) * 1000.0, 1)
220
+
221
+ console.file = io.StringIO()
222
+
223
+ start = process_time()
224
+ console.print(test_card)
225
+ taken = round((process_time() - start) * 1000.0, 1)
226
+
227
+ c = Console(record=True)
228
+ c.print(test_card)
229
+
230
+ print(f"rendered in {pre_cache_taken}ms (cold cache)")
231
+ print(f"rendered in {taken}ms (warm cache)")
232
+
233
+ from pip._vendor.rich.panel import Panel
234
+
235
+ console = Console()
236
+
237
+ sponsor_message = Table.grid(padding=1)
238
+ sponsor_message.add_column(style="green", justify="right")
239
+ sponsor_message.add_column(no_wrap=True)
240
+
241
+ sponsor_message.add_row(
242
+ "Textualize",
243
+ "[u blue link=https://github.com/textualize]https://github.com/textualize",
244
+ )
245
+ sponsor_message.add_row(
246
+ "Twitter",
247
+ "[u blue link=https://twitter.com/willmcgugan]https://twitter.com/willmcgugan",
248
+ )
249
+
250
+ intro_message = Text.from_markup(
251
+ """\
252
+ We hope you enjoy using Rich!
253
+
254
+ Rich is maintained with [red]:heart:[/] by [link=https://www.textualize.io]Textualize.io[/]
255
+
256
+ - Will McGugan"""
257
+ )
258
+
259
+ message = Table.grid(padding=2)
260
+ message.add_column()
261
+ message.add_column(no_wrap=True)
262
+ message.add_row(intro_message, sponsor_message)
263
+
264
+ console.print(
265
+ Panel.fit(
266
+ message,
267
+ box=box.ROUNDED,
268
+ padding=(1, 2),
269
+ title="[b red]Thanks for trying out Rich!",
270
+ border_style="bright_blue",
271
+ ),
272
+ justify="center",
273
+ )
llava/lib/python3.10/site-packages/pip/_vendor/rich/_emoji_replace.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Callable, Match, Optional
2
+ import re
3
+
4
+ from ._emoji_codes import EMOJI
5
+
6
+
7
+ _ReStringMatch = Match[str] # regex match object
8
+ _ReSubCallable = Callable[[_ReStringMatch], str] # Callable invoked by re.sub
9
+ _EmojiSubMethod = Callable[[_ReSubCallable, str], str] # Sub method of a compiled re
10
+
11
+
12
+ def _emoji_replace(
13
+ text: str,
14
+ default_variant: Optional[str] = None,
15
+ _emoji_sub: _EmojiSubMethod = re.compile(r"(:(\S*?)(?:(?:\-)(emoji|text))?:)").sub,
16
+ ) -> str:
17
+ """Replace emoji code in text."""
18
+ get_emoji = EMOJI.__getitem__
19
+ variants = {"text": "\uFE0E", "emoji": "\uFE0F"}
20
+ get_variant = variants.get
21
+ default_variant_code = variants.get(default_variant, "") if default_variant else ""
22
+
23
+ def do_replace(match: Match[str]) -> str:
24
+ emoji_code, emoji_name, variant = match.groups()
25
+ try:
26
+ return get_emoji(emoji_name.lower()) + get_variant(
27
+ variant, default_variant_code
28
+ )
29
+ except KeyError:
30
+ return emoji_code
31
+
32
+ return _emoji_sub(do_replace, text)
llava/lib/python3.10/site-packages/pip/_vendor/rich/_log_render.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import datetime
2
+ from typing import Iterable, List, Optional, TYPE_CHECKING, Union, Callable
3
+
4
+
5
+ from .text import Text, TextType
6
+
7
+ if TYPE_CHECKING:
8
+ from .console import Console, ConsoleRenderable, RenderableType
9
+ from .table import Table
10
+
11
+ FormatTimeCallable = Callable[[datetime], Text]
12
+
13
+
14
+ class LogRender:
15
+ def __init__(
16
+ self,
17
+ show_time: bool = True,
18
+ show_level: bool = False,
19
+ show_path: bool = True,
20
+ time_format: Union[str, FormatTimeCallable] = "[%x %X]",
21
+ omit_repeated_times: bool = True,
22
+ level_width: Optional[int] = 8,
23
+ ) -> None:
24
+ self.show_time = show_time
25
+ self.show_level = show_level
26
+ self.show_path = show_path
27
+ self.time_format = time_format
28
+ self.omit_repeated_times = omit_repeated_times
29
+ self.level_width = level_width
30
+ self._last_time: Optional[Text] = None
31
+
32
+ def __call__(
33
+ self,
34
+ console: "Console",
35
+ renderables: Iterable["ConsoleRenderable"],
36
+ log_time: Optional[datetime] = None,
37
+ time_format: Optional[Union[str, FormatTimeCallable]] = None,
38
+ level: TextType = "",
39
+ path: Optional[str] = None,
40
+ line_no: Optional[int] = None,
41
+ link_path: Optional[str] = None,
42
+ ) -> "Table":
43
+ from .containers import Renderables
44
+ from .table import Table
45
+
46
+ output = Table.grid(padding=(0, 1))
47
+ output.expand = True
48
+ if self.show_time:
49
+ output.add_column(style="log.time")
50
+ if self.show_level:
51
+ output.add_column(style="log.level", width=self.level_width)
52
+ output.add_column(ratio=1, style="log.message", overflow="fold")
53
+ if self.show_path and path:
54
+ output.add_column(style="log.path")
55
+ row: List["RenderableType"] = []
56
+ if self.show_time:
57
+ log_time = log_time or console.get_datetime()
58
+ time_format = time_format or self.time_format
59
+ if callable(time_format):
60
+ log_time_display = time_format(log_time)
61
+ else:
62
+ log_time_display = Text(log_time.strftime(time_format))
63
+ if log_time_display == self._last_time and self.omit_repeated_times:
64
+ row.append(Text(" " * len(log_time_display)))
65
+ else:
66
+ row.append(log_time_display)
67
+ self._last_time = log_time_display
68
+ if self.show_level:
69
+ row.append(level)
70
+
71
+ row.append(Renderables(renderables))
72
+ if self.show_path and path:
73
+ path_text = Text()
74
+ path_text.append(
75
+ path, style=f"link file://{link_path}" if link_path else ""
76
+ )
77
+ if line_no:
78
+ path_text.append(":")
79
+ path_text.append(
80
+ f"{line_no}",
81
+ style=f"link file://{link_path}#{line_no}" if link_path else "",
82
+ )
83
+ row.append(path_text)
84
+
85
+ output.add_row(*row)
86
+ return output
87
+
88
+
89
+ if __name__ == "__main__": # pragma: no cover
90
+ from pip._vendor.rich.console import Console
91
+
92
+ c = Console()
93
+ c.print("[on blue]Hello", justify="right")
94
+ c.log("[on blue]hello", justify="right")
llava/lib/python3.10/site-packages/pip/_vendor/rich/_loop.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Iterable, Tuple, TypeVar
2
+
3
+ T = TypeVar("T")
4
+
5
+
6
+ def loop_first(values: Iterable[T]) -> Iterable[Tuple[bool, T]]:
7
+ """Iterate and generate a tuple with a flag for first value."""
8
+ iter_values = iter(values)
9
+ try:
10
+ value = next(iter_values)
11
+ except StopIteration:
12
+ return
13
+ yield True, value
14
+ for value in iter_values:
15
+ yield False, value
16
+
17
+
18
+ def loop_last(values: Iterable[T]) -> Iterable[Tuple[bool, T]]:
19
+ """Iterate and generate a tuple with a flag for last value."""
20
+ iter_values = iter(values)
21
+ try:
22
+ previous_value = next(iter_values)
23
+ except StopIteration:
24
+ return
25
+ for value in iter_values:
26
+ yield False, previous_value
27
+ previous_value = value
28
+ yield True, previous_value
29
+
30
+
31
+ def loop_first_last(values: Iterable[T]) -> Iterable[Tuple[bool, bool, T]]:
32
+ """Iterate and generate a tuple with a flag for first and last value."""
33
+ iter_values = iter(values)
34
+ try:
35
+ previous_value = next(iter_values)
36
+ except StopIteration:
37
+ return
38
+ first = True
39
+ for value in iter_values:
40
+ yield first, False, previous_value
41
+ first = False
42
+ previous_value = value
43
+ yield first, True, previous_value
llava/lib/python3.10/site-packages/pip/_vendor/rich/_palettes.py ADDED
@@ -0,0 +1,309 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .palette import Palette
2
+
3
+
4
+ # Taken from https://en.wikipedia.org/wiki/ANSI_escape_code (Windows 10 column)
5
+ WINDOWS_PALETTE = Palette(
6
+ [
7
+ (12, 12, 12),
8
+ (197, 15, 31),
9
+ (19, 161, 14),
10
+ (193, 156, 0),
11
+ (0, 55, 218),
12
+ (136, 23, 152),
13
+ (58, 150, 221),
14
+ (204, 204, 204),
15
+ (118, 118, 118),
16
+ (231, 72, 86),
17
+ (22, 198, 12),
18
+ (249, 241, 165),
19
+ (59, 120, 255),
20
+ (180, 0, 158),
21
+ (97, 214, 214),
22
+ (242, 242, 242),
23
+ ]
24
+ )
25
+
26
+ # # The standard ansi colors (including bright variants)
27
+ STANDARD_PALETTE = Palette(
28
+ [
29
+ (0, 0, 0),
30
+ (170, 0, 0),
31
+ (0, 170, 0),
32
+ (170, 85, 0),
33
+ (0, 0, 170),
34
+ (170, 0, 170),
35
+ (0, 170, 170),
36
+ (170, 170, 170),
37
+ (85, 85, 85),
38
+ (255, 85, 85),
39
+ (85, 255, 85),
40
+ (255, 255, 85),
41
+ (85, 85, 255),
42
+ (255, 85, 255),
43
+ (85, 255, 255),
44
+ (255, 255, 255),
45
+ ]
46
+ )
47
+
48
+
49
+ # The 256 color palette
50
+ EIGHT_BIT_PALETTE = Palette(
51
+ [
52
+ (0, 0, 0),
53
+ (128, 0, 0),
54
+ (0, 128, 0),
55
+ (128, 128, 0),
56
+ (0, 0, 128),
57
+ (128, 0, 128),
58
+ (0, 128, 128),
59
+ (192, 192, 192),
60
+ (128, 128, 128),
61
+ (255, 0, 0),
62
+ (0, 255, 0),
63
+ (255, 255, 0),
64
+ (0, 0, 255),
65
+ (255, 0, 255),
66
+ (0, 255, 255),
67
+ (255, 255, 255),
68
+ (0, 0, 0),
69
+ (0, 0, 95),
70
+ (0, 0, 135),
71
+ (0, 0, 175),
72
+ (0, 0, 215),
73
+ (0, 0, 255),
74
+ (0, 95, 0),
75
+ (0, 95, 95),
76
+ (0, 95, 135),
77
+ (0, 95, 175),
78
+ (0, 95, 215),
79
+ (0, 95, 255),
80
+ (0, 135, 0),
81
+ (0, 135, 95),
82
+ (0, 135, 135),
83
+ (0, 135, 175),
84
+ (0, 135, 215),
85
+ (0, 135, 255),
86
+ (0, 175, 0),
87
+ (0, 175, 95),
88
+ (0, 175, 135),
89
+ (0, 175, 175),
90
+ (0, 175, 215),
91
+ (0, 175, 255),
92
+ (0, 215, 0),
93
+ (0, 215, 95),
94
+ (0, 215, 135),
95
+ (0, 215, 175),
96
+ (0, 215, 215),
97
+ (0, 215, 255),
98
+ (0, 255, 0),
99
+ (0, 255, 95),
100
+ (0, 255, 135),
101
+ (0, 255, 175),
102
+ (0, 255, 215),
103
+ (0, 255, 255),
104
+ (95, 0, 0),
105
+ (95, 0, 95),
106
+ (95, 0, 135),
107
+ (95, 0, 175),
108
+ (95, 0, 215),
109
+ (95, 0, 255),
110
+ (95, 95, 0),
111
+ (95, 95, 95),
112
+ (95, 95, 135),
113
+ (95, 95, 175),
114
+ (95, 95, 215),
115
+ (95, 95, 255),
116
+ (95, 135, 0),
117
+ (95, 135, 95),
118
+ (95, 135, 135),
119
+ (95, 135, 175),
120
+ (95, 135, 215),
121
+ (95, 135, 255),
122
+ (95, 175, 0),
123
+ (95, 175, 95),
124
+ (95, 175, 135),
125
+ (95, 175, 175),
126
+ (95, 175, 215),
127
+ (95, 175, 255),
128
+ (95, 215, 0),
129
+ (95, 215, 95),
130
+ (95, 215, 135),
131
+ (95, 215, 175),
132
+ (95, 215, 215),
133
+ (95, 215, 255),
134
+ (95, 255, 0),
135
+ (95, 255, 95),
136
+ (95, 255, 135),
137
+ (95, 255, 175),
138
+ (95, 255, 215),
139
+ (95, 255, 255),
140
+ (135, 0, 0),
141
+ (135, 0, 95),
142
+ (135, 0, 135),
143
+ (135, 0, 175),
144
+ (135, 0, 215),
145
+ (135, 0, 255),
146
+ (135, 95, 0),
147
+ (135, 95, 95),
148
+ (135, 95, 135),
149
+ (135, 95, 175),
150
+ (135, 95, 215),
151
+ (135, 95, 255),
152
+ (135, 135, 0),
153
+ (135, 135, 95),
154
+ (135, 135, 135),
155
+ (135, 135, 175),
156
+ (135, 135, 215),
157
+ (135, 135, 255),
158
+ (135, 175, 0),
159
+ (135, 175, 95),
160
+ (135, 175, 135),
161
+ (135, 175, 175),
162
+ (135, 175, 215),
163
+ (135, 175, 255),
164
+ (135, 215, 0),
165
+ (135, 215, 95),
166
+ (135, 215, 135),
167
+ (135, 215, 175),
168
+ (135, 215, 215),
169
+ (135, 215, 255),
170
+ (135, 255, 0),
171
+ (135, 255, 95),
172
+ (135, 255, 135),
173
+ (135, 255, 175),
174
+ (135, 255, 215),
175
+ (135, 255, 255),
176
+ (175, 0, 0),
177
+ (175, 0, 95),
178
+ (175, 0, 135),
179
+ (175, 0, 175),
180
+ (175, 0, 215),
181
+ (175, 0, 255),
182
+ (175, 95, 0),
183
+ (175, 95, 95),
184
+ (175, 95, 135),
185
+ (175, 95, 175),
186
+ (175, 95, 215),
187
+ (175, 95, 255),
188
+ (175, 135, 0),
189
+ (175, 135, 95),
190
+ (175, 135, 135),
191
+ (175, 135, 175),
192
+ (175, 135, 215),
193
+ (175, 135, 255),
194
+ (175, 175, 0),
195
+ (175, 175, 95),
196
+ (175, 175, 135),
197
+ (175, 175, 175),
198
+ (175, 175, 215),
199
+ (175, 175, 255),
200
+ (175, 215, 0),
201
+ (175, 215, 95),
202
+ (175, 215, 135),
203
+ (175, 215, 175),
204
+ (175, 215, 215),
205
+ (175, 215, 255),
206
+ (175, 255, 0),
207
+ (175, 255, 95),
208
+ (175, 255, 135),
209
+ (175, 255, 175),
210
+ (175, 255, 215),
211
+ (175, 255, 255),
212
+ (215, 0, 0),
213
+ (215, 0, 95),
214
+ (215, 0, 135),
215
+ (215, 0, 175),
216
+ (215, 0, 215),
217
+ (215, 0, 255),
218
+ (215, 95, 0),
219
+ (215, 95, 95),
220
+ (215, 95, 135),
221
+ (215, 95, 175),
222
+ (215, 95, 215),
223
+ (215, 95, 255),
224
+ (215, 135, 0),
225
+ (215, 135, 95),
226
+ (215, 135, 135),
227
+ (215, 135, 175),
228
+ (215, 135, 215),
229
+ (215, 135, 255),
230
+ (215, 175, 0),
231
+ (215, 175, 95),
232
+ (215, 175, 135),
233
+ (215, 175, 175),
234
+ (215, 175, 215),
235
+ (215, 175, 255),
236
+ (215, 215, 0),
237
+ (215, 215, 95),
238
+ (215, 215, 135),
239
+ (215, 215, 175),
240
+ (215, 215, 215),
241
+ (215, 215, 255),
242
+ (215, 255, 0),
243
+ (215, 255, 95),
244
+ (215, 255, 135),
245
+ (215, 255, 175),
246
+ (215, 255, 215),
247
+ (215, 255, 255),
248
+ (255, 0, 0),
249
+ (255, 0, 95),
250
+ (255, 0, 135),
251
+ (255, 0, 175),
252
+ (255, 0, 215),
253
+ (255, 0, 255),
254
+ (255, 95, 0),
255
+ (255, 95, 95),
256
+ (255, 95, 135),
257
+ (255, 95, 175),
258
+ (255, 95, 215),
259
+ (255, 95, 255),
260
+ (255, 135, 0),
261
+ (255, 135, 95),
262
+ (255, 135, 135),
263
+ (255, 135, 175),
264
+ (255, 135, 215),
265
+ (255, 135, 255),
266
+ (255, 175, 0),
267
+ (255, 175, 95),
268
+ (255, 175, 135),
269
+ (255, 175, 175),
270
+ (255, 175, 215),
271
+ (255, 175, 255),
272
+ (255, 215, 0),
273
+ (255, 215, 95),
274
+ (255, 215, 135),
275
+ (255, 215, 175),
276
+ (255, 215, 215),
277
+ (255, 215, 255),
278
+ (255, 255, 0),
279
+ (255, 255, 95),
280
+ (255, 255, 135),
281
+ (255, 255, 175),
282
+ (255, 255, 215),
283
+ (255, 255, 255),
284
+ (8, 8, 8),
285
+ (18, 18, 18),
286
+ (28, 28, 28),
287
+ (38, 38, 38),
288
+ (48, 48, 48),
289
+ (58, 58, 58),
290
+ (68, 68, 68),
291
+ (78, 78, 78),
292
+ (88, 88, 88),
293
+ (98, 98, 98),
294
+ (108, 108, 108),
295
+ (118, 118, 118),
296
+ (128, 128, 128),
297
+ (138, 138, 138),
298
+ (148, 148, 148),
299
+ (158, 158, 158),
300
+ (168, 168, 168),
301
+ (178, 178, 178),
302
+ (188, 188, 188),
303
+ (198, 198, 198),
304
+ (208, 208, 208),
305
+ (218, 218, 218),
306
+ (228, 228, 228),
307
+ (238, 238, 238),
308
+ ]
309
+ )
llava/lib/python3.10/site-packages/pip/_vendor/rich/_spinners.py ADDED
@@ -0,0 +1,482 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Spinners are from:
3
+ * cli-spinners:
4
+ MIT License
5
+ Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights to
9
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
10
+ the Software, and to permit persons to whom the Software is furnished to do so,
11
+ subject to the following conditions:
12
+ The above copyright notice and this permission notice shall be included
13
+ in all copies or substantial portions of the Software.
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
15
+ INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
16
+ PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
17
+ FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
18
+ ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
19
+ IN THE SOFTWARE.
20
+ """
21
+
22
+ SPINNERS = {
23
+ "dots": {
24
+ "interval": 80,
25
+ "frames": "⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏",
26
+ },
27
+ "dots2": {"interval": 80, "frames": "⣾⣽⣻⢿⡿⣟⣯⣷"},
28
+ "dots3": {
29
+ "interval": 80,
30
+ "frames": "⠋⠙⠚⠞⠖⠦⠴⠲⠳⠓",
31
+ },
32
+ "dots4": {
33
+ "interval": 80,
34
+ "frames": "⠄⠆⠇⠋⠙⠸⠰⠠⠰⠸⠙⠋⠇⠆",
35
+ },
36
+ "dots5": {
37
+ "interval": 80,
38
+ "frames": "⠋⠙⠚⠒⠂⠂⠒⠲⠴⠦⠖⠒⠐⠐⠒⠓⠋",
39
+ },
40
+ "dots6": {
41
+ "interval": 80,
42
+ "frames": "⠁⠉⠙⠚⠒⠂⠂⠒⠲⠴⠤⠄⠄⠤⠴⠲⠒⠂⠂⠒⠚⠙⠉⠁",
43
+ },
44
+ "dots7": {
45
+ "interval": 80,
46
+ "frames": "⠈⠉⠋⠓⠒⠐⠐⠒⠖⠦⠤⠠⠠⠤⠦⠖⠒⠐⠐⠒⠓⠋⠉⠈",
47
+ },
48
+ "dots8": {
49
+ "interval": 80,
50
+ "frames": "⠁⠁⠉⠙⠚⠒⠂⠂⠒⠲⠴⠤⠄⠄⠤⠠⠠⠤⠦⠖⠒⠐⠐⠒⠓⠋⠉⠈⠈",
51
+ },
52
+ "dots9": {"interval": 80, "frames": "⢹⢺⢼⣸⣇⡧⡗⡏"},
53
+ "dots10": {"interval": 80, "frames": "⢄⢂⢁⡁⡈⡐⡠"},
54
+ "dots11": {"interval": 100, "frames": "⠁⠂⠄⡀⢀⠠⠐⠈"},
55
+ "dots12": {
56
+ "interval": 80,
57
+ "frames": [
58
+ "⢀⠀",
59
+ "⡀⠀",
60
+ "⠄⠀",
61
+ "⢂⠀",
62
+ "⡂⠀",
63
+ "⠅⠀",
64
+ "⢃⠀",
65
+ "⡃⠀",
66
+ "⠍⠀",
67
+ "⢋⠀",
68
+ "⡋⠀",
69
+ "⠍⠁",
70
+ "⢋⠁",
71
+ "⡋⠁",
72
+ "⠍⠉",
73
+ "⠋⠉",
74
+ "⠋⠉",
75
+ "⠉⠙",
76
+ "⠉⠙",
77
+ "⠉⠩",
78
+ "⠈⢙",
79
+ "⠈⡙",
80
+ "⢈⠩",
81
+ "⡀⢙",
82
+ "⠄⡙",
83
+ "⢂⠩",
84
+ "⡂⢘",
85
+ "⠅⡘",
86
+ "⢃⠨",
87
+ "⡃⢐",
88
+ "⠍⡐",
89
+ "⢋⠠",
90
+ "⡋⢀",
91
+ "⠍⡁",
92
+ "⢋⠁",
93
+ "⡋⠁",
94
+ "⠍⠉",
95
+ "⠋⠉",
96
+ "⠋⠉",
97
+ "⠉⠙",
98
+ "⠉⠙",
99
+ "⠉⠩",
100
+ "⠈⢙",
101
+ "⠈⡙",
102
+ "⠈⠩",
103
+ "⠀⢙",
104
+ "⠀⡙",
105
+ "⠀⠩",
106
+ "⠀⢘",
107
+ "⠀⡘",
108
+ "⠀⠨",
109
+ "⠀⢐",
110
+ "⠀⡐",
111
+ "⠀⠠",
112
+ "⠀⢀",
113
+ "⠀⡀",
114
+ ],
115
+ },
116
+ "dots8Bit": {
117
+ "interval": 80,
118
+ "frames": "⠀⠁⠂⠃⠄⠅⠆⠇⡀⡁⡂⡃⡄⡅⡆⡇⠈⠉⠊⠋⠌⠍⠎⠏⡈⡉⡊⡋⡌⡍⡎⡏⠐⠑⠒⠓⠔⠕⠖⠗⡐⡑⡒⡓⡔⡕⡖⡗⠘⠙⠚⠛⠜⠝⠞⠟⡘⡙"
119
+ "⡚⡛⡜⡝⡞⡟⠠⠡⠢⠣⠤⠥⠦⠧⡠⡡⡢⡣⡤⡥⡦⡧⠨⠩⠪⠫⠬⠭⠮⠯⡨⡩⡪⡫⡬⡭⡮⡯⠰⠱⠲⠳⠴⠵⠶⠷⡰⡱⡲⡳⡴⡵⡶⡷⠸⠹⠺⠻"
120
+ "⠼⠽⠾⠿⡸⡹⡺⡻⡼⡽⡾⡿⢀⢁⢂⢃⢄⢅⢆⢇⣀⣁⣂⣃⣄⣅⣆⣇⢈⢉⢊⢋⢌⢍⢎⢏⣈⣉⣊⣋⣌⣍⣎⣏⢐⢑⢒⢓⢔⢕⢖⢗⣐⣑⣒⣓⣔⣕"
121
+ "⣖⣗⢘⢙⢚⢛⢜⢝⢞⢟⣘⣙⣚⣛⣜⣝⣞⣟⢠⢡⢢⢣⢤⢥⢦⢧⣠⣡⣢⣣⣤⣥⣦⣧⢨⢩⢪⢫⢬⢭⢮⢯⣨⣩⣪⣫⣬⣭⣮⣯⢰⢱⢲⢳⢴⢵⢶⢷"
122
+ "⣰⣱⣲⣳⣴⣵⣶⣷⢸⢹⢺⢻⢼⢽⢾⢿⣸⣹⣺⣻⣼⣽⣾⣿",
123
+ },
124
+ "line": {"interval": 130, "frames": ["-", "\\", "|", "/"]},
125
+ "line2": {"interval": 100, "frames": "⠂-–—–-"},
126
+ "pipe": {"interval": 100, "frames": "┤┘┴└├┌┬┐"},
127
+ "simpleDots": {"interval": 400, "frames": [". ", ".. ", "...", " "]},
128
+ "simpleDotsScrolling": {
129
+ "interval": 200,
130
+ "frames": [". ", ".. ", "...", " ..", " .", " "],
131
+ },
132
+ "star": {"interval": 70, "frames": "✶✸✹✺✹✷"},
133
+ "star2": {"interval": 80, "frames": "+x*"},
134
+ "flip": {
135
+ "interval": 70,
136
+ "frames": "___-``'´-___",
137
+ },
138
+ "hamburger": {"interval": 100, "frames": "☱☲☴"},
139
+ "growVertical": {
140
+ "interval": 120,
141
+ "frames": "▁▃▄▅▆▇▆▅▄▃",
142
+ },
143
+ "growHorizontal": {
144
+ "interval": 120,
145
+ "frames": "▏▎▍▌▋▊▉▊▋▌▍▎",
146
+ },
147
+ "balloon": {"interval": 140, "frames": " .oO@* "},
148
+ "balloon2": {"interval": 120, "frames": ".oO°Oo."},
149
+ "noise": {"interval": 100, "frames": "▓▒░"},
150
+ "bounce": {"interval": 120, "frames": "⠁⠂⠄⠂"},
151
+ "boxBounce": {"interval": 120, "frames": "▖▘▝▗"},
152
+ "boxBounce2": {"interval": 100, "frames": "▌▀▐▄"},
153
+ "triangle": {"interval": 50, "frames": "◢◣◤◥"},
154
+ "arc": {"interval": 100, "frames": "◜◠◝◞◡◟"},
155
+ "circle": {"interval": 120, "frames": "◡⊙◠"},
156
+ "squareCorners": {"interval": 180, "frames": "◰◳◲◱"},
157
+ "circleQuarters": {"interval": 120, "frames": "◴◷◶◵"},
158
+ "circleHalves": {"interval": 50, "frames": "◐◓◑◒"},
159
+ "squish": {"interval": 100, "frames": "╫╪"},
160
+ "toggle": {"interval": 250, "frames": "⊶⊷"},
161
+ "toggle2": {"interval": 80, "frames": "▫▪"},
162
+ "toggle3": {"interval": 120, "frames": "□■"},
163
+ "toggle4": {"interval": 100, "frames": "■□▪▫"},
164
+ "toggle5": {"interval": 100, "frames": "▮▯"},
165
+ "toggle6": {"interval": 300, "frames": "ဝ၀"},
166
+ "toggle7": {"interval": 80, "frames": "⦾⦿"},
167
+ "toggle8": {"interval": 100, "frames": "◍◌"},
168
+ "toggle9": {"interval": 100, "frames": "◉◎"},
169
+ "toggle10": {"interval": 100, "frames": "㊂㊀㊁"},
170
+ "toggle11": {"interval": 50, "frames": "⧇⧆"},
171
+ "toggle12": {"interval": 120, "frames": "☗☖"},
172
+ "toggle13": {"interval": 80, "frames": "=*-"},
173
+ "arrow": {"interval": 100, "frames": "←↖↑↗→↘↓↙"},
174
+ "arrow2": {
175
+ "interval": 80,
176
+ "frames": ["⬆️ ", "↗️ ", "➡️ ", "↘️ ", "⬇️ ", "↙️ ", "⬅️ ", "↖️ "],
177
+ },
178
+ "arrow3": {
179
+ "interval": 120,
180
+ "frames": ["▹▹▹▹▹", "▸▹▹▹▹", "▹▸▹▹▹", "▹▹▸▹▹", "▹▹▹▸▹", "▹▹▹▹▸"],
181
+ },
182
+ "bouncingBar": {
183
+ "interval": 80,
184
+ "frames": [
185
+ "[ ]",
186
+ "[= ]",
187
+ "[== ]",
188
+ "[=== ]",
189
+ "[ ===]",
190
+ "[ ==]",
191
+ "[ =]",
192
+ "[ ]",
193
+ "[ =]",
194
+ "[ ==]",
195
+ "[ ===]",
196
+ "[====]",
197
+ "[=== ]",
198
+ "[== ]",
199
+ "[= ]",
200
+ ],
201
+ },
202
+ "bouncingBall": {
203
+ "interval": 80,
204
+ "frames": [
205
+ "( ● )",
206
+ "( ● )",
207
+ "( ● )",
208
+ "( ● )",
209
+ "( ●)",
210
+ "( ● )",
211
+ "( ● )",
212
+ "( ● )",
213
+ "( ● )",
214
+ "(● )",
215
+ ],
216
+ },
217
+ "smiley": {"interval": 200, "frames": ["😄 ", "😝 "]},
218
+ "monkey": {"interval": 300, "frames": ["🙈 ", "🙈 ", "🙉 ", "🙊 "]},
219
+ "hearts": {"interval": 100, "frames": ["💛 ", "💙 ", "💜 ", "💚 ", "❤️ "]},
220
+ "clock": {
221
+ "interval": 100,
222
+ "frames": [
223
+ "🕛 ",
224
+ "🕐 ",
225
+ "🕑 ",
226
+ "🕒 ",
227
+ "🕓 ",
228
+ "🕔 ",
229
+ "🕕 ",
230
+ "🕖 ",
231
+ "🕗 ",
232
+ "🕘 ",
233
+ "🕙 ",
234
+ "🕚 ",
235
+ ],
236
+ },
237
+ "earth": {"interval": 180, "frames": ["🌍 ", "🌎 ", "🌏 "]},
238
+ "material": {
239
+ "interval": 17,
240
+ "frames": [
241
+ "█▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁",
242
+ "██▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁",
243
+ "███▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁",
244
+ "████▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁",
245
+ "██████▁▁▁▁▁▁▁▁▁▁▁▁▁▁",
246
+ "██████▁▁▁▁▁▁▁▁▁▁▁▁▁▁",
247
+ "███████▁▁▁▁▁▁▁▁▁▁▁▁▁",
248
+ "████████▁▁▁▁▁▁▁▁▁▁▁▁",
249
+ "█████████▁▁▁▁▁▁▁▁▁▁▁",
250
+ "█████████▁▁▁▁▁▁▁▁▁▁▁",
251
+ "██████████▁▁▁▁▁▁▁▁▁▁",
252
+ "███████████▁▁▁▁▁▁▁▁▁",
253
+ "█████████████▁▁▁▁▁▁▁",
254
+ "██████████████▁▁▁▁▁▁",
255
+ "██████████████▁▁▁▁▁▁",
256
+ "▁██████████████▁▁▁▁▁",
257
+ "▁██████████████▁▁▁▁▁",
258
+ "▁██████████████▁▁▁▁▁",
259
+ "▁▁██████████████▁▁▁▁",
260
+ "▁▁▁██████████████▁▁▁",
261
+ "▁▁▁▁█████████████▁▁▁",
262
+ "▁▁▁▁██████████████▁▁",
263
+ "▁▁▁▁██████████████▁▁",
264
+ "▁▁▁▁▁██████████████▁",
265
+ "▁▁▁▁▁██████████████▁",
266
+ "▁▁▁▁▁██████████████▁",
267
+ "▁▁▁▁▁▁██████████████",
268
+ "▁▁▁▁▁▁██████████████",
269
+ "▁▁▁▁▁▁▁█████████████",
270
+ "▁▁▁▁▁▁▁█████████████",
271
+ "▁▁▁▁▁▁▁▁████████████",
272
+ "▁▁▁▁▁▁▁▁████████████",
273
+ "▁▁▁▁▁▁▁▁▁███████████",
274
+ "▁▁▁▁▁▁▁▁▁███████████",
275
+ "▁▁▁▁▁▁▁▁▁▁██████████",
276
+ "▁▁▁▁▁▁▁▁▁▁██████████",
277
+ "▁▁▁▁▁▁▁▁▁▁▁▁████████",
278
+ "▁▁▁▁▁▁▁▁▁▁▁▁▁███████",
279
+ "▁▁▁▁▁▁▁▁▁▁▁▁▁▁██████",
280
+ "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█████",
281
+ "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█████",
282
+ "█▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁████",
283
+ "██▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁███",
284
+ "██▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁███",
285
+ "███▁▁▁▁▁▁▁▁▁▁▁▁▁▁███",
286
+ "████▁▁▁▁▁▁▁▁▁▁▁▁▁▁██",
287
+ "█████▁▁▁▁▁▁▁▁▁▁▁▁▁▁█",
288
+ "█████▁▁▁▁▁▁▁▁▁▁▁▁▁▁█",
289
+ "██████▁▁▁▁▁▁▁▁▁▁▁▁▁█",
290
+ "████████▁▁▁▁▁▁▁▁▁▁▁▁",
291
+ "█████████▁▁▁▁▁▁▁▁▁▁▁",
292
+ "█████████▁▁▁▁▁▁▁▁▁▁▁",
293
+ "█████████▁▁▁▁▁▁▁▁▁▁▁",
294
+ "█████████▁▁▁▁▁▁▁▁▁▁▁",
295
+ "███████████▁▁▁▁▁▁▁▁▁",
296
+ "████████████▁▁▁▁▁▁▁▁",
297
+ "████████████▁▁▁▁▁▁▁▁",
298
+ "██████████████▁▁▁▁▁▁",
299
+ "██████████████▁▁▁▁▁▁",
300
+ "▁██████████████▁▁▁▁▁",
301
+ "▁██████████████▁▁▁▁▁",
302
+ "▁▁▁█████████████▁▁▁▁",
303
+ "▁▁▁▁▁████████████▁▁▁",
304
+ "▁▁▁▁▁████████████▁▁▁",
305
+ "▁▁▁▁▁▁███████████▁▁▁",
306
+ "▁▁▁▁▁▁▁▁█████████▁▁▁",
307
+ "▁▁▁▁▁▁▁▁█████████▁▁▁",
308
+ "▁▁▁▁▁▁▁▁▁█████████▁▁",
309
+ "▁▁▁▁▁▁▁▁▁█████████▁▁",
310
+ "▁▁▁▁▁▁▁▁▁▁█████████▁",
311
+ "▁▁▁▁▁▁▁▁▁▁▁████████▁",
312
+ "▁▁▁▁▁▁▁▁▁▁▁████████▁",
313
+ "▁▁▁▁▁▁▁▁▁▁▁▁███████▁",
314
+ "▁▁▁▁▁▁▁▁▁▁▁▁███████▁",
315
+ "▁▁▁▁▁▁▁▁▁▁▁▁▁███████",
316
+ "▁▁▁▁▁▁▁▁▁▁▁▁▁███████",
317
+ "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█████",
318
+ "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁████",
319
+ "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁████",
320
+ "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁████",
321
+ "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁███",
322
+ "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁███",
323
+ "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁██",
324
+ "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁██",
325
+ "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁██",
326
+ "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█",
327
+ "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█",
328
+ "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█",
329
+ "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁",
330
+ "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁",
331
+ "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁",
332
+ "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁",
333
+ ],
334
+ },
335
+ "moon": {
336
+ "interval": 80,
337
+ "frames": ["🌑 ", "🌒 ", "🌓 ", "🌔 ", "🌕 ", "🌖 ", "🌗 ", "🌘 "],
338
+ },
339
+ "runner": {"interval": 140, "frames": ["🚶 ", "🏃 "]},
340
+ "pong": {
341
+ "interval": 80,
342
+ "frames": [
343
+ "▐⠂ ▌",
344
+ "▐⠈ ▌",
345
+ "▐ ⠂ ▌",
346
+ "▐ ⠠ ▌",
347
+ "▐ ⡀ ▌",
348
+ "▐ ⠠ ▌",
349
+ "▐ ⠂ ▌",
350
+ "▐ ⠈ ▌",
351
+ "▐ ⠂ ▌",
352
+ "▐ ⠠ ▌",
353
+ "▐ ⡀ ▌",
354
+ "▐ ⠠ ▌",
355
+ "▐ ⠂ ▌",
356
+ "▐ ⠈ ▌",
357
+ "▐ ⠂▌",
358
+ "▐ ⠠▌",
359
+ "▐ ⡀▌",
360
+ "▐ ⠠ ▌",
361
+ "▐ ⠂ ▌",
362
+ "▐ ⠈ ▌",
363
+ "▐ ⠂ ▌",
364
+ "▐ ⠠ ▌",
365
+ "▐ ⡀ ▌",
366
+ "▐ ⠠ ▌",
367
+ "▐ ⠂ ▌",
368
+ "▐ ⠈ ▌",
369
+ "▐ ⠂ ▌",
370
+ "▐ ⠠ ▌",
371
+ "▐ ⡀ ▌",
372
+ "▐⠠ ▌",
373
+ ],
374
+ },
375
+ "shark": {
376
+ "interval": 120,
377
+ "frames": [
378
+ "▐|\\____________▌",
379
+ "▐_|\\___________▌",
380
+ "▐__|\\__________▌",
381
+ "▐___|\\_________▌",
382
+ "▐____|\\________▌",
383
+ "▐_____|\\_______▌",
384
+ "▐______|\\______▌",
385
+ "▐_______|\\_____▌",
386
+ "▐________|\\____▌",
387
+ "▐_________|\\___▌",
388
+ "▐__________|\\__▌",
389
+ "▐___________|\\_▌",
390
+ "▐____________|\\▌",
391
+ "▐____________/|▌",
392
+ "▐___________/|_▌",
393
+ "▐__________/|__▌",
394
+ "▐_________/|___▌",
395
+ "▐________/|____▌",
396
+ "▐_______/|_____▌",
397
+ "▐______/|______▌",
398
+ "▐_____/|_______▌",
399
+ "▐____/|________▌",
400
+ "▐___/|_________▌",
401
+ "▐__/|__________▌",
402
+ "▐_/|___________▌",
403
+ "▐/|____________▌",
404
+ ],
405
+ },
406
+ "dqpb": {"interval": 100, "frames": "dqpb"},
407
+ "weather": {
408
+ "interval": 100,
409
+ "frames": [
410
+ "☀️ ",
411
+ "☀️ ",
412
+ "☀️ ",
413
+ "🌤 ",
414
+ "⛅️ ",
415
+ "🌥 ",
416
+ "☁️ ",
417
+ "🌧 ",
418
+ "🌨 ",
419
+ "🌧 ",
420
+ "🌨 ",
421
+ "🌧 ",
422
+ "🌨 ",
423
+ "⛈ ",
424
+ "🌨 ",
425
+ "🌧 ",
426
+ "🌨 ",
427
+ "☁️ ",
428
+ "🌥 ",
429
+ "⛅️ ",
430
+ "🌤 ",
431
+ "☀️ ",
432
+ "☀️ ",
433
+ ],
434
+ },
435
+ "christmas": {"interval": 400, "frames": "🌲🎄"},
436
+ "grenade": {
437
+ "interval": 80,
438
+ "frames": [
439
+ "، ",
440
+ "′ ",
441
+ " ´ ",
442
+ " ‾ ",
443
+ " ⸌",
444
+ " ⸊",
445
+ " |",
446
+ " ⁎",
447
+ " ⁕",
448
+ " ෴ ",
449
+ " ⁓",
450
+ " ",
451
+ " ",
452
+ " ",
453
+ ],
454
+ },
455
+ "point": {"interval": 125, "frames": ["∙∙∙", "●∙∙", "∙●∙", "∙∙●", "∙∙∙"]},
456
+ "layer": {"interval": 150, "frames": "-=≡"},
457
+ "betaWave": {
458
+ "interval": 80,
459
+ "frames": [
460
+ "ρββββββ",
461
+ "βρβββββ",
462
+ "ββρββββ",
463
+ "βββρβββ",
464
+ "ββββρββ",
465
+ "βββββρβ",
466
+ "ββββββρ",
467
+ ],
468
+ },
469
+ "aesthetic": {
470
+ "interval": 80,
471
+ "frames": [
472
+ "▰▱▱▱▱▱▱",
473
+ "▰▰▱▱▱▱▱",
474
+ "▰▰▰▱▱▱▱",
475
+ "▰▰▰▰▱▱▱",
476
+ "▰▰▰▰▰▱▱",
477
+ "▰▰▰▰▰▰▱",
478
+ "▰▰▰▰▰▰▰",
479
+ "▰▱▱▱▱▱▱",
480
+ ],
481
+ },
482
+ }
llava/lib/python3.10/site-packages/pip/_vendor/rich/_stack.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List, TypeVar
2
+
3
+ T = TypeVar("T")
4
+
5
+
6
+ class Stack(List[T]):
7
+ """A small shim over builtin list."""
8
+
9
+ @property
10
+ def top(self) -> T:
11
+ """Get top of stack."""
12
+ return self[-1]
13
+
14
+ def push(self, item: T) -> None:
15
+ """Push an item on to the stack (append in stack nomenclature)."""
16
+ self.append(item)
llava/lib/python3.10/site-packages/pip/_vendor/rich/ansi.py ADDED
@@ -0,0 +1,241 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ import sys
3
+ from contextlib import suppress
4
+ from typing import Iterable, NamedTuple, Optional
5
+
6
+ from .color import Color
7
+ from .style import Style
8
+ from .text import Text
9
+
10
+ re_ansi = re.compile(
11
+ r"""
12
+ (?:\x1b[0-?])|
13
+ (?:\x1b\](.*?)\x1b\\)|
14
+ (?:\x1b([(@-Z\\-_]|\[[0-?]*[ -/]*[@-~]))
15
+ """,
16
+ re.VERBOSE,
17
+ )
18
+
19
+
20
+ class _AnsiToken(NamedTuple):
21
+ """Result of ansi tokenized string."""
22
+
23
+ plain: str = ""
24
+ sgr: Optional[str] = ""
25
+ osc: Optional[str] = ""
26
+
27
+
28
+ def _ansi_tokenize(ansi_text: str) -> Iterable[_AnsiToken]:
29
+ """Tokenize a string in to plain text and ANSI codes.
30
+
31
+ Args:
32
+ ansi_text (str): A String containing ANSI codes.
33
+
34
+ Yields:
35
+ AnsiToken: A named tuple of (plain, sgr, osc)
36
+ """
37
+
38
+ position = 0
39
+ sgr: Optional[str]
40
+ osc: Optional[str]
41
+ for match in re_ansi.finditer(ansi_text):
42
+ start, end = match.span(0)
43
+ osc, sgr = match.groups()
44
+ if start > position:
45
+ yield _AnsiToken(ansi_text[position:start])
46
+ if sgr:
47
+ if sgr == "(":
48
+ position = end + 1
49
+ continue
50
+ if sgr.endswith("m"):
51
+ yield _AnsiToken("", sgr[1:-1], osc)
52
+ else:
53
+ yield _AnsiToken("", sgr, osc)
54
+ position = end
55
+ if position < len(ansi_text):
56
+ yield _AnsiToken(ansi_text[position:])
57
+
58
+
59
+ SGR_STYLE_MAP = {
60
+ 1: "bold",
61
+ 2: "dim",
62
+ 3: "italic",
63
+ 4: "underline",
64
+ 5: "blink",
65
+ 6: "blink2",
66
+ 7: "reverse",
67
+ 8: "conceal",
68
+ 9: "strike",
69
+ 21: "underline2",
70
+ 22: "not dim not bold",
71
+ 23: "not italic",
72
+ 24: "not underline",
73
+ 25: "not blink",
74
+ 26: "not blink2",
75
+ 27: "not reverse",
76
+ 28: "not conceal",
77
+ 29: "not strike",
78
+ 30: "color(0)",
79
+ 31: "color(1)",
80
+ 32: "color(2)",
81
+ 33: "color(3)",
82
+ 34: "color(4)",
83
+ 35: "color(5)",
84
+ 36: "color(6)",
85
+ 37: "color(7)",
86
+ 39: "default",
87
+ 40: "on color(0)",
88
+ 41: "on color(1)",
89
+ 42: "on color(2)",
90
+ 43: "on color(3)",
91
+ 44: "on color(4)",
92
+ 45: "on color(5)",
93
+ 46: "on color(6)",
94
+ 47: "on color(7)",
95
+ 49: "on default",
96
+ 51: "frame",
97
+ 52: "encircle",
98
+ 53: "overline",
99
+ 54: "not frame not encircle",
100
+ 55: "not overline",
101
+ 90: "color(8)",
102
+ 91: "color(9)",
103
+ 92: "color(10)",
104
+ 93: "color(11)",
105
+ 94: "color(12)",
106
+ 95: "color(13)",
107
+ 96: "color(14)",
108
+ 97: "color(15)",
109
+ 100: "on color(8)",
110
+ 101: "on color(9)",
111
+ 102: "on color(10)",
112
+ 103: "on color(11)",
113
+ 104: "on color(12)",
114
+ 105: "on color(13)",
115
+ 106: "on color(14)",
116
+ 107: "on color(15)",
117
+ }
118
+
119
+
120
+ class AnsiDecoder:
121
+ """Translate ANSI code in to styled Text."""
122
+
123
+ def __init__(self) -> None:
124
+ self.style = Style.null()
125
+
126
+ def decode(self, terminal_text: str) -> Iterable[Text]:
127
+ """Decode ANSI codes in an iterable of lines.
128
+
129
+ Args:
130
+ lines (Iterable[str]): An iterable of lines of terminal output.
131
+
132
+ Yields:
133
+ Text: Marked up Text.
134
+ """
135
+ for line in terminal_text.splitlines():
136
+ yield self.decode_line(line)
137
+
138
+ def decode_line(self, line: str) -> Text:
139
+ """Decode a line containing ansi codes.
140
+
141
+ Args:
142
+ line (str): A line of terminal output.
143
+
144
+ Returns:
145
+ Text: A Text instance marked up according to ansi codes.
146
+ """
147
+ from_ansi = Color.from_ansi
148
+ from_rgb = Color.from_rgb
149
+ _Style = Style
150
+ text = Text()
151
+ append = text.append
152
+ line = line.rsplit("\r", 1)[-1]
153
+ for plain_text, sgr, osc in _ansi_tokenize(line):
154
+ if plain_text:
155
+ append(plain_text, self.style or None)
156
+ elif osc is not None:
157
+ if osc.startswith("8;"):
158
+ _params, semicolon, link = osc[2:].partition(";")
159
+ if semicolon:
160
+ self.style = self.style.update_link(link or None)
161
+ elif sgr is not None:
162
+ # Translate in to semi-colon separated codes
163
+ # Ignore invalid codes, because we want to be lenient
164
+ codes = [
165
+ min(255, int(_code) if _code else 0)
166
+ for _code in sgr.split(";")
167
+ if _code.isdigit() or _code == ""
168
+ ]
169
+ iter_codes = iter(codes)
170
+ for code in iter_codes:
171
+ if code == 0:
172
+ # reset
173
+ self.style = _Style.null()
174
+ elif code in SGR_STYLE_MAP:
175
+ # styles
176
+ self.style += _Style.parse(SGR_STYLE_MAP[code])
177
+ elif code == 38:
178
+ #  Foreground
179
+ with suppress(StopIteration):
180
+ color_type = next(iter_codes)
181
+ if color_type == 5:
182
+ self.style += _Style.from_color(
183
+ from_ansi(next(iter_codes))
184
+ )
185
+ elif color_type == 2:
186
+ self.style += _Style.from_color(
187
+ from_rgb(
188
+ next(iter_codes),
189
+ next(iter_codes),
190
+ next(iter_codes),
191
+ )
192
+ )
193
+ elif code == 48:
194
+ # Background
195
+ with suppress(StopIteration):
196
+ color_type = next(iter_codes)
197
+ if color_type == 5:
198
+ self.style += _Style.from_color(
199
+ None, from_ansi(next(iter_codes))
200
+ )
201
+ elif color_type == 2:
202
+ self.style += _Style.from_color(
203
+ None,
204
+ from_rgb(
205
+ next(iter_codes),
206
+ next(iter_codes),
207
+ next(iter_codes),
208
+ ),
209
+ )
210
+
211
+ return text
212
+
213
+
214
+ if sys.platform != "win32" and __name__ == "__main__": # pragma: no cover
215
+ import io
216
+ import os
217
+ import pty
218
+ import sys
219
+
220
+ decoder = AnsiDecoder()
221
+
222
+ stdout = io.BytesIO()
223
+
224
+ def read(fd: int) -> bytes:
225
+ data = os.read(fd, 1024)
226
+ stdout.write(data)
227
+ return data
228
+
229
+ pty.spawn(sys.argv[1:], read)
230
+
231
+ from .console import Console
232
+
233
+ console = Console(record=True)
234
+
235
+ stdout_result = stdout.getvalue().decode("utf-8")
236
+ print(stdout_result)
237
+
238
+ for line in decoder.decode(stdout_result):
239
+ console.print(line)
240
+
241
+ console.save_html("stdout.html")
llava/lib/python3.10/site-packages/pip/_vendor/rich/console.py ADDED
The diff for this file is too large to render. See raw diff
 
llava/lib/python3.10/site-packages/pip/_vendor/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
llava/lib/python3.10/site-packages/pip/_vendor/rich/containers.py ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from itertools import zip_longest
2
+ from typing import (
3
+ TYPE_CHECKING,
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)
llava/lib/python3.10/site-packages/pip/_vendor/rich/diagnose.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import platform
3
+
4
+ from pip._vendor.rich import inspect
5
+ from pip._vendor.rich.console import Console, get_windows_console_features
6
+ from pip._vendor.rich.panel import Panel
7
+ from pip._vendor.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
+ "TERM",
19
+ "COLORTERM",
20
+ "CLICOLOR",
21
+ "NO_COLOR",
22
+ "TERM_PROGRAM",
23
+ "COLUMNS",
24
+ "LINES",
25
+ "JUPYTER_COLUMNS",
26
+ "JUPYTER_LINES",
27
+ "JPY_PARENT_PID",
28
+ "VSCODE_VERBOSE_LOGGING",
29
+ )
30
+ env = {name: os.getenv(name) for name in env_names}
31
+ console.print(Panel.fit((Pretty(env)), title="[b]Environment Variables"))
32
+
33
+ console.print(f'platform="{platform.system()}"')
34
+
35
+
36
+ if __name__ == "__main__": # pragma: no cover
37
+ report()
llava/lib/python3.10/site-packages/pip/_vendor/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()
llava/lib/python3.10/site-packages/pip/_vendor/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
+ )
llava/lib/python3.10/site-packages/pip/_vendor/rich/logging.py ADDED
@@ -0,0 +1,297 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 pip._vendor.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: 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))
llava/lib/python3.10/site-packages/pip/_vendor/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 pip._vendor.rich import print
244
+ from pip._vendor.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)
llava/lib/python3.10/site-packages/pip/_vendor/rich/progress.py ADDED
@@ -0,0 +1,1715 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import io
2
+ import sys
3
+ import typing
4
+ import warnings
5
+ from abc import ABC, abstractmethod
6
+ from collections import deque
7
+ from dataclasses import dataclass, field
8
+ from datetime import timedelta
9
+ from io import RawIOBase, UnsupportedOperation
10
+ from math import ceil
11
+ from mmap import mmap
12
+ from operator import length_hint
13
+ from os import PathLike, stat
14
+ from threading import Event, RLock, Thread
15
+ from types import TracebackType
16
+ from typing import (
17
+ Any,
18
+ BinaryIO,
19
+ Callable,
20
+ ContextManager,
21
+ Deque,
22
+ Dict,
23
+ Generic,
24
+ Iterable,
25
+ List,
26
+ NamedTuple,
27
+ NewType,
28
+ Optional,
29
+ Sequence,
30
+ TextIO,
31
+ Tuple,
32
+ Type,
33
+ TypeVar,
34
+ Union,
35
+ )
36
+
37
+ if sys.version_info >= (3, 8):
38
+ from typing import Literal
39
+ else:
40
+ from pip._vendor.typing_extensions import Literal # pragma: no cover
41
+
42
+ if sys.version_info >= (3, 11):
43
+ from typing import Self
44
+ else:
45
+ from pip._vendor.typing_extensions import Self # pragma: no cover
46
+
47
+ from . import filesize, get_console
48
+ from .console import Console, Group, JustifyMethod, RenderableType
49
+ from .highlighter import Highlighter
50
+ from .jupyter import JupyterMixin
51
+ from .live import Live
52
+ from .progress_bar import ProgressBar
53
+ from .spinner import Spinner
54
+ from .style import StyleType
55
+ from .table import Column, Table
56
+ from .text import Text, TextType
57
+
58
+ TaskID = NewType("TaskID", int)
59
+
60
+ ProgressType = TypeVar("ProgressType")
61
+
62
+ GetTimeCallable = Callable[[], float]
63
+
64
+
65
+ _I = typing.TypeVar("_I", TextIO, BinaryIO)
66
+
67
+
68
+ class _TrackThread(Thread):
69
+ """A thread to periodically update progress."""
70
+
71
+ def __init__(self, progress: "Progress", task_id: "TaskID", update_period: float):
72
+ self.progress = progress
73
+ self.task_id = task_id
74
+ self.update_period = update_period
75
+ self.done = Event()
76
+
77
+ self.completed = 0
78
+ super().__init__(daemon=True)
79
+
80
+ def run(self) -> None:
81
+ task_id = self.task_id
82
+ advance = self.progress.advance
83
+ update_period = self.update_period
84
+ last_completed = 0
85
+ wait = self.done.wait
86
+ while not wait(update_period) and self.progress.live.is_started:
87
+ completed = self.completed
88
+ if last_completed != completed:
89
+ advance(task_id, completed - last_completed)
90
+ last_completed = completed
91
+
92
+ self.progress.update(self.task_id, completed=self.completed, refresh=True)
93
+
94
+ def __enter__(self) -> "_TrackThread":
95
+ self.start()
96
+ return self
97
+
98
+ def __exit__(
99
+ self,
100
+ exc_type: Optional[Type[BaseException]],
101
+ exc_val: Optional[BaseException],
102
+ exc_tb: Optional[TracebackType],
103
+ ) -> None:
104
+ self.done.set()
105
+ self.join()
106
+
107
+
108
+ def track(
109
+ sequence: Union[Sequence[ProgressType], Iterable[ProgressType]],
110
+ description: str = "Working...",
111
+ total: Optional[float] = None,
112
+ completed: int = 0,
113
+ auto_refresh: bool = True,
114
+ console: Optional[Console] = None,
115
+ transient: bool = False,
116
+ get_time: Optional[Callable[[], float]] = None,
117
+ refresh_per_second: float = 10,
118
+ style: StyleType = "bar.back",
119
+ complete_style: StyleType = "bar.complete",
120
+ finished_style: StyleType = "bar.finished",
121
+ pulse_style: StyleType = "bar.pulse",
122
+ update_period: float = 0.1,
123
+ disable: bool = False,
124
+ show_speed: bool = True,
125
+ ) -> Iterable[ProgressType]:
126
+ """Track progress by iterating over a sequence.
127
+
128
+ Args:
129
+ sequence (Iterable[ProgressType]): A sequence (must support "len") you wish to iterate over.
130
+ description (str, optional): Description of task show next to progress bar. Defaults to "Working".
131
+ total: (float, optional): Total number of steps. Default is len(sequence).
132
+ completed (int, optional): Number of steps completed so far. Defaults to 0.
133
+ auto_refresh (bool, optional): Automatic refresh, disable to force a refresh after each iteration. Default is True.
134
+ transient: (bool, optional): Clear the progress on exit. Defaults to False.
135
+ console (Console, optional): Console to write to. Default creates internal Console instance.
136
+ refresh_per_second (float): Number of times per second to refresh the progress information. Defaults to 10.
137
+ style (StyleType, optional): Style for the bar background. Defaults to "bar.back".
138
+ complete_style (StyleType, optional): Style for the completed bar. Defaults to "bar.complete".
139
+ finished_style (StyleType, optional): Style for a finished bar. Defaults to "bar.finished".
140
+ pulse_style (StyleType, optional): Style for pulsing bars. Defaults to "bar.pulse".
141
+ update_period (float, optional): Minimum time (in seconds) between calls to update(). Defaults to 0.1.
142
+ disable (bool, optional): Disable display of progress.
143
+ show_speed (bool, optional): Show speed if total isn't known. Defaults to True.
144
+ Returns:
145
+ Iterable[ProgressType]: An iterable of the values in the sequence.
146
+
147
+ """
148
+
149
+ columns: List["ProgressColumn"] = (
150
+ [TextColumn("[progress.description]{task.description}")] if description else []
151
+ )
152
+ columns.extend(
153
+ (
154
+ BarColumn(
155
+ style=style,
156
+ complete_style=complete_style,
157
+ finished_style=finished_style,
158
+ pulse_style=pulse_style,
159
+ ),
160
+ TaskProgressColumn(show_speed=show_speed),
161
+ TimeRemainingColumn(elapsed_when_finished=True),
162
+ )
163
+ )
164
+ progress = Progress(
165
+ *columns,
166
+ auto_refresh=auto_refresh,
167
+ console=console,
168
+ transient=transient,
169
+ get_time=get_time,
170
+ refresh_per_second=refresh_per_second or 10,
171
+ disable=disable,
172
+ )
173
+
174
+ with progress:
175
+ yield from progress.track(
176
+ sequence,
177
+ total=total,
178
+ completed=completed,
179
+ description=description,
180
+ update_period=update_period,
181
+ )
182
+
183
+
184
+ class _Reader(RawIOBase, BinaryIO):
185
+ """A reader that tracks progress while it's being read from."""
186
+
187
+ def __init__(
188
+ self,
189
+ handle: BinaryIO,
190
+ progress: "Progress",
191
+ task: TaskID,
192
+ close_handle: bool = True,
193
+ ) -> None:
194
+ self.handle = handle
195
+ self.progress = progress
196
+ self.task = task
197
+ self.close_handle = close_handle
198
+ self._closed = False
199
+
200
+ def __enter__(self) -> "_Reader":
201
+ self.handle.__enter__()
202
+ return self
203
+
204
+ def __exit__(
205
+ self,
206
+ exc_type: Optional[Type[BaseException]],
207
+ exc_val: Optional[BaseException],
208
+ exc_tb: Optional[TracebackType],
209
+ ) -> None:
210
+ self.close()
211
+
212
+ def __iter__(self) -> BinaryIO:
213
+ return self
214
+
215
+ def __next__(self) -> bytes:
216
+ line = next(self.handle)
217
+ self.progress.advance(self.task, advance=len(line))
218
+ return line
219
+
220
+ @property
221
+ def closed(self) -> bool:
222
+ return self._closed
223
+
224
+ def fileno(self) -> int:
225
+ return self.handle.fileno()
226
+
227
+ def isatty(self) -> bool:
228
+ return self.handle.isatty()
229
+
230
+ @property
231
+ def mode(self) -> str:
232
+ return self.handle.mode
233
+
234
+ @property
235
+ def name(self) -> str:
236
+ return self.handle.name
237
+
238
+ def readable(self) -> bool:
239
+ return self.handle.readable()
240
+
241
+ def seekable(self) -> bool:
242
+ return self.handle.seekable()
243
+
244
+ def writable(self) -> bool:
245
+ return False
246
+
247
+ def read(self, size: int = -1) -> bytes:
248
+ block = self.handle.read(size)
249
+ self.progress.advance(self.task, advance=len(block))
250
+ return block
251
+
252
+ def readinto(self, b: Union[bytearray, memoryview, mmap]): # type: ignore[no-untyped-def, override]
253
+ n = self.handle.readinto(b) # type: ignore[attr-defined]
254
+ self.progress.advance(self.task, advance=n)
255
+ return n
256
+
257
+ def readline(self, size: int = -1) -> bytes: # type: ignore[override]
258
+ line = self.handle.readline(size)
259
+ self.progress.advance(self.task, advance=len(line))
260
+ return line
261
+
262
+ def readlines(self, hint: int = -1) -> List[bytes]:
263
+ lines = self.handle.readlines(hint)
264
+ self.progress.advance(self.task, advance=sum(map(len, lines)))
265
+ return lines
266
+
267
+ def close(self) -> None:
268
+ if self.close_handle:
269
+ self.handle.close()
270
+ self._closed = True
271
+
272
+ def seek(self, offset: int, whence: int = 0) -> int:
273
+ pos = self.handle.seek(offset, whence)
274
+ self.progress.update(self.task, completed=pos)
275
+ return pos
276
+
277
+ def tell(self) -> int:
278
+ return self.handle.tell()
279
+
280
+ def write(self, s: Any) -> int:
281
+ raise UnsupportedOperation("write")
282
+
283
+ def writelines(self, lines: Iterable[Any]) -> None:
284
+ raise UnsupportedOperation("writelines")
285
+
286
+
287
+ class _ReadContext(ContextManager[_I], Generic[_I]):
288
+ """A utility class to handle a context for both a reader and a progress."""
289
+
290
+ def __init__(self, progress: "Progress", reader: _I) -> None:
291
+ self.progress = progress
292
+ self.reader: _I = reader
293
+
294
+ def __enter__(self) -> _I:
295
+ self.progress.start()
296
+ return self.reader.__enter__()
297
+
298
+ def __exit__(
299
+ self,
300
+ exc_type: Optional[Type[BaseException]],
301
+ exc_val: Optional[BaseException],
302
+ exc_tb: Optional[TracebackType],
303
+ ) -> None:
304
+ self.progress.stop()
305
+ self.reader.__exit__(exc_type, exc_val, exc_tb)
306
+
307
+
308
+ def wrap_file(
309
+ file: BinaryIO,
310
+ total: int,
311
+ *,
312
+ description: str = "Reading...",
313
+ auto_refresh: bool = True,
314
+ console: Optional[Console] = None,
315
+ transient: bool = False,
316
+ get_time: Optional[Callable[[], float]] = None,
317
+ refresh_per_second: float = 10,
318
+ style: StyleType = "bar.back",
319
+ complete_style: StyleType = "bar.complete",
320
+ finished_style: StyleType = "bar.finished",
321
+ pulse_style: StyleType = "bar.pulse",
322
+ disable: bool = False,
323
+ ) -> ContextManager[BinaryIO]:
324
+ """Read bytes from a file while tracking progress.
325
+
326
+ Args:
327
+ file (Union[str, PathLike[str], BinaryIO]): The path to the file to read, or a file-like object in binary mode.
328
+ total (int): Total number of bytes to read.
329
+ description (str, optional): Description of task show next to progress bar. Defaults to "Reading".
330
+ auto_refresh (bool, optional): Automatic refresh, disable to force a refresh after each iteration. Default is True.
331
+ transient: (bool, optional): Clear the progress on exit. Defaults to False.
332
+ console (Console, optional): Console to write to. Default creates internal Console instance.
333
+ refresh_per_second (float): Number of times per second to refresh the progress information. Defaults to 10.
334
+ style (StyleType, optional): Style for the bar background. Defaults to "bar.back".
335
+ complete_style (StyleType, optional): Style for the completed bar. Defaults to "bar.complete".
336
+ finished_style (StyleType, optional): Style for a finished bar. Defaults to "bar.finished".
337
+ pulse_style (StyleType, optional): Style for pulsing bars. Defaults to "bar.pulse".
338
+ disable (bool, optional): Disable display of progress.
339
+ Returns:
340
+ ContextManager[BinaryIO]: A context manager yielding a progress reader.
341
+
342
+ """
343
+
344
+ columns: List["ProgressColumn"] = (
345
+ [TextColumn("[progress.description]{task.description}")] if description else []
346
+ )
347
+ columns.extend(
348
+ (
349
+ BarColumn(
350
+ style=style,
351
+ complete_style=complete_style,
352
+ finished_style=finished_style,
353
+ pulse_style=pulse_style,
354
+ ),
355
+ DownloadColumn(),
356
+ TimeRemainingColumn(),
357
+ )
358
+ )
359
+ progress = Progress(
360
+ *columns,
361
+ auto_refresh=auto_refresh,
362
+ console=console,
363
+ transient=transient,
364
+ get_time=get_time,
365
+ refresh_per_second=refresh_per_second or 10,
366
+ disable=disable,
367
+ )
368
+
369
+ reader = progress.wrap_file(file, total=total, description=description)
370
+ return _ReadContext(progress, reader)
371
+
372
+
373
+ @typing.overload
374
+ def open(
375
+ file: Union[str, "PathLike[str]", bytes],
376
+ mode: Union[Literal["rt"], Literal["r"]],
377
+ buffering: int = -1,
378
+ encoding: Optional[str] = None,
379
+ errors: Optional[str] = None,
380
+ newline: Optional[str] = None,
381
+ *,
382
+ total: Optional[int] = None,
383
+ description: str = "Reading...",
384
+ auto_refresh: bool = True,
385
+ console: Optional[Console] = None,
386
+ transient: bool = False,
387
+ get_time: Optional[Callable[[], float]] = None,
388
+ refresh_per_second: float = 10,
389
+ style: StyleType = "bar.back",
390
+ complete_style: StyleType = "bar.complete",
391
+ finished_style: StyleType = "bar.finished",
392
+ pulse_style: StyleType = "bar.pulse",
393
+ disable: bool = False,
394
+ ) -> ContextManager[TextIO]:
395
+ pass
396
+
397
+
398
+ @typing.overload
399
+ def open(
400
+ file: Union[str, "PathLike[str]", bytes],
401
+ mode: Literal["rb"],
402
+ buffering: int = -1,
403
+ encoding: Optional[str] = None,
404
+ errors: Optional[str] = None,
405
+ newline: Optional[str] = None,
406
+ *,
407
+ total: Optional[int] = None,
408
+ description: str = "Reading...",
409
+ auto_refresh: bool = True,
410
+ console: Optional[Console] = None,
411
+ transient: bool = False,
412
+ get_time: Optional[Callable[[], float]] = None,
413
+ refresh_per_second: float = 10,
414
+ style: StyleType = "bar.back",
415
+ complete_style: StyleType = "bar.complete",
416
+ finished_style: StyleType = "bar.finished",
417
+ pulse_style: StyleType = "bar.pulse",
418
+ disable: bool = False,
419
+ ) -> ContextManager[BinaryIO]:
420
+ pass
421
+
422
+
423
+ def open(
424
+ file: Union[str, "PathLike[str]", bytes],
425
+ mode: Union[Literal["rb"], Literal["rt"], Literal["r"]] = "r",
426
+ buffering: int = -1,
427
+ encoding: Optional[str] = None,
428
+ errors: Optional[str] = None,
429
+ newline: Optional[str] = None,
430
+ *,
431
+ total: Optional[int] = None,
432
+ description: str = "Reading...",
433
+ auto_refresh: bool = True,
434
+ console: Optional[Console] = None,
435
+ transient: bool = False,
436
+ get_time: Optional[Callable[[], float]] = None,
437
+ refresh_per_second: float = 10,
438
+ style: StyleType = "bar.back",
439
+ complete_style: StyleType = "bar.complete",
440
+ finished_style: StyleType = "bar.finished",
441
+ pulse_style: StyleType = "bar.pulse",
442
+ disable: bool = False,
443
+ ) -> Union[ContextManager[BinaryIO], ContextManager[TextIO]]:
444
+ """Read bytes from a file while tracking progress.
445
+
446
+ Args:
447
+ path (Union[str, PathLike[str], BinaryIO]): The path to the file to read, or a file-like object in binary mode.
448
+ mode (str): The mode to use to open the file. Only supports "r", "rb" or "rt".
449
+ buffering (int): The buffering strategy to use, see :func:`io.open`.
450
+ encoding (str, optional): The encoding to use when reading in text mode, see :func:`io.open`.
451
+ errors (str, optional): The error handling strategy for decoding errors, see :func:`io.open`.
452
+ newline (str, optional): The strategy for handling newlines in text mode, see :func:`io.open`
453
+ 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.
454
+ description (str, optional): Description of task show next to progress bar. Defaults to "Reading".
455
+ auto_refresh (bool, optional): Automatic refresh, disable to force a refresh after each iteration. Default is True.
456
+ transient: (bool, optional): Clear the progress on exit. Defaults to False.
457
+ console (Console, optional): Console to write to. Default creates internal Console instance.
458
+ refresh_per_second (float): Number of times per second to refresh the progress information. Defaults to 10.
459
+ style (StyleType, optional): Style for the bar background. Defaults to "bar.back".
460
+ complete_style (StyleType, optional): Style for the completed bar. Defaults to "bar.complete".
461
+ finished_style (StyleType, optional): Style for a finished bar. Defaults to "bar.finished".
462
+ pulse_style (StyleType, optional): Style for pulsing bars. Defaults to "bar.pulse".
463
+ disable (bool, optional): Disable display of progress.
464
+ encoding (str, optional): The encoding to use when reading in text mode.
465
+
466
+ Returns:
467
+ ContextManager[BinaryIO]: A context manager yielding a progress reader.
468
+
469
+ """
470
+
471
+ columns: List["ProgressColumn"] = (
472
+ [TextColumn("[progress.description]{task.description}")] if description else []
473
+ )
474
+ columns.extend(
475
+ (
476
+ BarColumn(
477
+ style=style,
478
+ complete_style=complete_style,
479
+ finished_style=finished_style,
480
+ pulse_style=pulse_style,
481
+ ),
482
+ DownloadColumn(),
483
+ TimeRemainingColumn(),
484
+ )
485
+ )
486
+ progress = Progress(
487
+ *columns,
488
+ auto_refresh=auto_refresh,
489
+ console=console,
490
+ transient=transient,
491
+ get_time=get_time,
492
+ refresh_per_second=refresh_per_second or 10,
493
+ disable=disable,
494
+ )
495
+
496
+ reader = progress.open(
497
+ file,
498
+ mode=mode,
499
+ buffering=buffering,
500
+ encoding=encoding,
501
+ errors=errors,
502
+ newline=newline,
503
+ total=total,
504
+ description=description,
505
+ )
506
+ return _ReadContext(progress, reader) # type: ignore[return-value, type-var]
507
+
508
+
509
+ class ProgressColumn(ABC):
510
+ """Base class for a widget to use in progress display."""
511
+
512
+ max_refresh: Optional[float] = None
513
+
514
+ def __init__(self, table_column: Optional[Column] = None) -> None:
515
+ self._table_column = table_column
516
+ self._renderable_cache: Dict[TaskID, Tuple[float, RenderableType]] = {}
517
+ self._update_time: Optional[float] = None
518
+
519
+ def get_table_column(self) -> Column:
520
+ """Get a table column, used to build tasks table."""
521
+ return self._table_column or Column()
522
+
523
+ def __call__(self, task: "Task") -> RenderableType:
524
+ """Called by the Progress object to return a renderable for the given task.
525
+
526
+ Args:
527
+ task (Task): An object containing information regarding the task.
528
+
529
+ Returns:
530
+ RenderableType: Anything renderable (including str).
531
+ """
532
+ current_time = task.get_time()
533
+ if self.max_refresh is not None and not task.completed:
534
+ try:
535
+ timestamp, renderable = self._renderable_cache[task.id]
536
+ except KeyError:
537
+ pass
538
+ else:
539
+ if timestamp + self.max_refresh > current_time:
540
+ return renderable
541
+
542
+ renderable = self.render(task)
543
+ self._renderable_cache[task.id] = (current_time, renderable)
544
+ return renderable
545
+
546
+ @abstractmethod
547
+ def render(self, task: "Task") -> RenderableType:
548
+ """Should return a renderable object."""
549
+
550
+
551
+ class RenderableColumn(ProgressColumn):
552
+ """A column to insert an arbitrary column.
553
+
554
+ Args:
555
+ renderable (RenderableType, optional): Any renderable. Defaults to empty string.
556
+ """
557
+
558
+ def __init__(
559
+ self, renderable: RenderableType = "", *, table_column: Optional[Column] = None
560
+ ):
561
+ self.renderable = renderable
562
+ super().__init__(table_column=table_column)
563
+
564
+ def render(self, task: "Task") -> RenderableType:
565
+ return self.renderable
566
+
567
+
568
+ class SpinnerColumn(ProgressColumn):
569
+ """A column with a 'spinner' animation.
570
+
571
+ Args:
572
+ spinner_name (str, optional): Name of spinner animation. Defaults to "dots".
573
+ style (StyleType, optional): Style of spinner. Defaults to "progress.spinner".
574
+ speed (float, optional): Speed factor of spinner. Defaults to 1.0.
575
+ finished_text (TextType, optional): Text used when task is finished. Defaults to " ".
576
+ """
577
+
578
+ def __init__(
579
+ self,
580
+ spinner_name: str = "dots",
581
+ style: Optional[StyleType] = "progress.spinner",
582
+ speed: float = 1.0,
583
+ finished_text: TextType = " ",
584
+ table_column: Optional[Column] = None,
585
+ ):
586
+ self.spinner = Spinner(spinner_name, style=style, speed=speed)
587
+ self.finished_text = (
588
+ Text.from_markup(finished_text)
589
+ if isinstance(finished_text, str)
590
+ else finished_text
591
+ )
592
+ super().__init__(table_column=table_column)
593
+
594
+ def set_spinner(
595
+ self,
596
+ spinner_name: str,
597
+ spinner_style: Optional[StyleType] = "progress.spinner",
598
+ speed: float = 1.0,
599
+ ) -> None:
600
+ """Set a new spinner.
601
+
602
+ Args:
603
+ spinner_name (str): Spinner name, see python -m rich.spinner.
604
+ spinner_style (Optional[StyleType], optional): Spinner style. Defaults to "progress.spinner".
605
+ speed (float, optional): Speed factor of spinner. Defaults to 1.0.
606
+ """
607
+ self.spinner = Spinner(spinner_name, style=spinner_style, speed=speed)
608
+
609
+ def render(self, task: "Task") -> RenderableType:
610
+ text = (
611
+ self.finished_text
612
+ if task.finished
613
+ else self.spinner.render(task.get_time())
614
+ )
615
+ return text
616
+
617
+
618
+ class TextColumn(ProgressColumn):
619
+ """A column containing text."""
620
+
621
+ def __init__(
622
+ self,
623
+ text_format: str,
624
+ style: StyleType = "none",
625
+ justify: JustifyMethod = "left",
626
+ markup: bool = True,
627
+ highlighter: Optional[Highlighter] = None,
628
+ table_column: Optional[Column] = None,
629
+ ) -> None:
630
+ self.text_format = text_format
631
+ self.justify: JustifyMethod = justify
632
+ self.style = style
633
+ self.markup = markup
634
+ self.highlighter = highlighter
635
+ super().__init__(table_column=table_column or Column(no_wrap=True))
636
+
637
+ def render(self, task: "Task") -> Text:
638
+ _text = self.text_format.format(task=task)
639
+ if self.markup:
640
+ text = Text.from_markup(_text, style=self.style, justify=self.justify)
641
+ else:
642
+ text = Text(_text, style=self.style, justify=self.justify)
643
+ if self.highlighter:
644
+ self.highlighter.highlight(text)
645
+ return text
646
+
647
+
648
+ class BarColumn(ProgressColumn):
649
+ """Renders a visual progress bar.
650
+
651
+ Args:
652
+ bar_width (Optional[int], optional): Width of bar or None for full width. Defaults to 40.
653
+ style (StyleType, optional): Style for the bar background. Defaults to "bar.back".
654
+ complete_style (StyleType, optional): Style for the completed bar. Defaults to "bar.complete".
655
+ finished_style (StyleType, optional): Style for a finished bar. Defaults to "bar.finished".
656
+ pulse_style (StyleType, optional): Style for pulsing bars. Defaults to "bar.pulse".
657
+ """
658
+
659
+ def __init__(
660
+ self,
661
+ bar_width: Optional[int] = 40,
662
+ style: StyleType = "bar.back",
663
+ complete_style: StyleType = "bar.complete",
664
+ finished_style: StyleType = "bar.finished",
665
+ pulse_style: StyleType = "bar.pulse",
666
+ table_column: Optional[Column] = None,
667
+ ) -> None:
668
+ self.bar_width = bar_width
669
+ self.style = style
670
+ self.complete_style = complete_style
671
+ self.finished_style = finished_style
672
+ self.pulse_style = pulse_style
673
+ super().__init__(table_column=table_column)
674
+
675
+ def render(self, task: "Task") -> ProgressBar:
676
+ """Gets a progress bar widget for a task."""
677
+ return ProgressBar(
678
+ total=max(0, task.total) if task.total is not None else None,
679
+ completed=max(0, task.completed),
680
+ width=None if self.bar_width is None else max(1, self.bar_width),
681
+ pulse=not task.started,
682
+ animation_time=task.get_time(),
683
+ style=self.style,
684
+ complete_style=self.complete_style,
685
+ finished_style=self.finished_style,
686
+ pulse_style=self.pulse_style,
687
+ )
688
+
689
+
690
+ class TimeElapsedColumn(ProgressColumn):
691
+ """Renders time elapsed."""
692
+
693
+ def render(self, task: "Task") -> Text:
694
+ """Show time elapsed."""
695
+ elapsed = task.finished_time if task.finished else task.elapsed
696
+ if elapsed is None:
697
+ return Text("-:--:--", style="progress.elapsed")
698
+ delta = timedelta(seconds=max(0, int(elapsed)))
699
+ return Text(str(delta), style="progress.elapsed")
700
+
701
+
702
+ class TaskProgressColumn(TextColumn):
703
+ """Show task progress as a percentage.
704
+
705
+ Args:
706
+ text_format (str, optional): Format for percentage display. Defaults to "[progress.percentage]{task.percentage:>3.0f}%".
707
+ text_format_no_percentage (str, optional): Format if percentage is unknown. Defaults to "".
708
+ style (StyleType, optional): Style of output. Defaults to "none".
709
+ justify (JustifyMethod, optional): Text justification. Defaults to "left".
710
+ markup (bool, optional): Enable markup. Defaults to True.
711
+ highlighter (Optional[Highlighter], optional): Highlighter to apply to output. Defaults to None.
712
+ table_column (Optional[Column], optional): Table Column to use. Defaults to None.
713
+ show_speed (bool, optional): Show speed if total is unknown. Defaults to False.
714
+ """
715
+
716
+ def __init__(
717
+ self,
718
+ text_format: str = "[progress.percentage]{task.percentage:>3.0f}%",
719
+ text_format_no_percentage: str = "",
720
+ style: StyleType = "none",
721
+ justify: JustifyMethod = "left",
722
+ markup: bool = True,
723
+ highlighter: Optional[Highlighter] = None,
724
+ table_column: Optional[Column] = None,
725
+ show_speed: bool = False,
726
+ ) -> None:
727
+ self.text_format_no_percentage = text_format_no_percentage
728
+ self.show_speed = show_speed
729
+ super().__init__(
730
+ text_format=text_format,
731
+ style=style,
732
+ justify=justify,
733
+ markup=markup,
734
+ highlighter=highlighter,
735
+ table_column=table_column,
736
+ )
737
+
738
+ @classmethod
739
+ def render_speed(cls, speed: Optional[float]) -> Text:
740
+ """Render the speed in iterations per second.
741
+
742
+ Args:
743
+ task (Task): A Task object.
744
+
745
+ Returns:
746
+ Text: Text object containing the task speed.
747
+ """
748
+ if speed is None:
749
+ return Text("", style="progress.percentage")
750
+ unit, suffix = filesize.pick_unit_and_suffix(
751
+ int(speed),
752
+ ["", "×10³", "×10⁶", "×10⁹", "×10¹²"],
753
+ 1000,
754
+ )
755
+ data_speed = speed / unit
756
+ return Text(f"{data_speed:.1f}{suffix} it/s", style="progress.percentage")
757
+
758
+ def render(self, task: "Task") -> Text:
759
+ if task.total is None and self.show_speed:
760
+ return self.render_speed(task.finished_speed or task.speed)
761
+ text_format = (
762
+ self.text_format_no_percentage if task.total is None else self.text_format
763
+ )
764
+ _text = text_format.format(task=task)
765
+ if self.markup:
766
+ text = Text.from_markup(_text, style=self.style, justify=self.justify)
767
+ else:
768
+ text = Text(_text, style=self.style, justify=self.justify)
769
+ if self.highlighter:
770
+ self.highlighter.highlight(text)
771
+ return text
772
+
773
+
774
+ class TimeRemainingColumn(ProgressColumn):
775
+ """Renders estimated time remaining.
776
+
777
+ Args:
778
+ compact (bool, optional): Render MM:SS when time remaining is less than an hour. Defaults to False.
779
+ elapsed_when_finished (bool, optional): Render time elapsed when the task is finished. Defaults to False.
780
+ """
781
+
782
+ # Only refresh twice a second to prevent jitter
783
+ max_refresh = 0.5
784
+
785
+ def __init__(
786
+ self,
787
+ compact: bool = False,
788
+ elapsed_when_finished: bool = False,
789
+ table_column: Optional[Column] = None,
790
+ ):
791
+ self.compact = compact
792
+ self.elapsed_when_finished = elapsed_when_finished
793
+ super().__init__(table_column=table_column)
794
+
795
+ def render(self, task: "Task") -> Text:
796
+ """Show time remaining."""
797
+ if self.elapsed_when_finished and task.finished:
798
+ task_time = task.finished_time
799
+ style = "progress.elapsed"
800
+ else:
801
+ task_time = task.time_remaining
802
+ style = "progress.remaining"
803
+
804
+ if task.total is None:
805
+ return Text("", style=style)
806
+
807
+ if task_time is None:
808
+ return Text("--:--" if self.compact else "-:--:--", style=style)
809
+
810
+ # Based on https://github.com/tqdm/tqdm/blob/master/tqdm/std.py
811
+ minutes, seconds = divmod(int(task_time), 60)
812
+ hours, minutes = divmod(minutes, 60)
813
+
814
+ if self.compact and not hours:
815
+ formatted = f"{minutes:02d}:{seconds:02d}"
816
+ else:
817
+ formatted = f"{hours:d}:{minutes:02d}:{seconds:02d}"
818
+
819
+ return Text(formatted, style=style)
820
+
821
+
822
+ class FileSizeColumn(ProgressColumn):
823
+ """Renders completed filesize."""
824
+
825
+ def render(self, task: "Task") -> Text:
826
+ """Show data completed."""
827
+ data_size = filesize.decimal(int(task.completed))
828
+ return Text(data_size, style="progress.filesize")
829
+
830
+
831
+ class TotalFileSizeColumn(ProgressColumn):
832
+ """Renders total filesize."""
833
+
834
+ def render(self, task: "Task") -> Text:
835
+ """Show data completed."""
836
+ data_size = filesize.decimal(int(task.total)) if task.total is not None else ""
837
+ return Text(data_size, style="progress.filesize.total")
838
+
839
+
840
+ class MofNCompleteColumn(ProgressColumn):
841
+ """Renders completed count/total, e.g. ' 10/1000'.
842
+
843
+ Best for bounded tasks with int quantities.
844
+
845
+ Space pads the completed count so that progress length does not change as task progresses
846
+ past powers of 10.
847
+
848
+ Args:
849
+ separator (str, optional): Text to separate completed and total values. Defaults to "/".
850
+ """
851
+
852
+ def __init__(self, separator: str = "/", table_column: Optional[Column] = None):
853
+ self.separator = separator
854
+ super().__init__(table_column=table_column)
855
+
856
+ def render(self, task: "Task") -> Text:
857
+ """Show completed/total."""
858
+ completed = int(task.completed)
859
+ total = int(task.total) if task.total is not None else "?"
860
+ total_width = len(str(total))
861
+ return Text(
862
+ f"{completed:{total_width}d}{self.separator}{total}",
863
+ style="progress.download",
864
+ )
865
+
866
+
867
+ class DownloadColumn(ProgressColumn):
868
+ """Renders file size downloaded and total, e.g. '0.5/2.3 GB'.
869
+
870
+ Args:
871
+ binary_units (bool, optional): Use binary units, KiB, MiB etc. Defaults to False.
872
+ """
873
+
874
+ def __init__(
875
+ self, binary_units: bool = False, table_column: Optional[Column] = None
876
+ ) -> None:
877
+ self.binary_units = binary_units
878
+ super().__init__(table_column=table_column)
879
+
880
+ def render(self, task: "Task") -> Text:
881
+ """Calculate common unit for completed and total."""
882
+ completed = int(task.completed)
883
+
884
+ unit_and_suffix_calculation_base = (
885
+ int(task.total) if task.total is not None else completed
886
+ )
887
+ if self.binary_units:
888
+ unit, suffix = filesize.pick_unit_and_suffix(
889
+ unit_and_suffix_calculation_base,
890
+ ["bytes", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"],
891
+ 1024,
892
+ )
893
+ else:
894
+ unit, suffix = filesize.pick_unit_and_suffix(
895
+ unit_and_suffix_calculation_base,
896
+ ["bytes", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"],
897
+ 1000,
898
+ )
899
+ precision = 0 if unit == 1 else 1
900
+
901
+ completed_ratio = completed / unit
902
+ completed_str = f"{completed_ratio:,.{precision}f}"
903
+
904
+ if task.total is not None:
905
+ total = int(task.total)
906
+ total_ratio = total / unit
907
+ total_str = f"{total_ratio:,.{precision}f}"
908
+ else:
909
+ total_str = "?"
910
+
911
+ download_status = f"{completed_str}/{total_str} {suffix}"
912
+ download_text = Text(download_status, style="progress.download")
913
+ return download_text
914
+
915
+
916
+ class TransferSpeedColumn(ProgressColumn):
917
+ """Renders human readable transfer speed."""
918
+
919
+ def render(self, task: "Task") -> Text:
920
+ """Show data transfer speed."""
921
+ speed = task.finished_speed or task.speed
922
+ if speed is None:
923
+ return Text("?", style="progress.data.speed")
924
+ data_speed = filesize.decimal(int(speed))
925
+ return Text(f"{data_speed}/s", style="progress.data.speed")
926
+
927
+
928
+ class ProgressSample(NamedTuple):
929
+ """Sample of progress for a given time."""
930
+
931
+ timestamp: float
932
+ """Timestamp of sample."""
933
+ completed: float
934
+ """Number of steps completed."""
935
+
936
+
937
+ @dataclass
938
+ class Task:
939
+ """Information regarding a progress task.
940
+
941
+ This object should be considered read-only outside of the :class:`~Progress` class.
942
+
943
+ """
944
+
945
+ id: TaskID
946
+ """Task ID associated with this task (used in Progress methods)."""
947
+
948
+ description: str
949
+ """str: Description of the task."""
950
+
951
+ total: Optional[float]
952
+ """Optional[float]: Total number of steps in this task."""
953
+
954
+ completed: float
955
+ """float: Number of steps completed"""
956
+
957
+ _get_time: GetTimeCallable
958
+ """Callable to get the current time."""
959
+
960
+ finished_time: Optional[float] = None
961
+ """float: Time task was finished."""
962
+
963
+ visible: bool = True
964
+ """bool: Indicates if this task is visible in the progress display."""
965
+
966
+ fields: Dict[str, Any] = field(default_factory=dict)
967
+ """dict: Arbitrary fields passed in via Progress.update."""
968
+
969
+ start_time: Optional[float] = field(default=None, init=False, repr=False)
970
+ """Optional[float]: Time this task was started, or None if not started."""
971
+
972
+ stop_time: Optional[float] = field(default=None, init=False, repr=False)
973
+ """Optional[float]: Time this task was stopped, or None if not stopped."""
974
+
975
+ finished_speed: Optional[float] = None
976
+ """Optional[float]: The last speed for a finished task."""
977
+
978
+ _progress: Deque[ProgressSample] = field(
979
+ default_factory=lambda: deque(maxlen=1000), init=False, repr=False
980
+ )
981
+
982
+ _lock: RLock = field(repr=False, default_factory=RLock)
983
+ """Thread lock."""
984
+
985
+ def get_time(self) -> float:
986
+ """float: Get the current time, in seconds."""
987
+ return self._get_time()
988
+
989
+ @property
990
+ def started(self) -> bool:
991
+ """bool: Check if the task as started."""
992
+ return self.start_time is not None
993
+
994
+ @property
995
+ def remaining(self) -> Optional[float]:
996
+ """Optional[float]: Get the number of steps remaining, if a non-None total was set."""
997
+ if self.total is None:
998
+ return None
999
+ return self.total - self.completed
1000
+
1001
+ @property
1002
+ def elapsed(self) -> Optional[float]:
1003
+ """Optional[float]: Time elapsed since task was started, or ``None`` if the task hasn't started."""
1004
+ if self.start_time is None:
1005
+ return None
1006
+ if self.stop_time is not None:
1007
+ return self.stop_time - self.start_time
1008
+ return self.get_time() - self.start_time
1009
+
1010
+ @property
1011
+ def finished(self) -> bool:
1012
+ """Check if the task has finished."""
1013
+ return self.finished_time is not None
1014
+
1015
+ @property
1016
+ def percentage(self) -> float:
1017
+ """float: Get progress of task as a percentage. If a None total was set, returns 0"""
1018
+ if not self.total:
1019
+ return 0.0
1020
+ completed = (self.completed / self.total) * 100.0
1021
+ completed = min(100.0, max(0.0, completed))
1022
+ return completed
1023
+
1024
+ @property
1025
+ def speed(self) -> Optional[float]:
1026
+ """Optional[float]: Get the estimated speed in steps per second."""
1027
+ if self.start_time is None:
1028
+ return None
1029
+ with self._lock:
1030
+ progress = self._progress
1031
+ if not progress:
1032
+ return None
1033
+ total_time = progress[-1].timestamp - progress[0].timestamp
1034
+ if total_time == 0:
1035
+ return None
1036
+ iter_progress = iter(progress)
1037
+ next(iter_progress)
1038
+ total_completed = sum(sample.completed for sample in iter_progress)
1039
+ speed = total_completed / total_time
1040
+ return speed
1041
+
1042
+ @property
1043
+ def time_remaining(self) -> Optional[float]:
1044
+ """Optional[float]: Get estimated time to completion, or ``None`` if no data."""
1045
+ if self.finished:
1046
+ return 0.0
1047
+ speed = self.speed
1048
+ if not speed:
1049
+ return None
1050
+ remaining = self.remaining
1051
+ if remaining is None:
1052
+ return None
1053
+ estimate = ceil(remaining / speed)
1054
+ return estimate
1055
+
1056
+ def _reset(self) -> None:
1057
+ """Reset progress."""
1058
+ self._progress.clear()
1059
+ self.finished_time = None
1060
+ self.finished_speed = None
1061
+
1062
+
1063
+ class Progress(JupyterMixin):
1064
+ """Renders an auto-updating progress bar(s).
1065
+
1066
+ Args:
1067
+ console (Console, optional): Optional Console instance. Defaults to an internal Console instance writing to stdout.
1068
+ auto_refresh (bool, optional): Enable auto refresh. If disabled, you will need to call `refresh()`.
1069
+ 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.
1070
+ speed_estimate_period: (float, optional): Period (in seconds) used to calculate the speed estimate. Defaults to 30.
1071
+ transient: (bool, optional): Clear the progress on exit. Defaults to False.
1072
+ redirect_stdout: (bool, optional): Enable redirection of stdout, so ``print`` may be used. Defaults to True.
1073
+ redirect_stderr: (bool, optional): Enable redirection of stderr. Defaults to True.
1074
+ get_time: (Callable, optional): A callable that gets the current time, or None to use Console.get_time. Defaults to None.
1075
+ disable (bool, optional): Disable progress display. Defaults to False
1076
+ expand (bool, optional): Expand tasks table to fit width. Defaults to False.
1077
+ """
1078
+
1079
+ def __init__(
1080
+ self,
1081
+ *columns: Union[str, ProgressColumn],
1082
+ console: Optional[Console] = None,
1083
+ auto_refresh: bool = True,
1084
+ refresh_per_second: float = 10,
1085
+ speed_estimate_period: float = 30.0,
1086
+ transient: bool = False,
1087
+ redirect_stdout: bool = True,
1088
+ redirect_stderr: bool = True,
1089
+ get_time: Optional[GetTimeCallable] = None,
1090
+ disable: bool = False,
1091
+ expand: bool = False,
1092
+ ) -> None:
1093
+ assert refresh_per_second > 0, "refresh_per_second must be > 0"
1094
+ self._lock = RLock()
1095
+ self.columns = columns or self.get_default_columns()
1096
+ self.speed_estimate_period = speed_estimate_period
1097
+
1098
+ self.disable = disable
1099
+ self.expand = expand
1100
+ self._tasks: Dict[TaskID, Task] = {}
1101
+ self._task_index: TaskID = TaskID(0)
1102
+ self.live = Live(
1103
+ console=console or get_console(),
1104
+ auto_refresh=auto_refresh,
1105
+ refresh_per_second=refresh_per_second,
1106
+ transient=transient,
1107
+ redirect_stdout=redirect_stdout,
1108
+ redirect_stderr=redirect_stderr,
1109
+ get_renderable=self.get_renderable,
1110
+ )
1111
+ self.get_time = get_time or self.console.get_time
1112
+ self.print = self.console.print
1113
+ self.log = self.console.log
1114
+
1115
+ @classmethod
1116
+ def get_default_columns(cls) -> Tuple[ProgressColumn, ...]:
1117
+ """Get the default columns used for a new Progress instance:
1118
+ - a text column for the description (TextColumn)
1119
+ - the bar itself (BarColumn)
1120
+ - a text column showing completion percentage (TextColumn)
1121
+ - an estimated-time-remaining column (TimeRemainingColumn)
1122
+ If the Progress instance is created without passing a columns argument,
1123
+ the default columns defined here will be used.
1124
+
1125
+ You can also create a Progress instance using custom columns before
1126
+ and/or after the defaults, as in this example:
1127
+
1128
+ progress = Progress(
1129
+ SpinnerColumn(),
1130
+ *Progress.get_default_columns(),
1131
+ "Elapsed:",
1132
+ TimeElapsedColumn(),
1133
+ )
1134
+
1135
+ This code shows the creation of a Progress display, containing
1136
+ a spinner to the left, the default columns, and a labeled elapsed
1137
+ time column.
1138
+ """
1139
+ return (
1140
+ TextColumn("[progress.description]{task.description}"),
1141
+ BarColumn(),
1142
+ TaskProgressColumn(),
1143
+ TimeRemainingColumn(),
1144
+ )
1145
+
1146
+ @property
1147
+ def console(self) -> Console:
1148
+ return self.live.console
1149
+
1150
+ @property
1151
+ def tasks(self) -> List[Task]:
1152
+ """Get a list of Task instances."""
1153
+ with self._lock:
1154
+ return list(self._tasks.values())
1155
+
1156
+ @property
1157
+ def task_ids(self) -> List[TaskID]:
1158
+ """A list of task IDs."""
1159
+ with self._lock:
1160
+ return list(self._tasks.keys())
1161
+
1162
+ @property
1163
+ def finished(self) -> bool:
1164
+ """Check if all tasks have been completed."""
1165
+ with self._lock:
1166
+ if not self._tasks:
1167
+ return True
1168
+ return all(task.finished for task in self._tasks.values())
1169
+
1170
+ def start(self) -> None:
1171
+ """Start the progress display."""
1172
+ if not self.disable:
1173
+ self.live.start(refresh=True)
1174
+
1175
+ def stop(self) -> None:
1176
+ """Stop the progress display."""
1177
+ self.live.stop()
1178
+ if not self.console.is_interactive and not self.console.is_jupyter:
1179
+ self.console.print()
1180
+
1181
+ def __enter__(self) -> Self:
1182
+ self.start()
1183
+ return self
1184
+
1185
+ def __exit__(
1186
+ self,
1187
+ exc_type: Optional[Type[BaseException]],
1188
+ exc_val: Optional[BaseException],
1189
+ exc_tb: Optional[TracebackType],
1190
+ ) -> None:
1191
+ self.stop()
1192
+
1193
+ def track(
1194
+ self,
1195
+ sequence: Union[Iterable[ProgressType], Sequence[ProgressType]],
1196
+ total: Optional[float] = None,
1197
+ completed: int = 0,
1198
+ task_id: Optional[TaskID] = None,
1199
+ description: str = "Working...",
1200
+ update_period: float = 0.1,
1201
+ ) -> Iterable[ProgressType]:
1202
+ """Track progress by iterating over a sequence.
1203
+
1204
+ Args:
1205
+ sequence (Sequence[ProgressType]): A sequence of 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))
llava/lib/python3.10/site-packages/pip/_vendor/rich/py.typed ADDED
File without changes
llava/lib/python3.10/site-packages/pip/_vendor/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 pip._vendor.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)
llava/lib/python3.10/site-packages/pip/_vendor/rich/rule.py ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Union
2
+
3
+ from .align import AlignMethod
4
+ from .cells import cell_len, set_cell_size
5
+ from .console import Console, ConsoleOptions, RenderResult
6
+ from .jupyter import JupyterMixin
7
+ from .measure import Measurement
8
+ from .style import Style
9
+ from .text import Text
10
+
11
+
12
+ class Rule(JupyterMixin):
13
+ """A console renderable to draw a horizontal rule (line).
14
+
15
+ Args:
16
+ title (Union[str, Text], optional): Text to render in the rule. Defaults to "".
17
+ characters (str, optional): Character(s) used to draw the line. Defaults to "─".
18
+ style (StyleType, optional): Style of Rule. Defaults to "rule.line".
19
+ end (str, optional): Character at end of Rule. defaults to "\\\\n"
20
+ align (str, optional): How to align the title, one of "left", "center", or "right". Defaults to "center".
21
+ """
22
+
23
+ def __init__(
24
+ self,
25
+ title: Union[str, Text] = "",
26
+ *,
27
+ characters: str = "─",
28
+ style: Union[str, Style] = "rule.line",
29
+ end: str = "\n",
30
+ align: AlignMethod = "center",
31
+ ) -> None:
32
+ if cell_len(characters) < 1:
33
+ raise ValueError(
34
+ "'characters' argument must have a cell width of at least 1"
35
+ )
36
+ if align not in ("left", "center", "right"):
37
+ raise ValueError(
38
+ f'invalid value for align, expected "left", "center", "right" (not {align!r})'
39
+ )
40
+ self.title = title
41
+ self.characters = characters
42
+ self.style = style
43
+ self.end = end
44
+ self.align = align
45
+
46
+ def __repr__(self) -> str:
47
+ return f"Rule({self.title!r}, {self.characters!r})"
48
+
49
+ def __rich_console__(
50
+ self, console: Console, options: ConsoleOptions
51
+ ) -> RenderResult:
52
+ width = options.max_width
53
+
54
+ characters = (
55
+ "-"
56
+ if (options.ascii_only and not self.characters.isascii())
57
+ else self.characters
58
+ )
59
+
60
+ chars_len = cell_len(characters)
61
+ if not self.title:
62
+ yield self._rule_line(chars_len, width)
63
+ return
64
+
65
+ if isinstance(self.title, Text):
66
+ title_text = self.title
67
+ else:
68
+ title_text = console.render_str(self.title, style="rule.text")
69
+
70
+ title_text.plain = title_text.plain.replace("\n", " ")
71
+ title_text.expand_tabs()
72
+
73
+ required_space = 4 if self.align == "center" else 2
74
+ truncate_width = max(0, width - required_space)
75
+ if not truncate_width:
76
+ yield self._rule_line(chars_len, width)
77
+ return
78
+
79
+ rule_text = Text(end=self.end)
80
+ if self.align == "center":
81
+ title_text.truncate(truncate_width, overflow="ellipsis")
82
+ side_width = (width - cell_len(title_text.plain)) // 2
83
+ left = Text(characters * (side_width // chars_len + 1))
84
+ left.truncate(side_width - 1)
85
+ right_length = width - cell_len(left.plain) - cell_len(title_text.plain)
86
+ right = Text(characters * (side_width // chars_len + 1))
87
+ right.truncate(right_length)
88
+ rule_text.append(left.plain + " ", self.style)
89
+ rule_text.append(title_text)
90
+ rule_text.append(" " + right.plain, self.style)
91
+ elif self.align == "left":
92
+ title_text.truncate(truncate_width, overflow="ellipsis")
93
+ rule_text.append(title_text)
94
+ rule_text.append(" ")
95
+ rule_text.append(characters * (width - rule_text.cell_len), self.style)
96
+ elif self.align == "right":
97
+ title_text.truncate(truncate_width, overflow="ellipsis")
98
+ rule_text.append(characters * (width - title_text.cell_len - 1), self.style)
99
+ rule_text.append(" ")
100
+ rule_text.append(title_text)
101
+
102
+ rule_text.plain = set_cell_size(rule_text.plain, width)
103
+ yield rule_text
104
+
105
+ def _rule_line(self, chars_len: int, width: int) -> Text:
106
+ rule_text = Text(self.characters * ((width // chars_len) + 1), self.style)
107
+ rule_text.truncate(width)
108
+ rule_text.plain = set_cell_size(rule_text.plain, width)
109
+ return rule_text
110
+
111
+ def __rich_measure__(
112
+ self, console: Console, options: ConsoleOptions
113
+ ) -> Measurement:
114
+ return Measurement(1, 1)
115
+
116
+
117
+ if __name__ == "__main__": # pragma: no cover
118
+ import sys
119
+
120
+ from pip._vendor.rich.console import Console
121
+
122
+ try:
123
+ text = sys.argv[1]
124
+ except IndexError:
125
+ text = "Hello, World"
126
+ console = Console()
127
+ console.print(Rule(title=text))
128
+
129
+ console = Console()
130
+ console.print(Rule("foo"), width=4)
llava/lib/python3.10/site-packages/pip/_vendor/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 pip._vendor.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
llava/lib/python3.10/site-packages/pip/_vendor/rich/spinner.py ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import cast, List, Optional, TYPE_CHECKING, Union
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, RenderResult, RenderableType
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 .columns import Columns
121
+ from .panel import Panel
122
+ from .live import Live
123
+
124
+ all_spinners = Columns(
125
+ [
126
+ Spinner(spinner_name, text=Text(repr(spinner_name), style="green"))
127
+ for spinner_name in sorted(SPINNERS.keys())
128
+ ],
129
+ column_first=True,
130
+ expand=True,
131
+ )
132
+
133
+ with Live(
134
+ Panel(all_spinners, title="Spinners", border_style="blue"),
135
+ refresh_per_second=20,
136
+ ) as live:
137
+ while True:
138
+ sleep(0.1)
llava/lib/python3.10/site-packages/pip/_vendor/rich/syntax.py ADDED
@@ -0,0 +1,966 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os.path
2
+ import re
3
+ import sys
4
+ import textwrap
5
+ from abc import ABC, abstractmethod
6
+ from pathlib import Path
7
+ from typing import (
8
+ Any,
9
+ Dict,
10
+ Iterable,
11
+ List,
12
+ NamedTuple,
13
+ Optional,
14
+ Sequence,
15
+ Set,
16
+ Tuple,
17
+ Type,
18
+ Union,
19
+ )
20
+
21
+ from pip._vendor.pygments.lexer import Lexer
22
+ from pip._vendor.pygments.lexers import get_lexer_by_name, guess_lexer_for_filename
23
+ from pip._vendor.pygments.style import Style as PygmentsStyle
24
+ from pip._vendor.pygments.styles import get_style_by_name
25
+ from pip._vendor.pygments.token import (
26
+ Comment,
27
+ Error,
28
+ Generic,
29
+ Keyword,
30
+ Name,
31
+ Number,
32
+ Operator,
33
+ String,
34
+ Token,
35
+ Whitespace,
36
+ )
37
+ from pip._vendor.pygments.util import ClassNotFound
38
+
39
+ from pip._vendor.rich.containers import Lines
40
+ from pip._vendor.rich.padding import Padding, PaddingDimensions
41
+
42
+ from ._loop import loop_first
43
+ from .cells import cell_len
44
+ from .color import Color, blend_rgb
45
+ from .console import Console, ConsoleOptions, JustifyMethod, RenderResult
46
+ from .jupyter import JupyterMixin
47
+ from .measure import Measurement
48
+ from .segment import Segment, Segments
49
+ from .style import Style, StyleType
50
+ from .text import Text
51
+
52
+ TokenType = Tuple[str, ...]
53
+
54
+ WINDOWS = sys.platform == "win32"
55
+ DEFAULT_THEME = "monokai"
56
+
57
+ # The following styles are based on https://github.com/pygments/pygments/blob/master/pygments/formatters/terminal.py
58
+ # A few modifications were made
59
+
60
+ ANSI_LIGHT: Dict[TokenType, Style] = {
61
+ Token: Style(),
62
+ Whitespace: Style(color="white"),
63
+ Comment: Style(dim=True),
64
+ Comment.Preproc: Style(color="cyan"),
65
+ Keyword: Style(color="blue"),
66
+ Keyword.Type: Style(color="cyan"),
67
+ Operator.Word: Style(color="magenta"),
68
+ Name.Builtin: Style(color="cyan"),
69
+ Name.Function: Style(color="green"),
70
+ Name.Namespace: Style(color="cyan", underline=True),
71
+ Name.Class: Style(color="green", underline=True),
72
+ Name.Exception: Style(color="cyan"),
73
+ Name.Decorator: Style(color="magenta", bold=True),
74
+ Name.Variable: Style(color="red"),
75
+ Name.Constant: Style(color="red"),
76
+ Name.Attribute: Style(color="cyan"),
77
+ Name.Tag: Style(color="bright_blue"),
78
+ String: Style(color="yellow"),
79
+ Number: Style(color="blue"),
80
+ Generic.Deleted: Style(color="bright_red"),
81
+ Generic.Inserted: Style(color="green"),
82
+ Generic.Heading: Style(bold=True),
83
+ Generic.Subheading: Style(color="magenta", bold=True),
84
+ Generic.Prompt: Style(bold=True),
85
+ Generic.Error: Style(color="bright_red"),
86
+ Error: Style(color="red", underline=True),
87
+ }
88
+
89
+ ANSI_DARK: Dict[TokenType, Style] = {
90
+ Token: Style(),
91
+ Whitespace: Style(color="bright_black"),
92
+ Comment: Style(dim=True),
93
+ Comment.Preproc: Style(color="bright_cyan"),
94
+ Keyword: Style(color="bright_blue"),
95
+ Keyword.Type: Style(color="bright_cyan"),
96
+ Operator.Word: Style(color="bright_magenta"),
97
+ Name.Builtin: Style(color="bright_cyan"),
98
+ Name.Function: Style(color="bright_green"),
99
+ Name.Namespace: Style(color="bright_cyan", underline=True),
100
+ Name.Class: Style(color="bright_green", underline=True),
101
+ Name.Exception: Style(color="bright_cyan"),
102
+ Name.Decorator: Style(color="bright_magenta", bold=True),
103
+ Name.Variable: Style(color="bright_red"),
104
+ Name.Constant: Style(color="bright_red"),
105
+ Name.Attribute: Style(color="bright_cyan"),
106
+ Name.Tag: Style(color="bright_blue"),
107
+ String: Style(color="yellow"),
108
+ Number: Style(color="bright_blue"),
109
+ Generic.Deleted: Style(color="bright_red"),
110
+ Generic.Inserted: Style(color="bright_green"),
111
+ Generic.Heading: Style(bold=True),
112
+ Generic.Subheading: Style(color="bright_magenta", bold=True),
113
+ Generic.Prompt: Style(bold=True),
114
+ Generic.Error: Style(color="bright_red"),
115
+ Error: Style(color="red", underline=True),
116
+ }
117
+
118
+ RICH_SYNTAX_THEMES = {"ansi_light": ANSI_LIGHT, "ansi_dark": ANSI_DARK}
119
+ NUMBERS_COLUMN_DEFAULT_PADDING = 2
120
+
121
+
122
+ class SyntaxTheme(ABC):
123
+ """Base class for a syntax theme."""
124
+
125
+ @abstractmethod
126
+ def get_style_for_token(self, token_type: TokenType) -> Style:
127
+ """Get a style for a given Pygments token."""
128
+ raise NotImplementedError # pragma: no cover
129
+
130
+ @abstractmethod
131
+ def get_background_style(self) -> Style:
132
+ """Get the background color."""
133
+ raise NotImplementedError # pragma: no cover
134
+
135
+
136
+ class PygmentsSyntaxTheme(SyntaxTheme):
137
+ """Syntax theme that delegates to Pygments theme."""
138
+
139
+ def __init__(self, theme: Union[str, Type[PygmentsStyle]]) -> None:
140
+ self._style_cache: Dict[TokenType, Style] = {}
141
+ if isinstance(theme, str):
142
+ try:
143
+ self._pygments_style_class = get_style_by_name(theme)
144
+ except ClassNotFound:
145
+ self._pygments_style_class = get_style_by_name("default")
146
+ else:
147
+ self._pygments_style_class = theme
148
+
149
+ self._background_color = self._pygments_style_class.background_color
150
+ self._background_style = Style(bgcolor=self._background_color)
151
+
152
+ def get_style_for_token(self, token_type: TokenType) -> Style:
153
+ """Get a style from a Pygments class."""
154
+ try:
155
+ return self._style_cache[token_type]
156
+ except KeyError:
157
+ try:
158
+ pygments_style = self._pygments_style_class.style_for_token(token_type)
159
+ except KeyError:
160
+ style = Style.null()
161
+ else:
162
+ color = pygments_style["color"]
163
+ bgcolor = pygments_style["bgcolor"]
164
+ style = Style(
165
+ color="#" + color if color else "#000000",
166
+ bgcolor="#" + bgcolor if bgcolor else self._background_color,
167
+ bold=pygments_style["bold"],
168
+ italic=pygments_style["italic"],
169
+ underline=pygments_style["underline"],
170
+ )
171
+ self._style_cache[token_type] = style
172
+ return style
173
+
174
+ def get_background_style(self) -> Style:
175
+ return self._background_style
176
+
177
+
178
+ class ANSISyntaxTheme(SyntaxTheme):
179
+ """Syntax theme to use standard colors."""
180
+
181
+ def __init__(self, style_map: Dict[TokenType, Style]) -> None:
182
+ self.style_map = style_map
183
+ self._missing_style = Style.null()
184
+ self._background_style = Style.null()
185
+ self._style_cache: Dict[TokenType, Style] = {}
186
+
187
+ def get_style_for_token(self, token_type: TokenType) -> Style:
188
+ """Look up style in the style map."""
189
+ try:
190
+ return self._style_cache[token_type]
191
+ except KeyError:
192
+ # Styles form a hierarchy
193
+ # We need to go from most to least specific
194
+ # e.g. ("foo", "bar", "baz") to ("foo", "bar") to ("foo",)
195
+ get_style = self.style_map.get
196
+ token = tuple(token_type)
197
+ style = self._missing_style
198
+ while token:
199
+ _style = get_style(token)
200
+ if _style is not None:
201
+ style = _style
202
+ break
203
+ token = token[:-1]
204
+ self._style_cache[token_type] = style
205
+ return style
206
+
207
+ def get_background_style(self) -> Style:
208
+ return self._background_style
209
+
210
+
211
+ SyntaxPosition = Tuple[int, int]
212
+
213
+
214
+ class _SyntaxHighlightRange(NamedTuple):
215
+ """
216
+ A range to highlight in a Syntax object.
217
+ `start` and `end` are 2-integers tuples, where the first integer is the line number
218
+ (starting from 1) and the second integer is the column index (starting from 0).
219
+ """
220
+
221
+ style: StyleType
222
+ start: SyntaxPosition
223
+ end: SyntaxPosition
224
+ style_before: bool = False
225
+
226
+
227
+ class Syntax(JupyterMixin):
228
+ """Construct a Syntax object to render syntax highlighted code.
229
+
230
+ Args:
231
+ code (str): Code to highlight.
232
+ lexer (Lexer | str): Lexer to use (see https://pygments.org/docs/lexers/)
233
+ theme (str, optional): Color theme, aka Pygments style (see https://pygments.org/docs/styles/#getting-a-list-of-available-styles). Defaults to "monokai".
234
+ dedent (bool, optional): Enable stripping of initial whitespace. Defaults to False.
235
+ line_numbers (bool, optional): Enable rendering of line numbers. Defaults to False.
236
+ start_line (int, optional): Starting number for line numbers. Defaults to 1.
237
+ line_range (Tuple[int | None, int | None], optional): If given should be a tuple of the start and end line to render.
238
+ A value of None in the tuple indicates the range is open in that direction.
239
+ highlight_lines (Set[int]): A set of line numbers to highlight.
240
+ code_width: Width of code to render (not including line numbers), or ``None`` to use all available width.
241
+ tab_size (int, optional): Size of tabs. Defaults to 4.
242
+ word_wrap (bool, optional): Enable word wrapping.
243
+ background_color (str, optional): Optional background color, or None to use theme color. Defaults to None.
244
+ indent_guides (bool, optional): Show indent guides. Defaults to False.
245
+ padding (PaddingDimensions): Padding to apply around the syntax. Defaults to 0 (no padding).
246
+ """
247
+
248
+ _pygments_style_class: Type[PygmentsStyle]
249
+ _theme: SyntaxTheme
250
+
251
+ @classmethod
252
+ def get_theme(cls, name: Union[str, SyntaxTheme]) -> SyntaxTheme:
253
+ """Get a syntax theme instance."""
254
+ if isinstance(name, SyntaxTheme):
255
+ return name
256
+ theme: SyntaxTheme
257
+ if name in RICH_SYNTAX_THEMES:
258
+ theme = ANSISyntaxTheme(RICH_SYNTAX_THEMES[name])
259
+ else:
260
+ theme = PygmentsSyntaxTheme(name)
261
+ return theme
262
+
263
+ def __init__(
264
+ self,
265
+ code: str,
266
+ lexer: Union[Lexer, str],
267
+ *,
268
+ theme: Union[str, SyntaxTheme] = DEFAULT_THEME,
269
+ dedent: bool = False,
270
+ line_numbers: bool = False,
271
+ start_line: int = 1,
272
+ line_range: Optional[Tuple[Optional[int], Optional[int]]] = None,
273
+ highlight_lines: Optional[Set[int]] = None,
274
+ code_width: Optional[int] = None,
275
+ tab_size: int = 4,
276
+ word_wrap: bool = False,
277
+ background_color: Optional[str] = None,
278
+ indent_guides: bool = False,
279
+ padding: PaddingDimensions = 0,
280
+ ) -> None:
281
+ self.code = code
282
+ self._lexer = lexer
283
+ self.dedent = dedent
284
+ self.line_numbers = line_numbers
285
+ self.start_line = start_line
286
+ self.line_range = line_range
287
+ self.highlight_lines = highlight_lines or set()
288
+ self.code_width = code_width
289
+ self.tab_size = tab_size
290
+ self.word_wrap = word_wrap
291
+ self.background_color = background_color
292
+ self.background_style = (
293
+ Style(bgcolor=background_color) if background_color else Style()
294
+ )
295
+ self.indent_guides = indent_guides
296
+ self.padding = padding
297
+
298
+ self._theme = self.get_theme(theme)
299
+ self._stylized_ranges: List[_SyntaxHighlightRange] = []
300
+
301
+ @classmethod
302
+ def from_path(
303
+ cls,
304
+ path: str,
305
+ encoding: str = "utf-8",
306
+ lexer: Optional[Union[Lexer, str]] = None,
307
+ theme: Union[str, SyntaxTheme] = DEFAULT_THEME,
308
+ dedent: bool = False,
309
+ line_numbers: bool = False,
310
+ line_range: Optional[Tuple[int, int]] = None,
311
+ start_line: int = 1,
312
+ highlight_lines: Optional[Set[int]] = None,
313
+ code_width: Optional[int] = None,
314
+ tab_size: int = 4,
315
+ word_wrap: bool = False,
316
+ background_color: Optional[str] = None,
317
+ indent_guides: bool = False,
318
+ padding: PaddingDimensions = 0,
319
+ ) -> "Syntax":
320
+ """Construct a Syntax object from a file.
321
+
322
+ Args:
323
+ path (str): Path to file to highlight.
324
+ encoding (str): Encoding of file.
325
+ lexer (str | Lexer, optional): Lexer to use. If None, lexer will be auto-detected from path/file content.
326
+ theme (str, optional): Color theme, aka Pygments style (see https://pygments.org/docs/styles/#getting-a-list-of-available-styles). Defaults to "emacs".
327
+ dedent (bool, optional): Enable stripping of initial whitespace. Defaults to True.
328
+ line_numbers (bool, optional): Enable rendering of line numbers. Defaults to False.
329
+ start_line (int, optional): Starting number for line numbers. Defaults to 1.
330
+ line_range (Tuple[int, int], optional): If given should be a tuple of the start and end line to render.
331
+ highlight_lines (Set[int]): A set of line numbers to highlight.
332
+ code_width: Width of code to render (not including line numbers), or ``None`` to use all available width.
333
+ tab_size (int, optional): Size of tabs. Defaults to 4.
334
+ word_wrap (bool, optional): Enable word wrapping of code.
335
+ background_color (str, optional): Optional background color, or None to use theme color. Defaults to None.
336
+ indent_guides (bool, optional): Show indent guides. Defaults to False.
337
+ padding (PaddingDimensions): Padding to apply around the syntax. Defaults to 0 (no padding).
338
+
339
+ Returns:
340
+ [Syntax]: A Syntax object that may be printed to the console
341
+ """
342
+ code = Path(path).read_text(encoding=encoding)
343
+
344
+ if not lexer:
345
+ lexer = cls.guess_lexer(path, code=code)
346
+
347
+ return cls(
348
+ code,
349
+ lexer,
350
+ theme=theme,
351
+ dedent=dedent,
352
+ line_numbers=line_numbers,
353
+ line_range=line_range,
354
+ start_line=start_line,
355
+ highlight_lines=highlight_lines,
356
+ code_width=code_width,
357
+ tab_size=tab_size,
358
+ word_wrap=word_wrap,
359
+ background_color=background_color,
360
+ indent_guides=indent_guides,
361
+ padding=padding,
362
+ )
363
+
364
+ @classmethod
365
+ def guess_lexer(cls, path: str, code: Optional[str] = None) -> str:
366
+ """Guess the alias of the Pygments lexer to use based on a path and an optional string of code.
367
+ If code is supplied, it will use a combination of the code and the filename to determine the
368
+ best lexer to use. For example, if the file is ``index.html`` and the file contains Django
369
+ templating syntax, then "html+django" will be returned. If the file is ``index.html``, and no
370
+ templating language is used, the "html" lexer will be used. If no string of code
371
+ is supplied, the lexer will be chosen based on the file extension..
372
+
373
+ Args:
374
+ path (AnyStr): The path to the file containing the code you wish to know the lexer for.
375
+ code (str, optional): Optional string of code that will be used as a fallback if no lexer
376
+ is found for the supplied path.
377
+
378
+ Returns:
379
+ str: The name of the Pygments lexer that best matches the supplied path/code.
380
+ """
381
+ lexer: Optional[Lexer] = None
382
+ lexer_name = "default"
383
+ if code:
384
+ try:
385
+ lexer = guess_lexer_for_filename(path, code)
386
+ except ClassNotFound:
387
+ pass
388
+
389
+ if not lexer:
390
+ try:
391
+ _, ext = os.path.splitext(path)
392
+ if ext:
393
+ extension = ext.lstrip(".").lower()
394
+ lexer = get_lexer_by_name(extension)
395
+ except ClassNotFound:
396
+ pass
397
+
398
+ if lexer:
399
+ if lexer.aliases:
400
+ lexer_name = lexer.aliases[0]
401
+ else:
402
+ lexer_name = lexer.name
403
+
404
+ return lexer_name
405
+
406
+ def _get_base_style(self) -> Style:
407
+ """Get the base style."""
408
+ default_style = self._theme.get_background_style() + self.background_style
409
+ return default_style
410
+
411
+ def _get_token_color(self, token_type: TokenType) -> Optional[Color]:
412
+ """Get a color (if any) for the given token.
413
+
414
+ Args:
415
+ token_type (TokenType): A token type tuple from Pygments.
416
+
417
+ Returns:
418
+ Optional[Color]: Color from theme, or None for no color.
419
+ """
420
+ style = self._theme.get_style_for_token(token_type)
421
+ return style.color
422
+
423
+ @property
424
+ def lexer(self) -> Optional[Lexer]:
425
+ """The lexer for this syntax, or None if no lexer was found.
426
+
427
+ Tries to find the lexer by name if a string was passed to the constructor.
428
+ """
429
+
430
+ if isinstance(self._lexer, Lexer):
431
+ return self._lexer
432
+ try:
433
+ return get_lexer_by_name(
434
+ self._lexer,
435
+ stripnl=False,
436
+ ensurenl=True,
437
+ tabsize=self.tab_size,
438
+ )
439
+ except ClassNotFound:
440
+ return None
441
+
442
+ @property
443
+ def default_lexer(self) -> Lexer:
444
+ """A Pygments Lexer to use if one is not specified or invalid."""
445
+ return get_lexer_by_name(
446
+ "text",
447
+ stripnl=False,
448
+ ensurenl=True,
449
+ tabsize=self.tab_size,
450
+ )
451
+
452
+ def highlight(
453
+ self,
454
+ code: str,
455
+ line_range: Optional[Tuple[Optional[int], Optional[int]]] = None,
456
+ ) -> Text:
457
+ """Highlight code and return a Text instance.
458
+
459
+ Args:
460
+ code (str): Code to highlight.
461
+ line_range(Tuple[int, int], optional): Optional line range to highlight.
462
+
463
+ Returns:
464
+ Text: A text instance containing highlighted syntax.
465
+ """
466
+
467
+ base_style = self._get_base_style()
468
+ justify: JustifyMethod = (
469
+ "default" if base_style.transparent_background else "left"
470
+ )
471
+
472
+ text = Text(
473
+ justify=justify,
474
+ style=base_style,
475
+ tab_size=self.tab_size,
476
+ no_wrap=not self.word_wrap,
477
+ )
478
+ _get_theme_style = self._theme.get_style_for_token
479
+
480
+ lexer = self.lexer or self.default_lexer
481
+
482
+ if lexer is None:
483
+ text.append(code)
484
+ else:
485
+ if line_range:
486
+ # More complicated path to only stylize a portion of the code
487
+ # This speeds up further operations as there are less spans to process
488
+ line_start, line_end = line_range
489
+
490
+ def line_tokenize() -> Iterable[Tuple[Any, str]]:
491
+ """Split tokens to one per line."""
492
+ assert lexer # required to make MyPy happy - we know lexer is not None at this point
493
+
494
+ for token_type, token in lexer.get_tokens(code):
495
+ while token:
496
+ line_token, new_line, token = token.partition("\n")
497
+ yield token_type, line_token + new_line
498
+
499
+ def tokens_to_spans() -> Iterable[Tuple[str, Optional[Style]]]:
500
+ """Convert tokens to spans."""
501
+ tokens = iter(line_tokenize())
502
+ line_no = 0
503
+ _line_start = line_start - 1 if line_start else 0
504
+
505
+ # Skip over tokens until line start
506
+ while line_no < _line_start:
507
+ try:
508
+ _token_type, token = next(tokens)
509
+ except StopIteration:
510
+ break
511
+ yield (token, None)
512
+ if token.endswith("\n"):
513
+ line_no += 1
514
+ # Generate spans until line end
515
+ for token_type, token in tokens:
516
+ yield (token, _get_theme_style(token_type))
517
+ if token.endswith("\n"):
518
+ line_no += 1
519
+ if line_end and line_no >= line_end:
520
+ break
521
+
522
+ text.append_tokens(tokens_to_spans())
523
+
524
+ else:
525
+ text.append_tokens(
526
+ (token, _get_theme_style(token_type))
527
+ for token_type, token in lexer.get_tokens(code)
528
+ )
529
+ if self.background_color is not None:
530
+ text.stylize(f"on {self.background_color}")
531
+
532
+ if self._stylized_ranges:
533
+ self._apply_stylized_ranges(text)
534
+
535
+ return text
536
+
537
+ def stylize_range(
538
+ self,
539
+ style: StyleType,
540
+ start: SyntaxPosition,
541
+ end: SyntaxPosition,
542
+ style_before: bool = False,
543
+ ) -> None:
544
+ """
545
+ Adds a custom style on a part of the code, that will be applied to the syntax display when it's rendered.
546
+ Line numbers are 1-based, while column indexes are 0-based.
547
+
548
+ Args:
549
+ style (StyleType): The style to apply.
550
+ start (Tuple[int, int]): The start of the range, in the form `[line number, column index]`.
551
+ end (Tuple[int, int]): The end of the range, in the form `[line number, column index]`.
552
+ style_before (bool): Apply the style before any existing styles.
553
+ """
554
+ self._stylized_ranges.append(
555
+ _SyntaxHighlightRange(style, start, end, style_before)
556
+ )
557
+
558
+ def _get_line_numbers_color(self, blend: float = 0.3) -> Color:
559
+ background_style = self._theme.get_background_style() + self.background_style
560
+ background_color = background_style.bgcolor
561
+ if background_color is None or background_color.is_system_defined:
562
+ return Color.default()
563
+ foreground_color = self._get_token_color(Token.Text)
564
+ if foreground_color is None or foreground_color.is_system_defined:
565
+ return foreground_color or Color.default()
566
+ new_color = blend_rgb(
567
+ background_color.get_truecolor(),
568
+ foreground_color.get_truecolor(),
569
+ cross_fade=blend,
570
+ )
571
+ return Color.from_triplet(new_color)
572
+
573
+ @property
574
+ def _numbers_column_width(self) -> int:
575
+ """Get the number of characters used to render the numbers column."""
576
+ column_width = 0
577
+ if self.line_numbers:
578
+ column_width = (
579
+ len(str(self.start_line + self.code.count("\n")))
580
+ + NUMBERS_COLUMN_DEFAULT_PADDING
581
+ )
582
+ return column_width
583
+
584
+ def _get_number_styles(self, console: Console) -> Tuple[Style, Style, Style]:
585
+ """Get background, number, and highlight styles for line numbers."""
586
+ background_style = self._get_base_style()
587
+ if background_style.transparent_background:
588
+ return Style.null(), Style(dim=True), Style.null()
589
+ if console.color_system in ("256", "truecolor"):
590
+ number_style = Style.chain(
591
+ background_style,
592
+ self._theme.get_style_for_token(Token.Text),
593
+ Style(color=self._get_line_numbers_color()),
594
+ self.background_style,
595
+ )
596
+ highlight_number_style = Style.chain(
597
+ background_style,
598
+ self._theme.get_style_for_token(Token.Text),
599
+ Style(bold=True, color=self._get_line_numbers_color(0.9)),
600
+ self.background_style,
601
+ )
602
+ else:
603
+ number_style = background_style + Style(dim=True)
604
+ highlight_number_style = background_style + Style(dim=False)
605
+ return background_style, number_style, highlight_number_style
606
+
607
+ def __rich_measure__(
608
+ self, console: "Console", options: "ConsoleOptions"
609
+ ) -> "Measurement":
610
+ _, right, _, left = Padding.unpack(self.padding)
611
+ padding = left + right
612
+ if self.code_width is not None:
613
+ width = self.code_width + self._numbers_column_width + padding + 1
614
+ return Measurement(self._numbers_column_width, width)
615
+ lines = self.code.splitlines()
616
+ width = (
617
+ self._numbers_column_width
618
+ + padding
619
+ + (max(cell_len(line) for line in lines) if lines else 0)
620
+ )
621
+ if self.line_numbers:
622
+ width += 1
623
+ return Measurement(self._numbers_column_width, width)
624
+
625
+ def __rich_console__(
626
+ self, console: Console, options: ConsoleOptions
627
+ ) -> RenderResult:
628
+ segments = Segments(self._get_syntax(console, options))
629
+ if self.padding:
630
+ yield Padding(segments, style=self._get_base_style(), pad=self.padding)
631
+ else:
632
+ yield segments
633
+
634
+ def _get_syntax(
635
+ self,
636
+ console: Console,
637
+ options: ConsoleOptions,
638
+ ) -> Iterable[Segment]:
639
+ """
640
+ Get the Segments for the Syntax object, excluding any vertical/horizontal padding
641
+ """
642
+ transparent_background = self._get_base_style().transparent_background
643
+ code_width = (
644
+ (
645
+ (options.max_width - self._numbers_column_width - 1)
646
+ if self.line_numbers
647
+ else options.max_width
648
+ )
649
+ if self.code_width is None
650
+ else self.code_width
651
+ )
652
+
653
+ ends_on_nl, processed_code = self._process_code(self.code)
654
+ text = self.highlight(processed_code, self.line_range)
655
+
656
+ if not self.line_numbers and not self.word_wrap and not self.line_range:
657
+ if not ends_on_nl:
658
+ text.remove_suffix("\n")
659
+ # Simple case of just rendering text
660
+ style = (
661
+ self._get_base_style()
662
+ + self._theme.get_style_for_token(Comment)
663
+ + Style(dim=True)
664
+ + self.background_style
665
+ )
666
+ if self.indent_guides and not options.ascii_only:
667
+ text = text.with_indent_guides(self.tab_size, style=style)
668
+ text.overflow = "crop"
669
+ if style.transparent_background:
670
+ yield from console.render(
671
+ text, options=options.update(width=code_width)
672
+ )
673
+ else:
674
+ syntax_lines = console.render_lines(
675
+ text,
676
+ options.update(width=code_width, height=None, justify="left"),
677
+ style=self.background_style,
678
+ pad=True,
679
+ new_lines=True,
680
+ )
681
+ for syntax_line in syntax_lines:
682
+ yield from syntax_line
683
+ return
684
+
685
+ start_line, end_line = self.line_range or (None, None)
686
+ line_offset = 0
687
+ if start_line:
688
+ line_offset = max(0, start_line - 1)
689
+ lines: Union[List[Text], Lines] = text.split("\n", allow_blank=ends_on_nl)
690
+ if self.line_range:
691
+ if line_offset > len(lines):
692
+ return
693
+ lines = lines[line_offset:end_line]
694
+
695
+ if self.indent_guides and not options.ascii_only:
696
+ style = (
697
+ self._get_base_style()
698
+ + self._theme.get_style_for_token(Comment)
699
+ + Style(dim=True)
700
+ + self.background_style
701
+ )
702
+ lines = (
703
+ Text("\n")
704
+ .join(lines)
705
+ .with_indent_guides(self.tab_size, style=style + Style(italic=False))
706
+ .split("\n", allow_blank=True)
707
+ )
708
+
709
+ numbers_column_width = self._numbers_column_width
710
+ render_options = options.update(width=code_width)
711
+
712
+ highlight_line = self.highlight_lines.__contains__
713
+ _Segment = Segment
714
+ new_line = _Segment("\n")
715
+
716
+ line_pointer = "> " if options.legacy_windows else "❱ "
717
+
718
+ (
719
+ background_style,
720
+ number_style,
721
+ highlight_number_style,
722
+ ) = self._get_number_styles(console)
723
+
724
+ for line_no, line in enumerate(lines, self.start_line + line_offset):
725
+ if self.word_wrap:
726
+ wrapped_lines = console.render_lines(
727
+ line,
728
+ render_options.update(height=None, justify="left"),
729
+ style=background_style,
730
+ pad=not transparent_background,
731
+ )
732
+ else:
733
+ segments = list(line.render(console, end=""))
734
+ if options.no_wrap:
735
+ wrapped_lines = [segments]
736
+ else:
737
+ wrapped_lines = [
738
+ _Segment.adjust_line_length(
739
+ segments,
740
+ render_options.max_width,
741
+ style=background_style,
742
+ pad=not transparent_background,
743
+ )
744
+ ]
745
+
746
+ if self.line_numbers:
747
+ wrapped_line_left_pad = _Segment(
748
+ " " * numbers_column_width + " ", background_style
749
+ )
750
+ for first, wrapped_line in loop_first(wrapped_lines):
751
+ if first:
752
+ line_column = str(line_no).rjust(numbers_column_width - 2) + " "
753
+ if highlight_line(line_no):
754
+ yield _Segment(line_pointer, Style(color="red"))
755
+ yield _Segment(line_column, highlight_number_style)
756
+ else:
757
+ yield _Segment(" ", highlight_number_style)
758
+ yield _Segment(line_column, number_style)
759
+ else:
760
+ yield wrapped_line_left_pad
761
+ yield from wrapped_line
762
+ yield new_line
763
+ else:
764
+ for wrapped_line in wrapped_lines:
765
+ yield from wrapped_line
766
+ yield new_line
767
+
768
+ def _apply_stylized_ranges(self, text: Text) -> None:
769
+ """
770
+ Apply stylized ranges to a text instance,
771
+ using the given code to determine the right portion to apply the style to.
772
+
773
+ Args:
774
+ text (Text): Text instance to apply the style to.
775
+ """
776
+ code = text.plain
777
+ newlines_offsets = [
778
+ # Let's add outer boundaries at each side of the list:
779
+ 0,
780
+ # N.B. using "\n" here is much faster than using metacharacters such as "^" or "\Z":
781
+ *[
782
+ match.start() + 1
783
+ for match in re.finditer("\n", code, flags=re.MULTILINE)
784
+ ],
785
+ len(code) + 1,
786
+ ]
787
+
788
+ for stylized_range in self._stylized_ranges:
789
+ start = _get_code_index_for_syntax_position(
790
+ newlines_offsets, stylized_range.start
791
+ )
792
+ end = _get_code_index_for_syntax_position(
793
+ newlines_offsets, stylized_range.end
794
+ )
795
+ if start is not None and end is not None:
796
+ if stylized_range.style_before:
797
+ text.stylize_before(stylized_range.style, start, end)
798
+ else:
799
+ text.stylize(stylized_range.style, start, end)
800
+
801
+ def _process_code(self, code: str) -> Tuple[bool, str]:
802
+ """
803
+ Applies various processing to a raw code string
804
+ (normalises it so it always ends with a line return, dedents it if necessary, etc.)
805
+
806
+ Args:
807
+ code (str): The raw code string to process
808
+
809
+ Returns:
810
+ Tuple[bool, str]: the boolean indicates whether the raw code ends with a line return,
811
+ while the string is the processed code.
812
+ """
813
+ ends_on_nl = code.endswith("\n")
814
+ processed_code = code if ends_on_nl else code + "\n"
815
+ processed_code = (
816
+ textwrap.dedent(processed_code) if self.dedent else processed_code
817
+ )
818
+ processed_code = processed_code.expandtabs(self.tab_size)
819
+ return ends_on_nl, processed_code
820
+
821
+
822
+ def _get_code_index_for_syntax_position(
823
+ newlines_offsets: Sequence[int], position: SyntaxPosition
824
+ ) -> Optional[int]:
825
+ """
826
+ Returns the index of the code string for the given positions.
827
+
828
+ Args:
829
+ newlines_offsets (Sequence[int]): The offset of each newline character found in the code snippet.
830
+ position (SyntaxPosition): The position to search for.
831
+
832
+ Returns:
833
+ Optional[int]: The index of the code string for this position, or `None`
834
+ if the given position's line number is out of range (if it's the column that is out of range
835
+ we silently clamp its value so that it reaches the end of the line)
836
+ """
837
+ lines_count = len(newlines_offsets)
838
+
839
+ line_number, column_index = position
840
+ if line_number > lines_count or len(newlines_offsets) < (line_number + 1):
841
+ return None # `line_number` is out of range
842
+ line_index = line_number - 1
843
+ line_length = newlines_offsets[line_index + 1] - newlines_offsets[line_index] - 1
844
+ # If `column_index` is out of range: let's silently clamp it:
845
+ column_index = min(line_length, column_index)
846
+ return newlines_offsets[line_index] + column_index
847
+
848
+
849
+ if __name__ == "__main__": # pragma: no cover
850
+ import argparse
851
+ import sys
852
+
853
+ parser = argparse.ArgumentParser(
854
+ description="Render syntax to the console with Rich"
855
+ )
856
+ parser.add_argument(
857
+ "path",
858
+ metavar="PATH",
859
+ help="path to file, or - for stdin",
860
+ )
861
+ parser.add_argument(
862
+ "-c",
863
+ "--force-color",
864
+ dest="force_color",
865
+ action="store_true",
866
+ default=None,
867
+ help="force color for non-terminals",
868
+ )
869
+ parser.add_argument(
870
+ "-i",
871
+ "--indent-guides",
872
+ dest="indent_guides",
873
+ action="store_true",
874
+ default=False,
875
+ help="display indent guides",
876
+ )
877
+ parser.add_argument(
878
+ "-l",
879
+ "--line-numbers",
880
+ dest="line_numbers",
881
+ action="store_true",
882
+ help="render line numbers",
883
+ )
884
+ parser.add_argument(
885
+ "-w",
886
+ "--width",
887
+ type=int,
888
+ dest="width",
889
+ default=None,
890
+ help="width of output (default will auto-detect)",
891
+ )
892
+ parser.add_argument(
893
+ "-r",
894
+ "--wrap",
895
+ dest="word_wrap",
896
+ action="store_true",
897
+ default=False,
898
+ help="word wrap long lines",
899
+ )
900
+ parser.add_argument(
901
+ "-s",
902
+ "--soft-wrap",
903
+ action="store_true",
904
+ dest="soft_wrap",
905
+ default=False,
906
+ help="enable soft wrapping mode",
907
+ )
908
+ parser.add_argument(
909
+ "-t", "--theme", dest="theme", default="monokai", help="pygments theme"
910
+ )
911
+ parser.add_argument(
912
+ "-b",
913
+ "--background-color",
914
+ dest="background_color",
915
+ default=None,
916
+ help="Override background color",
917
+ )
918
+ parser.add_argument(
919
+ "-x",
920
+ "--lexer",
921
+ default=None,
922
+ dest="lexer_name",
923
+ help="Lexer name",
924
+ )
925
+ parser.add_argument(
926
+ "-p", "--padding", type=int, default=0, dest="padding", help="Padding"
927
+ )
928
+ parser.add_argument(
929
+ "--highlight-line",
930
+ type=int,
931
+ default=None,
932
+ dest="highlight_line",
933
+ help="The line number (not index!) to highlight",
934
+ )
935
+ args = parser.parse_args()
936
+
937
+ from pip._vendor.rich.console import Console
938
+
939
+ console = Console(force_terminal=args.force_color, width=args.width)
940
+
941
+ if args.path == "-":
942
+ code = sys.stdin.read()
943
+ syntax = Syntax(
944
+ code=code,
945
+ lexer=args.lexer_name,
946
+ line_numbers=args.line_numbers,
947
+ word_wrap=args.word_wrap,
948
+ theme=args.theme,
949
+ background_color=args.background_color,
950
+ indent_guides=args.indent_guides,
951
+ padding=args.padding,
952
+ highlight_lines={args.highlight_line},
953
+ )
954
+ else:
955
+ syntax = Syntax.from_path(
956
+ args.path,
957
+ lexer=args.lexer_name,
958
+ line_numbers=args.line_numbers,
959
+ word_wrap=args.word_wrap,
960
+ theme=args.theme,
961
+ background_color=args.background_color,
962
+ indent_guides=args.indent_guides,
963
+ padding=args.padding,
964
+ highlight_lines={args.highlight_line},
965
+ )
966
+ console.print(syntax, soft_wrap=args.soft_wrap)
llava/lib/python3.10/site-packages/pip/_vendor/rich/terminal_theme.py ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List, Optional, Tuple
2
+
3
+ from .color_triplet import ColorTriplet
4
+ from .palette import Palette
5
+
6
+ _ColorTuple = Tuple[int, int, int]
7
+
8
+
9
+ class TerminalTheme:
10
+ """A color theme used when exporting console content.
11
+
12
+ Args:
13
+ background (Tuple[int, int, int]): The background color.
14
+ foreground (Tuple[int, int, int]): The foreground (text) color.
15
+ normal (List[Tuple[int, int, int]]): A list of 8 normal intensity colors.
16
+ bright (List[Tuple[int, int, int]], optional): A list of 8 bright colors, or None
17
+ to repeat normal intensity. Defaults to None.
18
+ """
19
+
20
+ def __init__(
21
+ self,
22
+ background: _ColorTuple,
23
+ foreground: _ColorTuple,
24
+ normal: List[_ColorTuple],
25
+ bright: Optional[List[_ColorTuple]] = None,
26
+ ) -> None:
27
+ self.background_color = ColorTriplet(*background)
28
+ self.foreground_color = ColorTriplet(*foreground)
29
+ self.ansi_colors = Palette(normal + (bright or normal))
30
+
31
+
32
+ DEFAULT_TERMINAL_THEME = TerminalTheme(
33
+ (255, 255, 255),
34
+ (0, 0, 0),
35
+ [
36
+ (0, 0, 0),
37
+ (128, 0, 0),
38
+ (0, 128, 0),
39
+ (128, 128, 0),
40
+ (0, 0, 128),
41
+ (128, 0, 128),
42
+ (0, 128, 128),
43
+ (192, 192, 192),
44
+ ],
45
+ [
46
+ (128, 128, 128),
47
+ (255, 0, 0),
48
+ (0, 255, 0),
49
+ (255, 255, 0),
50
+ (0, 0, 255),
51
+ (255, 0, 255),
52
+ (0, 255, 255),
53
+ (255, 255, 255),
54
+ ],
55
+ )
56
+
57
+ MONOKAI = TerminalTheme(
58
+ (12, 12, 12),
59
+ (217, 217, 217),
60
+ [
61
+ (26, 26, 26),
62
+ (244, 0, 95),
63
+ (152, 224, 36),
64
+ (253, 151, 31),
65
+ (157, 101, 255),
66
+ (244, 0, 95),
67
+ (88, 209, 235),
68
+ (196, 197, 181),
69
+ (98, 94, 76),
70
+ ],
71
+ [
72
+ (244, 0, 95),
73
+ (152, 224, 36),
74
+ (224, 213, 97),
75
+ (157, 101, 255),
76
+ (244, 0, 95),
77
+ (88, 209, 235),
78
+ (246, 246, 239),
79
+ ],
80
+ )
81
+ DIMMED_MONOKAI = TerminalTheme(
82
+ (25, 25, 25),
83
+ (185, 188, 186),
84
+ [
85
+ (58, 61, 67),
86
+ (190, 63, 72),
87
+ (135, 154, 59),
88
+ (197, 166, 53),
89
+ (79, 118, 161),
90
+ (133, 92, 141),
91
+ (87, 143, 164),
92
+ (185, 188, 186),
93
+ (136, 137, 135),
94
+ ],
95
+ [
96
+ (251, 0, 31),
97
+ (15, 114, 47),
98
+ (196, 112, 51),
99
+ (24, 109, 227),
100
+ (251, 0, 103),
101
+ (46, 112, 109),
102
+ (253, 255, 185),
103
+ ],
104
+ )
105
+ NIGHT_OWLISH = TerminalTheme(
106
+ (255, 255, 255),
107
+ (64, 63, 83),
108
+ [
109
+ (1, 22, 39),
110
+ (211, 66, 62),
111
+ (42, 162, 152),
112
+ (218, 170, 1),
113
+ (72, 118, 214),
114
+ (64, 63, 83),
115
+ (8, 145, 106),
116
+ (122, 129, 129),
117
+ (122, 129, 129),
118
+ ],
119
+ [
120
+ (247, 110, 110),
121
+ (73, 208, 197),
122
+ (218, 194, 107),
123
+ (92, 167, 228),
124
+ (105, 112, 152),
125
+ (0, 201, 144),
126
+ (152, 159, 177),
127
+ ],
128
+ )
129
+
130
+ SVG_EXPORT_THEME = TerminalTheme(
131
+ (41, 41, 41),
132
+ (197, 200, 198),
133
+ [
134
+ (75, 78, 85),
135
+ (204, 85, 90),
136
+ (152, 168, 75),
137
+ (208, 179, 68),
138
+ (96, 138, 177),
139
+ (152, 114, 159),
140
+ (104, 160, 179),
141
+ (197, 200, 198),
142
+ (154, 155, 153),
143
+ ],
144
+ [
145
+ (255, 38, 39),
146
+ (0, 130, 61),
147
+ (208, 132, 66),
148
+ (25, 132, 233),
149
+ (255, 44, 122),
150
+ (57, 130, 128),
151
+ (253, 253, 197),
152
+ ],
153
+ )
llava/lib/python3.10/site-packages/pip/_vendor/rich/text.py ADDED
@@ -0,0 +1,1361 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ from functools import partial, reduce
3
+ from math import gcd
4
+ from operator import itemgetter
5
+ from typing import (
6
+ TYPE_CHECKING,
7
+ Any,
8
+ Callable,
9
+ Dict,
10
+ Iterable,
11
+ List,
12
+ NamedTuple,
13
+ Optional,
14
+ Pattern,
15
+ Tuple,
16
+ Union,
17
+ )
18
+
19
+ from ._loop import loop_last
20
+ from ._pick import pick_bool
21
+ from ._wrap import divide_line
22
+ from .align import AlignMethod
23
+ from .cells import cell_len, set_cell_size
24
+ from .containers import Lines
25
+ from .control import strip_control_codes
26
+ from .emoji import EmojiVariant
27
+ from .jupyter import JupyterMixin
28
+ from .measure import Measurement
29
+ from .segment import Segment
30
+ from .style import Style, StyleType
31
+
32
+ if TYPE_CHECKING: # pragma: no cover
33
+ from .console import Console, ConsoleOptions, JustifyMethod, OverflowMethod
34
+
35
+ DEFAULT_JUSTIFY: "JustifyMethod" = "default"
36
+ DEFAULT_OVERFLOW: "OverflowMethod" = "fold"
37
+
38
+
39
+ _re_whitespace = re.compile(r"\s+$")
40
+
41
+ TextType = Union[str, "Text"]
42
+ """A plain string or a :class:`Text` instance."""
43
+
44
+ GetStyleCallable = Callable[[str], Optional[StyleType]]
45
+
46
+
47
+ class Span(NamedTuple):
48
+ """A marked up region in some text."""
49
+
50
+ start: int
51
+ """Span start index."""
52
+ end: int
53
+ """Span end index."""
54
+ style: Union[str, Style]
55
+ """Style associated with the span."""
56
+
57
+ def __repr__(self) -> str:
58
+ return f"Span({self.start}, {self.end}, {self.style!r})"
59
+
60
+ def __bool__(self) -> bool:
61
+ return self.end > self.start
62
+
63
+ def split(self, offset: int) -> Tuple["Span", Optional["Span"]]:
64
+ """Split a span in to 2 from a given offset."""
65
+
66
+ if offset < self.start:
67
+ return self, None
68
+ if offset >= self.end:
69
+ return self, None
70
+
71
+ start, end, style = self
72
+ span1 = Span(start, min(end, offset), style)
73
+ span2 = Span(span1.end, end, style)
74
+ return span1, span2
75
+
76
+ def move(self, offset: int) -> "Span":
77
+ """Move start and end by a given offset.
78
+
79
+ Args:
80
+ offset (int): Number of characters to add to start and end.
81
+
82
+ Returns:
83
+ TextSpan: A new TextSpan with adjusted position.
84
+ """
85
+ start, end, style = self
86
+ return Span(start + offset, end + offset, style)
87
+
88
+ def right_crop(self, offset: int) -> "Span":
89
+ """Crop the span at the given offset.
90
+
91
+ Args:
92
+ offset (int): A value between start and end.
93
+
94
+ Returns:
95
+ Span: A new (possibly smaller) span.
96
+ """
97
+ start, end, style = self
98
+ if offset >= end:
99
+ return self
100
+ return Span(start, min(offset, end), style)
101
+
102
+ def extend(self, cells: int) -> "Span":
103
+ """Extend the span by the given number of cells.
104
+
105
+ Args:
106
+ cells (int): Additional space to add to end of span.
107
+
108
+ Returns:
109
+ Span: A span.
110
+ """
111
+ if cells:
112
+ start, end, style = self
113
+ return Span(start, end + cells, style)
114
+ else:
115
+ return self
116
+
117
+
118
+ class Text(JupyterMixin):
119
+ """Text with color / style.
120
+
121
+ Args:
122
+ text (str, optional): Default unstyled text. Defaults to "".
123
+ style (Union[str, Style], optional): Base style for text. Defaults to "".
124
+ justify (str, optional): Justify method: "left", "center", "full", "right". Defaults to None.
125
+ overflow (str, optional): Overflow method: "crop", "fold", "ellipsis". Defaults to None.
126
+ no_wrap (bool, optional): Disable text wrapping, or None for default. Defaults to None.
127
+ end (str, optional): Character to end text with. Defaults to "\\\\n".
128
+ tab_size (int): Number of spaces per tab, or ``None`` to use ``console.tab_size``. Defaults to None.
129
+ spans (List[Span], optional). A list of predefined style spans. Defaults to None.
130
+ """
131
+
132
+ __slots__ = [
133
+ "_text",
134
+ "style",
135
+ "justify",
136
+ "overflow",
137
+ "no_wrap",
138
+ "end",
139
+ "tab_size",
140
+ "_spans",
141
+ "_length",
142
+ ]
143
+
144
+ def __init__(
145
+ self,
146
+ text: str = "",
147
+ style: Union[str, Style] = "",
148
+ *,
149
+ justify: Optional["JustifyMethod"] = None,
150
+ overflow: Optional["OverflowMethod"] = None,
151
+ no_wrap: Optional[bool] = None,
152
+ end: str = "\n",
153
+ tab_size: Optional[int] = None,
154
+ spans: Optional[List[Span]] = None,
155
+ ) -> None:
156
+ sanitized_text = strip_control_codes(text)
157
+ self._text = [sanitized_text]
158
+ self.style = style
159
+ self.justify: Optional["JustifyMethod"] = justify
160
+ self.overflow: Optional["OverflowMethod"] = overflow
161
+ self.no_wrap = no_wrap
162
+ self.end = end
163
+ self.tab_size = tab_size
164
+ self._spans: List[Span] = spans or []
165
+ self._length: int = len(sanitized_text)
166
+
167
+ def __len__(self) -> int:
168
+ return self._length
169
+
170
+ def __bool__(self) -> bool:
171
+ return bool(self._length)
172
+
173
+ def __str__(self) -> str:
174
+ return self.plain
175
+
176
+ def __repr__(self) -> str:
177
+ return f"<text {self.plain!r} {self._spans!r} {self.style!r}>"
178
+
179
+ def __add__(self, other: Any) -> "Text":
180
+ if isinstance(other, (str, Text)):
181
+ result = self.copy()
182
+ result.append(other)
183
+ return result
184
+ return NotImplemented
185
+
186
+ def __eq__(self, other: object) -> bool:
187
+ if not isinstance(other, Text):
188
+ return NotImplemented
189
+ return self.plain == other.plain and self._spans == other._spans
190
+
191
+ def __contains__(self, other: object) -> bool:
192
+ if isinstance(other, str):
193
+ return other in self.plain
194
+ elif isinstance(other, Text):
195
+ return other.plain in self.plain
196
+ return False
197
+
198
+ def __getitem__(self, slice: Union[int, slice]) -> "Text":
199
+ def get_text_at(offset: int) -> "Text":
200
+ _Span = Span
201
+ text = Text(
202
+ self.plain[offset],
203
+ spans=[
204
+ _Span(0, 1, style)
205
+ for start, end, style in self._spans
206
+ if end > offset >= start
207
+ ],
208
+ end="",
209
+ )
210
+ return text
211
+
212
+ if isinstance(slice, int):
213
+ return get_text_at(slice)
214
+ else:
215
+ start, stop, step = slice.indices(len(self.plain))
216
+ if step == 1:
217
+ lines = self.divide([start, stop])
218
+ return lines[1]
219
+ else:
220
+ # This would be a bit of work to implement efficiently
221
+ # For now, its not required
222
+ raise TypeError("slices with step!=1 are not supported")
223
+
224
+ @property
225
+ def cell_len(self) -> int:
226
+ """Get the number of cells required to render this text."""
227
+ return cell_len(self.plain)
228
+
229
+ @property
230
+ def markup(self) -> str:
231
+ """Get console markup to render this Text.
232
+
233
+ Returns:
234
+ str: A string potentially creating markup tags.
235
+ """
236
+ from .markup import escape
237
+
238
+ output: List[str] = []
239
+
240
+ plain = self.plain
241
+ markup_spans = [
242
+ (0, False, self.style),
243
+ *((span.start, False, span.style) for span in self._spans),
244
+ *((span.end, True, span.style) for span in self._spans),
245
+ (len(plain), True, self.style),
246
+ ]
247
+ markup_spans.sort(key=itemgetter(0, 1))
248
+ position = 0
249
+ append = output.append
250
+ for offset, closing, style in markup_spans:
251
+ if offset > position:
252
+ append(escape(plain[position:offset]))
253
+ position = offset
254
+ if style:
255
+ append(f"[/{style}]" if closing else f"[{style}]")
256
+ markup = "".join(output)
257
+ return markup
258
+
259
+ @classmethod
260
+ def from_markup(
261
+ cls,
262
+ text: str,
263
+ *,
264
+ style: Union[str, Style] = "",
265
+ emoji: bool = True,
266
+ emoji_variant: Optional[EmojiVariant] = None,
267
+ justify: Optional["JustifyMethod"] = None,
268
+ overflow: Optional["OverflowMethod"] = None,
269
+ end: str = "\n",
270
+ ) -> "Text":
271
+ """Create Text instance from markup.
272
+
273
+ Args:
274
+ text (str): A string containing console markup.
275
+ style (Union[str, Style], optional): Base style for text. Defaults to "".
276
+ emoji (bool, optional): Also render emoji code. Defaults to True.
277
+ emoji_variant (str, optional): Optional emoji variant, either "text" or "emoji". Defaults to None.
278
+ justify (str, optional): Justify method: "left", "center", "full", "right". Defaults to None.
279
+ overflow (str, optional): Overflow method: "crop", "fold", "ellipsis". Defaults to None.
280
+ end (str, optional): Character to end text with. Defaults to "\\\\n".
281
+
282
+ Returns:
283
+ Text: A Text instance with markup rendered.
284
+ """
285
+ from .markup import render
286
+
287
+ rendered_text = render(text, style, emoji=emoji, emoji_variant=emoji_variant)
288
+ rendered_text.justify = justify
289
+ rendered_text.overflow = overflow
290
+ rendered_text.end = end
291
+ return rendered_text
292
+
293
+ @classmethod
294
+ def from_ansi(
295
+ cls,
296
+ text: str,
297
+ *,
298
+ style: Union[str, Style] = "",
299
+ justify: Optional["JustifyMethod"] = None,
300
+ overflow: Optional["OverflowMethod"] = None,
301
+ no_wrap: Optional[bool] = None,
302
+ end: str = "\n",
303
+ tab_size: Optional[int] = 8,
304
+ ) -> "Text":
305
+ """Create a Text object from a string containing ANSI escape codes.
306
+
307
+ Args:
308
+ text (str): A string containing escape codes.
309
+ style (Union[str, Style], optional): Base style for text. Defaults to "".
310
+ justify (str, optional): Justify method: "left", "center", "full", "right". Defaults to None.
311
+ overflow (str, optional): Overflow method: "crop", "fold", "ellipsis". Defaults to None.
312
+ no_wrap (bool, optional): Disable text wrapping, or None for default. Defaults to None.
313
+ end (str, optional): Character to end text with. Defaults to "\\\\n".
314
+ tab_size (int): Number of spaces per tab, or ``None`` to use ``console.tab_size``. Defaults to None.
315
+ """
316
+ from .ansi import AnsiDecoder
317
+
318
+ joiner = Text(
319
+ "\n",
320
+ justify=justify,
321
+ overflow=overflow,
322
+ no_wrap=no_wrap,
323
+ end=end,
324
+ tab_size=tab_size,
325
+ style=style,
326
+ )
327
+ decoder = AnsiDecoder()
328
+ result = joiner.join(line for line in decoder.decode(text))
329
+ return result
330
+
331
+ @classmethod
332
+ def styled(
333
+ cls,
334
+ text: str,
335
+ style: StyleType = "",
336
+ *,
337
+ justify: Optional["JustifyMethod"] = None,
338
+ overflow: Optional["OverflowMethod"] = None,
339
+ ) -> "Text":
340
+ """Construct a Text instance with a pre-applied styled. A style applied in this way won't be used
341
+ to pad the text when it is justified.
342
+
343
+ Args:
344
+ text (str): A string containing console markup.
345
+ style (Union[str, Style]): Style to apply to the text. Defaults to "".
346
+ justify (str, optional): Justify method: "left", "center", "full", "right". Defaults to None.
347
+ overflow (str, optional): Overflow method: "crop", "fold", "ellipsis". Defaults to None.
348
+
349
+ Returns:
350
+ Text: A text instance with a style applied to the entire string.
351
+ """
352
+ styled_text = cls(text, justify=justify, overflow=overflow)
353
+ styled_text.stylize(style)
354
+ return styled_text
355
+
356
+ @classmethod
357
+ def assemble(
358
+ cls,
359
+ *parts: Union[str, "Text", Tuple[str, StyleType]],
360
+ style: Union[str, Style] = "",
361
+ justify: Optional["JustifyMethod"] = None,
362
+ overflow: Optional["OverflowMethod"] = None,
363
+ no_wrap: Optional[bool] = None,
364
+ end: str = "\n",
365
+ tab_size: int = 8,
366
+ meta: Optional[Dict[str, Any]] = None,
367
+ ) -> "Text":
368
+ """Construct a text instance by combining a sequence of strings with optional styles.
369
+ The positional arguments should be either strings, or a tuple of string + style.
370
+
371
+ Args:
372
+ style (Union[str, Style], optional): Base style for text. Defaults to "".
373
+ justify (str, optional): Justify method: "left", "center", "full", "right". Defaults to None.
374
+ overflow (str, optional): Overflow method: "crop", "fold", "ellipsis". Defaults to None.
375
+ no_wrap (bool, optional): Disable text wrapping, or None for default. Defaults to None.
376
+ end (str, optional): Character to end text with. Defaults to "\\\\n".
377
+ tab_size (int): Number of spaces per tab, or ``None`` to use ``console.tab_size``. Defaults to None.
378
+ meta (Dict[str, Any], optional). Meta data to apply to text, or None for no meta data. Default to None
379
+
380
+ Returns:
381
+ Text: A new text instance.
382
+ """
383
+ text = cls(
384
+ style=style,
385
+ justify=justify,
386
+ overflow=overflow,
387
+ no_wrap=no_wrap,
388
+ end=end,
389
+ tab_size=tab_size,
390
+ )
391
+ append = text.append
392
+ _Text = Text
393
+ for part in parts:
394
+ if isinstance(part, (_Text, str)):
395
+ append(part)
396
+ else:
397
+ append(*part)
398
+ if meta:
399
+ text.apply_meta(meta)
400
+ return text
401
+
402
+ @property
403
+ def plain(self) -> str:
404
+ """Get the text as a single string."""
405
+ if len(self._text) != 1:
406
+ self._text[:] = ["".join(self._text)]
407
+ return self._text[0]
408
+
409
+ @plain.setter
410
+ def plain(self, new_text: str) -> None:
411
+ """Set the text to a new value."""
412
+ if new_text != self.plain:
413
+ sanitized_text = strip_control_codes(new_text)
414
+ self._text[:] = [sanitized_text]
415
+ old_length = self._length
416
+ self._length = len(sanitized_text)
417
+ if old_length > self._length:
418
+ self._trim_spans()
419
+
420
+ @property
421
+ def spans(self) -> List[Span]:
422
+ """Get a reference to the internal list of spans."""
423
+ return self._spans
424
+
425
+ @spans.setter
426
+ def spans(self, spans: List[Span]) -> None:
427
+ """Set spans."""
428
+ self._spans = spans[:]
429
+
430
+ def blank_copy(self, plain: str = "") -> "Text":
431
+ """Return a new Text instance with copied metadata (but not the string or spans)."""
432
+ copy_self = Text(
433
+ plain,
434
+ style=self.style,
435
+ justify=self.justify,
436
+ overflow=self.overflow,
437
+ no_wrap=self.no_wrap,
438
+ end=self.end,
439
+ tab_size=self.tab_size,
440
+ )
441
+ return copy_self
442
+
443
+ def copy(self) -> "Text":
444
+ """Return a copy of this instance."""
445
+ copy_self = Text(
446
+ self.plain,
447
+ style=self.style,
448
+ justify=self.justify,
449
+ overflow=self.overflow,
450
+ no_wrap=self.no_wrap,
451
+ end=self.end,
452
+ tab_size=self.tab_size,
453
+ )
454
+ copy_self._spans[:] = self._spans
455
+ return copy_self
456
+
457
+ def stylize(
458
+ self,
459
+ style: Union[str, Style],
460
+ start: int = 0,
461
+ end: Optional[int] = None,
462
+ ) -> None:
463
+ """Apply a style to the text, or a portion of the text.
464
+
465
+ Args:
466
+ style (Union[str, Style]): Style instance or style definition to apply.
467
+ start (int): Start offset (negative indexing is supported). Defaults to 0.
468
+ end (Optional[int], optional): End offset (negative indexing is supported), or None for end of text. Defaults to None.
469
+ """
470
+ if style:
471
+ length = len(self)
472
+ if start < 0:
473
+ start = length + start
474
+ if end is None:
475
+ end = length
476
+ if end < 0:
477
+ end = length + end
478
+ if start >= length or end <= start:
479
+ # Span not in text or not valid
480
+ return
481
+ self._spans.append(Span(start, min(length, end), style))
482
+
483
+ def stylize_before(
484
+ self,
485
+ style: Union[str, Style],
486
+ start: int = 0,
487
+ end: Optional[int] = None,
488
+ ) -> None:
489
+ """Apply a style to the text, or a portion of the text. Styles will be applied before other styles already present.
490
+
491
+ Args:
492
+ style (Union[str, Style]): Style instance or style definition to apply.
493
+ start (int): Start offset (negative indexing is supported). Defaults to 0.
494
+ end (Optional[int], optional): End offset (negative indexing is supported), or None for end of text. Defaults to None.
495
+ """
496
+ if style:
497
+ length = len(self)
498
+ if start < 0:
499
+ start = length + start
500
+ if end is None:
501
+ end = length
502
+ if end < 0:
503
+ end = length + end
504
+ if start >= length or end <= start:
505
+ # Span not in text or not valid
506
+ return
507
+ self._spans.insert(0, Span(start, min(length, end), style))
508
+
509
+ def apply_meta(
510
+ self, meta: Dict[str, Any], start: int = 0, end: Optional[int] = None
511
+ ) -> None:
512
+ """Apply metadata to the text, or a portion of the text.
513
+
514
+ Args:
515
+ meta (Dict[str, Any]): A dict of meta information.
516
+ start (int): Start offset (negative indexing is supported). Defaults to 0.
517
+ end (Optional[int], optional): End offset (negative indexing is supported), or None for end of text. Defaults to None.
518
+
519
+ """
520
+ style = Style.from_meta(meta)
521
+ self.stylize(style, start=start, end=end)
522
+
523
+ def on(self, meta: Optional[Dict[str, Any]] = None, **handlers: Any) -> "Text":
524
+ """Apply event handlers (used by Textual project).
525
+
526
+ Example:
527
+ >>> from rich.text import Text
528
+ >>> text = Text("hello world")
529
+ >>> text.on(click="view.toggle('world')")
530
+
531
+ Args:
532
+ meta (Dict[str, Any]): Mapping of meta information.
533
+ **handlers: Keyword args are prefixed with "@" to defined handlers.
534
+
535
+ Returns:
536
+ Text: Self is returned to method may be chained.
537
+ """
538
+ meta = {} if meta is None else meta
539
+ meta.update({f"@{key}": value for key, value in handlers.items()})
540
+ self.stylize(Style.from_meta(meta))
541
+ return self
542
+
543
+ def remove_suffix(self, suffix: str) -> None:
544
+ """Remove a suffix if it exists.
545
+
546
+ Args:
547
+ suffix (str): Suffix to remove.
548
+ """
549
+ if self.plain.endswith(suffix):
550
+ self.right_crop(len(suffix))
551
+
552
+ def get_style_at_offset(self, console: "Console", offset: int) -> Style:
553
+ """Get the style of a character at give offset.
554
+
555
+ Args:
556
+ console (~Console): Console where text will be rendered.
557
+ offset (int): Offset in to text (negative indexing supported)
558
+
559
+ Returns:
560
+ Style: A Style instance.
561
+ """
562
+ # TODO: This is a little inefficient, it is only used by full justify
563
+ if offset < 0:
564
+ offset = len(self) + offset
565
+ get_style = console.get_style
566
+ style = get_style(self.style).copy()
567
+ for start, end, span_style in self._spans:
568
+ if end > offset >= start:
569
+ style += get_style(span_style, default="")
570
+ return style
571
+
572
+ def extend_style(self, spaces: int) -> None:
573
+ """Extend the Text given number of spaces where the spaces have the same style as the last character.
574
+
575
+ Args:
576
+ spaces (int): Number of spaces to add to the Text.
577
+ """
578
+ if spaces <= 0:
579
+ return
580
+ spans = self.spans
581
+ new_spaces = " " * spaces
582
+ if spans:
583
+ end_offset = len(self)
584
+ self._spans[:] = [
585
+ span.extend(spaces) if span.end >= end_offset else span
586
+ for span in spans
587
+ ]
588
+ self._text.append(new_spaces)
589
+ self._length += spaces
590
+ else:
591
+ self.plain += new_spaces
592
+
593
+ def highlight_regex(
594
+ self,
595
+ re_highlight: Union[Pattern[str], str],
596
+ style: Optional[Union[GetStyleCallable, StyleType]] = None,
597
+ *,
598
+ style_prefix: str = "",
599
+ ) -> int:
600
+ """Highlight text with a regular expression, where group names are
601
+ translated to styles.
602
+
603
+ Args:
604
+ re_highlight (Union[re.Pattern, str]): A regular expression object or string.
605
+ style (Union[GetStyleCallable, StyleType]): Optional style to apply to whole match, or a callable
606
+ which accepts the matched text and returns a style. Defaults to None.
607
+ style_prefix (str, optional): Optional prefix to add to style group names.
608
+
609
+ Returns:
610
+ int: Number of regex matches
611
+ """
612
+ count = 0
613
+ append_span = self._spans.append
614
+ _Span = Span
615
+ plain = self.plain
616
+ if isinstance(re_highlight, str):
617
+ re_highlight = re.compile(re_highlight)
618
+ for match in re_highlight.finditer(plain):
619
+ get_span = match.span
620
+ if style:
621
+ start, end = get_span()
622
+ match_style = style(plain[start:end]) if callable(style) else style
623
+ if match_style is not None and end > start:
624
+ append_span(_Span(start, end, match_style))
625
+
626
+ count += 1
627
+ for name in match.groupdict().keys():
628
+ start, end = get_span(name)
629
+ if start != -1 and end > start:
630
+ append_span(_Span(start, end, f"{style_prefix}{name}"))
631
+ return count
632
+
633
+ def highlight_words(
634
+ self,
635
+ words: Iterable[str],
636
+ style: Union[str, Style],
637
+ *,
638
+ case_sensitive: bool = True,
639
+ ) -> int:
640
+ """Highlight words with a style.
641
+
642
+ Args:
643
+ words (Iterable[str]): Words to highlight.
644
+ style (Union[str, Style]): Style to apply.
645
+ case_sensitive (bool, optional): Enable case sensitive matching. Defaults to True.
646
+
647
+ Returns:
648
+ int: Number of words highlighted.
649
+ """
650
+ re_words = "|".join(re.escape(word) for word in words)
651
+ add_span = self._spans.append
652
+ count = 0
653
+ _Span = Span
654
+ for match in re.finditer(
655
+ re_words, self.plain, flags=0 if case_sensitive else re.IGNORECASE
656
+ ):
657
+ start, end = match.span(0)
658
+ add_span(_Span(start, end, style))
659
+ count += 1
660
+ return count
661
+
662
+ def rstrip(self) -> None:
663
+ """Strip whitespace from end of text."""
664
+ self.plain = self.plain.rstrip()
665
+
666
+ def rstrip_end(self, size: int) -> None:
667
+ """Remove whitespace beyond a certain width at the end of the text.
668
+
669
+ Args:
670
+ size (int): The desired size of the text.
671
+ """
672
+ text_length = len(self)
673
+ if text_length > size:
674
+ excess = text_length - size
675
+ whitespace_match = _re_whitespace.search(self.plain)
676
+ if whitespace_match is not None:
677
+ whitespace_count = len(whitespace_match.group(0))
678
+ self.right_crop(min(whitespace_count, excess))
679
+
680
+ def set_length(self, new_length: int) -> None:
681
+ """Set new length of the text, clipping or padding is required."""
682
+ length = len(self)
683
+ if length != new_length:
684
+ if length < new_length:
685
+ self.pad_right(new_length - length)
686
+ else:
687
+ self.right_crop(length - new_length)
688
+
689
+ def __rich_console__(
690
+ self, console: "Console", options: "ConsoleOptions"
691
+ ) -> Iterable[Segment]:
692
+ tab_size: int = console.tab_size if self.tab_size is None else self.tab_size
693
+ justify = self.justify or options.justify or DEFAULT_JUSTIFY
694
+
695
+ overflow = self.overflow or options.overflow or DEFAULT_OVERFLOW
696
+
697
+ lines = self.wrap(
698
+ console,
699
+ options.max_width,
700
+ justify=justify,
701
+ overflow=overflow,
702
+ tab_size=tab_size or 8,
703
+ no_wrap=pick_bool(self.no_wrap, options.no_wrap, False),
704
+ )
705
+ all_lines = Text("\n").join(lines)
706
+ yield from all_lines.render(console, end=self.end)
707
+
708
+ def __rich_measure__(
709
+ self, console: "Console", options: "ConsoleOptions"
710
+ ) -> Measurement:
711
+ text = self.plain
712
+ lines = text.splitlines()
713
+ max_text_width = max(cell_len(line) for line in lines) if lines else 0
714
+ words = text.split()
715
+ min_text_width = (
716
+ max(cell_len(word) for word in words) if words else max_text_width
717
+ )
718
+ return Measurement(min_text_width, max_text_width)
719
+
720
+ def render(self, console: "Console", end: str = "") -> Iterable["Segment"]:
721
+ """Render the text as Segments.
722
+
723
+ Args:
724
+ console (Console): Console instance.
725
+ end (Optional[str], optional): Optional end character.
726
+
727
+ Returns:
728
+ Iterable[Segment]: Result of render that may be written to the console.
729
+ """
730
+ _Segment = Segment
731
+ text = self.plain
732
+ if not self._spans:
733
+ yield Segment(text)
734
+ if end:
735
+ yield _Segment(end)
736
+ return
737
+ get_style = partial(console.get_style, default=Style.null())
738
+
739
+ enumerated_spans = list(enumerate(self._spans, 1))
740
+ style_map = {index: get_style(span.style) for index, span in enumerated_spans}
741
+ style_map[0] = get_style(self.style)
742
+
743
+ spans = [
744
+ (0, False, 0),
745
+ *((span.start, False, index) for index, span in enumerated_spans),
746
+ *((span.end, True, index) for index, span in enumerated_spans),
747
+ (len(text), True, 0),
748
+ ]
749
+ spans.sort(key=itemgetter(0, 1))
750
+
751
+ stack: List[int] = []
752
+ stack_append = stack.append
753
+ stack_pop = stack.remove
754
+
755
+ style_cache: Dict[Tuple[Style, ...], Style] = {}
756
+ style_cache_get = style_cache.get
757
+ combine = Style.combine
758
+
759
+ def get_current_style() -> Style:
760
+ """Construct current style from stack."""
761
+ styles = tuple(style_map[_style_id] for _style_id in sorted(stack))
762
+ cached_style = style_cache_get(styles)
763
+ if cached_style is not None:
764
+ return cached_style
765
+ current_style = combine(styles)
766
+ style_cache[styles] = current_style
767
+ return current_style
768
+
769
+ for (offset, leaving, style_id), (next_offset, _, _) in zip(spans, spans[1:]):
770
+ if leaving:
771
+ stack_pop(style_id)
772
+ else:
773
+ stack_append(style_id)
774
+ if next_offset > offset:
775
+ yield _Segment(text[offset:next_offset], get_current_style())
776
+ if end:
777
+ yield _Segment(end)
778
+
779
+ def join(self, lines: Iterable["Text"]) -> "Text":
780
+ """Join text together with this instance as the separator.
781
+
782
+ Args:
783
+ lines (Iterable[Text]): An iterable of Text instances to join.
784
+
785
+ Returns:
786
+ Text: A new text instance containing join text.
787
+ """
788
+
789
+ new_text = self.blank_copy()
790
+
791
+ def iter_text() -> Iterable["Text"]:
792
+ if self.plain:
793
+ for last, line in loop_last(lines):
794
+ yield line
795
+ if not last:
796
+ yield self
797
+ else:
798
+ yield from lines
799
+
800
+ extend_text = new_text._text.extend
801
+ append_span = new_text._spans.append
802
+ extend_spans = new_text._spans.extend
803
+ offset = 0
804
+ _Span = Span
805
+
806
+ for text in iter_text():
807
+ extend_text(text._text)
808
+ if text.style:
809
+ append_span(_Span(offset, offset + len(text), text.style))
810
+ extend_spans(
811
+ _Span(offset + start, offset + end, style)
812
+ for start, end, style in text._spans
813
+ )
814
+ offset += len(text)
815
+ new_text._length = offset
816
+ return new_text
817
+
818
+ def expand_tabs(self, tab_size: Optional[int] = None) -> None:
819
+ """Converts tabs to spaces.
820
+
821
+ Args:
822
+ tab_size (int, optional): Size of tabs. Defaults to 8.
823
+
824
+ """
825
+ if "\t" not in self.plain:
826
+ return
827
+ if tab_size is None:
828
+ tab_size = self.tab_size
829
+ if tab_size is None:
830
+ tab_size = 8
831
+
832
+ new_text: List[Text] = []
833
+ append = new_text.append
834
+
835
+ for line in self.split("\n", include_separator=True):
836
+ if "\t" not in line.plain:
837
+ append(line)
838
+ else:
839
+ cell_position = 0
840
+ parts = line.split("\t", include_separator=True)
841
+ for part in parts:
842
+ if part.plain.endswith("\t"):
843
+ part._text[-1] = part._text[-1][:-1] + " "
844
+ cell_position += part.cell_len
845
+ tab_remainder = cell_position % tab_size
846
+ if tab_remainder:
847
+ spaces = tab_size - tab_remainder
848
+ part.extend_style(spaces)
849
+ cell_position += spaces
850
+ else:
851
+ cell_position += part.cell_len
852
+ append(part)
853
+
854
+ result = Text("").join(new_text)
855
+
856
+ self._text = [result.plain]
857
+ self._length = len(self.plain)
858
+ self._spans[:] = result._spans
859
+
860
+ def truncate(
861
+ self,
862
+ max_width: int,
863
+ *,
864
+ overflow: Optional["OverflowMethod"] = None,
865
+ pad: bool = False,
866
+ ) -> None:
867
+ """Truncate text if it is longer that a given width.
868
+
869
+ Args:
870
+ max_width (int): Maximum number of characters in text.
871
+ overflow (str, optional): Overflow method: "crop", "fold", or "ellipsis". Defaults to None, to use self.overflow.
872
+ pad (bool, optional): Pad with spaces if the length is less than max_width. Defaults to False.
873
+ """
874
+ _overflow = overflow or self.overflow or DEFAULT_OVERFLOW
875
+ if _overflow != "ignore":
876
+ length = cell_len(self.plain)
877
+ if length > max_width:
878
+ if _overflow == "ellipsis":
879
+ self.plain = set_cell_size(self.plain, max_width - 1) + "…"
880
+ else:
881
+ self.plain = set_cell_size(self.plain, max_width)
882
+ if pad and length < max_width:
883
+ spaces = max_width - length
884
+ self._text = [f"{self.plain}{' ' * spaces}"]
885
+ self._length = len(self.plain)
886
+
887
+ def _trim_spans(self) -> None:
888
+ """Remove or modify any spans that are over the end of the text."""
889
+ max_offset = len(self.plain)
890
+ _Span = Span
891
+ self._spans[:] = [
892
+ (
893
+ span
894
+ if span.end < max_offset
895
+ else _Span(span.start, min(max_offset, span.end), span.style)
896
+ )
897
+ for span in self._spans
898
+ if span.start < max_offset
899
+ ]
900
+
901
+ def pad(self, count: int, character: str = " ") -> None:
902
+ """Pad left and right with a given number of characters.
903
+
904
+ Args:
905
+ count (int): Width of padding.
906
+ character (str): The character to pad with. Must be a string of length 1.
907
+ """
908
+ assert len(character) == 1, "Character must be a string of length 1"
909
+ if count:
910
+ pad_characters = character * count
911
+ self.plain = f"{pad_characters}{self.plain}{pad_characters}"
912
+ _Span = Span
913
+ self._spans[:] = [
914
+ _Span(start + count, end + count, style)
915
+ for start, end, style in self._spans
916
+ ]
917
+
918
+ def pad_left(self, count: int, character: str = " ") -> None:
919
+ """Pad the left with a given character.
920
+
921
+ Args:
922
+ count (int): Number of characters to pad.
923
+ character (str, optional): Character to pad with. Defaults to " ".
924
+ """
925
+ assert len(character) == 1, "Character must be a string of length 1"
926
+ if count:
927
+ self.plain = f"{character * count}{self.plain}"
928
+ _Span = Span
929
+ self._spans[:] = [
930
+ _Span(start + count, end + count, style)
931
+ for start, end, style in self._spans
932
+ ]
933
+
934
+ def pad_right(self, count: int, character: str = " ") -> None:
935
+ """Pad the right with a given character.
936
+
937
+ Args:
938
+ count (int): Number of characters to pad.
939
+ character (str, optional): Character to pad with. Defaults to " ".
940
+ """
941
+ assert len(character) == 1, "Character must be a string of length 1"
942
+ if count:
943
+ self.plain = f"{self.plain}{character * count}"
944
+
945
+ def align(self, align: AlignMethod, width: int, character: str = " ") -> None:
946
+ """Align text to a given width.
947
+
948
+ Args:
949
+ align (AlignMethod): One of "left", "center", or "right".
950
+ width (int): Desired width.
951
+ character (str, optional): Character to pad with. Defaults to " ".
952
+ """
953
+ self.truncate(width)
954
+ excess_space = width - cell_len(self.plain)
955
+ if excess_space:
956
+ if align == "left":
957
+ self.pad_right(excess_space, character)
958
+ elif align == "center":
959
+ left = excess_space // 2
960
+ self.pad_left(left, character)
961
+ self.pad_right(excess_space - left, character)
962
+ else:
963
+ self.pad_left(excess_space, character)
964
+
965
+ def append(
966
+ self, text: Union["Text", str], style: Optional[Union[str, "Style"]] = None
967
+ ) -> "Text":
968
+ """Add text with an optional style.
969
+
970
+ Args:
971
+ text (Union[Text, str]): A str or Text to append.
972
+ style (str, optional): A style name. Defaults to None.
973
+
974
+ Returns:
975
+ Text: Returns self for chaining.
976
+ """
977
+
978
+ if not isinstance(text, (str, Text)):
979
+ raise TypeError("Only str or Text can be appended to Text")
980
+
981
+ if len(text):
982
+ if isinstance(text, str):
983
+ sanitized_text = strip_control_codes(text)
984
+ self._text.append(sanitized_text)
985
+ offset = len(self)
986
+ text_length = len(sanitized_text)
987
+ if style:
988
+ self._spans.append(Span(offset, offset + text_length, style))
989
+ self._length += text_length
990
+ elif isinstance(text, Text):
991
+ _Span = Span
992
+ if style is not None:
993
+ raise ValueError(
994
+ "style must not be set when appending Text instance"
995
+ )
996
+ text_length = self._length
997
+ if text.style:
998
+ self._spans.append(
999
+ _Span(text_length, text_length + len(text), text.style)
1000
+ )
1001
+ self._text.append(text.plain)
1002
+ self._spans.extend(
1003
+ _Span(start + text_length, end + text_length, style)
1004
+ for start, end, style in text._spans.copy()
1005
+ )
1006
+ self._length += len(text)
1007
+ return self
1008
+
1009
+ def append_text(self, text: "Text") -> "Text":
1010
+ """Append another Text instance. This method is more performant that Text.append, but
1011
+ only works for Text.
1012
+
1013
+ Args:
1014
+ text (Text): The Text instance to append to this instance.
1015
+
1016
+ Returns:
1017
+ Text: Returns self for chaining.
1018
+ """
1019
+ _Span = Span
1020
+ text_length = self._length
1021
+ if text.style:
1022
+ self._spans.append(_Span(text_length, text_length + len(text), text.style))
1023
+ self._text.append(text.plain)
1024
+ self._spans.extend(
1025
+ _Span(start + text_length, end + text_length, style)
1026
+ for start, end, style in text._spans.copy()
1027
+ )
1028
+ self._length += len(text)
1029
+ return self
1030
+
1031
+ def append_tokens(
1032
+ self, tokens: Iterable[Tuple[str, Optional[StyleType]]]
1033
+ ) -> "Text":
1034
+ """Append iterable of str and style. Style may be a Style instance or a str style definition.
1035
+
1036
+ Args:
1037
+ tokens (Iterable[Tuple[str, Optional[StyleType]]]): An iterable of tuples containing str content and style.
1038
+
1039
+ Returns:
1040
+ Text: Returns self for chaining.
1041
+ """
1042
+ append_text = self._text.append
1043
+ append_span = self._spans.append
1044
+ _Span = Span
1045
+ offset = len(self)
1046
+ for content, style in tokens:
1047
+ content = strip_control_codes(content)
1048
+ append_text(content)
1049
+ if style:
1050
+ append_span(_Span(offset, offset + len(content), style))
1051
+ offset += len(content)
1052
+ self._length = offset
1053
+ return self
1054
+
1055
+ def copy_styles(self, text: "Text") -> None:
1056
+ """Copy styles from another Text instance.
1057
+
1058
+ Args:
1059
+ text (Text): A Text instance to copy styles from, must be the same length.
1060
+ """
1061
+ self._spans.extend(text._spans)
1062
+
1063
+ def split(
1064
+ self,
1065
+ separator: str = "\n",
1066
+ *,
1067
+ include_separator: bool = False,
1068
+ allow_blank: bool = False,
1069
+ ) -> Lines:
1070
+ """Split rich text in to lines, preserving styles.
1071
+
1072
+ Args:
1073
+ separator (str, optional): String to split on. Defaults to "\\\\n".
1074
+ include_separator (bool, optional): Include the separator in the lines. Defaults to False.
1075
+ allow_blank (bool, optional): Return a blank line if the text ends with a separator. Defaults to False.
1076
+
1077
+ Returns:
1078
+ List[RichText]: A list of rich text, one per line of the original.
1079
+ """
1080
+ assert separator, "separator must not be empty"
1081
+
1082
+ text = self.plain
1083
+ if separator not in text:
1084
+ return Lines([self.copy()])
1085
+
1086
+ if include_separator:
1087
+ lines = self.divide(
1088
+ match.end() for match in re.finditer(re.escape(separator), text)
1089
+ )
1090
+ else:
1091
+
1092
+ def flatten_spans() -> Iterable[int]:
1093
+ for match in re.finditer(re.escape(separator), text):
1094
+ start, end = match.span()
1095
+ yield start
1096
+ yield end
1097
+
1098
+ lines = Lines(
1099
+ line for line in self.divide(flatten_spans()) if line.plain != separator
1100
+ )
1101
+
1102
+ if not allow_blank and text.endswith(separator):
1103
+ lines.pop()
1104
+
1105
+ return lines
1106
+
1107
+ def divide(self, offsets: Iterable[int]) -> Lines:
1108
+ """Divide text in to a number of lines at given offsets.
1109
+
1110
+ Args:
1111
+ offsets (Iterable[int]): Offsets used to divide text.
1112
+
1113
+ Returns:
1114
+ Lines: New RichText instances between offsets.
1115
+ """
1116
+ _offsets = list(offsets)
1117
+
1118
+ if not _offsets:
1119
+ return Lines([self.copy()])
1120
+
1121
+ text = self.plain
1122
+ text_length = len(text)
1123
+ divide_offsets = [0, *_offsets, text_length]
1124
+ line_ranges = list(zip(divide_offsets, divide_offsets[1:]))
1125
+
1126
+ style = self.style
1127
+ justify = self.justify
1128
+ overflow = self.overflow
1129
+ _Text = Text
1130
+ new_lines = Lines(
1131
+ _Text(
1132
+ text[start:end],
1133
+ style=style,
1134
+ justify=justify,
1135
+ overflow=overflow,
1136
+ )
1137
+ for start, end in line_ranges
1138
+ )
1139
+ if not self._spans:
1140
+ return new_lines
1141
+
1142
+ _line_appends = [line._spans.append for line in new_lines._lines]
1143
+ line_count = len(line_ranges)
1144
+ _Span = Span
1145
+
1146
+ for span_start, span_end, style in self._spans:
1147
+ lower_bound = 0
1148
+ upper_bound = line_count
1149
+ start_line_no = (lower_bound + upper_bound) // 2
1150
+
1151
+ while True:
1152
+ line_start, line_end = line_ranges[start_line_no]
1153
+ if span_start < line_start:
1154
+ upper_bound = start_line_no - 1
1155
+ elif span_start > line_end:
1156
+ lower_bound = start_line_no + 1
1157
+ else:
1158
+ break
1159
+ start_line_no = (lower_bound + upper_bound) // 2
1160
+
1161
+ if span_end < line_end:
1162
+ end_line_no = start_line_no
1163
+ else:
1164
+ end_line_no = lower_bound = start_line_no
1165
+ upper_bound = line_count
1166
+
1167
+ while True:
1168
+ line_start, line_end = line_ranges[end_line_no]
1169
+ if span_end < line_start:
1170
+ upper_bound = end_line_no - 1
1171
+ elif span_end > line_end:
1172
+ lower_bound = end_line_no + 1
1173
+ else:
1174
+ break
1175
+ end_line_no = (lower_bound + upper_bound) // 2
1176
+
1177
+ for line_no in range(start_line_no, end_line_no + 1):
1178
+ line_start, line_end = line_ranges[line_no]
1179
+ new_start = max(0, span_start - line_start)
1180
+ new_end = min(span_end - line_start, line_end - line_start)
1181
+ if new_end > new_start:
1182
+ _line_appends[line_no](_Span(new_start, new_end, style))
1183
+
1184
+ return new_lines
1185
+
1186
+ def right_crop(self, amount: int = 1) -> None:
1187
+ """Remove a number of characters from the end of the text."""
1188
+ max_offset = len(self.plain) - amount
1189
+ _Span = Span
1190
+ self._spans[:] = [
1191
+ (
1192
+ span
1193
+ if span.end < max_offset
1194
+ else _Span(span.start, min(max_offset, span.end), span.style)
1195
+ )
1196
+ for span in self._spans
1197
+ if span.start < max_offset
1198
+ ]
1199
+ self._text = [self.plain[:-amount]]
1200
+ self._length -= amount
1201
+
1202
+ def wrap(
1203
+ self,
1204
+ console: "Console",
1205
+ width: int,
1206
+ *,
1207
+ justify: Optional["JustifyMethod"] = None,
1208
+ overflow: Optional["OverflowMethod"] = None,
1209
+ tab_size: int = 8,
1210
+ no_wrap: Optional[bool] = None,
1211
+ ) -> Lines:
1212
+ """Word wrap the text.
1213
+
1214
+ Args:
1215
+ console (Console): Console instance.
1216
+ width (int): Number of cells available per line.
1217
+ justify (str, optional): Justify method: "default", "left", "center", "full", "right". Defaults to "default".
1218
+ overflow (str, optional): Overflow method: "crop", "fold", or "ellipsis". Defaults to None.
1219
+ tab_size (int, optional): Default tab size. Defaults to 8.
1220
+ no_wrap (bool, optional): Disable wrapping, Defaults to False.
1221
+
1222
+ Returns:
1223
+ Lines: Number of lines.
1224
+ """
1225
+ wrap_justify = justify or self.justify or DEFAULT_JUSTIFY
1226
+ wrap_overflow = overflow or self.overflow or DEFAULT_OVERFLOW
1227
+
1228
+ no_wrap = pick_bool(no_wrap, self.no_wrap, False) or overflow == "ignore"
1229
+
1230
+ lines = Lines()
1231
+ for line in self.split(allow_blank=True):
1232
+ if "\t" in line:
1233
+ line.expand_tabs(tab_size)
1234
+ if no_wrap:
1235
+ new_lines = Lines([line])
1236
+ else:
1237
+ offsets = divide_line(str(line), width, fold=wrap_overflow == "fold")
1238
+ new_lines = line.divide(offsets)
1239
+ for line in new_lines:
1240
+ line.rstrip_end(width)
1241
+ if wrap_justify:
1242
+ new_lines.justify(
1243
+ console, width, justify=wrap_justify, overflow=wrap_overflow
1244
+ )
1245
+ for line in new_lines:
1246
+ line.truncate(width, overflow=wrap_overflow)
1247
+ lines.extend(new_lines)
1248
+ return lines
1249
+
1250
+ def fit(self, width: int) -> Lines:
1251
+ """Fit the text in to given width by chopping in to lines.
1252
+
1253
+ Args:
1254
+ width (int): Maximum characters in a line.
1255
+
1256
+ Returns:
1257
+ Lines: Lines container.
1258
+ """
1259
+ lines: Lines = Lines()
1260
+ append = lines.append
1261
+ for line in self.split():
1262
+ line.set_length(width)
1263
+ append(line)
1264
+ return lines
1265
+
1266
+ def detect_indentation(self) -> int:
1267
+ """Auto-detect indentation of code.
1268
+
1269
+ Returns:
1270
+ int: Number of spaces used to indent code.
1271
+ """
1272
+
1273
+ _indentations = {
1274
+ len(match.group(1))
1275
+ for match in re.finditer(r"^( *)(.*)$", self.plain, flags=re.MULTILINE)
1276
+ }
1277
+
1278
+ try:
1279
+ indentation = (
1280
+ reduce(gcd, [indent for indent in _indentations if not indent % 2]) or 1
1281
+ )
1282
+ except TypeError:
1283
+ indentation = 1
1284
+
1285
+ return indentation
1286
+
1287
+ def with_indent_guides(
1288
+ self,
1289
+ indent_size: Optional[int] = None,
1290
+ *,
1291
+ character: str = "│",
1292
+ style: StyleType = "dim green",
1293
+ ) -> "Text":
1294
+ """Adds indent guide lines to text.
1295
+
1296
+ Args:
1297
+ indent_size (Optional[int]): Size of indentation, or None to auto detect. Defaults to None.
1298
+ character (str, optional): Character to use for indentation. Defaults to "│".
1299
+ style (Union[Style, str], optional): Style of indent guides.
1300
+
1301
+ Returns:
1302
+ Text: New text with indentation guides.
1303
+ """
1304
+
1305
+ _indent_size = self.detect_indentation() if indent_size is None else indent_size
1306
+
1307
+ text = self.copy()
1308
+ text.expand_tabs()
1309
+ indent_line = f"{character}{' ' * (_indent_size - 1)}"
1310
+
1311
+ re_indent = re.compile(r"^( *)(.*)$")
1312
+ new_lines: List[Text] = []
1313
+ add_line = new_lines.append
1314
+ blank_lines = 0
1315
+ for line in text.split(allow_blank=True):
1316
+ match = re_indent.match(line.plain)
1317
+ if not match or not match.group(2):
1318
+ blank_lines += 1
1319
+ continue
1320
+ indent = match.group(1)
1321
+ full_indents, remaining_space = divmod(len(indent), _indent_size)
1322
+ new_indent = f"{indent_line * full_indents}{' ' * remaining_space}"
1323
+ line.plain = new_indent + line.plain[len(new_indent) :]
1324
+ line.stylize(style, 0, len(new_indent))
1325
+ if blank_lines:
1326
+ new_lines.extend([Text(new_indent, style=style)] * blank_lines)
1327
+ blank_lines = 0
1328
+ add_line(line)
1329
+ if blank_lines:
1330
+ new_lines.extend([Text("", style=style)] * blank_lines)
1331
+
1332
+ new_text = text.blank_copy("\n").join(new_lines)
1333
+ return new_text
1334
+
1335
+
1336
+ if __name__ == "__main__": # pragma: no cover
1337
+ from pip._vendor.rich.console import Console
1338
+
1339
+ text = Text(
1340
+ """\nLorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.\n"""
1341
+ )
1342
+ text.highlight_words(["Lorem"], "bold")
1343
+ text.highlight_words(["ipsum"], "italic")
1344
+
1345
+ console = Console()
1346
+
1347
+ console.rule("justify='left'")
1348
+ console.print(text, style="red")
1349
+ console.print()
1350
+
1351
+ console.rule("justify='center'")
1352
+ console.print(text, style="green", justify="center")
1353
+ console.print()
1354
+
1355
+ console.rule("justify='right'")
1356
+ console.print(text, style="blue", justify="right")
1357
+ console.print()
1358
+
1359
+ console.rule("justify='full'")
1360
+ console.print(text, style="magenta", justify="full")
1361
+ console.print()
llava/lib/python3.10/site-packages/pip/_vendor/rich/theme.py ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import configparser
2
+ from typing import IO, Dict, List, Mapping, Optional
3
+
4
+ from .default_styles import DEFAULT_STYLES
5
+ from .style import Style, StyleType
6
+
7
+
8
+ class Theme:
9
+ """A container for style information, used by :class:`~rich.console.Console`.
10
+
11
+ Args:
12
+ styles (Dict[str, Style], optional): A mapping of style names on to styles. Defaults to None for a theme with no styles.
13
+ inherit (bool, optional): Inherit default styles. Defaults to True.
14
+ """
15
+
16
+ styles: Dict[str, Style]
17
+
18
+ def __init__(
19
+ self, styles: Optional[Mapping[str, StyleType]] = None, inherit: bool = True
20
+ ):
21
+ self.styles = DEFAULT_STYLES.copy() if inherit else {}
22
+ if styles is not None:
23
+ self.styles.update(
24
+ {
25
+ name: style if isinstance(style, Style) else Style.parse(style)
26
+ for name, style in styles.items()
27
+ }
28
+ )
29
+
30
+ @property
31
+ def config(self) -> str:
32
+ """Get contents of a config file for this theme."""
33
+ config = "[styles]\n" + "\n".join(
34
+ f"{name} = {style}" for name, style in sorted(self.styles.items())
35
+ )
36
+ return config
37
+
38
+ @classmethod
39
+ def from_file(
40
+ cls, config_file: IO[str], source: Optional[str] = None, inherit: bool = True
41
+ ) -> "Theme":
42
+ """Load a theme from a text mode file.
43
+
44
+ Args:
45
+ config_file (IO[str]): An open conf file.
46
+ source (str, optional): The filename of the open file. Defaults to None.
47
+ inherit (bool, optional): Inherit default styles. Defaults to True.
48
+
49
+ Returns:
50
+ Theme: A New theme instance.
51
+ """
52
+ config = configparser.ConfigParser()
53
+ config.read_file(config_file, source=source)
54
+ styles = {name: Style.parse(value) for name, value in config.items("styles")}
55
+ theme = Theme(styles, inherit=inherit)
56
+ return theme
57
+
58
+ @classmethod
59
+ def read(
60
+ cls, path: str, inherit: bool = True, encoding: Optional[str] = None
61
+ ) -> "Theme":
62
+ """Read a theme from a path.
63
+
64
+ Args:
65
+ path (str): Path to a config file readable by Python configparser module.
66
+ inherit (bool, optional): Inherit default styles. Defaults to True.
67
+ encoding (str, optional): Encoding of the config file. Defaults to None.
68
+
69
+ Returns:
70
+ Theme: A new theme instance.
71
+ """
72
+ with open(path, encoding=encoding) as config_file:
73
+ return cls.from_file(config_file, source=path, inherit=inherit)
74
+
75
+
76
+ class ThemeStackError(Exception):
77
+ """Base exception for errors related to the theme stack."""
78
+
79
+
80
+ class ThemeStack:
81
+ """A stack of themes.
82
+
83
+ Args:
84
+ theme (Theme): A theme instance
85
+ """
86
+
87
+ def __init__(self, theme: Theme) -> None:
88
+ self._entries: List[Dict[str, Style]] = [theme.styles]
89
+ self.get = self._entries[-1].get
90
+
91
+ def push_theme(self, theme: Theme, inherit: bool = True) -> None:
92
+ """Push a theme on the top of the stack.
93
+
94
+ Args:
95
+ theme (Theme): A Theme instance.
96
+ inherit (boolean, optional): Inherit styles from current top of stack.
97
+ """
98
+ styles: Dict[str, Style]
99
+ styles = (
100
+ {**self._entries[-1], **theme.styles} if inherit else theme.styles.copy()
101
+ )
102
+ self._entries.append(styles)
103
+ self.get = self._entries[-1].get
104
+
105
+ def pop_theme(self) -> None:
106
+ """Pop (and discard) the top-most theme."""
107
+ if len(self._entries) == 1:
108
+ raise ThemeStackError("Unable to pop base theme")
109
+ self._entries.pop()
110
+ self.get = self._entries[-1].get
111
+
112
+
113
+ if __name__ == "__main__": # pragma: no cover
114
+ theme = Theme()
115
+ print(theme.config)
llava/lib/python3.10/site-packages/pip/_vendor/rich/traceback.py ADDED
@@ -0,0 +1,797 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import inspect
2
+ import linecache
3
+ import os
4
+ import sys
5
+ from dataclasses import dataclass, field
6
+ from itertools import islice
7
+ from traceback import walk_tb
8
+ from types import ModuleType, TracebackType
9
+ from typing import (
10
+ Any,
11
+ Callable,
12
+ Dict,
13
+ Iterable,
14
+ List,
15
+ Optional,
16
+ Sequence,
17
+ Tuple,
18
+ Type,
19
+ Union,
20
+ )
21
+
22
+ from pip._vendor.pygments.lexers import guess_lexer_for_filename
23
+ from pip._vendor.pygments.token import Comment, Keyword, Name, Number, Operator, String
24
+ from pip._vendor.pygments.token import Text as TextToken
25
+ from pip._vendor.pygments.token import Token
26
+ from pip._vendor.pygments.util import ClassNotFound
27
+
28
+ from . import pretty
29
+ from ._loop import loop_last
30
+ from .columns import Columns
31
+ from .console import Console, ConsoleOptions, ConsoleRenderable, RenderResult, group
32
+ from .constrain import Constrain
33
+ from .highlighter import RegexHighlighter, ReprHighlighter
34
+ from .panel import Panel
35
+ from .scope import render_scope
36
+ from .style import Style
37
+ from .syntax import Syntax
38
+ from .text import Text
39
+ from .theme import Theme
40
+
41
+ WINDOWS = sys.platform == "win32"
42
+
43
+ LOCALS_MAX_LENGTH = 10
44
+ LOCALS_MAX_STRING = 80
45
+
46
+
47
+ def install(
48
+ *,
49
+ console: Optional[Console] = None,
50
+ width: Optional[int] = 100,
51
+ code_width: Optional[int] = 88,
52
+ extra_lines: int = 3,
53
+ theme: Optional[str] = None,
54
+ word_wrap: bool = False,
55
+ show_locals: bool = False,
56
+ locals_max_length: int = LOCALS_MAX_LENGTH,
57
+ locals_max_string: int = LOCALS_MAX_STRING,
58
+ locals_hide_dunder: bool = True,
59
+ locals_hide_sunder: Optional[bool] = None,
60
+ indent_guides: bool = True,
61
+ suppress: Iterable[Union[str, ModuleType]] = (),
62
+ max_frames: int = 100,
63
+ ) -> Callable[[Type[BaseException], BaseException, Optional[TracebackType]], Any]:
64
+ """Install a rich traceback handler.
65
+
66
+ Once installed, any tracebacks will be printed with syntax highlighting and rich formatting.
67
+
68
+
69
+ Args:
70
+ console (Optional[Console], optional): Console to write exception to. Default uses internal Console instance.
71
+ width (Optional[int], optional): Width (in characters) of traceback. Defaults to 100.
72
+ code_width (Optional[int], optional): Code width (in characters) of traceback. Defaults to 88.
73
+ extra_lines (int, optional): Extra lines of code. Defaults to 3.
74
+ theme (Optional[str], optional): Pygments theme to use in traceback. Defaults to ``None`` which will pick
75
+ a theme appropriate for the platform.
76
+ word_wrap (bool, optional): Enable word wrapping of long lines. Defaults to False.
77
+ show_locals (bool, optional): Enable display of local variables. Defaults to False.
78
+ locals_max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation.
79
+ Defaults to 10.
80
+ locals_max_string (int, optional): Maximum length of string before truncating, or None to disable. Defaults to 80.
81
+ locals_hide_dunder (bool, optional): Hide locals prefixed with double underscore. Defaults to True.
82
+ locals_hide_sunder (bool, optional): Hide locals prefixed with single underscore. Defaults to False.
83
+ indent_guides (bool, optional): Enable indent guides in code and locals. Defaults to True.
84
+ suppress (Sequence[Union[str, ModuleType]]): Optional sequence of modules or paths to exclude from traceback.
85
+
86
+ Returns:
87
+ Callable: The previous exception handler that was replaced.
88
+
89
+ """
90
+ traceback_console = Console(stderr=True) if console is None else console
91
+
92
+ locals_hide_sunder = (
93
+ True
94
+ if (traceback_console.is_jupyter and locals_hide_sunder is None)
95
+ else locals_hide_sunder
96
+ )
97
+
98
+ def excepthook(
99
+ type_: Type[BaseException],
100
+ value: BaseException,
101
+ traceback: Optional[TracebackType],
102
+ ) -> None:
103
+ traceback_console.print(
104
+ Traceback.from_exception(
105
+ type_,
106
+ value,
107
+ traceback,
108
+ width=width,
109
+ code_width=code_width,
110
+ extra_lines=extra_lines,
111
+ theme=theme,
112
+ word_wrap=word_wrap,
113
+ show_locals=show_locals,
114
+ locals_max_length=locals_max_length,
115
+ locals_max_string=locals_max_string,
116
+ locals_hide_dunder=locals_hide_dunder,
117
+ locals_hide_sunder=bool(locals_hide_sunder),
118
+ indent_guides=indent_guides,
119
+ suppress=suppress,
120
+ max_frames=max_frames,
121
+ )
122
+ )
123
+
124
+ def ipy_excepthook_closure(ip: Any) -> None: # pragma: no cover
125
+ tb_data = {} # store information about showtraceback call
126
+ default_showtraceback = ip.showtraceback # keep reference of default traceback
127
+
128
+ def ipy_show_traceback(*args: Any, **kwargs: Any) -> None:
129
+ """wrap the default ip.showtraceback to store info for ip._showtraceback"""
130
+ nonlocal tb_data
131
+ tb_data = kwargs
132
+ default_showtraceback(*args, **kwargs)
133
+
134
+ def ipy_display_traceback(
135
+ *args: Any, is_syntax: bool = False, **kwargs: Any
136
+ ) -> None:
137
+ """Internally called traceback from ip._showtraceback"""
138
+ nonlocal tb_data
139
+ exc_tuple = ip._get_exc_info()
140
+
141
+ # do not display trace on syntax error
142
+ tb: Optional[TracebackType] = None if is_syntax else exc_tuple[2]
143
+
144
+ # determine correct tb_offset
145
+ compiled = tb_data.get("running_compiled_code", False)
146
+ tb_offset = tb_data.get("tb_offset", 1 if compiled else 0)
147
+ # remove ipython internal frames from trace with tb_offset
148
+ for _ in range(tb_offset):
149
+ if tb is None:
150
+ break
151
+ tb = tb.tb_next
152
+
153
+ excepthook(exc_tuple[0], exc_tuple[1], tb)
154
+ tb_data = {} # clear data upon usage
155
+
156
+ # replace _showtraceback instead of showtraceback to allow ipython features such as debugging to work
157
+ # this is also what the ipython docs recommends to modify when subclassing InteractiveShell
158
+ ip._showtraceback = ipy_display_traceback
159
+ # add wrapper to capture tb_data
160
+ ip.showtraceback = ipy_show_traceback
161
+ ip.showsyntaxerror = lambda *args, **kwargs: ipy_display_traceback(
162
+ *args, is_syntax=True, **kwargs
163
+ )
164
+
165
+ try: # pragma: no cover
166
+ # if within ipython, use customized traceback
167
+ ip = get_ipython() # type: ignore[name-defined]
168
+ ipy_excepthook_closure(ip)
169
+ return sys.excepthook
170
+ except Exception:
171
+ # otherwise use default system hook
172
+ old_excepthook = sys.excepthook
173
+ sys.excepthook = excepthook
174
+ return old_excepthook
175
+
176
+
177
+ @dataclass
178
+ class Frame:
179
+ filename: str
180
+ lineno: int
181
+ name: str
182
+ line: str = ""
183
+ locals: Optional[Dict[str, pretty.Node]] = None
184
+ last_instruction: Optional[Tuple[Tuple[int, int], Tuple[int, int]]] = None
185
+
186
+
187
+ @dataclass
188
+ class _SyntaxError:
189
+ offset: int
190
+ filename: str
191
+ line: str
192
+ lineno: int
193
+ msg: str
194
+
195
+
196
+ @dataclass
197
+ class Stack:
198
+ exc_type: str
199
+ exc_value: str
200
+ syntax_error: Optional[_SyntaxError] = None
201
+ is_cause: bool = False
202
+ frames: List[Frame] = field(default_factory=list)
203
+
204
+
205
+ @dataclass
206
+ class Trace:
207
+ stacks: List[Stack]
208
+
209
+
210
+ class PathHighlighter(RegexHighlighter):
211
+ highlights = [r"(?P<dim>.*/)(?P<bold>.+)"]
212
+
213
+
214
+ class Traceback:
215
+ """A Console renderable that renders a traceback.
216
+
217
+ Args:
218
+ trace (Trace, optional): A `Trace` object produced from `extract`. Defaults to None, which uses
219
+ the last exception.
220
+ width (Optional[int], optional): Number of characters used to traceback. Defaults to 100.
221
+ code_width (Optional[int], optional): Number of code characters used to traceback. Defaults to 88.
222
+ extra_lines (int, optional): Additional lines of code to render. Defaults to 3.
223
+ theme (str, optional): Override pygments theme used in traceback.
224
+ word_wrap (bool, optional): Enable word wrapping of long lines. Defaults to False.
225
+ show_locals (bool, optional): Enable display of local variables. Defaults to False.
226
+ indent_guides (bool, optional): Enable indent guides in code and locals. Defaults to True.
227
+ locals_max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation.
228
+ Defaults to 10.
229
+ locals_max_string (int, optional): Maximum length of string before truncating, or None to disable. Defaults to 80.
230
+ locals_hide_dunder (bool, optional): Hide locals prefixed with double underscore. Defaults to True.
231
+ locals_hide_sunder (bool, optional): Hide locals prefixed with single underscore. Defaults to False.
232
+ suppress (Sequence[Union[str, ModuleType]]): Optional sequence of modules or paths to exclude from traceback.
233
+ max_frames (int): Maximum number of frames to show in a traceback, 0 for no maximum. Defaults to 100.
234
+
235
+ """
236
+
237
+ LEXERS = {
238
+ "": "text",
239
+ ".py": "python",
240
+ ".pxd": "cython",
241
+ ".pyx": "cython",
242
+ ".pxi": "pyrex",
243
+ }
244
+
245
+ def __init__(
246
+ self,
247
+ trace: Optional[Trace] = None,
248
+ *,
249
+ width: Optional[int] = 100,
250
+ code_width: Optional[int] = 88,
251
+ extra_lines: int = 3,
252
+ theme: Optional[str] = None,
253
+ word_wrap: bool = False,
254
+ show_locals: bool = False,
255
+ locals_max_length: int = LOCALS_MAX_LENGTH,
256
+ locals_max_string: int = LOCALS_MAX_STRING,
257
+ locals_hide_dunder: bool = True,
258
+ locals_hide_sunder: bool = False,
259
+ indent_guides: bool = True,
260
+ suppress: Iterable[Union[str, ModuleType]] = (),
261
+ max_frames: int = 100,
262
+ ):
263
+ if trace is None:
264
+ exc_type, exc_value, traceback = sys.exc_info()
265
+ if exc_type is None or exc_value is None or traceback is None:
266
+ raise ValueError(
267
+ "Value for 'trace' required if not called in except: block"
268
+ )
269
+ trace = self.extract(
270
+ exc_type, exc_value, traceback, show_locals=show_locals
271
+ )
272
+ self.trace = trace
273
+ self.width = width
274
+ self.code_width = code_width
275
+ self.extra_lines = extra_lines
276
+ self.theme = Syntax.get_theme(theme or "ansi_dark")
277
+ self.word_wrap = word_wrap
278
+ self.show_locals = show_locals
279
+ self.indent_guides = indent_guides
280
+ self.locals_max_length = locals_max_length
281
+ self.locals_max_string = locals_max_string
282
+ self.locals_hide_dunder = locals_hide_dunder
283
+ self.locals_hide_sunder = locals_hide_sunder
284
+
285
+ self.suppress: Sequence[str] = []
286
+ for suppress_entity in suppress:
287
+ if not isinstance(suppress_entity, str):
288
+ assert (
289
+ suppress_entity.__file__ is not None
290
+ ), f"{suppress_entity!r} must be a module with '__file__' attribute"
291
+ path = os.path.dirname(suppress_entity.__file__)
292
+ else:
293
+ path = suppress_entity
294
+ path = os.path.normpath(os.path.abspath(path))
295
+ self.suppress.append(path)
296
+ self.max_frames = max(4, max_frames) if max_frames > 0 else 0
297
+
298
+ @classmethod
299
+ def from_exception(
300
+ cls,
301
+ exc_type: Type[Any],
302
+ exc_value: BaseException,
303
+ traceback: Optional[TracebackType],
304
+ *,
305
+ width: Optional[int] = 100,
306
+ code_width: Optional[int] = 88,
307
+ extra_lines: int = 3,
308
+ theme: Optional[str] = None,
309
+ word_wrap: bool = False,
310
+ show_locals: bool = False,
311
+ locals_max_length: int = LOCALS_MAX_LENGTH,
312
+ locals_max_string: int = LOCALS_MAX_STRING,
313
+ locals_hide_dunder: bool = True,
314
+ locals_hide_sunder: bool = False,
315
+ indent_guides: bool = True,
316
+ suppress: Iterable[Union[str, ModuleType]] = (),
317
+ max_frames: int = 100,
318
+ ) -> "Traceback":
319
+ """Create a traceback from exception info
320
+
321
+ Args:
322
+ exc_type (Type[BaseException]): Exception type.
323
+ exc_value (BaseException): Exception value.
324
+ traceback (TracebackType): Python Traceback object.
325
+ width (Optional[int], optional): Number of characters used to traceback. Defaults to 100.
326
+ code_width (Optional[int], optional): Number of code characters used to traceback. Defaults to 88.
327
+ extra_lines (int, optional): Additional lines of code to render. Defaults to 3.
328
+ theme (str, optional): Override pygments theme used in traceback.
329
+ word_wrap (bool, optional): Enable word wrapping of long lines. Defaults to False.
330
+ show_locals (bool, optional): Enable display of local variables. Defaults to False.
331
+ indent_guides (bool, optional): Enable indent guides in code and locals. Defaults to True.
332
+ locals_max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation.
333
+ Defaults to 10.
334
+ locals_max_string (int, optional): Maximum length of string before truncating, or None to disable. Defaults to 80.
335
+ locals_hide_dunder (bool, optional): Hide locals prefixed with double underscore. Defaults to True.
336
+ locals_hide_sunder (bool, optional): Hide locals prefixed with single underscore. Defaults to False.
337
+ suppress (Iterable[Union[str, ModuleType]]): Optional sequence of modules or paths to exclude from traceback.
338
+ max_frames (int): Maximum number of frames to show in a traceback, 0 for no maximum. Defaults to 100.
339
+
340
+ Returns:
341
+ Traceback: A Traceback instance that may be printed.
342
+ """
343
+ rich_traceback = cls.extract(
344
+ exc_type,
345
+ exc_value,
346
+ traceback,
347
+ show_locals=show_locals,
348
+ locals_max_length=locals_max_length,
349
+ locals_max_string=locals_max_string,
350
+ locals_hide_dunder=locals_hide_dunder,
351
+ locals_hide_sunder=locals_hide_sunder,
352
+ )
353
+
354
+ return cls(
355
+ rich_traceback,
356
+ width=width,
357
+ code_width=code_width,
358
+ extra_lines=extra_lines,
359
+ theme=theme,
360
+ word_wrap=word_wrap,
361
+ show_locals=show_locals,
362
+ indent_guides=indent_guides,
363
+ locals_max_length=locals_max_length,
364
+ locals_max_string=locals_max_string,
365
+ locals_hide_dunder=locals_hide_dunder,
366
+ locals_hide_sunder=locals_hide_sunder,
367
+ suppress=suppress,
368
+ max_frames=max_frames,
369
+ )
370
+
371
+ @classmethod
372
+ def extract(
373
+ cls,
374
+ exc_type: Type[BaseException],
375
+ exc_value: BaseException,
376
+ traceback: Optional[TracebackType],
377
+ *,
378
+ show_locals: bool = False,
379
+ locals_max_length: int = LOCALS_MAX_LENGTH,
380
+ locals_max_string: int = LOCALS_MAX_STRING,
381
+ locals_hide_dunder: bool = True,
382
+ locals_hide_sunder: bool = False,
383
+ ) -> Trace:
384
+ """Extract traceback information.
385
+
386
+ Args:
387
+ exc_type (Type[BaseException]): Exception type.
388
+ exc_value (BaseException): Exception value.
389
+ traceback (TracebackType): Python Traceback object.
390
+ show_locals (bool, optional): Enable display of local variables. Defaults to False.
391
+ locals_max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation.
392
+ Defaults to 10.
393
+ locals_max_string (int, optional): Maximum length of string before truncating, or None to disable. Defaults to 80.
394
+ locals_hide_dunder (bool, optional): Hide locals prefixed with double underscore. Defaults to True.
395
+ locals_hide_sunder (bool, optional): Hide locals prefixed with single underscore. Defaults to False.
396
+
397
+ Returns:
398
+ Trace: A Trace instance which you can use to construct a `Traceback`.
399
+ """
400
+
401
+ stacks: List[Stack] = []
402
+ is_cause = False
403
+
404
+ from pip._vendor.rich import _IMPORT_CWD
405
+
406
+ def safe_str(_object: Any) -> str:
407
+ """Don't allow exceptions from __str__ to propagate."""
408
+ try:
409
+ return str(_object)
410
+ except Exception:
411
+ return "<exception str() failed>"
412
+
413
+ while True:
414
+ stack = Stack(
415
+ exc_type=safe_str(exc_type.__name__),
416
+ exc_value=safe_str(exc_value),
417
+ is_cause=is_cause,
418
+ )
419
+
420
+ if isinstance(exc_value, SyntaxError):
421
+ stack.syntax_error = _SyntaxError(
422
+ offset=exc_value.offset or 0,
423
+ filename=exc_value.filename or "?",
424
+ lineno=exc_value.lineno or 0,
425
+ line=exc_value.text or "",
426
+ msg=exc_value.msg,
427
+ )
428
+
429
+ stacks.append(stack)
430
+ append = stack.frames.append
431
+
432
+ def get_locals(
433
+ iter_locals: Iterable[Tuple[str, object]]
434
+ ) -> Iterable[Tuple[str, object]]:
435
+ """Extract locals from an iterator of key pairs."""
436
+ if not (locals_hide_dunder or locals_hide_sunder):
437
+ yield from iter_locals
438
+ return
439
+ for key, value in iter_locals:
440
+ if locals_hide_dunder and key.startswith("__"):
441
+ continue
442
+ if locals_hide_sunder and key.startswith("_"):
443
+ continue
444
+ yield key, value
445
+
446
+ for frame_summary, line_no in walk_tb(traceback):
447
+ filename = frame_summary.f_code.co_filename
448
+
449
+ last_instruction: Optional[Tuple[Tuple[int, int], Tuple[int, int]]]
450
+ last_instruction = None
451
+ if sys.version_info >= (3, 11):
452
+ instruction_index = frame_summary.f_lasti // 2
453
+ instruction_position = next(
454
+ islice(
455
+ frame_summary.f_code.co_positions(),
456
+ instruction_index,
457
+ instruction_index + 1,
458
+ )
459
+ )
460
+ (
461
+ start_line,
462
+ end_line,
463
+ start_column,
464
+ end_column,
465
+ ) = instruction_position
466
+ if (
467
+ start_line is not None
468
+ and end_line is not None
469
+ and start_column is not None
470
+ and end_column is not None
471
+ ):
472
+ last_instruction = (
473
+ (start_line, start_column),
474
+ (end_line, end_column),
475
+ )
476
+
477
+ if filename and not filename.startswith("<"):
478
+ if not os.path.isabs(filename):
479
+ filename = os.path.join(_IMPORT_CWD, filename)
480
+ if frame_summary.f_locals.get("_rich_traceback_omit", False):
481
+ continue
482
+
483
+ frame = Frame(
484
+ filename=filename or "?",
485
+ lineno=line_no,
486
+ name=frame_summary.f_code.co_name,
487
+ locals=(
488
+ {
489
+ key: pretty.traverse(
490
+ value,
491
+ max_length=locals_max_length,
492
+ max_string=locals_max_string,
493
+ )
494
+ for key, value in get_locals(frame_summary.f_locals.items())
495
+ if not (inspect.isfunction(value) or inspect.isclass(value))
496
+ }
497
+ if show_locals
498
+ else None
499
+ ),
500
+ last_instruction=last_instruction,
501
+ )
502
+ append(frame)
503
+ if frame_summary.f_locals.get("_rich_traceback_guard", False):
504
+ del stack.frames[:]
505
+
506
+ cause = getattr(exc_value, "__cause__", None)
507
+ if cause:
508
+ exc_type = cause.__class__
509
+ exc_value = cause
510
+ # __traceback__ can be None, e.g. for exceptions raised by the
511
+ # 'multiprocessing' module
512
+ traceback = cause.__traceback__
513
+ is_cause = True
514
+ continue
515
+
516
+ cause = exc_value.__context__
517
+ if cause and not getattr(exc_value, "__suppress_context__", False):
518
+ exc_type = cause.__class__
519
+ exc_value = cause
520
+ traceback = cause.__traceback__
521
+ is_cause = False
522
+ continue
523
+ # No cover, code is reached but coverage doesn't recognize it.
524
+ break # pragma: no cover
525
+
526
+ trace = Trace(stacks=stacks)
527
+ return trace
528
+
529
+ def __rich_console__(
530
+ self, console: Console, options: ConsoleOptions
531
+ ) -> RenderResult:
532
+ theme = self.theme
533
+ background_style = theme.get_background_style()
534
+ token_style = theme.get_style_for_token
535
+
536
+ traceback_theme = Theme(
537
+ {
538
+ "pretty": token_style(TextToken),
539
+ "pygments.text": token_style(Token),
540
+ "pygments.string": token_style(String),
541
+ "pygments.function": token_style(Name.Function),
542
+ "pygments.number": token_style(Number),
543
+ "repr.indent": token_style(Comment) + Style(dim=True),
544
+ "repr.str": token_style(String),
545
+ "repr.brace": token_style(TextToken) + Style(bold=True),
546
+ "repr.number": token_style(Number),
547
+ "repr.bool_true": token_style(Keyword.Constant),
548
+ "repr.bool_false": token_style(Keyword.Constant),
549
+ "repr.none": token_style(Keyword.Constant),
550
+ "scope.border": token_style(String.Delimiter),
551
+ "scope.equals": token_style(Operator),
552
+ "scope.key": token_style(Name),
553
+ "scope.key.special": token_style(Name.Constant) + Style(dim=True),
554
+ },
555
+ inherit=False,
556
+ )
557
+
558
+ highlighter = ReprHighlighter()
559
+ for last, stack in loop_last(reversed(self.trace.stacks)):
560
+ if stack.frames:
561
+ stack_renderable: ConsoleRenderable = Panel(
562
+ self._render_stack(stack),
563
+ title="[traceback.title]Traceback [dim](most recent call last)",
564
+ style=background_style,
565
+ border_style="traceback.border",
566
+ expand=True,
567
+ padding=(0, 1),
568
+ )
569
+ stack_renderable = Constrain(stack_renderable, self.width)
570
+ with console.use_theme(traceback_theme):
571
+ yield stack_renderable
572
+ if stack.syntax_error is not None:
573
+ with console.use_theme(traceback_theme):
574
+ yield Constrain(
575
+ Panel(
576
+ self._render_syntax_error(stack.syntax_error),
577
+ style=background_style,
578
+ border_style="traceback.border.syntax_error",
579
+ expand=True,
580
+ padding=(0, 1),
581
+ width=self.width,
582
+ ),
583
+ self.width,
584
+ )
585
+ yield Text.assemble(
586
+ (f"{stack.exc_type}: ", "traceback.exc_type"),
587
+ highlighter(stack.syntax_error.msg),
588
+ )
589
+ elif stack.exc_value:
590
+ yield Text.assemble(
591
+ (f"{stack.exc_type}: ", "traceback.exc_type"),
592
+ highlighter(stack.exc_value),
593
+ )
594
+ else:
595
+ yield Text.assemble((f"{stack.exc_type}", "traceback.exc_type"))
596
+
597
+ if not last:
598
+ if stack.is_cause:
599
+ yield Text.from_markup(
600
+ "\n[i]The above exception was the direct cause of the following exception:\n",
601
+ )
602
+ else:
603
+ yield Text.from_markup(
604
+ "\n[i]During handling of the above exception, another exception occurred:\n",
605
+ )
606
+
607
+ @group()
608
+ def _render_syntax_error(self, syntax_error: _SyntaxError) -> RenderResult:
609
+ highlighter = ReprHighlighter()
610
+ path_highlighter = PathHighlighter()
611
+ if syntax_error.filename != "<stdin>":
612
+ if os.path.exists(syntax_error.filename):
613
+ text = Text.assemble(
614
+ (f" {syntax_error.filename}", "pygments.string"),
615
+ (":", "pygments.text"),
616
+ (str(syntax_error.lineno), "pygments.number"),
617
+ style="pygments.text",
618
+ )
619
+ yield path_highlighter(text)
620
+ syntax_error_text = highlighter(syntax_error.line.rstrip())
621
+ syntax_error_text.no_wrap = True
622
+ offset = min(syntax_error.offset - 1, len(syntax_error_text))
623
+ syntax_error_text.stylize("bold underline", offset, offset)
624
+ syntax_error_text += Text.from_markup(
625
+ "\n" + " " * offset + "[traceback.offset]▲[/]",
626
+ style="pygments.text",
627
+ )
628
+ yield syntax_error_text
629
+
630
+ @classmethod
631
+ def _guess_lexer(cls, filename: str, code: str) -> str:
632
+ ext = os.path.splitext(filename)[-1]
633
+ if not ext:
634
+ # No extension, look at first line to see if it is a hashbang
635
+ # Note, this is an educated guess and not a guarantee
636
+ # If it fails, the only downside is that the code is highlighted strangely
637
+ new_line_index = code.index("\n")
638
+ first_line = code[:new_line_index] if new_line_index != -1 else code
639
+ if first_line.startswith("#!") and "python" in first_line.lower():
640
+ return "python"
641
+ try:
642
+ return cls.LEXERS.get(ext) or guess_lexer_for_filename(filename, code).name
643
+ except ClassNotFound:
644
+ return "text"
645
+
646
+ @group()
647
+ def _render_stack(self, stack: Stack) -> RenderResult:
648
+ path_highlighter = PathHighlighter()
649
+ theme = self.theme
650
+
651
+ def read_code(filename: str) -> str:
652
+ """Read files, and cache results on filename.
653
+
654
+ Args:
655
+ filename (str): Filename to read
656
+
657
+ Returns:
658
+ str: Contents of file
659
+ """
660
+ return "".join(linecache.getlines(filename))
661
+
662
+ def render_locals(frame: Frame) -> Iterable[ConsoleRenderable]:
663
+ if frame.locals:
664
+ yield render_scope(
665
+ frame.locals,
666
+ title="locals",
667
+ indent_guides=self.indent_guides,
668
+ max_length=self.locals_max_length,
669
+ max_string=self.locals_max_string,
670
+ )
671
+
672
+ exclude_frames: Optional[range] = None
673
+ if self.max_frames != 0:
674
+ exclude_frames = range(
675
+ self.max_frames // 2,
676
+ len(stack.frames) - self.max_frames // 2,
677
+ )
678
+
679
+ excluded = False
680
+ for frame_index, frame in enumerate(stack.frames):
681
+ if exclude_frames and frame_index in exclude_frames:
682
+ excluded = True
683
+ continue
684
+
685
+ if excluded:
686
+ assert exclude_frames is not None
687
+ yield Text(
688
+ f"\n... {len(exclude_frames)} frames hidden ...",
689
+ justify="center",
690
+ style="traceback.error",
691
+ )
692
+ excluded = False
693
+
694
+ first = frame_index == 0
695
+ frame_filename = frame.filename
696
+ suppressed = any(frame_filename.startswith(path) for path in self.suppress)
697
+
698
+ if os.path.exists(frame.filename):
699
+ text = Text.assemble(
700
+ path_highlighter(Text(frame.filename, style="pygments.string")),
701
+ (":", "pygments.text"),
702
+ (str(frame.lineno), "pygments.number"),
703
+ " in ",
704
+ (frame.name, "pygments.function"),
705
+ style="pygments.text",
706
+ )
707
+ else:
708
+ text = Text.assemble(
709
+ "in ",
710
+ (frame.name, "pygments.function"),
711
+ (":", "pygments.text"),
712
+ (str(frame.lineno), "pygments.number"),
713
+ style="pygments.text",
714
+ )
715
+ if not frame.filename.startswith("<") and not first:
716
+ yield ""
717
+ yield text
718
+ if frame.filename.startswith("<"):
719
+ yield from render_locals(frame)
720
+ continue
721
+ if not suppressed:
722
+ try:
723
+ code = read_code(frame.filename)
724
+ if not code:
725
+ # code may be an empty string if the file doesn't exist, OR
726
+ # if the traceback filename is generated dynamically
727
+ continue
728
+ lexer_name = self._guess_lexer(frame.filename, code)
729
+ syntax = Syntax(
730
+ code,
731
+ lexer_name,
732
+ theme=theme,
733
+ line_numbers=True,
734
+ line_range=(
735
+ frame.lineno - self.extra_lines,
736
+ frame.lineno + self.extra_lines,
737
+ ),
738
+ highlight_lines={frame.lineno},
739
+ word_wrap=self.word_wrap,
740
+ code_width=self.code_width,
741
+ indent_guides=self.indent_guides,
742
+ dedent=False,
743
+ )
744
+ yield ""
745
+ except Exception as error:
746
+ yield Text.assemble(
747
+ (f"\n{error}", "traceback.error"),
748
+ )
749
+ else:
750
+ if frame.last_instruction is not None:
751
+ start, end = frame.last_instruction
752
+ syntax.stylize_range(
753
+ style="traceback.error_range",
754
+ start=start,
755
+ end=end,
756
+ style_before=True,
757
+ )
758
+ yield (
759
+ Columns(
760
+ [
761
+ syntax,
762
+ *render_locals(frame),
763
+ ],
764
+ padding=1,
765
+ )
766
+ if frame.locals
767
+ else syntax
768
+ )
769
+
770
+
771
+ if __name__ == "__main__": # pragma: no cover
772
+ install(show_locals=True)
773
+ import sys
774
+
775
+ def bar(
776
+ a: Any,
777
+ ) -> None: # 这是对亚洲语言支持的测试。面对模棱两可的想法,拒绝猜测的诱惑
778
+ one = 1
779
+ print(one / a)
780
+
781
+ def foo(a: Any) -> None:
782
+ _rich_traceback_guard = True
783
+ zed = {
784
+ "characters": {
785
+ "Paul Atreides",
786
+ "Vladimir Harkonnen",
787
+ "Thufir Hawat",
788
+ "Duncan Idaho",
789
+ },
790
+ "atomic_types": (None, False, True),
791
+ }
792
+ bar(a)
793
+
794
+ def error() -> None:
795
+ foo(0)
796
+
797
+ error()
minigpt2/lib/python3.10/site-packages/imageio/config/__init__.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .extensions import (
2
+ extension_list,
3
+ known_extensions,
4
+ FileExtension,
5
+ video_extensions,
6
+ )
7
+ from .plugins import known_plugins, PluginConfig
8
+
9
+ __all__ = [
10
+ "known_plugins",
11
+ "PluginConfig",
12
+ "extension_list",
13
+ "known_extensions",
14
+ "FileExtension",
15
+ "video_extensions",
16
+ ]
minigpt2/lib/python3.10/site-packages/imageio/config/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (414 Bytes). View file
 
minigpt2/lib/python3.10/site-packages/imageio/config/__pycache__/extensions.cpython-310.pyc ADDED
Binary file (32.5 kB). View file
 
minigpt2/lib/python3.10/site-packages/imageio/config/__pycache__/plugins.cpython-310.pyc ADDED
Binary file (10.9 kB). View file
 
minigpt2/lib/python3.10/site-packages/imageio/config/extensions.py ADDED
@@ -0,0 +1,2002 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ A set of objects representing each file extension recognized by ImageIO. If an
3
+ extension is not listed here it is still supported, as long as there exists a
4
+ supporting backend.
5
+
6
+ """
7
+
8
+
9
+ class FileExtension:
10
+ """File Extension Metadata
11
+
12
+ This class holds information about a image file format associated with a
13
+ given extension. This information is used to track plugins that are known to
14
+ be able to handle a particular format. It also contains additional
15
+ information about a format, which is used when creating the supported format
16
+ docs.
17
+
18
+ Plugins known to be able to handle this format are ordered by a ``priority``
19
+ list. This list is used to determine the ideal plugin to use when choosing a
20
+ plugin based on file extension.
21
+
22
+ Parameters
23
+ ----------
24
+ extension : str
25
+ The name of the extension including the initial dot, e.g. ".png".
26
+ priority : List
27
+ A list of plugin names (entries in config.known_plugins) that can handle
28
+ this format. The position of a plugin expresses a preference, e.g.
29
+ ["plugin1", "plugin2"] indicates that, if available, plugin1 should be
30
+ preferred over plugin2 when handling a request related to this format.
31
+ name : str
32
+ The full name of the format.
33
+ description : str
34
+ A description of the format.
35
+ external_link : str
36
+ A link to further information about the format. Typically, the format's
37
+ specification.
38
+ volume_support : str
39
+ If True, the format/extension supports volumetric image data.
40
+
41
+ Examples
42
+ --------
43
+ >>> FileExtension(
44
+ name="Bitmap",
45
+ extension=".bmp",
46
+ priority=["pillow", "BMP-PIL", "BMP-FI", "ITK"],
47
+ external_link="https://en.wikipedia.org/wiki/BMP_file_format",
48
+ )
49
+
50
+ """
51
+
52
+ def __init__(
53
+ self,
54
+ *,
55
+ extension,
56
+ priority,
57
+ name=None,
58
+ description=None,
59
+ external_link=None,
60
+ volume_support=False
61
+ ):
62
+ self.extension = extension
63
+ self.priority = priority
64
+ self.name = name
65
+ self.description = description
66
+ self.external_link = external_link
67
+ self.default_priority = priority.copy()
68
+ self.volume_support = volume_support
69
+
70
+ def reset(self):
71
+ self.priority = self.default_priority.copy()
72
+
73
+
74
+ extension_list = [
75
+ FileExtension(
76
+ name="Hasselblad raw",
77
+ extension=".3fr",
78
+ priority=["RAW-FI"],
79
+ ),
80
+ FileExtension(
81
+ name="Sony alpha",
82
+ extension=".arw",
83
+ priority=["RAW-FI"],
84
+ ),
85
+ FileExtension(
86
+ name="Animated Portable Network Graphics",
87
+ external_link="https://en.wikipedia.org/wiki/APNG",
88
+ extension=".apng",
89
+ priority=["pillow", "pyav"],
90
+ ),
91
+ FileExtension(
92
+ name="Audio Video Interleave",
93
+ extension=".avi",
94
+ priority=["FFMPEG"],
95
+ ),
96
+ FileExtension(
97
+ name="Casio raw format",
98
+ extension=".bay",
99
+ priority=["RAW-FI"],
100
+ ),
101
+ FileExtension(
102
+ extension=".blp",
103
+ priority=["pillow"],
104
+ ),
105
+ FileExtension(
106
+ name="Bitmap",
107
+ extension=".bmp",
108
+ priority=["pillow", "BMP-PIL", "BMP-FI", "ITK", "pyav", "opencv"],
109
+ external_link="https://en.wikipedia.org/wiki/BMP_file_format",
110
+ ),
111
+ FileExtension(
112
+ name="Device-Independent Bitmap",
113
+ extension=".dip",
114
+ priority=["opencv"],
115
+ external_link="https://en.wikipedia.org/wiki/BMP_file_format",
116
+ ),
117
+ FileExtension(
118
+ name="Re-Volt mipmap",
119
+ extension=".bmq",
120
+ priority=["RAW-FI"],
121
+ ),
122
+ FileExtension(
123
+ name="Binary Structured Data Format",
124
+ extension=".bsdf",
125
+ priority=["BSDF"],
126
+ external_link="http://bsdf.io/",
127
+ ),
128
+ FileExtension(
129
+ name="Binary Universal Form for the Representation of meteorological data",
130
+ extension=".bufr",
131
+ priority=["pillow", "BUFR-PIL"],
132
+ ),
133
+ FileExtension(
134
+ name="Silicon Graphics Image",
135
+ extension=".bw",
136
+ priority=["pillow", "SGI-PIL", "SGI-FI"],
137
+ ),
138
+ FileExtension(
139
+ name="Scirra Construct",
140
+ extension=".cap",
141
+ priority=["RAW-FI"],
142
+ ),
143
+ FileExtension(
144
+ name="AMETEK High Speed Camera Format",
145
+ extension=".cine",
146
+ priority=["RAW-FI"],
147
+ external_link="https://phantomhighspeed-knowledge.secure.force.com/servlet/fileField?id=0BE1N000000kD2i#:~:text=Cine%20is%20a%20video%20file,camera%20model%20and%20image%20resolution",
148
+ ),
149
+ FileExtension(extension=".cr2", priority=["RAW-FI"]),
150
+ FileExtension(
151
+ extension=".crw",
152
+ priority=["RAW-FI"],
153
+ ),
154
+ FileExtension(
155
+ extension=".cs1",
156
+ priority=["RAW-FI"],
157
+ ),
158
+ FileExtension(
159
+ name="Computerized Tomography",
160
+ extension=".ct",
161
+ priority=["DICOM"],
162
+ ),
163
+ FileExtension(
164
+ name="Windows Cursor Icons",
165
+ extension=".cur",
166
+ priority=["pillow", "CUR-PIL"],
167
+ ),
168
+ FileExtension(
169
+ name="Dr. Halo",
170
+ extension=".cut",
171
+ priority=["CUT-FI"],
172
+ ),
173
+ FileExtension(
174
+ extension=".dc2",
175
+ priority=["RAW-FI"],
176
+ ),
177
+ FileExtension(
178
+ name="DICOM file format",
179
+ extension=".dcm",
180
+ priority=["DICOM", "ITK"],
181
+ ),
182
+ FileExtension(
183
+ extension=".dcr",
184
+ priority=["RAW-FI"],
185
+ ),
186
+ FileExtension(
187
+ name="Intel DCX",
188
+ extension=".dcx",
189
+ priority=["pillow", "DCX-PIL"],
190
+ ),
191
+ FileExtension(
192
+ name="DirectX Texture Container",
193
+ extension=".dds",
194
+ priority=["pillow", "DDS-FI", "DDS-PIL"],
195
+ ),
196
+ FileExtension(
197
+ name="Windows Bitmap",
198
+ extension=".dib",
199
+ priority=["pillow", "DIB-PIL"],
200
+ ),
201
+ FileExtension(
202
+ name="DICOM file format",
203
+ extension=".dicom",
204
+ priority=["ITK"],
205
+ ),
206
+ FileExtension(
207
+ extension=".dng",
208
+ priority=["RAW-FI"],
209
+ ),
210
+ FileExtension(
211
+ extension=".drf",
212
+ priority=["RAW-FI"],
213
+ ),
214
+ FileExtension(
215
+ extension=".dsc",
216
+ priority=["RAW-FI"],
217
+ ),
218
+ FileExtension(
219
+ name="Enhanced Compression Wavelet",
220
+ extension=".ecw",
221
+ priority=["GDAL"],
222
+ ),
223
+ FileExtension(
224
+ name="Windows Metafile",
225
+ extension=".emf",
226
+ priority=["pillow", "WMF-PIL"],
227
+ ),
228
+ FileExtension(
229
+ name="Encapsulated Postscript",
230
+ extension=".eps",
231
+ priority=["pillow", "EPS-PIL"],
232
+ ),
233
+ FileExtension(
234
+ extension=".erf",
235
+ priority=["RAW-FI"],
236
+ ),
237
+ FileExtension(
238
+ name="OpenEXR",
239
+ extension=".exr",
240
+ external_link="https://openexr.readthedocs.io/en/latest/",
241
+ priority=["EXR-FI", "pyav", "opencv"],
242
+ ),
243
+ FileExtension(
244
+ extension=".fff",
245
+ priority=["RAW-FI"],
246
+ ),
247
+ FileExtension(
248
+ name="Flexible Image Transport System File",
249
+ extension=".fit",
250
+ priority=["pillow", "FITS-PIL", "FITS"],
251
+ ),
252
+ FileExtension(
253
+ name="Flexible Image Transport System File",
254
+ extension=".fits",
255
+ priority=["pillow", "FITS-PIL", "FITS", "pyav"],
256
+ ),
257
+ FileExtension(
258
+ name="Autodesk FLC Animation",
259
+ extension=".flc",
260
+ priority=["pillow", "FLI-PIL"],
261
+ ),
262
+ FileExtension(
263
+ name="Autodesk FLI Animation",
264
+ extension=".fli",
265
+ priority=["pillow", "FLI-PIL"],
266
+ ),
267
+ FileExtension(
268
+ name="Kodak FlashPix",
269
+ extension=".fpx",
270
+ priority=["pillow", "FPX-PIL"],
271
+ ),
272
+ FileExtension(
273
+ name="Independence War 2: Edge Of Chaos Texture Format",
274
+ extension=".ftc",
275
+ priority=["pillow", "FTEX-PIL"],
276
+ ),
277
+ FileExtension(
278
+ name="Flexible Image Transport System File",
279
+ extension=".fts",
280
+ priority=["FITS"],
281
+ ),
282
+ FileExtension(
283
+ name="Independence War 2: Edge Of Chaos Texture Format",
284
+ extension=".ftu",
285
+ priority=["pillow", "FTEX-PIL"],
286
+ ),
287
+ FileExtension(
288
+ name="Flexible Image Transport System File",
289
+ extension=".fz",
290
+ priority=["FITS"],
291
+ ),
292
+ FileExtension(
293
+ name="Raw fax format CCITT G.3",
294
+ extension=".g3",
295
+ priority=["G3-FI"],
296
+ ),
297
+ FileExtension(
298
+ name="GIMP brush file",
299
+ extension=".gbr",
300
+ priority=["pillow", "GBR-PIL"],
301
+ ),
302
+ FileExtension(
303
+ name="Grassroots DICOM",
304
+ extension=".gdcm",
305
+ priority=["ITK"],
306
+ ),
307
+ FileExtension(
308
+ name="Graphics Interchange Format",
309
+ extension=".gif",
310
+ priority=["pillow", "GIF-PIL", "pyav"],
311
+ ),
312
+ FileExtension(
313
+ name="UMDS GIPL",
314
+ extension=".gipl",
315
+ priority=["ITK"],
316
+ ),
317
+ FileExtension(
318
+ name="gridded meteorological data",
319
+ extension=".grib",
320
+ priority=["pillow", "GRIB-PIL"],
321
+ ),
322
+ FileExtension(
323
+ name="Hierarchical Data Format 5",
324
+ extension=".h5",
325
+ priority=["pillow", "HDF5-PIL"],
326
+ ),
327
+ FileExtension(
328
+ name="Hierarchical Data Format 5",
329
+ extension=".hdf",
330
+ priority=["pillow", "HDF5-PIL"],
331
+ ),
332
+ FileExtension(
333
+ name="Hierarchical Data Format 5",
334
+ extension=".hdf5",
335
+ priority=["ITK"],
336
+ ),
337
+ FileExtension(
338
+ name="JPEG Extended Range",
339
+ extension=".hdp",
340
+ priority=["JPEG-XR-FI"],
341
+ ),
342
+ FileExtension(
343
+ name="High Dynamic Range Image",
344
+ extension=".hdr",
345
+ priority=["HDR-FI", "ITK", "opencv"],
346
+ ),
347
+ FileExtension(
348
+ extension=".ia",
349
+ priority=["RAW-FI"],
350
+ ),
351
+ FileExtension(
352
+ extension=".icb",
353
+ priority=["pillow"],
354
+ ),
355
+ FileExtension(
356
+ name="Mac OS Icon File",
357
+ extension=".icns",
358
+ priority=["pillow", "ICNS-PIL"],
359
+ ),
360
+ FileExtension(
361
+ name="Windows Icon File",
362
+ extension=".ico",
363
+ priority=["pillow", "ICO-FI", "ICO-PIL", "pyav"],
364
+ ),
365
+ FileExtension(
366
+ name="ILBM Interleaved Bitmap",
367
+ extension=".iff",
368
+ priority=["IFF-FI"],
369
+ ),
370
+ FileExtension(
371
+ name="IPTC/NAA",
372
+ extension=".iim",
373
+ priority=["pillow", "IPTC-PIL"],
374
+ ),
375
+ FileExtension(
376
+ extension=".iiq",
377
+ priority=["RAW-FI"],
378
+ ),
379
+ FileExtension(
380
+ name="IFUNC Image Memory",
381
+ extension=".im",
382
+ priority=["pillow", "IM-PIL"],
383
+ ),
384
+ FileExtension(
385
+ extension=".img",
386
+ priority=["ITK", "GDAL"],
387
+ ),
388
+ FileExtension(
389
+ extension=".img.gz",
390
+ priority=["ITK"],
391
+ ),
392
+ FileExtension(
393
+ name="IM Tools",
394
+ extension=".IMT",
395
+ priority=["pillow", "IMT-PIL"],
396
+ ),
397
+ FileExtension(
398
+ name="Image Processing Lab",
399
+ extension=".ipl",
400
+ priority=["ITK"],
401
+ ),
402
+ FileExtension(
403
+ name="JPEG 2000",
404
+ extension=".j2c",
405
+ priority=["pillow", "J2K-FI", "JPEG2000-PIL", "pyav"],
406
+ ),
407
+ FileExtension(
408
+ name="JPEG 2000",
409
+ extension=".j2k",
410
+ priority=["pillow", "J2K-FI", "JPEG2000-PIL", "pyav"],
411
+ ),
412
+ FileExtension(
413
+ name="JPEG",
414
+ extension=".jfif",
415
+ priority=["pillow", "JPEG-PIL"],
416
+ ),
417
+ FileExtension(
418
+ name="JPEG",
419
+ extension=".jif",
420
+ priority=["JPEG-FI"],
421
+ ),
422
+ FileExtension(
423
+ name="JPEG Network Graphics",
424
+ extension=".jng",
425
+ priority=["JNG-FI"],
426
+ ),
427
+ FileExtension(
428
+ name="JPEG 2000",
429
+ extension=".jp2",
430
+ priority=["pillow", "JP2-FI", "JPEG2000-PIL", "pyav", "opencv"],
431
+ ),
432
+ FileExtension(
433
+ name="JPEG 2000",
434
+ extension=".jpc",
435
+ priority=["pillow", "JPEG2000-PIL"],
436
+ ),
437
+ FileExtension(
438
+ name="JPEG",
439
+ extension=".jpe",
440
+ priority=["pillow", "JPEG-FI", "JPEG-PIL", "opencv"],
441
+ ),
442
+ FileExtension(
443
+ name="Joint Photographic Experts Group",
444
+ extension=".jpeg",
445
+ priority=["pillow", "JPEG-PIL", "JPEG-FI", "ITK", "GDAL", "pyav", "opencv"],
446
+ ),
447
+ FileExtension(
448
+ name="JPEG 2000",
449
+ extension=".jpf",
450
+ priority=["pillow", "JPEG2000-PIL"],
451
+ ),
452
+ FileExtension(
453
+ name="Joint Photographic Experts Group",
454
+ extension=".jpg",
455
+ priority=["pillow", "JPEG-PIL", "JPEG-FI", "ITK", "GDAL", "pyav", "opencv"],
456
+ ),
457
+ FileExtension(
458
+ name="JPEG 2000",
459
+ extension=".jpx",
460
+ priority=["pillow", "JPEG2000-PIL"],
461
+ ),
462
+ FileExtension(
463
+ name="JPEG Extended Range",
464
+ extension=".jxr",
465
+ priority=["JPEG-XR-FI"],
466
+ ),
467
+ FileExtension(
468
+ extension=".k25",
469
+ priority=["RAW-FI"],
470
+ ),
471
+ FileExtension(
472
+ extension=".kc2",
473
+ priority=["RAW-FI"],
474
+ ),
475
+ FileExtension(
476
+ extension=".kdc",
477
+ priority=["RAW-FI"],
478
+ ),
479
+ FileExtension(
480
+ name="C64 Koala Graphics",
481
+ extension=".koa",
482
+ priority=["KOALA-FI"],
483
+ ),
484
+ FileExtension(
485
+ name="ILBM Interleaved Bitmap",
486
+ extension=".lbm",
487
+ priority=["IFF-FI"],
488
+ ),
489
+ FileExtension(
490
+ name="Lytro F01",
491
+ extension=".lfp",
492
+ priority=["LYTRO-LFP"],
493
+ ),
494
+ FileExtension(
495
+ name="Lytro Illum",
496
+ extension=".lfr",
497
+ priority=["LYTRO-LFR"],
498
+ ),
499
+ FileExtension(
500
+ name="ZEISS LSM",
501
+ extension=".lsm",
502
+ priority=["tifffile", "ITK", "TIFF"],
503
+ ),
504
+ FileExtension(
505
+ name="McIdas area file",
506
+ extension=".MCIDAS",
507
+ priority=["pillow", "MCIDAS-PIL"],
508
+ external_link="https://www.ssec.wisc.edu/mcidas/doc/prog_man/2003print/progman2003-formats.html",
509
+ ),
510
+ FileExtension(
511
+ extension=".mdc",
512
+ priority=["RAW-FI"],
513
+ ),
514
+ FileExtension(
515
+ extension=".mef",
516
+ priority=["RAW-FI"],
517
+ ),
518
+ FileExtension(
519
+ name="FreeSurfer File Format",
520
+ extension=".mgh",
521
+ priority=["ITK"],
522
+ ),
523
+ FileExtension(
524
+ name="ITK MetaImage",
525
+ extension=".mha",
526
+ priority=["ITK"],
527
+ ),
528
+ FileExtension(
529
+ name="ITK MetaImage Header",
530
+ extension=".mhd",
531
+ priority=["ITK"],
532
+ ),
533
+ FileExtension(
534
+ name="Microsoft Image Composer",
535
+ extension=".mic",
536
+ priority=["pillow", "MIC-PIL"],
537
+ ),
538
+ FileExtension(
539
+ name="Matroska Multimedia Container",
540
+ extension=".mkv",
541
+ priority=["FFMPEG", "pyav"],
542
+ ),
543
+ FileExtension(
544
+ name="Medical Imaging NetCDF",
545
+ extension=".mnc",
546
+ priority=["ITK"],
547
+ ),
548
+ FileExtension(
549
+ name="Medical Imaging NetCDF 2",
550
+ extension=".mnc2",
551
+ priority=["ITK"],
552
+ ),
553
+ FileExtension(
554
+ name="Leaf Raw Image Format",
555
+ extension=".mos",
556
+ priority=["RAW-FI"],
557
+ ),
558
+ FileExtension(
559
+ name="QuickTime File Format",
560
+ extension=".mov",
561
+ priority=["FFMPEG", "pyav"],
562
+ ),
563
+ FileExtension(
564
+ name="MPEG-4 Part 14",
565
+ extension=".mp4",
566
+ priority=["FFMPEG", "pyav"],
567
+ ),
568
+ FileExtension(
569
+ name="MPEG-1 Moving Picture Experts Group",
570
+ extension=".mpeg",
571
+ priority=["FFMPEG", "pyav"],
572
+ ),
573
+ FileExtension(
574
+ name="Moving Picture Experts Group",
575
+ extension=".mpg",
576
+ priority=["pillow", "FFMPEG", "pyav"],
577
+ ),
578
+ FileExtension(
579
+ name="JPEG Multi-Picture Format",
580
+ extension=".mpo",
581
+ priority=["pillow", "MPO-PIL"],
582
+ ),
583
+ FileExtension(
584
+ name="Magnetic resonance imaging",
585
+ extension=".mri",
586
+ priority=["DICOM"],
587
+ ),
588
+ FileExtension(
589
+ extension=".mrw",
590
+ priority=["RAW-FI"],
591
+ ),
592
+ FileExtension(
593
+ name="Windows Paint",
594
+ extension=".msp",
595
+ priority=["pillow", "MSP-PIL"],
596
+ ),
597
+ FileExtension(
598
+ extension=".nef",
599
+ priority=["RAW-FI", "rawpy"],
600
+ ),
601
+ FileExtension(
602
+ extension=".nhdr",
603
+ priority=["ITK"],
604
+ ),
605
+ FileExtension(
606
+ extension=".nia",
607
+ priority=["ITK"],
608
+ ),
609
+ FileExtension(
610
+ extension=".nii",
611
+ priority=["ITK"],
612
+ ),
613
+ FileExtension(
614
+ name="nii.gz",
615
+ extension=".nii.gz",
616
+ priority=["ITK"],
617
+ ),
618
+ FileExtension(
619
+ name="Numpy Array",
620
+ extension=".npz",
621
+ priority=["NPZ"],
622
+ volume_support=True,
623
+ ),
624
+ FileExtension(
625
+ extension=".nrrd",
626
+ priority=["ITK"],
627
+ ),
628
+ FileExtension(
629
+ extension=".nrw",
630
+ priority=["RAW-FI"],
631
+ ),
632
+ FileExtension(
633
+ extension=".orf",
634
+ priority=["RAW-FI"],
635
+ ),
636
+ FileExtension(
637
+ extension=".palm",
638
+ priority=["pillow"],
639
+ ),
640
+ FileExtension(
641
+ name="Portable Bitmap",
642
+ extension=".pbm",
643
+ priority=["PGM-FI", "PGMRAW-FI", "pyav", "opencv"],
644
+ ),
645
+ FileExtension(
646
+ name="Kodak PhotoCD",
647
+ extension=".pcd",
648
+ priority=["pillow", "PCD-FI", "PCD-PIL"],
649
+ ),
650
+ FileExtension(
651
+ name="Macintosh PICT",
652
+ extension=".pct",
653
+ priority=["PICT-FI"],
654
+ ),
655
+ FileExtension(
656
+ name="Zsoft Paintbrush",
657
+ extension=".PCX",
658
+ priority=["pillow", "PCX-FI", "PCX-PIL"],
659
+ ),
660
+ FileExtension(
661
+ extension=".pdf",
662
+ priority=["pillow"],
663
+ ),
664
+ FileExtension(
665
+ extension=".pef",
666
+ priority=["RAW-FI"],
667
+ ),
668
+ FileExtension(
669
+ extension=".pfm",
670
+ priority=["PFM-FI", "pyav", "opencv"],
671
+ ),
672
+ FileExtension(
673
+ name="Portable Greymap",
674
+ extension=".pgm",
675
+ priority=["pillow", "PGM-FI", "PGMRAW-FI", "pyav", "opencv"],
676
+ ),
677
+ FileExtension(
678
+ name="Macintosh PICT",
679
+ extension=".pic",
680
+ priority=["PICT-FI", "ITK", "opencv"],
681
+ ),
682
+ FileExtension(
683
+ name="Macintosh PICT",
684
+ extension=".pict",
685
+ priority=["PICT-FI"],
686
+ ),
687
+ FileExtension(
688
+ name="Portable Network Graphics",
689
+ extension=".png",
690
+ priority=["pillow", "PNG-PIL", "PNG-FI", "ITK", "pyav", "opencv"],
691
+ ),
692
+ FileExtension(
693
+ name="Portable Image Format",
694
+ extension=".pnm",
695
+ priority=["pillow", "opencv"],
696
+ ),
697
+ FileExtension(
698
+ name="Pbmplus image",
699
+ extension=".ppm",
700
+ priority=["pillow", "PPM-PIL", "pyav"],
701
+ ),
702
+ FileExtension(
703
+ name="Pbmplus image",
704
+ extension=".pbm",
705
+ priority=["pillow", "PPM-PIL", "PPM-FI"],
706
+ ),
707
+ FileExtension(
708
+ name="Portable image format",
709
+ extension=".pxm",
710
+ priority=["opencv"],
711
+ ),
712
+ FileExtension(
713
+ name="Portable Pixelmap (ASCII)",
714
+ extension=".ppm",
715
+ priority=["PPM-FI", "opencv"],
716
+ ),
717
+ FileExtension(
718
+ name="Portable Pixelmap (Raw)",
719
+ extension=".ppm",
720
+ priority=["PPMRAW-FI"],
721
+ ),
722
+ FileExtension(
723
+ name="Ghostscript",
724
+ extension=".ps",
725
+ priority=["pillow", "EPS-PIL"],
726
+ ),
727
+ FileExtension(
728
+ name="Adope Photoshop 2.5 and 3.0",
729
+ extension=".psd",
730
+ priority=["pillow", "PSD-PIL", "PSD-FI"],
731
+ ),
732
+ FileExtension(
733
+ extension=".ptx",
734
+ priority=["RAW-FI"],
735
+ ),
736
+ FileExtension(
737
+ extension=".pxn",
738
+ priority=["RAW-FI"],
739
+ ),
740
+ FileExtension(
741
+ name="PIXAR raster image",
742
+ extension=".pxr",
743
+ priority=["pillow", "PIXAR-PIL"],
744
+ ),
745
+ FileExtension(
746
+ extension=".qtk",
747
+ priority=["RAW-FI"],
748
+ ),
749
+ FileExtension(
750
+ extension=".raf",
751
+ priority=["RAW-FI"],
752
+ ),
753
+ FileExtension(
754
+ name="Sun Raster File",
755
+ extension=".ras",
756
+ priority=["pillow", "SUN-PIL", "RAS-FI", "pyav", "opencv"],
757
+ ),
758
+ FileExtension(
759
+ name="Sun Raster File",
760
+ extension=".sr",
761
+ priority=["opencv"],
762
+ ),
763
+ FileExtension(
764
+ extension=".raw",
765
+ priority=["RAW-FI", "LYTRO-ILLUM-RAW", "LYTRO-F01-RAW", "rawpy"],
766
+ ),
767
+ FileExtension(
768
+ extension=".rdc",
769
+ priority=["RAW-FI"],
770
+ ),
771
+ FileExtension(
772
+ name="Silicon Graphics Image",
773
+ extension=".rgb",
774
+ priority=["pillow", "SGI-PIL"],
775
+ ),
776
+ FileExtension(
777
+ name="Silicon Graphics Image",
778
+ extension=".rgba",
779
+ priority=["pillow", "SGI-PIL"],
780
+ ),
781
+ FileExtension(
782
+ extension=".rw2",
783
+ priority=["RAW-FI"],
784
+ ),
785
+ FileExtension(
786
+ extension=".rwl",
787
+ priority=["RAW-FI"],
788
+ ),
789
+ FileExtension(
790
+ extension=".rwz",
791
+ priority=["RAW-FI"],
792
+ ),
793
+ FileExtension(
794
+ name="Silicon Graphics Image",
795
+ extension=".sgi",
796
+ priority=["pillow", "SGI-PIL", "pyav"],
797
+ ),
798
+ FileExtension(
799
+ name="SPE File Format",
800
+ extension=".spe",
801
+ priority=["SPE"],
802
+ ),
803
+ FileExtension(
804
+ extension=".SPIDER",
805
+ priority=["pillow", "SPIDER-PIL"],
806
+ ),
807
+ FileExtension(
808
+ extension=".sr2",
809
+ priority=["RAW-FI"],
810
+ ),
811
+ FileExtension(
812
+ extension=".srf",
813
+ priority=["RAW-FI"],
814
+ ),
815
+ FileExtension(
816
+ extension=".srw",
817
+ priority=["RAW-FI"],
818
+ ),
819
+ FileExtension(
820
+ extension=".sti",
821
+ priority=["RAW-FI"],
822
+ ),
823
+ FileExtension(
824
+ extension=".stk",
825
+ priority=["tifffile", "TIFF"],
826
+ ),
827
+ FileExtension(
828
+ name="ShockWave Flash",
829
+ extension=".swf",
830
+ priority=["SWF", "pyav"],
831
+ ),
832
+ FileExtension(
833
+ name="Truevision TGA",
834
+ extension=".targa",
835
+ priority=["pillow", "TARGA-FI"],
836
+ ),
837
+ FileExtension(
838
+ name="Truevision TGA",
839
+ extension=".tga",
840
+ priority=["pillow", "TGA-PIL", "TARGA-FI", "pyav"],
841
+ ),
842
+ FileExtension(
843
+ name="Tagged Image File",
844
+ extension=".tif",
845
+ priority=[
846
+ "tifffile",
847
+ "TIFF",
848
+ "pillow",
849
+ "TIFF-PIL",
850
+ "TIFF-FI",
851
+ "FEI",
852
+ "ITK",
853
+ "GDAL",
854
+ "pyav",
855
+ "opencv",
856
+ ],
857
+ volume_support=True,
858
+ ),
859
+ FileExtension(
860
+ name="Tagged Image File Format",
861
+ extension=".tiff",
862
+ priority=[
863
+ "tifffile",
864
+ "TIFF",
865
+ "pillow",
866
+ "TIFF-PIL",
867
+ "TIFF-FI",
868
+ "FEI",
869
+ "ITK",
870
+ "GDAL",
871
+ "pyav",
872
+ "opencv",
873
+ ],
874
+ volume_support=True,
875
+ ),
876
+ FileExtension(
877
+ extension=".vda",
878
+ priority=["pillow"],
879
+ ),
880
+ FileExtension(
881
+ extension=".vst",
882
+ priority=["pillow"],
883
+ ),
884
+ FileExtension(
885
+ extension=".vtk",
886
+ priority=["ITK"],
887
+ ),
888
+ FileExtension(
889
+ name="Wireless Bitmap",
890
+ extension=".wap",
891
+ priority=["WBMP-FI"],
892
+ ),
893
+ FileExtension(
894
+ name="Wireless Bitmap",
895
+ extension=".wbm",
896
+ priority=["WBMP-FI"],
897
+ ),
898
+ FileExtension(
899
+ name="Wireless Bitmap",
900
+ extension=".wbmp",
901
+ priority=["WBMP-FI"],
902
+ ),
903
+ FileExtension(
904
+ name="JPEG Extended Range",
905
+ extension=".wdp",
906
+ priority=["JPEG-XR-FI"],
907
+ ),
908
+ FileExtension(
909
+ name="Matroska",
910
+ extension=".webm",
911
+ priority=["FFMPEG", "pyav"],
912
+ ),
913
+ FileExtension(
914
+ name="Google WebP",
915
+ extension=".webp",
916
+ priority=["pillow", "WEBP-FI", "pyav", "opencv"],
917
+ ),
918
+ FileExtension(
919
+ name="Windows Meta File",
920
+ extension=".wmf",
921
+ priority=["pillow", "WMF-PIL"],
922
+ ),
923
+ FileExtension(
924
+ name="Windows Media Video",
925
+ extension=".wmv",
926
+ priority=["FFMPEG"],
927
+ ),
928
+ FileExtension(
929
+ name="X11 Bitmap",
930
+ extension=".xbm",
931
+ priority=["pillow", "XBM-PIL", "XBM-FI", "pyav"],
932
+ ),
933
+ FileExtension(
934
+ name="X11 Pixel Map",
935
+ extension=".xpm",
936
+ priority=["pillow", "XPM-PIL", "XPM-FI"],
937
+ ),
938
+ FileExtension(
939
+ name="Thumbnail Image",
940
+ extension=".XVTHUMB",
941
+ priority=["pillow", "XVTHUMB-PIL"],
942
+ ),
943
+ FileExtension(
944
+ extension=".dpx",
945
+ priority=["pyav"],
946
+ ),
947
+ FileExtension(
948
+ extension=".im1",
949
+ priority=["pyav"],
950
+ ),
951
+ FileExtension(
952
+ extension=".im24",
953
+ priority=["pyav"],
954
+ ),
955
+ FileExtension(
956
+ extension=".im8",
957
+ priority=["pyav"],
958
+ ),
959
+ FileExtension(
960
+ extension=".jls",
961
+ priority=["pyav"],
962
+ ),
963
+ FileExtension(
964
+ extension=".ljpg",
965
+ priority=["pyav"],
966
+ ),
967
+ FileExtension(
968
+ extension=".pam",
969
+ priority=["pyav"],
970
+ ),
971
+ FileExtension(
972
+ extension=".pcx",
973
+ priority=["pyav"],
974
+ ),
975
+ FileExtension(
976
+ extension=".pgmyuv",
977
+ priority=["pyav"],
978
+ ),
979
+ FileExtension(
980
+ extension=".pix",
981
+ priority=["pyav"],
982
+ ),
983
+ FileExtension(
984
+ extension=".ppm",
985
+ priority=["pyav"],
986
+ ),
987
+ FileExtension(
988
+ extension=".rs",
989
+ priority=["pyav"],
990
+ ),
991
+ FileExtension(
992
+ extension=".sun",
993
+ priority=["pyav"],
994
+ ),
995
+ FileExtension(
996
+ extension=".sunras",
997
+ priority=["pyav"],
998
+ ),
999
+ FileExtension(
1000
+ extension=".xface",
1001
+ priority=["pyav"],
1002
+ ),
1003
+ FileExtension(
1004
+ extension=".xwd",
1005
+ priority=["pyav"],
1006
+ ),
1007
+ FileExtension(
1008
+ extension=".y",
1009
+ priority=["pyav"],
1010
+ ),
1011
+ FileExtension(
1012
+ name="3GP (3GPP file format)",
1013
+ extension=".3g2",
1014
+ priority=["pyav"],
1015
+ ),
1016
+ FileExtension(
1017
+ name="3GP (3GPP file format)",
1018
+ extension=".3gp",
1019
+ priority=["pyav"],
1020
+ ),
1021
+ FileExtension(
1022
+ name="3GP (3GPP file format)",
1023
+ extension=".f4v",
1024
+ priority=["pyav"],
1025
+ ),
1026
+ FileExtension(
1027
+ name="3GP (3GPP file format)",
1028
+ extension=".ism",
1029
+ priority=["pyav"],
1030
+ ),
1031
+ FileExtension(
1032
+ name="3GP (3GPP file format)",
1033
+ extension=".isma",
1034
+ priority=["pyav"],
1035
+ ),
1036
+ FileExtension(
1037
+ name="3GP (3GPP file format)",
1038
+ extension=".ismv",
1039
+ priority=["pyav"],
1040
+ ),
1041
+ FileExtension(
1042
+ name="3GP (3GPP file format)",
1043
+ extension=".m4a",
1044
+ priority=["pyav"],
1045
+ ),
1046
+ FileExtension(
1047
+ name="3GP (3GPP file format)",
1048
+ extension=".m4b",
1049
+ priority=["pyav"],
1050
+ ),
1051
+ FileExtension(
1052
+ name="3GP (3GPP file format)",
1053
+ extension=".mj2",
1054
+ priority=["pyav"],
1055
+ ),
1056
+ FileExtension(
1057
+ name="3GP (3GPP file format)",
1058
+ extension=".psp",
1059
+ priority=["pyav"],
1060
+ ),
1061
+ FileExtension(
1062
+ name="3GP2 (3GPP2 file format)",
1063
+ extension=".3g2",
1064
+ priority=["pyav"],
1065
+ ),
1066
+ FileExtension(
1067
+ name="3GP2 (3GPP2 file format)",
1068
+ extension=".3gp",
1069
+ priority=["pyav"],
1070
+ ),
1071
+ FileExtension(
1072
+ name="3GP2 (3GPP2 file format)",
1073
+ extension=".f4v",
1074
+ priority=["pyav"],
1075
+ ),
1076
+ FileExtension(
1077
+ name="3GP2 (3GPP2 file format)",
1078
+ extension=".ism",
1079
+ priority=["pyav"],
1080
+ ),
1081
+ FileExtension(
1082
+ name="3GP2 (3GPP2 file format)",
1083
+ extension=".isma",
1084
+ priority=["pyav"],
1085
+ ),
1086
+ FileExtension(
1087
+ name="3GP2 (3GPP2 file format)",
1088
+ extension=".ismv",
1089
+ priority=["pyav"],
1090
+ ),
1091
+ FileExtension(
1092
+ name="3GP2 (3GPP2 file format)",
1093
+ extension=".m4a",
1094
+ priority=["pyav"],
1095
+ ),
1096
+ FileExtension(
1097
+ name="3GP2 (3GPP2 file format)",
1098
+ extension=".m4b",
1099
+ priority=["pyav"],
1100
+ ),
1101
+ FileExtension(
1102
+ name="3GP2 (3GPP2 file format)",
1103
+ extension=".mj2",
1104
+ priority=["pyav"],
1105
+ ),
1106
+ FileExtension(
1107
+ name="3GP2 (3GPP2 file format)",
1108
+ extension=".psp",
1109
+ priority=["pyav"],
1110
+ ),
1111
+ FileExtension(
1112
+ name="3GPP AMR",
1113
+ extension=".amr",
1114
+ priority=["pyav"],
1115
+ ),
1116
+ FileExtension(
1117
+ name="a64 - video for Commodore 64",
1118
+ extension=".A64",
1119
+ priority=["pyav"],
1120
+ ),
1121
+ FileExtension(
1122
+ name="a64 - video for Commodore 64",
1123
+ extension=".a64",
1124
+ priority=["pyav"],
1125
+ ),
1126
+ FileExtension(
1127
+ name="Adobe Filmstrip",
1128
+ extension=".flm",
1129
+ priority=["pyav"],
1130
+ ),
1131
+ FileExtension(
1132
+ name="AMV",
1133
+ extension=".amv",
1134
+ priority=["pyav"],
1135
+ ),
1136
+ FileExtension(
1137
+ name="ASF (Advanced / Active Streaming Format)",
1138
+ extension=".asf",
1139
+ priority=["pyav"],
1140
+ ),
1141
+ FileExtension(
1142
+ name="ASF (Advanced / Active Streaming Format)",
1143
+ extension=".asf",
1144
+ priority=["pyav"],
1145
+ ),
1146
+ FileExtension(
1147
+ name="ASF (Advanced / Active Streaming Format)",
1148
+ extension=".wmv",
1149
+ priority=["pyav"],
1150
+ ),
1151
+ FileExtension(
1152
+ name="ASF (Advanced / Active Streaming Format)",
1153
+ extension=".wmv",
1154
+ priority=["pyav"],
1155
+ ),
1156
+ FileExtension(
1157
+ name="AV1 Annex B",
1158
+ extension=".obu",
1159
+ priority=["pyav"],
1160
+ ),
1161
+ FileExtension(
1162
+ name="AV1 low overhead OBU",
1163
+ extension=".obu",
1164
+ priority=["pyav"],
1165
+ ),
1166
+ FileExtension(
1167
+ name="AVI (Audio Video Interleaved)",
1168
+ extension=".avi",
1169
+ priority=["pyav"],
1170
+ ),
1171
+ FileExtension(
1172
+ name="AVR (Audio Visual Research)",
1173
+ extension=".avr",
1174
+ priority=["pyav"],
1175
+ ),
1176
+ FileExtension(
1177
+ name="Beam Software SIFF",
1178
+ extension=".vb",
1179
+ priority=["pyav"],
1180
+ ),
1181
+ FileExtension(
1182
+ name="CD Graphics",
1183
+ extension=".cdg",
1184
+ priority=["pyav"],
1185
+ ),
1186
+ FileExtension(
1187
+ name="Commodore CDXL video",
1188
+ extension=".cdxl",
1189
+ priority=["pyav"],
1190
+ ),
1191
+ FileExtension(
1192
+ name="Commodore CDXL video",
1193
+ extension=".xl",
1194
+ priority=["pyav"],
1195
+ ),
1196
+ FileExtension(
1197
+ name="DASH Muxer",
1198
+ extension=".mpd",
1199
+ priority=["pyav"],
1200
+ ),
1201
+ FileExtension(
1202
+ name="Digital Pictures SGA",
1203
+ extension=".sga",
1204
+ priority=["pyav"],
1205
+ ),
1206
+ FileExtension(
1207
+ name="Discworld II BMV",
1208
+ extension=".bmv",
1209
+ priority=["pyav"],
1210
+ ),
1211
+ FileExtension(
1212
+ name="DV (Digital Video)",
1213
+ extension=".dif",
1214
+ priority=["pyav"],
1215
+ ),
1216
+ FileExtension(
1217
+ name="DV (Digital Video)",
1218
+ extension=".dv",
1219
+ priority=["pyav"],
1220
+ ),
1221
+ FileExtension(
1222
+ name="F4V Adobe Flash Video",
1223
+ extension=".f4v",
1224
+ priority=["pyav"],
1225
+ ),
1226
+ FileExtension(
1227
+ name="FLV (Flash Video)",
1228
+ extension=".flv",
1229
+ priority=["pyav"],
1230
+ ),
1231
+ FileExtension(
1232
+ name="GXF (General eXchange Format)",
1233
+ extension=".gxf",
1234
+ priority=["pyav"],
1235
+ ),
1236
+ FileExtension(
1237
+ name="iCE Draw File",
1238
+ extension=".idf",
1239
+ priority=["pyav"],
1240
+ ),
1241
+ FileExtension(
1242
+ name="IFV CCTV DVR",
1243
+ extension=".ifv",
1244
+ priority=["pyav"],
1245
+ ),
1246
+ FileExtension(
1247
+ name="iPod H.264 MP4 (MPEG-4 Part 14)",
1248
+ extension=".m4a",
1249
+ priority=["pyav"],
1250
+ ),
1251
+ FileExtension(
1252
+ name="iPod H.264 MP4 (MPEG-4 Part 14)",
1253
+ extension=".m4b",
1254
+ priority=["pyav"],
1255
+ ),
1256
+ FileExtension(
1257
+ name="iPod H.264 MP4 (MPEG-4 Part 14)",
1258
+ extension=".m4v",
1259
+ priority=["pyav"],
1260
+ ),
1261
+ FileExtension(
1262
+ name="IVR (Internet Video Recording)",
1263
+ extension=".ivr",
1264
+ priority=["pyav"],
1265
+ ),
1266
+ FileExtension(
1267
+ name="Konami PS2 SVAG",
1268
+ extension=".svag",
1269
+ priority=["pyav"],
1270
+ ),
1271
+ FileExtension(
1272
+ name="KUX (YouKu)",
1273
+ extension=".kux",
1274
+ priority=["pyav"],
1275
+ ),
1276
+ FileExtension(
1277
+ name="live RTMP FLV (Flash Video)",
1278
+ extension=".flv",
1279
+ priority=["pyav"],
1280
+ ),
1281
+ FileExtension(
1282
+ name="Loki SDL MJPEG",
1283
+ extension=".mjpg",
1284
+ priority=["pyav"],
1285
+ ),
1286
+ FileExtension(
1287
+ name="LVF",
1288
+ extension=".lvf",
1289
+ priority=["pyav"],
1290
+ ),
1291
+ FileExtension(
1292
+ name="Matroska / WebM",
1293
+ extension=".mk3d",
1294
+ priority=["pyav"],
1295
+ ),
1296
+ FileExtension(
1297
+ name="Matroska / WebM",
1298
+ extension=".mka",
1299
+ priority=["pyav"],
1300
+ ),
1301
+ FileExtension(
1302
+ name="Matroska / WebM",
1303
+ extension=".mks",
1304
+ priority=["pyav"],
1305
+ ),
1306
+ FileExtension(
1307
+ name="Microsoft XMV",
1308
+ extension=".xmv",
1309
+ priority=["pyav"],
1310
+ ),
1311
+ FileExtension(
1312
+ name="MIME multipart JPEG",
1313
+ extension=".mjpg",
1314
+ priority=["pyav"],
1315
+ ),
1316
+ FileExtension(
1317
+ name="MobiClip MODS",
1318
+ extension=".mods",
1319
+ priority=["pyav"],
1320
+ ),
1321
+ FileExtension(
1322
+ name="MobiClip MOFLEX",
1323
+ extension=".moflex",
1324
+ priority=["pyav"],
1325
+ ),
1326
+ FileExtension(
1327
+ name="Motion Pixels MVI",
1328
+ extension=".mvi",
1329
+ priority=["pyav"],
1330
+ ),
1331
+ FileExtension(
1332
+ name="MP4 (MPEG-4 Part 14)",
1333
+ extension=".3g2",
1334
+ priority=["pyav"],
1335
+ ),
1336
+ FileExtension(
1337
+ name="MP4 (MPEG-4 Part 14)",
1338
+ extension=".3gp",
1339
+ priority=["pyav"],
1340
+ ),
1341
+ FileExtension(
1342
+ name="MP4 (MPEG-4 Part 14)",
1343
+ extension=".f4v",
1344
+ priority=["pyav"],
1345
+ ),
1346
+ FileExtension(
1347
+ name="MP4 (MPEG-4 Part 14)",
1348
+ extension=".ism",
1349
+ priority=["pyav"],
1350
+ ),
1351
+ FileExtension(
1352
+ name="MP4 (MPEG-4 Part 14)",
1353
+ extension=".isma",
1354
+ priority=["pyav"],
1355
+ ),
1356
+ FileExtension(
1357
+ name="MP4 (MPEG-4 Part 14)",
1358
+ extension=".ismv",
1359
+ priority=["pyav"],
1360
+ ),
1361
+ FileExtension(
1362
+ name="MP4 (MPEG-4 Part 14)",
1363
+ extension=".m4a",
1364
+ priority=["pyav"],
1365
+ ),
1366
+ FileExtension(
1367
+ name="MP4 (MPEG-4 Part 14)",
1368
+ extension=".m4b",
1369
+ priority=["pyav"],
1370
+ ),
1371
+ FileExtension(
1372
+ name="MP4 (MPEG-4 Part 14)",
1373
+ extension=".mj2",
1374
+ priority=["pyav"],
1375
+ ),
1376
+ FileExtension(
1377
+ name="MP4 (MPEG-4 Part 14)",
1378
+ extension=".psp",
1379
+ priority=["pyav"],
1380
+ ),
1381
+ FileExtension(
1382
+ name="MPEG-2 PS (DVD VOB)",
1383
+ extension=".dvd",
1384
+ priority=["pyav"],
1385
+ ),
1386
+ FileExtension(
1387
+ name="MPEG-2 PS (SVCD)",
1388
+ extension=".vob",
1389
+ priority=["pyav"],
1390
+ ),
1391
+ FileExtension(
1392
+ name="MPEG-2 PS (VOB)",
1393
+ extension=".vob",
1394
+ priority=["pyav"],
1395
+ ),
1396
+ FileExtension(
1397
+ name="MPEG-TS (MPEG-2 Transport Stream)",
1398
+ extension=".m2t",
1399
+ priority=["pyav"],
1400
+ ),
1401
+ FileExtension(
1402
+ name="MPEG-TS (MPEG-2 Transport Stream)",
1403
+ extension=".m2ts",
1404
+ priority=["pyav"],
1405
+ ),
1406
+ FileExtension(
1407
+ name="MPEG-TS (MPEG-2 Transport Stream)",
1408
+ extension=".mts",
1409
+ priority=["pyav"],
1410
+ ),
1411
+ FileExtension(
1412
+ name="MPEG-TS (MPEG-2 Transport Stream)",
1413
+ extension=".ts",
1414
+ priority=["pyav"],
1415
+ ),
1416
+ FileExtension(
1417
+ name="Musepack",
1418
+ extension=".mpc",
1419
+ priority=["pyav"],
1420
+ ),
1421
+ FileExtension(
1422
+ name="MXF (Material eXchange Format) Operational Pattern Atom",
1423
+ extension=".mxf",
1424
+ priority=["pyav"],
1425
+ ),
1426
+ FileExtension(
1427
+ name="MXF (Material eXchange Format)",
1428
+ extension=".mxf",
1429
+ priority=["pyav"],
1430
+ ),
1431
+ FileExtension(
1432
+ name="MxPEG clip",
1433
+ extension=".mxg",
1434
+ priority=["pyav"],
1435
+ ),
1436
+ FileExtension(
1437
+ name="NC camera feed",
1438
+ extension=".v",
1439
+ priority=["pyav"],
1440
+ ),
1441
+ FileExtension(
1442
+ name="NUT",
1443
+ extension=".nut",
1444
+ priority=["pyav"],
1445
+ ),
1446
+ FileExtension(
1447
+ name="Ogg Video",
1448
+ extension=".ogv",
1449
+ priority=["pyav"],
1450
+ ),
1451
+ FileExtension(
1452
+ name="Ogg",
1453
+ extension=".ogg",
1454
+ priority=["pyav"],
1455
+ ),
1456
+ FileExtension(
1457
+ name="On2 IVF",
1458
+ extension=".ivf",
1459
+ priority=["pyav"],
1460
+ ),
1461
+ FileExtension(
1462
+ name="PSP MP4 (MPEG-4 Part 14)",
1463
+ extension=".psp",
1464
+ priority=["pyav"],
1465
+ ),
1466
+ FileExtension(
1467
+ name="Psygnosis YOP",
1468
+ extension=".yop",
1469
+ priority=["pyav"],
1470
+ ),
1471
+ FileExtension(
1472
+ name="QuickTime / MOV",
1473
+ extension=".3g2",
1474
+ priority=["pyav"],
1475
+ ),
1476
+ FileExtension(
1477
+ name="QuickTime / MOV",
1478
+ extension=".3gp",
1479
+ priority=["pyav"],
1480
+ ),
1481
+ FileExtension(
1482
+ name="QuickTime / MOV",
1483
+ extension=".f4v",
1484
+ priority=["pyav"],
1485
+ ),
1486
+ FileExtension(
1487
+ name="QuickTime / MOV",
1488
+ extension=".ism",
1489
+ priority=["pyav"],
1490
+ ),
1491
+ FileExtension(
1492
+ name="QuickTime / MOV",
1493
+ extension=".isma",
1494
+ priority=["pyav"],
1495
+ ),
1496
+ FileExtension(
1497
+ name="QuickTime / MOV",
1498
+ extension=".ismv",
1499
+ priority=["pyav"],
1500
+ ),
1501
+ FileExtension(
1502
+ name="QuickTime / MOV",
1503
+ extension=".m4a",
1504
+ priority=["pyav"],
1505
+ ),
1506
+ FileExtension(
1507
+ name="QuickTime / MOV",
1508
+ extension=".m4b",
1509
+ priority=["pyav"],
1510
+ ),
1511
+ FileExtension(
1512
+ name="QuickTime / MOV",
1513
+ extension=".mj2",
1514
+ priority=["pyav"],
1515
+ ),
1516
+ FileExtension(
1517
+ name="QuickTime / MOV",
1518
+ extension=".psp",
1519
+ priority=["pyav"],
1520
+ ),
1521
+ FileExtension(
1522
+ name="raw AVS2-P2/IEEE1857.4 video",
1523
+ extension=".avs",
1524
+ priority=["pyav"],
1525
+ ),
1526
+ FileExtension(
1527
+ name="raw AVS2-P2/IEEE1857.4 video",
1528
+ extension=".avs2",
1529
+ priority=["pyav"],
1530
+ ),
1531
+ FileExtension(
1532
+ name="raw AVS3-P2/IEEE1857.10",
1533
+ extension=".avs3",
1534
+ priority=["pyav"],
1535
+ ),
1536
+ FileExtension(
1537
+ name="raw Chinese AVS (Audio Video Standard) video",
1538
+ extension=".cavs",
1539
+ priority=["pyav"],
1540
+ ),
1541
+ FileExtension(
1542
+ name="raw Dirac",
1543
+ extension=".drc",
1544
+ priority=["pyav"],
1545
+ ),
1546
+ FileExtension(
1547
+ name="raw Dirac",
1548
+ extension=".vc2",
1549
+ priority=["pyav"],
1550
+ ),
1551
+ FileExtension(
1552
+ name="raw DNxHD (SMPTE VC-3)",
1553
+ extension=".dnxhd",
1554
+ priority=["pyav"],
1555
+ ),
1556
+ FileExtension(
1557
+ name="raw DNxHD (SMPTE VC-3)",
1558
+ extension=".dnxhr",
1559
+ priority=["pyav"],
1560
+ ),
1561
+ FileExtension(
1562
+ name="raw GSM",
1563
+ extension=".gsm",
1564
+ priority=["pyav"],
1565
+ ),
1566
+ FileExtension(
1567
+ name="raw H.261",
1568
+ extension=".h261",
1569
+ priority=["pyav"],
1570
+ ),
1571
+ FileExtension(
1572
+ name="raw H.263",
1573
+ extension=".h263",
1574
+ priority=["pyav"],
1575
+ ),
1576
+ FileExtension(
1577
+ name="raw H.264 video",
1578
+ extension=".264",
1579
+ priority=["pyav"],
1580
+ ),
1581
+ FileExtension(
1582
+ name="raw H.264 video",
1583
+ extension=".avc",
1584
+ priority=["pyav"],
1585
+ ),
1586
+ FileExtension(
1587
+ name="raw H.264 video",
1588
+ extension=".h264",
1589
+ priority=["pyav", "FFMPEG"],
1590
+ ),
1591
+ FileExtension(
1592
+ name="raw H.264 video",
1593
+ extension=".h26l",
1594
+ priority=["pyav"],
1595
+ ),
1596
+ FileExtension(
1597
+ name="raw HEVC video",
1598
+ extension=".265",
1599
+ priority=["pyav"],
1600
+ ),
1601
+ FileExtension(
1602
+ name="raw HEVC video",
1603
+ extension=".h265",
1604
+ priority=["pyav"],
1605
+ ),
1606
+ FileExtension(
1607
+ name="raw HEVC video",
1608
+ extension=".hevc",
1609
+ priority=["pyav"],
1610
+ ),
1611
+ FileExtension(
1612
+ name="raw id RoQ",
1613
+ extension=".roq",
1614
+ priority=["pyav"],
1615
+ ),
1616
+ FileExtension(
1617
+ name="raw Ingenient MJPEG",
1618
+ extension=".cgi",
1619
+ priority=["pyav"],
1620
+ ),
1621
+ FileExtension(
1622
+ name="raw IPU Video",
1623
+ extension=".ipu",
1624
+ priority=["pyav"],
1625
+ ),
1626
+ FileExtension(
1627
+ name="raw MJPEG 2000 video",
1628
+ extension=".j2k",
1629
+ priority=["pyav"],
1630
+ ),
1631
+ FileExtension(
1632
+ name="raw MJPEG video",
1633
+ extension=".mjpeg",
1634
+ priority=["pyav"],
1635
+ ),
1636
+ FileExtension(
1637
+ name="raw MJPEG video",
1638
+ extension=".mjpg",
1639
+ priority=["pyav"],
1640
+ ),
1641
+ FileExtension(
1642
+ name="raw MJPEG video",
1643
+ extension=".mpo",
1644
+ priority=["pyav"],
1645
+ ),
1646
+ FileExtension(
1647
+ name="raw MPEG-1 video",
1648
+ extension=".m1v",
1649
+ priority=["pyav"],
1650
+ ),
1651
+ FileExtension(
1652
+ name="raw MPEG-1 video",
1653
+ extension=".mpeg",
1654
+ priority=["pyav"],
1655
+ ),
1656
+ FileExtension(
1657
+ name="raw MPEG-1 video",
1658
+ extension=".mpg",
1659
+ priority=["pyav"],
1660
+ ),
1661
+ FileExtension(
1662
+ name="raw MPEG-2 video",
1663
+ extension=".m2v",
1664
+ priority=["pyav"],
1665
+ ),
1666
+ FileExtension(
1667
+ name="raw MPEG-4 video",
1668
+ extension=".m4v",
1669
+ priority=["pyav"],
1670
+ ),
1671
+ FileExtension(
1672
+ name="raw VC-1 video",
1673
+ extension=".vc1",
1674
+ priority=["pyav"],
1675
+ ),
1676
+ FileExtension(
1677
+ name="raw video",
1678
+ extension=".cif",
1679
+ priority=["pyav"],
1680
+ ),
1681
+ FileExtension(
1682
+ name="raw video",
1683
+ extension=".qcif",
1684
+ priority=["pyav"],
1685
+ ),
1686
+ FileExtension(
1687
+ name="raw video",
1688
+ extension=".rgb",
1689
+ priority=["pyav"],
1690
+ ),
1691
+ FileExtension(
1692
+ name="raw video",
1693
+ extension=".yuv",
1694
+ priority=["pyav"],
1695
+ ),
1696
+ FileExtension(
1697
+ name="RealMedia",
1698
+ extension=".rm",
1699
+ priority=["pyav"],
1700
+ ),
1701
+ FileExtension(
1702
+ name="SDR2",
1703
+ extension=".sdr2",
1704
+ priority=["pyav"],
1705
+ ),
1706
+ FileExtension(
1707
+ name="Sega FILM / CPK",
1708
+ extension=".cpk",
1709
+ priority=["pyav"],
1710
+ ),
1711
+ FileExtension(
1712
+ name="SER (Simple uncompressed video format for astronomical capturing)",
1713
+ extension=".ser",
1714
+ priority=["pyav"],
1715
+ ),
1716
+ FileExtension(
1717
+ name="Simbiosis Interactive IMX",
1718
+ extension=".imx",
1719
+ priority=["pyav"],
1720
+ ),
1721
+ FileExtension(
1722
+ name="Square SVS",
1723
+ extension=".svs",
1724
+ priority=["tifffile", "pyav"],
1725
+ ),
1726
+ FileExtension(
1727
+ name="TiVo TY Stream",
1728
+ extension=".ty",
1729
+ priority=["pyav"],
1730
+ ),
1731
+ FileExtension(
1732
+ name="TiVo TY Stream",
1733
+ extension=".ty+",
1734
+ priority=["pyav"],
1735
+ ),
1736
+ FileExtension(
1737
+ name="Uncompressed 4:2:2 10-bit",
1738
+ extension=".v210",
1739
+ priority=["pyav"],
1740
+ ),
1741
+ FileExtension(
1742
+ name="Uncompressed 4:2:2 10-bit",
1743
+ extension=".yuv10",
1744
+ priority=["pyav"],
1745
+ ),
1746
+ FileExtension(
1747
+ name="VC-1 test bitstream",
1748
+ extension=".rcv",
1749
+ priority=["pyav"],
1750
+ ),
1751
+ FileExtension(
1752
+ name="Video CCTV DAT",
1753
+ extension=".dat",
1754
+ priority=["pyav"],
1755
+ ),
1756
+ FileExtension(
1757
+ name="Video DAV",
1758
+ extension=".dav",
1759
+ priority=["pyav"],
1760
+ ),
1761
+ FileExtension(
1762
+ name="Vivo",
1763
+ extension=".viv",
1764
+ priority=["pyav"],
1765
+ ),
1766
+ FileExtension(
1767
+ name="WebM Chunk Muxer",
1768
+ extension=".chk",
1769
+ priority=["pyav"],
1770
+ ),
1771
+ FileExtension(
1772
+ name="WebM",
1773
+ extension=".mk3d",
1774
+ priority=["pyav"],
1775
+ ),
1776
+ FileExtension(
1777
+ name="WebM",
1778
+ extension=".mka",
1779
+ priority=["pyav"],
1780
+ ),
1781
+ FileExtension(
1782
+ name="WebM",
1783
+ extension=".mks",
1784
+ priority=["pyav"],
1785
+ ),
1786
+ FileExtension(
1787
+ name="Windows Television (WTV)",
1788
+ extension=".wtv",
1789
+ priority=["pyav"],
1790
+ ),
1791
+ FileExtension(
1792
+ name="Xilam DERF",
1793
+ extension=".adp",
1794
+ priority=["pyav"],
1795
+ ),
1796
+ FileExtension(
1797
+ name="YUV4MPEG pipe",
1798
+ extension=".y4m",
1799
+ priority=["pyav"],
1800
+ ),
1801
+ FileExtension(
1802
+ extension=".qpi",
1803
+ priority=["tifffile"],
1804
+ ),
1805
+ FileExtension(
1806
+ name="PCO Camera",
1807
+ extension=".pcoraw",
1808
+ priority=["tifffile"],
1809
+ ),
1810
+ FileExtension(
1811
+ name="PCO Camera",
1812
+ extension=".rec",
1813
+ priority=["tifffile"],
1814
+ ),
1815
+ FileExtension(
1816
+ name="Perkin Elmer Vectra",
1817
+ extension=".qptiff",
1818
+ priority=["tifffile"],
1819
+ ),
1820
+ FileExtension(
1821
+ name="Pyramid Encoded TIFF",
1822
+ extension=".ptiff",
1823
+ priority=["tifffile"],
1824
+ ),
1825
+ FileExtension(
1826
+ name="Pyramid Encoded TIFF",
1827
+ extension=".ptif",
1828
+ priority=["tifffile"],
1829
+ ),
1830
+ FileExtension(
1831
+ name="Opticks Gel",
1832
+ extension=".gel",
1833
+ priority=["tifffile"],
1834
+ ),
1835
+ FileExtension(
1836
+ name="Zoomify Image Format",
1837
+ extension=".zif",
1838
+ priority=["tifffile"],
1839
+ ),
1840
+ FileExtension(
1841
+ name="Hamamatsu Slide Scanner",
1842
+ extension=".ndpi",
1843
+ priority=["tifffile"],
1844
+ ),
1845
+ FileExtension(
1846
+ name="Roche Digital Pathology",
1847
+ extension=".bif",
1848
+ priority=["tifffile"],
1849
+ ),
1850
+ FileExtension(
1851
+ extension=".tf8",
1852
+ priority=["tifffile"],
1853
+ ),
1854
+ FileExtension(
1855
+ extension=".btf",
1856
+ priority=["tifffile"],
1857
+ ),
1858
+ FileExtension(
1859
+ name="High Efficiency Image File Format",
1860
+ extension=".heic",
1861
+ priority=["pillow"],
1862
+ ),
1863
+ FileExtension(
1864
+ name="AV1 Image File Format",
1865
+ extension=".avif",
1866
+ priority=["pillow"],
1867
+ ),
1868
+ ]
1869
+ extension_list.sort(key=lambda x: x.extension)
1870
+
1871
+
1872
+ known_extensions = dict()
1873
+ for ext in extension_list:
1874
+ if ext.extension not in known_extensions:
1875
+ known_extensions[ext.extension] = list()
1876
+ known_extensions[ext.extension].append(ext)
1877
+
1878
+ extension_list = [ext for ext_list in known_extensions.values() for ext in ext_list]
1879
+
1880
+ _video_extension_strings = [
1881
+ ".264",
1882
+ ".265",
1883
+ ".3g2",
1884
+ ".3gp",
1885
+ ".a64",
1886
+ ".A64",
1887
+ ".adp",
1888
+ ".amr",
1889
+ ".amv",
1890
+ ".asf",
1891
+ ".avc",
1892
+ ".avi",
1893
+ ".avr",
1894
+ ".avs",
1895
+ ".avs2",
1896
+ ".avs3",
1897
+ ".bmv",
1898
+ ".cavs",
1899
+ ".cdg",
1900
+ ".cdxl",
1901
+ ".cgi",
1902
+ ".chk",
1903
+ ".cif",
1904
+ ".cpk",
1905
+ ".dat",
1906
+ ".dav",
1907
+ ".dif",
1908
+ ".dnxhd",
1909
+ ".dnxhr",
1910
+ ".drc",
1911
+ ".dv",
1912
+ ".dvd",
1913
+ ".f4v",
1914
+ ".flm",
1915
+ ".flv",
1916
+ ".gsm",
1917
+ ".gxf",
1918
+ ".h261",
1919
+ ".h263",
1920
+ ".h264",
1921
+ ".h265",
1922
+ ".h26l",
1923
+ ".hevc",
1924
+ ".idf",
1925
+ ".ifv",
1926
+ ".imx",
1927
+ ".ipu",
1928
+ ".ism",
1929
+ ".isma",
1930
+ ".ismv",
1931
+ ".ivf",
1932
+ ".ivr",
1933
+ ".j2k",
1934
+ ".kux",
1935
+ ".lvf",
1936
+ ".m1v",
1937
+ ".m2t",
1938
+ ".m2ts",
1939
+ ".m2v",
1940
+ ".m4a",
1941
+ ".m4b",
1942
+ ".m4v",
1943
+ ".mj2",
1944
+ ".mjpeg",
1945
+ ".mjpg",
1946
+ ".mk3d",
1947
+ ".mka",
1948
+ ".mks",
1949
+ ".mkv",
1950
+ ".mods",
1951
+ ".moflex",
1952
+ ".mov",
1953
+ ".mp4",
1954
+ ".mpc",
1955
+ ".mpd",
1956
+ ".mpeg",
1957
+ ".mpg",
1958
+ ".mpo",
1959
+ ".mts",
1960
+ ".mvi",
1961
+ ".mxf",
1962
+ ".mxg",
1963
+ ".nut",
1964
+ ".obu",
1965
+ ".ogg",
1966
+ ".ogv",
1967
+ ".psp",
1968
+ ".qcif",
1969
+ ".rcv",
1970
+ ".rgb",
1971
+ ".rm",
1972
+ ".roq",
1973
+ ".sdr2",
1974
+ ".ser",
1975
+ ".sga",
1976
+ ".svag",
1977
+ ".svs",
1978
+ ".ts",
1979
+ ".ty",
1980
+ ".ty+",
1981
+ ".v",
1982
+ ".v210",
1983
+ ".vb",
1984
+ ".vc1",
1985
+ ".vc2",
1986
+ ".viv",
1987
+ ".vob",
1988
+ ".webm",
1989
+ ".wmv",
1990
+ ".wtv",
1991
+ ".xl",
1992
+ ".xmv",
1993
+ ".y4m",
1994
+ ".yop",
1995
+ ".yuv",
1996
+ ".yuv10",
1997
+ ]
1998
+ video_extensions = list()
1999
+ for ext_string in _video_extension_strings:
2000
+ formats = known_extensions[ext_string]
2001
+ video_extensions.append(formats[0])
2002
+ video_extensions.sort(key=lambda x: x.extension)
minigpt2/lib/python3.10/site-packages/imageio/config/extensions.pyi ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List, Dict, Optional
2
+
3
+ class FileExtension:
4
+ extension: str
5
+ priority: List[str]
6
+ name: Optional[str] = None
7
+ description: Optional[str] = None
8
+ external_link: Optional[str] = None
9
+ volume_support: bool
10
+
11
+ def __init__(
12
+ self,
13
+ *,
14
+ extension: str,
15
+ priority: List[str],
16
+ name: str = None,
17
+ description: str = None,
18
+ external_link: str = None
19
+ ) -> None: ...
20
+ def reset(self) -> None: ...
21
+
22
+ extension_list: List[FileExtension]
23
+ known_extensions: Dict[str, List[FileExtension]]
24
+ video_extensions: List[FileExtension]
minigpt2/lib/python3.10/site-packages/imageio/config/plugins.py ADDED
@@ -0,0 +1,782 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import importlib
2
+
3
+ from ..core.legacy_plugin_wrapper import LegacyPlugin
4
+
5
+
6
+ class PluginConfig:
7
+ """Plugin Configuration Metadata
8
+
9
+ This class holds the information needed to lazy-import plugins.
10
+
11
+ Parameters
12
+ ----------
13
+ name : str
14
+ The name of the plugin.
15
+ class_name : str
16
+ The name of the plugin class inside the plugin module.
17
+ module_name : str
18
+ The name of the module/package from which to import the plugin.
19
+ is_legacy : bool
20
+ If True, this plugin is a v2 plugin and will be wrapped in a
21
+ LegacyPlugin. Default: False.
22
+ package_name : str
23
+ If the given module name points to a relative module, then the package
24
+ name determines the package it is relative to.
25
+ install_name : str
26
+ The name of the optional dependency that can be used to install this
27
+ plugin if it is missing.
28
+ legacy_args : Dict
29
+ A dictionary of kwargs to pass to the v2 plugin (Format) upon construction.
30
+
31
+ Examples
32
+ --------
33
+ >>> PluginConfig(
34
+ name="TIFF",
35
+ class_name="TiffFormat",
36
+ module_name="imageio.plugins.tifffile",
37
+ is_legacy=True,
38
+ install_name="tifffile",
39
+ legacy_args={
40
+ "description": "TIFF format",
41
+ "extensions": ".tif .tiff .stk .lsm",
42
+ "modes": "iIvV",
43
+ },
44
+ )
45
+ >>> PluginConfig(
46
+ name="pillow",
47
+ class_name="PillowPlugin",
48
+ module_name="imageio.plugins.pillow"
49
+ )
50
+
51
+ """
52
+
53
+ def __init__(
54
+ self,
55
+ name,
56
+ class_name,
57
+ module_name,
58
+ *,
59
+ is_legacy=False,
60
+ package_name=None,
61
+ install_name=None,
62
+ legacy_args=None,
63
+ ):
64
+ legacy_args = legacy_args or dict()
65
+
66
+ self.name = name
67
+ self.class_name = class_name
68
+ self.module_name = module_name
69
+ self.package_name = package_name
70
+
71
+ self.is_legacy = is_legacy
72
+ self.install_name = install_name or self.name
73
+ self.legacy_args = {"name": name, "description": "A legacy plugin"}
74
+ self.legacy_args.update(legacy_args)
75
+
76
+ @property
77
+ def format(self):
78
+ """For backwards compatibility with FormatManager
79
+
80
+ Delete when migrating to v3
81
+ """
82
+ if not self.is_legacy:
83
+ raise RuntimeError("Can only get format for legacy plugins.")
84
+
85
+ module = importlib.import_module(self.module_name, self.package_name)
86
+ clazz = getattr(module, self.class_name)
87
+ return clazz(**self.legacy_args)
88
+
89
+ @property
90
+ def plugin_class(self):
91
+ """Get the plugin class (import if needed)
92
+
93
+ Returns
94
+ -------
95
+ plugin_class : Any
96
+ The class that can be used to instantiate plugins.
97
+
98
+ """
99
+
100
+ module = importlib.import_module(self.module_name, self.package_name)
101
+ clazz = getattr(module, self.class_name)
102
+
103
+ if self.is_legacy:
104
+ legacy_plugin = clazz(**self.legacy_args)
105
+
106
+ def partial_legacy_plugin(request):
107
+ return LegacyPlugin(request, legacy_plugin)
108
+
109
+ clazz = partial_legacy_plugin
110
+
111
+ return clazz
112
+
113
+
114
+ known_plugins = dict()
115
+ known_plugins["pillow"] = PluginConfig(
116
+ name="pillow", class_name="PillowPlugin", module_name="imageio.plugins.pillow"
117
+ )
118
+ known_plugins["pyav"] = PluginConfig(
119
+ name="pyav", class_name="PyAVPlugin", module_name="imageio.plugins.pyav"
120
+ )
121
+ known_plugins["opencv"] = PluginConfig(
122
+ name="opencv", class_name="OpenCVPlugin", module_name="imageio.plugins.opencv"
123
+ )
124
+ known_plugins["tifffile"] = PluginConfig(
125
+ name="tifffile",
126
+ class_name="TifffilePlugin",
127
+ module_name="imageio.plugins.tifffile_v3",
128
+ )
129
+ known_plugins["SPE"] = PluginConfig(
130
+ name="spe", class_name="SpePlugin", module_name="imageio.plugins.spe"
131
+ )
132
+ known_plugins["rawpy"] = PluginConfig(
133
+ name="rawpy", class_name="RawPyPlugin", module_name="imageio.plugins.rawpy"
134
+ )
135
+
136
+ # Legacy plugins
137
+ # ==============
138
+ #
139
+ # Which are partly registered by format, partly by plugin, and partly by a mix
140
+ # of both. We keep the naming here for backwards compatibility.
141
+ # In v3 this should become a single entry per plugin named after the plugin
142
+ # We can choose extension-specific priority in ``config.extensions``.
143
+ #
144
+ # Note: Since python 3.7 order of insertion determines the order of dict().keys()
145
+ # This means that the order here determines the order by which plugins are
146
+ # checked during the full fallback search. We don't advertise this downstream,
147
+ # but it could be a useful thing to keep in mind to choose a sensible default
148
+ # search order.
149
+
150
+ known_plugins["TIFF"] = PluginConfig(
151
+ name="TIFF",
152
+ class_name="TiffFormat",
153
+ module_name="imageio.plugins.tifffile",
154
+ is_legacy=True,
155
+ install_name="tifffile",
156
+ legacy_args={
157
+ "description": "TIFF format",
158
+ "extensions": ".tif .tiff .stk .lsm",
159
+ "modes": "iIvV",
160
+ },
161
+ )
162
+
163
+ # PILLOW plugin formats (legacy)
164
+ PILLOW_FORMATS = [
165
+ ("BMP", "Windows Bitmap", ".bmp", "PillowFormat"),
166
+ ("BUFR", "BUFR", ".bufr", "PillowFormat"),
167
+ ("CUR", "Windows Cursor", ".cur", "PillowFormat"),
168
+ ("DCX", "Intel DCX", ".dcx", "PillowFormat"),
169
+ ("DDS", "DirectDraw Surface", ".dds", "PillowFormat"),
170
+ ("DIB", "Windows Bitmap", "", "PillowFormat"),
171
+ ("EPS", "Encapsulated Postscript", ".ps .eps", "PillowFormat"),
172
+ ("FITS", "FITS", ".fit .fits", "PillowFormat"),
173
+ ("FLI", "Autodesk FLI/FLC Animation", ".fli .flc", "PillowFormat"),
174
+ ("FPX", "FlashPix", ".fpx", "PillowFormat"),
175
+ ("FTEX", "Texture File Format (IW2:EOC)", ".ftc .ftu", "PillowFormat"),
176
+ ("GBR", "GIMP brush file", ".gbr", "PillowFormat"),
177
+ ("GIF", "Compuserve GIF", ".gif", "GIFFormat"),
178
+ ("GRIB", "GRIB", ".grib", "PillowFormat"),
179
+ ("HDF5", "HDF5", ".h5 .hdf", "PillowFormat"),
180
+ ("ICNS", "Mac OS icns resource", ".icns", "PillowFormat"),
181
+ ("ICO", "Windows Icon", ".ico", "PillowFormat"),
182
+ ("IM", "IFUNC Image Memory", ".im", "PillowFormat"),
183
+ ("IMT", "IM Tools", "", "PillowFormat"),
184
+ ("IPTC", "IPTC/NAA", ".iim", "PillowFormat"),
185
+ ("JPEG", "JPEG (ISO 10918)", ".jfif .jpe .jpg .jpeg", "JPEGFormat"),
186
+ (
187
+ "JPEG2000",
188
+ "JPEG 2000 (ISO 15444)",
189
+ ".jp2 .j2k .jpc .jpf .jpx .j2c",
190
+ "JPEG2000Format",
191
+ ),
192
+ ("MCIDAS", "McIdas area file", "", "PillowFormat"),
193
+ ("MIC", "Microsoft Image Composer", ".mic", "PillowFormat"),
194
+ # skipped in legacy pillow
195
+ # ("MPEG", "MPEG", ".mpg .mpeg", "PillowFormat"),
196
+ ("MPO", "MPO (CIPA DC-007)", ".mpo", "PillowFormat"),
197
+ ("MSP", "Windows Paint", ".msp", "PillowFormat"),
198
+ ("PCD", "Kodak PhotoCD", ".pcd", "PillowFormat"),
199
+ ("PCX", "Paintbrush", ".pcx", "PillowFormat"),
200
+ ("PIXAR", "PIXAR raster image", ".pxr", "PillowFormat"),
201
+ ("PNG", "Portable network graphics", ".png", "PNGFormat"),
202
+ ("PPM", "Pbmplus image", ".pbm .pgm .ppm", "PillowFormat"),
203
+ ("PSD", "Adobe Photoshop", ".psd", "PillowFormat"),
204
+ ("SGI", "SGI Image File Format", ".bw .rgb .rgba .sgi", "PillowFormat"),
205
+ ("SPIDER", "Spider 2D image", "", "PillowFormat"),
206
+ ("SUN", "Sun Raster File", ".ras", "PillowFormat"),
207
+ ("TGA", "Targa", ".tga", "PillowFormat"),
208
+ ("TIFF", "Adobe TIFF", ".tif .tiff", "TIFFFormat"),
209
+ ("WMF", "Windows Metafile", ".wmf .emf", "PillowFormat"),
210
+ ("XBM", "X11 Bitmap", ".xbm", "PillowFormat"),
211
+ ("XPM", "X11 Pixel Map", ".xpm", "PillowFormat"),
212
+ ("XVTHUMB", "XV thumbnail image", "", "PillowFormat"),
213
+ ]
214
+ for id, summary, ext, class_name in PILLOW_FORMATS:
215
+ config = PluginConfig(
216
+ name=id.upper() + "-PIL",
217
+ class_name=class_name,
218
+ module_name="imageio.plugins.pillow_legacy",
219
+ is_legacy=True,
220
+ install_name="pillow",
221
+ legacy_args={
222
+ "description": summary + " via Pillow",
223
+ "extensions": ext,
224
+ "modes": "iI" if class_name == "GIFFormat" else "i",
225
+ "plugin_id": id,
226
+ },
227
+ )
228
+ known_plugins[config.name] = config
229
+
230
+ known_plugins["FFMPEG"] = PluginConfig(
231
+ name="FFMPEG",
232
+ class_name="FfmpegFormat",
233
+ module_name="imageio.plugins.ffmpeg",
234
+ is_legacy=True,
235
+ install_name="ffmpeg",
236
+ legacy_args={
237
+ "description": "Many video formats and cameras (via ffmpeg)",
238
+ "extensions": ".mov .avi .mpg .mpeg .mp4 .mkv .webm .wmv .h264",
239
+ "modes": "I",
240
+ },
241
+ )
242
+
243
+ known_plugins["BSDF"] = PluginConfig(
244
+ name="BSDF",
245
+ class_name="BsdfFormat",
246
+ module_name="imageio.plugins.bsdf",
247
+ is_legacy=True,
248
+ install_name="bsdf",
249
+ legacy_args={
250
+ "description": "Format based on the Binary Structured Data Format",
251
+ "extensions": ".bsdf",
252
+ "modes": "iIvV",
253
+ },
254
+ )
255
+
256
+ known_plugins["DICOM"] = PluginConfig(
257
+ name="DICOM",
258
+ class_name="DicomFormat",
259
+ module_name="imageio.plugins.dicom",
260
+ is_legacy=True,
261
+ install_name="dicom",
262
+ legacy_args={
263
+ "description": "Digital Imaging and Communications in Medicine",
264
+ "extensions": ".dcm .ct .mri",
265
+ "modes": "iIvV",
266
+ },
267
+ )
268
+
269
+ known_plugins["FEI"] = PluginConfig(
270
+ name="FEI",
271
+ class_name="FEISEMFormat",
272
+ module_name="imageio.plugins.feisem",
273
+ is_legacy=True,
274
+ install_name="feisem",
275
+ legacy_args={
276
+ "description": "FEI-SEM TIFF format",
277
+ "extensions": [".tif", ".tiff"],
278
+ "modes": "iv",
279
+ },
280
+ )
281
+
282
+ known_plugins["FITS"] = PluginConfig(
283
+ name="FITS",
284
+ class_name="FitsFormat",
285
+ module_name="imageio.plugins.fits",
286
+ is_legacy=True,
287
+ install_name="fits",
288
+ legacy_args={
289
+ "description": "Flexible Image Transport System (FITS) format",
290
+ "extensions": ".fits .fit .fts .fz",
291
+ "modes": "iIvV",
292
+ },
293
+ )
294
+
295
+ known_plugins["GDAL"] = PluginConfig(
296
+ name="GDAL",
297
+ class_name="GdalFormat",
298
+ module_name="imageio.plugins.gdal",
299
+ is_legacy=True,
300
+ install_name="gdal",
301
+ legacy_args={
302
+ "description": "Geospatial Data Abstraction Library",
303
+ "extensions": ".tiff .tif .img .ecw .jpg .jpeg",
304
+ "modes": "iIvV",
305
+ },
306
+ )
307
+
308
+ known_plugins["ITK"] = PluginConfig(
309
+ name="ITK",
310
+ class_name="ItkFormat",
311
+ module_name="imageio.plugins.simpleitk",
312
+ is_legacy=True,
313
+ install_name="simpleitk",
314
+ legacy_args={
315
+ "description": "Insight Segmentation and Registration Toolkit (ITK) format",
316
+ "extensions": " ".join(
317
+ (
318
+ ".gipl",
319
+ ".ipl",
320
+ ".mha",
321
+ ".mhd",
322
+ ".nhdr",
323
+ ".nia",
324
+ ".hdr",
325
+ ".nrrd",
326
+ ".nii",
327
+ ".nii.gz",
328
+ ".img",
329
+ ".img.gz",
330
+ ".vtk",
331
+ ".hdf5",
332
+ ".lsm",
333
+ ".mnc",
334
+ ".mnc2",
335
+ ".mgh",
336
+ ".mnc",
337
+ ".pic",
338
+ ".bmp",
339
+ ".jpeg",
340
+ ".jpg",
341
+ ".png",
342
+ ".tiff",
343
+ ".tif",
344
+ ".dicom",
345
+ ".dcm",
346
+ ".gdcm",
347
+ )
348
+ ),
349
+ "modes": "iIvV",
350
+ },
351
+ )
352
+
353
+ known_plugins["NPZ"] = PluginConfig(
354
+ name="NPZ",
355
+ class_name="NpzFormat",
356
+ module_name="imageio.plugins.npz",
357
+ is_legacy=True,
358
+ install_name="numpy",
359
+ legacy_args={
360
+ "description": "Numpy's compressed array format",
361
+ "extensions": ".npz",
362
+ "modes": "iIvV",
363
+ },
364
+ )
365
+
366
+ known_plugins["SWF"] = PluginConfig(
367
+ name="SWF",
368
+ class_name="SWFFormat",
369
+ module_name="imageio.plugins.swf",
370
+ is_legacy=True,
371
+ install_name="swf",
372
+ legacy_args={
373
+ "description": "Shockwave flash",
374
+ "extensions": ".swf",
375
+ "modes": "I",
376
+ },
377
+ )
378
+
379
+ known_plugins["SCREENGRAB"] = PluginConfig(
380
+ name="SCREENGRAB",
381
+ class_name="ScreenGrabFormat",
382
+ module_name="imageio.plugins.grab",
383
+ is_legacy=True,
384
+ install_name="pillow",
385
+ legacy_args={
386
+ "description": "Grab screenshots (Windows and OS X only)",
387
+ "extensions": [],
388
+ "modes": "i",
389
+ },
390
+ )
391
+
392
+ known_plugins["CLIPBOARDGRAB"] = PluginConfig(
393
+ name="CLIPBOARDGRAB",
394
+ class_name="ClipboardGrabFormat",
395
+ module_name="imageio.plugins.grab",
396
+ is_legacy=True,
397
+ install_name="pillow",
398
+ legacy_args={
399
+ "description": "Grab from clipboard (Windows only)",
400
+ "extensions": [],
401
+ "modes": "i",
402
+ },
403
+ )
404
+
405
+ # LYTRO plugin (legacy)
406
+ lytro_formats = [
407
+ ("lytro-lfr", "Lytro Illum lfr image file", ".lfr", "i", "LytroLfrFormat"),
408
+ (
409
+ "lytro-illum-raw",
410
+ "Lytro Illum raw image file",
411
+ ".raw",
412
+ "i",
413
+ "LytroIllumRawFormat",
414
+ ),
415
+ ("lytro-lfp", "Lytro F01 lfp image file", ".lfp", "i", "LytroLfpFormat"),
416
+ ("lytro-f01-raw", "Lytro F01 raw image file", ".raw", "i", "LytroF01RawFormat"),
417
+ ]
418
+ for name, des, ext, mode, class_name in lytro_formats:
419
+ config = PluginConfig(
420
+ name=name.upper(),
421
+ class_name=class_name,
422
+ module_name="imageio.plugins.lytro",
423
+ is_legacy=True,
424
+ install_name="lytro",
425
+ legacy_args={
426
+ "description": des,
427
+ "extensions": ext,
428
+ "modes": mode,
429
+ },
430
+ )
431
+ known_plugins[config.name] = config
432
+
433
+ # FreeImage plugin (legacy)
434
+ FREEIMAGE_FORMATS = [
435
+ (
436
+ "BMP",
437
+ 0,
438
+ "Windows or OS/2 Bitmap",
439
+ ".bmp",
440
+ "i",
441
+ "FreeimageBmpFormat",
442
+ "imageio.plugins.freeimage",
443
+ ),
444
+ (
445
+ "CUT",
446
+ 21,
447
+ "Dr. Halo",
448
+ ".cut",
449
+ "i",
450
+ "FreeimageFormat",
451
+ "imageio.plugins.freeimage",
452
+ ),
453
+ (
454
+ "DDS",
455
+ 24,
456
+ "DirectX Surface",
457
+ ".dds",
458
+ "i",
459
+ "FreeimageFormat",
460
+ "imageio.plugins.freeimage",
461
+ ),
462
+ (
463
+ "EXR",
464
+ 29,
465
+ "ILM OpenEXR",
466
+ ".exr",
467
+ "i",
468
+ "FreeimageFormat",
469
+ "imageio.plugins.freeimage",
470
+ ),
471
+ (
472
+ "G3",
473
+ 27,
474
+ "Raw fax format CCITT G.3",
475
+ ".g3",
476
+ "i",
477
+ "FreeimageFormat",
478
+ "imageio.plugins.freeimage",
479
+ ),
480
+ (
481
+ "GIF",
482
+ 25,
483
+ "Static and animated gif (FreeImage)",
484
+ ".gif",
485
+ "iI",
486
+ "GifFormat",
487
+ "imageio.plugins.freeimagemulti",
488
+ ),
489
+ (
490
+ "HDR",
491
+ 26,
492
+ "High Dynamic Range Image",
493
+ ".hdr",
494
+ "i",
495
+ "FreeimageFormat",
496
+ "imageio.plugins.freeimage",
497
+ ),
498
+ (
499
+ "ICO",
500
+ 1,
501
+ "Windows Icon",
502
+ ".ico",
503
+ "iI",
504
+ "IcoFormat",
505
+ "imageio.plugins.freeimagemulti",
506
+ ),
507
+ (
508
+ "IFF",
509
+ 5,
510
+ "IFF Interleaved Bitmap",
511
+ ".iff .lbm",
512
+ "i",
513
+ "FreeimageFormat",
514
+ "imageio.plugins.freeimage",
515
+ ),
516
+ (
517
+ "J2K",
518
+ 30,
519
+ "JPEG-2000 codestream",
520
+ ".j2k .j2c",
521
+ "i",
522
+ "FreeimageFormat",
523
+ "imageio.plugins.freeimage",
524
+ ),
525
+ (
526
+ "JNG",
527
+ 3,
528
+ "JPEG Network Graphics",
529
+ ".jng",
530
+ "i",
531
+ "FreeimageFormat",
532
+ "imageio.plugins.freeimage",
533
+ ),
534
+ (
535
+ "JP2",
536
+ 31,
537
+ "JPEG-2000 File Format",
538
+ ".jp2",
539
+ "i",
540
+ "FreeimageFormat",
541
+ "imageio.plugins.freeimage",
542
+ ),
543
+ (
544
+ "JPEG",
545
+ 2,
546
+ "JPEG - JFIF Compliant",
547
+ ".jpg .jif .jpeg .jpe",
548
+ "i",
549
+ "FreeimageJpegFormat",
550
+ "imageio.plugins.freeimage",
551
+ ),
552
+ (
553
+ "JPEG-XR",
554
+ 36,
555
+ "JPEG XR image format",
556
+ ".jxr .wdp .hdp",
557
+ "i",
558
+ "FreeimageFormat",
559
+ "imageio.plugins.freeimage",
560
+ ),
561
+ (
562
+ "KOALA",
563
+ 4,
564
+ "C64 Koala Graphics",
565
+ ".koa",
566
+ "i",
567
+ "FreeimageFormat",
568
+ "imageio.plugins.freeimage",
569
+ ),
570
+ # not registered in legacy pillow
571
+ # ("MNG", 6, "Multiple-image Network Graphics", ".mng", "i", "FreeimageFormat", "imageio.plugins.freeimage"),
572
+ (
573
+ "PBM",
574
+ 7,
575
+ "Portable Bitmap (ASCII)",
576
+ ".pbm",
577
+ "i",
578
+ "FreeimageFormat",
579
+ "imageio.plugins.freeimage",
580
+ ),
581
+ (
582
+ "PBMRAW",
583
+ 8,
584
+ "Portable Bitmap (RAW)",
585
+ ".pbm",
586
+ "i",
587
+ "FreeimageFormat",
588
+ "imageio.plugins.freeimage",
589
+ ),
590
+ (
591
+ "PCD",
592
+ 9,
593
+ "Kodak PhotoCD",
594
+ ".pcd",
595
+ "i",
596
+ "FreeimageFormat",
597
+ "imageio.plugins.freeimage",
598
+ ),
599
+ (
600
+ "PCX",
601
+ 10,
602
+ "Zsoft Paintbrush",
603
+ ".pcx",
604
+ "i",
605
+ "FreeimageFormat",
606
+ "imageio.plugins.freeimage",
607
+ ),
608
+ (
609
+ "PFM",
610
+ 32,
611
+ "Portable floatmap",
612
+ ".pfm",
613
+ "i",
614
+ "FreeimageFormat",
615
+ "imageio.plugins.freeimage",
616
+ ),
617
+ (
618
+ "PGM",
619
+ 11,
620
+ "Portable Greymap (ASCII)",
621
+ ".pgm",
622
+ "i",
623
+ "FreeimageFormat",
624
+ "imageio.plugins.freeimage",
625
+ ),
626
+ (
627
+ "PGMRAW",
628
+ 12,
629
+ "Portable Greymap (RAW)",
630
+ ".pgm",
631
+ "i",
632
+ "FreeimageFormat",
633
+ "imageio.plugins.freeimage",
634
+ ),
635
+ (
636
+ "PICT",
637
+ 33,
638
+ "Macintosh PICT",
639
+ ".pct .pict .pic",
640
+ "i",
641
+ "FreeimageFormat",
642
+ "imageio.plugins.freeimage",
643
+ ),
644
+ (
645
+ "PNG",
646
+ 13,
647
+ "Portable Network Graphics",
648
+ ".png",
649
+ "i",
650
+ "FreeimagePngFormat",
651
+ "imageio.plugins.freeimage",
652
+ ),
653
+ (
654
+ "PPM",
655
+ 14,
656
+ "Portable Pixelmap (ASCII)",
657
+ ".ppm",
658
+ "i",
659
+ "FreeimagePnmFormat",
660
+ "imageio.plugins.freeimage",
661
+ ),
662
+ (
663
+ "PPMRAW",
664
+ 15,
665
+ "Portable Pixelmap (RAW)",
666
+ ".ppm",
667
+ "i",
668
+ "FreeimagePnmFormat",
669
+ "imageio.plugins.freeimage",
670
+ ),
671
+ (
672
+ "PSD",
673
+ 20,
674
+ "Adobe Photoshop",
675
+ ".psd",
676
+ "i",
677
+ "FreeimageFormat",
678
+ "imageio.plugins.freeimage",
679
+ ),
680
+ (
681
+ "RAS",
682
+ 16,
683
+ "Sun Raster Image",
684
+ ".ras",
685
+ "i",
686
+ "FreeimageFormat",
687
+ "imageio.plugins.freeimage",
688
+ ),
689
+ (
690
+ "RAW",
691
+ 34,
692
+ "RAW camera image",
693
+ ".3fr .arw .bay .bmq .cap .cine .cr2 .crw .cs1 .dc2 "
694
+ ".dcr .drf .dsc .dng .erf .fff .ia .iiq .k25 .kc2 .kdc .mdc .mef .mos .mrw .nef .nrw .orf "
695
+ ".pef .ptx .pxn .qtk .raf .raw .rdc .rw2 .rwl .rwz .sr2 .srf .srw .sti",
696
+ "i",
697
+ "FreeimageFormat",
698
+ "imageio.plugins.freeimage",
699
+ ),
700
+ (
701
+ "SGI",
702
+ 28,
703
+ "SGI Image Format",
704
+ ".sgi .rgb .rgba .bw",
705
+ "i",
706
+ "FreeimageFormat",
707
+ "imageio.plugins.freeimage",
708
+ ),
709
+ (
710
+ "TARGA",
711
+ 17,
712
+ "Truevision Targa",
713
+ ".tga .targa",
714
+ "i",
715
+ "FreeimageFormat",
716
+ "imageio.plugins.freeimage",
717
+ ),
718
+ (
719
+ "TIFF",
720
+ 18,
721
+ "Tagged Image File Format",
722
+ ".tif .tiff",
723
+ "i",
724
+ "FreeimageFormat",
725
+ "imageio.plugins.freeimage",
726
+ ),
727
+ (
728
+ "WBMP",
729
+ 19,
730
+ "Wireless Bitmap",
731
+ ".wap .wbmp .wbm",
732
+ "i",
733
+ "FreeimageFormat",
734
+ "imageio.plugins.freeimage",
735
+ ),
736
+ (
737
+ "WebP",
738
+ 35,
739
+ "Google WebP image format",
740
+ ".webp",
741
+ "i",
742
+ "FreeimageFormat",
743
+ "imageio.plugins.freeimage",
744
+ ),
745
+ (
746
+ "XBM",
747
+ 22,
748
+ "X11 Bitmap Format",
749
+ ".xbm",
750
+ "i",
751
+ "FreeimageFormat",
752
+ "imageio.plugins.freeimage",
753
+ ),
754
+ (
755
+ "XPM",
756
+ 23,
757
+ "X11 Pixmap Format",
758
+ ".xpm",
759
+ "i",
760
+ "FreeimageFormat",
761
+ "imageio.plugins.freeimage",
762
+ ),
763
+ ]
764
+ for name, i, des, ext, mode, class_name, module_name in FREEIMAGE_FORMATS:
765
+ config = PluginConfig(
766
+ name=name.upper() + "-FI",
767
+ class_name=class_name,
768
+ module_name=module_name,
769
+ is_legacy=True,
770
+ install_name="freeimage",
771
+ legacy_args={
772
+ "description": des,
773
+ "extensions": ext,
774
+ "modes": mode,
775
+ "fif": i,
776
+ },
777
+ )
778
+ known_plugins[config.name] = config
779
+
780
+ # exists for backwards compatibility with FormatManager
781
+ # delete in V3
782
+ _original_order = [x for x, config in known_plugins.items() if config.is_legacy]
minigpt2/lib/python3.10/site-packages/imageio/config/plugins.pyi ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Dict, Optional
2
+ from ..core.v3_plugin_api import PluginV3
3
+
4
+ class PluginConfig:
5
+ name: str
6
+ class_name: str
7
+ module_name: str
8
+ is_legacy: bool
9
+ package_name: Optional[str] = None
10
+ install_name: Optional[str] = None
11
+ legacy_args: Optional[dict] = None
12
+ @property
13
+ def format(self) -> Any: ...
14
+ @property
15
+ def plugin_class(self) -> PluginV3: ...
16
+ def __init__(
17
+ self,
18
+ name: str,
19
+ class_name: str,
20
+ module_name: str,
21
+ *,
22
+ is_legacy: bool = False,
23
+ package_name: str = None,
24
+ install_name: str = None,
25
+ legacy_args: dict = None,
26
+ ) -> None: ...
27
+
28
+ known_plugins: Dict[str, PluginConfig]
minigpt2/lib/python3.10/site-packages/imageio/freeze.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Helper functions for freezing imageio.
3
+ """
4
+
5
+
6
+ def get_includes():
7
+ return ["email", "urllib.request", "numpy", "zipfile", "io"]
8
+
9
+
10
+ def get_excludes():
11
+ return []
minigpt2/lib/python3.10/site-packages/imageio/plugins/__init__.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # imageio is distributed under the terms of the (new) BSD License.
3
+
4
+ # flake8: noqa
5
+
6
+ """
7
+ Here you can find documentation on how to write your own plugin to allow
8
+ ImageIO to access a new backend. Plugins are quite object oriented, and
9
+ the relevant classes and their interaction are documented here:
10
+
11
+ .. currentmodule:: imageio
12
+
13
+ .. autosummary::
14
+ :toctree: ../_autosummary
15
+ :template: better_class.rst
16
+
17
+ imageio.core.Format
18
+ imageio.core.Request
19
+
20
+ .. note::
21
+ You can always check existing plugins if you want to see examples.
22
+
23
+ What methods to implement
24
+ -------------------------
25
+
26
+ To implement a new plugin, create a new class that inherits from
27
+ :class:`imageio.core.Format`. and implement the following functions:
28
+
29
+ .. autosummary::
30
+ :toctree: ../_autosummary
31
+
32
+ imageio.core.Format.__init__
33
+ imageio.core.Format._can_read
34
+ imageio.core.Format._can_write
35
+
36
+ Further, each format contains up to two nested classes; one for reading and
37
+ one for writing. To support reading and/or writing, the respective classes
38
+ need to be defined.
39
+
40
+ For reading, create a nested class that inherits from
41
+ ``imageio.core.Format.Reader`` and that implements the following functions:
42
+
43
+ * Implement ``_open(**kwargs)`` to initialize the reader. Deal with the
44
+ user-provided keyword arguments here.
45
+ * Implement ``_close()`` to clean up.
46
+ * Implement ``_get_length()`` to provide a suitable length based on what
47
+ the user expects. Can be ``inf`` for streaming data.
48
+ * Implement ``_get_data(index)`` to return an array and a meta-data dict.
49
+ * Implement ``_get_meta_data(index)`` to return a meta-data dict. If index
50
+ is None, it should return the 'global' meta-data.
51
+
52
+ For writing, create a nested class that inherits from
53
+ ``imageio.core.Format.Writer`` and implement the following functions:
54
+
55
+ * Implement ``_open(**kwargs)`` to initialize the writer. Deal with the
56
+ user-provided keyword arguments here.
57
+ * Implement ``_close()`` to clean up.
58
+ * Implement ``_append_data(im, meta)`` to add data (and meta-data).
59
+ * Implement ``_set_meta_data(meta)`` to set the global meta-data.
60
+
61
+ """
62
+
63
+ import importlib
64
+ import os
65
+ import warnings
66
+
67
+
68
+ # v2 imports remove in v3
69
+ from .. import formats
70
+
71
+ # v2 allows formatting plugins by environment variable
72
+ # this is done here.
73
+ env_plugin_order = os.getenv("IMAGEIO_FORMAT_ORDER", None)
74
+ if env_plugin_order is not None: # pragma: no cover
75
+ warnings.warn(
76
+ "Setting plugin priority through an environment variable is"
77
+ " deprecated and will be removed in ImageIO v3. There is no"
78
+ " replacement planned for this feature. If you have an"
79
+ " active use-case for it, please reach out to us on GitHub.",
80
+ DeprecationWarning,
81
+ )
82
+
83
+ formats.sort(*os.getenv("IMAGEIO_FORMAT_ORDER", "").split(","))
84
+
85
+
86
+ # this class replaces plugin module. For details
87
+ # see https://stackoverflow.com/questions/2447353/getattr-on-a-module
88
+ def __getattr__(name):
89
+ """Lazy-Import Plugins
90
+
91
+ This function dynamically loads plugins into the imageio.plugin
92
+ namespace upon first access. For example, the following snippet will
93
+ delay importing freeimage until the second line:
94
+
95
+ >>> import imageio
96
+ >>> imageio.plugins.freeimage.download()
97
+
98
+ """
99
+
100
+ try:
101
+ return importlib.import_module(f"imageio.plugins.{name}")
102
+ except ImportError:
103
+ raise AttributeError(f"module '{__name__}' has no attribute '{name}'") from None
minigpt2/lib/python3.10/site-packages/imageio/plugins/_bsdf.py ADDED
@@ -0,0 +1,915 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # This file is distributed under the terms of the 2-clause BSD License.
3
+ # Copyright (c) 2017-2018, Almar Klein
4
+
5
+ """
6
+ Python implementation of the Binary Structured Data Format (BSDF).
7
+
8
+ BSDF is a binary format for serializing structured (scientific) data.
9
+ See http://bsdf.io for more information.
10
+
11
+ This is the reference implementation, which is relatively relatively
12
+ sophisticated, providing e.g. lazy loading of blobs and streamed
13
+ reading/writing. A simpler Python implementation is available as
14
+ ``bsdf_lite.py``.
15
+
16
+ This module has no dependencies and works on Python 2.7 and 3.4+.
17
+
18
+ Note: on Legacy Python (Python 2.7), non-Unicode strings are encoded as bytes.
19
+ """
20
+
21
+ # todo: in 2020, remove six stuff, __future__ and _isidentifier
22
+ # todo: in 2020, remove 'utf-8' args to encode/decode; it's faster
23
+
24
+ from __future__ import absolute_import, division, print_function
25
+
26
+ import bz2
27
+ import hashlib
28
+ import logging
29
+ import os
30
+ import re
31
+ import struct
32
+ import sys
33
+ import types
34
+ import zlib
35
+ from io import BytesIO
36
+
37
+ logger = logging.getLogger(__name__)
38
+
39
+ # Notes on versioning: the major and minor numbers correspond to the
40
+ # BSDF format version. The major number if increased when backward
41
+ # incompatible changes are introduced. An implementation must raise an
42
+ # exception when the file being read has a higher major version. The
43
+ # minor number is increased when new backward compatible features are
44
+ # introduced. An implementation must display a warning when the file
45
+ # being read has a higher minor version. The patch version is increased
46
+ # for subsequent releases of the implementation.
47
+ VERSION = 2, 1, 2
48
+ __version__ = ".".join(str(i) for i in VERSION)
49
+
50
+
51
+ # %% The encoder and decoder implementation
52
+
53
+ # From six.py
54
+ PY3 = sys.version_info[0] >= 3
55
+ if PY3:
56
+ text_type = str
57
+ string_types = str
58
+ unicode_types = str
59
+ integer_types = int
60
+ classtypes = type
61
+ else: # pragma: no cover
62
+ logging.basicConfig() # avoid "no handlers found" error
63
+ text_type = unicode # noqa
64
+ string_types = basestring # noqa
65
+ unicode_types = unicode # noqa
66
+ integer_types = (int, long) # noqa
67
+ classtypes = type, types.ClassType
68
+
69
+ # Shorthands
70
+ spack = struct.pack
71
+ strunpack = struct.unpack
72
+
73
+
74
+ def lencode(x):
75
+ """Encode an unsigned integer into a variable sized blob of bytes."""
76
+ # We could support 16 bit and 32 bit as well, but the gain is low, since
77
+ # 9 bytes for collections with over 250 elements is marginal anyway.
78
+ if x <= 250:
79
+ return spack("<B", x)
80
+ # elif x < 65536:
81
+ # return spack('<BH', 251, x)
82
+ # elif x < 4294967296:
83
+ # return spack('<BI', 252, x)
84
+ else:
85
+ return spack("<BQ", 253, x)
86
+
87
+
88
+ # Include len decoder for completeness; we've inlined it for performance.
89
+ def lendecode(f):
90
+ """Decode an unsigned integer from a file."""
91
+ n = strunpack("<B", f.read(1))[0]
92
+ if n == 253:
93
+ n = strunpack("<Q", f.read(8))[0] # noqa
94
+ return n
95
+
96
+
97
+ def encode_type_id(b, ext_id):
98
+ """Encode the type identifier, with or without extension id."""
99
+ if ext_id is not None:
100
+ bb = ext_id.encode("UTF-8")
101
+ return b.upper() + lencode(len(bb)) + bb # noqa
102
+ else:
103
+ return b # noqa
104
+
105
+
106
+ def _isidentifier(s): # pragma: no cover
107
+ """Use of str.isidentifier() for Legacy Python, but slower."""
108
+ # http://stackoverflow.com/questions/2544972/
109
+ return (
110
+ isinstance(s, string_types)
111
+ and re.match(r"^\w+$", s, re.UNICODE)
112
+ and re.match(r"^[0-9]", s) is None
113
+ )
114
+
115
+
116
+ class BsdfSerializer(object):
117
+ """Instances of this class represent a BSDF encoder/decoder.
118
+
119
+ It acts as a placeholder for a set of extensions and encoding/decoding
120
+ options. Use this to predefine extensions and options for high
121
+ performance encoding/decoding. For general use, see the functions
122
+ `save()`, `encode()`, `load()`, and `decode()`.
123
+
124
+ This implementation of BSDF supports streaming lists (keep adding
125
+ to a list after writing the main file), lazy loading of blobs, and
126
+ in-place editing of blobs (for streams opened with a+).
127
+
128
+ Options for encoding:
129
+
130
+ * compression (int or str): ``0`` or "no" for no compression (default),
131
+ ``1`` or "zlib" for Zlib compression (same as zip files and PNG), and
132
+ ``2`` or "bz2" for Bz2 compression (more compact but slower writing).
133
+ Note that some BSDF implementations (e.g. JavaScript) may not support
134
+ compression.
135
+ * use_checksum (bool): whether to include a checksum with binary blobs.
136
+ * float64 (bool): Whether to write floats as 64 bit (default) or 32 bit.
137
+
138
+ Options for decoding:
139
+
140
+ * load_streaming (bool): if True, and the final object in the structure was
141
+ a stream, will make it available as a stream in the decoded object.
142
+ * lazy_blob (bool): if True, bytes are represented as Blob objects that can
143
+ be used to lazily access the data, and also overwrite the data if the
144
+ file is open in a+ mode.
145
+ """
146
+
147
+ def __init__(self, extensions=None, **options):
148
+ self._extensions = {} # name -> extension
149
+ self._extensions_by_cls = {} # cls -> (name, extension.encode)
150
+ if extensions is None:
151
+ extensions = standard_extensions
152
+ for extension in extensions:
153
+ self.add_extension(extension)
154
+ self._parse_options(**options)
155
+
156
+ def _parse_options(
157
+ self,
158
+ compression=0,
159
+ use_checksum=False,
160
+ float64=True,
161
+ load_streaming=False,
162
+ lazy_blob=False,
163
+ ):
164
+ # Validate compression
165
+ if isinstance(compression, string_types):
166
+ m = {"no": 0, "zlib": 1, "bz2": 2}
167
+ compression = m.get(compression.lower(), compression)
168
+ if compression not in (0, 1, 2):
169
+ raise TypeError("Compression must be 0, 1, 2, " '"no", "zlib", or "bz2"')
170
+ self._compression = compression
171
+
172
+ # Other encoding args
173
+ self._use_checksum = bool(use_checksum)
174
+ self._float64 = bool(float64)
175
+
176
+ # Decoding args
177
+ self._load_streaming = bool(load_streaming)
178
+ self._lazy_blob = bool(lazy_blob)
179
+
180
+ def add_extension(self, extension_class):
181
+ """Add an extension to this serializer instance, which must be
182
+ a subclass of Extension. Can be used as a decorator.
183
+ """
184
+ # Check class
185
+ if not (
186
+ isinstance(extension_class, type) and issubclass(extension_class, Extension)
187
+ ):
188
+ raise TypeError("add_extension() expects a Extension class.")
189
+ extension = extension_class()
190
+
191
+ # Get name
192
+ name = extension.name
193
+ if not isinstance(name, str):
194
+ raise TypeError("Extension name must be str.")
195
+ if len(name) == 0 or len(name) > 250:
196
+ raise NameError(
197
+ "Extension names must be nonempty and shorter " "than 251 chars."
198
+ )
199
+ if name in self._extensions:
200
+ logger.warning(
201
+ 'BSDF warning: overwriting extension "%s", '
202
+ "consider removing first" % name
203
+ )
204
+
205
+ # Get classes
206
+ cls = extension.cls
207
+ if not cls:
208
+ clss = []
209
+ elif isinstance(cls, (tuple, list)):
210
+ clss = cls
211
+ else:
212
+ clss = [cls]
213
+ for cls in clss:
214
+ if not isinstance(cls, classtypes):
215
+ raise TypeError("Extension classes must be types.")
216
+
217
+ # Store
218
+ for cls in clss:
219
+ self._extensions_by_cls[cls] = name, extension.encode
220
+ self._extensions[name] = extension
221
+ return extension_class
222
+
223
+ def remove_extension(self, name):
224
+ """Remove a converted by its unique name."""
225
+ if not isinstance(name, str):
226
+ raise TypeError("Extension name must be str.")
227
+ if name in self._extensions:
228
+ self._extensions.pop(name)
229
+ for cls in list(self._extensions_by_cls.keys()):
230
+ if self._extensions_by_cls[cls][0] == name:
231
+ self._extensions_by_cls.pop(cls)
232
+
233
+ def _encode(self, f, value, streams, ext_id):
234
+ """Main encoder function."""
235
+ x = encode_type_id
236
+
237
+ if value is None:
238
+ f.write(x(b"v", ext_id)) # V for void
239
+ elif value is True:
240
+ f.write(x(b"y", ext_id)) # Y for yes
241
+ elif value is False:
242
+ f.write(x(b"n", ext_id)) # N for no
243
+ elif isinstance(value, integer_types):
244
+ if -32768 <= value <= 32767:
245
+ f.write(x(b"h", ext_id) + spack("h", value)) # H for ...
246
+ else:
247
+ f.write(x(b"i", ext_id) + spack("<q", value)) # I for int
248
+ elif isinstance(value, float):
249
+ if self._float64:
250
+ f.write(x(b"d", ext_id) + spack("<d", value)) # D for double
251
+ else:
252
+ f.write(x(b"f", ext_id) + spack("<f", value)) # f for float
253
+ elif isinstance(value, unicode_types):
254
+ bb = value.encode("UTF-8")
255
+ f.write(x(b"s", ext_id) + lencode(len(bb))) # S for str
256
+ f.write(bb)
257
+ elif isinstance(value, (list, tuple)):
258
+ f.write(x(b"l", ext_id) + lencode(len(value))) # L for list
259
+ for v in value:
260
+ self._encode(f, v, streams, None)
261
+ elif isinstance(value, dict):
262
+ f.write(x(b"m", ext_id) + lencode(len(value))) # M for mapping
263
+ for key, v in value.items():
264
+ if PY3:
265
+ assert key.isidentifier() # faster
266
+ else: # pragma: no cover
267
+ assert _isidentifier(key)
268
+ # yield ' ' * indent + key
269
+ name_b = key.encode("UTF-8")
270
+ f.write(lencode(len(name_b)))
271
+ f.write(name_b)
272
+ self._encode(f, v, streams, None)
273
+ elif isinstance(value, bytes):
274
+ f.write(x(b"b", ext_id)) # B for blob
275
+ blob = Blob(
276
+ value, compression=self._compression, use_checksum=self._use_checksum
277
+ )
278
+ blob._to_file(f) # noqa
279
+ elif isinstance(value, Blob):
280
+ f.write(x(b"b", ext_id)) # B for blob
281
+ value._to_file(f) # noqa
282
+ elif isinstance(value, BaseStream):
283
+ # Initialize the stream
284
+ if value.mode != "w":
285
+ raise ValueError("Cannot serialize a read-mode stream.")
286
+ elif isinstance(value, ListStream):
287
+ f.write(x(b"l", ext_id) + spack("<BQ", 255, 0)) # L for list
288
+ else:
289
+ raise TypeError("Only ListStream is supported")
290
+ # Mark this as *the* stream, and activate the stream.
291
+ # The save() function verifies this is the last written object.
292
+ if len(streams) > 0:
293
+ raise ValueError("Can only have one stream per file.")
294
+ streams.append(value)
295
+ value._activate(f, self._encode, self._decode) # noqa
296
+ else:
297
+ if ext_id is not None:
298
+ raise ValueError(
299
+ "Extension %s wronfully encodes object to another "
300
+ "extension object (though it may encode to a list/dict "
301
+ "that contains other extension objects)." % ext_id
302
+ )
303
+ # Try if the value is of a type we know
304
+ ex = self._extensions_by_cls.get(value.__class__, None)
305
+ # Maybe its a subclass of a type we know
306
+ if ex is None:
307
+ for name, c in self._extensions.items():
308
+ if c.match(self, value):
309
+ ex = name, c.encode
310
+ break
311
+ else:
312
+ ex = None
313
+ # Success or fail
314
+ if ex is not None:
315
+ ext_id2, extension_encode = ex
316
+ self._encode(f, extension_encode(self, value), streams, ext_id2)
317
+ else:
318
+ t = (
319
+ "Class %r is not a valid base BSDF type, nor is it "
320
+ "handled by an extension."
321
+ )
322
+ raise TypeError(t % value.__class__.__name__)
323
+
324
+ def _decode(self, f):
325
+ """Main decoder function."""
326
+
327
+ # Get value
328
+ char = f.read(1)
329
+ c = char.lower()
330
+
331
+ # Conversion (uppercase value identifiers signify converted values)
332
+ if not char:
333
+ raise EOFError()
334
+ elif char != c:
335
+ n = strunpack("<B", f.read(1))[0]
336
+ # if n == 253: n = strunpack('<Q', f.read(8))[0] # noqa - noneed
337
+ ext_id = f.read(n).decode("UTF-8")
338
+ else:
339
+ ext_id = None
340
+
341
+ if c == b"v":
342
+ value = None
343
+ elif c == b"y":
344
+ value = True
345
+ elif c == b"n":
346
+ value = False
347
+ elif c == b"h":
348
+ value = strunpack("<h", f.read(2))[0]
349
+ elif c == b"i":
350
+ value = strunpack("<q", f.read(8))[0]
351
+ elif c == b"f":
352
+ value = strunpack("<f", f.read(4))[0]
353
+ elif c == b"d":
354
+ value = strunpack("<d", f.read(8))[0]
355
+ elif c == b"s":
356
+ n_s = strunpack("<B", f.read(1))[0]
357
+ if n_s == 253:
358
+ n_s = strunpack("<Q", f.read(8))[0] # noqa
359
+ value = f.read(n_s).decode("UTF-8")
360
+ elif c == b"l":
361
+ n = strunpack("<B", f.read(1))[0]
362
+ if n >= 254:
363
+ # Streaming
364
+ closed = n == 254
365
+ n = strunpack("<Q", f.read(8))[0]
366
+ if self._load_streaming:
367
+ value = ListStream(n if closed else "r")
368
+ value._activate(f, self._encode, self._decode) # noqa
369
+ elif closed:
370
+ value = [self._decode(f) for i in range(n)]
371
+ else:
372
+ value = []
373
+ try:
374
+ while True:
375
+ value.append(self._decode(f))
376
+ except EOFError:
377
+ pass
378
+ else:
379
+ # Normal
380
+ if n == 253:
381
+ n = strunpack("<Q", f.read(8))[0] # noqa
382
+ value = [self._decode(f) for i in range(n)]
383
+ elif c == b"m":
384
+ value = dict()
385
+ n = strunpack("<B", f.read(1))[0]
386
+ if n == 253:
387
+ n = strunpack("<Q", f.read(8))[0] # noqa
388
+ for i in range(n):
389
+ n_name = strunpack("<B", f.read(1))[0]
390
+ if n_name == 253:
391
+ n_name = strunpack("<Q", f.read(8))[0] # noqa
392
+ assert n_name > 0
393
+ name = f.read(n_name).decode("UTF-8")
394
+ value[name] = self._decode(f)
395
+ elif c == b"b":
396
+ if self._lazy_blob:
397
+ value = Blob((f, True))
398
+ else:
399
+ blob = Blob((f, False))
400
+ value = blob.get_bytes()
401
+ else:
402
+ raise RuntimeError("Parse error %r" % char)
403
+
404
+ # Convert value if we have an extension for it
405
+ if ext_id is not None:
406
+ extension = self._extensions.get(ext_id, None)
407
+ if extension is not None:
408
+ value = extension.decode(self, value)
409
+ else:
410
+ logger.warning("BSDF warning: no extension found for %r" % ext_id)
411
+
412
+ return value
413
+
414
+ def encode(self, ob):
415
+ """Save the given object to bytes."""
416
+ f = BytesIO()
417
+ self.save(f, ob)
418
+ return f.getvalue()
419
+
420
+ def save(self, f, ob):
421
+ """Write the given object to the given file object."""
422
+ f.write(b"BSDF")
423
+ f.write(struct.pack("<B", VERSION[0]))
424
+ f.write(struct.pack("<B", VERSION[1]))
425
+
426
+ # Prepare streaming, this list will have 0 or 1 item at the end
427
+ streams = []
428
+
429
+ self._encode(f, ob, streams, None)
430
+
431
+ # Verify that stream object was at the end, and add initial elements
432
+ if len(streams) > 0:
433
+ stream = streams[0]
434
+ if stream._start_pos != f.tell():
435
+ raise ValueError(
436
+ "The stream object must be " "the last object to be encoded."
437
+ )
438
+
439
+ def decode(self, bb):
440
+ """Load the data structure that is BSDF-encoded in the given bytes."""
441
+ f = BytesIO(bb)
442
+ return self.load(f)
443
+
444
+ def load(self, f):
445
+ """Load a BSDF-encoded object from the given file object."""
446
+ # Check magic string
447
+ f4 = f.read(4)
448
+ if f4 != b"BSDF":
449
+ raise RuntimeError("This does not look like a BSDF file: %r" % f4)
450
+ # Check version
451
+ major_version = strunpack("<B", f.read(1))[0]
452
+ minor_version = strunpack("<B", f.read(1))[0]
453
+ file_version = "%i.%i" % (major_version, minor_version)
454
+ if major_version != VERSION[0]: # major version should be 2
455
+ t = (
456
+ "Reading file with different major version (%s) "
457
+ "from the implementation (%s)."
458
+ )
459
+ raise RuntimeError(t % (__version__, file_version))
460
+ if minor_version > VERSION[1]: # minor should be < ours
461
+ t = (
462
+ "BSDF warning: reading file with higher minor version (%s) "
463
+ "than the implementation (%s)."
464
+ )
465
+ logger.warning(t % (__version__, file_version))
466
+
467
+ return self._decode(f)
468
+
469
+
470
+ # %% Streaming and blob-files
471
+
472
+
473
+ class BaseStream(object):
474
+ """Base class for streams."""
475
+
476
+ def __init__(self, mode="w"):
477
+ self._i = 0
478
+ self._count = -1
479
+ if isinstance(mode, int):
480
+ self._count = mode
481
+ mode = "r"
482
+ elif mode == "w":
483
+ self._count = 0
484
+ assert mode in ("r", "w")
485
+ self._mode = mode
486
+ self._f = None
487
+ self._start_pos = 0
488
+
489
+ def _activate(self, file, encode_func, decode_func):
490
+ if self._f is not None: # Associated with another write
491
+ raise IOError("Stream object cannot be activated twice?")
492
+ self._f = file
493
+ self._start_pos = self._f.tell()
494
+ self._encode = encode_func
495
+ self._decode = decode_func
496
+
497
+ @property
498
+ def mode(self):
499
+ """The mode of this stream: 'r' or 'w'."""
500
+ return self._mode
501
+
502
+
503
+ class ListStream(BaseStream):
504
+ """A streamable list object used for writing or reading.
505
+ In read mode, it can also be iterated over.
506
+ """
507
+
508
+ @property
509
+ def count(self):
510
+ """The number of elements in the stream (can be -1 for unclosed
511
+ streams in read-mode).
512
+ """
513
+ return self._count
514
+
515
+ @property
516
+ def index(self):
517
+ """The current index of the element to read/write."""
518
+ return self._i
519
+
520
+ def append(self, item):
521
+ """Append an item to the streaming list. The object is immediately
522
+ serialized and written to the underlying file.
523
+ """
524
+ # if self._mode != 'w':
525
+ # raise IOError('This ListStream is not in write mode.')
526
+ if self._count != self._i:
527
+ raise IOError("Can only append items to the end of the stream.")
528
+ if self._f is None:
529
+ raise IOError("List stream is not associated with a file yet.")
530
+ if self._f.closed:
531
+ raise IOError("Cannot stream to a close file.")
532
+ self._encode(self._f, item, [self], None)
533
+ self._i += 1
534
+ self._count += 1
535
+
536
+ def close(self, unstream=False):
537
+ """Close the stream, marking the number of written elements. New
538
+ elements may still be appended, but they won't be read during decoding.
539
+ If ``unstream`` is False, the stream is turned into a regular list
540
+ (not streaming).
541
+ """
542
+ # if self._mode != 'w':
543
+ # raise IOError('This ListStream is not in write mode.')
544
+ if self._count != self._i:
545
+ raise IOError("Can only close when at the end of the stream.")
546
+ if self._f is None:
547
+ raise IOError("ListStream is not associated with a file yet.")
548
+ if self._f.closed:
549
+ raise IOError("Cannot close a stream on a close file.")
550
+ i = self._f.tell()
551
+ self._f.seek(self._start_pos - 8 - 1)
552
+ self._f.write(spack("<B", 253 if unstream else 254))
553
+ self._f.write(spack("<Q", self._count))
554
+ self._f.seek(i)
555
+
556
+ def next(self):
557
+ """Read and return the next element in the streaming list.
558
+ Raises StopIteration if the stream is exhausted.
559
+ """
560
+ if self._mode != "r":
561
+ raise IOError("This ListStream in not in read mode.")
562
+ if self._f is None:
563
+ raise IOError("ListStream is not associated with a file yet.")
564
+ if getattr(self._f, "closed", None): # not present on 2.7 http req :/
565
+ raise IOError("Cannot read a stream from a close file.")
566
+ if self._count >= 0:
567
+ if self._i >= self._count:
568
+ raise StopIteration()
569
+ self._i += 1
570
+ return self._decode(self._f)
571
+ else:
572
+ # This raises EOFError at some point.
573
+ try:
574
+ res = self._decode(self._f)
575
+ self._i += 1
576
+ return res
577
+ except EOFError:
578
+ self._count = self._i
579
+ raise StopIteration()
580
+
581
+ def __iter__(self):
582
+ if self._mode != "r":
583
+ raise IOError("Cannot iterate: ListStream in not in read mode.")
584
+ return self
585
+
586
+ def __next__(self):
587
+ return self.next()
588
+
589
+
590
+ class Blob(object):
591
+ """Object to represent a blob of bytes. When used to write a BSDF file,
592
+ it's a wrapper for bytes plus properties such as what compression to apply.
593
+ When used to read a BSDF file, it can be used to read the data lazily, and
594
+ also modify the data if reading in 'r+' mode and the blob isn't compressed.
595
+ """
596
+
597
+ # For now, this does not allow re-sizing blobs (within the allocated size)
598
+ # but this can be added later.
599
+
600
+ def __init__(self, bb, compression=0, extra_size=0, use_checksum=False):
601
+ if isinstance(bb, bytes):
602
+ self._f = None
603
+ self.compressed = self._from_bytes(bb, compression)
604
+ self.compression = compression
605
+ self.allocated_size = self.used_size + extra_size
606
+ self.use_checksum = use_checksum
607
+ elif isinstance(bb, tuple) and len(bb) == 2 and hasattr(bb[0], "read"):
608
+ self._f, allow_seek = bb
609
+ self.compressed = None
610
+ self._from_file(self._f, allow_seek)
611
+ self._modified = False
612
+ else:
613
+ raise TypeError("Wrong argument to create Blob.")
614
+
615
+ def _from_bytes(self, value, compression):
616
+ """When used to wrap bytes in a blob."""
617
+ if compression == 0:
618
+ compressed = value
619
+ elif compression == 1:
620
+ compressed = zlib.compress(value, 9)
621
+ elif compression == 2:
622
+ compressed = bz2.compress(value, 9)
623
+ else: # pragma: no cover
624
+ assert False, "Unknown compression identifier"
625
+
626
+ self.data_size = len(value)
627
+ self.used_size = len(compressed)
628
+ return compressed
629
+
630
+ def _to_file(self, f):
631
+ """Private friend method called by encoder to write a blob to a file."""
632
+ # Write sizes - write at least in a size that allows resizing
633
+ if self.allocated_size <= 250 and self.compression == 0:
634
+ f.write(spack("<B", self.allocated_size))
635
+ f.write(spack("<B", self.used_size))
636
+ f.write(lencode(self.data_size))
637
+ else:
638
+ f.write(spack("<BQ", 253, self.allocated_size))
639
+ f.write(spack("<BQ", 253, self.used_size))
640
+ f.write(spack("<BQ", 253, self.data_size))
641
+ # Compression and checksum
642
+ f.write(spack("B", self.compression))
643
+ if self.use_checksum:
644
+ f.write(b"\xff" + hashlib.md5(self.compressed).digest())
645
+ else:
646
+ f.write(b"\x00")
647
+ # Byte alignment (only necessary for uncompressed data)
648
+ if self.compression == 0:
649
+ alignment = 8 - (f.tell() + 1) % 8 # +1 for the byte to write
650
+ f.write(spack("<B", alignment)) # padding for byte alignment
651
+ f.write(b"\x00" * alignment)
652
+ else:
653
+ f.write(spack("<B", 0))
654
+ # The actual data and extra space
655
+ f.write(self.compressed)
656
+ f.write(b"\x00" * (self.allocated_size - self.used_size))
657
+
658
+ def _from_file(self, f, allow_seek):
659
+ """Used when a blob is read by the decoder."""
660
+ # Read blob header data (5 to 42 bytes)
661
+ # Size
662
+ allocated_size = strunpack("<B", f.read(1))[0]
663
+ if allocated_size == 253:
664
+ allocated_size = strunpack("<Q", f.read(8))[0] # noqa
665
+ used_size = strunpack("<B", f.read(1))[0]
666
+ if used_size == 253:
667
+ used_size = strunpack("<Q", f.read(8))[0] # noqa
668
+ data_size = strunpack("<B", f.read(1))[0]
669
+ if data_size == 253:
670
+ data_size = strunpack("<Q", f.read(8))[0] # noqa
671
+ # Compression and checksum
672
+ compression = strunpack("<B", f.read(1))[0]
673
+ has_checksum = strunpack("<B", f.read(1))[0]
674
+ if has_checksum:
675
+ checksum = f.read(16)
676
+ # Skip alignment
677
+ alignment = strunpack("<B", f.read(1))[0]
678
+ f.read(alignment)
679
+ # Get or skip data + extra space
680
+ if allow_seek:
681
+ self.start_pos = f.tell()
682
+ self.end_pos = self.start_pos + used_size
683
+ f.seek(self.start_pos + allocated_size)
684
+ else:
685
+ self.start_pos = None
686
+ self.end_pos = None
687
+ self.compressed = f.read(used_size)
688
+ f.read(allocated_size - used_size)
689
+ # Store info
690
+ self.alignment = alignment
691
+ self.compression = compression
692
+ self.use_checksum = checksum if has_checksum else None
693
+ self.used_size = used_size
694
+ self.allocated_size = allocated_size
695
+ self.data_size = data_size
696
+
697
+ def seek(self, p):
698
+ """Seek to the given position (relative to the blob start)."""
699
+ if self._f is None:
700
+ raise RuntimeError(
701
+ "Cannot seek in a blob " "that is not created by the BSDF decoder."
702
+ )
703
+ if p < 0:
704
+ p = self.allocated_size + p
705
+ if p < 0 or p > self.allocated_size:
706
+ raise IOError("Seek beyond blob boundaries.")
707
+ self._f.seek(self.start_pos + p)
708
+
709
+ def tell(self):
710
+ """Get the current file pointer position (relative to the blob start)."""
711
+ if self._f is None:
712
+ raise RuntimeError(
713
+ "Cannot tell in a blob " "that is not created by the BSDF decoder."
714
+ )
715
+ return self._f.tell() - self.start_pos
716
+
717
+ def write(self, bb):
718
+ """Write bytes to the blob."""
719
+ if self._f is None:
720
+ raise RuntimeError(
721
+ "Cannot write in a blob " "that is not created by the BSDF decoder."
722
+ )
723
+ if self.compression:
724
+ raise IOError("Cannot arbitrarily write in compressed blob.")
725
+ if self._f.tell() + len(bb) > self.end_pos:
726
+ raise IOError("Write beyond blob boundaries.")
727
+ self._modified = True
728
+ return self._f.write(bb)
729
+
730
+ def read(self, n):
731
+ """Read n bytes from the blob."""
732
+ if self._f is None:
733
+ raise RuntimeError(
734
+ "Cannot read in a blob " "that is not created by the BSDF decoder."
735
+ )
736
+ if self.compression:
737
+ raise IOError("Cannot arbitrarily read in compressed blob.")
738
+ if self._f.tell() + n > self.end_pos:
739
+ raise IOError("Read beyond blob boundaries.")
740
+ return self._f.read(n)
741
+
742
+ def get_bytes(self):
743
+ """Get the contents of the blob as bytes."""
744
+ if self.compressed is not None:
745
+ compressed = self.compressed
746
+ else:
747
+ i = self._f.tell()
748
+ self.seek(0)
749
+ compressed = self._f.read(self.used_size)
750
+ self._f.seek(i)
751
+ if self.compression == 0:
752
+ value = compressed
753
+ elif self.compression == 1:
754
+ value = zlib.decompress(compressed)
755
+ elif self.compression == 2:
756
+ value = bz2.decompress(compressed)
757
+ else: # pragma: no cover
758
+ raise RuntimeError("Invalid compression %i" % self.compression)
759
+ return value
760
+
761
+ def update_checksum(self):
762
+ """Reset the blob's checksum if present. Call this after modifying
763
+ the data.
764
+ """
765
+ # or ... should the presence of a checksum mean that data is proteced?
766
+ if self.use_checksum and self._modified:
767
+ self.seek(0)
768
+ compressed = self._f.read(self.used_size)
769
+ self._f.seek(self.start_pos - self.alignment - 1 - 16)
770
+ self._f.write(hashlib.md5(compressed).digest())
771
+
772
+
773
+ # %% High-level functions
774
+
775
+
776
+ def encode(ob, extensions=None, **options):
777
+ """Save (BSDF-encode) the given object to bytes.
778
+ See `BSDFSerializer` for details on extensions and options.
779
+ """
780
+ s = BsdfSerializer(extensions, **options)
781
+ return s.encode(ob)
782
+
783
+
784
+ def save(f, ob, extensions=None, **options):
785
+ """Save (BSDF-encode) the given object to the given filename or
786
+ file object. See` BSDFSerializer` for details on extensions and options.
787
+ """
788
+ s = BsdfSerializer(extensions, **options)
789
+ if isinstance(f, string_types):
790
+ with open(f, "wb") as fp:
791
+ return s.save(fp, ob)
792
+ else:
793
+ return s.save(f, ob)
794
+
795
+
796
+ def decode(bb, extensions=None, **options):
797
+ """Load a (BSDF-encoded) structure from bytes.
798
+ See `BSDFSerializer` for details on extensions and options.
799
+ """
800
+ s = BsdfSerializer(extensions, **options)
801
+ return s.decode(bb)
802
+
803
+
804
+ def load(f, extensions=None, **options):
805
+ """Load a (BSDF-encoded) structure from the given filename or file object.
806
+ See `BSDFSerializer` for details on extensions and options.
807
+ """
808
+ s = BsdfSerializer(extensions, **options)
809
+ if isinstance(f, string_types):
810
+ if f.startswith(("~/", "~\\")): # pragma: no cover
811
+ f = os.path.expanduser(f)
812
+ with open(f, "rb") as fp:
813
+ return s.load(fp)
814
+ else:
815
+ return s.load(f)
816
+
817
+
818
+ # Aliases for json compat
819
+ loads = decode
820
+ dumps = encode
821
+
822
+
823
+ # %% Standard extensions
824
+
825
+ # Defining extensions as a dict would be more compact and feel lighter, but
826
+ # that would only allow lambdas, which is too limiting, e.g. for ndarray
827
+ # extension.
828
+
829
+
830
+ class Extension(object):
831
+ """Base class to implement BSDF extensions for special data types.
832
+
833
+ Extension classes are provided to the BSDF serializer, which
834
+ instantiates the class. That way, the extension can be somewhat dynamic:
835
+ e.g. the NDArrayExtension exposes the ndarray class only when numpy
836
+ is imported.
837
+
838
+ A extension instance must have two attributes. These can be attributes of
839
+ the class, or of the instance set in ``__init__()``:
840
+
841
+ * name (str): the name by which encoded values will be identified.
842
+ * cls (type): the type (or list of types) to match values with.
843
+ This is optional, but it makes the encoder select extensions faster.
844
+
845
+ Further, it needs 3 methods:
846
+
847
+ * `match(serializer, value) -> bool`: return whether the extension can
848
+ convert the given value. The default is ``isinstance(value, self.cls)``.
849
+ * `encode(serializer, value) -> encoded_value`: the function to encode a
850
+ value to more basic data types.
851
+ * `decode(serializer, encoded_value) -> value`: the function to decode an
852
+ encoded value back to its intended representation.
853
+
854
+ """
855
+
856
+ name = ""
857
+ cls = ()
858
+
859
+ def __repr__(self):
860
+ return "<BSDF extension %r at 0x%s>" % (self.name, hex(id(self)))
861
+
862
+ def match(self, s, v):
863
+ return isinstance(v, self.cls)
864
+
865
+ def encode(self, s, v):
866
+ raise NotImplementedError()
867
+
868
+ def decode(self, s, v):
869
+ raise NotImplementedError()
870
+
871
+
872
+ class ComplexExtension(Extension):
873
+ name = "c"
874
+ cls = complex
875
+
876
+ def encode(self, s, v):
877
+ return (v.real, v.imag)
878
+
879
+ def decode(self, s, v):
880
+ return complex(v[0], v[1])
881
+
882
+
883
+ class NDArrayExtension(Extension):
884
+ name = "ndarray"
885
+
886
+ def __init__(self):
887
+ if "numpy" in sys.modules:
888
+ import numpy as np
889
+
890
+ self.cls = np.ndarray
891
+
892
+ def match(self, s, v): # pragma: no cover - e.g. work for nd arrays in JS
893
+ return hasattr(v, "shape") and hasattr(v, "dtype") and hasattr(v, "tobytes")
894
+
895
+ def encode(self, s, v):
896
+ return dict(shape=v.shape, dtype=text_type(v.dtype), data=v.tobytes())
897
+
898
+ def decode(self, s, v):
899
+ try:
900
+ import numpy as np
901
+ except ImportError: # pragma: no cover
902
+ return v
903
+ a = np.frombuffer(v["data"], dtype=v["dtype"])
904
+ a.shape = v["shape"]
905
+ return a
906
+
907
+
908
+ standard_extensions = [ComplexExtension, NDArrayExtension]
909
+
910
+
911
+ if __name__ == "__main__":
912
+ # Invoke CLI
913
+ import bsdf_cli
914
+
915
+ bsdf_cli.main()
minigpt2/lib/python3.10/site-packages/imageio/plugins/_dicom.py ADDED
@@ -0,0 +1,932 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # imageio is distributed under the terms of the (new) BSD License.
3
+
4
+ """ Plugin for reading DICOM files.
5
+ """
6
+
7
+ # todo: Use pydicom:
8
+ # * Note: is not py3k ready yet
9
+ # * Allow reading the full meta info
10
+ # I think we can more or less replace the SimpleDicomReader with a
11
+ # pydicom.Dataset For series, only ned to read the full info from one
12
+ # file: speed still high
13
+ # * Perhaps allow writing?
14
+
15
+ import sys
16
+ import os
17
+ import struct
18
+ import logging
19
+
20
+ import numpy as np
21
+
22
+
23
+ logger = logging.getLogger(__name__)
24
+
25
+ # Determine endianity of system
26
+ sys_is_little_endian = sys.byteorder == "little"
27
+
28
+ # Define a dictionary that contains the tags that we would like to know
29
+ MINIDICT = {
30
+ (0x7FE0, 0x0010): ("PixelData", "OB"),
31
+ # Date and time
32
+ (0x0008, 0x0020): ("StudyDate", "DA"),
33
+ (0x0008, 0x0021): ("SeriesDate", "DA"),
34
+ (0x0008, 0x0022): ("AcquisitionDate", "DA"),
35
+ (0x0008, 0x0023): ("ContentDate", "DA"),
36
+ (0x0008, 0x0030): ("StudyTime", "TM"),
37
+ (0x0008, 0x0031): ("SeriesTime", "TM"),
38
+ (0x0008, 0x0032): ("AcquisitionTime", "TM"),
39
+ (0x0008, 0x0033): ("ContentTime", "TM"),
40
+ # With what, where, by whom?
41
+ (0x0008, 0x0060): ("Modality", "CS"),
42
+ (0x0008, 0x0070): ("Manufacturer", "LO"),
43
+ (0x0008, 0x0080): ("InstitutionName", "LO"),
44
+ # Descriptions
45
+ (0x0008, 0x1030): ("StudyDescription", "LO"),
46
+ (0x0008, 0x103E): ("SeriesDescription", "LO"),
47
+ # UID's
48
+ (0x0008, 0x0016): ("SOPClassUID", "UI"),
49
+ (0x0008, 0x0018): ("SOPInstanceUID", "UI"),
50
+ (0x0020, 0x000D): ("StudyInstanceUID", "UI"),
51
+ (0x0020, 0x000E): ("SeriesInstanceUID", "UI"),
52
+ (0x0008, 0x0117): ("ContextUID", "UI"),
53
+ # Numbers
54
+ (0x0020, 0x0011): ("SeriesNumber", "IS"),
55
+ (0x0020, 0x0012): ("AcquisitionNumber", "IS"),
56
+ (0x0020, 0x0013): ("InstanceNumber", "IS"),
57
+ (0x0020, 0x0014): ("IsotopeNumber", "IS"),
58
+ (0x0020, 0x0015): ("PhaseNumber", "IS"),
59
+ (0x0020, 0x0016): ("IntervalNumber", "IS"),
60
+ (0x0020, 0x0017): ("TimeSlotNumber", "IS"),
61
+ (0x0020, 0x0018): ("AngleNumber", "IS"),
62
+ (0x0020, 0x0019): ("ItemNumber", "IS"),
63
+ (0x0020, 0x0020): ("PatientOrientation", "CS"),
64
+ (0x0020, 0x0030): ("ImagePosition", "CS"),
65
+ (0x0020, 0x0032): ("ImagePositionPatient", "CS"),
66
+ (0x0020, 0x0035): ("ImageOrientation", "CS"),
67
+ (0x0020, 0x0037): ("ImageOrientationPatient", "CS"),
68
+ # Patient information
69
+ (0x0010, 0x0010): ("PatientName", "PN"),
70
+ (0x0010, 0x0020): ("PatientID", "LO"),
71
+ (0x0010, 0x0030): ("PatientBirthDate", "DA"),
72
+ (0x0010, 0x0040): ("PatientSex", "CS"),
73
+ (0x0010, 0x1010): ("PatientAge", "AS"),
74
+ (0x0010, 0x1020): ("PatientSize", "DS"),
75
+ (0x0010, 0x1030): ("PatientWeight", "DS"),
76
+ # Image specific (required to construct numpy array)
77
+ (0x0028, 0x0002): ("SamplesPerPixel", "US"),
78
+ (0x0028, 0x0008): ("NumberOfFrames", "IS"),
79
+ (0x0028, 0x0100): ("BitsAllocated", "US"),
80
+ (0x0028, 0x0101): ("BitsStored", "US"),
81
+ (0x0028, 0x0102): ("HighBit", "US"),
82
+ (0x0028, 0x0103): ("PixelRepresentation", "US"),
83
+ (0x0028, 0x0010): ("Rows", "US"),
84
+ (0x0028, 0x0011): ("Columns", "US"),
85
+ (0x0028, 0x1052): ("RescaleIntercept", "DS"),
86
+ (0x0028, 0x1053): ("RescaleSlope", "DS"),
87
+ # Image specific (for the user)
88
+ (0x0028, 0x0030): ("PixelSpacing", "DS"),
89
+ (0x0018, 0x0088): ("SliceSpacing", "DS"),
90
+ }
91
+
92
+ # Define some special tags:
93
+ # See PS 3.5-2008 section 7.5 (p.40)
94
+ ItemTag = (0xFFFE, 0xE000) # start of Sequence Item
95
+ ItemDelimiterTag = (0xFFFE, 0xE00D) # end of Sequence Item
96
+ SequenceDelimiterTag = (0xFFFE, 0xE0DD) # end of Sequence of undefined length
97
+
98
+ # Define set of groups that we're interested in (so we can quickly skip others)
99
+ GROUPS = set([key[0] for key in MINIDICT.keys()])
100
+ VRS = set([val[1] for val in MINIDICT.values()])
101
+
102
+
103
+ class NotADicomFile(Exception):
104
+ pass
105
+
106
+
107
+ class CompressedDicom(RuntimeError):
108
+ pass
109
+
110
+
111
+ class SimpleDicomReader(object):
112
+ """
113
+ This class provides reading of pixel data from DICOM files. It is
114
+ focussed on getting the pixel data, not the meta info.
115
+
116
+ To use, first create an instance of this class (giving it
117
+ a file object or filename). Next use the info attribute to
118
+ get a dict of the meta data. The loading of pixel data is
119
+ deferred until get_numpy_array() is called.
120
+
121
+ Comparison with Pydicom
122
+ -----------------------
123
+
124
+ This code focusses on getting the pixel data out, which allows some
125
+ shortcuts, resulting in the code being much smaller.
126
+
127
+ Since the processing of data elements is much cheaper (it skips a lot
128
+ of tags), this code is about 3x faster than pydicom (except for the
129
+ deflated DICOM files).
130
+
131
+ This class does borrow some code (and ideas) from the pydicom
132
+ project, and (to the best of our knowledge) has the same limitations
133
+ as pydicom with regard to the type of files that it can handle.
134
+
135
+ Limitations
136
+ -----------
137
+
138
+ For more advanced DICOM processing, please check out pydicom.
139
+
140
+ * Only a predefined subset of data elements (meta information) is read.
141
+ * This is a reader; it can not write DICOM files.
142
+ * (just like pydicom) it can handle none of the compressed DICOM
143
+ formats except for "Deflated Explicit VR Little Endian"
144
+ (1.2.840.10008.1.2.1.99).
145
+
146
+ """
147
+
148
+ def __init__(self, file):
149
+ # Open file if filename given
150
+ if isinstance(file, str):
151
+ self._filename = file
152
+ self._file = open(file, "rb")
153
+ else:
154
+ self._filename = "<unknown file>"
155
+ self._file = file
156
+ # Init variable to store position and size of pixel data
157
+ self._pixel_data_loc = None
158
+ # The meta header is always explicit and little endian
159
+ self.is_implicit_VR = False
160
+ self.is_little_endian = True
161
+ self._unpackPrefix = "<"
162
+ # Dict to store data elements of interest in
163
+ self._info = {}
164
+ # VR Conversion
165
+ self._converters = {
166
+ # Numbers
167
+ "US": lambda x: self._unpack("H", x),
168
+ "UL": lambda x: self._unpack("L", x),
169
+ # Numbers encoded as strings
170
+ "DS": lambda x: self._splitValues(x, float, "\\"),
171
+ "IS": lambda x: self._splitValues(x, int, "\\"),
172
+ # strings
173
+ "AS": lambda x: x.decode("ascii", "ignore").strip("\x00"),
174
+ "DA": lambda x: x.decode("ascii", "ignore").strip("\x00"),
175
+ "TM": lambda x: x.decode("ascii", "ignore").strip("\x00"),
176
+ "UI": lambda x: x.decode("ascii", "ignore").strip("\x00"),
177
+ "LO": lambda x: x.decode("utf-8", "ignore").strip("\x00").rstrip(),
178
+ "CS": lambda x: self._splitValues(x, float, "\\"),
179
+ "PN": lambda x: x.decode("utf-8", "ignore").strip("\x00").rstrip(),
180
+ }
181
+
182
+ # Initiate reading
183
+ self._read()
184
+
185
+ @property
186
+ def info(self):
187
+ return self._info
188
+
189
+ def _splitValues(self, x, type, splitter):
190
+ s = x.decode("ascii").strip("\x00")
191
+ try:
192
+ if splitter in s:
193
+ return tuple([type(v) for v in s.split(splitter) if v.strip()])
194
+ else:
195
+ return type(s)
196
+ except ValueError:
197
+ return s
198
+
199
+ def _unpack(self, fmt, value):
200
+ return struct.unpack(self._unpackPrefix + fmt, value)[0]
201
+
202
+ # Really only so we need minimal changes to _pixel_data_numpy
203
+ def __iter__(self):
204
+ return iter(self._info.keys())
205
+
206
+ def __getattr__(self, key):
207
+ info = object.__getattribute__(self, "_info")
208
+ if key in info:
209
+ return info[key]
210
+ return object.__getattribute__(self, key) # pragma: no cover
211
+
212
+ def _read(self):
213
+ f = self._file
214
+ # Check prefix after peamble
215
+ f.seek(128)
216
+ if f.read(4) != b"DICM":
217
+ raise NotADicomFile("Not a valid DICOM file.")
218
+ # Read
219
+ self._read_header()
220
+ self._read_data_elements()
221
+ self._get_shape_and_sampling()
222
+ # Close if done, reopen if necessary to read pixel data
223
+ if os.path.isfile(self._filename):
224
+ self._file.close()
225
+ self._file = None
226
+
227
+ def _readDataElement(self):
228
+ f = self._file
229
+ # Get group and element
230
+ group = self._unpack("H", f.read(2))
231
+ element = self._unpack("H", f.read(2))
232
+ # Get value length
233
+ if self.is_implicit_VR:
234
+ vl = self._unpack("I", f.read(4))
235
+ else:
236
+ vr = f.read(2)
237
+ if vr in (b"OB", b"OW", b"SQ", b"UN"):
238
+ reserved = f.read(2) # noqa
239
+ vl = self._unpack("I", f.read(4))
240
+ else:
241
+ vl = self._unpack("H", f.read(2))
242
+ # Get value
243
+ if group == 0x7FE0 and element == 0x0010:
244
+ here = f.tell()
245
+ self._pixel_data_loc = here, vl
246
+ f.seek(here + vl)
247
+ return group, element, b"Deferred loading of pixel data"
248
+ else:
249
+ if vl == 0xFFFFFFFF:
250
+ value = self._read_undefined_length_value()
251
+ else:
252
+ value = f.read(vl)
253
+ return group, element, value
254
+
255
+ def _read_undefined_length_value(self, read_size=128):
256
+ """Copied (in compacted form) from PyDicom
257
+ Copyright Darcy Mason.
258
+ """
259
+ fp = self._file
260
+ # data_start = fp.tell()
261
+ search_rewind = 3
262
+ bytes_to_find = struct.pack(
263
+ self._unpackPrefix + "HH", SequenceDelimiterTag[0], SequenceDelimiterTag[1]
264
+ )
265
+
266
+ found = False
267
+ value_chunks = []
268
+ while not found:
269
+ chunk_start = fp.tell()
270
+ bytes_read = fp.read(read_size)
271
+ if len(bytes_read) < read_size:
272
+ # try again,
273
+ # if still don't get required amount, this is last block
274
+ new_bytes = fp.read(read_size - len(bytes_read))
275
+ bytes_read += new_bytes
276
+ if len(bytes_read) < read_size:
277
+ raise EOFError(
278
+ "End of file reached before sequence " "delimiter found."
279
+ )
280
+ index = bytes_read.find(bytes_to_find)
281
+ if index != -1:
282
+ found = True
283
+ value_chunks.append(bytes_read[:index])
284
+ fp.seek(chunk_start + index + 4) # rewind to end of delimiter
285
+ length = fp.read(4)
286
+ if length != b"\0\0\0\0":
287
+ logger.warning(
288
+ "Expected 4 zero bytes after undefined length " "delimiter"
289
+ )
290
+ else:
291
+ fp.seek(fp.tell() - search_rewind) # rewind a bit
292
+ # accumulate the bytes read (not including the rewind)
293
+ value_chunks.append(bytes_read[:-search_rewind])
294
+
295
+ # if get here then have found the byte string
296
+ return b"".join(value_chunks)
297
+
298
+ def _read_header(self):
299
+ f = self._file
300
+ TransferSyntaxUID = None
301
+
302
+ # Read all elements, store transferSyntax when we encounter it
303
+ try:
304
+ while True:
305
+ fp_save = f.tell()
306
+ # Get element
307
+ group, element, value = self._readDataElement()
308
+ if group == 0x02:
309
+ if group == 0x02 and element == 0x10:
310
+ TransferSyntaxUID = value.decode("ascii").strip("\x00")
311
+ else:
312
+ # No more group 2: rewind and break
313
+ # (don't trust group length)
314
+ f.seek(fp_save)
315
+ break
316
+ except (EOFError, struct.error): # pragma: no cover
317
+ raise RuntimeError("End of file reached while still in header.")
318
+
319
+ # Handle transfer syntax
320
+ self._info["TransferSyntaxUID"] = TransferSyntaxUID
321
+ #
322
+ if TransferSyntaxUID is None:
323
+ # Assume ExplicitVRLittleEndian
324
+ is_implicit_VR, is_little_endian = False, True
325
+ elif TransferSyntaxUID == "1.2.840.10008.1.2.1":
326
+ # ExplicitVRLittleEndian
327
+ is_implicit_VR, is_little_endian = False, True
328
+ elif TransferSyntaxUID == "1.2.840.10008.1.2.2":
329
+ # ExplicitVRBigEndian
330
+ is_implicit_VR, is_little_endian = False, False
331
+ elif TransferSyntaxUID == "1.2.840.10008.1.2":
332
+ # implicit VR little endian
333
+ is_implicit_VR, is_little_endian = True, True
334
+ elif TransferSyntaxUID == "1.2.840.10008.1.2.1.99":
335
+ # DeflatedExplicitVRLittleEndian:
336
+ is_implicit_VR, is_little_endian = False, True
337
+ self._inflate()
338
+ else:
339
+ # http://www.dicomlibrary.com/dicom/transfer-syntax/
340
+ t, extra_info = TransferSyntaxUID, ""
341
+ if "1.2.840.10008.1.2.4.50" <= t < "1.2.840.10008.1.2.4.99":
342
+ extra_info = " (JPEG)"
343
+ if "1.2.840.10008.1.2.4.90" <= t < "1.2.840.10008.1.2.4.99":
344
+ extra_info = " (JPEG 2000)"
345
+ if t == "1.2.840.10008.1.2.5":
346
+ extra_info = " (RLE)"
347
+ if t == "1.2.840.10008.1.2.6.1":
348
+ extra_info = " (RFC 2557)"
349
+ raise CompressedDicom(
350
+ "The dicom reader can only read files with "
351
+ "uncompressed image data - not %r%s. You "
352
+ "can try using dcmtk or gdcm to convert the "
353
+ "image." % (t, extra_info)
354
+ )
355
+
356
+ # From hereon, use implicit/explicit big/little endian
357
+ self.is_implicit_VR = is_implicit_VR
358
+ self.is_little_endian = is_little_endian
359
+ self._unpackPrefix = "><"[is_little_endian]
360
+
361
+ def _read_data_elements(self):
362
+ info = self._info
363
+ try:
364
+ while True:
365
+ # Get element
366
+ group, element, value = self._readDataElement()
367
+ # Is it a group we are interested in?
368
+ if group in GROUPS:
369
+ key = (group, element)
370
+ name, vr = MINIDICT.get(key, (None, None))
371
+ # Is it an element we are interested in?
372
+ if name:
373
+ # Store value
374
+ converter = self._converters.get(vr, lambda x: x)
375
+ info[name] = converter(value)
376
+ except (EOFError, struct.error):
377
+ pass # end of file ...
378
+
379
+ def get_numpy_array(self):
380
+ """Get numpy arra for this DICOM file, with the correct shape,
381
+ and pixel values scaled appropriately.
382
+ """
383
+ # Is there pixel data at all?
384
+ if "PixelData" not in self:
385
+ raise TypeError("No pixel data found in this dataset.")
386
+
387
+ # Load it now if it was not already loaded
388
+ if self._pixel_data_loc and len(self.PixelData) < 100:
389
+ # Reopen file?
390
+ close_file = False
391
+ if self._file is None:
392
+ close_file = True
393
+ self._file = open(self._filename, "rb")
394
+ # Read data
395
+ self._file.seek(self._pixel_data_loc[0])
396
+ if self._pixel_data_loc[1] == 0xFFFFFFFF:
397
+ value = self._read_undefined_length_value()
398
+ else:
399
+ value = self._file.read(self._pixel_data_loc[1])
400
+ # Close file
401
+ if close_file:
402
+ self._file.close()
403
+ self._file = None
404
+ # Overwrite
405
+ self._info["PixelData"] = value
406
+
407
+ # Get data
408
+ data = self._pixel_data_numpy()
409
+ data = self._apply_slope_and_offset(data)
410
+
411
+ # Remove data again to preserve memory
412
+ # Note that the data for the original file is loaded twice ...
413
+ self._info["PixelData"] = (
414
+ b"Data converted to numpy array, " + b"raw data removed to preserve memory"
415
+ )
416
+ return data
417
+
418
+ def _get_shape_and_sampling(self):
419
+ """Get shape and sampling without actuall using the pixel data.
420
+ In this way, the user can get an idea what's inside without having
421
+ to load it.
422
+ """
423
+ # Get shape (in the same way that pydicom does)
424
+ if "NumberOfFrames" in self and self.NumberOfFrames > 1:
425
+ if self.SamplesPerPixel > 1:
426
+ shape = (
427
+ self.SamplesPerPixel,
428
+ self.NumberOfFrames,
429
+ self.Rows,
430
+ self.Columns,
431
+ )
432
+ else:
433
+ shape = self.NumberOfFrames, self.Rows, self.Columns
434
+ elif "SamplesPerPixel" in self:
435
+ if self.SamplesPerPixel > 1:
436
+ if self.BitsAllocated == 8:
437
+ shape = self.SamplesPerPixel, self.Rows, self.Columns
438
+ else:
439
+ raise NotImplementedError(
440
+ "DICOM plugin only handles "
441
+ "SamplesPerPixel > 1 if Bits "
442
+ "Allocated = 8"
443
+ )
444
+ else:
445
+ shape = self.Rows, self.Columns
446
+ else:
447
+ raise RuntimeError(
448
+ "DICOM file has no SamplesPerPixel " "(perhaps this is a report?)"
449
+ )
450
+
451
+ # Try getting sampling between pixels
452
+ if "PixelSpacing" in self:
453
+ sampling = float(self.PixelSpacing[0]), float(self.PixelSpacing[1])
454
+ else:
455
+ sampling = 1.0, 1.0
456
+ if "SliceSpacing" in self:
457
+ sampling = (abs(self.SliceSpacing),) + sampling
458
+
459
+ # Ensure that sampling has as many elements as shape
460
+ sampling = (1.0,) * (len(shape) - len(sampling)) + sampling[-len(shape) :]
461
+
462
+ # Set shape and sampling
463
+ self._info["shape"] = shape
464
+ self._info["sampling"] = sampling
465
+
466
+ def _pixel_data_numpy(self):
467
+ """Return a NumPy array of the pixel data."""
468
+ # Taken from pydicom
469
+ # Copyright (c) 2008-2012 Darcy Mason
470
+
471
+ if "PixelData" not in self:
472
+ raise TypeError("No pixel data found in this dataset.")
473
+
474
+ # determine the type used for the array
475
+ need_byteswap = self.is_little_endian != sys_is_little_endian
476
+
477
+ # Make NumPy format code, e.g. "uint16", "int32" etc
478
+ # from two pieces of info:
479
+ # self.PixelRepresentation -- 0 for unsigned, 1 for signed;
480
+ # self.BitsAllocated -- 8, 16, or 32
481
+ format_str = "%sint%d" % (
482
+ ("u", "")[self.PixelRepresentation],
483
+ self.BitsAllocated,
484
+ )
485
+ try:
486
+ numpy_format = np.dtype(format_str)
487
+ except TypeError: # pragma: no cover
488
+ raise TypeError(
489
+ "Data type not understood by NumPy: format='%s', "
490
+ " PixelRepresentation=%d, BitsAllocated=%d"
491
+ % (numpy_format, self.PixelRepresentation, self.BitsAllocated)
492
+ )
493
+
494
+ # Have correct Numpy format, so create the NumPy array
495
+ arr = np.frombuffer(self.PixelData, numpy_format).copy()
496
+
497
+ # XXX byte swap - may later handle this in read_file!!?
498
+ if need_byteswap:
499
+ arr.byteswap(True) # True means swap in-place, don't make new copy
500
+
501
+ # Note the following reshape operations return a new *view* onto arr,
502
+ # but don't copy the data
503
+ arr = arr.reshape(*self._info["shape"])
504
+ return arr
505
+
506
+ def _apply_slope_and_offset(self, data):
507
+ """
508
+ If RescaleSlope and RescaleIntercept are present in the data,
509
+ apply them. The data type of the data is changed if necessary.
510
+ """
511
+ # Obtain slope and offset
512
+ slope, offset = 1, 0
513
+ needFloats, needApplySlopeOffset = False, False
514
+ if "RescaleSlope" in self:
515
+ needApplySlopeOffset = True
516
+ slope = self.RescaleSlope
517
+ if "RescaleIntercept" in self:
518
+ needApplySlopeOffset = True
519
+ offset = self.RescaleIntercept
520
+ if int(slope) != slope or int(offset) != offset:
521
+ needFloats = True
522
+ if not needFloats:
523
+ slope, offset = int(slope), int(offset)
524
+
525
+ # Apply slope and offset
526
+ if needApplySlopeOffset:
527
+ # Maybe we need to change the datatype?
528
+ if data.dtype in [np.float32, np.float64]:
529
+ pass
530
+ elif needFloats:
531
+ data = data.astype(np.float32)
532
+ else:
533
+ # Determine required range
534
+ minReq, maxReq = data.min().item(), data.max().item()
535
+ minReq = min([minReq, minReq * slope + offset, maxReq * slope + offset])
536
+ maxReq = max([maxReq, minReq * slope + offset, maxReq * slope + offset])
537
+
538
+ # Determine required datatype from that
539
+ dtype = None
540
+ if minReq < 0:
541
+ # Signed integer type
542
+ maxReq = max([-minReq, maxReq])
543
+ if maxReq < 2**7:
544
+ dtype = np.int8
545
+ elif maxReq < 2**15:
546
+ dtype = np.int16
547
+ elif maxReq < 2**31:
548
+ dtype = np.int32
549
+ else:
550
+ dtype = np.float32
551
+ else:
552
+ # Unsigned integer type
553
+ if maxReq < 2**8:
554
+ dtype = np.int8
555
+ elif maxReq < 2**16:
556
+ dtype = np.int16
557
+ elif maxReq < 2**32:
558
+ dtype = np.int32
559
+ else:
560
+ dtype = np.float32
561
+ # Change datatype
562
+ if dtype != data.dtype:
563
+ data = data.astype(dtype)
564
+
565
+ # Apply slope and offset
566
+ data *= slope
567
+ data += offset
568
+
569
+ # Done
570
+ return data
571
+
572
+ def _inflate(self):
573
+ # Taken from pydicom
574
+ # Copyright (c) 2008-2012 Darcy Mason
575
+ import zlib
576
+ from io import BytesIO
577
+
578
+ # See PS3.6-2008 A.5 (p 71) -- when written, the entire dataset
579
+ # following the file metadata was prepared the normal way,
580
+ # then "deflate" compression applied.
581
+ # All that is needed here is to decompress and then
582
+ # use as normal in a file-like object
583
+ zipped = self._file.read()
584
+ # -MAX_WBITS part is from comp.lang.python answer:
585
+ # groups.google.com/group/comp.lang.python/msg/e95b3b38a71e6799
586
+ unzipped = zlib.decompress(zipped, -zlib.MAX_WBITS)
587
+ self._file = BytesIO(unzipped) # a file-like object
588
+
589
+
590
+ class DicomSeries(object):
591
+ """DicomSeries
592
+ This class represents a serie of dicom files (SimpleDicomReader
593
+ objects) that belong together. If these are multiple files, they
594
+ represent the slices of a volume (like for CT or MRI).
595
+ """
596
+
597
+ def __init__(self, suid, progressIndicator):
598
+ # Init dataset list and the callback
599
+ self._entries = []
600
+
601
+ # Init props
602
+ self._suid = suid
603
+ self._info = {}
604
+ self._progressIndicator = progressIndicator
605
+
606
+ def __len__(self):
607
+ return len(self._entries)
608
+
609
+ def __iter__(self):
610
+ return iter(self._entries)
611
+
612
+ def __getitem__(self, index):
613
+ return self._entries[index]
614
+
615
+ @property
616
+ def suid(self):
617
+ return self._suid
618
+
619
+ @property
620
+ def shape(self):
621
+ """The shape of the data (nz, ny, nx)."""
622
+ return self._info["shape"]
623
+
624
+ @property
625
+ def sampling(self):
626
+ """The sampling (voxel distances) of the data (dz, dy, dx)."""
627
+ return self._info["sampling"]
628
+
629
+ @property
630
+ def info(self):
631
+ """A dictionary containing the information as present in the
632
+ first dicomfile of this serie. None if there are no entries."""
633
+ return self._info
634
+
635
+ @property
636
+ def description(self):
637
+ """A description of the dicom series. Used fields are
638
+ PatientName, shape of the data, SeriesDescription, and
639
+ ImageComments.
640
+ """
641
+ info = self.info
642
+
643
+ # If no info available, return simple description
644
+ if not info: # pragma: no cover
645
+ return "DicomSeries containing %i images" % len(self)
646
+
647
+ fields = []
648
+ # Give patient name
649
+ if "PatientName" in info:
650
+ fields.append("" + info["PatientName"])
651
+ # Also add dimensions
652
+ if self.shape:
653
+ tmp = [str(d) for d in self.shape]
654
+ fields.append("x".join(tmp))
655
+ # Try adding more fields
656
+ if "SeriesDescription" in info:
657
+ fields.append("'" + info["SeriesDescription"] + "'")
658
+ if "ImageComments" in info:
659
+ fields.append("'" + info["ImageComments"] + "'")
660
+
661
+ # Combine
662
+ return " ".join(fields)
663
+
664
+ def __repr__(self):
665
+ adr = hex(id(self)).upper()
666
+ return "<DicomSeries with %i images at %s>" % (len(self), adr)
667
+
668
+ def get_numpy_array(self):
669
+ """Get (load) the data that this DicomSeries represents, and return
670
+ it as a numpy array. If this serie contains multiple images, the
671
+ resulting array is 3D, otherwise it's 2D.
672
+ """
673
+
674
+ # It's easy if no file or if just a single file
675
+ if len(self) == 0:
676
+ raise ValueError("Serie does not contain any files.")
677
+ elif len(self) == 1:
678
+ return self[0].get_numpy_array()
679
+
680
+ # Check info
681
+ if self.info is None:
682
+ raise RuntimeError("Cannot return volume if series not finished.")
683
+
684
+ # Init data (using what the dicom packaged produces as a reference)
685
+ slice = self[0].get_numpy_array()
686
+ vol = np.zeros(self.shape, dtype=slice.dtype)
687
+ vol[0] = slice
688
+
689
+ # Fill volume
690
+ self._progressIndicator.start("loading data", "", len(self))
691
+ for z in range(1, len(self)):
692
+ vol[z] = self[z].get_numpy_array()
693
+ self._progressIndicator.set_progress(z + 1)
694
+ self._progressIndicator.finish()
695
+
696
+ # Done
697
+ import gc
698
+
699
+ gc.collect()
700
+ return vol
701
+
702
+ def _append(self, dcm):
703
+ self._entries.append(dcm)
704
+
705
+ def _sort(self):
706
+ self._entries.sort(
707
+ key=lambda k: (
708
+ k.InstanceNumber,
709
+ (
710
+ k.ImagePositionPatient[2]
711
+ if hasattr(k, "ImagePositionPatient")
712
+ else None
713
+ ),
714
+ )
715
+ )
716
+
717
+ def _finish(self):
718
+ """
719
+ Evaluate the series of dicom files. Together they should make up
720
+ a volumetric dataset. This means the files should meet certain
721
+ conditions. Also some additional information has to be calculated,
722
+ such as the distance between the slices. This method sets the
723
+ attributes for "shape", "sampling" and "info".
724
+
725
+ This method checks:
726
+ * that there are no missing files
727
+ * that the dimensions of all images match
728
+ * that the pixel spacing of all images match
729
+ """
730
+
731
+ # The datasets list should be sorted by instance number
732
+ L = self._entries
733
+ if len(L) == 0:
734
+ return
735
+ elif len(L) == 1:
736
+ self._info = L[0].info
737
+ return
738
+
739
+ # Get previous
740
+ ds1 = L[0]
741
+ # Init measures to calculate average of
742
+ distance_sum = 0.0
743
+ # Init measures to check (these are in 2D)
744
+ dimensions = ds1.Rows, ds1.Columns
745
+ # sampling = float(ds1.PixelSpacing[0]), float(ds1.PixelSpacing[1])
746
+ sampling = ds1.info["sampling"][:2] # row, column
747
+
748
+ for index in range(len(L)):
749
+ # The first round ds1 and ds2 will be the same, for the
750
+ # distance calculation this does not matter
751
+ # Get current
752
+ ds2 = L[index]
753
+ # Get positions
754
+ pos1 = float(ds1.ImagePositionPatient[2])
755
+ pos2 = float(ds2.ImagePositionPatient[2])
756
+ # Update distance_sum to calculate distance later
757
+ distance_sum += abs(pos1 - pos2)
758
+ # Test measures
759
+ dimensions2 = ds2.Rows, ds2.Columns
760
+ # sampling2 = float(ds2.PixelSpacing[0]), float(ds2.PixelSpacing[1])
761
+ sampling2 = ds2.info["sampling"][:2] # row, column
762
+ if dimensions != dimensions2:
763
+ # We cannot produce a volume if the dimensions match
764
+ raise ValueError("Dimensions of slices does not match.")
765
+ if sampling != sampling2:
766
+ # We can still produce a volume, but we should notify the user
767
+ self._progressIndicator.write("Warn: sampling does not match.")
768
+ # Store previous
769
+ ds1 = ds2
770
+
771
+ # Finish calculating average distance
772
+ # (Note that there are len(L)-1 distances)
773
+ distance_mean = distance_sum / (len(L) - 1)
774
+
775
+ # Set info dict
776
+ self._info = L[0].info.copy()
777
+
778
+ # Store information that is specific for the serie
779
+ self._info["shape"] = (len(L),) + ds2.info["shape"]
780
+ self._info["sampling"] = (distance_mean,) + ds2.info["sampling"]
781
+
782
+
783
+ def list_files(files, path):
784
+ """List all files in the directory, recursively."""
785
+ for item in os.listdir(path):
786
+ item = os.path.join(path, item)
787
+ if os.path.isdir(item):
788
+ list_files(files, item)
789
+ elif os.path.isfile(item):
790
+ files.append(item)
791
+
792
+
793
+ def process_directory(request, progressIndicator, readPixelData=False):
794
+ """
795
+ Reads dicom files and returns a list of DicomSeries objects, which
796
+ contain information about the data, and can be used to load the
797
+ image or volume data.
798
+
799
+ if readPixelData is True, the pixel data of all series is read. By
800
+ default the loading of pixeldata is deferred until it is requested
801
+ using the DicomSeries.get_pixel_array() method. In general, both
802
+ methods should be equally fast.
803
+ """
804
+ # Get directory to examine
805
+ if os.path.isdir(request.filename):
806
+ path = request.filename
807
+ elif os.path.isfile(request.filename):
808
+ path = os.path.dirname(request.filename)
809
+ else: # pragma: no cover - tested earlier
810
+ raise ValueError("Dicom plugin needs a valid filename to examine the directory")
811
+
812
+ # Check files
813
+ files = []
814
+ list_files(files, path) # Find files recursively
815
+
816
+ # Gather file data and put in DicomSeries
817
+ series = {}
818
+ count = 0
819
+ progressIndicator.start("examining files", "files", len(files))
820
+ for filename in files:
821
+ # Show progress (note that we always start with a 0.0)
822
+ count += 1
823
+ progressIndicator.set_progress(count)
824
+ # Skip DICOMDIR files
825
+ if filename.count("DICOMDIR"): # pragma: no cover
826
+ continue
827
+ # Try loading dicom ...
828
+ try:
829
+ dcm = SimpleDicomReader(filename)
830
+ except NotADicomFile:
831
+ continue # skip non-dicom file
832
+ except Exception as why: # pragma: no cover
833
+ progressIndicator.write(str(why))
834
+ continue
835
+ # Get SUID and register the file with an existing or new series object
836
+ try:
837
+ suid = dcm.SeriesInstanceUID
838
+ except AttributeError: # pragma: no cover
839
+ continue # some other kind of dicom file
840
+ if suid not in series:
841
+ series[suid] = DicomSeries(suid, progressIndicator)
842
+ series[suid]._append(dcm)
843
+
844
+ # Finish progress
845
+ # progressIndicator.finish('Found %i series.' % len(series))
846
+
847
+ # Make a list and sort, so that the order is deterministic
848
+ series = list(series.values())
849
+ series.sort(key=lambda x: x.suid)
850
+
851
+ # Split series if necessary
852
+ for serie in reversed([serie for serie in series]):
853
+ splitSerieIfRequired(serie, series, progressIndicator)
854
+
855
+ # Finish all series
856
+ # progressIndicator.start('analyse series', '', len(series))
857
+ series_ = []
858
+ for i in range(len(series)):
859
+ try:
860
+ series[i]._finish()
861
+ series_.append(series[i])
862
+ except Exception as err: # pragma: no cover
863
+ progressIndicator.write(str(err))
864
+ pass # Skip serie (probably report-like file without pixels)
865
+ # progressIndicator.set_progress(i+1)
866
+ progressIndicator.finish("Found %i correct series." % len(series_))
867
+
868
+ # Done
869
+ return series_
870
+
871
+
872
+ def splitSerieIfRequired(serie, series, progressIndicator):
873
+ """
874
+ Split the serie in multiple series if this is required. The choice
875
+ is based on examing the image position relative to the previous
876
+ image. If it differs too much, it is assumed that there is a new
877
+ dataset. This can happen for example in unspitted gated CT data.
878
+ """
879
+
880
+ # Sort the original list and get local name
881
+ serie._sort()
882
+ L = serie._entries
883
+ # Init previous slice
884
+ ds1 = L[0]
885
+ # Check whether we can do this
886
+ if "ImagePositionPatient" not in ds1:
887
+ return
888
+ # Initialize a list of new lists
889
+ L2 = [[ds1]]
890
+ # Init slice distance estimate
891
+ distance = 0
892
+
893
+ for index in range(1, len(L)):
894
+ # Get current slice
895
+ ds2 = L[index]
896
+ # Get positions
897
+ pos1 = float(ds1.ImagePositionPatient[2])
898
+ pos2 = float(ds2.ImagePositionPatient[2])
899
+ # Get distances
900
+ newDist = abs(pos1 - pos2)
901
+ # deltaDist = abs(firstPos-pos2)
902
+ # If the distance deviates more than 2x from what we've seen,
903
+ # we can agree it's a new dataset.
904
+ if distance and newDist > 2.1 * distance:
905
+ L2.append([])
906
+ distance = 0
907
+ else:
908
+ # Test missing file
909
+ if distance and newDist > 1.5 * distance:
910
+ progressIndicator.write(
911
+ "Warning: missing file after %r" % ds1._filename
912
+ )
913
+ distance = newDist
914
+ # Add to last list
915
+ L2[-1].append(ds2)
916
+ # Store previous
917
+ ds1 = ds2
918
+
919
+ # Split if we should
920
+ if len(L2) > 1:
921
+ # At what position are we now?
922
+ i = series.index(serie)
923
+ # Create new series
924
+ series2insert = []
925
+ for L in L2:
926
+ newSerie = DicomSeries(serie.suid, progressIndicator)
927
+ newSerie._entries = L
928
+ series2insert.append(newSerie)
929
+ # Insert series and remove self
930
+ for newSerie in reversed(series2insert):
931
+ series.insert(i, newSerie)
932
+ series.remove(serie)
minigpt2/lib/python3.10/site-packages/imageio/plugins/_freeimage.py ADDED
@@ -0,0 +1,1312 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # imageio is distributed under the terms of the (new) BSD License.
3
+
4
+ # styletest: ignore E261
5
+
6
+ """ Module imageio/freeimage.py
7
+
8
+ This module contains the wrapper code for the freeimage library.
9
+ The functions defined in this module are relatively thin; just thin
10
+ enough so that arguments and results are native Python/numpy data
11
+ types.
12
+
13
+ """
14
+
15
+ import os
16
+ import sys
17
+ import ctypes
18
+ import threading
19
+ import logging
20
+ import numpy
21
+
22
+ from ..core import (
23
+ get_remote_file,
24
+ load_lib,
25
+ Dict,
26
+ resource_dirs,
27
+ IS_PYPY,
28
+ get_platform,
29
+ InternetNotAllowedError,
30
+ NeedDownloadError,
31
+ )
32
+
33
+ logger = logging.getLogger(__name__)
34
+
35
+ TEST_NUMPY_NO_STRIDES = False # To test pypy fallback
36
+
37
+ FNAME_PER_PLATFORM = {
38
+ "osx32": "libfreeimage-3.16.0-osx10.6.dylib", # universal library
39
+ "osx64": "libfreeimage-3.16.0-osx10.6.dylib",
40
+ "win32": "FreeImage-3.18.0-win32.dll",
41
+ "win64": "FreeImage-3.18.0-win64.dll",
42
+ "linux32": "libfreeimage-3.16.0-linux32.so",
43
+ "linux64": "libfreeimage-3.16.0-linux64.so",
44
+ }
45
+
46
+
47
+ def download(directory=None, force_download=False):
48
+ """Download the FreeImage library to your computer.
49
+
50
+ Parameters
51
+ ----------
52
+ directory : str | None
53
+ The directory where the file will be cached if a download was
54
+ required to obtain the file. By default, the appdata directory
55
+ is used. This is also the first directory that is checked for
56
+ a local version of the file.
57
+ force_download : bool | str
58
+ If True, the file will be downloaded even if a local copy exists
59
+ (and this copy will be overwritten). Can also be a YYYY-MM-DD date
60
+ to ensure a file is up-to-date (modified date of a file on disk,
61
+ if present, is checked).
62
+ """
63
+ plat = get_platform()
64
+ if plat and plat in FNAME_PER_PLATFORM:
65
+ fname = "freeimage/" + FNAME_PER_PLATFORM[plat]
66
+ get_remote_file(fname=fname, directory=directory, force_download=force_download)
67
+ fi._lib = None # allow trying again (needed to make tests work)
68
+
69
+
70
+ def get_freeimage_lib():
71
+ """Ensure we have our version of the binary freeimage lib."""
72
+
73
+ lib = os.getenv("IMAGEIO_FREEIMAGE_LIB", None)
74
+ if lib: # pragma: no cover
75
+ return lib
76
+
77
+ # Get filename to load
78
+ # If we do not provide a binary, the system may still do ...
79
+ plat = get_platform()
80
+ if plat and plat in FNAME_PER_PLATFORM:
81
+ try:
82
+ return get_remote_file("freeimage/" + FNAME_PER_PLATFORM[plat], auto=False)
83
+ except InternetNotAllowedError:
84
+ pass
85
+ except NeedDownloadError:
86
+ raise NeedDownloadError(
87
+ "Need FreeImage library. "
88
+ "You can obtain it with either:\n"
89
+ " - download using the command: "
90
+ "imageio_download_bin freeimage\n"
91
+ " - download by calling (in Python): "
92
+ "imageio.plugins.freeimage.download()\n"
93
+ )
94
+ except RuntimeError as e: # pragma: no cover
95
+ logger.warning(str(e))
96
+
97
+
98
+ # Define function to encode a filename to bytes (for the current system)
99
+ def efn(x):
100
+ return x.encode(sys.getfilesystemencoding())
101
+
102
+
103
+ # 4-byte quads of 0,v,v,v from 0,0,0,0 to 0,255,255,255
104
+ GREY_PALETTE = numpy.arange(0, 0x01000000, 0x00010101, dtype=numpy.uint32)
105
+
106
+
107
+ class FI_TYPES(object):
108
+ FIT_UNKNOWN = 0
109
+ FIT_BITMAP = 1
110
+ FIT_UINT16 = 2
111
+ FIT_INT16 = 3
112
+ FIT_UINT32 = 4
113
+ FIT_INT32 = 5
114
+ FIT_FLOAT = 6
115
+ FIT_DOUBLE = 7
116
+ FIT_COMPLEX = 8
117
+ FIT_RGB16 = 9
118
+ FIT_RGBA16 = 10
119
+ FIT_RGBF = 11
120
+ FIT_RGBAF = 12
121
+
122
+ dtypes = {
123
+ FIT_BITMAP: numpy.uint8,
124
+ FIT_UINT16: numpy.uint16,
125
+ FIT_INT16: numpy.int16,
126
+ FIT_UINT32: numpy.uint32,
127
+ FIT_INT32: numpy.int32,
128
+ FIT_FLOAT: numpy.float32,
129
+ FIT_DOUBLE: numpy.float64,
130
+ FIT_COMPLEX: numpy.complex128,
131
+ FIT_RGB16: numpy.uint16,
132
+ FIT_RGBA16: numpy.uint16,
133
+ FIT_RGBF: numpy.float32,
134
+ FIT_RGBAF: numpy.float32,
135
+ }
136
+
137
+ fi_types = {
138
+ (numpy.uint8, 1): FIT_BITMAP,
139
+ (numpy.uint8, 3): FIT_BITMAP,
140
+ (numpy.uint8, 4): FIT_BITMAP,
141
+ (numpy.uint16, 1): FIT_UINT16,
142
+ (numpy.int16, 1): FIT_INT16,
143
+ (numpy.uint32, 1): FIT_UINT32,
144
+ (numpy.int32, 1): FIT_INT32,
145
+ (numpy.float32, 1): FIT_FLOAT,
146
+ (numpy.float64, 1): FIT_DOUBLE,
147
+ (numpy.complex128, 1): FIT_COMPLEX,
148
+ (numpy.uint16, 3): FIT_RGB16,
149
+ (numpy.uint16, 4): FIT_RGBA16,
150
+ (numpy.float32, 3): FIT_RGBF,
151
+ (numpy.float32, 4): FIT_RGBAF,
152
+ }
153
+
154
+ extra_dims = {
155
+ FIT_UINT16: [],
156
+ FIT_INT16: [],
157
+ FIT_UINT32: [],
158
+ FIT_INT32: [],
159
+ FIT_FLOAT: [],
160
+ FIT_DOUBLE: [],
161
+ FIT_COMPLEX: [],
162
+ FIT_RGB16: [3],
163
+ FIT_RGBA16: [4],
164
+ FIT_RGBF: [3],
165
+ FIT_RGBAF: [4],
166
+ }
167
+
168
+
169
+ class IO_FLAGS(object):
170
+ FIF_LOAD_NOPIXELS = 0x8000 # loading: load the image header only
171
+ # # (not supported by all plugins)
172
+ BMP_DEFAULT = 0
173
+ BMP_SAVE_RLE = 1
174
+ CUT_DEFAULT = 0
175
+ DDS_DEFAULT = 0
176
+ EXR_DEFAULT = 0 # save data as half with piz-based wavelet compression
177
+ EXR_FLOAT = 0x0001 # save data as float instead of half (not recommended)
178
+ EXR_NONE = 0x0002 # save with no compression
179
+ EXR_ZIP = 0x0004 # save with zlib compression, in blocks of 16 scan lines
180
+ EXR_PIZ = 0x0008 # save with piz-based wavelet compression
181
+ EXR_PXR24 = 0x0010 # save with lossy 24-bit float compression
182
+ EXR_B44 = 0x0020 # save with lossy 44% float compression
183
+ # # - goes to 22% when combined with EXR_LC
184
+ EXR_LC = 0x0040 # save images with one luminance and two chroma channels,
185
+ # # rather than as RGB (lossy compression)
186
+ FAXG3_DEFAULT = 0
187
+ GIF_DEFAULT = 0
188
+ GIF_LOAD256 = 1 # Load the image as a 256 color image with ununsed
189
+ # # palette entries, if it's 16 or 2 color
190
+ GIF_PLAYBACK = 2 # 'Play' the GIF to generate each frame (as 32bpp)
191
+ # # instead of returning raw frame data when loading
192
+ HDR_DEFAULT = 0
193
+ ICO_DEFAULT = 0
194
+ ICO_MAKEALPHA = 1 # convert to 32bpp and create an alpha channel from the
195
+ # # AND-mask when loading
196
+ IFF_DEFAULT = 0
197
+ J2K_DEFAULT = 0 # save with a 16:1 rate
198
+ JP2_DEFAULT = 0 # save with a 16:1 rate
199
+ JPEG_DEFAULT = 0 # loading (see JPEG_FAST);
200
+ # # saving (see JPEG_QUALITYGOOD|JPEG_SUBSAMPLING_420)
201
+ JPEG_FAST = 0x0001 # load the file as fast as possible,
202
+ # # sacrificing some quality
203
+ JPEG_ACCURATE = 0x0002 # load the file with the best quality,
204
+ # # sacrificing some speed
205
+ JPEG_CMYK = 0x0004 # load separated CMYK "as is"
206
+ # # (use | to combine with other load flags)
207
+ JPEG_EXIFROTATE = 0x0008 # load and rotate according to
208
+ # # Exif 'Orientation' tag if available
209
+ JPEG_QUALITYSUPERB = 0x80 # save with superb quality (100:1)
210
+ JPEG_QUALITYGOOD = 0x0100 # save with good quality (75:1)
211
+ JPEG_QUALITYNORMAL = 0x0200 # save with normal quality (50:1)
212
+ JPEG_QUALITYAVERAGE = 0x0400 # save with average quality (25:1)
213
+ JPEG_QUALITYBAD = 0x0800 # save with bad quality (10:1)
214
+ JPEG_PROGRESSIVE = 0x2000 # save as a progressive-JPEG
215
+ # # (use | to combine with other save flags)
216
+ JPEG_SUBSAMPLING_411 = 0x1000 # save with high 4x1 chroma
217
+ # # subsampling (4:1:1)
218
+ JPEG_SUBSAMPLING_420 = 0x4000 # save with medium 2x2 medium chroma
219
+ # # subsampling (4:2:0) - default value
220
+ JPEG_SUBSAMPLING_422 = 0x8000 # save /w low 2x1 chroma subsampling (4:2:2)
221
+ JPEG_SUBSAMPLING_444 = 0x10000 # save with no chroma subsampling (4:4:4)
222
+ JPEG_OPTIMIZE = 0x20000 # on saving, compute optimal Huffman coding tables
223
+ # # (can reduce a few percent of file size)
224
+ JPEG_BASELINE = 0x40000 # save basic JPEG, without metadata or any markers
225
+ KOALA_DEFAULT = 0
226
+ LBM_DEFAULT = 0
227
+ MNG_DEFAULT = 0
228
+ PCD_DEFAULT = 0
229
+ PCD_BASE = 1 # load the bitmap sized 768 x 512
230
+ PCD_BASEDIV4 = 2 # load the bitmap sized 384 x 256
231
+ PCD_BASEDIV16 = 3 # load the bitmap sized 192 x 128
232
+ PCX_DEFAULT = 0
233
+ PFM_DEFAULT = 0
234
+ PICT_DEFAULT = 0
235
+ PNG_DEFAULT = 0
236
+ PNG_IGNOREGAMMA = 1 # loading: avoid gamma correction
237
+ PNG_Z_BEST_SPEED = 0x0001 # save using ZLib level 1 compression flag
238
+ # # (default value is 6)
239
+ PNG_Z_DEFAULT_COMPRESSION = 0x0006 # save using ZLib level 6 compression
240
+ # # flag (default recommended value)
241
+ PNG_Z_BEST_COMPRESSION = 0x0009 # save using ZLib level 9 compression flag
242
+ # # (default value is 6)
243
+ PNG_Z_NO_COMPRESSION = 0x0100 # save without ZLib compression
244
+ PNG_INTERLACED = 0x0200 # save using Adam7 interlacing (use | to combine
245
+ # # with other save flags)
246
+ PNM_DEFAULT = 0
247
+ PNM_SAVE_RAW = 0 # Writer saves in RAW format (i.e. P4, P5 or P6)
248
+ PNM_SAVE_ASCII = 1 # Writer saves in ASCII format (i.e. P1, P2 or P3)
249
+ PSD_DEFAULT = 0
250
+ PSD_CMYK = 1 # reads tags for separated CMYK (default is conversion to RGB)
251
+ PSD_LAB = 2 # reads tags for CIELab (default is conversion to RGB)
252
+ RAS_DEFAULT = 0
253
+ RAW_DEFAULT = 0 # load the file as linear RGB 48-bit
254
+ RAW_PREVIEW = 1 # try to load the embedded JPEG preview with included
255
+ # # Exif Data or default to RGB 24-bit
256
+ RAW_DISPLAY = 2 # load the file as RGB 24-bit
257
+ SGI_DEFAULT = 0
258
+ TARGA_DEFAULT = 0
259
+ TARGA_LOAD_RGB888 = 1 # Convert RGB555 and ARGB8888 -> RGB888.
260
+ TARGA_SAVE_RLE = 2 # Save with RLE compression
261
+ TIFF_DEFAULT = 0
262
+ TIFF_CMYK = 0x0001 # reads/stores tags for separated CMYK
263
+ # # (use | to combine with compression flags)
264
+ TIFF_PACKBITS = 0x0100 # save using PACKBITS compression
265
+ TIFF_DEFLATE = 0x0200 # save using DEFLATE (a.k.a. ZLIB) compression
266
+ TIFF_ADOBE_DEFLATE = 0x0400 # save using ADOBE DEFLATE compression
267
+ TIFF_NONE = 0x0800 # save without any compression
268
+ TIFF_CCITTFAX3 = 0x1000 # save using CCITT Group 3 fax encoding
269
+ TIFF_CCITTFAX4 = 0x2000 # save using CCITT Group 4 fax encoding
270
+ TIFF_LZW = 0x4000 # save using LZW compression
271
+ TIFF_JPEG = 0x8000 # save using JPEG compression
272
+ TIFF_LOGLUV = 0x10000 # save using LogLuv compression
273
+ WBMP_DEFAULT = 0
274
+ XBM_DEFAULT = 0
275
+ XPM_DEFAULT = 0
276
+
277
+
278
+ class METADATA_MODELS(object):
279
+ FIMD_COMMENTS = 0
280
+ FIMD_EXIF_MAIN = 1
281
+ FIMD_EXIF_EXIF = 2
282
+ FIMD_EXIF_GPS = 3
283
+ FIMD_EXIF_MAKERNOTE = 4
284
+ FIMD_EXIF_INTEROP = 5
285
+ FIMD_IPTC = 6
286
+ FIMD_XMP = 7
287
+ FIMD_GEOTIFF = 8
288
+ FIMD_ANIMATION = 9
289
+
290
+
291
+ class METADATA_DATATYPE(object):
292
+ FIDT_BYTE = 1 # 8-bit unsigned integer
293
+ FIDT_ASCII = 2 # 8-bit bytes w/ last byte null
294
+ FIDT_SHORT = 3 # 16-bit unsigned integer
295
+ FIDT_LONG = 4 # 32-bit unsigned integer
296
+ FIDT_RATIONAL = 5 # 64-bit unsigned fraction
297
+ FIDT_SBYTE = 6 # 8-bit signed integer
298
+ FIDT_UNDEFINED = 7 # 8-bit untyped data
299
+ FIDT_SSHORT = 8 # 16-bit signed integer
300
+ FIDT_SLONG = 9 # 32-bit signed integer
301
+ FIDT_SRATIONAL = 10 # 64-bit signed fraction
302
+ FIDT_FLOAT = 11 # 32-bit IEEE floating point
303
+ FIDT_DOUBLE = 12 # 64-bit IEEE floating point
304
+ FIDT_IFD = 13 # 32-bit unsigned integer (offset)
305
+ FIDT_PALETTE = 14 # 32-bit RGBQUAD
306
+ FIDT_LONG8 = 16 # 64-bit unsigned integer
307
+ FIDT_SLONG8 = 17 # 64-bit signed integer
308
+ FIDT_IFD8 = 18 # 64-bit unsigned integer (offset)
309
+
310
+ dtypes = {
311
+ FIDT_BYTE: numpy.uint8,
312
+ FIDT_SHORT: numpy.uint16,
313
+ FIDT_LONG: numpy.uint32,
314
+ FIDT_RATIONAL: [("numerator", numpy.uint32), ("denominator", numpy.uint32)],
315
+ FIDT_LONG8: numpy.uint64,
316
+ FIDT_SLONG8: numpy.int64,
317
+ FIDT_IFD8: numpy.uint64,
318
+ FIDT_SBYTE: numpy.int8,
319
+ FIDT_UNDEFINED: numpy.uint8,
320
+ FIDT_SSHORT: numpy.int16,
321
+ FIDT_SLONG: numpy.int32,
322
+ FIDT_SRATIONAL: [("numerator", numpy.int32), ("denominator", numpy.int32)],
323
+ FIDT_FLOAT: numpy.float32,
324
+ FIDT_DOUBLE: numpy.float64,
325
+ FIDT_IFD: numpy.uint32,
326
+ FIDT_PALETTE: [
327
+ ("R", numpy.uint8),
328
+ ("G", numpy.uint8),
329
+ ("B", numpy.uint8),
330
+ ("A", numpy.uint8),
331
+ ],
332
+ }
333
+
334
+
335
+ class Freeimage(object):
336
+ """Class to represent an interface to the FreeImage library.
337
+ This class is relatively thin. It provides a Pythonic API that converts
338
+ Freeimage objects to Python objects, but that's about it.
339
+ The actual implementation should be provided by the plugins.
340
+
341
+ The recommended way to call into the Freeimage library (so that
342
+ errors and warnings show up in the right moment) is to use this
343
+ object as a context manager:
344
+ with imageio.fi as lib:
345
+ lib.FreeImage_GetPalette()
346
+
347
+ """
348
+
349
+ _API = {
350
+ # All we're doing here is telling ctypes that some of the
351
+ # FreeImage functions return pointers instead of integers. (On
352
+ # 64-bit systems, without this information the pointers get
353
+ # truncated and crashes result). There's no need to list
354
+ # functions that return ints, or the types of the parameters
355
+ # to these or other functions -- that's fine to do implicitly.
356
+ # Note that the ctypes immediately converts the returned void_p
357
+ # back to a python int again! This is really not helpful,
358
+ # because then passing it back to another library call will
359
+ # cause truncation-to-32-bits on 64-bit systems. Thanks, ctypes!
360
+ # So after these calls one must immediately re-wrap the int as
361
+ # a c_void_p if it is to be passed back into FreeImage.
362
+ "FreeImage_AllocateT": (ctypes.c_void_p, None),
363
+ "FreeImage_FindFirstMetadata": (ctypes.c_void_p, None),
364
+ "FreeImage_GetBits": (ctypes.c_void_p, None),
365
+ "FreeImage_GetPalette": (ctypes.c_void_p, None),
366
+ "FreeImage_GetTagKey": (ctypes.c_char_p, None),
367
+ "FreeImage_GetTagValue": (ctypes.c_void_p, None),
368
+ "FreeImage_CreateTag": (ctypes.c_void_p, None),
369
+ "FreeImage_Save": (ctypes.c_void_p, None),
370
+ "FreeImage_Load": (ctypes.c_void_p, None),
371
+ "FreeImage_LoadFromMemory": (ctypes.c_void_p, None),
372
+ "FreeImage_OpenMultiBitmap": (ctypes.c_void_p, None),
373
+ "FreeImage_LoadMultiBitmapFromMemory": (ctypes.c_void_p, None),
374
+ "FreeImage_LockPage": (ctypes.c_void_p, None),
375
+ "FreeImage_OpenMemory": (ctypes.c_void_p, None),
376
+ # 'FreeImage_ReadMemory': (ctypes.c_void_p, None),
377
+ # 'FreeImage_CloseMemory': (ctypes.c_void_p, None),
378
+ "FreeImage_GetVersion": (ctypes.c_char_p, None),
379
+ "FreeImage_GetFIFExtensionList": (ctypes.c_char_p, None),
380
+ "FreeImage_GetFormatFromFIF": (ctypes.c_char_p, None),
381
+ "FreeImage_GetFIFDescription": (ctypes.c_char_p, None),
382
+ "FreeImage_ColorQuantizeEx": (ctypes.c_void_p, None),
383
+ # Pypy wants some extra definitions, so here we go ...
384
+ "FreeImage_IsLittleEndian": (ctypes.c_int, None),
385
+ "FreeImage_SetOutputMessage": (ctypes.c_void_p, None),
386
+ "FreeImage_GetFIFCount": (ctypes.c_int, None),
387
+ "FreeImage_IsPluginEnabled": (ctypes.c_int, None),
388
+ "FreeImage_GetFileType": (ctypes.c_int, None),
389
+ #
390
+ "FreeImage_GetTagType": (ctypes.c_int, None),
391
+ "FreeImage_GetTagLength": (ctypes.c_int, None),
392
+ "FreeImage_FindNextMetadata": (ctypes.c_int, None),
393
+ "FreeImage_FindCloseMetadata": (ctypes.c_void_p, None),
394
+ #
395
+ "FreeImage_GetFIFFromFilename": (ctypes.c_int, None),
396
+ "FreeImage_FIFSupportsReading": (ctypes.c_int, None),
397
+ "FreeImage_FIFSupportsWriting": (ctypes.c_int, None),
398
+ "FreeImage_FIFSupportsExportType": (ctypes.c_int, None),
399
+ "FreeImage_FIFSupportsExportBPP": (ctypes.c_int, None),
400
+ "FreeImage_GetHeight": (ctypes.c_int, None),
401
+ "FreeImage_GetWidth": (ctypes.c_int, None),
402
+ "FreeImage_GetImageType": (ctypes.c_int, None),
403
+ "FreeImage_GetBPP": (ctypes.c_int, None),
404
+ "FreeImage_GetColorsUsed": (ctypes.c_int, None),
405
+ "FreeImage_ConvertTo32Bits": (ctypes.c_void_p, None),
406
+ "FreeImage_GetPitch": (ctypes.c_int, None),
407
+ "FreeImage_Unload": (ctypes.c_void_p, None),
408
+ }
409
+
410
+ def __init__(self):
411
+ # Initialize freeimage lib as None
412
+ self._lib = None
413
+
414
+ # A lock to create thread-safety
415
+ self._lock = threading.RLock()
416
+
417
+ # Init log messages lists
418
+ self._messages = []
419
+
420
+ # Select functype for error handler
421
+ if sys.platform.startswith("win"):
422
+ functype = ctypes.WINFUNCTYPE
423
+ else:
424
+ functype = ctypes.CFUNCTYPE
425
+
426
+ # Create output message handler
427
+ @functype(None, ctypes.c_int, ctypes.c_char_p)
428
+ def error_handler(fif, message):
429
+ message = message.decode("utf-8")
430
+ self._messages.append(message)
431
+ while (len(self._messages)) > 256:
432
+ self._messages.pop(0)
433
+
434
+ # Make sure to keep a ref to function
435
+ self._error_handler = error_handler
436
+
437
+ @property
438
+ def lib(self):
439
+ if self._lib is None:
440
+ try:
441
+ self.load_freeimage()
442
+ except OSError as err:
443
+ self._lib = "The freeimage library could not be loaded: "
444
+ self._lib += str(err)
445
+ if isinstance(self._lib, str):
446
+ raise RuntimeError(self._lib)
447
+ return self._lib
448
+
449
+ def has_lib(self):
450
+ try:
451
+ self.lib
452
+ except Exception:
453
+ return False
454
+ return True
455
+
456
+ def load_freeimage(self):
457
+ """Try to load the freeimage lib from the system. If not successful,
458
+ try to download the imageio version and try again.
459
+ """
460
+ # Load library and register API
461
+ success = False
462
+ try:
463
+ # Try without forcing a download, but giving preference
464
+ # to the imageio-provided lib (if previously downloaded)
465
+ self._load_freeimage()
466
+ self._register_api()
467
+ if self.lib.FreeImage_GetVersion().decode("utf-8") >= "3.15":
468
+ success = True
469
+ except OSError:
470
+ pass
471
+
472
+ if not success:
473
+ # Ensure we have our own lib, try again
474
+ get_freeimage_lib()
475
+ self._load_freeimage()
476
+ self._register_api()
477
+
478
+ # Wrap up
479
+ self.lib.FreeImage_SetOutputMessage(self._error_handler)
480
+ self.lib_version = self.lib.FreeImage_GetVersion().decode("utf-8")
481
+
482
+ def _load_freeimage(self):
483
+ # Define names
484
+ lib_names = ["freeimage", "libfreeimage"]
485
+ exact_lib_names = [
486
+ "FreeImage",
487
+ "libfreeimage.dylib",
488
+ "libfreeimage.so",
489
+ "libfreeimage.so.3",
490
+ ]
491
+ # Add names of libraries that we provide (that file may not exist)
492
+ res_dirs = resource_dirs()
493
+ plat = get_platform()
494
+ if plat: # Can be None on e.g. FreeBSD
495
+ fname = FNAME_PER_PLATFORM[plat]
496
+ for dir in res_dirs:
497
+ exact_lib_names.insert(0, os.path.join(dir, "freeimage", fname))
498
+
499
+ # Add the path specified with IMAGEIO_FREEIMAGE_LIB:
500
+ lib = os.getenv("IMAGEIO_FREEIMAGE_LIB", None)
501
+ if lib is not None:
502
+ exact_lib_names.insert(0, lib)
503
+
504
+ # Load
505
+ try:
506
+ lib, fname = load_lib(exact_lib_names, lib_names, res_dirs)
507
+ except OSError as err: # pragma: no cover
508
+ err_msg = str(err) + "\nPlease install the FreeImage library."
509
+ raise OSError(err_msg)
510
+
511
+ # Store
512
+ self._lib = lib
513
+ self.lib_fname = fname
514
+
515
+ def _register_api(self):
516
+ # Albert's ctypes pattern
517
+ for f, (restype, argtypes) in self._API.items():
518
+ func = getattr(self.lib, f)
519
+ func.restype = restype
520
+ func.argtypes = argtypes
521
+
522
+ # Handling of output messages
523
+
524
+ def __enter__(self):
525
+ self._lock.acquire()
526
+ return self.lib
527
+
528
+ def __exit__(self, *args):
529
+ self._show_any_warnings()
530
+ self._lock.release()
531
+
532
+ def _reset_log(self):
533
+ """Reset the list of output messages. Call this before
534
+ loading or saving an image with the FreeImage API.
535
+ """
536
+ self._messages = []
537
+
538
+ def _get_error_message(self):
539
+ """Get the output messages produced since the last reset as
540
+ one string. Returns 'No known reason.' if there are no messages.
541
+ Also resets the log.
542
+ """
543
+ if self._messages:
544
+ res = " ".join(self._messages)
545
+ self._reset_log()
546
+ return res
547
+ else:
548
+ return "No known reason."
549
+
550
+ def _show_any_warnings(self):
551
+ """If there were any messages since the last reset, show them
552
+ as a warning. Otherwise do nothing. Also resets the messages.
553
+ """
554
+ if self._messages:
555
+ logger.warning("imageio.freeimage warning: " + self._get_error_message())
556
+ self._reset_log()
557
+
558
+ def get_output_log(self):
559
+ """Return a list of the last 256 output messages
560
+ (warnings and errors) produced by the FreeImage library.
561
+ """
562
+ # This message log is not cleared/reset, but kept to 256 elements.
563
+ return [m for m in self._messages]
564
+
565
+ def getFIF(self, filename, mode, bb=None):
566
+ """Get the freeimage Format (FIF) from a given filename.
567
+ If mode is 'r', will try to determine the format by reading
568
+ the file, otherwise only the filename is used.
569
+
570
+ This function also tests whether the format supports reading/writing.
571
+ """
572
+ with self as lib:
573
+ # Init
574
+ ftype = -1
575
+ if mode not in "rw":
576
+ raise ValueError('Invalid mode (must be "r" or "w").')
577
+
578
+ # Try getting format from the content. Note that some files
579
+ # do not have a header that allows reading the format from
580
+ # the file.
581
+ if mode == "r":
582
+ if bb is not None:
583
+ fimemory = lib.FreeImage_OpenMemory(ctypes.c_char_p(bb), len(bb))
584
+ ftype = lib.FreeImage_GetFileTypeFromMemory(
585
+ ctypes.c_void_p(fimemory), len(bb)
586
+ )
587
+ lib.FreeImage_CloseMemory(ctypes.c_void_p(fimemory))
588
+ if (ftype == -1) and os.path.isfile(filename):
589
+ ftype = lib.FreeImage_GetFileType(efn(filename), 0)
590
+ # Try getting the format from the extension
591
+ if ftype == -1:
592
+ ftype = lib.FreeImage_GetFIFFromFilename(efn(filename))
593
+
594
+ # Test if ok
595
+ if ftype == -1:
596
+ raise ValueError('Cannot determine format of file "%s"' % filename)
597
+ elif mode == "w" and not lib.FreeImage_FIFSupportsWriting(ftype):
598
+ raise ValueError('Cannot write the format of file "%s"' % filename)
599
+ elif mode == "r" and not lib.FreeImage_FIFSupportsReading(ftype):
600
+ raise ValueError('Cannot read the format of file "%s"' % filename)
601
+ return ftype
602
+
603
+ def create_bitmap(self, filename, ftype, flags=0):
604
+ """create_bitmap(filename, ftype, flags=0)
605
+ Create a wrapped bitmap object.
606
+ """
607
+ return FIBitmap(self, filename, ftype, flags)
608
+
609
+ def create_multipage_bitmap(self, filename, ftype, flags=0):
610
+ """create_multipage_bitmap(filename, ftype, flags=0)
611
+ Create a wrapped multipage bitmap object.
612
+ """
613
+ return FIMultipageBitmap(self, filename, ftype, flags)
614
+
615
+
616
+ class FIBaseBitmap(object):
617
+ def __init__(self, fi, filename, ftype, flags):
618
+ self._fi = fi
619
+ self._filename = filename
620
+ self._ftype = ftype
621
+ self._flags = flags
622
+ self._bitmap = None
623
+ self._close_funcs = []
624
+
625
+ def __del__(self):
626
+ self.close()
627
+
628
+ def close(self):
629
+ if (self._bitmap is not None) and self._close_funcs:
630
+ for close_func in self._close_funcs:
631
+ try:
632
+ with self._fi:
633
+ fun = close_func[0]
634
+ fun(*close_func[1:])
635
+ except Exception: # pragma: no cover
636
+ pass
637
+ self._close_funcs = []
638
+ self._bitmap = None
639
+
640
+ def _set_bitmap(self, bitmap, close_func=None):
641
+ """Function to set the bitmap and specify the function to unload it."""
642
+ if self._bitmap is not None:
643
+ pass # bitmap is converted
644
+ if close_func is None:
645
+ close_func = self._fi.lib.FreeImage_Unload, bitmap
646
+
647
+ self._bitmap = bitmap
648
+ if close_func:
649
+ self._close_funcs.append(close_func)
650
+
651
+ def get_meta_data(self):
652
+ # todo: there is also FreeImage_TagToString, is that useful?
653
+ # and would that work well when reading and then saving?
654
+
655
+ # Create a list of (model_name, number) tuples
656
+ models = [
657
+ (name[5:], number)
658
+ for name, number in METADATA_MODELS.__dict__.items()
659
+ if name.startswith("FIMD_")
660
+ ]
661
+
662
+ # Prepare
663
+ metadata = Dict()
664
+ tag = ctypes.c_void_p()
665
+
666
+ with self._fi as lib:
667
+ # Iterate over all FreeImage meta models
668
+ for model_name, number in models:
669
+ # Find beginning, get search handle
670
+ mdhandle = lib.FreeImage_FindFirstMetadata(
671
+ number, self._bitmap, ctypes.byref(tag)
672
+ )
673
+ mdhandle = ctypes.c_void_p(mdhandle)
674
+ if mdhandle:
675
+ # Iterate over all tags in this model
676
+ more = True
677
+ while more:
678
+ # Get info about tag
679
+ tag_name = lib.FreeImage_GetTagKey(tag).decode("utf-8")
680
+ tag_type = lib.FreeImage_GetTagType(tag)
681
+ byte_size = lib.FreeImage_GetTagLength(tag)
682
+ char_ptr = ctypes.c_char * byte_size
683
+ data = char_ptr.from_address(lib.FreeImage_GetTagValue(tag))
684
+ # Convert in a way compatible with Pypy
685
+ tag_bytes = bytes(bytearray(data))
686
+ # The default value is the raw bytes
687
+ tag_val = tag_bytes
688
+ # Convert to a Python value in the metadata dict
689
+ if tag_type == METADATA_DATATYPE.FIDT_ASCII:
690
+ tag_val = tag_bytes.decode("utf-8", "replace")
691
+ elif tag_type in METADATA_DATATYPE.dtypes:
692
+ dtype = METADATA_DATATYPE.dtypes[tag_type]
693
+ if IS_PYPY and isinstance(dtype, (list, tuple)):
694
+ pass # pragma: no cover - or we get a segfault
695
+ else:
696
+ try:
697
+ tag_val = numpy.frombuffer(
698
+ tag_bytes, dtype=dtype
699
+ ).copy()
700
+ if len(tag_val) == 1:
701
+ tag_val = tag_val[0]
702
+ except Exception: # pragma: no cover
703
+ pass
704
+ # Store data in dict
705
+ subdict = metadata.setdefault(model_name, Dict())
706
+ subdict[tag_name] = tag_val
707
+ # Next
708
+ more = lib.FreeImage_FindNextMetadata(
709
+ mdhandle, ctypes.byref(tag)
710
+ )
711
+
712
+ # Close search handle for current meta model
713
+ lib.FreeImage_FindCloseMetadata(mdhandle)
714
+
715
+ # Done
716
+ return metadata
717
+
718
+ def set_meta_data(self, metadata):
719
+ # Create a dict mapping model_name to number
720
+ models = {}
721
+ for name, number in METADATA_MODELS.__dict__.items():
722
+ if name.startswith("FIMD_"):
723
+ models[name[5:]] = number
724
+
725
+ # Create a mapping from numpy.dtype to METADATA_DATATYPE
726
+ def get_tag_type_number(dtype):
727
+ for number, numpy_dtype in METADATA_DATATYPE.dtypes.items():
728
+ if dtype == numpy_dtype:
729
+ return number
730
+ else:
731
+ return None
732
+
733
+ with self._fi as lib:
734
+ for model_name, subdict in metadata.items():
735
+ # Get model number
736
+ number = models.get(model_name, None)
737
+ if number is None:
738
+ continue # Unknown model, silent ignore
739
+
740
+ for tag_name, tag_val in subdict.items():
741
+ # Create new tag
742
+ tag = lib.FreeImage_CreateTag()
743
+ tag = ctypes.c_void_p(tag)
744
+
745
+ try:
746
+ # Convert Python value to FI type, val
747
+ is_ascii = False
748
+ if isinstance(tag_val, str):
749
+ try:
750
+ tag_bytes = tag_val.encode("ascii")
751
+ is_ascii = True
752
+ except UnicodeError:
753
+ pass
754
+ if is_ascii:
755
+ tag_type = METADATA_DATATYPE.FIDT_ASCII
756
+ tag_count = len(tag_bytes)
757
+ else:
758
+ if not hasattr(tag_val, "dtype"):
759
+ tag_val = numpy.array([tag_val])
760
+ tag_type = get_tag_type_number(tag_val.dtype)
761
+ if tag_type is None:
762
+ logger.warning(
763
+ "imageio.freeimage warning: Could not "
764
+ "determine tag type of %r." % tag_name
765
+ )
766
+ continue
767
+ tag_bytes = tag_val.tobytes()
768
+ tag_count = tag_val.size
769
+ # Set properties
770
+ lib.FreeImage_SetTagKey(tag, tag_name.encode("utf-8"))
771
+ lib.FreeImage_SetTagType(tag, tag_type)
772
+ lib.FreeImage_SetTagCount(tag, tag_count)
773
+ lib.FreeImage_SetTagLength(tag, len(tag_bytes))
774
+ lib.FreeImage_SetTagValue(tag, tag_bytes)
775
+ # Store tag
776
+ tag_key = lib.FreeImage_GetTagKey(tag)
777
+ lib.FreeImage_SetMetadata(number, self._bitmap, tag_key, tag)
778
+
779
+ except Exception as err: # pragma: no cover
780
+ logger.warning(
781
+ "imagio.freeimage warning: Could not set tag "
782
+ "%r: %s, %s"
783
+ % (tag_name, self._fi._get_error_message(), str(err))
784
+ )
785
+ finally:
786
+ lib.FreeImage_DeleteTag(tag)
787
+
788
+
789
+ class FIBitmap(FIBaseBitmap):
790
+ """Wrapper for the FI bitmap object."""
791
+
792
+ def allocate(self, array):
793
+ # Prepare array
794
+ assert isinstance(array, numpy.ndarray)
795
+ shape = array.shape
796
+ dtype = array.dtype
797
+
798
+ # Get shape and channel info
799
+ r, c = shape[:2]
800
+ if len(shape) == 2:
801
+ n_channels = 1
802
+ elif len(shape) == 3:
803
+ n_channels = shape[2]
804
+ else:
805
+ n_channels = shape[0]
806
+
807
+ # Get fi_type
808
+ try:
809
+ fi_type = FI_TYPES.fi_types[(dtype.type, n_channels)]
810
+ self._fi_type = fi_type
811
+ except KeyError:
812
+ raise ValueError("Cannot write arrays of given type and shape.")
813
+
814
+ # Allocate bitmap
815
+ with self._fi as lib:
816
+ bpp = 8 * dtype.itemsize * n_channels
817
+ bitmap = lib.FreeImage_AllocateT(fi_type, c, r, bpp, 0, 0, 0)
818
+ bitmap = ctypes.c_void_p(bitmap)
819
+
820
+ # Check and store
821
+ if not bitmap: # pragma: no cover
822
+ raise RuntimeError(
823
+ "Could not allocate bitmap for storage: %s"
824
+ % self._fi._get_error_message()
825
+ )
826
+ self._set_bitmap(bitmap, (lib.FreeImage_Unload, bitmap))
827
+
828
+ def load_from_filename(self, filename=None):
829
+ if filename is None:
830
+ filename = self._filename
831
+
832
+ with self._fi as lib:
833
+ # Create bitmap
834
+ bitmap = lib.FreeImage_Load(self._ftype, efn(filename), self._flags)
835
+ bitmap = ctypes.c_void_p(bitmap)
836
+
837
+ # Check and store
838
+ if not bitmap: # pragma: no cover
839
+ raise ValueError(
840
+ 'Could not load bitmap "%s": %s'
841
+ % (self._filename, self._fi._get_error_message())
842
+ )
843
+ self._set_bitmap(bitmap, (lib.FreeImage_Unload, bitmap))
844
+
845
+ # def load_from_bytes(self, bb):
846
+ # with self._fi as lib:
847
+ # # Create bitmap
848
+ # fimemory = lib.FreeImage_OpenMemory(
849
+ # ctypes.c_char_p(bb), len(bb))
850
+ # bitmap = lib.FreeImage_LoadFromMemory(
851
+ # self._ftype, ctypes.c_void_p(fimemory), self._flags)
852
+ # bitmap = ctypes.c_void_p(bitmap)
853
+ # lib.FreeImage_CloseMemory(ctypes.c_void_p(fimemory))
854
+ #
855
+ # # Check
856
+ # if not bitmap:
857
+ # raise ValueError('Could not load bitmap "%s": %s'
858
+ # % (self._filename, self._fi._get_error_message()))
859
+ # else:
860
+ # self._set_bitmap(bitmap, (lib.FreeImage_Unload, bitmap))
861
+
862
+ def save_to_filename(self, filename=None):
863
+ if filename is None:
864
+ filename = self._filename
865
+
866
+ ftype = self._ftype
867
+ bitmap = self._bitmap
868
+ fi_type = self._fi_type # element type
869
+
870
+ with self._fi as lib:
871
+ # Check if can write
872
+ if fi_type == FI_TYPES.FIT_BITMAP:
873
+ can_write = lib.FreeImage_FIFSupportsExportBPP(
874
+ ftype, lib.FreeImage_GetBPP(bitmap)
875
+ )
876
+ else:
877
+ can_write = lib.FreeImage_FIFSupportsExportType(ftype, fi_type)
878
+ if not can_write:
879
+ raise TypeError("Cannot save image of this format to this file type")
880
+
881
+ # Save to file
882
+ res = lib.FreeImage_Save(ftype, bitmap, efn(filename), self._flags)
883
+ # Check
884
+ if res is None: # pragma: no cover, we do so many checks, this is rare
885
+ raise RuntimeError(
886
+ f"Could not save file `{self._filename}`: {self._fi._get_error_message()}"
887
+ )
888
+
889
+ # def save_to_bytes(self):
890
+ # ftype = self._ftype
891
+ # bitmap = self._bitmap
892
+ # fi_type = self._fi_type # element type
893
+ #
894
+ # with self._fi as lib:
895
+ # # Check if can write
896
+ # if fi_type == FI_TYPES.FIT_BITMAP:
897
+ # can_write = lib.FreeImage_FIFSupportsExportBPP(ftype,
898
+ # lib.FreeImage_GetBPP(bitmap))
899
+ # else:
900
+ # can_write = lib.FreeImage_FIFSupportsExportType(ftype, fi_type)
901
+ # if not can_write:
902
+ # raise TypeError('Cannot save image of this format '
903
+ # 'to this file type')
904
+ #
905
+ # # Extract the bytes
906
+ # fimemory = lib.FreeImage_OpenMemory(0, 0)
907
+ # res = lib.FreeImage_SaveToMemory(ftype, bitmap,
908
+ # ctypes.c_void_p(fimemory),
909
+ # self._flags)
910
+ # if res:
911
+ # N = lib.FreeImage_TellMemory(ctypes.c_void_p(fimemory))
912
+ # result = ctypes.create_string_buffer(N)
913
+ # lib.FreeImage_SeekMemory(ctypes.c_void_p(fimemory), 0)
914
+ # lib.FreeImage_ReadMemory(result, 1, N, ctypes.c_void_p(fimemory))
915
+ # result = result.raw
916
+ # lib.FreeImage_CloseMemory(ctypes.c_void_p(fimemory))
917
+ #
918
+ # # Check
919
+ # if not res:
920
+ # raise RuntimeError('Could not save file "%s": %s'
921
+ # % (self._filename, self._fi._get_error_message()))
922
+ #
923
+ # # Done
924
+ # return result
925
+
926
+ def get_image_data(self):
927
+ dtype, shape, bpp = self._get_type_and_shape()
928
+ array = self._wrap_bitmap_bits_in_array(shape, dtype, False)
929
+ with self._fi as lib:
930
+ isle = lib.FreeImage_IsLittleEndian()
931
+
932
+ # swizzle the color components and flip the scanlines to go from
933
+ # FreeImage's BGR[A] and upside-down internal memory format to
934
+ # something more normal
935
+ def n(arr):
936
+ # return arr[..., ::-1].T # Does not work on numpypy yet
937
+ if arr.ndim == 1: # pragma: no cover
938
+ return arr[::-1].T
939
+ elif arr.ndim == 2: # Always the case here ...
940
+ return arr[:, ::-1].T
941
+ elif arr.ndim == 3: # pragma: no cover
942
+ return arr[:, :, ::-1].T
943
+ elif arr.ndim == 4: # pragma: no cover
944
+ return arr[:, :, :, ::-1].T
945
+
946
+ if len(shape) == 3 and isle and dtype.type == numpy.uint8:
947
+ b = n(array[0])
948
+ g = n(array[1])
949
+ r = n(array[2])
950
+ if shape[0] == 3:
951
+ return numpy.dstack((r, g, b))
952
+ elif shape[0] == 4:
953
+ a = n(array[3])
954
+ return numpy.dstack((r, g, b, a))
955
+ else: # pragma: no cover - we check this earlier
956
+ raise ValueError("Cannot handle images of shape %s" % shape)
957
+
958
+ # We need to copy because array does *not* own its memory
959
+ # after bitmap is freed.
960
+ a = n(array).copy()
961
+ return a
962
+
963
+ def set_image_data(self, array):
964
+ # Prepare array
965
+ assert isinstance(array, numpy.ndarray)
966
+ shape = array.shape
967
+ dtype = array.dtype
968
+ with self._fi as lib:
969
+ isle = lib.FreeImage_IsLittleEndian()
970
+
971
+ # Calculate shape and channels
972
+ r, c = shape[:2]
973
+ if len(shape) == 2:
974
+ n_channels = 1
975
+ w_shape = (c, r)
976
+ elif len(shape) == 3:
977
+ n_channels = shape[2]
978
+ w_shape = (n_channels, c, r)
979
+ else:
980
+ n_channels = shape[0]
981
+
982
+ def n(arr): # normalise to freeimage's in-memory format
983
+ return arr[::-1].T
984
+
985
+ wrapped_array = self._wrap_bitmap_bits_in_array(w_shape, dtype, True)
986
+ # swizzle the color components and flip the scanlines to go to
987
+ # FreeImage's BGR[A] and upside-down internal memory format
988
+ # The BGR[A] order is only used for 8bits per channel images
989
+ # on little endian machines. For everything else RGB[A] is
990
+ # used.
991
+ if len(shape) == 3 and isle and dtype.type == numpy.uint8:
992
+ R = array[:, :, 0]
993
+ G = array[:, :, 1]
994
+ B = array[:, :, 2]
995
+ wrapped_array[0] = n(B)
996
+ wrapped_array[1] = n(G)
997
+ wrapped_array[2] = n(R)
998
+ if shape[2] == 4:
999
+ A = array[:, :, 3]
1000
+ wrapped_array[3] = n(A)
1001
+ else:
1002
+ wrapped_array[:] = n(array)
1003
+ if self._need_finish:
1004
+ self._finish_wrapped_array(wrapped_array)
1005
+
1006
+ if len(shape) == 2 and dtype.type == numpy.uint8:
1007
+ with self._fi as lib:
1008
+ palette = lib.FreeImage_GetPalette(self._bitmap)
1009
+ palette = ctypes.c_void_p(palette)
1010
+ if not palette:
1011
+ raise RuntimeError("Could not get image palette")
1012
+ try:
1013
+ palette_data = GREY_PALETTE.ctypes.data
1014
+ except Exception: # pragma: no cover - IS_PYPY
1015
+ palette_data = GREY_PALETTE.__array_interface__["data"][0]
1016
+ ctypes.memmove(palette, palette_data, 1024)
1017
+
1018
+ def _wrap_bitmap_bits_in_array(self, shape, dtype, save):
1019
+ """Return an ndarray view on the data in a FreeImage bitmap. Only
1020
+ valid for as long as the bitmap is loaded (if single page) / locked
1021
+ in memory (if multipage). This is used in loading data, but
1022
+ also during saving, to prepare a strided numpy array buffer.
1023
+
1024
+ """
1025
+ # Get bitmap info
1026
+ with self._fi as lib:
1027
+ pitch = lib.FreeImage_GetPitch(self._bitmap)
1028
+ bits = lib.FreeImage_GetBits(self._bitmap)
1029
+
1030
+ # Get more info
1031
+ height = shape[-1]
1032
+ byte_size = height * pitch
1033
+ itemsize = dtype.itemsize
1034
+
1035
+ # Get strides
1036
+ if len(shape) == 3:
1037
+ strides = (itemsize, shape[0] * itemsize, pitch)
1038
+ else:
1039
+ strides = (itemsize, pitch)
1040
+
1041
+ # Create numpy array and return
1042
+ data = (ctypes.c_char * byte_size).from_address(bits)
1043
+ try:
1044
+ self._need_finish = False
1045
+ if TEST_NUMPY_NO_STRIDES:
1046
+ raise NotImplementedError()
1047
+ return numpy.ndarray(shape, dtype=dtype, buffer=data, strides=strides)
1048
+ except NotImplementedError:
1049
+ # IS_PYPY - not very efficient. We create a C-contiguous
1050
+ # numpy array (because pypy does not support Fortran-order)
1051
+ # and shape it such that the rest of the code can remain.
1052
+ if save:
1053
+ self._need_finish = True # Flag to use _finish_wrapped_array
1054
+ return numpy.zeros(shape, dtype=dtype)
1055
+ else:
1056
+ bb = bytes(bytearray(data))
1057
+ array = numpy.frombuffer(bb, dtype=dtype).copy()
1058
+ # Deal with strides
1059
+ if len(shape) == 3:
1060
+ array.shape = shape[2], strides[-1] // shape[0], shape[0]
1061
+ array2 = array[: shape[2], : shape[1], : shape[0]]
1062
+ array = numpy.zeros(shape, dtype=array.dtype)
1063
+ for i in range(shape[0]):
1064
+ array[i] = array2[:, :, i].T
1065
+ else:
1066
+ array.shape = shape[1], strides[-1]
1067
+ array = array[: shape[1], : shape[0]].T
1068
+ return array
1069
+
1070
+ def _finish_wrapped_array(self, array): # IS_PYPY
1071
+ """Hardcore way to inject numpy array in bitmap."""
1072
+ # Get bitmap info
1073
+ with self._fi as lib:
1074
+ pitch = lib.FreeImage_GetPitch(self._bitmap)
1075
+ bits = lib.FreeImage_GetBits(self._bitmap)
1076
+ bpp = lib.FreeImage_GetBPP(self._bitmap)
1077
+ # Get channels and realwidth
1078
+ nchannels = bpp // 8 // array.itemsize
1079
+ realwidth = pitch // nchannels
1080
+ # Apply padding for pitch if necessary
1081
+ extra = realwidth - array.shape[-2]
1082
+ assert 0 <= extra < 10
1083
+ # Make sort of Fortran, also take padding (i.e. pitch) into account
1084
+ newshape = array.shape[-1], realwidth, nchannels
1085
+ array2 = numpy.zeros(newshape, array.dtype)
1086
+ if nchannels == 1:
1087
+ array2[:, : array.shape[-2], 0] = array.T
1088
+ else:
1089
+ for i in range(nchannels):
1090
+ array2[:, : array.shape[-2], i] = array[i, :, :].T
1091
+ # copy data
1092
+ data_ptr = array2.__array_interface__["data"][0]
1093
+ ctypes.memmove(bits, data_ptr, array2.nbytes)
1094
+ del array2
1095
+
1096
+ def _get_type_and_shape(self):
1097
+ bitmap = self._bitmap
1098
+
1099
+ # Get info on bitmap
1100
+ with self._fi as lib:
1101
+ w = lib.FreeImage_GetWidth(bitmap)
1102
+ h = lib.FreeImage_GetHeight(bitmap)
1103
+ self._fi_type = fi_type = lib.FreeImage_GetImageType(bitmap)
1104
+ if not fi_type:
1105
+ raise ValueError("Unknown image pixel type")
1106
+
1107
+ # Determine required props for numpy array
1108
+ bpp = None
1109
+ dtype = FI_TYPES.dtypes[fi_type]
1110
+
1111
+ if fi_type == FI_TYPES.FIT_BITMAP:
1112
+ with self._fi as lib:
1113
+ bpp = lib.FreeImage_GetBPP(bitmap)
1114
+ has_pallette = lib.FreeImage_GetColorsUsed(bitmap)
1115
+ if has_pallette:
1116
+ # Examine the palette. If it is grayscale, we return as such
1117
+ if has_pallette == 256:
1118
+ palette = lib.FreeImage_GetPalette(bitmap)
1119
+ palette = ctypes.c_void_p(palette)
1120
+ p = (ctypes.c_uint8 * (256 * 4)).from_address(palette.value)
1121
+ p = numpy.frombuffer(p, numpy.uint32).copy()
1122
+ if (GREY_PALETTE == p).all():
1123
+ extra_dims = []
1124
+ return numpy.dtype(dtype), extra_dims + [w, h], bpp
1125
+ # Convert bitmap and call this method again
1126
+ newbitmap = lib.FreeImage_ConvertTo32Bits(bitmap)
1127
+ newbitmap = ctypes.c_void_p(newbitmap)
1128
+ self._set_bitmap(newbitmap)
1129
+ return self._get_type_and_shape()
1130
+ elif bpp == 8:
1131
+ extra_dims = []
1132
+ elif bpp == 24:
1133
+ extra_dims = [3]
1134
+ elif bpp == 32:
1135
+ extra_dims = [4]
1136
+ else: # pragma: no cover
1137
+ # raise ValueError('Cannot convert %d BPP bitmap' % bpp)
1138
+ # Convert bitmap and call this method again
1139
+ newbitmap = lib.FreeImage_ConvertTo32Bits(bitmap)
1140
+ newbitmap = ctypes.c_void_p(newbitmap)
1141
+ self._set_bitmap(newbitmap)
1142
+ return self._get_type_and_shape()
1143
+ else:
1144
+ extra_dims = FI_TYPES.extra_dims[fi_type]
1145
+
1146
+ # Return dtype and shape
1147
+ return numpy.dtype(dtype), extra_dims + [w, h], bpp
1148
+
1149
+ def quantize(self, quantizer=0, palettesize=256):
1150
+ """Quantize the bitmap to make it 8-bit (paletted). Returns a new
1151
+ FIBitmap object.
1152
+ Only for 24 bit images.
1153
+ """
1154
+ with self._fi as lib:
1155
+ # New bitmap
1156
+ bitmap = lib.FreeImage_ColorQuantizeEx(
1157
+ self._bitmap, quantizer, palettesize, 0, None
1158
+ )
1159
+ bitmap = ctypes.c_void_p(bitmap)
1160
+
1161
+ # Check and return
1162
+ if not bitmap:
1163
+ raise ValueError(
1164
+ 'Could not quantize bitmap "%s": %s'
1165
+ % (self._filename, self._fi._get_error_message())
1166
+ )
1167
+
1168
+ new = FIBitmap(self._fi, self._filename, self._ftype, self._flags)
1169
+ new._set_bitmap(bitmap, (lib.FreeImage_Unload, bitmap))
1170
+ new._fi_type = self._fi_type
1171
+ return new
1172
+
1173
+
1174
+ # def convert_to_32bit(self):
1175
+ # """ Convert to 32bit image.
1176
+ # """
1177
+ # with self._fi as lib:
1178
+ # # New bitmap
1179
+ # bitmap = lib.FreeImage_ConvertTo32Bits(self._bitmap)
1180
+ # bitmap = ctypes.c_void_p(bitmap)
1181
+ #
1182
+ # # Check and return
1183
+ # if not bitmap:
1184
+ # raise ValueError('Could not convert bitmap to 32bit "%s": %s' %
1185
+ # (self._filename,
1186
+ # self._fi._get_error_message()))
1187
+ # else:
1188
+ # new = FIBitmap(self._fi, self._filename, self._ftype,
1189
+ # self._flags)
1190
+ # new._set_bitmap(bitmap, (lib.FreeImage_Unload, bitmap))
1191
+ # new._fi_type = self._fi_type
1192
+ # return new
1193
+
1194
+
1195
+ class FIMultipageBitmap(FIBaseBitmap):
1196
+ """Wrapper for the multipage FI bitmap object."""
1197
+
1198
+ def load_from_filename(self, filename=None):
1199
+ if filename is None: # pragma: no cover
1200
+ filename = self._filename
1201
+
1202
+ # Prepare
1203
+ create_new = False
1204
+ read_only = True
1205
+ keep_cache_in_memory = False
1206
+
1207
+ # Try opening
1208
+ with self._fi as lib:
1209
+ # Create bitmap
1210
+ multibitmap = lib.FreeImage_OpenMultiBitmap(
1211
+ self._ftype,
1212
+ efn(filename),
1213
+ create_new,
1214
+ read_only,
1215
+ keep_cache_in_memory,
1216
+ self._flags,
1217
+ )
1218
+ multibitmap = ctypes.c_void_p(multibitmap)
1219
+
1220
+ # Check
1221
+ if not multibitmap: # pragma: no cover
1222
+ err = self._fi._get_error_message()
1223
+ raise ValueError(
1224
+ 'Could not open file "%s" as multi-image: %s'
1225
+ % (self._filename, err)
1226
+ )
1227
+ self._set_bitmap(multibitmap, (lib.FreeImage_CloseMultiBitmap, multibitmap))
1228
+
1229
+ # def load_from_bytes(self, bb):
1230
+ # with self._fi as lib:
1231
+ # # Create bitmap
1232
+ # fimemory = lib.FreeImage_OpenMemory(
1233
+ # ctypes.c_char_p(bb), len(bb))
1234
+ # multibitmap = lib.FreeImage_LoadMultiBitmapFromMemory(
1235
+ # self._ftype, ctypes.c_void_p(fimemory), self._flags)
1236
+ # multibitmap = ctypes.c_void_p(multibitmap)
1237
+ # #lib.FreeImage_CloseMemory(ctypes.c_void_p(fimemory))
1238
+ # self._mem = fimemory
1239
+ # self._bytes = bb
1240
+ # # Check
1241
+ # if not multibitmap:
1242
+ # raise ValueError('Could not load multibitmap "%s": %s'
1243
+ # % (self._filename, self._fi._get_error_message()))
1244
+ # else:
1245
+ # self._set_bitmap(multibitmap,
1246
+ # (lib.FreeImage_CloseMultiBitmap, multibitmap))
1247
+
1248
+ def save_to_filename(self, filename=None):
1249
+ if filename is None: # pragma: no cover
1250
+ filename = self._filename
1251
+
1252
+ # Prepare
1253
+ create_new = True
1254
+ read_only = False
1255
+ keep_cache_in_memory = False
1256
+
1257
+ # Open the file
1258
+ # todo: Set flags at close func
1259
+ with self._fi as lib:
1260
+ multibitmap = lib.FreeImage_OpenMultiBitmap(
1261
+ self._ftype,
1262
+ efn(filename),
1263
+ create_new,
1264
+ read_only,
1265
+ keep_cache_in_memory,
1266
+ 0,
1267
+ )
1268
+ multibitmap = ctypes.c_void_p(multibitmap)
1269
+
1270
+ # Check
1271
+ if not multibitmap: # pragma: no cover
1272
+ msg = 'Could not open file "%s" for writing multi-image: %s' % (
1273
+ self._filename,
1274
+ self._fi._get_error_message(),
1275
+ )
1276
+ raise ValueError(msg)
1277
+ self._set_bitmap(multibitmap, (lib.FreeImage_CloseMultiBitmap, multibitmap))
1278
+
1279
+ def __len__(self):
1280
+ with self._fi as lib:
1281
+ return lib.FreeImage_GetPageCount(self._bitmap)
1282
+
1283
+ def get_page(self, index):
1284
+ """Return the sub-bitmap for the given page index.
1285
+ Please close the returned bitmap when done.
1286
+ """
1287
+ with self._fi as lib:
1288
+ # Create low-level bitmap in freeimage
1289
+ bitmap = lib.FreeImage_LockPage(self._bitmap, index)
1290
+ bitmap = ctypes.c_void_p(bitmap)
1291
+ if not bitmap: # pragma: no cover
1292
+ raise ValueError(
1293
+ "Could not open sub-image %i in %r: %s"
1294
+ % (index, self._filename, self._fi._get_error_message())
1295
+ )
1296
+
1297
+ # Get bitmap object to wrap this bitmap
1298
+ bm = FIBitmap(self._fi, self._filename, self._ftype, self._flags)
1299
+ bm._set_bitmap(
1300
+ bitmap, (lib.FreeImage_UnlockPage, self._bitmap, bitmap, False)
1301
+ )
1302
+ return bm
1303
+
1304
+ def append_bitmap(self, bitmap):
1305
+ """Add a sub-bitmap to the multi-page bitmap."""
1306
+ with self._fi as lib:
1307
+ # no return value
1308
+ lib.FreeImage_AppendPage(self._bitmap, bitmap._bitmap)
1309
+
1310
+
1311
+ # Create instance
1312
+ fi = Freeimage()
minigpt2/lib/python3.10/site-packages/imageio/plugins/_tifffile.py ADDED
The diff for this file is too large to render. See raw diff
 
minigpt2/lib/python3.10/site-packages/imageio/plugins/bsdf.py ADDED
@@ -0,0 +1,324 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # imageio is distributed under the terms of the (new) BSD License.
3
+
4
+ """ Read/Write BSDF files.
5
+
6
+ Backend Library: internal
7
+
8
+ The BSDF format enables reading and writing of image data in the
9
+ BSDF serialization format. This format allows storage of images, volumes,
10
+ and series thereof. Data can be of any numeric data type, and can
11
+ optionally be compressed. Each image/volume can have associated
12
+ meta data, which can consist of any data type supported by BSDF.
13
+
14
+ By default, image data is lazily loaded; the actual image data is
15
+ not read until it is requested. This allows storing multiple images
16
+ in a single file and still have fast access to individual images.
17
+ Alternatively, a series of images can be read in streaming mode, reading
18
+ images as they are read (e.g. from http).
19
+
20
+ BSDF is a simple generic binary format. It is easy to extend and there
21
+ are standard extension definitions for 2D and 3D image data.
22
+ Read more at http://bsdf.io.
23
+
24
+
25
+ Parameters
26
+ ----------
27
+ random_access : bool
28
+ Whether individual images in the file can be read in random order.
29
+ Defaults to True for normal files, and to False when reading from HTTP.
30
+ If False, the file is read in "streaming mode", allowing reading
31
+ files as they are read, but without support for "rewinding".
32
+ Note that setting this to True when reading from HTTP, the whole file
33
+ is read upon opening it (since lazy loading is not possible over HTTP).
34
+
35
+ compression : int
36
+ Use ``0`` or "no" for no compression, ``1`` or "zlib" for Zlib
37
+ compression (same as zip files and PNG), and ``2`` or "bz2" for Bz2
38
+ compression (more compact but slower). Default 1 (zlib).
39
+ Note that some BSDF implementations may not support compression
40
+ (e.g. JavaScript).
41
+
42
+ """
43
+
44
+ import numpy as np
45
+
46
+ from ..core import Format
47
+
48
+
49
+ def get_bsdf_serializer(options):
50
+ from . import _bsdf as bsdf
51
+
52
+ class NDArrayExtension(bsdf.Extension):
53
+ """Copy of BSDF's NDArrayExtension but deal with lazy blobs."""
54
+
55
+ name = "ndarray"
56
+ cls = np.ndarray
57
+
58
+ def encode(self, s, v):
59
+ return dict(shape=v.shape, dtype=str(v.dtype), data=v.tobytes())
60
+
61
+ def decode(self, s, v):
62
+ return v # return as dict, because of lazy blobs, decode in Image
63
+
64
+ class ImageExtension(bsdf.Extension):
65
+ """We implement two extensions that trigger on the Image classes."""
66
+
67
+ def encode(self, s, v):
68
+ return dict(array=v.array, meta=v.meta)
69
+
70
+ def decode(self, s, v):
71
+ return Image(v["array"], v["meta"])
72
+
73
+ class Image2DExtension(ImageExtension):
74
+ name = "image2d"
75
+ cls = Image2D
76
+
77
+ class Image3DExtension(ImageExtension):
78
+ name = "image3d"
79
+ cls = Image3D
80
+
81
+ exts = [NDArrayExtension, Image2DExtension, Image3DExtension]
82
+ serializer = bsdf.BsdfSerializer(exts, **options)
83
+
84
+ return bsdf, serializer
85
+
86
+
87
+ class Image:
88
+ """Class in which we wrap the array and meta data. By using an extension
89
+ we can make BSDF trigger on these classes and thus encode the images.
90
+ as actual images.
91
+ """
92
+
93
+ def __init__(self, array, meta):
94
+ self.array = array
95
+ self.meta = meta
96
+
97
+ def get_array(self):
98
+ if not isinstance(self.array, np.ndarray):
99
+ v = self.array
100
+ blob = v["data"]
101
+ if not isinstance(blob, bytes): # then it's a lazy bsdf.Blob
102
+ blob = blob.get_bytes()
103
+ self.array = np.frombuffer(blob, dtype=v["dtype"])
104
+ self.array.shape = v["shape"]
105
+ return self.array
106
+
107
+ def get_meta(self):
108
+ return self.meta
109
+
110
+
111
+ class Image2D(Image):
112
+ pass
113
+
114
+
115
+ class Image3D(Image):
116
+ pass
117
+
118
+
119
+ class BsdfFormat(Format):
120
+ """The BSDF format enables reading and writing of image data in the
121
+ BSDF serialization format. This format allows storage of images, volumes,
122
+ and series thereof. Data can be of any numeric data type, and can
123
+ optionally be compressed. Each image/volume can have associated
124
+ meta data, which can consist of any data type supported by BSDF.
125
+
126
+ By default, image data is lazily loaded; the actual image data is
127
+ not read until it is requested. This allows storing multiple images
128
+ in a single file and still have fast access to individual images.
129
+ Alternatively, a series of images can be read in streaming mode, reading
130
+ images as they are read (e.g. from http).
131
+
132
+ BSDF is a simple generic binary format. It is easy to extend and there
133
+ are standard extension definitions for 2D and 3D image data.
134
+ Read more at http://bsdf.io.
135
+
136
+ Parameters for reading
137
+ ----------------------
138
+ random_access : bool
139
+ Whether individual images in the file can be read in random order.
140
+ Defaults to True for normal files, and to False when reading from HTTP.
141
+ If False, the file is read in "streaming mode", allowing reading
142
+ files as they are read, but without support for "rewinding".
143
+ Note that setting this to True when reading from HTTP, the whole file
144
+ is read upon opening it (since lazy loading is not possible over HTTP).
145
+
146
+ Parameters for saving
147
+ ---------------------
148
+ compression : {0, 1, 2}
149
+ Use ``0`` or "no" for no compression, ``1`` or "zlib" for Zlib
150
+ compression (same as zip files and PNG), and ``2`` or "bz2" for Bz2
151
+ compression (more compact but slower). Default 1 (zlib).
152
+ Note that some BSDF implementations may not support compression
153
+ (e.g. JavaScript).
154
+
155
+ """
156
+
157
+ def _can_read(self, request):
158
+ if request.mode[1] in (self.modes + "?"):
159
+ # if request.extension in self.extensions:
160
+ # return True
161
+ if request.firstbytes.startswith(b"BSDF"):
162
+ return True
163
+
164
+ def _can_write(self, request):
165
+ if request.mode[1] in (self.modes + "?"):
166
+ if request.extension in self.extensions:
167
+ return True
168
+
169
+ # -- reader
170
+
171
+ class Reader(Format.Reader):
172
+ def _open(self, random_access=None):
173
+ # Validate - we need a BSDF file consisting of a list of images
174
+ # The list is typically a stream, but does not have to be.
175
+ assert self.request.firstbytes[:4] == b"BSDF", "Not a BSDF file"
176
+ # self.request.firstbytes[5:6] == major and minor version
177
+ if not (
178
+ self.request.firstbytes[6:15] == b"M\x07image2D"
179
+ or self.request.firstbytes[6:15] == b"M\x07image3D"
180
+ or self.request.firstbytes[6:7] == b"l"
181
+ ):
182
+ pass # Actually, follow a more duck-type approach ...
183
+ # raise RuntimeError('BSDF file does not look like an '
184
+ # 'image container.')
185
+ # Set options. If we think that seeking is allowed, we lazily load
186
+ # blobs, and set streaming to False (i.e. the whole file is read,
187
+ # but we skip over binary blobs), so that we subsequently allow
188
+ # random access to the images.
189
+ # If seeking is not allowed (e.g. with a http request), we cannot
190
+ # lazily load blobs, but we can still load streaming from the web.
191
+ options = {}
192
+ if self.request.filename.startswith(("http://", "https://")):
193
+ ra = False if random_access is None else bool(random_access)
194
+ options["lazy_blob"] = False # Because we cannot seek now
195
+ options["load_streaming"] = not ra # Load as a stream?
196
+ else:
197
+ ra = True if random_access is None else bool(random_access)
198
+ options["lazy_blob"] = ra # Don't read data until needed
199
+ options["load_streaming"] = not ra
200
+
201
+ file = self.request.get_file()
202
+ bsdf, self._serializer = get_bsdf_serializer(options)
203
+ self._stream = self._serializer.load(file)
204
+ # Another validation
205
+ if (
206
+ isinstance(self._stream, dict)
207
+ and "meta" in self._stream
208
+ and "array" in self._stream
209
+ ):
210
+ self._stream = Image(self._stream["array"], self._stream["meta"])
211
+ if not isinstance(self._stream, (Image, list, bsdf.ListStream)):
212
+ raise RuntimeError(
213
+ "BSDF file does not look seem to have an " "image container."
214
+ )
215
+
216
+ def _close(self):
217
+ pass
218
+
219
+ def _get_length(self):
220
+ if isinstance(self._stream, Image):
221
+ return 1
222
+ elif isinstance(self._stream, list):
223
+ return len(self._stream)
224
+ elif self._stream.count < 0:
225
+ return np.inf
226
+ return self._stream.count
227
+
228
+ def _get_data(self, index):
229
+ # Validate
230
+ if index < 0 or index >= self.get_length():
231
+ raise IndexError(
232
+ "Image index %i not in [0 %i]." % (index, self.get_length())
233
+ )
234
+ # Get Image object
235
+ if isinstance(self._stream, Image):
236
+ image_ob = self._stream # singleton
237
+ elif isinstance(self._stream, list):
238
+ # Easy when we have random access
239
+ image_ob = self._stream[index]
240
+ else:
241
+ # For streaming, we need to skip over frames
242
+ if index < self._stream.index:
243
+ raise IndexError(
244
+ "BSDF file is being read in streaming "
245
+ "mode, thus does not allow rewinding."
246
+ )
247
+ while index > self._stream.index:
248
+ self._stream.next()
249
+ image_ob = self._stream.next() # Can raise StopIteration
250
+ # Is this an image?
251
+ if (
252
+ isinstance(image_ob, dict)
253
+ and "meta" in image_ob
254
+ and "array" in image_ob
255
+ ):
256
+ image_ob = Image(image_ob["array"], image_ob["meta"])
257
+ if isinstance(image_ob, Image):
258
+ # Return as array (if we have lazy blobs, they are read now)
259
+ return image_ob.get_array(), image_ob.get_meta()
260
+ else:
261
+ r = repr(image_ob)
262
+ r = r if len(r) < 200 else r[:197] + "..."
263
+ raise RuntimeError("BSDF file contains non-image " + r)
264
+
265
+ def _get_meta_data(self, index): # pragma: no cover
266
+ return {} # This format does not support global meta data
267
+
268
+ # -- writer
269
+
270
+ class Writer(Format.Writer):
271
+ def _open(self, compression=1):
272
+ options = {"compression": compression}
273
+ bsdf, self._serializer = get_bsdf_serializer(options)
274
+ if self.request.mode[1] in "iv":
275
+ self._stream = None # Singleton image
276
+ self._written = False
277
+ else:
278
+ # Series (stream) of images
279
+ file = self.request.get_file()
280
+ self._stream = bsdf.ListStream()
281
+ self._serializer.save(file, self._stream)
282
+
283
+ def _close(self):
284
+ # We close the stream here, which will mark the number of written
285
+ # elements. If we would not close it, the file would be fine, it's
286
+ # just that upon reading it would not be known how many items are
287
+ # in there.
288
+ if self._stream is not None:
289
+ self._stream.close(False) # False says "keep this a stream"
290
+
291
+ def _append_data(self, im, meta):
292
+ # Determine dimension
293
+ ndim = None
294
+ if self.request.mode[1] in "iI":
295
+ ndim = 2
296
+ elif self.request.mode[1] in "vV":
297
+ ndim = 3
298
+ else:
299
+ ndim = 3 # Make an educated guess
300
+ if im.ndim == 2 or (im.ndim == 3 and im.shape[-1] <= 4):
301
+ ndim = 2
302
+ # Validate shape
303
+ assert ndim in (2, 3)
304
+ if ndim == 2:
305
+ assert im.ndim == 2 or (im.ndim == 3 and im.shape[-1] <= 4)
306
+ else:
307
+ assert im.ndim == 3 or (im.ndim == 4 and im.shape[-1] <= 4)
308
+ # Wrap data and meta data in our special class that will trigger
309
+ # the BSDF image2D or image3D extension.
310
+ if ndim == 2:
311
+ ob = Image2D(im, meta)
312
+ else:
313
+ ob = Image3D(im, meta)
314
+ # Write directly or to stream
315
+ if self._stream is None:
316
+ assert not self._written, "Cannot write singleton image twice"
317
+ self._written = True
318
+ file = self.request.get_file()
319
+ self._serializer.save(file, ob)
320
+ else:
321
+ self._stream.append(ob)
322
+
323
+ def set_meta_data(self, meta): # pragma: no cover
324
+ raise RuntimeError("The BSDF format only supports " "per-image meta data.")
minigpt2/lib/python3.10/site-packages/imageio/plugins/dicom.py ADDED
@@ -0,0 +1,333 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # imageio is distributed under the terms of the (new) BSD License.
3
+
4
+ """Read DICOM files.
5
+
6
+ Backend Library: internal
7
+
8
+ A format for reading DICOM images: a common format used to store
9
+ medical image data, such as X-ray, CT and MRI.
10
+
11
+ This format borrows some code (and ideas) from the pydicom project. However,
12
+ only a predefined subset of tags are extracted from the file. This allows
13
+ for great simplifications allowing us to make a stand-alone reader, and
14
+ also results in a much faster read time.
15
+
16
+ By default, only uncompressed and deflated transfer syntaxes are supported.
17
+ If gdcm or dcmtk is installed, these will be used to automatically convert
18
+ the data. See https://github.com/malaterre/GDCM/releases for installing GDCM.
19
+
20
+ This format provides functionality to group images of the same
21
+ series together, thus extracting volumes (and multiple volumes).
22
+ Using volread will attempt to yield a volume. If multiple volumes
23
+ are present, the first one is given. Using mimread will simply yield
24
+ all images in the given directory (not taking series into account).
25
+
26
+ Parameters
27
+ ----------
28
+ progress : {True, False, BaseProgressIndicator}
29
+ Whether to show progress when reading from multiple files.
30
+ Default True. By passing an object that inherits from
31
+ BaseProgressIndicator, the way in which progress is reported
32
+ can be costumized.
33
+
34
+ """
35
+
36
+ # todo: Use pydicom:
37
+ # * Note: is not py3k ready yet
38
+ # * Allow reading the full meta info
39
+ # I think we can more or less replace the SimpleDicomReader with a
40
+ # pydicom.Dataset For series, only ned to read the full info from one
41
+ # file: speed still high
42
+ # * Perhaps allow writing?
43
+
44
+ import os
45
+ import sys
46
+ import logging
47
+ import subprocess
48
+
49
+ from ..core import Format, BaseProgressIndicator, StdoutProgressIndicator
50
+ from ..core import read_n_bytes
51
+
52
+ _dicom = None # lazily loaded in load_lib()
53
+
54
+ logger = logging.getLogger(__name__)
55
+
56
+
57
+ def load_lib():
58
+ global _dicom
59
+ from . import _dicom
60
+
61
+ return _dicom
62
+
63
+
64
+ # Determine endianity of system
65
+ sys_is_little_endian = sys.byteorder == "little"
66
+
67
+
68
+ def get_dcmdjpeg_exe():
69
+ fname = "dcmdjpeg" + ".exe" * sys.platform.startswith("win")
70
+ for dir in (
71
+ "c:\\dcmtk",
72
+ "c:\\Program Files",
73
+ "c:\\Program Files\\dcmtk",
74
+ "c:\\Program Files (x86)\\dcmtk",
75
+ ):
76
+ filename = os.path.join(dir, fname)
77
+ if os.path.isfile(filename):
78
+ return [filename]
79
+
80
+ try:
81
+ subprocess.check_call([fname, "--version"])
82
+ return [fname]
83
+ except Exception:
84
+ return None
85
+
86
+
87
+ def get_gdcmconv_exe():
88
+ fname = "gdcmconv" + ".exe" * sys.platform.startswith("win")
89
+ # Maybe it's on the path
90
+ try:
91
+ subprocess.check_call([fname, "--version"])
92
+ return [fname, "--raw"]
93
+ except Exception:
94
+ pass
95
+ # Select directories where it could be
96
+ candidates = []
97
+ base_dirs = [r"c:\Program Files"]
98
+ for base_dir in base_dirs:
99
+ if os.path.isdir(base_dir):
100
+ for dname in os.listdir(base_dir):
101
+ if dname.lower().startswith("gdcm"):
102
+ suffix = dname[4:].strip()
103
+ candidates.append((suffix, os.path.join(base_dir, dname)))
104
+ # Sort, so higher versions are tried earlier
105
+ candidates.sort(reverse=True)
106
+ # Select executable
107
+ filename = None
108
+ for _, dirname in candidates:
109
+ exe1 = os.path.join(dirname, "gdcmconv.exe")
110
+ exe2 = os.path.join(dirname, "bin", "gdcmconv.exe")
111
+ if os.path.isfile(exe1):
112
+ filename = exe1
113
+ break
114
+ if os.path.isfile(exe2):
115
+ filename = exe2
116
+ break
117
+ else:
118
+ return None
119
+ return [filename, "--raw"]
120
+
121
+
122
+ class DicomFormat(Format):
123
+ """See :mod:`imageio.plugins.dicom`"""
124
+
125
+ def _can_read(self, request):
126
+ # If user URI was a directory, we check whether it has a DICOM file
127
+ if os.path.isdir(request.filename):
128
+ files = os.listdir(request.filename)
129
+ for fname in sorted(files): # Sorting make it consistent
130
+ filename = os.path.join(request.filename, fname)
131
+ if os.path.isfile(filename) and "DICOMDIR" not in fname:
132
+ with open(filename, "rb") as f:
133
+ first_bytes = read_n_bytes(f, 140)
134
+ return first_bytes[128:132] == b"DICM"
135
+ else:
136
+ return False
137
+ # Check
138
+ return request.firstbytes[128:132] == b"DICM"
139
+
140
+ def _can_write(self, request):
141
+ # We cannot save yet. May be possible if we will used pydicom as
142
+ # a backend.
143
+ return False
144
+
145
+ # --
146
+
147
+ class Reader(Format.Reader):
148
+ _compressed_warning_dirs = set()
149
+
150
+ def _open(self, progress=True):
151
+ if not _dicom:
152
+ load_lib()
153
+ if os.path.isdir(self.request.filename):
154
+ # A dir can be given if the user used the format explicitly
155
+ self._info = {}
156
+ self._data = None
157
+ else:
158
+ # Read the given dataset now ...
159
+ try:
160
+ dcm = _dicom.SimpleDicomReader(self.request.get_file())
161
+ except _dicom.CompressedDicom as err:
162
+ # We cannot do this on our own. Perhaps with some help ...
163
+ cmd = get_gdcmconv_exe()
164
+ if not cmd and "JPEG" in str(err):
165
+ cmd = get_dcmdjpeg_exe()
166
+ if not cmd:
167
+ msg = err.args[0].replace("using", "installing")
168
+ msg = msg.replace("convert", "auto-convert")
169
+ err.args = (msg,)
170
+ raise
171
+ else:
172
+ fname1 = self.request.get_local_filename()
173
+ fname2 = fname1 + ".raw"
174
+ try:
175
+ subprocess.check_call(cmd + [fname1, fname2])
176
+ except Exception:
177
+ raise err
178
+ d = os.path.dirname(fname1)
179
+ if d not in self._compressed_warning_dirs:
180
+ self._compressed_warning_dirs.add(d)
181
+ logger.warning(
182
+ "DICOM file contained compressed data. "
183
+ + "Autoconverting with "
184
+ + cmd[0]
185
+ + " (this warning is shown once for each directory)"
186
+ )
187
+ dcm = _dicom.SimpleDicomReader(fname2)
188
+
189
+ self._info = dcm._info
190
+ self._data = dcm.get_numpy_array()
191
+
192
+ # Initialize series, list of DicomSeries objects
193
+ self._series = None # only created if needed
194
+
195
+ # Set progress indicator
196
+ if isinstance(progress, BaseProgressIndicator):
197
+ self._progressIndicator = progress
198
+ elif progress is True:
199
+ p = StdoutProgressIndicator("Reading DICOM")
200
+ self._progressIndicator = p
201
+ elif progress in (None, False):
202
+ self._progressIndicator = BaseProgressIndicator("Dummy")
203
+ else:
204
+ raise ValueError("Invalid value for progress.")
205
+
206
+ def _close(self):
207
+ # Clean up
208
+ self._info = None
209
+ self._data = None
210
+ self._series = None
211
+
212
+ @property
213
+ def series(self):
214
+ if self._series is None:
215
+ pi = self._progressIndicator
216
+ self._series = _dicom.process_directory(self.request, pi)
217
+ return self._series
218
+
219
+ def _get_length(self):
220
+ if self._data is None:
221
+ dcm = self.series[0][0]
222
+ self._info = dcm._info
223
+ self._data = dcm.get_numpy_array()
224
+
225
+ nslices = self._data.shape[0] if (self._data.ndim == 3) else 1
226
+
227
+ if self.request.mode[1] == "i":
228
+ # User expects one, but lets be honest about this file
229
+ return nslices
230
+ elif self.request.mode[1] == "I":
231
+ # User expects multiple, if this file has multiple slices, ok.
232
+ # Otherwise we have to check the series.
233
+ if nslices > 1:
234
+ return nslices
235
+ else:
236
+ return sum([len(serie) for serie in self.series])
237
+ elif self.request.mode[1] == "v":
238
+ # User expects a volume, if this file has one, ok.
239
+ # Otherwise we have to check the series
240
+ if nslices > 1:
241
+ return 1
242
+ else:
243
+ return len(self.series) # We assume one volume per series
244
+ elif self.request.mode[1] == "V":
245
+ # User expects multiple volumes. We have to check the series
246
+ return len(self.series) # We assume one volume per series
247
+ else:
248
+ raise RuntimeError("DICOM plugin should know what to expect.")
249
+
250
+ def _get_slice_data(self, index):
251
+ nslices = self._data.shape[0] if (self._data.ndim == 3) else 1
252
+
253
+ # Allow index >1 only if this file contains >1
254
+ if nslices > 1:
255
+ return self._data[index], self._info
256
+ elif index == 0:
257
+ return self._data, self._info
258
+ else:
259
+ raise IndexError("Dicom file contains only one slice.")
260
+
261
+ def _get_data(self, index):
262
+ if self._data is None:
263
+ dcm = self.series[0][0]
264
+ self._info = dcm._info
265
+ self._data = dcm.get_numpy_array()
266
+
267
+ nslices = self._data.shape[0] if (self._data.ndim == 3) else 1
268
+
269
+ if self.request.mode[1] == "i":
270
+ return self._get_slice_data(index)
271
+ elif self.request.mode[1] == "I":
272
+ # Return slice from volume, or return item from series
273
+ if index == 0 and nslices > 1:
274
+ return self._data[index], self._info
275
+ else:
276
+ L = []
277
+ for serie in self.series:
278
+ L.extend([dcm_ for dcm_ in serie])
279
+ return L[index].get_numpy_array(), L[index].info
280
+ elif self.request.mode[1] in "vV":
281
+ # Return volume or series
282
+ if index == 0 and nslices > 1:
283
+ return self._data, self._info
284
+ else:
285
+ return (
286
+ self.series[index].get_numpy_array(),
287
+ self.series[index].info,
288
+ )
289
+ # mode is `?` (typically because we are using V3). If there is a
290
+ # series (multiple files), index referrs to the element of the
291
+ # series and we read volumes. If there is no series, index
292
+ # referrs to the slice in the volume we read "flat" images.
293
+ elif len(self.series) > 1:
294
+ # mode is `?` and there are multiple series. Each series is a ndimage.
295
+ return (
296
+ self.series[index].get_numpy_array(),
297
+ self.series[index].info,
298
+ )
299
+ else:
300
+ # mode is `?` and there is only one series. Each slice is an ndimage.
301
+ return self._get_slice_data(index)
302
+
303
+ def _get_meta_data(self, index):
304
+ if self._data is None:
305
+ dcm = self.series[0][0]
306
+ self._info = dcm._info
307
+ self._data = dcm.get_numpy_array()
308
+
309
+ nslices = self._data.shape[0] if (self._data.ndim == 3) else 1
310
+
311
+ # Default is the meta data of the given file, or the "first" file.
312
+ if index is None:
313
+ return self._info
314
+
315
+ if self.request.mode[1] == "i":
316
+ return self._info
317
+ elif self.request.mode[1] == "I":
318
+ # Return slice from volume, or return item from series
319
+ if index == 0 and nslices > 1:
320
+ return self._info
321
+ else:
322
+ L = []
323
+ for serie in self.series:
324
+ L.extend([dcm_ for dcm_ in serie])
325
+ return L[index].info
326
+ elif self.request.mode[1] in "vV":
327
+ # Return volume or series
328
+ if index == 0 and nslices > 1:
329
+ return self._info
330
+ else:
331
+ return self.series[index].info
332
+ else: # pragma: no cover
333
+ raise ValueError("DICOM plugin should know what to expect.")
minigpt2/lib/python3.10/site-packages/imageio/plugins/feisem.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # imageio is distributed under the terms of the (new) BSD License.
3
+
4
+ """Read TIFF from FEI SEM microscopes.
5
+
6
+ Backend Library: internal
7
+
8
+ This format is based on :mod:`TIFF <imageio.plugins.tifffile>`, and supports the
9
+ same parameters. FEI microscopes append metadata as ASCII text at the end of the
10
+ file, which this reader correctly extracts.
11
+
12
+ Parameters
13
+ ----------
14
+ discard_watermark : bool
15
+ If True (default), discard the bottom rows of the image, which
16
+ contain no image data, only a watermark with metadata.
17
+ watermark_height : int
18
+ The height in pixels of the FEI watermark. The default is 70.
19
+
20
+ See Also
21
+ --------
22
+ :mod:`imageio.plugins.tifffile`
23
+
24
+ """
25
+
26
+
27
+ from .tifffile import TiffFormat
28
+
29
+
30
+ class FEISEMFormat(TiffFormat):
31
+ """See :mod:`imageio.plugins.feisem`"""
32
+
33
+ def _can_write(self, request):
34
+ return False # FEI-SEM only supports reading
35
+
36
+ class Reader(TiffFormat.Reader):
37
+ def _get_data(self, index=0, discard_watermark=True, watermark_height=70):
38
+ """Get image and metadata from given index.
39
+
40
+ FEI images usually (always?) contain a watermark at the
41
+ bottom of the image, 70 pixels high. We discard this by
42
+ default as it does not contain any information not present
43
+ in the metadata.
44
+ """
45
+ im, meta = super(FEISEMFormat.Reader, self)._get_data(index)
46
+ if discard_watermark:
47
+ im = im[:-watermark_height]
48
+ return im, meta
49
+
50
+ def _get_meta_data(self, index=None):
51
+ """Read the metadata from an FEI SEM TIFF.
52
+
53
+ This metadata is included as ASCII text at the end of the file.
54
+
55
+ The index, if provided, is ignored.
56
+
57
+ Returns
58
+ -------
59
+ metadata : dict
60
+ Dictionary of metadata.
61
+ """
62
+ if hasattr(self, "_fei_meta"):
63
+ return self._fei_meta
64
+
65
+ md = {"root": {}}
66
+ current_tag = "root"
67
+ reading_metadata = False
68
+ filename = self.request.get_local_filename()
69
+ with open(filename, encoding="utf8", errors="ignore") as fin:
70
+ for line in fin:
71
+ if not reading_metadata:
72
+ if not line.startswith("Date="):
73
+ continue
74
+ else:
75
+ reading_metadata = True
76
+ line = line.rstrip()
77
+ if line.startswith("["):
78
+ current_tag = line.lstrip("[").rstrip("]")
79
+ md[current_tag] = {}
80
+ else:
81
+ if "=" in line: # ignore empty and irrelevant lines
82
+ key, val = line.split("=", maxsplit=1)
83
+ for tag_type in (int, float):
84
+ try:
85
+ val = tag_type(val)
86
+ except ValueError:
87
+ continue
88
+ else:
89
+ break
90
+ md[current_tag][key] = val
91
+ if not md["root"] and len(md) == 1:
92
+ raise ValueError("Input file %s contains no FEI metadata." % filename)
93
+
94
+ self._fei_meta = md
95
+ return md
minigpt2/lib/python3.10/site-packages/imageio/plugins/ffmpeg.py ADDED
@@ -0,0 +1,729 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # imageio is distributed under the terms of the (new) BSD License.
3
+
4
+ """Read/Write video using FFMPEG
5
+
6
+ .. note::
7
+ We are in the process of (slowly) replacing this plugin with a new one that
8
+ is based on `pyav <https://pyav.org/docs/stable/>`_. It is faster and more
9
+ flexible than the plugin documented here. Check the :mod:`pyav
10
+ plugin's documentation <imageio.plugins.pyav>` for more information about
11
+ this plugin.
12
+
13
+ Backend Library: https://github.com/imageio/imageio-ffmpeg
14
+
15
+ .. note::
16
+ To use this plugin you have to install its backend::
17
+
18
+ pip install imageio[ffmpeg]
19
+
20
+
21
+ The ffmpeg format provides reading and writing for a wide range of movie formats
22
+ such as .avi, .mpeg, .mp4, etc. as well as the ability to read streams from
23
+ webcams and USB cameras. It is based on ffmpeg and is inspired by/based `moviepy
24
+ <https://github.com/Zulko/moviepy/>`_ by Zulko.
25
+
26
+ Parameters for reading
27
+ ----------------------
28
+ fps : scalar
29
+ The number of frames per second of the input stream. Default None (i.e.
30
+ read at the file's native fps). One can use this for files with a
31
+ variable fps, or in cases where imageio is unable to correctly detect
32
+ the fps. In case of trouble opening camera streams, it may help to set an
33
+ explicit fps value matching a framerate supported by the camera.
34
+ loop : bool
35
+ If True, the video will rewind as soon as a frame is requested
36
+ beyond the last frame. Otherwise, IndexError is raised. Default False.
37
+ Setting this to True will internally call ``count_frames()``,
38
+ and set the reader's length to that value instead of inf.
39
+ size : str | tuple
40
+ The frame size (i.e. resolution) to read the images, e.g.
41
+ (100, 100) or "640x480". For camera streams, this allows setting
42
+ the capture resolution. For normal video data, ffmpeg will
43
+ rescale the data.
44
+ dtype : str | type
45
+ The dtype for the output arrays. Determines the bit-depth that
46
+ is requested from ffmpeg. Supported dtypes: uint8, uint16.
47
+ Default: uint8.
48
+ pixelformat : str
49
+ The pixel format for the camera to use (e.g. "yuyv422" or
50
+ "gray"). The camera needs to support the format in order for
51
+ this to take effect. Note that the images produced by this
52
+ reader are always RGB.
53
+ input_params : list
54
+ List additional arguments to ffmpeg for input file options.
55
+ (Can also be provided as ``ffmpeg_params`` for backwards compatibility)
56
+ Example ffmpeg arguments to use aggressive error handling:
57
+ ['-err_detect', 'aggressive']
58
+ output_params : list
59
+ List additional arguments to ffmpeg for output file options (i.e. the
60
+ stream being read by imageio).
61
+ print_info : bool
62
+ Print information about the video file as reported by ffmpeg.
63
+
64
+ Parameters for writing
65
+ ----------------------
66
+ fps : scalar
67
+ The number of frames per second. Default 10.
68
+ codec : str
69
+ the video codec to use. Default 'libx264', which represents the
70
+ widely available mpeg4. Except when saving .wmv files, then the
71
+ defaults is 'msmpeg4' which is more commonly supported for windows
72
+ quality : float | None
73
+ Video output quality. Default is 5. Uses variable bit rate. Highest
74
+ quality is 10, lowest is 0. Set to None to prevent variable bitrate
75
+ flags to FFMPEG so you can manually specify them using output_params
76
+ instead. Specifying a fixed bitrate using 'bitrate' disables this
77
+ parameter.
78
+ bitrate : int | None
79
+ Set a constant bitrate for the video encoding. Default is None causing
80
+ 'quality' parameter to be used instead. Better quality videos with
81
+ smaller file sizes will result from using the 'quality' variable
82
+ bitrate parameter rather than specifying a fixed bitrate with this
83
+ parameter.
84
+ pixelformat: str
85
+ The output video pixel format. Default is 'yuv420p' which most widely
86
+ supported by video players.
87
+ input_params : list
88
+ List additional arguments to ffmpeg for input file options (i.e. the
89
+ stream that imageio provides).
90
+ output_params : list
91
+ List additional arguments to ffmpeg for output file options.
92
+ (Can also be provided as ``ffmpeg_params`` for backwards compatibility)
93
+ Example ffmpeg arguments to use only intra frames and set aspect ratio:
94
+ ['-intra', '-aspect', '16:9']
95
+ ffmpeg_log_level: str
96
+ Sets ffmpeg output log level. Default is "warning".
97
+ Values can be "quiet", "panic", "fatal", "error", "warning", "info"
98
+ "verbose", or "debug". Also prints the FFMPEG command being used by
99
+ imageio if "info", "verbose", or "debug".
100
+ macro_block_size: int
101
+ Size constraint for video. Width and height, must be divisible by this
102
+ number. If not divisible by this number imageio will tell ffmpeg to
103
+ scale the image up to the next closest size
104
+ divisible by this number. Most codecs are compatible with a macroblock
105
+ size of 16 (default), some can go smaller (4, 8). To disable this
106
+ automatic feature set it to None or 1, however be warned many players
107
+ can't decode videos that are odd in size and some codecs will produce
108
+ poor results or fail. See https://en.wikipedia.org/wiki/Macroblock.
109
+ audio_path : str | None
110
+ Audio path of any audio that needs to be written. Defaults to nothing,
111
+ so no audio will be written. Please note, when writing shorter video
112
+ than the original, ffmpeg will not truncate the audio track; it
113
+ will maintain its original length and be longer than the video.
114
+ audio_codec : str | None
115
+ The audio codec to use. Defaults to nothing, but if an audio_path has
116
+ been provided ffmpeg will attempt to set a default codec.
117
+
118
+ Notes
119
+ -----
120
+ If you are using anaconda and ``anaconda/ffmpeg`` you will not be able to
121
+ encode/decode H.264 (likely due to licensing concerns). If you need this
122
+ format on anaconda install ``conda-forge/ffmpeg`` instead.
123
+
124
+ You can use the ``IMAGEIO_FFMPEG_EXE`` environment variable to force using a
125
+ specific ffmpeg executable.
126
+
127
+ To get the number of frames before having read them all, you can use the
128
+ ``reader.count_frames()`` method (the reader will then use
129
+ ``imageio_ffmpeg.count_frames_and_secs()`` to get the exact number of frames,
130
+ note that this operation can take a few seconds on large files). Alternatively,
131
+ the number of frames can be estimated from the fps and duration in the meta data
132
+ (though these values themselves are not always present/reliable).
133
+
134
+ """
135
+
136
+ import re
137
+ import sys
138
+ import time
139
+ import logging
140
+ import platform
141
+ import threading
142
+ import subprocess as sp
143
+ import imageio_ffmpeg
144
+
145
+ import numpy as np
146
+
147
+ from ..core import Format, image_as_uint
148
+
149
+ logger = logging.getLogger(__name__)
150
+
151
+ # Get camera format
152
+ if sys.platform.startswith("win"):
153
+ CAM_FORMAT = "dshow" # dshow or vfwcap
154
+ elif sys.platform.startswith("linux"):
155
+ CAM_FORMAT = "video4linux2"
156
+ elif sys.platform.startswith("darwin"):
157
+ CAM_FORMAT = "avfoundation"
158
+ else: # pragma: no cover
159
+ CAM_FORMAT = "unknown-cam-format"
160
+
161
+
162
+ def download(directory=None, force_download=False): # pragma: no cover
163
+ raise RuntimeError(
164
+ "imageio.ffmpeg.download() has been deprecated. "
165
+ "Use 'pip install imageio-ffmpeg' instead.'"
166
+ )
167
+
168
+
169
+ # For backwards compatibility - we dont use this ourselves
170
+ def get_exe(): # pragma: no cover
171
+ """Wrapper for imageio_ffmpeg.get_ffmpeg_exe()"""
172
+
173
+ return imageio_ffmpeg.get_ffmpeg_exe()
174
+
175
+
176
+ class FfmpegFormat(Format):
177
+ """Read/Write ImageResources using FFMPEG.
178
+
179
+ See :mod:`imageio.plugins.ffmpeg`
180
+ """
181
+
182
+ def _can_read(self, request):
183
+ # Read from video stream?
184
+ # Note that we could write the _video flag here, but a user might
185
+ # select this format explicitly (and this code is not run)
186
+ if re.match(r"<video(\d+)>", request.filename):
187
+ return True
188
+
189
+ # Read from file that we know?
190
+ if request.extension in self.extensions:
191
+ return True
192
+
193
+ def _can_write(self, request):
194
+ if request.extension in self.extensions:
195
+ return True
196
+
197
+ # --
198
+
199
+ class Reader(Format.Reader):
200
+ _frame_catcher = None
201
+ _read_gen = None
202
+
203
+ def _get_cam_inputname(self, index):
204
+ if sys.platform.startswith("linux"):
205
+ return "/dev/" + self.request._video[1:-1]
206
+
207
+ elif sys.platform.startswith("win"):
208
+ # Ask ffmpeg for list of dshow device names
209
+ ffmpeg_api = imageio_ffmpeg
210
+ cmd = [
211
+ ffmpeg_api.get_ffmpeg_exe(),
212
+ "-list_devices",
213
+ "true",
214
+ "-f",
215
+ CAM_FORMAT,
216
+ "-i",
217
+ "dummy",
218
+ ]
219
+ # Set `shell=True` in sp.run to prevent popup of a command
220
+ # line window in frozen applications. Note: this would be a
221
+ # security vulnerability if user-input goes into the cmd.
222
+ # Note that the ffmpeg process returns with exit code 1 when
223
+ # using `-list_devices` (or `-list_options`), even if the
224
+ # command is successful, so we set `check=False` explicitly.
225
+ completed_process = sp.run(
226
+ cmd,
227
+ stdout=sp.PIPE,
228
+ stderr=sp.PIPE,
229
+ encoding="utf-8",
230
+ shell=True,
231
+ check=False,
232
+ )
233
+
234
+ # Return device name at index
235
+ try:
236
+ name = parse_device_names(completed_process.stderr)[index]
237
+ except IndexError:
238
+ raise IndexError("No ffdshow camera at index %i." % index)
239
+ return "video=%s" % name
240
+
241
+ elif sys.platform.startswith("darwin"):
242
+ # Appears that newer ffmpeg builds don't support -list-devices
243
+ # on OS X. But you can directly open the camera by index.
244
+ name = str(index)
245
+ return name
246
+
247
+ else: # pragma: no cover
248
+ return "??"
249
+
250
+ def _open(
251
+ self,
252
+ loop=False,
253
+ size=None,
254
+ dtype=None,
255
+ pixelformat=None,
256
+ print_info=False,
257
+ ffmpeg_params=None,
258
+ input_params=None,
259
+ output_params=None,
260
+ fps=None,
261
+ ):
262
+ # Get generator functions
263
+ self._ffmpeg_api = imageio_ffmpeg
264
+ # Process input args
265
+ self._arg_loop = bool(loop)
266
+ if size is None:
267
+ self._arg_size = None
268
+ elif isinstance(size, tuple):
269
+ self._arg_size = "%ix%i" % size
270
+ elif isinstance(size, str) and "x" in size:
271
+ self._arg_size = size
272
+ else:
273
+ raise ValueError('FFMPEG size must be tuple of "NxM"')
274
+ if pixelformat is None:
275
+ pass
276
+ elif not isinstance(pixelformat, str):
277
+ raise ValueError("FFMPEG pixelformat must be str")
278
+ if dtype is None:
279
+ self._dtype = np.dtype("uint8")
280
+ else:
281
+ self._dtype = np.dtype(dtype)
282
+ allowed_dtypes = ["uint8", "uint16"]
283
+ if self._dtype.name not in allowed_dtypes:
284
+ raise ValueError(
285
+ "dtype must be one of: {}".format(", ".join(allowed_dtypes))
286
+ )
287
+ self._arg_pixelformat = pixelformat
288
+ self._arg_input_params = input_params or []
289
+ self._arg_output_params = output_params or []
290
+ self._arg_input_params += ffmpeg_params or [] # backward compat
291
+ # Write "_video"_arg - indicating webcam support
292
+ self.request._video = None
293
+ regex_match = re.match(r"<video(\d+)>", self.request.filename)
294
+ if regex_match:
295
+ self.request._video = self.request.filename
296
+ # Get local filename
297
+ if self.request._video:
298
+ index = int(regex_match.group(1))
299
+ self._filename = self._get_cam_inputname(index)
300
+ else:
301
+ self._filename = self.request.get_local_filename()
302
+ # When passed to ffmpeg on command line, carets need to be escaped.
303
+ self._filename = self._filename.replace("^", "^^")
304
+ # Determine pixel format and depth
305
+ self._depth = 3
306
+ if self._dtype.name == "uint8":
307
+ self._pix_fmt = "rgb24"
308
+ self._bytes_per_channel = 1
309
+ else:
310
+ self._pix_fmt = "rgb48le"
311
+ self._bytes_per_channel = 2
312
+ # Initialize parameters
313
+ self._pos = -1
314
+ self._meta = {"plugin": "ffmpeg"}
315
+ self._lastread = None
316
+
317
+ # Calculating this from fps and duration is not accurate,
318
+ # and calculating it exactly with ffmpeg_api.count_frames_and_secs
319
+ # takes too long to do for each video. But we need it for looping.
320
+ self._nframes = float("inf")
321
+ if self._arg_loop and not self.request._video:
322
+ self._nframes = self.count_frames()
323
+ self._meta["nframes"] = self._nframes
324
+
325
+ # Specify input framerate? (only on macOS)
326
+ # Ideally we'd get the supported framerate from the metadata, but we get the
327
+ # metadata when we boot ffmpeg ... maybe we could refactor this so we can
328
+ # get the metadata beforehand, but for now we'll just give it 2 tries on MacOS,
329
+ # one with fps 30 and one with fps 15.
330
+ need_input_fps = need_output_fps = False
331
+ if self.request._video and platform.system().lower() == "darwin":
332
+ if "-framerate" not in str(self._arg_input_params):
333
+ need_input_fps = True
334
+ if not self.request.kwargs.get("fps", None):
335
+ need_output_fps = True
336
+ if need_input_fps:
337
+ self._arg_input_params.extend(["-framerate", str(float(30))])
338
+ if need_output_fps:
339
+ self._arg_output_params.extend(["-r", str(float(30))])
340
+
341
+ # Start ffmpeg subprocess and get meta information
342
+ try:
343
+ self._initialize()
344
+ except IndexError:
345
+ # Specify input framerate again, this time different.
346
+ if need_input_fps:
347
+ self._arg_input_params[-1] = str(float(15))
348
+ self._initialize()
349
+ else:
350
+ raise
351
+
352
+ # For cameras, create thread that keeps reading the images
353
+ if self.request._video:
354
+ self._frame_catcher = FrameCatcher(self._read_gen)
355
+
356
+ # For reference - but disabled, because it is inaccurate
357
+ # if self._meta["nframes"] == float("inf"):
358
+ # if self._meta.get("fps", 0) > 0:
359
+ # if self._meta.get("duration", 0) > 0:
360
+ # n = round(self._meta["duration"] * self._meta["fps"])
361
+ # self._meta["nframes"] = int(n)
362
+
363
+ def _close(self):
364
+ # First close the frame catcher, because we cannot close the gen
365
+ # if the frame catcher thread is using it
366
+ if self._frame_catcher is not None:
367
+ self._frame_catcher.stop_me()
368
+ self._frame_catcher = None
369
+ if self._read_gen is not None:
370
+ self._read_gen.close()
371
+ self._read_gen = None
372
+
373
+ def count_frames(self):
374
+ """Count the number of frames. Note that this can take a few
375
+ seconds for large files. Also note that it counts the number
376
+ of frames in the original video and does not take a given fps
377
+ into account.
378
+ """
379
+ # This would have been nice, but this does not work :(
380
+ # oargs = []
381
+ # if self.request.kwargs.get("fps", None):
382
+ # fps = float(self.request.kwargs["fps"])
383
+ # oargs += ["-r", "%.02f" % fps]
384
+ cf = self._ffmpeg_api.count_frames_and_secs
385
+ return cf(self._filename)[0]
386
+
387
+ def _get_length(self):
388
+ return self._nframes # only not inf if loop is True
389
+
390
+ def _get_data(self, index):
391
+ """Reads a frame at index. Note for coders: getting an
392
+ arbitrary frame in the video with ffmpeg can be painfully
393
+ slow if some decoding has to be done. This function tries
394
+ to avoid fectching arbitrary frames whenever possible, by
395
+ moving between adjacent frames."""
396
+ # Modulo index (for looping)
397
+ if self._arg_loop and self._nframes < float("inf"):
398
+ index %= self._nframes
399
+
400
+ if index == self._pos:
401
+ return self._lastread, dict(new=False)
402
+ elif index < 0:
403
+ raise IndexError("Frame index must be >= 0")
404
+ elif index >= self._nframes:
405
+ raise IndexError("Reached end of video")
406
+ else:
407
+ if (index < self._pos) or (index > self._pos + 100):
408
+ self._initialize(index)
409
+ else:
410
+ self._skip_frames(index - self._pos - 1)
411
+ result, is_new = self._read_frame()
412
+ self._pos = index
413
+ return result, dict(new=is_new)
414
+
415
+ def _get_meta_data(self, index):
416
+ return self._meta
417
+
418
+ def _initialize(self, index=0):
419
+ # Close the current generator, and thereby terminate its subprocess
420
+ if self._read_gen is not None:
421
+ self._read_gen.close()
422
+
423
+ iargs = []
424
+ oargs = []
425
+
426
+ # Create input args
427
+ iargs += self._arg_input_params
428
+ if self.request._video:
429
+ iargs += ["-f", CAM_FORMAT]
430
+ if self._arg_pixelformat:
431
+ iargs += ["-pix_fmt", self._arg_pixelformat]
432
+ if self._arg_size:
433
+ iargs += ["-s", self._arg_size]
434
+ elif index > 0: # re-initialize / seek
435
+ # Note: only works if we initialized earlier, and now have meta
436
+ # Some info here: https://trac.ffmpeg.org/wiki/Seeking
437
+ # There are two ways to seek, one before -i (input_params) and
438
+ # after (output_params). The former is fast, because it uses
439
+ # keyframes, the latter is slow but accurate. According to
440
+ # the article above, the fast method should also be accurate
441
+ # from ffmpeg version 2.1, however in version 4.1 our tests
442
+ # start failing again. Not sure why, but we can solve this
443
+ # by combining slow and fast. Seek the long stretch using
444
+ # the fast method, and seek the last 10s the slow way.
445
+ starttime = index / self._meta["fps"]
446
+ seek_slow = min(10, starttime)
447
+ seek_fast = starttime - seek_slow
448
+ # We used to have this epsilon earlier, when we did not use
449
+ # the slow seek. I don't think we need it anymore.
450
+ # epsilon = -1 / self._meta["fps"] * 0.1
451
+ iargs += ["-ss", "%.06f" % (seek_fast)]
452
+ oargs += ["-ss", "%.06f" % (seek_slow)]
453
+
454
+ # Output args, for writing to pipe
455
+ if self._arg_size:
456
+ oargs += ["-s", self._arg_size]
457
+ if self.request.kwargs.get("fps", None):
458
+ fps = float(self.request.kwargs["fps"])
459
+ oargs += ["-r", "%.02f" % fps]
460
+ oargs += self._arg_output_params
461
+
462
+ # Get pixelformat and bytes per pixel
463
+ pix_fmt = self._pix_fmt
464
+ bpp = self._depth * self._bytes_per_channel
465
+
466
+ # Create generator
467
+ rf = self._ffmpeg_api.read_frames
468
+ self._read_gen = rf(
469
+ self._filename, pix_fmt, bpp, input_params=iargs, output_params=oargs
470
+ )
471
+
472
+ # Read meta data. This start the generator (and ffmpeg subprocess)
473
+ if self.request._video:
474
+ # With cameras, catch error and turn into IndexError
475
+ try:
476
+ meta = self._read_gen.__next__()
477
+ except IOError as err:
478
+ err_text = str(err)
479
+ if "darwin" in sys.platform:
480
+ if "Unknown input format: 'avfoundation'" in err_text:
481
+ err_text += (
482
+ "Try installing FFMPEG using "
483
+ "home brew to get a version with "
484
+ "support for cameras."
485
+ )
486
+ raise IndexError(
487
+ "No (working) camera at {}.\n\n{}".format(
488
+ self.request._video, err_text
489
+ )
490
+ )
491
+ else:
492
+ self._meta.update(meta)
493
+ elif index == 0:
494
+ self._meta.update(self._read_gen.__next__())
495
+ else:
496
+ self._read_gen.__next__() # we already have meta data
497
+
498
+ def _skip_frames(self, n=1):
499
+ """Reads and throws away n frames"""
500
+ for i in range(n):
501
+ self._read_gen.__next__()
502
+ self._pos += n
503
+
504
+ def _read_frame(self):
505
+ # Read and convert to numpy array
506
+ w, h = self._meta["size"]
507
+ framesize = w * h * self._depth * self._bytes_per_channel
508
+ # t0 = time.time()
509
+
510
+ # Read frame
511
+ if self._frame_catcher: # pragma: no cover - camera thing
512
+ s, is_new = self._frame_catcher.get_frame()
513
+ else:
514
+ s = self._read_gen.__next__()
515
+ is_new = True
516
+
517
+ # Check
518
+ if len(s) != framesize:
519
+ raise RuntimeError(
520
+ "Frame is %i bytes, but expected %i." % (len(s), framesize)
521
+ )
522
+
523
+ result = np.frombuffer(s, dtype=self._dtype).copy()
524
+ result = result.reshape((h, w, self._depth))
525
+ # t1 = time.time()
526
+ # print('etime', t1-t0)
527
+
528
+ # Store and return
529
+ self._lastread = result
530
+ return result, is_new
531
+
532
+ # --
533
+
534
+ class Writer(Format.Writer):
535
+ _write_gen = None
536
+
537
+ def _open(
538
+ self,
539
+ fps=10,
540
+ codec="libx264",
541
+ bitrate=None,
542
+ pixelformat="yuv420p",
543
+ ffmpeg_params=None,
544
+ input_params=None,
545
+ output_params=None,
546
+ ffmpeg_log_level="quiet",
547
+ quality=5,
548
+ macro_block_size=16,
549
+ audio_path=None,
550
+ audio_codec=None,
551
+ ):
552
+ self._ffmpeg_api = imageio_ffmpeg
553
+ self._filename = self.request.get_local_filename()
554
+ self._pix_fmt = None
555
+ self._depth = None
556
+ self._size = None
557
+
558
+ def _close(self):
559
+ if self._write_gen is not None:
560
+ self._write_gen.close()
561
+ self._write_gen = None
562
+
563
+ def _append_data(self, im, meta):
564
+ # Get props of image
565
+ h, w = im.shape[:2]
566
+ size = w, h
567
+ depth = 1 if im.ndim == 2 else im.shape[2]
568
+
569
+ # Ensure that image is in uint8
570
+ im = image_as_uint(im, bitdepth=8)
571
+ # To be written efficiently, ie. without creating an immutable
572
+ # buffer, by calling im.tobytes() the array must be contiguous.
573
+ if not im.flags.c_contiguous:
574
+ # checkign the flag is a micro optimization.
575
+ # the image will be a numpy subclass. See discussion
576
+ # https://github.com/numpy/numpy/issues/11804
577
+ im = np.ascontiguousarray(im)
578
+
579
+ # Set size and initialize if not initialized yet
580
+ if self._size is None:
581
+ map = {1: "gray", 2: "gray8a", 3: "rgb24", 4: "rgba"}
582
+ self._pix_fmt = map.get(depth, None)
583
+ if self._pix_fmt is None:
584
+ raise ValueError("Image must have 1, 2, 3 or 4 channels")
585
+ self._size = size
586
+ self._depth = depth
587
+ self._initialize()
588
+
589
+ # Check size of image
590
+ if size != self._size:
591
+ raise ValueError("All images in a movie should have same size")
592
+ if depth != self._depth:
593
+ raise ValueError(
594
+ "All images in a movie should have same " "number of channels"
595
+ )
596
+
597
+ assert self._write_gen is not None # Check status
598
+
599
+ # Write. Yes, we can send the data in as a numpy array
600
+ self._write_gen.send(im)
601
+
602
+ def set_meta_data(self, meta):
603
+ raise RuntimeError(
604
+ "The ffmpeg format does not support setting " "meta data."
605
+ )
606
+
607
+ def _initialize(self):
608
+ # Close existing generator
609
+ if self._write_gen is not None:
610
+ self._write_gen.close()
611
+
612
+ # Get parameters
613
+ # Use None to let imageio-ffmpeg (or ffmpeg) select good results
614
+ fps = self.request.kwargs.get("fps", 10)
615
+ codec = self.request.kwargs.get("codec", None)
616
+ bitrate = self.request.kwargs.get("bitrate", None)
617
+ quality = self.request.kwargs.get("quality", None)
618
+ input_params = self.request.kwargs.get("input_params") or []
619
+ output_params = self.request.kwargs.get("output_params") or []
620
+ output_params += self.request.kwargs.get("ffmpeg_params") or []
621
+ pixelformat = self.request.kwargs.get("pixelformat", None)
622
+ macro_block_size = self.request.kwargs.get("macro_block_size", 16)
623
+ ffmpeg_log_level = self.request.kwargs.get("ffmpeg_log_level", None)
624
+ audio_path = self.request.kwargs.get("audio_path", None)
625
+ audio_codec = self.request.kwargs.get("audio_codec", None)
626
+
627
+ macro_block_size = macro_block_size or 1 # None -> 1
628
+
629
+ # Create generator
630
+ self._write_gen = self._ffmpeg_api.write_frames(
631
+ self._filename,
632
+ self._size,
633
+ pix_fmt_in=self._pix_fmt,
634
+ pix_fmt_out=pixelformat,
635
+ fps=fps,
636
+ quality=quality,
637
+ bitrate=bitrate,
638
+ codec=codec,
639
+ macro_block_size=macro_block_size,
640
+ ffmpeg_log_level=ffmpeg_log_level,
641
+ input_params=input_params,
642
+ output_params=output_params,
643
+ audio_path=audio_path,
644
+ audio_codec=audio_codec,
645
+ )
646
+
647
+ # Seed the generator (this is where the ffmpeg subprocess starts)
648
+ self._write_gen.send(None)
649
+
650
+
651
+ class FrameCatcher(threading.Thread):
652
+ """Thread to keep reading the frame data from stdout. This is
653
+ useful when streaming from a webcam. Otherwise, if the user code
654
+ does not grab frames fast enough, the buffer will fill up, leading
655
+ to lag, and ffmpeg can also stall (experienced on Linux). The
656
+ get_frame() method always returns the last available image.
657
+ """
658
+
659
+ def __init__(self, gen):
660
+ self._gen = gen
661
+ self._frame = None
662
+ self._frame_is_new = False
663
+ self._lock = threading.RLock()
664
+ threading.Thread.__init__(self)
665
+ self.daemon = True # do not let this thread hold up Python shutdown
666
+ self._should_stop = False
667
+ self.start()
668
+
669
+ def stop_me(self):
670
+ self._should_stop = True
671
+ while self.is_alive():
672
+ time.sleep(0.001)
673
+
674
+ def get_frame(self):
675
+ while self._frame is None: # pragma: no cover - an init thing
676
+ time.sleep(0.001)
677
+ with self._lock:
678
+ is_new = self._frame_is_new
679
+ self._frame_is_new = False # reset
680
+ return self._frame, is_new
681
+
682
+ def run(self):
683
+ # This runs in the worker thread
684
+ try:
685
+ while not self._should_stop:
686
+ time.sleep(0) # give control to other threads
687
+ frame = self._gen.__next__()
688
+ with self._lock:
689
+ self._frame = frame
690
+ self._frame_is_new = True
691
+ except (StopIteration, EOFError):
692
+ pass
693
+
694
+
695
+ def parse_device_names(ffmpeg_output):
696
+ """Parse the output of the ffmpeg -list-devices command"""
697
+ # Collect device names - get [friendly_name, alt_name] of each
698
+ device_names = []
699
+ in_video_devices = False
700
+ for line in ffmpeg_output.splitlines():
701
+ if line.startswith("[dshow"):
702
+ logger.debug(line)
703
+ line = line.split("]", 1)[1].strip()
704
+ if in_video_devices and line.startswith('"'):
705
+ friendly_name = line[1:-1]
706
+ device_names.append([friendly_name, ""])
707
+ elif in_video_devices and line.lower().startswith("alternative name"):
708
+ alt_name = line.split(" name ", 1)[1].strip()[1:-1]
709
+ if sys.platform.startswith("win"):
710
+ alt_name = alt_name.replace("&", "^&") # Tested to work
711
+ else:
712
+ alt_name = alt_name.replace("&", "\\&") # Does this work?
713
+ device_names[-1][-1] = alt_name
714
+ elif "video devices" in line:
715
+ in_video_devices = True
716
+ elif "devices" in line:
717
+ # set False for subsequent "devices" sections
718
+ in_video_devices = False
719
+ # Post-process, see #441
720
+ # prefer friendly names, use alt name if two cams have same friendly name
721
+ device_names2 = []
722
+ for friendly_name, alt_name in device_names:
723
+ if friendly_name not in device_names2:
724
+ device_names2.append(friendly_name)
725
+ elif alt_name:
726
+ device_names2.append(alt_name)
727
+ else:
728
+ device_names2.append(friendly_name) # duplicate, but not much we can do
729
+ return device_names2
minigpt2/lib/python3.10/site-packages/imageio/plugins/fits.py ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # imageio is distributed under the terms of the (new) BSD License.
3
+
4
+ """Read FITS files.
5
+
6
+ Backend Library: `Astropy <https://www.astropy.org/>`_
7
+
8
+ .. note::
9
+ To use this plugin you have to install its backend::
10
+
11
+ pip install imageio[fits]
12
+
13
+ Flexible Image Transport System (FITS) is an open standard defining a
14
+ digital file format useful for storage, transmission and processing of
15
+ scientific and other images. FITS is the most commonly used digital
16
+ file format in astronomy.
17
+
18
+
19
+ Parameters
20
+ ----------
21
+ cache : bool
22
+ If the file name is a URL, `~astropy.utils.data.download_file` is used
23
+ to open the file. This specifies whether or not to save the file
24
+ locally in Astropy's download cache (default: `True`).
25
+ uint : bool
26
+ Interpret signed integer data where ``BZERO`` is the
27
+ central value and ``BSCALE == 1`` as unsigned integer
28
+ data. For example, ``int16`` data with ``BZERO = 32768``
29
+ and ``BSCALE = 1`` would be treated as ``uint16`` data.
30
+
31
+ Note, for backward compatibility, the kwarg **uint16** may
32
+ be used instead. The kwarg was renamed when support was
33
+ added for integers of any size.
34
+ ignore_missing_end : bool
35
+ Do not issue an exception when opening a file that is
36
+ missing an ``END`` card in the last header.
37
+ checksum : bool or str
38
+ If `True`, verifies that both ``DATASUM`` and
39
+ ``CHECKSUM`` card values (when present in the HDU header)
40
+ match the header and data of all HDU's in the file. Updates to a
41
+ file that already has a checksum will preserve and update the
42
+ existing checksums unless this argument is given a value of
43
+ 'remove', in which case the CHECKSUM and DATASUM values are not
44
+ checked, and are removed when saving changes to the file.
45
+ disable_image_compression : bool, optional
46
+ If `True`, treats compressed image HDU's like normal
47
+ binary table HDU's.
48
+ do_not_scale_image_data : bool
49
+ If `True`, image data is not scaled using BSCALE/BZERO values
50
+ when read.
51
+ ignore_blank : bool
52
+ If `True`, the BLANK keyword is ignored if present.
53
+ scale_back : bool
54
+ If `True`, when saving changes to a file that contained scaled
55
+ image data, restore the data to the original type and reapply the
56
+ original BSCALE/BZERO values. This could lead to loss of accuracy
57
+ if scaling back to integer values after performing floating point
58
+ operations on the data.
59
+
60
+ """
61
+
62
+ from ..core import Format
63
+
64
+ _fits = None # lazily loaded
65
+
66
+
67
+ def load_lib():
68
+ global _fits
69
+ try:
70
+ from astropy.io import fits as _fits
71
+ except ImportError:
72
+ raise ImportError(
73
+ "The FITS format relies on the astropy package."
74
+ "Please refer to http://www.astropy.org/ "
75
+ "for further instructions."
76
+ )
77
+ return _fits
78
+
79
+
80
+ class FitsFormat(Format):
81
+ """See :mod:`imageio.plugins.fits`"""
82
+
83
+ def _can_read(self, request):
84
+ # We return True if ext matches, because this is the only plugin
85
+ # that can. If astropy is not installed, a useful error follows.
86
+ return request.extension in self.extensions
87
+
88
+ def _can_write(self, request):
89
+ # No write support
90
+ return False
91
+
92
+ # -- reader
93
+
94
+ class Reader(Format.Reader):
95
+ def _open(self, cache=False, **kwargs):
96
+ if not _fits:
97
+ load_lib()
98
+ hdulist = _fits.open(self.request.get_file(), cache=cache, **kwargs)
99
+
100
+ self._index = []
101
+ allowed_hdu_types = (_fits.ImageHDU, _fits.PrimaryHDU, _fits.CompImageHDU)
102
+ for n, hdu in zip(range(len(hdulist)), hdulist):
103
+ if isinstance(hdu, allowed_hdu_types):
104
+ # Ignore (primary) header units with no data (use '.size'
105
+ # rather than '.data' to avoid actually loading the image):
106
+ if hdu.size > 0:
107
+ self._index.append(n)
108
+ self._hdulist = hdulist
109
+
110
+ def _close(self):
111
+ self._hdulist.close()
112
+
113
+ def _get_length(self):
114
+ return len(self._index)
115
+
116
+ def _get_data(self, index):
117
+ # Get data
118
+ if index < 0 or index >= len(self._index):
119
+ raise IndexError("Index out of range while reading from fits")
120
+ im = self._hdulist[self._index[index]].data
121
+ # Return array and empty meta data
122
+ return im, {}
123
+
124
+ def _get_meta_data(self, index):
125
+ # Get the meta data for the given index
126
+ raise RuntimeError("The fits format does not support meta data.")
minigpt2/lib/python3.10/site-packages/imageio/plugins/freeimage.py ADDED
@@ -0,0 +1,404 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # imageio is distributed under the terms of the (new) BSD License.
3
+
4
+ """Read/Write images using FreeImage.
5
+
6
+ Backend Library: `FreeImage <https://freeimage.sourceforge.io/>`_
7
+
8
+ .. note::
9
+ To use this plugin you have to install its backend::
10
+
11
+ imageio_download_bin freeimage
12
+
13
+ or you can download the backend using the function::
14
+
15
+ imageio.plugins.freeimage.download()
16
+
17
+ Each Freeimage format has the ``flags`` keyword argument. See the `Freeimage
18
+ documentation <https://freeimage.sourceforge.io/>`_ for more information.
19
+
20
+ Parameters
21
+ ----------
22
+ flags : int
23
+ A freeimage-specific option. In most cases we provide explicit
24
+ parameters for influencing image reading.
25
+
26
+ """
27
+
28
+ import numpy as np
29
+
30
+ from ..core import Format, image_as_uint
31
+ from ..core.request import RETURN_BYTES
32
+ from ._freeimage import FNAME_PER_PLATFORM, IO_FLAGS, download, fi # noqa
33
+
34
+ # todo: support files with only meta data
35
+
36
+
37
+ class FreeimageFormat(Format):
38
+ """See :mod:`imageio.plugins.freeimage`"""
39
+
40
+ _modes = "i"
41
+
42
+ def __init__(self, name, description, extensions=None, modes=None, *, fif=None):
43
+ super().__init__(name, description, extensions=extensions, modes=modes)
44
+ self._fif = fif
45
+
46
+ @property
47
+ def fif(self):
48
+ return self._fif # Set when format is created
49
+
50
+ def _can_read(self, request):
51
+ # Ask freeimage if it can read it, maybe ext missing
52
+ if fi.has_lib():
53
+ if not hasattr(request, "_fif"):
54
+ try:
55
+ request._fif = fi.getFIF(request.filename, "r", request.firstbytes)
56
+ except Exception: # pragma: no cover
57
+ request._fif = -1
58
+ if request._fif == self.fif:
59
+ return True
60
+ elif request._fif == 7 and self.fif == 14:
61
+ # PPM gets identified as PBM and PPM can read PBM
62
+ # see: https://github.com/imageio/imageio/issues/677
63
+ return True
64
+
65
+ def _can_write(self, request):
66
+ # Ask freeimage, because we are not aware of all formats
67
+ if fi.has_lib():
68
+ if not hasattr(request, "_fif"):
69
+ try:
70
+ request._fif = fi.getFIF(request.filename, "w")
71
+ except ValueError: # pragma: no cover
72
+ if request.raw_uri == RETURN_BYTES:
73
+ request._fif = self.fif
74
+ else:
75
+ request._fif = -1
76
+ if request._fif is self.fif:
77
+ return True
78
+
79
+ # --
80
+
81
+ class Reader(Format.Reader):
82
+ def _get_length(self):
83
+ return 1
84
+
85
+ def _open(self, flags=0):
86
+ self._bm = fi.create_bitmap(self.request.filename, self.format.fif, flags)
87
+ self._bm.load_from_filename(self.request.get_local_filename())
88
+
89
+ def _close(self):
90
+ self._bm.close()
91
+
92
+ def _get_data(self, index):
93
+ if index != 0:
94
+ raise IndexError("This format only supports singleton images.")
95
+ return self._bm.get_image_data(), self._bm.get_meta_data()
96
+
97
+ def _get_meta_data(self, index):
98
+ if not (index is None or index == 0):
99
+ raise IndexError()
100
+ return self._bm.get_meta_data()
101
+
102
+ # --
103
+
104
+ class Writer(Format.Writer):
105
+ def _open(self, flags=0):
106
+ self._flags = flags # Store flags for later use
107
+ self._bm = None
108
+ self._is_set = False # To prevent appending more than one image
109
+ self._meta = {}
110
+
111
+ def _close(self):
112
+ # Set global meta data
113
+ self._bm.set_meta_data(self._meta)
114
+ # Write and close
115
+ self._bm.save_to_filename(self.request.get_local_filename())
116
+ self._bm.close()
117
+
118
+ def _append_data(self, im, meta):
119
+ # Check if set
120
+ if not self._is_set:
121
+ self._is_set = True
122
+ else:
123
+ raise RuntimeError(
124
+ "Singleton image; " "can only append image data once."
125
+ )
126
+ # Pop unit dimension for grayscale images
127
+ if im.ndim == 3 and im.shape[-1] == 1:
128
+ im = im[:, :, 0]
129
+ # Lazy instantaion of the bitmap, we need image data
130
+ if self._bm is None:
131
+ self._bm = fi.create_bitmap(
132
+ self.request.filename, self.format.fif, self._flags
133
+ )
134
+ self._bm.allocate(im)
135
+ # Set data
136
+ self._bm.set_image_data(im)
137
+ # There is no distinction between global and per-image meta data
138
+ # for singleton images
139
+ self._meta = meta
140
+
141
+ def _set_meta_data(self, meta):
142
+ self._meta = meta
143
+
144
+
145
+ # Special plugins
146
+
147
+ # todo: there is also FIF_LOAD_NOPIXELS,
148
+ # but perhaps that should be used with get_meta_data.
149
+
150
+
151
+ class FreeimageBmpFormat(FreeimageFormat):
152
+ """A BMP format based on the Freeimage library.
153
+
154
+ This format supports grayscale, RGB and RGBA images.
155
+
156
+ The freeimage plugin requires a `freeimage` binary. If this binary
157
+ not available on the system, it can be downloaded manually from
158
+ <https://github.com/imageio/imageio-binaries> by either
159
+
160
+ - the command line script ``imageio_download_bin freeimage``
161
+ - the Python method ``imageio.plugins.freeimage.download()``
162
+
163
+ Parameters for saving
164
+ ---------------------
165
+ compression : bool
166
+ Whether to compress the bitmap using RLE when saving. Default False.
167
+ It seems this does not always work, but who cares, you should use
168
+ PNG anyway.
169
+
170
+ """
171
+
172
+ class Writer(FreeimageFormat.Writer):
173
+ def _open(self, flags=0, compression=False):
174
+ # Build flags from kwargs
175
+ flags = int(flags)
176
+ if compression:
177
+ flags |= IO_FLAGS.BMP_SAVE_RLE
178
+ else:
179
+ flags |= IO_FLAGS.BMP_DEFAULT
180
+ # Act as usual, but with modified flags
181
+ return FreeimageFormat.Writer._open(self, flags)
182
+
183
+ def _append_data(self, im, meta):
184
+ im = image_as_uint(im, bitdepth=8)
185
+ return FreeimageFormat.Writer._append_data(self, im, meta)
186
+
187
+
188
+ class FreeimagePngFormat(FreeimageFormat):
189
+ """A PNG format based on the Freeimage library.
190
+
191
+ This format supports grayscale, RGB and RGBA images.
192
+
193
+ The freeimage plugin requires a `freeimage` binary. If this binary
194
+ not available on the system, it can be downloaded manually from
195
+ <https://github.com/imageio/imageio-binaries> by either
196
+
197
+ - the command line script ``imageio_download_bin freeimage``
198
+ - the Python method ``imageio.plugins.freeimage.download()``
199
+
200
+ Parameters for reading
201
+ ----------------------
202
+ ignoregamma : bool
203
+ Avoid gamma correction. Default True.
204
+
205
+ Parameters for saving
206
+ ---------------------
207
+ compression : {0, 1, 6, 9}
208
+ The compression factor. Higher factors result in more
209
+ compression at the cost of speed. Note that PNG compression is
210
+ always lossless. Default 9.
211
+ quantize : int
212
+ If specified, turn the given RGB or RGBA image in a paletted image
213
+ for more efficient storage. The value should be between 2 and 256.
214
+ If the value of 0 the image is not quantized.
215
+ interlaced : bool
216
+ Save using Adam7 interlacing. Default False.
217
+ """
218
+
219
+ class Reader(FreeimageFormat.Reader):
220
+ def _open(self, flags=0, ignoregamma=True):
221
+ # Build flags from kwargs
222
+ flags = int(flags)
223
+ if ignoregamma:
224
+ flags |= IO_FLAGS.PNG_IGNOREGAMMA
225
+ # Enter as usual, with modified flags
226
+ return FreeimageFormat.Reader._open(self, flags)
227
+
228
+ # --
229
+
230
+ class Writer(FreeimageFormat.Writer):
231
+ def _open(self, flags=0, compression=9, quantize=0, interlaced=False):
232
+ compression_map = {
233
+ 0: IO_FLAGS.PNG_Z_NO_COMPRESSION,
234
+ 1: IO_FLAGS.PNG_Z_BEST_SPEED,
235
+ 6: IO_FLAGS.PNG_Z_DEFAULT_COMPRESSION,
236
+ 9: IO_FLAGS.PNG_Z_BEST_COMPRESSION,
237
+ }
238
+ # Build flags from kwargs
239
+ flags = int(flags)
240
+ if interlaced:
241
+ flags |= IO_FLAGS.PNG_INTERLACED
242
+ try:
243
+ flags |= compression_map[compression]
244
+ except KeyError:
245
+ raise ValueError("Png compression must be 0, 1, 6, or 9.")
246
+ # Act as usual, but with modified flags
247
+ return FreeimageFormat.Writer._open(self, flags)
248
+
249
+ def _append_data(self, im, meta):
250
+ if str(im.dtype) == "uint16":
251
+ im = image_as_uint(im, bitdepth=16)
252
+ else:
253
+ im = image_as_uint(im, bitdepth=8)
254
+ FreeimageFormat.Writer._append_data(self, im, meta)
255
+ # Quantize?
256
+ q = int(self.request.kwargs.get("quantize", False))
257
+ if not q:
258
+ pass
259
+ elif not (im.ndim == 3 and im.shape[-1] == 3):
260
+ raise ValueError("Can only quantize RGB images")
261
+ elif q < 2 or q > 256:
262
+ raise ValueError("PNG quantize param must be 2..256")
263
+ else:
264
+ bm = self._bm.quantize(0, q)
265
+ self._bm.close()
266
+ self._bm = bm
267
+
268
+
269
+ class FreeimageJpegFormat(FreeimageFormat):
270
+ """A JPEG format based on the Freeimage library.
271
+
272
+ This format supports grayscale and RGB images.
273
+
274
+ The freeimage plugin requires a `freeimage` binary. If this binary
275
+ not available on the system, it can be downloaded manually from
276
+ <https://github.com/imageio/imageio-binaries> by either
277
+
278
+ - the command line script ``imageio_download_bin freeimage``
279
+ - the Python method ``imageio.plugins.freeimage.download()``
280
+
281
+ Parameters for reading
282
+ ----------------------
283
+ exifrotate : bool
284
+ Automatically rotate the image according to the exif flag.
285
+ Default True. If 2 is given, do the rotation in Python instead
286
+ of freeimage.
287
+ quickread : bool
288
+ Read the image more quickly, at the expense of quality.
289
+ Default False.
290
+
291
+ Parameters for saving
292
+ ---------------------
293
+ quality : scalar
294
+ The compression factor of the saved image (1..100), higher
295
+ numbers result in higher quality but larger file size. Default 75.
296
+ progressive : bool
297
+ Save as a progressive JPEG file (e.g. for images on the web).
298
+ Default False.
299
+ optimize : bool
300
+ On saving, compute optimal Huffman coding tables (can reduce a
301
+ few percent of file size). Default False.
302
+ baseline : bool
303
+ Save basic JPEG, without metadata or any markers. Default False.
304
+
305
+ """
306
+
307
+ class Reader(FreeimageFormat.Reader):
308
+ def _open(self, flags=0, exifrotate=True, quickread=False):
309
+ # Build flags from kwargs
310
+ flags = int(flags)
311
+ if exifrotate and exifrotate != 2:
312
+ flags |= IO_FLAGS.JPEG_EXIFROTATE
313
+ if not quickread:
314
+ flags |= IO_FLAGS.JPEG_ACCURATE
315
+ # Enter as usual, with modified flags
316
+ return FreeimageFormat.Reader._open(self, flags)
317
+
318
+ def _get_data(self, index):
319
+ im, meta = FreeimageFormat.Reader._get_data(self, index)
320
+ im = self._rotate(im, meta)
321
+ return im, meta
322
+
323
+ def _rotate(self, im, meta):
324
+ """Use Orientation information from EXIF meta data to
325
+ orient the image correctly. Freeimage is also supposed to
326
+ support that, and I am pretty sure it once did, but now it
327
+ does not, so let's just do it in Python.
328
+ Edit: and now it works again, just leave in place as a fallback.
329
+ """
330
+ if self.request.kwargs.get("exifrotate", None) == 2:
331
+ try:
332
+ ori = meta["EXIF_MAIN"]["Orientation"]
333
+ except KeyError: # pragma: no cover
334
+ pass # Orientation not available
335
+ else: # pragma: no cover - we cannot touch all cases
336
+ # www.impulseadventure.com/photo/exif-orientation.html
337
+ if ori in [1, 2]:
338
+ pass
339
+ if ori in [3, 4]:
340
+ im = np.rot90(im, 2)
341
+ if ori in [5, 6]:
342
+ im = np.rot90(im, 3)
343
+ if ori in [7, 8]:
344
+ im = np.rot90(im)
345
+ if ori in [2, 4, 5, 7]: # Flipped cases (rare)
346
+ im = np.fliplr(im)
347
+ return im
348
+
349
+ # --
350
+
351
+ class Writer(FreeimageFormat.Writer):
352
+ def _open(
353
+ self, flags=0, quality=75, progressive=False, optimize=False, baseline=False
354
+ ):
355
+ # Test quality
356
+ quality = int(quality)
357
+ if quality < 1 or quality > 100:
358
+ raise ValueError("JPEG quality should be between 1 and 100.")
359
+ # Build flags from kwargs
360
+ flags = int(flags)
361
+ flags |= quality
362
+ if progressive:
363
+ flags |= IO_FLAGS.JPEG_PROGRESSIVE
364
+ if optimize:
365
+ flags |= IO_FLAGS.JPEG_OPTIMIZE
366
+ if baseline:
367
+ flags |= IO_FLAGS.JPEG_BASELINE
368
+ # Act as usual, but with modified flags
369
+ return FreeimageFormat.Writer._open(self, flags)
370
+
371
+ def _append_data(self, im, meta):
372
+ if im.ndim == 3 and im.shape[-1] == 4:
373
+ raise IOError("JPEG does not support alpha channel.")
374
+ im = image_as_uint(im, bitdepth=8)
375
+ return FreeimageFormat.Writer._append_data(self, im, meta)
376
+
377
+
378
+ class FreeimagePnmFormat(FreeimageFormat):
379
+ """A PNM format based on the Freeimage library.
380
+
381
+ This format supports single bit (PBM), grayscale (PGM) and RGB (PPM)
382
+ images, even with ASCII or binary coding.
383
+
384
+ The freeimage plugin requires a `freeimage` binary. If this binary
385
+ not available on the system, it can be downloaded manually from
386
+ <https://github.com/imageio/imageio-binaries> by either
387
+
388
+ - the command line script ``imageio_download_bin freeimage``
389
+ - the Python method ``imageio.plugins.freeimage.download()``
390
+
391
+ Parameters for saving
392
+ ---------------------
393
+ use_ascii : bool
394
+ Save with ASCII coding. Default True.
395
+ """
396
+
397
+ class Writer(FreeimageFormat.Writer):
398
+ def _open(self, flags=0, use_ascii=True):
399
+ # Build flags from kwargs
400
+ flags = int(flags)
401
+ if use_ascii:
402
+ flags |= IO_FLAGS.PNM_SAVE_ASCII
403
+ # Act as usual, but with modified flags
404
+ return FreeimageFormat.Writer._open(self, flags)
minigpt2/lib/python3.10/site-packages/imageio/plugins/freeimagemulti.py ADDED
@@ -0,0 +1,316 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # imageio is distributed under the terms of the (new) BSD License.
3
+
4
+ """Plugin for multi-image freeimafe formats, like animated GIF and ico.
5
+ """
6
+
7
+ import logging
8
+ import numpy as np
9
+
10
+ from ..core import Format, image_as_uint
11
+ from ._freeimage import fi, IO_FLAGS
12
+ from .freeimage import FreeimageFormat
13
+
14
+ logger = logging.getLogger(__name__)
15
+
16
+
17
+ class FreeimageMulti(FreeimageFormat):
18
+ """Base class for freeimage formats that support multiple images."""
19
+
20
+ _modes = "iI"
21
+ _fif = -1
22
+
23
+ class Reader(Format.Reader):
24
+ def _open(self, flags=0):
25
+ flags = int(flags)
26
+ # Create bitmap
27
+ self._bm = fi.create_multipage_bitmap(
28
+ self.request.filename, self.format.fif, flags
29
+ )
30
+ self._bm.load_from_filename(self.request.get_local_filename())
31
+
32
+ def _close(self):
33
+ self._bm.close()
34
+
35
+ def _get_length(self):
36
+ return len(self._bm)
37
+
38
+ def _get_data(self, index):
39
+ sub = self._bm.get_page(index)
40
+ try:
41
+ return sub.get_image_data(), sub.get_meta_data()
42
+ finally:
43
+ sub.close()
44
+
45
+ def _get_meta_data(self, index):
46
+ index = index or 0
47
+ if index < 0 or index >= len(self._bm):
48
+ raise IndexError()
49
+ sub = self._bm.get_page(index)
50
+ try:
51
+ return sub.get_meta_data()
52
+ finally:
53
+ sub.close()
54
+
55
+ # --
56
+
57
+ class Writer(FreeimageFormat.Writer):
58
+ def _open(self, flags=0):
59
+ # Set flags
60
+ self._flags = flags = int(flags)
61
+ # Instantiate multi-page bitmap
62
+ self._bm = fi.create_multipage_bitmap(
63
+ self.request.filename, self.format.fif, flags
64
+ )
65
+ self._bm.save_to_filename(self.request.get_local_filename())
66
+
67
+ def _close(self):
68
+ # Close bitmap
69
+ self._bm.close()
70
+
71
+ def _append_data(self, im, meta):
72
+ # Prepare data
73
+ if im.ndim == 3 and im.shape[-1] == 1:
74
+ im = im[:, :, 0]
75
+ im = image_as_uint(im, bitdepth=8)
76
+ # Create sub bitmap
77
+ sub1 = fi.create_bitmap(self._bm._filename, self.format.fif)
78
+ # Let subclass add data to bitmap, optionally return new
79
+ sub2 = self._append_bitmap(im, meta, sub1)
80
+ # Add
81
+ self._bm.append_bitmap(sub2)
82
+ sub2.close()
83
+ if sub1 is not sub2:
84
+ sub1.close()
85
+
86
+ def _append_bitmap(self, im, meta, bitmap):
87
+ # Set data
88
+ bitmap.allocate(im)
89
+ bitmap.set_image_data(im)
90
+ bitmap.set_meta_data(meta)
91
+ # Return that same bitmap
92
+ return bitmap
93
+
94
+ def _set_meta_data(self, meta):
95
+ pass # ignore global meta data
96
+
97
+
98
+ class MngFormat(FreeimageMulti):
99
+ """An Mng format based on the Freeimage library.
100
+
101
+ Read only. Seems broken.
102
+ """
103
+
104
+ _fif = 6
105
+
106
+ def _can_write(self, request): # pragma: no cover
107
+ return False
108
+
109
+
110
+ class IcoFormat(FreeimageMulti):
111
+ """An ICO format based on the Freeimage library.
112
+
113
+ This format supports grayscale, RGB and RGBA images.
114
+
115
+ The freeimage plugin requires a `freeimage` binary. If this binary
116
+ is not available on the system, it can be downloaded by either
117
+
118
+ - the command line script ``imageio_download_bin freeimage``
119
+ - the Python method ``imageio.plugins.freeimage.download()``
120
+
121
+ Parameters for reading
122
+ ----------------------
123
+ makealpha : bool
124
+ Convert to 32-bit and create an alpha channel from the AND-
125
+ mask when loading. Default False. Note that this returns wrong
126
+ results if the image was already RGBA.
127
+
128
+ """
129
+
130
+ _fif = 1
131
+
132
+ class Reader(FreeimageMulti.Reader):
133
+ def _open(self, flags=0, makealpha=False):
134
+ # Build flags from kwargs
135
+ flags = int(flags)
136
+ if makealpha:
137
+ flags |= IO_FLAGS.ICO_MAKEALPHA
138
+ return FreeimageMulti.Reader._open(self, flags)
139
+
140
+
141
+ class GifFormat(FreeimageMulti):
142
+ """A format for reading and writing static and animated GIF, based
143
+ on the Freeimage library.
144
+
145
+ Images read with this format are always RGBA. Currently,
146
+ the alpha channel is ignored when saving RGB images with this
147
+ format.
148
+
149
+ The freeimage plugin requires a `freeimage` binary. If this binary
150
+ is not available on the system, it can be downloaded by either
151
+
152
+ - the command line script ``imageio_download_bin freeimage``
153
+ - the Python method ``imageio.plugins.freeimage.download()``
154
+
155
+ Parameters for reading
156
+ ----------------------
157
+ playback : bool
158
+ 'Play' the GIF to generate each frame (as 32bpp) instead of
159
+ returning raw frame data when loading. Default True.
160
+
161
+ Parameters for saving
162
+ ---------------------
163
+ loop : int
164
+ The number of iterations. Default 0 (meaning loop indefinitely)
165
+ duration : {float, list}
166
+ The duration (in seconds) of each frame. Either specify one value
167
+ that is used for all frames, or one value for each frame.
168
+ Note that in the GIF format the duration/delay is expressed in
169
+ hundredths of a second, which limits the precision of the duration.
170
+ fps : float
171
+ The number of frames per second. If duration is not given, the
172
+ duration for each frame is set to 1/fps. Default 10.
173
+ palettesize : int
174
+ The number of colors to quantize the image to. Is rounded to
175
+ the nearest power of two. Default 256.
176
+ quantizer : {'wu', 'nq'}
177
+ The quantization algorithm:
178
+ * wu - Wu, Xiaolin, Efficient Statistical Computations for
179
+ Optimal Color Quantization
180
+ * nq (neuqant) - Dekker A. H., Kohonen neural networks for
181
+ optimal color quantization
182
+ subrectangles : bool
183
+ If True, will try and optimize the GIF by storing only the
184
+ rectangular parts of each frame that change with respect to the
185
+ previous. Unfortunately, this option seems currently broken
186
+ because FreeImage does not handle DisposalMethod correctly.
187
+ Default False.
188
+ """
189
+
190
+ _fif = 25
191
+
192
+ class Reader(FreeimageMulti.Reader):
193
+ def _open(self, flags=0, playback=True):
194
+ # Build flags from kwargs
195
+ flags = int(flags)
196
+ if playback:
197
+ flags |= IO_FLAGS.GIF_PLAYBACK
198
+ FreeimageMulti.Reader._open(self, flags)
199
+
200
+ def _get_data(self, index):
201
+ im, meta = FreeimageMulti.Reader._get_data(self, index)
202
+ # im = im[:, :, :3] # Drop alpha channel
203
+ return im, meta
204
+
205
+ # -- writer
206
+
207
+ class Writer(FreeimageMulti.Writer):
208
+ # todo: subrectangles
209
+ # todo: global palette
210
+
211
+ def _open(
212
+ self,
213
+ flags=0,
214
+ loop=0,
215
+ duration=None,
216
+ fps=10,
217
+ palettesize=256,
218
+ quantizer="Wu",
219
+ subrectangles=False,
220
+ ):
221
+ # Check palettesize
222
+ if palettesize < 2 or palettesize > 256:
223
+ raise ValueError("GIF quantize param must be 2..256")
224
+ if palettesize not in [2, 4, 8, 16, 32, 64, 128, 256]:
225
+ palettesize = 2 ** int(np.log2(128) + 0.999)
226
+ logger.warning(
227
+ "Warning: palettesize (%r) modified to a factor of "
228
+ "two between 2-256." % palettesize
229
+ )
230
+ self._palettesize = palettesize
231
+ # Check quantizer
232
+ self._quantizer = {"wu": 0, "nq": 1}.get(quantizer.lower(), None)
233
+ if self._quantizer is None:
234
+ raise ValueError('Invalid quantizer, must be "wu" or "nq".')
235
+ # Check frametime
236
+ if duration is None:
237
+ self._frametime = [int(1000 / float(fps) + 0.5)]
238
+ elif isinstance(duration, list):
239
+ self._frametime = [int(1000 * d) for d in duration]
240
+ elif isinstance(duration, (float, int)):
241
+ self._frametime = [int(1000 * duration)]
242
+ else:
243
+ raise ValueError("Invalid value for duration: %r" % duration)
244
+ # Check subrectangles
245
+ self._subrectangles = bool(subrectangles)
246
+ self._prev_im = None
247
+ # Init
248
+ FreeimageMulti.Writer._open(self, flags)
249
+ # Set global meta data
250
+ self._meta = {}
251
+ self._meta["ANIMATION"] = {
252
+ # 'GlobalPalette': np.array([0]).astype(np.uint8),
253
+ "Loop": np.array([loop]).astype(np.uint32),
254
+ # 'LogicalWidth': np.array([x]).astype(np.uint16),
255
+ # 'LogicalHeight': np.array([x]).astype(np.uint16),
256
+ }
257
+
258
+ def _append_bitmap(self, im, meta, bitmap):
259
+ # Prepare meta data
260
+ meta = meta.copy()
261
+ meta_a = meta["ANIMATION"] = {}
262
+ # If this is the first frame, assign it our "global" meta data
263
+ if len(self._bm) == 0:
264
+ meta.update(self._meta)
265
+ meta_a = meta["ANIMATION"]
266
+ # Set frame time
267
+ index = len(self._bm)
268
+ if index < len(self._frametime):
269
+ ft = self._frametime[index]
270
+ else:
271
+ ft = self._frametime[-1]
272
+ meta_a["FrameTime"] = np.array([ft]).astype(np.uint32)
273
+ # Check array
274
+ if im.ndim == 3 and im.shape[-1] == 4:
275
+ im = im[:, :, :3]
276
+ # Process subrectangles
277
+ im_uncropped = im
278
+ if self._subrectangles and self._prev_im is not None:
279
+ im, xy = self._get_sub_rectangles(self._prev_im, im)
280
+ meta_a["DisposalMethod"] = np.array([1]).astype(np.uint8)
281
+ meta_a["FrameLeft"] = np.array([xy[0]]).astype(np.uint16)
282
+ meta_a["FrameTop"] = np.array([xy[1]]).astype(np.uint16)
283
+ self._prev_im = im_uncropped
284
+ # Set image data
285
+ sub2 = sub1 = bitmap
286
+ sub1.allocate(im)
287
+ sub1.set_image_data(im)
288
+ # Quantize it if its RGB
289
+ if im.ndim == 3 and im.shape[-1] == 3:
290
+ sub2 = sub1.quantize(self._quantizer, self._palettesize)
291
+ # Set meta data and return
292
+ sub2.set_meta_data(meta)
293
+ return sub2
294
+
295
+ def _get_sub_rectangles(self, prev, im):
296
+ """
297
+ Calculate the minimal rectangles that need updating each frame.
298
+ Returns a two-element tuple containing the cropped images and a
299
+ list of x-y positions.
300
+ """
301
+ # Get difference, sum over colors
302
+ diff = np.abs(im - prev)
303
+ if diff.ndim == 3:
304
+ diff = diff.sum(2)
305
+ # Get begin and end for both dimensions
306
+ X = np.argwhere(diff.sum(0))
307
+ Y = np.argwhere(diff.sum(1))
308
+ # Get rect coordinates
309
+ if X.size and Y.size:
310
+ x0, x1 = int(X[0]), int(X[-1]) + 1
311
+ y0, y1 = int(Y[0]), int(Y[-1]) + 1
312
+ else: # No change ... make it minimal
313
+ x0, x1 = 0, 2
314
+ y0, y1 = 0, 2
315
+ # Cut out and return
316
+ return im[y0:y1, x0:x1], (x0, y0)
minigpt2/lib/python3.10/site-packages/imageio/plugins/gdal.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # imageio is distributed under the terms of the (new) BSD License.
3
+
4
+ """ Read GDAL files.
5
+
6
+ Backend: `GDAL <https://gdal.org/>`_
7
+
8
+ .. note::
9
+ To use this plugin you have to install its backend::
10
+
11
+ pip install imageio[gdal]
12
+
13
+ Parameters
14
+ ----------
15
+ none
16
+ """
17
+
18
+ from ..core import Format, has_module
19
+
20
+ _gdal = None # lazily loaded in load_lib()
21
+
22
+
23
+ def load_lib():
24
+ global _gdal
25
+ try:
26
+ import osgeo.gdal as _gdal
27
+ except ImportError:
28
+ raise ImportError(
29
+ "The GDAL format relies on the GDAL package."
30
+ "Please refer to http://www.gdal.org/"
31
+ "for further instructions."
32
+ )
33
+ return _gdal
34
+
35
+
36
+ GDAL_FORMATS = (".tiff", " .tif", ".img", ".ecw", ".jpg", ".jpeg")
37
+
38
+
39
+ class GdalFormat(Format):
40
+ """See :mod:`imageio.plugins.gdal`"""
41
+
42
+ def _can_read(self, request):
43
+ if request.extension in (".ecw",):
44
+ return True
45
+ if has_module("osgeo.gdal"):
46
+ return request.extension in self.extensions
47
+
48
+ def _can_write(self, request):
49
+ return False
50
+
51
+ # --
52
+
53
+ class Reader(Format.Reader):
54
+ def _open(self):
55
+ if not _gdal:
56
+ load_lib()
57
+ self._ds = _gdal.Open(self.request.get_local_filename())
58
+
59
+ def _close(self):
60
+ del self._ds
61
+
62
+ def _get_length(self):
63
+ return 1
64
+
65
+ def _get_data(self, index):
66
+ if index != 0:
67
+ raise IndexError("Gdal file contains only one dataset")
68
+ return self._ds.ReadAsArray(), self._get_meta_data(index)
69
+
70
+ def _get_meta_data(self, index):
71
+ return self._ds.GetMetadata()
minigpt2/lib/python3.10/site-packages/imageio/plugins/grab.py ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ PIL-based formats to take screenshots and grab from the clipboard.
3
+ """
4
+
5
+ import threading
6
+
7
+ import numpy as np
8
+
9
+ from ..core import Format
10
+
11
+
12
+ class BaseGrabFormat(Format):
13
+ """Base format for grab formats."""
14
+
15
+ _pillow_imported = False
16
+ _ImageGrab = None
17
+
18
+ def __init__(self, *args, **kwargs):
19
+ super(BaseGrabFormat, self).__init__(*args, **kwargs)
20
+ self._lock = threading.RLock()
21
+
22
+ def _can_write(self, request):
23
+ return False
24
+
25
+ def _init_pillow(self):
26
+ with self._lock:
27
+ if not self._pillow_imported:
28
+ self._pillow_imported = True # more like tried to import
29
+ import PIL
30
+
31
+ if not hasattr(PIL, "__version__"): # pragma: no cover
32
+ raise ImportError("Imageio Pillow requires " "Pillow, not PIL!")
33
+ try:
34
+ from PIL import ImageGrab
35
+ except ImportError:
36
+ return None
37
+ self._ImageGrab = ImageGrab
38
+ return self._ImageGrab
39
+
40
+ class Reader(Format.Reader):
41
+ def _open(self):
42
+ pass
43
+
44
+ def _close(self):
45
+ pass
46
+
47
+ def _get_data(self, index):
48
+ return self.format._get_data(index)
49
+
50
+
51
+ class ScreenGrabFormat(BaseGrabFormat):
52
+ """The ScreenGrabFormat provided a means to grab screenshots using
53
+ the uri of "<screen>".
54
+
55
+ This functionality is provided via Pillow. Note that "<screen>" is
56
+ only supported on Windows and OS X.
57
+
58
+ Parameters for reading
59
+ ----------------------
60
+ No parameters.
61
+ """
62
+
63
+ def _can_read(self, request):
64
+ if request.filename != "<screen>":
65
+ return False
66
+ return bool(self._init_pillow())
67
+
68
+ def _get_data(self, index):
69
+ ImageGrab = self._init_pillow()
70
+ assert ImageGrab
71
+
72
+ pil_im = ImageGrab.grab()
73
+ assert pil_im is not None
74
+ im = np.asarray(pil_im)
75
+ return im, {}
76
+
77
+
78
+ class ClipboardGrabFormat(BaseGrabFormat):
79
+ """The ClipboardGrabFormat provided a means to grab image data from
80
+ the clipboard, using the uri "<clipboard>"
81
+
82
+ This functionality is provided via Pillow. Note that "<clipboard>" is
83
+ only supported on Windows.
84
+
85
+ Parameters for reading
86
+ ----------------------
87
+ No parameters.
88
+ """
89
+
90
+ def _can_read(self, request):
91
+ if request.filename != "<clipboard>":
92
+ return False
93
+ return bool(self._init_pillow())
94
+
95
+ def _get_data(self, index):
96
+ ImageGrab = self._init_pillow()
97
+ assert ImageGrab
98
+
99
+ pil_im = ImageGrab.grabclipboard()
100
+ if pil_im is None:
101
+ raise RuntimeError(
102
+ "There seems to be no image data on the " "clipboard now."
103
+ )
104
+ im = np.asarray(pil_im)
105
+ return im, {}