ZTWHHH commited on
Commit
95bbea1
·
verified ·
1 Parent(s): 30bbdd5

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. .gitattributes +1 -0
  2. llava/lib/python3.10/site-packages/pip/_vendor/pygments/console.py +70 -0
  3. llava/lib/python3.10/site-packages/pip/_vendor/pygments/filter.py +70 -0
  4. llava/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/__init__.py +157 -0
  5. llava/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/bbcode.py +108 -0
  6. llava/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/groff.py +170 -0
  7. llava/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/html.py +987 -0
  8. llava/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/img.py +685 -0
  9. llava/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/latex.py +518 -0
  10. llava/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/other.py +160 -0
  11. llava/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/pangomarkup.py +83 -0
  12. llava/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/rtf.py +349 -0
  13. llava/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/terminal.py +127 -0
  14. llava/lib/python3.10/site-packages/pip/_vendor/pygments/plugin.py +72 -0
  15. llava/lib/python3.10/site-packages/pip/_vendor/pygments/scanner.py +104 -0
  16. llava/lib/python3.10/site-packages/pip/_vendor/pygments/sphinxext.py +247 -0
  17. llava/lib/python3.10/site-packages/pip/_vendor/pygments/util.py +324 -0
  18. minigpt2/lib/python3.10/site-packages/Crypto/Math/_modexp.abi3.so +3 -0
  19. minigpt2/lib/python3.10/site-packages/decord/__init__.py +19 -0
  20. minigpt2/lib/python3.10/site-packages/decord/_api_internal.py +1 -0
  21. minigpt2/lib/python3.10/site-packages/decord/audio_reader.py +182 -0
  22. minigpt2/lib/python3.10/site-packages/decord/av_reader.py +149 -0
  23. minigpt2/lib/python3.10/site-packages/decord/base.py +20 -0
  24. minigpt2/lib/python3.10/site-packages/decord/logging.py +23 -0
  25. minigpt2/lib/python3.10/site-packages/decord/video_loader.py +121 -0
  26. minigpt2/lib/python3.10/site-packages/decord/video_reader.py +251 -0
  27. minigpt2/lib/python3.10/site-packages/ftfy-6.3.1.dist-info/INSTALLER +1 -0
  28. minigpt2/lib/python3.10/site-packages/ftfy-6.3.1.dist-info/METADATA +151 -0
  29. minigpt2/lib/python3.10/site-packages/ftfy-6.3.1.dist-info/RECORD +27 -0
  30. minigpt2/lib/python3.10/site-packages/ftfy-6.3.1.dist-info/REQUESTED +0 -0
  31. minigpt2/lib/python3.10/site-packages/ftfy-6.3.1.dist-info/WHEEL +4 -0
  32. minigpt2/lib/python3.10/site-packages/ftfy-6.3.1.dist-info/entry_points.txt +2 -0
  33. minigpt2/lib/python3.10/site-packages/ftfy-6.3.1.dist-info/licenses/LICENSE.txt +13 -0
  34. minigpt2/lib/python3.10/site-packages/multipart/__init__.py +24 -0
  35. minigpt2/lib/python3.10/site-packages/multipart/__pycache__/__init__.cpython-310.pyc +0 -0
  36. minigpt2/lib/python3.10/site-packages/multipart/__pycache__/decoders.cpython-310.pyc +0 -0
  37. minigpt2/lib/python3.10/site-packages/multipart/__pycache__/exceptions.cpython-310.pyc +0 -0
  38. minigpt2/lib/python3.10/site-packages/multipart/__pycache__/multipart.cpython-310.pyc +0 -0
  39. minigpt2/lib/python3.10/site-packages/multipart/decoders.py +1 -0
  40. minigpt2/lib/python3.10/site-packages/multipart/exceptions.py +1 -0
  41. minigpt2/lib/python3.10/site-packages/multipart/multipart.py +1 -0
  42. minigpt2/lib/python3.10/site-packages/xformers-0.0.28.post3.dist-info/RECORD +373 -0
  43. parrot/lib/python3.10/site-packages/torch/include/ATen/ops/_adaptive_avg_pool2d_cpu_dispatch.h +24 -0
  44. parrot/lib/python3.10/site-packages/torch/include/ATen/ops/_foreach_add_native.h +40 -0
  45. parrot/lib/python3.10/site-packages/torch/include/ATen/ops/_foreach_div_ops.h +149 -0
  46. parrot/lib/python3.10/site-packages/torch/include/ATen/ops/_foreach_max_ops.h +39 -0
  47. parrot/lib/python3.10/site-packages/torch/include/ATen/ops/_is_zerotensor_native.h +21 -0
  48. parrot/lib/python3.10/site-packages/torch/include/ATen/ops/_nested_view_from_jagged_native.h +20 -0
  49. parrot/lib/python3.10/site-packages/torch/include/ATen/ops/_reshape_alias_meta_dispatch.h +24 -0
  50. parrot/lib/python3.10/site-packages/torch/include/ATen/ops/_test_optional_intlist_ops.h +39 -0
.gitattributes CHANGED
@@ -1356,3 +1356,4 @@ minigpt2/lib/python3.10/site-packages/Crypto/PublicKey/_ec_ws.abi3.so filter=lfs
1356
  minigpt2/lib/python3.10/site-packages/Crypto/PublicKey/_curve25519.abi3.so filter=lfs diff=lfs merge=lfs -text
1357
  minigpt2/lib/python3.10/site-packages/Crypto/PublicKey/_ed25519.abi3.so filter=lfs diff=lfs merge=lfs -text
1358
  llava/lib/python3.10/site-packages/pip/_vendor/rich/__pycache__/_emoji_codes.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
 
 
1356
  minigpt2/lib/python3.10/site-packages/Crypto/PublicKey/_curve25519.abi3.so filter=lfs diff=lfs merge=lfs -text
1357
  minigpt2/lib/python3.10/site-packages/Crypto/PublicKey/_ed25519.abi3.so filter=lfs diff=lfs merge=lfs -text
1358
  llava/lib/python3.10/site-packages/pip/_vendor/rich/__pycache__/_emoji_codes.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
