ZTWHHH commited on
Commit
7d577ba
·
verified ·
1 Parent(s): fa754a7

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 +2 -0
  2. videollama2/lib/python3.10/site-packages/nvidia/cusparse/lib/libcusparse.so.12 +3 -0
  3. vllm/lib/python3.10/site-packages/blessed/__init__.py +23 -0
  4. vllm/lib/python3.10/site-packages/blessed/__pycache__/__init__.cpython-310.pyc +0 -0
  5. vllm/lib/python3.10/site-packages/blessed/__pycache__/_capabilities.cpython-310.pyc +0 -0
  6. vllm/lib/python3.10/site-packages/blessed/__pycache__/color.cpython-310.pyc +0 -0
  7. vllm/lib/python3.10/site-packages/blessed/__pycache__/colorspace.cpython-310.pyc +0 -0
  8. vllm/lib/python3.10/site-packages/blessed/__pycache__/formatters.cpython-310.pyc +0 -0
  9. vllm/lib/python3.10/site-packages/blessed/__pycache__/keyboard.cpython-310.pyc +0 -0
  10. vllm/lib/python3.10/site-packages/blessed/__pycache__/sequences.cpython-310.pyc +0 -0
  11. vllm/lib/python3.10/site-packages/blessed/__pycache__/terminal.cpython-310.pyc +0 -0
  12. vllm/lib/python3.10/site-packages/blessed/__pycache__/win_terminal.cpython-310.pyc +0 -0
  13. vllm/lib/python3.10/site-packages/blessed/_capabilities.py +168 -0
  14. vllm/lib/python3.10/site-packages/blessed/_capabilities.pyi +7 -0
  15. vllm/lib/python3.10/site-packages/blessed/color.py +258 -0
  16. vllm/lib/python3.10/site-packages/blessed/color.pyi +17 -0
  17. vllm/lib/python3.10/site-packages/blessed/colorspace.py +973 -0
  18. vllm/lib/python3.10/site-packages/blessed/colorspace.pyi +12 -0
  19. vllm/lib/python3.10/site-packages/blessed/formatters.py +496 -0
  20. vllm/lib/python3.10/site-packages/blessed/formatters.pyi +70 -0
  21. vllm/lib/python3.10/site-packages/blessed/keyboard.py +451 -0
  22. vllm/lib/python3.10/site-packages/blessed/keyboard.pyi +28 -0
  23. vllm/lib/python3.10/site-packages/blessed/py.typed +0 -0
  24. vllm/lib/python3.10/site-packages/blessed/sequences.py +461 -0
  25. vllm/lib/python3.10/site-packages/blessed/sequences.pyi +55 -0
  26. vllm/lib/python3.10/site-packages/blessed/terminal.py +1552 -0
  27. vllm/lib/python3.10/site-packages/blessed/terminal.pyi +108 -0
  28. vllm/lib/python3.10/site-packages/blessed/win_terminal.py +163 -0
  29. vllm/lib/python3.10/site-packages/blessed/win_terminal.pyi +11 -0
  30. vllm/lib/python3.10/site-packages/python_multipart-0.0.20.dist-info/RECORD +23 -0
  31. vllm/lib/python3.10/site-packages/python_multipart-0.0.20.dist-info/REQUESTED +0 -0
  32. vllm/lib/python3.10/site-packages/python_multipart-0.0.20.dist-info/WHEEL +4 -0
  33. vllm/lib/python3.10/site-packages/python_multipart-0.0.20.dist-info/licenses/LICENSE.txt +14 -0
  34. vllm/lib/python3.10/site-packages/requests/__init__.py +184 -0
  35. vllm/lib/python3.10/site-packages/requests/adapters.py +719 -0
  36. vllm/lib/python3.10/site-packages/requests/api.py +157 -0
  37. vllm/lib/python3.10/site-packages/requests/certs.py +17 -0
  38. vllm/lib/python3.10/site-packages/requests/compat.py +94 -0
  39. vllm/lib/python3.10/site-packages/requests/exceptions.py +151 -0
  40. vllm/lib/python3.10/site-packages/requests/hooks.py +33 -0
  41. vllm/lib/python3.10/site-packages/requests/sessions.py +831 -0
  42. vllm/lib/python3.10/site-packages/requests/structures.py +99 -0
  43. vllm/lib/python3.10/site-packages/requests/utils.py +1096 -0
  44. vllm/lib/python3.10/site-packages/rsa-4.9.dist-info/INSTALLER +1 -0
  45. vllm/lib/python3.10/site-packages/rsa-4.9.dist-info/LICENSE +13 -0
  46. vllm/lib/python3.10/site-packages/rsa-4.9.dist-info/METADATA +106 -0
  47. vllm/lib/python3.10/site-packages/rsa-4.9.dist-info/RECORD +42 -0
  48. vllm/lib/python3.10/site-packages/rsa-4.9.dist-info/REQUESTED +0 -0
  49. vllm/lib/python3.10/site-packages/rsa-4.9.dist-info/WHEEL +4 -0
  50. vllm/lib/python3.10/site-packages/rsa-4.9.dist-info/entry_points.txt +8 -0
.gitattributes CHANGED
@@ -1649,3 +1649,5 @@ vllm/lib/python3.10/site-packages/transformers/models/perceiver/__pycache__/mode
1649
  vllm/lib/python3.10/site-packages/cupyx/cutensor.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1650
  vllm/lib/python3.10/site-packages/transformers/models/seamless_m4t_v2/__pycache__/modeling_seamless_m4t_v2.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
1651
  vllm/lib/python3.10/site-packages/transformers/models/speecht5/__pycache__/modeling_speecht5.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
 
 
 
1649
  vllm/lib/python3.10/site-packages/cupyx/cutensor.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1650
  vllm/lib/python3.10/site-packages/transformers/models/seamless_m4t_v2/__pycache__/modeling_seamless_m4t_v2.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
1651
  vllm/lib/python3.10/site-packages/transformers/models/speecht5/__pycache__/modeling_speecht5.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
1652
+ videollama2/lib/python3.10/site-packages/nvidia/cusparse/lib/libcusparse.so.12 filter=lfs diff=lfs merge=lfs -text
1653
+ vllm/lib/python3.10/site-packages/safetensors/_safetensors_rust.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
videollama2/lib/python3.10/site-packages/nvidia/cusparse/lib/libcusparse.so.12 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:500466a2f559de622a71bb920d3d2923e69135245747a2742ee13edff0ba6085
3
+ size 264876688
vllm/lib/python3.10/site-packages/blessed/__init__.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ A thin, practical wrapper around terminal capabilities in Python.
3
+
4
+ http://pypi.python.org/pypi/blessed
5
+ """
6
+ # std imports
7
+ import sys as _sys
8
+ import platform as _platform
9
+
10
+ # isort: off
11
+ if _platform.system() == 'Windows':
12
+ from blessed.win_terminal import Terminal
13
+ else:
14
+ from blessed.terminal import Terminal # type: ignore
15
+
16
+ if (3, 0, 0) <= _sys.version_info[:3] < (3, 2, 3):
17
+ # Good till 3.2.10
18
+ # Python 3.x < 3.2.3 has a bug in which tparm() erroneously takes a string.
19
+ raise ImportError('Blessed needs Python 3.2.3 or greater for Python 3 '
20
+ 'support due to http://bugs.python.org/issue10570.')
21
+
22
+ __all__ = ('Terminal',)
23
+ __version__ = "1.20.0"
vllm/lib/python3.10/site-packages/blessed/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (702 Bytes). View file
 
vllm/lib/python3.10/site-packages/blessed/__pycache__/_capabilities.cpython-310.pyc ADDED
Binary file (4.76 kB). View file
 
vllm/lib/python3.10/site-packages/blessed/__pycache__/color.cpython-310.pyc ADDED
Binary file (6.76 kB). View file
 
vllm/lib/python3.10/site-packages/blessed/__pycache__/colorspace.cpython-310.pyc ADDED
Binary file (34.4 kB). View file
 
vllm/lib/python3.10/site-packages/blessed/__pycache__/formatters.cpython-310.pyc ADDED
Binary file (16 kB). View file
 
vllm/lib/python3.10/site-packages/blessed/__pycache__/keyboard.cpython-310.pyc ADDED
Binary file (13.4 kB). View file
 
vllm/lib/python3.10/site-packages/blessed/__pycache__/sequences.cpython-310.pyc ADDED
Binary file (15.4 kB). View file
 
vllm/lib/python3.10/site-packages/blessed/__pycache__/terminal.cpython-310.pyc ADDED
Binary file (48.8 kB). View file
 
vllm/lib/python3.10/site-packages/blessed/__pycache__/win_terminal.cpython-310.pyc ADDED
Binary file (5.39 kB). View file
 
vllm/lib/python3.10/site-packages/blessed/_capabilities.py ADDED
@@ -0,0 +1,168 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Terminal capability builder patterns."""
2
+ # std imports
3
+ import re
4
+ from collections import OrderedDict
5
+
6
+ __all__ = (
7
+ 'CAPABILITY_DATABASE',
8
+ 'CAPABILITIES_RAW_MIXIN',
9
+ 'CAPABILITIES_ADDITIVES',
10
+ 'CAPABILITIES_CAUSE_MOVEMENT',
11
+ )
12
+
13
+ CAPABILITY_DATABASE = OrderedDict((
14
+ ('bell', ('bel', {})),
15
+ ('carriage_return', ('cr', {})),
16
+ ('change_scroll_region', ('csr', {'nparams': 2})),
17
+ ('clear_all_tabs', ('tbc', {})),
18
+ ('clear_screen', ('clear', {})),
19
+ ('clr_bol', ('el1', {})),
20
+ ('clr_eol', ('el', {})),
21
+ ('clr_eos', ('clear_eos', {})),
22
+ ('column_address', ('hpa', {'nparams': 1})),
23
+ ('cursor_address', ('cup', {'nparams': 2, 'match_grouped': True})),
24
+ ('cursor_down', ('cud1', {})),
25
+ ('cursor_home', ('home', {})),
26
+ ('cursor_invisible', ('civis', {})),
27
+ ('cursor_left', ('cub1', {})),
28
+ ('cursor_normal', ('cnorm', {})),
29
+ ('cursor_report', ('u6', {'nparams': 2, 'match_grouped': True})),
30
+ ('cursor_right', ('cuf1', {})),
31
+ ('cursor_up', ('cuu1', {})),
32
+ ('cursor_visible', ('cvvis', {})),
33
+ ('delete_character', ('dch1', {})),
34
+ ('delete_line', ('dl1', {})),
35
+ ('enter_blink_mode', ('blink', {})),
36
+ ('enter_bold_mode', ('bold', {})),
37
+ ('enter_dim_mode', ('dim', {})),
38
+ ('enter_fullscreen', ('smcup', {})),
39
+ ('enter_standout_mode', ('standout', {})),
40
+ ('enter_superscript_mode', ('superscript', {})),
41
+ ('enter_susimpleript_mode', ('susimpleript', {})),
42
+ ('enter_underline_mode', ('underline', {})),
43
+ ('erase_chars', ('ech', {'nparams': 1})),
44
+ ('exit_alt_charset_mode', ('rmacs', {})),
45
+ ('exit_am_mode', ('rmam', {})),
46
+ ('exit_attribute_mode', ('sgr0', {})),
47
+ ('exit_ca_mode', ('rmcup', {})),
48
+ ('exit_fullscreen', ('rmcup', {})),
49
+ ('exit_insert_mode', ('rmir', {})),
50
+ ('exit_standout_mode', ('rmso', {})),
51
+ ('exit_underline_mode', ('rmul', {})),
52
+ ('flash_hook', ('hook', {})),
53
+ ('flash_screen', ('flash', {})),
54
+ ('insert_line', ('il1', {})),
55
+ ('keypad_local', ('rmkx', {})),
56
+ ('keypad_xmit', ('smkx', {})),
57
+ ('meta_off', ('rmm', {})),
58
+ ('meta_on', ('smm', {})),
59
+ ('orig_pair', ('op', {})),
60
+ ('parm_down_cursor', ('cud', {'nparams': 1})),
61
+ ('parm_left_cursor', ('cub', {'nparams': 1, 'match_grouped': True})),
62
+ ('parm_dch', ('dch', {'nparams': 1})),
63
+ ('parm_delete_line', ('dl', {'nparams': 1})),
64
+ ('parm_ich', ('ich', {'nparams': 1})),
65
+ ('parm_index', ('indn', {'nparams': 1})),
66
+ ('parm_insert_line', ('il', {'nparams': 1})),
67
+ ('parm_right_cursor', ('cuf', {'nparams': 1, 'match_grouped': True})),
68
+ ('parm_rindex', ('rin', {'nparams': 1})),
69
+ ('parm_up_cursor', ('cuu', {'nparams': 1})),
70
+ ('print_screen', ('mc0', {})),
71
+ ('prtr_off', ('mc4', {})),
72
+ ('prtr_on', ('mc5', {})),
73
+ ('reset_1string', ('r1', {})),
74
+ ('reset_2string', ('r2', {})),
75
+ ('reset_3string', ('r3', {})),
76
+ ('restore_cursor', ('rc', {})),
77
+ ('row_address', ('vpa', {'nparams': 1})),
78
+ ('save_cursor', ('sc', {})),
79
+ ('scroll_forward', ('ind', {})),
80
+ ('scroll_reverse', ('rev', {})),
81
+ ('set0_des_seq', ('s0ds', {})),
82
+ ('set1_des_seq', ('s1ds', {})),
83
+ ('set2_des_seq', ('s2ds', {})),
84
+ ('set3_des_seq', ('s3ds', {})),
85
+ # this 'color' is deceiving, but often matching, and a better match
86
+ # than set_a_attributes1 or set_a_foreground.
87
+ ('color', ('_foreground_color', {'nparams': 1, 'match_any': True,
88
+ 'numeric': 1})),
89
+ ('set_a_foreground', ('color', {'nparams': 1, 'match_any': True,
90
+ 'numeric': 1})),
91
+ ('set_a_background', ('on_color', {'nparams': 1, 'match_any': True,
92
+ 'numeric': 1})),
93
+ ('set_tab', ('hts', {})),
94
+ ('tab', ('ht', {})),
95
+ ('italic', ('sitm', {})),
96
+ ('no_italic', ('sitm', {})),
97
+ ))
98
+
99
+ CAPABILITIES_RAW_MIXIN = {
100
+ 'bell': re.escape('\a'),
101
+ 'carriage_return': re.escape('\r'),
102
+ 'cursor_left': re.escape('\b'),
103
+ 'cursor_report': re.escape('\x1b') + r'\[(\d+)\;(\d+)R',
104
+ 'cursor_right': re.escape('\x1b') + r'\[C',
105
+ 'exit_attribute_mode': re.escape('\x1b') + r'\[m',
106
+ 'parm_left_cursor': re.escape('\x1b') + r'\[(\d+)D',
107
+ 'parm_right_cursor': re.escape('\x1b') + r'\[(\d+)C',
108
+ 'restore_cursor': re.escape(r'\x1b\[u'),
109
+ 'save_cursor': re.escape(r'\x1b\[s'),
110
+ 'scroll_forward': re.escape('\n'),
111
+ 'set0_des_seq': re.escape('\x1b(B'),
112
+ 'tab': re.escape('\t'),
113
+ }
114
+ _ANY_NOTESC = '[^' + re.escape('\x1b') + ']*'
115
+
116
+ CAPABILITIES_ADDITIVES = {
117
+ 'link': ('link',
118
+ re.escape('\x1b') + r'\]8;' + _ANY_NOTESC + ';' +
119
+ _ANY_NOTESC + re.escape('\x1b') + '\\\\'),
120
+ 'color256': ('color', re.escape('\x1b') + r'\[38;5;\d+m'),
121
+ 'on_color256': ('on_color', re.escape('\x1b') + r'\[48;5;\d+m'),
122
+ 'color_rgb': ('color_rgb', re.escape('\x1b') + r'\[38;2;\d+;\d+;\d+m'),
123
+ 'on_color_rgb': ('on_color_rgb', re.escape('\x1b') + r'\[48;2;\d+;\d+;\d+m'),
124
+ 'shift_in': ('', re.escape('\x0f')),
125
+ 'shift_out': ('', re.escape('\x0e')),
126
+ # sgr(...) outputs strangely, use the basic ANSI/EMCA-48 codes here.
127
+ 'set_a_attributes1': (
128
+ 'sgr', re.escape('\x1b') + r'\[\d+m'),
129
+ 'set_a_attributes2': (
130
+ 'sgr', re.escape('\x1b') + r'\[\d+\;\d+m'),
131
+ 'set_a_attributes3': (
132
+ 'sgr', re.escape('\x1b') + r'\[\d+\;\d+\;\d+m'),
133
+ 'set_a_attributes4': (
134
+ 'sgr', re.escape('\x1b') + r'\[\d+\;\d+\;\d+\;\d+m'),
135
+ # this helps where xterm's sgr0 includes set0_des_seq, we'd
136
+ # rather like to also match this immediate substring.
137
+ 'sgr0': ('sgr0', re.escape('\x1b') + r'\[m'),
138
+ 'backspace': ('', re.escape('\b')),
139
+ 'ascii_tab': ('', re.escape('\t')),
140
+ 'clr_eol': ('', re.escape('\x1b[K')),
141
+ 'clr_eol0': ('', re.escape('\x1b[0K')),
142
+ 'clr_bol': ('', re.escape('\x1b[1K')),
143
+ 'clr_eosK': ('', re.escape('\x1b[2K')),
144
+ }
145
+
146
+ CAPABILITIES_CAUSE_MOVEMENT = (
147
+ 'ascii_tab',
148
+ 'backspace',
149
+ 'carriage_return',
150
+ 'clear_screen',
151
+ 'column_address',
152
+ 'cursor_address',
153
+ 'cursor_down',
154
+ 'cursor_home',
155
+ 'cursor_left',
156
+ 'cursor_right',
157
+ 'cursor_up',
158
+ 'enter_fullscreen',
159
+ 'exit_fullscreen',
160
+ 'parm_down_cursor',
161
+ 'parm_left_cursor',
162
+ 'parm_right_cursor',
163
+ 'parm_up_cursor',
164
+ 'restore_cursor',
165
+ 'row_address',
166
+ 'scroll_forward',
167
+ 'tab',
168
+ )
vllm/lib/python3.10/site-packages/blessed/_capabilities.pyi ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # std imports
2
+ from typing import Any, Dict, Tuple, OrderedDict
3
+
4
+ CAPABILITY_DATABASE: OrderedDict[str, Tuple[str, Dict[str, Any]]]
5
+ CAPABILITIES_RAW_MIXIN: Dict[str, str]
6
+ CAPABILITIES_ADDITIVES: Dict[str, Tuple[str, str]]
7
+ CAPABILITIES_CAUSE_MOVEMENT: Tuple[str, ...]
vllm/lib/python3.10/site-packages/blessed/color.py ADDED
@@ -0,0 +1,258 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ Sub-module providing color functions.
4
+
5
+ References,
6
+
7
+ - https://en.wikipedia.org/wiki/Color_difference
8
+ - http://www.easyrgb.com/en/math.php
9
+ - Measuring Colour by R.W.G. Hunt and M.R. Pointer
10
+ """
11
+
12
+ # std imports
13
+ from math import cos, exp, sin, sqrt, atan2
14
+
15
+ # isort: off
16
+ try:
17
+ from functools import lru_cache
18
+ except ImportError:
19
+ # lru_cache was added in Python 3.2
20
+ from backports.functools_lru_cache import lru_cache
21
+
22
+
23
+ def rgb_to_xyz(red, green, blue):
24
+ """
25
+ Convert standard RGB color to XYZ color.
26
+
27
+ :arg int red: RGB value of Red.
28
+ :arg int green: RGB value of Green.
29
+ :arg int blue: RGB value of Blue.
30
+ :returns: Tuple (X, Y, Z) representing XYZ color
31
+ :rtype: tuple
32
+
33
+ D65/2° standard illuminant
34
+ """
35
+ rgb = []
36
+ for val in red, green, blue:
37
+ val /= 255.0
38
+ if val > 0.04045:
39
+ val = pow((val + 0.055) / 1.055, 2.4)
40
+ else:
41
+ val /= 12.92
42
+ val *= 100
43
+ rgb.append(val)
44
+
45
+ red, green, blue = rgb # pylint: disable=unbalanced-tuple-unpacking
46
+ x_val = red * 0.4124 + green * 0.3576 + blue * 0.1805
47
+ y_val = red * 0.2126 + green * 0.7152 + blue * 0.0722
48
+ z_val = red * 0.0193 + green * 0.1192 + blue * 0.9505
49
+
50
+ return x_val, y_val, z_val
51
+
52
+
53
+ def xyz_to_lab(x_val, y_val, z_val):
54
+ """
55
+ Convert XYZ color to CIE-Lab color.
56
+
57
+ :arg float x_val: XYZ value of X.
58
+ :arg float y_val: XYZ value of Y.
59
+ :arg float z_val: XYZ value of Z.
60
+ :returns: Tuple (L, a, b) representing CIE-Lab color
61
+ :rtype: tuple
62
+
63
+ D65/2° standard illuminant
64
+ """
65
+ xyz = []
66
+ for val, ref in (x_val, 95.047), (y_val, 100.0), (z_val, 108.883):
67
+ val /= ref
68
+ val = pow(val, 1 / 3.0) if val > 0.008856 else 7.787 * val + 16 / 116.0
69
+ xyz.append(val)
70
+
71
+ x_val, y_val, z_val = xyz # pylint: disable=unbalanced-tuple-unpacking
72
+ cie_l = 116 * y_val - 16
73
+ cie_a = 500 * (x_val - y_val)
74
+ cie_b = 200 * (y_val - z_val)
75
+
76
+ return cie_l, cie_a, cie_b
77
+
78
+
79
+ @lru_cache(maxsize=256)
80
+ def rgb_to_lab(red, green, blue):
81
+ """
82
+ Convert RGB color to CIE-Lab color.
83
+
84
+ :arg int red: RGB value of Red.
85
+ :arg int green: RGB value of Green.
86
+ :arg int blue: RGB value of Blue.
87
+ :returns: Tuple (L, a, b) representing CIE-Lab color
88
+ :rtype: tuple
89
+
90
+ D65/2° standard illuminant
91
+ """
92
+ return xyz_to_lab(*rgb_to_xyz(red, green, blue))
93
+
94
+
95
+ def dist_rgb(rgb1, rgb2):
96
+ """
97
+ Determine distance between two rgb colors.
98
+
99
+ :arg tuple rgb1: RGB color definition
100
+ :arg tuple rgb2: RGB color definition
101
+ :returns: Square of the distance between provided colors
102
+ :rtype: float
103
+
104
+ This works by treating RGB colors as coordinates in three dimensional
105
+ space and finding the closest point within the configured color range
106
+ using the formula::
107
+
108
+ d^2 = (r2 - r1)^2 + (g2 - g1)^2 + (b2 - b1)^2
109
+
110
+ For efficiency, the square of the distance is returned
111
+ which is sufficient for comparisons
112
+ """
113
+ return sum(pow(rgb1[idx] - rgb2[idx], 2) for idx in (0, 1, 2))
114
+
115
+
116
+ def dist_rgb_weighted(rgb1, rgb2):
117
+ """
118
+ Determine the weighted distance between two rgb colors.
119
+
120
+ :arg tuple rgb1: RGB color definition
121
+ :arg tuple rgb2: RGB color definition
122
+ :returns: Square of the distance between provided colors
123
+ :rtype: float
124
+
125
+ Similar to a standard distance formula, the values are weighted
126
+ to approximate human perception of color differences
127
+
128
+ For efficiency, the square of the distance is returned
129
+ which is sufficient for comparisons
130
+ """
131
+ red_mean = (rgb1[0] + rgb2[0]) / 2.0
132
+
133
+ return ((2 + red_mean / 256) * pow(rgb1[0] - rgb2[0], 2) +
134
+ 4 * pow(rgb1[1] - rgb2[1], 2) +
135
+ (2 + (255 - red_mean) / 256) * pow(rgb1[2] - rgb2[2], 2))
136
+
137
+
138
+ def dist_cie76(rgb1, rgb2):
139
+ """
140
+ Determine distance between two rgb colors using the CIE94 algorithm.
141
+
142
+ :arg tuple rgb1: RGB color definition
143
+ :arg tuple rgb2: RGB color definition
144
+ :returns: Square of the distance between provided colors
145
+ :rtype: float
146
+
147
+ For efficiency, the square of the distance is returned
148
+ which is sufficient for comparisons
149
+ """
150
+ l_1, a_1, b_1 = rgb_to_lab(*rgb1)
151
+ l_2, a_2, b_2 = rgb_to_lab(*rgb2)
152
+ return pow(l_1 - l_2, 2) + pow(a_1 - a_2, 2) + pow(b_1 - b_2, 2)
153
+
154
+
155
+ def dist_cie94(rgb1, rgb2):
156
+ # pylint: disable=too-many-locals
157
+ """
158
+ Determine distance between two rgb colors using the CIE94 algorithm.
159
+
160
+ :arg tuple rgb1: RGB color definition
161
+ :arg tuple rgb2: RGB color definition
162
+ :returns: Square of the distance between provided colors
163
+ :rtype: float
164
+
165
+ For efficiency, the square of the distance is returned
166
+ which is sufficient for comparisons
167
+ """
168
+ l_1, a_1, b_1 = rgb_to_lab(*rgb1)
169
+ l_2, a_2, b_2 = rgb_to_lab(*rgb2)
170
+
171
+ s_l = k_l = k_c = k_h = 1
172
+ k_1 = 0.045
173
+ k_2 = 0.015
174
+
175
+ delta_l = l_1 - l_2
176
+ delta_a = a_1 - a_2
177
+ delta_b = b_1 - b_2
178
+ c_1 = sqrt(a_1 ** 2 + b_1 ** 2)
179
+ c_2 = sqrt(a_2 ** 2 + b_2 ** 2)
180
+ delta_c = c_1 - c_2
181
+ delta_h = sqrt(delta_a ** 2 + delta_b ** 2 + delta_c ** 2)
182
+ s_c = 1 + k_1 * c_1
183
+ s_h = 1 + k_2 * c_1
184
+
185
+ return ((delta_l / (k_l * s_l)) ** 2 + # pylint: disable=superfluous-parens
186
+ (delta_c / (k_c * s_c)) ** 2 +
187
+ (delta_h / (k_h * s_h)) ** 2)
188
+
189
+
190
+ def dist_cie2000(rgb1, rgb2):
191
+ # pylint: disable=too-many-locals
192
+ """
193
+ Determine distance between two rgb colors using the CIE2000 algorithm.
194
+
195
+ :arg tuple rgb1: RGB color definition
196
+ :arg tuple rgb2: RGB color definition
197
+ :returns: Square of the distance between provided colors
198
+ :rtype: float
199
+
200
+ For efficiency, the square of the distance is returned
201
+ which is sufficient for comparisons
202
+ """
203
+ s_l = k_l = k_c = k_h = 1
204
+
205
+ l_1, a_1, b_1 = rgb_to_lab(*rgb1)
206
+ l_2, a_2, b_2 = rgb_to_lab(*rgb2)
207
+
208
+ delta_l = l_2 - l_1
209
+ l_mean = (l_1 + l_2) / 2
210
+
211
+ c_1 = sqrt(a_1 ** 2 + b_1 ** 2)
212
+ c_2 = sqrt(a_2 ** 2 + b_2 ** 2)
213
+ c_mean = (c_1 + c_2) / 2
214
+ delta_c = c_1 - c_2
215
+
216
+ g_x = sqrt(c_mean ** 7 / (c_mean ** 7 + 25 ** 7))
217
+ h_1 = atan2(b_1, a_1 + (a_1 / 2) * (1 - g_x)) % 360
218
+ h_2 = atan2(b_2, a_2 + (a_2 / 2) * (1 - g_x)) % 360
219
+
220
+ if 0 in (c_1, c_2):
221
+ delta_h_prime = 0
222
+ h_mean = h_1 + h_2
223
+ else:
224
+ delta_h_prime = h_2 - h_1
225
+ if abs(delta_h_prime) <= 180:
226
+ h_mean = (h_1 + h_2) / 2
227
+ else:
228
+ if h_2 <= h_1:
229
+ delta_h_prime += 360
230
+ else:
231
+ delta_h_prime -= 360
232
+ h_mean = (h_1 + h_2 + 360) / 2 if h_1 + h_2 < 360 else (h_1 + h_2 - 360) / 2
233
+
234
+ delta_h = 2 * sqrt(c_1 * c_2) * sin(delta_h_prime / 2)
235
+
236
+ t_x = (1 -
237
+ 0.17 * cos(h_mean - 30) +
238
+ 0.24 * cos(2 * h_mean) +
239
+ 0.32 * cos(3 * h_mean + 6) -
240
+ 0.20 * cos(4 * h_mean - 63))
241
+
242
+ s_l = 1 + (0.015 * (l_mean - 50) ** 2) / sqrt(20 + (l_mean - 50) ** 2)
243
+ s_c = 1 + 0.045 * c_mean
244
+ s_h = 1 + 0.015 * c_mean * t_x
245
+ r_t = -2 * g_x * sin(abs(60 * exp(-1 * abs((delta_h - 275) / 25) ** 2)))
246
+
247
+ delta_l = delta_l / (k_l * s_l)
248
+ delta_c = delta_c / (k_c * s_c)
249
+ delta_h = delta_h / (k_h * s_h)
250
+
251
+ return delta_l ** 2 + delta_c ** 2 + delta_h ** 2 + r_t * delta_c * delta_h
252
+
253
+
254
+ COLOR_DISTANCE_ALGORITHMS = {'rgb': dist_rgb,
255
+ 'rgb-weighted': dist_rgb_weighted,
256
+ 'cie76': dist_cie76,
257
+ 'cie94': dist_cie94,
258
+ 'cie2000': dist_cie2000}
vllm/lib/python3.10/site-packages/blessed/color.pyi ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # std imports
2
+ from typing import Dict, Tuple, Callable
3
+
4
+ _RGB = Tuple[int, int, int]
5
+
6
+ def rgb_to_xyz(red: int, green: int, blue: int) -> Tuple[float, float, float]: ...
7
+ def xyz_to_lab(
8
+ x_val: float, y_val: float, z_val: float
9
+ ) -> Tuple[float, float, float]: ...
10
+ def rgb_to_lab(red: int, green: int, blue: int) -> Tuple[float, float, float]: ...
11
+ def dist_rgb(rgb1: _RGB, rgb2: _RGB) -> float: ...
12
+ def dist_rgb_weighted(rgb1: _RGB, rgb2: _RGB) -> float: ...
13
+ def dist_cie76(rgb1: _RGB, rgb2: _RGB) -> float: ...
14
+ def dist_cie94(rgb1: _RGB, rgb2: _RGB) -> float: ...
15
+ def dist_cie2000(rgb1: _RGB, rgb2: _RGB) -> float: ...
16
+
17
+ COLOR_DISTANCE_ALGORITHMS: Dict[str, Callable[[_RGB, _RGB], float]]
vllm/lib/python3.10/site-packages/blessed/colorspace.py ADDED
@@ -0,0 +1,973 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Color reference data.
3
+
4
+ References,
5
+
6
+ - https://github.com/freedesktop/xorg-rgb/blob/master/rgb.txt
7
+ - https://github.com/ThomasDickey/xterm-snapshots/blob/master/256colres.h
8
+ - https://github.com/ThomasDickey/xterm-snapshots/blob/master/XTerm-col.ad
9
+ - https://en.wikipedia.org/wiki/ANSI_escape_code#Colors
10
+ - https://gist.github.com/XVilka/8346728
11
+ - https://devblogs.microsoft.com/commandline/24-bit-color-in-the-windows-console/
12
+ - http://jdebp.uk/Softwares/nosh/guide/TerminalCapabilities.html
13
+ """
14
+
15
+ # std imports
16
+ import collections
17
+
18
+ __all__ = (
19
+ 'CGA_COLORS',
20
+ 'RGBColor',
21
+ 'RGB_256TABLE',
22
+ 'X11_COLORNAMES_TO_RGB',
23
+ )
24
+
25
+ CGA_COLORS = {'black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white'}
26
+
27
+
28
+ class RGBColor(collections.namedtuple("RGBColor", ["red", "green", "blue"])):
29
+ """Named tuple for an RGB color definition."""
30
+
31
+ def __str__(self):
32
+ return '#{0:02x}{1:02x}{2:02x}'.format(*self)
33
+
34
+
35
+ #: X11 Color names to (XTerm-defined) RGB values from xorg-rgb/rgb.txt
36
+ X11_COLORNAMES_TO_RGB = {
37
+ 'aliceblue': RGBColor(240, 248, 255),
38
+ 'antiquewhite': RGBColor(250, 235, 215),
39
+ 'antiquewhite1': RGBColor(255, 239, 219),
40
+ 'antiquewhite2': RGBColor(238, 223, 204),
41
+ 'antiquewhite3': RGBColor(205, 192, 176),
42
+ 'antiquewhite4': RGBColor(139, 131, 120),
43
+ 'aqua': RGBColor(0, 255, 255),
44
+ 'aquamarine': RGBColor(127, 255, 212),
45
+ 'aquamarine1': RGBColor(127, 255, 212),
46
+ 'aquamarine2': RGBColor(118, 238, 198),
47
+ 'aquamarine3': RGBColor(102, 205, 170),
48
+ 'aquamarine4': RGBColor(69, 139, 116),
49
+ 'azure': RGBColor(240, 255, 255),
50
+ 'azure1': RGBColor(240, 255, 255),
51
+ 'azure2': RGBColor(224, 238, 238),
52
+ 'azure3': RGBColor(193, 205, 205),
53
+ 'azure4': RGBColor(131, 139, 139),
54
+ 'beige': RGBColor(245, 245, 220),
55
+ 'bisque': RGBColor(255, 228, 196),
56
+ 'bisque1': RGBColor(255, 228, 196),
57
+ 'bisque2': RGBColor(238, 213, 183),
58
+ 'bisque3': RGBColor(205, 183, 158),
59
+ 'bisque4': RGBColor(139, 125, 107),
60
+ 'black': RGBColor(0, 0, 0),
61
+ 'blanchedalmond': RGBColor(255, 235, 205),
62
+ 'blue': RGBColor(0, 0, 255),
63
+ 'blue1': RGBColor(0, 0, 255),
64
+ 'blue2': RGBColor(0, 0, 238),
65
+ 'blue3': RGBColor(0, 0, 205),
66
+ 'blue4': RGBColor(0, 0, 139),
67
+ 'blueviolet': RGBColor(138, 43, 226),
68
+ 'brown': RGBColor(165, 42, 42),
69
+ 'brown1': RGBColor(255, 64, 64),
70
+ 'brown2': RGBColor(238, 59, 59),
71
+ 'brown3': RGBColor(205, 51, 51),
72
+ 'brown4': RGBColor(139, 35, 35),
73
+ 'burlywood': RGBColor(222, 184, 135),
74
+ 'burlywood1': RGBColor(255, 211, 155),
75
+ 'burlywood2': RGBColor(238, 197, 145),
76
+ 'burlywood3': RGBColor(205, 170, 125),
77
+ 'burlywood4': RGBColor(139, 115, 85),
78
+ 'cadetblue': RGBColor(95, 158, 160),
79
+ 'cadetblue1': RGBColor(152, 245, 255),
80
+ 'cadetblue2': RGBColor(142, 229, 238),
81
+ 'cadetblue3': RGBColor(122, 197, 205),
82
+ 'cadetblue4': RGBColor(83, 134, 139),
83
+ 'chartreuse': RGBColor(127, 255, 0),
84
+ 'chartreuse1': RGBColor(127, 255, 0),
85
+ 'chartreuse2': RGBColor(118, 238, 0),
86
+ 'chartreuse3': RGBColor(102, 205, 0),
87
+ 'chartreuse4': RGBColor(69, 139, 0),
88
+ 'chocolate': RGBColor(210, 105, 30),
89
+ 'chocolate1': RGBColor(255, 127, 36),
90
+ 'chocolate2': RGBColor(238, 118, 33),
91
+ 'chocolate3': RGBColor(205, 102, 29),
92
+ 'chocolate4': RGBColor(139, 69, 19),
93
+ 'coral': RGBColor(255, 127, 80),
94
+ 'coral1': RGBColor(255, 114, 86),
95
+ 'coral2': RGBColor(238, 106, 80),
96
+ 'coral3': RGBColor(205, 91, 69),
97
+ 'coral4': RGBColor(139, 62, 47),
98
+ 'cornflowerblue': RGBColor(100, 149, 237),
99
+ 'cornsilk': RGBColor(255, 248, 220),
100
+ 'cornsilk1': RGBColor(255, 248, 220),
101
+ 'cornsilk2': RGBColor(238, 232, 205),
102
+ 'cornsilk3': RGBColor(205, 200, 177),
103
+ 'cornsilk4': RGBColor(139, 136, 120),
104
+ 'crimson': RGBColor(220, 20, 60),
105
+ 'cyan': RGBColor(0, 255, 255),
106
+ 'cyan1': RGBColor(0, 255, 255),
107
+ 'cyan2': RGBColor(0, 238, 238),
108
+ 'cyan3': RGBColor(0, 205, 205),
109
+ 'cyan4': RGBColor(0, 139, 139),
110
+ 'darkblue': RGBColor(0, 0, 139),
111
+ 'darkcyan': RGBColor(0, 139, 139),
112
+ 'darkgoldenrod': RGBColor(184, 134, 11),
113
+ 'darkgoldenrod1': RGBColor(255, 185, 15),
114
+ 'darkgoldenrod2': RGBColor(238, 173, 14),
115
+ 'darkgoldenrod3': RGBColor(205, 149, 12),
116
+ 'darkgoldenrod4': RGBColor(139, 101, 8),
117
+ 'darkgray': RGBColor(169, 169, 169),
118
+ 'darkgreen': RGBColor(0, 100, 0),
119
+ 'darkgrey': RGBColor(169, 169, 169),
120
+ 'darkkhaki': RGBColor(189, 183, 107),
121
+ 'darkmagenta': RGBColor(139, 0, 139),
122
+ 'darkolivegreen': RGBColor(85, 107, 47),
123
+ 'darkolivegreen1': RGBColor(202, 255, 112),
124
+ 'darkolivegreen2': RGBColor(188, 238, 104),
125
+ 'darkolivegreen3': RGBColor(162, 205, 90),
126
+ 'darkolivegreen4': RGBColor(110, 139, 61),
127
+ 'darkorange': RGBColor(255, 140, 0),
128
+ 'darkorange1': RGBColor(255, 127, 0),
129
+ 'darkorange2': RGBColor(238, 118, 0),
130
+ 'darkorange3': RGBColor(205, 102, 0),
131
+ 'darkorange4': RGBColor(139, 69, 0),
132
+ 'darkorchid': RGBColor(153, 50, 204),
133
+ 'darkorchid1': RGBColor(191, 62, 255),
134
+ 'darkorchid2': RGBColor(178, 58, 238),
135
+ 'darkorchid3': RGBColor(154, 50, 205),
136
+ 'darkorchid4': RGBColor(104, 34, 139),
137
+ 'darkred': RGBColor(139, 0, 0),
138
+ 'darksalmon': RGBColor(233, 150, 122),
139
+ 'darkseagreen': RGBColor(143, 188, 143),
140
+ 'darkseagreen1': RGBColor(193, 255, 193),
141
+ 'darkseagreen2': RGBColor(180, 238, 180),
142
+ 'darkseagreen3': RGBColor(155, 205, 155),
143
+ 'darkseagreen4': RGBColor(105, 139, 105),
144
+ 'darkslateblue': RGBColor(72, 61, 139),
145
+ 'darkslategray': RGBColor(47, 79, 79),
146
+ 'darkslategray1': RGBColor(151, 255, 255),
147
+ 'darkslategray2': RGBColor(141, 238, 238),
148
+ 'darkslategray3': RGBColor(121, 205, 205),
149
+ 'darkslategray4': RGBColor(82, 139, 139),
150
+ 'darkslategrey': RGBColor(47, 79, 79),
151
+ 'darkturquoise': RGBColor(0, 206, 209),
152
+ 'darkviolet': RGBColor(148, 0, 211),
153
+ 'deeppink': RGBColor(255, 20, 147),
154
+ 'deeppink1': RGBColor(255, 20, 147),
155
+ 'deeppink2': RGBColor(238, 18, 137),
156
+ 'deeppink3': RGBColor(205, 16, 118),
157
+ 'deeppink4': RGBColor(139, 10, 80),
158
+ 'deepskyblue': RGBColor(0, 191, 255),
159
+ 'deepskyblue1': RGBColor(0, 191, 255),
160
+ 'deepskyblue2': RGBColor(0, 178, 238),
161
+ 'deepskyblue3': RGBColor(0, 154, 205),
162
+ 'deepskyblue4': RGBColor(0, 104, 139),
163
+ 'dimgray': RGBColor(105, 105, 105),
164
+ 'dimgrey': RGBColor(105, 105, 105),
165
+ 'dodgerblue': RGBColor(30, 144, 255),
166
+ 'dodgerblue1': RGBColor(30, 144, 255),
167
+ 'dodgerblue2': RGBColor(28, 134, 238),
168
+ 'dodgerblue3': RGBColor(24, 116, 205),
169
+ 'dodgerblue4': RGBColor(16, 78, 139),
170
+ 'firebrick': RGBColor(178, 34, 34),
171
+ 'firebrick1': RGBColor(255, 48, 48),
172
+ 'firebrick2': RGBColor(238, 44, 44),
173
+ 'firebrick3': RGBColor(205, 38, 38),
174
+ 'firebrick4': RGBColor(139, 26, 26),
175
+ 'floralwhite': RGBColor(255, 250, 240),
176
+ 'forestgreen': RGBColor(34, 139, 34),
177
+ 'fuchsia': RGBColor(255, 0, 255),
178
+ 'gainsboro': RGBColor(220, 220, 220),
179
+ 'ghostwhite': RGBColor(248, 248, 255),
180
+ 'gold': RGBColor(255, 215, 0),
181
+ 'gold1': RGBColor(255, 215, 0),
182
+ 'gold2': RGBColor(238, 201, 0),
183
+ 'gold3': RGBColor(205, 173, 0),
184
+ 'gold4': RGBColor(139, 117, 0),
185
+ 'goldenrod': RGBColor(218, 165, 32),
186
+ 'goldenrod1': RGBColor(255, 193, 37),
187
+ 'goldenrod2': RGBColor(238, 180, 34),
188
+ 'goldenrod3': RGBColor(205, 155, 29),
189
+ 'goldenrod4': RGBColor(139, 105, 20),
190
+ 'gray': RGBColor(190, 190, 190),
191
+ 'gray0': RGBColor(0, 0, 0),
192
+ 'gray1': RGBColor(3, 3, 3),
193
+ 'gray10': RGBColor(26, 26, 26),
194
+ 'gray100': RGBColor(255, 255, 255),
195
+ 'gray11': RGBColor(28, 28, 28),
196
+ 'gray12': RGBColor(31, 31, 31),
197
+ 'gray13': RGBColor(33, 33, 33),
198
+ 'gray14': RGBColor(36, 36, 36),
199
+ 'gray15': RGBColor(38, 38, 38),
200
+ 'gray16': RGBColor(41, 41, 41),
201
+ 'gray17': RGBColor(43, 43, 43),
202
+ 'gray18': RGBColor(46, 46, 46),
203
+ 'gray19': RGBColor(48, 48, 48),
204
+ 'gray2': RGBColor(5, 5, 5),
205
+ 'gray20': RGBColor(51, 51, 51),
206
+ 'gray21': RGBColor(54, 54, 54),
207
+ 'gray22': RGBColor(56, 56, 56),
208
+ 'gray23': RGBColor(59, 59, 59),
209
+ 'gray24': RGBColor(61, 61, 61),
210
+ 'gray25': RGBColor(64, 64, 64),
211
+ 'gray26': RGBColor(66, 66, 66),
212
+ 'gray27': RGBColor(69, 69, 69),
213
+ 'gray28': RGBColor(71, 71, 71),
214
+ 'gray29': RGBColor(74, 74, 74),
215
+ 'gray3': RGBColor(8, 8, 8),
216
+ 'gray30': RGBColor(77, 77, 77),
217
+ 'gray31': RGBColor(79, 79, 79),
218
+ 'gray32': RGBColor(82, 82, 82),
219
+ 'gray33': RGBColor(84, 84, 84),
220
+ 'gray34': RGBColor(87, 87, 87),
221
+ 'gray35': RGBColor(89, 89, 89),
222
+ 'gray36': RGBColor(92, 92, 92),
223
+ 'gray37': RGBColor(94, 94, 94),
224
+ 'gray38': RGBColor(97, 97, 97),
225
+ 'gray39': RGBColor(99, 99, 99),
226
+ 'gray4': RGBColor(10, 10, 10),
227
+ 'gray40': RGBColor(102, 102, 102),
228
+ 'gray41': RGBColor(105, 105, 105),
229
+ 'gray42': RGBColor(107, 107, 107),
230
+ 'gray43': RGBColor(110, 110, 110),
231
+ 'gray44': RGBColor(112, 112, 112),
232
+ 'gray45': RGBColor(115, 115, 115),
233
+ 'gray46': RGBColor(117, 117, 117),
234
+ 'gray47': RGBColor(120, 120, 120),
235
+ 'gray48': RGBColor(122, 122, 122),
236
+ 'gray49': RGBColor(125, 125, 125),
237
+ 'gray5': RGBColor(13, 13, 13),
238
+ 'gray50': RGBColor(127, 127, 127),
239
+ 'gray51': RGBColor(130, 130, 130),
240
+ 'gray52': RGBColor(133, 133, 133),
241
+ 'gray53': RGBColor(135, 135, 135),
242
+ 'gray54': RGBColor(138, 138, 138),
243
+ 'gray55': RGBColor(140, 140, 140),
244
+ 'gray56': RGBColor(143, 143, 143),
245
+ 'gray57': RGBColor(145, 145, 145),
246
+ 'gray58': RGBColor(148, 148, 148),
247
+ 'gray59': RGBColor(150, 150, 150),
248
+ 'gray6': RGBColor(15, 15, 15),
249
+ 'gray60': RGBColor(153, 153, 153),
250
+ 'gray61': RGBColor(156, 156, 156),
251
+ 'gray62': RGBColor(158, 158, 158),
252
+ 'gray63': RGBColor(161, 161, 161),
253
+ 'gray64': RGBColor(163, 163, 163),
254
+ 'gray65': RGBColor(166, 166, 166),
255
+ 'gray66': RGBColor(168, 168, 168),
256
+ 'gray67': RGBColor(171, 171, 171),
257
+ 'gray68': RGBColor(173, 173, 173),
258
+ 'gray69': RGBColor(176, 176, 176),
259
+ 'gray7': RGBColor(18, 18, 18),
260
+ 'gray70': RGBColor(179, 179, 179),
261
+ 'gray71': RGBColor(181, 181, 181),
262
+ 'gray72': RGBColor(184, 184, 184),
263
+ 'gray73': RGBColor(186, 186, 186),
264
+ 'gray74': RGBColor(189, 189, 189),
265
+ 'gray75': RGBColor(191, 191, 191),
266
+ 'gray76': RGBColor(194, 194, 194),
267
+ 'gray77': RGBColor(196, 196, 196),
268
+ 'gray78': RGBColor(199, 199, 199),
269
+ 'gray79': RGBColor(201, 201, 201),
270
+ 'gray8': RGBColor(20, 20, 20),
271
+ 'gray80': RGBColor(204, 204, 204),
272
+ 'gray81': RGBColor(207, 207, 207),
273
+ 'gray82': RGBColor(209, 209, 209),
274
+ 'gray83': RGBColor(212, 212, 212),
275
+ 'gray84': RGBColor(214, 214, 214),
276
+ 'gray85': RGBColor(217, 217, 217),
277
+ 'gray86': RGBColor(219, 219, 219),
278
+ 'gray87': RGBColor(222, 222, 222),
279
+ 'gray88': RGBColor(224, 224, 224),
280
+ 'gray89': RGBColor(227, 227, 227),
281
+ 'gray9': RGBColor(23, 23, 23),
282
+ 'gray90': RGBColor(229, 229, 229),
283
+ 'gray91': RGBColor(232, 232, 232),
284
+ 'gray92': RGBColor(235, 235, 235),
285
+ 'gray93': RGBColor(237, 237, 237),
286
+ 'gray94': RGBColor(240, 240, 240),
287
+ 'gray95': RGBColor(242, 242, 242),
288
+ 'gray96': RGBColor(245, 245, 245),
289
+ 'gray97': RGBColor(247, 247, 247),
290
+ 'gray98': RGBColor(250, 250, 250),
291
+ 'gray99': RGBColor(252, 252, 252),
292
+ 'green': RGBColor(0, 255, 0),
293
+ 'green1': RGBColor(0, 255, 0),
294
+ 'green2': RGBColor(0, 238, 0),
295
+ 'green3': RGBColor(0, 205, 0),
296
+ 'green4': RGBColor(0, 139, 0),
297
+ 'greenyellow': RGBColor(173, 255, 47),
298
+ 'grey': RGBColor(190, 190, 190),
299
+ 'grey0': RGBColor(0, 0, 0),
300
+ 'grey1': RGBColor(3, 3, 3),
301
+ 'grey10': RGBColor(26, 26, 26),
302
+ 'grey100': RGBColor(255, 255, 255),
303
+ 'grey11': RGBColor(28, 28, 28),
304
+ 'grey12': RGBColor(31, 31, 31),
305
+ 'grey13': RGBColor(33, 33, 33),
306
+ 'grey14': RGBColor(36, 36, 36),
307
+ 'grey15': RGBColor(38, 38, 38),
308
+ 'grey16': RGBColor(41, 41, 41),
309
+ 'grey17': RGBColor(43, 43, 43),
310
+ 'grey18': RGBColor(46, 46, 46),
311
+ 'grey19': RGBColor(48, 48, 48),
312
+ 'grey2': RGBColor(5, 5, 5),
313
+ 'grey20': RGBColor(51, 51, 51),
314
+ 'grey21': RGBColor(54, 54, 54),
315
+ 'grey22': RGBColor(56, 56, 56),
316
+ 'grey23': RGBColor(59, 59, 59),
317
+ 'grey24': RGBColor(61, 61, 61),
318
+ 'grey25': RGBColor(64, 64, 64),
319
+ 'grey26': RGBColor(66, 66, 66),
320
+ 'grey27': RGBColor(69, 69, 69),
321
+ 'grey28': RGBColor(71, 71, 71),
322
+ 'grey29': RGBColor(74, 74, 74),
323
+ 'grey3': RGBColor(8, 8, 8),
324
+ 'grey30': RGBColor(77, 77, 77),
325
+ 'grey31': RGBColor(79, 79, 79),
326
+ 'grey32': RGBColor(82, 82, 82),
327
+ 'grey33': RGBColor(84, 84, 84),
328
+ 'grey34': RGBColor(87, 87, 87),
329
+ 'grey35': RGBColor(89, 89, 89),
330
+ 'grey36': RGBColor(92, 92, 92),
331
+ 'grey37': RGBColor(94, 94, 94),
332
+ 'grey38': RGBColor(97, 97, 97),
333
+ 'grey39': RGBColor(99, 99, 99),
334
+ 'grey4': RGBColor(10, 10, 10),
335
+ 'grey40': RGBColor(102, 102, 102),
336
+ 'grey41': RGBColor(105, 105, 105),
337
+ 'grey42': RGBColor(107, 107, 107),
338
+ 'grey43': RGBColor(110, 110, 110),
339
+ 'grey44': RGBColor(112, 112, 112),
340
+ 'grey45': RGBColor(115, 115, 115),
341
+ 'grey46': RGBColor(117, 117, 117),
342
+ 'grey47': RGBColor(120, 120, 120),
343
+ 'grey48': RGBColor(122, 122, 122),
344
+ 'grey49': RGBColor(125, 125, 125),
345
+ 'grey5': RGBColor(13, 13, 13),
346
+ 'grey50': RGBColor(127, 127, 127),
347
+ 'grey51': RGBColor(130, 130, 130),
348
+ 'grey52': RGBColor(133, 133, 133),
349
+ 'grey53': RGBColor(135, 135, 135),
350
+ 'grey54': RGBColor(138, 138, 138),
351
+ 'grey55': RGBColor(140, 140, 140),
352
+ 'grey56': RGBColor(143, 143, 143),
353
+ 'grey57': RGBColor(145, 145, 145),
354
+ 'grey58': RGBColor(148, 148, 148),
355
+ 'grey59': RGBColor(150, 150, 150),
356
+ 'grey6': RGBColor(15, 15, 15),
357
+ 'grey60': RGBColor(153, 153, 153),
358
+ 'grey61': RGBColor(156, 156, 156),
359
+ 'grey62': RGBColor(158, 158, 158),
360
+ 'grey63': RGBColor(161, 161, 161),
361
+ 'grey64': RGBColor(163, 163, 163),
362
+ 'grey65': RGBColor(166, 166, 166),
363
+ 'grey66': RGBColor(168, 168, 168),
364
+ 'grey67': RGBColor(171, 171, 171),
365
+ 'grey68': RGBColor(173, 173, 173),
366
+ 'grey69': RGBColor(176, 176, 176),
367
+ 'grey7': RGBColor(18, 18, 18),
368
+ 'grey70': RGBColor(179, 179, 179),
369
+ 'grey71': RGBColor(181, 181, 181),
370
+ 'grey72': RGBColor(184, 184, 184),
371
+ 'grey73': RGBColor(186, 186, 186),
372
+ 'grey74': RGBColor(189, 189, 189),
373
+ 'grey75': RGBColor(191, 191, 191),
374
+ 'grey76': RGBColor(194, 194, 194),
375
+ 'grey77': RGBColor(196, 196, 196),
376
+ 'grey78': RGBColor(199, 199, 199),
377
+ 'grey79': RGBColor(201, 201, 201),
378
+ 'grey8': RGBColor(20, 20, 20),
379
+ 'grey80': RGBColor(204, 204, 204),
380
+ 'grey81': RGBColor(207, 207, 207),
381
+ 'grey82': RGBColor(209, 209, 209),
382
+ 'grey83': RGBColor(212, 212, 212),
383
+ 'grey84': RGBColor(214, 214, 214),
384
+ 'grey85': RGBColor(217, 217, 217),
385
+ 'grey86': RGBColor(219, 219, 219),
386
+ 'grey87': RGBColor(222, 222, 222),
387
+ 'grey88': RGBColor(224, 224, 224),
388
+ 'grey89': RGBColor(227, 227, 227),
389
+ 'grey9': RGBColor(23, 23, 23),
390
+ 'grey90': RGBColor(229, 229, 229),
391
+ 'grey91': RGBColor(232, 232, 232),
392
+ 'grey92': RGBColor(235, 235, 235),
393
+ 'grey93': RGBColor(237, 237, 237),
394
+ 'grey94': RGBColor(240, 240, 240),
395
+ 'grey95': RGBColor(242, 242, 242),
396
+ 'grey96': RGBColor(245, 245, 245),
397
+ 'grey97': RGBColor(247, 247, 247),
398
+ 'grey98': RGBColor(250, 250, 250),
399
+ 'grey99': RGBColor(252, 252, 252),
400
+ 'honeydew': RGBColor(240, 255, 240),
401
+ 'honeydew1': RGBColor(240, 255, 240),
402
+ 'honeydew2': RGBColor(224, 238, 224),
403
+ 'honeydew3': RGBColor(193, 205, 193),
404
+ 'honeydew4': RGBColor(131, 139, 131),
405
+ 'hotpink': RGBColor(255, 105, 180),
406
+ 'hotpink1': RGBColor(255, 110, 180),
407
+ 'hotpink2': RGBColor(238, 106, 167),
408
+ 'hotpink3': RGBColor(205, 96, 144),
409
+ 'hotpink4': RGBColor(139, 58, 98),
410
+ 'indianred': RGBColor(205, 92, 92),
411
+ 'indianred1': RGBColor(255, 106, 106),
412
+ 'indianred2': RGBColor(238, 99, 99),
413
+ 'indianred3': RGBColor(205, 85, 85),
414
+ 'indianred4': RGBColor(139, 58, 58),
415
+ 'indigo': RGBColor(75, 0, 130),
416
+ 'ivory': RGBColor(255, 255, 240),
417
+ 'ivory1': RGBColor(255, 255, 240),
418
+ 'ivory2': RGBColor(238, 238, 224),
419
+ 'ivory3': RGBColor(205, 205, 193),
420
+ 'ivory4': RGBColor(139, 139, 131),
421
+ 'khaki': RGBColor(240, 230, 140),
422
+ 'khaki1': RGBColor(255, 246, 143),
423
+ 'khaki2': RGBColor(238, 230, 133),
424
+ 'khaki3': RGBColor(205, 198, 115),
425
+ 'khaki4': RGBColor(139, 134, 78),
426
+ 'lavender': RGBColor(230, 230, 250),
427
+ 'lavenderblush': RGBColor(255, 240, 245),
428
+ 'lavenderblush1': RGBColor(255, 240, 245),
429
+ 'lavenderblush2': RGBColor(238, 224, 229),
430
+ 'lavenderblush3': RGBColor(205, 193, 197),
431
+ 'lavenderblush4': RGBColor(139, 131, 134),
432
+ 'lawngreen': RGBColor(124, 252, 0),
433
+ 'lemonchiffon': RGBColor(255, 250, 205),
434
+ 'lemonchiffon1': RGBColor(255, 250, 205),
435
+ 'lemonchiffon2': RGBColor(238, 233, 191),
436
+ 'lemonchiffon3': RGBColor(205, 201, 165),
437
+ 'lemonchiffon4': RGBColor(139, 137, 112),
438
+ 'lightblue': RGBColor(173, 216, 230),
439
+ 'lightblue1': RGBColor(191, 239, 255),
440
+ 'lightblue2': RGBColor(178, 223, 238),
441
+ 'lightblue3': RGBColor(154, 192, 205),
442
+ 'lightblue4': RGBColor(104, 131, 139),
443
+ 'lightcoral': RGBColor(240, 128, 128),
444
+ 'lightcyan': RGBColor(224, 255, 255),
445
+ 'lightcyan1': RGBColor(224, 255, 255),
446
+ 'lightcyan2': RGBColor(209, 238, 238),
447
+ 'lightcyan3': RGBColor(180, 205, 205),
448
+ 'lightcyan4': RGBColor(122, 139, 139),
449
+ 'lightgoldenrod': RGBColor(238, 221, 130),
450
+ 'lightgoldenrod1': RGBColor(255, 236, 139),
451
+ 'lightgoldenrod2': RGBColor(238, 220, 130),
452
+ 'lightgoldenrod3': RGBColor(205, 190, 112),
453
+ 'lightgoldenrod4': RGBColor(139, 129, 76),
454
+ 'lightgoldenrodyellow': RGBColor(250, 250, 210),
455
+ 'lightgray': RGBColor(211, 211, 211),
456
+ 'lightgreen': RGBColor(144, 238, 144),
457
+ 'lightgrey': RGBColor(211, 211, 211),
458
+ 'lightpink': RGBColor(255, 182, 193),
459
+ 'lightpink1': RGBColor(255, 174, 185),
460
+ 'lightpink2': RGBColor(238, 162, 173),
461
+ 'lightpink3': RGBColor(205, 140, 149),
462
+ 'lightpink4': RGBColor(139, 95, 101),
463
+ 'lightsalmon': RGBColor(255, 160, 122),
464
+ 'lightsalmon1': RGBColor(255, 160, 122),
465
+ 'lightsalmon2': RGBColor(238, 149, 114),
466
+ 'lightsalmon3': RGBColor(205, 129, 98),
467
+ 'lightsalmon4': RGBColor(139, 87, 66),
468
+ 'lightseagreen': RGBColor(32, 178, 170),
469
+ 'lightskyblue': RGBColor(135, 206, 250),
470
+ 'lightskyblue1': RGBColor(176, 226, 255),
471
+ 'lightskyblue2': RGBColor(164, 211, 238),
472
+ 'lightskyblue3': RGBColor(141, 182, 205),
473
+ 'lightskyblue4': RGBColor(96, 123, 139),
474
+ 'lightslateblue': RGBColor(132, 112, 255),
475
+ 'lightslategray': RGBColor(119, 136, 153),
476
+ 'lightslategrey': RGBColor(119, 136, 153),
477
+ 'lightsteelblue': RGBColor(176, 196, 222),
478
+ 'lightsteelblue1': RGBColor(202, 225, 255),
479
+ 'lightsteelblue2': RGBColor(188, 210, 238),
480
+ 'lightsteelblue3': RGBColor(162, 181, 205),
481
+ 'lightsteelblue4': RGBColor(110, 123, 139),
482
+ 'lightyellow': RGBColor(255, 255, 224),
483
+ 'lightyellow1': RGBColor(255, 255, 224),
484
+ 'lightyellow2': RGBColor(238, 238, 209),
485
+ 'lightyellow3': RGBColor(205, 205, 180),
486
+ 'lightyellow4': RGBColor(139, 139, 122),
487
+ 'lime': RGBColor(0, 255, 0),
488
+ 'limegreen': RGBColor(50, 205, 50),
489
+ 'linen': RGBColor(250, 240, 230),
490
+ 'magenta': RGBColor(255, 0, 255),
491
+ 'magenta1': RGBColor(255, 0, 255),
492
+ 'magenta2': RGBColor(238, 0, 238),
493
+ 'magenta3': RGBColor(205, 0, 205),
494
+ 'magenta4': RGBColor(139, 0, 139),
495
+ 'maroon': RGBColor(176, 48, 96),
496
+ 'maroon1': RGBColor(255, 52, 179),
497
+ 'maroon2': RGBColor(238, 48, 167),
498
+ 'maroon3': RGBColor(205, 41, 144),
499
+ 'maroon4': RGBColor(139, 28, 98),
500
+ 'mediumaquamarine': RGBColor(102, 205, 170),
501
+ 'mediumblue': RGBColor(0, 0, 205),
502
+ 'mediumorchid': RGBColor(186, 85, 211),
503
+ 'mediumorchid1': RGBColor(224, 102, 255),
504
+ 'mediumorchid2': RGBColor(209, 95, 238),
505
+ 'mediumorchid3': RGBColor(180, 82, 205),
506
+ 'mediumorchid4': RGBColor(122, 55, 139),
507
+ 'mediumpurple': RGBColor(147, 112, 219),
508
+ 'mediumpurple1': RGBColor(171, 130, 255),
509
+ 'mediumpurple2': RGBColor(159, 121, 238),
510
+ 'mediumpurple3': RGBColor(137, 104, 205),
511
+ 'mediumpurple4': RGBColor(93, 71, 139),
512
+ 'mediumseagreen': RGBColor(60, 179, 113),
513
+ 'mediumslateblue': RGBColor(123, 104, 238),
514
+ 'mediumspringgreen': RGBColor(0, 250, 154),
515
+ 'mediumturquoise': RGBColor(72, 209, 204),
516
+ 'mediumvioletred': RGBColor(199, 21, 133),
517
+ 'midnightblue': RGBColor(25, 25, 112),
518
+ 'mintcream': RGBColor(245, 255, 250),
519
+ 'mistyrose': RGBColor(255, 228, 225),
520
+ 'mistyrose1': RGBColor(255, 228, 225),
521
+ 'mistyrose2': RGBColor(238, 213, 210),
522
+ 'mistyrose3': RGBColor(205, 183, 181),
523
+ 'mistyrose4': RGBColor(139, 125, 123),
524
+ 'moccasin': RGBColor(255, 228, 181),
525
+ 'navajowhite': RGBColor(255, 222, 173),
526
+ 'navajowhite1': RGBColor(255, 222, 173),
527
+ 'navajowhite2': RGBColor(238, 207, 161),
528
+ 'navajowhite3': RGBColor(205, 179, 139),
529
+ 'navajowhite4': RGBColor(139, 121, 94),
530
+ 'navy': RGBColor(0, 0, 128),
531
+ 'navyblue': RGBColor(0, 0, 128),
532
+ 'oldlace': RGBColor(253, 245, 230),
533
+ 'olive': RGBColor(128, 128, 0),
534
+ 'olivedrab': RGBColor(107, 142, 35),
535
+ 'olivedrab1': RGBColor(192, 255, 62),
536
+ 'olivedrab2': RGBColor(179, 238, 58),
537
+ 'olivedrab3': RGBColor(154, 205, 50),
538
+ 'olivedrab4': RGBColor(105, 139, 34),
539
+ 'orange': RGBColor(255, 165, 0),
540
+ 'orange1': RGBColor(255, 165, 0),
541
+ 'orange2': RGBColor(238, 154, 0),
542
+ 'orange3': RGBColor(205, 133, 0),
543
+ 'orange4': RGBColor(139, 90, 0),
544
+ 'orangered': RGBColor(255, 69, 0),
545
+ 'orangered1': RGBColor(255, 69, 0),
546
+ 'orangered2': RGBColor(238, 64, 0),
547
+ 'orangered3': RGBColor(205, 55, 0),
548
+ 'orangered4': RGBColor(139, 37, 0),
549
+ 'orchid': RGBColor(218, 112, 214),
550
+ 'orchid1': RGBColor(255, 131, 250),
551
+ 'orchid2': RGBColor(238, 122, 233),
552
+ 'orchid3': RGBColor(205, 105, 201),
553
+ 'orchid4': RGBColor(139, 71, 137),
554
+ 'palegoldenrod': RGBColor(238, 232, 170),
555
+ 'palegreen': RGBColor(152, 251, 152),
556
+ 'palegreen1': RGBColor(154, 255, 154),
557
+ 'palegreen2': RGBColor(144, 238, 144),
558
+ 'palegreen3': RGBColor(124, 205, 124),
559
+ 'palegreen4': RGBColor(84, 139, 84),
560
+ 'paleturquoise': RGBColor(175, 238, 238),
561
+ 'paleturquoise1': RGBColor(187, 255, 255),
562
+ 'paleturquoise2': RGBColor(174, 238, 238),
563
+ 'paleturquoise3': RGBColor(150, 205, 205),
564
+ 'paleturquoise4': RGBColor(102, 139, 139),
565
+ 'palevioletred': RGBColor(219, 112, 147),
566
+ 'palevioletred1': RGBColor(255, 130, 171),
567
+ 'palevioletred2': RGBColor(238, 121, 159),
568
+ 'palevioletred3': RGBColor(205, 104, 137),
569
+ 'palevioletred4': RGBColor(139, 71, 93),
570
+ 'papayawhip': RGBColor(255, 239, 213),
571
+ 'peachpuff': RGBColor(255, 218, 185),
572
+ 'peachpuff1': RGBColor(255, 218, 185),
573
+ 'peachpuff2': RGBColor(238, 203, 173),
574
+ 'peachpuff3': RGBColor(205, 175, 149),
575
+ 'peachpuff4': RGBColor(139, 119, 101),
576
+ 'peru': RGBColor(205, 133, 63),
577
+ 'pink': RGBColor(255, 192, 203),
578
+ 'pink1': RGBColor(255, 181, 197),
579
+ 'pink2': RGBColor(238, 169, 184),
580
+ 'pink3': RGBColor(205, 145, 158),
581
+ 'pink4': RGBColor(139, 99, 108),
582
+ 'plum': RGBColor(221, 160, 221),
583
+ 'plum1': RGBColor(255, 187, 255),
584
+ 'plum2': RGBColor(238, 174, 238),
585
+ 'plum3': RGBColor(205, 150, 205),
586
+ 'plum4': RGBColor(139, 102, 139),
587
+ 'powderblue': RGBColor(176, 224, 230),
588
+ 'purple': RGBColor(160, 32, 240),
589
+ 'purple1': RGBColor(155, 48, 255),
590
+ 'purple2': RGBColor(145, 44, 238),
591
+ 'purple3': RGBColor(125, 38, 205),
592
+ 'purple4': RGBColor(85, 26, 139),
593
+ 'rebeccapurple': RGBColor(102, 51, 153),
594
+ 'red': RGBColor(255, 0, 0),
595
+ 'red1': RGBColor(255, 0, 0),
596
+ 'red2': RGBColor(238, 0, 0),
597
+ 'red3': RGBColor(205, 0, 0),
598
+ 'red4': RGBColor(139, 0, 0),
599
+ 'rosybrown': RGBColor(188, 143, 143),
600
+ 'rosybrown1': RGBColor(255, 193, 193),
601
+ 'rosybrown2': RGBColor(238, 180, 180),
602
+ 'rosybrown3': RGBColor(205, 155, 155),
603
+ 'rosybrown4': RGBColor(139, 105, 105),
604
+ 'royalblue': RGBColor(65, 105, 225),
605
+ 'royalblue1': RGBColor(72, 118, 255),
606
+ 'royalblue2': RGBColor(67, 110, 238),
607
+ 'royalblue3': RGBColor(58, 95, 205),
608
+ 'royalblue4': RGBColor(39, 64, 139),
609
+ 'saddlebrown': RGBColor(139, 69, 19),
610
+ 'salmon': RGBColor(250, 128, 114),
611
+ 'salmon1': RGBColor(255, 140, 105),
612
+ 'salmon2': RGBColor(238, 130, 98),
613
+ 'salmon3': RGBColor(205, 112, 84),
614
+ 'salmon4': RGBColor(139, 76, 57),
615
+ 'sandybrown': RGBColor(244, 164, 96),
616
+ 'seagreen': RGBColor(46, 139, 87),
617
+ 'seagreen1': RGBColor(84, 255, 159),
618
+ 'seagreen2': RGBColor(78, 238, 148),
619
+ 'seagreen3': RGBColor(67, 205, 128),
620
+ 'seagreen4': RGBColor(46, 139, 87),
621
+ 'seashell': RGBColor(255, 245, 238),
622
+ 'seashell1': RGBColor(255, 245, 238),
623
+ 'seashell2': RGBColor(238, 229, 222),
624
+ 'seashell3': RGBColor(205, 197, 191),
625
+ 'seashell4': RGBColor(139, 134, 130),
626
+ 'sienna': RGBColor(160, 82, 45),
627
+ 'sienna1': RGBColor(255, 130, 71),
628
+ 'sienna2': RGBColor(238, 121, 66),
629
+ 'sienna3': RGBColor(205, 104, 57),
630
+ 'sienna4': RGBColor(139, 71, 38),
631
+ 'silver': RGBColor(192, 192, 192),
632
+ 'skyblue': RGBColor(135, 206, 235),
633
+ 'skyblue1': RGBColor(135, 206, 255),
634
+ 'skyblue2': RGBColor(126, 192, 238),
635
+ 'skyblue3': RGBColor(108, 166, 205),
636
+ 'skyblue4': RGBColor(74, 112, 139),
637
+ 'slateblue': RGBColor(106, 90, 205),
638
+ 'slateblue1': RGBColor(131, 111, 255),
639
+ 'slateblue2': RGBColor(122, 103, 238),
640
+ 'slateblue3': RGBColor(105, 89, 205),
641
+ 'slateblue4': RGBColor(71, 60, 139),
642
+ 'slategray': RGBColor(112, 128, 144),
643
+ 'slategray1': RGBColor(198, 226, 255),
644
+ 'slategray2': RGBColor(185, 211, 238),
645
+ 'slategray3': RGBColor(159, 182, 205),
646
+ 'slategray4': RGBColor(108, 123, 139),
647
+ 'slategrey': RGBColor(112, 128, 144),
648
+ 'snow': RGBColor(255, 250, 250),
649
+ 'snow1': RGBColor(255, 250, 250),
650
+ 'snow2': RGBColor(238, 233, 233),
651
+ 'snow3': RGBColor(205, 201, 201),
652
+ 'snow4': RGBColor(139, 137, 137),
653
+ 'springgreen': RGBColor(0, 255, 127),
654
+ 'springgreen1': RGBColor(0, 255, 127),
655
+ 'springgreen2': RGBColor(0, 238, 118),
656
+ 'springgreen3': RGBColor(0, 205, 102),
657
+ 'springgreen4': RGBColor(0, 139, 69),
658
+ 'steelblue': RGBColor(70, 130, 180),
659
+ 'steelblue1': RGBColor(99, 184, 255),
660
+ 'steelblue2': RGBColor(92, 172, 238),
661
+ 'steelblue3': RGBColor(79, 148, 205),
662
+ 'steelblue4': RGBColor(54, 100, 139),
663
+ 'tan': RGBColor(210, 180, 140),
664
+ 'tan1': RGBColor(255, 165, 79),
665
+ 'tan2': RGBColor(238, 154, 73),
666
+ 'tan3': RGBColor(205, 133, 63),
667
+ 'tan4': RGBColor(139, 90, 43),
668
+ 'teal': RGBColor(0, 128, 128),
669
+ 'thistle': RGBColor(216, 191, 216),
670
+ 'thistle1': RGBColor(255, 225, 255),
671
+ 'thistle2': RGBColor(238, 210, 238),
672
+ 'thistle3': RGBColor(205, 181, 205),
673
+ 'thistle4': RGBColor(139, 123, 139),
674
+ 'tomato': RGBColor(255, 99, 71),
675
+ 'tomato1': RGBColor(255, 99, 71),
676
+ 'tomato2': RGBColor(238, 92, 66),
677
+ 'tomato3': RGBColor(205, 79, 57),
678
+ 'tomato4': RGBColor(139, 54, 38),
679
+ 'turquoise': RGBColor(64, 224, 208),
680
+ 'turquoise1': RGBColor(0, 245, 255),
681
+ 'turquoise2': RGBColor(0, 229, 238),
682
+ 'turquoise3': RGBColor(0, 197, 205),
683
+ 'turquoise4': RGBColor(0, 134, 139),
684
+ 'violet': RGBColor(238, 130, 238),
685
+ 'violetred': RGBColor(208, 32, 144),
686
+ 'violetred1': RGBColor(255, 62, 150),
687
+ 'violetred2': RGBColor(238, 58, 140),
688
+ 'violetred3': RGBColor(205, 50, 120),
689
+ 'violetred4': RGBColor(139, 34, 82),
690
+ 'webgray': RGBColor(128, 128, 128),
691
+ 'webgreen': RGBColor(0, 128, 0),
692
+ 'webgrey': RGBColor(128, 128, 128),
693
+ 'webmaroon': RGBColor(128, 0, 0),
694
+ 'webpurple': RGBColor(128, 0, 128),
695
+ 'wheat': RGBColor(245, 222, 179),
696
+ 'wheat1': RGBColor(255, 231, 186),
697
+ 'wheat2': RGBColor(238, 216, 174),
698
+ 'wheat3': RGBColor(205, 186, 150),
699
+ 'wheat4': RGBColor(139, 126, 102),
700
+ 'white': RGBColor(255, 255, 255),
701
+ 'whitesmoke': RGBColor(245, 245, 245),
702
+ 'x11gray': RGBColor(190, 190, 190),
703
+ 'x11green': RGBColor(0, 255, 0),
704
+ 'x11grey': RGBColor(190, 190, 190),
705
+ 'x11maroon': RGBColor(176, 48, 96),
706
+ 'x11purple': RGBColor(160, 32, 240),
707
+ 'yellow': RGBColor(255, 255, 0),
708
+ 'yellow1': RGBColor(255, 255, 0),
709
+ 'yellow2': RGBColor(238, 238, 0),
710
+ 'yellow3': RGBColor(205, 205, 0),
711
+ 'yellow4': RGBColor(139, 139, 0),
712
+ 'yellowgreen': RGBColor(154, 205, 50)
713
+ }
714
+
715
+ #: Curses color indices of 8, 16, and 256-color terminals
716
+ RGB_256TABLE = (
717
+ RGBColor(0, 0, 0),
718
+ RGBColor(205, 0, 0),
719
+ RGBColor(0, 205, 0),
720
+ RGBColor(205, 205, 0),
721
+ RGBColor(0, 0, 238),
722
+ RGBColor(205, 0, 205),
723
+ RGBColor(0, 205, 205),
724
+ RGBColor(229, 229, 229),
725
+ RGBColor(127, 127, 127),
726
+ RGBColor(255, 0, 0),
727
+ RGBColor(0, 255, 0),
728
+ RGBColor(255, 255, 0),
729
+ RGBColor(92, 92, 255),
730
+ RGBColor(255, 0, 255),
731
+ RGBColor(0, 255, 255),
732
+ RGBColor(255, 255, 255),
733
+ RGBColor(0, 0, 0),
734
+ RGBColor(0, 0, 95),
735
+ RGBColor(0, 0, 135),
736
+ RGBColor(0, 0, 175),
737
+ RGBColor(0, 0, 215),
738
+ RGBColor(0, 0, 255),
739
+ RGBColor(0, 95, 0),
740
+ RGBColor(0, 95, 95),
741
+ RGBColor(0, 95, 135),
742
+ RGBColor(0, 95, 175),
743
+ RGBColor(0, 95, 215),
744
+ RGBColor(0, 95, 255),
745
+ RGBColor(0, 135, 0),
746
+ RGBColor(0, 135, 95),
747
+ RGBColor(0, 135, 135),
748
+ RGBColor(0, 135, 175),
749
+ RGBColor(0, 135, 215),
750
+ RGBColor(0, 135, 255),
751
+ RGBColor(0, 175, 0),
752
+ RGBColor(0, 175, 95),
753
+ RGBColor(0, 175, 135),
754
+ RGBColor(0, 175, 175),
755
+ RGBColor(0, 175, 215),
756
+ RGBColor(0, 175, 255),
757
+ RGBColor(0, 215, 0),
758
+ RGBColor(0, 215, 95),
759
+ RGBColor(0, 215, 135),
760
+ RGBColor(0, 215, 175),
761
+ RGBColor(0, 215, 215),
762
+ RGBColor(0, 215, 255),
763
+ RGBColor(0, 255, 0),
764
+ RGBColor(0, 255, 95),
765
+ RGBColor(0, 255, 135),
766
+ RGBColor(0, 255, 175),
767
+ RGBColor(0, 255, 215),
768
+ RGBColor(0, 255, 255),
769
+ RGBColor(95, 0, 0),
770
+ RGBColor(95, 0, 95),
771
+ RGBColor(95, 0, 135),
772
+ RGBColor(95, 0, 175),
773
+ RGBColor(95, 0, 215),
774
+ RGBColor(95, 0, 255),
775
+ RGBColor(95, 95, 0),
776
+ RGBColor(95, 95, 95),
777
+ RGBColor(95, 95, 135),
778
+ RGBColor(95, 95, 175),
779
+ RGBColor(95, 95, 215),
780
+ RGBColor(95, 95, 255),
781
+ RGBColor(95, 135, 0),
782
+ RGBColor(95, 135, 95),
783
+ RGBColor(95, 135, 135),
784
+ RGBColor(95, 135, 175),
785
+ RGBColor(95, 135, 215),
786
+ RGBColor(95, 135, 255),
787
+ RGBColor(95, 175, 0),
788
+ RGBColor(95, 175, 95),
789
+ RGBColor(95, 175, 135),
790
+ RGBColor(95, 175, 175),
791
+ RGBColor(95, 175, 215),
792
+ RGBColor(95, 175, 255),
793
+ RGBColor(95, 215, 0),
794
+ RGBColor(95, 215, 95),
795
+ RGBColor(95, 215, 135),
796
+ RGBColor(95, 215, 175),
797
+ RGBColor(95, 215, 215),
798
+ RGBColor(95, 215, 255),
799
+ RGBColor(95, 255, 0),
800
+ RGBColor(95, 255, 95),
801
+ RGBColor(95, 255, 135),
802
+ RGBColor(95, 255, 175),
803
+ RGBColor(95, 255, 215),
804
+ RGBColor(95, 255, 255),
805
+ RGBColor(135, 0, 0),
806
+ RGBColor(135, 0, 95),
807
+ RGBColor(135, 0, 135),
808
+ RGBColor(135, 0, 175),
809
+ RGBColor(135, 0, 215),
810
+ RGBColor(135, 0, 255),
811
+ RGBColor(135, 95, 0),
812
+ RGBColor(135, 95, 95),
813
+ RGBColor(135, 95, 135),
814
+ RGBColor(135, 95, 175),
815
+ RGBColor(135, 95, 215),
816
+ RGBColor(135, 95, 255),
817
+ RGBColor(135, 135, 0),
818
+ RGBColor(135, 135, 95),
819
+ RGBColor(135, 135, 135),
820
+ RGBColor(135, 135, 175),
821
+ RGBColor(135, 135, 215),
822
+ RGBColor(135, 135, 255),
823
+ RGBColor(135, 175, 0),
824
+ RGBColor(135, 175, 95),
825
+ RGBColor(135, 175, 135),
826
+ RGBColor(135, 175, 175),
827
+ RGBColor(135, 175, 215),
828
+ RGBColor(135, 175, 255),
829
+ RGBColor(135, 215, 0),
830
+ RGBColor(135, 215, 95),
831
+ RGBColor(135, 215, 135),
832
+ RGBColor(135, 215, 175),
833
+ RGBColor(135, 215, 215),
834
+ RGBColor(135, 215, 255),
835
+ RGBColor(135, 255, 0),
836
+ RGBColor(135, 255, 95),
837
+ RGBColor(135, 255, 135),
838
+ RGBColor(135, 255, 175),
839
+ RGBColor(135, 255, 215),
840
+ RGBColor(135, 255, 255),
841
+ RGBColor(175, 0, 0),
842
+ RGBColor(175, 0, 95),
843
+ RGBColor(175, 0, 135),
844
+ RGBColor(175, 0, 175),
845
+ RGBColor(175, 0, 215),
846
+ RGBColor(175, 0, 255),
847
+ RGBColor(175, 95, 0),
848
+ RGBColor(175, 95, 95),
849
+ RGBColor(175, 95, 135),
850
+ RGBColor(175, 95, 175),
851
+ RGBColor(175, 95, 215),
852
+ RGBColor(175, 95, 255),
853
+ RGBColor(175, 135, 0),
854
+ RGBColor(175, 135, 95),
855
+ RGBColor(175, 135, 135),
856
+ RGBColor(175, 135, 175),
857
+ RGBColor(175, 135, 215),
858
+ RGBColor(175, 135, 255),
859
+ RGBColor(175, 175, 0),
860
+ RGBColor(175, 175, 95),
861
+ RGBColor(175, 175, 135),
862
+ RGBColor(175, 175, 175),
863
+ RGBColor(175, 175, 215),
864
+ RGBColor(175, 175, 255),
865
+ RGBColor(175, 215, 0),
866
+ RGBColor(175, 215, 95),
867
+ RGBColor(175, 215, 135),
868
+ RGBColor(175, 215, 175),
869
+ RGBColor(175, 215, 215),
870
+ RGBColor(175, 215, 255),
871
+ RGBColor(175, 255, 0),
872
+ RGBColor(175, 255, 95),
873
+ RGBColor(175, 255, 135),
874
+ RGBColor(175, 255, 175),
875
+ RGBColor(175, 255, 215),
876
+ RGBColor(175, 255, 255),
877
+ RGBColor(215, 0, 0),
878
+ RGBColor(215, 0, 95),
879
+ RGBColor(215, 0, 135),
880
+ RGBColor(215, 0, 175),
881
+ RGBColor(215, 0, 215),
882
+ RGBColor(215, 0, 255),
883
+ RGBColor(215, 95, 0),
884
+ RGBColor(215, 95, 95),
885
+ RGBColor(215, 95, 135),
886
+ RGBColor(215, 95, 175),
887
+ RGBColor(215, 95, 215),
888
+ RGBColor(215, 95, 255),
889
+ RGBColor(215, 135, 0),
890
+ RGBColor(215, 135, 95),
891
+ RGBColor(215, 135, 135),
892
+ RGBColor(215, 135, 175),
893
+ RGBColor(215, 135, 215),
894
+ RGBColor(215, 135, 255),
895
+ RGBColor(215, 175, 0),
896
+ RGBColor(215, 175, 95),
897
+ RGBColor(215, 175, 135),
898
+ RGBColor(215, 175, 175),
899
+ RGBColor(215, 175, 215),
900
+ RGBColor(215, 175, 255),
901
+ RGBColor(215, 215, 0),
902
+ RGBColor(215, 215, 95),
903
+ RGBColor(215, 215, 135),
904
+ RGBColor(215, 215, 175),
905
+ RGBColor(215, 215, 215),
906
+ RGBColor(215, 215, 255),
907
+ RGBColor(215, 255, 0),
908
+ RGBColor(215, 255, 95),
909
+ RGBColor(215, 255, 135),
910
+ RGBColor(215, 255, 175),
911
+ RGBColor(215, 255, 215),
912
+ RGBColor(215, 255, 255),
913
+ RGBColor(255, 0, 0),
914
+ RGBColor(255, 0, 135),
915
+ RGBColor(255, 0, 95),
916
+ RGBColor(255, 0, 175),
917
+ RGBColor(255, 0, 215),
918
+ RGBColor(255, 0, 255),
919
+ RGBColor(255, 95, 0),
920
+ RGBColor(255, 95, 95),
921
+ RGBColor(255, 95, 135),
922
+ RGBColor(255, 95, 175),
923
+ RGBColor(255, 95, 215),
924
+ RGBColor(255, 95, 255),
925
+ RGBColor(255, 135, 0),
926
+ RGBColor(255, 135, 95),
927
+ RGBColor(255, 135, 135),
928
+ RGBColor(255, 135, 175),
929
+ RGBColor(255, 135, 215),
930
+ RGBColor(255, 135, 255),
931
+ RGBColor(255, 175, 0),
932
+ RGBColor(255, 175, 95),
933
+ RGBColor(255, 175, 135),
934
+ RGBColor(255, 175, 175),
935
+ RGBColor(255, 175, 215),
936
+ RGBColor(255, 175, 255),
937
+ RGBColor(255, 215, 0),
938
+ RGBColor(255, 215, 95),
939
+ RGBColor(255, 215, 135),
940
+ RGBColor(255, 215, 175),
941
+ RGBColor(255, 215, 215),
942
+ RGBColor(255, 215, 255),
943
+ RGBColor(255, 255, 0),
944
+ RGBColor(255, 255, 95),
945
+ RGBColor(255, 255, 135),
946
+ RGBColor(255, 255, 175),
947
+ RGBColor(255, 255, 215),
948
+ RGBColor(255, 255, 255),
949
+ RGBColor(8, 8, 8),
950
+ RGBColor(18, 18, 18),
951
+ RGBColor(28, 28, 28),
952
+ RGBColor(38, 38, 38),
953
+ RGBColor(48, 48, 48),
954
+ RGBColor(58, 58, 58),
955
+ RGBColor(68, 68, 68),
956
+ RGBColor(78, 78, 78),
957
+ RGBColor(88, 88, 88),
958
+ RGBColor(98, 98, 98),
959
+ RGBColor(108, 108, 108),
960
+ RGBColor(118, 118, 118),
961
+ RGBColor(128, 128, 128),
962
+ RGBColor(138, 138, 138),
963
+ RGBColor(148, 148, 148),
964
+ RGBColor(158, 158, 158),
965
+ RGBColor(168, 168, 168),
966
+ RGBColor(178, 178, 178),
967
+ RGBColor(188, 188, 188),
968
+ RGBColor(198, 198, 198),
969
+ RGBColor(208, 208, 208),
970
+ RGBColor(218, 218, 218),
971
+ RGBColor(228, 228, 228),
972
+ RGBColor(238, 238, 238),
973
+ )
vllm/lib/python3.10/site-packages/blessed/colorspace.pyi ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # std imports
2
+ from typing import Set, Dict, Tuple, NamedTuple
3
+
4
+ CGA_COLORS: Set[str]
5
+
6
+ class RGBColor(NamedTuple):
7
+ red: int
8
+ green: int
9
+ blue: int
10
+
11
+ X11_COLORNAMES_TO_RGB: Dict[str, RGBColor]
12
+ RGB_256TABLE: Tuple[RGBColor, ...]
vllm/lib/python3.10/site-packages/blessed/formatters.py ADDED
@@ -0,0 +1,496 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Sub-module providing sequence-formatting functions."""
2
+ # std imports
3
+ import platform
4
+
5
+ # 3rd party
6
+ import six
7
+
8
+ # local
9
+ from blessed.colorspace import CGA_COLORS, X11_COLORNAMES_TO_RGB
10
+
11
+ # isort: off
12
+ # curses
13
+ if platform.system() == 'Windows':
14
+ import jinxed as curses # pylint: disable=import-error
15
+ else:
16
+ import curses
17
+
18
+
19
+ def _make_colors():
20
+ """
21
+ Return set of valid colors and their derivatives.
22
+
23
+ :rtype: set
24
+ :returns: Color names with prefixes
25
+ """
26
+ colors = set()
27
+ # basic CGA foreground color, background, high intensity, and bold
28
+ # background ('iCE colors' in my day).
29
+ for cga_color in CGA_COLORS:
30
+ colors.add(cga_color)
31
+ colors.add('on_' + cga_color)
32
+ colors.add('bright_' + cga_color)
33
+ colors.add('on_bright_' + cga_color)
34
+
35
+ # foreground and background VGA color
36
+ for vga_color in X11_COLORNAMES_TO_RGB:
37
+ colors.add(vga_color)
38
+ colors.add('on_' + vga_color)
39
+ return colors
40
+
41
+
42
+ #: Valid colors and their background (on), bright, and bright-background
43
+ #: derivatives.
44
+ COLORS = _make_colors()
45
+
46
+ #: Attributes that may be compounded with colors, by underscore, such as
47
+ #: 'reverse_indigo'.
48
+ COMPOUNDABLES = set('bold underline reverse blink italic standout'.split())
49
+
50
+
51
+ class ParameterizingString(six.text_type):
52
+ r"""
53
+ A Unicode string which can be called as a parameterizing termcap.
54
+
55
+ For example::
56
+
57
+ >>> from blessed import Terminal
58
+ >>> term = Terminal()
59
+ >>> color = ParameterizingString(term.color, term.normal, 'color')
60
+ >>> color(9)('color #9')
61
+ u'\x1b[91mcolor #9\x1b(B\x1b[m'
62
+ """
63
+
64
+ def __new__(cls, cap, normal=u'', name=u'<not specified>'):
65
+ # pylint: disable = missing-return-doc, missing-return-type-doc
66
+ """
67
+ Class constructor accepting 3 positional arguments.
68
+
69
+ :arg str cap: parameterized string suitable for curses.tparm()
70
+ :arg str normal: terminating sequence for this capability (optional).
71
+ :arg str name: name of this terminal capability (optional).
72
+ """
73
+ new = six.text_type.__new__(cls, cap)
74
+ new._normal = normal
75
+ new._name = name
76
+ return new
77
+
78
+ def __call__(self, *args):
79
+ """
80
+ Returning :class:`FormattingString` instance for given parameters.
81
+
82
+ Return evaluated terminal capability (self), receiving arguments
83
+ ``*args``, followed by the terminating sequence (self.normal) into
84
+ a :class:`FormattingString` capable of being called.
85
+
86
+ :raises TypeError: Mismatch between capability and arguments
87
+ :raises curses.error: :func:`curses.tparm` raised an exception
88
+ :rtype: :class:`FormattingString` or :class:`NullCallableString`
89
+ :returns: Callable string for given parameters
90
+ """
91
+ try:
92
+ # Re-encode the cap, because tparm() takes a bytestring in Python
93
+ # 3. However, appear to be a plain Unicode string otherwise so
94
+ # concats work.
95
+ attr = curses.tparm(self.encode('latin1'), *args).decode('latin1')
96
+ return FormattingString(attr, self._normal)
97
+ except TypeError as err:
98
+ # If the first non-int (i.e. incorrect) arg was a string, suggest
99
+ # something intelligent:
100
+ if args and isinstance(args[0], six.string_types):
101
+ raise TypeError(
102
+ "Unknown terminal capability, %r, or, TypeError "
103
+ "for arguments %r: %s" % (self._name, args, err))
104
+ # Somebody passed a non-string; I don't feel confident
105
+ # guessing what they were trying to do.
106
+ raise
107
+ except curses.error as err:
108
+ # ignore 'tparm() returned NULL', you won't get any styling,
109
+ # even if does_styling is True. This happens on win32 platforms
110
+ # with http://www.lfd.uci.edu/~gohlke/pythonlibs/#curses installed
111
+ if "tparm() returned NULL" not in six.text_type(err):
112
+ raise
113
+ return NullCallableString()
114
+
115
+
116
+ class ParameterizingProxyString(six.text_type):
117
+ r"""
118
+ A Unicode string which can be called to proxy missing termcap entries.
119
+
120
+ This class supports the function :func:`get_proxy_string`, and mirrors
121
+ the behavior of :class:`ParameterizingString`, except that instead of
122
+ a capability name, receives a format string, and callable to filter the
123
+ given positional ``*args`` of :meth:`ParameterizingProxyString.__call__`
124
+ into a terminal sequence.
125
+
126
+ For example::
127
+
128
+ >>> from blessed import Terminal
129
+ >>> term = Terminal('screen')
130
+ >>> hpa = ParameterizingString(term.hpa, term.normal, 'hpa')
131
+ >>> hpa(9)
132
+ u''
133
+ >>> fmt = u'\x1b[{0}G'
134
+ >>> fmt_arg = lambda *arg: (arg[0] + 1,)
135
+ >>> hpa = ParameterizingProxyString((fmt, fmt_arg), term.normal, 'hpa')
136
+ >>> hpa(9)
137
+ u'\x1b[10G'
138
+ """
139
+
140
+ def __new__(cls, fmt_pair, normal=u'', name=u'<not specified>'):
141
+ # pylint: disable = missing-return-doc, missing-return-type-doc
142
+ """
143
+ Class constructor accepting 4 positional arguments.
144
+
145
+ :arg tuple fmt_pair: Two element tuple containing:
146
+ - format string suitable for displaying terminal sequences
147
+ - callable suitable for receiving __call__ arguments for formatting string
148
+ :arg str normal: terminating sequence for this capability (optional).
149
+ :arg str name: name of this terminal capability (optional).
150
+ """
151
+ assert isinstance(fmt_pair, tuple), fmt_pair
152
+ assert callable(fmt_pair[1]), fmt_pair[1]
153
+ new = six.text_type.__new__(cls, fmt_pair[0])
154
+ new._fmt_args = fmt_pair[1]
155
+ new._normal = normal
156
+ new._name = name
157
+ return new
158
+
159
+ def __call__(self, *args):
160
+ """
161
+ Returning :class:`FormattingString` instance for given parameters.
162
+
163
+ Arguments are determined by the capability. For example, ``hpa``
164
+ (move_x) receives only a single integer, whereas ``cup`` (move)
165
+ receives two integers. See documentation in terminfo(5) for the
166
+ given capability.
167
+
168
+ :rtype: FormattingString
169
+ :returns: Callable string for given parameters
170
+ """
171
+ return FormattingString(self.format(*self._fmt_args(*args)),
172
+ self._normal)
173
+
174
+
175
+ class FormattingString(six.text_type):
176
+ r"""
177
+ A Unicode string which doubles as a callable.
178
+
179
+ This is used for terminal attributes, so that it may be used both
180
+ directly, or as a callable. When used directly, it simply emits
181
+ the given terminal sequence. When used as a callable, it wraps the
182
+ given (string) argument with the 2nd argument used by the class
183
+ constructor::
184
+
185
+ >>> from blessed import Terminal
186
+ >>> term = Terminal()
187
+ >>> style = FormattingString(term.bright_blue, term.normal)
188
+ >>> print(repr(style))
189
+ u'\x1b[94m'
190
+ >>> style('Big Blue')
191
+ u'\x1b[94mBig Blue\x1b(B\x1b[m'
192
+ """
193
+
194
+ def __new__(cls, sequence, normal=u''):
195
+ # pylint: disable = missing-return-doc, missing-return-type-doc
196
+ """
197
+ Class constructor accepting 2 positional arguments.
198
+
199
+ :arg str sequence: terminal attribute sequence.
200
+ :arg str normal: terminating sequence for this attribute (optional).
201
+ """
202
+ new = six.text_type.__new__(cls, sequence)
203
+ new._normal = normal
204
+ return new
205
+
206
+ def __call__(self, *args):
207
+ """
208
+ Return ``text`` joined by ``sequence`` and ``normal``.
209
+
210
+ :raises TypeError: Not a string type
211
+ :rtype: str
212
+ :returns: Arguments wrapped in sequence and normal
213
+ """
214
+ # Jim Allman brings us this convenience of allowing existing
215
+ # unicode strings to be joined as a call parameter to a formatting
216
+ # string result, allowing nestation:
217
+ #
218
+ # >>> t.red('This is ', t.bold('extremely'), ' dangerous!')
219
+ for idx, ucs_part in enumerate(args):
220
+ if not isinstance(ucs_part, six.string_types):
221
+ expected_types = ', '.join(_type.__name__ for _type in six.string_types)
222
+ raise TypeError(
223
+ "TypeError for FormattingString argument, "
224
+ "%r, at position %s: expected type %s, "
225
+ "got %s" % (ucs_part, idx, expected_types,
226
+ type(ucs_part).__name__))
227
+ postfix = u''
228
+ if self and self._normal:
229
+ postfix = self._normal
230
+ _refresh = self._normal + self
231
+ args = [_refresh.join(ucs_part.split(self._normal))
232
+ for ucs_part in args]
233
+
234
+ return self + u''.join(args) + postfix
235
+
236
+
237
+ class FormattingOtherString(six.text_type):
238
+ r"""
239
+ A Unicode string which doubles as a callable for another sequence when called.
240
+
241
+ This is used for the :meth:`~.Terminal.move_up`, ``down``, ``left``, and ``right()``
242
+ family of functions::
243
+
244
+ >>> from blessed import Terminal
245
+ >>> term = Terminal()
246
+ >>> move_right = FormattingOtherString(term.cuf1, term.cuf)
247
+ >>> print(repr(move_right))
248
+ u'\x1b[C'
249
+ >>> print(repr(move_right(666)))
250
+ u'\x1b[666C'
251
+ >>> print(repr(move_right()))
252
+ u'\x1b[C'
253
+ """
254
+
255
+ def __new__(cls, direct, target):
256
+ # pylint: disable = missing-return-doc, missing-return-type-doc
257
+ """
258
+ Class constructor accepting 2 positional arguments.
259
+
260
+ :arg str direct: capability name for direct formatting, eg ``('x' + term.right)``.
261
+ :arg str target: capability name for callable, eg ``('x' + term.right(99))``.
262
+ """
263
+ new = six.text_type.__new__(cls, direct)
264
+ new._callable = target
265
+ return new
266
+
267
+ def __getnewargs__(self):
268
+ # return arguments used for the __new__ method upon unpickling.
269
+ return six.text_type.__new__(six.text_type, self), self._callable
270
+
271
+ def __call__(self, *args):
272
+ """Return ``text`` by ``target``."""
273
+ return self._callable(*args) if args else self
274
+
275
+
276
+ class NullCallableString(six.text_type):
277
+ """
278
+ A dummy callable Unicode alternative to :class:`FormattingString`.
279
+
280
+ This is used for colors on terminals that do not support colors, it is just a basic form of
281
+ unicode that may also act as a callable.
282
+ """
283
+
284
+ def __new__(cls):
285
+ """Class constructor."""
286
+ return six.text_type.__new__(cls, u'')
287
+
288
+ def __call__(self, *args):
289
+ """
290
+ Allow empty string to be callable, returning given string, if any.
291
+
292
+ When called with an int as the first arg, return an empty Unicode. An
293
+ int is a good hint that I am a :class:`ParameterizingString`, as there
294
+ are only about half a dozen string-returning capabilities listed in
295
+ terminfo(5) which accept non-int arguments, they are seldom used.
296
+
297
+ When called with a non-int as the first arg (no no args at all), return
298
+ the first arg, acting in place of :class:`FormattingString` without
299
+ any attributes.
300
+ """
301
+ if not args or isinstance(args[0], int):
302
+ # As a NullCallableString, even when provided with a parameter,
303
+ # such as t.color(5), we must also still be callable, fe:
304
+ #
305
+ # >>> t.color(5)('shmoo')
306
+ #
307
+ # is actually simplified result of NullCallable()() on terminals
308
+ # without color support, so turtles all the way down: we return
309
+ # another instance.
310
+ return NullCallableString()
311
+ return u''.join(args)
312
+
313
+
314
+ def get_proxy_string(term, attr):
315
+ """
316
+ Proxy and return callable string for proxied attributes.
317
+
318
+ :arg Terminal term: :class:`~.Terminal` instance.
319
+ :arg str attr: terminal capability name that may be proxied.
320
+ :rtype: None or :class:`ParameterizingProxyString`.
321
+ :returns: :class:`ParameterizingProxyString` for some attributes
322
+ of some terminal types that support it, where the terminfo(5)
323
+ database would otherwise come up empty, such as ``move_x``
324
+ attribute for ``term.kind`` of ``screen``. Otherwise, None.
325
+ """
326
+ # normalize 'screen-256color', or 'ansi.sys' to its basic names
327
+ term_kind = next(iter(_kind for _kind in ('screen', 'ansi',)
328
+ if term.kind.startswith(_kind)), term)
329
+ _proxy_table = { # pragma: no cover
330
+ 'screen': {
331
+ # proxy move_x/move_y for 'screen' terminal type, used by tmux(1).
332
+ 'hpa': ParameterizingProxyString(
333
+ (u'\x1b[{0}G', lambda *arg: (arg[0] + 1,)), term.normal, attr),
334
+ 'vpa': ParameterizingProxyString(
335
+ (u'\x1b[{0}d', lambda *arg: (arg[0] + 1,)), term.normal, attr),
336
+ },
337
+ 'ansi': {
338
+ # proxy show/hide cursor for 'ansi' terminal type. There is some
339
+ # demand for a richly working ANSI terminal type for some reason.
340
+ 'civis': ParameterizingProxyString(
341
+ (u'\x1b[?25l', lambda *arg: ()), term.normal, attr),
342
+ 'cnorm': ParameterizingProxyString(
343
+ (u'\x1b[?25h', lambda *arg: ()), term.normal, attr),
344
+ 'hpa': ParameterizingProxyString(
345
+ (u'\x1b[{0}G', lambda *arg: (arg[0] + 1,)), term.normal, attr),
346
+ 'vpa': ParameterizingProxyString(
347
+ (u'\x1b[{0}d', lambda *arg: (arg[0] + 1,)), term.normal, attr),
348
+ 'sc': '\x1b[s',
349
+ 'rc': '\x1b[u',
350
+ }
351
+ }
352
+ return _proxy_table.get(term_kind, {}).get(attr, None)
353
+
354
+
355
+ def split_compound(compound):
356
+ """
357
+ Split compound formating string into segments.
358
+
359
+ >>> split_compound('bold_underline_bright_blue_on_red')
360
+ ['bold', 'underline', 'bright_blue', 'on_red']
361
+
362
+ :arg str compound: a string that may contain compounds, separated by
363
+ underline (``_``).
364
+ :rtype: list
365
+ :returns: List of formating string segments
366
+ """
367
+ merged_segs = []
368
+ # These occur only as prefixes, so they can always be merged:
369
+ mergeable_prefixes = ['on', 'bright', 'on_bright']
370
+ for segment in compound.split('_'):
371
+ if merged_segs and merged_segs[-1] in mergeable_prefixes:
372
+ merged_segs[-1] += '_' + segment
373
+ else:
374
+ merged_segs.append(segment)
375
+ return merged_segs
376
+
377
+
378
+ def resolve_capability(term, attr):
379
+ """
380
+ Resolve a raw terminal capability using :func:`tigetstr`.
381
+
382
+ :arg Terminal term: :class:`~.Terminal` instance.
383
+ :arg str attr: terminal capability name.
384
+ :returns: string of the given terminal capability named by ``attr``,
385
+ which may be empty (u'') if not found or not supported by the
386
+ given :attr:`~.Terminal.kind`.
387
+ :rtype: str
388
+ """
389
+ if not term.does_styling:
390
+ return u''
391
+ val = curses.tigetstr(term._sugar.get(attr, attr)) # pylint: disable=protected-access
392
+ # Decode sequences as latin1, as they are always 8-bit bytes, so when
393
+ # b'\xff' is returned, this is decoded as u'\xff'.
394
+ return u'' if val is None else val.decode('latin1')
395
+
396
+
397
+ def resolve_color(term, color):
398
+ """
399
+ Resolve a simple color name to a callable capability.
400
+
401
+ This function supports :func:`resolve_attribute`.
402
+
403
+ :arg Terminal term: :class:`~.Terminal` instance.
404
+ :arg str color: any string found in set :const:`COLORS`.
405
+ :returns: a string class instance which emits the terminal sequence
406
+ for the given color, and may be used as a callable to wrap the
407
+ given string with such sequence.
408
+ :returns: :class:`NullCallableString` when
409
+ :attr:`~.Terminal.number_of_colors` is 0,
410
+ otherwise :class:`FormattingString`.
411
+ :rtype: :class:`NullCallableString` or :class:`FormattingString`
412
+ """
413
+ # pylint: disable=protected-access
414
+ if term.number_of_colors == 0:
415
+ return NullCallableString()
416
+
417
+ # fg/bg capabilities terminals that support 0-256+ colors.
418
+ vga_color_cap = (term._background_color if 'on_' in color else
419
+ term._foreground_color)
420
+
421
+ base_color = color.rsplit('_', 1)[-1]
422
+ if base_color in CGA_COLORS:
423
+ # curses constants go up to only 7, so add an offset to get at the
424
+ # bright colors at 8-15:
425
+ offset = 8 if 'bright_' in color else 0
426
+ base_color = color.rsplit('_', 1)[-1]
427
+ attr = 'COLOR_%s' % (base_color.upper(),)
428
+ fmt_attr = vga_color_cap(getattr(curses, attr) + offset)
429
+ return FormattingString(fmt_attr, term.normal)
430
+
431
+ assert base_color in X11_COLORNAMES_TO_RGB, (
432
+ 'color not known', base_color)
433
+ rgb = X11_COLORNAMES_TO_RGB[base_color]
434
+
435
+ # downconvert X11 colors to CGA, EGA, or VGA color spaces
436
+ if term.number_of_colors <= 256:
437
+ fmt_attr = vga_color_cap(term.rgb_downconvert(*rgb))
438
+ return FormattingString(fmt_attr, term.normal)
439
+
440
+ # Modern 24-bit color terminals are written pretty basically. The
441
+ # foreground and background sequences are:
442
+ # - ^[38;2;<r>;<g>;<b>m
443
+ # - ^[48;2;<r>;<g>;<b>m
444
+ fgbg_seq = ('48' if 'on_' in color else '38')
445
+ assert term.number_of_colors == 1 << 24
446
+ fmt_attr = u'\x1b[' + fgbg_seq + ';2;{0};{1};{2}m'
447
+ return FormattingString(fmt_attr.format(*rgb), term.normal)
448
+
449
+
450
+ def resolve_attribute(term, attr):
451
+ """
452
+ Resolve a terminal attribute name into a capability class.
453
+
454
+ :arg Terminal term: :class:`~.Terminal` instance.
455
+ :arg str attr: Sugary, ordinary, or compound formatted terminal
456
+ capability, such as "red_on_white", "normal", "red", or
457
+ "bold_on_black".
458
+ :returns: a string class instance which emits the terminal sequence
459
+ for the given terminal capability, or may be used as a callable to
460
+ wrap the given string with such sequence.
461
+ :returns: :class:`NullCallableString` when
462
+ :attr:`~.Terminal.number_of_colors` is 0,
463
+ otherwise :class:`FormattingString`.
464
+ :rtype: :class:`NullCallableString` or :class:`FormattingString`
465
+ """
466
+ if attr in COLORS:
467
+ return resolve_color(term, attr)
468
+
469
+ # A direct compoundable, such as `bold' or `on_red'.
470
+ if attr in COMPOUNDABLES:
471
+ sequence = resolve_capability(term, attr)
472
+ return FormattingString(sequence, term.normal)
473
+
474
+ # Given `bold_on_red', resolve to ('bold', 'on_red'), RECURSIVE
475
+ # call for each compounding section, joined and returned as
476
+ # a completed completed FormattingString.
477
+ formatters = split_compound(attr)
478
+ if all((fmt in COLORS or fmt in COMPOUNDABLES) for fmt in formatters):
479
+ resolution = (resolve_attribute(term, fmt) for fmt in formatters)
480
+ return FormattingString(u''.join(resolution), term.normal)
481
+
482
+ # otherwise, this is our end-game: given a sequence such as 'csr'
483
+ # (change scrolling region), return a ParameterizingString instance,
484
+ # that when called, performs and returns the final string after curses
485
+ # capability lookup is performed.
486
+ tparm_capseq = resolve_capability(term, attr)
487
+ if not tparm_capseq:
488
+ # and, for special terminals, such as 'screen', provide a Proxy
489
+ # ParameterizingString for attributes they do not claim to support,
490
+ # but actually do! (such as 'hpa' and 'vpa').
491
+ proxy = get_proxy_string(term,
492
+ term._sugar.get(attr, attr)) # pylint: disable=protected-access
493
+ if proxy is not None:
494
+ return proxy
495
+
496
+ return ParameterizingString(tparm_capseq, term.normal, attr)
vllm/lib/python3.10/site-packages/blessed/formatters.pyi ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # std imports
2
+ from typing import (Any,
3
+ Set,
4
+ List,
5
+ Type,
6
+ Tuple,
7
+ Union,
8
+ TypeVar,
9
+ Callable,
10
+ NoReturn,
11
+ Optional,
12
+ overload)
13
+
14
+ # local
15
+ from .terminal import Terminal
16
+
17
+ COLORS: Set[str]
18
+ COMPOUNDABLES: Set[str]
19
+
20
+ _T = TypeVar("_T")
21
+
22
+ class ParameterizingString(str):
23
+ def __new__(cls: Type[_T], cap: str, normal: str = ..., name: str = ...) -> _T: ...
24
+ @overload
25
+ def __call__(
26
+ self, *args: int
27
+ ) -> Union["FormattingString", "NullCallableString"]: ...
28
+ @overload
29
+ def __call__(self, *args: str) -> NoReturn: ...
30
+
31
+ class ParameterizingProxyString(str):
32
+ def __new__(
33
+ cls: Type[_T],
34
+ fmt_pair: Tuple[str, Callable[..., Tuple[object, ...]]],
35
+ normal: str = ...,
36
+ name: str = ...,
37
+ ) -> _T: ...
38
+ def __call__(self, *args: Any) -> "FormattingString": ...
39
+
40
+ class FormattingString(str):
41
+ def __new__(cls: Type[_T], sequence: str, normal: str = ...) -> _T: ...
42
+ @overload
43
+ def __call__(self, *args: int) -> NoReturn: ...
44
+ @overload
45
+ def __call__(self, *args: str) -> str: ...
46
+
47
+ class FormattingOtherString(str):
48
+ def __new__(
49
+ cls: Type[_T], direct: ParameterizingString, target: ParameterizingString = ...
50
+ ) -> _T: ...
51
+ def __call__(self, *args: Union[int, str]) -> str: ...
52
+
53
+ class NullCallableString(str):
54
+ def __new__(cls: Type[_T]) -> _T: ...
55
+ @overload
56
+ def __call__(self, *args: int) -> "NullCallableString": ...
57
+ @overload
58
+ def __call__(self, *args: str) -> str: ...
59
+
60
+ def get_proxy_string(
61
+ term: Terminal, attr: str
62
+ ) -> Optional[ParameterizingProxyString]: ...
63
+ def split_compound(compound: str) -> List[str]: ...
64
+ def resolve_capability(term: Terminal, attr: str) -> str: ...
65
+ def resolve_color(
66
+ term: Terminal, color: str
67
+ ) -> Union[NullCallableString, FormattingString]: ...
68
+ def resolve_attribute(
69
+ term: Terminal, attr: str
70
+ ) -> Union[ParameterizingString, FormattingString]: ...
vllm/lib/python3.10/site-packages/blessed/keyboard.py ADDED
@@ -0,0 +1,451 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Sub-module providing 'keyboard awareness'."""
2
+
3
+ # std imports
4
+ import re
5
+ import time
6
+ import platform
7
+ from collections import OrderedDict
8
+
9
+ # 3rd party
10
+ import six
11
+
12
+ # isort: off
13
+ # curses
14
+ if platform.system() == 'Windows':
15
+ # pylint: disable=import-error
16
+ import jinxed as curses
17
+ from jinxed.has_key import _capability_names as capability_names
18
+ else:
19
+ import curses
20
+ from curses.has_key import _capability_names as capability_names
21
+
22
+
23
+ class Keystroke(six.text_type):
24
+ """
25
+ A unicode-derived class for describing a single keystroke.
26
+
27
+ A class instance describes a single keystroke received on input,
28
+ which may contain multiple characters as a multibyte sequence,
29
+ which is indicated by properties :attr:`is_sequence` returning
30
+ ``True``.
31
+
32
+ When the string is a known sequence, :attr:`code` matches terminal
33
+ class attributes for comparison, such as ``term.KEY_LEFT``.
34
+
35
+ The string-name of the sequence, such as ``u'KEY_LEFT'`` is accessed
36
+ by property :attr:`name`, and is used by the :meth:`__repr__` method
37
+ to display a human-readable form of the Keystroke this class
38
+ instance represents. It may otherwise by joined, split, or evaluated
39
+ just as as any other unicode string.
40
+ """
41
+
42
+ def __new__(cls, ucs='', code=None, name=None):
43
+ """Class constructor."""
44
+ new = six.text_type.__new__(cls, ucs)
45
+ new._name = name
46
+ new._code = code
47
+ return new
48
+
49
+ @property
50
+ def is_sequence(self):
51
+ """Whether the value represents a multibyte sequence (bool)."""
52
+ return self._code is not None
53
+
54
+ def __repr__(self):
55
+ """Docstring overwritten."""
56
+ return (six.text_type.__repr__(self) if self._name is None else
57
+ self._name)
58
+ __repr__.__doc__ = six.text_type.__doc__
59
+
60
+ @property
61
+ def name(self):
62
+ """String-name of key sequence, such as ``u'KEY_LEFT'`` (str)."""
63
+ return self._name
64
+
65
+ @property
66
+ def code(self):
67
+ """Integer keycode value of multibyte sequence (int)."""
68
+ return self._code
69
+
70
+
71
+ def get_curses_keycodes():
72
+ """
73
+ Return mapping of curses key-names paired by their keycode integer value.
74
+
75
+ :rtype: dict
76
+ :returns: Dictionary of (name, code) pairs for curses keyboard constant
77
+ values and their mnemonic name. Such as code ``260``, with the value of
78
+ its key-name identity, ``u'KEY_LEFT'``.
79
+ """
80
+ _keynames = [attr for attr in dir(curses)
81
+ if attr.startswith('KEY_')]
82
+ return {keyname: getattr(curses, keyname) for keyname in _keynames}
83
+
84
+
85
+ def get_keyboard_codes():
86
+ """
87
+ Return mapping of keycode integer values paired by their curses key-name.
88
+
89
+ :rtype: dict
90
+ :returns: Dictionary of (code, name) pairs for curses keyboard constant
91
+ values and their mnemonic name. Such as key ``260``, with the value of
92
+ its identity, ``u'KEY_LEFT'``.
93
+
94
+ These keys are derived from the attributes by the same of the curses module,
95
+ with the following exceptions:
96
+
97
+ * ``KEY_DELETE`` in place of ``KEY_DC``
98
+ * ``KEY_INSERT`` in place of ``KEY_IC``
99
+ * ``KEY_PGUP`` in place of ``KEY_PPAGE``
100
+ * ``KEY_PGDOWN`` in place of ``KEY_NPAGE``
101
+ * ``KEY_ESCAPE`` in place of ``KEY_EXIT``
102
+ * ``KEY_SUP`` in place of ``KEY_SR``
103
+ * ``KEY_SDOWN`` in place of ``KEY_SF``
104
+
105
+ This function is the inverse of :func:`get_curses_keycodes`. With the
106
+ given override "mixins" listed above, the keycode for the delete key will
107
+ map to our imaginary ``KEY_DELETE`` mnemonic, effectively erasing the
108
+ phrase ``KEY_DC`` from our code vocabulary for anyone that wishes to use
109
+ the return value to determine the key-name by keycode.
110
+ """
111
+ keycodes = OrderedDict(get_curses_keycodes())
112
+ keycodes.update(CURSES_KEYCODE_OVERRIDE_MIXIN)
113
+ # merge _CURSES_KEYCODE_ADDINS added to our module space
114
+ keycodes.update(
115
+ (name, value) for name, value in globals().copy().items() if name.startswith('KEY_')
116
+ )
117
+
118
+ # invert dictionary (key, values) => (values, key), preferring the
119
+ # last-most inserted value ('KEY_DELETE' over 'KEY_DC').
120
+ return dict(zip(keycodes.values(), keycodes.keys()))
121
+
122
+
123
+ def _alternative_left_right(term):
124
+ r"""
125
+ Determine and return mapping of left and right arrow keys sequences.
126
+
127
+ :arg blessed.Terminal term: :class:`~.Terminal` instance.
128
+ :rtype: dict
129
+ :returns: Dictionary of sequences ``term._cuf1``, and ``term._cub1``,
130
+ valued as ``KEY_RIGHT``, ``KEY_LEFT`` (when appropriate).
131
+
132
+ This function supports :func:`get_terminal_sequences` to discover
133
+ the preferred input sequence for the left and right application keys.
134
+
135
+ It is necessary to check the value of these sequences to ensure we do not
136
+ use ``u' '`` and ``u'\b'`` for ``KEY_RIGHT`` and ``KEY_LEFT``,
137
+ preferring their true application key sequence, instead.
138
+ """
139
+ # pylint: disable=protected-access
140
+ keymap = {}
141
+ if term._cuf1 and term._cuf1 != u' ':
142
+ keymap[term._cuf1] = curses.KEY_RIGHT
143
+ if term._cub1 and term._cub1 != u'\b':
144
+ keymap[term._cub1] = curses.KEY_LEFT
145
+ return keymap
146
+
147
+
148
+ def get_keyboard_sequences(term):
149
+ r"""
150
+ Return mapping of keyboard sequences paired by keycodes.
151
+
152
+ :arg blessed.Terminal term: :class:`~.Terminal` instance.
153
+ :returns: mapping of keyboard unicode sequences paired by keycodes
154
+ as integer. This is used as the argument ``mapper`` to
155
+ the supporting function :func:`resolve_sequence`.
156
+ :rtype: OrderedDict
157
+
158
+ Initialize and return a keyboard map and sequence lookup table,
159
+ (sequence, keycode) from :class:`~.Terminal` instance ``term``,
160
+ where ``sequence`` is a multibyte input sequence of unicode
161
+ characters, such as ``u'\x1b[D'``, and ``keycode`` is an integer
162
+ value, matching curses constant such as term.KEY_LEFT.
163
+
164
+ The return value is an OrderedDict instance, with their keys
165
+ sorted longest-first.
166
+ """
167
+ # A small gem from curses.has_key that makes this all possible,
168
+ # _capability_names: a lookup table of terminal capability names for
169
+ # keyboard sequences (fe. kcub1, key_left), keyed by the values of
170
+ # constants found beginning with KEY_ in the main curses module
171
+ # (such as KEY_LEFT).
172
+ #
173
+ # latin1 encoding is used so that bytes in 8-bit range of 127-255
174
+ # have equivalent chr() and unichr() values, so that the sequence
175
+ # of a kermit or avatar terminal, for example, remains unchanged
176
+ # in its byte sequence values even when represented by unicode.
177
+ #
178
+ sequence_map = dict((
179
+ (seq.decode('latin1'), val)
180
+ for (seq, val) in (
181
+ (curses.tigetstr(cap), val)
182
+ for (val, cap) in capability_names.items()
183
+ ) if seq
184
+ ) if term.does_styling else ())
185
+
186
+ sequence_map.update(_alternative_left_right(term))
187
+ sequence_map.update(DEFAULT_SEQUENCE_MIXIN)
188
+
189
+ # This is for fast lookup matching of sequences, preferring
190
+ # full-length sequence such as ('\x1b[D', KEY_LEFT)
191
+ # over simple sequences such as ('\x1b', KEY_EXIT).
192
+ return OrderedDict((
193
+ (seq, sequence_map[seq]) for seq in sorted(
194
+ sequence_map.keys(), key=len, reverse=True)))
195
+
196
+
197
+ def get_leading_prefixes(sequences):
198
+ """
199
+ Return a set of proper prefixes for given sequence of strings.
200
+
201
+ :arg iterable sequences
202
+ :rtype: set
203
+ :return: Set of all string prefixes
204
+
205
+ Given an iterable of strings, all textparts leading up to the final
206
+ string is returned as a unique set. This function supports the
207
+ :meth:`~.Terminal.inkey` method by determining whether the given
208
+ input is a sequence that **may** lead to a final matching pattern.
209
+
210
+ >>> prefixes(['abc', 'abdf', 'e', 'jkl'])
211
+ set([u'a', u'ab', u'abd', u'j', u'jk'])
212
+ """
213
+ return {seq[:i] for seq in sequences for i in range(1, len(seq))}
214
+
215
+
216
+ def resolve_sequence(text, mapper, codes):
217
+ r"""
218
+ Return a single :class:`Keystroke` instance for given sequence ``text``.
219
+
220
+ :arg str text: string of characters received from terminal input stream.
221
+ :arg OrderedDict mapper: unicode multibyte sequences, such as ``u'\x1b[D'``
222
+ paired by their integer value (260)
223
+ :arg dict codes: a :type:`dict` of integer values (such as 260) paired
224
+ by their mnemonic name, such as ``'KEY_LEFT'``.
225
+ :rtype: Keystroke
226
+ :returns: Keystroke instance for the given sequence
227
+
228
+ The given ``text`` may extend beyond a matching sequence, such as
229
+ ``u\x1b[Dxxx`` returns a :class:`Keystroke` instance of attribute
230
+ :attr:`Keystroke.sequence` valued only ``u\x1b[D``. It is up to
231
+ calls to determine that ``xxx`` remains unresolved.
232
+ """
233
+ for sequence, code in mapper.items():
234
+ if text.startswith(sequence):
235
+ return Keystroke(ucs=sequence, code=code, name=codes[code])
236
+ return Keystroke(ucs=text and text[0] or u'')
237
+
238
+
239
+ def _time_left(stime, timeout):
240
+ """
241
+ Return time remaining since ``stime`` before given ``timeout``.
242
+
243
+ This function assists determining the value of ``timeout`` for
244
+ class method :meth:`~.Terminal.kbhit` and similar functions.
245
+
246
+ :arg float stime: starting time for measurement
247
+ :arg float timeout: timeout period, may be set to None to
248
+ indicate no timeout (where None is always returned).
249
+ :rtype: float or int
250
+ :returns: time remaining as float. If no time is remaining,
251
+ then the integer ``0`` is returned.
252
+ """
253
+ return max(0, timeout - (time.time() - stime)) if timeout else timeout
254
+
255
+
256
+ def _read_until(term, pattern, timeout):
257
+ """
258
+ Convenience read-until-pattern function, supporting :meth:`~.get_location`.
259
+
260
+ :arg blessed.Terminal term: :class:`~.Terminal` instance.
261
+ :arg float timeout: timeout period, may be set to None to indicate no
262
+ timeout (where 0 is always returned).
263
+ :arg str pattern: target regular expression pattern to seek.
264
+ :rtype: tuple
265
+ :returns: tuple in form of ``(match, str)``, *match*
266
+ may be :class:`re.MatchObject` if pattern is discovered
267
+ in input stream before timeout has elapsed, otherwise
268
+ None. ``str`` is any remaining text received exclusive
269
+ of the matching pattern).
270
+
271
+ The reason a tuple containing non-matching data is returned, is that the
272
+ consumer should push such data back into the input buffer by
273
+ :meth:`~.Terminal.ungetch` if any was received.
274
+
275
+ For example, when a user is performing rapid input keystrokes while its
276
+ terminal emulator surreptitiously responds to this in-band sequence, we
277
+ must ensure any such keyboard data is well-received by the next call to
278
+ term.inkey() without delay.
279
+ """
280
+ stime = time.time()
281
+ match, buf = None, u''
282
+
283
+ # first, buffer all pending data. pexpect library provides a
284
+ # 'searchwindowsize' attribute that limits this memory region. We're not
285
+ # concerned about OOM conditions: only (human) keyboard input and terminal
286
+ # response sequences are expected.
287
+
288
+ while True: # pragma: no branch
289
+ # block as long as necessary to ensure at least one character is
290
+ # received on input or remaining timeout has elapsed.
291
+ ucs = term.inkey(timeout=_time_left(stime, timeout))
292
+ # while the keyboard buffer is "hot" (has input), we continue to
293
+ # aggregate all awaiting data. We do this to ensure slow I/O
294
+ # calls do not unnecessarily give up within the first 'while' loop
295
+ # for short timeout periods.
296
+ while ucs:
297
+ buf += ucs
298
+ ucs = term.inkey(timeout=0)
299
+
300
+ match = re.search(pattern=pattern, string=buf)
301
+ if match is not None:
302
+ # match
303
+ break
304
+
305
+ if timeout is not None and not _time_left(stime, timeout):
306
+ # timeout
307
+ break
308
+
309
+ return match, buf
310
+
311
+
312
+ #: Though we may determine *keynames* and codes for keyboard input that
313
+ #: generate multibyte sequences, it is also especially useful to aliases
314
+ #: a few basic ASCII characters such as ``KEY_TAB`` instead of ``u'\t'`` for
315
+ #: uniformity.
316
+ #:
317
+ #: Furthermore, many key-names for application keys enabled only by context
318
+ #: manager :meth:`~.Terminal.keypad` are surprisingly absent. We inject them
319
+ #: here directly into the curses module.
320
+ _CURSES_KEYCODE_ADDINS = (
321
+ 'TAB',
322
+ 'KP_MULTIPLY',
323
+ 'KP_ADD',
324
+ 'KP_SEPARATOR',
325
+ 'KP_SUBTRACT',
326
+ 'KP_DECIMAL',
327
+ 'KP_DIVIDE',
328
+ 'KP_EQUAL',
329
+ 'KP_0',
330
+ 'KP_1',
331
+ 'KP_2',
332
+ 'KP_3',
333
+ 'KP_4',
334
+ 'KP_5',
335
+ 'KP_6',
336
+ 'KP_7',
337
+ 'KP_8',
338
+ 'KP_9')
339
+
340
+ _LASTVAL = max(get_curses_keycodes().values())
341
+ for keycode_name in _CURSES_KEYCODE_ADDINS:
342
+ _LASTVAL += 1
343
+ globals()['KEY_' + keycode_name] = _LASTVAL
344
+
345
+ #: In a perfect world, terminal emulators would always send exactly what
346
+ #: the terminfo(5) capability database plans for them, accordingly by the
347
+ #: value of the ``TERM`` name they declare.
348
+ #:
349
+ #: But this isn't a perfect world. Many vt220-derived terminals, such as
350
+ #: those declaring 'xterm', will continue to send vt220 codes instead of
351
+ #: their native-declared codes, for backwards-compatibility.
352
+ #:
353
+ #: This goes for many: rxvt, putty, iTerm.
354
+ #:
355
+ #: These "mixins" are used for *all* terminals, regardless of their type.
356
+ #:
357
+ #: Furthermore, curses does not provide sequences sent by the keypad,
358
+ #: at least, it does not provide a way to distinguish between keypad 0
359
+ #: and numeric 0.
360
+ DEFAULT_SEQUENCE_MIXIN = (
361
+ # these common control characters (and 127, ctrl+'?') mapped to
362
+ # an application key definition.
363
+ (six.unichr(10), curses.KEY_ENTER),
364
+ (six.unichr(13), curses.KEY_ENTER),
365
+ (six.unichr(8), curses.KEY_BACKSPACE),
366
+ (six.unichr(9), KEY_TAB), # noqa # pylint: disable=undefined-variable
367
+ (six.unichr(27), curses.KEY_EXIT),
368
+ (six.unichr(127), curses.KEY_BACKSPACE),
369
+
370
+ (u"\x1b[A", curses.KEY_UP),
371
+ (u"\x1b[B", curses.KEY_DOWN),
372
+ (u"\x1b[C", curses.KEY_RIGHT),
373
+ (u"\x1b[D", curses.KEY_LEFT),
374
+ (u"\x1b[1;2A", curses.KEY_SR),
375
+ (u"\x1b[1;2B", curses.KEY_SF),
376
+ (u"\x1b[1;2C", curses.KEY_SRIGHT),
377
+ (u"\x1b[1;2D", curses.KEY_SLEFT),
378
+ (u"\x1b[F", curses.KEY_END),
379
+ (u"\x1b[H", curses.KEY_HOME),
380
+ # not sure where these are from .. please report
381
+ (u"\x1b[K", curses.KEY_END),
382
+ (u"\x1b[U", curses.KEY_NPAGE),
383
+ (u"\x1b[V", curses.KEY_PPAGE),
384
+
385
+ # keys sent after term.smkx (keypad_xmit) is emitted, source:
386
+ # http://www.xfree86.org/current/ctlseqs.html#PC-Style%20Function%20Keys
387
+ # http://fossies.org/linux/rxvt/doc/rxvtRef.html#KeyCodes
388
+ #
389
+ # keypad, numlock on
390
+ (u"\x1bOM", curses.KEY_ENTER), # noqa return
391
+ (u"\x1bOj", KEY_KP_MULTIPLY), # noqa * # pylint: disable=undefined-variable
392
+ (u"\x1bOk", KEY_KP_ADD), # noqa + # pylint: disable=undefined-variable
393
+ (u"\x1bOl", KEY_KP_SEPARATOR), # noqa , # pylint: disable=undefined-variable
394
+ (u"\x1bOm", KEY_KP_SUBTRACT), # noqa - # pylint: disable=undefined-variable
395
+ (u"\x1bOn", KEY_KP_DECIMAL), # noqa . # pylint: disable=undefined-variable
396
+ (u"\x1bOo", KEY_KP_DIVIDE), # noqa / # pylint: disable=undefined-variable
397
+ (u"\x1bOX", KEY_KP_EQUAL), # noqa = # pylint: disable=undefined-variable
398
+ (u"\x1bOp", KEY_KP_0), # noqa 0 # pylint: disable=undefined-variable
399
+ (u"\x1bOq", KEY_KP_1), # noqa 1 # pylint: disable=undefined-variable
400
+ (u"\x1bOr", KEY_KP_2), # noqa 2 # pylint: disable=undefined-variable
401
+ (u"\x1bOs", KEY_KP_3), # noqa 3 # pylint: disable=undefined-variable
402
+ (u"\x1bOt", KEY_KP_4), # noqa 4 # pylint: disable=undefined-variable
403
+ (u"\x1bOu", KEY_KP_5), # noqa 5 # pylint: disable=undefined-variable
404
+ (u"\x1bOv", KEY_KP_6), # noqa 6 # pylint: disable=undefined-variable
405
+ (u"\x1bOw", KEY_KP_7), # noqa 7 # pylint: disable=undefined-variable
406
+ (u"\x1bOx", KEY_KP_8), # noqa 8 # pylint: disable=undefined-variable
407
+ (u"\x1bOy", KEY_KP_9), # noqa 9 # pylint: disable=undefined-variable
408
+
409
+ # keypad, numlock off
410
+ (u"\x1b[1~", curses.KEY_FIND), # find
411
+ (u"\x1b[2~", curses.KEY_IC), # insert (0)
412
+ (u"\x1b[3~", curses.KEY_DC), # delete (.), "Execute"
413
+ (u"\x1b[4~", curses.KEY_SELECT), # select
414
+ (u"\x1b[5~", curses.KEY_PPAGE), # pgup (9)
415
+ (u"\x1b[6~", curses.KEY_NPAGE), # pgdown (3)
416
+ (u"\x1b[7~", curses.KEY_HOME), # home
417
+ (u"\x1b[8~", curses.KEY_END), # end
418
+ (u"\x1b[OA", curses.KEY_UP), # up (8)
419
+ (u"\x1b[OB", curses.KEY_DOWN), # down (2)
420
+ (u"\x1b[OC", curses.KEY_RIGHT), # right (6)
421
+ (u"\x1b[OD", curses.KEY_LEFT), # left (4)
422
+ (u"\x1b[OF", curses.KEY_END), # end (1)
423
+ (u"\x1b[OH", curses.KEY_HOME), # home (7)
424
+
425
+ # The vt220 placed F1-F4 above the keypad, in place of actual
426
+ # F1-F4 were local functions (hold screen, print screen,
427
+ # set up, data/talk, break).
428
+ (u"\x1bOP", curses.KEY_F1),
429
+ (u"\x1bOQ", curses.KEY_F2),
430
+ (u"\x1bOR", curses.KEY_F3),
431
+ (u"\x1bOS", curses.KEY_F4),
432
+ )
433
+
434
+ #: Override mixins for a few curses constants with easier
435
+ #: mnemonics: there may only be a 1:1 mapping when only a
436
+ #: keycode (int) is given, where these phrases are preferred.
437
+ CURSES_KEYCODE_OVERRIDE_MIXIN = (
438
+ ('KEY_DELETE', curses.KEY_DC),
439
+ ('KEY_INSERT', curses.KEY_IC),
440
+ ('KEY_PGUP', curses.KEY_PPAGE),
441
+ ('KEY_PGDOWN', curses.KEY_NPAGE),
442
+ ('KEY_ESCAPE', curses.KEY_EXIT),
443
+ ('KEY_SUP', curses.KEY_SR),
444
+ ('KEY_SDOWN', curses.KEY_SF),
445
+ ('KEY_UP_LEFT', curses.KEY_A1),
446
+ ('KEY_UP_RIGHT', curses.KEY_A3),
447
+ ('KEY_CENTER', curses.KEY_B2),
448
+ ('KEY_BEGIN', curses.KEY_BEG),
449
+ )
450
+
451
+ __all__ = ('Keystroke', 'get_keyboard_codes', 'get_keyboard_sequences',)
vllm/lib/python3.10/site-packages/blessed/keyboard.pyi ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # std imports
2
+ from typing import Set, Dict, Type, Mapping, TypeVar, Iterable, Optional, OrderedDict
3
+
4
+ # local
5
+ from .terminal import Terminal
6
+
7
+ _T = TypeVar("_T")
8
+
9
+ class Keystroke(str):
10
+ def __new__(
11
+ cls: Type[_T],
12
+ ucs: str = ...,
13
+ code: Optional[int] = ...,
14
+ name: Optional[str] = ...,
15
+ ) -> _T: ...
16
+ @property
17
+ def is_sequence(self) -> bool: ...
18
+ @property
19
+ def name(self) -> Optional[str]: ...
20
+ @property
21
+ def code(self) -> Optional[int]: ...
22
+
23
+ def get_keyboard_codes() -> Dict[int, str]: ...
24
+ def get_keyboard_sequences(term: Terminal) -> OrderedDict[str, int]: ...
25
+ def get_leading_prefixes(sequences: Iterable[str]) -> Set[str]: ...
26
+ def resolve_sequence(
27
+ text: str, mapper: Mapping[str, int], codes: Mapping[int, str]
28
+ ) -> Keystroke: ...
vllm/lib/python3.10/site-packages/blessed/py.typed ADDED
File without changes
vllm/lib/python3.10/site-packages/blessed/sequences.py ADDED
@@ -0,0 +1,461 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """Module providing 'sequence awareness'."""
3
+ # std imports
4
+ import re
5
+ import math
6
+ import textwrap
7
+
8
+ # 3rd party
9
+ import six
10
+ from wcwidth import wcwidth
11
+
12
+ # local
13
+ from blessed._capabilities import CAPABILITIES_CAUSE_MOVEMENT
14
+
15
+ __all__ = ('Sequence', 'SequenceTextWrapper', 'iter_parse', 'measure_length')
16
+
17
+
18
+ class Termcap(object):
19
+ """Terminal capability of given variable name and pattern."""
20
+
21
+ def __init__(self, name, pattern, attribute):
22
+ """
23
+ Class initializer.
24
+
25
+ :arg str name: name describing capability.
26
+ :arg str pattern: regular expression string.
27
+ :arg str attribute: :class:`~.Terminal` attribute used to build
28
+ this terminal capability.
29
+ """
30
+ self.name = name
31
+ self.pattern = pattern
32
+ self.attribute = attribute
33
+ self._re_compiled = None
34
+
35
+ def __repr__(self):
36
+ # pylint: disable=redundant-keyword-arg
37
+ return '<Termcap {self.name}:{self.pattern!r}>'.format(self=self)
38
+
39
+ @property
40
+ def named_pattern(self):
41
+ """Regular expression pattern for capability with named group."""
42
+ # pylint: disable=redundant-keyword-arg
43
+ return '(?P<{self.name}>{self.pattern})'.format(self=self)
44
+
45
+ @property
46
+ def re_compiled(self):
47
+ """Compiled regular expression pattern for capability."""
48
+ if self._re_compiled is None:
49
+ self._re_compiled = re.compile(self.pattern)
50
+ return self._re_compiled
51
+
52
+ @property
53
+ def will_move(self):
54
+ """Whether capability causes cursor movement."""
55
+ return self.name in CAPABILITIES_CAUSE_MOVEMENT
56
+
57
+ def horizontal_distance(self, text):
58
+ """
59
+ Horizontal carriage adjusted by capability, may be negative.
60
+
61
+ :rtype: int
62
+ :arg str text: for capabilities *parm_left_cursor*,
63
+ *parm_right_cursor*, provide the matching sequence
64
+ text, its interpreted distance is returned.
65
+
66
+ :returns: 0 except for matching '
67
+ """
68
+ value = {
69
+ 'cursor_left': -1,
70
+ 'backspace': -1,
71
+ 'cursor_right': 1,
72
+ 'tab': 8,
73
+ 'ascii_tab': 8,
74
+ }.get(self.name)
75
+ if value is not None:
76
+ return value
77
+
78
+ unit = {
79
+ 'parm_left_cursor': -1,
80
+ 'parm_right_cursor': 1
81
+ }.get(self.name)
82
+ if unit is not None:
83
+ value = int(self.re_compiled.match(text).group(1))
84
+ return unit * value
85
+
86
+ return 0
87
+
88
+ # pylint: disable=too-many-arguments
89
+ @classmethod
90
+ def build(cls, name, capability, attribute, nparams=0,
91
+ numeric=99, match_grouped=False, match_any=False,
92
+ match_optional=False):
93
+ r"""
94
+ Class factory builder for given capability definition.
95
+
96
+ :arg str name: Variable name given for this pattern.
97
+ :arg str capability: A unicode string representing a terminal
98
+ capability to build for. When ``nparams`` is non-zero, it
99
+ must be a callable unicode string (such as the result from
100
+ ``getattr(term, 'bold')``.
101
+ :arg str attribute: The terminfo(5) capability name by which this
102
+ pattern is known.
103
+ :arg int nparams: number of positional arguments for callable.
104
+ :arg int numeric: Value to substitute into capability to when generating pattern
105
+ :arg bool match_grouped: If the numeric pattern should be
106
+ grouped, ``(\d+)`` when ``True``, ``\d+`` default.
107
+ :arg bool match_any: When keyword argument ``nparams`` is given,
108
+ *any* numeric found in output is suitable for building as
109
+ pattern ``(\d+)``. Otherwise, only the first matching value of
110
+ range *(numeric - 1)* through *(numeric + 1)* will be replaced by
111
+ pattern ``(\d+)`` in builder.
112
+ :arg bool match_optional: When ``True``, building of numeric patterns
113
+ containing ``(\d+)`` will be built as optional, ``(\d+)?``.
114
+ :rtype: blessed.sequences.Termcap
115
+ :returns: Terminal capability instance for given capability definition
116
+ """
117
+ _numeric_regex = r'\d+'
118
+ if match_grouped:
119
+ _numeric_regex = r'(\d+)'
120
+ if match_optional:
121
+ _numeric_regex = r'(\d+)?'
122
+ numeric = 99 if numeric is None else numeric
123
+
124
+ # basic capability attribute, not used as a callable
125
+ if nparams == 0:
126
+ return cls(name, re.escape(capability), attribute)
127
+
128
+ # a callable capability accepting numeric argument
129
+ _outp = re.escape(capability(*(numeric,) * nparams))
130
+ if not match_any:
131
+ for num in range(numeric - 1, numeric + 2):
132
+ if str(num) in _outp:
133
+ pattern = _outp.replace(str(num), _numeric_regex)
134
+ return cls(name, pattern, attribute)
135
+
136
+ if match_grouped:
137
+ pattern = re.sub(r'(\d+)', lambda x: _numeric_regex, _outp)
138
+ else:
139
+ pattern = re.sub(r'\d+', lambda x: _numeric_regex, _outp)
140
+ return cls(name, pattern, attribute)
141
+
142
+
143
+ class SequenceTextWrapper(textwrap.TextWrapper):
144
+ """Docstring overridden."""
145
+
146
+ def __init__(self, width, term, **kwargs):
147
+ """
148
+ Class initializer.
149
+
150
+ This class supports the :meth:`~.Terminal.wrap` method.
151
+ """
152
+ self.term = term
153
+ textwrap.TextWrapper.__init__(self, width, **kwargs)
154
+
155
+ def _wrap_chunks(self, chunks):
156
+ """
157
+ Sequence-aware variant of :meth:`textwrap.TextWrapper._wrap_chunks`.
158
+
159
+ :raises ValueError: ``self.width`` is not a positive integer
160
+ :rtype: list
161
+ :returns: text chunks adjusted for width
162
+
163
+ This simply ensures that word boundaries are not broken mid-sequence, as standard python
164
+ textwrap would incorrectly determine the length of a string containing sequences, and may
165
+ also break consider sequences part of a "word" that may be broken by hyphen (``-``), where
166
+ this implementation corrects both.
167
+ """
168
+ lines = []
169
+ if self.width <= 0 or not isinstance(self.width, int):
170
+ raise ValueError(
171
+ "invalid width {0!r}({1!r}) (must be integer > 0)"
172
+ .format(self.width, type(self.width)))
173
+
174
+ term = self.term
175
+ drop_whitespace = not hasattr(self, 'drop_whitespace'
176
+ ) or self.drop_whitespace
177
+ chunks.reverse()
178
+ while chunks:
179
+ cur_line = []
180
+ cur_len = 0
181
+ indent = self.subsequent_indent if lines else self.initial_indent
182
+ width = self.width - len(indent)
183
+ if drop_whitespace and (
184
+ Sequence(chunks[-1], term).strip() == '' and lines):
185
+ del chunks[-1]
186
+ while chunks:
187
+ chunk_len = Sequence(chunks[-1], term).length()
188
+ if cur_len + chunk_len > width:
189
+ break
190
+ cur_line.append(chunks.pop())
191
+ cur_len += chunk_len
192
+ if chunks and Sequence(chunks[-1], term).length() > width:
193
+ self._handle_long_word(chunks, cur_line, cur_len, width)
194
+ if drop_whitespace and (
195
+ cur_line and Sequence(cur_line[-1], term).strip() == ''):
196
+ del cur_line[-1]
197
+ if cur_line:
198
+ lines.append(indent + u''.join(cur_line))
199
+ return lines
200
+
201
+ def _handle_long_word(self, reversed_chunks, cur_line, cur_len, width):
202
+ """
203
+ Sequence-aware :meth:`textwrap.TextWrapper._handle_long_word`.
204
+
205
+ This simply ensures that word boundaries are not broken mid-sequence, as standard python
206
+ textwrap would incorrectly determine the length of a string containing sequences, and may
207
+ also break consider sequences part of a "word" that may be broken by hyphen (``-``), where
208
+ this implementation corrects both.
209
+ """
210
+ # Figure out when indent is larger than the specified width, and make
211
+ # sure at least one character is stripped off on every pass
212
+ space_left = 1 if width < 1 else width - cur_len
213
+ # If we're allowed to break long words, then do so: put as much
214
+ # of the next chunk onto the current line as will fit.
215
+
216
+ if self.break_long_words:
217
+ term = self.term
218
+ chunk = reversed_chunks[-1]
219
+ idx = nxt = 0
220
+ for text, _ in iter_parse(term, chunk):
221
+ nxt += len(text)
222
+ if Sequence(chunk[:nxt], term).length() > space_left:
223
+ break
224
+ idx = nxt
225
+ cur_line.append(chunk[:idx])
226
+ reversed_chunks[-1] = chunk[idx:]
227
+
228
+ # Otherwise, we have to preserve the long word intact. Only add
229
+ # it to the current line if there's nothing already there --
230
+ # that minimizes how much we violate the width constraint.
231
+ elif not cur_line:
232
+ cur_line.append(reversed_chunks.pop())
233
+
234
+ # If we're not allowed to break long words, and there's already
235
+ # text on the current line, do nothing. Next time through the
236
+ # main loop of _wrap_chunks(), we'll wind up here again, but
237
+ # cur_len will be zero, so the next line will be entirely
238
+ # devoted to the long word that we can't handle right now.
239
+
240
+
241
+ SequenceTextWrapper.__doc__ = textwrap.TextWrapper.__doc__
242
+
243
+
244
+ class Sequence(six.text_type):
245
+ """
246
+ A "sequence-aware" version of the base :class:`str` class.
247
+
248
+ This unicode-derived class understands the effect of escape sequences
249
+ of printable length, allowing a properly implemented :meth:`rjust`,
250
+ :meth:`ljust`, :meth:`center`, and :meth:`length`.
251
+ """
252
+
253
+ def __new__(cls, sequence_text, term):
254
+ # pylint: disable = missing-return-doc, missing-return-type-doc
255
+ """
256
+ Class constructor.
257
+
258
+ :arg str sequence_text: A string that may contain sequences.
259
+ :arg blessed.Terminal term: :class:`~.Terminal` instance.
260
+ """
261
+ new = six.text_type.__new__(cls, sequence_text)
262
+ new._term = term
263
+ return new
264
+
265
+ def ljust(self, width, fillchar=u' '):
266
+ """
267
+ Return string containing sequences, left-adjusted.
268
+
269
+ :arg int width: Total width given to left-adjust ``text``. If
270
+ unspecified, the width of the attached terminal is used (default).
271
+ :arg str fillchar: String for padding right-of ``text``.
272
+ :returns: String of ``text``, left-aligned by ``width``.
273
+ :rtype: str
274
+ """
275
+ rightside = fillchar * int(
276
+ (max(0.0, float(width.__index__() - self.length()))) / float(len(fillchar)))
277
+ return u''.join((self, rightside))
278
+
279
+ def rjust(self, width, fillchar=u' '):
280
+ """
281
+ Return string containing sequences, right-adjusted.
282
+
283
+ :arg int width: Total width given to right-adjust ``text``. If
284
+ unspecified, the width of the attached terminal is used (default).
285
+ :arg str fillchar: String for padding left-of ``text``.
286
+ :returns: String of ``text``, right-aligned by ``width``.
287
+ :rtype: str
288
+ """
289
+ leftside = fillchar * int(
290
+ (max(0.0, float(width.__index__() - self.length()))) / float(len(fillchar)))
291
+ return u''.join((leftside, self))
292
+
293
+ def center(self, width, fillchar=u' '):
294
+ """
295
+ Return string containing sequences, centered.
296
+
297
+ :arg int width: Total width given to center ``text``. If
298
+ unspecified, the width of the attached terminal is used (default).
299
+ :arg str fillchar: String for padding left and right-of ``text``.
300
+ :returns: String of ``text``, centered by ``width``.
301
+ :rtype: str
302
+ """
303
+ split = max(0.0, float(width.__index__()) - self.length()) / 2
304
+ leftside = fillchar * int(
305
+ (max(0.0, math.floor(split))) / float(len(fillchar)))
306
+ rightside = fillchar * int(
307
+ (max(0.0, math.ceil(split))) / float(len(fillchar)))
308
+ return u''.join((leftside, self, rightside))
309
+
310
+ def truncate(self, width):
311
+ """
312
+ Truncate a string in a sequence-aware manner.
313
+
314
+ Any printable characters beyond ``width`` are removed, while all
315
+ sequences remain in place. Horizontal Sequences are first expanded
316
+ by :meth:`padd`.
317
+
318
+ :arg int width: The printable width to truncate the string to.
319
+ :rtype: str
320
+ :returns: String truncated to at most ``width`` printable characters.
321
+ """
322
+ output = ""
323
+ current_width = 0
324
+ target_width = width.__index__()
325
+ parsed_seq = iter_parse(self._term, self.padd())
326
+
327
+ # Retain all text until non-cap width reaches desired width
328
+ for text, cap in parsed_seq:
329
+ if not cap:
330
+ # use wcwidth clipped to 0 because it can sometimes return -1
331
+ current_width += max(wcwidth(text), 0)
332
+ if current_width > target_width:
333
+ break
334
+ output += text
335
+
336
+ # Return with remaining caps appended
337
+ return output + ''.join(text for text, cap in parsed_seq if cap)
338
+
339
+ def length(self):
340
+ r"""
341
+ Return the printable length of string containing sequences.
342
+
343
+ Strings containing ``term.left`` or ``\b`` will cause "overstrike",
344
+ but a length less than 0 is not ever returned. So ``_\b+`` is a
345
+ length of 1 (displays as ``+``), but ``\b`` alone is simply a
346
+ length of 0.
347
+
348
+ Some characters may consume more than one cell, mainly those CJK
349
+ Unified Ideographs (Chinese, Japanese, Korean) defined by Unicode
350
+ as half or full-width characters.
351
+
352
+ For example:
353
+
354
+ >>> from blessed import Terminal
355
+ >>> from blessed.sequences import Sequence
356
+ >>> term = Terminal()
357
+ >>> msg = term.clear + term.red(u'コンニチハ')
358
+ >>> Sequence(msg, term).length()
359
+ 10
360
+
361
+ .. note:: Although accounted for, strings containing sequences such
362
+ as ``term.clear`` will not give accurate returns, it is not
363
+ considered lengthy (a length of 0).
364
+ """
365
+ # because control characters may return -1, "clip" their length to 0.
366
+ return sum(max(wcwidth(w_char), 0) for w_char in self.padd(strip=True))
367
+
368
+ def strip(self, chars=None):
369
+ """
370
+ Return string of sequences, leading and trailing whitespace removed.
371
+
372
+ :arg str chars: Remove characters in chars instead of whitespace.
373
+ :rtype: str
374
+ :returns: string of sequences with leading and trailing whitespace removed.
375
+ """
376
+ return self.strip_seqs().strip(chars)
377
+
378
+ def lstrip(self, chars=None):
379
+ """
380
+ Return string of all sequences and leading whitespace removed.
381
+
382
+ :arg str chars: Remove characters in chars instead of whitespace.
383
+ :rtype: str
384
+ :returns: string of sequences with leading removed.
385
+ """
386
+ return self.strip_seqs().lstrip(chars)
387
+
388
+ def rstrip(self, chars=None):
389
+ """
390
+ Return string of all sequences and trailing whitespace removed.
391
+
392
+ :arg str chars: Remove characters in chars instead of whitespace.
393
+ :rtype: str
394
+ :returns: string of sequences with trailing removed.
395
+ """
396
+ return self.strip_seqs().rstrip(chars)
397
+
398
+ def strip_seqs(self):
399
+ """
400
+ Return ``text`` stripped of only its terminal sequences.
401
+
402
+ :rtype: str
403
+ :returns: Text with terminal sequences removed
404
+ """
405
+ return self.padd(strip=True)
406
+
407
+ def padd(self, strip=False):
408
+ """
409
+ Return non-destructive horizontal movement as destructive spacing.
410
+
411
+ :arg bool strip: Strip terminal sequences
412
+ :rtype: str
413
+ :returns: Text adjusted for horizontal movement
414
+ """
415
+ outp = ''
416
+ for text, cap in iter_parse(self._term, self):
417
+ if not cap:
418
+ outp += text
419
+ continue
420
+
421
+ value = cap.horizontal_distance(text)
422
+ if value > 0:
423
+ outp += ' ' * value
424
+ elif value < 0:
425
+ outp = outp[:value]
426
+ elif not strip:
427
+ outp += text
428
+ return outp
429
+
430
+
431
+ def iter_parse(term, text):
432
+ """
433
+ Generator yields (text, capability) for characters of ``text``.
434
+
435
+ value for ``capability`` may be ``None``, where ``text`` is
436
+ :class:`str` of length 1. Otherwise, ``text`` is a full
437
+ matching sequence of given capability.
438
+ """
439
+ for match in term._caps_compiled_any.finditer(text): # pylint: disable=protected-access
440
+ name = match.lastgroup
441
+ value = match.group(name)
442
+ if name == 'MISMATCH':
443
+ yield (value, None)
444
+ else:
445
+ yield value, term.caps[name]
446
+
447
+
448
+ def measure_length(text, term):
449
+ """
450
+ .. deprecated:: 1.12.0.
451
+
452
+ :rtype: int
453
+ :returns: Length of the first sequence in the string
454
+ """
455
+ try:
456
+ text, capability = next(iter_parse(term, text))
457
+ if capability:
458
+ return len(text)
459
+ except StopIteration:
460
+ return 0
461
+ return 0
vllm/lib/python3.10/site-packages/blessed/sequences.pyi ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # std imports
2
+ import textwrap
3
+ from typing import Any, Type, Tuple, Pattern, TypeVar, Iterator, Optional, SupportsIndex
4
+
5
+ # local
6
+ from .terminal import Terminal
7
+
8
+ _T = TypeVar("_T")
9
+
10
+ class Termcap:
11
+ name: str = ...
12
+ pattern: str = ...
13
+ attribute: str = ...
14
+ def __init__(self, name: str, pattern: str, attribute: str) -> None: ...
15
+ @property
16
+ def named_pattern(self) -> str: ...
17
+ @property
18
+ def re_compiled(self) -> Pattern[str]: ...
19
+ @property
20
+ def will_move(self) -> bool: ...
21
+ def horizontal_distance(self, text: str) -> int: ...
22
+ @classmethod
23
+ def build(
24
+ cls,
25
+ name: str,
26
+ capability: str,
27
+ attribute: str,
28
+ nparams: int = ...,
29
+ numeric: int = ...,
30
+ match_grouped: bool = ...,
31
+ match_any: bool = ...,
32
+ match_optional: bool = ...,
33
+ ) -> "Termcap": ...
34
+
35
+ class SequenceTextWrapper(textwrap.TextWrapper):
36
+ term: Terminal = ...
37
+ def __init__(self, width: int, term: Terminal, **kwargs: Any) -> None: ...
38
+
39
+ class Sequence(str):
40
+ def __new__(cls: Type[_T], sequence_text: str, term: Terminal) -> _T: ...
41
+ def ljust(self, width: SupportsIndex, fillchar: str = ...) -> str: ...
42
+ def rjust(self, width: SupportsIndex, fillchar: str = ...) -> str: ...
43
+ def center(self, width: SupportsIndex, fillchar: str = ...) -> str: ...
44
+ def truncate(self, width: SupportsIndex) -> str: ...
45
+ def length(self) -> int: ...
46
+ def strip(self, chars: Optional[str] = ...) -> str: ...
47
+ def lstrip(self, chars: Optional[str] = ...) -> str: ...
48
+ def rstrip(self, chars: Optional[str] = ...) -> str: ...
49
+ def strip_seqs(self) -> str: ...
50
+ def padd(self, strip: bool = ...) -> str: ...
51
+
52
+ def iter_parse(
53
+ term: Terminal, text: str
54
+ ) -> Iterator[Tuple[str, Optional[Termcap]]]: ...
55
+ def measure_length(text: str, term: Terminal) -> int: ...
vllm/lib/python3.10/site-packages/blessed/terminal.py ADDED
@@ -0,0 +1,1552 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # pylint: disable=too-many-lines
3
+ """Module containing :class:`Terminal`, the primary API entry point."""
4
+ # std imports
5
+ import os
6
+ import re
7
+ import sys
8
+ import time
9
+ import codecs
10
+ import locale
11
+ import select
12
+ import struct
13
+ import platform
14
+ import warnings
15
+ import functools
16
+ import contextlib
17
+ import collections
18
+
19
+ # local
20
+ from .color import COLOR_DISTANCE_ALGORITHMS
21
+ from .keyboard import (_time_left,
22
+ _read_until,
23
+ resolve_sequence,
24
+ get_keyboard_codes,
25
+ get_leading_prefixes,
26
+ get_keyboard_sequences)
27
+ from .sequences import Termcap, Sequence, SequenceTextWrapper
28
+ from .colorspace import RGB_256TABLE
29
+ from .formatters import (COLORS,
30
+ COMPOUNDABLES,
31
+ FormattingString,
32
+ NullCallableString,
33
+ ParameterizingString,
34
+ FormattingOtherString,
35
+ split_compound,
36
+ resolve_attribute,
37
+ resolve_capability)
38
+ from ._capabilities import CAPABILITY_DATABASE, CAPABILITIES_ADDITIVES, CAPABILITIES_RAW_MIXIN
39
+
40
+ # isort: off
41
+
42
+ # Alias py2 exception to py3
43
+ if sys.version_info[:2] < (3, 3):
44
+ InterruptedError = select.error # pylint: disable=redefined-builtin
45
+
46
+
47
+ HAS_TTY = True
48
+ if platform.system() == 'Windows':
49
+ IS_WINDOWS = True
50
+ import jinxed as curses # pylint: disable=import-error
51
+ from jinxed.win32 import get_console_input_encoding # pylint: disable=import-error
52
+ else:
53
+ IS_WINDOWS = False
54
+ import curses
55
+
56
+ try:
57
+ import fcntl
58
+ import termios
59
+ import tty
60
+ except ImportError:
61
+ _TTY_METHODS = ('setraw', 'cbreak', 'kbhit', 'height', 'width')
62
+ _MSG_NOSUPPORT = (
63
+ "One or more of the modules: 'termios', 'fcntl', and 'tty' "
64
+ "are not found on your platform '{platform}'. "
65
+ "The following methods of Terminal are dummy/no-op "
66
+ "unless a deriving class overrides them: {tty_methods}."
67
+ .format(platform=platform.system(),
68
+ tty_methods=', '.join(_TTY_METHODS)))
69
+ warnings.warn(_MSG_NOSUPPORT)
70
+ HAS_TTY = False
71
+
72
+ _CUR_TERM = None # See comments at end of file
73
+
74
+
75
+ class Terminal(object):
76
+ """
77
+ An abstraction for color, style, positioning, and input in the terminal.
78
+
79
+ This keeps the endless calls to ``tigetstr()`` and ``tparm()`` out of your code, acts
80
+ intelligently when somebody pipes your output to a non-terminal, and abstracts over the
81
+ complexity of unbuffered keyboard input. It uses the terminfo database to remain portable across
82
+ terminal types.
83
+ """
84
+ # pylint: disable=too-many-instance-attributes,too-many-public-methods
85
+ # Too many public methods (28/20)
86
+ # Too many instance attributes (12/7)
87
+
88
+ #: Sugary names for commonly-used capabilities
89
+ _sugar = {
90
+ 'save': 'sc',
91
+ 'restore': 'rc',
92
+ 'clear_eol': 'el',
93
+ 'clear_bol': 'el1',
94
+ 'clear_eos': 'ed',
95
+ 'enter_fullscreen': 'smcup',
96
+ 'exit_fullscreen': 'rmcup',
97
+ 'move': 'cup',
98
+ 'move_yx': 'cup',
99
+ 'move_x': 'hpa',
100
+ 'move_y': 'vpa',
101
+ 'hide_cursor': 'civis',
102
+ 'normal_cursor': 'cnorm',
103
+ 'reset_colors': 'op',
104
+ 'normal': 'sgr0',
105
+ 'reverse': 'rev',
106
+ 'italic': 'sitm',
107
+ 'no_italic': 'ritm',
108
+ 'shadow': 'sshm',
109
+ 'no_shadow': 'rshm',
110
+ 'standout': 'smso',
111
+ 'no_standout': 'rmso',
112
+ 'subscript': 'ssubm',
113
+ 'no_subscript': 'rsubm',
114
+ 'superscript': 'ssupm',
115
+ 'no_superscript': 'rsupm',
116
+ 'underline': 'smul',
117
+ 'no_underline': 'rmul',
118
+ 'cursor_report': 'u6',
119
+ 'cursor_request': 'u7',
120
+ 'terminal_answerback': 'u8',
121
+ 'terminal_enquire': 'u9',
122
+ }
123
+
124
+ def __init__(self, kind=None, stream=None, force_styling=False):
125
+ """
126
+ Initialize the terminal.
127
+
128
+ :arg str kind: A terminal string as taken by :func:`curses.setupterm`.
129
+ Defaults to the value of the ``TERM`` environment variable.
130
+
131
+ .. note:: Terminals withing a single process must share a common
132
+ ``kind``. See :obj:`_CUR_TERM`.
133
+
134
+ :arg file stream: A file-like object representing the Terminal output.
135
+ Defaults to the original value of :obj:`sys.__stdout__`, like
136
+ :func:`curses.initscr` does.
137
+
138
+ If ``stream`` is not a tty, empty Unicode strings are returned for
139
+ all capability values, so things like piping your program output to
140
+ a pipe or file does not emit terminal sequences.
141
+
142
+ :arg bool force_styling: Whether to force the emission of capabilities
143
+ even if :obj:`sys.__stdout__` does not seem to be connected to a
144
+ terminal. If you want to force styling to not happen, use
145
+ ``force_styling=None``.
146
+
147
+ This comes in handy if users are trying to pipe your output through
148
+ something like ``less -r`` or build systems which support decoding
149
+ of terminal sequences.
150
+ """
151
+ # pylint: disable=global-statement,too-many-branches
152
+ global _CUR_TERM
153
+ self.errors = ['parameters: kind=%r, stream=%r, force_styling=%r' %
154
+ (kind, stream, force_styling)]
155
+ self._normal = None # cache normal attr, preventing recursive lookups
156
+ # we assume our input stream to be line-buffered until either the
157
+ # cbreak of raw context manager methods are entered with an attached tty.
158
+ self._line_buffered = True
159
+
160
+ self._stream = stream
161
+ self._keyboard_fd = None
162
+ self._init_descriptor = None
163
+ self._is_a_tty = False
164
+ self.__init__streams()
165
+
166
+ if IS_WINDOWS and self._init_descriptor is not None:
167
+ self._kind = kind or curses.get_term(self._init_descriptor)
168
+ else:
169
+ self._kind = kind or os.environ.get('TERM', 'dumb') or 'dumb'
170
+
171
+ self._does_styling = False
172
+ if force_styling is None and self.is_a_tty:
173
+ self.errors.append('force_styling is None')
174
+ elif force_styling or self.is_a_tty:
175
+ self._does_styling = True
176
+
177
+ if self.does_styling:
178
+ # Initialize curses (call setupterm), so things like tigetstr() work.
179
+ try:
180
+ curses.setupterm(self._kind, self._init_descriptor)
181
+ except curses.error as err:
182
+ msg = 'Failed to setupterm(kind={0!r}): {1}'.format(self._kind, err)
183
+ warnings.warn(msg)
184
+ self.errors.append(msg)
185
+ self._kind = None
186
+ self._does_styling = False
187
+ else:
188
+ if _CUR_TERM is None or self._kind == _CUR_TERM:
189
+ _CUR_TERM = self._kind
190
+ else:
191
+ # termcap 'kind' is immutable in a python process! Once
192
+ # initialized by setupterm, it is unsupported by the
193
+ # 'curses' module to change the terminal type again. If you
194
+ # are a downstream developer and you need this
195
+ # functionality, consider sub-processing, instead.
196
+ warnings.warn(
197
+ 'A terminal of kind "%s" has been requested; due to an'
198
+ ' internal python curses bug, terminal capabilities'
199
+ ' for a terminal of kind "%s" will continue to be'
200
+ ' returned for the remainder of this process.' % (
201
+ self._kind, _CUR_TERM,))
202
+
203
+ self.__init__color_capabilities()
204
+ self.__init__capabilities()
205
+ self.__init__keycodes()
206
+
207
+ def __init__streams(self):
208
+ # pylint: disable=too-complex,too-many-branches
209
+ # Agree to disagree !
210
+ stream_fd = None
211
+
212
+ # Default stream is stdout
213
+ if self._stream is None:
214
+ self._stream = sys.__stdout__
215
+
216
+ if not hasattr(self._stream, 'fileno'):
217
+ self.errors.append('stream has no fileno method')
218
+ elif not callable(self._stream.fileno):
219
+ self.errors.append('stream.fileno is not callable')
220
+ else:
221
+ try:
222
+ stream_fd = self._stream.fileno()
223
+ except ValueError as err:
224
+ # The stream is not a file, such as the case of StringIO, or, when it has been
225
+ # "detached", such as might be the case of stdout in some test scenarios.
226
+ self.errors.append('Unable to determine output stream file descriptor: %s' % err)
227
+ else:
228
+ self._is_a_tty = os.isatty(stream_fd)
229
+ if not self._is_a_tty:
230
+ self.errors.append('stream not a TTY')
231
+
232
+ # Keyboard valid as stdin only when output stream is stdout or stderr and is a tty.
233
+ if self._stream in (sys.__stdout__, sys.__stderr__):
234
+ try:
235
+ self._keyboard_fd = sys.__stdin__.fileno()
236
+ except (AttributeError, ValueError) as err:
237
+ self.errors.append('Unable to determine input stream file descriptor: %s' % err)
238
+ else:
239
+ # _keyboard_fd only non-None if both stdin and stdout is a tty.
240
+ if not self.is_a_tty:
241
+ self.errors.append('Output stream is not a TTY')
242
+ self._keyboard_fd = None
243
+ elif not os.isatty(self._keyboard_fd):
244
+ self.errors.append('Input stream is not a TTY')
245
+ self._keyboard_fd = None
246
+ else:
247
+ self.errors.append('Output stream is not a default stream')
248
+
249
+ # The descriptor to direct terminal initialization sequences to.
250
+ self._init_descriptor = stream_fd
251
+ if stream_fd is None:
252
+ try:
253
+ self._init_descriptor = sys.__stdout__.fileno()
254
+ except ValueError as err:
255
+ self.errors.append('Unable to determine __stdout__ file descriptor: %s' % err)
256
+
257
+ def __init__color_capabilities(self):
258
+ self._color_distance_algorithm = 'cie2000'
259
+ if not self.does_styling:
260
+ self.number_of_colors = 0
261
+ elif IS_WINDOWS or os.environ.get('COLORTERM') in ('truecolor', '24bit'):
262
+ self.number_of_colors = 1 << 24
263
+ else:
264
+ self.number_of_colors = max(0, curses.tigetnum('colors') or -1)
265
+
266
+ def __clear_color_capabilities(self):
267
+ for cached_color_cap in set(dir(self)) & COLORS:
268
+ delattr(self, cached_color_cap)
269
+
270
+ def __init__capabilities(self):
271
+ # important that we lay these in their ordered direction, so that our
272
+ # preferred, 'color' over 'set_a_attributes1', for example.
273
+ self.caps = collections.OrderedDict()
274
+
275
+ # some static injected patterns, esp. without named attribute access.
276
+ for name, (attribute, pattern) in CAPABILITIES_ADDITIVES.items():
277
+ self.caps[name] = Termcap(name, pattern, attribute)
278
+
279
+ for name, (attribute, kwds) in CAPABILITY_DATABASE.items():
280
+ if self.does_styling:
281
+ # attempt dynamic lookup
282
+ cap = getattr(self, attribute)
283
+ if cap:
284
+ self.caps[name] = Termcap.build(
285
+ name, cap, attribute, **kwds)
286
+ continue
287
+
288
+ # fall-back
289
+ pattern = CAPABILITIES_RAW_MIXIN.get(name)
290
+ if pattern:
291
+ self.caps[name] = Termcap(name, pattern, attribute)
292
+
293
+ # make a compiled named regular expression table
294
+ self.caps_compiled = re.compile(
295
+ '|'.join(cap.pattern for name, cap in self.caps.items()))
296
+
297
+ # for tokenizer, the '.lastgroup' is the primary lookup key for
298
+ # 'self.caps', unless 'MISMATCH'; then it is an unmatched character.
299
+ self._caps_compiled_any = re.compile('|'.join(
300
+ cap.named_pattern for name, cap in self.caps.items()
301
+ ) + '|(?P<MISMATCH>.)')
302
+ self._caps_unnamed_any = re.compile('|'.join(
303
+ '({0})'.format(cap.pattern) for name, cap in self.caps.items()
304
+ ) + '|(.)')
305
+
306
+ def __init__keycodes(self):
307
+ # Initialize keyboard data determined by capability.
308
+ # Build database of int code <=> KEY_NAME.
309
+ self._keycodes = get_keyboard_codes()
310
+
311
+ # Store attributes as: self.KEY_NAME = code.
312
+ for key_code, key_name in self._keycodes.items():
313
+ setattr(self, key_name, key_code)
314
+
315
+ # Build database of sequence <=> KEY_NAME.
316
+ self._keymap = get_keyboard_sequences(self)
317
+
318
+ # build set of prefixes of sequences
319
+ self._keymap_prefixes = get_leading_prefixes(self._keymap)
320
+
321
+ # keyboard stream buffer
322
+ self._keyboard_buf = collections.deque()
323
+
324
+ if self._keyboard_fd is not None:
325
+ # set input encoding and initialize incremental decoder
326
+
327
+ if IS_WINDOWS:
328
+ self._encoding = get_console_input_encoding() \
329
+ or locale.getpreferredencoding() or 'UTF-8'
330
+ else:
331
+ self._encoding = locale.getpreferredencoding() or 'UTF-8'
332
+
333
+ try:
334
+ self._keyboard_decoder = codecs.getincrementaldecoder(self._encoding)()
335
+ except LookupError as err:
336
+ # encoding is illegal or unsupported, use 'UTF-8'
337
+ warnings.warn('LookupError: {0}, defaulting to UTF-8 for keyboard.'.format(err))
338
+ self._encoding = 'UTF-8'
339
+ self._keyboard_decoder = codecs.getincrementaldecoder(self._encoding)()
340
+
341
+ def __getattr__(self, attr):
342
+ r"""
343
+ Return a terminal capability as Unicode string.
344
+
345
+ For example, ``term.bold`` is a unicode string that may be prepended
346
+ to text to set the video attribute for bold, which should also be
347
+ terminated with the pairing :attr:`normal`. This capability
348
+ returns a callable, so you can use ``term.bold("hi")`` which
349
+ results in the joining of ``(term.bold, "hi", term.normal)``.
350
+
351
+ Compound formatters may also be used. For example::
352
+
353
+ >>> term.bold_blink_red_on_green("merry x-mas!")
354
+
355
+ For a parameterized capability such as ``move`` (or ``cup``), pass the
356
+ parameters as positional arguments::
357
+
358
+ >>> term.move(line, column)
359
+
360
+ See the manual page `terminfo(5)
361
+ <https://invisible-island.net/ncurses/man/terminfo.5.html>`_ for a
362
+ complete list of capabilities and their arguments.
363
+ """
364
+ if not self._does_styling:
365
+ return NullCallableString()
366
+ # Fetch the missing 'attribute' into some kind of curses-resolved
367
+ # capability, and cache by attaching to this Terminal class instance.
368
+ #
369
+ # Note that this will prevent future calls to __getattr__(), but
370
+ # that's precisely the idea of the cache!
371
+ val = resolve_attribute(self, attr)
372
+ setattr(self, attr, val)
373
+ return val
374
+
375
+ @property
376
+ def kind(self):
377
+ """
378
+ Read-only property: Terminal kind determined on class initialization.
379
+
380
+ :rtype: str
381
+ """
382
+ return self._kind
383
+
384
+ @property
385
+ def does_styling(self):
386
+ """
387
+ Read-only property: Whether this class instance may emit sequences.
388
+
389
+ :rtype: bool
390
+ """
391
+ return self._does_styling
392
+
393
+ @property
394
+ def is_a_tty(self):
395
+ """
396
+ Read-only property: Whether :attr:`~.stream` is a terminal.
397
+
398
+ :rtype: bool
399
+ """
400
+ return self._is_a_tty
401
+
402
+ @property
403
+ def height(self):
404
+ """
405
+ Read-only property: Height of the terminal (in number of lines).
406
+
407
+ :rtype: int
408
+ """
409
+ return self._height_and_width().ws_row
410
+
411
+ @property
412
+ def width(self):
413
+ """
414
+ Read-only property: Width of the terminal (in number of columns).
415
+
416
+ :rtype: int
417
+ """
418
+ return self._height_and_width().ws_col
419
+
420
+ @property
421
+ def pixel_height(self):
422
+ """
423
+ Read-only property: Height ofthe terminal (in pixels).
424
+
425
+ :rtype: int
426
+ """
427
+ return self._height_and_width().ws_ypixel
428
+
429
+ @property
430
+ def pixel_width(self):
431
+ """
432
+ Read-only property: Width of terminal (in pixels).
433
+
434
+ :rtype: int
435
+ """
436
+ return self._height_and_width().ws_xpixel
437
+
438
+ @staticmethod
439
+ def _winsize(fd):
440
+ """
441
+ Return named tuple describing size of the terminal by ``fd``.
442
+
443
+ If the given platform does not have modules :mod:`termios`,
444
+ :mod:`fcntl`, or :mod:`tty`, window size of 80 columns by 25
445
+ rows is always returned.
446
+
447
+ :arg int fd: file descriptor queries for its window size.
448
+ :raises IOError: the file descriptor ``fd`` is not a terminal.
449
+ :rtype: WINSZ
450
+ :returns: named tuple describing size of the terminal
451
+
452
+ WINSZ is a :class:`collections.namedtuple` instance, whose structure
453
+ directly maps to the return value of the :const:`termios.TIOCGWINSZ`
454
+ ioctl return value. The return parameters are:
455
+
456
+ - ``ws_row``: width of terminal by its number of character cells.
457
+ - ``ws_col``: height of terminal by its number of character cells.
458
+ - ``ws_xpixel``: width of terminal by pixels (not accurate).
459
+ - ``ws_ypixel``: height of terminal by pixels (not accurate).
460
+ """
461
+ if HAS_TTY:
462
+ # pylint: disable=protected-access
463
+ data = fcntl.ioctl(fd, termios.TIOCGWINSZ, WINSZ._BUF)
464
+ return WINSZ(*struct.unpack(WINSZ._FMT, data))
465
+ return WINSZ(ws_row=25, ws_col=80, ws_xpixel=0, ws_ypixel=0)
466
+
467
+ def _height_and_width(self):
468
+ """
469
+ Return a tuple of (terminal height, terminal width).
470
+
471
+ If :attr:`stream` or :obj:`sys.__stdout__` is not a tty or does not
472
+ support :func:`fcntl.ioctl` of :const:`termios.TIOCGWINSZ`, a window
473
+ size of 80 columns by 25 rows is returned for any values not
474
+ represented by environment variables ``LINES`` and ``COLUMNS``, which
475
+ is the default text mode of IBM PC compatibles.
476
+
477
+ :rtype: WINSZ
478
+ :returns: Named tuple specifying the terminal size
479
+
480
+ WINSZ is a :class:`collections.namedtuple` instance, whose structure
481
+ directly maps to the return value of the :const:`termios.TIOCGWINSZ`
482
+ ioctl return value. The return parameters are:
483
+
484
+ - ``ws_row``: height of terminal by its number of cell rows.
485
+ - ``ws_col``: width of terminal by its number of cell columns.
486
+ - ``ws_xpixel``: width of terminal by pixels (not accurate).
487
+ - ``ws_ypixel``: height of terminal by pixels (not accurate).
488
+
489
+ .. note:: the peculiar (height, width, width, height) order, which
490
+ matches the return order of TIOCGWINSZ!
491
+ """
492
+ for fd in (self._init_descriptor, sys.__stdout__):
493
+ try:
494
+ if fd is not None:
495
+ return self._winsize(fd)
496
+ except (IOError, OSError, ValueError, TypeError): # pylint: disable=overlapping-except
497
+ pass
498
+
499
+ return WINSZ(ws_row=int(os.getenv('LINES', '25')),
500
+ ws_col=int(os.getenv('COLUMNS', '80')),
501
+ ws_xpixel=None,
502
+ ws_ypixel=None)
503
+
504
+ def _query_response(self, query_str, response_re, timeout):
505
+ """
506
+ Sends a query string to the terminal and waits for a response.
507
+
508
+ :arg str query_str: Query string written to output
509
+ :arg str response_re: Regular expression matching query response
510
+ :arg float timeout: Return after time elapsed in seconds
511
+ :return: re.match object for response_re or None if not found
512
+ :rtype: re.Match
513
+ """
514
+ # Avoid changing user's desired raw or cbreak mode if already entered,
515
+ # by entering cbreak mode ourselves. This is necessary to receive user
516
+ # input without awaiting a human to press the return key. This mode
517
+ # also disables echo, which we should also hide, as our input is an
518
+ # sequence that is not meaningful for display as an output sequence.
519
+
520
+ ctx = None
521
+ try:
522
+ if self._line_buffered:
523
+ ctx = self.cbreak()
524
+ ctx.__enter__() # pylint: disable=no-member
525
+
526
+ # Emit the query sequence,
527
+ self.stream.write(query_str)
528
+ self.stream.flush()
529
+
530
+ # Wait for response
531
+ match, data = _read_until(term=self,
532
+ pattern=response_re,
533
+ timeout=timeout)
534
+
535
+ # Exclude response from subsequent input
536
+ if match:
537
+ data = data[:match.start()] + data[match.end():]
538
+
539
+ # re-buffer keyboard data, if any
540
+ self.ungetch(data)
541
+
542
+ finally:
543
+ if ctx is not None:
544
+ ctx.__exit__(None, None, None) # pylint: disable=no-member
545
+
546
+ return match
547
+
548
+ @contextlib.contextmanager
549
+ def location(self, x=None, y=None):
550
+ """
551
+ Context manager for temporarily moving the cursor.
552
+
553
+ :arg int x: horizontal position, from left, *0*, to right edge of screen, *self.width - 1*.
554
+ :arg int y: vertical position, from top, *0*, to bottom of screen, *self.height - 1*.
555
+ :return: a context manager.
556
+ :rtype: Iterator
557
+
558
+ Move the cursor to a certain position on entry, do any kind of I/O, and upon exit
559
+ let you print stuff there, then return the cursor to its original position:
560
+
561
+
562
+ .. code-block:: python
563
+
564
+ term = Terminal()
565
+ with term.location(y=0, x=0):
566
+ for row_num in range(term.height-1):
567
+ print('Row #{row_num}')
568
+ print(term.clear_eol + 'Back to original location.')
569
+
570
+ Specify ``x`` to move to a certain column, ``y`` to move to a certain
571
+ row, both, or neither. If you specify neither, only the saving and
572
+ restoration of cursor position will happen. This can be useful if you
573
+ simply want to restore your place after doing some manual cursor
574
+ movement.
575
+
576
+ Calls cannot be nested: only one should be entered at a time.
577
+
578
+ .. note:: The argument order *(x, y)* differs from the return value order *(y, x)*
579
+ of :meth:`get_location`, or argument order *(y, x)* of :meth:`move`. This is
580
+ for API Compaibility with the blessings library, sorry for the trouble!
581
+ """
582
+ # pylint: disable=invalid-name
583
+ # Invalid argument name "x"
584
+
585
+ # Save position and move to the requested column, row, or both:
586
+ self.stream.write(self.save)
587
+ if x is not None and y is not None:
588
+ self.stream.write(self.move(y, x))
589
+ elif x is not None:
590
+ self.stream.write(self.move_x(x))
591
+ elif y is not None:
592
+ self.stream.write(self.move_y(y))
593
+ try:
594
+ self.stream.flush()
595
+ yield
596
+ finally:
597
+ # Restore original cursor position:
598
+ self.stream.write(self.restore)
599
+ self.stream.flush()
600
+
601
+ def get_location(self, timeout=None):
602
+ r"""
603
+ Return tuple (row, column) of cursor position.
604
+
605
+ :arg float timeout: Return after time elapsed in seconds with value ``(-1, -1)`` indicating
606
+ that the remote end did not respond.
607
+ :rtype: tuple
608
+ :returns: cursor position as tuple in form of ``(y, x)``. When a timeout is specified,
609
+ always ensure the return value is checked for ``(-1, -1)``.
610
+
611
+ The location of the cursor is determined by emitting the ``u7`` terminal capability, or
612
+ VT100 `Query Cursor Position
613
+ <https://www2.ccs.neu.edu/research/gpc/VonaUtils/vona/terminal/vtansi.htm#status>`_
614
+ when such capability is undefined, which elicits a response from a reply string described by
615
+ capability ``u6``, or again VT100's definition of ``\x1b[%i%d;%dR`` when undefined.
616
+
617
+ The ``(y, x)`` return value matches the parameter order of the :meth:`move_xy` capability.
618
+ The following sequence should cause the cursor to not move at all::
619
+
620
+ >>> term = Terminal()
621
+ >>> term.move_yx(*term.get_location()))
622
+
623
+ And the following should assert True with a terminal:
624
+
625
+ >>> term = Terminal()
626
+ >>> given_y, given_x = 10, 20
627
+ >>> with term.location(y=given_y, x=given_x):
628
+ ... result_y, result_x = term.get_location()
629
+ ...
630
+ >>> assert given_x == result_x, (given_x, result_x)
631
+ >>> assert given_y == result_y, (given_y, result_y)
632
+ """
633
+ # Local lines attached by termios and remote login protocols such as
634
+ # ssh and telnet both provide a means to determine the window
635
+ # dimensions of a connected client, but **no means to determine the
636
+ # location of the cursor**.
637
+ #
638
+ # from https://invisible-island.net/ncurses/terminfo.src.html,
639
+ #
640
+ # > The System V Release 4 and XPG4 terminfo format defines ten string
641
+ # > capabilities for use by applications, <u0>...<u9>. In this file,
642
+ # > we use certain of these capabilities to describe functions which
643
+ # > are not covered by terminfo. The mapping is as follows:
644
+ # >
645
+ # > u9 terminal enquire string (equiv. to ANSI/ECMA-48 DA)
646
+ # > u8 terminal answerback description
647
+ # > u7 cursor position request (equiv. to VT100/ANSI/ECMA-48 DSR 6)
648
+ # > u6 cursor position report (equiv. to ANSI/ECMA-48 CPR)
649
+
650
+ response_str = getattr(self, self.caps['cursor_report'].attribute) or u'\x1b[%i%d;%dR'
651
+ match = self._query_response(
652
+ self.u7 or u'\x1b[6n', self.caps['cursor_report'].re_compiled, timeout
653
+ )
654
+
655
+ if match:
656
+ # return matching sequence response, the cursor location.
657
+ row, col = (int(val) for val in match.groups())
658
+
659
+ # Per https://invisible-island.net/ncurses/terminfo.src.html
660
+ # The cursor position report (<u6>) string must contain two
661
+ # scanf(3)-style %d format elements. The first of these must
662
+ # correspond to the Y coordinate and the second to the %d.
663
+ # If the string contains the sequence %i, it is taken as an
664
+ # instruction to decrement each value after reading it (this is
665
+ # the inverse sense from the cup string).
666
+ if u'%i' in response_str:
667
+ row -= 1
668
+ col -= 1
669
+ return row, col
670
+
671
+ # We chose to return an illegal value rather than an exception,
672
+ # favoring that users author function filters, such as max(0, y),
673
+ # rather than crowbarring such logic into an exception handler.
674
+ return -1, -1
675
+
676
+ def get_fgcolor(self, timeout=None):
677
+ """
678
+ Return tuple (r, g, b) of foreground color.
679
+
680
+ :arg float timeout: Return after time elapsed in seconds with value ``(-1, -1, -1)``
681
+ indicating that the remote end did not respond.
682
+ :rtype: tuple
683
+ :returns: foreground color as tuple in form of ``(r, g, b)``. When a timeout is specified,
684
+ always ensure the return value is checked for ``(-1, -1, -1)``.
685
+
686
+ The foreground color is determined by emitting an `OSC 10 color query
687
+ <https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h3-Operating-System-Commands>`_.
688
+ """
689
+ match = self._query_response(
690
+ u'\x1b]10;?\x07',
691
+ re.compile(u'\x1b]10;rgb:([0-9a-fA-F]+)/([0-9a-fA-F]+)/([0-9a-fA-F]+)\x07'),
692
+ timeout
693
+ )
694
+
695
+ return tuple(int(val, 16) for val in match.groups()) if match else (-1, -1, -1)
696
+
697
+ def get_bgcolor(self, timeout=None):
698
+ """
699
+ Return tuple (r, g, b) of background color.
700
+
701
+ :arg float timeout: Return after time elapsed in seconds with value ``(-1, -1, -1)``
702
+ indicating that the remote end did not respond.
703
+ :rtype: tuple
704
+ :returns: background color as tuple in form of ``(r, g, b)``. When a timeout is specified,
705
+ always ensure the return value is checked for ``(-1, -1, -1)``.
706
+
707
+ The background color is determined by emitting an `OSC 11 color query
708
+ <https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h3-Operating-System-Commands>`_.
709
+ """
710
+ match = self._query_response(
711
+ u'\x1b]11;?\x07',
712
+ re.compile(u'\x1b]11;rgb:([0-9a-fA-F]+)/([0-9a-fA-F]+)/([0-9a-fA-F]+)\x07'),
713
+ timeout
714
+ )
715
+
716
+ return tuple(int(val, 16) for val in match.groups()) if match else (-1, -1, -1)
717
+
718
+ @contextlib.contextmanager
719
+ def fullscreen(self):
720
+ """
721
+ Context manager that switches to secondary screen, restoring on exit.
722
+
723
+ Under the hood, this switches between the primary screen buffer and
724
+ the secondary one. The primary one is saved on entry and restored on
725
+ exit. Likewise, the secondary contents are also stable and are
726
+ faithfully restored on the next entry::
727
+
728
+ with term.fullscreen():
729
+ main()
730
+
731
+ .. note:: There is only one primary and one secondary screen buffer.
732
+ :meth:`fullscreen` calls cannot be nested, only one should be
733
+ entered at a time.
734
+ """
735
+ self.stream.write(self.enter_fullscreen)
736
+ self.stream.flush()
737
+ try:
738
+ yield
739
+ finally:
740
+ self.stream.write(self.exit_fullscreen)
741
+ self.stream.flush()
742
+
743
+ @contextlib.contextmanager
744
+ def hidden_cursor(self):
745
+ """
746
+ Context manager that hides the cursor, setting visibility on exit.
747
+
748
+ with term.hidden_cursor():
749
+ main()
750
+
751
+ .. note:: :meth:`hidden_cursor` calls cannot be nested: only one
752
+ should be entered at a time.
753
+ """
754
+ self.stream.write(self.hide_cursor)
755
+ self.stream.flush()
756
+ try:
757
+ yield
758
+ finally:
759
+ self.stream.write(self.normal_cursor)
760
+ self.stream.flush()
761
+
762
+ def move_xy(self, x, y):
763
+ """
764
+ A callable string that moves the cursor to the given ``(x, y)`` screen coordinates.
765
+
766
+ :arg int x: horizontal position, from left, *0*, to right edge of screen, *self.width - 1*.
767
+ :arg int y: vertical position, from top, *0*, to bottom of screen, *self.height - 1*.
768
+ :rtype: ParameterizingString
769
+ :returns: Callable string that moves the cursor to the given coordinates
770
+ """
771
+ # this is just a convenience alias to the built-in, but hidden 'move'
772
+ # attribute -- we encourage folks to use only (x, y) positional
773
+ # arguments, or, if they must use (y, x), then use the 'move_yx'
774
+ # alias.
775
+ return self.move(y, x)
776
+
777
+ def move_yx(self, y, x):
778
+ """
779
+ A callable string that moves the cursor to the given ``(y, x)`` screen coordinates.
780
+
781
+ :arg int y: vertical position, from top, *0*, to bottom of screen, *self.height - 1*.
782
+ :arg int x: horizontal position, from left, *0*, to right edge of screen, *self.width - 1*.
783
+ :rtype: ParameterizingString
784
+ :returns: Callable string that moves the cursor to the given coordinates
785
+ """
786
+ return self.move(y, x)
787
+
788
+ @property
789
+ def move_left(self):
790
+ """Move cursor 1 cells to the left, or callable string for n>1 cells."""
791
+ return FormattingOtherString(self.cub1, ParameterizingString(self.cub))
792
+
793
+ @property
794
+ def move_right(self):
795
+ """Move cursor 1 or more cells to the right, or callable string for n>1 cells."""
796
+ return FormattingOtherString(self.cuf1, ParameterizingString(self.cuf))
797
+
798
+ @property
799
+ def move_up(self):
800
+ """Move cursor 1 or more cells upwards, or callable string for n>1 cells."""
801
+ return FormattingOtherString(self.cuu1, ParameterizingString(self.cuu))
802
+
803
+ @property
804
+ def move_down(self):
805
+ """Move cursor 1 or more cells downwards, or callable string for n>1 cells."""
806
+ return FormattingOtherString(self.cud1, ParameterizingString(self.cud))
807
+
808
+ @property
809
+ def color(self):
810
+ """
811
+ A callable string that sets the foreground color.
812
+
813
+ :rtype: ParameterizingString
814
+
815
+ The capability is unparameterized until called and passed a number, at which point it
816
+ returns another string which represents a specific color change. This second string can
817
+ further be called to color a piece of text and set everything back to normal afterward.
818
+
819
+ This should not be used directly, but rather a specific color by name or
820
+ :meth:`~.Terminal.color_rgb` value.
821
+ """
822
+ if self.does_styling:
823
+ return ParameterizingString(self._foreground_color, self.normal, 'color')
824
+
825
+ return NullCallableString()
826
+
827
+ def color_rgb(self, red, green, blue):
828
+ """
829
+ Provides callable formatting string to set foreground color to the specified RGB color.
830
+
831
+ :arg int red: RGB value of Red.
832
+ :arg int green: RGB value of Green.
833
+ :arg int blue: RGB value of Blue.
834
+ :rtype: FormattingString
835
+ :returns: Callable string that sets the foreground color
836
+
837
+ If the terminal does not support RGB color, the nearest supported
838
+ color will be determined using :py:attr:`color_distance_algorithm`.
839
+ """
840
+ if self.number_of_colors == 1 << 24:
841
+ # "truecolor" 24-bit
842
+ fmt_attr = u'\x1b[38;2;{0};{1};{2}m'.format(red, green, blue)
843
+ return FormattingString(fmt_attr, self.normal)
844
+
845
+ # color by approximation to 256 or 16-color terminals
846
+ color_idx = self.rgb_downconvert(red, green, blue)
847
+ return FormattingString(self._foreground_color(color_idx), self.normal)
848
+
849
+ @property
850
+ def on_color(self):
851
+ """
852
+ A callable capability that sets the background color.
853
+
854
+ :rtype: ParameterizingString
855
+ """
856
+ if self.does_styling:
857
+ return ParameterizingString(self._background_color, self.normal, 'on_color')
858
+
859
+ return NullCallableString()
860
+
861
+ def on_color_rgb(self, red, green, blue):
862
+ """
863
+ Provides callable formatting string to set background color to the specified RGB color.
864
+
865
+ :arg int red: RGB value of Red.
866
+ :arg int green: RGB value of Green.
867
+ :arg int blue: RGB value of Blue.
868
+ :rtype: FormattingString
869
+ :returns: Callable string that sets the foreground color
870
+
871
+ If the terminal does not support RGB color, the nearest supported
872
+ color will be determined using :py:attr:`color_distance_algorithm`.
873
+ """
874
+ if self.number_of_colors == 1 << 24:
875
+ fmt_attr = u'\x1b[48;2;{0};{1};{2}m'.format(red, green, blue)
876
+ return FormattingString(fmt_attr, self.normal)
877
+
878
+ color_idx = self.rgb_downconvert(red, green, blue)
879
+ return FormattingString(self._background_color(color_idx), self.normal)
880
+
881
+ def formatter(self, value):
882
+ """
883
+ Provides callable formatting string to set color and other text formatting options.
884
+
885
+ :arg str value: Sugary, ordinary, or compound formatted terminal capability,
886
+ such as "red_on_white", "normal", "red", or "bold_on_black".
887
+ :rtype: :class:`FormattingString` or :class:`NullCallableString`
888
+ :returns: Callable string that sets color and other text formatting options
889
+
890
+ Calling ``term.formatter('bold_on_red')`` is equivalent to ``term.bold_on_red``, but a
891
+ string that is not a valid text formatter will return a :class:`NullCallableString`.
892
+ This is intended to allow validation of text formatters without the possibility of
893
+ inadvertently returning another terminal capability.
894
+ """
895
+ formatters = split_compound(value)
896
+ if all((fmt in COLORS or fmt in COMPOUNDABLES) for fmt in formatters):
897
+ return getattr(self, value)
898
+
899
+ return NullCallableString()
900
+
901
+ def rgb_downconvert(self, red, green, blue):
902
+ """
903
+ Translate an RGB color to a color code of the terminal's color depth.
904
+
905
+ :arg int red: RGB value of Red (0-255).
906
+ :arg int green: RGB value of Green (0-255).
907
+ :arg int blue: RGB value of Blue (0-255).
908
+ :rtype: int
909
+ :returns: Color code of downconverted RGB color
910
+ """
911
+ # Though pre-computing all 1 << 24 options is memory-intensive, a pre-computed
912
+ # "k-d tree" of 256 (x,y,z) vectors of a colorspace in 3 dimensions, such as a
913
+ # cone of HSV, or simply 255x255x255 RGB square, any given rgb value is just a
914
+ # nearest-neighbor search of 256 points, which k-d should be much faster by
915
+ # sub-dividing / culling search points, rather than our "search all 256 points
916
+ # always" approach.
917
+ fn_distance = COLOR_DISTANCE_ALGORITHMS[self.color_distance_algorithm]
918
+ color_idx = 7
919
+ shortest_distance = None
920
+ for cmp_depth, cmp_rgb in enumerate(RGB_256TABLE):
921
+ cmp_distance = fn_distance(cmp_rgb, (red, green, blue))
922
+ if shortest_distance is None or cmp_distance < shortest_distance:
923
+ shortest_distance = cmp_distance
924
+ color_idx = cmp_depth
925
+ if cmp_depth >= self.number_of_colors:
926
+ break
927
+ return color_idx
928
+
929
+ @property
930
+ def normal(self):
931
+ """
932
+ A capability that resets all video attributes.
933
+
934
+ :rtype: str
935
+
936
+ ``normal`` is an alias for ``sgr0`` or ``exit_attribute_mode``. Any
937
+ styling attributes previously applied, such as foreground or
938
+ background colors, reverse video, or bold are reset to defaults.
939
+ """
940
+ if self._normal:
941
+ return self._normal
942
+ self._normal = resolve_capability(self, 'normal')
943
+ return self._normal
944
+
945
+ def link(self, url, text, url_id=''):
946
+ """
947
+ Display ``text`` that when touched or clicked, navigates to ``url``.
948
+
949
+ Optional ``url_id`` may be specified, so that non-adjacent cells can reference a single
950
+ target, all cells painted with the same "id" will highlight on hover, rather than any
951
+ individual one, as described in "Hovering and underlining the id parameter" of gist
952
+ https://gist.github.com/egmontkob/eb114294efbcd5adb1944c9f3cb5feda.
953
+
954
+ :param str url: Hyperlink URL.
955
+ :param str text: Clickable text.
956
+ :param str url_id: Optional 'id'.
957
+ :rtype: str
958
+ :returns: String of ``text`` as a hyperlink to ``url``.
959
+ """
960
+ assert len(url) < 2000, (len(url), url)
961
+ if url_id:
962
+ assert len(str(url_id)) < 250, (len(str(url_id)), url_id)
963
+ params = 'id={0}'.format(url_id)
964
+ else:
965
+ params = ''
966
+ if not self.does_styling:
967
+ return text
968
+ return ('\x1b]8;{0};{1}\x1b\\{2}'
969
+ '\x1b]8;;\x1b\\'.format(params, url, text))
970
+
971
+ @property
972
+ def stream(self):
973
+ """
974
+ Read-only property: stream the terminal outputs to.
975
+
976
+ This is a convenience attribute. It is used internally for implied
977
+ writes performed by context managers :meth:`~.hidden_cursor`,
978
+ :meth:`~.fullscreen`, :meth:`~.location`, and :meth:`~.keypad`.
979
+ """
980
+ return self._stream
981
+
982
+ @property
983
+ def number_of_colors(self):
984
+ """
985
+ Number of colors supported by terminal.
986
+
987
+ Common return values are 0, 8, 16, 256, or 1 << 24.
988
+
989
+ This may be used to test whether the terminal supports colors,
990
+ and at what depth, if that's a concern.
991
+
992
+ If this property is assigned a value of 88, the value 16 will be saved. This is due to the
993
+ the rarity of 88 color support and the inconsistency of behavior between implementations.
994
+
995
+ Assigning this property to a value other than 0, 4, 8, 16, 88, 256, or 1 << 24 will
996
+ raise an :py:exc:`AssertionError`.
997
+ """
998
+ return self._number_of_colors
999
+
1000
+ @number_of_colors.setter
1001
+ def number_of_colors(self, value):
1002
+ assert value in (0, 4, 8, 16, 88, 256, 1 << 24)
1003
+ # Because 88 colors is rare and we can't guarantee consistent behavior,
1004
+ # when 88 colors is detected, it is treated as 16 colors
1005
+ self._number_of_colors = 16 if value == 88 else value
1006
+ self.__clear_color_capabilities()
1007
+
1008
+ @property
1009
+ def color_distance_algorithm(self):
1010
+ """
1011
+ Color distance algorithm used by :meth:`rgb_downconvert`.
1012
+
1013
+ The slowest, but most accurate, 'cie2000', is default. Other available options are 'rgb',
1014
+ 'rgb-weighted', 'cie76', and 'cie94'.
1015
+ """
1016
+ return self._color_distance_algorithm
1017
+
1018
+ @color_distance_algorithm.setter
1019
+ def color_distance_algorithm(self, value):
1020
+ assert value in COLOR_DISTANCE_ALGORITHMS
1021
+ self._color_distance_algorithm = value
1022
+ self.__clear_color_capabilities()
1023
+
1024
+ @property
1025
+ def _foreground_color(self):
1026
+ """
1027
+ Convenience capability to support :attr:`~.on_color`.
1028
+
1029
+ Prefers returning sequence for capability ``setaf``, "Set foreground color to #1, using ANSI
1030
+ escape". If the given terminal does not support such sequence, fallback to returning
1031
+ attribute ``setf``, "Set foreground color #1".
1032
+ """
1033
+ return self.setaf or self.setf
1034
+
1035
+ @property
1036
+ def _background_color(self):
1037
+ """
1038
+ Convenience capability to support :attr:`~.on_color`.
1039
+
1040
+ Prefers returning sequence for capability ``setab``, "Set background color to #1, using ANSI
1041
+ escape". If the given terminal does not support such sequence, fallback to returning
1042
+ attribute ``setb``, "Set background color #1".
1043
+ """
1044
+ return self.setab or self.setb
1045
+
1046
+ def ljust(self, text, width=None, fillchar=u' '):
1047
+ """
1048
+ Left-align ``text``, which may contain terminal sequences.
1049
+
1050
+ :arg str text: String to be aligned
1051
+ :arg int width: Total width to fill with aligned text. If
1052
+ unspecified, the whole width of the terminal is filled.
1053
+ :arg str fillchar: String for padding the right of ``text``
1054
+ :rtype: str
1055
+ :returns: String of ``text``, left-aligned by ``width``.
1056
+ """
1057
+ # Left justification is different from left alignment, but we continue
1058
+ # the vocabulary error of the str method for polymorphism.
1059
+ if width is None:
1060
+ width = self.width
1061
+ return Sequence(text, self).ljust(width, fillchar)
1062
+
1063
+ def rjust(self, text, width=None, fillchar=u' '):
1064
+ """
1065
+ Right-align ``text``, which may contain terminal sequences.
1066
+
1067
+ :arg str text: String to be aligned
1068
+ :arg int width: Total width to fill with aligned text. If
1069
+ unspecified, the whole width of the terminal is used.
1070
+ :arg str fillchar: String for padding the left of ``text``
1071
+ :rtype: str
1072
+ :returns: String of ``text``, right-aligned by ``width``.
1073
+ """
1074
+ if width is None:
1075
+ width = self.width
1076
+ return Sequence(text, self).rjust(width, fillchar)
1077
+
1078
+ def center(self, text, width=None, fillchar=u' '):
1079
+ """
1080
+ Center ``text``, which may contain terminal sequences.
1081
+
1082
+ :arg str text: String to be centered
1083
+ :arg int width: Total width in which to center text. If
1084
+ unspecified, the whole width of the terminal is used.
1085
+ :arg str fillchar: String for padding the left and right of ``text``
1086
+ :rtype: str
1087
+ :returns: String of ``text``, centered by ``width``
1088
+ """
1089
+ if width is None:
1090
+ width = self.width
1091
+ return Sequence(text, self).center(width, fillchar)
1092
+
1093
+ def truncate(self, text, width=None):
1094
+ r"""
1095
+ Truncate ``text`` to maximum ``width`` printable characters, retaining terminal sequences.
1096
+
1097
+ :arg str text: Text to truncate
1098
+ :arg int width: The maximum width to truncate it to
1099
+ :rtype: str
1100
+ :returns: ``text`` truncated to at most ``width`` printable characters
1101
+
1102
+ >>> term.truncate(u'xyz\x1b[0;3m', 2)
1103
+ u'xy\x1b[0;3m'
1104
+ """
1105
+ if width is None:
1106
+ width = self.width
1107
+ return Sequence(text, self).truncate(width)
1108
+
1109
+ def length(self, text):
1110
+ u"""
1111
+ Return printable length of a string containing sequences.
1112
+
1113
+ :arg str text: String to measure. May contain terminal sequences.
1114
+ :rtype: int
1115
+ :returns: The number of terminal character cells the string will occupy
1116
+ when printed
1117
+
1118
+ Wide characters that consume 2 character cells are supported:
1119
+
1120
+ >>> term = Terminal()
1121
+ >>> term.length(term.clear + term.red(u'コンニチハ'))
1122
+ 10
1123
+
1124
+ .. note:: Sequences such as 'clear', which is considered as a
1125
+ "movement sequence" because it would move the cursor to
1126
+ (y, x)(0, 0), are evaluated as a printable length of
1127
+ *0*.
1128
+ """
1129
+ return Sequence(text, self).length()
1130
+
1131
+ def strip(self, text, chars=None):
1132
+ r"""
1133
+ Return ``text`` without sequences and leading or trailing whitespace.
1134
+
1135
+ :rtype: str
1136
+ :returns: Text with leading and trailing whitespace removed
1137
+
1138
+ >>> term.strip(u' \x1b[0;3m xyz ')
1139
+ u'xyz'
1140
+ """
1141
+ return Sequence(text, self).strip(chars)
1142
+
1143
+ def rstrip(self, text, chars=None):
1144
+ r"""
1145
+ Return ``text`` without terminal sequences or trailing whitespace.
1146
+
1147
+ :rtype: str
1148
+ :returns: Text with terminal sequences and trailing whitespace removed
1149
+
1150
+ >>> term.rstrip(u' \x1b[0;3m xyz ')
1151
+ u' xyz'
1152
+ """
1153
+ return Sequence(text, self).rstrip(chars)
1154
+
1155
+ def lstrip(self, text, chars=None):
1156
+ r"""
1157
+ Return ``text`` without terminal sequences or leading whitespace.
1158
+
1159
+ :rtype: str
1160
+ :returns: Text with terminal sequences and leading whitespace removed
1161
+
1162
+ >>> term.lstrip(u' \x1b[0;3m xyz ')
1163
+ u'xyz '
1164
+ """
1165
+ return Sequence(text, self).lstrip(chars)
1166
+
1167
+ def strip_seqs(self, text):
1168
+ r"""
1169
+ Return ``text`` stripped of only its terminal sequences.
1170
+
1171
+ :rtype: str
1172
+ :returns: Text with terminal sequences removed
1173
+
1174
+ >>> term.strip_seqs(u'\x1b[0;3mxyz')
1175
+ u'xyz'
1176
+ >>> term.strip_seqs(term.cuf(5) + term.red(u'test'))
1177
+ u' test'
1178
+
1179
+ .. note:: Non-destructive sequences that adjust horizontal distance
1180
+ (such as ``\b`` or ``term.cuf(5)``) are replaced by destructive
1181
+ space or erasing.
1182
+ """
1183
+ return Sequence(text, self).strip_seqs()
1184
+
1185
+ def split_seqs(self, text, maxsplit=0):
1186
+ r"""
1187
+ Return ``text`` split by individual character elements and sequences.
1188
+
1189
+ :arg str text: String containing sequences
1190
+ :arg int maxsplit: When maxsplit is nonzero, at most maxsplit splits
1191
+ occur, and the remainder of the string is returned as the final element
1192
+ of the list (same meaning is argument for :func:`re.split`).
1193
+ :rtype: list[str]
1194
+ :returns: List of sequences and individual characters
1195
+
1196
+ >>> term.split_seqs(term.underline(u'xyz'))
1197
+ ['\x1b[4m', 'x', 'y', 'z', '\x1b(B', '\x1b[m']
1198
+
1199
+ >>> term.split_seqs(term.underline(u'xyz'), 1)
1200
+ ['\x1b[4m', r'xyz\x1b(B\x1b[m']
1201
+ """
1202
+ pattern = self._caps_unnamed_any
1203
+ result = []
1204
+ for idx, match in enumerate(re.finditer(pattern, text)):
1205
+ result.append(match.group())
1206
+ if maxsplit and idx == maxsplit:
1207
+ remaining = text[match.end():]
1208
+ if remaining:
1209
+ result[-1] += remaining
1210
+ break
1211
+ return result
1212
+
1213
+ def wrap(self, text, width=None, **kwargs):
1214
+ r"""
1215
+ Text-wrap a string, returning a list of wrapped lines.
1216
+
1217
+ :arg str text: Unlike :func:`textwrap.wrap`, ``text`` may contain
1218
+ terminal sequences, such as colors, bold, or underline. By
1219
+ default, tabs in ``text`` are expanded by
1220
+ :func:`string.expandtabs`.
1221
+ :arg int width: Unlike :func:`textwrap.wrap`, ``width`` will
1222
+ default to the width of the attached terminal.
1223
+ :arg \**kwargs: See :py:class:`textwrap.TextWrapper`
1224
+ :rtype: list
1225
+ :returns: List of wrapped lines
1226
+
1227
+ See :class:`textwrap.TextWrapper` for keyword arguments that can
1228
+ customize wrapping behaviour.
1229
+ """
1230
+ width = self.width if width is None else width
1231
+ wrapper = SequenceTextWrapper(width=width, term=self, **kwargs)
1232
+ lines = []
1233
+ for line in text.splitlines():
1234
+ lines.extend(iter(wrapper.wrap(line)) if line.strip() else (u'',))
1235
+
1236
+ return lines
1237
+
1238
+ def getch(self):
1239
+ """
1240
+ Read, decode, and return the next byte from the keyboard stream.
1241
+
1242
+ :rtype: unicode
1243
+ :returns: a single unicode character, or ``u''`` if a multi-byte
1244
+ sequence has not yet been fully received.
1245
+
1246
+ This method name and behavior mimics curses ``getch(void)``, and
1247
+ it supports :meth:`inkey`, reading only one byte from
1248
+ the keyboard string at a time. This method should always return
1249
+ without blocking if called after :meth:`kbhit` has returned True.
1250
+
1251
+ Implementors of alternate input stream methods should override
1252
+ this method.
1253
+ """
1254
+ assert self._keyboard_fd is not None
1255
+ byte = os.read(self._keyboard_fd, 1)
1256
+ return self._keyboard_decoder.decode(byte, final=False)
1257
+
1258
+ def ungetch(self, text):
1259
+ """
1260
+ Buffer input data to be discovered by next call to :meth:`~.inkey`.
1261
+
1262
+ :arg str text: String to be buffered as keyboard input.
1263
+ """
1264
+ self._keyboard_buf.extendleft(text)
1265
+
1266
+ def kbhit(self, timeout=None):
1267
+ """
1268
+ Return whether a keypress has been detected on the keyboard.
1269
+
1270
+ This method is used by :meth:`inkey` to determine if a byte may
1271
+ be read using :meth:`getch` without blocking. The standard
1272
+ implementation simply uses the :func:`select.select` call on stdin.
1273
+
1274
+ :arg float timeout: When ``timeout`` is 0, this call is
1275
+ non-blocking, otherwise blocking indefinitely until keypress
1276
+ is detected when None (default). When ``timeout`` is a
1277
+ positive number, returns after ``timeout`` seconds have
1278
+ elapsed (float).
1279
+ :rtype: bool
1280
+ :returns: True if a keypress is awaiting to be read on the keyboard
1281
+ attached to this terminal. When input is not a terminal, False is
1282
+ always returned.
1283
+ """
1284
+ stime = time.time()
1285
+ ready_r = [None, ]
1286
+ check_r = [self._keyboard_fd] if self._keyboard_fd is not None else []
1287
+
1288
+ while HAS_TTY:
1289
+ try:
1290
+ ready_r, _, _ = select.select(check_r, [], [], timeout)
1291
+ except InterruptedError:
1292
+ # Beginning with python3.5, IntrruptError is no longer thrown
1293
+ # https://www.python.org/dev/peps/pep-0475/
1294
+ #
1295
+ # For previous versions of python, we take special care to
1296
+ # retry select on InterruptedError exception, namely to handle
1297
+ # a custom SIGWINCH handler. When installed, it would cause
1298
+ # select() to be interrupted with errno 4 (EAGAIN).
1299
+ #
1300
+ # Just as in python3.5, it is ignored, and a new timeout value
1301
+ # is derived from the previous unless timeout becomes negative.
1302
+ # because the signal handler has blocked beyond timeout, then
1303
+ # False is returned. Otherwise, when timeout is None, we
1304
+ # continue to block indefinitely (default).
1305
+ if timeout is not None:
1306
+ # subtract time already elapsed,
1307
+ timeout -= time.time() - stime
1308
+ if timeout > 0:
1309
+ continue
1310
+ # no time remains after handling exception (rare)
1311
+ ready_r = [] # pragma: no cover
1312
+ break # pragma: no cover
1313
+ else:
1314
+ break
1315
+
1316
+ return False if self._keyboard_fd is None else check_r == ready_r
1317
+
1318
+ @contextlib.contextmanager
1319
+ def cbreak(self):
1320
+ """
1321
+ Allow each keystroke to be read immediately after it is pressed.
1322
+
1323
+ This is a context manager for :func:`tty.setcbreak`.
1324
+
1325
+ This context manager activates 'rare' mode, the opposite of 'cooked'
1326
+ mode: On entry, :func:`tty.setcbreak` mode is activated disabling
1327
+ line-buffering of keyboard input and turning off automatic echo of
1328
+ input as output.
1329
+
1330
+ .. note:: You must explicitly print any user input you would like
1331
+ displayed. If you provide any kind of editing, you must handle
1332
+ backspace and other line-editing control functions in this mode
1333
+ as well!
1334
+
1335
+ **Normally**, characters received from the keyboard cannot be read
1336
+ by Python until the *Return* key is pressed. Also known as *cooked* or
1337
+ *canonical input* mode, it allows the tty driver to provide
1338
+ line-editing before shuttling the input to your program and is the
1339
+ (implicit) default terminal mode set by most unix shells before
1340
+ executing programs.
1341
+
1342
+ Technically, this context manager sets the :mod:`termios` attributes
1343
+ of the terminal attached to :obj:`sys.__stdin__`.
1344
+
1345
+ .. note:: :func:`tty.setcbreak` sets ``VMIN = 1`` and ``VTIME = 0``,
1346
+ see http://www.unixwiz.net/techtips/termios-vmin-vtime.html
1347
+ """
1348
+ if HAS_TTY and self._keyboard_fd is not None:
1349
+ # Save current terminal mode:
1350
+ save_mode = termios.tcgetattr(self._keyboard_fd)
1351
+ save_line_buffered = self._line_buffered
1352
+ tty.setcbreak(self._keyboard_fd, termios.TCSANOW)
1353
+ try:
1354
+ self._line_buffered = False
1355
+ yield
1356
+ finally:
1357
+ # Restore prior mode:
1358
+ termios.tcsetattr(self._keyboard_fd,
1359
+ termios.TCSAFLUSH,
1360
+ save_mode)
1361
+ self._line_buffered = save_line_buffered
1362
+ else:
1363
+ yield
1364
+
1365
+ @contextlib.contextmanager
1366
+ def raw(self):
1367
+ r"""
1368
+ A context manager for :func:`tty.setraw`.
1369
+
1370
+ Although both :meth:`break` and :meth:`raw` modes allow each keystroke
1371
+ to be read immediately after it is pressed, Raw mode disables
1372
+ processing of input and output.
1373
+
1374
+ In cbreak mode, special input characters such as ``^C`` or ``^S`` are
1375
+ interpreted by the terminal driver and excluded from the stdin stream.
1376
+ In raw mode these values are receive by the :meth:`inkey` method.
1377
+
1378
+ Because output processing is not done, the newline ``'\n'`` is not
1379
+ enough, you must also print carriage return to ensure that the cursor
1380
+ is returned to the first column::
1381
+
1382
+ with term.raw():
1383
+ print("printing in raw mode", end="\r\n")
1384
+ """
1385
+ if HAS_TTY and self._keyboard_fd is not None:
1386
+ # Save current terminal mode:
1387
+ save_mode = termios.tcgetattr(self._keyboard_fd)
1388
+ save_line_buffered = self._line_buffered
1389
+ tty.setraw(self._keyboard_fd, termios.TCSANOW)
1390
+ try:
1391
+ self._line_buffered = False
1392
+ yield
1393
+ finally:
1394
+ # Restore prior mode:
1395
+ termios.tcsetattr(self._keyboard_fd,
1396
+ termios.TCSAFLUSH,
1397
+ save_mode)
1398
+ self._line_buffered = save_line_buffered
1399
+ else:
1400
+ yield
1401
+
1402
+ @contextlib.contextmanager
1403
+ def keypad(self):
1404
+ r"""
1405
+ Context manager that enables directional keypad input.
1406
+
1407
+ On entrying, this puts the terminal into "keyboard_transmit" mode by
1408
+ emitting the keypad_xmit (smkx) capability. On exit, it emits
1409
+ keypad_local (rmkx).
1410
+
1411
+ On an IBM-PC keyboard with numeric keypad of terminal-type *xterm*,
1412
+ with numlock off, the lower-left diagonal key transmits sequence
1413
+ ``\\x1b[F``, translated to :class:`~.Terminal` attribute
1414
+ ``KEY_END``.
1415
+
1416
+ However, upon entering :meth:`keypad`, ``\\x1b[OF`` is transmitted,
1417
+ translating to ``KEY_LL`` (lower-left key), allowing you to determine
1418
+ diagonal direction keys.
1419
+ """
1420
+ try:
1421
+ self.stream.write(self.smkx)
1422
+ self.stream.flush()
1423
+ yield
1424
+ finally:
1425
+ self.stream.write(self.rmkx)
1426
+ self.stream.flush()
1427
+
1428
+ def inkey(self, timeout=None, esc_delay=0.35):
1429
+ """
1430
+ Read and return the next keyboard event within given timeout.
1431
+
1432
+ Generally, this should be used inside the :meth:`raw` context manager.
1433
+
1434
+ :arg float timeout: Number of seconds to wait for a keystroke before
1435
+ returning. When ``None`` (default), this method may block
1436
+ indefinitely.
1437
+ :arg float esc_delay: To distinguish between the keystroke of
1438
+ ``KEY_ESCAPE``, and sequences beginning with escape, the parameter
1439
+ ``esc_delay`` specifies the amount of time after receiving escape
1440
+ (``chr(27)``) to seek for the completion of an application key
1441
+ before returning a :class:`~.Keystroke` instance for
1442
+ ``KEY_ESCAPE``.
1443
+ :rtype: :class:`~.Keystroke`.
1444
+ :returns: :class:`~.Keystroke`, which may be empty (``u''``) if
1445
+ ``timeout`` is specified and keystroke is not received.
1446
+
1447
+ .. note:: When used without the context manager :meth:`cbreak`, or
1448
+ :meth:`raw`, :obj:`sys.__stdin__` remains line-buffered, and this
1449
+ function will block until the return key is pressed!
1450
+
1451
+ .. note:: On Windows, a 10 ms sleep is added to the key press detection loop to reduce CPU
1452
+ load. Due to the behavior of :py:func:`time.sleep` on Windows, this will actually
1453
+ result in a 15.6 ms delay when using the default `time resolution
1454
+ <https://docs.microsoft.com/en-us/windows/win32/api/timeapi/nf-timeapi-timebeginperiod>`_.
1455
+ Decreasing the time resolution will reduce this to 10 ms, while increasing it, which
1456
+ is rarely done, will have a perceptable impact on the behavior.
1457
+ """
1458
+ resolve = functools.partial(resolve_sequence,
1459
+ mapper=self._keymap,
1460
+ codes=self._keycodes)
1461
+
1462
+ stime = time.time()
1463
+
1464
+ # re-buffer previously received keystrokes,
1465
+ ucs = u''
1466
+ while self._keyboard_buf:
1467
+ ucs += self._keyboard_buf.pop()
1468
+
1469
+ # receive all immediately available bytes
1470
+ while self.kbhit(timeout=0):
1471
+ ucs += self.getch()
1472
+
1473
+ # decode keystroke, if any
1474
+ ks = resolve(text=ucs)
1475
+
1476
+ # so long as the most immediately received or buffered keystroke is
1477
+ # incomplete, (which may be a multibyte encoding), block until until
1478
+ # one is received.
1479
+ while not ks and self.kbhit(timeout=_time_left(stime, timeout)):
1480
+ ucs += self.getch()
1481
+ ks = resolve(text=ucs)
1482
+
1483
+ # handle escape key (KEY_ESCAPE) vs. escape sequence (like those
1484
+ # that begin with \x1b[ or \x1bO) up to esc_delay when
1485
+ # received. This is not optimal, but causes least delay when
1486
+ # "meta sends escape" is used, or when an unsupported sequence is
1487
+ # sent.
1488
+ #
1489
+ # The statement, "ucs in self._keymap_prefixes" has an effect on
1490
+ # keystrokes such as Alt + Z ("\x1b[z" with metaSendsEscape): because
1491
+ # no known input sequences begin with such phrasing to allow it to be
1492
+ # returned more quickly than esc_delay otherwise blocks for.
1493
+ if ks.code == self.KEY_ESCAPE:
1494
+ esctime = time.time()
1495
+ while (ks.code == self.KEY_ESCAPE and
1496
+ ucs in self._keymap_prefixes and
1497
+ self.kbhit(timeout=_time_left(esctime, esc_delay))):
1498
+ ucs += self.getch()
1499
+ ks = resolve(text=ucs)
1500
+
1501
+ # buffer any remaining text received
1502
+ self.ungetch(ucs[len(ks):])
1503
+ return ks
1504
+
1505
+
1506
+ class WINSZ(collections.namedtuple('WINSZ', (
1507
+ 'ws_row', 'ws_col', 'ws_xpixel', 'ws_ypixel'))):
1508
+ """
1509
+ Structure represents return value of :const:`termios.TIOCGWINSZ`.
1510
+
1511
+ .. py:attribute:: ws_row
1512
+
1513
+ rows, in characters
1514
+
1515
+ .. py:attribute:: ws_col
1516
+
1517
+ columns, in characters
1518
+
1519
+ .. py:attribute:: ws_xpixel
1520
+
1521
+ horizontal size, pixels
1522
+
1523
+ .. py:attribute:: ws_ypixel
1524
+
1525
+ vertical size, pixels
1526
+ """
1527
+ #: format of termios structure
1528
+ _FMT = 'hhhh'
1529
+ #: buffer of termios structure appropriate for ioctl argument
1530
+ _BUF = '\x00' * struct.calcsize(_FMT)
1531
+
1532
+
1533
+ #: _CUR_TERM = None
1534
+ #: From libcurses/doc/ncurses-intro.html (ESR, Thomas Dickey, et. al)::
1535
+ #:
1536
+ #: "After the call to setupterm(), the global variable cur_term is set to
1537
+ #: point to the current structure of terminal capabilities. By calling
1538
+ #: setupterm() for each terminal, and saving and restoring cur_term, it
1539
+ #: is possible for a program to use two or more terminals at once."
1540
+ #:
1541
+ #: However, if you study Python's ``./Modules/_cursesmodule.c``, you'll find::
1542
+ #:
1543
+ #: if (!initialised_setupterm && setupterm(termstr,fd,&err) == ERR) {
1544
+ #:
1545
+ #: Python - perhaps wrongly - will not allow for re-initialisation of new
1546
+ #: terminals through :func:`curses.setupterm`, so the value of cur_term cannot
1547
+ #: be changed once set: subsequent calls to :func:`curses.setupterm` have no
1548
+ #: effect.
1549
+ #:
1550
+ #: Therefore, the :attr:`Terminal.kind` of each :class:`Terminal` is
1551
+ #: essentially a singleton. This global variable reflects that, and a warning
1552
+ #: is emitted if somebody expects otherwise.
vllm/lib/python3.10/site-packages/blessed/terminal.pyi ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # std imports
2
+ from typing import IO, Any, List, Tuple, Union, Optional, OrderedDict, SupportsIndex, ContextManager
3
+
4
+ # local
5
+ from .keyboard import Keystroke
6
+ from .sequences import Termcap
7
+ from .formatters import (FormattingString,
8
+ NullCallableString,
9
+ ParameterizingString,
10
+ FormattingOtherString)
11
+
12
+ HAS_TTY: bool
13
+
14
+ class Terminal:
15
+ caps: OrderedDict[str, Termcap]
16
+ errors: List[str] = ...
17
+ def __init__(
18
+ self,
19
+ kind: Optional[str] = ...,
20
+ stream: Optional[IO[str]] = ...,
21
+ force_styling: bool = ...,
22
+ ) -> None: ...
23
+ def __getattr__(
24
+ self, attr: str
25
+ ) -> Union[NullCallableString, ParameterizingString, FormattingString]: ...
26
+ @property
27
+ def kind(self) -> str: ...
28
+ @property
29
+ def does_styling(self) -> bool: ...
30
+ @property
31
+ def is_a_tty(self) -> bool: ...
32
+ @property
33
+ def height(self) -> int: ...
34
+ @property
35
+ def width(self) -> int: ...
36
+ @property
37
+ def pixel_height(self) -> int: ...
38
+ @property
39
+ def pixel_width(self) -> int: ...
40
+ def location(
41
+ self, x: Optional[int] = ..., y: Optional[int] = ...
42
+ ) -> ContextManager[None]: ...
43
+ def get_location(self, timeout: Optional[float] = ...) -> Tuple[int, int]: ...
44
+ def get_fgcolor(self, timeout: Optional[float] = ...) -> Tuple[int, int, int]: ...
45
+ def get_bgcolor(self, timeout: Optional[float] = ...) -> Tuple[int, int, int]: ...
46
+ def fullscreen(self) -> ContextManager[None]: ...
47
+ def hidden_cursor(self) -> ContextManager[None]: ...
48
+ def move_xy(self, x: int, y: int) -> ParameterizingString: ...
49
+ def move_yx(self, y: int, x: int) -> ParameterizingString: ...
50
+ @property
51
+ def move_left(self) -> FormattingOtherString: ...
52
+ @property
53
+ def move_right(self) -> FormattingOtherString: ...
54
+ @property
55
+ def move_up(self) -> FormattingOtherString: ...
56
+ @property
57
+ def move_down(self) -> FormattingOtherString: ...
58
+ @property
59
+ def color(self) -> Union[NullCallableString, ParameterizingString]: ...
60
+ def color_rgb(self, red: int, green: int, blue: int) -> FormattingString: ...
61
+ @property
62
+ def on_color(self) -> Union[NullCallableString, ParameterizingString]: ...
63
+ def on_color_rgb(self, red: int, green: int, blue: int) -> FormattingString: ...
64
+ def formatter(self, value: str) -> Union[NullCallableString, FormattingString]: ...
65
+ def rgb_downconvert(self, red: int, green: int, blue: int) -> int: ...
66
+ @property
67
+ def normal(self) -> str: ...
68
+ def link(self, url: str, text: str, url_id: str = ...) -> str: ...
69
+ @property
70
+ def stream(self) -> IO[str]: ...
71
+ @property
72
+ def number_of_colors(self) -> int: ...
73
+ @number_of_colors.setter
74
+ def number_of_colors(self, value: int) -> None: ...
75
+ @property
76
+ def color_distance_algorithm(self) -> str: ...
77
+ @color_distance_algorithm.setter
78
+ def color_distance_algorithm(self, value: str) -> None: ...
79
+ def ljust(
80
+ self, text: str, width: Optional[SupportsIndex] = ..., fillchar: str = ...
81
+ ) -> str: ...
82
+ def rjust(
83
+ self, text: str, width: Optional[SupportsIndex] = ..., fillchar: str = ...
84
+ ) -> str: ...
85
+ def center(
86
+ self, text: str, width: Optional[SupportsIndex] = ..., fillchar: str = ...
87
+ ) -> str: ...
88
+ def truncate(self, text: str, width: Optional[SupportsIndex] = ...) -> str: ...
89
+ def length(self, text: str) -> int: ...
90
+ def strip(self, text: str, chars: Optional[str] = ...) -> str: ...
91
+ def rstrip(self, text: str, chars: Optional[str] = ...) -> str: ...
92
+ def lstrip(self, text: str, chars: Optional[str] = ...) -> str: ...
93
+ def strip_seqs(self, text: str) -> str: ...
94
+ def split_seqs(self, text: str, maxsplit: int) -> List[str]: ...
95
+ def wrap(
96
+ self, text: str, width: Optional[int] = ..., **kwargs: Any
97
+ ) -> List[str]: ...
98
+ def getch(self) -> str: ...
99
+ def ungetch(self, text: str) -> None: ...
100
+ def kbhit(self, timeout: Optional[float] = ...) -> bool: ...
101
+ def cbreak(self) -> ContextManager[None]: ...
102
+ def raw(self) -> ContextManager[None]: ...
103
+ def keypad(self) -> ContextManager[None]: ...
104
+ def inkey(
105
+ self, timeout: Optional[float] = ..., esc_delay: float = ...
106
+ ) -> Keystroke: ...
107
+
108
+ class WINSZ: ...
vllm/lib/python3.10/site-packages/blessed/win_terminal.py ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """Module containing Windows version of :class:`Terminal`."""
3
+
4
+ from __future__ import absolute_import
5
+
6
+ # std imports
7
+ import time
8
+ import msvcrt # pylint: disable=import-error
9
+ import contextlib
10
+
11
+ # 3rd party
12
+ from jinxed import win32 # pylint: disable=import-error
13
+
14
+ # local
15
+ from .terminal import WINSZ
16
+ from .terminal import Terminal as _Terminal
17
+
18
+
19
+ class Terminal(_Terminal):
20
+ """Windows subclass of :class:`Terminal`."""
21
+
22
+ def getch(self):
23
+ r"""
24
+ Read, decode, and return the next byte from the keyboard stream.
25
+
26
+ :rtype: unicode
27
+ :returns: a single unicode character, or ``u''`` if a multi-byte
28
+ sequence has not yet been fully received.
29
+
30
+ For versions of Windows 10.0.10586 and later, the console is expected
31
+ to be in ENABLE_VIRTUAL_TERMINAL_INPUT mode and the default method is
32
+ called.
33
+
34
+ For older versions of Windows, msvcrt.getwch() is used. If the received
35
+ character is ``\x00`` or ``\xe0``, the next character is
36
+ automatically retrieved.
37
+ """
38
+ if win32.VTMODE_SUPPORTED:
39
+ return super(Terminal, self).getch()
40
+
41
+ rtn = msvcrt.getwch()
42
+ if rtn in ('\x00', '\xe0'):
43
+ rtn += msvcrt.getwch()
44
+ return rtn
45
+
46
+ def kbhit(self, timeout=None):
47
+ """
48
+ Return whether a keypress has been detected on the keyboard.
49
+
50
+ This method is used by :meth:`inkey` to determine if a byte may
51
+ be read using :meth:`getch` without blocking. This is implemented
52
+ by wrapping msvcrt.kbhit() in a timeout.
53
+
54
+ :arg float timeout: When ``timeout`` is 0, this call is
55
+ non-blocking, otherwise blocking indefinitely until keypress
56
+ is detected when None (default). When ``timeout`` is a
57
+ positive number, returns after ``timeout`` seconds have
58
+ elapsed (float).
59
+ :rtype: bool
60
+ :returns: True if a keypress is awaiting to be read on the keyboard
61
+ attached to this terminal.
62
+ """
63
+ end = time.time() + (timeout or 0)
64
+ while True:
65
+
66
+ if msvcrt.kbhit():
67
+ return True
68
+
69
+ if timeout is not None and end < time.time():
70
+ break
71
+
72
+ time.sleep(0.01) # Sleep to reduce CPU load
73
+ return False
74
+
75
+ @staticmethod
76
+ def _winsize(fd):
77
+ """
78
+ Return named tuple describing size of the terminal by ``fd``.
79
+
80
+ :arg int fd: file descriptor queries for its window size.
81
+ :rtype: WINSZ
82
+ :returns: named tuple describing size of the terminal
83
+
84
+ WINSZ is a :class:`collections.namedtuple` instance, whose structure
85
+ directly maps to the return value of the :const:`termios.TIOCGWINSZ`
86
+ ioctl return value. The return parameters are:
87
+
88
+ - ``ws_row``: width of terminal by its number of character cells.
89
+ - ``ws_col``: height of terminal by its number of character cells.
90
+ - ``ws_xpixel``: width of terminal by pixels (not accurate).
91
+ - ``ws_ypixel``: height of terminal by pixels (not accurate).
92
+ """
93
+ window = win32.get_terminal_size(fd)
94
+ return WINSZ(ws_row=window.lines, ws_col=window.columns,
95
+ ws_xpixel=0, ws_ypixel=0)
96
+
97
+ @contextlib.contextmanager
98
+ def cbreak(self):
99
+ """
100
+ Allow each keystroke to be read immediately after it is pressed.
101
+
102
+ This is a context manager for ``jinxed.w32.setcbreak()``.
103
+
104
+ .. note:: You must explicitly print any user input you would like
105
+ displayed. If you provide any kind of editing, you must handle
106
+ backspace and other line-editing control functions in this mode
107
+ as well!
108
+
109
+ **Normally**, characters received from the keyboard cannot be read
110
+ by Python until the *Return* key is pressed. Also known as *cooked* or
111
+ *canonical input* mode, it allows the tty driver to provide
112
+ line-editing before shuttling the input to your program and is the
113
+ (implicit) default terminal mode set by most unix shells before
114
+ executing programs.
115
+ """
116
+ if self._keyboard_fd is not None:
117
+
118
+ filehandle = msvcrt.get_osfhandle(self._keyboard_fd)
119
+
120
+ # Save current terminal mode:
121
+ save_mode = win32.get_console_mode(filehandle)
122
+ save_line_buffered = self._line_buffered
123
+ win32.setcbreak(filehandle)
124
+ try:
125
+ self._line_buffered = False
126
+ yield
127
+ finally:
128
+ win32.set_console_mode(filehandle, save_mode)
129
+ self._line_buffered = save_line_buffered
130
+
131
+ else:
132
+ yield
133
+
134
+ @contextlib.contextmanager
135
+ def raw(self):
136
+ """
137
+ A context manager for ``jinxed.w32.setcbreak()``.
138
+
139
+ Although both :meth:`break` and :meth:`raw` modes allow each keystroke
140
+ to be read immediately after it is pressed, Raw mode disables
141
+ processing of input and output.
142
+
143
+ In cbreak mode, special input characters such as ``^C`` are
144
+ interpreted by the terminal driver and excluded from the stdin stream.
145
+ In raw mode these values are receive by the :meth:`inkey` method.
146
+ """
147
+ if self._keyboard_fd is not None:
148
+
149
+ filehandle = msvcrt.get_osfhandle(self._keyboard_fd)
150
+
151
+ # Save current terminal mode:
152
+ save_mode = win32.get_console_mode(filehandle)
153
+ save_line_buffered = self._line_buffered
154
+ win32.setraw(filehandle)
155
+ try:
156
+ self._line_buffered = False
157
+ yield
158
+ finally:
159
+ win32.set_console_mode(filehandle, save_mode)
160
+ self._line_buffered = save_line_buffered
161
+
162
+ else:
163
+ yield
vllm/lib/python3.10/site-packages/blessed/win_terminal.pyi ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # std imports
2
+ from typing import Optional, ContextManager
3
+
4
+ # local
5
+ from .terminal import Terminal as _Terminal
6
+
7
+ class Terminal(_Terminal):
8
+ def getch(self) -> str: ...
9
+ def kbhit(self, timeout: Optional[float] = ...) -> bool: ...
10
+ def cbreak(self) -> ContextManager[None]: ...
11
+ def raw(self) -> ContextManager[None]: ...
vllm/lib/python3.10/site-packages/python_multipart-0.0.20.dist-info/RECORD ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ multipart/__init__.py,sha256=_ttxOAFnTN4jeac-_8NeXpaXYYo0PPEIp8Ogo4YFNHE,935
2
+ multipart/__pycache__/__init__.cpython-310.pyc,,
3
+ multipart/__pycache__/decoders.cpython-310.pyc,,
4
+ multipart/__pycache__/exceptions.cpython-310.pyc,,
5
+ multipart/__pycache__/multipart.cpython-310.pyc,,
6
+ multipart/decoders.py,sha256=XvkAwTU9UFPiXkc0hkvovHf0W6H3vK-2ieWlhav02hQ,40
7
+ multipart/exceptions.py,sha256=6D_X-seiOmMAlIeiGlPGUs8-vpcvIGJeQycFMDb1f7A,42
8
+ multipart/multipart.py,sha256=8fDH14j_VMbrch_58wlzi63XNARGv80kOZAyN72aG7A,41
9
+ python_multipart-0.0.20.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
10
+ python_multipart-0.0.20.dist-info/METADATA,sha256=h2GtPOVShbVkpBUrjp5KE3t6eiJJhd0_WCaCXrb5TgU,1817
11
+ python_multipart-0.0.20.dist-info/RECORD,,
12
+ python_multipart-0.0.20.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
13
+ python_multipart-0.0.20.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
14
+ python_multipart-0.0.20.dist-info/licenses/LICENSE.txt,sha256=qOgzF2zWF9rwC51tOfoVyo7evG0WQwec0vSJPAwom-I,556
15
+ python_multipart/__init__.py,sha256=Nlw6Yrc__qXnCZLo17OzbJR2w2mwiSFk69IG4Wl35EU,512
16
+ python_multipart/__pycache__/__init__.cpython-310.pyc,,
17
+ python_multipart/__pycache__/decoders.cpython-310.pyc,,
18
+ python_multipart/__pycache__/exceptions.cpython-310.pyc,,
19
+ python_multipart/__pycache__/multipart.cpython-310.pyc,,
20
+ python_multipart/decoders.py,sha256=JM43FMNn_EKP0MI2ZkuZHhNa0MOASoIR0U5TvdG585k,6669
21
+ python_multipart/exceptions.py,sha256=a9buSOv_eiHZoukEJhdWX9LJYSJ6t7XOK3ZEaWoQZlk,992
22
+ python_multipart/multipart.py,sha256=pk3o3eB3KXbNxzOBxbEjCdz-1ESEZIMXVIfl12grG-o,76427
23
+ python_multipart/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
vllm/lib/python3.10/site-packages/python_multipart-0.0.20.dist-info/REQUESTED ADDED
File without changes
vllm/lib/python3.10/site-packages/python_multipart-0.0.20.dist-info/WHEEL ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.27.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
vllm/lib/python3.10/site-packages/python_multipart-0.0.20.dist-info/licenses/LICENSE.txt ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Copyright 2012, Andrew Dunham
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
+ https://www.apache.org/licenses/LICENSE-2.0
8
+
9
+ Unless required by applicable law or agreed to in writing, software
10
+ distributed under the License is distributed on an "AS IS" BASIS,
11
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ See the License for the specific language governing permissions and
13
+ limitations under the License.
14
+
vllm/lib/python3.10/site-packages/requests/__init__.py ADDED
@@ -0,0 +1,184 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # __
2
+ # /__) _ _ _ _ _/ _
3
+ # / ( (- (/ (/ (- _) / _)
4
+ # /
5
+
6
+ """
7
+ Requests HTTP Library
8
+ ~~~~~~~~~~~~~~~~~~~~~
9
+
10
+ Requests is an HTTP library, written in Python, for human beings.
11
+ Basic GET usage:
12
+
13
+ >>> import requests
14
+ >>> r = requests.get('https://www.python.org')
15
+ >>> r.status_code
16
+ 200
17
+ >>> b'Python is a programming language' in r.content
18
+ True
19
+
20
+ ... or POST:
21
+
22
+ >>> payload = dict(key1='value1', key2='value2')
23
+ >>> r = requests.post('https://httpbin.org/post', data=payload)
24
+ >>> print(r.text)
25
+ {
26
+ ...
27
+ "form": {
28
+ "key1": "value1",
29
+ "key2": "value2"
30
+ },
31
+ ...
32
+ }
33
+
34
+ The other HTTP methods are supported - see `requests.api`. Full documentation
35
+ is at <https://requests.readthedocs.io>.
36
+
37
+ :copyright: (c) 2017 by Kenneth Reitz.
38
+ :license: Apache 2.0, see LICENSE for more details.
39
+ """
40
+
41
+ import warnings
42
+
43
+ import urllib3
44
+
45
+ from .exceptions import RequestsDependencyWarning
46
+
47
+ try:
48
+ from charset_normalizer import __version__ as charset_normalizer_version
49
+ except ImportError:
50
+ charset_normalizer_version = None
51
+
52
+ try:
53
+ from chardet import __version__ as chardet_version
54
+ except ImportError:
55
+ chardet_version = None
56
+
57
+
58
+ def check_compatibility(urllib3_version, chardet_version, charset_normalizer_version):
59
+ urllib3_version = urllib3_version.split(".")
60
+ assert urllib3_version != ["dev"] # Verify urllib3 isn't installed from git.
61
+
62
+ # Sometimes, urllib3 only reports its version as 16.1.
63
+ if len(urllib3_version) == 2:
64
+ urllib3_version.append("0")
65
+
66
+ # Check urllib3 for compatibility.
67
+ major, minor, patch = urllib3_version # noqa: F811
68
+ major, minor, patch = int(major), int(minor), int(patch)
69
+ # urllib3 >= 1.21.1
70
+ assert major >= 1
71
+ if major == 1:
72
+ assert minor >= 21
73
+
74
+ # Check charset_normalizer for compatibility.
75
+ if chardet_version:
76
+ major, minor, patch = chardet_version.split(".")[:3]
77
+ major, minor, patch = int(major), int(minor), int(patch)
78
+ # chardet_version >= 3.0.2, < 6.0.0
79
+ assert (3, 0, 2) <= (major, minor, patch) < (6, 0, 0)
80
+ elif charset_normalizer_version:
81
+ major, minor, patch = charset_normalizer_version.split(".")[:3]
82
+ major, minor, patch = int(major), int(minor), int(patch)
83
+ # charset_normalizer >= 2.0.0 < 4.0.0
84
+ assert (2, 0, 0) <= (major, minor, patch) < (4, 0, 0)
85
+ else:
86
+ warnings.warn(
87
+ "Unable to find acceptable character detection dependency "
88
+ "(chardet or charset_normalizer).",
89
+ RequestsDependencyWarning,
90
+ )
91
+
92
+
93
+ def _check_cryptography(cryptography_version):
94
+ # cryptography < 1.3.4
95
+ try:
96
+ cryptography_version = list(map(int, cryptography_version.split(".")))
97
+ except ValueError:
98
+ return
99
+
100
+ if cryptography_version < [1, 3, 4]:
101
+ warning = "Old version of cryptography ({}) may cause slowdown.".format(
102
+ cryptography_version
103
+ )
104
+ warnings.warn(warning, RequestsDependencyWarning)
105
+
106
+
107
+ # Check imported dependencies for compatibility.
108
+ try:
109
+ check_compatibility(
110
+ urllib3.__version__, chardet_version, charset_normalizer_version
111
+ )
112
+ except (AssertionError, ValueError):
113
+ warnings.warn(
114
+ "urllib3 ({}) or chardet ({})/charset_normalizer ({}) doesn't match a supported "
115
+ "version!".format(
116
+ urllib3.__version__, chardet_version, charset_normalizer_version
117
+ ),
118
+ RequestsDependencyWarning,
119
+ )
120
+
121
+ # Attempt to enable urllib3's fallback for SNI support
122
+ # if the standard library doesn't support SNI or the
123
+ # 'ssl' library isn't available.
124
+ try:
125
+ try:
126
+ import ssl
127
+ except ImportError:
128
+ ssl = None
129
+
130
+ if not getattr(ssl, "HAS_SNI", False):
131
+ from urllib3.contrib import pyopenssl
132
+
133
+ pyopenssl.inject_into_urllib3()
134
+
135
+ # Check cryptography version
136
+ from cryptography import __version__ as cryptography_version
137
+
138
+ _check_cryptography(cryptography_version)
139
+ except ImportError:
140
+ pass
141
+
142
+ # urllib3's DependencyWarnings should be silenced.
143
+ from urllib3.exceptions import DependencyWarning
144
+
145
+ warnings.simplefilter("ignore", DependencyWarning)
146
+
147
+ # Set default logging handler to avoid "No handler found" warnings.
148
+ import logging
149
+ from logging import NullHandler
150
+
151
+ from . import packages, utils
152
+ from .__version__ import (
153
+ __author__,
154
+ __author_email__,
155
+ __build__,
156
+ __cake__,
157
+ __copyright__,
158
+ __description__,
159
+ __license__,
160
+ __title__,
161
+ __url__,
162
+ __version__,
163
+ )
164
+ from .api import delete, get, head, options, patch, post, put, request
165
+ from .exceptions import (
166
+ ConnectionError,
167
+ ConnectTimeout,
168
+ FileModeWarning,
169
+ HTTPError,
170
+ JSONDecodeError,
171
+ ReadTimeout,
172
+ RequestException,
173
+ Timeout,
174
+ TooManyRedirects,
175
+ URLRequired,
176
+ )
177
+ from .models import PreparedRequest, Request, Response
178
+ from .sessions import Session, session
179
+ from .status_codes import codes
180
+
181
+ logging.getLogger(__name__).addHandler(NullHandler())
182
+
183
+ # FileModeWarnings go off per the default.
184
+ warnings.simplefilter("default", FileModeWarning, append=True)
vllm/lib/python3.10/site-packages/requests/adapters.py ADDED
@@ -0,0 +1,719 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ requests.adapters
3
+ ~~~~~~~~~~~~~~~~~
4
+
5
+ This module contains the transport adapters that Requests uses to define
6
+ and maintain connections.
7
+ """
8
+
9
+ import os.path
10
+ import socket # noqa: F401
11
+ import typing
12
+ import warnings
13
+
14
+ from urllib3.exceptions import ClosedPoolError, ConnectTimeoutError
15
+ from urllib3.exceptions import HTTPError as _HTTPError
16
+ from urllib3.exceptions import InvalidHeader as _InvalidHeader
17
+ from urllib3.exceptions import (
18
+ LocationValueError,
19
+ MaxRetryError,
20
+ NewConnectionError,
21
+ ProtocolError,
22
+ )
23
+ from urllib3.exceptions import ProxyError as _ProxyError
24
+ from urllib3.exceptions import ReadTimeoutError, ResponseError
25
+ from urllib3.exceptions import SSLError as _SSLError
26
+ from urllib3.poolmanager import PoolManager, proxy_from_url
27
+ from urllib3.util import Timeout as TimeoutSauce
28
+ from urllib3.util import parse_url
29
+ from urllib3.util.retry import Retry
30
+ from urllib3.util.ssl_ import create_urllib3_context
31
+
32
+ from .auth import _basic_auth_str
33
+ from .compat import basestring, urlparse
34
+ from .cookies import extract_cookies_to_jar
35
+ from .exceptions import (
36
+ ConnectionError,
37
+ ConnectTimeout,
38
+ InvalidHeader,
39
+ InvalidProxyURL,
40
+ InvalidSchema,
41
+ InvalidURL,
42
+ ProxyError,
43
+ ReadTimeout,
44
+ RetryError,
45
+ SSLError,
46
+ )
47
+ from .models import Response
48
+ from .structures import CaseInsensitiveDict
49
+ from .utils import (
50
+ DEFAULT_CA_BUNDLE_PATH,
51
+ extract_zipped_paths,
52
+ get_auth_from_url,
53
+ get_encoding_from_headers,
54
+ prepend_scheme_if_needed,
55
+ select_proxy,
56
+ urldefragauth,
57
+ )
58
+
59
+ try:
60
+ from urllib3.contrib.socks import SOCKSProxyManager
61
+ except ImportError:
62
+
63
+ def SOCKSProxyManager(*args, **kwargs):
64
+ raise InvalidSchema("Missing dependencies for SOCKS support.")
65
+
66
+
67
+ if typing.TYPE_CHECKING:
68
+ from .models import PreparedRequest
69
+
70
+
71
+ DEFAULT_POOLBLOCK = False
72
+ DEFAULT_POOLSIZE = 10
73
+ DEFAULT_RETRIES = 0
74
+ DEFAULT_POOL_TIMEOUT = None
75
+
76
+
77
+ try:
78
+ import ssl # noqa: F401
79
+
80
+ _preloaded_ssl_context = create_urllib3_context()
81
+ _preloaded_ssl_context.load_verify_locations(
82
+ extract_zipped_paths(DEFAULT_CA_BUNDLE_PATH)
83
+ )
84
+ except ImportError:
85
+ # Bypass default SSLContext creation when Python
86
+ # interpreter isn't built with the ssl module.
87
+ _preloaded_ssl_context = None
88
+
89
+
90
+ def _urllib3_request_context(
91
+ request: "PreparedRequest",
92
+ verify: "bool | str | None",
93
+ client_cert: "typing.Tuple[str, str] | str | None",
94
+ poolmanager: "PoolManager",
95
+ ) -> "(typing.Dict[str, typing.Any], typing.Dict[str, typing.Any])":
96
+ host_params = {}
97
+ pool_kwargs = {}
98
+ parsed_request_url = urlparse(request.url)
99
+ scheme = parsed_request_url.scheme.lower()
100
+ port = parsed_request_url.port
101
+
102
+ # Determine if we have and should use our default SSLContext
103
+ # to optimize performance on standard requests.
104
+ poolmanager_kwargs = getattr(poolmanager, "connection_pool_kw", {})
105
+ has_poolmanager_ssl_context = poolmanager_kwargs.get("ssl_context")
106
+ should_use_default_ssl_context = (
107
+ _preloaded_ssl_context is not None and not has_poolmanager_ssl_context
108
+ )
109
+
110
+ cert_reqs = "CERT_REQUIRED"
111
+ if verify is False:
112
+ cert_reqs = "CERT_NONE"
113
+ elif verify is True and should_use_default_ssl_context:
114
+ pool_kwargs["ssl_context"] = _preloaded_ssl_context
115
+ elif isinstance(verify, str):
116
+ if not os.path.isdir(verify):
117
+ pool_kwargs["ca_certs"] = verify
118
+ else:
119
+ pool_kwargs["ca_cert_dir"] = verify
120
+ pool_kwargs["cert_reqs"] = cert_reqs
121
+ if client_cert is not None:
122
+ if isinstance(client_cert, tuple) and len(client_cert) == 2:
123
+ pool_kwargs["cert_file"] = client_cert[0]
124
+ pool_kwargs["key_file"] = client_cert[1]
125
+ else:
126
+ # According to our docs, we allow users to specify just the client
127
+ # cert path
128
+ pool_kwargs["cert_file"] = client_cert
129
+ host_params = {
130
+ "scheme": scheme,
131
+ "host": parsed_request_url.hostname,
132
+ "port": port,
133
+ }
134
+ return host_params, pool_kwargs
135
+
136
+
137
+ class BaseAdapter:
138
+ """The Base Transport Adapter"""
139
+
140
+ def __init__(self):
141
+ super().__init__()
142
+
143
+ def send(
144
+ self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None
145
+ ):
146
+ """Sends PreparedRequest object. Returns Response object.
147
+
148
+ :param request: The :class:`PreparedRequest <PreparedRequest>` being sent.
149
+ :param stream: (optional) Whether to stream the request content.
150
+ :param timeout: (optional) How long to wait for the server to send
151
+ data before giving up, as a float, or a :ref:`(connect timeout,
152
+ read timeout) <timeouts>` tuple.
153
+ :type timeout: float or tuple
154
+ :param verify: (optional) Either a boolean, in which case it controls whether we verify
155
+ the server's TLS certificate, or a string, in which case it must be a path
156
+ to a CA bundle to use
157
+ :param cert: (optional) Any user-provided SSL certificate to be trusted.
158
+ :param proxies: (optional) The proxies dictionary to apply to the request.
159
+ """
160
+ raise NotImplementedError
161
+
162
+ def close(self):
163
+ """Cleans up adapter specific items."""
164
+ raise NotImplementedError
165
+
166
+
167
+ class HTTPAdapter(BaseAdapter):
168
+ """The built-in HTTP Adapter for urllib3.
169
+
170
+ Provides a general-case interface for Requests sessions to contact HTTP and
171
+ HTTPS urls by implementing the Transport Adapter interface. This class will
172
+ usually be created by the :class:`Session <Session>` class under the
173
+ covers.
174
+
175
+ :param pool_connections: The number of urllib3 connection pools to cache.
176
+ :param pool_maxsize: The maximum number of connections to save in the pool.
177
+ :param max_retries: The maximum number of retries each connection
178
+ should attempt. Note, this applies only to failed DNS lookups, socket
179
+ connections and connection timeouts, never to requests where data has
180
+ made it to the server. By default, Requests does not retry failed
181
+ connections. If you need granular control over the conditions under
182
+ which we retry a request, import urllib3's ``Retry`` class and pass
183
+ that instead.
184
+ :param pool_block: Whether the connection pool should block for connections.
185
+
186
+ Usage::
187
+
188
+ >>> import requests
189
+ >>> s = requests.Session()
190
+ >>> a = requests.adapters.HTTPAdapter(max_retries=3)
191
+ >>> s.mount('http://', a)
192
+ """
193
+
194
+ __attrs__ = [
195
+ "max_retries",
196
+ "config",
197
+ "_pool_connections",
198
+ "_pool_maxsize",
199
+ "_pool_block",
200
+ ]
201
+
202
+ def __init__(
203
+ self,
204
+ pool_connections=DEFAULT_POOLSIZE,
205
+ pool_maxsize=DEFAULT_POOLSIZE,
206
+ max_retries=DEFAULT_RETRIES,
207
+ pool_block=DEFAULT_POOLBLOCK,
208
+ ):
209
+ if max_retries == DEFAULT_RETRIES:
210
+ self.max_retries = Retry(0, read=False)
211
+ else:
212
+ self.max_retries = Retry.from_int(max_retries)
213
+ self.config = {}
214
+ self.proxy_manager = {}
215
+
216
+ super().__init__()
217
+
218
+ self._pool_connections = pool_connections
219
+ self._pool_maxsize = pool_maxsize
220
+ self._pool_block = pool_block
221
+
222
+ self.init_poolmanager(pool_connections, pool_maxsize, block=pool_block)
223
+
224
+ def __getstate__(self):
225
+ return {attr: getattr(self, attr, None) for attr in self.__attrs__}
226
+
227
+ def __setstate__(self, state):
228
+ # Can't handle by adding 'proxy_manager' to self.__attrs__ because
229
+ # self.poolmanager uses a lambda function, which isn't pickleable.
230
+ self.proxy_manager = {}
231
+ self.config = {}
232
+
233
+ for attr, value in state.items():
234
+ setattr(self, attr, value)
235
+
236
+ self.init_poolmanager(
237
+ self._pool_connections, self._pool_maxsize, block=self._pool_block
238
+ )
239
+
240
+ def init_poolmanager(
241
+ self, connections, maxsize, block=DEFAULT_POOLBLOCK, **pool_kwargs
242
+ ):
243
+ """Initializes a urllib3 PoolManager.
244
+
245
+ This method should not be called from user code, and is only
246
+ exposed for use when subclassing the
247
+ :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
248
+
249
+ :param connections: The number of urllib3 connection pools to cache.
250
+ :param maxsize: The maximum number of connections to save in the pool.
251
+ :param block: Block when no free connections are available.
252
+ :param pool_kwargs: Extra keyword arguments used to initialize the Pool Manager.
253
+ """
254
+ # save these values for pickling
255
+ self._pool_connections = connections
256
+ self._pool_maxsize = maxsize
257
+ self._pool_block = block
258
+
259
+ self.poolmanager = PoolManager(
260
+ num_pools=connections,
261
+ maxsize=maxsize,
262
+ block=block,
263
+ **pool_kwargs,
264
+ )
265
+
266
+ def proxy_manager_for(self, proxy, **proxy_kwargs):
267
+ """Return urllib3 ProxyManager for the given proxy.
268
+
269
+ This method should not be called from user code, and is only
270
+ exposed for use when subclassing the
271
+ :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
272
+
273
+ :param proxy: The proxy to return a urllib3 ProxyManager for.
274
+ :param proxy_kwargs: Extra keyword arguments used to configure the Proxy Manager.
275
+ :returns: ProxyManager
276
+ :rtype: urllib3.ProxyManager
277
+ """
278
+ if proxy in self.proxy_manager:
279
+ manager = self.proxy_manager[proxy]
280
+ elif proxy.lower().startswith("socks"):
281
+ username, password = get_auth_from_url(proxy)
282
+ manager = self.proxy_manager[proxy] = SOCKSProxyManager(
283
+ proxy,
284
+ username=username,
285
+ password=password,
286
+ num_pools=self._pool_connections,
287
+ maxsize=self._pool_maxsize,
288
+ block=self._pool_block,
289
+ **proxy_kwargs,
290
+ )
291
+ else:
292
+ proxy_headers = self.proxy_headers(proxy)
293
+ manager = self.proxy_manager[proxy] = proxy_from_url(
294
+ proxy,
295
+ proxy_headers=proxy_headers,
296
+ num_pools=self._pool_connections,
297
+ maxsize=self._pool_maxsize,
298
+ block=self._pool_block,
299
+ **proxy_kwargs,
300
+ )
301
+
302
+ return manager
303
+
304
+ def cert_verify(self, conn, url, verify, cert):
305
+ """Verify a SSL certificate. This method should not be called from user
306
+ code, and is only exposed for use when subclassing the
307
+ :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
308
+
309
+ :param conn: The urllib3 connection object associated with the cert.
310
+ :param url: The requested URL.
311
+ :param verify: Either a boolean, in which case it controls whether we verify
312
+ the server's TLS certificate, or a string, in which case it must be a path
313
+ to a CA bundle to use
314
+ :param cert: The SSL certificate to verify.
315
+ """
316
+ if url.lower().startswith("https") and verify:
317
+ conn.cert_reqs = "CERT_REQUIRED"
318
+
319
+ # Only load the CA certificates if 'verify' is a string indicating the CA bundle to use.
320
+ # Otherwise, if verify is a boolean, we don't load anything since
321
+ # the connection will be using a context with the default certificates already loaded,
322
+ # and this avoids a call to the slow load_verify_locations()
323
+ if verify is not True:
324
+ # `verify` must be a str with a path then
325
+ cert_loc = verify
326
+
327
+ if not os.path.exists(cert_loc):
328
+ raise OSError(
329
+ f"Could not find a suitable TLS CA certificate bundle, "
330
+ f"invalid path: {cert_loc}"
331
+ )
332
+
333
+ if not os.path.isdir(cert_loc):
334
+ conn.ca_certs = cert_loc
335
+ else:
336
+ conn.ca_cert_dir = cert_loc
337
+ else:
338
+ conn.cert_reqs = "CERT_NONE"
339
+ conn.ca_certs = None
340
+ conn.ca_cert_dir = None
341
+
342
+ if cert:
343
+ if not isinstance(cert, basestring):
344
+ conn.cert_file = cert[0]
345
+ conn.key_file = cert[1]
346
+ else:
347
+ conn.cert_file = cert
348
+ conn.key_file = None
349
+ if conn.cert_file and not os.path.exists(conn.cert_file):
350
+ raise OSError(
351
+ f"Could not find the TLS certificate file, "
352
+ f"invalid path: {conn.cert_file}"
353
+ )
354
+ if conn.key_file and not os.path.exists(conn.key_file):
355
+ raise OSError(
356
+ f"Could not find the TLS key file, invalid path: {conn.key_file}"
357
+ )
358
+
359
+ def build_response(self, req, resp):
360
+ """Builds a :class:`Response <requests.Response>` object from a urllib3
361
+ response. This should not be called from user code, and is only exposed
362
+ for use when subclassing the
363
+ :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`
364
+
365
+ :param req: The :class:`PreparedRequest <PreparedRequest>` used to generate the response.
366
+ :param resp: The urllib3 response object.
367
+ :rtype: requests.Response
368
+ """
369
+ response = Response()
370
+
371
+ # Fallback to None if there's no status_code, for whatever reason.
372
+ response.status_code = getattr(resp, "status", None)
373
+
374
+ # Make headers case-insensitive.
375
+ response.headers = CaseInsensitiveDict(getattr(resp, "headers", {}))
376
+
377
+ # Set encoding.
378
+ response.encoding = get_encoding_from_headers(response.headers)
379
+ response.raw = resp
380
+ response.reason = response.raw.reason
381
+
382
+ if isinstance(req.url, bytes):
383
+ response.url = req.url.decode("utf-8")
384
+ else:
385
+ response.url = req.url
386
+
387
+ # Add new cookies from the server.
388
+ extract_cookies_to_jar(response.cookies, req, resp)
389
+
390
+ # Give the Response some context.
391
+ response.request = req
392
+ response.connection = self
393
+
394
+ return response
395
+
396
+ def build_connection_pool_key_attributes(self, request, verify, cert=None):
397
+ """Build the PoolKey attributes used by urllib3 to return a connection.
398
+
399
+ This looks at the PreparedRequest, the user-specified verify value,
400
+ and the value of the cert parameter to determine what PoolKey values
401
+ to use to select a connection from a given urllib3 Connection Pool.
402
+
403
+ The SSL related pool key arguments are not consistently set. As of
404
+ this writing, use the following to determine what keys may be in that
405
+ dictionary:
406
+
407
+ * If ``verify`` is ``True``, ``"ssl_context"`` will be set and will be the
408
+ default Requests SSL Context
409
+ * If ``verify`` is ``False``, ``"ssl_context"`` will not be set but
410
+ ``"cert_reqs"`` will be set
411
+ * If ``verify`` is a string, (i.e., it is a user-specified trust bundle)
412
+ ``"ca_certs"`` will be set if the string is not a directory recognized
413
+ by :py:func:`os.path.isdir`, otherwise ``"ca_certs_dir"`` will be
414
+ set.
415
+ * If ``"cert"`` is specified, ``"cert_file"`` will always be set. If
416
+ ``"cert"`` is a tuple with a second item, ``"key_file"`` will also
417
+ be present
418
+
419
+ To override these settings, one may subclass this class, call this
420
+ method and use the above logic to change parameters as desired. For
421
+ example, if one wishes to use a custom :py:class:`ssl.SSLContext` one
422
+ must both set ``"ssl_context"`` and based on what else they require,
423
+ alter the other keys to ensure the desired behaviour.
424
+
425
+ :param request:
426
+ The PreparedReqest being sent over the connection.
427
+ :type request:
428
+ :class:`~requests.models.PreparedRequest`
429
+ :param verify:
430
+ Either a boolean, in which case it controls whether
431
+ we verify the server's TLS certificate, or a string, in which case it
432
+ must be a path to a CA bundle to use.
433
+ :param cert:
434
+ (optional) Any user-provided SSL certificate for client
435
+ authentication (a.k.a., mTLS). This may be a string (i.e., just
436
+ the path to a file which holds both certificate and key) or a
437
+ tuple of length 2 with the certificate file path and key file
438
+ path.
439
+ :returns:
440
+ A tuple of two dictionaries. The first is the "host parameters"
441
+ portion of the Pool Key including scheme, hostname, and port. The
442
+ second is a dictionary of SSLContext related parameters.
443
+ """
444
+ return _urllib3_request_context(request, verify, cert, self.poolmanager)
445
+
446
+ def get_connection_with_tls_context(self, request, verify, proxies=None, cert=None):
447
+ """Returns a urllib3 connection for the given request and TLS settings.
448
+ This should not be called from user code, and is only exposed for use
449
+ when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
450
+
451
+ :param request:
452
+ The :class:`PreparedRequest <PreparedRequest>` object to be sent
453
+ over the connection.
454
+ :param verify:
455
+ Either a boolean, in which case it controls whether we verify the
456
+ server's TLS certificate, or a string, in which case it must be a
457
+ path to a CA bundle to use.
458
+ :param proxies:
459
+ (optional) The proxies dictionary to apply to the request.
460
+ :param cert:
461
+ (optional) Any user-provided SSL certificate to be used for client
462
+ authentication (a.k.a., mTLS).
463
+ :rtype:
464
+ urllib3.ConnectionPool
465
+ """
466
+ proxy = select_proxy(request.url, proxies)
467
+ try:
468
+ host_params, pool_kwargs = self.build_connection_pool_key_attributes(
469
+ request,
470
+ verify,
471
+ cert,
472
+ )
473
+ except ValueError as e:
474
+ raise InvalidURL(e, request=request)
475
+ if proxy:
476
+ proxy = prepend_scheme_if_needed(proxy, "http")
477
+ proxy_url = parse_url(proxy)
478
+ if not proxy_url.host:
479
+ raise InvalidProxyURL(
480
+ "Please check proxy URL. It is malformed "
481
+ "and could be missing the host."
482
+ )
483
+ proxy_manager = self.proxy_manager_for(proxy)
484
+ conn = proxy_manager.connection_from_host(
485
+ **host_params, pool_kwargs=pool_kwargs
486
+ )
487
+ else:
488
+ # Only scheme should be lower case
489
+ conn = self.poolmanager.connection_from_host(
490
+ **host_params, pool_kwargs=pool_kwargs
491
+ )
492
+
493
+ return conn
494
+
495
+ def get_connection(self, url, proxies=None):
496
+ """DEPRECATED: Users should move to `get_connection_with_tls_context`
497
+ for all subclasses of HTTPAdapter using Requests>=2.32.2.
498
+
499
+ Returns a urllib3 connection for the given URL. This should not be
500
+ called from user code, and is only exposed for use when subclassing the
501
+ :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
502
+
503
+ :param url: The URL to connect to.
504
+ :param proxies: (optional) A Requests-style dictionary of proxies used on this request.
505
+ :rtype: urllib3.ConnectionPool
506
+ """
507
+ warnings.warn(
508
+ (
509
+ "`get_connection` has been deprecated in favor of "
510
+ "`get_connection_with_tls_context`. Custom HTTPAdapter subclasses "
511
+ "will need to migrate for Requests>=2.32.2. Please see "
512
+ "https://github.com/psf/requests/pull/6710 for more details."
513
+ ),
514
+ DeprecationWarning,
515
+ )
516
+ proxy = select_proxy(url, proxies)
517
+
518
+ if proxy:
519
+ proxy = prepend_scheme_if_needed(proxy, "http")
520
+ proxy_url = parse_url(proxy)
521
+ if not proxy_url.host:
522
+ raise InvalidProxyURL(
523
+ "Please check proxy URL. It is malformed "
524
+ "and could be missing the host."
525
+ )
526
+ proxy_manager = self.proxy_manager_for(proxy)
527
+ conn = proxy_manager.connection_from_url(url)
528
+ else:
529
+ # Only scheme should be lower case
530
+ parsed = urlparse(url)
531
+ url = parsed.geturl()
532
+ conn = self.poolmanager.connection_from_url(url)
533
+
534
+ return conn
535
+
536
+ def close(self):
537
+ """Disposes of any internal state.
538
+
539
+ Currently, this closes the PoolManager and any active ProxyManager,
540
+ which closes any pooled connections.
541
+ """
542
+ self.poolmanager.clear()
543
+ for proxy in self.proxy_manager.values():
544
+ proxy.clear()
545
+
546
+ def request_url(self, request, proxies):
547
+ """Obtain the url to use when making the final request.
548
+
549
+ If the message is being sent through a HTTP proxy, the full URL has to
550
+ be used. Otherwise, we should only use the path portion of the URL.
551
+
552
+ This should not be called from user code, and is only exposed for use
553
+ when subclassing the
554
+ :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
555
+
556
+ :param request: The :class:`PreparedRequest <PreparedRequest>` being sent.
557
+ :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs.
558
+ :rtype: str
559
+ """
560
+ proxy = select_proxy(request.url, proxies)
561
+ scheme = urlparse(request.url).scheme
562
+
563
+ is_proxied_http_request = proxy and scheme != "https"
564
+ using_socks_proxy = False
565
+ if proxy:
566
+ proxy_scheme = urlparse(proxy).scheme.lower()
567
+ using_socks_proxy = proxy_scheme.startswith("socks")
568
+
569
+ url = request.path_url
570
+ if url.startswith("//"): # Don't confuse urllib3
571
+ url = f"/{url.lstrip('/')}"
572
+
573
+ if is_proxied_http_request and not using_socks_proxy:
574
+ url = urldefragauth(request.url)
575
+
576
+ return url
577
+
578
+ def add_headers(self, request, **kwargs):
579
+ """Add any headers needed by the connection. As of v2.0 this does
580
+ nothing by default, but is left for overriding by users that subclass
581
+ the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
582
+
583
+ This should not be called from user code, and is only exposed for use
584
+ when subclassing the
585
+ :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
586
+
587
+ :param request: The :class:`PreparedRequest <PreparedRequest>` to add headers to.
588
+ :param kwargs: The keyword arguments from the call to send().
589
+ """
590
+ pass
591
+
592
+ def proxy_headers(self, proxy):
593
+ """Returns a dictionary of the headers to add to any request sent
594
+ through a proxy. This works with urllib3 magic to ensure that they are
595
+ correctly sent to the proxy, rather than in a tunnelled request if
596
+ CONNECT is being used.
597
+
598
+ This should not be called from user code, and is only exposed for use
599
+ when subclassing the
600
+ :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
601
+
602
+ :param proxy: The url of the proxy being used for this request.
603
+ :rtype: dict
604
+ """
605
+ headers = {}
606
+ username, password = get_auth_from_url(proxy)
607
+
608
+ if username:
609
+ headers["Proxy-Authorization"] = _basic_auth_str(username, password)
610
+
611
+ return headers
612
+
613
+ def send(
614
+ self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None
615
+ ):
616
+ """Sends PreparedRequest object. Returns Response object.
617
+
618
+ :param request: The :class:`PreparedRequest <PreparedRequest>` being sent.
619
+ :param stream: (optional) Whether to stream the request content.
620
+ :param timeout: (optional) How long to wait for the server to send
621
+ data before giving up, as a float, or a :ref:`(connect timeout,
622
+ read timeout) <timeouts>` tuple.
623
+ :type timeout: float or tuple or urllib3 Timeout object
624
+ :param verify: (optional) Either a boolean, in which case it controls whether
625
+ we verify the server's TLS certificate, or a string, in which case it
626
+ must be a path to a CA bundle to use
627
+ :param cert: (optional) Any user-provided SSL certificate to be trusted.
628
+ :param proxies: (optional) The proxies dictionary to apply to the request.
629
+ :rtype: requests.Response
630
+ """
631
+
632
+ try:
633
+ conn = self.get_connection_with_tls_context(
634
+ request, verify, proxies=proxies, cert=cert
635
+ )
636
+ except LocationValueError as e:
637
+ raise InvalidURL(e, request=request)
638
+
639
+ self.cert_verify(conn, request.url, verify, cert)
640
+ url = self.request_url(request, proxies)
641
+ self.add_headers(
642
+ request,
643
+ stream=stream,
644
+ timeout=timeout,
645
+ verify=verify,
646
+ cert=cert,
647
+ proxies=proxies,
648
+ )
649
+
650
+ chunked = not (request.body is None or "Content-Length" in request.headers)
651
+
652
+ if isinstance(timeout, tuple):
653
+ try:
654
+ connect, read = timeout
655
+ timeout = TimeoutSauce(connect=connect, read=read)
656
+ except ValueError:
657
+ raise ValueError(
658
+ f"Invalid timeout {timeout}. Pass a (connect, read) timeout tuple, "
659
+ f"or a single float to set both timeouts to the same value."
660
+ )
661
+ elif isinstance(timeout, TimeoutSauce):
662
+ pass
663
+ else:
664
+ timeout = TimeoutSauce(connect=timeout, read=timeout)
665
+
666
+ try:
667
+ resp = conn.urlopen(
668
+ method=request.method,
669
+ url=url,
670
+ body=request.body,
671
+ headers=request.headers,
672
+ redirect=False,
673
+ assert_same_host=False,
674
+ preload_content=False,
675
+ decode_content=False,
676
+ retries=self.max_retries,
677
+ timeout=timeout,
678
+ chunked=chunked,
679
+ )
680
+
681
+ except (ProtocolError, OSError) as err:
682
+ raise ConnectionError(err, request=request)
683
+
684
+ except MaxRetryError as e:
685
+ if isinstance(e.reason, ConnectTimeoutError):
686
+ # TODO: Remove this in 3.0.0: see #2811
687
+ if not isinstance(e.reason, NewConnectionError):
688
+ raise ConnectTimeout(e, request=request)
689
+
690
+ if isinstance(e.reason, ResponseError):
691
+ raise RetryError(e, request=request)
692
+
693
+ if isinstance(e.reason, _ProxyError):
694
+ raise ProxyError(e, request=request)
695
+
696
+ if isinstance(e.reason, _SSLError):
697
+ # This branch is for urllib3 v1.22 and later.
698
+ raise SSLError(e, request=request)
699
+
700
+ raise ConnectionError(e, request=request)
701
+
702
+ except ClosedPoolError as e:
703
+ raise ConnectionError(e, request=request)
704
+
705
+ except _ProxyError as e:
706
+ raise ProxyError(e)
707
+
708
+ except (_SSLError, _HTTPError) as e:
709
+ if isinstance(e, _SSLError):
710
+ # This branch is for urllib3 versions earlier than v1.22
711
+ raise SSLError(e, request=request)
712
+ elif isinstance(e, ReadTimeoutError):
713
+ raise ReadTimeout(e, request=request)
714
+ elif isinstance(e, _InvalidHeader):
715
+ raise InvalidHeader(e, request=request)
716
+ else:
717
+ raise
718
+
719
+ return self.build_response(request, resp)
vllm/lib/python3.10/site-packages/requests/api.py ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ requests.api
3
+ ~~~~~~~~~~~~
4
+
5
+ This module implements the Requests API.
6
+
7
+ :copyright: (c) 2012 by Kenneth Reitz.
8
+ :license: Apache2, see LICENSE for more details.
9
+ """
10
+
11
+ from . import sessions
12
+
13
+
14
+ def request(method, url, **kwargs):
15
+ """Constructs and sends a :class:`Request <Request>`.
16
+
17
+ :param method: method for the new :class:`Request` object: ``GET``, ``OPTIONS``, ``HEAD``, ``POST``, ``PUT``, ``PATCH``, or ``DELETE``.
18
+ :param url: URL for the new :class:`Request` object.
19
+ :param params: (optional) Dictionary, list of tuples or bytes to send
20
+ in the query string for the :class:`Request`.
21
+ :param data: (optional) Dictionary, list of tuples, bytes, or file-like
22
+ object to send in the body of the :class:`Request`.
23
+ :param json: (optional) A JSON serializable Python object to send in the body of the :class:`Request`.
24
+ :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`.
25
+ :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`.
26
+ :param files: (optional) Dictionary of ``'name': file-like-objects`` (or ``{'name': file-tuple}``) for multipart encoding upload.
27
+ ``file-tuple`` can be a 2-tuple ``('filename', fileobj)``, 3-tuple ``('filename', fileobj, 'content_type')``
28
+ or a 4-tuple ``('filename', fileobj, 'content_type', custom_headers)``, where ``'content_type'`` is a string
29
+ defining the content type of the given file and ``custom_headers`` a dict-like object containing additional headers
30
+ to add for the file.
31
+ :param auth: (optional) Auth tuple to enable Basic/Digest/Custom HTTP Auth.
32
+ :param timeout: (optional) How many seconds to wait for the server to send data
33
+ before giving up, as a float, or a :ref:`(connect timeout, read
34
+ timeout) <timeouts>` tuple.
35
+ :type timeout: float or tuple
36
+ :param allow_redirects: (optional) Boolean. Enable/disable GET/OPTIONS/POST/PUT/PATCH/DELETE/HEAD redirection. Defaults to ``True``.
37
+ :type allow_redirects: bool
38
+ :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.
39
+ :param verify: (optional) Either a boolean, in which case it controls whether we verify
40
+ the server's TLS certificate, or a string, in which case it must be a path
41
+ to a CA bundle to use. Defaults to ``True``.
42
+ :param stream: (optional) if ``False``, the response content will be immediately downloaded.
43
+ :param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair.
44
+ :return: :class:`Response <Response>` object
45
+ :rtype: requests.Response
46
+
47
+ Usage::
48
+
49
+ >>> import requests
50
+ >>> req = requests.request('GET', 'https://httpbin.org/get')
51
+ >>> req
52
+ <Response [200]>
53
+ """
54
+
55
+ # By using the 'with' statement we are sure the session is closed, thus we
56
+ # avoid leaving sockets open which can trigger a ResourceWarning in some
57
+ # cases, and look like a memory leak in others.
58
+ with sessions.Session() as session:
59
+ return session.request(method=method, url=url, **kwargs)
60
+
61
+
62
+ def get(url, params=None, **kwargs):
63
+ r"""Sends a GET request.
64
+
65
+ :param url: URL for the new :class:`Request` object.
66
+ :param params: (optional) Dictionary, list of tuples or bytes to send
67
+ in the query string for the :class:`Request`.
68
+ :param \*\*kwargs: Optional arguments that ``request`` takes.
69
+ :return: :class:`Response <Response>` object
70
+ :rtype: requests.Response
71
+ """
72
+
73
+ return request("get", url, params=params, **kwargs)
74
+
75
+
76
+ def options(url, **kwargs):
77
+ r"""Sends an OPTIONS request.
78
+
79
+ :param url: URL for the new :class:`Request` object.
80
+ :param \*\*kwargs: Optional arguments that ``request`` takes.
81
+ :return: :class:`Response <Response>` object
82
+ :rtype: requests.Response
83
+ """
84
+
85
+ return request("options", url, **kwargs)
86
+
87
+
88
+ def head(url, **kwargs):
89
+ r"""Sends a HEAD request.
90
+
91
+ :param url: URL for the new :class:`Request` object.
92
+ :param \*\*kwargs: Optional arguments that ``request`` takes. If
93
+ `allow_redirects` is not provided, it will be set to `False` (as
94
+ opposed to the default :meth:`request` behavior).
95
+ :return: :class:`Response <Response>` object
96
+ :rtype: requests.Response
97
+ """
98
+
99
+ kwargs.setdefault("allow_redirects", False)
100
+ return request("head", url, **kwargs)
101
+
102
+
103
+ def post(url, data=None, json=None, **kwargs):
104
+ r"""Sends a POST request.
105
+
106
+ :param url: URL for the new :class:`Request` object.
107
+ :param data: (optional) Dictionary, list of tuples, bytes, or file-like
108
+ object to send in the body of the :class:`Request`.
109
+ :param json: (optional) A JSON serializable Python object to send in the body of the :class:`Request`.
110
+ :param \*\*kwargs: Optional arguments that ``request`` takes.
111
+ :return: :class:`Response <Response>` object
112
+ :rtype: requests.Response
113
+ """
114
+
115
+ return request("post", url, data=data, json=json, **kwargs)
116
+
117
+
118
+ def put(url, data=None, **kwargs):
119
+ r"""Sends a PUT request.
120
+
121
+ :param url: URL for the new :class:`Request` object.
122
+ :param data: (optional) Dictionary, list of tuples, bytes, or file-like
123
+ object to send in the body of the :class:`Request`.
124
+ :param json: (optional) A JSON serializable Python object to send in the body of the :class:`Request`.
125
+ :param \*\*kwargs: Optional arguments that ``request`` takes.
126
+ :return: :class:`Response <Response>` object
127
+ :rtype: requests.Response
128
+ """
129
+
130
+ return request("put", url, data=data, **kwargs)
131
+
132
+
133
+ def patch(url, data=None, **kwargs):
134
+ r"""Sends a PATCH request.
135
+
136
+ :param url: URL for the new :class:`Request` object.
137
+ :param data: (optional) Dictionary, list of tuples, bytes, or file-like
138
+ object to send in the body of the :class:`Request`.
139
+ :param json: (optional) A JSON serializable Python object to send in the body of the :class:`Request`.
140
+ :param \*\*kwargs: Optional arguments that ``request`` takes.
141
+ :return: :class:`Response <Response>` object
142
+ :rtype: requests.Response
143
+ """
144
+
145
+ return request("patch", url, data=data, **kwargs)
146
+
147
+
148
+ def delete(url, **kwargs):
149
+ r"""Sends a DELETE request.
150
+
151
+ :param url: URL for the new :class:`Request` object.
152
+ :param \*\*kwargs: Optional arguments that ``request`` takes.
153
+ :return: :class:`Response <Response>` object
154
+ :rtype: requests.Response
155
+ """
156
+
157
+ return request("delete", url, **kwargs)
vllm/lib/python3.10/site-packages/requests/certs.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ """
4
+ requests.certs
5
+ ~~~~~~~~~~~~~~
6
+
7
+ This module returns the preferred default CA certificate bundle. There is
8
+ only one — the one from the certifi package.
9
+
10
+ If you are packaging Requests, e.g., for a Linux distribution or a managed
11
+ environment, you can change the definition of where() to return a separately
12
+ packaged CA bundle.
13
+ """
14
+ from certifi import where
15
+
16
+ if __name__ == "__main__":
17
+ print(where())
vllm/lib/python3.10/site-packages/requests/compat.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ requests.compat
3
+ ~~~~~~~~~~~~~~~
4
+
5
+ This module previously handled import compatibility issues
6
+ between Python 2 and Python 3. It remains for backwards
7
+ compatibility until the next major version.
8
+ """
9
+
10
+ import importlib
11
+ import sys
12
+
13
+ # -------------------
14
+ # Character Detection
15
+ # -------------------
16
+
17
+
18
+ def _resolve_char_detection():
19
+ """Find supported character detection libraries."""
20
+ chardet = None
21
+ for lib in ("chardet", "charset_normalizer"):
22
+ if chardet is None:
23
+ try:
24
+ chardet = importlib.import_module(lib)
25
+ except ImportError:
26
+ pass
27
+ return chardet
28
+
29
+
30
+ chardet = _resolve_char_detection()
31
+
32
+ # -------
33
+ # Pythons
34
+ # -------
35
+
36
+ # Syntax sugar.
37
+ _ver = sys.version_info
38
+
39
+ #: Python 2.x?
40
+ is_py2 = _ver[0] == 2
41
+
42
+ #: Python 3.x?
43
+ is_py3 = _ver[0] == 3
44
+
45
+ # json/simplejson module import resolution
46
+ has_simplejson = False
47
+ try:
48
+ import simplejson as json
49
+
50
+ has_simplejson = True
51
+ except ImportError:
52
+ import json
53
+
54
+ if has_simplejson:
55
+ from simplejson import JSONDecodeError
56
+ else:
57
+ from json import JSONDecodeError
58
+
59
+ # Keep OrderedDict for backwards compatibility.
60
+ from collections import OrderedDict
61
+ from collections.abc import Callable, Mapping, MutableMapping
62
+ from http import cookiejar as cookielib
63
+ from http.cookies import Morsel
64
+ from io import StringIO
65
+
66
+ # --------------
67
+ # Legacy Imports
68
+ # --------------
69
+ from urllib.parse import (
70
+ quote,
71
+ quote_plus,
72
+ unquote,
73
+ unquote_plus,
74
+ urldefrag,
75
+ urlencode,
76
+ urljoin,
77
+ urlparse,
78
+ urlsplit,
79
+ urlunparse,
80
+ )
81
+ from urllib.request import (
82
+ getproxies,
83
+ getproxies_environment,
84
+ parse_http_list,
85
+ proxy_bypass,
86
+ proxy_bypass_environment,
87
+ )
88
+
89
+ builtin_str = str
90
+ str = str
91
+ bytes = bytes
92
+ basestring = (str, bytes)
93
+ numeric_types = (int, float)
94
+ integer_types = (int,)
vllm/lib/python3.10/site-packages/requests/exceptions.py ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ requests.exceptions
3
+ ~~~~~~~~~~~~~~~~~~~
4
+
5
+ This module contains the set of Requests' exceptions.
6
+ """
7
+ from urllib3.exceptions import HTTPError as BaseHTTPError
8
+
9
+ from .compat import JSONDecodeError as CompatJSONDecodeError
10
+
11
+
12
+ class RequestException(IOError):
13
+ """There was an ambiguous exception that occurred while handling your
14
+ request.
15
+ """
16
+
17
+ def __init__(self, *args, **kwargs):
18
+ """Initialize RequestException with `request` and `response` objects."""
19
+ response = kwargs.pop("response", None)
20
+ self.response = response
21
+ self.request = kwargs.pop("request", None)
22
+ if response is not None and not self.request and hasattr(response, "request"):
23
+ self.request = self.response.request
24
+ super().__init__(*args, **kwargs)
25
+
26
+
27
+ class InvalidJSONError(RequestException):
28
+ """A JSON error occurred."""
29
+
30
+
31
+ class JSONDecodeError(InvalidJSONError, CompatJSONDecodeError):
32
+ """Couldn't decode the text into json"""
33
+
34
+ def __init__(self, *args, **kwargs):
35
+ """
36
+ Construct the JSONDecodeError instance first with all
37
+ args. Then use it's args to construct the IOError so that
38
+ the json specific args aren't used as IOError specific args
39
+ and the error message from JSONDecodeError is preserved.
40
+ """
41
+ CompatJSONDecodeError.__init__(self, *args)
42
+ InvalidJSONError.__init__(self, *self.args, **kwargs)
43
+
44
+ def __reduce__(self):
45
+ """
46
+ The __reduce__ method called when pickling the object must
47
+ be the one from the JSONDecodeError (be it json/simplejson)
48
+ as it expects all the arguments for instantiation, not just
49
+ one like the IOError, and the MRO would by default call the
50
+ __reduce__ method from the IOError due to the inheritance order.
51
+ """
52
+ return CompatJSONDecodeError.__reduce__(self)
53
+
54
+
55
+ class HTTPError(RequestException):
56
+ """An HTTP error occurred."""
57
+
58
+
59
+ class ConnectionError(RequestException):
60
+ """A Connection error occurred."""
61
+
62
+
63
+ class ProxyError(ConnectionError):
64
+ """A proxy error occurred."""
65
+
66
+
67
+ class SSLError(ConnectionError):
68
+ """An SSL error occurred."""
69
+
70
+
71
+ class Timeout(RequestException):
72
+ """The request timed out.
73
+
74
+ Catching this error will catch both
75
+ :exc:`~requests.exceptions.ConnectTimeout` and
76
+ :exc:`~requests.exceptions.ReadTimeout` errors.
77
+ """
78
+
79
+
80
+ class ConnectTimeout(ConnectionError, Timeout):
81
+ """The request timed out while trying to connect to the remote server.
82
+
83
+ Requests that produced this error are safe to retry.
84
+ """
85
+
86
+
87
+ class ReadTimeout(Timeout):
88
+ """The server did not send any data in the allotted amount of time."""
89
+
90
+
91
+ class URLRequired(RequestException):
92
+ """A valid URL is required to make a request."""
93
+
94
+
95
+ class TooManyRedirects(RequestException):
96
+ """Too many redirects."""
97
+
98
+
99
+ class MissingSchema(RequestException, ValueError):
100
+ """The URL scheme (e.g. http or https) is missing."""
101
+
102
+
103
+ class InvalidSchema(RequestException, ValueError):
104
+ """The URL scheme provided is either invalid or unsupported."""
105
+
106
+
107
+ class InvalidURL(RequestException, ValueError):
108
+ """The URL provided was somehow invalid."""
109
+
110
+
111
+ class InvalidHeader(RequestException, ValueError):
112
+ """The header value provided was somehow invalid."""
113
+
114
+
115
+ class InvalidProxyURL(InvalidURL):
116
+ """The proxy URL provided is invalid."""
117
+
118
+
119
+ class ChunkedEncodingError(RequestException):
120
+ """The server declared chunked encoding but sent an invalid chunk."""
121
+
122
+
123
+ class ContentDecodingError(RequestException, BaseHTTPError):
124
+ """Failed to decode response content."""
125
+
126
+
127
+ class StreamConsumedError(RequestException, TypeError):
128
+ """The content for this response was already consumed."""
129
+
130
+
131
+ class RetryError(RequestException):
132
+ """Custom retries logic failed"""
133
+
134
+
135
+ class UnrewindableBodyError(RequestException):
136
+ """Requests encountered an error when trying to rewind a body."""
137
+
138
+
139
+ # Warnings
140
+
141
+
142
+ class RequestsWarning(Warning):
143
+ """Base warning for Requests."""
144
+
145
+
146
+ class FileModeWarning(RequestsWarning, DeprecationWarning):
147
+ """A file was opened in text mode, but Requests determined its binary length."""
148
+
149
+
150
+ class RequestsDependencyWarning(RequestsWarning):
151
+ """An imported dependency doesn't match the expected version range."""
vllm/lib/python3.10/site-packages/requests/hooks.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ requests.hooks
3
+ ~~~~~~~~~~~~~~
4
+
5
+ This module provides the capabilities for the Requests hooks system.
6
+
7
+ Available hooks:
8
+
9
+ ``response``:
10
+ The response generated from a Request.
11
+ """
12
+ HOOKS = ["response"]
13
+
14
+
15
+ def default_hooks():
16
+ return {event: [] for event in HOOKS}
17
+
18
+
19
+ # TODO: response is the only one
20
+
21
+
22
+ def dispatch_hook(key, hooks, hook_data, **kwargs):
23
+ """Dispatches a hook dictionary on a given piece of data."""
24
+ hooks = hooks or {}
25
+ hooks = hooks.get(key)
26
+ if hooks:
27
+ if hasattr(hooks, "__call__"):
28
+ hooks = [hooks]
29
+ for hook in hooks:
30
+ _hook_data = hook(hook_data, **kwargs)
31
+ if _hook_data is not None:
32
+ hook_data = _hook_data
33
+ return hook_data
vllm/lib/python3.10/site-packages/requests/sessions.py ADDED
@@ -0,0 +1,831 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ requests.sessions
3
+ ~~~~~~~~~~~~~~~~~
4
+
5
+ This module provides a Session object to manage and persist settings across
6
+ requests (cookies, auth, proxies).
7
+ """
8
+ import os
9
+ import sys
10
+ import time
11
+ from collections import OrderedDict
12
+ from datetime import timedelta
13
+
14
+ from ._internal_utils import to_native_string
15
+ from .adapters import HTTPAdapter
16
+ from .auth import _basic_auth_str
17
+ from .compat import Mapping, cookielib, urljoin, urlparse
18
+ from .cookies import (
19
+ RequestsCookieJar,
20
+ cookiejar_from_dict,
21
+ extract_cookies_to_jar,
22
+ merge_cookies,
23
+ )
24
+ from .exceptions import (
25
+ ChunkedEncodingError,
26
+ ContentDecodingError,
27
+ InvalidSchema,
28
+ TooManyRedirects,
29
+ )
30
+ from .hooks import default_hooks, dispatch_hook
31
+
32
+ # formerly defined here, reexposed here for backward compatibility
33
+ from .models import ( # noqa: F401
34
+ DEFAULT_REDIRECT_LIMIT,
35
+ REDIRECT_STATI,
36
+ PreparedRequest,
37
+ Request,
38
+ )
39
+ from .status_codes import codes
40
+ from .structures import CaseInsensitiveDict
41
+ from .utils import ( # noqa: F401
42
+ DEFAULT_PORTS,
43
+ default_headers,
44
+ get_auth_from_url,
45
+ get_environ_proxies,
46
+ get_netrc_auth,
47
+ requote_uri,
48
+ resolve_proxies,
49
+ rewind_body,
50
+ should_bypass_proxies,
51
+ to_key_val_list,
52
+ )
53
+
54
+ # Preferred clock, based on which one is more accurate on a given system.
55
+ if sys.platform == "win32":
56
+ preferred_clock = time.perf_counter
57
+ else:
58
+ preferred_clock = time.time
59
+
60
+
61
+ def merge_setting(request_setting, session_setting, dict_class=OrderedDict):
62
+ """Determines appropriate setting for a given request, taking into account
63
+ the explicit setting on that request, and the setting in the session. If a
64
+ setting is a dictionary, they will be merged together using `dict_class`
65
+ """
66
+
67
+ if session_setting is None:
68
+ return request_setting
69
+
70
+ if request_setting is None:
71
+ return session_setting
72
+
73
+ # Bypass if not a dictionary (e.g. verify)
74
+ if not (
75
+ isinstance(session_setting, Mapping) and isinstance(request_setting, Mapping)
76
+ ):
77
+ return request_setting
78
+
79
+ merged_setting = dict_class(to_key_val_list(session_setting))
80
+ merged_setting.update(to_key_val_list(request_setting))
81
+
82
+ # Remove keys that are set to None. Extract keys first to avoid altering
83
+ # the dictionary during iteration.
84
+ none_keys = [k for (k, v) in merged_setting.items() if v is None]
85
+ for key in none_keys:
86
+ del merged_setting[key]
87
+
88
+ return merged_setting
89
+
90
+
91
+ def merge_hooks(request_hooks, session_hooks, dict_class=OrderedDict):
92
+ """Properly merges both requests and session hooks.
93
+
94
+ This is necessary because when request_hooks == {'response': []}, the
95
+ merge breaks Session hooks entirely.
96
+ """
97
+ if session_hooks is None or session_hooks.get("response") == []:
98
+ return request_hooks
99
+
100
+ if request_hooks is None or request_hooks.get("response") == []:
101
+ return session_hooks
102
+
103
+ return merge_setting(request_hooks, session_hooks, dict_class)
104
+
105
+
106
+ class SessionRedirectMixin:
107
+ def get_redirect_target(self, resp):
108
+ """Receives a Response. Returns a redirect URI or ``None``"""
109
+ # Due to the nature of how requests processes redirects this method will
110
+ # be called at least once upon the original response and at least twice
111
+ # on each subsequent redirect response (if any).
112
+ # If a custom mixin is used to handle this logic, it may be advantageous
113
+ # to cache the redirect location onto the response object as a private
114
+ # attribute.
115
+ if resp.is_redirect:
116
+ location = resp.headers["location"]
117
+ # Currently the underlying http module on py3 decode headers
118
+ # in latin1, but empirical evidence suggests that latin1 is very
119
+ # rarely used with non-ASCII characters in HTTP headers.
120
+ # It is more likely to get UTF8 header rather than latin1.
121
+ # This causes incorrect handling of UTF8 encoded location headers.
122
+ # To solve this, we re-encode the location in latin1.
123
+ location = location.encode("latin1")
124
+ return to_native_string(location, "utf8")
125
+ return None
126
+
127
+ def should_strip_auth(self, old_url, new_url):
128
+ """Decide whether Authorization header should be removed when redirecting"""
129
+ old_parsed = urlparse(old_url)
130
+ new_parsed = urlparse(new_url)
131
+ if old_parsed.hostname != new_parsed.hostname:
132
+ return True
133
+ # Special case: allow http -> https redirect when using the standard
134
+ # ports. This isn't specified by RFC 7235, but is kept to avoid
135
+ # breaking backwards compatibility with older versions of requests
136
+ # that allowed any redirects on the same host.
137
+ if (
138
+ old_parsed.scheme == "http"
139
+ and old_parsed.port in (80, None)
140
+ and new_parsed.scheme == "https"
141
+ and new_parsed.port in (443, None)
142
+ ):
143
+ return False
144
+
145
+ # Handle default port usage corresponding to scheme.
146
+ changed_port = old_parsed.port != new_parsed.port
147
+ changed_scheme = old_parsed.scheme != new_parsed.scheme
148
+ default_port = (DEFAULT_PORTS.get(old_parsed.scheme, None), None)
149
+ if (
150
+ not changed_scheme
151
+ and old_parsed.port in default_port
152
+ and new_parsed.port in default_port
153
+ ):
154
+ return False
155
+
156
+ # Standard case: root URI must match
157
+ return changed_port or changed_scheme
158
+
159
+ def resolve_redirects(
160
+ self,
161
+ resp,
162
+ req,
163
+ stream=False,
164
+ timeout=None,
165
+ verify=True,
166
+ cert=None,
167
+ proxies=None,
168
+ yield_requests=False,
169
+ **adapter_kwargs,
170
+ ):
171
+ """Receives a Response. Returns a generator of Responses or Requests."""
172
+
173
+ hist = [] # keep track of history
174
+
175
+ url = self.get_redirect_target(resp)
176
+ previous_fragment = urlparse(req.url).fragment
177
+ while url:
178
+ prepared_request = req.copy()
179
+
180
+ # Update history and keep track of redirects.
181
+ # resp.history must ignore the original request in this loop
182
+ hist.append(resp)
183
+ resp.history = hist[1:]
184
+
185
+ try:
186
+ resp.content # Consume socket so it can be released
187
+ except (ChunkedEncodingError, ContentDecodingError, RuntimeError):
188
+ resp.raw.read(decode_content=False)
189
+
190
+ if len(resp.history) >= self.max_redirects:
191
+ raise TooManyRedirects(
192
+ f"Exceeded {self.max_redirects} redirects.", response=resp
193
+ )
194
+
195
+ # Release the connection back into the pool.
196
+ resp.close()
197
+
198
+ # Handle redirection without scheme (see: RFC 1808 Section 4)
199
+ if url.startswith("//"):
200
+ parsed_rurl = urlparse(resp.url)
201
+ url = ":".join([to_native_string(parsed_rurl.scheme), url])
202
+
203
+ # Normalize url case and attach previous fragment if needed (RFC 7231 7.1.2)
204
+ parsed = urlparse(url)
205
+ if parsed.fragment == "" and previous_fragment:
206
+ parsed = parsed._replace(fragment=previous_fragment)
207
+ elif parsed.fragment:
208
+ previous_fragment = parsed.fragment
209
+ url = parsed.geturl()
210
+
211
+ # Facilitate relative 'location' headers, as allowed by RFC 7231.
212
+ # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource')
213
+ # Compliant with RFC3986, we percent encode the url.
214
+ if not parsed.netloc:
215
+ url = urljoin(resp.url, requote_uri(url))
216
+ else:
217
+ url = requote_uri(url)
218
+
219
+ prepared_request.url = to_native_string(url)
220
+
221
+ self.rebuild_method(prepared_request, resp)
222
+
223
+ # https://github.com/psf/requests/issues/1084
224
+ if resp.status_code not in (
225
+ codes.temporary_redirect,
226
+ codes.permanent_redirect,
227
+ ):
228
+ # https://github.com/psf/requests/issues/3490
229
+ purged_headers = ("Content-Length", "Content-Type", "Transfer-Encoding")
230
+ for header in purged_headers:
231
+ prepared_request.headers.pop(header, None)
232
+ prepared_request.body = None
233
+
234
+ headers = prepared_request.headers
235
+ headers.pop("Cookie", None)
236
+
237
+ # Extract any cookies sent on the response to the cookiejar
238
+ # in the new request. Because we've mutated our copied prepared
239
+ # request, use the old one that we haven't yet touched.
240
+ extract_cookies_to_jar(prepared_request._cookies, req, resp.raw)
241
+ merge_cookies(prepared_request._cookies, self.cookies)
242
+ prepared_request.prepare_cookies(prepared_request._cookies)
243
+
244
+ # Rebuild auth and proxy information.
245
+ proxies = self.rebuild_proxies(prepared_request, proxies)
246
+ self.rebuild_auth(prepared_request, resp)
247
+
248
+ # A failed tell() sets `_body_position` to `object()`. This non-None
249
+ # value ensures `rewindable` will be True, allowing us to raise an
250
+ # UnrewindableBodyError, instead of hanging the connection.
251
+ rewindable = prepared_request._body_position is not None and (
252
+ "Content-Length" in headers or "Transfer-Encoding" in headers
253
+ )
254
+
255
+ # Attempt to rewind consumed file-like object.
256
+ if rewindable:
257
+ rewind_body(prepared_request)
258
+
259
+ # Override the original request.
260
+ req = prepared_request
261
+
262
+ if yield_requests:
263
+ yield req
264
+ else:
265
+ resp = self.send(
266
+ req,
267
+ stream=stream,
268
+ timeout=timeout,
269
+ verify=verify,
270
+ cert=cert,
271
+ proxies=proxies,
272
+ allow_redirects=False,
273
+ **adapter_kwargs,
274
+ )
275
+
276
+ extract_cookies_to_jar(self.cookies, prepared_request, resp.raw)
277
+
278
+ # extract redirect url, if any, for the next loop
279
+ url = self.get_redirect_target(resp)
280
+ yield resp
281
+
282
+ def rebuild_auth(self, prepared_request, response):
283
+ """When being redirected we may want to strip authentication from the
284
+ request to avoid leaking credentials. This method intelligently removes
285
+ and reapplies authentication where possible to avoid credential loss.
286
+ """
287
+ headers = prepared_request.headers
288
+ url = prepared_request.url
289
+
290
+ if "Authorization" in headers and self.should_strip_auth(
291
+ response.request.url, url
292
+ ):
293
+ # If we get redirected to a new host, we should strip out any
294
+ # authentication headers.
295
+ del headers["Authorization"]
296
+
297
+ # .netrc might have more auth for us on our new host.
298
+ new_auth = get_netrc_auth(url) if self.trust_env else None
299
+ if new_auth is not None:
300
+ prepared_request.prepare_auth(new_auth)
301
+
302
+ def rebuild_proxies(self, prepared_request, proxies):
303
+ """This method re-evaluates the proxy configuration by considering the
304
+ environment variables. If we are redirected to a URL covered by
305
+ NO_PROXY, we strip the proxy configuration. Otherwise, we set missing
306
+ proxy keys for this URL (in case they were stripped by a previous
307
+ redirect).
308
+
309
+ This method also replaces the Proxy-Authorization header where
310
+ necessary.
311
+
312
+ :rtype: dict
313
+ """
314
+ headers = prepared_request.headers
315
+ scheme = urlparse(prepared_request.url).scheme
316
+ new_proxies = resolve_proxies(prepared_request, proxies, self.trust_env)
317
+
318
+ if "Proxy-Authorization" in headers:
319
+ del headers["Proxy-Authorization"]
320
+
321
+ try:
322
+ username, password = get_auth_from_url(new_proxies[scheme])
323
+ except KeyError:
324
+ username, password = None, None
325
+
326
+ # urllib3 handles proxy authorization for us in the standard adapter.
327
+ # Avoid appending this to TLS tunneled requests where it may be leaked.
328
+ if not scheme.startswith("https") and username and password:
329
+ headers["Proxy-Authorization"] = _basic_auth_str(username, password)
330
+
331
+ return new_proxies
332
+
333
+ def rebuild_method(self, prepared_request, response):
334
+ """When being redirected we may want to change the method of the request
335
+ based on certain specs or browser behavior.
336
+ """
337
+ method = prepared_request.method
338
+
339
+ # https://tools.ietf.org/html/rfc7231#section-6.4.4
340
+ if response.status_code == codes.see_other and method != "HEAD":
341
+ method = "GET"
342
+
343
+ # Do what the browsers do, despite standards...
344
+ # First, turn 302s into GETs.
345
+ if response.status_code == codes.found and method != "HEAD":
346
+ method = "GET"
347
+
348
+ # Second, if a POST is responded to with a 301, turn it into a GET.
349
+ # This bizarre behaviour is explained in Issue 1704.
350
+ if response.status_code == codes.moved and method == "POST":
351
+ method = "GET"
352
+
353
+ prepared_request.method = method
354
+
355
+
356
+ class Session(SessionRedirectMixin):
357
+ """A Requests session.
358
+
359
+ Provides cookie persistence, connection-pooling, and configuration.
360
+
361
+ Basic Usage::
362
+
363
+ >>> import requests
364
+ >>> s = requests.Session()
365
+ >>> s.get('https://httpbin.org/get')
366
+ <Response [200]>
367
+
368
+ Or as a context manager::
369
+
370
+ >>> with requests.Session() as s:
371
+ ... s.get('https://httpbin.org/get')
372
+ <Response [200]>
373
+ """
374
+
375
+ __attrs__ = [
376
+ "headers",
377
+ "cookies",
378
+ "auth",
379
+ "proxies",
380
+ "hooks",
381
+ "params",
382
+ "verify",
383
+ "cert",
384
+ "adapters",
385
+ "stream",
386
+ "trust_env",
387
+ "max_redirects",
388
+ ]
389
+
390
+ def __init__(self):
391
+ #: A case-insensitive dictionary of headers to be sent on each
392
+ #: :class:`Request <Request>` sent from this
393
+ #: :class:`Session <Session>`.
394
+ self.headers = default_headers()
395
+
396
+ #: Default Authentication tuple or object to attach to
397
+ #: :class:`Request <Request>`.
398
+ self.auth = None
399
+
400
+ #: Dictionary mapping protocol or protocol and host to the URL of the proxy
401
+ #: (e.g. {'http': 'foo.bar:3128', 'http://host.name': 'foo.bar:4012'}) to
402
+ #: be used on each :class:`Request <Request>`.
403
+ self.proxies = {}
404
+
405
+ #: Event-handling hooks.
406
+ self.hooks = default_hooks()
407
+
408
+ #: Dictionary of querystring data to attach to each
409
+ #: :class:`Request <Request>`. The dictionary values may be lists for
410
+ #: representing multivalued query parameters.
411
+ self.params = {}
412
+
413
+ #: Stream response content default.
414
+ self.stream = False
415
+
416
+ #: SSL Verification default.
417
+ #: Defaults to `True`, requiring requests to verify the TLS certificate at the
418
+ #: remote end.
419
+ #: If verify is set to `False`, requests will accept any TLS certificate
420
+ #: presented by the server, and will ignore hostname mismatches and/or
421
+ #: expired certificates, which will make your application vulnerable to
422
+ #: man-in-the-middle (MitM) attacks.
423
+ #: Only set this to `False` for testing.
424
+ self.verify = True
425
+
426
+ #: SSL client certificate default, if String, path to ssl client
427
+ #: cert file (.pem). If Tuple, ('cert', 'key') pair.
428
+ self.cert = None
429
+
430
+ #: Maximum number of redirects allowed. If the request exceeds this
431
+ #: limit, a :class:`TooManyRedirects` exception is raised.
432
+ #: This defaults to requests.models.DEFAULT_REDIRECT_LIMIT, which is
433
+ #: 30.
434
+ self.max_redirects = DEFAULT_REDIRECT_LIMIT
435
+
436
+ #: Trust environment settings for proxy configuration, default
437
+ #: authentication and similar.
438
+ self.trust_env = True
439
+
440
+ #: A CookieJar containing all currently outstanding cookies set on this
441
+ #: session. By default it is a
442
+ #: :class:`RequestsCookieJar <requests.cookies.RequestsCookieJar>`, but
443
+ #: may be any other ``cookielib.CookieJar`` compatible object.
444
+ self.cookies = cookiejar_from_dict({})
445
+
446
+ # Default connection adapters.
447
+ self.adapters = OrderedDict()
448
+ self.mount("https://", HTTPAdapter())
449
+ self.mount("http://", HTTPAdapter())
450
+
451
+ def __enter__(self):
452
+ return self
453
+
454
+ def __exit__(self, *args):
455
+ self.close()
456
+
457
+ def prepare_request(self, request):
458
+ """Constructs a :class:`PreparedRequest <PreparedRequest>` for
459
+ transmission and returns it. The :class:`PreparedRequest` has settings
460
+ merged from the :class:`Request <Request>` instance and those of the
461
+ :class:`Session`.
462
+
463
+ :param request: :class:`Request` instance to prepare with this
464
+ session's settings.
465
+ :rtype: requests.PreparedRequest
466
+ """
467
+ cookies = request.cookies or {}
468
+
469
+ # Bootstrap CookieJar.
470
+ if not isinstance(cookies, cookielib.CookieJar):
471
+ cookies = cookiejar_from_dict(cookies)
472
+
473
+ # Merge with session cookies
474
+ merged_cookies = merge_cookies(
475
+ merge_cookies(RequestsCookieJar(), self.cookies), cookies
476
+ )
477
+
478
+ # Set environment's basic authentication if not explicitly set.
479
+ auth = request.auth
480
+ if self.trust_env and not auth and not self.auth:
481
+ auth = get_netrc_auth(request.url)
482
+
483
+ p = PreparedRequest()
484
+ p.prepare(
485
+ method=request.method.upper(),
486
+ url=request.url,
487
+ files=request.files,
488
+ data=request.data,
489
+ json=request.json,
490
+ headers=merge_setting(
491
+ request.headers, self.headers, dict_class=CaseInsensitiveDict
492
+ ),
493
+ params=merge_setting(request.params, self.params),
494
+ auth=merge_setting(auth, self.auth),
495
+ cookies=merged_cookies,
496
+ hooks=merge_hooks(request.hooks, self.hooks),
497
+ )
498
+ return p
499
+
500
+ def request(
501
+ self,
502
+ method,
503
+ url,
504
+ params=None,
505
+ data=None,
506
+ headers=None,
507
+ cookies=None,
508
+ files=None,
509
+ auth=None,
510
+ timeout=None,
511
+ allow_redirects=True,
512
+ proxies=None,
513
+ hooks=None,
514
+ stream=None,
515
+ verify=None,
516
+ cert=None,
517
+ json=None,
518
+ ):
519
+ """Constructs a :class:`Request <Request>`, prepares it and sends it.
520
+ Returns :class:`Response <Response>` object.
521
+
522
+ :param method: method for the new :class:`Request` object.
523
+ :param url: URL for the new :class:`Request` object.
524
+ :param params: (optional) Dictionary or bytes to be sent in the query
525
+ string for the :class:`Request`.
526
+ :param data: (optional) Dictionary, list of tuples, bytes, or file-like
527
+ object to send in the body of the :class:`Request`.
528
+ :param json: (optional) json to send in the body of the
529
+ :class:`Request`.
530
+ :param headers: (optional) Dictionary of HTTP Headers to send with the
531
+ :class:`Request`.
532
+ :param cookies: (optional) Dict or CookieJar object to send with the
533
+ :class:`Request`.
534
+ :param files: (optional) Dictionary of ``'filename': file-like-objects``
535
+ for multipart encoding upload.
536
+ :param auth: (optional) Auth tuple or callable to enable
537
+ Basic/Digest/Custom HTTP Auth.
538
+ :param timeout: (optional) How long to wait for the server to send
539
+ data before giving up, as a float, or a :ref:`(connect timeout,
540
+ read timeout) <timeouts>` tuple.
541
+ :type timeout: float or tuple
542
+ :param allow_redirects: (optional) Set to True by default.
543
+ :type allow_redirects: bool
544
+ :param proxies: (optional) Dictionary mapping protocol or protocol and
545
+ hostname to the URL of the proxy.
546
+ :param hooks: (optional) Dictionary mapping hook name to one event or
547
+ list of events, event must be callable.
548
+ :param stream: (optional) whether to immediately download the response
549
+ content. Defaults to ``False``.
550
+ :param verify: (optional) Either a boolean, in which case it controls whether we verify
551
+ the server's TLS certificate, or a string, in which case it must be a path
552
+ to a CA bundle to use. Defaults to ``True``. When set to
553
+ ``False``, requests will accept any TLS certificate presented by
554
+ the server, and will ignore hostname mismatches and/or expired
555
+ certificates, which will make your application vulnerable to
556
+ man-in-the-middle (MitM) attacks. Setting verify to ``False``
557
+ may be useful during local development or testing.
558
+ :param cert: (optional) if String, path to ssl client cert file (.pem).
559
+ If Tuple, ('cert', 'key') pair.
560
+ :rtype: requests.Response
561
+ """
562
+ # Create the Request.
563
+ req = Request(
564
+ method=method.upper(),
565
+ url=url,
566
+ headers=headers,
567
+ files=files,
568
+ data=data or {},
569
+ json=json,
570
+ params=params or {},
571
+ auth=auth,
572
+ cookies=cookies,
573
+ hooks=hooks,
574
+ )
575
+ prep = self.prepare_request(req)
576
+
577
+ proxies = proxies or {}
578
+
579
+ settings = self.merge_environment_settings(
580
+ prep.url, proxies, stream, verify, cert
581
+ )
582
+
583
+ # Send the request.
584
+ send_kwargs = {
585
+ "timeout": timeout,
586
+ "allow_redirects": allow_redirects,
587
+ }
588
+ send_kwargs.update(settings)
589
+ resp = self.send(prep, **send_kwargs)
590
+
591
+ return resp
592
+
593
+ def get(self, url, **kwargs):
594
+ r"""Sends a GET request. Returns :class:`Response` object.
595
+
596
+ :param url: URL for the new :class:`Request` object.
597
+ :param \*\*kwargs: Optional arguments that ``request`` takes.
598
+ :rtype: requests.Response
599
+ """
600
+
601
+ kwargs.setdefault("allow_redirects", True)
602
+ return self.request("GET", url, **kwargs)
603
+
604
+ def options(self, url, **kwargs):
605
+ r"""Sends a OPTIONS request. Returns :class:`Response` object.
606
+
607
+ :param url: URL for the new :class:`Request` object.
608
+ :param \*\*kwargs: Optional arguments that ``request`` takes.
609
+ :rtype: requests.Response
610
+ """
611
+
612
+ kwargs.setdefault("allow_redirects", True)
613
+ return self.request("OPTIONS", url, **kwargs)
614
+
615
+ def head(self, url, **kwargs):
616
+ r"""Sends a HEAD request. Returns :class:`Response` object.
617
+
618
+ :param url: URL for the new :class:`Request` object.
619
+ :param \*\*kwargs: Optional arguments that ``request`` takes.
620
+ :rtype: requests.Response
621
+ """
622
+
623
+ kwargs.setdefault("allow_redirects", False)
624
+ return self.request("HEAD", url, **kwargs)
625
+
626
+ def post(self, url, data=None, json=None, **kwargs):
627
+ r"""Sends a POST request. Returns :class:`Response` object.
628
+
629
+ :param url: URL for the new :class:`Request` object.
630
+ :param data: (optional) Dictionary, list of tuples, bytes, or file-like
631
+ object to send in the body of the :class:`Request`.
632
+ :param json: (optional) json to send in the body of the :class:`Request`.
633
+ :param \*\*kwargs: Optional arguments that ``request`` takes.
634
+ :rtype: requests.Response
635
+ """
636
+
637
+ return self.request("POST", url, data=data, json=json, **kwargs)
638
+
639
+ def put(self, url, data=None, **kwargs):
640
+ r"""Sends a PUT request. Returns :class:`Response` object.
641
+
642
+ :param url: URL for the new :class:`Request` object.
643
+ :param data: (optional) Dictionary, list of tuples, bytes, or file-like
644
+ object to send in the body of the :class:`Request`.
645
+ :param \*\*kwargs: Optional arguments that ``request`` takes.
646
+ :rtype: requests.Response
647
+ """
648
+
649
+ return self.request("PUT", url, data=data, **kwargs)
650
+
651
+ def patch(self, url, data=None, **kwargs):
652
+ r"""Sends a PATCH request. Returns :class:`Response` object.
653
+
654
+ :param url: URL for the new :class:`Request` object.
655
+ :param data: (optional) Dictionary, list of tuples, bytes, or file-like
656
+ object to send in the body of the :class:`Request`.
657
+ :param \*\*kwargs: Optional arguments that ``request`` takes.
658
+ :rtype: requests.Response
659
+ """
660
+
661
+ return self.request("PATCH", url, data=data, **kwargs)
662
+
663
+ def delete(self, url, **kwargs):
664
+ r"""Sends a DELETE request. Returns :class:`Response` object.
665
+
666
+ :param url: URL for the new :class:`Request` object.
667
+ :param \*\*kwargs: Optional arguments that ``request`` takes.
668
+ :rtype: requests.Response
669
+ """
670
+
671
+ return self.request("DELETE", url, **kwargs)
672
+
673
+ def send(self, request, **kwargs):
674
+ """Send a given PreparedRequest.
675
+
676
+ :rtype: requests.Response
677
+ """
678
+ # Set defaults that the hooks can utilize to ensure they always have
679
+ # the correct parameters to reproduce the previous request.
680
+ kwargs.setdefault("stream", self.stream)
681
+ kwargs.setdefault("verify", self.verify)
682
+ kwargs.setdefault("cert", self.cert)
683
+ if "proxies" not in kwargs:
684
+ kwargs["proxies"] = resolve_proxies(request, self.proxies, self.trust_env)
685
+
686
+ # It's possible that users might accidentally send a Request object.
687
+ # Guard against that specific failure case.
688
+ if isinstance(request, Request):
689
+ raise ValueError("You can only send PreparedRequests.")
690
+
691
+ # Set up variables needed for resolve_redirects and dispatching of hooks
692
+ allow_redirects = kwargs.pop("allow_redirects", True)
693
+ stream = kwargs.get("stream")
694
+ hooks = request.hooks
695
+
696
+ # Get the appropriate adapter to use
697
+ adapter = self.get_adapter(url=request.url)
698
+
699
+ # Start time (approximately) of the request
700
+ start = preferred_clock()
701
+
702
+ # Send the request
703
+ r = adapter.send(request, **kwargs)
704
+
705
+ # Total elapsed time of the request (approximately)
706
+ elapsed = preferred_clock() - start
707
+ r.elapsed = timedelta(seconds=elapsed)
708
+
709
+ # Response manipulation hooks
710
+ r = dispatch_hook("response", hooks, r, **kwargs)
711
+
712
+ # Persist cookies
713
+ if r.history:
714
+ # If the hooks create history then we want those cookies too
715
+ for resp in r.history:
716
+ extract_cookies_to_jar(self.cookies, resp.request, resp.raw)
717
+
718
+ extract_cookies_to_jar(self.cookies, request, r.raw)
719
+
720
+ # Resolve redirects if allowed.
721
+ if allow_redirects:
722
+ # Redirect resolving generator.
723
+ gen = self.resolve_redirects(r, request, **kwargs)
724
+ history = [resp for resp in gen]
725
+ else:
726
+ history = []
727
+
728
+ # Shuffle things around if there's history.
729
+ if history:
730
+ # Insert the first (original) request at the start
731
+ history.insert(0, r)
732
+ # Get the last request made
733
+ r = history.pop()
734
+ r.history = history
735
+
736
+ # If redirects aren't being followed, store the response on the Request for Response.next().
737
+ if not allow_redirects:
738
+ try:
739
+ r._next = next(
740
+ self.resolve_redirects(r, request, yield_requests=True, **kwargs)
741
+ )
742
+ except StopIteration:
743
+ pass
744
+
745
+ if not stream:
746
+ r.content
747
+
748
+ return r
749
+
750
+ def merge_environment_settings(self, url, proxies, stream, verify, cert):
751
+ """
752
+ Check the environment and merge it with some settings.
753
+
754
+ :rtype: dict
755
+ """
756
+ # Gather clues from the surrounding environment.
757
+ if self.trust_env:
758
+ # Set environment's proxies.
759
+ no_proxy = proxies.get("no_proxy") if proxies is not None else None
760
+ env_proxies = get_environ_proxies(url, no_proxy=no_proxy)
761
+ for k, v in env_proxies.items():
762
+ proxies.setdefault(k, v)
763
+
764
+ # Look for requests environment configuration
765
+ # and be compatible with cURL.
766
+ if verify is True or verify is None:
767
+ verify = (
768
+ os.environ.get("REQUESTS_CA_BUNDLE")
769
+ or os.environ.get("CURL_CA_BUNDLE")
770
+ or verify
771
+ )
772
+
773
+ # Merge all the kwargs.
774
+ proxies = merge_setting(proxies, self.proxies)
775
+ stream = merge_setting(stream, self.stream)
776
+ verify = merge_setting(verify, self.verify)
777
+ cert = merge_setting(cert, self.cert)
778
+
779
+ return {"proxies": proxies, "stream": stream, "verify": verify, "cert": cert}
780
+
781
+ def get_adapter(self, url):
782
+ """
783
+ Returns the appropriate connection adapter for the given URL.
784
+
785
+ :rtype: requests.adapters.BaseAdapter
786
+ """
787
+ for prefix, adapter in self.adapters.items():
788
+ if url.lower().startswith(prefix.lower()):
789
+ return adapter
790
+
791
+ # Nothing matches :-/
792
+ raise InvalidSchema(f"No connection adapters were found for {url!r}")
793
+
794
+ def close(self):
795
+ """Closes all adapters and as such the session"""
796
+ for v in self.adapters.values():
797
+ v.close()
798
+
799
+ def mount(self, prefix, adapter):
800
+ """Registers a connection adapter to a prefix.
801
+
802
+ Adapters are sorted in descending order by prefix length.
803
+ """
804
+ self.adapters[prefix] = adapter
805
+ keys_to_move = [k for k in self.adapters if len(k) < len(prefix)]
806
+
807
+ for key in keys_to_move:
808
+ self.adapters[key] = self.adapters.pop(key)
809
+
810
+ def __getstate__(self):
811
+ state = {attr: getattr(self, attr, None) for attr in self.__attrs__}
812
+ return state
813
+
814
+ def __setstate__(self, state):
815
+ for attr, value in state.items():
816
+ setattr(self, attr, value)
817
+
818
+
819
+ def session():
820
+ """
821
+ Returns a :class:`Session` for context-management.
822
+
823
+ .. deprecated:: 1.0.0
824
+
825
+ This method has been deprecated since version 1.0.0 and is only kept for
826
+ backwards compatibility. New code should use :class:`~requests.sessions.Session`
827
+ to create a session. This may be removed at a future date.
828
+
829
+ :rtype: Session
830
+ """
831
+ return Session()
vllm/lib/python3.10/site-packages/requests/structures.py ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ requests.structures
3
+ ~~~~~~~~~~~~~~~~~~~
4
+
5
+ Data structures that power Requests.
6
+ """
7
+
8
+ from collections import OrderedDict
9
+
10
+ from .compat import Mapping, MutableMapping
11
+
12
+
13
+ class CaseInsensitiveDict(MutableMapping):
14
+ """A case-insensitive ``dict``-like object.
15
+
16
+ Implements all methods and operations of
17
+ ``MutableMapping`` as well as dict's ``copy``. Also
18
+ provides ``lower_items``.
19
+
20
+ All keys are expected to be strings. The structure remembers the
21
+ case of the last key to be set, and ``iter(instance)``,
22
+ ``keys()``, ``items()``, ``iterkeys()``, and ``iteritems()``
23
+ will contain case-sensitive keys. However, querying and contains
24
+ testing is case insensitive::
25
+
26
+ cid = CaseInsensitiveDict()
27
+ cid['Accept'] = 'application/json'
28
+ cid['aCCEPT'] == 'application/json' # True
29
+ list(cid) == ['Accept'] # True
30
+
31
+ For example, ``headers['content-encoding']`` will return the
32
+ value of a ``'Content-Encoding'`` response header, regardless
33
+ of how the header name was originally stored.
34
+
35
+ If the constructor, ``.update``, or equality comparison
36
+ operations are given keys that have equal ``.lower()``s, the
37
+ behavior is undefined.
38
+ """
39
+
40
+ def __init__(self, data=None, **kwargs):
41
+ self._store = OrderedDict()
42
+ if data is None:
43
+ data = {}
44
+ self.update(data, **kwargs)
45
+
46
+ def __setitem__(self, key, value):
47
+ # Use the lowercased key for lookups, but store the actual
48
+ # key alongside the value.
49
+ self._store[key.lower()] = (key, value)
50
+
51
+ def __getitem__(self, key):
52
+ return self._store[key.lower()][1]
53
+
54
+ def __delitem__(self, key):
55
+ del self._store[key.lower()]
56
+
57
+ def __iter__(self):
58
+ return (casedkey for casedkey, mappedvalue in self._store.values())
59
+
60
+ def __len__(self):
61
+ return len(self._store)
62
+
63
+ def lower_items(self):
64
+ """Like iteritems(), but with all lowercase keys."""
65
+ return ((lowerkey, keyval[1]) for (lowerkey, keyval) in self._store.items())
66
+
67
+ def __eq__(self, other):
68
+ if isinstance(other, Mapping):
69
+ other = CaseInsensitiveDict(other)
70
+ else:
71
+ return NotImplemented
72
+ # Compare insensitively
73
+ return dict(self.lower_items()) == dict(other.lower_items())
74
+
75
+ # Copy is required
76
+ def copy(self):
77
+ return CaseInsensitiveDict(self._store.values())
78
+
79
+ def __repr__(self):
80
+ return str(dict(self.items()))
81
+
82
+
83
+ class LookupDict(dict):
84
+ """Dictionary lookup object."""
85
+
86
+ def __init__(self, name=None):
87
+ self.name = name
88
+ super().__init__()
89
+
90
+ def __repr__(self):
91
+ return f"<lookup '{self.name}'>"
92
+
93
+ def __getitem__(self, key):
94
+ # We allow fall-through here, so values default to None
95
+
96
+ return self.__dict__.get(key, None)
97
+
98
+ def get(self, key, default=None):
99
+ return self.__dict__.get(key, default)
vllm/lib/python3.10/site-packages/requests/utils.py ADDED
@@ -0,0 +1,1096 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ requests.utils
3
+ ~~~~~~~~~~~~~~
4
+
5
+ This module provides utility functions that are used within Requests
6
+ that are also useful for external consumption.
7
+ """
8
+
9
+ import codecs
10
+ import contextlib
11
+ import io
12
+ import os
13
+ import re
14
+ import socket
15
+ import struct
16
+ import sys
17
+ import tempfile
18
+ import warnings
19
+ import zipfile
20
+ from collections import OrderedDict
21
+
22
+ from urllib3.util import make_headers, parse_url
23
+
24
+ from . import certs
25
+ from .__version__ import __version__
26
+
27
+ # to_native_string is unused here, but imported here for backwards compatibility
28
+ from ._internal_utils import ( # noqa: F401
29
+ _HEADER_VALIDATORS_BYTE,
30
+ _HEADER_VALIDATORS_STR,
31
+ HEADER_VALIDATORS,
32
+ to_native_string,
33
+ )
34
+ from .compat import (
35
+ Mapping,
36
+ basestring,
37
+ bytes,
38
+ getproxies,
39
+ getproxies_environment,
40
+ integer_types,
41
+ )
42
+ from .compat import parse_http_list as _parse_list_header
43
+ from .compat import (
44
+ proxy_bypass,
45
+ proxy_bypass_environment,
46
+ quote,
47
+ str,
48
+ unquote,
49
+ urlparse,
50
+ urlunparse,
51
+ )
52
+ from .cookies import cookiejar_from_dict
53
+ from .exceptions import (
54
+ FileModeWarning,
55
+ InvalidHeader,
56
+ InvalidURL,
57
+ UnrewindableBodyError,
58
+ )
59
+ from .structures import CaseInsensitiveDict
60
+
61
+ NETRC_FILES = (".netrc", "_netrc")
62
+
63
+ DEFAULT_CA_BUNDLE_PATH = certs.where()
64
+
65
+ DEFAULT_PORTS = {"http": 80, "https": 443}
66
+
67
+ # Ensure that ', ' is used to preserve previous delimiter behavior.
68
+ DEFAULT_ACCEPT_ENCODING = ", ".join(
69
+ re.split(r",\s*", make_headers(accept_encoding=True)["accept-encoding"])
70
+ )
71
+
72
+
73
+ if sys.platform == "win32":
74
+ # provide a proxy_bypass version on Windows without DNS lookups
75
+
76
+ def proxy_bypass_registry(host):
77
+ try:
78
+ import winreg
79
+ except ImportError:
80
+ return False
81
+
82
+ try:
83
+ internetSettings = winreg.OpenKey(
84
+ winreg.HKEY_CURRENT_USER,
85
+ r"Software\Microsoft\Windows\CurrentVersion\Internet Settings",
86
+ )
87
+ # ProxyEnable could be REG_SZ or REG_DWORD, normalizing it
88
+ proxyEnable = int(winreg.QueryValueEx(internetSettings, "ProxyEnable")[0])
89
+ # ProxyOverride is almost always a string
90
+ proxyOverride = winreg.QueryValueEx(internetSettings, "ProxyOverride")[0]
91
+ except (OSError, ValueError):
92
+ return False
93
+ if not proxyEnable or not proxyOverride:
94
+ return False
95
+
96
+ # make a check value list from the registry entry: replace the
97
+ # '<local>' string by the localhost entry and the corresponding
98
+ # canonical entry.
99
+ proxyOverride = proxyOverride.split(";")
100
+ # filter out empty strings to avoid re.match return true in the following code.
101
+ proxyOverride = filter(None, proxyOverride)
102
+ # now check if we match one of the registry values.
103
+ for test in proxyOverride:
104
+ if test == "<local>":
105
+ if "." not in host:
106
+ return True
107
+ test = test.replace(".", r"\.") # mask dots
108
+ test = test.replace("*", r".*") # change glob sequence
109
+ test = test.replace("?", r".") # change glob char
110
+ if re.match(test, host, re.I):
111
+ return True
112
+ return False
113
+
114
+ def proxy_bypass(host): # noqa
115
+ """Return True, if the host should be bypassed.
116
+
117
+ Checks proxy settings gathered from the environment, if specified,
118
+ or the registry.
119
+ """
120
+ if getproxies_environment():
121
+ return proxy_bypass_environment(host)
122
+ else:
123
+ return proxy_bypass_registry(host)
124
+
125
+
126
+ def dict_to_sequence(d):
127
+ """Returns an internal sequence dictionary update."""
128
+
129
+ if hasattr(d, "items"):
130
+ d = d.items()
131
+
132
+ return d
133
+
134
+
135
+ def super_len(o):
136
+ total_length = None
137
+ current_position = 0
138
+
139
+ if isinstance(o, str):
140
+ o = o.encode("utf-8")
141
+
142
+ if hasattr(o, "__len__"):
143
+ total_length = len(o)
144
+
145
+ elif hasattr(o, "len"):
146
+ total_length = o.len
147
+
148
+ elif hasattr(o, "fileno"):
149
+ try:
150
+ fileno = o.fileno()
151
+ except (io.UnsupportedOperation, AttributeError):
152
+ # AttributeError is a surprising exception, seeing as how we've just checked
153
+ # that `hasattr(o, 'fileno')`. It happens for objects obtained via
154
+ # `Tarfile.extractfile()`, per issue 5229.
155
+ pass
156
+ else:
157
+ total_length = os.fstat(fileno).st_size
158
+
159
+ # Having used fstat to determine the file length, we need to
160
+ # confirm that this file was opened up in binary mode.
161
+ if "b" not in o.mode:
162
+ warnings.warn(
163
+ (
164
+ "Requests has determined the content-length for this "
165
+ "request using the binary size of the file: however, the "
166
+ "file has been opened in text mode (i.e. without the 'b' "
167
+ "flag in the mode). This may lead to an incorrect "
168
+ "content-length. In Requests 3.0, support will be removed "
169
+ "for files in text mode."
170
+ ),
171
+ FileModeWarning,
172
+ )
173
+
174
+ if hasattr(o, "tell"):
175
+ try:
176
+ current_position = o.tell()
177
+ except OSError:
178
+ # This can happen in some weird situations, such as when the file
179
+ # is actually a special file descriptor like stdin. In this
180
+ # instance, we don't know what the length is, so set it to zero and
181
+ # let requests chunk it instead.
182
+ if total_length is not None:
183
+ current_position = total_length
184
+ else:
185
+ if hasattr(o, "seek") and total_length is None:
186
+ # StringIO and BytesIO have seek but no usable fileno
187
+ try:
188
+ # seek to end of file
189
+ o.seek(0, 2)
190
+ total_length = o.tell()
191
+
192
+ # seek back to current position to support
193
+ # partially read file-like objects
194
+ o.seek(current_position or 0)
195
+ except OSError:
196
+ total_length = 0
197
+
198
+ if total_length is None:
199
+ total_length = 0
200
+
201
+ return max(0, total_length - current_position)
202
+
203
+
204
+ def get_netrc_auth(url, raise_errors=False):
205
+ """Returns the Requests tuple auth for a given url from netrc."""
206
+
207
+ netrc_file = os.environ.get("NETRC")
208
+ if netrc_file is not None:
209
+ netrc_locations = (netrc_file,)
210
+ else:
211
+ netrc_locations = (f"~/{f}" for f in NETRC_FILES)
212
+
213
+ try:
214
+ from netrc import NetrcParseError, netrc
215
+
216
+ netrc_path = None
217
+
218
+ for f in netrc_locations:
219
+ try:
220
+ loc = os.path.expanduser(f)
221
+ except KeyError:
222
+ # os.path.expanduser can fail when $HOME is undefined and
223
+ # getpwuid fails. See https://bugs.python.org/issue20164 &
224
+ # https://github.com/psf/requests/issues/1846
225
+ return
226
+
227
+ if os.path.exists(loc):
228
+ netrc_path = loc
229
+ break
230
+
231
+ # Abort early if there isn't one.
232
+ if netrc_path is None:
233
+ return
234
+
235
+ ri = urlparse(url)
236
+
237
+ # Strip port numbers from netloc. This weird `if...encode`` dance is
238
+ # used for Python 3.2, which doesn't support unicode literals.
239
+ splitstr = b":"
240
+ if isinstance(url, str):
241
+ splitstr = splitstr.decode("ascii")
242
+ host = ri.netloc.split(splitstr)[0]
243
+
244
+ try:
245
+ _netrc = netrc(netrc_path).authenticators(host)
246
+ if _netrc:
247
+ # Return with login / password
248
+ login_i = 0 if _netrc[0] else 1
249
+ return (_netrc[login_i], _netrc[2])
250
+ except (NetrcParseError, OSError):
251
+ # If there was a parsing error or a permissions issue reading the file,
252
+ # we'll just skip netrc auth unless explicitly asked to raise errors.
253
+ if raise_errors:
254
+ raise
255
+
256
+ # App Engine hackiness.
257
+ except (ImportError, AttributeError):
258
+ pass
259
+
260
+
261
+ def guess_filename(obj):
262
+ """Tries to guess the filename of the given object."""
263
+ name = getattr(obj, "name", None)
264
+ if name and isinstance(name, basestring) and name[0] != "<" and name[-1] != ">":
265
+ return os.path.basename(name)
266
+
267
+
268
+ def extract_zipped_paths(path):
269
+ """Replace nonexistent paths that look like they refer to a member of a zip
270
+ archive with the location of an extracted copy of the target, or else
271
+ just return the provided path unchanged.
272
+ """
273
+ if os.path.exists(path):
274
+ # this is already a valid path, no need to do anything further
275
+ return path
276
+
277
+ # find the first valid part of the provided path and treat that as a zip archive
278
+ # assume the rest of the path is the name of a member in the archive
279
+ archive, member = os.path.split(path)
280
+ while archive and not os.path.exists(archive):
281
+ archive, prefix = os.path.split(archive)
282
+ if not prefix:
283
+ # If we don't check for an empty prefix after the split (in other words, archive remains unchanged after the split),
284
+ # we _can_ end up in an infinite loop on a rare corner case affecting a small number of users
285
+ break
286
+ member = "/".join([prefix, member])
287
+
288
+ if not zipfile.is_zipfile(archive):
289
+ return path
290
+
291
+ zip_file = zipfile.ZipFile(archive)
292
+ if member not in zip_file.namelist():
293
+ return path
294
+
295
+ # we have a valid zip archive and a valid member of that archive
296
+ tmp = tempfile.gettempdir()
297
+ extracted_path = os.path.join(tmp, member.split("/")[-1])
298
+ if not os.path.exists(extracted_path):
299
+ # use read + write to avoid the creating nested folders, we only want the file, avoids mkdir racing condition
300
+ with atomic_open(extracted_path) as file_handler:
301
+ file_handler.write(zip_file.read(member))
302
+ return extracted_path
303
+
304
+
305
+ @contextlib.contextmanager
306
+ def atomic_open(filename):
307
+ """Write a file to the disk in an atomic fashion"""
308
+ tmp_descriptor, tmp_name = tempfile.mkstemp(dir=os.path.dirname(filename))
309
+ try:
310
+ with os.fdopen(tmp_descriptor, "wb") as tmp_handler:
311
+ yield tmp_handler
312
+ os.replace(tmp_name, filename)
313
+ except BaseException:
314
+ os.remove(tmp_name)
315
+ raise
316
+
317
+
318
+ def from_key_val_list(value):
319
+ """Take an object and test to see if it can be represented as a
320
+ dictionary. Unless it can not be represented as such, return an
321
+ OrderedDict, e.g.,
322
+
323
+ ::
324
+
325
+ >>> from_key_val_list([('key', 'val')])
326
+ OrderedDict([('key', 'val')])
327
+ >>> from_key_val_list('string')
328
+ Traceback (most recent call last):
329
+ ...
330
+ ValueError: cannot encode objects that are not 2-tuples
331
+ >>> from_key_val_list({'key': 'val'})
332
+ OrderedDict([('key', 'val')])
333
+
334
+ :rtype: OrderedDict
335
+ """
336
+ if value is None:
337
+ return None
338
+
339
+ if isinstance(value, (str, bytes, bool, int)):
340
+ raise ValueError("cannot encode objects that are not 2-tuples")
341
+
342
+ return OrderedDict(value)
343
+
344
+
345
+ def to_key_val_list(value):
346
+ """Take an object and test to see if it can be represented as a
347
+ dictionary. If it can be, return a list of tuples, e.g.,
348
+
349
+ ::
350
+
351
+ >>> to_key_val_list([('key', 'val')])
352
+ [('key', 'val')]
353
+ >>> to_key_val_list({'key': 'val'})
354
+ [('key', 'val')]
355
+ >>> to_key_val_list('string')
356
+ Traceback (most recent call last):
357
+ ...
358
+ ValueError: cannot encode objects that are not 2-tuples
359
+
360
+ :rtype: list
361
+ """
362
+ if value is None:
363
+ return None
364
+
365
+ if isinstance(value, (str, bytes, bool, int)):
366
+ raise ValueError("cannot encode objects that are not 2-tuples")
367
+
368
+ if isinstance(value, Mapping):
369
+ value = value.items()
370
+
371
+ return list(value)
372
+
373
+
374
+ # From mitsuhiko/werkzeug (used with permission).
375
+ def parse_list_header(value):
376
+ """Parse lists as described by RFC 2068 Section 2.
377
+
378
+ In particular, parse comma-separated lists where the elements of
379
+ the list may include quoted-strings. A quoted-string could
380
+ contain a comma. A non-quoted string could have quotes in the
381
+ middle. Quotes are removed automatically after parsing.
382
+
383
+ It basically works like :func:`parse_set_header` just that items
384
+ may appear multiple times and case sensitivity is preserved.
385
+
386
+ The return value is a standard :class:`list`:
387
+
388
+ >>> parse_list_header('token, "quoted value"')
389
+ ['token', 'quoted value']
390
+
391
+ To create a header from the :class:`list` again, use the
392
+ :func:`dump_header` function.
393
+
394
+ :param value: a string with a list header.
395
+ :return: :class:`list`
396
+ :rtype: list
397
+ """
398
+ result = []
399
+ for item in _parse_list_header(value):
400
+ if item[:1] == item[-1:] == '"':
401
+ item = unquote_header_value(item[1:-1])
402
+ result.append(item)
403
+ return result
404
+
405
+
406
+ # From mitsuhiko/werkzeug (used with permission).
407
+ def parse_dict_header(value):
408
+ """Parse lists of key, value pairs as described by RFC 2068 Section 2 and
409
+ convert them into a python dict:
410
+
411
+ >>> d = parse_dict_header('foo="is a fish", bar="as well"')
412
+ >>> type(d) is dict
413
+ True
414
+ >>> sorted(d.items())
415
+ [('bar', 'as well'), ('foo', 'is a fish')]
416
+
417
+ If there is no value for a key it will be `None`:
418
+
419
+ >>> parse_dict_header('key_without_value')
420
+ {'key_without_value': None}
421
+
422
+ To create a header from the :class:`dict` again, use the
423
+ :func:`dump_header` function.
424
+
425
+ :param value: a string with a dict header.
426
+ :return: :class:`dict`
427
+ :rtype: dict
428
+ """
429
+ result = {}
430
+ for item in _parse_list_header(value):
431
+ if "=" not in item:
432
+ result[item] = None
433
+ continue
434
+ name, value = item.split("=", 1)
435
+ if value[:1] == value[-1:] == '"':
436
+ value = unquote_header_value(value[1:-1])
437
+ result[name] = value
438
+ return result
439
+
440
+
441
+ # From mitsuhiko/werkzeug (used with permission).
442
+ def unquote_header_value(value, is_filename=False):
443
+ r"""Unquotes a header value. (Reversal of :func:`quote_header_value`).
444
+ This does not use the real unquoting but what browsers are actually
445
+ using for quoting.
446
+
447
+ :param value: the header value to unquote.
448
+ :rtype: str
449
+ """
450
+ if value and value[0] == value[-1] == '"':
451
+ # this is not the real unquoting, but fixing this so that the
452
+ # RFC is met will result in bugs with internet explorer and
453
+ # probably some other browsers as well. IE for example is
454
+ # uploading files with "C:\foo\bar.txt" as filename
455
+ value = value[1:-1]
456
+
457
+ # if this is a filename and the starting characters look like
458
+ # a UNC path, then just return the value without quotes. Using the
459
+ # replace sequence below on a UNC path has the effect of turning
460
+ # the leading double slash into a single slash and then
461
+ # _fix_ie_filename() doesn't work correctly. See #458.
462
+ if not is_filename or value[:2] != "\\\\":
463
+ return value.replace("\\\\", "\\").replace('\\"', '"')
464
+ return value
465
+
466
+
467
+ def dict_from_cookiejar(cj):
468
+ """Returns a key/value dictionary from a CookieJar.
469
+
470
+ :param cj: CookieJar object to extract cookies from.
471
+ :rtype: dict
472
+ """
473
+
474
+ cookie_dict = {cookie.name: cookie.value for cookie in cj}
475
+ return cookie_dict
476
+
477
+
478
+ def add_dict_to_cookiejar(cj, cookie_dict):
479
+ """Returns a CookieJar from a key/value dictionary.
480
+
481
+ :param cj: CookieJar to insert cookies into.
482
+ :param cookie_dict: Dict of key/values to insert into CookieJar.
483
+ :rtype: CookieJar
484
+ """
485
+
486
+ return cookiejar_from_dict(cookie_dict, cj)
487
+
488
+
489
+ def get_encodings_from_content(content):
490
+ """Returns encodings from given content string.
491
+
492
+ :param content: bytestring to extract encodings from.
493
+ """
494
+ warnings.warn(
495
+ (
496
+ "In requests 3.0, get_encodings_from_content will be removed. For "
497
+ "more information, please see the discussion on issue #2266. (This"
498
+ " warning should only appear once.)"
499
+ ),
500
+ DeprecationWarning,
501
+ )
502
+
503
+ charset_re = re.compile(r'<meta.*?charset=["\']*(.+?)["\'>]', flags=re.I)
504
+ pragma_re = re.compile(r'<meta.*?content=["\']*;?charset=(.+?)["\'>]', flags=re.I)
505
+ xml_re = re.compile(r'^<\?xml.*?encoding=["\']*(.+?)["\'>]')
506
+
507
+ return (
508
+ charset_re.findall(content)
509
+ + pragma_re.findall(content)
510
+ + xml_re.findall(content)
511
+ )
512
+
513
+
514
+ def _parse_content_type_header(header):
515
+ """Returns content type and parameters from given header
516
+
517
+ :param header: string
518
+ :return: tuple containing content type and dictionary of
519
+ parameters
520
+ """
521
+
522
+ tokens = header.split(";")
523
+ content_type, params = tokens[0].strip(), tokens[1:]
524
+ params_dict = {}
525
+ items_to_strip = "\"' "
526
+
527
+ for param in params:
528
+ param = param.strip()
529
+ if param:
530
+ key, value = param, True
531
+ index_of_equals = param.find("=")
532
+ if index_of_equals != -1:
533
+ key = param[:index_of_equals].strip(items_to_strip)
534
+ value = param[index_of_equals + 1 :].strip(items_to_strip)
535
+ params_dict[key.lower()] = value
536
+ return content_type, params_dict
537
+
538
+
539
+ def get_encoding_from_headers(headers):
540
+ """Returns encodings from given HTTP Header Dict.
541
+
542
+ :param headers: dictionary to extract encoding from.
543
+ :rtype: str
544
+ """
545
+
546
+ content_type = headers.get("content-type")
547
+
548
+ if not content_type:
549
+ return None
550
+
551
+ content_type, params = _parse_content_type_header(content_type)
552
+
553
+ if "charset" in params:
554
+ return params["charset"].strip("'\"")
555
+
556
+ if "text" in content_type:
557
+ return "ISO-8859-1"
558
+
559
+ if "application/json" in content_type:
560
+ # Assume UTF-8 based on RFC 4627: https://www.ietf.org/rfc/rfc4627.txt since the charset was unset
561
+ return "utf-8"
562
+
563
+
564
+ def stream_decode_response_unicode(iterator, r):
565
+ """Stream decodes an iterator."""
566
+
567
+ if r.encoding is None:
568
+ yield from iterator
569
+ return
570
+
571
+ decoder = codecs.getincrementaldecoder(r.encoding)(errors="replace")
572
+ for chunk in iterator:
573
+ rv = decoder.decode(chunk)
574
+ if rv:
575
+ yield rv
576
+ rv = decoder.decode(b"", final=True)
577
+ if rv:
578
+ yield rv
579
+
580
+
581
+ def iter_slices(string, slice_length):
582
+ """Iterate over slices of a string."""
583
+ pos = 0
584
+ if slice_length is None or slice_length <= 0:
585
+ slice_length = len(string)
586
+ while pos < len(string):
587
+ yield string[pos : pos + slice_length]
588
+ pos += slice_length
589
+
590
+
591
+ def get_unicode_from_response(r):
592
+ """Returns the requested content back in unicode.
593
+
594
+ :param r: Response object to get unicode content from.
595
+
596
+ Tried:
597
+
598
+ 1. charset from content-type
599
+ 2. fall back and replace all unicode characters
600
+
601
+ :rtype: str
602
+ """
603
+ warnings.warn(
604
+ (
605
+ "In requests 3.0, get_unicode_from_response will be removed. For "
606
+ "more information, please see the discussion on issue #2266. (This"
607
+ " warning should only appear once.)"
608
+ ),
609
+ DeprecationWarning,
610
+ )
611
+
612
+ tried_encodings = []
613
+
614
+ # Try charset from content-type
615
+ encoding = get_encoding_from_headers(r.headers)
616
+
617
+ if encoding:
618
+ try:
619
+ return str(r.content, encoding)
620
+ except UnicodeError:
621
+ tried_encodings.append(encoding)
622
+
623
+ # Fall back:
624
+ try:
625
+ return str(r.content, encoding, errors="replace")
626
+ except TypeError:
627
+ return r.content
628
+
629
+
630
+ # The unreserved URI characters (RFC 3986)
631
+ UNRESERVED_SET = frozenset(
632
+ "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" + "0123456789-._~"
633
+ )
634
+
635
+
636
+ def unquote_unreserved(uri):
637
+ """Un-escape any percent-escape sequences in a URI that are unreserved
638
+ characters. This leaves all reserved, illegal and non-ASCII bytes encoded.
639
+
640
+ :rtype: str
641
+ """
642
+ parts = uri.split("%")
643
+ for i in range(1, len(parts)):
644
+ h = parts[i][0:2]
645
+ if len(h) == 2 and h.isalnum():
646
+ try:
647
+ c = chr(int(h, 16))
648
+ except ValueError:
649
+ raise InvalidURL(f"Invalid percent-escape sequence: '{h}'")
650
+
651
+ if c in UNRESERVED_SET:
652
+ parts[i] = c + parts[i][2:]
653
+ else:
654
+ parts[i] = f"%{parts[i]}"
655
+ else:
656
+ parts[i] = f"%{parts[i]}"
657
+ return "".join(parts)
658
+
659
+
660
+ def requote_uri(uri):
661
+ """Re-quote the given URI.
662
+
663
+ This function passes the given URI through an unquote/quote cycle to
664
+ ensure that it is fully and consistently quoted.
665
+
666
+ :rtype: str
667
+ """
668
+ safe_with_percent = "!#$%&'()*+,/:;=?@[]~"
669
+ safe_without_percent = "!#$&'()*+,/:;=?@[]~"
670
+ try:
671
+ # Unquote only the unreserved characters
672
+ # Then quote only illegal characters (do not quote reserved,
673
+ # unreserved, or '%')
674
+ return quote(unquote_unreserved(uri), safe=safe_with_percent)
675
+ except InvalidURL:
676
+ # We couldn't unquote the given URI, so let's try quoting it, but
677
+ # there may be unquoted '%'s in the URI. We need to make sure they're
678
+ # properly quoted so they do not cause issues elsewhere.
679
+ return quote(uri, safe=safe_without_percent)
680
+
681
+
682
+ def address_in_network(ip, net):
683
+ """This function allows you to check if an IP belongs to a network subnet
684
+
685
+ Example: returns True if ip = 192.168.1.1 and net = 192.168.1.0/24
686
+ returns False if ip = 192.168.1.1 and net = 192.168.100.0/24
687
+
688
+ :rtype: bool
689
+ """
690
+ ipaddr = struct.unpack("=L", socket.inet_aton(ip))[0]
691
+ netaddr, bits = net.split("/")
692
+ netmask = struct.unpack("=L", socket.inet_aton(dotted_netmask(int(bits))))[0]
693
+ network = struct.unpack("=L", socket.inet_aton(netaddr))[0] & netmask
694
+ return (ipaddr & netmask) == (network & netmask)
695
+
696
+
697
+ def dotted_netmask(mask):
698
+ """Converts mask from /xx format to xxx.xxx.xxx.xxx
699
+
700
+ Example: if mask is 24 function returns 255.255.255.0
701
+
702
+ :rtype: str
703
+ """
704
+ bits = 0xFFFFFFFF ^ (1 << 32 - mask) - 1
705
+ return socket.inet_ntoa(struct.pack(">I", bits))
706
+
707
+
708
+ def is_ipv4_address(string_ip):
709
+ """
710
+ :rtype: bool
711
+ """
712
+ try:
713
+ socket.inet_aton(string_ip)
714
+ except OSError:
715
+ return False
716
+ return True
717
+
718
+
719
+ def is_valid_cidr(string_network):
720
+ """
721
+ Very simple check of the cidr format in no_proxy variable.
722
+
723
+ :rtype: bool
724
+ """
725
+ if string_network.count("/") == 1:
726
+ try:
727
+ mask = int(string_network.split("/")[1])
728
+ except ValueError:
729
+ return False
730
+
731
+ if mask < 1 or mask > 32:
732
+ return False
733
+
734
+ try:
735
+ socket.inet_aton(string_network.split("/")[0])
736
+ except OSError:
737
+ return False
738
+ else:
739
+ return False
740
+ return True
741
+
742
+
743
+ @contextlib.contextmanager
744
+ def set_environ(env_name, value):
745
+ """Set the environment variable 'env_name' to 'value'
746
+
747
+ Save previous value, yield, and then restore the previous value stored in
748
+ the environment variable 'env_name'.
749
+
750
+ If 'value' is None, do nothing"""
751
+ value_changed = value is not None
752
+ if value_changed:
753
+ old_value = os.environ.get(env_name)
754
+ os.environ[env_name] = value
755
+ try:
756
+ yield
757
+ finally:
758
+ if value_changed:
759
+ if old_value is None:
760
+ del os.environ[env_name]
761
+ else:
762
+ os.environ[env_name] = old_value
763
+
764
+
765
+ def should_bypass_proxies(url, no_proxy):
766
+ """
767
+ Returns whether we should bypass proxies or not.
768
+
769
+ :rtype: bool
770
+ """
771
+
772
+ # Prioritize lowercase environment variables over uppercase
773
+ # to keep a consistent behaviour with other http projects (curl, wget).
774
+ def get_proxy(key):
775
+ return os.environ.get(key) or os.environ.get(key.upper())
776
+
777
+ # First check whether no_proxy is defined. If it is, check that the URL
778
+ # we're getting isn't in the no_proxy list.
779
+ no_proxy_arg = no_proxy
780
+ if no_proxy is None:
781
+ no_proxy = get_proxy("no_proxy")
782
+ parsed = urlparse(url)
783
+
784
+ if parsed.hostname is None:
785
+ # URLs don't always have hostnames, e.g. file:/// urls.
786
+ return True
787
+
788
+ if no_proxy:
789
+ # We need to check whether we match here. We need to see if we match
790
+ # the end of the hostname, both with and without the port.
791
+ no_proxy = (host for host in no_proxy.replace(" ", "").split(",") if host)
792
+
793
+ if is_ipv4_address(parsed.hostname):
794
+ for proxy_ip in no_proxy:
795
+ if is_valid_cidr(proxy_ip):
796
+ if address_in_network(parsed.hostname, proxy_ip):
797
+ return True
798
+ elif parsed.hostname == proxy_ip:
799
+ # If no_proxy ip was defined in plain IP notation instead of cidr notation &
800
+ # matches the IP of the index
801
+ return True
802
+ else:
803
+ host_with_port = parsed.hostname
804
+ if parsed.port:
805
+ host_with_port += f":{parsed.port}"
806
+
807
+ for host in no_proxy:
808
+ if parsed.hostname.endswith(host) or host_with_port.endswith(host):
809
+ # The URL does match something in no_proxy, so we don't want
810
+ # to apply the proxies on this URL.
811
+ return True
812
+
813
+ with set_environ("no_proxy", no_proxy_arg):
814
+ # parsed.hostname can be `None` in cases such as a file URI.
815
+ try:
816
+ bypass = proxy_bypass(parsed.hostname)
817
+ except (TypeError, socket.gaierror):
818
+ bypass = False
819
+
820
+ if bypass:
821
+ return True
822
+
823
+ return False
824
+
825
+
826
+ def get_environ_proxies(url, no_proxy=None):
827
+ """
828
+ Return a dict of environment proxies.
829
+
830
+ :rtype: dict
831
+ """
832
+ if should_bypass_proxies(url, no_proxy=no_proxy):
833
+ return {}
834
+ else:
835
+ return getproxies()
836
+
837
+
838
+ def select_proxy(url, proxies):
839
+ """Select a proxy for the url, if applicable.
840
+
841
+ :param url: The url being for the request
842
+ :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs
843
+ """
844
+ proxies = proxies or {}
845
+ urlparts = urlparse(url)
846
+ if urlparts.hostname is None:
847
+ return proxies.get(urlparts.scheme, proxies.get("all"))
848
+
849
+ proxy_keys = [
850
+ urlparts.scheme + "://" + urlparts.hostname,
851
+ urlparts.scheme,
852
+ "all://" + urlparts.hostname,
853
+ "all",
854
+ ]
855
+ proxy = None
856
+ for proxy_key in proxy_keys:
857
+ if proxy_key in proxies:
858
+ proxy = proxies[proxy_key]
859
+ break
860
+
861
+ return proxy
862
+
863
+
864
+ def resolve_proxies(request, proxies, trust_env=True):
865
+ """This method takes proxy information from a request and configuration
866
+ input to resolve a mapping of target proxies. This will consider settings
867
+ such as NO_PROXY to strip proxy configurations.
868
+
869
+ :param request: Request or PreparedRequest
870
+ :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs
871
+ :param trust_env: Boolean declaring whether to trust environment configs
872
+
873
+ :rtype: dict
874
+ """
875
+ proxies = proxies if proxies is not None else {}
876
+ url = request.url
877
+ scheme = urlparse(url).scheme
878
+ no_proxy = proxies.get("no_proxy")
879
+ new_proxies = proxies.copy()
880
+
881
+ if trust_env and not should_bypass_proxies(url, no_proxy=no_proxy):
882
+ environ_proxies = get_environ_proxies(url, no_proxy=no_proxy)
883
+
884
+ proxy = environ_proxies.get(scheme, environ_proxies.get("all"))
885
+
886
+ if proxy:
887
+ new_proxies.setdefault(scheme, proxy)
888
+ return new_proxies
889
+
890
+
891
+ def default_user_agent(name="python-requests"):
892
+ """
893
+ Return a string representing the default user agent.
894
+
895
+ :rtype: str
896
+ """
897
+ return f"{name}/{__version__}"
898
+
899
+
900
+ def default_headers():
901
+ """
902
+ :rtype: requests.structures.CaseInsensitiveDict
903
+ """
904
+ return CaseInsensitiveDict(
905
+ {
906
+ "User-Agent": default_user_agent(),
907
+ "Accept-Encoding": DEFAULT_ACCEPT_ENCODING,
908
+ "Accept": "*/*",
909
+ "Connection": "keep-alive",
910
+ }
911
+ )
912
+
913
+
914
+ def parse_header_links(value):
915
+ """Return a list of parsed link headers proxies.
916
+
917
+ i.e. Link: <http:/.../front.jpeg>; rel=front; type="image/jpeg",<http://.../back.jpeg>; rel=back;type="image/jpeg"
918
+
919
+ :rtype: list
920
+ """
921
+
922
+ links = []
923
+
924
+ replace_chars = " '\""
925
+
926
+ value = value.strip(replace_chars)
927
+ if not value:
928
+ return links
929
+
930
+ for val in re.split(", *<", value):
931
+ try:
932
+ url, params = val.split(";", 1)
933
+ except ValueError:
934
+ url, params = val, ""
935
+
936
+ link = {"url": url.strip("<> '\"")}
937
+
938
+ for param in params.split(";"):
939
+ try:
940
+ key, value = param.split("=")
941
+ except ValueError:
942
+ break
943
+
944
+ link[key.strip(replace_chars)] = value.strip(replace_chars)
945
+
946
+ links.append(link)
947
+
948
+ return links
949
+
950
+
951
+ # Null bytes; no need to recreate these on each call to guess_json_utf
952
+ _null = "\x00".encode("ascii") # encoding to ASCII for Python 3
953
+ _null2 = _null * 2
954
+ _null3 = _null * 3
955
+
956
+
957
+ def guess_json_utf(data):
958
+ """
959
+ :rtype: str
960
+ """
961
+ # JSON always starts with two ASCII characters, so detection is as
962
+ # easy as counting the nulls and from their location and count
963
+ # determine the encoding. Also detect a BOM, if present.
964
+ sample = data[:4]
965
+ if sample in (codecs.BOM_UTF32_LE, codecs.BOM_UTF32_BE):
966
+ return "utf-32" # BOM included
967
+ if sample[:3] == codecs.BOM_UTF8:
968
+ return "utf-8-sig" # BOM included, MS style (discouraged)
969
+ if sample[:2] in (codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE):
970
+ return "utf-16" # BOM included
971
+ nullcount = sample.count(_null)
972
+ if nullcount == 0:
973
+ return "utf-8"
974
+ if nullcount == 2:
975
+ if sample[::2] == _null2: # 1st and 3rd are null
976
+ return "utf-16-be"
977
+ if sample[1::2] == _null2: # 2nd and 4th are null
978
+ return "utf-16-le"
979
+ # Did not detect 2 valid UTF-16 ascii-range characters
980
+ if nullcount == 3:
981
+ if sample[:3] == _null3:
982
+ return "utf-32-be"
983
+ if sample[1:] == _null3:
984
+ return "utf-32-le"
985
+ # Did not detect a valid UTF-32 ascii-range character
986
+ return None
987
+
988
+
989
+ def prepend_scheme_if_needed(url, new_scheme):
990
+ """Given a URL that may or may not have a scheme, prepend the given scheme.
991
+ Does not replace a present scheme with the one provided as an argument.
992
+
993
+ :rtype: str
994
+ """
995
+ parsed = parse_url(url)
996
+ scheme, auth, host, port, path, query, fragment = parsed
997
+
998
+ # A defect in urlparse determines that there isn't a netloc present in some
999
+ # urls. We previously assumed parsing was overly cautious, and swapped the
1000
+ # netloc and path. Due to a lack of tests on the original defect, this is
1001
+ # maintained with parse_url for backwards compatibility.
1002
+ netloc = parsed.netloc
1003
+ if not netloc:
1004
+ netloc, path = path, netloc
1005
+
1006
+ if auth:
1007
+ # parse_url doesn't provide the netloc with auth
1008
+ # so we'll add it ourselves.
1009
+ netloc = "@".join([auth, netloc])
1010
+ if scheme is None:
1011
+ scheme = new_scheme
1012
+ if path is None:
1013
+ path = ""
1014
+
1015
+ return urlunparse((scheme, netloc, path, "", query, fragment))
1016
+
1017
+
1018
+ def get_auth_from_url(url):
1019
+ """Given a url with authentication components, extract them into a tuple of
1020
+ username,password.
1021
+
1022
+ :rtype: (str,str)
1023
+ """
1024
+ parsed = urlparse(url)
1025
+
1026
+ try:
1027
+ auth = (unquote(parsed.username), unquote(parsed.password))
1028
+ except (AttributeError, TypeError):
1029
+ auth = ("", "")
1030
+
1031
+ return auth
1032
+
1033
+
1034
+ def check_header_validity(header):
1035
+ """Verifies that header parts don't contain leading whitespace
1036
+ reserved characters, or return characters.
1037
+
1038
+ :param header: tuple, in the format (name, value).
1039
+ """
1040
+ name, value = header
1041
+ _validate_header_part(header, name, 0)
1042
+ _validate_header_part(header, value, 1)
1043
+
1044
+
1045
+ def _validate_header_part(header, header_part, header_validator_index):
1046
+ if isinstance(header_part, str):
1047
+ validator = _HEADER_VALIDATORS_STR[header_validator_index]
1048
+ elif isinstance(header_part, bytes):
1049
+ validator = _HEADER_VALIDATORS_BYTE[header_validator_index]
1050
+ else:
1051
+ raise InvalidHeader(
1052
+ f"Header part ({header_part!r}) from {header} "
1053
+ f"must be of type str or bytes, not {type(header_part)}"
1054
+ )
1055
+
1056
+ if not validator.match(header_part):
1057
+ header_kind = "name" if header_validator_index == 0 else "value"
1058
+ raise InvalidHeader(
1059
+ f"Invalid leading whitespace, reserved character(s), or return "
1060
+ f"character(s) in header {header_kind}: {header_part!r}"
1061
+ )
1062
+
1063
+
1064
+ def urldefragauth(url):
1065
+ """
1066
+ Given a url remove the fragment and the authentication part.
1067
+
1068
+ :rtype: str
1069
+ """
1070
+ scheme, netloc, path, params, query, fragment = urlparse(url)
1071
+
1072
+ # see func:`prepend_scheme_if_needed`
1073
+ if not netloc:
1074
+ netloc, path = path, netloc
1075
+
1076
+ netloc = netloc.rsplit("@", 1)[-1]
1077
+
1078
+ return urlunparse((scheme, netloc, path, params, query, ""))
1079
+
1080
+
1081
+ def rewind_body(prepared_request):
1082
+ """Move file pointer back to its recorded starting position
1083
+ so it can be read again on redirect.
1084
+ """
1085
+ body_seek = getattr(prepared_request.body, "seek", None)
1086
+ if body_seek is not None and isinstance(
1087
+ prepared_request._body_position, integer_types
1088
+ ):
1089
+ try:
1090
+ body_seek(prepared_request._body_position)
1091
+ except OSError:
1092
+ raise UnrewindableBodyError(
1093
+ "An error occurred when rewinding request body for redirect."
1094
+ )
1095
+ else:
1096
+ raise UnrewindableBodyError("Unable to rewind request body for redirect.")
vllm/lib/python3.10/site-packages/rsa-4.9.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ pip
vllm/lib/python3.10/site-packages/rsa-4.9.dist-info/LICENSE ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Copyright 2011 Sybren A. Stüvel <sybren@stuvel.eu>
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
+ https://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.
vllm/lib/python3.10/site-packages/rsa-4.9.dist-info/METADATA ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.1
2
+ Name: rsa
3
+ Version: 4.9
4
+ Summary: Pure-Python RSA implementation
5
+ Home-page: https://stuvel.eu/rsa
6
+ License: Apache-2.0
7
+ Author: Sybren A. Stüvel
8
+ Author-email: sybren@stuvel.eu
9
+ Requires-Python: >=3.6,<4
10
+ Classifier: Development Status :: 5 - Production/Stable
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Intended Audience :: Education
13
+ Classifier: Intended Audience :: Information Technology
14
+ Classifier: License :: OSI Approved :: Apache Software License
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.6
20
+ Classifier: Programming Language :: Python :: 3.7
21
+ Classifier: Programming Language :: Python :: 3.8
22
+ Classifier: Programming Language :: Python :: 3.9
23
+ Classifier: Programming Language :: Python :: Implementation :: CPython
24
+ Classifier: Programming Language :: Python :: Implementation :: PyPy
25
+ Classifier: Topic :: Security :: Cryptography
26
+ Requires-Dist: pyasn1 (>=0.1.3)
27
+ Project-URL: Repository, https://github.com/sybrenstuvel/python-rsa
28
+ Description-Content-Type: text/markdown
29
+
30
+ # Pure Python RSA implementation
31
+
32
+ [![PyPI](https://img.shields.io/pypi/v/rsa.svg)](https://pypi.org/project/rsa/)
33
+ [![Build Status](https://travis-ci.org/sybrenstuvel/python-rsa.svg?branch=master)](https://travis-ci.org/sybrenstuvel/python-rsa)
34
+ [![Coverage Status](https://coveralls.io/repos/github/sybrenstuvel/python-rsa/badge.svg?branch=master)](https://coveralls.io/github/sybrenstuvel/python-rsa?branch=master)
35
+ [![Code Climate](https://api.codeclimate.com/v1/badges/a99a88d28ad37a79dbf6/maintainability)](https://codeclimate.com/github/codeclimate/codeclimate/maintainability)
36
+
37
+ [Python-RSA](https://stuvel.eu/rsa) is a pure-Python RSA implementation. It supports
38
+ encryption and decryption, signing and verifying signatures, and key
39
+ generation according to PKCS#1 version 1.5. It can be used as a Python
40
+ library as well as on the commandline. The code was mostly written by
41
+ Sybren A. Stüvel.
42
+
43
+ Documentation can be found at the [Python-RSA homepage](https://stuvel.eu/rsa). For all changes, check [the changelog](https://github.com/sybrenstuvel/python-rsa/blob/master/CHANGELOG.md).
44
+
45
+ Download and install using:
46
+
47
+ pip install rsa
48
+
49
+ or download it from the [Python Package Index](https://pypi.org/project/rsa/).
50
+
51
+ The source code is maintained at [GitHub](https://github.com/sybrenstuvel/python-rsa/) and is
52
+ licensed under the [Apache License, version 2.0](https://www.apache.org/licenses/LICENSE-2.0)
53
+
54
+ ## Security
55
+
56
+ Because of how Python internally stores numbers, it is very hard (if not impossible) to make a pure-Python program secure against timing attacks. This library is no exception, so use it with care. See https://securitypitfalls.wordpress.com/2018/08/03/constant-time-compare-in-python/ for more info.
57
+
58
+ ## Setup of Development Environment
59
+
60
+ ```
61
+ python3 -m venv .venv
62
+ . ./.venv/bin/activate
63
+ pip install poetry
64
+ poetry install
65
+ ```
66
+
67
+ ## Publishing a New Release
68
+
69
+ Since this project is considered critical on the Python Package Index,
70
+ two-factor authentication is required. For uploading packages to PyPi, an API
71
+ key is required; username+password will not work.
72
+
73
+ First, generate an API token at https://pypi.org/manage/account/token/. Then,
74
+ use this token when publishing instead of your username and password.
75
+
76
+ As username, use `__token__`.
77
+ As password, use the token itself, including the `pypi-` prefix.
78
+
79
+ See https://pypi.org/help/#apitoken for help using API tokens to publish. This
80
+ is what I have in `~/.pypirc`:
81
+
82
+ ```
83
+ [distutils]
84
+ index-servers =
85
+ rsa
86
+
87
+ # Use `twine upload -r rsa` to upload with this token.
88
+ [rsa]
89
+ repository = https://upload.pypi.org/legacy/
90
+ username = __token__
91
+ password = pypi-token
92
+ ```
93
+
94
+ ```
95
+ . ./.venv/bin/activate
96
+ pip install twine
97
+
98
+ poetry build
99
+ twine check dist/rsa-4.9.tar.gz dist/rsa-4.9-*.whl
100
+ twine upload -r rsa dist/rsa-4.9.tar.gz dist/rsa-4.9-*.whl
101
+ ```
102
+
103
+ The `pip install twine` is necessary as Python-RSA requires Python >= 3.6, and
104
+ Twine requires at least version 3.7. This means Poetry refuses to add it as
105
+ dependency.
106
+
vllm/lib/python3.10/site-packages/rsa-4.9.dist-info/RECORD ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ../../../bin/pyrsa-decrypt,sha256=tAsI7GKCA4cITVWBlc00H-Pfp5XVADAxIdsktqOgfwc,222
2
+ ../../../bin/pyrsa-encrypt,sha256=zV92ZQ4x8pk9HRzSwStdRrGoFHJOXOluRa4ih6_UM9M,222
3
+ ../../../bin/pyrsa-keygen,sha256=Z7wBo6532p6lsX1Z6tiVf0ovrc-EFDhfDvgBJ6f908s,220
4
+ ../../../bin/pyrsa-priv2pub,sha256=0vc_03u4pi4xFIr-86qM-7eKWtkNQpV9xy3_01hjTMA,243
5
+ ../../../bin/pyrsa-sign,sha256=gLjeBckcKpRGE5yqk-xzahg0BK7IY0FKW8n0u1gBkCc,216
6
+ ../../../bin/pyrsa-verify,sha256=i9uGJ9Ls1PyM7oOauehuGO4DSigKIbRu8PSzR32jHpo,220
7
+ rsa-4.9.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
8
+ rsa-4.9.dist-info/LICENSE,sha256=Bz8ot9OJyP509gfhfCf4HqpazmntxDqITyP0G0HFxyY,577
9
+ rsa-4.9.dist-info/METADATA,sha256=-540qZBdoxQdUSuhxWlXTnY-oMNVz3EML49u9IfmmQ4,4173
10
+ rsa-4.9.dist-info/RECORD,,
11
+ rsa-4.9.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
12
+ rsa-4.9.dist-info/WHEEL,sha256=y3eDiaFVSNTPbgzfNn0nYn5tEn1cX6WrdetDlQM4xWw,83
13
+ rsa-4.9.dist-info/entry_points.txt,sha256=p0nVsezmPSjm5x4GDMD4a9Sshc9ukdfw1kkmOmpaAu0,201
14
+ rsa/__init__.py,sha256=5bc5rkBB8vxWEtVYwoMQxM8df3O1Ak2_zEXqnkK9oes,1605
15
+ rsa/__pycache__/__init__.cpython-310.pyc,,
16
+ rsa/__pycache__/asn1.cpython-310.pyc,,
17
+ rsa/__pycache__/cli.cpython-310.pyc,,
18
+ rsa/__pycache__/common.cpython-310.pyc,,
19
+ rsa/__pycache__/core.cpython-310.pyc,,
20
+ rsa/__pycache__/key.cpython-310.pyc,,
21
+ rsa/__pycache__/parallel.cpython-310.pyc,,
22
+ rsa/__pycache__/pem.cpython-310.pyc,,
23
+ rsa/__pycache__/pkcs1.cpython-310.pyc,,
24
+ rsa/__pycache__/pkcs1_v2.cpython-310.pyc,,
25
+ rsa/__pycache__/prime.cpython-310.pyc,,
26
+ rsa/__pycache__/randnum.cpython-310.pyc,,
27
+ rsa/__pycache__/transform.cpython-310.pyc,,
28
+ rsa/__pycache__/util.cpython-310.pyc,,
29
+ rsa/asn1.py,sha256=WL2bhDg-q7riT8P8cBMpydsh020i6Ejl6vcQIuA0VXA,1792
30
+ rsa/cli.py,sha256=DOE66cB0-0SjUhs-PX2gbxiSma5-CT1lEAdcCYrTXwE,10183
31
+ rsa/common.py,sha256=DAWwAuOSv1X67CBHzBvH-1wOsRe9np6eVsL_ZLrBWcg,4863
32
+ rsa/core.py,sha256=Rf33atg4-pI7U-mTdoosmn8gTeTyX5xP7yv0iqWyogc,1714
33
+ rsa/key.py,sha256=3_xv7B-AZZ5jIIz-vpnpfJtStS415e8fNr2iTYOu5CM,28285
34
+ rsa/parallel.py,sha256=NcL1QjNWJxH9zL2OAOYKgr-HbAeEEmdckdxC6KMhkmM,2405
35
+ rsa/pem.py,sha256=lzFulzgLHyqhimeo3T4GeBXuGRClfkTMYYZbgmYYmQk,4123
36
+ rsa/pkcs1.py,sha256=wN9SWn1_zFJvHDNLGPeGZxoDA5T7ipVy9DntNcCYBpU,16690
37
+ rsa/pkcs1_v2.py,sha256=d5A27EcOgbgJeikuLZkzANOzBQh4nVX-Bom5DUXgXHw,3549
38
+ rsa/prime.py,sha256=Kij81g-VneGw20Cq6LRaCVT3b9tX4gWIzkWV-3h4qMg,5304
39
+ rsa/py.typed,sha256=TfYjsEjlfDcVNGFibSYzbCf81u37bSXWmv4oTYf0zY8,64
40
+ rsa/randnum.py,sha256=AwhXEZAT6spbUUPjhwQXGXKOTlG8FPHOI3gmTAcQ0pk,2752
41
+ rsa/transform.py,sha256=i-nVC7JcPZkYz1W-d-qg0n0PQS17kKeXhfd9IkDehj4,2272
42
+ rsa/util.py,sha256=9PuWg2jQfV8FHdE9hpGHDCi2iGM8Z-r4tIQXRVFmqYY,3090
vllm/lib/python3.10/site-packages/rsa-4.9.dist-info/REQUESTED ADDED
File without changes
vllm/lib/python3.10/site-packages/rsa-4.9.dist-info/WHEEL ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: poetry 1.0.7
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
vllm/lib/python3.10/site-packages/rsa-4.9.dist-info/entry_points.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ [console_scripts]
2
+ pyrsa-decrypt=rsa.cli:decrypt
3
+ pyrsa-encrypt=rsa.cli:encrypt
4
+ pyrsa-keygen=rsa.cli:keygen
5
+ pyrsa-priv2pub=rsa.util:private_to_public
6
+ pyrsa-sign=rsa.cli:sign
7
+ pyrsa-verify=rsa.cli:verify
8
+