1359
+ minigpt2/lib/python3.10/site-packages/Crypto/Math/_modexp.abi3.so filter=lfs diff=lfs merge=lfs -text
llava/lib/python3.10/site-packages/pip/_vendor/pygments/console.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ pygments.console
3
+ ~~~~~~~~~~~~~~~~
4
+
5
+ Format colored console output.
6
+
7
+ :copyright: Copyright 2006-2024 by the Pygments team, see AUTHORS.
8
+ :license: BSD, see LICENSE for details.
9
+ """
10
+
11
+ esc = "\x1b["
12
+
13
+ codes = {}
14
+ codes[""] = ""
15
+ codes["reset"] = esc + "39;49;00m"
16
+
17
+ codes["bold"] = esc + "01m"
18
+ codes["faint"] = esc + "02m"
19
+ codes["standout"] = esc + "03m"
20
+ codes["underline"] = esc + "04m"
21
+ codes["blink"] = esc + "05m"
22
+ codes["overline"] = esc + "06m"
23
+
24
+ dark_colors = ["black", "red", "green", "yellow", "blue",
25
+ "magenta", "cyan", "gray"]
26
+ light_colors = ["brightblack", "brightred", "brightgreen", "brightyellow", "brightblue",
27
+ "brightmagenta", "brightcyan", "white"]
28
+
29
+ x = 30
30
+ for dark, light in zip(dark_colors, light_colors):
31
+ codes[dark] = esc + "%im" % x
32
+ codes[light] = esc + "%im" % (60 + x)
33
+ x += 1
34
+
35
+ del dark, light, x
36
+
37
+ codes["white"] = codes["bold"]
38
+
39
+
40
+ def reset_color():
41
+ return codes["reset"]
42
+
43
+
44
+ def colorize(color_key, text):
45
+ return codes[color_key] + text + codes["reset"]
46
+
47
+
48
+ def ansiformat(attr, text):
49
+ """
50
+ Format ``text`` with a color and/or some attributes::
51
+
52
+ color normal color
53
+ *color* bold color
54
+ _color_ underlined color
55
+ +color+ blinking color
56
+ """
57
+ result = []
58
+ if attr[:1] == attr[-1:] == '+':
59
+ result.append(codes['blink'])
60
+ attr = attr[1:-1]
61
+ if attr[:1] == attr[-1:] == '*':
62
+ result.append(codes['bold'])
63
+ attr = attr[1:-1]
64
+ if attr[:1] == attr[-1:] == '_':
65
+ result.append(codes['underline'])
66
+ attr = attr[1:-1]
67
+ result.append(codes[attr])
68
+ result.append(text)
69
+ result.append(codes['reset'])
70
+ return ''.join(result)
llava/lib/python3.10/site-packages/pip/_vendor/pygments/filter.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ pygments.filter
3
+ ~~~~~~~~~~~~~~~
4
+
5
+ Module that implements the default filter.
6
+
7
+ :copyright: Copyright 2006-2024 by the Pygments team, see AUTHORS.
8
+ :license: BSD, see LICENSE for details.
9
+ """
10
+
11
+
12
+ def apply_filters(stream, filters, lexer=None):
13
+ """
14
+ Use this method to apply an iterable of filters to
15
+ a stream. If lexer is given it's forwarded to the
16
+ filter, otherwise the filter receives `None`.
17
+ """
18
+ def _apply(filter_, stream):
19
+ yield from filter_.filter(lexer, stream)
20
+ for filter_ in filters:
21
+ stream = _apply(filter_, stream)
22
+ return stream
23
+
24
+
25
+ def simplefilter(f):
26
+ """
27
+ Decorator that converts a function into a filter::
28
+
29
+ @simplefilter
30
+ def lowercase(self, lexer, stream, options):
31
+ for ttype, value in stream:
32
+ yield ttype, value.lower()
33
+ """
34
+ return type(f.__name__, (FunctionFilter,), {
35
+ '__module__': getattr(f, '__module__'),
36
+ '__doc__': f.__doc__,
37
+ 'function': f,
38
+ })
39
+
40
+
41
+ class Filter:
42
+ """
43
+ Default filter. Subclass this class or use the `simplefilter`
44
+ decorator to create own filters.
45
+ """
46
+
47
+ def __init__(self, **options):
48
+ self.options = options
49
+
50
+ def filter(self, lexer, stream):
51
+ raise NotImplementedError()
52
+
53
+
54
+ class FunctionFilter(Filter):
55
+ """
56
+ Abstract class used by `simplefilter` to create simple
57
+ function filters on the fly. The `simplefilter` decorator
58
+ automatically creates subclasses of this class for
59
+ functions passed to it.
60
+ """
61
+ function = None
62
+
63
+ def __init__(self, **options):
64
+ if not hasattr(self, 'function'):
65
+ raise TypeError(f'{self.__class__.__name__!r} used without bound function')
66
+ Filter.__init__(self, **options)
67
+
68
+ def filter(self, lexer, stream):
69
+ # pylint: disable=not-callable
70
+ yield from self.function(lexer, stream, self.options)
llava/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/__init__.py ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ pygments.formatters
3
+ ~~~~~~~~~~~~~~~~~~~
4
+
5
+ Pygments formatters.
6
+
7
+ :copyright: Copyright 2006-2024 by the Pygments team, see AUTHORS.
8
+ :license: BSD, see LICENSE for details.
9
+ """
10
+
11
+ import re
12
+ import sys
13
+ import types
14
+ import fnmatch
15
+ from os.path import basename
16
+
17
+ from pip._vendor.pygments.formatters._mapping import FORMATTERS
18
+ from pip._vendor.pygments.plugin import find_plugin_formatters
19
+ from pip._vendor.pygments.util import ClassNotFound
20
+
21
+ __all__ = ['get_formatter_by_name', 'get_formatter_for_filename',
22
+ 'get_all_formatters', 'load_formatter_from_file'] + list(FORMATTERS)
23
+
24
+ _formatter_cache = {} # classes by name
25
+ _pattern_cache = {}
26
+
27
+
28
+ def _fn_matches(fn, glob):
29
+ """Return whether the supplied file name fn matches pattern filename."""
30
+ if glob not in _pattern_cache:
31
+ pattern = _pattern_cache[glob] = re.compile(fnmatch.translate(glob))
32
+ return pattern.match(fn)
33
+ return _pattern_cache[glob].match(fn)
34
+
35
+
36
+ def _load_formatters(module_name):
37
+ """Load a formatter (and all others in the module too)."""
38
+ mod = __import__(module_name, None, None, ['__all__'])
39
+ for formatter_name in mod.__all__:
40
+ cls = getattr(mod, formatter_name)
41
+ _formatter_cache[cls.name] = cls
42
+
43
+
44
+ def get_all_formatters():
45
+ """Return a generator for all formatter classes."""
46
+ # NB: this returns formatter classes, not info like get_all_lexers().
47
+ for info in FORMATTERS.values():
48
+ if info[1] not in _formatter_cache:
49
+ _load_formatters(info[0])
50
+ yield _formatter_cache[info[1]]
51
+ for _, formatter in find_plugin_formatters():
52
+ yield formatter
53
+
54
+
55
+ def find_formatter_class(alias):
56
+ """Lookup a formatter by alias.
57
+
58
+ Returns None if not found.
59
+ """
60
+ for module_name, name, aliases, _, _ in FORMATTERS.values():
61
+ if alias in aliases:
62
+ if name not in _formatter_cache:
63
+ _load_formatters(module_name)
64
+ return _formatter_cache[name]
65
+ for _, cls in find_plugin_formatters():
66
+ if alias in cls.aliases:
67
+ return cls
68
+
69
+
70
+ def get_formatter_by_name(_alias, **options):
71
+ """
72
+ Return an instance of a :class:`.Formatter` subclass that has `alias` in its
73
+ aliases list. The formatter is given the `options` at its instantiation.
74
+
75
+ Will raise :exc:`pygments.util.ClassNotFound` if no formatter with that
76
+ alias is found.
77
+ """
78
+ cls = find_formatter_class(_alias)
79
+ if cls is None:
80
+ raise ClassNotFound(f"no formatter found for name {_alias!r}")
81
+ return cls(**options)
82
+
83
+
84
+ def load_formatter_from_file(filename, formattername="CustomFormatter", **options):
85
+ """
86
+ Return a `Formatter` subclass instance loaded from the provided file, relative
87
+ to the current directory.
88
+
89
+ The file is expected to contain a Formatter class named ``formattername``
90
+ (by default, CustomFormatter). Users should be very careful with the input, because
91
+ this method is equivalent to running ``eval()`` on the input file. The formatter is
92
+ given the `options` at its instantiation.
93
+
94
+ :exc:`pygments.util.ClassNotFound` is raised if there are any errors loading
95
+ the formatter.
96
+
97
+ .. versionadded:: 2.2
98
+ """
99
+ try:
100
+ # This empty dict will contain the namespace for the exec'd file
101
+ custom_namespace = {}
102
+ with open(filename, 'rb') as f:
103
+ exec(f.read(), custom_namespace)
104
+ # Retrieve the class `formattername` from that namespace
105
+ if formattername not in custom_namespace:
106
+ raise ClassNotFound(f'no valid {formattername} class found in {filename}')
107
+ formatter_class = custom_namespace[formattername]
108
+ # And finally instantiate it with the options
109
+ return formatter_class(**options)
110
+ except OSError as err:
111
+ raise ClassNotFound(f'cannot read {filename}: {err}')
112
+ except ClassNotFound:
113
+ raise
114
+ except Exception as err:
115
+ raise ClassNotFound(f'error when loading custom formatter: {err}')
116
+
117
+
118
+ def get_formatter_for_filename(fn, **options):
119
+ """
120
+ Return a :class:`.Formatter` subclass instance that has a filename pattern
121
+ matching `fn`. The formatter is given the `options` at its instantiation.
122
+
123
+ Will raise :exc:`pygments.util.ClassNotFound` if no formatter for that filename
124
+ is found.
125
+ """
126
+ fn = basename(fn)
127
+ for modname, name, _, filenames, _ in FORMATTERS.values():
128
+ for filename in filenames:
129
+ if _fn_matches(fn, filename):
130
+ if name not in _formatter_cache:
131
+ _load_formatters(modname)
132
+ return _formatter_cache[name](**options)
133
+ for _name, cls in find_plugin_formatters():
134
+ for filename in cls.filenames:
135
+ if _fn_matches(fn, filename):
136
+ return cls(**options)
137
+ raise ClassNotFound(f"no formatter found for file name {fn!r}")
138
+
139
+
140
+ class _automodule(types.ModuleType):
141
+ """Automatically import formatters."""
142
+
143
+ def __getattr__(self, name):
144
+ info = FORMATTERS.get(name)
145
+ if info:
146
+ _load_formatters(info[0])
147
+ cls = _formatter_cache[info[1]]
148
+ setattr(self, name, cls)
149
+ return cls
150
+ raise AttributeError(name)
151
+
152
+
153
+ oldmod = sys.modules[__name__]
154
+ newmod = _automodule(__name__)
155
+ newmod.__dict__.update(oldmod.__dict__)
156
+ sys.modules[__name__] = newmod
157
+ del newmod.newmod, newmod.oldmod, newmod.sys, newmod.types
llava/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/bbcode.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ pygments.formatters.bbcode
3
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
4
+
5
+ BBcode formatter.
6
+
7
+ :copyright: Copyright 2006-2024 by the Pygments team, see AUTHORS.
8
+ :license: BSD, see LICENSE for details.
9
+ """
10
+
11
+
12
+ from pip._vendor.pygments.formatter import Formatter
13
+ from pip._vendor.pygments.util import get_bool_opt
14
+
15
+ __all__ = ['BBCodeFormatter']
16
+
17
+
18
+ class BBCodeFormatter(Formatter):
19
+ """
20
+ Format tokens with BBcodes. These formatting codes are used by many
21
+ bulletin boards, so you can highlight your sourcecode with pygments before
22
+ posting it there.
23
+
24
+ This formatter has no support for background colors and borders, as there
25
+ are no common BBcode tags for that.
26
+
27
+ Some board systems (e.g. phpBB) don't support colors in their [code] tag,
28
+ so you can't use the highlighting together with that tag.
29
+ Text in a [code] tag usually is shown with a monospace font (which this
30
+ formatter can do with the ``monofont`` option) and no spaces (which you
31
+ need for indentation) are removed.
32
+
33
+ Additional options accepted:
34
+
35
+ `style`
36
+ The style to use, can be a string or a Style subclass (default:
37
+ ``'default'``).
38
+
39
+ `codetag`
40
+ If set to true, put the output into ``[code]`` tags (default:
41
+ ``false``)
42
+
43
+ `monofont`
44
+ If set to true, add a tag to show the code with a monospace font
45
+ (default: ``false``).
46
+ """
47
+ name = 'BBCode'
48
+ aliases = ['bbcode', 'bb']
49
+ filenames = []
50
+
51
+ def __init__(self, **options):
52
+ Formatter.__init__(self, **options)
53
+ self._code = get_bool_opt(options, 'codetag', False)
54
+ self._mono = get_bool_opt(options, 'monofont', False)
55
+
56
+ self.styles = {}
57
+ self._make_styles()
58
+
59
+ def _make_styles(self):
60
+ for ttype, ndef in self.style:
61
+ start = end = ''
62
+ if ndef['color']:
63
+ start += '[color=#{}]'.format(ndef['color'])
64
+ end = '[/color]' + end
65
+ if ndef['bold']:
66
+ start += '[b]'
67
+ end = '[/b]' + end
68
+ if ndef['italic']:
69
+ start += '[i]'
70
+ end = '[/i]' + end
71
+ if ndef['underline']:
72
+ start += '[u]'
73
+ end = '[/u]' + end
74
+ # there are no common BBcodes for background-color and border
75
+
76
+ self.styles[ttype] = start, end
77
+
78
+ def format_unencoded(self, tokensource, outfile):
79
+ if self._code:
80
+ outfile.write('[code]')
81
+ if self._mono:
82
+ outfile.write('[font=monospace]')
83
+
84
+ lastval = ''
85
+ lasttype = None
86
+
87
+ for ttype, value in tokensource:
88
+ while ttype not in self.styles:
89
+ ttype = ttype.parent
90
+ if ttype == lasttype:
91
+ lastval += value
92
+ else:
93
+ if lastval:
94
+ start, end = self.styles[lasttype]
95
+ outfile.write(''.join((start, lastval, end)))
96
+ lastval = value
97
+ lasttype = ttype
98
+
99
+ if lastval:
100
+ start, end = self.styles[lasttype]
101
+ outfile.write(''.join((start, lastval, end)))
102
+
103
+ if self._mono:
104
+ outfile.write('[/font]')
105
+ if self._code:
106
+ outfile.write('[/code]')
107
+ if self._code or self._mono:
108
+ outfile.write('\n')
llava/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/groff.py ADDED
@@ -0,0 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ pygments.formatters.groff
3
+ ~~~~~~~~~~~~~~~~~~~~~~~~~
4
+
5
+ Formatter for groff output.
6
+
7
+ :copyright: Copyright 2006-2024 by the Pygments team, see AUTHORS.
8
+ :license: BSD, see LICENSE for details.
9
+ """
10
+
11
+ import math
12
+ from pip._vendor.pygments.formatter import Formatter
13
+ from pip._vendor.pygments.util import get_bool_opt, get_int_opt
14
+
15
+ __all__ = ['GroffFormatter']
16
+
17
+
18
+ class GroffFormatter(Formatter):
19
+ """
20
+ Format tokens with groff escapes to change their color and font style.
21
+
22
+ .. versionadded:: 2.11
23
+
24
+ Additional options accepted:
25
+
26
+ `style`
27
+ The style to use, can be a string or a Style subclass (default:
28
+ ``'default'``).
29
+
30
+ `monospaced`
31
+ If set to true, monospace font will be used (default: ``true``).
32
+
33
+ `linenos`
34
+ If set to true, print the line numbers (default: ``false``).
35
+
36
+ `wrap`
37
+ Wrap lines to the specified number of characters. Disabled if set to 0
38
+ (default: ``0``).
39
+ """
40
+
41
+ name = 'groff'
42
+ aliases = ['groff','troff','roff']
43
+ filenames = []
44
+
45
+ def __init__(self, **options):
46
+ Formatter.__init__(self, **options)
47
+
48
+ self.monospaced = get_bool_opt(options, 'monospaced', True)
49
+ self.linenos = get_bool_opt(options, 'linenos', False)
50
+ self._lineno = 0
51
+ self.wrap = get_int_opt(options, 'wrap', 0)
52
+ self._linelen = 0
53
+
54
+ self.styles = {}
55
+ self._make_styles()
56
+
57
+
58
+ def _make_styles(self):
59
+ regular = '\\f[CR]' if self.monospaced else '\\f[R]'
60
+ bold = '\\f[CB]' if self.monospaced else '\\f[B]'
61
+ italic = '\\f[CI]' if self.monospaced else '\\f[I]'
62
+
63
+ for ttype, ndef in self.style:
64
+ start = end = ''
65
+ if ndef['color']:
66
+ start += '\\m[{}]'.format(ndef['color'])
67
+ end = '\\m[]' + end
68
+ if ndef['bold']:
69
+ start += bold
70
+ end = regular + end
71
+ if ndef['italic']:
72
+ start += italic
73
+ end = regular + end
74
+ if ndef['bgcolor']:
75
+ start += '\\M[{}]'.format(ndef['bgcolor'])
76
+ end = '\\M[]' + end
77
+
78
+ self.styles[ttype] = start, end
79
+
80
+
81
+ def _define_colors(self, outfile):
82
+ colors = set()
83
+ for _, ndef in self.style:
84
+ if ndef['color'] is not None:
85
+ colors.add(ndef['color'])
86
+
87
+ for color in sorted(colors):
88
+ outfile.write('.defcolor ' + color + ' rgb #' + color + '\n')
89
+
90
+
91
+ def _write_lineno(self, outfile):
92
+ self._lineno += 1
93
+ outfile.write("%s% 4d " % (self._lineno != 1 and '\n' or '', self._lineno))
94
+
95
+
96
+ def _wrap_line(self, line):
97
+ length = len(line.rstrip('\n'))
98
+ space = ' ' if self.linenos else ''
99
+ newline = ''
100
+
101
+ if length > self.wrap:
102
+ for i in range(0, math.floor(length / self.wrap)):
103
+ chunk = line[i*self.wrap:i*self.wrap+self.wrap]
104
+ newline += (chunk + '\n' + space)
105
+ remainder = length % self.wrap
106
+ if remainder > 0:
107
+ newline += line[-remainder-1:]
108
+ self._linelen = remainder
109
+ elif self._linelen + length > self.wrap:
110
+ newline = ('\n' + space) + line
111
+ self._linelen = length
112
+ else:
113
+ newline = line
114
+ self._linelen += length
115
+
116
+ return newline
117
+
118
+
119
+ def _escape_chars(self, text):
120
+ text = text.replace('\\', '\\[u005C]'). \
121
+ replace('.', '\\[char46]'). \
122
+ replace('\'', '\\[u0027]'). \
123
+ replace('`', '\\[u0060]'). \
124
+ replace('~', '\\[u007E]')
125
+ copy = text
126
+
127
+ for char in copy:
128
+ if len(char) != len(char.encode()):
129
+ uni = char.encode('unicode_escape') \
130
+ .decode()[1:] \
131
+ .replace('x', 'u00') \
132
+ .upper()
133
+ text = text.replace(char, '\\[u' + uni[1:] + ']')
134
+
135
+ return text
136
+
137
+
138
+ def format_unencoded(self, tokensource, outfile):
139
+ self._define_colors(outfile)
140
+
141
+ outfile.write('.nf\n\\f[CR]\n')
142
+
143
+ if self.linenos:
144
+ self._write_lineno(outfile)
145
+
146
+ for ttype, value in tokensource:
147
+ while ttype not in self.styles:
148
+ ttype = ttype.parent
149
+ start, end = self.styles[ttype]
150
+
151
+ for line in value.splitlines(True):
152
+ if self.wrap > 0:
153
+ line = self._wrap_line(line)
154
+
155
+ if start and end:
156
+ text = self._escape_chars(line.rstrip('\n'))
157
+ if text != '':
158
+ outfile.write(''.join((start, text, end)))
159
+ else:
160
+ outfile.write(self._escape_chars(line.rstrip('\n')))
161
+
162
+ if line.endswith('\n'):
163
+ if self.linenos:
164
+ self._write_lineno(outfile)
165
+ self._linelen = 0
166
+ else:
167
+ outfile.write('\n')
168
+ self._linelen = 0
169
+
170
+ outfile.write('\n.fi')
llava/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/html.py ADDED
@@ -0,0 +1,987 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ pygments.formatters.html
3
+ ~~~~~~~~~~~~~~~~~~~~~~~~
4
+
5
+ Formatter for HTML output.
6
+
7
+ :copyright: Copyright 2006-2024 by the Pygments team, see AUTHORS.
8
+ :license: BSD, see LICENSE for details.
9
+ """
10
+
11
+ import functools
12
+ import os
13
+ import sys
14
+ import os.path
15
+ from io import StringIO
16
+
17
+ from pip._vendor.pygments.formatter import Formatter
18
+ from pip._vendor.pygments.token import Token, Text, STANDARD_TYPES
19
+ from pip._vendor.pygments.util import get_bool_opt, get_int_opt, get_list_opt
20
+
21
+ try:
22
+ import ctags
23
+ except ImportError:
24
+ ctags = None
25
+
26
+ __all__ = ['HtmlFormatter']
27
+
28
+
29
+ _escape_html_table = {
30
+ ord('&'): '&',
31
+ ord('<'): '&lt;',
32
+ ord('>'): '&gt;',
33
+ ord('"'): '&quot;',
34
+ ord("'"): '&#39;',
35
+ }
36
+
37
+
38
+ def escape_html(text, table=_escape_html_table):
39
+ """Escape &, <, > as well as single and double quotes for HTML."""
40
+ return text.translate(table)
41
+
42
+
43
+ def webify(color):
44
+ if color.startswith('calc') or color.startswith('var'):
45
+ return color
46
+ else:
47
+ return '#' + color
48
+
49
+
50
+ def _get_ttype_class(ttype):
51
+ fname = STANDARD_TYPES.get(ttype)
52
+ if fname:
53
+ return fname
54
+ aname = ''
55
+ while fname is None:
56
+ aname = '-' + ttype[-1] + aname
57
+ ttype = ttype.parent
58
+ fname = STANDARD_TYPES.get(ttype)
59
+ return fname + aname
60
+
61
+
62
+ CSSFILE_TEMPLATE = '''\
63
+ /*
64
+ generated by Pygments <https://pygments.org/>
65
+ Copyright 2006-2024 by the Pygments team.
66
+ Licensed under the BSD license, see LICENSE for details.
67
+ */
68
+ %(styledefs)s
69
+ '''
70
+
71
+ DOC_HEADER = '''\
72
+ <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
73
+ "http://www.w3.org/TR/html4/strict.dtd">
74
+ <!--
75
+ generated by Pygments <https://pygments.org/>
76
+ Copyright 2006-2024 by the Pygments team.
77
+ Licensed under the BSD license, see LICENSE for details.
78
+ -->
79
+ <html>
80
+ <head>
81
+ <title>%(title)s</title>
82
+ <meta http-equiv="content-type" content="text/html; charset=%(encoding)s">
83
+ <style type="text/css">
84
+ ''' + CSSFILE_TEMPLATE + '''
85
+ </style>
86
+ </head>
87
+ <body>
88
+ <h2>%(title)s</h2>
89
+
90
+ '''
91
+
92
+ DOC_HEADER_EXTERNALCSS = '''\
93
+ <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
94
+ "http://www.w3.org/TR/html4/strict.dtd">
95
+
96
+ <html>
97
+ <head>
98
+ <title>%(title)s</title>
99
+ <meta http-equiv="content-type" content="text/html; charset=%(encoding)s">
100
+ <link rel="stylesheet" href="%(cssfile)s" type="text/css">
101
+ </head>
102
+ <body>
103
+ <h2>%(title)s</h2>
104
+
105
+ '''
106
+
107
+ DOC_FOOTER = '''\
108
+ </body>
109
+ </html>
110
+ '''
111
+
112
+
113
+ class HtmlFormatter(Formatter):
114
+ r"""
115
+ Format tokens as HTML 4 ``<span>`` tags. By default, the content is enclosed
116
+ in a ``<pre>`` tag, itself wrapped in a ``<div>`` tag (but see the `nowrap` option).
117
+ The ``<div>``'s CSS class can be set by the `cssclass` option.
118
+
119
+ If the `linenos` option is set to ``"table"``, the ``<pre>`` is
120
+ additionally wrapped inside a ``<table>`` which has one row and two
121
+ cells: one containing the line numbers and one containing the code.
122
+ Example:
123
+
124
+ .. sourcecode:: html
125
+
126
+ <div class="highlight" >
127
+ <table><tr>
128
+ <td class="linenos" title="click to toggle"
129
+ onclick="with (this.firstChild.style)
130
+ { display = (display == '') ? 'none' : '' }">
131
+ <pre>1
132
+ 2</pre>
133
+ </td>
134
+ <td class="code">
135
+ <pre><span class="Ke">def </span><span class="NaFu">foo</span>(bar):
136
+ <span class="Ke">pass</span>
137
+ </pre>
138
+ </td>
139
+ </tr></table></div>
140
+
141
+ (whitespace added to improve clarity).
142
+
143
+ A list of lines can be specified using the `hl_lines` option to make these
144
+ lines highlighted (as of Pygments 0.11).
145
+
146
+ With the `full` option, a complete HTML 4 document is output, including
147
+ the style definitions inside a ``<style>`` tag, or in a separate file if
148
+ the `cssfile` option is given.
149
+
150
+ When `tagsfile` is set to the path of a ctags index file, it is used to
151
+ generate hyperlinks from names to their definition. You must enable
152
+ `lineanchors` and run ctags with the `-n` option for this to work. The
153
+ `python-ctags` module from PyPI must be installed to use this feature;
154
+ otherwise a `RuntimeError` will be raised.
155
+
156
+ The `get_style_defs(arg='')` method of a `HtmlFormatter` returns a string
157
+ containing CSS rules for the CSS classes used by the formatter. The
158
+ argument `arg` can be used to specify additional CSS selectors that
159
+ are prepended to the classes. A call `fmter.get_style_defs('td .code')`
160
+ would result in the following CSS classes:
161
+
162
+ .. sourcecode:: css
163
+
164
+ td .code .kw { font-weight: bold; color: #00FF00 }
165
+ td .code .cm { color: #999999 }
166
+ ...
167
+
168
+ If you have Pygments 0.6 or higher, you can also pass a list or tuple to the
169
+ `get_style_defs()` method to request multiple prefixes for the tokens:
170
+
171
+ .. sourcecode:: python
172
+
173
+ formatter.get_style_defs(['div.syntax pre', 'pre.syntax'])
174
+
175
+ The output would then look like this:
176
+
177
+ .. sourcecode:: css
178
+
179
+ div.syntax pre .kw,
180
+ pre.syntax .kw { font-weight: bold; color: #00FF00 }
181
+ div.syntax pre .cm,
182
+ pre.syntax .cm { color: #999999 }
183
+ ...
184
+
185
+ Additional options accepted:
186
+
187
+ `nowrap`
188
+ If set to ``True``, don't add a ``<pre>`` and a ``<div>`` tag
189
+ around the tokens. This disables most other options (default: ``False``).
190
+
191
+ `full`
192
+ Tells the formatter to output a "full" document, i.e. a complete
193
+ self-contained document (default: ``False``).
194
+
195
+ `title`
196
+ If `full` is true, the title that should be used to caption the
197
+ document (default: ``''``).
198
+
199
+ `style`
200
+ The style to use, can be a string or a Style subclass (default:
201
+ ``'default'``). This option has no effect if the `cssfile`
202
+ and `noclobber_cssfile` option are given and the file specified in
203
+ `cssfile` exists.
204
+
205
+ `noclasses`
206
+ If set to true, token ``<span>`` tags (as well as line number elements)
207
+ will not use CSS classes, but inline styles. This is not recommended
208
+ for larger pieces of code since it increases output size by quite a bit
209
+ (default: ``False``).
210
+
211
+ `classprefix`
212
+ Since the token types use relatively short class names, they may clash
213
+ with some of your own class names. In this case you can use the
214
+ `classprefix` option to give a string to prepend to all Pygments-generated
215
+ CSS class names for token types.
216
+ Note that this option also affects the output of `get_style_defs()`.
217
+
218
+ `cssclass`
219
+ CSS class for the wrapping ``<div>`` tag (default: ``'highlight'``).
220
+ If you set this option, the default selector for `get_style_defs()`
221
+ will be this class.
222
+
223
+ .. versionadded:: 0.9
224
+ If you select the ``'table'`` line numbers, the wrapping table will
225
+ have a CSS class of this string plus ``'table'``, the default is
226
+ accordingly ``'highlighttable'``.
227
+
228
+ `cssstyles`
229
+ Inline CSS styles for the wrapping ``<div>`` tag (default: ``''``).
230
+
231
+ `prestyles`
232
+ Inline CSS styles for the ``<pre>`` tag (default: ``''``).
233
+
234
+ .. versionadded:: 0.11
235
+
236
+ `cssfile`
237
+ If the `full` option is true and this option is given, it must be the
238
+ name of an external file. If the filename does not include an absolute
239
+ path, the file's path will be assumed to be relative to the main output
240
+ file's path, if the latter can be found. The stylesheet is then written
241
+ to this file instead of the HTML file.
242
+
243
+ .. versionadded:: 0.6
244
+
245
+ `noclobber_cssfile`
246
+ If `cssfile` is given and the specified file exists, the css file will
247
+ not be overwritten. This allows the use of the `full` option in
248
+ combination with a user specified css file. Default is ``False``.
249
+
250
+ .. versionadded:: 1.1
251
+
252
+ `linenos`
253
+ If set to ``'table'``, output line numbers as a table with two cells,
254
+ one containing the line numbers, the other the whole code. This is
255
+ copy-and-paste-friendly, but may cause alignment problems with some
256
+ browsers or fonts. If set to ``'inline'``, the line numbers will be
257
+ integrated in the ``<pre>`` tag that contains the code (that setting
258
+ is *new in Pygments 0.8*).
259
+
260
+ For compatibility with Pygments 0.7 and earlier, every true value
261
+ except ``'inline'`` means the same as ``'table'`` (in particular, that
262
+ means also ``True``).
263
+
264
+ The default value is ``False``, which means no line numbers at all.
265
+
266
+ **Note:** with the default ("table") line number mechanism, the line
267
+ numbers and code can have different line heights in Internet Explorer
268
+ unless you give the enclosing ``<pre>`` tags an explicit ``line-height``
269
+ CSS property (you get the default line spacing with ``line-height:
270
+ 125%``).
271
+
272
+ `hl_lines`
273
+ Specify a list of lines to be highlighted. The line numbers are always
274
+ relative to the input (i.e. the first line is line 1) and are
275
+ independent of `linenostart`.
276
+
277
+ .. versionadded:: 0.11
278
+
279
+ `linenostart`
280
+ The line number for the first line (default: ``1``).
281
+
282
+ `linenostep`
283
+ If set to a number n > 1, only every nth line number is printed.
284
+
285
+ `linenospecial`
286
+ If set to a number n > 0, every nth line number is given the CSS
287
+ class ``"special"`` (default: ``0``).
288
+
289
+ `nobackground`
290
+ If set to ``True``, the formatter won't output the background color
291
+ for the wrapping element (this automatically defaults to ``False``
292
+ when there is no wrapping element [eg: no argument for the
293
+ `get_syntax_defs` method given]) (default: ``False``).
294
+
295
+ .. versionadded:: 0.6
296
+
297
+ `lineseparator`
298
+ This string is output between lines of code. It defaults to ``"\n"``,
299
+ which is enough to break a line inside ``<pre>`` tags, but you can
300
+ e.g. set it to ``"<br>"`` to get HTML line breaks.
301
+
302
+ .. versionadded:: 0.7
303
+
304
+ `lineanchors`
305
+ If set to a nonempty string, e.g. ``foo``, the formatter will wrap each
306
+ output line in an anchor tag with an ``id`` (and `name`) of ``foo-linenumber``.
307
+ This allows easy linking to certain lines.
308
+
309
+ .. versionadded:: 0.9
310
+
311
+ `linespans`
312
+ If set to a nonempty string, e.g. ``foo``, the formatter will wrap each
313
+ output line in a span tag with an ``id`` of ``foo-linenumber``.
314
+ This allows easy access to lines via javascript.
315
+
316
+ .. versionadded:: 1.6
317
+
318
+ `anchorlinenos`
319
+ If set to `True`, will wrap line numbers in <a> tags. Used in
320
+ combination with `linenos` and `lineanchors`.
321
+
322
+ `tagsfile`
323
+ If set to the path of a ctags file, wrap names in anchor tags that
324
+ link to their definitions. `lineanchors` should be used, and the
325
+ tags file should specify line numbers (see the `-n` option to ctags).
326
+ The tags file is assumed to be encoded in UTF-8.
327
+
328
+ .. versionadded:: 1.6
329
+
330
+ `tagurlformat`
331
+ A string formatting pattern used to generate links to ctags definitions.
332
+ Available variables are `%(path)s`, `%(fname)s` and `%(fext)s`.
333
+ Defaults to an empty string, resulting in just `#prefix-number` links.
334
+
335
+ .. versionadded:: 1.6
336
+
337
+ `filename`
338
+ A string used to generate a filename when rendering ``<pre>`` blocks,
339
+ for example if displaying source code. If `linenos` is set to
340
+ ``'table'`` then the filename will be rendered in an initial row
341
+ containing a single `<th>` which spans both columns.
342
+
343
+ .. versionadded:: 2.1
344
+
345
+ `wrapcode`
346
+ Wrap the code inside ``<pre>`` blocks using ``<code>``, as recommended
347
+ by the HTML5 specification.
348
+
349
+ .. versionadded:: 2.4
350
+
351
+ `debug_token_types`
352
+ Add ``title`` attributes to all token ``<span>`` tags that show the
353
+ name of the token.
354
+
355
+ .. versionadded:: 2.10
356
+
357
+
358
+ **Subclassing the HTML formatter**
359
+
360
+ .. versionadded:: 0.7
361
+
362
+ The HTML formatter is now built in a way that allows easy subclassing, thus
363
+ customizing the output HTML code. The `format()` method calls
364
+ `self._format_lines()` which returns a generator that yields tuples of ``(1,
365
+ line)``, where the ``1`` indicates that the ``line`` is a line of the
366
+ formatted source code.
367
+
368
+ If the `nowrap` option is set, the generator is the iterated over and the
369
+ resulting HTML is output.
370
+
371
+ Otherwise, `format()` calls `self.wrap()`, which wraps the generator with
372
+ other generators. These may add some HTML code to the one generated by
373
+ `_format_lines()`, either by modifying the lines generated by the latter,
374
+ then yielding them again with ``(1, line)``, and/or by yielding other HTML
375
+ code before or after the lines, with ``(0, html)``. The distinction between
376
+ source lines and other code makes it possible to wrap the generator multiple
377
+ times.
378
+
379
+ The default `wrap()` implementation adds a ``<div>`` and a ``<pre>`` tag.
380
+
381
+ A custom `HtmlFormatter` subclass could look like this:
382
+
383
+ .. sourcecode:: python
384
+
385
+ class CodeHtmlFormatter(HtmlFormatter):
386
+
387
+ def wrap(self, source, *, include_div):
388
+ return self._wrap_code(source)
389
+
390
+ def _wrap_code(self, source):
391
+ yield 0, '<code>'
392
+ for i, t in source:
393
+ if i == 1:
394
+ # it's a line of formatted code
395
+ t += '<br>'
396
+ yield i, t
397
+ yield 0, '</code>'
398
+
399
+ This results in wrapping the formatted lines with a ``<code>`` tag, where the
400
+ source lines are broken using ``<br>`` tags.
401
+
402
+ After calling `wrap()`, the `format()` method also adds the "line numbers"
403
+ and/or "full document" wrappers if the respective options are set. Then, all
404
+ HTML yielded by the wrapped generator is output.
405
+ """
406
+
407
+ name = 'HTML'
408
+ aliases = ['html']
409
+ filenames = ['*.html', '*.htm']
410
+
411
+ def __init__(self, **options):
412
+ Formatter.__init__(self, **options)
413
+ self.title = self._decodeifneeded(self.title)
414
+ self.nowrap = get_bool_opt(options, 'nowrap', False)
415
+ self.noclasses = get_bool_opt(options, 'noclasses', False)
416
+ self.classprefix = options.get('classprefix', '')
417
+ self.cssclass = self._decodeifneeded(options.get('cssclass', 'highlight'))
418
+ self.cssstyles = self._decodeifneeded(options.get('cssstyles', ''))
419
+ self.prestyles = self._decodeifneeded(options.get('prestyles', ''))
420
+ self.cssfile = self._decodeifneeded(options.get('cssfile', ''))
421
+ self.noclobber_cssfile = get_bool_opt(options, 'noclobber_cssfile', False)
422
+ self.tagsfile = self._decodeifneeded(options.get('tagsfile', ''))
423
+ self.tagurlformat = self._decodeifneeded(options.get('tagurlformat', ''))
424
+ self.filename = self._decodeifneeded(options.get('filename', ''))
425
+ self.wrapcode = get_bool_opt(options, 'wrapcode', False)
426
+ self.span_element_openers = {}
427
+ self.debug_token_types = get_bool_opt(options, 'debug_token_types', False)
428
+
429
+ if self.tagsfile:
430
+ if not ctags:
431
+ raise RuntimeError('The "ctags" package must to be installed '
432
+ 'to be able to use the "tagsfile" feature.')
433
+ self._ctags = ctags.CTags(self.tagsfile)
434
+
435
+ linenos = options.get('linenos', False)
436
+ if linenos == 'inline':
437
+ self.linenos = 2
438
+ elif linenos:
439
+ # compatibility with <= 0.7
440
+ self.linenos = 1
441
+ else:
442
+ self.linenos = 0
443
+ self.linenostart = abs(get_int_opt(options, 'linenostart', 1))
444
+ self.linenostep = abs(get_int_opt(options, 'linenostep', 1))
445
+ self.linenospecial = abs(get_int_opt(options, 'linenospecial', 0))
446
+ self.nobackground = get_bool_opt(options, 'nobackground', False)
447
+ self.lineseparator = options.get('lineseparator', '\n')
448
+ self.lineanchors = options.get('lineanchors', '')
449
+ self.linespans = options.get('linespans', '')
450
+ self.anchorlinenos = get_bool_opt(options, 'anchorlinenos', False)
451
+ self.hl_lines = set()
452
+ for lineno in get_list_opt(options, 'hl_lines', []):
453
+ try:
454
+ self.hl_lines.add(int(lineno))
455
+ except ValueError:
456
+ pass
457
+
458
+ self._create_stylesheet()
459
+
460
+ def _get_css_class(self, ttype):
461
+ """Return the css class of this token type prefixed with
462
+ the classprefix option."""
463
+ ttypeclass = _get_ttype_class(ttype)
464
+ if ttypeclass:
465
+ return self.classprefix + ttypeclass
466
+ return ''
467
+
468
+ def _get_css_classes(self, ttype):
469
+ """Return the CSS classes of this token type prefixed with the classprefix option."""
470
+ cls = self._get_css_class(ttype)
471
+ while ttype not in STANDARD_TYPES:
472
+ ttype = ttype.parent
473
+ cls = self._get_css_class(ttype) + ' ' + cls
474
+ return cls or ''
475
+
476
+ def _get_css_inline_styles(self, ttype):
477
+ """Return the inline CSS styles for this token type."""
478
+ cclass = self.ttype2class.get(ttype)
479
+ while cclass is None:
480
+ ttype = ttype.parent
481
+ cclass = self.ttype2class.get(ttype)
482
+ return cclass or ''
483
+
484
+ def _create_stylesheet(self):
485
+ t2c = self.ttype2class = {Token: ''}
486
+ c2s = self.class2style = {}
487
+ for ttype, ndef in self.style:
488
+ name = self._get_css_class(ttype)
489
+ style = ''
490
+ if ndef['color']:
491
+ style += 'color: {}; '.format(webify(ndef['color']))
492
+ if ndef['bold']:
493
+ style += 'font-weight: bold; '
494
+ if ndef['italic']:
495
+ style += 'font-style: italic; '
496
+ if ndef['underline']:
497
+ style += 'text-decoration: underline; '
498
+ if ndef['bgcolor']:
499
+ style += 'background-color: {}; '.format(webify(ndef['bgcolor']))
500
+ if ndef['border']:
501
+ style += 'border: 1px solid {}; '.format(webify(ndef['border']))
502
+ if style:
503
+ t2c[ttype] = name
504
+ # save len(ttype) to enable ordering the styles by
505
+ # hierarchy (necessary for CSS cascading rules!)
506
+ c2s[name] = (style[:-2], ttype, len(ttype))
507
+
508
+ def get_style_defs(self, arg=None):
509
+ """
510
+ Return CSS style definitions for the classes produced by the current
511
+ highlighting style. ``arg`` can be a string or list of selectors to
512
+ insert before the token type classes.
513
+ """
514
+ style_lines = []
515
+
516
+ style_lines.extend(self.get_linenos_style_defs())
517
+ style_lines.extend(self.get_background_style_defs(arg))
518
+ style_lines.extend(self.get_token_style_defs(arg))
519
+
520
+ return '\n'.join(style_lines)
521
+
522
+ def get_token_style_defs(self, arg=None):
523
+ prefix = self.get_css_prefix(arg)
524
+
525
+ styles = [
526
+ (level, ttype, cls, style)
527
+ for cls, (style, ttype, level) in self.class2style.items()
528
+ if cls and style
529
+ ]
530
+ styles.sort()
531
+
532
+ lines = [
533
+ f'{prefix(cls)} {{ {style} }} /* {repr(ttype)[6:]} */'
534
+ for (level, ttype, cls, style) in styles
535
+ ]
536
+
537
+ return lines
538
+
539
+ def get_background_style_defs(self, arg=None):
540
+ prefix = self.get_css_prefix(arg)
541
+ bg_color = self.style.background_color
542
+ hl_color = self.style.highlight_color
543
+
544
+ lines = []
545
+
546
+ if arg and not self.nobackground and bg_color is not None:
547
+ text_style = ''
548
+ if Text in self.ttype2class:
549
+ text_style = ' ' + self.class2style[self.ttype2class[Text]][0]
550
+ lines.insert(
551
+ 0, '{}{{ background: {};{} }}'.format(
552
+ prefix(''), bg_color, text_style
553
+ )
554
+ )
555
+ if hl_color is not None:
556
+ lines.insert(
557
+ 0, '{} {{ background-color: {} }}'.format(prefix('hll'), hl_color)
558
+ )
559
+
560
+ return lines
561
+
562
+ def get_linenos_style_defs(self):
563
+ lines = [
564
+ f'pre {{ {self._pre_style} }}',
565
+ f'td.linenos .normal {{ {self._linenos_style} }}',
566
+ f'span.linenos {{ {self._linenos_style} }}',
567
+ f'td.linenos .special {{ {self._linenos_special_style} }}',
568
+ f'span.linenos.special {{ {self._linenos_special_style} }}',
569
+ ]
570
+
571
+ return lines
572
+
573
+ def get_css_prefix(self, arg):
574
+ if arg is None:
575
+ arg = ('cssclass' in self.options and '.'+self.cssclass or '')
576
+ if isinstance(arg, str):
577
+ args = [arg]
578
+ else:
579
+ args = list(arg)
580
+
581
+ def prefix(cls):
582
+ if cls:
583
+ cls = '.' + cls
584
+ tmp = []
585
+ for arg in args:
586
+ tmp.append((arg and arg + ' ' or '') + cls)
587
+ return ', '.join(tmp)
588
+
589
+ return prefix
590
+
591
+ @property
592
+ def _pre_style(self):
593
+ return 'line-height: 125%;'
594
+
595
+ @property
596
+ def _linenos_style(self):
597
+ color = self.style.line_number_color
598
+ background_color = self.style.line_number_background_color
599
+ return f'color: {color}; background-color: {background_color}; padding-left: 5px; padding-right: 5px;'
600
+
601
+ @property
602
+ def _linenos_special_style(self):
603
+ color = self.style.line_number_special_color
604
+ background_color = self.style.line_number_special_background_color
605
+ return f'color: {color}; background-color: {background_color}; padding-left: 5px; padding-right: 5px;'
606
+
607
+ def _decodeifneeded(self, value):
608
+ if isinstance(value, bytes):
609
+ if self.encoding:
610
+ return value.decode(self.encoding)
611
+ return value.decode()
612
+ return value
613
+
614
+ def _wrap_full(self, inner, outfile):
615
+ if self.cssfile:
616
+ if os.path.isabs(self.cssfile):
617
+ # it's an absolute filename
618
+ cssfilename = self.cssfile
619
+ else:
620
+ try:
621
+ filename = outfile.name
622
+ if not filename or filename[0] == '<':
623
+ # pseudo files, e.g. name == '<fdopen>'
624
+ raise AttributeError
625
+ cssfilename = os.path.join(os.path.dirname(filename),
626
+ self.cssfile)
627
+ except AttributeError:
628
+ print('Note: Cannot determine output file name, '
629
+ 'using current directory as base for the CSS file name',
630
+ file=sys.stderr)
631
+ cssfilename = self.cssfile
632
+ # write CSS file only if noclobber_cssfile isn't given as an option.
633
+ try:
634
+ if not os.path.exists(cssfilename) or not self.noclobber_cssfile:
635
+ with open(cssfilename, "w", encoding="utf-8") as cf:
636
+ cf.write(CSSFILE_TEMPLATE %
637
+ {'styledefs': self.get_style_defs('body')})
638
+ except OSError as err:
639
+ err.strerror = 'Error writing CSS file: ' + err.strerror
640
+ raise
641
+
642
+ yield 0, (DOC_HEADER_EXTERNALCSS %
643
+ dict(title=self.title,
644
+ cssfile=self.cssfile,
645
+ encoding=self.encoding))
646
+ else:
647
+ yield 0, (DOC_HEADER %
648
+ dict(title=self.title,
649
+ styledefs=self.get_style_defs('body'),
650
+ encoding=self.encoding))
651
+
652
+ yield from inner
653
+ yield 0, DOC_FOOTER
654
+
655
+ def _wrap_tablelinenos(self, inner):
656
+ dummyoutfile = StringIO()
657
+ lncount = 0
658
+ for t, line in inner:
659
+ if t:
660
+ lncount += 1
661
+ dummyoutfile.write(line)
662
+
663
+ fl = self.linenostart
664
+ mw = len(str(lncount + fl - 1))
665
+ sp = self.linenospecial
666
+ st = self.linenostep
667
+ anchor_name = self.lineanchors or self.linespans
668
+ aln = self.anchorlinenos
669
+ nocls = self.noclasses
670
+
671
+ lines = []
672
+
673
+ for i in range(fl, fl+lncount):
674
+ print_line = i % st == 0
675
+ special_line = sp and i % sp == 0
676
+
677
+ if print_line:
678
+ line = '%*d' % (mw, i)
679
+ if aln:
680
+ line = '<a href="#%s-%d">%s</a>' % (anchor_name, i, line)
681
+ else:
682
+ line = ' ' * mw
683
+
684
+ if nocls:
685
+ if special_line:
686
+ style = f' style="{self._linenos_special_style}"'
687
+ else:
688
+ style = f' style="{self._linenos_style}"'
689
+ else:
690
+ if special_line:
691
+ style = ' class="special"'
692
+ else:
693
+ style = ' class="normal"'
694
+
695
+ if style:
696
+ line = f'<span{style}>{line}</span>'
697
+
698
+ lines.append(line)
699
+
700
+ ls = '\n'.join(lines)
701
+
702
+ # If a filename was specified, we can't put it into the code table as it
703
+ # would misalign the line numbers. Hence we emit a separate row for it.
704
+ filename_tr = ""
705
+ if self.filename:
706
+ filename_tr = (
707
+ '<tr><th colspan="2" class="filename">'
708
+ '<span class="filename">' + self.filename + '</span>'
709
+ '</th></tr>')
710
+
711
+ # in case you wonder about the seemingly redundant <div> here: since the
712
+ # content in the other cell also is wrapped in a div, some browsers in
713
+ # some configurations seem to mess up the formatting...
714
+ yield 0, (f'<table class="{self.cssclass}table">' + filename_tr +
715
+ '<tr><td class="linenos"><div class="linenodiv"><pre>' +
716
+ ls + '</pre></div></td><td class="code">')
717
+ yield 0, '<div>'
718
+ yield 0, dummyoutfile.getvalue()
719
+ yield 0, '</div>'
720
+ yield 0, '</td></tr></table>'
721
+
722
+
723
+ def _wrap_inlinelinenos(self, inner):
724
+ # need a list of lines since we need the width of a single number :(
725
+ inner_lines = list(inner)
726
+ sp = self.linenospecial
727
+ st = self.linenostep
728
+ num = self.linenostart
729
+ mw = len(str(len(inner_lines) + num - 1))
730
+ anchor_name = self.lineanchors or self.linespans
731
+ aln = self.anchorlinenos
732
+ nocls = self.noclasses
733
+
734
+ for _, inner_line in inner_lines:
735
+ print_line = num % st == 0
736
+ special_line = sp and num % sp == 0
737
+
738
+ if print_line:
739
+ line = '%*d' % (mw, num)
740
+ else:
741
+ line = ' ' * mw
742
+
743
+ if nocls:
744
+ if special_line:
745
+ style = f' style="{self._linenos_special_style}"'
746
+ else:
747
+ style = f' style="{self._linenos_style}"'
748
+ else:
749
+ if special_line:
750
+ style = ' class="linenos special"'
751
+ else:
752
+ style = ' class="linenos"'
753
+
754
+ if style:
755
+ linenos = f'<span{style}>{line}</span>'
756
+ else:
757
+ linenos = line
758
+
759
+ if aln:
760
+ yield 1, ('<a href="#%s-%d">%s</a>' % (anchor_name, num, linenos) +
761
+ inner_line)
762
+ else:
763
+ yield 1, linenos + inner_line
764
+ num += 1
765
+
766
+ def _wrap_lineanchors(self, inner):
767
+ s = self.lineanchors
768
+ # subtract 1 since we have to increment i *before* yielding
769
+ i = self.linenostart - 1
770
+ for t, line in inner:
771
+ if t:
772
+ i += 1
773
+ href = "" if self.linenos else ' href="#%s-%d"' % (s, i)
774
+ yield 1, '<a id="%s-%d" name="%s-%d"%s></a>' % (s, i, s, i, href) + line
775
+ else:
776
+ yield 0, line
777
+
778
+ def _wrap_linespans(self, inner):
779
+ s = self.linespans
780
+ i = self.linenostart - 1
781
+ for t, line in inner:
782
+ if t:
783
+ i += 1
784
+ yield 1, '<span id="%s-%d">%s</span>' % (s, i, line)
785
+ else:
786
+ yield 0, line
787
+
788
+ def _wrap_div(self, inner):
789
+ style = []
790
+ if (self.noclasses and not self.nobackground and
791
+ self.style.background_color is not None):
792
+ style.append(f'background: {self.style.background_color}')
793
+ if self.cssstyles:
794
+ style.append(self.cssstyles)
795
+ style = '; '.join(style)
796
+
797
+ yield 0, ('<div' + (self.cssclass and f' class="{self.cssclass}"') +
798
+ (style and (f' style="{style}"')) + '>')
799
+ yield from inner
800
+ yield 0, '</div>\n'
801
+
802
+ def _wrap_pre(self, inner):
803
+ style = []
804
+ if self.prestyles:
805
+ style.append(self.prestyles)
806
+ if self.noclasses:
807
+ style.append(self._pre_style)
808
+ style = '; '.join(style)
809
+
810
+ if self.filename and self.linenos != 1:
811
+ yield 0, ('<span class="filename">' + self.filename + '</span>')
812
+
813
+ # the empty span here is to keep leading empty lines from being
814
+ # ignored by HTML parsers
815
+ yield 0, ('<pre' + (style and f' style="{style}"') + '><span></span>')
816
+ yield from inner
817
+ yield 0, '</pre>'
818
+
819
+ def _wrap_code(self, inner):
820
+ yield 0, '<code>'
821
+ yield from inner
822
+ yield 0, '</code>'
823
+
824
+ @functools.lru_cache(maxsize=100)
825
+ def _translate_parts(self, value):
826
+ """HTML-escape a value and split it by newlines."""
827
+ return value.translate(_escape_html_table).split('\n')
828
+
829
+ def _format_lines(self, tokensource):
830
+ """
831
+ Just format the tokens, without any wrapping tags.
832
+ Yield individual lines.
833
+ """
834
+ nocls = self.noclasses
835
+ lsep = self.lineseparator
836
+ tagsfile = self.tagsfile
837
+
838
+ lspan = ''
839
+ line = []
840
+ for ttype, value in tokensource:
841
+ try:
842
+ cspan = self.span_element_openers[ttype]
843
+ except KeyError:
844
+ title = ' title="{}"'.format('.'.join(ttype)) if self.debug_token_types else ''
845
+ if nocls:
846
+ css_style = self._get_css_inline_styles(ttype)
847
+ if css_style:
848
+ css_style = self.class2style[css_style][0]
849
+ cspan = f'<span style="{css_style}"{title}>'
850
+ else:
851
+ cspan = ''
852
+ else:
853
+ css_class = self._get_css_classes(ttype)
854
+ if css_class:
855
+ cspan = f'<span class="{css_class}"{title}>'
856
+ else:
857
+ cspan = ''
858
+ self.span_element_openers[ttype] = cspan
859
+
860
+ parts = self._translate_parts(value)
861
+
862
+ if tagsfile and ttype in Token.Name:
863
+ filename, linenumber = self._lookup_ctag(value)
864
+ if linenumber:
865
+ base, filename = os.path.split(filename)
866
+ if base:
867
+ base += '/'
868
+ filename, extension = os.path.splitext(filename)
869
+ url = self.tagurlformat % {'path': base, 'fname': filename,
870
+ 'fext': extension}
871
+ parts[0] = "<a href=\"%s#%s-%d\">%s" % \
872
+ (url, self.lineanchors, linenumber, parts[0])
873
+ parts[-1] = parts[-1] + "</a>"
874
+
875
+ # for all but the last line
876
+ for part in parts[:-1]:
877
+ if line:
878
+ # Also check for part being non-empty, so we avoid creating
879
+ # empty <span> tags
880
+ if lspan != cspan and part:
881
+ line.extend(((lspan and '</span>'), cspan, part,
882
+ (cspan and '</span>'), lsep))
883
+ else: # both are the same, or the current part was empty
884
+ line.extend((part, (lspan and '</span>'), lsep))
885
+ yield 1, ''.join(line)
886
+ line = []
887
+ elif part:
888
+ yield 1, ''.join((cspan, part, (cspan and '</span>'), lsep))
889
+ else:
890
+ yield 1, lsep
891
+ # for the last line
892
+ if line and parts[-1]:
893
+ if lspan != cspan:
894
+ line.extend(((lspan and '</span>'), cspan, parts[-1]))
895
+ lspan = cspan
896
+ else:
897
+ line.append(parts[-1])
898
+ elif parts[-1]:
899
+ line = [cspan, parts[-1]]
900
+ lspan = cspan
901
+ # else we neither have to open a new span nor set lspan
902
+
903
+ if line:
904
+ line.extend(((lspan and '</span>'), lsep))
905
+ yield 1, ''.join(line)
906
+
907
+ def _lookup_ctag(self, token):
908
+ entry = ctags.TagEntry()
909
+ if self._ctags.find(entry, token.encode(), 0):
910
+ return entry['file'].decode(), entry['lineNumber']
911
+ else:
912
+ return None, None
913
+
914
+ def _highlight_lines(self, tokensource):
915
+ """
916
+ Highlighted the lines specified in the `hl_lines` option by
917
+ post-processing the token stream coming from `_format_lines`.
918
+ """
919
+ hls = self.hl_lines
920
+
921
+ for i, (t, value) in enumerate(tokensource):
922
+ if t != 1:
923
+ yield t, value
924
+ if i + 1 in hls: # i + 1 because Python indexes start at 0
925
+ if self.noclasses:
926
+ style = ''
927
+ if self.style.highlight_color is not None:
928
+ style = (f' style="background-color: {self.style.highlight_color}"')
929
+ yield 1, f'<span{style}>{value}</span>'
930
+ else:
931
+ yield 1, f'<span class="hll">{value}</span>'
932
+ else:
933
+ yield 1, value
934
+
935
+ def wrap(self, source):
936
+ """
937
+ Wrap the ``source``, which is a generator yielding
938
+ individual lines, in custom generators. See docstring
939
+ for `format`. Can be overridden.
940
+ """
941
+
942
+ output = source
943
+ if self.wrapcode:
944
+ output = self._wrap_code(output)
945
+
946
+ output = self._wrap_pre(output)
947
+
948
+ return output
949
+
950
+ def format_unencoded(self, tokensource, outfile):
951
+ """
952
+ The formatting process uses several nested generators; which of
953
+ them are used is determined by the user's options.
954
+
955
+ Each generator should take at least one argument, ``inner``,
956
+ and wrap the pieces of text generated by this.
957
+
958
+ Always yield 2-tuples: (code, text). If "code" is 1, the text
959
+ is part of the original tokensource being highlighted, if it's
960
+ 0, the text is some piece of wrapping. This makes it possible to
961
+ use several different wrappers that process the original source
962
+ linewise, e.g. line number generators.
963
+ """
964
+ source = self._format_lines(tokensource)
965
+
966
+ # As a special case, we wrap line numbers before line highlighting
967
+ # so the line numbers get wrapped in the highlighting tag.
968
+ if not self.nowrap and self.linenos == 2:
969
+ source = self._wrap_inlinelinenos(source)
970
+
971
+ if self.hl_lines:
972
+ source = self._highlight_lines(source)
973
+
974
+ if not self.nowrap:
975
+ if self.lineanchors:
976
+ source = self._wrap_lineanchors(source)
977
+ if self.linespans:
978
+ source = self._wrap_linespans(source)
979
+ source = self.wrap(source)
980
+ if self.linenos == 1:
981
+ source = self._wrap_tablelinenos(source)
982
+ source = self._wrap_div(source)
983
+ if self.full:
984
+ source = self._wrap_full(source, outfile)
985
+
986
+ for t, piece in source:
987
+ outfile.write(piece)
llava/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/img.py ADDED
@@ -0,0 +1,685 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ pygments.formatters.img
3
+ ~~~~~~~~~~~~~~~~~~~~~~~
4
+
5
+ Formatter for Pixmap output.
6
+
7
+ :copyright: Copyright 2006-2024 by the Pygments team, see AUTHORS.
8
+ :license: BSD, see LICENSE for details.
9
+ """
10
+ import os
11
+ import sys
12
+
13
+ from pip._vendor.pygments.formatter import Formatter
14
+ from pip._vendor.pygments.util import get_bool_opt, get_int_opt, get_list_opt, \
15
+ get_choice_opt
16
+
17
+ import subprocess
18
+
19
+ # Import this carefully
20
+ try:
21
+ from PIL import Image, ImageDraw, ImageFont
22
+ pil_available = True
23
+ except ImportError:
24
+ pil_available = False
25
+
26
+ try:
27
+ import _winreg
28
+ except ImportError:
29
+ try:
30
+ import winreg as _winreg
31
+ except ImportError:
32
+ _winreg = None
33
+
34
+ __all__ = ['ImageFormatter', 'GifImageFormatter', 'JpgImageFormatter',
35
+ 'BmpImageFormatter']
36
+
37
+
38
+ # For some unknown reason every font calls it something different
39
+ STYLES = {
40
+ 'NORMAL': ['', 'Roman', 'Book', 'Normal', 'Regular', 'Medium'],
41
+ 'ITALIC': ['Oblique', 'Italic'],
42
+ 'BOLD': ['Bold'],
43
+ 'BOLDITALIC': ['Bold Oblique', 'Bold Italic'],
44
+ }
45
+
46
+ # A sane default for modern systems
47
+ DEFAULT_FONT_NAME_NIX = 'DejaVu Sans Mono'
48
+ DEFAULT_FONT_NAME_WIN = 'Courier New'
49
+ DEFAULT_FONT_NAME_MAC = 'Menlo'
50
+
51
+
52
+ class PilNotAvailable(ImportError):
53
+ """When Python imaging library is not available"""
54
+
55
+
56
+ class FontNotFound(Exception):
57
+ """When there are no usable fonts specified"""
58
+
59
+
60
+ class FontManager:
61
+ """
62
+ Manages a set of fonts: normal, italic, bold, etc...
63
+ """
64
+
65
+ def __init__(self, font_name, font_size=14):
66
+ self.font_name = font_name
67
+ self.font_size = font_size
68
+ self.fonts = {}
69
+ self.encoding = None
70
+ self.variable = False
71
+ if hasattr(font_name, 'read') or os.path.isfile(font_name):
72
+ font = ImageFont.truetype(font_name, self.font_size)
73
+ self.variable = True
74
+ for style in STYLES:
75
+ self.fonts[style] = font
76
+
77
+ return
78
+
79
+ if sys.platform.startswith('win'):
80
+ if not font_name:
81
+ self.font_name = DEFAULT_FONT_NAME_WIN
82
+ self._create_win()
83
+ elif sys.platform.startswith('darwin'):
84
+ if not font_name:
85
+ self.font_name = DEFAULT_FONT_NAME_MAC
86
+ self._create_mac()
87
+ else:
88
+ if not font_name:
89
+ self.font_name = DEFAULT_FONT_NAME_NIX
90
+ self._create_nix()
91
+
92
+ def _get_nix_font_path(self, name, style):
93
+ proc = subprocess.Popen(['fc-list', f"{name}:style={style}", 'file'],
94
+ stdout=subprocess.PIPE, stderr=None)
95
+ stdout, _ = proc.communicate()
96
+ if proc.returncode == 0:
97
+ lines = stdout.splitlines()
98
+ for line in lines:
99
+ if line.startswith(b'Fontconfig warning:'):
100
+ continue
101
+ path = line.decode().strip().strip(':')
102
+ if path:
103
+ return path
104
+ return None
105
+
106
+ def _create_nix(self):
107
+ for name in STYLES['NORMAL']:
108
+ path = self._get_nix_font_path(self.font_name, name)
109
+ if path is not None:
110
+ self.fonts['NORMAL'] = ImageFont.truetype(path, self.font_size)
111
+ break
112
+ else:
113
+ raise FontNotFound(f'No usable fonts named: "{self.font_name}"')
114
+ for style in ('ITALIC', 'BOLD', 'BOLDITALIC'):
115
+ for stylename in STYLES[style]:
116
+ path = self._get_nix_font_path(self.font_name, stylename)
117
+ if path is not None:
118
+ self.fonts[style] = ImageFont.truetype(path, self.font_size)
119
+ break
120
+ else:
121
+ if style == 'BOLDITALIC':
122
+ self.fonts[style] = self.fonts['BOLD']
123
+ else:
124
+ self.fonts[style] = self.fonts['NORMAL']
125
+
126
+ def _get_mac_font_path(self, font_map, name, style):
127
+ return font_map.get((name + ' ' + style).strip().lower())
128
+
129
+ def _create_mac(self):
130
+ font_map = {}
131
+ for font_dir in (os.path.join(os.getenv("HOME"), 'Library/Fonts/'),
132
+ '/Library/Fonts/', '/System/Library/Fonts/'):
133
+ font_map.update(
134
+ (os.path.splitext(f)[0].lower(), os.path.join(font_dir, f))
135
+ for f in os.listdir(font_dir)
136
+ if f.lower().endswith(('ttf', 'ttc')))
137
+
138
+ for name in STYLES['NORMAL']:
139
+ path = self._get_mac_font_path(font_map, self.font_name, name)
140
+ if path is not None:
141
+ self.fonts['NORMAL'] = ImageFont.truetype(path, self.font_size)
142
+ break
143
+ else:
144
+ raise FontNotFound(f'No usable fonts named: "{self.font_name}"')
145
+ for style in ('ITALIC', 'BOLD', 'BOLDITALIC'):
146
+ for stylename in STYLES[style]:
147
+ path = self._get_mac_font_path(font_map, self.font_name, stylename)
148
+ if path is not None:
149
+ self.fonts[style] = ImageFont.truetype(path, self.font_size)
150
+ break
151
+ else:
152
+ if style == 'BOLDITALIC':
153
+ self.fonts[style] = self.fonts['BOLD']
154
+ else:
155
+ self.fonts[style] = self.fonts['NORMAL']
156
+
157
+ def _lookup_win(self, key, basename, styles, fail=False):
158
+ for suffix in ('', ' (TrueType)'):
159
+ for style in styles:
160
+ try:
161
+ valname = '{}{}{}'.format(basename, style and ' '+style, suffix)
162
+ val, _ = _winreg.QueryValueEx(key, valname)
163
+ return val
164
+ except OSError:
165
+ continue
166
+ else:
167
+ if fail:
168
+ raise FontNotFound(f'Font {basename} ({styles[0]}) not found in registry')
169
+ return None
170
+
171
+ def _create_win(self):
172
+ lookuperror = None
173
+ keynames = [ (_winreg.HKEY_CURRENT_USER, r'Software\Microsoft\Windows NT\CurrentVersion\Fonts'),
174
+ (_winreg.HKEY_CURRENT_USER, r'Software\Microsoft\Windows\CurrentVersion\Fonts'),
175
+ (_winreg.HKEY_LOCAL_MACHINE, r'Software\Microsoft\Windows NT\CurrentVersion\Fonts'),
176
+ (_winreg.HKEY_LOCAL_MACHINE, r'Software\Microsoft\Windows\CurrentVersion\Fonts') ]
177
+ for keyname in keynames:
178
+ try:
179
+ key = _winreg.OpenKey(*keyname)
180
+ try:
181
+ path = self._lookup_win(key, self.font_name, STYLES['NORMAL'], True)
182
+ self.fonts['NORMAL'] = ImageFont.truetype(path, self.font_size)
183
+ for style in ('ITALIC', 'BOLD', 'BOLDITALIC'):
184
+ path = self._lookup_win(key, self.font_name, STYLES[style])
185
+ if path:
186
+ self.fonts[style] = ImageFont.truetype(path, self.font_size)
187
+ else:
188
+ if style == 'BOLDITALIC':
189
+ self.fonts[style] = self.fonts['BOLD']
190
+ else:
191
+ self.fonts[style] = self.fonts['NORMAL']
192
+ return
193
+ except FontNotFound as err:
194
+ lookuperror = err
195
+ finally:
196
+ _winreg.CloseKey(key)
197
+ except OSError:
198
+ pass
199
+ else:
200
+ # If we get here, we checked all registry keys and had no luck
201
+ # We can be in one of two situations now:
202
+ # * All key lookups failed. In this case lookuperror is None and we
203
+ # will raise a generic error
204
+ # * At least one lookup failed with a FontNotFound error. In this
205
+ # case, we will raise that as a more specific error
206
+ if lookuperror:
207
+ raise lookuperror
208
+ raise FontNotFound('Can\'t open Windows font registry key')
209
+
210
+ def get_char_size(self):
211
+ """
212
+ Get the character size.
213
+ """
214
+ return self.get_text_size('M')
215
+
216
+ def get_text_size(self, text):
217
+ """
218
+ Get the text size (width, height).
219
+ """
220
+ font = self.fonts['NORMAL']
221
+ if hasattr(font, 'getbbox'): # Pillow >= 9.2.0
222
+ return font.getbbox(text)[2:4]
223
+ else:
224
+ return font.getsize(text)
225
+
226
+ def get_font(self, bold, oblique):
227
+ """
228
+ Get the font based on bold and italic flags.
229
+ """
230
+ if bold and oblique:
231
+ if self.variable:
232
+ return self.get_style('BOLDITALIC')
233
+
234
+ return self.fonts['BOLDITALIC']
235
+ elif bold:
236
+ if self.variable:
237
+ return self.get_style('BOLD')
238
+
239
+ return self.fonts['BOLD']
240
+ elif oblique:
241
+ if self.variable:
242
+ return self.get_style('ITALIC')
243
+
244
+ return self.fonts['ITALIC']
245
+ else:
246
+ if self.variable:
247
+ return self.get_style('NORMAL')
248
+
249
+ return self.fonts['NORMAL']
250
+
251
+ def get_style(self, style):
252
+ """
253
+ Get the specified style of the font if it is a variable font.
254
+ If not found, return the normal font.
255
+ """
256
+ font = self.fonts[style]
257
+ for style_name in STYLES[style]:
258
+ try:
259
+ font.set_variation_by_name(style_name)
260
+ return font
261
+ except ValueError:
262
+ pass
263
+ except OSError:
264
+ return font
265
+
266
+ return font
267
+
268
+
269
+ class ImageFormatter(Formatter):
270
+ """
271
+ Create a PNG image from source code. This uses the Python Imaging Library to
272
+ generate a pixmap from the source code.
273
+
274
+ .. versionadded:: 0.10
275
+
276
+ Additional options accepted:
277
+
278
+ `image_format`
279
+ An image format to output to that is recognised by PIL, these include:
280
+
281
+ * "PNG" (default)
282
+ * "JPEG"
283
+ * "BMP"
284
+ * "GIF"
285
+
286
+ `line_pad`
287
+ The extra spacing (in pixels) between each line of text.
288
+
289
+ Default: 2
290
+
291
+ `font_name`
292
+ The font name to be used as the base font from which others, such as
293
+ bold and italic fonts will be generated. This really should be a
294
+ monospace font to look sane.
295
+ If a filename or a file-like object is specified, the user must
296
+ provide different styles of the font.
297
+
298
+ Default: "Courier New" on Windows, "Menlo" on Mac OS, and
299
+ "DejaVu Sans Mono" on \\*nix
300
+
301
+ `font_size`
302
+ The font size in points to be used.
303
+
304
+ Default: 14
305
+
306
+ `image_pad`
307
+ The padding, in pixels to be used at each edge of the resulting image.
308
+
309
+ Default: 10
310
+
311
+ `line_numbers`
312
+ Whether line numbers should be shown: True/False
313
+
314
+ Default: True
315
+
316
+ `line_number_start`
317
+ The line number of the first line.
318
+
319
+ Default: 1
320
+
321
+ `line_number_step`
322
+ The step used when printing line numbers.
323
+
324
+ Default: 1
325
+
326
+ `line_number_bg`
327
+ The background colour (in "#123456" format) of the line number bar, or
328
+ None to use the style background color.
329
+
330
+ Default: "#eed"
331
+
332
+ `line_number_fg`
333
+ The text color of the line numbers (in "#123456"-like format).
334
+
335
+ Default: "#886"
336
+
337
+ `line_number_chars`
338
+ The number of columns of line numbers allowable in the line number
339
+ margin.
340
+
341
+ Default: 2
342
+
343
+ `line_number_bold`
344
+ Whether line numbers will be bold: True/False
345
+
346
+ Default: False
347
+
348
+ `line_number_italic`
349
+ Whether line numbers will be italicized: True/False
350
+
351
+ Default: False
352
+
353
+ `line_number_separator`
354
+ Whether a line will be drawn between the line number area and the
355
+ source code area: True/False
356
+
357
+ Default: True
358
+
359
+ `line_number_pad`
360
+ The horizontal padding (in pixels) between the line number margin, and
361
+ the source code area.
362
+
363
+ Default: 6
364
+
365
+ `hl_lines`
366
+ Specify a list of lines to be highlighted.
367
+
368
+ .. versionadded:: 1.2
369
+
370
+ Default: empty list
371
+
372
+ `hl_color`
373
+ Specify the color for highlighting lines.
374
+
375
+ .. versionadded:: 1.2
376
+
377
+ Default: highlight color of the selected style
378
+ """
379
+
380
+ # Required by the pygments mapper
381
+ name = 'img'
382
+ aliases = ['img', 'IMG', 'png']
383
+ filenames = ['*.png']
384
+
385
+ unicodeoutput = False
386
+
387
+ default_image_format = 'png'
388
+
389
+ def __init__(self, **options):
390
+ """
391
+ See the class docstring for explanation of options.
392
+ """
393
+ if not pil_available:
394
+ raise PilNotAvailable(
395
+ 'Python Imaging Library is required for this formatter')
396
+ Formatter.__init__(self, **options)
397
+ self.encoding = 'latin1' # let pygments.format() do the right thing
398
+ # Read the style
399
+ self.styles = dict(self.style)
400
+ if self.style.background_color is None:
401
+ self.background_color = '#fff'
402
+ else:
403
+ self.background_color = self.style.background_color
404
+ # Image options
405
+ self.image_format = get_choice_opt(
406
+ options, 'image_format', ['png', 'jpeg', 'gif', 'bmp'],
407
+ self.default_image_format, normcase=True)
408
+ self.image_pad = get_int_opt(options, 'image_pad', 10)
409
+ self.line_pad = get_int_opt(options, 'line_pad', 2)
410
+ # The fonts
411
+ fontsize = get_int_opt(options, 'font_size', 14)
412
+ self.fonts = FontManager(options.get('font_name', ''), fontsize)
413
+ self.fontw, self.fonth = self.fonts.get_char_size()
414
+ # Line number options
415
+ self.line_number_fg = options.get('line_number_fg', '#886')
416
+ self.line_number_bg = options.get('line_number_bg', '#eed')
417
+ self.line_number_chars = get_int_opt(options,
418
+ 'line_number_chars', 2)
419
+ self.line_number_bold = get_bool_opt(options,
420
+ 'line_number_bold', False)
421
+ self.line_number_italic = get_bool_opt(options,
422
+ 'line_number_italic', False)
423
+ self.line_number_pad = get_int_opt(options, 'line_number_pad', 6)
424
+ self.line_numbers = get_bool_opt(options, 'line_numbers', True)
425
+ self.line_number_separator = get_bool_opt(options,
426
+ 'line_number_separator', True)
427
+ self.line_number_step = get_int_opt(options, 'line_number_step', 1)
428
+ self.line_number_start = get_int_opt(options, 'line_number_start', 1)
429
+ if self.line_numbers:
430
+ self.line_number_width = (self.fontw * self.line_number_chars +
431
+ self.line_number_pad * 2)
432
+ else:
433
+ self.line_number_width = 0
434
+ self.hl_lines = []
435
+ hl_lines_str = get_list_opt(options, 'hl_lines', [])
436
+ for line in hl_lines_str:
437
+ try:
438
+ self.hl_lines.append(int(line))
439
+ except ValueError:
440
+ pass
441
+ self.hl_color = options.get('hl_color',
442
+ self.style.highlight_color) or '#f90'
443
+ self.drawables = []
444
+
445
+ def get_style_defs(self, arg=''):
446
+ raise NotImplementedError('The -S option is meaningless for the image '
447
+ 'formatter. Use -O style=<stylename> instead.')
448
+
449
+ def _get_line_height(self):
450
+ """
451
+ Get the height of a line.
452
+ """
453
+ return self.fonth + self.line_pad
454
+
455
+ def _get_line_y(self, lineno):
456
+ """
457
+ Get the Y coordinate of a line number.
458
+ """
459
+ return lineno * self._get_line_height() + self.image_pad
460
+
461
+ def _get_char_width(self):
462
+ """
463
+ Get the width of a character.
464
+ """
465
+ return self.fontw
466
+
467
+ def _get_char_x(self, linelength):
468
+ """
469
+ Get the X coordinate of a character position.
470
+ """
471
+ return linelength + self.image_pad + self.line_number_width
472
+
473
+ def _get_text_pos(self, linelength, lineno):
474
+ """
475
+ Get the actual position for a character and line position.
476
+ """
477
+ return self._get_char_x(linelength), self._get_line_y(lineno)
478
+
479
+ def _get_linenumber_pos(self, lineno):
480
+ """
481
+ Get the actual position for the start of a line number.
482
+ """
483
+ return (self.image_pad, self._get_line_y(lineno))
484
+
485
+ def _get_text_color(self, style):
486
+ """
487
+ Get the correct color for the token from the style.
488
+ """
489
+ if style['color'] is not None:
490
+ fill = '#' + style['color']
491
+ else:
492
+ fill = '#000'
493
+ return fill
494
+
495
+ def _get_text_bg_color(self, style):
496
+ """
497
+ Get the correct background color for the token from the style.
498
+ """
499
+ if style['bgcolor'] is not None:
500
+ bg_color = '#' + style['bgcolor']
501
+ else:
502
+ bg_color = None
503
+ return bg_color
504
+
505
+ def _get_style_font(self, style):
506
+ """
507
+ Get the correct font for the style.
508
+ """
509
+ return self.fonts.get_font(style['bold'], style['italic'])
510
+
511
+ def _get_image_size(self, maxlinelength, maxlineno):
512
+ """
513
+ Get the required image size.
514
+ """
515
+ return (self._get_char_x(maxlinelength) + self.image_pad,
516
+ self._get_line_y(maxlineno + 0) + self.image_pad)
517
+
518
+ def _draw_linenumber(self, posno, lineno):
519
+ """
520
+ Remember a line number drawable to paint later.
521
+ """
522
+ self._draw_text(
523
+ self._get_linenumber_pos(posno),
524
+ str(lineno).rjust(self.line_number_chars),
525
+ font=self.fonts.get_font(self.line_number_bold,
526
+ self.line_number_italic),
527
+ text_fg=self.line_number_fg,
528
+ text_bg=None,
529
+ )
530
+
531
+ def _draw_text(self, pos, text, font, text_fg, text_bg):
532
+ """
533
+ Remember a single drawable tuple to paint later.
534
+ """
535
+ self.drawables.append((pos, text, font, text_fg, text_bg))
536
+
537
+ def _create_drawables(self, tokensource):
538
+ """
539
+ Create drawables for the token content.
540
+ """
541
+ lineno = charno = maxcharno = 0
542
+ maxlinelength = linelength = 0
543
+ for ttype, value in tokensource:
544
+ while ttype not in self.styles:
545
+ ttype = ttype.parent
546
+ style = self.styles[ttype]
547
+ # TODO: make sure tab expansion happens earlier in the chain. It
548
+ # really ought to be done on the input, as to do it right here is
549
+ # quite complex.
550
+ value = value.expandtabs(4)
551
+ lines = value.splitlines(True)
552
+ # print lines
553
+ for i, line in enumerate(lines):
554
+ temp = line.rstrip('\n')
555
+ if temp:
556
+ self._draw_text(
557
+ self._get_text_pos(linelength, lineno),
558
+ temp,
559
+ font = self._get_style_font(style),
560
+ text_fg = self._get_text_color(style),
561
+ text_bg = self._get_text_bg_color(style),
562
+ )
563
+ temp_width, _ = self.fonts.get_text_size(temp)
564
+ linelength += temp_width
565
+ maxlinelength = max(maxlinelength, linelength)
566
+ charno += len(temp)
567
+ maxcharno = max(maxcharno, charno)
568
+ if line.endswith('\n'):
569
+ # add a line for each extra line in the value
570
+ linelength = 0
571
+ charno = 0
572
+ lineno += 1
573
+ self.maxlinelength = maxlinelength
574
+ self.maxcharno = maxcharno
575
+ self.maxlineno = lineno
576
+
577
+ def _draw_line_numbers(self):
578
+ """
579
+ Create drawables for the line numbers.
580
+ """
581
+ if not self.line_numbers:
582
+ return
583
+ for p in range(self.maxlineno):
584
+ n = p + self.line_number_start
585
+ if (n % self.line_number_step) == 0:
586
+ self._draw_linenumber(p, n)
587
+
588
+ def _paint_line_number_bg(self, im):
589
+ """
590
+ Paint the line number background on the image.
591
+ """
592
+ if not self.line_numbers:
593
+ return
594
+ if self.line_number_fg is None:
595
+ return
596
+ draw = ImageDraw.Draw(im)
597
+ recth = im.size[-1]
598
+ rectw = self.image_pad + self.line_number_width - self.line_number_pad
599
+ draw.rectangle([(0, 0), (rectw, recth)],
600
+ fill=self.line_number_bg)
601
+ if self.line_number_separator:
602
+ draw.line([(rectw, 0), (rectw, recth)], fill=self.line_number_fg)
603
+ del draw
604
+
605
+ def format(self, tokensource, outfile):
606
+ """
607
+ Format ``tokensource``, an iterable of ``(tokentype, tokenstring)``
608
+ tuples and write it into ``outfile``.
609
+
610
+ This implementation calculates where it should draw each token on the
611
+ pixmap, then calculates the required pixmap size and draws the items.
612
+ """
613
+ self._create_drawables(tokensource)
614
+ self._draw_line_numbers()
615
+ im = Image.new(
616
+ 'RGB',
617
+ self._get_image_size(self.maxlinelength, self.maxlineno),
618
+ self.background_color
619
+ )
620
+ self._paint_line_number_bg(im)
621
+ draw = ImageDraw.Draw(im)
622
+ # Highlight
623
+ if self.hl_lines:
624
+ x = self.image_pad + self.line_number_width - self.line_number_pad + 1
625
+ recth = self._get_line_height()
626
+ rectw = im.size[0] - x
627
+ for linenumber in self.hl_lines:
628
+ y = self._get_line_y(linenumber - 1)
629
+ draw.rectangle([(x, y), (x + rectw, y + recth)],
630
+ fill=self.hl_color)
631
+ for pos, value, font, text_fg, text_bg in self.drawables:
632
+ if text_bg:
633
+ # see deprecations https://pillow.readthedocs.io/en/stable/releasenotes/9.2.0.html#font-size-and-offset-methods
634
+ if hasattr(draw, 'textsize'):
635
+ text_size = draw.textsize(text=value, font=font)
636
+ else:
637
+ text_size = font.getbbox(value)[2:]
638
+ draw.rectangle([pos[0], pos[1], pos[0] + text_size[0], pos[1] + text_size[1]], fill=text_bg)
639
+ draw.text(pos, value, font=font, fill=text_fg)
640
+ im.save(outfile, self.image_format.upper())
641
+
642
+
643
+ # Add one formatter per format, so that the "-f gif" option gives the correct result
644
+ # when used in pygmentize.
645
+
646
+ class GifImageFormatter(ImageFormatter):
647
+ """
648
+ Create a GIF image from source code. This uses the Python Imaging Library to
649
+ generate a pixmap from the source code.
650
+
651
+ .. versionadded:: 1.0
652
+ """
653
+
654
+ name = 'img_gif'
655
+ aliases = ['gif']
656
+ filenames = ['*.gif']
657
+ default_image_format = 'gif'
658
+
659
+
660
+ class JpgImageFormatter(ImageFormatter):
661
+ """
662
+ Create a JPEG image from source code. This uses the Python Imaging Library to
663
+ generate a pixmap from the source code.
664
+
665
+ .. versionadded:: 1.0
666
+ """
667
+
668
+ name = 'img_jpg'
669
+ aliases = ['jpg', 'jpeg']
670
+ filenames = ['*.jpg']
671
+ default_image_format = 'jpeg'
672
+
673
+
674
+ class BmpImageFormatter(ImageFormatter):
675
+ """
676
+ Create a bitmap image from source code. This uses the Python Imaging Library to
677
+ generate a pixmap from the source code.
678
+
679
+ .. versionadded:: 1.0
680
+ """
681
+
682
+ name = 'img_bmp'
683
+ aliases = ['bmp', 'bitmap']
684
+ filenames = ['*.bmp']
685
+ default_image_format = 'bmp'
llava/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/latex.py ADDED
@@ -0,0 +1,518 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ pygments.formatters.latex
3
+ ~~~~~~~~~~~~~~~~~~~~~~~~~
4
+
5
+ Formatter for LaTeX fancyvrb output.
6
+
7
+ :copyright: Copyright 2006-2024 by the Pygments team, see AUTHORS.
8
+ :license: BSD, see LICENSE for details.
9
+ """
10
+
11
+ from io import StringIO
12
+
13
+ from pip._vendor.pygments.formatter import Formatter
14
+ from pip._vendor.pygments.lexer import Lexer, do_insertions
15
+ from pip._vendor.pygments.token import Token, STANDARD_TYPES
16
+ from pip._vendor.pygments.util import get_bool_opt, get_int_opt
17
+
18
+
19
+ __all__ = ['LatexFormatter']
20
+
21
+
22
+ def escape_tex(text, commandprefix):
23
+ return text.replace('\\', '\x00'). \
24
+ replace('{', '\x01'). \
25
+ replace('}', '\x02'). \
26
+ replace('\x00', rf'\{commandprefix}Zbs{{}}'). \
27
+ replace('\x01', rf'\{commandprefix}Zob{{}}'). \
28
+ replace('\x02', rf'\{commandprefix}Zcb{{}}'). \
29
+ replace('^', rf'\{commandprefix}Zca{{}}'). \
30
+ replace('_', rf'\{commandprefix}Zus{{}}'). \
31
+ replace('&', rf'\{commandprefix}Zam{{}}'). \
32
+ replace('<', rf'\{commandprefix}Zlt{{}}'). \
33
+ replace('>', rf'\{commandprefix}Zgt{{}}'). \
34
+ replace('#', rf'\{commandprefix}Zsh{{}}'). \
35
+ replace('%', rf'\{commandprefix}Zpc{{}}'). \
36
+ replace('$', rf'\{commandprefix}Zdl{{}}'). \
37
+ replace('-', rf'\{commandprefix}Zhy{{}}'). \
38
+ replace("'", rf'\{commandprefix}Zsq{{}}'). \
39
+ replace('"', rf'\{commandprefix}Zdq{{}}'). \
40
+ replace('~', rf'\{commandprefix}Zti{{}}')
41
+
42
+
43
+ DOC_TEMPLATE = r'''
44
+ \documentclass{%(docclass)s}
45
+ \usepackage{fancyvrb}
46
+ \usepackage{color}
47
+ \usepackage[%(encoding)s]{inputenc}
48
+ %(preamble)s
49
+
50
+ %(styledefs)s
51
+
52
+ \begin{document}
53
+
54
+ \section*{%(title)s}
55
+
56
+ %(code)s
57
+ \end{document}
58
+ '''
59
+
60
+ ## Small explanation of the mess below :)
61
+ #
62
+ # The previous version of the LaTeX formatter just assigned a command to
63
+ # each token type defined in the current style. That obviously is
64
+ # problematic if the highlighted code is produced for a different style
65
+ # than the style commands themselves.
66
+ #
67
+ # This version works much like the HTML formatter which assigns multiple
68
+ # CSS classes to each <span> tag, from the most specific to the least
69
+ # specific token type, thus falling back to the parent token type if one
70
+ # is not defined. Here, the classes are there too and use the same short
71
+ # forms given in token.STANDARD_TYPES.
72
+ #
73
+ # Highlighted code now only uses one custom command, which by default is
74
+ # \PY and selectable by the commandprefix option (and in addition the
75
+ # escapes \PYZat, \PYZlb and \PYZrb which haven't been renamed for
76
+ # backwards compatibility purposes).
77
+ #
78
+ # \PY has two arguments: the classes, separated by +, and the text to
79
+ # render in that style. The classes are resolved into the respective
80
+ # style commands by magic, which serves to ignore unknown classes.
81
+ #
82
+ # The magic macros are:
83
+ # * \PY@it, \PY@bf, etc. are unconditionally wrapped around the text
84
+ # to render in \PY@do. Their definition determines the style.
85
+ # * \PY@reset resets \PY@it etc. to do nothing.
86
+ # * \PY@toks parses the list of classes, using magic inspired by the
87
+ # keyval package (but modified to use plusses instead of commas
88
+ # because fancyvrb redefines commas inside its environments).
89
+ # * \PY@tok processes one class, calling the \PY@tok@classname command
90
+ # if it exists.
91
+ # * \PY@tok@classname sets the \PY@it etc. to reflect the chosen style
92
+ # for its class.
93
+ # * \PY resets the style, parses the classnames and then calls \PY@do.
94
+ #
95
+ # Tip: to read this code, print it out in substituted form using e.g.
96
+ # >>> print STYLE_TEMPLATE % {'cp': 'PY'}
97
+
98
+ STYLE_TEMPLATE = r'''
99
+ \makeatletter
100
+ \def\%(cp)s@reset{\let\%(cp)s@it=\relax \let\%(cp)s@bf=\relax%%
101
+ \let\%(cp)s@ul=\relax \let\%(cp)s@tc=\relax%%
102
+ \let\%(cp)s@bc=\relax \let\%(cp)s@ff=\relax}
103
+ \def\%(cp)s@tok#1{\csname %(cp)s@tok@#1\endcsname}
104
+ \def\%(cp)s@toks#1+{\ifx\relax#1\empty\else%%
105
+ \%(cp)s@tok{#1}\expandafter\%(cp)s@toks\fi}
106
+ \def\%(cp)s@do#1{\%(cp)s@bc{\%(cp)s@tc{\%(cp)s@ul{%%
107
+ \%(cp)s@it{\%(cp)s@bf{\%(cp)s@ff{#1}}}}}}}
108
+ \def\%(cp)s#1#2{\%(cp)s@reset\%(cp)s@toks#1+\relax+\%(cp)s@do{#2}}
109
+
110
+ %(styles)s
111
+
112
+ \def\%(cp)sZbs{\char`\\}
113
+ \def\%(cp)sZus{\char`\_}
114
+ \def\%(cp)sZob{\char`\{}
115
+ \def\%(cp)sZcb{\char`\}}
116
+ \def\%(cp)sZca{\char`\^}
117
+ \def\%(cp)sZam{\char`\&}
118
+ \def\%(cp)sZlt{\char`\<}
119
+ \def\%(cp)sZgt{\char`\>}
120
+ \def\%(cp)sZsh{\char`\#}
121
+ \def\%(cp)sZpc{\char`\%%}
122
+ \def\%(cp)sZdl{\char`\$}
123
+ \def\%(cp)sZhy{\char`\-}
124
+ \def\%(cp)sZsq{\char`\'}
125
+ \def\%(cp)sZdq{\char`\"}
126
+ \def\%(cp)sZti{\char`\~}
127
+ %% for compatibility with earlier versions
128
+ \def\%(cp)sZat{@}
129
+ \def\%(cp)sZlb{[}
130
+ \def\%(cp)sZrb{]}
131
+ \makeatother
132
+ '''
133
+
134
+
135
+ def _get_ttype_name(ttype):
136
+ fname = STANDARD_TYPES.get(ttype)
137
+ if fname:
138
+ return fname
139
+ aname = ''
140
+ while fname is None:
141
+ aname = ttype[-1] + aname
142
+ ttype = ttype.parent
143
+ fname = STANDARD_TYPES.get(ttype)
144
+ return fname + aname
145
+
146
+
147
+ class LatexFormatter(Formatter):
148
+ r"""
149
+ Format tokens as LaTeX code. This needs the `fancyvrb` and `color`
150
+ standard packages.
151
+
152
+ Without the `full` option, code is formatted as one ``Verbatim``
153
+ environment, like this:
154
+
155
+ .. sourcecode:: latex
156
+
157
+ \begin{Verbatim}[commandchars=\\\{\}]
158
+ \PY{k}{def }\PY{n+nf}{foo}(\PY{n}{bar}):
159
+ \PY{k}{pass}
160
+ \end{Verbatim}
161
+
162
+ Wrapping can be disabled using the `nowrap` option.
163
+
164
+ The special command used here (``\PY``) and all the other macros it needs
165
+ are output by the `get_style_defs` method.
166
+
167
+ With the `full` option, a complete LaTeX document is output, including
168
+ the command definitions in the preamble.
169
+
170
+ The `get_style_defs()` method of a `LatexFormatter` returns a string
171
+ containing ``\def`` commands defining the macros needed inside the
172
+ ``Verbatim`` environments.
173
+
174
+ Additional options accepted:
175
+
176
+ `nowrap`
177
+ If set to ``True``, don't wrap the tokens at all, not even inside a
178
+ ``\begin{Verbatim}`` environment. This disables most other options
179
+ (default: ``False``).
180
+
181
+ `style`
182
+ The style to use, can be a string or a Style subclass (default:
183
+ ``'default'``).
184
+
185
+ `full`
186
+ Tells the formatter to output a "full" document, i.e. a complete
187
+ self-contained document (default: ``False``).
188
+
189
+ `title`
190
+ If `full` is true, the title that should be used to caption the
191
+ document (default: ``''``).
192
+
193
+ `docclass`
194
+ If the `full` option is enabled, this is the document class to use
195
+ (default: ``'article'``).
196
+
197
+ `preamble`
198
+ If the `full` option is enabled, this can be further preamble commands,
199
+ e.g. ``\usepackage`` (default: ``''``).
200
+
201
+ `linenos`
202
+ If set to ``True``, output line numbers (default: ``False``).
203
+
204
+ `linenostart`
205
+ The line number for the first line (default: ``1``).
206
+
207
+ `linenostep`
208
+ If set to a number n > 1, only every nth line number is printed.
209
+
210
+ `verboptions`
211
+ Additional options given to the Verbatim environment (see the *fancyvrb*
212
+ docs for possible values) (default: ``''``).
213
+
214
+ `commandprefix`
215
+ The LaTeX commands used to produce colored output are constructed
216
+ using this prefix and some letters (default: ``'PY'``).
217
+
218
+ .. versionadded:: 0.7
219
+ .. versionchanged:: 0.10
220
+ The default is now ``'PY'`` instead of ``'C'``.
221
+
222
+ `texcomments`
223
+ If set to ``True``, enables LaTeX comment lines. That is, LaTex markup
224
+ in comment tokens is not escaped so that LaTeX can render it (default:
225
+ ``False``).
226
+
227
+ .. versionadded:: 1.2
228
+
229
+ `mathescape`
230
+ If set to ``True``, enables LaTeX math mode escape in comments. That
231
+ is, ``'$...$'`` inside a comment will trigger math mode (default:
232
+ ``False``).
233
+
234
+ .. versionadded:: 1.2
235
+
236
+ `escapeinside`
237
+ If set to a string of length 2, enables escaping to LaTeX. Text
238
+ delimited by these 2 characters is read as LaTeX code and
239
+ typeset accordingly. It has no effect in string literals. It has
240
+ no effect in comments if `texcomments` or `mathescape` is
241
+ set. (default: ``''``).
242
+
243
+ .. versionadded:: 2.0
244
+
245
+ `envname`
246
+ Allows you to pick an alternative environment name replacing Verbatim.
247
+ The alternate environment still has to support Verbatim's option syntax.
248
+ (default: ``'Verbatim'``).
249
+
250
+ .. versionadded:: 2.0
251
+ """
252
+ name = 'LaTeX'
253
+ aliases = ['latex', 'tex']
254
+ filenames = ['*.tex']
255
+
256
+ def __init__(self, **options):
257
+ Formatter.__init__(self, **options)
258
+ self.nowrap = get_bool_opt(options, 'nowrap', False)
259
+ self.docclass = options.get('docclass', 'article')
260
+ self.preamble = options.get('preamble', '')
261
+ self.linenos = get_bool_opt(options, 'linenos', False)
262
+ self.linenostart = abs(get_int_opt(options, 'linenostart', 1))
263
+ self.linenostep = abs(get_int_opt(options, 'linenostep', 1))
264
+ self.verboptions = options.get('verboptions', '')
265
+ self.nobackground = get_bool_opt(options, 'nobackground', False)
266
+ self.commandprefix = options.get('commandprefix', 'PY')
267
+ self.texcomments = get_bool_opt(options, 'texcomments', False)
268
+ self.mathescape = get_bool_opt(options, 'mathescape', False)
269
+ self.escapeinside = options.get('escapeinside', '')
270
+ if len(self.escapeinside) == 2:
271
+ self.left = self.escapeinside[0]
272
+ self.right = self.escapeinside[1]
273
+ else:
274
+ self.escapeinside = ''
275
+ self.envname = options.get('envname', 'Verbatim')
276
+
277
+ self._create_stylesheet()
278
+
279
+ def _create_stylesheet(self):
280
+ t2n = self.ttype2name = {Token: ''}
281
+ c2d = self.cmd2def = {}
282
+ cp = self.commandprefix
283
+
284
+ def rgbcolor(col):
285
+ if col:
286
+ return ','.join(['%.2f' % (int(col[i] + col[i + 1], 16) / 255.0)
287
+ for i in (0, 2, 4)])
288
+ else:
289
+ return '1,1,1'
290
+
291
+ for ttype, ndef in self.style:
292
+ name = _get_ttype_name(ttype)
293
+ cmndef = ''
294
+ if ndef['bold']:
295
+ cmndef += r'\let\$$@bf=\textbf'
296
+ if ndef['italic']:
297
+ cmndef += r'\let\$$@it=\textit'
298
+ if ndef['underline']:
299
+ cmndef += r'\let\$$@ul=\underline'
300
+ if ndef['roman']:
301
+ cmndef += r'\let\$$@ff=\textrm'
302
+ if ndef['sans']:
303
+ cmndef += r'\let\$$@ff=\textsf'
304
+ if ndef['mono']:
305
+ cmndef += r'\let\$$@ff=\textsf'
306
+ if ndef['color']:
307
+ cmndef += (r'\def\$$@tc##1{{\textcolor[rgb]{{{}}}{{##1}}}}'.format(rgbcolor(ndef['color'])))
308
+ if ndef['border']:
309
+ cmndef += (r'\def\$$@bc##1{{{{\setlength{{\fboxsep}}{{\string -\fboxrule}}'
310
+ r'\fcolorbox[rgb]{{{}}}{{{}}}{{\strut ##1}}}}}}'.format(rgbcolor(ndef['border']),
311
+ rgbcolor(ndef['bgcolor'])))
312
+ elif ndef['bgcolor']:
313
+ cmndef += (r'\def\$$@bc##1{{{{\setlength{{\fboxsep}}{{0pt}}'
314
+ r'\colorbox[rgb]{{{}}}{{\strut ##1}}}}}}'.format(rgbcolor(ndef['bgcolor'])))
315
+ if cmndef == '':
316
+ continue
317
+ cmndef = cmndef.replace('$$', cp)
318
+ t2n[ttype] = name
319
+ c2d[name] = cmndef
320
+
321
+ def get_style_defs(self, arg=''):
322
+ """
323
+ Return the command sequences needed to define the commands
324
+ used to format text in the verbatim environment. ``arg`` is ignored.
325
+ """
326
+ cp = self.commandprefix
327
+ styles = []
328
+ for name, definition in self.cmd2def.items():
329
+ styles.append(rf'\@namedef{{{cp}@tok@{name}}}{{{definition}}}')
330
+ return STYLE_TEMPLATE % {'cp': self.commandprefix,
331
+ 'styles': '\n'.join(styles)}
332
+
333
+ def format_unencoded(self, tokensource, outfile):
334
+ # TODO: add support for background colors
335
+ t2n = self.ttype2name
336
+ cp = self.commandprefix
337
+
338
+ if self.full:
339
+ realoutfile = outfile
340
+ outfile = StringIO()
341
+
342
+ if not self.nowrap:
343
+ outfile.write('\\begin{' + self.envname + '}[commandchars=\\\\\\{\\}')
344
+ if self.linenos:
345
+ start, step = self.linenostart, self.linenostep
346
+ outfile.write(',numbers=left' +
347
+ (start and ',firstnumber=%d' % start or '') +
348
+ (step and ',stepnumber=%d' % step or ''))
349
+ if self.mathescape or self.texcomments or self.escapeinside:
350
+ outfile.write(',codes={\\catcode`\\$=3\\catcode`\\^=7'
351
+ '\\catcode`\\_=8\\relax}')
352
+ if self.verboptions:
353
+ outfile.write(',' + self.verboptions)
354
+ outfile.write(']\n')
355
+
356
+ for ttype, value in tokensource:
357
+ if ttype in Token.Comment:
358
+ if self.texcomments:
359
+ # Try to guess comment starting lexeme and escape it ...
360
+ start = value[0:1]
361
+ for i in range(1, len(value)):
362
+ if start[0] != value[i]:
363
+ break
364
+ start += value[i]
365
+
366
+ value = value[len(start):]
367
+ start = escape_tex(start, cp)
368
+
369
+ # ... but do not escape inside comment.
370
+ value = start + value
371
+ elif self.mathescape:
372
+ # Only escape parts not inside a math environment.
373
+ parts = value.split('$')
374
+ in_math = False
375
+ for i, part in enumerate(parts):
376
+ if not in_math:
377
+ parts[i] = escape_tex(part, cp)
378
+ in_math = not in_math
379
+ value = '$'.join(parts)
380
+ elif self.escapeinside:
381
+ text = value
382
+ value = ''
383
+ while text:
384
+ a, sep1, text = text.partition(self.left)
385
+ if sep1:
386
+ b, sep2, text = text.partition(self.right)
387
+ if sep2:
388
+ value += escape_tex(a, cp) + b
389
+ else:
390
+ value += escape_tex(a + sep1 + b, cp)
391
+ else:
392
+ value += escape_tex(a, cp)
393
+ else:
394
+ value = escape_tex(value, cp)
395
+ elif ttype not in Token.Escape:
396
+ value = escape_tex(value, cp)
397
+ styles = []
398
+ while ttype is not Token:
399
+ try:
400
+ styles.append(t2n[ttype])
401
+ except KeyError:
402
+ # not in current style
403
+ styles.append(_get_ttype_name(ttype))
404
+ ttype = ttype.parent
405
+ styleval = '+'.join(reversed(styles))
406
+ if styleval:
407
+ spl = value.split('\n')
408
+ for line in spl[:-1]:
409
+ if line:
410
+ outfile.write(f"\\{cp}{{{styleval}}}{{{line}}}")
411
+ outfile.write('\n')
412
+ if spl[-1]:
413
+ outfile.write(f"\\{cp}{{{styleval}}}{{{spl[-1]}}}")
414
+ else:
415
+ outfile.write(value)
416
+
417
+ if not self.nowrap:
418
+ outfile.write('\\end{' + self.envname + '}\n')
419
+
420
+ if self.full:
421
+ encoding = self.encoding or 'utf8'
422
+ # map known existings encodings from LaTeX distribution
423
+ encoding = {
424
+ 'utf_8': 'utf8',
425
+ 'latin_1': 'latin1',
426
+ 'iso_8859_1': 'latin1',
427
+ }.get(encoding.replace('-', '_'), encoding)
428
+ realoutfile.write(DOC_TEMPLATE %
429
+ dict(docclass = self.docclass,
430
+ preamble = self.preamble,
431
+ title = self.title,
432
+ encoding = encoding,
433
+ styledefs = self.get_style_defs(),
434
+ code = outfile.getvalue()))
435
+
436
+
437
+ class LatexEmbeddedLexer(Lexer):
438
+ """
439
+ This lexer takes one lexer as argument, the lexer for the language
440
+ being formatted, and the left and right delimiters for escaped text.
441
+
442
+ First everything is scanned using the language lexer to obtain
443
+ strings and comments. All other consecutive tokens are merged and
444
+ the resulting text is scanned for escaped segments, which are given
445
+ the Token.Escape type. Finally text that is not escaped is scanned
446
+ again with the language lexer.
447
+ """
448
+ def __init__(self, left, right, lang, **options):
449
+ self.left = left
450
+ self.right = right
451
+ self.lang = lang
452
+ Lexer.__init__(self, **options)
453
+
454
+ def get_tokens_unprocessed(self, text):
455
+ # find and remove all the escape tokens (replace with an empty string)
456
+ # this is very similar to DelegatingLexer.get_tokens_unprocessed.
457
+ buffered = ''
458
+ insertions = []
459
+ insertion_buf = []
460
+ for i, t, v in self._find_safe_escape_tokens(text):
461
+ if t is None:
462
+ if insertion_buf:
463
+ insertions.append((len(buffered), insertion_buf))
464
+ insertion_buf = []
465
+ buffered += v
466
+ else:
467
+ insertion_buf.append((i, t, v))
468
+ if insertion_buf:
469
+ insertions.append((len(buffered), insertion_buf))
470
+ return do_insertions(insertions,
471
+ self.lang.get_tokens_unprocessed(buffered))
472
+
473
+ def _find_safe_escape_tokens(self, text):
474
+ """ find escape tokens that are not in strings or comments """
475
+ for i, t, v in self._filter_to(
476
+ self.lang.get_tokens_unprocessed(text),
477
+ lambda t: t in Token.Comment or t in Token.String
478
+ ):
479
+ if t is None:
480
+ for i2, t2, v2 in self._find_escape_tokens(v):
481
+ yield i + i2, t2, v2
482
+ else:
483
+ yield i, None, v
484
+
485
+ def _filter_to(self, it, pred):
486
+ """ Keep only the tokens that match `pred`, merge the others together """
487
+ buf = ''
488
+ idx = 0
489
+ for i, t, v in it:
490
+ if pred(t):
491
+ if buf:
492
+ yield idx, None, buf
493
+ buf = ''
494
+ yield i, t, v
495
+ else:
496
+ if not buf:
497
+ idx = i
498
+ buf += v
499
+ if buf:
500
+ yield idx, None, buf
501
+
502
+ def _find_escape_tokens(self, text):
503
+ """ Find escape tokens within text, give token=None otherwise """
504
+ index = 0
505
+ while text:
506
+ a, sep1, text = text.partition(self.left)
507
+ if a:
508
+ yield index, None, a
509
+ index += len(a)
510
+ if sep1:
511
+ b, sep2, text = text.partition(self.right)
512
+ if sep2:
513
+ yield index + len(sep1), Token.Escape, b
514
+ index += len(sep1) + len(b) + len(sep2)
515
+ else:
516
+ yield index, Token.Error, sep1
517
+ index += len(sep1)
518
+ text = b
llava/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/other.py ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ pygments.formatters.other
3
+ ~~~~~~~~~~~~~~~~~~~~~~~~~
4
+
5
+ Other formatters: NullFormatter, RawTokenFormatter.
6
+
7
+ :copyright: Copyright 2006-2024 by the Pygments team, see AUTHORS.
8
+ :license: BSD, see LICENSE for details.
9
+ """
10
+
11
+ from pip._vendor.pygments.formatter import Formatter
12
+ from pip._vendor.pygments.util import get_choice_opt
13
+ from pip._vendor.pygments.token import Token
14
+ from pip._vendor.pygments.console import colorize
15
+
16
+ __all__ = ['NullFormatter', 'RawTokenFormatter', 'TestcaseFormatter']
17
+
18
+
19
+ class NullFormatter(Formatter):
20
+ """
21
+ Output the text unchanged without any formatting.
22
+ """
23
+ name = 'Text only'
24
+ aliases = ['text', 'null']
25
+ filenames = ['*.txt']
26
+
27
+ def format(self, tokensource, outfile):
28
+ enc = self.encoding
29
+ for ttype, value in tokensource:
30
+ if enc:
31
+ outfile.write(value.encode(enc))
32
+ else:
33
+ outfile.write(value)
34
+
35
+
36
+ class RawTokenFormatter(Formatter):
37
+ r"""
38
+ Format tokens as a raw representation for storing token streams.
39
+
40
+ The format is ``tokentype<TAB>repr(tokenstring)\n``. The output can later
41
+ be converted to a token stream with the `RawTokenLexer`, described in the
42
+ :doc:`lexer list <lexers>`.
43
+
44
+ Only two options are accepted:
45
+
46
+ `compress`
47
+ If set to ``'gz'`` or ``'bz2'``, compress the output with the given
48
+ compression algorithm after encoding (default: ``''``).
49
+ `error_color`
50
+ If set to a color name, highlight error tokens using that color. If
51
+ set but with no value, defaults to ``'red'``.
52
+
53
+ .. versionadded:: 0.11
54
+
55
+ """
56
+ name = 'Raw tokens'
57
+ aliases = ['raw', 'tokens']
58
+ filenames = ['*.raw']
59
+
60
+ unicodeoutput = False
61
+
62
+ def __init__(self, **options):
63
+ Formatter.__init__(self, **options)
64
+ # We ignore self.encoding if it is set, since it gets set for lexer
65
+ # and formatter if given with -Oencoding on the command line.
66
+ # The RawTokenFormatter outputs only ASCII. Override here.
67
+ self.encoding = 'ascii' # let pygments.format() do the right thing
68
+ self.compress = get_choice_opt(options, 'compress',
69
+ ['', 'none', 'gz', 'bz2'], '')
70
+ self.error_color = options.get('error_color', None)
71
+ if self.error_color is True:
72
+ self.error_color = 'red'
73
+ if self.error_color is not None:
74
+ try:
75
+ colorize(self.error_color, '')
76
+ except KeyError:
77
+ raise ValueError(f"Invalid color {self.error_color!r} specified")
78
+
79
+ def format(self, tokensource, outfile):
80
+ try:
81
+ outfile.write(b'')
82
+ except TypeError:
83
+ raise TypeError('The raw tokens formatter needs a binary '
84
+ 'output file')
85
+ if self.compress == 'gz':
86
+ import gzip
87
+ outfile = gzip.GzipFile('', 'wb', 9, outfile)
88
+
89
+ write = outfile.write
90
+ flush = outfile.close
91
+ elif self.compress == 'bz2':
92
+ import bz2
93
+ compressor = bz2.BZ2Compressor(9)
94
+
95
+ def write(text):
96
+ outfile.write(compressor.compress(text))
97
+
98
+ def flush():
99
+ outfile.write(compressor.flush())
100
+ outfile.flush()
101
+ else:
102
+ write = outfile.write
103
+ flush = outfile.flush
104
+
105
+ if self.error_color:
106
+ for ttype, value in tokensource:
107
+ line = b"%r\t%r\n" % (ttype, value)
108
+ if ttype is Token.Error:
109
+ write(colorize(self.error_color, line))
110
+ else:
111
+ write(line)
112
+ else:
113
+ for ttype, value in tokensource:
114
+ write(b"%r\t%r\n" % (ttype, value))
115
+ flush()
116
+
117
+
118
+ TESTCASE_BEFORE = '''\
119
+ def testNeedsName(lexer):
120
+ fragment = %r
121
+ tokens = [
122
+ '''
123
+ TESTCASE_AFTER = '''\
124
+ ]
125
+ assert list(lexer.get_tokens(fragment)) == tokens
126
+ '''
127
+
128
+
129
+ class TestcaseFormatter(Formatter):
130
+ """
131
+ Format tokens as appropriate for a new testcase.
132
+
133
+ .. versionadded:: 2.0
134
+ """
135
+ name = 'Testcase'
136
+ aliases = ['testcase']
137
+
138
+ def __init__(self, **options):
139
+ Formatter.__init__(self, **options)
140
+ if self.encoding is not None and self.encoding != 'utf-8':
141
+ raise ValueError("Only None and utf-8 are allowed encodings.")
142
+
143
+ def format(self, tokensource, outfile):
144
+ indentation = ' ' * 12
145
+ rawbuf = []
146
+ outbuf = []
147
+ for ttype, value in tokensource:
148
+ rawbuf.append(value)
149
+ outbuf.append(f'{indentation}({ttype}, {value!r}),\n')
150
+
151
+ before = TESTCASE_BEFORE % (''.join(rawbuf),)
152
+ during = ''.join(outbuf)
153
+ after = TESTCASE_AFTER
154
+ if self.encoding is None:
155
+ outfile.write(before + during + after)
156
+ else:
157
+ outfile.write(before.encode('utf-8'))
158
+ outfile.write(during.encode('utf-8'))
159
+ outfile.write(after.encode('utf-8'))
160
+ outfile.flush()
llava/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/pangomarkup.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ pygments.formatters.pangomarkup
3
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4
+
5
+ Formatter for Pango markup output.
6
+
7
+ :copyright: Copyright 2006-2024 by the Pygments team, see AUTHORS.
8
+ :license: BSD, see LICENSE for details.
9
+ """
10
+
11
+ from pip._vendor.pygments.formatter import Formatter
12
+
13
+
14
+ __all__ = ['PangoMarkupFormatter']
15
+
16
+
17
+ _escape_table = {
18
+ ord('&'): '&amp;',
19
+ ord('<'): '&lt;',
20
+ }
21
+
22
+
23
+ def escape_special_chars(text, table=_escape_table):
24
+ """Escape & and < for Pango Markup."""
25
+ return text.translate(table)
26
+
27
+
28
+ class PangoMarkupFormatter(Formatter):
29
+ """
30
+ Format tokens as Pango Markup code. It can then be rendered to an SVG.
31
+
32
+ .. versionadded:: 2.9
33
+ """
34
+
35
+ name = 'Pango Markup'
36
+ aliases = ['pango', 'pangomarkup']
37
+ filenames = []
38
+
39
+ def __init__(self, **options):
40
+ Formatter.__init__(self, **options)
41
+
42
+ self.styles = {}
43
+
44
+ for token, style in self.style:
45
+ start = ''
46
+ end = ''
47
+ if style['color']:
48
+ start += '<span fgcolor="#{}">'.format(style['color'])
49
+ end = '</span>' + end
50
+ if style['bold']:
51
+ start += '<b>'
52
+ end = '</b>' + end
53
+ if style['italic']:
54
+ start += '<i>'
55
+ end = '</i>' + end
56
+ if style['underline']:
57
+ start += '<u>'
58
+ end = '</u>' + end
59
+ self.styles[token] = (start, end)
60
+
61
+ def format_unencoded(self, tokensource, outfile):
62
+ lastval = ''
63
+ lasttype = None
64
+
65
+ outfile.write('<tt>')
66
+
67
+ for ttype, value in tokensource:
68
+ while ttype not in self.styles:
69
+ ttype = ttype.parent
70
+ if ttype == lasttype:
71
+ lastval += escape_special_chars(value)
72
+ else:
73
+ if lastval:
74
+ stylebegin, styleend = self.styles[lasttype]
75
+ outfile.write(stylebegin + lastval + styleend)
76
+ lastval = escape_special_chars(value)
77
+ lasttype = ttype
78
+
79
+ if lastval:
80
+ stylebegin, styleend = self.styles[lasttype]
81
+ outfile.write(stylebegin + lastval + styleend)
82
+
83
+ outfile.write('</tt>')
llava/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/rtf.py ADDED
@@ -0,0 +1,349 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ pygments.formatters.rtf
3
+ ~~~~~~~~~~~~~~~~~~~~~~~
4
+
5
+ A formatter that generates RTF files.
6
+
7
+ :copyright: Copyright 2006-2024 by the Pygments team, see AUTHORS.
8
+ :license: BSD, see LICENSE for details.
9
+ """
10
+
11
+ from collections import OrderedDict
12
+ from pip._vendor.pygments.formatter import Formatter
13
+ from pip._vendor.pygments.style import _ansimap
14
+ from pip._vendor.pygments.util import get_bool_opt, get_int_opt, get_list_opt, surrogatepair
15
+
16
+
17
+ __all__ = ['RtfFormatter']
18
+
19
+
20
+ class RtfFormatter(Formatter):
21
+ """
22
+ Format tokens as RTF markup. This formatter automatically outputs full RTF
23
+ documents with color information and other useful stuff. Perfect for Copy and
24
+ Paste into Microsoft(R) Word(R) documents.
25
+
26
+ Please note that ``encoding`` and ``outencoding`` options are ignored.
27
+ The RTF format is ASCII natively, but handles unicode characters correctly
28
+ thanks to escape sequences.
29
+
30
+ .. versionadded:: 0.6
31
+
32
+ Additional options accepted:
33
+
34
+ `style`
35
+ The style to use, can be a string or a Style subclass (default:
36
+ ``'default'``).
37
+
38
+ `fontface`
39
+ The used font family, for example ``Bitstream Vera Sans``. Defaults to
40
+ some generic font which is supposed to have fixed width.
41
+
42
+ `fontsize`
43
+ Size of the font used. Size is specified in half points. The
44
+ default is 24 half-points, giving a size 12 font.
45
+
46
+ .. versionadded:: 2.0
47
+
48
+ `linenos`
49
+ Turn on line numbering (default: ``False``).
50
+
51
+ .. versionadded:: 2.18
52
+
53
+ `lineno_fontsize`
54
+ Font size for line numbers. Size is specified in half points
55
+ (default: `fontsize`).
56
+
57
+ .. versionadded:: 2.18
58
+
59
+ `lineno_padding`
60
+ Number of spaces between the (inline) line numbers and the
61
+ source code (default: ``2``).
62
+
63
+ .. versionadded:: 2.18
64
+
65
+ `linenostart`
66
+ The line number for the first line (default: ``1``).
67
+
68
+ .. versionadded:: 2.18
69
+
70
+ `linenostep`
71
+ If set to a number n > 1, only every nth line number is printed.
72
+
73
+ .. versionadded:: 2.18
74
+
75
+ `lineno_color`
76
+ Color for line numbers specified as a hex triplet, e.g. ``'5e5e5e'``.
77
+ Defaults to the style's line number color if it is a hex triplet,
78
+ otherwise ansi bright black.
79
+
80
+ .. versionadded:: 2.18
81
+
82
+ `hl_lines`
83
+ Specify a list of lines to be highlighted, as line numbers separated by
84
+ spaces, e.g. ``'3 7 8'``. The line numbers are relative to the input
85
+ (i.e. the first line is line 1) unless `hl_linenostart` is set.
86
+
87
+ .. versionadded:: 2.18
88
+
89
+ `hl_color`
90
+ Color for highlighting the lines specified in `hl_lines`, specified as
91
+ a hex triplet (default: style's `highlight_color`).
92
+
93
+ .. versionadded:: 2.18
94
+
95
+ `hl_linenostart`
96
+ If set to ``True`` line numbers in `hl_lines` are specified
97
+ relative to `linenostart` (default ``False``).
98
+
99
+ .. versionadded:: 2.18
100
+ """
101
+ name = 'RTF'
102
+ aliases = ['rtf']
103
+ filenames = ['*.rtf']
104
+
105
+ def __init__(self, **options):
106
+ r"""
107
+ Additional options accepted:
108
+
109
+ ``fontface``
110
+ Name of the font used. Could for example be ``'Courier New'``
111
+ to further specify the default which is ``'\fmodern'``. The RTF
112
+ specification claims that ``\fmodern`` are "Fixed-pitch serif
113
+ and sans serif fonts". Hope every RTF implementation thinks
114
+ the same about modern...
115
+
116
+ """
117
+ Formatter.__init__(self, **options)
118
+ self.fontface = options.get('fontface') or ''
119
+ self.fontsize = get_int_opt(options, 'fontsize', 0)
120
+ self.linenos = get_bool_opt(options, 'linenos', False)
121
+ self.lineno_fontsize = get_int_opt(options, 'lineno_fontsize',
122
+ self.fontsize)
123
+ self.lineno_padding = get_int_opt(options, 'lineno_padding', 2)
124
+ self.linenostart = abs(get_int_opt(options, 'linenostart', 1))
125
+ self.linenostep = abs(get_int_opt(options, 'linenostep', 1))
126
+ self.hl_linenostart = get_bool_opt(options, 'hl_linenostart', False)
127
+
128
+ self.hl_color = options.get('hl_color', '')
129
+ if not self.hl_color:
130
+ self.hl_color = self.style.highlight_color
131
+
132
+ self.hl_lines = []
133
+ for lineno in get_list_opt(options, 'hl_lines', []):
134
+ try:
135
+ lineno = int(lineno)
136
+ if self.hl_linenostart:
137
+ lineno = lineno - self.linenostart + 1
138
+ self.hl_lines.append(lineno)
139
+ except ValueError:
140
+ pass
141
+
142
+ self.lineno_color = options.get('lineno_color', '')
143
+ if not self.lineno_color:
144
+ if self.style.line_number_color == 'inherit':
145
+ # style color is the css value 'inherit'
146
+ # default to ansi bright-black
147
+ self.lineno_color = _ansimap['ansibrightblack']
148
+ else:
149
+ # style color is assumed to be a hex triplet as other
150
+ # colors in pygments/style.py
151
+ self.lineno_color = self.style.line_number_color
152
+
153
+ self.color_mapping = self._create_color_mapping()
154
+
155
+ def _escape(self, text):
156
+ return text.replace('\\', '\\\\') \
157
+ .replace('{', '\\{') \
158
+ .replace('}', '\\}')
159
+
160
+ def _escape_text(self, text):
161
+ # empty strings, should give a small performance improvement
162
+ if not text:
163
+ return ''
164
+
165
+ # escape text
166
+ text = self._escape(text)
167
+
168
+ buf = []
169
+ for c in text:
170
+ cn = ord(c)
171
+ if cn < (2**7):
172
+ # ASCII character
173
+ buf.append(str(c))
174
+ elif (2**7) <= cn < (2**16):
175
+ # single unicode escape sequence
176
+ buf.append('{\\u%d}' % cn)
177
+ elif (2**16) <= cn:
178
+ # RTF limits unicode to 16 bits.
179
+ # Force surrogate pairs
180
+ buf.append('{\\u%d}{\\u%d}' % surrogatepair(cn))
181
+
182
+ return ''.join(buf).replace('\n', '\\par')
183
+
184
+ @staticmethod
185
+ def hex_to_rtf_color(hex_color):
186
+ if hex_color[0] == "#":
187
+ hex_color = hex_color[1:]
188
+
189
+ return '\\red%d\\green%d\\blue%d;' % (
190
+ int(hex_color[0:2], 16),
191
+ int(hex_color[2:4], 16),
192
+ int(hex_color[4:6], 16)
193
+ )
194
+
195
+ def _split_tokens_on_newlines(self, tokensource):
196
+ """
197
+ Split tokens containing newline characters into multiple token
198
+ each representing a line of the input file. Needed for numbering
199
+ lines of e.g. multiline comments.
200
+ """
201
+ for ttype, value in tokensource:
202
+ if value == '\n':
203
+ yield (ttype, value)
204
+ elif "\n" in value:
205
+ lines = value.split("\n")
206
+ for line in lines[:-1]:
207
+ yield (ttype, line+"\n")
208
+ if lines[-1]:
209
+ yield (ttype, lines[-1])
210
+ else:
211
+ yield (ttype, value)
212
+
213
+ def _create_color_mapping(self):
214
+ """
215
+ Create a mapping of style hex colors to index/offset in
216
+ the RTF color table.
217
+ """
218
+ color_mapping = OrderedDict()
219
+ offset = 1
220
+
221
+ if self.linenos:
222
+ color_mapping[self.lineno_color] = offset
223
+ offset += 1
224
+
225
+ if self.hl_lines:
226
+ color_mapping[self.hl_color] = offset
227
+ offset += 1
228
+
229
+ for _, style in self.style:
230
+ for color in style['color'], style['bgcolor'], style['border']:
231
+ if color and color not in color_mapping:
232
+ color_mapping[color] = offset
233
+ offset += 1
234
+
235
+ return color_mapping
236
+
237
+ @property
238
+ def _lineno_template(self):
239
+ if self.lineno_fontsize != self.fontsize:
240
+ return '{{\\fs{} \\cf{} %s{}}}'.format(self.lineno_fontsize,
241
+ self.color_mapping[self.lineno_color],
242
+ " " * self.lineno_padding)
243
+
244
+ return '{{\\cf{} %s{}}}'.format(self.color_mapping[self.lineno_color],
245
+ " " * self.lineno_padding)
246
+
247
+ @property
248
+ def _hl_open_str(self):
249
+ return rf'{{\highlight{self.color_mapping[self.hl_color]} '
250
+
251
+ @property
252
+ def _rtf_header(self):
253
+ lines = []
254
+ # rtf 1.8 header
255
+ lines.append('{\\rtf1\\ansi\\uc0\\deff0'
256
+ '{\\fonttbl{\\f0\\fmodern\\fprq1\\fcharset0%s;}}'
257
+ % (self.fontface and ' '
258
+ + self._escape(self.fontface) or ''))
259
+
260
+ # color table
261
+ lines.append('{\\colortbl;')
262
+ for color, _ in self.color_mapping.items():
263
+ lines.append(self.hex_to_rtf_color(color))
264
+ lines.append('}')
265
+
266
+ # font and fontsize
267
+ lines.append('\\f0\\sa0')
268
+ if self.fontsize:
269
+ lines.append('\\fs%d' % self.fontsize)
270
+
271
+ # ensure Libre Office Writer imports and renders consecutive
272
+ # space characters the same width, needed for line numbering.
273
+ # https://bugs.documentfoundation.org/show_bug.cgi?id=144050
274
+ lines.append('\\dntblnsbdb')
275
+
276
+ return lines
277
+
278
+ def format_unencoded(self, tokensource, outfile):
279
+ for line in self._rtf_header:
280
+ outfile.write(line + "\n")
281
+
282
+ tokensource = self._split_tokens_on_newlines(tokensource)
283
+
284
+ # first pass of tokens to count lines, needed for line numbering
285
+ if self.linenos:
286
+ line_count = 0
287
+ tokens = [] # for copying the token source generator
288
+ for ttype, value in tokensource:
289
+ tokens.append((ttype, value))
290
+ if value.endswith("\n"):
291
+ line_count += 1
292
+
293
+ # width of line number strings (for padding with spaces)
294
+ linenos_width = len(str(line_count+self.linenostart-1))
295
+
296
+ tokensource = tokens
297
+
298
+ # highlight stream
299
+ lineno = 1
300
+ start_new_line = True
301
+ for ttype, value in tokensource:
302
+ if start_new_line and lineno in self.hl_lines:
303
+ outfile.write(self._hl_open_str)
304
+
305
+ if start_new_line and self.linenos:
306
+ if (lineno-self.linenostart+1)%self.linenostep == 0:
307
+ current_lineno = lineno + self.linenostart - 1
308
+ lineno_str = str(current_lineno).rjust(linenos_width)
309
+ else:
310
+ lineno_str = "".rjust(linenos_width)
311
+ outfile.write(self._lineno_template % lineno_str)
312
+
313
+ while not self.style.styles_token(ttype) and ttype.parent:
314
+ ttype = ttype.parent
315
+ style = self.style.style_for_token(ttype)
316
+ buf = []
317
+ if style['bgcolor']:
318
+ buf.append('\\cb%d' % self.color_mapping[style['bgcolor']])
319
+ if style['color']:
320
+ buf.append('\\cf%d' % self.color_mapping[style['color']])
321
+ if style['bold']:
322
+ buf.append('\\b')
323
+ if style['italic']:
324
+ buf.append('\\i')
325
+ if style['underline']:
326
+ buf.append('\\ul')
327
+ if style['border']:
328
+ buf.append('\\chbrdr\\chcfpat%d' %
329
+ self.color_mapping[style['border']])
330
+ start = ''.join(buf)
331
+ if start:
332
+ outfile.write(f'{{{start} ')
333
+ outfile.write(self._escape_text(value))
334
+ if start:
335
+ outfile.write('}')
336
+ start_new_line = False
337
+
338
+ # complete line of input
339
+ if value.endswith("\n"):
340
+ # close line highlighting
341
+ if lineno in self.hl_lines:
342
+ outfile.write('}')
343
+ # newline in RTF file after closing }
344
+ outfile.write("\n")
345
+
346
+ start_new_line = True
347
+ lineno += 1
348
+
349
+ outfile.write('}\n')
llava/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/terminal.py ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ pygments.formatters.terminal
3
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4
+
5
+ Formatter for terminal output with ANSI sequences.
6
+
7
+ :copyright: Copyright 2006-2024 by the Pygments team, see AUTHORS.
8
+ :license: BSD, see LICENSE for details.
9
+ """
10
+
11
+ from pip._vendor.pygments.formatter import Formatter
12
+ from pip._vendor.pygments.token import Keyword, Name, Comment, String, Error, \
13
+ Number, Operator, Generic, Token, Whitespace
14
+ from pip._vendor.pygments.console import ansiformat
15
+ from pip._vendor.pygments.util import get_choice_opt
16
+
17
+
18
+ __all__ = ['TerminalFormatter']
19
+
20
+
21
+ #: Map token types to a tuple of color values for light and dark
22
+ #: backgrounds.
23
+ TERMINAL_COLORS = {
24
+ Token: ('', ''),
25
+
26
+ Whitespace: ('gray', 'brightblack'),
27
+ Comment: ('gray', 'brightblack'),
28
+ Comment.Preproc: ('cyan', 'brightcyan'),
29
+ Keyword: ('blue', 'brightblue'),
30
+ Keyword.Type: ('cyan', 'brightcyan'),
31
+ Operator.Word: ('magenta', 'brightmagenta'),
32
+ Name.Builtin: ('cyan', 'brightcyan'),
33
+ Name.Function: ('green', 'brightgreen'),
34
+ Name.Namespace: ('_cyan_', '_brightcyan_'),
35
+ Name.Class: ('_green_', '_brightgreen_'),
36
+ Name.Exception: ('cyan', 'brightcyan'),
37
+ Name.Decorator: ('brightblack', 'gray'),
38
+ Name.Variable: ('red', 'brightred'),
39
+ Name.Constant: ('red', 'brightred'),
40
+ Name.Attribute: ('cyan', 'brightcyan'),
41
+ Name.Tag: ('brightblue', 'brightblue'),
42
+ String: ('yellow', 'yellow'),
43
+ Number: ('blue', 'brightblue'),
44
+
45
+ Generic.Deleted: ('brightred', 'brightred'),
46
+ Generic.Inserted: ('green', 'brightgreen'),
47
+ Generic.Heading: ('**', '**'),
48
+ Generic.Subheading: ('*magenta*', '*brightmagenta*'),
49
+ Generic.Prompt: ('**', '**'),
50
+ Generic.Error: ('brightred', 'brightred'),
51
+
52
+ Error: ('_brightred_', '_brightred_'),
53
+ }
54
+
55
+
56
+ class TerminalFormatter(Formatter):
57
+ r"""
58
+ Format tokens with ANSI color sequences, for output in a text console.
59
+ Color sequences are terminated at newlines, so that paging the output
60
+ works correctly.
61
+
62
+ The `get_style_defs()` method doesn't do anything special since there is
63
+ no support for common styles.
64
+
65
+ Options accepted:
66
+
67
+ `bg`
68
+ Set to ``"light"`` or ``"dark"`` depending on the terminal's background
69
+ (default: ``"light"``).
70
+
71
+ `colorscheme`
72
+ A dictionary mapping token types to (lightbg, darkbg) color names or
73
+ ``None`` (default: ``None`` = use builtin colorscheme).
74
+
75
+ `linenos`
76
+ Set to ``True`` to have line numbers on the terminal output as well
77
+ (default: ``False`` = no line numbers).
78
+ """
79
+ name = 'Terminal'
80
+ aliases = ['terminal', 'console']
81
+ filenames = []
82
+
83
+ def __init__(self, **options):
84
+ Formatter.__init__(self, **options)
85
+ self.darkbg = get_choice_opt(options, 'bg',
86
+ ['light', 'dark'], 'light') == 'dark'
87
+ self.colorscheme = options.get('colorscheme', None) or TERMINAL_COLORS
88
+ self.linenos = options.get('linenos', False)
89
+ self._lineno = 0
90
+
91
+ def format(self, tokensource, outfile):
92
+ return Formatter.format(self, tokensource, outfile)
93
+
94
+ def _write_lineno(self, outfile):
95
+ self._lineno += 1
96
+ outfile.write("%s%04d: " % (self._lineno != 1 and '\n' or '', self._lineno))
97
+
98
+ def _get_color(self, ttype):
99
+ # self.colorscheme is a dict containing usually generic types, so we
100
+ # have to walk the tree of dots. The base Token type must be a key,
101
+ # even if it's empty string, as in the default above.
102
+ colors = self.colorscheme.get(ttype)
103
+ while colors is None:
104
+ ttype = ttype.parent
105
+ colors = self.colorscheme.get(ttype)
106
+ return colors[self.darkbg]
107
+
108
+ def format_unencoded(self, tokensource, outfile):
109
+ if self.linenos:
110
+ self._write_lineno(outfile)
111
+
112
+ for ttype, value in tokensource:
113
+ color = self._get_color(ttype)
114
+
115
+ for line in value.splitlines(True):
116
+ if color:
117
+ outfile.write(ansiformat(color, line.rstrip('\n')))
118
+ else:
119
+ outfile.write(line.rstrip('\n'))
120
+ if line.endswith('\n'):
121
+ if self.linenos:
122
+ self._write_lineno(outfile)
123
+ else:
124
+ outfile.write('\n')
125
+
126
+ if self.linenos:
127
+ outfile.write("\n")
llava/lib/python3.10/site-packages/pip/_vendor/pygments/plugin.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ pygments.plugin
3
+ ~~~~~~~~~~~~~~~
4
+
5
+ Pygments plugin interface.
6
+
7
+ lexer plugins::
8
+
9
+ [pygments.lexers]
10
+ yourlexer = yourmodule:YourLexer
11
+
12
+ formatter plugins::
13
+
14
+ [pygments.formatters]
15
+ yourformatter = yourformatter:YourFormatter
16
+ /.ext = yourformatter:YourFormatter
17
+
18
+ As you can see, you can define extensions for the formatter
19
+ with a leading slash.
20
+
21
+ syntax plugins::
22
+
23
+ [pygments.styles]
24
+ yourstyle = yourstyle:YourStyle
25
+
26
+ filter plugin::
27
+
28
+ [pygments.filter]
29
+ yourfilter = yourfilter:YourFilter
30
+
31
+
32
+ :copyright: Copyright 2006-2024 by the Pygments team, see AUTHORS.
33
+ :license: BSD, see LICENSE for details.
34
+ """
35
+ from importlib.metadata import entry_points
36
+
37
+ LEXER_ENTRY_POINT = 'pygments.lexers'
38
+ FORMATTER_ENTRY_POINT = 'pygments.formatters'
39
+ STYLE_ENTRY_POINT = 'pygments.styles'
40
+ FILTER_ENTRY_POINT = 'pygments.filters'
41
+
42
+
43
+ def iter_entry_points(group_name):
44
+ groups = entry_points()
45
+ if hasattr(groups, 'select'):
46
+ # New interface in Python 3.10 and newer versions of the
47
+ # importlib_metadata backport.
48
+ return groups.select(group=group_name)
49
+ else:
50
+ # Older interface, deprecated in Python 3.10 and recent
51
+ # importlib_metadata, but we need it in Python 3.8 and 3.9.
52
+ return groups.get(group_name, [])
53
+
54
+
55
+ def find_plugin_lexers():
56
+ for entrypoint in iter_entry_points(LEXER_ENTRY_POINT):
57
+ yield entrypoint.load()
58
+
59
+
60
+ def find_plugin_formatters():
61
+ for entrypoint in iter_entry_points(FORMATTER_ENTRY_POINT):
62
+ yield entrypoint.name, entrypoint.load()
63
+
64
+
65
+ def find_plugin_styles():
66
+ for entrypoint in iter_entry_points(STYLE_ENTRY_POINT):
67
+ yield entrypoint.name, entrypoint.load()
68
+
69
+
70
+ def find_plugin_filters():
71
+ for entrypoint in iter_entry_points(FILTER_ENTRY_POINT):
72
+ yield entrypoint.name, entrypoint.load()
llava/lib/python3.10/site-packages/pip/_vendor/pygments/scanner.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ pygments.scanner
3
+ ~~~~~~~~~~~~~~~~
4
+
5
+ This library implements a regex based scanner. Some languages
6
+ like Pascal are easy to parse but have some keywords that
7
+ depend on the context. Because of this it's impossible to lex
8
+ that just by using a regular expression lexer like the
9
+ `RegexLexer`.
10
+
11
+ Have a look at the `DelphiLexer` to get an idea of how to use
12
+ this scanner.
13
+
14
+ :copyright: Copyright 2006-2024 by the Pygments team, see AUTHORS.
15
+ :license: BSD, see LICENSE for details.
16
+ """
17
+ import re
18
+
19
+
20
+ class EndOfText(RuntimeError):
21
+ """
22
+ Raise if end of text is reached and the user
23
+ tried to call a match function.
24
+ """
25
+
26
+
27
+ class Scanner:
28
+ """
29
+ Simple scanner
30
+
31
+ All method patterns are regular expression strings (not
32
+ compiled expressions!)
33
+ """
34
+
35
+ def __init__(self, text, flags=0):
36
+ """
37
+ :param text: The text which should be scanned
38
+ :param flags: default regular expression flags
39
+ """
40
+ self.data = text
41
+ self.data_length = len(text)
42
+ self.start_pos = 0
43
+ self.pos = 0
44
+ self.flags = flags
45
+ self.last = None
46
+ self.match = None
47
+ self._re_cache = {}
48
+
49
+ def eos(self):
50
+ """`True` if the scanner reached the end of text."""
51
+ return self.pos >= self.data_length
52
+ eos = property(eos, eos.__doc__)
53
+
54
+ def check(self, pattern):
55
+ """
56
+ Apply `pattern` on the current position and return
57
+ the match object. (Doesn't touch pos). Use this for
58
+ lookahead.
59
+ """
60
+ if self.eos:
61
+ raise EndOfText()
62
+ if pattern not in self._re_cache:
63
+ self._re_cache[pattern] = re.compile(pattern, self.flags)
64
+ return self._re_cache[pattern].match(self.data, self.pos)
65
+
66
+ def test(self, pattern):
67
+ """Apply a pattern on the current position and check
68
+ if it patches. Doesn't touch pos.
69
+ """
70
+ return self.check(pattern) is not None
71
+
72
+ def scan(self, pattern):
73
+ """
74
+ Scan the text for the given pattern and update pos/match
75
+ and related fields. The return value is a boolean that
76
+ indicates if the pattern matched. The matched value is
77
+ stored on the instance as ``match``, the last value is
78
+ stored as ``last``. ``start_pos`` is the position of the
79
+ pointer before the pattern was matched, ``pos`` is the
80
+ end position.
81
+ """
82
+ if self.eos:
83
+ raise EndOfText()
84
+ if pattern not in self._re_cache:
85
+ self._re_cache[pattern] = re.compile(pattern, self.flags)
86
+ self.last = self.match
87
+ m = self._re_cache[pattern].match(self.data, self.pos)
88
+ if m is None:
89
+ return False
90
+ self.start_pos = m.start()
91
+ self.pos = m.end()
92
+ self.match = m.group()
93
+ return True
94
+
95
+ def get_char(self):
96
+ """Scan exactly one char."""
97
+ self.scan('.')
98
+
99
+ def __repr__(self):
100
+ return '<%s %d/%d>' % (
101
+ self.__class__.__name__,
102
+ self.pos,
103
+ self.data_length
104
+ )
llava/lib/python3.10/site-packages/pip/_vendor/pygments/sphinxext.py ADDED
@@ -0,0 +1,247 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ pygments.sphinxext
3
+ ~~~~~~~~~~~~~~~~~~
4
+
5
+ Sphinx extension to generate automatic documentation of lexers,
6
+ formatters and filters.
7
+
8
+ :copyright: Copyright 2006-2024 by the Pygments team, see AUTHORS.
9
+ :license: BSD, see LICENSE for details.
10
+ """
11
+
12
+ import sys
13
+
14
+ from docutils import nodes
15
+ from docutils.statemachine import ViewList
16
+ from docutils.parsers.rst import Directive
17
+ from sphinx.util.nodes import nested_parse_with_titles
18
+
19
+
20
+ MODULEDOC = '''
21
+ .. module:: %s
22
+
23
+ %s
24
+ %s
25
+ '''
26
+
27
+ LEXERDOC = '''
28
+ .. class:: %s
29
+
30
+ :Short names: %s
31
+ :Filenames: %s
32
+ :MIME types: %s
33
+
34
+ %s
35
+
36
+ %s
37
+
38
+ '''
39
+
40
+ FMTERDOC = '''
41
+ .. class:: %s
42
+
43
+ :Short names: %s
44
+ :Filenames: %s
45
+
46
+ %s
47
+
48
+ '''
49
+
50
+ FILTERDOC = '''
51
+ .. class:: %s
52
+
53
+ :Name: %s
54
+
55
+ %s
56
+
57
+ '''
58
+
59
+
60
+ class PygmentsDoc(Directive):
61
+ """
62
+ A directive to collect all lexers/formatters/filters and generate
63
+ autoclass directives for them.
64
+ """
65
+ has_content = False
66
+ required_arguments = 1
67
+ optional_arguments = 0
68
+ final_argument_whitespace = False
69
+ option_spec = {}
70
+
71
+ def run(self):
72
+ self.filenames = set()
73
+ if self.arguments[0] == 'lexers':
74
+ out = self.document_lexers()
75
+ elif self.arguments[0] == 'formatters':
76
+ out = self.document_formatters()
77
+ elif self.arguments[0] == 'filters':
78
+ out = self.document_filters()
79
+ elif self.arguments[0] == 'lexers_overview':
80
+ out = self.document_lexers_overview()
81
+ else:
82
+ raise Exception('invalid argument for "pygmentsdoc" directive')
83
+ node = nodes.compound()
84
+ vl = ViewList(out.split('\n'), source='')
85
+ nested_parse_with_titles(self.state, vl, node)
86
+ for fn in self.filenames:
87
+ self.state.document.settings.record_dependencies.add(fn)
88
+ return node.children
89
+
90
+ def document_lexers_overview(self):
91
+ """Generate a tabular overview of all lexers.
92
+
93
+ The columns are the lexer name, the extensions handled by this lexer
94
+ (or "None"), the aliases and a link to the lexer class."""
95
+ from pip._vendor.pygments.lexers._mapping import LEXERS
96
+ from pip._vendor.pygments.lexers import find_lexer_class
97
+ out = []
98
+
99
+ table = []
100
+
101
+ def format_link(name, url):
102
+ if url:
103
+ return f'`{name} <{url}>`_'
104
+ return name
105
+
106
+ for classname, data in sorted(LEXERS.items(), key=lambda x: x[1][1].lower()):
107
+ lexer_cls = find_lexer_class(data[1])
108
+ extensions = lexer_cls.filenames + lexer_cls.alias_filenames
109
+
110
+ table.append({
111
+ 'name': format_link(data[1], lexer_cls.url),
112
+ 'extensions': ', '.join(extensions).replace('*', '\\*').replace('_', '\\') or 'None',
113
+ 'aliases': ', '.join(data[2]),
114
+ 'class': f'{data[0]}.{classname}'
115
+ })
116
+
117
+ column_names = ['name', 'extensions', 'aliases', 'class']
118
+ column_lengths = [max([len(row[column]) for row in table if row[column]])
119
+ for column in column_names]
120
+
121
+ def write_row(*columns):
122
+ """Format a table row"""
123
+ out = []
124
+ for length, col in zip(column_lengths, columns):
125
+ if col:
126
+ out.append(col.ljust(length))
127
+ else:
128
+ out.append(' '*length)
129
+
130
+ return ' '.join(out)
131
+
132
+ def write_seperator():
133
+ """Write a table separator row"""
134
+ sep = ['='*c for c in column_lengths]
135
+ return write_row(*sep)
136
+
137
+ out.append(write_seperator())
138
+ out.append(write_row('Name', 'Extension(s)', 'Short name(s)', 'Lexer class'))
139
+ out.append(write_seperator())
140
+ for row in table:
141
+ out.append(write_row(
142
+ row['name'],
143
+ row['extensions'],
144
+ row['aliases'],
145
+ f':class:`~{row["class"]}`'))
146
+ out.append(write_seperator())
147
+
148
+ return '\n'.join(out)
149
+
150
+ def document_lexers(self):
151
+ from pip._vendor.pygments.lexers._mapping import LEXERS
152
+ from pip._vendor import pygments
153
+ import inspect
154
+ import pathlib
155
+
156
+ out = []
157
+ modules = {}
158
+ moduledocstrings = {}
159
+ for classname, data in sorted(LEXERS.items(), key=lambda x: x[0]):
160
+ module = data[0]
161
+ mod = __import__(module, None, None, [classname])
162
+ self.filenames.add(mod.__file__)
163
+ cls = getattr(mod, classname)
164
+ if not cls.__doc__:
165
+ print(f"Warning: {classname} does not have a docstring.")
166
+ docstring = cls.__doc__
167
+ if isinstance(docstring, bytes):
168
+ docstring = docstring.decode('utf8')
169
+
170
+ example_file = getattr(cls, '_example', None)
171
+ if example_file:
172
+ p = pathlib.Path(inspect.getabsfile(pygments)).parent.parent /\
173
+ 'tests' / 'examplefiles' / example_file
174
+ content = p.read_text(encoding='utf-8')
175
+ if not content:
176
+ raise Exception(
177
+ f"Empty example file '{example_file}' for lexer "
178
+ f"{classname}")
179
+
180
+ if data[2]:
181
+ lexer_name = data[2][0]
182
+ docstring += '\n\n .. admonition:: Example\n'
183
+ docstring += f'\n .. code-block:: {lexer_name}\n\n'
184
+ for line in content.splitlines():
185
+ docstring += f' {line}\n'
186
+
187
+ if cls.version_added:
188
+ version_line = f'.. versionadded:: {cls.version_added}'
189
+ else:
190
+ version_line = ''
191
+
192
+ modules.setdefault(module, []).append((
193
+ classname,
194
+ ', '.join(data[2]) or 'None',
195
+ ', '.join(data[3]).replace('*', '\\*').replace('_', '\\') or 'None',
196
+ ', '.join(data[4]) or 'None',
197
+ docstring,
198
+ version_line))
199
+ if module not in moduledocstrings:
200
+ moddoc = mod.__doc__
201
+ if isinstance(moddoc, bytes):
202
+ moddoc = moddoc.decode('utf8')
203
+ moduledocstrings[module] = moddoc
204
+
205
+ for module, lexers in sorted(modules.items(), key=lambda x: x[0]):
206
+ if moduledocstrings[module] is None:
207
+ raise Exception(f"Missing docstring for {module}")
208
+ heading = moduledocstrings[module].splitlines()[4].strip().rstrip('.')
209
+ out.append(MODULEDOC % (module, heading, '-'*len(heading)))
210
+ for data in lexers:
211
+ out.append(LEXERDOC % data)
212
+
213
+ return ''.join(out)
214
+
215
+ def document_formatters(self):
216
+ from pip._vendor.pygments.formatters import FORMATTERS
217
+
218
+ out = []
219
+ for classname, data in sorted(FORMATTERS.items(), key=lambda x: x[0]):
220
+ module = data[0]
221
+ mod = __import__(module, None, None, [classname])
222
+ self.filenames.add(mod.__file__)
223
+ cls = getattr(mod, classname)
224
+ docstring = cls.__doc__
225
+ if isinstance(docstring, bytes):
226
+ docstring = docstring.decode('utf8')
227
+ heading = cls.__name__
228
+ out.append(FMTERDOC % (heading, ', '.join(data[2]) or 'None',
229
+ ', '.join(data[3]).replace('*', '\\*') or 'None',
230
+ docstring))
231
+ return ''.join(out)
232
+
233
+ def document_filters(self):
234
+ from pip._vendor.pygments.filters import FILTERS
235
+
236
+ out = []
237
+ for name, cls in FILTERS.items():
238
+ self.filenames.add(sys.modules[cls.__module__].__file__)
239
+ docstring = cls.__doc__
240
+ if isinstance(docstring, bytes):
241
+ docstring = docstring.decode('utf8')
242
+ out.append(FILTERDOC % (cls.__name__, name, docstring))
243
+ return ''.join(out)
244
+
245
+
246
+ def setup(app):
247
+ app.add_directive('pygmentsdoc', PygmentsDoc)
llava/lib/python3.10/site-packages/pip/_vendor/pygments/util.py ADDED
@@ -0,0 +1,324 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ pygments.util
3
+ ~~~~~~~~~~~~~
4
+
5
+ Utility functions.
6
+
7
+ :copyright: Copyright 2006-2024 by the Pygments team, see AUTHORS.
8
+ :license: BSD, see LICENSE for details.
9
+ """
10
+
11
+ import re
12
+ from io import TextIOWrapper
13
+
14
+
15
+ split_path_re = re.compile(r'[/\\ ]')
16
+ doctype_lookup_re = re.compile(r'''
17
+ <!DOCTYPE\s+(
18
+ [a-zA-Z_][a-zA-Z0-9]*
19
+ (?: \s+ # optional in HTML5
20
+ [a-zA-Z_][a-zA-Z0-9]*\s+
21
+ "[^"]*")?
22
+ )
23
+ [^>]*>
24
+ ''', re.DOTALL | re.MULTILINE | re.VERBOSE)
25
+ tag_re = re.compile(r'<(.+?)(\s.*?)?>.*?</.+?>',
26
+ re.IGNORECASE | re.DOTALL | re.MULTILINE)
27
+ xml_decl_re = re.compile(r'\s*<\?xml[^>]*\?>', re.I)
28
+
29
+
30
+ class ClassNotFound(ValueError):
31
+ """Raised if one of the lookup functions didn't find a matching class."""
32
+
33
+
34
+ class OptionError(Exception):
35
+ """
36
+ This exception will be raised by all option processing functions if
37
+ the type or value of the argument is not correct.
38
+ """
39
+
40
+ def get_choice_opt(options, optname, allowed, default=None, normcase=False):
41
+ """
42
+ If the key `optname` from the dictionary is not in the sequence
43
+ `allowed`, raise an error, otherwise return it.
44
+ """
45
+ string = options.get(optname, default)
46
+ if normcase:
47
+ string = string.lower()
48
+ if string not in allowed:
49
+ raise OptionError('Value for option {} must be one of {}'.format(optname, ', '.join(map(str, allowed))))
50
+ return string
51
+
52
+
53
+ def get_bool_opt(options, optname, default=None):
54
+ """
55
+ Intuitively, this is `options.get(optname, default)`, but restricted to
56
+ Boolean value. The Booleans can be represented as string, in order to accept
57
+ Boolean value from the command line arguments. If the key `optname` is
58
+ present in the dictionary `options` and is not associated with a Boolean,
59
+ raise an `OptionError`. If it is absent, `default` is returned instead.
60
+
61
+ The valid string values for ``True`` are ``1``, ``yes``, ``true`` and
62
+ ``on``, the ones for ``False`` are ``0``, ``no``, ``false`` and ``off``
63
+ (matched case-insensitively).
64
+ """
65
+ string = options.get(optname, default)
66
+ if isinstance(string, bool):
67
+ return string
68
+ elif isinstance(string, int):
69
+ return bool(string)
70
+ elif not isinstance(string, str):
71
+ raise OptionError(f'Invalid type {string!r} for option {optname}; use '
72
+ '1/0, yes/no, true/false, on/off')
73
+ elif string.lower() in ('1', 'yes', 'true', 'on'):
74
+ return True
75
+ elif string.lower() in ('0', 'no', 'false', 'off'):
76
+ return False
77
+ else:
78
+ raise OptionError(f'Invalid value {string!r} for option {optname}; use '
79
+ '1/0, yes/no, true/false, on/off')
80
+
81
+
82
+ def get_int_opt(options, optname, default=None):
83
+ """As :func:`get_bool_opt`, but interpret the value as an integer."""
84
+ string = options.get(optname, default)
85
+ try:
86
+ return int(string)
87
+ except TypeError:
88
+ raise OptionError(f'Invalid type {string!r} for option {optname}; you '
89
+ 'must give an integer value')
90
+ except ValueError:
91
+ raise OptionError(f'Invalid value {string!r} for option {optname}; you '
92
+ 'must give an integer value')
93
+
94
+ def get_list_opt(options, optname, default=None):
95
+ """
96
+ If the key `optname` from the dictionary `options` is a string,
97
+ split it at whitespace and return it. If it is already a list
98
+ or a tuple, it is returned as a list.
99
+ """
100
+ val = options.get(optname, default)
101
+ if isinstance(val, str):
102
+ return val.split()
103
+ elif isinstance(val, (list, tuple)):
104
+ return list(val)
105
+ else:
106
+ raise OptionError(f'Invalid type {val!r} for option {optname}; you '
107
+ 'must give a list value')
108
+
109
+
110
+ def docstring_headline(obj):
111
+ if not obj.__doc__:
112
+ return ''
113
+ res = []
114
+ for line in obj.__doc__.strip().splitlines():
115
+ if line.strip():
116
+ res.append(" " + line.strip())
117
+ else:
118
+ break
119
+ return ''.join(res).lstrip()
120
+
121
+
122
+ def make_analysator(f):
123
+ """Return a static text analyser function that returns float values."""
124
+ def text_analyse(text):
125
+ try:
126
+ rv = f(text)
127
+ except Exception:
128
+ return 0.0
129
+ if not rv:
130
+ return 0.0
131
+ try:
132
+ return min(1.0, max(0.0, float(rv)))
133
+ except (ValueError, TypeError):
134
+ return 0.0
135
+ text_analyse.__doc__ = f.__doc__
136
+ return staticmethod(text_analyse)
137
+
138
+
139
+ def shebang_matches(text, regex):
140
+ r"""Check if the given regular expression matches the last part of the
141
+ shebang if one exists.
142
+
143
+ >>> from pygments.util import shebang_matches
144
+ >>> shebang_matches('#!/usr/bin/env python', r'python(2\.\d)?')
145
+ True
146
+ >>> shebang_matches('#!/usr/bin/python2.4', r'python(2\.\d)?')
147
+ True
148
+ >>> shebang_matches('#!/usr/bin/python-ruby', r'python(2\.\d)?')
149
+ False
150
+ >>> shebang_matches('#!/usr/bin/python/ruby', r'python(2\.\d)?')
151
+ False
152
+ >>> shebang_matches('#!/usr/bin/startsomethingwith python',
153
+ ... r'python(2\.\d)?')
154
+ True
155
+
156
+ It also checks for common windows executable file extensions::
157
+
158
+ >>> shebang_matches('#!C:\\Python2.4\\Python.exe', r'python(2\.\d)?')
159
+ True
160
+
161
+ Parameters (``'-f'`` or ``'--foo'`` are ignored so ``'perl'`` does
162
+ the same as ``'perl -e'``)
163
+
164
+ Note that this method automatically searches the whole string (eg:
165
+ the regular expression is wrapped in ``'^$'``)
166
+ """
167
+ index = text.find('\n')
168
+ if index >= 0:
169
+ first_line = text[:index].lower()
170
+ else:
171
+ first_line = text.lower()
172
+ if first_line.startswith('#!'):
173
+ try:
174
+ found = [x for x in split_path_re.split(first_line[2:].strip())
175
+ if x and not x.startswith('-')][-1]
176
+ except IndexError:
177
+ return False
178
+ regex = re.compile(rf'^{regex}(\.(exe|cmd|bat|bin))?$', re.IGNORECASE)
179
+ if regex.search(found) is not None:
180
+ return True
181
+ return False
182
+
183
+
184
+ def doctype_matches(text, regex):
185
+ """Check if the doctype matches a regular expression (if present).
186
+
187
+ Note that this method only checks the first part of a DOCTYPE.
188
+ eg: 'html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"'
189
+ """
190
+ m = doctype_lookup_re.search(text)
191
+ if m is None:
192
+ return False
193
+ doctype = m.group(1)
194
+ return re.compile(regex, re.I).match(doctype.strip()) is not None
195
+
196
+
197
+ def html_doctype_matches(text):
198
+ """Check if the file looks like it has a html doctype."""
199
+ return doctype_matches(text, r'html')
200
+
201
+
202
+ _looks_like_xml_cache = {}
203
+
204
+
205
+ def looks_like_xml(text):
206
+ """Check if a doctype exists or if we have some tags."""
207
+ if xml_decl_re.match(text):
208
+ return True
209
+ key = hash(text)
210
+ try:
211
+ return _looks_like_xml_cache[key]
212
+ except KeyError:
213
+ m = doctype_lookup_re.search(text)
214
+ if m is not None:
215
+ return True
216
+ rv = tag_re.search(text[:1000]) is not None
217
+ _looks_like_xml_cache[key] = rv
218
+ return rv
219
+
220
+
221
+ def surrogatepair(c):
222
+ """Given a unicode character code with length greater than 16 bits,
223
+ return the two 16 bit surrogate pair.
224
+ """
225
+ # From example D28 of:
226
+ # http://www.unicode.org/book/ch03.pdf
227
+ return (0xd7c0 + (c >> 10), (0xdc00 + (c & 0x3ff)))
228
+
229
+
230
+ def format_lines(var_name, seq, raw=False, indent_level=0):
231
+ """Formats a sequence of strings for output."""
232
+ lines = []
233
+ base_indent = ' ' * indent_level * 4
234
+ inner_indent = ' ' * (indent_level + 1) * 4
235
+ lines.append(base_indent + var_name + ' = (')
236
+ if raw:
237
+ # These should be preformatted reprs of, say, tuples.
238
+ for i in seq:
239
+ lines.append(inner_indent + i + ',')
240
+ else:
241
+ for i in seq:
242
+ # Force use of single quotes
243
+ r = repr(i + '"')
244
+ lines.append(inner_indent + r[:-2] + r[-1] + ',')
245
+ lines.append(base_indent + ')')
246
+ return '\n'.join(lines)
247
+
248
+
249
+ def duplicates_removed(it, already_seen=()):
250
+ """
251
+ Returns a list with duplicates removed from the iterable `it`.
252
+
253
+ Order is preserved.
254
+ """
255
+ lst = []
256
+ seen = set()
257
+ for i in it:
258
+ if i in seen or i in already_seen:
259
+ continue
260
+ lst.append(i)
261
+ seen.add(i)
262
+ return lst
263
+
264
+
265
+ class Future:
266
+ """Generic class to defer some work.
267
+
268
+ Handled specially in RegexLexerMeta, to support regex string construction at
269
+ first use.
270
+ """
271
+ def get(self):
272
+ raise NotImplementedError
273
+
274
+
275
+ def guess_decode(text):
276
+ """Decode *text* with guessed encoding.
277
+
278
+ First try UTF-8; this should fail for non-UTF-8 encodings.
279
+ Then try the preferred locale encoding.
280
+ Fall back to latin-1, which always works.
281
+ """
282
+ try:
283
+ text = text.decode('utf-8')
284
+ return text, 'utf-8'
285
+ except UnicodeDecodeError:
286
+ try:
287
+ import locale
288
+ prefencoding = locale.getpreferredencoding()
289
+ text = text.decode()
290
+ return text, prefencoding
291
+ except (UnicodeDecodeError, LookupError):
292
+ text = text.decode('latin1')
293
+ return text, 'latin1'
294
+
295
+
296
+ def guess_decode_from_terminal(text, term):
297
+ """Decode *text* coming from terminal *term*.
298
+
299
+ First try the terminal encoding, if given.
300
+ Then try UTF-8. Then try the preferred locale encoding.
301
+ Fall back to latin-1, which always works.
302
+ """
303
+ if getattr(term, 'encoding', None):
304
+ try:
305
+ text = text.decode(term.encoding)
306
+ except UnicodeDecodeError:
307
+ pass
308
+ else:
309
+ return text, term.encoding
310
+ return guess_decode(text)
311
+
312
+
313
+ def terminal_encoding(term):
314
+ """Return our best guess of encoding for the given *term*."""
315
+ if getattr(term, 'encoding', None):
316
+ return term.encoding
317
+ import locale
318
+ return locale.getpreferredencoding()
319
+
320
+
321
+ class UnclosingTextIOWrapper(TextIOWrapper):
322
+ # Don't close underlying buffer on destruction.
323
+ def close(self):
324
+ self.flush()
minigpt2/lib/python3.10/site-packages/Crypto/Math/_modexp.abi3.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:93b056fe341952f08d2160cd7232bf5c5293fdf611cfc0a0f8958a9badc4d6a9
3
+ size 220424
minigpt2/lib/python3.10/site-packages/decord/__init__.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Decord python package"""
2
+ from . import function
3
+
4
+ from ._ffi.runtime_ctypes import TypeCode
5
+ from ._ffi.function import register_func, get_global_func, list_global_func_names, extract_ext_funcs
6
+ from ._ffi.base import DECORDError, DECORDLimitReachedError, __version__
7
+
8
+ from .base import ALL
9
+
10
+ from . import ndarray as nd
11
+ from .ndarray import cpu, gpu
12
+ from . import bridge
13
+ from . import logging
14
+ from .video_reader import VideoReader
15
+ from .video_loader import VideoLoader
16
+ from .audio_reader import AudioReader
17
+ from .av_reader import AVReader
18
+
19
+ logging.set_level(logging.ERROR)
minigpt2/lib/python3.10/site-packages/decord/_api_internal.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """Namespace for internal apis."""
minigpt2/lib/python3.10/site-packages/decord/audio_reader.py ADDED
@@ -0,0 +1,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Audio Reader."""
2
+ from __future__ import absolute_import
3
+
4
+ import ctypes
5
+ import numpy as np
6
+ import math
7
+
8
+ from ._ffi.base import c_array, c_str
9
+ from ._ffi.function import _init_api
10
+ from ._ffi.ndarray import DECORDContext
11
+ from .base import DECORDError
12
+ from . import ndarray as _nd
13
+ from .ndarray import cpu, gpu
14
+ from .bridge import bridge_out
15
+
16
+ AudioReaderHandle = ctypes.c_void_p
17
+
18
+ class AudioReader(object):
19
+ """Individual audio reader with convenient indexing function.
20
+
21
+ Parameters
22
+ ----------
23
+ uri: str
24
+ Path of file.
25
+ ctx: decord.Context
26
+ The context to decode the file, can be decord.cpu() or decord.gpu().
27
+ sample_rate: int, default is -1
28
+ Desired output sample rate of the audio, unchanged if `-1` is specified.
29
+ mono: bool, default is True
30
+ Desired output channel layout of the audio.
31
+ Setting `True` will return the audio as mono layout.
32
+ Setting `False` will return the audio channel layout intact.
33
+
34
+ """
35
+
36
+ def __init__(self, uri, ctx=cpu(0), sample_rate=-1, mono=True):
37
+ self._handle = None
38
+ assert isinstance(ctx, DECORDContext)
39
+ is_mono = 1 if mono else 0
40
+ if hasattr(uri, 'read'):
41
+ ba = bytearray(uri.read())
42
+ uri = '{} bytes'.format(len(ba))
43
+ self._handle = _CAPI_AudioReaderGetAudioReader(
44
+ ba, ctx.device_type, ctx.device_id, sample_rate, 2, is_mono)
45
+ else:
46
+ self._handle = _CAPI_AudioReaderGetAudioReader(
47
+ uri, ctx.device_type, ctx.device_id, sample_rate, 0, is_mono)
48
+ if self._handle is None:
49
+ raise RuntimeError("Error reading " + uri + "...")
50
+ self._array = _CAPI_AudioReaderGetNDArray(self._handle)
51
+ self._array = self._array.asnumpy()
52
+ self._duration = _CAPI_AudioReaderGetDuration(self._handle)
53
+ self._num_samples_per_channel = _CAPI_AudioReaderGetNumSamplesPerChannel(self._handle)
54
+ self._num_channels = _CAPI_AudioReaderGetNumChannels(self._handle)
55
+ self.sample_rate = sample_rate
56
+ self._num_padding = None
57
+
58
+ def __len__(self):
59
+ """Get length of the audio. The length refer to the shape's first dimension. In this case,
60
+ the length is the number of channels.
61
+ Returns
62
+ -------
63
+ int
64
+ The number of channels in the audio track.
65
+ """
66
+ return self.shape[0]
67
+
68
+ def __del__(self):
69
+ if self._handle:
70
+ _CAPI_AudioReaderFree(self._handle)
71
+
72
+ def __getitem__(self, idx):
73
+ """Get sample at `idx`. idx is the index of resampled audio, unit is sample.
74
+
75
+ Parameters
76
+ ----------
77
+ idx : int or slice
78
+ The sample index, can be negative which means it will index backwards,
79
+ or slice of sample indices.
80
+
81
+ Returns
82
+ -------
83
+ ndarray
84
+ Samples of shape CxS,
85
+ where C is the number of channels, S is the number of samples of the index or slice.
86
+ """
87
+ assert self._handle is not None
88
+ if isinstance(idx, slice):
89
+ return self.get_batch(range(*idx.indices(self._num_samples_per_channel)))
90
+ if idx < 0:
91
+ idx += self._num_samples_per_channel
92
+ if idx >= self._num_samples_per_channel or idx < 0:
93
+ raise IndexError("Index: {} out of bound: {}".format(idx, self._num_samples_per_channel))
94
+ return bridge_out(_nd.array(self._array[:, idx]))
95
+
96
+ def get_batch(self, indices):
97
+ """Get entire batch of samples.
98
+
99
+ Parameters
100
+ ----------
101
+ indices : list of integers
102
+ A list of frame indices. If negative indices detected, the indices will be indexed from backward
103
+ Returns
104
+ -------
105
+ ndarray
106
+ Samples of shape CxS,
107
+ where C is the number of channels, S is the number of samples of the slice.
108
+
109
+ """
110
+ assert self._handle is not None
111
+ indices = self._validate_indices(indices)
112
+ indices = list(indices)
113
+ return bridge_out(_nd.array(self._array[:, indices]))
114
+
115
+ @property
116
+ def shape(self):
117
+ """Get shape of the entire audio samples.
118
+
119
+ Returns
120
+ -------
121
+ (int, int)
122
+ The number of channels, and the number of samples in each channel.
123
+
124
+ """
125
+ return (self._num_channels, self._num_samples_per_channel)
126
+
127
+ def duration(self):
128
+ """Get duration of the audio.
129
+
130
+ Returns
131
+ -------
132
+ double
133
+ Duration of the audio in secs.
134
+
135
+ """
136
+ return self._duration
137
+
138
+ def __get_num_padding(self):
139
+ """Get number of samples needed to pad the audio to start at time 0."""
140
+ if self._num_padding is None:
141
+ self._num_padding = _CAPI_AudioReaderGetNumPaddingSamples(self._handle)
142
+ return self._num_padding
143
+
144
+ def add_padding(self):
145
+ """Pad the audio samples so that it starts at time 0.
146
+
147
+ Returns
148
+ -------
149
+ int
150
+ Number of samples padded
151
+
152
+ """
153
+ self._array = np.pad(self._array, ((0, 0), (self.__get_num_padding(), 0)), 'constant', constant_values=0)
154
+ self._duration += self.__get_num_padding() * self.sample_rate
155
+ return self.__get_num_padding()
156
+
157
+ def get_info(self):
158
+ """Log out the basic info about the audio stream."""
159
+ _CAPI_AudioReaderGetInfo(self._handle)
160
+
161
+ def _time_to_sample(self, timestamp):
162
+ """Convert time in seconds to sample index"""
163
+ return math.ceil(timestamp * self.sample_rate)
164
+
165
+ def _times_to_samples(self, timestamps):
166
+ """Convert times in seconds to sample indices"""
167
+ return [self._time_to_sample(timestamp) for timestamp in timestamps]
168
+
169
+ def _validate_indices(self, indices):
170
+ """Validate int64 integers and convert negative integers to positive by backward search"""
171
+ assert self._handle is not None
172
+ indices = np.array(indices, dtype=np.int64)
173
+ # process negative indices
174
+ indices[indices < 0] += self._num_samples_per_channel
175
+ if not (indices >= 0).all():
176
+ raise IndexError(
177
+ 'Invalid negative indices: {}'.format(indices[indices < 0] + self._num_samples_per_channel))
178
+ if not (indices < self._num_samples_per_channel).all():
179
+ raise IndexError('Out of bound indices: {}'.format(indices[indices >= self._num_samples_per_channel]))
180
+ return indices
181
+
182
+ _init_api("decord.audio_reader")
minigpt2/lib/python3.10/site-packages/decord/av_reader.py ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """AV Reader."""
2
+ from __future__ import absolute_import
3
+
4
+ import ctypes
5
+ import numpy as np
6
+ import math
7
+ from .video_reader import VideoReader
8
+ from .audio_reader import AudioReader
9
+
10
+ from .ndarray import cpu, gpu
11
+ from . import ndarray as _nd
12
+ from .bridge import bridge_out
13
+
14
+ class AVReader(object):
15
+ """Individual audio video reader with convenient indexing function.
16
+
17
+ Parameters
18
+ ----------
19
+ uri: str
20
+ Path of file.
21
+ ctx: decord.Context
22
+ The context to decode the file, can be decord.cpu() or decord.gpu().
23
+ sample_rate: int, default is -1
24
+ Desired output sample rate of the audio, unchanged if `-1` is specified.
25
+ mono: bool, default is True
26
+ Desired output channel layout of the audio. `True` is mono layout. `False` is unchanged.
27
+ width : int, default is -1
28
+ Desired output width of the video, unchanged if `-1` is specified.
29
+ height : int, default is -1
30
+ Desired output height of the video, unchanged if `-1` is specified.
31
+ num_threads : int, default is 0
32
+ Number of decoding thread, auto if `0` is specified.
33
+ fault_tol : int, default is -1
34
+ The threshold of corupted and recovered frames. This is to prevent silent fault
35
+ tolerance when for example 50% frames of a video cannot be decoded and duplicate
36
+ frames are returned. You may find the fault tolerant feature sweet in many cases,
37
+ but not for training models. Say `N = # recovered frames`
38
+ If `fault_tol` < 0, nothing will happen.
39
+ If 0 < `fault_tol` < 1.0, if N > `fault_tol * len(video)`, raise `DECORDLimitReachedError`.
40
+ If 1 < `fault_tol`, if N > `fault_tol`, raise `DECORDLimitReachedError`.
41
+
42
+ """
43
+
44
+ def __init__(self, uri, ctx=cpu(0), sample_rate=44100, mono=True, width=-1, height=-1, num_threads=0, fault_tol=-1):
45
+ self.__audio_reader = AudioReader(uri, ctx, sample_rate, mono)
46
+ self.__audio_reader.add_padding()
47
+ if hasattr(uri, 'read'):
48
+ uri.seek(0)
49
+ self.__video_reader = VideoReader(uri, ctx, width, height, num_threads, fault_tol)
50
+
51
+ def __len__(self):
52
+ """Get length of the video. Note that sometimes FFMPEG reports inaccurate number of frames,
53
+ we always follow what FFMPEG reports.
54
+ Returns
55
+ -------
56
+ int
57
+ The number of frames in the video file.
58
+ """
59
+ return len(self.__video_reader)
60
+
61
+ def __getitem__(self, idx):
62
+ """Get audio samples and video frame at `idx`.
63
+
64
+ Parameters
65
+ ----------
66
+ idx : int or slice
67
+ The frame index, can be negative which means it will index backwards,
68
+ or slice of frame indices.
69
+
70
+ Returns
71
+ -------
72
+ (ndarray/list of ndarray, ndarray)
73
+ First element is samples of shape CxS or a list of length N containing samples of shape CxS,
74
+ where N is the number of frames, C is the number of channels,
75
+ S is the number of samples of the corresponding frame.
76
+
77
+ Second element is Frame of shape HxWx3 or batch of image frames with shape NxHxWx3,
78
+ where N is the length of the slice.
79
+ """
80
+ assert self.__video_reader is not None and self.__audio_reader is not None
81
+ if isinstance(idx, slice):
82
+ return self.get_batch(range(*idx.indices(len(self.__video_reader))))
83
+ if idx < 0:
84
+ idx += len(self.__video_reader)
85
+ if idx >= len(self.__video_reader) or idx < 0:
86
+ raise IndexError("Index: {} out of bound: {}".format(idx, len(self.__video_reader)))
87
+ audio_start_idx, audio_end_idx = self.__video_reader.get_frame_timestamp(idx)
88
+ audio_start_idx = self.__audio_reader._time_to_sample(audio_start_idx)
89
+ audio_end_idx = self.__audio_reader._time_to_sample(audio_end_idx)
90
+ return (self.__audio_reader[audio_start_idx:audio_end_idx], self.__video_reader[idx])
91
+
92
+ def get_batch(self, indices):
93
+ """Get entire batch of audio samples and video frames.
94
+
95
+ Parameters
96
+ ----------
97
+ indices : list of integers
98
+ A list of frame indices. If negative indices detected, the indices will be indexed from backward
99
+ Returns
100
+ -------
101
+ (list of ndarray, ndarray)
102
+ First element is a list of length N containing samples of shape CxS,
103
+ where N is the number of frames, C is the number of channels,
104
+ S is the number of samples of the corresponding frame.
105
+
106
+ Second element is Frame of shape HxWx3 or batch of image frames with shape NxHxWx3,
107
+ where N is the length of the slice.
108
+
109
+ """
110
+ assert self.__video_reader is not None and self.__audio_reader is not None
111
+ indices = self._validate_indices(indices)
112
+ audio_arr = []
113
+ prev_video_idx = None
114
+ prev_audio_end_idx = None
115
+ for idx in list(indices):
116
+ frame_start_time, frame_end_time = self.__video_reader.get_frame_timestamp(idx)
117
+ # timestamp and sample conversion could have some error that could cause non-continuous audio
118
+ # we detect if retrieving continuous frame and make the audio continuous
119
+ if prev_video_idx and idx == prev_video_idx+1:
120
+ audio_start_idx = prev_audio_end_idx
121
+ else:
122
+ audio_start_idx = self.__audio_reader._time_to_sample(frame_start_time)
123
+ audio_end_idx = self.__audio_reader._time_to_sample(frame_end_time)
124
+ audio_arr.append(self.__audio_reader[audio_start_idx:audio_end_idx])
125
+ prev_video_idx = idx
126
+ prev_audio_end_idx = audio_end_idx
127
+ return (audio_arr, self.__video_reader.get_batch(indices))
128
+
129
+ def _get_slice(self, sl):
130
+ audio_arr = np.empty(shape=(self.__audio_reader.shape()[0], 0), dtype='float32')
131
+ for idx in list(sl):
132
+ audio_start_idx, audio_end_idx = self.__video_reader.get_frame_timestamp(idx)
133
+ audio_start_idx = self.__audio_reader._time_to_sample(audio_start_idx)
134
+ audio_end_idx = self.__audio_reader._time_to_sample(audio_end_idx)
135
+ audio_arr = np.concatenate((audio_arr, self.__audio_reader[audio_start_idx:audio_end_idx].asnumpy()), axis=1)
136
+ return (bridge_out(_nd.array(audio_arr)), self.__video_reader.get_batch(sl))
137
+
138
+ def _validate_indices(self, indices):
139
+ """Validate int64 integers and convert negative integers to positive by backward search"""
140
+ assert self.__video_reader is not None and self.__audio_reader is not None
141
+ indices = np.array(indices, dtype=np.int64)
142
+ # process negative indices
143
+ indices[indices < 0] += len(self.__video_reader)
144
+ if not (indices >= 0).all():
145
+ raise IndexError(
146
+ 'Invalid negative indices: {}'.format(indices[indices < 0] + len(self.__video_reader)))
147
+ if not (indices < len(self.__video_reader)).all():
148
+ raise IndexError('Out of bound indices: {}'.format(indices[indices >= len(self.__video_reader)]))
149
+ return indices
minigpt2/lib/python3.10/site-packages/decord/base.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Module for base types and utilities."""
2
+ from __future__ import absolute_import
3
+
4
+ import warnings
5
+
6
+ from ._ffi.base import DECORDError # pylint: disable=unused-import
7
+ from ._ffi.function import _init_internal_api
8
+
9
+ # A special symbol for selecting all nodes or edges.
10
+ ALL = "__ALL__"
11
+
12
+ def is_all(arg):
13
+ """Return true if the argument is a special symbol for all nodes or edges."""
14
+ return isinstance(arg, str) and arg == ALL
15
+
16
+ def decord_warning(msg):
17
+ """Print out warning messages."""
18
+ warnings.warn(msg)
19
+
20
+ _init_internal_api()
minigpt2/lib/python3.10/site-packages/decord/logging.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """DECORD logging module.
2
+
3
+ You can adjust the logging level for ffmpeg.
4
+ """
5
+ from ._ffi.function import _init_api
6
+
7
+ QUIET = -8
8
+ PANIC = 0
9
+ FATAL = 8
10
+ ERROR = 16
11
+ WARNING = 24
12
+ INFO = 32
13
+ VERBOSE = 40
14
+ DEBUG = 48
15
+ TRACE = 56
16
+
17
+ # Mimicking stdlib.
18
+ CRITICAL = FATAL
19
+
20
+ def set_level(lvl=ERROR):
21
+ _CAPI_SetLoggingLevel(lvl)
22
+
23
+ _init_api("decord.logging")
minigpt2/lib/python3.10/site-packages/decord/video_loader.py ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Video Loader."""
2
+ from __future__ import absolute_import
3
+
4
+ import ctypes
5
+ import numpy as np
6
+
7
+ from ._ffi.base import c_array, c_str
8
+ from ._ffi.function import _init_api
9
+ from .base import DECORDError
10
+ from . import ndarray as _nd
11
+ from .ndarray import DECORDContext
12
+ from .bridge import bridge_out
13
+
14
+ VideoLoaderHandle = ctypes.c_void_p
15
+
16
+
17
+ class VideoLoader(object):
18
+ """Multiple video loader with advanced shuffling and batching methods.
19
+
20
+ Parameters
21
+ ----------
22
+ uris : list of str
23
+ List of video paths.
24
+ ctx : decord.Context or list of Context
25
+ The context to decode the video file, can be decord.cpu() or decord.gpu().
26
+ If ctx is a list, videos will be evenly split over many ctxs.
27
+ shape : tuple
28
+ Returned shape of the batch images, e.g., (2, 320, 240, 3) as (Batch, H, W, 3)
29
+ interval : int
30
+ Intra-batch frame interval.
31
+ skip : int
32
+ Inter-batch frame interval.
33
+ shuffle : int
34
+ Shuffling strategy. Can be
35
+ `0`: all sequential, no seeking, following initial filename order
36
+ `1`: random filename order, no random access for each video, very efficient
37
+ `2`: random order
38
+ `3`: random frame access in each video only.
39
+
40
+ """
41
+ def __init__(self, uris, ctx, shape, interval, skip, shuffle, prefetch=0):
42
+ self._handle = None
43
+ assert isinstance(uris, (list, tuple))
44
+ assert (len(uris) > 0)
45
+ uri = ','.join([x.strip() for x in uris])
46
+ if isinstance(ctx, DECORDContext):
47
+ ctx = [ctx]
48
+ for _ctx in ctx:
49
+ assert isinstance(_ctx, DECORDContext)
50
+ device_types = _nd.array([x.device_type for x in ctx])
51
+ device_ids = _nd.array([x.device_id for x in ctx])
52
+ assert isinstance(shape, (list, tuple))
53
+ assert len(shape) == 4, "expected shape: [bs, height, width, 3], given {}".format(shape)
54
+ self._handle = _CAPI_VideoLoaderGetVideoLoader(
55
+ uri, device_types, device_ids, shape[0], shape[1], shape[2], shape[3], interval, skip, shuffle, prefetch)
56
+ assert self._handle is not None
57
+ self._len = _CAPI_VideoLoaderLength(self._handle)
58
+ self._curr = 0
59
+
60
+ def __del__(self):
61
+ if self._handle:
62
+ _CAPI_VideoLoaderFree(self._handle)
63
+
64
+ def __len__(self):
65
+ """Get number of batches in each epoch.
66
+
67
+ Returns
68
+ -------
69
+ int
70
+ number of batches in each epoch.
71
+
72
+ """
73
+ return self._len
74
+
75
+ def reset(self):
76
+ """Reset loader for next epoch.
77
+
78
+ """
79
+ assert self._handle is not None
80
+ self._curr = 0
81
+ _CAPI_VideoLoaderReset(self._handle)
82
+
83
+ def __next__(self):
84
+ """Get the next batch.
85
+
86
+ Returns
87
+ -------
88
+ ndarray, ndarray
89
+ Frame data and corresponding indices in videos.
90
+ Indices are [(n0, k0), (n1, k1)...] where n0 is the index of video, k0 is the index
91
+ of frame in video n0.
92
+
93
+ """
94
+ assert self._handle is not None
95
+ # avoid calling CAPI HasNext
96
+ if self._curr >= self._len:
97
+ raise StopIteration
98
+ _CAPI_VideoLoaderNext(self._handle)
99
+ data = _CAPI_VideoLoaderNextData(self._handle)
100
+ indices = _CAPI_VideoLoaderNextIndices(self._handle)
101
+ self._curr += 1
102
+ return bridge_out(data), bridge_out(indices)
103
+
104
+ def next(self):
105
+ """Alias of __next__ for python2.
106
+
107
+ """
108
+ return self.__next__()
109
+
110
+ def __iter__(self):
111
+ assert self._handle is not None
112
+ # if (self._curr >= self._len):
113
+ # self.reset()
114
+ # else:
115
+ # err_msg = "Call __iter__ of VideoLoader during previous iteration is forbidden. \
116
+ # Consider using cached iterator by 'vl = iter(video_loader)' and reuse it."
117
+ # raise RuntimeError(err_msg)
118
+ return self
119
+
120
+
121
+ _init_api("decord.video_loader")
minigpt2/lib/python3.10/site-packages/decord/video_reader.py ADDED
@@ -0,0 +1,251 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Video Reader."""
2
+ from __future__ import absolute_import
3
+
4
+ import ctypes
5
+ import numpy as np
6
+
7
+ from ._ffi.base import c_array, c_str
8
+ from ._ffi.function import _init_api
9
+ from ._ffi.ndarray import DECORDContext
10
+ from .base import DECORDError
11
+ from . import ndarray as _nd
12
+ from .ndarray import cpu, gpu
13
+ from .bridge import bridge_out
14
+
15
+ VideoReaderHandle = ctypes.c_void_p
16
+
17
+
18
+ class VideoReader(object):
19
+ """Individual video reader with convenient indexing and seeking functions.
20
+
21
+ Parameters
22
+ ----------
23
+ uri : str
24
+ Path of video file.
25
+ ctx : decord.Context
26
+ The context to decode the video file, can be decord.cpu() or decord.gpu().
27
+ width : int, default is -1
28
+ Desired output width of the video, unchanged if `-1` is specified.
29
+ height : int, default is -1
30
+ Desired output height of the video, unchanged if `-1` is specified.
31
+ num_threads : int, default is 0
32
+ Number of decoding thread, auto if `0` is specified.
33
+ fault_tol : int, default is -1
34
+ The threshold of corupted and recovered frames. This is to prevent silent fault
35
+ tolerance when for example 50% frames of a video cannot be decoded and duplicate
36
+ frames are returned. You may find the fault tolerant feature sweet in many cases,
37
+ but not for training models. Say `N = # recovered frames`
38
+ If `fault_tol` < 0, nothing will happen.
39
+ If 0 < `fault_tol` < 1.0, if N > `fault_tol * len(video)`, raise `DECORDLimitReachedError`.
40
+ If 1 < `fault_tol`, if N > `fault_tol`, raise `DECORDLimitReachedError`.
41
+
42
+
43
+ """
44
+ def __init__(self, uri, ctx=cpu(0), width=-1, height=-1, num_threads=0, fault_tol=-1):
45
+ self._handle = None
46
+ assert isinstance(ctx, DECORDContext)
47
+ fault_tol = str(fault_tol)
48
+ if hasattr(uri, 'read'):
49
+ ba = bytearray(uri.read())
50
+ uri = '{} bytes'.format(len(ba))
51
+ self._handle = _CAPI_VideoReaderGetVideoReader(
52
+ ba, ctx.device_type, ctx.device_id, width, height, num_threads, 2, fault_tol)
53
+ else:
54
+ self._handle = _CAPI_VideoReaderGetVideoReader(
55
+ uri, ctx.device_type, ctx.device_id, width, height, num_threads, 0, fault_tol)
56
+ if self._handle is None:
57
+ raise RuntimeError("Error reading " + uri + "...")
58
+ self._num_frame = _CAPI_VideoReaderGetFrameCount(self._handle)
59
+ assert self._num_frame > 0, "Invalid frame count: {}".format(self._num_frame)
60
+ self._key_indices = None
61
+ self._frame_pts = None
62
+ self._avg_fps = None
63
+
64
+ def __del__(self):
65
+ try:
66
+ if self._handle is not None:
67
+ _CAPI_VideoReaderFree(self._handle)
68
+ except TypeError:
69
+ pass
70
+
71
+ def __len__(self):
72
+ """Get length of the video. Note that sometimes FFMPEG reports inaccurate number of frames,
73
+ we always follow what FFMPEG reports.
74
+
75
+ Returns
76
+ -------
77
+ int
78
+ The number of frames in the video file.
79
+
80
+ """
81
+ return self._num_frame
82
+
83
+ def __getitem__(self, idx):
84
+ """Get frame at `idx`.
85
+
86
+ Parameters
87
+ ----------
88
+ idx : int or slice
89
+ The frame index, can be negative which means it will index backwards,
90
+ or slice of frame indices.
91
+
92
+ Returns
93
+ -------
94
+ ndarray
95
+ Frame of shape HxWx3 or batch of image frames with shape NxHxWx3,
96
+ where N is the length of the slice.
97
+ """
98
+ if isinstance(idx, slice):
99
+ return self.get_batch(range(*idx.indices(len(self))))
100
+ if idx < 0:
101
+ idx += self._num_frame
102
+ if idx >= self._num_frame or idx < 0:
103
+ raise IndexError("Index: {} out of bound: {}".format(idx, self._num_frame))
104
+ self.seek_accurate(idx)
105
+ return self.next()
106
+
107
+ def next(self):
108
+ """Grab the next frame.
109
+
110
+ Returns
111
+ -------
112
+ ndarray
113
+ Frame with shape HxWx3.
114
+
115
+ """
116
+ assert self._handle is not None
117
+ arr = _CAPI_VideoReaderNextFrame(self._handle)
118
+ if not arr.shape:
119
+ raise StopIteration()
120
+ return bridge_out(arr)
121
+
122
+ def _validate_indices(self, indices):
123
+ """Validate int64 integers and convert negative integers to positive by backward search"""
124
+ assert self._handle is not None
125
+ indices = np.array(indices, dtype=np.int64)
126
+ # process negative indices
127
+ indices[indices < 0] += self._num_frame
128
+ if not (indices >= 0).all():
129
+ raise IndexError(
130
+ 'Invalid negative indices: {}'.format(indices[indices < 0] + self._num_frame))
131
+ if not (indices < self._num_frame).all():
132
+ raise IndexError('Out of bound indices: {}'.format(indices[indices >= self._num_frame]))
133
+ return indices
134
+
135
+ def get_frame_timestamp(self, idx):
136
+ """Get frame playback timestamp in unit(second).
137
+
138
+ Parameters
139
+ ----------
140
+ indices: list of integers or slice
141
+ A list of frame indices. If negative indices detected, the indices will be indexed from backward.
142
+
143
+ Returns
144
+ -------
145
+ numpy.ndarray
146
+ numpy.ndarray of shape (N, 2), where N is the size of indices. The format is `(start_second, end_second)`.
147
+ """
148
+ assert self._handle is not None
149
+ if isinstance(idx, slice):
150
+ idx = self.get_batch(range(*idx.indices(len(self))))
151
+ idx = self._validate_indices(idx)
152
+ if self._frame_pts is None:
153
+ self._frame_pts = _CAPI_VideoReaderGetFramePTS(self._handle).asnumpy()
154
+ return self._frame_pts[idx, :]
155
+
156
+
157
+ def get_batch(self, indices):
158
+ """Get entire batch of images. `get_batch` is optimized to handle seeking internally.
159
+ Duplicate frame indices will be optmized by copying existing frames rather than decode
160
+ from video again.
161
+
162
+ Parameters
163
+ ----------
164
+ indices : list of integers
165
+ A list of frame indices. If negative indices detected, the indices will be indexed from backward
166
+
167
+ Returns
168
+ -------
169
+ ndarray
170
+ An entire batch of image frames with shape NxHxWx3, where N is the length of `indices`.
171
+
172
+ """
173
+ assert self._handle is not None
174
+ indices = _nd.array(self._validate_indices(indices))
175
+ arr = _CAPI_VideoReaderGetBatch(self._handle, indices)
176
+ return bridge_out(arr)
177
+
178
+ def get_key_indices(self):
179
+ """Get list of key frame indices.
180
+
181
+ Returns
182
+ -------
183
+ list
184
+ List of key frame indices.
185
+
186
+ """
187
+ if self._key_indices is None:
188
+ self._key_indices = _CAPI_VideoReaderGetKeyIndices(self._handle).asnumpy().tolist()
189
+ return self._key_indices
190
+
191
+ def get_avg_fps(self):
192
+ """Get average FPS(frame per second).
193
+
194
+ Returns
195
+ -------
196
+ float
197
+ Average FPS.
198
+
199
+ """
200
+ if self._avg_fps is None:
201
+ self._avg_fps = _CAPI_VideoReaderGetAverageFPS(self._handle)
202
+ return self._avg_fps
203
+
204
+ def seek(self, pos):
205
+ """Fast seek to frame position, this does not guarantee accurate position.
206
+ To obtain accurate seeking, see `accurate_seek`.
207
+
208
+ Parameters
209
+ ----------
210
+ pos : integer
211
+ Non negative seeking position.
212
+
213
+ """
214
+ assert self._handle is not None
215
+ assert pos >= 0 and pos < self._num_frame
216
+ success = _CAPI_VideoReaderSeek(self._handle, pos)
217
+ if not success:
218
+ raise RuntimeError("Failed to seek to frame {}".format(pos))
219
+
220
+ def seek_accurate(self, pos):
221
+ """Accurately seek to frame position, this is slower than `seek`
222
+ but guarantees accurate position.
223
+
224
+ Parameters
225
+ ----------
226
+ pos : integer
227
+ Non negative seeking position.
228
+
229
+ """
230
+ assert self._handle is not None
231
+ assert pos >= 0 and pos < self._num_frame
232
+ success = _CAPI_VideoReaderSeekAccurate(self._handle, pos)
233
+ if not success:
234
+ raise RuntimeError("Failed to seek_accurate to frame {}".format(pos))
235
+
236
+ def skip_frames(self, num=1):
237
+ """Skip reading multiple frames. Skipped frames will still be decoded
238
+ (required by following frames) but it can save image resize/copy operations.
239
+
240
+
241
+ Parameters
242
+ ----------
243
+ num : int, default is 1
244
+ The number of frames to be skipped.
245
+
246
+ """
247
+ assert self._handle is not None
248
+ assert num > 0
249
+ _CAPI_VideoReaderSkipFrames(self._handle, num)
250
+
251
+ _init_api("decord.video_reader")
minigpt2/lib/python3.10/site-packages/ftfy-6.3.1.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ pip
minigpt2/lib/python3.10/site-packages/ftfy-6.3.1.dist-info/METADATA ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.3
2
+ Name: ftfy
3
+ Version: 6.3.1
4
+ Summary: Fixes mojibake and other problems with Unicode, after the fact
5
+ Project-URL: Homepage, https://ftfy.readthedocs.io/en/latest/
6
+ Project-URL: Documentation, https://ftfy.readthedocs.io/en/latest/
7
+ Project-URL: Repository, https://github.com/rspeer/python-ftfy
8
+ Project-URL: Issues, https://github.com/rspeer/python-ftfy/issues/
9
+ Project-URL: Changelog, https://github.com/rspeer/python-ftfy/blob/main/CHANGELOG.md
10
+ Project-URL: Blog, https://posts.arborelia.net
11
+ Author-email: Robyn Speer <rspeer@arborelia.net>
12
+ License: Apache-2.0
13
+ License-File: LICENSE.txt
14
+ Requires-Python: >=3.9
15
+ Requires-Dist: wcwidth
16
+ Description-Content-Type: text/markdown
17
+
18
+ # ftfy: fixes text for you
19
+
20
+ [![PyPI package](https://badge.fury.io/py/ftfy.svg)](https://badge.fury.io/py/ftfy)
21
+ [![Docs](https://readthedocs.org/projects/ftfy/badge/?version=latest)](https://ftfy.readthedocs.org/en/latest/)
22
+
23
+ ```python
24
+
25
+ >>> from ftfy import fix_encoding
26
+ >>> print(fix_encoding("(ง'⌣')ง"))
27
+ (ง'⌣')ง
28
+
29
+ ```
30
+
31
+ The full documentation of ftfy is available at [ftfy.readthedocs.org](https://ftfy.readthedocs.org). The documentation covers a lot more than this README, so here are some links into it:
32
+
33
+ - [Fixing problems and getting explanations](https://ftfy.readthedocs.io/en/latest/explain.html)
34
+ - [Configuring ftfy](https://ftfy.readthedocs.io/en/latest/config.html)
35
+ - [Encodings ftfy can handle](https://ftfy.readthedocs.io/en/latest/encodings.html)
36
+ - [“Fixer” functions](https://ftfy.readthedocs.io/en/latest/fixes.html)
37
+ - [Is ftfy an encoding detector?](https://ftfy.readthedocs.io/en/latest/detect.html)
38
+ - [Heuristics for detecting mojibake](https://ftfy.readthedocs.io/en/latest/heuristic.html)
39
+ - [Support for “bad” encodings](https://ftfy.readthedocs.io/en/latest/bad_encodings.html)
40
+ - [Command-line usage](https://ftfy.readthedocs.io/en/latest/cli.html)
41
+ - [Citing ftfy](https://ftfy.readthedocs.io/en/latest/cite.html)
42
+
43
+ ## Testimonials
44
+
45
+ - “My life is livable again!”
46
+ — [@planarrowspace](https://twitter.com/planarrowspace)
47
+ - “A handy piece of magic”
48
+ — [@simonw](https://twitter.com/simonw)
49
+ - “Saved me a large amount of frustrating dev work”
50
+ — [@iancal](https://twitter.com/iancal)
51
+ - “ftfy did the right thing right away, with no faffing about. Excellent work, solving a very tricky real-world (whole-world!) problem.”
52
+ — Brennan Young
53
+ - “I have no idea when I’m gonna need this, but I’m definitely bookmarking it.”
54
+ — [/u/ocrow](https://reddit.com/u/ocrow)
55
+
56
+ ## What it does
57
+
58
+ Here are some examples (found in the real world) of what ftfy can do:
59
+
60
+ ftfy can fix mojibake (encoding mix-ups), by detecting patterns of characters that were clearly meant to be UTF-8 but were decoded as something else:
61
+
62
+ >>> import ftfy
63
+ >>> ftfy.fix_text('✔ No problems')
64
+ '✔ No problems'
65
+
66
+ Does this sound impossible? It's really not. UTF-8 is a well-designed encoding that makes it obvious when it's being misused, and a string of mojibake usually contains all the information we need to recover the original string.
67
+
68
+ ftfy can fix multiple layers of mojibake simultaneously:
69
+
70
+ >>> ftfy.fix_text('The Mona Lisa doesn’t have eyebrows.')
71
+ "The Mona Lisa doesn't have eyebrows."
72
+
73
+ It can fix mojibake that has had "curly quotes" applied on top of it, which cannot be consistently decoded until the quotes are uncurled:
74
+
75
+ >>> ftfy.fix_text("l’humanité")
76
+ "l'humanité"
77
+
78
+ ftfy can fix mojibake that would have included the character U+A0 (non-breaking space), but the U+A0 was turned into an ASCII space and then combined with another following space:
79
+
80
+ >>> ftfy.fix_text('Ã\xa0 perturber la réflexion')
81
+ 'à perturber la réflexion'
82
+ >>> ftfy.fix_text('à perturber la réflexion')
83
+ 'à perturber la réflexion'
84
+
85
+ ftfy can also decode HTML entities that appear outside of HTML, even in cases where the entity has been incorrectly capitalized:
86
+
87
+ >>> # by the HTML 5 standard, only 'P&Eacute;REZ' is acceptable
88
+ >>> ftfy.fix_text('P&EACUTE;REZ')
89
+ 'PÉREZ'
90
+
91
+ These fixes are not applied in all cases, because ftfy has a strongly-held goal of avoiding false positives -- it should never change correctly-decoded text to something else.
92
+
93
+ The following text could be encoded in Windows-1252 and decoded in UTF-8, and it would decode as 'MARQUɅ'. However, the original text is already sensible, so it is unchanged.
94
+
95
+ >>> ftfy.fix_text('IL Y MARQUÉ…')
96
+ 'IL Y MARQUÉ…'
97
+
98
+ ## Installing
99
+
100
+ ftfy is a Python 3 package that can be installed using `pip` or `uv pip`:
101
+
102
+ pip install ftfy
103
+
104
+ (Or use `pip3 install ftfy` on systems where Python 2 and 3 are both globally installed and `pip` refers to Python 2.)
105
+
106
+ If you use `poetry`, you can use ftfy as a dependency in the usual way (such as `poetry add ftfy`).
107
+
108
+ ### Local development
109
+
110
+ ftfy is developed using [uv](https://github.com/astral-sh/uv). You can build a virtual environment with its local dependencies by running `uv venv`, and test it with `uv run pytest`.
111
+
112
+ ## Who maintains ftfy?
113
+
114
+ I'm Robyn Speer, also known as Elia Robyn Lake. You can find my projects
115
+ [on GitHub](https://github.com/rspeer) and my posts on [my own blog](https://posts.arborelia.net).
116
+
117
+ ## Citing ftfy
118
+
119
+ ftfy has been used as a crucial data processing step in major NLP research.
120
+
121
+ It's important to give credit appropriately to everyone whose work you build on in research. This includes software, not just high-status contributions such as mathematical models. All I ask when you use ftfy for research is that you cite it.
122
+
123
+ ftfy has a citable record [on Zenodo](https://zenodo.org/record/2591652). A citation of ftfy may look like this:
124
+
125
+ Robyn Speer. (2019). ftfy (Version 5.5). Zenodo.
126
+ http://doi.org/10.5281/zenodo.2591652
127
+
128
+ In BibTeX format, the citation is::
129
+
130
+ @misc{speer-2019-ftfy,
131
+ author = {Robyn Speer},
132
+ title = {ftfy},
133
+ note = {Version 5.5},
134
+ year = 2019,
135
+ howpublished = {Zenodo},
136
+ doi = {10.5281/zenodo.2591652},
137
+ url = {https://doi.org/10.5281/zenodo.2591652}
138
+ }
139
+
140
+ ## Important license clarifications
141
+
142
+ If you do not follow ftfy's license, you do not have a license to ftfy.
143
+
144
+ This sounds obvious and tautological, but there are people who think open source licenses mean that they can just do what they want, especially in the field of generative AI. It's a permissive license but you still have to follow it. The [Apache license](https://www.apache.org/licenses/LICENSE-2.0) is the only thing that gives you permission to use and copy ftfy; otherwise, all rights are reserved.
145
+
146
+ If you use or distribute ftfy, you must follow the terms of the [Apache license](https://www.apache.org/licenses/LICENSE-2.0), including that you must attribute the author of ftfy (Robyn Speer) correctly.
147
+
148
+ You _may not_ make a derived work of ftfy that obscures its authorship, such as by putting its code in an AI training dataset, including the code in AI training at runtime, or using a generative AI that copies code from such a dataset.
149
+
150
+ At my discretion, I may notify you of a license violation, and give you a chance to either remedy it or delete all copies of ftfy in your possession.
151
+
minigpt2/lib/python3.10/site-packages/ftfy-6.3.1.dist-info/RECORD ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ../../../bin/ftfy,sha256=5ETl199_N7sdm314lecQZRClJC6LZiy0tZjdPB2cOgU,221
2
+ ftfy-6.3.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
3
+ ftfy-6.3.1.dist-info/METADATA,sha256=g_Z8YoA3djfFYLXogCoAum7lErCh6h2uXf8edFsZ0d8,7257
4
+ ftfy-6.3.1.dist-info/RECORD,,
5
+ ftfy-6.3.1.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
+ ftfy-6.3.1.dist-info/WHEEL,sha256=1yFddiXMmvYK7QYTqtRNtX66WJ0Mz8PYEiEUoOUUxRY,87
7
+ ftfy-6.3.1.dist-info/entry_points.txt,sha256=sy4Ei29IqZhQRgYFC17GVrT1JkE6l1-ooJheKulSqO8,39
8
+ ftfy-6.3.1.dist-info/licenses/LICENSE.txt,sha256=oL_FAgvC4eggVRoGJccMlfqomMFec3EA_0iAqhAZeFc,552
9
+ ftfy/__init__.py,sha256=ekX6ZbJnR3UxmgWwpM2_0Eoizn82ukCYQRv57Bsiyzw,29593
10
+ ftfy/__pycache__/__init__.cpython-310.pyc,,
11
+ ftfy/__pycache__/badness.cpython-310.pyc,,
12
+ ftfy/__pycache__/chardata.cpython-310.pyc,,
13
+ ftfy/__pycache__/cli.cpython-310.pyc,,
14
+ ftfy/__pycache__/fixes.cpython-310.pyc,,
15
+ ftfy/__pycache__/formatting.cpython-310.pyc,,
16
+ ftfy/bad_codecs/__init__.py,sha256=sPKWae974vjc3JeOsGhZ8ZFNUoPTISx988zBbxJ7SIQ,3282
17
+ ftfy/bad_codecs/__pycache__/__init__.cpython-310.pyc,,
18
+ ftfy/bad_codecs/__pycache__/sloppy.cpython-310.pyc,,
19
+ ftfy/bad_codecs/__pycache__/utf8_variants.cpython-310.pyc,,
20
+ ftfy/bad_codecs/sloppy.py,sha256=bzgoZAQIrzRUxb-qJmDVX6_Eh2l143IqstdFFFayTII,6814
21
+ ftfy/bad_codecs/utf8_variants.py,sha256=WlyMbOtUFftePEj_SpxDTXirPAj8HcuxVZ1aSYApVh0,9964
22
+ ftfy/badness.py,sha256=jOR-ucAfX6LTjmUP4EdHS95VN766WXG3IsprQHnfb9M,15561
23
+ ftfy/chardata.py,sha256=tAXqrX2Y3zBslAZoj6tFBy-Yn-_-UwF1uszvKN7cVck,34911
24
+ ftfy/cli.py,sha256=q9DNi4LuhKGrleoH_Z3aB6J0oST34a2WWatap7Odr7s,4137
25
+ ftfy/fixes.py,sha256=G8XQKzMlcsw4aPhRrQgcwAMcxqatf7EDmNaOrsY-C6U,18233
26
+ ftfy/formatting.py,sha256=pbmBunYydgPs3bxMhCXFtaTM0_3qT_yp6esZvjvOKZk,5882
27
+ ftfy/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
minigpt2/lib/python3.10/site-packages/ftfy-6.3.1.dist-info/REQUESTED ADDED
File without changes
minigpt2/lib/python3.10/site-packages/ftfy-6.3.1.dist-info/WHEEL ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.25.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
minigpt2/lib/python3.10/site-packages/ftfy-6.3.1.dist-info/entry_points.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ [console_scripts]
2
+ ftfy = ftfy.cli:main
minigpt2/lib/python3.10/site-packages/ftfy-6.3.1.dist-info/licenses/LICENSE.txt ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Copyright 2023 Robyn Speer
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License");
4
+ you may not use this file except in compliance with the License.
5
+ You may obtain a copy of the License at
6
+
7
+ http://www.apache.org/licenses/LICENSE-2.0
8
+
9
+ Unless required by applicable law or agreed to in writing, software
10
+ distributed under the License is distributed on an "AS IS" BASIS,
11
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ See the License for the specific language governing permissions and
13
+ limitations under the License.
minigpt2/lib/python3.10/site-packages/multipart/__init__.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This only works if using a file system, other loaders not implemented.
2
+
3
+ import importlib.util
4
+ import sys
5
+ import warnings
6
+ from pathlib import Path
7
+
8
+ for p in sys.path:
9
+ file_path = Path(p, "multipart.py")
10
+ try:
11
+ if file_path.is_file():
12
+ spec = importlib.util.spec_from_file_location("multipart", file_path)
13
+ assert spec is not None, f"{file_path} found but not loadable!"
14
+ module = importlib.util.module_from_spec(spec)
15
+ sys.modules["multipart"] = module
16
+ assert spec.loader is not None, f"{file_path} must be loadable!"
17
+ spec.loader.exec_module(module)
18
+ break
19
+ except PermissionError:
20
+ pass
21
+ else:
22
+ warnings.warn("Please use `import python_multipart` instead.", PendingDeprecationWarning, stacklevel=2)
23
+ from python_multipart import *
24
+ from python_multipart import __all__, __author__, __copyright__, __license__, __version__
minigpt2/lib/python3.10/site-packages/multipart/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (934 Bytes). View file
 
minigpt2/lib/python3.10/site-packages/multipart/__pycache__/decoders.cpython-310.pyc ADDED
Binary file (205 Bytes). View file
 
minigpt2/lib/python3.10/site-packages/multipart/__pycache__/exceptions.cpython-310.pyc ADDED
Binary file (209 Bytes). View file
 
minigpt2/lib/python3.10/site-packages/multipart/__pycache__/multipart.cpython-310.pyc ADDED
Binary file (207 Bytes). View file
 
minigpt2/lib/python3.10/site-packages/multipart/decoders.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from python_multipart.decoders import *
minigpt2/lib/python3.10/site-packages/multipart/exceptions.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from python_multipart.exceptions import *
minigpt2/lib/python3.10/site-packages/multipart/multipart.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from python_multipart.multipart import *
minigpt2/lib/python3.10/site-packages/xformers-0.0.28.post3.dist-info/RECORD ADDED
@@ -0,0 +1,373 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ xformers-0.0.28.post3.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
2
+ xformers-0.0.28.post3.dist-info/LICENSE,sha256=iwaVhtHd3wMc1GkkT2Y_GzmnThI1eC5iVcJJQ-ACt-o,1610
3
+ xformers-0.0.28.post3.dist-info/METADATA,sha256=N6abyrP_cOV8tkpxSbHOTynvPNO4MHIC8WQU3gojjFU,1014
4
+ xformers-0.0.28.post3.dist-info/RECORD,,
5
+ xformers-0.0.28.post3.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
+ xformers-0.0.28.post3.dist-info/WHEEL,sha256=MxDuPpvkMaXLq_RQVb7oY7-yV_IeOYeifIMhtGld23w,114
7
+ xformers-0.0.28.post3.dist-info/top_level.txt,sha256=4Px1VcGhKk0j3XhKXjA8HtTm6EQOb0hazeJ5nQsNlKk,9
8
+ xformers/_C.so,sha256=nwn4NHfChZmFOXjCcxZj5Rfyf7oncUH_dNaswepcYMs,50942528
9
+ xformers/__init__.py,sha256=TKDA28gOAQdAzwVvU9IEpGWz677QRKgVFmnqvngAg2w,1710
10
+ xformers/__pycache__/__init__.cpython-310.pyc,,
11
+ xformers/__pycache__/_cpp_lib.cpython-310.pyc,,
12
+ xformers/__pycache__/_deprecation_warning.cpython-310.pyc,,
13
+ xformers/__pycache__/attn_bias_utils.cpython-310.pyc,,
14
+ xformers/__pycache__/checkpoint.cpython-310.pyc,,
15
+ xformers/__pycache__/info.cpython-310.pyc,,
16
+ xformers/__pycache__/test.cpython-310.pyc,,
17
+ xformers/__pycache__/utils.cpython-310.pyc,,
18
+ xformers/__pycache__/version.cpython-310.pyc,,
19
+ xformers/_cpp_lib.py,sha256=diLPbor1Tp80qZKvJLeoiYKYRfBf8UnsO2UbaMRuQLI,4958
20
+ xformers/_deprecation_warning.py,sha256=a2-JfNsT7EGLG5ZFarz7GTdnMe6EA3cli4BNfr3Wtog,456
21
+ xformers/_flash_attn/__init__.py,sha256=nsWkr1gPPxMV3ZfrC8Vcslhb7Z7ZHGsE--W46Od0luQ,285
22
+ xformers/_flash_attn/__pycache__/__init__.cpython-310.pyc,,
23
+ xformers/_flash_attn/__pycache__/bert_padding.cpython-310.pyc,,
24
+ xformers/_flash_attn/__pycache__/flash_attn_interface.cpython-310.pyc,,
25
+ xformers/_flash_attn/__pycache__/flash_attn_triton.cpython-310.pyc,,
26
+ xformers/_flash_attn/__pycache__/flash_attn_triton_og.cpython-310.pyc,,
27
+ xformers/_flash_attn/__pycache__/flash_blocksparse_attention.cpython-310.pyc,,
28
+ xformers/_flash_attn/__pycache__/flash_blocksparse_attn_interface.cpython-310.pyc,,
29
+ xformers/_flash_attn/__pycache__/fused_softmax.cpython-310.pyc,,
30
+ xformers/_flash_attn/bert_padding.py,sha256=MYMu_Dg9AcnM4-D56X0QGxp5WieqJ045RAvC4kPFI5w,9535
31
+ xformers/_flash_attn/flash_attn_interface.py,sha256=50ocGgMKfGorthN3M6fngQTlTb6x0H8G9KGJpV1JePM,47350
32
+ xformers/_flash_attn/flash_attn_triton.py,sha256=Du81zbh8Ls70ExEsm00opziGvjGFfcZCoZDUO2zut9Q,41112
33
+ xformers/_flash_attn/flash_attn_triton_og.py,sha256=LmvDju7LJG-wOYhoR6Zc2AmdPK2oWyB1VJpMjRhnWnE,11328
34
+ xformers/_flash_attn/flash_blocksparse_attention.py,sha256=aJlttNZVxVaktCNYAfP5AdqeZDu8jv42_ZbTkRnDkWg,7469
35
+ xformers/_flash_attn/flash_blocksparse_attn_interface.py,sha256=2qK2KvVCt851_j8ZzHvjS-aMfdgVDu1yne67-iScWfo,7265
36
+ xformers/_flash_attn/fused_softmax.py,sha256=0-XbXo7R1a5h4-EpUzPy--lwlGytfTDW34WGM5nmBAY,7793
37
+ xformers/_flash_attn/layers/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
38
+ xformers/_flash_attn/layers/__pycache__/__init__.cpython-310.pyc,,
39
+ xformers/_flash_attn/layers/__pycache__/patch_embed.cpython-310.pyc,,
40
+ xformers/_flash_attn/layers/__pycache__/rotary.cpython-310.pyc,,
41
+ xformers/_flash_attn/layers/patch_embed.py,sha256=H58CgME_qSOPTZLOG08wFgrQS1j34pvNwMPrkTj3Ek4,2136
42
+ xformers/_flash_attn/layers/rotary.py,sha256=RmDtuIpbFY-dqLATKwaPTjuVswcGJgL21_LvHwn2uw8,18874
43
+ xformers/_flash_attn/losses/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
44
+ xformers/_flash_attn/losses/__pycache__/__init__.cpython-310.pyc,,
45
+ xformers/_flash_attn/losses/__pycache__/cross_entropy.cpython-310.pyc,,
46
+ xformers/_flash_attn/losses/cross_entropy.py,sha256=tj5IoeUZuSzA1_82UFr7o-1WuoHyKAc1gVS6fWzAbDQ,3197
47
+ xformers/_flash_attn/models/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
48
+ xformers/_flash_attn/models/__pycache__/__init__.cpython-310.pyc,,
49
+ xformers/_flash_attn/models/__pycache__/baichuan.cpython-310.pyc,,
50
+ xformers/_flash_attn/models/__pycache__/bert.cpython-310.pyc,,
51
+ xformers/_flash_attn/models/__pycache__/bigcode.cpython-310.pyc,,
52
+ xformers/_flash_attn/models/__pycache__/btlm.cpython-310.pyc,,
53
+ xformers/_flash_attn/models/__pycache__/falcon.cpython-310.pyc,,
54
+ xformers/_flash_attn/models/__pycache__/gpt.cpython-310.pyc,,
55
+ xformers/_flash_attn/models/__pycache__/gpt_neox.cpython-310.pyc,,
56
+ xformers/_flash_attn/models/__pycache__/gptj.cpython-310.pyc,,
57
+ xformers/_flash_attn/models/__pycache__/llama.cpython-310.pyc,,
58
+ xformers/_flash_attn/models/__pycache__/opt.cpython-310.pyc,,
59
+ xformers/_flash_attn/models/__pycache__/vit.cpython-310.pyc,,
60
+ xformers/_flash_attn/models/baichuan.py,sha256=eFNWwoRQ02AIeQP0OoK8pNvYw0dqnHOshLigCQPkAEc,5730
61
+ xformers/_flash_attn/models/bert.py,sha256=-y6wVYzAfDqWWeO6n-dLapT1scn0lIsadKJKFzn48Vg,33241
62
+ xformers/_flash_attn/models/bigcode.py,sha256=mkYeItoJtmWVf2wKkUs5oXjwdbTdGSo5eHxi0-1maZ8,9383
63
+ xformers/_flash_attn/models/btlm.py,sha256=d8YDjYTa2G1DutYu-YuVf15S_Dn6oKn8-HzERoersLA,4631
64
+ xformers/_flash_attn/models/falcon.py,sha256=mA3wGv1a4zhbrUSlFNVVmTgVjiXc1sFTOi55eYpgSPo,6033
65
+ xformers/_flash_attn/models/gpt.py,sha256=QGBMCw_osxD4VMMj1uC6TMlXlM5lIInxSUKmq5J5kSU,47669
66
+ xformers/_flash_attn/models/gpt_neox.py,sha256=_704a9KQ2PcnID8uMV7yZ4ggjGlh1zZH5gszue6D1bI,5159
67
+ xformers/_flash_attn/models/gptj.py,sha256=k2eqMNyMbU7CJVM_BHBjlKt0ByFz6ITSETqS1mJa89g,4436
68
+ xformers/_flash_attn/models/llama.py,sha256=bDRI308iRpeJngZLrQlLTGYAmwYotqzUxnjBMirfn-k,16581
69
+ xformers/_flash_attn/models/opt.py,sha256=L0ZIWKpSP44lcEbiVCzVT9un_5gFMAW6cvnS3KHcb-A,5164
70
+ xformers/_flash_attn/models/vit.py,sha256=7i0WUI_jZvQ5TMoSKPPzf77ZcyMDfDJuQaINzXN_iQU,14074
71
+ xformers/_flash_attn/modules/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
72
+ xformers/_flash_attn/modules/__pycache__/__init__.cpython-310.pyc,,
73
+ xformers/_flash_attn/modules/__pycache__/block.cpython-310.pyc,,
74
+ xformers/_flash_attn/modules/__pycache__/embedding.cpython-310.pyc,,
75
+ xformers/_flash_attn/modules/__pycache__/mha.cpython-310.pyc,,
76
+ xformers/_flash_attn/modules/__pycache__/mlp.cpython-310.pyc,,
77
+ xformers/_flash_attn/modules/block.py,sha256=WLi7JKj9_Zpk89ppzC7WTIoykJJ7TLOJbUSZePNnW1E,17349
78
+ xformers/_flash_attn/modules/embedding.py,sha256=RCVeeiomlGNkLeQD8G6Udvex-NDI_xKD45hXjgZ2lbQ,8693
79
+ xformers/_flash_attn/modules/mha.py,sha256=V6Ynog9pb_G9UVxetRjXlmWGExZlxmJkYVwAExXqUEk,43297
80
+ xformers/_flash_attn/modules/mlp.py,sha256=G6KPQagfKq1DRn7hQRJ3OHznFJLZHj_PiidZE_zcLgg,6033
81
+ xformers/_flash_attn/ops/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
82
+ xformers/_flash_attn/ops/__pycache__/__init__.cpython-310.pyc,,
83
+ xformers/_flash_attn/ops/__pycache__/activations.cpython-310.pyc,,
84
+ xformers/_flash_attn/ops/__pycache__/fused_dense.cpython-310.pyc,,
85
+ xformers/_flash_attn/ops/__pycache__/layer_norm.cpython-310.pyc,,
86
+ xformers/_flash_attn/ops/__pycache__/rms_norm.cpython-310.pyc,,
87
+ xformers/_flash_attn/ops/activations.py,sha256=4f9iruZ2SKJSmOlNQ9L3t5EpQ2tKJVlyy-iBBF6sMgs,3936
88
+ xformers/_flash_attn/ops/fused_dense.py,sha256=ACJKqkIfxZibxI3nb5ycb3pXBKaL_CM63rUUyQYNAUE,27907
89
+ xformers/_flash_attn/ops/layer_norm.py,sha256=zr7NXIm-2mtEynTp1CS0fbFGI2Mqdp41dY4AfDWF6EQ,22443
90
+ xformers/_flash_attn/ops/rms_norm.py,sha256=XEnihcj0a4aSz4LO55m5iKGVn4HKTeKN8TIyHjuDgxI,3988
91
+ xformers/_flash_attn/ops/triton/__init__.py,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1
92
+ xformers/_flash_attn/ops/triton/__pycache__/__init__.cpython-310.pyc,,
93
+ xformers/_flash_attn/ops/triton/__pycache__/cross_entropy.cpython-310.pyc,,
94
+ xformers/_flash_attn/ops/triton/__pycache__/k_activations.cpython-310.pyc,,
95
+ xformers/_flash_attn/ops/triton/__pycache__/layer_norm.cpython-310.pyc,,
96
+ xformers/_flash_attn/ops/triton/__pycache__/linear.cpython-310.pyc,,
97
+ xformers/_flash_attn/ops/triton/__pycache__/mlp.cpython-310.pyc,,
98
+ xformers/_flash_attn/ops/triton/__pycache__/rotary.cpython-310.pyc,,
99
+ xformers/_flash_attn/ops/triton/cross_entropy.py,sha256=H2BMSRhivo-BW3uVFmvJD6WhivARqHDe9WbxgMJVqnQ,12454
100
+ xformers/_flash_attn/ops/triton/k_activations.py,sha256=-Z3vIyO4JkqBMipKsPvhzmxljtBdIhJCsl_M-_ESqBo,4034
101
+ xformers/_flash_attn/ops/triton/layer_norm.py,sha256=rNJwuijsZ6sKDtKHlkbT0qDzbi6vetVjjibpy9YRHFQ,35715
102
+ xformers/_flash_attn/ops/triton/linear.py,sha256=OtRvKz8xdpl-7v3q_ZTaS9fdBt9XrzMyapgRr50uBbM,20841
103
+ xformers/_flash_attn/ops/triton/mlp.py,sha256=_5lbZJFZg_pXeXYITGt4V_6LkB_yddClB_jt-diCOdw,6068
104
+ xformers/_flash_attn/ops/triton/rotary.py,sha256=-uMWkh2DhbhZYRY2PeMWZ8x3lDbuYp0ljsgHYYP3NYk,8582
105
+ xformers/_flash_attn/utils/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
106
+ xformers/_flash_attn/utils/__pycache__/__init__.cpython-310.pyc,,
107
+ xformers/_flash_attn/utils/__pycache__/benchmark.cpython-310.pyc,,
108
+ xformers/_flash_attn/utils/__pycache__/distributed.cpython-310.pyc,,
109
+ xformers/_flash_attn/utils/__pycache__/generation.cpython-310.pyc,,
110
+ xformers/_flash_attn/utils/__pycache__/pretrained.cpython-310.pyc,,
111
+ xformers/_flash_attn/utils/benchmark.py,sha256=JDtzdVhFyMIQqs3edbcXdXnmDf-O7RVpmZmn2ZFCvI0,7369
112
+ xformers/_flash_attn/utils/distributed.py,sha256=qhcybRXtslssuV9LYaQy37haPaPtklM4YUMDx9UvnnQ,5825
113
+ xformers/_flash_attn/utils/generation.py,sha256=9IVPvkf_hlbsxCWgECUA03293qHxXzWDFCTAOdqbAVo,30694
114
+ xformers/_flash_attn/utils/pretrained.py,sha256=VZ6qk90sBJA7M86gRzPsNc_CkQXkj5HyrJvwl0I355k,3246
115
+ xformers/attn_bias_utils.py,sha256=2MD_FqAf7Xci5W7jbeu6E3IYxqj0-4q6aWSXA_qzhko,19178
116
+ xformers/benchmarks/LRA/__init__.py,sha256=BBoPvMfJjZ0Fi25JCRS8sPYUfLbHneLncV3JeGDIGHg,198
117
+ xformers/benchmarks/LRA/__pycache__/__init__.cpython-310.pyc,,
118
+ xformers/benchmarks/LRA/__pycache__/batch_fetch_results.cpython-310.pyc,,
119
+ xformers/benchmarks/LRA/__pycache__/batch_submit.cpython-310.pyc,,
120
+ xformers/benchmarks/LRA/__pycache__/run_grid_search.cpython-310.pyc,,
121
+ xformers/benchmarks/LRA/__pycache__/run_tasks.cpython-310.pyc,,
122
+ xformers/benchmarks/LRA/__pycache__/run_with_submitit.cpython-310.pyc,,
123
+ xformers/benchmarks/LRA/batch_fetch_results.py,sha256=QsTgzFU45VP636TPiewnVCKD57bOR_YkjZq2KjMLzqc,3508
124
+ xformers/benchmarks/LRA/batch_submit.py,sha256=7BgzEgSCJNN4vaQ8m-hEY2x5DxSkaPzp_Jorr2fS5p4,1685
125
+ xformers/benchmarks/LRA/code/__init__.py,sha256=BBoPvMfJjZ0Fi25JCRS8sPYUfLbHneLncV3JeGDIGHg,198
126
+ xformers/benchmarks/LRA/code/__pycache__/__init__.cpython-310.pyc,,
127
+ xformers/benchmarks/LRA/code/__pycache__/dataset.cpython-310.pyc,,
128
+ xformers/benchmarks/LRA/code/__pycache__/model_wrapper.cpython-310.pyc,,
129
+ xformers/benchmarks/LRA/code/dataset.py,sha256=6iMOhcM8rY75Ub_t3fopBxGjo1zCWwSIRAC3eHqAsIs,1403
130
+ xformers/benchmarks/LRA/code/model_wrapper.py,sha256=18YKbVAASeoaGZqhM-Ps3scvblLbVoImHWKJqY7CQjw,9777
131
+ xformers/benchmarks/LRA/run_grid_search.py,sha256=yLhNnQv4HDbEdQVApCdJiZzFes9VeGZjPOafHAaZ5Ew,5327
132
+ xformers/benchmarks/LRA/run_tasks.py,sha256=GZP6cUgE1ftpQrp2IOf-MWbYJFcokt9bsLA8Q6PNyIU,9294
133
+ xformers/benchmarks/LRA/run_with_submitit.py,sha256=WUtQJLYWnVVcp6mbmBQuqiA3pdvayEpZzqEpW5FZRz0,4612
134
+ xformers/benchmarks/__init__.py,sha256=BBoPvMfJjZ0Fi25JCRS8sPYUfLbHneLncV3JeGDIGHg,198
135
+ xformers/benchmarks/__pycache__/__init__.cpython-310.pyc,,
136
+ xformers/benchmarks/__pycache__/benchmark_attn_decoding.cpython-310.pyc,,
137
+ xformers/benchmarks/__pycache__/benchmark_core.cpython-310.pyc,,
138
+ xformers/benchmarks/__pycache__/benchmark_indexing.cpython-310.pyc,,
139
+ xformers/benchmarks/__pycache__/benchmark_mem_eff_attention.cpython-310.pyc,,
140
+ xformers/benchmarks/__pycache__/benchmark_merge_attentions.cpython-310.pyc,,
141
+ xformers/benchmarks/__pycache__/benchmark_multi_head_dispatch.cpython-310.pyc,,
142
+ xformers/benchmarks/__pycache__/benchmark_nystrom_utils.cpython-310.pyc,,
143
+ xformers/benchmarks/__pycache__/benchmark_revnet.cpython-310.pyc,,
144
+ xformers/benchmarks/__pycache__/benchmark_sddmm.cpython-310.pyc,,
145
+ xformers/benchmarks/__pycache__/benchmark_sequence_parallel_fused.cpython-310.pyc,,
146
+ xformers/benchmarks/__pycache__/benchmark_sp24.cpython-310.pyc,,
147
+ xformers/benchmarks/__pycache__/benchmark_swiglu.cpython-310.pyc,,
148
+ xformers/benchmarks/__pycache__/benchmark_tiled_matmul.cpython-310.pyc,,
149
+ xformers/benchmarks/__pycache__/utils.cpython-310.pyc,,
150
+ xformers/benchmarks/benchmark_attn_decoding.py,sha256=Jp45OCalf0Wfk8WZ1y8NBqyccup9lSnFs9R1Oq6Gjqg,12368
151
+ xformers/benchmarks/benchmark_core.py,sha256=83x0wl7ouGqRgECQiRE3kzTXQwXHP3uWpQHvqxJWBlw,8626
152
+ xformers/benchmarks/benchmark_indexing.py,sha256=W55qQHBuwlEp98X3XzoCrlHQg7NF00b9gc52_qDzhSE,5288
153
+ xformers/benchmarks/benchmark_mem_eff_attention.py,sha256=HG8mfTCy1oFOsnOOQZ8zOGrOWotRTFU0fVJ4d4_xn0M,10101
154
+ xformers/benchmarks/benchmark_merge_attentions.py,sha256=_6iSEhJGoeljSrVbOdi-tncYHPQNE7lj1wrTQlubSLo,3042
155
+ xformers/benchmarks/benchmark_multi_head_dispatch.py,sha256=1ZAnVLx9rIRzRxgOx50tSdGZSHveH-n4aTU7wjJnlUc,3365
156
+ xformers/benchmarks/benchmark_nystrom_utils.py,sha256=mUML4twJT1LCoCwtvS_3isfcHDS4XTH18leB_kix-OY,3230
157
+ xformers/benchmarks/benchmark_revnet.py,sha256=qG7SxXpoJ-bi5cajWukyft7qVprmVfqqtx9PRQqIdI8,2671
158
+ xformers/benchmarks/benchmark_sddmm.py,sha256=Tvq1rgXpeaj7kGjCKn_6pX2QA7TOt_aNG-nLCYa9_Eo,3765
159
+ xformers/benchmarks/benchmark_sequence_parallel_fused.py,sha256=-Ob3G3c0xTJs--bw5yZQ203UqY1maOtKM3K5ZCDB6tw,14454
160
+ xformers/benchmarks/benchmark_sp24.py,sha256=xcp-cR8t7U5WGfvbDoZeDUoTLXD-w7vVQerfd2kybVw,4861
161
+ xformers/benchmarks/benchmark_swiglu.py,sha256=UD6tmg4JaPYct6KLwqnE_7UsFewKY_GpgV8XZMa1hFM,4295
162
+ xformers/benchmarks/benchmark_tiled_matmul.py,sha256=lo_y3IA-8a6cgcMv5w2bJjU_FQBcMFsmllUEod4hISw,3779
163
+ xformers/benchmarks/utils.py,sha256=MsKzrEjOWbNEi3UMSN8nRSEXkheC5_Ho27J3ysg8r6A,24202
164
+ xformers/checkpoint.py,sha256=PUYtKs1QE-3ZKoBfWhIT-aFHMD_uYJq4ZBNePE-Ug6o,20337
165
+ xformers/components/__init__.py,sha256=vu5FoGbeQpZbcgBdQ0m8mtsmWfBv7TVAe6oynsk7JXs,3377
166
+ xformers/components/__pycache__/__init__.cpython-310.pyc,,
167
+ xformers/components/__pycache__/activations.cpython-310.pyc,,
168
+ xformers/components/__pycache__/input_projection.cpython-310.pyc,,
169
+ xformers/components/__pycache__/multi_head_dispatch.cpython-310.pyc,,
170
+ xformers/components/__pycache__/patch_embedding.cpython-310.pyc,,
171
+ xformers/components/__pycache__/residual.cpython-310.pyc,,
172
+ xformers/components/__pycache__/reversible.cpython-310.pyc,,
173
+ xformers/components/__pycache__/simplicial_embedding.cpython-310.pyc,,
174
+ xformers/components/activations.py,sha256=_IZvFRgrwJsjZy4z-qbnjDl8P1PM4MOp3k00OvaO5b8,2002
175
+ xformers/components/attention/__init__.py,sha256=DHcMUQ13ANJAL1sClBXu0f-wJOAprJeMByQBYG4NYJ0,3802
176
+ xformers/components/attention/__pycache__/__init__.cpython-310.pyc,,
177
+ xformers/components/attention/__pycache__/_sputnik_sparse.cpython-310.pyc,,
178
+ xformers/components/attention/__pycache__/attention_mask.cpython-310.pyc,,
179
+ xformers/components/attention/__pycache__/attention_patterns.cpython-310.pyc,,
180
+ xformers/components/attention/__pycache__/base.cpython-310.pyc,,
181
+ xformers/components/attention/__pycache__/compositional.cpython-310.pyc,,
182
+ xformers/components/attention/__pycache__/core.cpython-310.pyc,,
183
+ xformers/components/attention/__pycache__/favor.cpython-310.pyc,,
184
+ xformers/components/attention/__pycache__/fourier_mix.cpython-310.pyc,,
185
+ xformers/components/attention/__pycache__/global_tokens.cpython-310.pyc,,
186
+ xformers/components/attention/__pycache__/lambda_layer.cpython-310.pyc,,
187
+ xformers/components/attention/__pycache__/linformer.cpython-310.pyc,,
188
+ xformers/components/attention/__pycache__/local.cpython-310.pyc,,
189
+ xformers/components/attention/__pycache__/nystrom.cpython-310.pyc,,
190
+ xformers/components/attention/__pycache__/ortho.cpython-310.pyc,,
191
+ xformers/components/attention/__pycache__/pooling.cpython-310.pyc,,
192
+ xformers/components/attention/__pycache__/random.cpython-310.pyc,,
193
+ xformers/components/attention/__pycache__/scaled_dot_product.cpython-310.pyc,,
194
+ xformers/components/attention/__pycache__/sparsity_config.cpython-310.pyc,,
195
+ xformers/components/attention/__pycache__/utils.cpython-310.pyc,,
196
+ xformers/components/attention/__pycache__/visual.cpython-310.pyc,,
197
+ xformers/components/attention/_sputnik_sparse.py,sha256=bibk2S-Coatt45gO9fzLTaAgUMKXbRi5U0eR_-QAbnw,3164
198
+ xformers/components/attention/attention_mask.py,sha256=Y0zyM5JDnFzfE0TGPx4BxEeQlqIPX-XnZpO_lskQn4w,4585
199
+ xformers/components/attention/attention_patterns.py,sha256=mZ-s8R-DS6XrOP_-ExZZku7XWVKUOEVfUdHpB9D5kek,9945
200
+ xformers/components/attention/base.py,sha256=X8qmru_ln4eSac68rnYZzfAF3pbQDz5l6UxfRE-pR6Y,3305
201
+ xformers/components/attention/compositional.py,sha256=H1prPE_o3Ymd_HbxBnjNWnz7vzYzA_9L5zgixpyWAlM,12954
202
+ xformers/components/attention/core.py,sha256=1VvBVYQEhjfIroVpoTBbJ6W4cEjPIXOCJzWltnXQekE,7625
203
+ xformers/components/attention/favor.py,sha256=55z-Hjv23fjwEGsRg8Qtyq7yX57C7Uz5czgIS19vLA4,6194
204
+ xformers/components/attention/feature_maps/__init__.py,sha256=YT-iC15A-WTj9uy6etXp6tWNBDo3tolDjGDc-DYmzvA,592
205
+ xformers/components/attention/feature_maps/__pycache__/__init__.cpython-310.pyc,,
206
+ xformers/components/attention/feature_maps/__pycache__/base.cpython-310.pyc,,
207
+ xformers/components/attention/feature_maps/__pycache__/softmax.cpython-310.pyc,,
208
+ xformers/components/attention/feature_maps/base.py,sha256=u4jzwUZludL_mFLYL6SzGFUFJGKkbHWYKE9iO5BzFzA,1672
209
+ xformers/components/attention/feature_maps/softmax.py,sha256=tpI2yz8wk1fC1mv9zCHQpvc54ozSQTGJVBA37pvufqE,10606
210
+ xformers/components/attention/fourier_mix.py,sha256=AKMjFgmSBomER9A8c9mbuERjnLR9KAcMafawRJ0eCko,1184
211
+ xformers/components/attention/global_tokens.py,sha256=JkN_jrNesrgjd6G_JzFdokGZLEYKDTnYHHc5IOmzYAw,4091
212
+ xformers/components/attention/lambda_layer.py,sha256=a15tl5a9VMi1NaKCrEps2-Tb46RaA0R_M6L8zAA0YiI,2814
213
+ xformers/components/attention/linformer.py,sha256=U-lqxbOdbx3CXnX7swpUvYaZXKJUNrGxJT4_jiyNH1c,2491
214
+ xformers/components/attention/local.py,sha256=MDUq0UDzP4NpUxJZ5gOtPeLT0bRcE6vsA3iMnylqg7g,3815
215
+ xformers/components/attention/nystrom.py,sha256=Za5veGImsv9j-rnA0fAHd61TGyNnfdY6I1O4AKWgje0,11405
216
+ xformers/components/attention/ortho.py,sha256=2FWSaeqZ5m3QdyL_-BYZtNNXSL4xQVo9LXLN0si7bOQ,12124
217
+ xformers/components/attention/pooling.py,sha256=-KGQxK9gSPxILByF_OsEaQfJqLr9GwbwjcgbYXDmOwM,2490
218
+ xformers/components/attention/random.py,sha256=0bcvaYreWLNeW3bA3fvuJXIZINxXW0hqw4hsFauQ--M,4131
219
+ xformers/components/attention/scaled_dot_product.py,sha256=vUcRVzQT3ol6hIqrTcCudlaCru1W1ZcZgjaTIkl7Lr4,4504
220
+ xformers/components/attention/sparsity_config.py,sha256=lZLGeKVcqnKVGKqkjE5Av2yGIHB5zZvU9IwrR3UrvZo,41608
221
+ xformers/components/attention/utils.py,sha256=04aEVvDG9LjzD9NfsQ3Kj-kZSnMFCppCFrJx6NPoV8g,3803
222
+ xformers/components/attention/visual.py,sha256=EiMRHtf10q7EnwQF_gKdXCp-BsMHj0yHeDCC6SKFx2Q,2929
223
+ xformers/components/feedforward/__init__.py,sha256=rfrm9w6hHacyANVqlHpQj4NF5tZJUcmMWMvSbQMoT1g,2367
224
+ xformers/components/feedforward/__pycache__/__init__.cpython-310.pyc,,
225
+ xformers/components/feedforward/__pycache__/base.cpython-310.pyc,,
226
+ xformers/components/feedforward/__pycache__/conv_mlp.cpython-310.pyc,,
227
+ xformers/components/feedforward/__pycache__/mixture_of_experts.cpython-310.pyc,,
228
+ xformers/components/feedforward/__pycache__/mlp.cpython-310.pyc,,
229
+ xformers/components/feedforward/base.py,sha256=YUgACRbibSrQom02k4JW5hoPgkhxJD6F40PKF5UWLaw,1594
230
+ xformers/components/feedforward/conv_mlp.py,sha256=iZwK8xy8FN9KhqXde8WcbNitoEDA4ertlYo6E1ua6cE,3011
231
+ xformers/components/feedforward/mixture_of_experts.py,sha256=Zci7y55TvQRGpmARVzsj7db8Y-xs1NVPioXP3nEkhr0,5343
232
+ xformers/components/feedforward/mlp.py,sha256=u5z2uYfgyddrz4o-xdylqyNo8onRg34CGacRGtkCsAQ,1308
233
+ xformers/components/input_projection.py,sha256=7oH2EfhMsujvjpXxIHzg5A3gT5xA0vJ2trb2-pZoh3g,3121
234
+ xformers/components/multi_head_dispatch.py,sha256=53-Wl6AgY8h8uf6LjGl1TOw85G7ChKec1qWa6017ePU,10265
235
+ xformers/components/patch_embedding.py,sha256=GpoaIBbVJ3ANUIOtTsHOHcjKXxekmg7ZCQqSNqbeezI,2400
236
+ xformers/components/positional_embedding/__init__.py,sha256=sN-9Mk3SeY8snW70vqSedHYqmAwzi5hZjcOfHFNPJos,2755
237
+ xformers/components/positional_embedding/__pycache__/__init__.cpython-310.pyc,,
238
+ xformers/components/positional_embedding/__pycache__/base.cpython-310.pyc,,
239
+ xformers/components/positional_embedding/__pycache__/param.cpython-310.pyc,,
240
+ xformers/components/positional_embedding/__pycache__/rotary.cpython-310.pyc,,
241
+ xformers/components/positional_embedding/__pycache__/sine.cpython-310.pyc,,
242
+ xformers/components/positional_embedding/__pycache__/vocab.cpython-310.pyc,,
243
+ xformers/components/positional_embedding/base.py,sha256=R9dgW6lgfqc_JKZwWSLKc6_NhOGAOPDKh4NvYhIbCDE,1069
244
+ xformers/components/positional_embedding/param.py,sha256=mvvt_ZKrFL9ZogeuXO8RxFlKGIiaLBF1YE-XcwiZRfg,1544
245
+ xformers/components/positional_embedding/rotary.py,sha256=_mYWMVhwNUdl62aMfrTOfY2W8P8fjqjXLcbrwB-aLEo,3274
246
+ xformers/components/positional_embedding/sine.py,sha256=kOeakSCWG4KcI05C5Qouh9fpBHIunEI_-8EGDD-U_g8,1365
247
+ xformers/components/positional_embedding/vocab.py,sha256=T-kvJyuU5HpB98_zuLUm2NLfhYsjW8zNnTCUqXhKi_4,1768
248
+ xformers/components/residual.py,sha256=jTAnAytB9dZoXv-xEw9NBL2NnSqo3C68q9jlOpfS04I,5693
249
+ xformers/components/reversible.py,sha256=JiqaElzMv-c16fbA2SJYCrj8LpjXgg1N8l9Uwtmfmuo,5390
250
+ xformers/components/simplicial_embedding.py,sha256=qNWz-ZW7yVYhWNOcpmIuhbN8Vtz95IQAClHXNsDYTNM,2118
251
+ xformers/cpp_lib.json,sha256=qWyhHc8R86em2g6SMnFyWU1keXCjhZ8QiIXt2n4OSsA,402
252
+ xformers/factory/__init__.py,sha256=4DY_EmTQiTJLO1Ttk8H7cVNx92e6ZuFm8kW9E5Xod0A,617
253
+ xformers/factory/__pycache__/__init__.cpython-310.pyc,,
254
+ xformers/factory/__pycache__/block_configs.cpython-310.pyc,,
255
+ xformers/factory/__pycache__/block_factory.cpython-310.pyc,,
256
+ xformers/factory/__pycache__/hydra_helper.cpython-310.pyc,,
257
+ xformers/factory/__pycache__/model_factory.cpython-310.pyc,,
258
+ xformers/factory/__pycache__/weight_init.cpython-310.pyc,,
259
+ xformers/factory/block_configs.py,sha256=Cy_lI_lDp8yfqnRxLrNpszGU1UzUljuw-1bIdNEgEpY,8175
260
+ xformers/factory/block_factory.py,sha256=i6VSVQoku9qShZmdosawlLFyKCrrYEmP81ujGP9Fflc,12960
261
+ xformers/factory/hydra_helper.py,sha256=5bP3myNgAai_J_Se69wVSkE1C5HGE2HZU_TW2xstgCA,1312
262
+ xformers/factory/model_factory.py,sha256=F3qk8ZO-n0XLD8cPU6iRjvXik9IspoiCOrXr3N2wVos,11899
263
+ xformers/factory/weight_init.py,sha256=DUZBhDIbkbtdk4GYzqp-Xu-yXjvWFueD3fOx4OhvqTE,9988
264
+ xformers/helpers/__init__.py,sha256=3zcfxEo1NykSJOddz1xp2I_ftiTsyaT0xPe-zpRZP3c,263
265
+ xformers/helpers/__pycache__/__init__.cpython-310.pyc,,
266
+ xformers/helpers/__pycache__/hierarchical_configs.cpython-310.pyc,,
267
+ xformers/helpers/__pycache__/test_utils.cpython-310.pyc,,
268
+ xformers/helpers/__pycache__/timm_sparse_attention.cpython-310.pyc,,
269
+ xformers/helpers/hierarchical_configs.py,sha256=sWNlYaxOI905dszrRlD8NNoj-gvXgtQWpygMyeZKsYM,3924
270
+ xformers/helpers/test_utils.py,sha256=OMD0494dmlWHmU-xH-l7ssRimZkufofxrbeZj0qsly0,800
271
+ xformers/helpers/timm_sparse_attention.py,sha256=E22N74lKwmAkwRX1SI4SZEpvxgBN1ZeJIYoVLvHnmro,1528
272
+ xformers/info.py,sha256=EzzBOTz7vp1OUPDlFT5yBSs3ItqAzMhfK975bv-A2FM,2672
273
+ xformers/ops/__init__.py,sha256=X7_uUyc_zxCAQplQBHG1Agb2Kh-qf8Tj67djP2dxddU,3501
274
+ xformers/ops/__pycache__/__init__.cpython-310.pyc,,
275
+ xformers/ops/__pycache__/common.cpython-310.pyc,,
276
+ xformers/ops/__pycache__/differentiable_collectives.cpython-310.pyc,,
277
+ xformers/ops/__pycache__/indexing.cpython-310.pyc,,
278
+ xformers/ops/__pycache__/ipc.cpython-310.pyc,,
279
+ xformers/ops/__pycache__/modpar_layers.cpython-310.pyc,,
280
+ xformers/ops/__pycache__/rmsnorm.cpython-310.pyc,,
281
+ xformers/ops/__pycache__/rope_padded.cpython-310.pyc,,
282
+ xformers/ops/__pycache__/seqpar.cpython-310.pyc,,
283
+ xformers/ops/__pycache__/sequence_parallel_fused_ops.cpython-310.pyc,,
284
+ xformers/ops/__pycache__/sp24.cpython-310.pyc,,
285
+ xformers/ops/__pycache__/swiglu_op.cpython-310.pyc,,
286
+ xformers/ops/__pycache__/tiled_matmul.cpython-310.pyc,,
287
+ xformers/ops/__pycache__/unbind.cpython-310.pyc,,
288
+ xformers/ops/_triton/__init__.py,sha256=G7u-HQ1NEf-mlR3LN5qupDMVCHHA94H1S_aXoStfKOI,741
289
+ xformers/ops/_triton/__pycache__/__init__.cpython-310.pyc,,
290
+ xformers/ops/_triton/__pycache__/k_index_select_cat.cpython-310.pyc,,
291
+ xformers/ops/_triton/__pycache__/k_scaled_index_add.cpython-310.pyc,,
292
+ xformers/ops/_triton/__pycache__/rmsnorm_kernels.cpython-310.pyc,,
293
+ xformers/ops/_triton/__pycache__/rope_padded_kernels.cpython-310.pyc,,
294
+ xformers/ops/_triton/__pycache__/tiled_matmul_kernels.cpython-310.pyc,,
295
+ xformers/ops/_triton/k_index_select_cat.py,sha256=_gFAuuUbKd_CH0Awkc_sspxE0lmd4Y-gLndLu3G3brA,6194
296
+ xformers/ops/_triton/k_scaled_index_add.py,sha256=KCEgK-9s_A1jdEVvBn84GlA4py7ZBrQSuxWyYaJG_jc,12802
297
+ xformers/ops/_triton/rmsnorm_kernels.py,sha256=5Q8hW66p_vmKyDWiGKpO5OLMdl5T8BD1JzrGgLa_vHs,5254
298
+ xformers/ops/_triton/rope_padded_kernels.py,sha256=4eto-GxPRBJDK9Bu_iuXaBh1jZ0wqOQANT8WKlRlH9s,7350
299
+ xformers/ops/_triton/tiled_matmul_kernels.py,sha256=kPgBpMf8uz52eaP4-WoR82Wv5NK2GM4qdV2Rjf52DTk,13808
300
+ xformers/ops/common.py,sha256=bgeQP7DxTkWhj_xiM-GUZ7QBoxRzg-VY3NfEOns5hhs,1911
301
+ xformers/ops/differentiable_collectives.py,sha256=moSee9BpQDlfXgEq_P3IqxYcF9NjJGi8jbge_cJ9yGI,5356
302
+ xformers/ops/fmha/__init__.py,sha256=68Igupx4OHt73ZRjykX7fnqBjR8ezimcKclpmB_CfWI,30478
303
+ xformers/ops/fmha/__pycache__/__init__.cpython-310.pyc,,
304
+ xformers/ops/fmha/__pycache__/attn_bias.cpython-310.pyc,,
305
+ xformers/ops/fmha/__pycache__/ck.cpython-310.pyc,,
306
+ xformers/ops/fmha/__pycache__/ck_decoder.cpython-310.pyc,,
307
+ xformers/ops/fmha/__pycache__/ck_splitk.cpython-310.pyc,,
308
+ xformers/ops/fmha/__pycache__/common.cpython-310.pyc,,
309
+ xformers/ops/fmha/__pycache__/cutlass.cpython-310.pyc,,
310
+ xformers/ops/fmha/__pycache__/dispatch.cpython-310.pyc,,
311
+ xformers/ops/fmha/__pycache__/flash.cpython-310.pyc,,
312
+ xformers/ops/fmha/__pycache__/flash3.cpython-310.pyc,,
313
+ xformers/ops/fmha/__pycache__/torch_attention_compat.cpython-310.pyc,,
314
+ xformers/ops/fmha/__pycache__/triton_splitk.cpython-310.pyc,,
315
+ xformers/ops/fmha/_triton/__init__.py,sha256=BBoPvMfJjZ0Fi25JCRS8sPYUfLbHneLncV3JeGDIGHg,198
316
+ xformers/ops/fmha/_triton/__pycache__/__init__.cpython-310.pyc,,
317
+ xformers/ops/fmha/_triton/__pycache__/splitk_kernels.cpython-310.pyc,,
318
+ xformers/ops/fmha/_triton/splitk_kernels.py,sha256=-xRJc2px_DXrkLekPeDIgcekKDqkY_eET2p1tzw3KeA,40672
319
+ xformers/ops/fmha/attn_bias.py,sha256=8y1qek-riIuV-Ek78EMSMDaaDjQokxDCW1n0UzdFNMI,60332
320
+ xformers/ops/fmha/ck.py,sha256=UMspvNjMdgWEG86_kuwAh3yXbMqN63Oj7JzxXplgTtI,17057
321
+ xformers/ops/fmha/ck_decoder.py,sha256=3Lm0DA4TYgBu7KmlKEntnaDSL21iv__d3-z-BH5RAB4,5092
322
+ xformers/ops/fmha/ck_splitk.py,sha256=4_kVxgiKM0YBUsQaWV071I6y4kDNmNore47rAZ_i-oc,6411
323
+ xformers/ops/fmha/common.py,sha256=pw-pcpErmjfHJxL6LgxLm2hWTtn6UbVkvD4JrTia9MI,18579
324
+ xformers/ops/fmha/cutlass.py,sha256=7QrJuAY1YlzEX__nH4B7lLwCMwCBs11Ykb0pnESiYyI,17611
325
+ xformers/ops/fmha/dispatch.py,sha256=BpkB5kFQkqjEZ_93olV5FMn2SRfH5Cl_UT4rKix9KP4,6334
326
+ xformers/ops/fmha/flash.py,sha256=1TCe6z89MDsf7LLUrnIps9XR1g-NgDTol19Hh6e4zsI,28942
327
+ xformers/ops/fmha/flash3.py,sha256=JNLwxQgCXtkVuZ0zrmJM4itPPLitmmaaAyQTAxMT8a4,13492
328
+ xformers/ops/fmha/torch_attention_compat.py,sha256=ifY6vGyzG2oQtCkAr276Wm8Y9U3gEGsoSvfBYZ3WK5w,5594
329
+ xformers/ops/fmha/triton_splitk.py,sha256=8bqMisrKRfncHFr8WkNRigQuSu-oFtGup9ru2fG5Orw,36605
330
+ xformers/ops/indexing.py,sha256=uQDU1rqgh-huDvOdtMekgSQSMXVndrC0n3vn8CFHNrI,6927
331
+ xformers/ops/ipc.py,sha256=Q5YRa5G1LrAbm8syGZiSBzPvMqQEvR-gqML6t_18G-0,6649
332
+ xformers/ops/modpar_layers.py,sha256=gOg2cAn3G-xhp1bQTM33dA1adQc5bmZp6v-jF4bh_sM,5703
333
+ xformers/ops/rmsnorm.py,sha256=ofNCqraOJZBt_z1WoTMuW5HgfCr2wpJ_zkL_b0e-n2s,3358
334
+ xformers/ops/rope_padded.py,sha256=bI6JCNHO0Rggp9oYW23KV4ONsoPqk4tGT3EGejqRZvY,12100
335
+ xformers/ops/seqpar.py,sha256=dTNVh1DPAYJeOP-dmopGEuulQQ9WjLvo7BU0B7Y8zcU,12063
336
+ xformers/ops/sequence_parallel_fused_ops.py,sha256=UVaJf0onPork4jw5LAVqa0-h-jryu0jpLdwevhQuSog,36973
337
+ xformers/ops/sp24.py,sha256=6UNvf_85rVxpRKEe6NMqXRA49tnG97Bbw9SPXi3G27k,27950
338
+ xformers/ops/swiglu_op.py,sha256=xD_XCCgipIwdmzaljY5BtoAcokSIyYX2cjEgjG8LdRg,17456
339
+ xformers/ops/tiled_matmul.py,sha256=mzGdPYDKIBwgwitOOo0R6ld_Q5wtm4mHawElx3bMPqY,12792
340
+ xformers/ops/unbind.py,sha256=KWEif28duVWbzj14bL-O3jJTxMuTZPvuGqCkZQhsgYQ,3925
341
+ xformers/profiler/__init__.py,sha256=4jTj_MGJ-HkCkHwkx6QneBm27dMMPxvNa6kLwro86bk,421
342
+ xformers/profiler/__pycache__/__init__.cpython-310.pyc,,
343
+ xformers/profiler/__pycache__/api.cpython-310.pyc,,
344
+ xformers/profiler/__pycache__/device_limits.cpython-310.pyc,,
345
+ xformers/profiler/__pycache__/find_slowest.cpython-310.pyc,,
346
+ xformers/profiler/__pycache__/profile_analyzer.cpython-310.pyc,,
347
+ xformers/profiler/__pycache__/profiler.cpython-310.pyc,,
348
+ xformers/profiler/__pycache__/profiler_dcgm.cpython-310.pyc,,
349
+ xformers/profiler/__pycache__/profiler_dcgm_impl.cpython-310.pyc,,
350
+ xformers/profiler/api.py,sha256=t-Cp6VqSEBk7Nm0zChnpJSIAKCMuY7VoYn9mySna7xQ,2685
351
+ xformers/profiler/device_limits.py,sha256=HzPTO6bHMk7HxHelSh3A0Bk8qyuxL3-SsFYGBXdjT6c,3588
352
+ xformers/profiler/find_slowest.py,sha256=DFHw8ybAb1eqXWjYqs5U1ZQ48CoIIqbjC8RoX2QGI_Y,6004
353
+ xformers/profiler/profile_analyzer.py,sha256=v1TKzsE9lm5kkFoCLCXbmc3XMSG_7QD_J3QbeqmyYLc,8717
354
+ xformers/profiler/profiler.py,sha256=sD_9eoeKttMBVfqhODw5LIzp4MYFNx8t7xC4qp5hAYw,12756
355
+ xformers/profiler/profiler_dcgm.py,sha256=1NWMET7oVtUoBYhEFoQ-F17s1B8xmqcrL3Hjddry-H0,1153
356
+ xformers/profiler/profiler_dcgm_impl.py,sha256=umLRJQCYOIyYHwFsyXDk9eNmbs4DUmuvAwe6tUahN6k,8472
357
+ xformers/sparse/__init__.py,sha256=NpDMLawDg0ra3mR7LpNnkua8KOpeY6h2AL4or88rGws,317
358
+ xformers/sparse/__pycache__/__init__.cpython-310.pyc,,
359
+ xformers/sparse/__pycache__/_csr_ops.cpython-310.pyc,,
360
+ xformers/sparse/__pycache__/blocksparse_tensor.cpython-310.pyc,,
361
+ xformers/sparse/__pycache__/csr_tensor.cpython-310.pyc,,
362
+ xformers/sparse/__pycache__/utils.cpython-310.pyc,,
363
+ xformers/sparse/_csr_ops.py,sha256=p8bGD91Y52LuYieY97ZCtlOpYFNnnPRjXDuBoK5_Bp0,4873
364
+ xformers/sparse/blocksparse_tensor.py,sha256=5f1iIqrK_R0cza1anOIJo4CkaMIUo1WbMlJ0LjPbd8s,8894
365
+ xformers/sparse/csr_tensor.py,sha256=TZbVB4aP0WVG2Gr8gB3orkPbNWdjeGxktxYzHAvkYfc,14191
366
+ xformers/sparse/utils.py,sha256=f52XNuTj8gsi5YZABkYeMykMWRGmBnHjIkXM4gzXTdM,4274
367
+ xformers/test.py,sha256=BBoPvMfJjZ0Fi25JCRS8sPYUfLbHneLncV3JeGDIGHg,198
368
+ xformers/triton/__init__.py,sha256=BBoPvMfJjZ0Fi25JCRS8sPYUfLbHneLncV3JeGDIGHg,198
369
+ xformers/triton/__pycache__/__init__.cpython-310.pyc,,
370
+ xformers/triton/__pycache__/vararg_kernel.cpython-310.pyc,,
371
+ xformers/triton/vararg_kernel.py,sha256=cJxRdMCIf2-fOqGKoCPOA54YjUs5d1KsN4-BbHhz9RE,6542
372
+ xformers/utils.py,sha256=eCX-EDLXtb0pOvQAeQVwC8LiMqeBiX2NEyb89jqEVas,5064
373
+ xformers/version.py,sha256=1LfsHAFttAgDDCXROlyBl91uXsK5xuONYMKLhXMH760,42
parrot/lib/python3.10/site-packages/torch/include/ATen/ops/_adaptive_avg_pool2d_cpu_dispatch.h ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace cpu {
19
+
20
+ TORCH_API at::Tensor _adaptive_avg_pool2d(const at::Tensor & self, at::IntArrayRef output_size);
21
+ TORCH_API at::Tensor _adaptive_avg_pool2d_symint(const at::Tensor & self, c10::SymIntArrayRef output_size);
22
+
23
+ } // namespace cpu
24
+ } // namespace at
parrot/lib/python3.10/site-packages/torch/include/ATen/ops/_foreach_add_native.h ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from NativeFunction.h
4
+
5
+ #include <c10/core/Scalar.h>
6
+ #include <c10/core/Storage.h>
7
+ #include <c10/core/TensorOptions.h>
8
+ #include <c10/util/Deprecated.h>
9
+ #include <c10/util/Optional.h>
10
+ #include <c10/core/QScheme.h>
11
+ #include <ATen/core/Reduction.h>
12
+ #include <ATen/core/Tensor.h>
13
+ #include <tuple>
14
+ #include <vector>
15
+
16
+
17
+ namespace at {
18
+ namespace native {
19
+ TORCH_API ::std::vector<at::Tensor> foreach_tensor_add_scalar_kernel_slow(at::TensorList self, const at::Scalar & scalar);
20
+ TORCH_API void _foreach_add_Scalar_out(at::TensorList self, const at::Scalar & scalar, at::TensorList out);
21
+ TORCH_API void foreach_tensor_add_scalar_kernel_slow_(at::TensorList self, const at::Scalar & scalar);
22
+ TORCH_API ::std::vector<at::Tensor> foreach_tensor_add_scalar_kernel_cuda(at::TensorList self, const at::Scalar & scalar);
23
+ TORCH_API void foreach_tensor_add_scalar_kernel_cuda_(at::TensorList self, const at::Scalar & scalar);
24
+ TORCH_API ::std::vector<at::Tensor> foreach_tensor_add_list_kernel_slow(at::TensorList self, at::TensorList other, const at::Scalar & alpha=1);
25
+ TORCH_API void _foreach_add_List_out(at::TensorList self, at::TensorList other, const at::Scalar & alpha, at::TensorList out);
26
+ TORCH_API void foreach_tensor_add_list_kernel_slow_(at::TensorList self, at::TensorList other, const at::Scalar & alpha=1);
27
+ TORCH_API ::std::vector<at::Tensor> foreach_tensor_add_list_kernel_cuda(at::TensorList self, at::TensorList other, const at::Scalar & alpha=1);
28
+ TORCH_API void foreach_tensor_add_list_kernel_cuda_(at::TensorList self, at::TensorList other, const at::Scalar & alpha=1);
29
+ TORCH_API ::std::vector<at::Tensor> foreach_tensor_add_scalarlist_kernel_slow(at::TensorList self, at::ArrayRef<at::Scalar> scalars);
30
+ TORCH_API void _foreach_add_ScalarList_out(at::TensorList self, at::ArrayRef<at::Scalar> scalars, at::TensorList out);
31
+ TORCH_API void foreach_tensor_add_scalarlist_kernel_slow_(at::TensorList self, at::ArrayRef<at::Scalar> scalars);
32
+ TORCH_API ::std::vector<at::Tensor> foreach_tensor_add_scalarlist_kernel_cuda(at::TensorList self, at::ArrayRef<at::Scalar> scalars);
33
+ TORCH_API void foreach_tensor_add_scalarlist_kernel_cuda_(at::TensorList self, at::ArrayRef<at::Scalar> scalars);
34
+ TORCH_API ::std::vector<at::Tensor> foreach_tensor_add_tensor_kernel_slow(at::TensorList self, const at::Tensor & other, const at::Scalar & alpha=1);
35
+ TORCH_API void _foreach_add_Tensor_out(at::TensorList self, const at::Tensor & other, const at::Scalar & alpha, at::TensorList out);
36
+ TORCH_API void foreach_tensor_add_tensor_kernel_slow_(at::TensorList self, const at::Tensor & other, const at::Scalar & alpha=1);
37
+ TORCH_API ::std::vector<at::Tensor> foreach_tensor_add_tensor_kernel_cuda(at::TensorList self, const at::Tensor & other, const at::Scalar & alpha=1);
38
+ TORCH_API void foreach_tensor_add_tensor_kernel_cuda_(at::TensorList self, const at::Tensor & other, const at::Scalar & alpha=1);
39
+ } // namespace native
40
+ } // namespace at
parrot/lib/python3.10/site-packages/torch/include/ATen/ops/_foreach_div_ops.h ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Operator.h
4
+
5
+ #include <tuple>
6
+ #include <vector>
7
+
8
+ // Forward declarations of any types needed in the operator signatures.
9
+ // We can't directly include these classes because it will cause circular include dependencies.
10
+ // This file is included by TensorBody.h, which defines the Tensor class.
11
+ #include <ATen/core/ATen_fwd.h>
12
+
13
+ namespace at {
14
+ namespace _ops {
15
+
16
+
17
+ struct TORCH_API _foreach_div_Scalar {
18
+ using schema = ::std::vector<at::Tensor> (at::TensorList, const at::Scalar &);
19
+ using ptr_schema = schema*;
20
+ // See Note [static constexpr char* members for windows NVCC]
21
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_foreach_div")
22
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Scalar")
23
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_foreach_div.Scalar(Tensor[] self, Scalar scalar) -> Tensor[]")
24
+ static ::std::vector<at::Tensor> call(at::TensorList self, const at::Scalar & scalar);
25
+ static ::std::vector<at::Tensor> redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList self, const at::Scalar & scalar);
26
+ };
27
+
28
+ struct TORCH_API _foreach_div__Scalar {
29
+ using schema = void (at::TensorList, const at::Scalar &);
30
+ using ptr_schema = schema*;
31
+ // See Note [static constexpr char* members for windows NVCC]
32
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_foreach_div_")
33
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Scalar")
34
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_foreach_div_.Scalar(Tensor(a!)[] self, Scalar scalar) -> ()")
35
+ static void call(at::TensorList self, const at::Scalar & scalar);
36
+ static void redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList self, const at::Scalar & scalar);
37
+ };
38
+
39
+ struct TORCH_API _foreach_div_List {
40
+ using schema = ::std::vector<at::Tensor> (at::TensorList, at::TensorList);
41
+ using ptr_schema = schema*;
42
+ // See Note [static constexpr char* members for windows NVCC]
43
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_foreach_div")
44
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "List")
45
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_foreach_div.List(Tensor[] self, Tensor[] other) -> Tensor[]")
46
+ static ::std::vector<at::Tensor> call(at::TensorList self, at::TensorList other);
47
+ static ::std::vector<at::Tensor> redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList self, at::TensorList other);
48
+ };
49
+
50
+ struct TORCH_API _foreach_div__List {
51
+ using schema = void (at::TensorList, at::TensorList);
52
+ using ptr_schema = schema*;
53
+ // See Note [static constexpr char* members for windows NVCC]
54
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_foreach_div_")
55
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "List")
56
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_foreach_div_.List(Tensor(a!)[] self, Tensor[] other) -> ()")
57
+ static void call(at::TensorList self, at::TensorList other);
58
+ static void redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList self, at::TensorList other);
59
+ };
60
+
61
+ struct TORCH_API _foreach_div_ScalarList {
62
+ using schema = ::std::vector<at::Tensor> (at::TensorList, at::ArrayRef<at::Scalar>);
63
+ using ptr_schema = schema*;
64
+ // See Note [static constexpr char* members for windows NVCC]
65
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_foreach_div")
66
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "ScalarList")
67
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_foreach_div.ScalarList(Tensor[] self, Scalar[] scalars) -> Tensor[]")
68
+ static ::std::vector<at::Tensor> call(at::TensorList self, at::ArrayRef<at::Scalar> scalars);
69
+ static ::std::vector<at::Tensor> redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList self, at::ArrayRef<at::Scalar> scalars);
70
+ };
71
+
72
+ struct TORCH_API _foreach_div__ScalarList {
73
+ using schema = void (at::TensorList, at::ArrayRef<at::Scalar>);
74
+ using ptr_schema = schema*;
75
+ // See Note [static constexpr char* members for windows NVCC]
76
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_foreach_div_")
77
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "ScalarList")
78
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_foreach_div_.ScalarList(Tensor(a!)[] self, Scalar[] scalars) -> ()")
79
+ static void call(at::TensorList self, at::ArrayRef<at::Scalar> scalars);
80
+ static void redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList self, at::ArrayRef<at::Scalar> scalars);
81
+ };
82
+
83
+ struct TORCH_API _foreach_div_Tensor {
84
+ using schema = ::std::vector<at::Tensor> (at::TensorList, const at::Tensor &);
85
+ using ptr_schema = schema*;
86
+ // See Note [static constexpr char* members for windows NVCC]
87
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_foreach_div")
88
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Tensor")
89
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_foreach_div.Tensor(Tensor[] self, Tensor other) -> Tensor[]")
90
+ static ::std::vector<at::Tensor> call(at::TensorList self, const at::Tensor & other);
91
+ static ::std::vector<at::Tensor> redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList self, const at::Tensor & other);
92
+ };
93
+
94
+ struct TORCH_API _foreach_div__Tensor {
95
+ using schema = void (at::TensorList, const at::Tensor &);
96
+ using ptr_schema = schema*;
97
+ // See Note [static constexpr char* members for windows NVCC]
98
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_foreach_div_")
99
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Tensor")
100
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_foreach_div_.Tensor(Tensor(a!)[] self, Tensor other) -> ()")
101
+ static void call(at::TensorList self, const at::Tensor & other);
102
+ static void redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList self, const at::Tensor & other);
103
+ };
104
+
105
+ struct TORCH_API _foreach_div_Scalar_out {
106
+ using schema = void (at::TensorList, const at::Scalar &, at::TensorList);
107
+ using ptr_schema = schema*;
108
+ // See Note [static constexpr char* members for windows NVCC]
109
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_foreach_div")
110
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Scalar_out")
111
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_foreach_div.Scalar_out(Tensor[] self, Scalar scalar, *, Tensor(a!)[] out) -> ()")
112
+ static void call(at::TensorList self, const at::Scalar & scalar, at::TensorList out);
113
+ static void redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList self, const at::Scalar & scalar, at::TensorList out);
114
+ };
115
+
116
+ struct TORCH_API _foreach_div_List_out {
117
+ using schema = void (at::TensorList, at::TensorList, at::TensorList);
118
+ using ptr_schema = schema*;
119
+ // See Note [static constexpr char* members for windows NVCC]
120
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_foreach_div")
121
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "List_out")
122
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_foreach_div.List_out(Tensor[] self, Tensor[] other, *, Tensor(a!)[] out) -> ()")
123
+ static void call(at::TensorList self, at::TensorList other, at::TensorList out);
124
+ static void redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList self, at::TensorList other, at::TensorList out);
125
+ };
126
+
127
+ struct TORCH_API _foreach_div_ScalarList_out {
128
+ using schema = void (at::TensorList, at::ArrayRef<at::Scalar>, at::TensorList);
129
+ using ptr_schema = schema*;
130
+ // See Note [static constexpr char* members for windows NVCC]
131
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_foreach_div")
132
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "ScalarList_out")
133
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_foreach_div.ScalarList_out(Tensor[] self, Scalar[] scalars, *, Tensor(a!)[] out) -> ()")
134
+ static void call(at::TensorList self, at::ArrayRef<at::Scalar> scalars, at::TensorList out);
135
+ static void redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList self, at::ArrayRef<at::Scalar> scalars, at::TensorList out);
136
+ };
137
+
138
+ struct TORCH_API _foreach_div_Tensor_out {
139
+ using schema = void (at::TensorList, const at::Tensor &, at::TensorList);
140
+ using ptr_schema = schema*;
141
+ // See Note [static constexpr char* members for windows NVCC]
142
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_foreach_div")
143
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Tensor_out")
144
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_foreach_div.Tensor_out(Tensor[] self, Tensor other, *, Tensor(a!)[] out) -> ()")
145
+ static void call(at::TensorList self, const at::Tensor & other, at::TensorList out);
146
+ static void redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList self, const at::Tensor & other, at::TensorList out);
147
+ };
148
+
149
+ }} // namespace at::_ops
parrot/lib/python3.10/site-packages/torch/include/ATen/ops/_foreach_max_ops.h ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Operator.h
4
+
5
+ #include <tuple>
6
+ #include <vector>
7
+
8
+ // Forward declarations of any types needed in the operator signatures.
9
+ // We can't directly include these classes because it will cause circular include dependencies.
10
+ // This file is included by TensorBody.h, which defines the Tensor class.
11
+ #include <ATen/core/ATen_fwd.h>
12
+
13
+ namespace at {
14
+ namespace _ops {
15
+
16
+
17
+ struct TORCH_API _foreach_max {
18
+ using schema = ::std::vector<at::Tensor> (at::TensorList);
19
+ using ptr_schema = schema*;
20
+ // See Note [static constexpr char* members for windows NVCC]
21
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_foreach_max")
22
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
23
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_foreach_max(Tensor[] self) -> Tensor[]")
24
+ static ::std::vector<at::Tensor> call(at::TensorList self);
25
+ static ::std::vector<at::Tensor> redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList self);
26
+ };
27
+
28
+ struct TORCH_API _foreach_max_out {
29
+ using schema = void (at::TensorList, at::TensorList);
30
+ using ptr_schema = schema*;
31
+ // See Note [static constexpr char* members for windows NVCC]
32
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_foreach_max")
33
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out")
34
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_foreach_max.out(Tensor[] self, *, Tensor(a!)[] out) -> ()")
35
+ static void call(at::TensorList self, at::TensorList out);
36
+ static void redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList self, at::TensorList out);
37
+ };
38
+
39
+ }} // namespace at::_ops
parrot/lib/python3.10/site-packages/torch/include/ATen/ops/_is_zerotensor_native.h ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from NativeFunction.h
4
+
5
+ #include <c10/core/Scalar.h>
6
+ #include <c10/core/Storage.h>
7
+ #include <c10/core/TensorOptions.h>
8
+ #include <c10/util/Deprecated.h>
9
+ #include <c10/util/Optional.h>
10
+ #include <c10/core/QScheme.h>
11
+ #include <ATen/core/Reduction.h>
12
+ #include <ATen/core/Tensor.h>
13
+ #include <tuple>
14
+ #include <vector>
15
+
16
+
17
+ namespace at {
18
+ namespace native {
19
+ TORCH_API bool _is_zerotensor(const at::Tensor & self);
20
+ } // namespace native
21
+ } // namespace at
parrot/lib/python3.10/site-packages/torch/include/ATen/ops/_nested_view_from_jagged_native.h ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from NativeFunction.h
4
+
5
+ #include <c10/core/Scalar.h>
6
+ #include <c10/core/Storage.h>
7
+ #include <c10/core/TensorOptions.h>
8
+ #include <c10/util/Deprecated.h>
9
+ #include <c10/util/Optional.h>
10
+ #include <c10/core/QScheme.h>
11
+ #include <ATen/core/Reduction.h>
12
+ #include <ATen/core/Tensor.h>
13
+ #include <tuple>
14
+ #include <vector>
15
+
16
+
17
+ namespace at {
18
+ namespace native {
19
+ } // namespace native
20
+ } // namespace at
parrot/lib/python3.10/site-packages/torch/include/ATen/ops/_reshape_alias_meta_dispatch.h ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace meta {
19
+
20
+ TORCH_API at::Tensor _reshape_alias(const at::Tensor & self, at::IntArrayRef size, at::IntArrayRef stride);
21
+ TORCH_API at::Tensor _reshape_alias_symint(const at::Tensor & self, c10::SymIntArrayRef size, c10::SymIntArrayRef stride);
22
+
23
+ } // namespace meta
24
+ } // namespace at
parrot/lib/python3.10/site-packages/torch/include/ATen/ops/_test_optional_intlist_ops.h ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Operator.h
4
+
5
+ #include <tuple>
6
+ #include <vector>
7
+
8
+ // Forward declarations of any types needed in the operator signatures.
9
+ // We can't directly include these classes because it will cause circular include dependencies.
10
+ // This file is included by TensorBody.h, which defines the Tensor class.
11
+ #include <ATen/core/ATen_fwd.h>
12
+
13
+ namespace at {
14
+ namespace _ops {
15
+
16
+
17
+ struct TORCH_API _test_optional_intlist {
18
+ using schema = at::Tensor (const at::Tensor &, at::OptionalIntArrayRef);
19
+ using ptr_schema = schema*;
20
+ // See Note [static constexpr char* members for windows NVCC]
21
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_test_optional_intlist")
22
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
23
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_test_optional_intlist(Tensor values, int[]? addends) -> Tensor")
24
+ static at::Tensor call(const at::Tensor & values, at::OptionalIntArrayRef addends);
25
+ static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & values, at::OptionalIntArrayRef addends);
26
+ };
27
+
28
+ struct TORCH_API _test_optional_intlist_out {
29
+ using schema = at::Tensor & (const at::Tensor &, at::OptionalIntArrayRef, at::Tensor &);
30
+ using ptr_schema = schema*;
31
+ // See Note [static constexpr char* members for windows NVCC]
32
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_test_optional_intlist")
33
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out")
34
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_test_optional_intlist.out(Tensor values, int[]? addends, *, Tensor(a!) out) -> Tensor(a!)")
35
+ static at::Tensor & call(const at::Tensor & values, at::OptionalIntArrayRef addends, at::Tensor & out);
36
+ static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & values, at::OptionalIntArrayRef addends, at::Tensor & out);
37
+ };
38
+
39
+ }} // namespace at::_ops