codekingpro commited on
Commit
2f871c1
·
verified ·
1 Parent(s): 0b0ead5

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. micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf-6.11.0.dist-info/WHEEL +4 -0
  2. micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf-6.11.0.dist-info/licenses/LICENSE +29 -0
  3. micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/__pycache__/_cmap.cpython-311.pyc +0 -0
  4. micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/__pycache__/_doc_common.cpython-311.pyc +0 -0
  5. micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/__pycache__/_encryption.cpython-311.pyc +0 -0
  6. micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/__pycache__/constants.cpython-311.pyc +0 -0
  7. micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/__pycache__/errors.cpython-311.pyc +0 -0
  8. micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/__pycache__/filters.cpython-311.pyc +0 -0
  9. micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/__pycache__/pagerange.cpython-311.pyc +0 -0
  10. micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/__pycache__/papersizes.cpython-311.pyc +0 -0
  11. micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/__pycache__/types.cpython-311.pyc +0 -0
  12. micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/__pycache__/xmp.cpython-311.pyc +0 -0
  13. micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_codecs/__init__.py +55 -0
  14. micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_codecs/_codecs.py +281 -0
  15. micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_codecs/adobe_glyphs.py +0 -0
  16. micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_codecs/core_font_metrics.py +0 -0
  17. micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_codecs/pdfdoc.py +264 -0
  18. micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_codecs/std.py +258 -0
  19. micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_codecs/symbol.py +260 -0
  20. micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_codecs/zapfding.py +261 -0
  21. micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_crypt_providers/__init__.py +80 -0
  22. micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_crypt_providers/_base.py +38 -0
  23. micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_crypt_providers/_cryptography.py +133 -0
  24. micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_crypt_providers/_fallback.py +93 -0
  25. micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_crypt_providers/_pycryptodome.py +110 -0
  26. micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_text_extraction/__init__.py +245 -0
  27. micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_text_extraction/_text_extractor.py +350 -0
  28. micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/annotations/__init__.py +42 -0
  29. micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/annotations/_base.py +29 -0
  30. micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/annotations/_markup_annotations.py +351 -0
  31. micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/annotations/_non_markup_annotations.py +106 -0
  32. micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/generic/__init__.py +115 -0
  33. micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/generic/_appearance_stream.py +589 -0
  34. micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/generic/_base.py +953 -0
  35. micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/generic/_data_structures.py +1804 -0
  36. micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/generic/_files.py +404 -0
  37. micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/generic/_fit.py +174 -0
  38. micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/generic/_image_inline.py +315 -0
  39. micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/generic/_image_xobject.py +590 -0
  40. micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/generic/_link.py +144 -0
  41. micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/generic/_outline.py +33 -0
  42. micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/generic/_rectangle.py +136 -0
  43. micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/generic/_utils.py +208 -0
  44. micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/generic/_viewerpref.py +164 -0
  45. micromamba_root/envs/pytorch_env/Lib/site-packages/pypika-0.51.1.dist-info/INSTALLER +1 -0
  46. micromamba_root/envs/pytorch_env/Lib/site-packages/pypika-0.51.1.dist-info/METADATA +1879 -0
  47. micromamba_root/envs/pytorch_env/Lib/site-packages/pypika-0.51.1.dist-info/RECORD +39 -0
  48. micromamba_root/envs/pytorch_env/Lib/site-packages/pypika-0.51.1.dist-info/WHEEL +6 -0
  49. micromamba_root/envs/pytorch_env/Lib/site-packages/pypika-0.51.1.dist-info/licenses/LICENSE.txt +201 -0
  50. micromamba_root/envs/pytorch_env/Lib/site-packages/pypika-0.51.1.dist-info/top_level.txt +1 -0
micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf-6.11.0.dist-info/WHEEL ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: flit 3.12.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf-6.11.0.dist-info/licenses/LICENSE ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Copyright (c) 2006-2008, Mathieu Fenniak
2
+ Some contributions copyright (c) 2007, Ashish Kulkarni <kulkarni.ashish@gmail.com>
3
+ Some contributions copyright (c) 2014, Steve Witham <switham_github@mac-guyver.com>
4
+
5
+ All rights reserved.
6
+
7
+ Redistribution and use in source and binary forms, with or without
8
+ modification, are permitted provided that the following conditions are
9
+ met:
10
+
11
+ * Redistributions of source code must retain the above copyright notice,
12
+ this list of conditions and the following disclaimer.
13
+ * Redistributions in binary form must reproduce the above copyright notice,
14
+ this list of conditions and the following disclaimer in the documentation
15
+ and/or other materials provided with the distribution.
16
+ * The name of the author may not be used to endorse or promote products
17
+ derived from this software without specific prior written permission.
18
+
19
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
20
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22
+ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
23
+ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24
+ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25
+ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26
+ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27
+ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28
+ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29
+ POSSIBILITY OF SUCH DAMAGE.
micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/__pycache__/_cmap.cpython-311.pyc ADDED
Binary file (17.1 kB). View file
 
micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/__pycache__/_doc_common.cpython-311.pyc ADDED
Binary file (70.5 kB). View file
 
micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/__pycache__/_encryption.cpython-311.pyc ADDED
Binary file (58.1 kB). View file
 
micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/__pycache__/constants.cpython-311.pyc ADDED
Binary file (27.5 kB). View file
 
micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/__pycache__/errors.cpython-311.pyc ADDED
Binary file (4.56 kB). View file
 
micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/__pycache__/filters.cpython-311.pyc ADDED
Binary file (37.1 kB). View file
 
micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/__pycache__/pagerange.cpython-311.pyc ADDED
Binary file (10.2 kB). View file
 
micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/__pycache__/papersizes.cpython-311.pyc ADDED
Binary file (1.64 kB). View file
 
micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/__pycache__/types.cpython-311.pyc ADDED
Binary file (2.15 kB). View file
 
micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/__pycache__/xmp.cpython-311.pyc ADDED
Binary file (45.9 kB). View file
 
micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_codecs/__init__.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .adobe_glyphs import adobe_glyphs
2
+ from .pdfdoc import _pdfdoc_encoding
3
+ from .std import _std_encoding
4
+ from .symbol import _symbol_encoding
5
+ from .zapfding import _zapfding_encoding
6
+
7
+
8
+ def fill_from_encoding(enc: str) -> list[str]:
9
+ lst: list[str] = []
10
+ for x in range(256):
11
+ try:
12
+ lst += (bytes((x,)).decode(enc),)
13
+ except Exception:
14
+ lst += (chr(x),)
15
+ return lst
16
+
17
+
18
+ def rev_encoding(enc: list[str]) -> dict[str, int]:
19
+ rev: dict[str, int] = {}
20
+ for i in range(256):
21
+ char = enc[i]
22
+ if char == "\u0000":
23
+ continue
24
+ assert char not in rev, f"{char} at {i} already at {rev[char]}"
25
+ rev[char] = i
26
+ return rev
27
+
28
+
29
+ _win_encoding = fill_from_encoding("cp1252")
30
+ _mac_encoding = fill_from_encoding("mac_roman")
31
+
32
+
33
+ _pdfdoc_encoding_rev: dict[str, int] = rev_encoding(_pdfdoc_encoding)
34
+
35
+
36
+ charset_encoding: dict[str, list[str]] = {
37
+ "/StandardEncoding": _std_encoding,
38
+ "/WinAnsiEncoding": _win_encoding,
39
+ "/MacRomanEncoding": _mac_encoding,
40
+ "/PDFDocEncoding": _pdfdoc_encoding,
41
+ "/Symbol": _symbol_encoding,
42
+ "/ZapfDingbats": _zapfding_encoding,
43
+ }
44
+
45
+ __all__ = [
46
+ "_mac_encoding",
47
+ "_pdfdoc_encoding",
48
+ "_pdfdoc_encoding_rev",
49
+ "_std_encoding",
50
+ "_symbol_encoding",
51
+ "_win_encoding",
52
+ "_zapfding_encoding",
53
+ "adobe_glyphs",
54
+ "charset_encoding",
55
+ ]
micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_codecs/_codecs.py ADDED
@@ -0,0 +1,281 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This module is for codecs only.
3
+
4
+ While the codec implementation can contain details of the PDF specification,
5
+ the module should not do any PDF parsing.
6
+ """
7
+
8
+ import io
9
+ from abc import ABC, abstractmethod
10
+
11
+ from pypdf._utils import logger_warning
12
+ from pypdf.errors import LimitReachedError
13
+
14
+
15
+ class Codec(ABC):
16
+ """Abstract base class for all codecs."""
17
+
18
+ @abstractmethod
19
+ def encode(self, data: bytes) -> bytes:
20
+ """
21
+ Encode the input data.
22
+
23
+ Args:
24
+ data: Data to encode.
25
+
26
+ Returns:
27
+ Encoded data.
28
+
29
+ """
30
+
31
+ @abstractmethod
32
+ def decode(self, data: bytes) -> bytes:
33
+ """
34
+ Decode the input data.
35
+
36
+ Args:
37
+ data: Data to decode.
38
+
39
+ Returns:
40
+ Decoded data.
41
+
42
+ """
43
+
44
+
45
+ class LzwCodec(Codec):
46
+ """Lempel-Ziv-Welch (LZW) adaptive compression codec."""
47
+
48
+ CLEAR_TABLE_MARKER = 256 # Special code to indicate table reset
49
+ EOD_MARKER = 257 # End-of-data marker
50
+ INITIAL_BITS_PER_CODE = 9 # Initial code bit width
51
+ MAX_BITS_PER_CODE = 12 # Maximum code bit width
52
+
53
+ def __init__(self, max_output_length: int = 75_000_000) -> None:
54
+ self.max_output_length = max_output_length
55
+
56
+ def _initialize_encoding_table(self) -> None:
57
+ """Initialize the encoding table and state to initial conditions."""
58
+ self.encoding_table: dict[bytes, int] = {bytes([i]): i for i in range(256)}
59
+ self.next_code = self.EOD_MARKER + 1
60
+ self.bits_per_code = self.INITIAL_BITS_PER_CODE
61
+ self.max_code_value = (1 << self.bits_per_code) - 1
62
+
63
+ def _increase_next_code(self) -> None:
64
+ """Update bits_per_code and max_code_value if necessary."""
65
+ self.next_code += 1
66
+ if (
67
+ self.next_code > self.max_code_value
68
+ and self.bits_per_code < self.MAX_BITS_PER_CODE
69
+ ):
70
+ self.bits_per_code += 1
71
+ self.max_code_value = (1 << self.bits_per_code) - 1
72
+
73
+ def encode(self, data: bytes) -> bytes:
74
+ """
75
+ Encode data using the LZW compression algorithm.
76
+
77
+ Taken from PDF 1.7 specs, "7.4.4.2 Details of LZW Encoding".
78
+ """
79
+ result_codes: list[int] = []
80
+
81
+ # The encoder shall begin by issuing a clear-table code
82
+ result_codes.append(self.CLEAR_TABLE_MARKER)
83
+ self._initialize_encoding_table()
84
+
85
+ current_sequence = b""
86
+ for byte in data:
87
+ next_sequence = current_sequence + bytes([byte])
88
+
89
+ if next_sequence in self.encoding_table:
90
+ # Extend current sequence if already in the table
91
+ current_sequence = next_sequence
92
+ else:
93
+ # Output code for the current sequence
94
+ result_codes.append(self.encoding_table[current_sequence])
95
+
96
+ # Add the new sequence to the table if there's room
97
+ if self.next_code <= (1 << self.MAX_BITS_PER_CODE) - 1:
98
+ self.encoding_table[next_sequence] = self.next_code
99
+ self._increase_next_code()
100
+ else:
101
+ # If the table is full, emit a clear-table command
102
+ result_codes.append(self.CLEAR_TABLE_MARKER)
103
+ self._initialize_encoding_table()
104
+
105
+ # Start new sequence
106
+ current_sequence = bytes([byte])
107
+
108
+ # Ensure everything actually is encoded
109
+ if current_sequence:
110
+ result_codes.append(self.encoding_table[current_sequence])
111
+ result_codes.append(self.EOD_MARKER)
112
+
113
+ return self._pack_codes_into_bytes(result_codes)
114
+
115
+ def _pack_codes_into_bytes(self, codes: list[int]) -> bytes:
116
+ """
117
+ Convert the list of result codes into a continuous byte stream, with codes packed as per the code bit-width.
118
+ The bit-width starts at 9 bits and expands as needed.
119
+ """
120
+ self._initialize_encoding_table()
121
+ buffer = 0
122
+ bits_in_buffer = 0
123
+ output = bytearray()
124
+
125
+ for code in codes:
126
+ buffer = (buffer << self.bits_per_code) | code
127
+ bits_in_buffer += self.bits_per_code
128
+
129
+ # Codes shall be packed into a continuous bit stream, high-order bit
130
+ # first. This stream shall then be divided into bytes, high-order bit
131
+ # first.
132
+ while bits_in_buffer >= 8:
133
+ bits_in_buffer -= 8
134
+ output.append((buffer >> bits_in_buffer) & 0xFF)
135
+
136
+ if code == self.CLEAR_TABLE_MARKER:
137
+ self._initialize_encoding_table()
138
+ elif code == self.EOD_MARKER:
139
+ continue
140
+ else:
141
+ self._increase_next_code()
142
+
143
+ # Flush any remaining bits in the buffer
144
+ if bits_in_buffer > 0:
145
+ output.append((buffer << (8 - bits_in_buffer)) & 0xFF)
146
+
147
+ return bytes(output)
148
+
149
+ def _initialize_decoding_table(self) -> None:
150
+ self.max_code_value = (1 << self.MAX_BITS_PER_CODE) - 1
151
+ self.decoding_table = [bytes([i]) for i in range(self.CLEAR_TABLE_MARKER)] + [
152
+ b""
153
+ ] * (self.max_code_value - self.CLEAR_TABLE_MARKER + 1)
154
+ self._table_index = self.EOD_MARKER + 1
155
+ self._bits_to_get = 9
156
+
157
+ def _next_code_decode(self, data: bytes) -> int:
158
+ self._next_data: int
159
+ try:
160
+ while self._next_bits < self._bits_to_get:
161
+ self._next_data = (self._next_data << 8) | (
162
+ data[self._byte_pointer]
163
+ )
164
+ self._byte_pointer += 1
165
+ self._next_bits += 8
166
+
167
+ code = (
168
+ self._next_data >> (self._next_bits - self._bits_to_get)
169
+ ) & self._and_table[self._bits_to_get - 9]
170
+ self._next_bits -= self._bits_to_get
171
+
172
+ # Reduce data to get rid of the overhead,
173
+ # which increases performance on large streams significantly.
174
+ self._next_data = self._next_data & 0xFFFFF
175
+
176
+ return code
177
+ except IndexError:
178
+ return self.EOD_MARKER
179
+
180
+ # The following method has been converted to Python from PDFsharp:
181
+ # https://github.com/empira/PDFsharp/blob/5fbf6ed14740bc4e16786816882d32e43af3ff5d/src/foundation/src/PDFsharp/src/PdfSharp/Pdf.Filters/LzwDecode.cs
182
+ #
183
+ # Original license:
184
+ #
185
+ # -------------------------------------------------------------------------
186
+ # Copyright (c) 2001-2024 empira Software GmbH, Troisdorf (Cologne Area),
187
+ # Germany
188
+ #
189
+ # http://docs.pdfsharp.net
190
+ #
191
+ # MIT License
192
+ #
193
+ # Permission is hereby granted, free of charge, to any person obtaining a
194
+ # copy of this software and associated documentation files (the "Software"),
195
+ # to deal in the Software without restriction, including without limitation
196
+ # the rights to use, copy, modify, merge, publish, distribute, sublicense,
197
+ # and/or sell copies of the Software, and to permit persons to whom the
198
+ # Software is furnished to do so, subject to the following conditions:
199
+ #
200
+ # The above copyright notice and this permission notice shall be included
201
+ # in all copies or substantial portions of the Software.
202
+ #
203
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
204
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
205
+ # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
206
+ # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
207
+ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
208
+ # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
209
+ # DEALINGS IN THE SOFTWARE.
210
+ # --------------------------------------------------------------------------
211
+ def decode(self, data: bytes) -> bytes:
212
+ """
213
+ The following code was converted to Python from the following code:
214
+ https://github.com/empira/PDFsharp/blob/master/src/foundation/src/PDFsharp/src/PdfSharp/Pdf.Filters/LzwDecode.cs
215
+ """
216
+ self._and_table = [511, 1023, 2047, 4095]
217
+ self._table_index = 0
218
+ self._bits_to_get = 9
219
+ self._byte_pointer = 0
220
+ self._next_data = 0
221
+ self._next_bits = 0
222
+
223
+ output_stream = io.BytesIO()
224
+ output_length = 0
225
+
226
+ self._initialize_decoding_table()
227
+ self._byte_pointer = 0
228
+ self._next_data = 0
229
+ self._next_bits = 0
230
+ old_code = self.CLEAR_TABLE_MARKER
231
+
232
+ while True:
233
+ code = self._next_code_decode(data)
234
+ if code == self.EOD_MARKER:
235
+ break
236
+
237
+ if code == self.CLEAR_TABLE_MARKER:
238
+ self._initialize_decoding_table()
239
+ code = self._next_code_decode(data)
240
+ if code == self.EOD_MARKER:
241
+ break
242
+ output_stream.write(decoded := self.decoding_table[code])
243
+ old_code = code
244
+ elif code < self._table_index:
245
+ decoded = self.decoding_table[code]
246
+ output_stream.write(decoded)
247
+ if old_code != self.CLEAR_TABLE_MARKER:
248
+ self._add_entry_decode(self.decoding_table[old_code], decoded[0])
249
+ old_code = code
250
+ else:
251
+ # The code is not in the table and not one of the special codes
252
+ decoded = (
253
+ self.decoding_table[old_code] + self.decoding_table[old_code][:1]
254
+ )
255
+ output_stream.write(decoded)
256
+ self._add_entry_decode(self.decoding_table[old_code], decoded[0])
257
+ old_code = code
258
+
259
+ output_length += len(decoded)
260
+ if output_length > self.max_output_length:
261
+ raise LimitReachedError(
262
+ f"Limit reached while decompressing: {output_length} > {self.max_output_length}"
263
+ )
264
+
265
+ return output_stream.getvalue()
266
+
267
+ def _add_entry_decode(self, old_string: bytes, new_char: int) -> None:
268
+ new_string = old_string + bytes([new_char])
269
+ if self._table_index > self.max_code_value:
270
+ logger_warning("Ignoring too large LZW table index.", __name__)
271
+ return
272
+ self.decoding_table[self._table_index] = new_string
273
+ self._table_index += 1
274
+
275
+ # Update the number of bits to get based on the table index
276
+ if self._table_index == 511:
277
+ self._bits_to_get = 10
278
+ elif self._table_index == 1023:
279
+ self._bits_to_get = 11
280
+ elif self._table_index == 2047:
281
+ self._bits_to_get = 12
micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_codecs/adobe_glyphs.py ADDED
The diff for this file is too large to render. See raw diff
 
micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_codecs/core_font_metrics.py ADDED
The diff for this file is too large to render. See raw diff
 
micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_codecs/pdfdoc.py ADDED
@@ -0,0 +1,264 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # PDFDocEncoding Character Set: Table D.2 of PDF Reference 1.7
2
+ # C.1 Predefined encodings sorted by character name of another PDF reference
3
+ # Some indices have '\u0000' although they should have something else:
4
+ # 22: should be '\u0017'
5
+ _pdfdoc_encoding = [
6
+ "\u0000",
7
+ "\u0001",
8
+ "\u0002",
9
+ "\u0003",
10
+ "\u0004",
11
+ "\u0005",
12
+ "\u0006",
13
+ "\u0007", # 0 - 7
14
+ "\u0008",
15
+ "\u0009",
16
+ "\u000a",
17
+ "\u000b",
18
+ "\u000c",
19
+ "\u000d",
20
+ "\u000e",
21
+ "\u000f", # 8 - 15
22
+ "\u0010",
23
+ "\u0011",
24
+ "\u0012",
25
+ "\u0013",
26
+ "\u0014",
27
+ "\u0015",
28
+ "\u0000",
29
+ "\u0017", # 16 - 23
30
+ "\u02d8",
31
+ "\u02c7",
32
+ "\u02c6",
33
+ "\u02d9",
34
+ "\u02dd",
35
+ "\u02db",
36
+ "\u02da",
37
+ "\u02dc", # 24 - 31
38
+ "\u0020",
39
+ "\u0021",
40
+ "\u0022",
41
+ "\u0023",
42
+ "\u0024",
43
+ "\u0025",
44
+ "\u0026",
45
+ "\u0027", # 32 - 39
46
+ "\u0028",
47
+ "\u0029",
48
+ "\u002a",
49
+ "\u002b",
50
+ "\u002c",
51
+ "\u002d",
52
+ "\u002e",
53
+ "\u002f", # 40 - 47
54
+ "\u0030",
55
+ "\u0031",
56
+ "\u0032",
57
+ "\u0033",
58
+ "\u0034",
59
+ "\u0035",
60
+ "\u0036",
61
+ "\u0037", # 48 - 55
62
+ "\u0038",
63
+ "\u0039",
64
+ "\u003a",
65
+ "\u003b",
66
+ "\u003c",
67
+ "\u003d",
68
+ "\u003e",
69
+ "\u003f", # 56 - 63
70
+ "\u0040",
71
+ "\u0041",
72
+ "\u0042",
73
+ "\u0043",
74
+ "\u0044",
75
+ "\u0045",
76
+ "\u0046",
77
+ "\u0047", # 64 - 71
78
+ "\u0048",
79
+ "\u0049",
80
+ "\u004a",
81
+ "\u004b",
82
+ "\u004c",
83
+ "\u004d",
84
+ "\u004e",
85
+ "\u004f", # 72 - 79
86
+ "\u0050",
87
+ "\u0051",
88
+ "\u0052",
89
+ "\u0053",
90
+ "\u0054",
91
+ "\u0055",
92
+ "\u0056",
93
+ "\u0057", # 80 - 87
94
+ "\u0058",
95
+ "\u0059",
96
+ "\u005a",
97
+ "\u005b",
98
+ "\u005c",
99
+ "\u005d",
100
+ "\u005e",
101
+ "\u005f", # 88 - 95
102
+ "\u0060",
103
+ "\u0061",
104
+ "\u0062",
105
+ "\u0063",
106
+ "\u0064",
107
+ "\u0065",
108
+ "\u0066",
109
+ "\u0067", # 96 - 103
110
+ "\u0068",
111
+ "\u0069",
112
+ "\u006a",
113
+ "\u006b",
114
+ "\u006c",
115
+ "\u006d",
116
+ "\u006e",
117
+ "\u006f", # 104 - 111
118
+ "\u0070",
119
+ "\u0071",
120
+ "\u0072",
121
+ "\u0073",
122
+ "\u0074",
123
+ "\u0075",
124
+ "\u0076",
125
+ "\u0077", # 112 - 119
126
+ "\u0078",
127
+ "\u0079",
128
+ "\u007a",
129
+ "\u007b",
130
+ "\u007c",
131
+ "\u007d",
132
+ "\u007e",
133
+ "\u0000", # 120 - 127
134
+ "\u2022",
135
+ "\u2020",
136
+ "\u2021",
137
+ "\u2026",
138
+ "\u2014",
139
+ "\u2013",
140
+ "\u0192",
141
+ "\u2044", # 128 - 135
142
+ "\u2039",
143
+ "\u203a",
144
+ "\u2212",
145
+ "\u2030",
146
+ "\u201e",
147
+ "\u201c",
148
+ "\u201d",
149
+ "\u2018", # 136 - 143
150
+ "\u2019",
151
+ "\u201a",
152
+ "\u2122",
153
+ "\ufb01",
154
+ "\ufb02",
155
+ "\u0141",
156
+ "\u0152",
157
+ "\u0160", # 144 - 151
158
+ "\u0178",
159
+ "\u017d",
160
+ "\u0131",
161
+ "\u0142",
162
+ "\u0153",
163
+ "\u0161",
164
+ "\u017e",
165
+ "\u0000", # 152 - 159
166
+ "\u20ac",
167
+ "\u00a1",
168
+ "\u00a2",
169
+ "\u00a3",
170
+ "\u00a4",
171
+ "\u00a5",
172
+ "\u00a6",
173
+ "\u00a7", # 160 - 167
174
+ "\u00a8",
175
+ "\u00a9",
176
+ "\u00aa",
177
+ "\u00ab",
178
+ "\u00ac",
179
+ "\u0000",
180
+ "\u00ae",
181
+ "\u00af", # 168 - 175
182
+ "\u00b0",
183
+ "\u00b1",
184
+ "\u00b2",
185
+ "\u00b3",
186
+ "\u00b4",
187
+ "\u00b5",
188
+ "\u00b6",
189
+ "\u00b7", # 176 - 183
190
+ "\u00b8",
191
+ "\u00b9",
192
+ "\u00ba",
193
+ "\u00bb",
194
+ "\u00bc",
195
+ "\u00bd",
196
+ "\u00be",
197
+ "\u00bf", # 184 - 191
198
+ "\u00c0",
199
+ "\u00c1",
200
+ "\u00c2",
201
+ "\u00c3",
202
+ "\u00c4",
203
+ "\u00c5",
204
+ "\u00c6",
205
+ "\u00c7", # 192 - 199
206
+ "\u00c8",
207
+ "\u00c9",
208
+ "\u00ca",
209
+ "\u00cb",
210
+ "\u00cc",
211
+ "\u00cd",
212
+ "\u00ce",
213
+ "\u00cf", # 200 - 207
214
+ "\u00d0",
215
+ "\u00d1",
216
+ "\u00d2",
217
+ "\u00d3",
218
+ "\u00d4",
219
+ "\u00d5",
220
+ "\u00d6",
221
+ "\u00d7", # 208 - 215
222
+ "\u00d8",
223
+ "\u00d9",
224
+ "\u00da",
225
+ "\u00db",
226
+ "\u00dc",
227
+ "\u00dd",
228
+ "\u00de",
229
+ "\u00df", # 216 - 223
230
+ "\u00e0",
231
+ "\u00e1",
232
+ "\u00e2",
233
+ "\u00e3",
234
+ "\u00e4",
235
+ "\u00e5",
236
+ "\u00e6",
237
+ "\u00e7", # 224 - 231
238
+ "\u00e8",
239
+ "\u00e9",
240
+ "\u00ea",
241
+ "\u00eb",
242
+ "\u00ec",
243
+ "\u00ed",
244
+ "\u00ee",
245
+ "\u00ef", # 232 - 239
246
+ "\u00f0",
247
+ "\u00f1",
248
+ "\u00f2",
249
+ "\u00f3",
250
+ "\u00f4",
251
+ "\u00f5",
252
+ "\u00f6",
253
+ "\u00f7", # 240 - 247
254
+ "\u00f8",
255
+ "\u00f9",
256
+ "\u00fa",
257
+ "\u00fb",
258
+ "\u00fc",
259
+ "\u00fd",
260
+ "\u00fe",
261
+ "\u00ff", # 248 - 255
262
+ ]
263
+
264
+ assert len(_pdfdoc_encoding) == 256
micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_codecs/std.py ADDED
@@ -0,0 +1,258 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ _std_encoding = [
2
+ "\x00",
3
+ "\x01",
4
+ "\x02",
5
+ "\x03",
6
+ "\x04",
7
+ "\x05",
8
+ "\x06",
9
+ "\x07",
10
+ "\x08",
11
+ "\t",
12
+ "\n",
13
+ "\x0b",
14
+ "\x0c",
15
+ "\r",
16
+ "\x0e",
17
+ "\x0f",
18
+ "\x10",
19
+ "\x11",
20
+ "\x12",
21
+ "\x13",
22
+ "\x14",
23
+ "\x15",
24
+ "\x16",
25
+ "\x17",
26
+ "\x18",
27
+ "\x19",
28
+ "\x1a",
29
+ "\x1b",
30
+ "\x1c",
31
+ "\x1d",
32
+ "\x1e",
33
+ "\x1f",
34
+ " ",
35
+ "!",
36
+ '"',
37
+ "#",
38
+ "$",
39
+ "%",
40
+ "&",
41
+ "’",
42
+ "(",
43
+ ")",
44
+ "*",
45
+ "+",
46
+ ",",
47
+ "-",
48
+ ".",
49
+ "/",
50
+ "0",
51
+ "1",
52
+ "2",
53
+ "3",
54
+ "4",
55
+ "5",
56
+ "6",
57
+ "7",
58
+ "8",
59
+ "9",
60
+ ":",
61
+ ";",
62
+ "<",
63
+ "=",
64
+ ">",
65
+ "?",
66
+ "@",
67
+ "A",
68
+ "B",
69
+ "C",
70
+ "D",
71
+ "E",
72
+ "F",
73
+ "G",
74
+ "H",
75
+ "I",
76
+ "J",
77
+ "K",
78
+ "L",
79
+ "M",
80
+ "N",
81
+ "O",
82
+ "P",
83
+ "Q",
84
+ "R",
85
+ "S",
86
+ "T",
87
+ "U",
88
+ "V",
89
+ "W",
90
+ "X",
91
+ "Y",
92
+ "Z",
93
+ "[",
94
+ "\\",
95
+ "]",
96
+ "^",
97
+ "_",
98
+ "‘",
99
+ "a",
100
+ "b",
101
+ "c",
102
+ "d",
103
+ "e",
104
+ "f",
105
+ "g",
106
+ "h",
107
+ "i",
108
+ "j",
109
+ "k",
110
+ "l",
111
+ "m",
112
+ "n",
113
+ "o",
114
+ "p",
115
+ "q",
116
+ "r",
117
+ "s",
118
+ "t",
119
+ "u",
120
+ "v",
121
+ "w",
122
+ "x",
123
+ "y",
124
+ "z",
125
+ "{",
126
+ "|",
127
+ "}",
128
+ "~",
129
+ "\x7f",
130
+ "\x80",
131
+ "\x81",
132
+ "\x82",
133
+ "\x83",
134
+ "\x84",
135
+ "\x85",
136
+ "\x86",
137
+ "\x87",
138
+ "\x88",
139
+ "\x89",
140
+ "\x8a",
141
+ "\x8b",
142
+ "\x8c",
143
+ "\x8d",
144
+ "\x8e",
145
+ "\x8f",
146
+ "\x90",
147
+ "\x91",
148
+ "\x92",
149
+ "\x93",
150
+ "\x94",
151
+ "\x95",
152
+ "\x96",
153
+ "\x97",
154
+ "\x98",
155
+ "\x99",
156
+ "\x9a",
157
+ "\x9b",
158
+ "\x9c",
159
+ "\x9d",
160
+ "\x9e",
161
+ "\x9f",
162
+ "\xa0",
163
+ "¡",
164
+ "¢",
165
+ "£",
166
+ "⁄",
167
+ "¥",
168
+ "ƒ",
169
+ "§",
170
+ "¤",
171
+ "'",
172
+ "“",
173
+ "«",
174
+ "‹",
175
+ "›",
176
+ "fi",
177
+ "fl",
178
+ "°",
179
+ "–",
180
+ "†",
181
+ "‡",
182
+ "·",
183
+ "µ",
184
+ "¶",
185
+ "•",
186
+ "‚",
187
+ "„",
188
+ "”",
189
+ "»",
190
+ "…",
191
+ "‰",
192
+ "¾",
193
+ "¿",
194
+ "À",
195
+ "`",
196
+ "´",
197
+ "ˆ",
198
+ "˜",
199
+ "¯",
200
+ "˘",
201
+ "˙",
202
+ "¨",
203
+ "É",
204
+ "˚",
205
+ "¸",
206
+ "Ì",
207
+ "˝",
208
+ "˛",
209
+ "ˇ",
210
+ "—",
211
+ "Ñ",
212
+ "Ò",
213
+ "Ó",
214
+ "Ô",
215
+ "Õ",
216
+ "Ö",
217
+ "×",
218
+ "Ø",
219
+ "Ù",
220
+ "Ú",
221
+ "Û",
222
+ "Ü",
223
+ "Ý",
224
+ "Þ",
225
+ "ß",
226
+ "à",
227
+ "Æ",
228
+ "â",
229
+ "ª",
230
+ "ä",
231
+ "å",
232
+ "æ",
233
+ "ç",
234
+ "Ł",
235
+ "Ø",
236
+ "Œ",
237
+ "º",
238
+ "ì",
239
+ "í",
240
+ "î",
241
+ "ï",
242
+ "ð",
243
+ "æ",
244
+ "ò",
245
+ "ó",
246
+ "ô",
247
+ "ı",
248
+ "ö",
249
+ "÷",
250
+ "ł",
251
+ "ø",
252
+ "œ",
253
+ "ß",
254
+ "ü",
255
+ "ý",
256
+ "þ",
257
+ "ÿ",
258
+ ]
micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_codecs/symbol.py ADDED
@@ -0,0 +1,260 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # manually generated from https://www.unicode.org/Public/MAPPINGS/VENDORS/ADOBE/symbol.txt
2
+ _symbol_encoding = [
3
+ "\u0000",
4
+ "\u0001",
5
+ "\u0002",
6
+ "\u0003",
7
+ "\u0004",
8
+ "\u0005",
9
+ "\u0006",
10
+ "\u0007",
11
+ "\u0008",
12
+ "\u0009",
13
+ "\u000A",
14
+ "\u000B",
15
+ "\u000C",
16
+ "\u000D",
17
+ "\u000E",
18
+ "\u000F",
19
+ "\u0010",
20
+ "\u0011",
21
+ "\u0012",
22
+ "\u0013",
23
+ "\u0014",
24
+ "\u0015",
25
+ "\u0016",
26
+ "\u0017",
27
+ "\u0018",
28
+ "\u0019",
29
+ "\u001A",
30
+ "\u001B",
31
+ "\u001C",
32
+ "\u001D",
33
+ "\u001E",
34
+ "\u001F",
35
+ "\u0020",
36
+ "\u0021",
37
+ "\u2200",
38
+ "\u0023",
39
+ "\u2203",
40
+ "\u0025",
41
+ "\u0026",
42
+ "\u220B",
43
+ "\u0028",
44
+ "\u0029",
45
+ "\u2217",
46
+ "\u002B",
47
+ "\u002C",
48
+ "\u2212",
49
+ "\u002E",
50
+ "\u002F",
51
+ "\u0030",
52
+ "\u0031",
53
+ "\u0032",
54
+ "\u0033",
55
+ "\u0034",
56
+ "\u0035",
57
+ "\u0036",
58
+ "\u0037",
59
+ "\u0038",
60
+ "\u0039",
61
+ "\u003A",
62
+ "\u003B",
63
+ "\u003C",
64
+ "\u003D",
65
+ "\u003E",
66
+ "\u003F",
67
+ "\u2245",
68
+ "\u0391",
69
+ "\u0392",
70
+ "\u03A7",
71
+ "\u0394",
72
+ "\u0395",
73
+ "\u03A6",
74
+ "\u0393",
75
+ "\u0397",
76
+ "\u0399",
77
+ "\u03D1",
78
+ "\u039A",
79
+ "\u039B",
80
+ "\u039C",
81
+ "\u039D",
82
+ "\u039F",
83
+ "\u03A0",
84
+ "\u0398",
85
+ "\u03A1",
86
+ "\u03A3",
87
+ "\u03A4",
88
+ "\u03A5",
89
+ "\u03C2",
90
+ "\u03A9",
91
+ "\u039E",
92
+ "\u03A8",
93
+ "\u0396",
94
+ "\u005B",
95
+ "\u2234",
96
+ "\u005D",
97
+ "\u22A5",
98
+ "\u005F",
99
+ "\uF8E5",
100
+ "\u03B1",
101
+ "\u03B2",
102
+ "\u03C7",
103
+ "\u03B4",
104
+ "\u03B5",
105
+ "\u03C6",
106
+ "\u03B3",
107
+ "\u03B7",
108
+ "\u03B9",
109
+ "\u03D5",
110
+ "\u03BA",
111
+ "\u03BB",
112
+ "\u00B5",
113
+ "\u03BD",
114
+ "\u03BF",
115
+ "\u03C0",
116
+ "\u03B8",
117
+ "\u03C1",
118
+ "\u03C3",
119
+ "\u03C4",
120
+ "\u03C5",
121
+ "\u03D6",
122
+ "\u03C9",
123
+ "\u03BE",
124
+ "\u03C8",
125
+ "\u03B6",
126
+ "\u007B",
127
+ "\u007C",
128
+ "\u007D",
129
+ "\u223C",
130
+ "\u007F",
131
+ "\u0080",
132
+ "\u0081",
133
+ "\u0082",
134
+ "\u0083",
135
+ "\u0084",
136
+ "\u0085",
137
+ "\u0086",
138
+ "\u0087",
139
+ "\u0088",
140
+ "\u0089",
141
+ "\u008A",
142
+ "\u008B",
143
+ "\u008C",
144
+ "\u008D",
145
+ "\u008E",
146
+ "\u008F",
147
+ "\u0090",
148
+ "\u0091",
149
+ "\u0092",
150
+ "\u0093",
151
+ "\u0094",
152
+ "\u0095",
153
+ "\u0096",
154
+ "\u0097",
155
+ "\u0098",
156
+ "\u0099",
157
+ "\u009A",
158
+ "\u009B",
159
+ "\u009C",
160
+ "\u009D",
161
+ "\u009E",
162
+ "\u009F",
163
+ "\u20AC",
164
+ "\u03D2",
165
+ "\u2032",
166
+ "\u2264",
167
+ "\u2044",
168
+ "\u221E",
169
+ "\u0192",
170
+ "\u2663",
171
+ "\u2666",
172
+ "\u2665",
173
+ "\u2660",
174
+ "\u2194",
175
+ "\u2190",
176
+ "\u2191",
177
+ "\u2192",
178
+ "\u2193",
179
+ "\u00B0",
180
+ "\u00B1",
181
+ "\u2033",
182
+ "\u2265",
183
+ "\u00D7",
184
+ "\u221D",
185
+ "\u2202",
186
+ "\u2022",
187
+ "\u00F7",
188
+ "\u2260",
189
+ "\u2261",
190
+ "\u2248",
191
+ "\u2026",
192
+ "\uF8E6",
193
+ "\uF8E7",
194
+ "\u21B5",
195
+ "\u2135",
196
+ "\u2111",
197
+ "\u211C",
198
+ "\u2118",
199
+ "\u2297",
200
+ "\u2295",
201
+ "\u2205",
202
+ "\u2229",
203
+ "\u222A",
204
+ "\u2283",
205
+ "\u2287",
206
+ "\u2284",
207
+ "\u2282",
208
+ "\u2286",
209
+ "\u2208",
210
+ "\u2209",
211
+ "\u2220",
212
+ "\u2207",
213
+ "\uF6DA",
214
+ "\uF6D9",
215
+ "\uF6DB",
216
+ "\u220F",
217
+ "\u221A",
218
+ "\u22C5",
219
+ "\u00AC",
220
+ "\u2227",
221
+ "\u2228",
222
+ "\u21D4",
223
+ "\u21D0",
224
+ "\u21D1",
225
+ "\u21D2",
226
+ "\u21D3",
227
+ "\u25CA",
228
+ "\u2329",
229
+ "\uF8E8",
230
+ "\uF8E9",
231
+ "\uF8EA",
232
+ "\u2211",
233
+ "\uF8EB",
234
+ "\uF8EC",
235
+ "\uF8ED",
236
+ "\uF8EE",
237
+ "\uF8EF",
238
+ "\uF8F0",
239
+ "\uF8F1",
240
+ "\uF8F2",
241
+ "\uF8F3",
242
+ "\uF8F4",
243
+ "\u00F0",
244
+ "\u232A",
245
+ "\u222B",
246
+ "\u2320",
247
+ "\uF8F5",
248
+ "\u2321",
249
+ "\uF8F6",
250
+ "\uF8F7",
251
+ "\uF8F8",
252
+ "\uF8F9",
253
+ "\uF8FA",
254
+ "\uF8FB",
255
+ "\uF8FC",
256
+ "\uF8FD",
257
+ "\uF8FE",
258
+ "\u00FF",
259
+ ]
260
+ assert len(_symbol_encoding) == 256
micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_codecs/zapfding.py ADDED
@@ -0,0 +1,261 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # manually generated from https://www.unicode.org/Public/MAPPINGS/VENDORS/ADOBE/zdingbat.txt
2
+
3
+ _zapfding_encoding = [
4
+ "\u0000",
5
+ "\u0001",
6
+ "\u0002",
7
+ "\u0003",
8
+ "\u0004",
9
+ "\u0005",
10
+ "\u0006",
11
+ "\u0007",
12
+ "\u0008",
13
+ "\u0009",
14
+ "\u000A",
15
+ "\u000B",
16
+ "\u000C",
17
+ "\u000D",
18
+ "\u000E",
19
+ "\u000F",
20
+ "\u0010",
21
+ "\u0011",
22
+ "\u0012",
23
+ "\u0013",
24
+ "\u0014",
25
+ "\u0015",
26
+ "\u0016",
27
+ "\u0017",
28
+ "\u0018",
29
+ "\u0019",
30
+ "\u001A",
31
+ "\u001B",
32
+ "\u001C",
33
+ "\u001D",
34
+ "\u001E",
35
+ "\u001F",
36
+ "\u0020",
37
+ "\u2701",
38
+ "\u2702",
39
+ "\u2703",
40
+ "\u2704",
41
+ "\u260E",
42
+ "\u2706",
43
+ "\u2707",
44
+ "\u2708",
45
+ "\u2709",
46
+ "\u261B",
47
+ "\u261E",
48
+ "\u270C",
49
+ "\u270D",
50
+ "\u270E",
51
+ "\u270F",
52
+ "\u2710",
53
+ "\u2711",
54
+ "\u2712",
55
+ "\u2713",
56
+ "\u2714",
57
+ "\u2715",
58
+ "\u2716",
59
+ "\u2717",
60
+ "\u2718",
61
+ "\u2719",
62
+ "\u271A",
63
+ "\u271B",
64
+ "\u271C",
65
+ "\u271D",
66
+ "\u271E",
67
+ "\u271F",
68
+ "\u2720",
69
+ "\u2721",
70
+ "\u2722",
71
+ "\u2723",
72
+ "\u2724",
73
+ "\u2725",
74
+ "\u2726",
75
+ "\u2727",
76
+ "\u2605",
77
+ "\u2729",
78
+ "\u272A",
79
+ "\u272B",
80
+ "\u272C",
81
+ "\u272D",
82
+ "\u272E",
83
+ "\u272F",
84
+ "\u2730",
85
+ "\u2731",
86
+ "\u2732",
87
+ "\u2733",
88
+ "\u2734",
89
+ "\u2735",
90
+ "\u2736",
91
+ "\u2737",
92
+ "\u2738",
93
+ "\u2739",
94
+ "\u273A",
95
+ "\u273B",
96
+ "\u273C",
97
+ "\u273D",
98
+ "\u273E",
99
+ "\u273F",
100
+ "\u2740",
101
+ "\u2741",
102
+ "\u2742",
103
+ "\u2743",
104
+ "\u2744",
105
+ "\u2745",
106
+ "\u2746",
107
+ "\u2747",
108
+ "\u2748",
109
+ "\u2749",
110
+ "\u274A",
111
+ "\u274B",
112
+ "\u25CF",
113
+ "\u274D",
114
+ "\u25A0",
115
+ "\u274F",
116
+ "\u2750",
117
+ "\u2751",
118
+ "\u2752",
119
+ "\u25B2",
120
+ "\u25BC",
121
+ "\u25C6",
122
+ "\u2756",
123
+ "\u25D7",
124
+ "\u2758",
125
+ "\u2759",
126
+ "\u275A",
127
+ "\u275B",
128
+ "\u275C",
129
+ "\u275D",
130
+ "\u275E",
131
+ "\u007F",
132
+ "\uF8D7",
133
+ "\uF8D8",
134
+ "\uF8D9",
135
+ "\uF8DA",
136
+ "\uF8DB",
137
+ "\uF8DC",
138
+ "\uF8DD",
139
+ "\uF8DE",
140
+ "\uF8DF",
141
+ "\uF8E0",
142
+ "\uF8E1",
143
+ "\uF8E2",
144
+ "\uF8E3",
145
+ "\uF8E4",
146
+ "\u008E",
147
+ "\u008F",
148
+ "\u0090",
149
+ "\u0091",
150
+ "\u0092",
151
+ "\u0093",
152
+ "\u0094",
153
+ "\u0095",
154
+ "\u0096",
155
+ "\u0097",
156
+ "\u0098",
157
+ "\u0099",
158
+ "\u009A",
159
+ "\u009B",
160
+ "\u009C",
161
+ "\u009D",
162
+ "\u009E",
163
+ "\u009F",
164
+ "\u00A0",
165
+ "\u2761",
166
+ "\u2762",
167
+ "\u2763",
168
+ "\u2764",
169
+ "\u2765",
170
+ "\u2766",
171
+ "\u2767",
172
+ "\u2663",
173
+ "\u2666",
174
+ "\u2665",
175
+ "\u2660",
176
+ "\u2460",
177
+ "\u2461",
178
+ "\u2462",
179
+ "\u2463",
180
+ "\u2464",
181
+ "\u2465",
182
+ "\u2466",
183
+ "\u2467",
184
+ "\u2468",
185
+ "\u2469",
186
+ "\u2776",
187
+ "\u2777",
188
+ "\u2778",
189
+ "\u2779",
190
+ "\u277A",
191
+ "\u277B",
192
+ "\u277C",
193
+ "\u277D",
194
+ "\u277E",
195
+ "\u277F",
196
+ "\u2780",
197
+ "\u2781",
198
+ "\u2782",
199
+ "\u2783",
200
+ "\u2784",
201
+ "\u2785",
202
+ "\u2786",
203
+ "\u2787",
204
+ "\u2788",
205
+ "\u2789",
206
+ "\u278A",
207
+ "\u278B",
208
+ "\u278C",
209
+ "\u278D",
210
+ "\u278E",
211
+ "\u278F",
212
+ "\u2790",
213
+ "\u2791",
214
+ "\u2792",
215
+ "\u2793",
216
+ "\u2794",
217
+ "\u2192",
218
+ "\u2194",
219
+ "\u2195",
220
+ "\u2798",
221
+ "\u2799",
222
+ "\u279A",
223
+ "\u279B",
224
+ "\u279C",
225
+ "\u279D",
226
+ "\u279E",
227
+ "\u279F",
228
+ "\u27A0",
229
+ "\u27A1",
230
+ "\u27A2",
231
+ "\u27A3",
232
+ "\u27A4",
233
+ "\u27A5",
234
+ "\u27A6",
235
+ "\u27A7",
236
+ "\u27A8",
237
+ "\u27A9",
238
+ "\u27AA",
239
+ "\u27AB",
240
+ "\u27AC",
241
+ "\u27AD",
242
+ "\u27AE",
243
+ "\u27AF",
244
+ "\u00F0",
245
+ "\u27B1",
246
+ "\u27B2",
247
+ "\u27B3",
248
+ "\u27B4",
249
+ "\u27B5",
250
+ "\u27B6",
251
+ "\u27B7",
252
+ "\u27B8",
253
+ "\u27B9",
254
+ "\u27BA",
255
+ "\u27BB",
256
+ "\u27BC",
257
+ "\u27BD",
258
+ "\u27BE",
259
+ "\u00FF",
260
+ ]
261
+ assert len(_zapfding_encoding) == 256
micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_crypt_providers/__init__.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2023, exiledkingcc
2
+ # All rights reserved.
3
+ #
4
+ # Redistribution and use in source and binary forms, with or without
5
+ # modification, are permitted provided that the following conditions are
6
+ # met:
7
+ #
8
+ # * Redistributions of source code must retain the above copyright notice,
9
+ # this list of conditions and the following disclaimer.
10
+ # * Redistributions in binary form must reproduce the above copyright notice,
11
+ # this list of conditions and the following disclaimer in the documentation
12
+ # and/or other materials provided with the distribution.
13
+ # * The name of the author may not be used to endorse or promote products
14
+ # derived from this software without specific prior written permission.
15
+ #
16
+ # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17
+ # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18
+ # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19
+ # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
20
+ # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21
+ # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22
+ # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23
+ # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24
+ # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25
+ # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26
+ # POSSIBILITY OF SUCH DAMAGE.
27
+
28
+ from pypdf._crypt_providers._base import CryptBase, CryptIdentity
29
+
30
+ try:
31
+ from pypdf._crypt_providers._cryptography import (
32
+ CryptAES,
33
+ CryptRC4,
34
+ aes_cbc_decrypt,
35
+ aes_cbc_encrypt,
36
+ aes_ecb_decrypt,
37
+ aes_ecb_encrypt,
38
+ crypt_provider,
39
+ rc4_decrypt,
40
+ rc4_encrypt,
41
+ )
42
+ except ImportError:
43
+ try:
44
+ from pypdf._crypt_providers._pycryptodome import ( # type: ignore
45
+ CryptAES,
46
+ CryptRC4,
47
+ aes_cbc_decrypt,
48
+ aes_cbc_encrypt,
49
+ aes_ecb_decrypt,
50
+ aes_ecb_encrypt,
51
+ crypt_provider,
52
+ rc4_decrypt,
53
+ rc4_encrypt,
54
+ )
55
+ except ImportError:
56
+ from pypdf._crypt_providers._fallback import ( # type: ignore
57
+ CryptAES,
58
+ CryptRC4,
59
+ aes_cbc_decrypt,
60
+ aes_cbc_encrypt,
61
+ aes_ecb_decrypt,
62
+ aes_ecb_encrypt,
63
+ crypt_provider,
64
+ rc4_decrypt,
65
+ rc4_encrypt,
66
+ )
67
+
68
+ __all__ = [
69
+ "CryptAES",
70
+ "CryptBase",
71
+ "CryptIdentity",
72
+ "CryptRC4",
73
+ "aes_cbc_decrypt",
74
+ "aes_cbc_encrypt",
75
+ "aes_ecb_decrypt",
76
+ "aes_ecb_encrypt",
77
+ "crypt_provider",
78
+ "rc4_decrypt",
79
+ "rc4_encrypt",
80
+ ]
micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_crypt_providers/_base.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2023, exiledkingcc
2
+ # All rights reserved.
3
+ #
4
+ # Redistribution and use in source and binary forms, with or without
5
+ # modification, are permitted provided that the following conditions are
6
+ # met:
7
+ #
8
+ # * Redistributions of source code must retain the above copyright notice,
9
+ # this list of conditions and the following disclaimer.
10
+ # * Redistributions in binary form must reproduce the above copyright notice,
11
+ # this list of conditions and the following disclaimer in the documentation
12
+ # and/or other materials provided with the distribution.
13
+ # * The name of the author may not be used to endorse or promote products
14
+ # derived from this software without specific prior written permission.
15
+ #
16
+ # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17
+ # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18
+ # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19
+ # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
20
+ # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21
+ # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22
+ # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23
+ # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24
+ # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25
+ # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26
+ # POSSIBILITY OF SUCH DAMAGE.
27
+
28
+
29
+ class CryptBase:
30
+ def encrypt(self, data: bytes) -> bytes: # pragma: no cover
31
+ return data
32
+
33
+ def decrypt(self, data: bytes, *, strict: bool = True) -> bytes: # pragma: no cover
34
+ return data
35
+
36
+
37
+ class CryptIdentity(CryptBase):
38
+ pass
micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_crypt_providers/_cryptography.py ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2023, exiledkingcc
2
+ # All rights reserved.
3
+ #
4
+ # Redistribution and use in source and binary forms, with or without
5
+ # modification, are permitted provided that the following conditions are
6
+ # met:
7
+ #
8
+ # * Redistributions of source code must retain the above copyright notice,
9
+ # this list of conditions and the following disclaimer.
10
+ # * Redistributions in binary form must reproduce the above copyright notice,
11
+ # this list of conditions and the following disclaimer in the documentation
12
+ # and/or other materials provided with the distribution.
13
+ # * The name of the author may not be used to endorse or promote products
14
+ # derived from this software without specific prior written permission.
15
+ #
16
+ # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17
+ # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18
+ # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19
+ # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
20
+ # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21
+ # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22
+ # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23
+ # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24
+ # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25
+ # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26
+ # POSSIBILITY OF SUCH DAMAGE.
27
+
28
+ import secrets
29
+
30
+ from cryptography import __version__
31
+ from cryptography.hazmat.primitives.ciphers.algorithms import AES
32
+ from cryptography.hazmat.primitives.padding import PKCS7
33
+
34
+ from pypdf._utils import logger_warning
35
+ from pypdf.errors import PdfStreamError
36
+
37
+ try:
38
+ # 43.0.0 - https://cryptography.io/en/latest/changelog/#v43-0-0
39
+ from cryptography.hazmat.decrepit.ciphers.algorithms import ARC4
40
+ except ImportError:
41
+ from cryptography.hazmat.primitives.ciphers.algorithms import ARC4
42
+ from cryptography.hazmat.primitives.ciphers.base import Cipher
43
+ from cryptography.hazmat.primitives.ciphers.modes import CBC, ECB
44
+
45
+ from pypdf._crypt_providers._base import CryptBase
46
+
47
+ crypt_provider = ("cryptography", __version__)
48
+
49
+
50
+ class CryptRC4(CryptBase):
51
+ def __init__(self, key: bytes) -> None:
52
+ self.cipher = Cipher(ARC4(key), mode=None)
53
+
54
+ def encrypt(self, data: bytes) -> bytes:
55
+ encryptor = self.cipher.encryptor()
56
+ return encryptor.update(data) + encryptor.finalize()
57
+
58
+ def decrypt(self, data: bytes, *, strict: bool = True) -> bytes:
59
+ decryptor = self.cipher.decryptor()
60
+ return decryptor.update(data) + decryptor.finalize()
61
+
62
+
63
+ class CryptAES(CryptBase):
64
+ def __init__(self, key: bytes) -> None:
65
+ self.alg = AES(key)
66
+
67
+ def encrypt(self, data: bytes) -> bytes:
68
+ iv = secrets.token_bytes(16)
69
+ padder = PKCS7(128).padder()
70
+ padded_data = padder.update(data) + padder.finalize()
71
+
72
+ cipher = Cipher(self.alg, CBC(iv))
73
+ encryptor = cipher.encryptor()
74
+ return iv + encryptor.update(padded_data) + encryptor.finalize()
75
+
76
+ def decrypt(self, data: bytes, *, strict: bool = True) -> bytes:
77
+ iv = data[:16]
78
+ data = data[16:]
79
+ # for empty encrypted data
80
+ if not data:
81
+ return data
82
+
83
+ if not strict and len(data) % 16 != 0:
84
+ logger_warning("Adding missing padding.", src=__name__)
85
+ padder = PKCS7(128).padder()
86
+ data = padder.update(data) + padder.finalize()
87
+
88
+ cipher = Cipher(self.alg, CBC(iv))
89
+ decryptor = cipher.decryptor()
90
+ try:
91
+ padded_data = decryptor.update(data) + decryptor.finalize()
92
+ except ValueError as exception:
93
+ # Only raised in strict mode. Non-strict mode fixes padding.
94
+ raise PdfStreamError(exception)
95
+
96
+ unpadder = PKCS7(128).unpadder()
97
+ try:
98
+ return unpadder.update(padded_data) + unpadder.finalize()
99
+ except ValueError as exception:
100
+ if strict:
101
+ raise PdfStreamError(exception)
102
+ logger_warning(f"Ignoring padding error: {exception}", src=__name__)
103
+ return padded_data[: -padded_data[-1]]
104
+
105
+
106
+ def rc4_encrypt(key: bytes, data: bytes) -> bytes:
107
+ encryptor = Cipher(ARC4(key), mode=None).encryptor()
108
+ return encryptor.update(data) + encryptor.finalize()
109
+
110
+
111
+ def rc4_decrypt(key: bytes, data: bytes) -> bytes:
112
+ decryptor = Cipher(ARC4(key), mode=None).decryptor()
113
+ return decryptor.update(data) + decryptor.finalize()
114
+
115
+
116
+ def aes_ecb_encrypt(key: bytes, data: bytes) -> bytes:
117
+ encryptor = Cipher(AES(key), mode=ECB()).encryptor()
118
+ return encryptor.update(data) + encryptor.finalize()
119
+
120
+
121
+ def aes_ecb_decrypt(key: bytes, data: bytes) -> bytes:
122
+ decryptor = Cipher(AES(key), mode=ECB()).decryptor()
123
+ return decryptor.update(data) + decryptor.finalize()
124
+
125
+
126
+ def aes_cbc_encrypt(key: bytes, iv: bytes, data: bytes) -> bytes:
127
+ encryptor = Cipher(AES(key), mode=CBC(iv)).encryptor()
128
+ return encryptor.update(data) + encryptor.finalize()
129
+
130
+
131
+ def aes_cbc_decrypt(key: bytes, iv: bytes, data: bytes) -> bytes:
132
+ decryptor = Cipher(AES(key), mode=CBC(iv)).decryptor()
133
+ return decryptor.update(data) + decryptor.finalize()
micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_crypt_providers/_fallback.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2023, exiledkingcc
2
+ # All rights reserved.
3
+ #
4
+ # Redistribution and use in source and binary forms, with or without
5
+ # modification, are permitted provided that the following conditions are
6
+ # met:
7
+ #
8
+ # * Redistributions of source code must retain the above copyright notice,
9
+ # this list of conditions and the following disclaimer.
10
+ # * Redistributions in binary form must reproduce the above copyright notice,
11
+ # this list of conditions and the following disclaimer in the documentation
12
+ # and/or other materials provided with the distribution.
13
+ # * The name of the author may not be used to endorse or promote products
14
+ # derived from this software without specific prior written permission.
15
+ #
16
+ # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17
+ # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18
+ # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19
+ # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
20
+ # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21
+ # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22
+ # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23
+ # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24
+ # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25
+ # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26
+ # POSSIBILITY OF SUCH DAMAGE.
27
+
28
+ from pypdf._crypt_providers._base import CryptBase
29
+ from pypdf.errors import DependencyError
30
+
31
+ _DEPENDENCY_ERROR_STR = "cryptography>=3.1 is required for AES algorithm"
32
+
33
+
34
+ crypt_provider = ("local_crypt_fallback", "0.0.0")
35
+
36
+
37
+ class CryptRC4(CryptBase):
38
+ def __init__(self, key: bytes) -> None:
39
+ self.s = bytearray(range(256))
40
+ j = 0
41
+ for i in range(256):
42
+ j = (j + self.s[i] + key[i % len(key)]) % 256
43
+ self.s[i], self.s[j] = self.s[j], self.s[i]
44
+
45
+ def encrypt(self, data: bytes) -> bytes:
46
+ s = bytearray(self.s)
47
+ out = [0 for _ in range(len(data))]
48
+ i, j = 0, 0
49
+ for k in range(len(data)):
50
+ i = (i + 1) % 256
51
+ j = (j + s[i]) % 256
52
+ s[i], s[j] = s[j], s[i]
53
+ x = s[(s[i] + s[j]) % 256]
54
+ out[k] = data[k] ^ x
55
+ return bytes(out)
56
+
57
+ def decrypt(self, data: bytes, *, strict: bool = True) -> bytes:
58
+ return self.encrypt(data)
59
+
60
+
61
+ class CryptAES(CryptBase):
62
+ def __init__(self, key: bytes) -> None:
63
+ pass
64
+
65
+ def encrypt(self, data: bytes) -> bytes:
66
+ raise DependencyError(_DEPENDENCY_ERROR_STR)
67
+
68
+ def decrypt(self, data: bytes, *, strict: bool = True) -> bytes:
69
+ raise DependencyError(_DEPENDENCY_ERROR_STR)
70
+
71
+
72
+ def rc4_encrypt(key: bytes, data: bytes) -> bytes:
73
+ return CryptRC4(key).encrypt(data)
74
+
75
+
76
+ def rc4_decrypt(key: bytes, data: bytes) -> bytes:
77
+ return CryptRC4(key).decrypt(data)
78
+
79
+
80
+ def aes_ecb_encrypt(key: bytes, data: bytes) -> bytes:
81
+ raise DependencyError(_DEPENDENCY_ERROR_STR)
82
+
83
+
84
+ def aes_ecb_decrypt(key: bytes, data: bytes) -> bytes:
85
+ raise DependencyError(_DEPENDENCY_ERROR_STR)
86
+
87
+
88
+ def aes_cbc_encrypt(key: bytes, iv: bytes, data: bytes) -> bytes:
89
+ raise DependencyError(_DEPENDENCY_ERROR_STR)
90
+
91
+
92
+ def aes_cbc_decrypt(key: bytes, iv: bytes, data: bytes) -> bytes:
93
+ raise DependencyError(_DEPENDENCY_ERROR_STR)
micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_crypt_providers/_pycryptodome.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2023, exiledkingcc
2
+ # All rights reserved.
3
+ #
4
+ # Redistribution and use in source and binary forms, with or without
5
+ # modification, are permitted provided that the following conditions are
6
+ # met:
7
+ #
8
+ # * Redistributions of source code must retain the above copyright notice,
9
+ # this list of conditions and the following disclaimer.
10
+ # * Redistributions in binary form must reproduce the above copyright notice,
11
+ # this list of conditions and the following disclaimer in the documentation
12
+ # and/or other materials provided with the distribution.
13
+ # * The name of the author may not be used to endorse or promote products
14
+ # derived from this software without specific prior written permission.
15
+ #
16
+ # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17
+ # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18
+ # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19
+ # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
20
+ # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21
+ # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22
+ # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23
+ # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24
+ # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25
+ # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26
+ # POSSIBILITY OF SUCH DAMAGE.
27
+
28
+ import secrets
29
+
30
+ from Crypto import __version__
31
+ from Crypto.Cipher import AES, ARC4
32
+ from Crypto.Util.Padding import pad, unpad
33
+
34
+ from pypdf._crypt_providers._base import CryptBase
35
+ from pypdf._utils import logger_warning
36
+ from pypdf.errors import PdfStreamError
37
+
38
+ crypt_provider = ("pycryptodome", __version__)
39
+
40
+
41
+ class CryptRC4(CryptBase):
42
+ def __init__(self, key: bytes) -> None:
43
+ self.key = key
44
+
45
+ def encrypt(self, data: bytes) -> bytes:
46
+ return ARC4.ARC4Cipher(self.key).encrypt(data)
47
+
48
+ def decrypt(self, data: bytes, *, strict: bool = True) -> bytes:
49
+ return ARC4.ARC4Cipher(self.key).decrypt(data)
50
+
51
+
52
+ class CryptAES(CryptBase):
53
+ def __init__(self, key: bytes) -> None:
54
+ self.key = key
55
+
56
+ def encrypt(self, data: bytes) -> bytes:
57
+ iv = secrets.token_bytes(16)
58
+ padded_data = pad(data, 16)
59
+ aes = AES.new(self.key, AES.MODE_CBC, iv)
60
+ return iv + aes.encrypt(padded_data)
61
+
62
+ def decrypt(self, data: bytes, *, strict: bool = True) -> bytes:
63
+ iv = data[:16]
64
+ data = data[16:]
65
+ # for empty encrypted data
66
+ if not data:
67
+ return data
68
+
69
+ if not strict and len(data) % 16 != 0:
70
+ logger_warning("Adding missing padding.", src=__name__)
71
+ data = pad(data, 16)
72
+
73
+ aes = AES.new(self.key, AES.MODE_CBC, iv)
74
+ try:
75
+ padded_data = aes.decrypt(data)
76
+ except ValueError as exception:
77
+ # Only raised in strict mode. Non-strict mode fixes padding.
78
+ raise PdfStreamError(exception)
79
+
80
+ try:
81
+ return unpad(padded_data, 16)
82
+ except ValueError as exception:
83
+ if strict:
84
+ raise PdfStreamError(exception)
85
+ logger_warning(f"Ignoring padding error: {exception}", src=__name__)
86
+ return padded_data[: -padded_data[-1]]
87
+
88
+
89
+ def rc4_encrypt(key: bytes, data: bytes) -> bytes:
90
+ return ARC4.ARC4Cipher(key).encrypt(data)
91
+
92
+
93
+ def rc4_decrypt(key: bytes, data: bytes) -> bytes:
94
+ return ARC4.ARC4Cipher(key).decrypt(data)
95
+
96
+
97
+ def aes_ecb_encrypt(key: bytes, data: bytes) -> bytes:
98
+ return AES.new(key, AES.MODE_ECB).encrypt(data)
99
+
100
+
101
+ def aes_ecb_decrypt(key: bytes, data: bytes) -> bytes:
102
+ return AES.new(key, AES.MODE_ECB).decrypt(data)
103
+
104
+
105
+ def aes_cbc_encrypt(key: bytes, iv: bytes, data: bytes) -> bytes:
106
+ return AES.new(key, AES.MODE_CBC, iv).encrypt(data)
107
+
108
+
109
+ def aes_cbc_decrypt(key: bytes, iv: bytes, data: bytes) -> bytes:
110
+ return AES.new(key, AES.MODE_CBC, iv).decrypt(data)
micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_text_extraction/__init__.py ADDED
@@ -0,0 +1,245 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Code related to text extraction.
3
+
4
+ Some parts are still in _page.py. In doubt, they will stay there.
5
+ """
6
+
7
+ import math
8
+ from typing import Any, Callable, Optional, Union
9
+
10
+ from .._font import Font
11
+ from ..generic import DictionaryObject, TextStringObject, encode_pdfdocencoding
12
+
13
+ CUSTOM_RTL_MIN: int = -1
14
+ CUSTOM_RTL_MAX: int = -1
15
+ CUSTOM_RTL_SPECIAL_CHARS: list[int] = []
16
+ LAYOUT_NEW_BT_GROUP_SPACE_WIDTHS: int = 5
17
+
18
+
19
+ class OrientationNotFoundError(Exception):
20
+ pass
21
+
22
+
23
+ def set_custom_rtl(
24
+ _min: Union[str, int, None] = None,
25
+ _max: Union[str, int, None] = None,
26
+ specials: Union[str, list[int], None] = None,
27
+ ) -> tuple[int, int, list[int]]:
28
+ """
29
+ Change the Right-To-Left and special characters custom parameters.
30
+
31
+ Args:
32
+ _min: The new minimum value for the range of custom characters that
33
+ will be written right to left.
34
+ If set to ``None``, the value will not be changed.
35
+ If set to an integer or string, it will be converted to its ASCII code.
36
+ The default value is -1, which sets no additional range to be converted.
37
+ _max: The new maximum value for the range of custom characters that will
38
+ be written right to left.
39
+ If set to ``None``, the value will not be changed.
40
+ If set to an integer or string, it will be converted to its ASCII code.
41
+ The default value is -1, which sets no additional range to be converted.
42
+ specials: The new list of special characters to be inserted in the
43
+ current insertion order.
44
+ If set to ``None``, the current value will not be changed.
45
+ If set to a string, it will be converted to a list of ASCII codes.
46
+ The default value is an empty list.
47
+
48
+ Returns:
49
+ A tuple containing the new values for ``CUSTOM_RTL_MIN``,
50
+ ``CUSTOM_RTL_MAX``, and ``CUSTOM_RTL_SPECIAL_CHARS``.
51
+
52
+ """
53
+ global CUSTOM_RTL_MIN, CUSTOM_RTL_MAX, CUSTOM_RTL_SPECIAL_CHARS
54
+ if isinstance(_min, int):
55
+ CUSTOM_RTL_MIN = _min
56
+ elif isinstance(_min, str):
57
+ CUSTOM_RTL_MIN = ord(_min)
58
+ if isinstance(_max, int):
59
+ CUSTOM_RTL_MAX = _max
60
+ elif isinstance(_max, str):
61
+ CUSTOM_RTL_MAX = ord(_max)
62
+ if isinstance(specials, str):
63
+ CUSTOM_RTL_SPECIAL_CHARS = [ord(x) for x in specials]
64
+ elif isinstance(specials, list):
65
+ CUSTOM_RTL_SPECIAL_CHARS = specials
66
+ return CUSTOM_RTL_MIN, CUSTOM_RTL_MAX, CUSTOM_RTL_SPECIAL_CHARS
67
+
68
+
69
+ def mult(m: list[float], n: list[float]) -> list[float]:
70
+ return [
71
+ m[0] * n[0] + m[1] * n[2],
72
+ m[0] * n[1] + m[1] * n[3],
73
+ m[2] * n[0] + m[3] * n[2],
74
+ m[2] * n[1] + m[3] * n[3],
75
+ m[4] * n[0] + m[5] * n[2] + n[4],
76
+ m[4] * n[1] + m[5] * n[3] + n[5],
77
+ ]
78
+
79
+
80
+ def orient(m: list[float]) -> int:
81
+ if m[3] > 1e-6:
82
+ return 0
83
+ if m[3] < -1e-6:
84
+ return 180
85
+ if m[1] > 0:
86
+ return 90
87
+ return 270
88
+
89
+
90
+ def crlf_space_check(
91
+ text: str,
92
+ cmtm_prev: tuple[list[float], list[float]],
93
+ cmtm_matrix: tuple[list[float], list[float]],
94
+ memo_cmtm: tuple[list[float], list[float]],
95
+ font_resource: Optional[DictionaryObject],
96
+ orientations: tuple[int, ...],
97
+ output: str,
98
+ font_size: float,
99
+ visitor_text: Optional[Callable[[Any, Any, Any, Any, Any], None]],
100
+ str_widths: float,
101
+ spacewidth: float,
102
+ str_height: float,
103
+ ) -> tuple[str, str, list[float], list[float]]:
104
+ cm_prev = cmtm_prev[0]
105
+ tm_prev = cmtm_prev[1]
106
+ cm_matrix = cmtm_matrix[0]
107
+ tm_matrix = cmtm_matrix[1]
108
+ memo_cm = memo_cmtm[0]
109
+ memo_tm = memo_cmtm[1]
110
+
111
+ m_prev = mult(tm_prev, cm_prev)
112
+ m = mult(tm_matrix, cm_matrix)
113
+ orientation = orient(m)
114
+ delta_x = m[4] - m_prev[4]
115
+ delta_y = m[5] - m_prev[5]
116
+ # Table 108 of the 1.7 reference ("Text positioning operators")
117
+ scale_prev_x = math.sqrt(tm_prev[0]**2 + tm_prev[1]**2)
118
+ scale_prev_y = math.sqrt(tm_prev[2]**2 + tm_prev[3]**2)
119
+ scale_y = math.sqrt(tm_matrix[2]**2 + tm_matrix[3]**2)
120
+ cm_prev = m
121
+
122
+ if orientation not in orientations:
123
+ raise OrientationNotFoundError
124
+ if orientation in (0, 180):
125
+ moved_height: float = delta_y
126
+ moved_width: float = delta_x
127
+ elif orientation in (90, 270):
128
+ moved_height = delta_x
129
+ moved_width = delta_y
130
+ try:
131
+ if abs(moved_height) > 0.8 * min(str_height * scale_prev_y, font_size * scale_y):
132
+ if (output + text)[-1] != "\n":
133
+ output += text + "\n"
134
+ if visitor_text is not None:
135
+ visitor_text(
136
+ text + "\n",
137
+ memo_cm,
138
+ memo_tm,
139
+ font_resource,
140
+ font_size,
141
+ )
142
+ text = ""
143
+ elif (
144
+ (moved_width >= (spacewidth + str_widths) * scale_prev_x)
145
+ and (output + text)[-1] != " "
146
+ ):
147
+ text += " "
148
+ except Exception:
149
+ pass
150
+ tm_prev = tm_matrix.copy()
151
+ cm_prev = cm_matrix.copy()
152
+ return text, output, cm_prev, tm_prev
153
+
154
+
155
+ def get_text_operands(
156
+ operands: list[Union[str, TextStringObject]],
157
+ cm_matrix: list[float],
158
+ tm_matrix: list[float],
159
+ font: Font,
160
+ orientations: tuple[int, ...]
161
+ ) -> tuple[str, bool]:
162
+ t: str = ""
163
+ is_str_operands = False
164
+ m = mult(tm_matrix, cm_matrix)
165
+ orientation = orient(m)
166
+ if orientation in orientations and len(operands) > 0:
167
+ if isinstance(operands[0], str):
168
+ t = operands[0]
169
+ is_str_operands = True
170
+ else:
171
+ t = ""
172
+ tt: bytes = (
173
+ encode_pdfdocencoding(operands[0])
174
+ if isinstance(operands[0], str)
175
+ else operands[0]
176
+ )
177
+ if isinstance(font.encoding, str):
178
+ try:
179
+ t = tt.decode(font.encoding, "surrogatepass") # apply str encoding
180
+ except Exception:
181
+ # the data does not match the expectation,
182
+ # we use the alternative ;
183
+ # text extraction may not be good
184
+ t = tt.decode(
185
+ "utf-16-be" if font.encoding == "charmap" else "charmap",
186
+ "surrogatepass",
187
+ ) # apply str encoding
188
+ else: # apply dict encoding
189
+ t = "".join(
190
+ [font.encoding[x] if x in font.encoding else bytes((x,)).decode() for x in tt]
191
+ )
192
+ return (t, is_str_operands)
193
+
194
+
195
+ def get_display_str(
196
+ text: str,
197
+ cm_matrix: list[float],
198
+ tm_matrix: list[float],
199
+ font_resource: Optional[DictionaryObject],
200
+ font: Font,
201
+ text_operands: str,
202
+ font_size: float,
203
+ rtl_dir: bool,
204
+ visitor_text: Optional[Callable[[Any, Any, Any, Any, Any], None]]
205
+ ) -> tuple[str, bool, float]:
206
+ # "\u0590 - \u08FF \uFB50 - \uFDFF"
207
+ widths: float = 0.0
208
+ for x in [font.character_map.get(x, x) for x in text_operands]:
209
+ # x can be a sequence of bytes ; ex: habibi.pdf
210
+ if len(x) == 1:
211
+ xx = ord(x)
212
+ else:
213
+ xx = 1
214
+ # fmt: off
215
+ if (
216
+ # cases where the current inserting order is kept
217
+ (xx <= 0x2F) # punctuations but...
218
+ or 0x3A <= xx <= 0x40 # numbers (x30-39)
219
+ or 0x2000 <= xx <= 0x206F # upper punctuations..
220
+ or 0x20A0 <= xx <= 0x21FF # but (numbers) indices/exponents
221
+ or xx in CUSTOM_RTL_SPECIAL_CHARS # customized....
222
+ ):
223
+ text = x + text if rtl_dir else text + x
224
+ elif ( # right-to-left characters set
225
+ 0x0590 <= xx <= 0x08FF
226
+ or 0xFB1D <= xx <= 0xFDFF
227
+ or 0xFE70 <= xx <= 0xFEFF
228
+ or CUSTOM_RTL_MIN <= xx <= CUSTOM_RTL_MAX
229
+ ):
230
+ if not rtl_dir:
231
+ rtl_dir = True
232
+ if visitor_text is not None:
233
+ visitor_text(text, cm_matrix, tm_matrix, font_resource, font_size)
234
+ text = ""
235
+ text = x + text
236
+ else: # left-to-right
237
+ if rtl_dir:
238
+ rtl_dir = False
239
+ if visitor_text is not None:
240
+ visitor_text(text, cm_matrix, tm_matrix, font_resource, font_size)
241
+ text = ""
242
+ text = text + x
243
+ widths += font.space_width if x == " " else font.text_width(x)
244
+ # fmt: on
245
+ return text, rtl_dir, widths
micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/_text_extraction/_text_extractor.py ADDED
@@ -0,0 +1,350 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2006, Mathieu Fenniak
2
+ # Copyright (c) 2007, Ashish Kulkarni <kulkarni.ashish@gmail.com>
3
+ #
4
+ # All rights reserved.
5
+ #
6
+ # Redistribution and use in source and binary forms, with or without
7
+ # modification, are permitted provided that the following conditions are
8
+ # met:
9
+ #
10
+ # * Redistributions of source code must retain the above copyright notice,
11
+ # this list of conditions and the following disclaimer.
12
+ # * Redistributions in binary form must reproduce the above copyright notice,
13
+ # this list of conditions and the following disclaimer in the documentation
14
+ # and/or other materials provided with the distribution.
15
+ # * The name of the author may not be used to endorse or promote products
16
+ # derived from this software without specific prior written permission.
17
+ #
18
+ # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19
+ # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20
+ # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21
+ # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
22
+ # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
23
+ # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
24
+ # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
25
+ # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
26
+ # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
27
+ # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28
+ # POSSIBILITY OF SUCH DAMAGE.
29
+
30
+ import math
31
+ from typing import Any, Callable, Optional, Union
32
+
33
+ from .._font import Font, FontDescriptor
34
+ from ..generic import DictionaryObject, TextStringObject
35
+ from . import OrientationNotFoundError, crlf_space_check, get_display_str, get_text_operands, mult
36
+
37
+
38
+ class TextExtraction:
39
+ """
40
+ A class to handle PDF text extraction operations.
41
+
42
+ This class encapsulates all the state and operations needed for extracting
43
+ text from PDF content streams, replacing the nested functions and nonlocal
44
+ variables in the original implementation.
45
+ """
46
+
47
+ def __init__(self) -> None:
48
+ self._font_width_maps: dict[str, tuple[dict[Any, float], str, float]] = {}
49
+
50
+ # Text extraction state variables
51
+ self.cm_matrix: list[float] = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]
52
+ self.tm_matrix: list[float] = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]
53
+ self.cm_stack: list[
54
+ tuple[
55
+ list[float],
56
+ Optional[DictionaryObject],
57
+ Font,
58
+ float,
59
+ float,
60
+ float,
61
+ float,
62
+ ]
63
+ ] = []
64
+
65
+ # Store the last modified matrices; can be an intermediate position
66
+ self.cm_prev: list[float] = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]
67
+ self.tm_prev: list[float] = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]
68
+
69
+ # Store the position at the beginning of building the text
70
+ self.memo_cm: list[float] = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]
71
+ self.memo_tm: list[float] = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]
72
+
73
+ self.char_scale = 1.0
74
+ self.space_scale = 1.0
75
+ self._space_width: float = 500.0 # will be set correctly at first Tf
76
+ self._actual_str_size: dict[str, float] = {
77
+ "str_widths": 0.0,
78
+ "str_height": 0.0,
79
+ } # will be set to string length calculation result
80
+ self.TL = 0.0
81
+ self.font_size = 12.0 # init just in case of
82
+
83
+ # Text extraction variables
84
+ self.text: str = ""
85
+ self.output: str = ""
86
+ self.rtl_dir: bool = False # right-to-left
87
+ self.font_resource: Optional[DictionaryObject] = None
88
+ self.font = Font(
89
+ name = "NotInitialized",
90
+ sub_type="Unknown",
91
+ encoding="charmap",
92
+ font_descriptor=FontDescriptor(),
93
+ )
94
+ self.orientations: tuple[int, ...] = (0, 90, 180, 270)
95
+ self.visitor_text: Optional[Callable[[Any, Any, Any, Any, Any], None]] = None
96
+ self.font_resources: dict[str, DictionaryObject] = {}
97
+ self.fonts: dict[str, Font] = {}
98
+
99
+ self.operation_handlers = {
100
+ b"BT": self._handle_bt,
101
+ b"ET": self._handle_et,
102
+ b"q": self._handle_save_graphics_state,
103
+ b"Q": self._handle_restore_graphics_state,
104
+ b"cm": self._handle_cm,
105
+ b"Tz": self._handle_tz,
106
+ b"Tw": self._handle_tw,
107
+ b"TL": self._handle_tl,
108
+ b"Tf": self._handle_tf,
109
+ b"Td": self._handle_td,
110
+ b"Tm": self._handle_tm,
111
+ b"T*": self._handle_t_star,
112
+ b"Tj": self._handle_tj_operation,
113
+ }
114
+
115
+ def initialize_extraction(
116
+ self,
117
+ orientations: tuple[int, ...] = (0, 90, 180, 270),
118
+ visitor_text: Optional[Callable[[Any, Any, Any, Any, Any], None]] = None,
119
+ font_resources: Optional[dict[str, DictionaryObject]] = None,
120
+ fonts: Optional[dict[str, Font]] = None
121
+ ) -> None:
122
+ """Initialize the extractor with extraction parameters."""
123
+ self.orientations = orientations
124
+ self.visitor_text = visitor_text
125
+ self.font_resources = font_resources or {}
126
+ self.fonts = fonts or {}
127
+
128
+ # Reset state
129
+ self.text = ""
130
+ self.output = ""
131
+ self.rtl_dir = False
132
+
133
+ def compute_str_widths(self, str_widths: float) -> float:
134
+ return str_widths / 1000
135
+
136
+ def process_operation(self, operator: bytes, operands: list[Any]) -> None:
137
+ if operator in self.operation_handlers:
138
+ handler = self.operation_handlers[operator]
139
+ str_widths = handler(operands)
140
+
141
+ # Post-process operations that affect text positioning
142
+ if operator in {b"Td", b"Tm", b"T*", b"Tj"}:
143
+ self._post_process_text_operation(str_widths or 0.0)
144
+
145
+ def _post_process_text_operation(self, str_widths: float) -> None:
146
+ """Handle common post-processing for text positioning operations."""
147
+ try:
148
+ self.text, self.output, self.cm_prev, self.tm_prev = crlf_space_check(
149
+ self.text,
150
+ (self.cm_prev, self.tm_prev),
151
+ (self.cm_matrix, self.tm_matrix),
152
+ (self.memo_cm, self.memo_tm),
153
+ self.font_resource,
154
+ self.orientations,
155
+ self.output,
156
+ self.font_size,
157
+ self.visitor_text,
158
+ str_widths,
159
+ self.compute_str_widths(self.font_size * self._space_width),
160
+ self._actual_str_size["str_height"],
161
+ )
162
+ if self.text == "":
163
+ self.memo_cm = self.cm_matrix.copy()
164
+ self.memo_tm = self.tm_matrix.copy()
165
+ except OrientationNotFoundError:
166
+ pass
167
+
168
+ def _handle_tj(
169
+ self,
170
+ text: str,
171
+ operands: list[Union[str, TextStringObject]],
172
+ cm_matrix: list[float],
173
+ tm_matrix: list[float],
174
+ font_resource: Optional[DictionaryObject],
175
+ font: Font,
176
+ orientations: tuple[int, ...],
177
+ font_size: float,
178
+ rtl_dir: bool,
179
+ visitor_text: Optional[Callable[[Any, Any, Any, Any, Any], None]],
180
+ actual_str_size: dict[str, float],
181
+ ) -> tuple[str, bool, dict[str, float]]:
182
+ text_operands, is_str_operands = get_text_operands(
183
+ operands, cm_matrix, tm_matrix, font, orientations
184
+ )
185
+ if is_str_operands:
186
+ text += text_operands
187
+ font_widths = sum([font.space_width if x == " " else font.text_width(x) for x in text_operands])
188
+ else:
189
+ text, rtl_dir, font_widths = get_display_str(
190
+ text,
191
+ cm_matrix,
192
+ tm_matrix, # text matrix
193
+ font_resource,
194
+ font,
195
+ text_operands,
196
+ font_size,
197
+ rtl_dir,
198
+ visitor_text,
199
+ )
200
+ actual_str_size["str_widths"] += font_widths * font_size
201
+ actual_str_size["str_height"] = font_size
202
+ return text, rtl_dir, actual_str_size
203
+
204
+ def _flush_text(self) -> None:
205
+ """Flush accumulated text to output and call visitor if present."""
206
+ self.output += self.text
207
+ if self.visitor_text is not None:
208
+ self.visitor_text(self.text, self.memo_cm, self.memo_tm, self.font_resource, self.font_size)
209
+ self.text = ""
210
+ self.memo_cm = self.cm_matrix.copy()
211
+ self.memo_tm = self.tm_matrix.copy()
212
+
213
+ # Operation handlers
214
+
215
+ def _handle_bt(self, operands: list[Any]) -> None:
216
+ """Handle BT (Begin Text) operation - Table 5.4 page 405."""
217
+ self.tm_matrix = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]
218
+ self._flush_text()
219
+
220
+ def _handle_et(self, operands: list[Any]) -> None:
221
+ """Handle ET (End Text) operation - Table 5.4 page 405."""
222
+ self._flush_text()
223
+
224
+ def _handle_save_graphics_state(self, operands: list[Any]) -> None:
225
+ """Handle q (Save graphics state) operation - Table 4.7 page 219."""
226
+ self.cm_stack.append(
227
+ (
228
+ self.cm_matrix,
229
+ self.font_resource,
230
+ self.font,
231
+ self.font_size,
232
+ self.char_scale,
233
+ self.space_scale,
234
+ self.TL,
235
+ )
236
+ )
237
+
238
+ def _handle_restore_graphics_state(self, operands: list[Any]) -> None:
239
+ """Handle Q (Restore graphics state) operation - Table 4.7 page 219."""
240
+ try:
241
+ (
242
+ self.cm_matrix,
243
+ self.font_resource,
244
+ self.font,
245
+ self.font_size,
246
+ self.char_scale,
247
+ self.space_scale,
248
+ self.TL,
249
+ ) = self.cm_stack.pop()
250
+ except Exception:
251
+ self.cm_matrix = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]
252
+
253
+ def _handle_cm(self, operands: list[Any]) -> None:
254
+ """Handle cm (Modify current matrix) operation - Table 4.7 page 219."""
255
+ self.output += self.text
256
+ if self.visitor_text is not None:
257
+ self.visitor_text(self.text, self.memo_cm, self.memo_tm, self.font_resource, self.font_size)
258
+ self.text = ""
259
+ try:
260
+ self.cm_matrix = mult([float(operand) for operand in operands[:6]], self.cm_matrix)
261
+ except Exception:
262
+ self.cm_matrix = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]
263
+ self.memo_cm = self.cm_matrix.copy()
264
+ self.memo_tm = self.tm_matrix.copy()
265
+
266
+ def _handle_tz(self, operands: list[Any]) -> None:
267
+ """Handle Tz (Set horizontal text scaling) operation - Table 5.2 page 398."""
268
+ self.char_scale = float(operands[0]) / 100 if operands else 1.0
269
+
270
+ def _handle_tw(self, operands: list[Any]) -> None:
271
+ """Handle Tw (Set word spacing) operation - Table 5.2 page 398."""
272
+ self.space_scale = 1.0 + float(operands[0] if operands else 0.0)
273
+
274
+ def _handle_tl(self, operands: list[Any]) -> None:
275
+ """Handle TL (Set Text Leading) operation - Table 5.2 page 398."""
276
+ scale_x = math.sqrt(self.tm_matrix[0] ** 2 + self.tm_matrix[2] ** 2)
277
+ self.TL = float(operands[0] if operands else 0.0) * self.font_size * scale_x
278
+
279
+ def _handle_tf(self, operands: list[Any]) -> None:
280
+ """Handle Tf (Set font size) operation - Table 5.2 page 398."""
281
+ if self.text != "":
282
+ self.output += self.text # .translate(cmap)
283
+ if self.visitor_text is not None:
284
+ self.visitor_text(self.text, self.memo_cm, self.memo_tm, self.font_resource, self.font_size)
285
+ self.text = ""
286
+ self.memo_cm = self.cm_matrix.copy()
287
+ self.memo_tm = self.tm_matrix.copy()
288
+ try:
289
+ self.font_resource = self.font_resources[operands[0]]
290
+ self.font = self.fonts[operands[0]]
291
+ except KeyError: # font not found
292
+ self.font_resource = None
293
+ font_descriptor = FontDescriptor()
294
+ self.font = Font(
295
+ "Unknown",
296
+ space_width=250,
297
+ encoding=dict.fromkeys(range(256), "�"),
298
+ font_descriptor=font_descriptor,
299
+ character_map={},
300
+ )
301
+
302
+ self._space_width = self.font.space_width / 2 # Actually the width of _half_ a space...
303
+ try:
304
+ self.font_size = float(operands[1])
305
+ except Exception:
306
+ pass # keep previous size
307
+
308
+ def _handle_td(self, operands: list[Any]) -> float:
309
+ """Handle Td (Move text position) operation - Table 5.5 page 406."""
310
+ # A special case is a translating only tm:
311
+ # tm = [1, 0, 0, 1, e, f]
312
+ # i.e. tm[4] += tx, tm[5] += ty.
313
+ tx, ty = float(operands[0]), float(operands[1])
314
+ self.tm_matrix[4] += tx * self.tm_matrix[0] + ty * self.tm_matrix[2]
315
+ self.tm_matrix[5] += tx * self.tm_matrix[1] + ty * self.tm_matrix[3]
316
+ str_widths = self.compute_str_widths(self._actual_str_size["str_widths"])
317
+ self._actual_str_size["str_widths"] = 0.0
318
+ return str_widths
319
+
320
+ def _handle_tm(self, operands: list[Any]) -> float:
321
+ """Handle Tm (Set text matrix) operation - Table 5.5 page 406."""
322
+ self.tm_matrix = [float(operand) for operand in operands[:6]]
323
+ str_widths = self.compute_str_widths(self._actual_str_size["str_widths"])
324
+ self._actual_str_size["str_widths"] = 0.0
325
+ return str_widths
326
+
327
+ def _handle_t_star(self, operands: list[Any]) -> float:
328
+ """Handle T* (Move to next line) operation - Table 5.5 page 406."""
329
+ self.tm_matrix[4] -= self.TL * self.tm_matrix[2]
330
+ self.tm_matrix[5] -= self.TL * self.tm_matrix[3]
331
+ str_widths = self.compute_str_widths(self._actual_str_size["str_widths"])
332
+ self._actual_str_size["str_widths"] = 0.0
333
+ return str_widths
334
+
335
+ def _handle_tj_operation(self, operands: list[Any]) -> float:
336
+ """Handle Tj (Show text) operation - Table 5.5 page 406."""
337
+ self.text, self.rtl_dir, self._actual_str_size = self._handle_tj(
338
+ self.text,
339
+ operands,
340
+ self.cm_matrix,
341
+ self.tm_matrix,
342
+ self.font_resource,
343
+ self.font,
344
+ self.orientations,
345
+ self.font_size,
346
+ self.rtl_dir,
347
+ self.visitor_text,
348
+ self._actual_str_size,
349
+ )
350
+ return 0.0 # str_widths will be handled in post-processing
micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/annotations/__init__.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ PDF specifies several annotation types which pypdf makes available here.
3
+
4
+ The names of the annotations and their attributes do not reflect the names in
5
+ the specification in all cases. For example, the PDF standard defines a
6
+ 'Square' annotation that does not actually need to be square. For this reason,
7
+ pypdf calls it 'Rectangle'.
8
+
9
+ At their core, all annotation types are DictionaryObjects. That means if pypdf
10
+ does not implement a feature, users can easily extend the given functionality.
11
+ """
12
+
13
+
14
+ from ._base import NO_FLAGS, AnnotationDictionary
15
+ from ._markup_annotations import (
16
+ Ellipse,
17
+ FreeText,
18
+ Highlight,
19
+ Line,
20
+ MarkupAnnotation,
21
+ Polygon,
22
+ PolyLine,
23
+ Rectangle,
24
+ Text,
25
+ )
26
+ from ._non_markup_annotations import Link, Popup
27
+
28
+ __all__ = [
29
+ "NO_FLAGS",
30
+ "AnnotationDictionary",
31
+ "Ellipse",
32
+ "FreeText",
33
+ "Highlight",
34
+ "Line",
35
+ "Link",
36
+ "MarkupAnnotation",
37
+ "PolyLine",
38
+ "Polygon",
39
+ "Popup",
40
+ "Rectangle",
41
+ "Text",
42
+ ]
micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/annotations/_base.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from abc import ABC
2
+
3
+ from ..constants import AnnotationFlag
4
+ from ..generic import NameObject, NumberObject
5
+ from ..generic._data_structures import DictionaryObject
6
+
7
+
8
+ class AnnotationDictionary(DictionaryObject, ABC):
9
+ def __init__(self) -> None:
10
+ super().__init__()
11
+
12
+ from ..generic._base import NameObject # noqa: PLC0415
13
+
14
+ # /Rect should not be added here as Polygon and PolyLine can automatically set it
15
+ self[NameObject("/Type")] = NameObject("/Annot")
16
+ # The flags were NOT added to the constructor on purpose:
17
+ # We expect that most users don't want to change the default.
18
+ # If they do, they can use the property. The default is 0.
19
+
20
+ @property
21
+ def flags(self) -> AnnotationFlag:
22
+ return AnnotationFlag(self.get(NameObject("/F"), 0))
23
+
24
+ @flags.setter
25
+ def flags(self, value: AnnotationFlag) -> None:
26
+ self[NameObject("/F")] = NumberObject(value)
27
+
28
+
29
+ NO_FLAGS = AnnotationFlag(0)
micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/annotations/_markup_annotations.py ADDED
@@ -0,0 +1,351 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ import uuid
3
+ from abc import ABC
4
+ from typing import Any, Literal, Optional, Union
5
+
6
+ from ..constants import AnnotationFlag
7
+ from ..generic import ArrayObject, DictionaryObject
8
+ from ..generic._base import (
9
+ BooleanObject,
10
+ FloatObject,
11
+ IndirectObject,
12
+ NameObject,
13
+ NumberObject,
14
+ TextStringObject,
15
+ )
16
+ from ..generic._rectangle import RectangleObject
17
+ from ..generic._utils import hex_to_rgb
18
+ from ._base import NO_FLAGS, AnnotationDictionary
19
+
20
+ if sys.version_info[:2] >= (3, 10):
21
+ from typing import TypeAlias
22
+ else:
23
+ # PEP 613 introduced typing.TypeAlias with Python 3.10
24
+ # For older Python versions, the backport typing_extensions is necessary:
25
+ from typing_extensions import TypeAlias
26
+
27
+
28
+ Vertex: TypeAlias = tuple[float, float]
29
+
30
+
31
+ def _get_bounding_rectangle(vertices: list[Vertex]) -> RectangleObject:
32
+ x_min, y_min = vertices[0][0], vertices[0][1]
33
+ x_max, y_max = vertices[0][0], vertices[0][1]
34
+ for x, y in vertices:
35
+ x_min = min(x_min, x)
36
+ y_min = min(y_min, y)
37
+ x_max = max(x_max, x)
38
+ y_max = max(y_max, y)
39
+ return RectangleObject((x_min, y_min, x_max, y_max))
40
+
41
+
42
+ class MarkupAnnotation(AnnotationDictionary, ABC):
43
+ """
44
+ Base class for all markup annotations.
45
+
46
+ Args:
47
+ title_bar: Text to be displayed in the title bar of the annotation;
48
+ by convention this is the name of the author
49
+ in_reply_to: The annotation that this annotation is "in reply to"
50
+ (PDF 1.5). Can be either an annotation (previously added using
51
+ :meth:`~pypdf.PdfWriter.add_annotation`) or a reference to the
52
+ target annotation.
53
+ reply_type: The relationship between this annotation and the one
54
+ specified by ``in_reply_to``. Either ``"R"`` (a reply, default)
55
+ or ``"Group"`` (grouped with the parent annotation). Raises
56
+ ``ValueError`` if a non-default value is provided without
57
+ ``in_reply_to``.
58
+ annotation_name: A text string uniquely identifying this annotation
59
+ among all annotations on its page. Automatically generated when
60
+ ``in_reply_to`` is set and no name is provided. Raises
61
+ ``ValueError`` if provided without ``in_reply_to``.
62
+
63
+ """
64
+
65
+ def __init__(
66
+ self,
67
+ *,
68
+ title_bar: Optional[str] = None,
69
+ in_reply_to: Optional[Union[DictionaryObject, IndirectObject]] = None,
70
+ reply_type: Literal["R", "Group"] = "R",
71
+ annotation_name: Optional[str] = None,
72
+ ) -> None:
73
+ if title_bar is not None:
74
+ self[NameObject("/T")] = TextStringObject(title_bar)
75
+ if annotation_name is not None and in_reply_to is None:
76
+ raise ValueError(
77
+ "annotation_name is only supported when in_reply_to is set"
78
+ )
79
+ if reply_type != "R" and in_reply_to is None:
80
+ raise ValueError(
81
+ "reply_type is only meaningful when in_reply_to is set"
82
+ )
83
+ if in_reply_to is not None:
84
+ if isinstance(in_reply_to, IndirectObject):
85
+ ref: IndirectObject = in_reply_to
86
+ else:
87
+ indirect_ref = getattr(in_reply_to, "indirect_reference", None)
88
+ if not isinstance(indirect_ref, IndirectObject):
89
+ raise ValueError(
90
+ "in_reply_to must be a registered annotation "
91
+ "(added via writer.add_annotation() first)"
92
+ )
93
+ ref = indirect_ref
94
+ self[NameObject("/IRT")] = ref
95
+ self[NameObject("/RT")] = NameObject(f"/{reply_type}")
96
+ if annotation_name is None:
97
+ annotation_name = str(uuid.uuid4())
98
+ self[NameObject("/NM")] = TextStringObject(annotation_name)
99
+
100
+
101
+ class Text(MarkupAnnotation):
102
+ """
103
+ A text annotation.
104
+
105
+ Args:
106
+ rect: array of four integers ``[xLL, yLL, xUR, yUR]``
107
+ specifying the clickable rectangular area
108
+ text: The text that is added to the document
109
+ open:
110
+ flags:
111
+
112
+ """
113
+
114
+ def __init__(
115
+ self,
116
+ *,
117
+ rect: Union[RectangleObject, tuple[float, float, float, float]],
118
+ text: str,
119
+ open: bool = False,
120
+ flags: int = NO_FLAGS,
121
+ **kwargs: Any,
122
+ ) -> None:
123
+ super().__init__(**kwargs)
124
+ self[NameObject("/Subtype")] = NameObject("/Text")
125
+ self[NameObject("/Rect")] = RectangleObject(rect)
126
+ self[NameObject("/Contents")] = TextStringObject(text)
127
+ self[NameObject("/Open")] = BooleanObject(open)
128
+ self[NameObject("/Flags")] = NumberObject(flags)
129
+
130
+
131
+ class FreeText(MarkupAnnotation):
132
+ """A FreeText annotation"""
133
+
134
+ def __init__(
135
+ self,
136
+ *,
137
+ text: str,
138
+ rect: Union[RectangleObject, tuple[float, float, float, float]],
139
+ font: str = "Helvetica",
140
+ bold: bool = False,
141
+ italic: bool = False,
142
+ font_size: str = "14pt",
143
+ font_color: str = "000000",
144
+ border_color: Optional[str] = "000000",
145
+ background_color: Optional[str] = "ffffff",
146
+ **kwargs: Any,
147
+ ) -> None:
148
+ super().__init__(**kwargs)
149
+ self[NameObject("/Subtype")] = NameObject("/FreeText")
150
+ self[NameObject("/Rect")] = RectangleObject(rect)
151
+
152
+ # Table 225 of the 1.7 reference ("CSS2 style attributes used in rich text strings")
153
+ font_str = "font: "
154
+ if italic:
155
+ font_str = f"{font_str}italic "
156
+ else:
157
+ font_str = f"{font_str}normal "
158
+ if bold:
159
+ font_str = f"{font_str}bold "
160
+ else:
161
+ font_str = f"{font_str}normal "
162
+ font_str = f"{font_str}{font_size} {font}"
163
+ font_str = f"{font_str};text-align:left;color:#{font_color}"
164
+
165
+ default_appearance_string = ""
166
+ if border_color:
167
+ for st in hex_to_rgb(border_color):
168
+ default_appearance_string = f"{default_appearance_string}{st} "
169
+ default_appearance_string = f"{default_appearance_string}rg"
170
+
171
+ self.update(
172
+ {
173
+ NameObject("/Subtype"): NameObject("/FreeText"),
174
+ NameObject("/Rect"): RectangleObject(rect),
175
+ NameObject("/Contents"): TextStringObject(text),
176
+ # font size color
177
+ NameObject("/DS"): TextStringObject(font_str),
178
+ NameObject("/DA"): TextStringObject(default_appearance_string),
179
+ }
180
+ )
181
+ if border_color is None:
182
+ # Border Style
183
+ self[NameObject("/BS")] = DictionaryObject(
184
+ {
185
+ # width of 0 means no border
186
+ NameObject("/W"): NumberObject(0)
187
+ }
188
+ )
189
+ if background_color is not None:
190
+ self[NameObject("/C")] = ArrayObject(
191
+ [FloatObject(n) for n in hex_to_rgb(background_color)]
192
+ )
193
+
194
+
195
+ class Line(MarkupAnnotation):
196
+ def __init__(
197
+ self,
198
+ p1: Vertex,
199
+ p2: Vertex,
200
+ rect: Union[RectangleObject, tuple[float, float, float, float]],
201
+ text: str = "",
202
+ **kwargs: Any,
203
+ ) -> None:
204
+ super().__init__(**kwargs)
205
+ self.update(
206
+ {
207
+ NameObject("/Subtype"): NameObject("/Line"),
208
+ NameObject("/Rect"): RectangleObject(rect),
209
+ NameObject("/L"): ArrayObject(
210
+ [
211
+ FloatObject(p1[0]),
212
+ FloatObject(p1[1]),
213
+ FloatObject(p2[0]),
214
+ FloatObject(p2[1]),
215
+ ]
216
+ ),
217
+ NameObject("/LE"): ArrayObject(
218
+ [
219
+ NameObject("/None"),
220
+ NameObject("/None"),
221
+ ]
222
+ ),
223
+ NameObject("/IC"): ArrayObject(
224
+ [
225
+ FloatObject(0.5),
226
+ FloatObject(0.5),
227
+ FloatObject(0.5),
228
+ ]
229
+ ),
230
+ NameObject("/Contents"): TextStringObject(text),
231
+ }
232
+ )
233
+
234
+
235
+ class PolyLine(MarkupAnnotation):
236
+ def __init__(
237
+ self,
238
+ vertices: list[Vertex],
239
+ **kwargs: Any,
240
+ ) -> None:
241
+ super().__init__(**kwargs)
242
+ if len(vertices) == 0:
243
+ raise ValueError("A polyline needs at least 1 vertex with two coordinates")
244
+ coord_list = []
245
+ for x, y in vertices:
246
+ coord_list.append(NumberObject(x))
247
+ coord_list.append(NumberObject(y))
248
+ self.update(
249
+ {
250
+ NameObject("/Subtype"): NameObject("/PolyLine"),
251
+ NameObject("/Vertices"): ArrayObject(coord_list),
252
+ NameObject("/Rect"): RectangleObject(_get_bounding_rectangle(vertices)),
253
+ }
254
+ )
255
+
256
+
257
+ class Rectangle(MarkupAnnotation):
258
+ def __init__(
259
+ self,
260
+ rect: Union[RectangleObject, tuple[float, float, float, float]],
261
+ *,
262
+ interior_color: Optional[str] = None,
263
+ **kwargs: Any,
264
+ ) -> None:
265
+ super().__init__(**kwargs)
266
+ self.update(
267
+ {
268
+ NameObject("/Type"): NameObject("/Annot"),
269
+ NameObject("/Subtype"): NameObject("/Square"),
270
+ NameObject("/Rect"): RectangleObject(rect),
271
+ }
272
+ )
273
+
274
+ if interior_color:
275
+ self[NameObject("/IC")] = ArrayObject(
276
+ [FloatObject(n) for n in hex_to_rgb(interior_color)]
277
+ )
278
+
279
+
280
+ class Highlight(MarkupAnnotation):
281
+ def __init__(
282
+ self,
283
+ *,
284
+ rect: Union[RectangleObject, tuple[float, float, float, float]],
285
+ quad_points: ArrayObject,
286
+ highlight_color: str = "ff0000",
287
+ printing: bool = False,
288
+ **kwargs: Any,
289
+ ) -> None:
290
+ super().__init__(**kwargs)
291
+ self.update(
292
+ {
293
+ NameObject("/Subtype"): NameObject("/Highlight"),
294
+ NameObject("/Rect"): RectangleObject(rect),
295
+ NameObject("/QuadPoints"): quad_points,
296
+ NameObject("/C"): ArrayObject(
297
+ [FloatObject(n) for n in hex_to_rgb(highlight_color)]
298
+ ),
299
+ }
300
+ )
301
+ if printing:
302
+ self.flags = AnnotationFlag.PRINT
303
+
304
+
305
+ class Ellipse(MarkupAnnotation):
306
+ def __init__(
307
+ self,
308
+ rect: Union[RectangleObject, tuple[float, float, float, float]],
309
+ *,
310
+ interior_color: Optional[str] = None,
311
+ **kwargs: Any,
312
+ ) -> None:
313
+ super().__init__(**kwargs)
314
+
315
+ self.update(
316
+ {
317
+ NameObject("/Type"): NameObject("/Annot"),
318
+ NameObject("/Subtype"): NameObject("/Circle"),
319
+ NameObject("/Rect"): RectangleObject(rect),
320
+ }
321
+ )
322
+
323
+ if interior_color:
324
+ self[NameObject("/IC")] = ArrayObject(
325
+ [FloatObject(n) for n in hex_to_rgb(interior_color)]
326
+ )
327
+
328
+
329
+ class Polygon(MarkupAnnotation):
330
+ def __init__(
331
+ self,
332
+ vertices: list[tuple[float, float]],
333
+ **kwargs: Any,
334
+ ) -> None:
335
+ super().__init__(**kwargs)
336
+ if len(vertices) == 0:
337
+ raise ValueError("A polygon needs at least 1 vertex with two coordinates")
338
+
339
+ coord_list = []
340
+ for x, y in vertices:
341
+ coord_list.append(NumberObject(x))
342
+ coord_list.append(NumberObject(y))
343
+ self.update(
344
+ {
345
+ NameObject("/Type"): NameObject("/Annot"),
346
+ NameObject("/Subtype"): NameObject("/Polygon"),
347
+ NameObject("/Vertices"): ArrayObject(coord_list),
348
+ NameObject("/IT"): NameObject("/PolygonCloud"),
349
+ NameObject("/Rect"): RectangleObject(_get_bounding_rectangle(vertices)),
350
+ }
351
+ )
micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/annotations/_non_markup_annotations.py ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import TYPE_CHECKING, Any, Optional, Union
2
+
3
+ from ..generic._base import (
4
+ BooleanObject,
5
+ NameObject,
6
+ NumberObject,
7
+ TextStringObject,
8
+ )
9
+ from ..generic._data_structures import ArrayObject, DictionaryObject
10
+ from ..generic._fit import DEFAULT_FIT, Fit
11
+ from ..generic._rectangle import RectangleObject
12
+ from ._base import AnnotationDictionary
13
+
14
+
15
+ class Link(AnnotationDictionary):
16
+ def __init__(
17
+ self,
18
+ *,
19
+ rect: Union[RectangleObject, tuple[float, float, float, float]],
20
+ border: Optional[ArrayObject] = None,
21
+ url: Optional[str] = None,
22
+ target_page_index: Optional[int] = None,
23
+ fit: Fit = DEFAULT_FIT,
24
+ **kwargs: Any,
25
+ ) -> None:
26
+ super().__init__(**kwargs)
27
+ if TYPE_CHECKING:
28
+ from ..types import BorderArrayType # noqa: PLC0415
29
+
30
+ is_external = url is not None
31
+ is_internal = target_page_index is not None
32
+ if not is_external and not is_internal:
33
+ raise ValueError(
34
+ "Either 'url' or 'target_page_index' have to be provided. Both were None."
35
+ )
36
+ if is_external and is_internal:
37
+ raise ValueError(
38
+ "Either 'url' or 'target_page_index' have to be provided. "
39
+ f"{url=}, {target_page_index=}"
40
+ )
41
+
42
+ border_arr: BorderArrayType
43
+ if border is not None:
44
+ border_arr = [NumberObject(n) for n in border[:3]]
45
+ if len(border) == 4:
46
+ dash_pattern = ArrayObject([NumberObject(n) for n in border[3]])
47
+ border_arr.append(dash_pattern)
48
+ else:
49
+ border_arr = [NumberObject(0)] * 3
50
+
51
+ self.update(
52
+ {
53
+ NameObject("/Type"): NameObject("/Annot"),
54
+ NameObject("/Subtype"): NameObject("/Link"),
55
+ NameObject("/Rect"): RectangleObject(rect),
56
+ NameObject("/Border"): ArrayObject(border_arr),
57
+ }
58
+ )
59
+ if is_external:
60
+ self[NameObject("/A")] = DictionaryObject(
61
+ {
62
+ NameObject("/S"): NameObject("/URI"),
63
+ NameObject("/Type"): NameObject("/Action"),
64
+ NameObject("/URI"): TextStringObject(url),
65
+ }
66
+ )
67
+ if is_internal:
68
+ # This needs to be updated later!
69
+ dest_deferred = DictionaryObject(
70
+ {
71
+ "target_page_index": NumberObject(target_page_index),
72
+ "fit": NameObject(fit.fit_type),
73
+ "fit_args": fit.fit_args,
74
+ }
75
+ )
76
+ self[NameObject("/Dest")] = dest_deferred
77
+
78
+
79
+ class Popup(AnnotationDictionary):
80
+ def __init__(
81
+ self,
82
+ *,
83
+ rect: Union[RectangleObject, tuple[float, float, float, float]],
84
+ parent: Optional[DictionaryObject] = None,
85
+ open: bool = False,
86
+ **kwargs: Any,
87
+ ) -> None:
88
+ super().__init__(**kwargs)
89
+ self.update(
90
+ {
91
+ NameObject("/Subtype"): NameObject("/Popup"),
92
+ NameObject("/Rect"): RectangleObject(rect),
93
+ NameObject("/Open"): BooleanObject(open),
94
+ }
95
+ )
96
+ if parent:
97
+ # This needs to be an indirect object
98
+ try:
99
+ self[NameObject("/Parent")] = parent.indirect_reference
100
+ except AttributeError:
101
+ from .._utils import logger_warning # noqa: PLC0415
102
+
103
+ logger_warning(
104
+ "Unregistered Parent object : No Parent field set",
105
+ __name__,
106
+ )
micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/generic/__init__.py ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2006, Mathieu Fenniak
2
+ # All rights reserved.
3
+ #
4
+ # Redistribution and use in source and binary forms, with or without
5
+ # modification, are permitted provided that the following conditions are
6
+ # met:
7
+ #
8
+ # * Redistributions of source code must retain the above copyright notice,
9
+ # this list of conditions and the following disclaimer.
10
+ # * Redistributions in binary form must reproduce the above copyright notice,
11
+ # this list of conditions and the following disclaimer in the documentation
12
+ # and/or other materials provided with the distribution.
13
+ # * The name of the author may not be used to endorse or promote products
14
+ # derived from this software without specific prior written permission.
15
+ #
16
+ # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17
+ # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18
+ # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19
+ # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
20
+ # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21
+ # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22
+ # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23
+ # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24
+ # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25
+ # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26
+ # POSSIBILITY OF SUCH DAMAGE.
27
+
28
+ """Implementation of generic PDF objects (dictionary, number, string, ...)."""
29
+ __author__ = "Mathieu Fenniak"
30
+ __author_email__ = "biziqe@mathieu.fenniak.net"
31
+
32
+ from ..constants import OutlineFontFlag
33
+ from ._base import (
34
+ BooleanObject,
35
+ ByteStringObject,
36
+ FloatObject,
37
+ IndirectObject,
38
+ NameObject,
39
+ NullObject,
40
+ NumberObject,
41
+ PdfObject,
42
+ TextStringObject,
43
+ encode_pdfdocencoding,
44
+ is_null_or_none,
45
+ )
46
+ from ._data_structures import (
47
+ ArrayObject,
48
+ ContentStream,
49
+ DecodedStreamObject,
50
+ Destination,
51
+ DictionaryObject,
52
+ EncodedStreamObject,
53
+ Field,
54
+ StreamObject,
55
+ TreeObject,
56
+ read_object,
57
+ )
58
+ from ._files import EmbeddedFile
59
+ from ._fit import Fit
60
+ from ._link import DirectReferenceLink, NamedReferenceLink, ReferenceLink, extract_links
61
+ from ._outline import OutlineItem
62
+ from ._rectangle import RectangleObject
63
+ from ._utils import (
64
+ create_string_object,
65
+ decode_pdfdocencoding,
66
+ hex_to_rgb,
67
+ read_hex_string_from_stream,
68
+ read_string_from_stream,
69
+ )
70
+ from ._viewerpref import ViewerPreferences
71
+
72
+ PAGE_FIT = Fit.fit()
73
+
74
+
75
+ __all__ = [
76
+ "PAGE_FIT",
77
+ "ArrayObject",
78
+ "BooleanObject",
79
+ "ByteStringObject",
80
+ "ContentStream",
81
+ "DecodedStreamObject",
82
+ "Destination",
83
+ "DictionaryObject",
84
+ "DirectReferenceLink",
85
+ "EmbeddedFile",
86
+ "EncodedStreamObject",
87
+ "Field",
88
+ "Fit",
89
+ "FloatObject",
90
+ "IndirectObject",
91
+ "NameObject",
92
+ "NamedReferenceLink",
93
+ "NullObject",
94
+ "NumberObject",
95
+ "OutlineFontFlag",
96
+ "OutlineItem",
97
+ "PdfObject",
98
+ "RectangleObject",
99
+ "ReferenceLink",
100
+ "StreamObject",
101
+ "TextStringObject",
102
+ "TreeObject",
103
+ "ViewerPreferences",
104
+ # Utility functions
105
+ "create_string_object",
106
+ "decode_pdfdocencoding",
107
+ "encode_pdfdocencoding",
108
+ "extract_links",
109
+ "hex_to_rgb",
110
+ "is_null_or_none",
111
+ "read_hex_string_from_stream",
112
+ # Data structures core functions
113
+ "read_object",
114
+ "read_string_from_stream",
115
+ ]
micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/generic/_appearance_stream.py ADDED
@@ -0,0 +1,589 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ from dataclasses import dataclass
3
+ from enum import IntEnum
4
+ from typing import Any, Optional, Union, cast
5
+
6
+ from .._codecs import fill_from_encoding
7
+ from .._codecs.core_font_metrics import CORE_FONT_METRICS
8
+ from .._font import Font
9
+ from .._utils import logger_warning
10
+ from ..constants import AnnotationDictionaryAttributes, BorderStyles, FieldDictionaryAttributes
11
+ from ..generic import (
12
+ DecodedStreamObject,
13
+ DictionaryObject,
14
+ NameObject,
15
+ NumberObject,
16
+ RectangleObject,
17
+ )
18
+ from ..generic._base import ByteStringObject, TextStringObject, is_null_or_none
19
+
20
+ DEFAULT_FONT_SIZE_IN_MULTILINE = 12
21
+
22
+
23
+ @dataclass
24
+ class BaseStreamConfig:
25
+ """A container representing the basic layout of an appearance stream."""
26
+ rectangle: Union[RectangleObject, tuple[float, float, float, float]] = (0.0, 0.0, 0.0, 0.0)
27
+ border_width: int = 1 # The width of the border in points
28
+ border_style: str = BorderStyles.SOLID
29
+
30
+
31
+ class BaseStreamAppearance(DecodedStreamObject):
32
+ """A class representing the very base of an appearance stream, that is, a rectangle and a border."""
33
+
34
+ def __init__(self, layout: Optional[BaseStreamConfig] = None) -> None:
35
+ """
36
+ Takes the appearance stream layout as an argument.
37
+
38
+ Args:
39
+ layout: The basic layout parameters.
40
+ """
41
+ super().__init__()
42
+ self._layout = layout or BaseStreamConfig()
43
+ self[NameObject("/Type")] = NameObject("/XObject")
44
+ self[NameObject("/Subtype")] = NameObject("/Form")
45
+ self[NameObject("/BBox")] = RectangleObject(self._layout.rectangle)
46
+
47
+
48
+ class TextAlignment(IntEnum):
49
+ """Defines the alignment options for text within a form field's appearance stream."""
50
+
51
+ LEFT = 0
52
+ CENTER = 1
53
+ RIGHT = 2
54
+
55
+
56
+ class TextStreamAppearance(BaseStreamAppearance):
57
+ """
58
+ A class representing the appearance stream for a text-based form field.
59
+
60
+ This class generates the content stream (the `ap_stream_data`) that dictates
61
+ how text is rendered within a form field's bounding box. It handles properties
62
+ like font, font size, color, multiline text, and text selection highlighting.
63
+ """
64
+
65
+ def _scale_text(
66
+ self,
67
+ font: Font,
68
+ font_size: float,
69
+ leading_factor: float,
70
+ field_width: float,
71
+ field_height: float,
72
+ text: str,
73
+ min_font_size: float,
74
+ font_size_step: float = 0.2
75
+ ) -> tuple[list[tuple[float, str]], float]:
76
+ """
77
+ Takes a piece of text and scales it to field_width or field_height, given font_name
78
+ and font_size. Wraps text where necessary.
79
+
80
+ Args:
81
+ font: The font to be used.
82
+ font_size: The font size in points.
83
+ leading_factor: The line distance.
84
+ field_width: The width of the field in which to fit the text.
85
+ field_height: The height of the field in which to fit the text.
86
+ text: The text to fit with the field.
87
+ min_font_size: The minimum font size at which to scale the text.
88
+ font_size_step: The amount by which to decrement font size per step while scaling.
89
+
90
+ Returns:
91
+ The text in the form of list of tuples, each tuple containing the length of a line
92
+ and its contents, and the font_size for these lines and lengths.
93
+ """
94
+ orig_text = text
95
+ paragraphs = text.replace("\n", "\r").split("\r")
96
+ wrapped_lines = []
97
+ current_line_words: list[str] = []
98
+ current_line_width: float = 0
99
+ space_width = font.space_width * font_size / 1000
100
+ for paragraph in paragraphs:
101
+ if not paragraph.strip():
102
+ wrapped_lines.append((0.0, ""))
103
+ continue
104
+ words = paragraph.split(" ")
105
+ for i, word in enumerate(words):
106
+ word_width = font.text_width(word) * font_size / 1000
107
+ test_width = current_line_width + word_width + (space_width if i else 0)
108
+ if test_width > field_width and current_line_words:
109
+ wrapped_lines.append((current_line_width, " ".join(current_line_words)))
110
+ current_line_words = [word]
111
+ current_line_width = word_width
112
+ elif not current_line_words and word_width > field_width:
113
+ wrapped_lines.append((word_width, word))
114
+ current_line_words = []
115
+ current_line_width = 0
116
+ else:
117
+ if current_line_words:
118
+ current_line_width += space_width
119
+ current_line_words.append(word)
120
+ current_line_width += word_width
121
+ if current_line_words:
122
+ wrapped_lines.append((current_line_width, " ".join(current_line_words)))
123
+ current_line_words = []
124
+ current_line_width = 0
125
+ # Estimate total height.
126
+ estimated_total_height = font_size + (len(wrapped_lines) - 1) * leading_factor * font_size
127
+ if estimated_total_height > field_height:
128
+ # Text overflows height; Retry with smaller font size.
129
+ new_font_size = font_size - font_size_step
130
+ if new_font_size >= min_font_size:
131
+ return self._scale_text(
132
+ font,
133
+ new_font_size,
134
+ leading_factor,
135
+ field_width,
136
+ field_height,
137
+ orig_text,
138
+ min_font_size,
139
+ font_size_step
140
+ )
141
+ return wrapped_lines, round(font_size, 1)
142
+
143
+ def _generate_appearance_stream_data(
144
+ self,
145
+ text: str,
146
+ selection: Union[list[str], None],
147
+ font: Font,
148
+ font_glyph_byte_map: Optional[dict[str, bytes]] = None,
149
+ font_name: str = "/Helv",
150
+ font_size: float = 0.0,
151
+ font_color: str = "0 g",
152
+ is_multiline: bool = False,
153
+ alignment: TextAlignment = TextAlignment.LEFT,
154
+ is_comb: bool = False,
155
+ max_length: Optional[int] = None
156
+ ) -> bytes:
157
+ """
158
+ Generates the raw bytes of the PDF appearance stream for a text field.
159
+
160
+ This private method assembles the PDF content stream operators to draw
161
+ the provided text within the specified rectangle. It handles text positioning,
162
+ font application, color, and special formatting like selected text.
163
+
164
+ Args:
165
+ text: The text to be rendered in the form field.
166
+ selection: An optional list of strings that should be highlighted as selected.
167
+ font: The font to use.
168
+ font_glyph_byte_map: An optional dictionary mapping characters to their
169
+ byte representation for glyph encoding.
170
+ font_name: The name of the font resource to use (e.g., "/Helv").
171
+ font_size: The font size. If 0, it is automatically calculated
172
+ based on whether the field is multiline or not.
173
+ font_color: The color to apply to the font, represented as a PDF
174
+ graphics state string (e.g., "0 g" for black).
175
+ is_multiline: A boolean indicating if the text field is multiline.
176
+ alignment: Text alignment, can be TextAlignment.LEFT, .RIGHT, or .CENTER.
177
+ is_comb: Boolean that designates fixed-length fields, where every character
178
+ fills one "cell", such as in a postcode.
179
+ max_length: Used if is_comb is set. The maximum number of characters for a fixed-
180
+ length field.
181
+
182
+ Returns:
183
+ A byte string containing the PDF content stream data.
184
+
185
+ """
186
+ rectangle = self._layout.rectangle
187
+ font_glyph_byte_map = font_glyph_byte_map or {}
188
+ if isinstance(rectangle, tuple):
189
+ rectangle = RectangleObject(rectangle)
190
+ leading_factor = (font.font_descriptor.bbox[3] - font.font_descriptor.bbox[1]) / 1000.0
191
+
192
+ # Set margins based on border width and style, but never less than 1 point
193
+ factor = 2 if self._layout.border_style in {"/B", "/I"} else 1
194
+ margin = max(self._layout.border_width * factor, 1)
195
+ field_height = rectangle.height - 2 * margin
196
+ field_width = rectangle.width - 4 * margin
197
+
198
+ # If font_size is 0, apply the logic for multiline or large-as-possible font
199
+ if font_size == 0:
200
+ min_font_size = 4.0 # The mininum font size
201
+ if selection: # Don't wrap text when dealing with a /Ch field, in order to prevent problems
202
+ is_multiline = False # with matching "selection" with "line" later on.
203
+ if is_multiline:
204
+ font_size = DEFAULT_FONT_SIZE_IN_MULTILINE
205
+ lines, font_size = self._scale_text(
206
+ font,
207
+ font_size,
208
+ leading_factor,
209
+ field_width,
210
+ field_height,
211
+ text,
212
+ min_font_size
213
+ )
214
+ else:
215
+ max_vertical_size = field_height / leading_factor
216
+ text_width_unscaled = font.text_width(text) / 1000
217
+ max_horizontal_size = field_width / (text_width_unscaled or 1)
218
+ font_size = round(max(min(max_vertical_size, max_horizontal_size), min_font_size), 1)
219
+ lines = [(text_width_unscaled * font_size, text)]
220
+ elif is_comb:
221
+ if max_length and len(text) > max_length:
222
+ logger_warning (
223
+ f"Length of text {text} exceeds maximum length ({max_length}) of field, input truncated.",
224
+ __name__
225
+ )
226
+ # We act as if each character is one line, because we draw it separately later on
227
+ lines = [(
228
+ font.text_width(char) * font_size / 1000,
229
+ char
230
+ ) for index, char in enumerate(text) if index < (max_length or len(text))]
231
+ else:
232
+ lines = [(
233
+ font.text_width(line) * font_size / 1000,
234
+ line
235
+ ) for line in text.replace("\n", "\r").split("\r")]
236
+
237
+ # Set the vertical offset
238
+ if is_multiline:
239
+ y_offset = rectangle.height + margin - font.font_descriptor.bbox[3] * font_size / 1000.0
240
+ else:
241
+ y_offset = margin + ((field_height - font.font_descriptor.ascent * font_size / 1000) / 2)
242
+ default_appearance = f"{font_name} {font_size} Tf {font_color}"
243
+
244
+ ap_stream = (
245
+ f"q\n/Tx BMC \nq\n{2 * margin} {margin} {field_width} {field_height} "
246
+ f"re\nW\nBT\n{default_appearance}\n"
247
+ ).encode()
248
+ current_x_pos: float = 0 # Initial virtual position within the text object.
249
+
250
+ for line_number, (line_width, line) in enumerate(lines):
251
+ if selection and line in selection:
252
+ # Might be improved, but cannot find how to get fill working => replaced with lined box
253
+ ap_stream += (
254
+ f"1 {y_offset - (line_number * font_size * leading_factor) - 1} "
255
+ f"{rectangle.width - 2} {font_size + 2} re\n"
256
+ f"0.5 0.5 0.5 rg s\n{default_appearance}\n"
257
+ ).encode()
258
+
259
+ # Calculate the desired absolute starting X for the current line
260
+ desired_abs_x_start: float = 0
261
+ if is_comb and max_length:
262
+ # Calculate the width of a cell for one character
263
+ cell_width = rectangle.width / max_length
264
+ # Space from the left edge of the cell to the character's baseline start
265
+ # line_width here is the *actual* character width in points for the single character 'line'
266
+ centering_offset_in_cell = (cell_width - line_width) / 2
267
+ # Absolute start X = (Cell Index, i.e., line_number * Cell Width) + Centering Offset
268
+ desired_abs_x_start = (line_number * cell_width) + centering_offset_in_cell
269
+ elif alignment == TextAlignment.RIGHT:
270
+ desired_abs_x_start = rectangle.width - margin * 2 - line_width
271
+ elif alignment == TextAlignment.CENTER:
272
+ desired_abs_x_start = (rectangle.width - line_width) / 2
273
+ else: # Left aligned; default
274
+ desired_abs_x_start = margin * 2
275
+ # Calculate x_rel_offset: how much to move from the current_x_pos
276
+ # to reach the desired_abs_x_start.
277
+ x_rel_offset = desired_abs_x_start - current_x_pos
278
+
279
+ # Y-offset:
280
+ y_rel_offset: float = 0
281
+ if line_number == 0:
282
+ y_rel_offset = y_offset # Initial vertical position
283
+ elif is_comb:
284
+ y_rel_offset = 0.0 # DO NOT move vertically for subsequent characters
285
+ else:
286
+ y_rel_offset = - font_size * leading_factor # Move down by line height
287
+
288
+ # Td is a relative translation (Tx and Ty).
289
+ # It updates the current text position.
290
+ ap_stream += f"{x_rel_offset} {y_rel_offset} Td\n".encode()
291
+ # Update current_x_pos based on the Td operation for the next iteration.
292
+ # This is the X position where the *current line* will start.
293
+ current_x_pos = desired_abs_x_start
294
+
295
+ encoded_line: list[bytes] = [
296
+ font_glyph_byte_map.get(c, c.encode("utf-16-be")) for c in line
297
+ ]
298
+ if any(len(c) >= 2 for c in encoded_line):
299
+ ap_stream += b"<" + (b"".join(encoded_line)).hex().encode() + b"> Tj\n"
300
+ else:
301
+ ap_stream += b"(" + b"".join(encoded_line) + b") Tj\n"
302
+ ap_stream += b"ET\nQ\nEMC\nQ\n"
303
+ return ap_stream
304
+
305
+ def __init__(
306
+ self,
307
+ layout: Optional[BaseStreamConfig] = None,
308
+ text: str = "",
309
+ selection: Optional[list[str]] = None,
310
+ font_resource: Optional[DictionaryObject] = None,
311
+ font_name: str = "/Helv",
312
+ font_size: float = 0.0,
313
+ font_color: str = "0 g",
314
+ is_multiline: bool = False,
315
+ alignment: TextAlignment = TextAlignment.LEFT,
316
+ is_comb: bool = False,
317
+ max_length: Optional[int] = None
318
+ ) -> None:
319
+ """
320
+ Initializes a TextStreamAppearance object.
321
+
322
+ This constructor creates a new PDF stream object configured as an XObject
323
+ of subtype Form. It uses the `_appearance_stream_data` method to generate
324
+ the content for the stream.
325
+
326
+ Args:
327
+ layout: The basic layout parameters.
328
+ text: The text to be rendered in the form field.
329
+ selection: An optional list of strings that should be highlighted as selected.
330
+ font_resource: An optional variable that represents a PDF font dictionary.
331
+ font_name: The name of the font resource, e.g., "/Helv".
332
+ font_size: The font size. If 0, it's auto-calculated.
333
+ font_color: The font color string.
334
+ is_multiline: A boolean indicating if the text field is multiline.
335
+ alignment: Text alignment, can be TextAlignment.LEFT, .RIGHT, or .CENTER.
336
+ is_comb: Boolean that designates fixed-length fields, where every character
337
+ fills one "cell", such as in a postcode.
338
+ max_length: Used if is_comb is set. The maximum number of characters for a fixed-
339
+ length field.
340
+
341
+ """
342
+ super().__init__(layout)
343
+
344
+ # If a font resource was added, get the font character map
345
+ if font_resource:
346
+ font = Font.from_font_resource(font_resource)
347
+ else:
348
+ logger_warning(f"Font dictionary for {font_name} not found; defaulting to Helvetica.", __name__)
349
+ font_name = "/Helv"
350
+ core_font_metrics = CORE_FONT_METRICS["Helvetica"]
351
+ font = Font(
352
+ name="Helvetica",
353
+ character_map={},
354
+ encoding=dict(zip(range(256), fill_from_encoding("cp1252"))), # WinAnsiEncoding
355
+ sub_type="Type1",
356
+ font_descriptor=core_font_metrics.font_descriptor,
357
+ character_widths=core_font_metrics.character_widths
358
+ )
359
+ font_resource = font.as_font_resource()
360
+
361
+ # Check whether the font resource is able to encode the text value.
362
+ encodable = True
363
+ try:
364
+ if isinstance(font.encoding, str):
365
+ text.encode(font.encoding, "surrogatepass")
366
+ else:
367
+ supported_chars = set(font.encoding.values())
368
+ if any(char not in supported_chars for char in text):
369
+ encodable = False
370
+ # We should add a final check against the character_map (CMap) of the font,
371
+ # but we don't appear to have PDF forms with such fonts, so we skip this for
372
+ # now.
373
+
374
+ except UnicodeEncodeError:
375
+ encodable = False
376
+
377
+ if not encodable:
378
+ logger_warning(
379
+ f"Text string '{text}' contains characters not supported by font encoding. "
380
+ "This may result in text corruption. "
381
+ "Consider calling writer.update_page_form_field_values with auto_regenerate=True.",
382
+ __name__
383
+ )
384
+
385
+ font_glyph_byte_map: dict[str, bytes]
386
+ if isinstance(font.encoding, str):
387
+ font_glyph_byte_map = {
388
+ v: k.encode(font.encoding) for k, v in font.character_map.items()
389
+ }
390
+ else:
391
+ font_glyph_byte_map = {v: bytes((k,)) for k, v in font.encoding.items()}
392
+ font_encoding_rev = {v: bytes((k,)) for k, v in font.encoding.items()}
393
+ for key, value in font.character_map.items():
394
+ font_glyph_byte_map[value] = font_encoding_rev.get(key, key)
395
+
396
+ ap_stream_data = self._generate_appearance_stream_data(
397
+ text,
398
+ selection,
399
+ font,
400
+ font_glyph_byte_map,
401
+ font_name=font_name,
402
+ font_size=font_size,
403
+ font_color=font_color,
404
+ is_multiline=is_multiline,
405
+ alignment=alignment,
406
+ is_comb=is_comb,
407
+ max_length=max_length
408
+ )
409
+
410
+ self.set_data(ByteStringObject(ap_stream_data))
411
+ self[NameObject("/Length")] = NumberObject(len(ap_stream_data))
412
+ # Update Resources with font information
413
+ self[NameObject("/Resources")] = DictionaryObject({
414
+ NameObject("/Font"): DictionaryObject({
415
+ NameObject(font_name): getattr(font_resource, "indirect_reference", font_resource)
416
+ })
417
+ })
418
+
419
+ @staticmethod
420
+ def _find_annotation_font_resource(
421
+ font_name: str,
422
+ annotation: DictionaryObject,
423
+ acro_form: DictionaryObject
424
+ ) -> tuple[str, DictionaryObject]:
425
+ # Try to find a resource dictionary for the font by examining the annotation and, if that fails,
426
+ # the AcroForm resources dictionary
427
+ acro_form_resources: Any = cast(
428
+ DictionaryObject,
429
+ annotation.get_inherited(
430
+ "/DR",
431
+ acro_form.get("/DR", DictionaryObject()),
432
+ ),
433
+ )
434
+ acro_form_font_resources = acro_form_resources.get("/Font", DictionaryObject())
435
+ font_resource = acro_form_font_resources.get(font_name, None)
436
+
437
+ # Normally, we should have found a font resource by now. However, when a user has provided a specific
438
+ # font name, we may not have found the associated font resource among the AcroForm resources. Also, in
439
+ # case of the 14 Adobe Core fonts, we may be expected to construct a font resource ourselves.
440
+ if is_null_or_none(font_resource):
441
+ if font_name.removeprefix("/") not in CORE_FONT_METRICS:
442
+ # Default to Helvetica if we haven't found a font resource and cannot construct one ourselves.
443
+ logger_warning(f"Font dictionary for {font_name} not found; defaulting to Helvetica.", __name__)
444
+ font_name = "/Helvetica"
445
+ core_font_metrics = CORE_FONT_METRICS[font_name.removeprefix("/")]
446
+ font_resource = Font(
447
+ name=font_name.removeprefix("/"),
448
+ character_map={},
449
+ encoding=dict(zip(range(256), fill_from_encoding("cp1252"))), # WinAnsiEncoding
450
+ sub_type="Type1",
451
+ font_descriptor=core_font_metrics.font_descriptor,
452
+ character_widths=core_font_metrics.character_widths
453
+ ).as_font_resource()
454
+
455
+ return font_name, font_resource
456
+
457
+ @classmethod
458
+ def from_text_annotation(
459
+ cls,
460
+ acro_form: DictionaryObject, # _root_object[CatalogDictionary.ACRO_FORM])
461
+ field: DictionaryObject,
462
+ annotation: DictionaryObject,
463
+ user_font_name: str = "",
464
+ user_font_size: float = -1,
465
+ ) -> "TextStreamAppearance":
466
+ """
467
+ Creates a TextStreamAppearance object from a text field annotation.
468
+
469
+ This class method is a factory for creating a `TextStreamAppearance`
470
+ instance by extracting all necessary information (bounding box, font,
471
+ text content, etc.) from the PDF field and annotation dictionaries.
472
+ It respects inheritance for properties like default appearance (`/DA`).
473
+
474
+ Args:
475
+ acro_form: The root AcroForm dictionary from the PDF catalog.
476
+ field: The field dictionary object.
477
+ annotation: The widget annotation dictionary object associated with the field.
478
+ user_font_name: An optional user-provided font name to override the
479
+ default. Defaults to an empty string.
480
+ user_font_size: An optional user-provided font size to override the
481
+ default. A value of -1 indicates no override.
482
+
483
+ Returns:
484
+ A new `TextStreamAppearance` instance configured for the given field.
485
+
486
+ """
487
+ # Calculate rectangle dimensions
488
+ _rectangle = cast(RectangleObject, annotation[AnnotationDictionaryAttributes.Rect])
489
+ rectangle = RectangleObject((0, 0, abs(_rectangle[2] - _rectangle[0]), abs(_rectangle[3] - _rectangle[1])))
490
+
491
+ # Get default appearance dictionary from annotation
492
+ default_appearance = annotation.get_inherited(
493
+ AnnotationDictionaryAttributes.DA,
494
+ acro_form.get(AnnotationDictionaryAttributes.DA, None),
495
+ )
496
+ if not default_appearance:
497
+ # Create a default appearance if none was found in the annotation
498
+ default_appearance = TextStringObject("/Helv 0 Tf 0 g")
499
+ else:
500
+ default_appearance = default_appearance.get_object()
501
+
502
+ # Retrieve field text and selected values
503
+ field_flags = field.get(FieldDictionaryAttributes.Ff, 0)
504
+ if (
505
+ field.get(FieldDictionaryAttributes.FT, "/Tx") == "/Ch" and
506
+ field_flags & FieldDictionaryAttributes.FfBits.Combo == 0
507
+ ):
508
+ text = "\n".join(annotation.get_inherited(FieldDictionaryAttributes.Opt, []))
509
+ selection = field.get("/V", [])
510
+ if not isinstance(selection, list):
511
+ selection = [selection]
512
+ else: # /Tx
513
+ text = field.get("/V", "")
514
+ selection = []
515
+
516
+ # Escape parentheses (PDF 1.7 reference, table 3.2, Literal Strings)
517
+ text = text.replace("\\", "\\\\").replace("(", r"\(").replace(")", r"\)")
518
+
519
+ # Derive font name, size and color from the default appearance. Also set
520
+ # user-provided font name and font size in the default appearance, if given.
521
+ # For a font name, this presumes that we can find an associated font resource
522
+ # dictionary. Uses the variable font_properties as an intermediate.
523
+ # As per the PDF spec:
524
+ # "At a minimum, the string [that is, default_appearance] shall include a Tf (text
525
+ # font) operator along with its two operands, font and size" (Section 12.7.4.3
526
+ # "Variable text" of the PDF 2.0 specification).
527
+ font_properties = [prop for prop in re.split(r"\s", default_appearance) if prop]
528
+ font_name = font_properties.pop(font_properties.index("Tf") - 2)
529
+ font_size = float(font_properties.pop(font_properties.index("Tf") - 1))
530
+ font_properties.remove("Tf")
531
+ font_color = " ".join(font_properties)
532
+ # Determine the font name to use, prioritizing the user's input
533
+ if user_font_name:
534
+ font_name = user_font_name
535
+ # Determine the font size to use, prioritizing the user's input
536
+ if user_font_size > 0:
537
+ font_size = user_font_size
538
+
539
+ font_name, font_resource = cls._find_annotation_font_resource(font_name, annotation, acro_form)
540
+
541
+ # Retrieve formatting information
542
+ is_comb = False
543
+ max_length = None
544
+ if field_flags & FieldDictionaryAttributes.FfBits.Comb:
545
+ is_comb = True
546
+ max_length = annotation.get("/MaxLen")
547
+ is_multiline = False
548
+ if field_flags & FieldDictionaryAttributes.FfBits.Multiline:
549
+ is_multiline = True
550
+ alignment = field.get("/Q", TextAlignment.LEFT)
551
+ border_width = 1
552
+ border_style = BorderStyles.SOLID
553
+ if "/BS" in field:
554
+ border_width = cast(DictionaryObject, field["/BS"]).get("/W", border_width)
555
+ border_style = cast(DictionaryObject, field["/BS"]).get("/S", border_style)
556
+
557
+ # Create the TextStreamAppearance instance
558
+ layout = BaseStreamConfig(rectangle=rectangle, border_width=border_width, border_style=border_style)
559
+ new_appearance_stream = cls(
560
+ layout,
561
+ text,
562
+ selection,
563
+ font_resource,
564
+ font_name=font_name,
565
+ font_size=font_size,
566
+ font_color=font_color,
567
+ is_multiline=is_multiline,
568
+ alignment=alignment,
569
+ is_comb=is_comb,
570
+ max_length=max_length
571
+ )
572
+
573
+ if AnnotationDictionaryAttributes.AP in annotation:
574
+ for key, value in (
575
+ cast(DictionaryObject, annotation[AnnotationDictionaryAttributes.AP]).get("/N", {}).items()
576
+ ):
577
+ if key in {"/BBox", "/Length", "/Subtype", "/Type", "/Filter"}:
578
+ continue
579
+ # Don't overwrite font resources added by TextAppearanceStream.__init__
580
+ if key == "/Resources":
581
+ if "/Font" not in value:
582
+ value.get_object()[NameObject("/Font")] = DictionaryObject()
583
+ value["/Font"].get_object()[NameObject(font_name)] = getattr(
584
+ font_resource, "indirect_reference", font_resource
585
+ )
586
+ else:
587
+ new_appearance_stream[key] = value
588
+
589
+ return new_appearance_stream
micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/generic/_base.py ADDED
@@ -0,0 +1,953 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2006, Mathieu Fenniak
2
+ # All rights reserved.
3
+ #
4
+ # Redistribution and use in source and binary forms, with or without
5
+ # modification, are permitted provided that the following conditions are
6
+ # met:
7
+ #
8
+ # * Redistributions of source code must retain the above copyright notice,
9
+ # this list of conditions and the following disclaimer.
10
+ # * Redistributions in binary form must reproduce the above copyright notice,
11
+ # this list of conditions and the following disclaimer in the documentation
12
+ # and/or other materials provided with the distribution.
13
+ # * The name of the author may not be used to endorse or promote products
14
+ # derived from this software without specific prior written permission.
15
+ #
16
+ # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17
+ # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18
+ # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19
+ # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
20
+ # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21
+ # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22
+ # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23
+ # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24
+ # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25
+ # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26
+ # POSSIBILITY OF SUCH DAMAGE.
27
+ import binascii
28
+ import codecs
29
+ import hashlib
30
+ import re
31
+ import sys
32
+ from collections.abc import Sequence
33
+ from math import log10
34
+ from struct import iter_unpack
35
+ from typing import Any, Callable, ClassVar, Optional, Union, cast
36
+
37
+ if sys.version_info[:2] >= (3, 10):
38
+ from typing import TypeGuard
39
+ else:
40
+ from typing_extensions import TypeGuard # PEP 647
41
+
42
+ if sys.version_info >= (3, 11):
43
+ from typing import Self
44
+ else:
45
+ from typing_extensions import Self
46
+
47
+ from .._codecs import _pdfdoc_encoding_rev
48
+ from .._protocols import PdfObjectProtocol, PdfWriterProtocol
49
+ from .._utils import (
50
+ StreamType,
51
+ classproperty,
52
+ deprecation_no_replacement,
53
+ deprecation_with_replacement,
54
+ logger_warning,
55
+ read_non_whitespace,
56
+ read_until_regex,
57
+ )
58
+ from ..errors import STREAM_TRUNCATED_PREMATURELY, PdfReadError, PdfStreamError
59
+
60
+ __author__ = "Mathieu Fenniak"
61
+ __author_email__ = "biziqe@mathieu.fenniak.net"
62
+
63
+
64
+ class PdfObject(PdfObjectProtocol):
65
+ # function for calculating a hash value
66
+ hash_func: Callable[..., "hashlib._Hash"] = hashlib.sha1
67
+ indirect_reference: Optional["IndirectObject"]
68
+
69
+ def hash_bin(self) -> int:
70
+ """
71
+ Used to detect modified object.
72
+
73
+ Returns:
74
+ Hash considering type and value.
75
+
76
+ """
77
+ raise NotImplementedError(
78
+ f"{self.__class__.__name__} does not implement .hash_bin() so far"
79
+ )
80
+
81
+ def hash_value_data(self) -> bytes:
82
+ return f"{self}".encode()
83
+
84
+ def hash_value(self) -> bytes:
85
+ return (
86
+ f"{self.__class__.__name__}:"
87
+ f"{self.hash_func(self.hash_value_data()).hexdigest()}"
88
+ ).encode()
89
+
90
+ def replicate(
91
+ self,
92
+ pdf_dest: PdfWriterProtocol,
93
+ ) -> "PdfObject":
94
+ """
95
+ Clone object into pdf_dest (PdfWriterProtocol which is an interface for PdfWriter)
96
+ without ensuring links. This is used in clone_document_from_root with incremental = True.
97
+
98
+ Args:
99
+ pdf_dest: Target to clone to.
100
+
101
+ Returns:
102
+ The cloned PdfObject
103
+
104
+ """
105
+ return self.clone(pdf_dest)
106
+
107
+ def clone(
108
+ self,
109
+ pdf_dest: PdfWriterProtocol,
110
+ force_duplicate: bool = False,
111
+ ignore_fields: Optional[Sequence[Union[str, int]]] = (),
112
+ ) -> "PdfObject":
113
+ """
114
+ Clone object into pdf_dest (PdfWriterProtocol which is an interface for PdfWriter).
115
+
116
+ By default, this method will call ``_reference_clone`` (see ``_reference``).
117
+
118
+
119
+ Args:
120
+ pdf_dest: Target to clone to.
121
+ force_duplicate: By default, if the object has already been cloned and referenced,
122
+ the copy will be returned; when ``True``, a new copy will be created.
123
+ (Default value = ``False``)
124
+ ignore_fields: List/tuple of field names (for dictionaries) that will be ignored
125
+ during cloning (applies to children duplication as well). If fields are to be
126
+ considered for a limited number of levels, you have to add it as integer, for
127
+ example ``[1,"/B","/TOTO"]`` means that ``"/B"`` will be ignored at the first
128
+ level only but ``"/TOTO"`` on all levels.
129
+
130
+ Returns:
131
+ The cloned PdfObject
132
+
133
+ """
134
+ raise NotImplementedError(
135
+ f"{self.__class__.__name__} does not implement .clone so far"
136
+ )
137
+
138
+ def _reference_clone(
139
+ self, clone: "PdfObject", pdf_dest: PdfWriterProtocol, force_duplicate: bool = False
140
+ ) -> "PdfObject":
141
+ """
142
+ Reference the object within the _objects of pdf_dest only if
143
+ indirect_reference attribute exists (which means the objects was
144
+ already identified in xref/xobjstm) if object has been already
145
+ referenced do nothing.
146
+
147
+ Args:
148
+ clone:
149
+ pdf_dest:
150
+
151
+ Returns:
152
+ The clone
153
+
154
+ """
155
+ try:
156
+ if (
157
+ not force_duplicate
158
+ and clone.indirect_reference is not None
159
+ and clone.indirect_reference.pdf == pdf_dest
160
+ ):
161
+ return clone
162
+ except Exception:
163
+ pass
164
+ # if hasattr(clone, "indirect_reference"):
165
+ try:
166
+ ind = self.indirect_reference
167
+ except AttributeError:
168
+ return clone
169
+ if (
170
+ pdf_dest.incremental
171
+ and ind is not None
172
+ and ind.pdf == pdf_dest._reader
173
+ and ind.idnum <= len(pdf_dest._objects)
174
+ ):
175
+ i = ind.idnum
176
+ else:
177
+ i = len(pdf_dest._objects) + 1
178
+ if ind is not None:
179
+ if id(ind.pdf) not in pdf_dest._id_translated:
180
+ pdf_dest._id_translated[id(ind.pdf)] = {}
181
+ pdf_dest._id_translated[id(ind.pdf)]["PreventGC"] = ind.pdf # type: ignore[index]
182
+ if (
183
+ not force_duplicate
184
+ and ind.idnum in pdf_dest._id_translated[id(ind.pdf)]
185
+ ):
186
+ obj = pdf_dest.get_object(
187
+ pdf_dest._id_translated[id(ind.pdf)][ind.idnum]
188
+ )
189
+ assert isinstance(obj, PdfObject), "mypy"
190
+ return obj
191
+ pdf_dest._id_translated[id(ind.pdf)][ind.idnum] = i
192
+ try:
193
+ pdf_dest._objects[i - 1] = clone
194
+ except IndexError:
195
+ pdf_dest._objects.append(clone)
196
+ i = len(pdf_dest._objects)
197
+ clone.indirect_reference = IndirectObject(i, 0, pdf_dest)
198
+ return clone
199
+
200
+ def get_object(self) -> Optional["PdfObject"]:
201
+ """Resolve indirect references."""
202
+ return self
203
+
204
+ def write_to_stream(
205
+ self, stream: StreamType, encryption_key: Union[None, str, bytes] = None
206
+ ) -> None:
207
+ raise NotImplementedError
208
+
209
+
210
+ class NullObject(PdfObject):
211
+ def clone(
212
+ self,
213
+ pdf_dest: PdfWriterProtocol,
214
+ force_duplicate: bool = False,
215
+ ignore_fields: Optional[Sequence[Union[str, int]]] = (),
216
+ ) -> "NullObject":
217
+ """Clone object into pdf_dest."""
218
+ return cast(
219
+ "NullObject", self._reference_clone(NullObject(), pdf_dest, force_duplicate)
220
+ )
221
+
222
+ def hash_bin(self) -> int:
223
+ """
224
+ Used to detect modified object.
225
+
226
+ Returns:
227
+ Hash considering type and value.
228
+
229
+ """
230
+ return hash((self.__class__,))
231
+
232
+ def write_to_stream(
233
+ self, stream: StreamType, encryption_key: Union[None, str, bytes] = None
234
+ ) -> None:
235
+ if encryption_key is not None: # deprecated
236
+ deprecation_no_replacement(
237
+ "the encryption_key parameter of write_to_stream", "5.0.0"
238
+ )
239
+ stream.write(b"null")
240
+
241
+ @staticmethod
242
+ def read_from_stream(stream: StreamType) -> "NullObject":
243
+ nulltxt = stream.read(4)
244
+ if nulltxt != b"null":
245
+ raise PdfReadError("Could not read Null object")
246
+ return NullObject()
247
+
248
+ def __repr__(self) -> str:
249
+ return "NullObject"
250
+
251
+ def __eq__(self, other: object) -> bool:
252
+ return isinstance(other, NullObject)
253
+
254
+ def __hash__(self) -> int:
255
+ return self.hash_bin()
256
+
257
+
258
+ class BooleanObject(PdfObject):
259
+ value: bool
260
+
261
+ def __init__(self, value: Any) -> None:
262
+ self.value = value
263
+
264
+ def clone(
265
+ self,
266
+ pdf_dest: PdfWriterProtocol,
267
+ force_duplicate: bool = False,
268
+ ignore_fields: Optional[Sequence[Union[str, int]]] = (),
269
+ ) -> "BooleanObject":
270
+ """Clone object into pdf_dest."""
271
+ return cast(
272
+ "BooleanObject",
273
+ self._reference_clone(BooleanObject(self.value), pdf_dest, force_duplicate),
274
+ )
275
+
276
+ def hash_bin(self) -> int:
277
+ """
278
+ Used to detect modified object.
279
+
280
+ Returns:
281
+ Hash considering type and value.
282
+
283
+ """
284
+ return hash((self.__class__, self.value))
285
+
286
+ def __eq__(self, o: object, /) -> bool:
287
+ if isinstance(o, BooleanObject):
288
+ return self.value == o.value
289
+ if isinstance(o, bool):
290
+ return self.value == o
291
+ return False
292
+
293
+ def __hash__(self) -> int:
294
+ return self.hash_bin()
295
+
296
+ def __repr__(self) -> str:
297
+ return "True" if self.value else "False"
298
+
299
+ def write_to_stream(
300
+ self, stream: StreamType, encryption_key: Union[None, str, bytes] = None
301
+ ) -> None:
302
+ if encryption_key is not None: # deprecated
303
+ deprecation_no_replacement(
304
+ "the encryption_key parameter of write_to_stream", "5.0.0"
305
+ )
306
+ if self.value:
307
+ stream.write(b"true")
308
+ else:
309
+ stream.write(b"false")
310
+
311
+ @staticmethod
312
+ def read_from_stream(stream: StreamType) -> "BooleanObject":
313
+ word = stream.read(4)
314
+ if word == b"true":
315
+ return BooleanObject(True)
316
+ if word == b"fals":
317
+ stream.read(1)
318
+ return BooleanObject(False)
319
+ raise PdfReadError("Could not read Boolean object")
320
+
321
+
322
+ class IndirectObject(PdfObject):
323
+ def __init__(self, idnum: int, generation: int, pdf: Any) -> None: # PdfReader
324
+ self.idnum = idnum
325
+ self.generation = generation
326
+ self.pdf = pdf
327
+
328
+ def __hash__(self) -> int:
329
+ return hash((self.idnum, self.generation, id(self.pdf)))
330
+
331
+ def hash_bin(self) -> int:
332
+ """
333
+ Used to detect modified object.
334
+
335
+ Returns:
336
+ Hash considering type and value.
337
+
338
+ """
339
+ return hash((self.__class__, self.idnum, self.generation, id(self.pdf)))
340
+
341
+ def replicate(
342
+ self,
343
+ pdf_dest: PdfWriterProtocol,
344
+ ) -> "PdfObject":
345
+ return IndirectObject(self.idnum, self.generation, pdf_dest)
346
+
347
+ def clone(
348
+ self,
349
+ pdf_dest: PdfWriterProtocol,
350
+ force_duplicate: bool = False,
351
+ ignore_fields: Optional[Sequence[Union[str, int]]] = (),
352
+ ) -> "IndirectObject":
353
+ """Clone object into pdf_dest."""
354
+ if self.pdf == pdf_dest and not force_duplicate:
355
+ # Already duplicated and no extra duplication required
356
+ return self
357
+ if id(self.pdf) not in pdf_dest._id_translated:
358
+ pdf_dest._id_translated[id(self.pdf)] = {}
359
+ pdf_dest._id_translated[id(self.pdf)]["PreventGC"] = self.pdf # type: ignore[index]
360
+
361
+ if self.idnum in pdf_dest._id_translated[id(self.pdf)]:
362
+ dup = pdf_dest.get_object(pdf_dest._id_translated[id(self.pdf)][self.idnum])
363
+ if force_duplicate:
364
+ assert dup is not None
365
+ assert dup.indirect_reference is not None
366
+ idref = dup.indirect_reference
367
+ return IndirectObject(idref.idnum, idref.generation, idref.pdf)
368
+ else:
369
+ obj = self.get_object()
370
+ # case observed : a pointed object can not be found
371
+ if obj is None:
372
+ # this normally
373
+ obj = NullObject()
374
+ assert isinstance(self, (IndirectObject,))
375
+ obj.indirect_reference = self
376
+ dup = pdf_dest._add_object(
377
+ obj.clone(pdf_dest, force_duplicate, ignore_fields)
378
+ )
379
+ assert isinstance(dup, PdfObject), "mypy"
380
+ assert dup.indirect_reference is not None, "mypy"
381
+ return dup.indirect_reference
382
+
383
+ @property
384
+ def indirect_reference(self) -> "IndirectObject": # type: ignore[override]
385
+ return self
386
+
387
+ def get_object(self) -> Optional["PdfObject"]:
388
+ obj: Optional[PdfObject] = self.pdf.get_object(self)
389
+ return obj
390
+
391
+ def __deepcopy__(self, memo: Any) -> "IndirectObject":
392
+ return IndirectObject(self.idnum, self.generation, self.pdf)
393
+
394
+ def _get_object_with_check(self) -> Optional["PdfObject"]:
395
+ o = self.get_object()
396
+ # the check is done here to not slow down get_object()
397
+ if isinstance(o, IndirectObject):
398
+ raise PdfStreamError(
399
+ f"{self.__repr__()} references an IndirectObject {o.__repr__()}"
400
+ )
401
+ return o
402
+
403
+ def __getattr__(self, name: str) -> Any:
404
+ # Attribute not found in object: look in pointed object
405
+ try:
406
+ return getattr(self._get_object_with_check(), name)
407
+ except AttributeError:
408
+ raise AttributeError(
409
+ f"No attribute {name} found in IndirectObject or pointed object"
410
+ )
411
+
412
+ def __getitem__(self, key: Any) -> Any:
413
+ # items should be extracted from pointed Object
414
+ return self._get_object_with_check()[key] # type: ignore
415
+
416
+ def __contains__(self, key: Any) -> bool:
417
+ return key in self._get_object_with_check() # type: ignore
418
+
419
+ def __iter__(self) -> Any:
420
+ return self._get_object_with_check().__iter__() # type: ignore
421
+
422
+ def __float__(self) -> str:
423
+ # in this case we are looking for the pointed data
424
+ return self.get_object().__float__() # type: ignore
425
+
426
+ def __int__(self) -> int:
427
+ # in this case we are looking for the pointed data
428
+ return self.get_object().__int__() # type: ignore
429
+
430
+ def __str__(self) -> str:
431
+ # in this case we are looking for the pointed data
432
+ return self.get_object().__str__()
433
+
434
+ def __repr__(self) -> str:
435
+ return f"IndirectObject({self.idnum!r}, {self.generation!r}, {id(self.pdf)})"
436
+
437
+ def __eq__(self, other: object) -> bool:
438
+ return (
439
+ other is not None
440
+ and isinstance(other, IndirectObject)
441
+ and self.idnum == other.idnum
442
+ and self.generation == other.generation
443
+ and self.pdf is other.pdf
444
+ )
445
+
446
+ def __ne__(self, other: object) -> bool:
447
+ return not self.__eq__(other)
448
+
449
+ def write_to_stream(
450
+ self, stream: StreamType, encryption_key: Union[None, str, bytes] = None
451
+ ) -> None:
452
+ if encryption_key is not None: # deprecated
453
+ deprecation_no_replacement(
454
+ "the encryption_key parameter of write_to_stream", "5.0.0"
455
+ )
456
+ stream.write(f"{self.idnum} {self.generation} R".encode())
457
+
458
+ @staticmethod
459
+ def read_from_stream(stream: StreamType, pdf: Any) -> "IndirectObject": # PdfReader
460
+ idnum = b""
461
+ while True:
462
+ tok = stream.read(1)
463
+ if not tok:
464
+ raise PdfStreamError(STREAM_TRUNCATED_PREMATURELY)
465
+ if tok.isspace():
466
+ break
467
+ idnum += tok
468
+ generation = b""
469
+ while True:
470
+ tok = stream.read(1)
471
+ if not tok:
472
+ raise PdfStreamError(STREAM_TRUNCATED_PREMATURELY)
473
+ if tok.isspace():
474
+ if not generation:
475
+ continue
476
+ break
477
+ generation += tok
478
+ r = read_non_whitespace(stream)
479
+ if r != b"R":
480
+ raise PdfReadError(
481
+ f"Error reading indirect object reference at byte {hex(stream.tell())}"
482
+ )
483
+ return IndirectObject(int(idnum), int(generation), pdf)
484
+
485
+
486
+ FLOAT_WRITE_PRECISION = 8 # shall be min 5 digits max, allow user adj
487
+
488
+
489
+ class FloatObject(float, PdfObject):
490
+ def __new__(
491
+ cls, value: Any = "0.0", context: Optional[Any] = None
492
+ ) -> Self:
493
+ try:
494
+ value = float(value)
495
+ return float.__new__(cls, value)
496
+ except Exception as e:
497
+ # If this isn't a valid decimal (happens in malformed PDFs)
498
+ # fallback to 0
499
+ logger_warning(
500
+ f"{e} : FloatObject ({value}) invalid; use 0.0 instead", __name__
501
+ )
502
+ return float.__new__(cls, 0.0)
503
+
504
+ def clone(
505
+ self,
506
+ pdf_dest: Any,
507
+ force_duplicate: bool = False,
508
+ ignore_fields: Optional[Sequence[Union[str, int]]] = (),
509
+ ) -> "FloatObject":
510
+ """Clone object into pdf_dest."""
511
+ return cast(
512
+ "FloatObject",
513
+ self._reference_clone(FloatObject(self), pdf_dest, force_duplicate),
514
+ )
515
+
516
+ def hash_bin(self) -> int:
517
+ """
518
+ Used to detect modified object.
519
+
520
+ Returns:
521
+ Hash considering type and value.
522
+
523
+ """
524
+ return hash((self.__class__, self.as_numeric))
525
+
526
+ def myrepr(self) -> str:
527
+ if self == 0: # type: ignore[comparison-overlap]
528
+ return "0.0"
529
+ nb = FLOAT_WRITE_PRECISION - int(log10(abs(self)))
530
+ return f"{self:.{max(1, nb)}f}".rstrip("0").rstrip(".")
531
+
532
+ def __repr__(self) -> str:
533
+ return self.myrepr() # repr(float(self))
534
+
535
+ def as_numeric(self) -> float:
536
+ return float(self)
537
+
538
+ def write_to_stream(
539
+ self, stream: StreamType, encryption_key: Union[None, str, bytes] = None
540
+ ) -> None:
541
+ if encryption_key is not None: # deprecated
542
+ deprecation_no_replacement(
543
+ "the encryption_key parameter of write_to_stream", "5.0.0"
544
+ )
545
+ stream.write(self.myrepr().encode("utf8"))
546
+
547
+
548
+ class NumberObject(int, PdfObject):
549
+ NumberPattern = re.compile(b"[^+-.0-9]")
550
+
551
+ def __new__(cls, value: Any) -> Self:
552
+ try:
553
+ return int.__new__(cls, int(value))
554
+ except ValueError:
555
+ logger_warning(f"NumberObject({value}) invalid; use 0 instead", __name__)
556
+ return int.__new__(cls, 0)
557
+
558
+ def clone(
559
+ self,
560
+ pdf_dest: Any,
561
+ force_duplicate: bool = False,
562
+ ignore_fields: Optional[Sequence[Union[str, int]]] = (),
563
+ ) -> "NumberObject":
564
+ """Clone object into pdf_dest."""
565
+ return cast(
566
+ "NumberObject",
567
+ self._reference_clone(NumberObject(self), pdf_dest, force_duplicate),
568
+ )
569
+
570
+ def hash_bin(self) -> int:
571
+ """
572
+ Used to detect modified object.
573
+
574
+ Returns:
575
+ Hash considering type and value.
576
+
577
+ """
578
+ return hash((self.__class__, self.as_numeric()))
579
+
580
+ def as_numeric(self) -> int:
581
+ return int(repr(self).encode("utf8"))
582
+
583
+ def write_to_stream(
584
+ self, stream: StreamType, encryption_key: Union[None, str, bytes] = None
585
+ ) -> None:
586
+ if encryption_key is not None: # deprecated
587
+ deprecation_no_replacement(
588
+ "the encryption_key parameter of write_to_stream", "5.0.0"
589
+ )
590
+ stream.write(repr(self).encode("utf8"))
591
+
592
+ @staticmethod
593
+ def read_from_stream(stream: StreamType) -> Union["NumberObject", "FloatObject"]:
594
+ num = read_until_regex(stream, NumberObject.NumberPattern)
595
+ if b"." in num:
596
+ return FloatObject(num)
597
+ return NumberObject(num)
598
+
599
+
600
+ class ByteStringObject(bytes, PdfObject):
601
+ """
602
+ Represents a string object where the text encoding could not be determined.
603
+
604
+ This occurs quite often, as the PDF spec doesn't provide an alternate way to
605
+ represent strings -- for example, the encryption data stored in files (like
606
+ /O) is clearly not text, but is still stored in a "String" object.
607
+ """
608
+
609
+ def clone(
610
+ self,
611
+ pdf_dest: Any,
612
+ force_duplicate: bool = False,
613
+ ignore_fields: Optional[Sequence[Union[str, int]]] = (),
614
+ ) -> "ByteStringObject":
615
+ """Clone object into pdf_dest."""
616
+ return cast(
617
+ "ByteStringObject",
618
+ self._reference_clone(
619
+ ByteStringObject(bytes(self)), pdf_dest, force_duplicate
620
+ ),
621
+ )
622
+
623
+ def hash_bin(self) -> int:
624
+ """
625
+ Used to detect modified object.
626
+
627
+ Returns:
628
+ Hash considering type and value.
629
+
630
+ """
631
+ return hash((self.__class__, bytes(self)))
632
+
633
+ @property
634
+ def original_bytes(self) -> bytes:
635
+ """For compatibility with TextStringObject.original_bytes."""
636
+ return self
637
+
638
+ def write_to_stream(
639
+ self, stream: StreamType, encryption_key: Union[None, str, bytes] = None
640
+ ) -> None:
641
+ if encryption_key is not None: # deprecated
642
+ deprecation_no_replacement(
643
+ "the encryption_key parameter of write_to_stream", "5.0.0"
644
+ )
645
+ stream.write(b"<")
646
+ stream.write(binascii.hexlify(self))
647
+ stream.write(b">")
648
+
649
+ def __str__(self) -> str:
650
+ charset_to_try = ["utf-16", *list(NameObject.CHARSETS)]
651
+ for enc in charset_to_try:
652
+ try:
653
+ return self.decode(enc)
654
+ except UnicodeDecodeError:
655
+ pass
656
+ raise PdfReadError("Cannot decode ByteStringObject.")
657
+
658
+
659
+ class TextStringObject(str, PdfObject): # noqa: SLOT000
660
+ """
661
+ A string object that has been decoded into a real unicode string.
662
+
663
+ If read from a PDF document, this string appeared to match the
664
+ PDFDocEncoding, or contained a UTF-16BE BOM mark to cause UTF-16 decoding
665
+ to occur.
666
+ """
667
+
668
+ autodetect_pdfdocencoding: bool
669
+ autodetect_utf16: bool
670
+ utf16_bom: bytes
671
+ _original_bytes: Optional[bytes] = None
672
+
673
+ def __new__(cls, value: Any) -> Self:
674
+ original_bytes = None
675
+ if isinstance(value, bytes):
676
+ original_bytes = value
677
+ value = value.decode("charmap")
678
+ text_string_object = str.__new__(cls, value)
679
+ text_string_object._original_bytes = original_bytes
680
+ text_string_object.autodetect_utf16 = False
681
+ text_string_object.autodetect_pdfdocencoding = False
682
+ text_string_object.utf16_bom = b""
683
+ if original_bytes is not None and original_bytes[:2] in {codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE}:
684
+ # The value of `original_bytes` is only set for inputs being `bytes`.
685
+ # If this is UTF-16 data according to the BOM (first two characters),
686
+ # perform special handling. All other cases should not need any special conversion
687
+ # due to already being a string.
688
+ try:
689
+ text_string_object = str.__new__(cls, original_bytes.decode("utf-16"))
690
+ except UnicodeDecodeError as exception:
691
+ logger_warning(
692
+ f"{exception!s}\ninitial string:{exception.object!r}",
693
+ __name__,
694
+ )
695
+ text_string_object = str.__new__(cls, exception.object[: exception.start].decode("utf-16"))
696
+ text_string_object._original_bytes = original_bytes
697
+ text_string_object.autodetect_utf16 = True
698
+ text_string_object.utf16_bom = original_bytes[:2]
699
+ else:
700
+ try:
701
+ encode_pdfdocencoding(text_string_object)
702
+ text_string_object.autodetect_pdfdocencoding = True
703
+ except UnicodeEncodeError:
704
+ text_string_object.autodetect_utf16 = True
705
+ text_string_object.utf16_bom = codecs.BOM_UTF16_BE
706
+ return text_string_object
707
+
708
+ def clone(
709
+ self,
710
+ pdf_dest: Any,
711
+ force_duplicate: bool = False,
712
+ ignore_fields: Optional[Sequence[Union[str, int]]] = (),
713
+ ) -> "TextStringObject":
714
+ """Clone object into pdf_dest."""
715
+ obj = TextStringObject(self)
716
+ obj._original_bytes = self._original_bytes
717
+ obj.autodetect_pdfdocencoding = self.autodetect_pdfdocencoding
718
+ obj.autodetect_utf16 = self.autodetect_utf16
719
+ obj.utf16_bom = self.utf16_bom
720
+ return cast(
721
+ "TextStringObject", self._reference_clone(obj, pdf_dest, force_duplicate)
722
+ )
723
+
724
+ def hash_bin(self) -> int:
725
+ """
726
+ Used to detect modified object.
727
+
728
+ Returns:
729
+ Hash considering type and value.
730
+
731
+ """
732
+ return hash((self.__class__, self.original_bytes))
733
+
734
+ @property
735
+ def original_bytes(self) -> bytes:
736
+ """
737
+ It is occasionally possible that a text string object gets created where
738
+ a byte string object was expected due to the autodetection mechanism --
739
+ if that occurs, this "original_bytes" property can be used to
740
+ back-calculate what the original encoded bytes were.
741
+ """
742
+ if self._original_bytes is not None:
743
+ return self._original_bytes
744
+ return self.get_original_bytes()
745
+
746
+ def get_original_bytes(self) -> bytes:
747
+ # We're a text string object, but the library is trying to get our raw
748
+ # bytes. This can happen if we auto-detected this string as text, but
749
+ # we were wrong. It's pretty common. Return the original bytes that
750
+ # would have been used to create this object, based upon the autodetect
751
+ # method.
752
+ if self.autodetect_utf16:
753
+ if self.utf16_bom == codecs.BOM_UTF16_LE:
754
+ return codecs.BOM_UTF16_LE + self.encode("utf-16le")
755
+ if self.utf16_bom == codecs.BOM_UTF16_BE:
756
+ return codecs.BOM_UTF16_BE + self.encode("utf-16be")
757
+ return self.encode("utf-16be")
758
+ if self.autodetect_pdfdocencoding:
759
+ return encode_pdfdocencoding(self)
760
+ raise Exception("no information about original bytes") # pragma: no cover
761
+
762
+ def get_encoded_bytes(self) -> bytes:
763
+ # Try to write the string out as a PDFDocEncoding encoded string. It's
764
+ # nicer to look at in the PDF file. Sadly, we take a performance hit
765
+ # here for trying...
766
+ try:
767
+ if self._original_bytes is not None:
768
+ return self._original_bytes
769
+ if self.autodetect_utf16:
770
+ raise UnicodeEncodeError("", "forced", -1, -1, "")
771
+ bytearr = encode_pdfdocencoding(self)
772
+ except UnicodeEncodeError:
773
+ if self.utf16_bom == codecs.BOM_UTF16_LE:
774
+ bytearr = codecs.BOM_UTF16_LE + self.encode("utf-16le")
775
+ elif self.utf16_bom == codecs.BOM_UTF16_BE:
776
+ bytearr = codecs.BOM_UTF16_BE + self.encode("utf-16be")
777
+ else:
778
+ bytearr = self.encode("utf-16be")
779
+ return bytearr
780
+
781
+ def write_to_stream(
782
+ self, stream: StreamType, encryption_key: Union[None, str, bytes] = None
783
+ ) -> None:
784
+ if encryption_key is not None: # deprecated
785
+ deprecation_no_replacement(
786
+ "the encryption_key parameter of write_to_stream", "5.0.0"
787
+ )
788
+ bytearr = self.get_encoded_bytes()
789
+ stream.write(b"(")
790
+ for c_ in iter_unpack("c", bytearr):
791
+ c = cast(bytes, c_[0])
792
+ if not c.isalnum() and c != b" ":
793
+ # This:
794
+ # stream.write(rf"\{c:0>3o}".encode())
795
+ # gives
796
+ # https://github.com/davidhalter/parso/issues/207
797
+ stream.write(b"\\%03o" % ord(c))
798
+ else:
799
+ stream.write(c)
800
+ stream.write(b")")
801
+
802
+
803
+ class NameObject(str, PdfObject): # noqa: SLOT000
804
+ delimiter_pattern = re.compile(rb"\s+|[\(\)<>\[\]{}/%]")
805
+ prefix = b"/"
806
+ renumber_table: ClassVar[dict[str, bytes]] = {
807
+ **{chr(i): f"#{i:02X}".encode() for i in b"#()<>[]{}/%"},
808
+ **{chr(i): f"#{i:02X}".encode() for i in range(33)},
809
+ }
810
+
811
+ def clone(
812
+ self,
813
+ pdf_dest: Any,
814
+ force_duplicate: bool = False,
815
+ ignore_fields: Optional[Sequence[Union[str, int]]] = (),
816
+ ) -> "NameObject":
817
+ """Clone object into pdf_dest."""
818
+ return cast(
819
+ "NameObject",
820
+ self._reference_clone(NameObject(self), pdf_dest, force_duplicate),
821
+ )
822
+
823
+ def hash_bin(self) -> int:
824
+ """
825
+ Used to detect modified object.
826
+
827
+ Returns:
828
+ Hash considering type and value.
829
+
830
+ """
831
+ return hash((self.__class__, self))
832
+
833
+ def write_to_stream(
834
+ self, stream: StreamType, encryption_key: Union[None, str, bytes] = None
835
+ ) -> None:
836
+ if encryption_key is not None: # deprecated
837
+ deprecation_no_replacement(
838
+ "the encryption_key parameter of write_to_stream", "5.0.0"
839
+ )
840
+ stream.write(self.renumber())
841
+
842
+ def renumber(self) -> bytes:
843
+ out = self[0].encode("utf-8")
844
+ if out != b"/":
845
+ deprecation_no_replacement(
846
+ f"Incorrect first char in NameObject, should start with '/': ({self})",
847
+ "5.0.0",
848
+ )
849
+ parts = [out]
850
+ for c in self[1:]:
851
+ if c > "~":
852
+ parts.extend(f"#{x:02X}".encode() for x in c.encode("utf-8"))
853
+ else:
854
+ try:
855
+ parts.append(self.renumber_table[c])
856
+ except KeyError:
857
+ parts.append(c.encode("utf-8"))
858
+ return b"".join(parts)
859
+
860
+ def _sanitize(self) -> "NameObject":
861
+ """
862
+ Sanitize the NameObject's name to be a valid PDF name part
863
+ (alphanumeric, underscore, hyphen). The _sanitize method replaces
864
+ spaces and any non-alphanumeric/non-underscore/non-hyphen with
865
+ underscores.
866
+
867
+ Returns:
868
+ NameObject with sanitized name.
869
+ """
870
+ name = str(self).removeprefix("/")
871
+ name = re.sub(r"\ ", "_", name)
872
+ name = re.sub(r"[^a-zA-Z0-9_-]", "_", name)
873
+ return NameObject("/" + name)
874
+
875
+ @classproperty
876
+ def surfix(cls) -> bytes: # noqa: N805
877
+ deprecation_with_replacement("surfix", "prefix", "5.0.0")
878
+ return b"/"
879
+
880
+ @staticmethod
881
+ def unnumber(sin: bytes) -> bytes:
882
+ result = bytearray()
883
+ i = 0
884
+ while i < len(sin):
885
+ if sin[i:i + 1] == b"#":
886
+ try:
887
+ result.append(int(sin[i + 1 : i + 3], 16))
888
+ i += 3
889
+ continue
890
+ except (ValueError, IndexError):
891
+ # if the 2 characters after # can not be converted to hex
892
+ # we change nothing and carry on
893
+ pass
894
+ result.append(sin[i])
895
+ i += 1
896
+ return bytes(result)
897
+
898
+ CHARSETS = ("utf-8", "gbk", "latin1")
899
+
900
+ @staticmethod
901
+ def read_from_stream(stream: StreamType, pdf: Any) -> "NameObject": # PdfReader
902
+ name = stream.read(1)
903
+ if name != NameObject.prefix:
904
+ raise PdfReadError("Name read error")
905
+ name += read_until_regex(stream, NameObject.delimiter_pattern)
906
+ try:
907
+ # Name objects should represent irregular characters
908
+ # with a '#' followed by the symbol's hex number
909
+ name = NameObject.unnumber(name)
910
+ for enc in NameObject.CHARSETS:
911
+ try:
912
+ ret = name.decode(enc)
913
+ return NameObject(ret)
914
+ except Exception:
915
+ pass
916
+ raise UnicodeDecodeError("", name, 0, 0, "Code Not Found")
917
+ except (UnicodeEncodeError, UnicodeDecodeError) as e:
918
+ if not pdf.strict:
919
+ logger_warning(
920
+ f"Illegal character in NameObject ({name!r}), "
921
+ "you may need to adjust NameObject.CHARSETS",
922
+ __name__,
923
+ )
924
+ return NameObject(name.decode("charmap"))
925
+ raise PdfReadError(
926
+ f"Illegal character in NameObject ({name!r}). "
927
+ "You may need to adjust NameObject.CHARSETS.",
928
+ ) from e
929
+
930
+
931
+ def encode_pdfdocencoding(unicode_string: str) -> bytes:
932
+ try:
933
+ return bytes([_pdfdoc_encoding_rev[k] for k in unicode_string])
934
+ except KeyError:
935
+ raise UnicodeEncodeError(
936
+ "pdfdocencoding",
937
+ unicode_string,
938
+ -1,
939
+ -1,
940
+ "does not exist in translation table",
941
+ )
942
+
943
+
944
+ def is_null_or_none(x: Any) -> TypeGuard[Union[None, NullObject, IndirectObject]]:
945
+ """
946
+ Returns:
947
+ True if x is None or NullObject.
948
+
949
+ """
950
+ return x is None or (
951
+ isinstance(x, PdfObject)
952
+ and (x.get_object() is None or isinstance(x.get_object(), NullObject))
953
+ )
micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/generic/_data_structures.py ADDED
@@ -0,0 +1,1804 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2006, Mathieu Fenniak
2
+ # All rights reserved.
3
+ #
4
+ # Redistribution and use in source and binary forms, with or without
5
+ # modification, are permitted provided that the following conditions are
6
+ # met:
7
+ #
8
+ # * Redistributions of source code must retain the above copyright notice,
9
+ # this list of conditions and the following disclaimer.
10
+ # * Redistributions in binary form must reproduce the above copyright notice,
11
+ # this list of conditions and the following disclaimer in the documentation
12
+ # and/or other materials provided with the distribution.
13
+ # * The name of the author may not be used to endorse or promote products
14
+ # derived from this software without specific prior written permission.
15
+ #
16
+ # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17
+ # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18
+ # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19
+ # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
20
+ # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21
+ # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22
+ # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23
+ # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24
+ # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25
+ # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26
+ # POSSIBILITY OF SUCH DAMAGE.
27
+
28
+
29
+ __author__ = "Mathieu Fenniak"
30
+ __author_email__ = "biziqe@mathieu.fenniak.net"
31
+
32
+ import logging
33
+ import re
34
+ import sys
35
+ from collections.abc import Iterable, Sequence
36
+ from io import BytesIO
37
+ from math import ceil
38
+ from typing import (
39
+ Any,
40
+ Callable,
41
+ Optional,
42
+ Union,
43
+ cast,
44
+ )
45
+
46
+ from .._protocols import PdfReaderProtocol, PdfWriterProtocol, XmpInformationProtocol
47
+ from .._utils import (
48
+ WHITESPACES,
49
+ BinaryStreamType,
50
+ StreamType,
51
+ deprecation_no_replacement,
52
+ logger_warning,
53
+ read_non_whitespace,
54
+ read_until_regex,
55
+ read_until_whitespace,
56
+ skip_over_comment,
57
+ )
58
+ from ..constants import (
59
+ CheckboxRadioButtonAttributes,
60
+ FieldDictionaryAttributes,
61
+ OutlineFontFlag,
62
+ StreamAttributes,
63
+ )
64
+ from ..constants import FilterTypes as FT
65
+ from ..constants import TypArguments as TA
66
+ from ..constants import TypFitArguments as TF
67
+ from ..errors import STREAM_TRUNCATED_PREMATURELY, LimitReachedError, PdfReadError, PdfStreamError
68
+ from ._base import (
69
+ BooleanObject,
70
+ ByteStringObject,
71
+ FloatObject,
72
+ IndirectObject,
73
+ NameObject,
74
+ NullObject,
75
+ NumberObject,
76
+ PdfObject,
77
+ TextStringObject,
78
+ is_null_or_none,
79
+ )
80
+ from ._fit import Fit
81
+ from ._image_inline import (
82
+ extract_inline__ascii85_decode,
83
+ extract_inline__ascii_hex_decode,
84
+ extract_inline__dct_decode,
85
+ extract_inline__run_length_decode,
86
+ extract_inline_default,
87
+ )
88
+ from ._utils import read_hex_string_from_stream, read_string_from_stream
89
+
90
+ if sys.version_info >= (3, 11):
91
+ from typing import Self
92
+ else:
93
+ from typing_extensions import Self
94
+
95
+ logger = logging.getLogger(__name__)
96
+
97
+ IndirectPattern = re.compile(rb"[+-]?(\d+)\s+(\d+)\s+R[^a-zA-Z]")
98
+
99
+
100
+ class ArrayObject(list[Any], PdfObject):
101
+ def replicate(
102
+ self,
103
+ pdf_dest: PdfWriterProtocol,
104
+ ) -> "ArrayObject":
105
+ arr = cast(
106
+ "ArrayObject",
107
+ self._reference_clone(ArrayObject(), pdf_dest, False),
108
+ )
109
+ for data in self:
110
+ if hasattr(data, "replicate"):
111
+ arr.append(data.replicate(pdf_dest))
112
+ else:
113
+ arr.append(data)
114
+ return arr
115
+
116
+ def clone(
117
+ self,
118
+ pdf_dest: PdfWriterProtocol,
119
+ force_duplicate: bool = False,
120
+ ignore_fields: Optional[Sequence[Union[str, int]]] = (),
121
+ ) -> "ArrayObject":
122
+ """Clone object into pdf_dest."""
123
+ try:
124
+ if self.indirect_reference.pdf == pdf_dest and not force_duplicate: # type: ignore
125
+ return self
126
+ except Exception:
127
+ pass
128
+ arr = cast(
129
+ "ArrayObject",
130
+ self._reference_clone(ArrayObject(), pdf_dest, force_duplicate=True),
131
+ )
132
+ for data in self:
133
+ if isinstance(data, StreamObject):
134
+ dup = data._reference_clone(
135
+ data.clone(pdf_dest, force_duplicate, ignore_fields),
136
+ pdf_dest,
137
+ force_duplicate,
138
+ )
139
+ arr.append(dup.indirect_reference)
140
+ elif isinstance(data, IndirectObject) and isinstance(resolved := data.get_object(), StreamObject):
141
+ dup = data._reference_clone(
142
+ resolved.clone(pdf_dest, force_duplicate=True, ignore_fields=ignore_fields),
143
+ pdf_dest,
144
+ force_duplicate,
145
+ )
146
+ arr.append(dup.indirect_reference)
147
+ elif hasattr(data, "clone"):
148
+ arr.append(data.clone(pdf_dest, force_duplicate, ignore_fields))
149
+ else:
150
+ arr.append(data)
151
+ return arr
152
+
153
+ def hash_bin(self) -> int:
154
+ """
155
+ Used to detect modified object.
156
+
157
+ Returns:
158
+ Hash considering type and value.
159
+
160
+ """
161
+ return hash((self.__class__, tuple(x.hash_bin() for x in self)))
162
+
163
+ def items(self) -> Iterable[Any]:
164
+ """Emulate DictionaryObject.items for a list (index, object)."""
165
+ return enumerate(self)
166
+
167
+ def _to_lst(self, lst: Any) -> list[Any]:
168
+ # Convert to list, internal
169
+ result: list[Any]
170
+ if isinstance(lst, (list, tuple, set)):
171
+ result = list(lst)
172
+ elif isinstance(lst, PdfObject):
173
+ result = [lst]
174
+ elif isinstance(lst, str):
175
+ if lst[0] == "/":
176
+ result = [NameObject(lst)]
177
+ else:
178
+ result = [TextStringObject(lst)]
179
+ elif isinstance(lst, bytes):
180
+ result = [ByteStringObject(lst)]
181
+ else: # for numbers,...
182
+ result = [lst]
183
+ return result
184
+
185
+ def __add__(self, lst: Any) -> "ArrayObject":
186
+ """
187
+ Allow extension by adding list or add one element only
188
+
189
+ Args:
190
+ lst: any list, tuples are extended the list.
191
+ other types(numbers,...) will be appended.
192
+ if str is passed it will be converted into TextStringObject
193
+ or NameObject (if starting with "/")
194
+ if bytes is passed it will be converted into ByteStringObject
195
+
196
+ Returns:
197
+ ArrayObject with all elements
198
+
199
+ """
200
+ temp = ArrayObject(self)
201
+ temp.extend(self._to_lst(lst))
202
+ return temp
203
+
204
+ def __iadd__(self, lst: Any) -> Self:
205
+ """
206
+ Allow extension by adding list or add one element only
207
+
208
+ Args:
209
+ lst: any list, tuples are extended the list.
210
+ other types(numbers,...) will be appended.
211
+ if str is passed it will be converted into TextStringObject
212
+ or NameObject (if starting with "/")
213
+ if bytes is passed it will be converted into ByteStringObject
214
+
215
+ """
216
+ self.extend(self._to_lst(lst))
217
+ return self
218
+
219
+ def __isub__(self, lst: Any) -> Self:
220
+ """Allow to remove items"""
221
+ for x in self._to_lst(lst):
222
+ try:
223
+ index = self.index(x)
224
+ del self[index]
225
+ except ValueError:
226
+ pass
227
+ return self
228
+
229
+ def write_to_stream(
230
+ self, stream: StreamType, encryption_key: Union[None, str, bytes] = None
231
+ ) -> None:
232
+ if encryption_key is not None: # deprecated
233
+ deprecation_no_replacement(
234
+ "the encryption_key parameter of write_to_stream", "5.0.0"
235
+ )
236
+ stream.write(b"[")
237
+ for data in self:
238
+ stream.write(b" ")
239
+ data.write_to_stream(stream)
240
+ stream.write(b" ]")
241
+
242
+ @staticmethod
243
+ def read_from_stream(
244
+ stream: StreamType,
245
+ pdf: Optional[PdfReaderProtocol],
246
+ forced_encoding: Union[None, str, list[str], dict[int, str]] = None,
247
+ ) -> "ArrayObject":
248
+ arr = ArrayObject()
249
+ tmp = stream.read(1)
250
+ if tmp != b"[":
251
+ raise PdfReadError("Could not read array")
252
+ while True:
253
+ # skip leading whitespace
254
+ tok = stream.read(1)
255
+ while tok.isspace():
256
+ tok = stream.read(1)
257
+ if tok == b"":
258
+ break
259
+ if tok == b"%":
260
+ stream.seek(-1, 1)
261
+ skip_over_comment(stream)
262
+ continue
263
+ stream.seek(-1, 1)
264
+ # check for array ending
265
+ peek_ahead = stream.read(1)
266
+ if peek_ahead == b"]":
267
+ break
268
+ stream.seek(-1, 1)
269
+ # read and append object
270
+ arr.append(read_object(stream, pdf, forced_encoding))
271
+ return arr
272
+
273
+
274
+ class DictionaryObject(dict[Any, Any], PdfObject):
275
+ def replicate(
276
+ self,
277
+ pdf_dest: PdfWriterProtocol,
278
+ ) -> "DictionaryObject":
279
+ d__ = cast(
280
+ "DictionaryObject",
281
+ self._reference_clone(self.__class__(), pdf_dest, False),
282
+ )
283
+ for k, v in self.items():
284
+ d__[k.replicate(pdf_dest)] = (
285
+ v.replicate(pdf_dest) if hasattr(v, "replicate") else v
286
+ )
287
+ return d__
288
+
289
+ def clone(
290
+ self,
291
+ pdf_dest: PdfWriterProtocol,
292
+ force_duplicate: bool = False,
293
+ ignore_fields: Optional[Sequence[Union[str, int]]] = (),
294
+ ) -> "DictionaryObject":
295
+ """Clone object into pdf_dest."""
296
+ try:
297
+ if self.indirect_reference.pdf == pdf_dest and not force_duplicate: # type: ignore
298
+ return self
299
+ except Exception:
300
+ pass
301
+
302
+ visited: set[tuple[int, int]] = set() # (idnum, generation)
303
+ d__ = cast(
304
+ "DictionaryObject",
305
+ self._reference_clone(self.__class__(), pdf_dest, force_duplicate),
306
+ )
307
+ if ignore_fields is None:
308
+ ignore_fields = []
309
+ if len(d__.keys()) == 0:
310
+ d__._clone(self, pdf_dest, force_duplicate, ignore_fields, visited)
311
+ return d__
312
+
313
+ def _clone(
314
+ self,
315
+ src: "DictionaryObject",
316
+ pdf_dest: PdfWriterProtocol,
317
+ force_duplicate: bool,
318
+ ignore_fields: Optional[Sequence[Union[str, int]]],
319
+ visited: set[tuple[int, int]], # (idnum, generation)
320
+ ) -> None:
321
+ """
322
+ Update the object from src.
323
+
324
+ Args:
325
+ src: "DictionaryObject":
326
+ pdf_dest:
327
+ force_duplicate:
328
+ ignore_fields:
329
+
330
+ """
331
+ # First we remove the ignore_fields
332
+ # that are for a limited number of levels
333
+ assert ignore_fields is not None
334
+ ignore_fields = list(ignore_fields)
335
+ x = 0
336
+ while x < len(ignore_fields):
337
+ if isinstance(ignore_fields[x], int):
338
+ if cast(int, ignore_fields[x]) <= 0:
339
+ del ignore_fields[x]
340
+ del ignore_fields[x]
341
+ continue
342
+ ignore_fields[x] -= 1 # type:ignore
343
+ x += 1
344
+ # Check if this is a chain list, we need to loop to prevent recur
345
+ if any(
346
+ field not in ignore_fields
347
+ and field in src
348
+ and isinstance(src.raw_get(field), IndirectObject)
349
+ and isinstance(src[field], DictionaryObject)
350
+ and (
351
+ src.get("/Type", None) is None
352
+ or cast(DictionaryObject, src[field]).get("/Type", None) is None
353
+ or src.get("/Type", None)
354
+ == cast(DictionaryObject, src[field]).get("/Type", None)
355
+ )
356
+ for field in ["/Next", "/Prev", "/N", "/V"]
357
+ ):
358
+ ignore_fields = list(ignore_fields)
359
+ for lst in (("/Next", "/Prev"), ("/N", "/V")):
360
+ for k in lst:
361
+ objs = []
362
+ if (
363
+ k in src
364
+ and k not in self
365
+ and isinstance(src.raw_get(k), IndirectObject)
366
+ and isinstance(src[k], DictionaryObject)
367
+ # If need to go further the idea is to check
368
+ # that the types are the same
369
+ and (
370
+ src.get("/Type", None) is None
371
+ or cast(DictionaryObject, src[k]).get("/Type", None) is None
372
+ or src.get("/Type", None)
373
+ == cast(DictionaryObject, src[k]).get("/Type", None)
374
+ )
375
+ ):
376
+ cur_obj: Optional[DictionaryObject] = cast(
377
+ "DictionaryObject", src[k]
378
+ )
379
+ prev_obj: Optional[DictionaryObject] = self
380
+ while cur_obj is not None:
381
+ clon = cast(
382
+ "DictionaryObject",
383
+ cur_obj._reference_clone(
384
+ cur_obj.__class__(), pdf_dest, force_duplicate
385
+ ),
386
+ )
387
+ # Check to see if we've previously processed our item
388
+ if clon.indirect_reference is not None:
389
+ idnum = clon.indirect_reference.idnum
390
+ generation = clon.indirect_reference.generation
391
+ if (idnum, generation) in visited:
392
+ cur_obj = None
393
+ break
394
+ visited.add((idnum, generation))
395
+ objs.append((cur_obj, clon))
396
+ assert prev_obj is not None
397
+ prev_obj[NameObject(k)] = clon.indirect_reference
398
+ prev_obj = clon
399
+ try:
400
+ if cur_obj == src:
401
+ cur_obj = None
402
+ else:
403
+ cur_obj = cast("DictionaryObject", cur_obj[k])
404
+ except Exception:
405
+ cur_obj = None
406
+ for s, c in objs:
407
+ c._clone(
408
+ s, pdf_dest, force_duplicate, ignore_fields, visited
409
+ )
410
+
411
+ for k, v in src.items():
412
+ if k not in ignore_fields:
413
+ if isinstance(v, StreamObject):
414
+ if not hasattr(v, "indirect_reference"):
415
+ v.indirect_reference = None
416
+ vv = v.clone(pdf_dest, force_duplicate, ignore_fields)
417
+ assert vv.indirect_reference is not None
418
+ self[k.clone(pdf_dest)] = vv.indirect_reference
419
+ elif k not in self:
420
+ self[NameObject(k)] = (
421
+ v.clone(pdf_dest, force_duplicate, ignore_fields)
422
+ if hasattr(v, "clone")
423
+ else v
424
+ )
425
+
426
+ def hash_bin(self) -> int:
427
+ """
428
+ Used to detect modified object.
429
+
430
+ Returns:
431
+ Hash considering type and value.
432
+
433
+ """
434
+ return hash(
435
+ (self.__class__, tuple(((k, v.hash_bin()) for k, v in self.items())))
436
+ )
437
+
438
+ def raw_get(self, key: Any) -> Any:
439
+ return dict.__getitem__(self, key)
440
+
441
+ def get_inherited(self, key: str, default: Any = None) -> Any:
442
+ """
443
+ Returns the value of a key or from the parent if not found.
444
+ If not found returns default.
445
+
446
+ Args:
447
+ key: string identifying the field to return
448
+
449
+ default: default value to return
450
+
451
+ Returns:
452
+ Current key or inherited one, otherwise default value.
453
+
454
+ """
455
+ if key in self:
456
+ return self[key]
457
+ try:
458
+ if "/Parent" not in self:
459
+ return default
460
+ raise KeyError("Not present")
461
+ except KeyError:
462
+ return cast("DictionaryObject", self["/Parent"].get_object()).get_inherited(
463
+ key, default
464
+ )
465
+
466
+ def __setitem__(self, key: Any, value: Any) -> Any:
467
+ if not isinstance(key, PdfObject):
468
+ raise ValueError("Key must be a PdfObject")
469
+ if not isinstance(value, PdfObject):
470
+ raise ValueError("Value must be a PdfObject")
471
+ return dict.__setitem__(self, key, value)
472
+
473
+ def setdefault(self, key: Any, value: Optional[Any] = None) -> Any:
474
+ if not isinstance(key, PdfObject):
475
+ raise ValueError("Key must be a PdfObject")
476
+ if not isinstance(value, PdfObject):
477
+ raise ValueError("Value must be a PdfObject")
478
+ return dict.setdefault(self, key, value)
479
+
480
+ def __getitem__(self, key: Any) -> PdfObject:
481
+ return cast(PdfObject, dict.__getitem__(self, key).get_object())
482
+
483
+ @property
484
+ def xmp_metadata(self) -> Optional[XmpInformationProtocol]:
485
+ """
486
+ Retrieve XMP (Extensible Metadata Platform) data relevant to this
487
+ object, if available.
488
+
489
+ See Table 347 — Additional entries in a metadata stream dictionary.
490
+
491
+ Returns:
492
+ Returns a :class:`~pypdf.xmp.XmpInformation` instance
493
+ that can be used to access XMP metadata from the document. Can also
494
+ return None if no metadata was found on the document root.
495
+
496
+ """
497
+ from ..xmp import XmpInformation # noqa: PLC0415
498
+
499
+ metadata = self.get("/Metadata", None)
500
+ if is_null_or_none(metadata):
501
+ return None
502
+ assert metadata is not None, "mypy"
503
+ metadata = metadata.get_object()
504
+ return XmpInformation(metadata)
505
+
506
+ def write_to_stream(
507
+ self, stream: StreamType, encryption_key: Union[None, str, bytes] = None
508
+ ) -> None:
509
+ if encryption_key is not None: # deprecated
510
+ deprecation_no_replacement(
511
+ "the encryption_key parameter of write_to_stream", "5.0.0"
512
+ )
513
+ stream.write(b"<<\n")
514
+ for key, value in self.items():
515
+ if len(key) > 2 and key[1] == "%" and key[-1] == "%":
516
+ continue
517
+ key.write_to_stream(stream, encryption_key)
518
+ stream.write(b" ")
519
+ value.write_to_stream(stream)
520
+ stream.write(b"\n")
521
+ stream.write(b">>")
522
+
523
+ @classmethod
524
+ def _get_next_object_position(
525
+ cls, position_before: int, position_end: int, generations: list[int], pdf: PdfReaderProtocol
526
+ ) -> int:
527
+ out = position_end
528
+ for generation in generations:
529
+ location = pdf.xref[generation]
530
+ values = [x for x in location.values() if position_before < x <= position_end]
531
+ if values:
532
+ out = min(out, *values)
533
+ return out
534
+
535
+ @classmethod
536
+ def _read_unsized_from_stream(
537
+ cls, stream: BinaryStreamType, pdf: PdfReaderProtocol
538
+ ) -> bytes:
539
+ object_position = cls._get_next_object_position(
540
+ position_before=stream.tell(), position_end=2 ** 32, generations=list(pdf.xref), pdf=pdf
541
+ ) - 1
542
+ current_position = stream.tell()
543
+ # Read until the next object position.
544
+ read_value = stream.read(object_position - stream.tell())
545
+ endstream_position = read_value.find(b"endstream")
546
+ if endstream_position < 0:
547
+ raise PdfReadError(
548
+ f"Unable to find 'endstream' marker for obj starting at {current_position}."
549
+ )
550
+ # 9 = len(b"endstream")
551
+ stream.seek(current_position + endstream_position + 9)
552
+ return read_value[: endstream_position - 1]
553
+
554
+ @staticmethod
555
+ def read_from_stream(
556
+ stream: StreamType,
557
+ pdf: Optional[PdfReaderProtocol],
558
+ forced_encoding: Union[None, str, list[str], dict[int, str]] = None,
559
+ ) -> "DictionaryObject":
560
+ tmp = stream.read(2)
561
+ if tmp != b"<<":
562
+ raise PdfReadError(
563
+ f"Dictionary read error at byte {hex(stream.tell())}: "
564
+ "stream must begin with '<<'"
565
+ )
566
+ data: dict[Any, Any] = {}
567
+ while True:
568
+ tok = read_non_whitespace(stream)
569
+ if tok == b"\x00":
570
+ continue
571
+ if tok == b"%":
572
+ stream.seek(-1, 1)
573
+ skip_over_comment(stream)
574
+ continue
575
+ if not tok:
576
+ raise PdfStreamError(STREAM_TRUNCATED_PREMATURELY)
577
+
578
+ if tok == b">":
579
+ stream.read(1)
580
+ break
581
+ stream.seek(-1, 1)
582
+ try:
583
+ try:
584
+ key = read_object(stream, pdf)
585
+ if isinstance(key, NullObject):
586
+ break
587
+ if not isinstance(key, NameObject):
588
+ raise PdfReadError(
589
+ f"Expecting a NameObject for key but found {key!r}"
590
+ )
591
+ except PdfReadError as exc:
592
+ if pdf is not None and pdf.strict:
593
+ raise
594
+ logger_warning(exc.__repr__(), __name__)
595
+ continue
596
+ tok = read_non_whitespace(stream)
597
+ stream.seek(-1, 1)
598
+ value = read_object(stream, pdf, forced_encoding)
599
+ except (RecursionError, LimitReachedError) as exc:
600
+ raise PdfReadError(exc.__repr__())
601
+ except Exception as exc:
602
+ if pdf is not None and pdf.strict:
603
+ raise PdfReadError(exc.__repr__())
604
+ logger_warning(exc.__repr__(), __name__)
605
+ retval = DictionaryObject()
606
+ retval.update(data)
607
+ return retval # return partial data
608
+
609
+ if not data.get(key):
610
+ data[key] = value
611
+ else:
612
+ # multiple definitions of key not permitted
613
+ msg = (
614
+ f"Multiple definitions in dictionary at byte "
615
+ f"{hex(stream.tell())} for key {key}"
616
+ )
617
+ if pdf is not None and pdf.strict:
618
+ raise PdfReadError(msg)
619
+ logger_warning(msg, __name__)
620
+
621
+ pos = stream.tell()
622
+ s = read_non_whitespace(stream)
623
+ if s == b"s" and stream.read(5) == b"tream":
624
+ eol = stream.read(1)
625
+ # Occasional PDF file output has spaces after 'stream' keyword but before EOL.
626
+ # patch provided by Danial Sandler
627
+ while eol == b" ":
628
+ eol = stream.read(1)
629
+ if eol not in (b"\n", b"\r"):
630
+ raise PdfStreamError("Stream data must be followed by a newline")
631
+ if eol == b"\r" and stream.read(1) != b"\n":
632
+ stream.seek(-1, 1)
633
+ # this is a stream object, not a dictionary
634
+ if StreamAttributes.LENGTH not in data:
635
+ if pdf is not None and pdf.strict:
636
+ raise PdfStreamError("Stream length not defined")
637
+ logger_warning(
638
+ f"Stream length not defined @pos={stream.tell()}", __name__
639
+ )
640
+ data[NameObject(StreamAttributes.LENGTH)] = NumberObject(-1)
641
+ length = data[StreamAttributes.LENGTH]
642
+ if isinstance(length, IndirectObject):
643
+ t = stream.tell()
644
+ assert pdf is not None, "mypy"
645
+ length = pdf.get_object(length)
646
+ stream.seek(t, 0)
647
+ if length is None: # if the PDF is damaged
648
+ length = -1
649
+ pstart = stream.tell()
650
+ if length >= 0:
651
+ from ..filters import MAX_DECLARED_STREAM_LENGTH # noqa: PLC0415
652
+ if length > MAX_DECLARED_STREAM_LENGTH:
653
+ raise LimitReachedError(f"Declared stream length of {length} exceeds maximum allowed length.")
654
+
655
+ data["__streamdata__"] = stream.read(length)
656
+ else:
657
+ data["__streamdata__"] = read_until_regex(
658
+ stream, re.compile(b"endstream")
659
+ )
660
+ e = read_non_whitespace(stream)
661
+ ndstream = stream.read(8)
662
+ if (e + ndstream) != b"endstream":
663
+ # the odd PDF file has a length that is too long, so
664
+ # we need to read backwards to find the "endstream" ending.
665
+ # ReportLab (unknown version) generates files with this bug,
666
+ # and Python users into PDF files tend to be our audience.
667
+ # we need to do this to correct the streamdata and chop off
668
+ # an extra character.
669
+ pos = stream.tell()
670
+ stream.seek(-10, 1)
671
+ end = stream.read(9)
672
+ if end == b"endstream":
673
+ # we found it by looking back one character further.
674
+ data["__streamdata__"] = data["__streamdata__"][:-1]
675
+ elif pdf is not None and not pdf.strict:
676
+ stream.seek(pstart, 0)
677
+ data["__streamdata__"] = DictionaryObject._read_unsized_from_stream(stream, pdf)
678
+ pos = stream.tell()
679
+ else:
680
+ stream.seek(pos, 0)
681
+ raise PdfReadError(
682
+ "Unable to find 'endstream' marker after stream at byte "
683
+ f"{hex(stream.tell())} (nd='{ndstream!r}', end='{end!r}')."
684
+ )
685
+ else:
686
+ stream.seek(pos, 0)
687
+ if "__streamdata__" in data:
688
+ return StreamObject.initialize_from_dictionary(data)
689
+ retval = DictionaryObject()
690
+ retval.update(data)
691
+ return retval
692
+
693
+
694
+ class TreeObject(DictionaryObject):
695
+ def __init__(self, dct: Optional[DictionaryObject] = None) -> None:
696
+ DictionaryObject.__init__(self)
697
+ if dct:
698
+ self.update(dct)
699
+
700
+ def has_children(self) -> bool:
701
+ return "/First" in self
702
+
703
+ def __iter__(self) -> Any:
704
+ return self.children()
705
+
706
+ def children(self) -> Iterable[Any]:
707
+ if not self.has_children():
708
+ return
709
+
710
+ child_ref = self[NameObject("/First")]
711
+ last = self[NameObject("/Last")]
712
+ child = child_ref.get_object()
713
+ visited: set[int] = set()
714
+ while True:
715
+ child_id = id(child)
716
+ if child_id in visited:
717
+ logger_warning(f"Detected cycle in outline structure for {child}", __name__)
718
+ return
719
+ visited.add(child_id)
720
+
721
+ yield child
722
+
723
+ if child == last:
724
+ return
725
+ child_ref = child.get(NameObject("/Next")) # type: ignore
726
+ if is_null_or_none(child_ref):
727
+ return
728
+ child = child_ref.get_object()
729
+
730
+ def add_child(self, child: Any, pdf: PdfWriterProtocol) -> None:
731
+ self.insert_child(child, None, pdf)
732
+
733
+ def inc_parent_counter_default(
734
+ self, parent: Union[None, IndirectObject, "TreeObject"], n: int
735
+ ) -> None:
736
+ if is_null_or_none(parent):
737
+ return
738
+ assert parent is not None, "mypy"
739
+ parent = cast("TreeObject", parent.get_object())
740
+ if "/Count" in parent:
741
+ parent[NameObject("/Count")] = NumberObject(
742
+ max(0, cast(int, parent[NameObject("/Count")]) + n)
743
+ )
744
+ self.inc_parent_counter_default(parent.get("/Parent", None), n)
745
+
746
+ def inc_parent_counter_outline(
747
+ self, parent: Union[None, IndirectObject, "TreeObject"], n: int
748
+ ) -> None:
749
+ if is_null_or_none(parent):
750
+ return
751
+ assert parent is not None, "mypy"
752
+ parent = cast("TreeObject", parent.get_object())
753
+ # BooleanObject requires comparison with == not is
754
+ opn = parent.get("/%is_open%", True) == True # noqa: E712
755
+ c = cast(int, parent.get("/Count", 0))
756
+ if c < 0:
757
+ c = abs(c)
758
+ parent[NameObject("/Count")] = NumberObject((c + n) * (1 if opn else -1))
759
+ if not opn:
760
+ return
761
+ self.inc_parent_counter_outline(parent.get("/Parent", None), n)
762
+
763
+ def insert_child(
764
+ self,
765
+ child: Any,
766
+ before: Any,
767
+ pdf: PdfWriterProtocol,
768
+ inc_parent_counter: Optional[Callable[..., Any]] = None,
769
+ ) -> IndirectObject:
770
+ if inc_parent_counter is None:
771
+ inc_parent_counter = self.inc_parent_counter_default
772
+ child_obj = child.get_object()
773
+ assert child.indirect_reference is not None, "mypy"
774
+ child_reference: IndirectObject = child.indirect_reference
775
+
776
+ prev: Optional[DictionaryObject]
777
+ if "/First" not in self: # no child yet
778
+ self[NameObject("/First")] = child_reference
779
+ self[NameObject("/Count")] = NumberObject(0)
780
+ self[NameObject("/Last")] = child_reference
781
+ child_obj[NameObject("/Parent")] = self.indirect_reference
782
+ inc_parent_counter(self, child_obj.get("/Count", 1))
783
+ if "/Next" in child_obj:
784
+ del child_obj["/Next"]
785
+ if "/Prev" in child_obj:
786
+ del child_obj["/Prev"]
787
+ return child_reference
788
+ prev = cast("DictionaryObject", self["/Last"])
789
+
790
+ while prev.indirect_reference != before:
791
+ if "/Next" in prev:
792
+ prev = cast("TreeObject", prev["/Next"])
793
+ else: # append at the end
794
+ prev[NameObject("/Next")] = cast("TreeObject", child_reference)
795
+ child_obj[NameObject("/Prev")] = prev.indirect_reference
796
+ child_obj[NameObject("/Parent")] = self.indirect_reference
797
+ if "/Next" in child_obj:
798
+ del child_obj["/Next"]
799
+ self[NameObject("/Last")] = child_reference
800
+ inc_parent_counter(self, child_obj.get("/Count", 1))
801
+ return child_reference
802
+ try: # insert as first or in the middle
803
+ assert isinstance(prev["/Prev"], DictionaryObject)
804
+ prev["/Prev"][NameObject("/Next")] = child_reference
805
+ child_obj[NameObject("/Prev")] = prev["/Prev"]
806
+ except Exception: # it means we are inserting in first position
807
+ del child_obj["/Next"]
808
+ child_obj[NameObject("/Next")] = prev
809
+ prev[NameObject("/Prev")] = child_reference
810
+ child_obj[NameObject("/Parent")] = self.indirect_reference
811
+ inc_parent_counter(self, child_obj.get("/Count", 1))
812
+ return child_reference
813
+
814
+ def _remove_node_from_tree(
815
+ self, prev: Any, prev_ref: Any, cur: Any, last: Any
816
+ ) -> None:
817
+ """
818
+ Adjust the pointers of the linked list and tree node count.
819
+
820
+ Args:
821
+ prev:
822
+ prev_ref:
823
+ cur:
824
+ last:
825
+
826
+ """
827
+ next_ref = cur.get(NameObject("/Next"), None)
828
+ if prev is None:
829
+ if next_ref:
830
+ # Removing first tree node
831
+ next_obj = next_ref.get_object()
832
+ del next_obj[NameObject("/Prev")]
833
+ self[NameObject("/First")] = next_ref
834
+ self[NameObject("/Count")] = NumberObject(
835
+ self[NameObject("/Count")] - 1 # type: ignore
836
+ )
837
+
838
+ else:
839
+ # Removing only tree node
840
+ self[NameObject("/Count")] = NumberObject(0)
841
+ del self[NameObject("/First")]
842
+ if NameObject("/Last") in self:
843
+ del self[NameObject("/Last")]
844
+ else:
845
+ if next_ref:
846
+ # Removing middle tree node
847
+ next_obj = next_ref.get_object()
848
+ next_obj[NameObject("/Prev")] = prev_ref
849
+ prev[NameObject("/Next")] = next_ref
850
+ else:
851
+ # Removing last tree node
852
+ assert cur == last
853
+ del prev[NameObject("/Next")]
854
+ self[NameObject("/Last")] = prev_ref
855
+ self[NameObject("/Count")] = NumberObject(self[NameObject("/Count")] - 1) # type: ignore
856
+
857
+ def remove_child(self, child: Any) -> None:
858
+ child_obj = child.get_object()
859
+ child = child_obj.indirect_reference
860
+
861
+ if NameObject("/Parent") not in child_obj:
862
+ raise ValueError("Removed child does not appear to be a tree item")
863
+ if child_obj[NameObject("/Parent")] != self:
864
+ raise ValueError("Removed child is not a member of this tree")
865
+
866
+ found = False
867
+ prev_ref = None
868
+ prev = None
869
+ cur_ref: Optional[Any] = self[NameObject("/First")]
870
+ cur: Optional[dict[str, Any]] = cur_ref.get_object() # type: ignore
871
+ last_ref = self[NameObject("/Last")]
872
+ last = last_ref.get_object()
873
+ while cur is not None:
874
+ if cur == child_obj:
875
+ self._remove_node_from_tree(prev, prev_ref, cur, last)
876
+ found = True
877
+ break
878
+
879
+ # Go to the next node
880
+ prev_ref = cur_ref
881
+ prev = cur
882
+ if NameObject("/Next") in cur:
883
+ cur_ref = cur[NameObject("/Next")]
884
+ cur = cur_ref.get_object()
885
+ else:
886
+ cur_ref = None
887
+ cur = None
888
+
889
+ if not found:
890
+ raise ValueError("Removal couldn't find item in tree")
891
+
892
+ _reset_node_tree_relationship(child_obj)
893
+
894
+ def remove_from_tree(self) -> None:
895
+ """Remove the object from the tree it is in."""
896
+ if NameObject("/Parent") not in self:
897
+ raise ValueError("Removed child does not appear to be a tree item")
898
+ cast("TreeObject", self["/Parent"]).remove_child(self)
899
+
900
+ def empty_tree(self) -> None:
901
+ for child in self:
902
+ child_obj = child.get_object()
903
+ _reset_node_tree_relationship(child_obj)
904
+
905
+ if NameObject("/Count") in self:
906
+ del self[NameObject("/Count")]
907
+ if NameObject("/First") in self:
908
+ del self[NameObject("/First")]
909
+ if NameObject("/Last") in self:
910
+ del self[NameObject("/Last")]
911
+
912
+
913
+ def _reset_node_tree_relationship(child_obj: Any) -> None:
914
+ """
915
+ Call this after a node has been removed from a tree.
916
+
917
+ This resets the nodes attributes in respect to that tree.
918
+
919
+ Args:
920
+ child_obj:
921
+
922
+ """
923
+ del child_obj[NameObject("/Parent")]
924
+ if NameObject("/Next") in child_obj:
925
+ del child_obj[NameObject("/Next")]
926
+ if NameObject("/Prev") in child_obj:
927
+ del child_obj[NameObject("/Prev")]
928
+
929
+
930
+ class StreamObject(DictionaryObject):
931
+ def __init__(self) -> None:
932
+ self._data: bytes = b""
933
+ self.decoded_self: Optional[DecodedStreamObject] = None
934
+
935
+ def replicate(
936
+ self,
937
+ pdf_dest: PdfWriterProtocol,
938
+ ) -> "StreamObject":
939
+ d__ = cast(
940
+ "StreamObject",
941
+ self._reference_clone(self.__class__(), pdf_dest, False),
942
+ )
943
+ d__._data = self._data
944
+ try:
945
+ decoded_self = self.decoded_self
946
+ if decoded_self is None:
947
+ self.decoded_self = None
948
+ else:
949
+ self.decoded_self = cast(
950
+ "DecodedStreamObject", decoded_self.replicate(pdf_dest)
951
+ )
952
+ except Exception:
953
+ pass
954
+ for k, v in self.items():
955
+ d__[k.replicate(pdf_dest)] = (
956
+ v.replicate(pdf_dest) if hasattr(v, "replicate") else v
957
+ )
958
+ return d__
959
+
960
+ def _clone(
961
+ self,
962
+ src: DictionaryObject,
963
+ pdf_dest: PdfWriterProtocol,
964
+ force_duplicate: bool,
965
+ ignore_fields: Optional[Sequence[Union[str, int]]],
966
+ visited: set[tuple[int, int]],
967
+ ) -> None:
968
+ """
969
+ Update the object from src.
970
+
971
+ Args:
972
+ src:
973
+ pdf_dest:
974
+ force_duplicate:
975
+ ignore_fields:
976
+
977
+ """
978
+ self._data = cast("StreamObject", src)._data
979
+ try:
980
+ decoded_self = cast("StreamObject", src).decoded_self
981
+ if decoded_self is None:
982
+ self.decoded_self = None
983
+ else:
984
+ self.decoded_self = cast(
985
+ "DecodedStreamObject",
986
+ decoded_self.clone(pdf_dest, force_duplicate, ignore_fields),
987
+ )
988
+ except Exception:
989
+ pass
990
+ super()._clone(src, pdf_dest, force_duplicate, ignore_fields, visited)
991
+
992
+ def hash_bin(self) -> int:
993
+ """
994
+ Used to detect modified object.
995
+
996
+ Returns:
997
+ Hash considering type and value.
998
+
999
+ """
1000
+ # Use _data to prevent errors on non-decoded streams.
1001
+ return hash((super().hash_bin(), self._data))
1002
+
1003
+ def get_data(self) -> bytes:
1004
+ return self._data
1005
+
1006
+ def set_data(self, data: bytes) -> None:
1007
+ self._data = data
1008
+
1009
+ def hash_value_data(self) -> bytes:
1010
+ data = super().hash_value_data()
1011
+ data += self.get_data()
1012
+ return data
1013
+
1014
+ def write_to_stream(
1015
+ self, stream: StreamType, encryption_key: Union[None, str, bytes] = None
1016
+ ) -> None:
1017
+ if encryption_key is not None: # deprecated
1018
+ deprecation_no_replacement(
1019
+ "the encryption_key parameter of write_to_stream", "5.0.0"
1020
+ )
1021
+ self[NameObject(StreamAttributes.LENGTH)] = NumberObject(len(self._data))
1022
+ DictionaryObject.write_to_stream(self, stream)
1023
+ del self[StreamAttributes.LENGTH]
1024
+ stream.write(b"\nstream\n")
1025
+ stream.write(self._data)
1026
+ stream.write(b"\nendstream")
1027
+
1028
+ @staticmethod
1029
+ def initialize_from_dictionary(
1030
+ data: dict[str, Any]
1031
+ ) -> Union["EncodedStreamObject", "DecodedStreamObject"]:
1032
+ retval: Union[EncodedStreamObject, DecodedStreamObject]
1033
+ if StreamAttributes.FILTER in data:
1034
+ retval = EncodedStreamObject()
1035
+ else:
1036
+ retval = DecodedStreamObject()
1037
+ retval._data = data["__streamdata__"]
1038
+ del data["__streamdata__"]
1039
+ if StreamAttributes.LENGTH in data:
1040
+ del data[StreamAttributes.LENGTH]
1041
+ retval.update(data)
1042
+ return retval
1043
+
1044
+ def flate_encode(self, level: int = -1) -> "EncodedStreamObject":
1045
+ from ..filters import FlateDecode # noqa: PLC0415
1046
+
1047
+ if StreamAttributes.FILTER in self:
1048
+ f = self[StreamAttributes.FILTER]
1049
+ if isinstance(f, ArrayObject):
1050
+ f = ArrayObject([NameObject(FT.FLATE_DECODE), *f])
1051
+ try:
1052
+ params = ArrayObject(
1053
+ [NullObject(), *self.get(StreamAttributes.DECODE_PARMS, ArrayObject())]
1054
+ )
1055
+ except TypeError:
1056
+ # case of error where the * operator is not working (not an array
1057
+ params = ArrayObject(
1058
+ [NullObject(), self.get(StreamAttributes.DECODE_PARMS, ArrayObject())]
1059
+ )
1060
+ else:
1061
+ f = ArrayObject([NameObject(FT.FLATE_DECODE), f])
1062
+ params = ArrayObject(
1063
+ [NullObject(), self.get(StreamAttributes.DECODE_PARMS, NullObject())]
1064
+ )
1065
+ else:
1066
+ f = NameObject(FT.FLATE_DECODE)
1067
+ params = None
1068
+ retval = EncodedStreamObject()
1069
+ retval.update(self)
1070
+ retval[NameObject(StreamAttributes.FILTER)] = f
1071
+ if params is not None:
1072
+ retval[NameObject(StreamAttributes.DECODE_PARMS)] = params
1073
+ retval._data = FlateDecode.encode(self._data, level)
1074
+ return retval
1075
+
1076
+ def decode_as_image(self, pillow_parameters: Union[dict[str, Any], None] = None) -> Any:
1077
+ """
1078
+ Try to decode the stream object as an image
1079
+
1080
+ Args:
1081
+ pillow_parameters: parameters provided to Pillow Image.save() method,
1082
+ cf. <https://pillow.readthedocs.io/en/stable/reference/Image.html#PIL.Image.Image.save>
1083
+
1084
+ Returns:
1085
+ a PIL image if proper decoding has been found
1086
+ Raises:
1087
+ Exception: Errors during decoding will be reported.
1088
+ It is recommended to catch exceptions to prevent
1089
+ stops in your program.
1090
+
1091
+ """
1092
+ from ._image_xobject import _xobj_to_image # noqa: PLC0415
1093
+
1094
+ if self.get("/Subtype", "") != "/Image":
1095
+ try:
1096
+ msg = f"{self.indirect_reference} does not seem to be an Image" # pragma: no cover
1097
+ except AttributeError:
1098
+ msg = f"{self.__repr__()} object does not seem to be an Image" # pragma: no cover
1099
+ logger_warning(msg, __name__)
1100
+ extension, _, img = _xobj_to_image(self, pillow_parameters)
1101
+ if extension is None:
1102
+ return None # pragma: no cover
1103
+ return img
1104
+
1105
+
1106
+ class DecodedStreamObject(StreamObject):
1107
+ pass
1108
+
1109
+
1110
+ class EncodedStreamObject(StreamObject):
1111
+ def __init__(self) -> None:
1112
+ self.decoded_self: Optional[DecodedStreamObject] = None
1113
+
1114
+ # This overrides the parent method
1115
+ def get_data(self) -> bytes:
1116
+ from ..filters import decode_stream_data # noqa: PLC0415
1117
+
1118
+ if self.decoded_self is not None:
1119
+ # Cached version of decoded object
1120
+ return self.decoded_self.get_data()
1121
+
1122
+ # Create decoded object
1123
+ decoded = DecodedStreamObject()
1124
+ decoded.set_data(decode_stream_data(self))
1125
+ for key, value in self.items():
1126
+ if key not in (StreamAttributes.LENGTH, StreamAttributes.FILTER, StreamAttributes.DECODE_PARMS):
1127
+ decoded[key] = value
1128
+ self.decoded_self = decoded
1129
+ return decoded.get_data()
1130
+
1131
+ # This overrides the parent method:
1132
+ def set_data(self, data: bytes) -> None:
1133
+ from ..filters import FlateDecode # noqa: PLC0415
1134
+
1135
+ if self.get(StreamAttributes.FILTER, "") in (FT.FLATE_DECODE, [FT.FLATE_DECODE]):
1136
+ if not isinstance(data, bytes):
1137
+ raise TypeError("Data must be bytes")
1138
+ if self.decoded_self is None:
1139
+ self.get_data() # to create self.decoded_self
1140
+ assert self.decoded_self is not None, "mypy"
1141
+ self.decoded_self.set_data(data)
1142
+ super().set_data(FlateDecode.encode(data))
1143
+ else:
1144
+ raise PdfReadError(
1145
+ "Streams encoded with a filter different from FlateDecode are not supported"
1146
+ )
1147
+
1148
+
1149
+ CONTENT_STREAM_ARRAY_MAX_LENGTH = 10_000
1150
+
1151
+
1152
+ class ContentStream(DecodedStreamObject):
1153
+ """
1154
+ In order to be fast, this data structure can contain either:
1155
+
1156
+ * raw data in ._data
1157
+ * parsed stream operations in ._operations.
1158
+
1159
+ At any time, ContentStream object can either have both of those fields defined,
1160
+ or one field defined and the other set to None.
1161
+
1162
+ These fields are "rebuilt" lazily, when accessed:
1163
+
1164
+ * when .get_data() is called, if ._data is None, it is rebuilt from ._operations.
1165
+ * when .operations is called, if ._operations is None, it is rebuilt from ._data.
1166
+
1167
+ Conversely, these fields can be invalidated:
1168
+
1169
+ * when .set_data() is called, ._operations is set to None.
1170
+ * when .operations is set, ._data is set to None.
1171
+ """
1172
+
1173
+ def __init__(
1174
+ self,
1175
+ stream: Any,
1176
+ pdf: Any,
1177
+ forced_encoding: Union[None, str, list[str], dict[int, str]] = None,
1178
+ ) -> None:
1179
+ self.pdf = pdf
1180
+ self._operations: list[tuple[Any, bytes]] = []
1181
+
1182
+ # stream may be a StreamObject or an ArrayObject containing
1183
+ # StreamObjects to be concatenated together.
1184
+ if stream is None:
1185
+ super().set_data(b"")
1186
+ else:
1187
+ stream = stream.get_object()
1188
+ if isinstance(stream, ArrayObject):
1189
+ from pypdf.filters import MAX_ARRAY_BASED_STREAM_OUTPUT_LENGTH # noqa: PLC0415
1190
+
1191
+ if (stream_length := len(stream)) > CONTENT_STREAM_ARRAY_MAX_LENGTH:
1192
+ raise LimitReachedError(
1193
+ f"Array-based stream has {stream_length} > {CONTENT_STREAM_ARRAY_MAX_LENGTH} elements."
1194
+ )
1195
+ data = bytearray()
1196
+ length = 0
1197
+ for s in stream:
1198
+ s_resolved = s.get_object()
1199
+ if isinstance(s_resolved, NullObject):
1200
+ continue
1201
+ if not isinstance(s_resolved, StreamObject):
1202
+ # No need to emit an exception here for now - the PDF structure
1203
+ # seems to already be broken beforehand in these cases.
1204
+ logger_warning(
1205
+ f"Expected StreamObject, got {type(s_resolved).__name__} instead. Data might be wrong.",
1206
+ __name__
1207
+ )
1208
+ else:
1209
+ new_data = s_resolved.get_data()
1210
+ length += len(new_data)
1211
+ if length > MAX_ARRAY_BASED_STREAM_OUTPUT_LENGTH:
1212
+ raise LimitReachedError(
1213
+ f"Array-based stream has at least {length} > "
1214
+ f"{MAX_ARRAY_BASED_STREAM_OUTPUT_LENGTH} output bytes."
1215
+ )
1216
+ data += new_data
1217
+ if len(data) == 0 or data[-1:] != b"\n":
1218
+ # There should be no direct need to check for a change of one byte.
1219
+ length += 1
1220
+ data += b"\n"
1221
+ super().set_data(bytes(data))
1222
+ else:
1223
+ stream_data = stream.get_data()
1224
+ assert stream_data is not None
1225
+ super().set_data(stream_data)
1226
+ self.forced_encoding = forced_encoding
1227
+
1228
+ def replicate(
1229
+ self,
1230
+ pdf_dest: PdfWriterProtocol,
1231
+ ) -> "ContentStream":
1232
+ d__ = cast(
1233
+ "ContentStream",
1234
+ self._reference_clone(self.__class__(None, None), pdf_dest, False),
1235
+ )
1236
+ d__._data = self._data
1237
+ try:
1238
+ decoded_self = self.decoded_self
1239
+ if decoded_self is None:
1240
+ self.decoded_self = None
1241
+ else:
1242
+ self.decoded_self = cast(
1243
+ "DecodedStreamObject", decoded_self.replicate(pdf_dest)
1244
+ )
1245
+ except Exception:
1246
+ pass
1247
+ for k, v in self.items():
1248
+ d__[k.replicate(pdf_dest)] = (
1249
+ v.replicate(pdf_dest) if hasattr(v, "replicate") else v
1250
+ )
1251
+ return d__
1252
+ d__.set_data(self._data)
1253
+ d__.pdf = pdf_dest
1254
+ d__._operations = list(self._operations)
1255
+ d__.forced_encoding = self.forced_encoding
1256
+ return d__
1257
+
1258
+ def clone(
1259
+ self,
1260
+ pdf_dest: Any,
1261
+ force_duplicate: bool = False,
1262
+ ignore_fields: Optional[Sequence[Union[str, int]]] = (),
1263
+ ) -> "ContentStream":
1264
+ """
1265
+ Clone object into pdf_dest.
1266
+
1267
+ Args:
1268
+ pdf_dest:
1269
+ force_duplicate:
1270
+ ignore_fields:
1271
+
1272
+ Returns:
1273
+ The cloned ContentStream
1274
+
1275
+ """
1276
+ try:
1277
+ if self.indirect_reference.pdf == pdf_dest and not force_duplicate: # type: ignore
1278
+ return self
1279
+ except Exception:
1280
+ pass
1281
+
1282
+ visited: set[tuple[int, int]] = set()
1283
+ d__ = cast(
1284
+ "ContentStream",
1285
+ self._reference_clone(
1286
+ self.__class__(None, None), pdf_dest, force_duplicate
1287
+ ),
1288
+ )
1289
+ if ignore_fields is None:
1290
+ ignore_fields = []
1291
+ d__._clone(self, pdf_dest, force_duplicate, ignore_fields, visited)
1292
+ return d__
1293
+
1294
+ def _clone(
1295
+ self,
1296
+ src: DictionaryObject,
1297
+ pdf_dest: PdfWriterProtocol,
1298
+ force_duplicate: bool,
1299
+ ignore_fields: Optional[Sequence[Union[str, int]]],
1300
+ visited: set[tuple[int, int]],
1301
+ ) -> None:
1302
+ """
1303
+ Update the object from src.
1304
+
1305
+ Args:
1306
+ src:
1307
+ pdf_dest:
1308
+ force_duplicate:
1309
+ ignore_fields:
1310
+
1311
+ """
1312
+ src_cs = cast("ContentStream", src)
1313
+ super().set_data(src_cs._data)
1314
+ self.pdf = pdf_dest
1315
+ self._operations = list(src_cs._operations)
1316
+ self.forced_encoding = src_cs.forced_encoding
1317
+ # no need to call DictionaryObjection or anything
1318
+ # like super(DictionaryObject,self)._clone(src, pdf_dest, force_duplicate, ignore_fields, visited)
1319
+
1320
+ def _parse_content_stream(self, stream: StreamType) -> None:
1321
+ # 7.8.2 Content Streams
1322
+ stream.seek(0, 0)
1323
+ operands: list[Union[int, str, PdfObject]] = []
1324
+ while True:
1325
+ peek = read_non_whitespace(stream)
1326
+ if peek in (b"", 0):
1327
+ break
1328
+ stream.seek(-1, 1)
1329
+ if peek.isalpha() or peek in (b"'", b'"'):
1330
+ operator = read_until_regex(stream, NameObject.delimiter_pattern)
1331
+ if operator == b"BI":
1332
+ # begin inline image - a completely different parsing
1333
+ # mechanism is required, of course... thanks buddy...
1334
+ assert operands == []
1335
+ ii = self._read_inline_image(stream)
1336
+ self._operations.append((ii, b"INLINE IMAGE"))
1337
+ else:
1338
+ self._operations.append((operands, operator))
1339
+ operands = []
1340
+ elif peek == b"%":
1341
+ # If we encounter a comment in the content stream, we have to
1342
+ # handle it here. Typically, read_object will handle
1343
+ # encountering a comment -- but read_object assumes that
1344
+ # following the comment must be the object we're trying to
1345
+ # read. In this case, it could be an operator instead.
1346
+ while peek not in (b"\r", b"\n", b""):
1347
+ peek = stream.read(1)
1348
+ else:
1349
+ operands.append(read_object(stream, None, self.forced_encoding))
1350
+
1351
+ def _read_inline_image(self, stream: StreamType) -> dict[str, Any]:
1352
+ # begin reading just after the "BI" - begin image
1353
+ # first read the dictionary of settings.
1354
+ settings = DictionaryObject()
1355
+ while True:
1356
+ tok = read_non_whitespace(stream)
1357
+ stream.seek(-1, 1)
1358
+ if tok == b"I":
1359
+ # "ID" - begin of image data
1360
+ break
1361
+ key = read_object(stream, self.pdf)
1362
+ tok = read_non_whitespace(stream)
1363
+ stream.seek(-1, 1)
1364
+ value = read_object(stream, self.pdf)
1365
+ settings[key] = value
1366
+ # left at beginning of ID
1367
+ tmp = stream.read(3)
1368
+ assert tmp[:2] == b"ID"
1369
+ filtr = settings.get("/F", settings.get("/Filter", "not set"))
1370
+ savpos = stream.tell()
1371
+ if isinstance(filtr, list):
1372
+ filtr = filtr[0] # used forencoding
1373
+ if "AHx" in filtr or "ASCIIHexDecode" in filtr:
1374
+ data = extract_inline__ascii_hex_decode(stream)
1375
+ elif "A85" in filtr or "ASCII85Decode" in filtr:
1376
+ data = extract_inline__ascii85_decode(stream)
1377
+ elif "RL" in filtr or "RunLengthDecode" in filtr:
1378
+ data = extract_inline__run_length_decode(stream)
1379
+ elif "DCT" in filtr or "DCTDecode" in filtr:
1380
+ data = extract_inline__dct_decode(stream)
1381
+ elif filtr == "not set":
1382
+ cs = settings.get("/CS", "")
1383
+ if isinstance(cs, list):
1384
+ cs = cs[0]
1385
+ if "RGB" in cs:
1386
+ lcs = 3
1387
+ elif "CMYK" in cs:
1388
+ lcs = 4
1389
+ else:
1390
+ bits = settings.get(
1391
+ "/BPC",
1392
+ 8 if cs in {"/I", "/G", "/Indexed", "/DeviceGray"} else -1,
1393
+ )
1394
+ if bits > 0:
1395
+ lcs = bits / 8.0
1396
+ else:
1397
+ data = extract_inline_default(stream)
1398
+ lcs = -1
1399
+ if lcs > 0:
1400
+ data = stream.read(
1401
+ ceil(cast(int, settings["/W"]) * lcs) * cast(int, settings["/H"])
1402
+ )
1403
+ # Move to the `EI` if possible.
1404
+ ei = read_non_whitespace(stream)
1405
+ stream.seek(-1, 1)
1406
+ else:
1407
+ data = extract_inline_default(stream)
1408
+
1409
+ ei = stream.read(3)
1410
+ stream.seek(-1, 1)
1411
+ if ei[:2] != b"EI" or ei[2:3] not in WHITESPACES:
1412
+ # Deal with wrong/missing `EI` tags. Example: Wrong dimensions specified above.
1413
+ stream.seek(savpos, 0)
1414
+ data = extract_inline_default(stream)
1415
+ ei = stream.read(3)
1416
+ stream.seek(-1, 1)
1417
+ if ei[:2] != b"EI" or ei[2:3] not in WHITESPACES: # pragma: no cover
1418
+ # Check the same condition again. This should never fail as
1419
+ # edge cases are covered by `extract_inline_default` above,
1420
+ # but check this ot make sure that we are behind the `EI` afterwards.
1421
+ raise PdfStreamError(
1422
+ f"Could not extract inline image, even using fallback. Expected 'EI', got {ei!r}"
1423
+ )
1424
+ return {"settings": settings, "data": data}
1425
+
1426
+ # This overrides the parent method
1427
+ def get_data(self) -> bytes:
1428
+ if not self._data:
1429
+ new_data = BytesIO()
1430
+ for operands, operator in self._operations:
1431
+ if operator == b"INLINE IMAGE":
1432
+ new_data.write(b"BI")
1433
+ dict_text = BytesIO()
1434
+ operands["settings"].write_to_stream(dict_text)
1435
+ new_data.write(dict_text.getvalue()[2:-2])
1436
+ new_data.write(b"ID ")
1437
+ new_data.write(operands["data"])
1438
+ new_data.write(b"EI")
1439
+ else:
1440
+ for op in operands:
1441
+ op.write_to_stream(new_data)
1442
+ new_data.write(b" ")
1443
+ new_data.write(operator)
1444
+ new_data.write(b"\n")
1445
+ self._data = new_data.getvalue()
1446
+ return self._data
1447
+
1448
+ # This overrides the parent method
1449
+ def set_data(self, data: bytes) -> None:
1450
+ super().set_data(data)
1451
+ self._operations = []
1452
+
1453
+ @property
1454
+ def operations(self) -> list[tuple[Any, bytes]]:
1455
+ if not self._operations and self._data:
1456
+ self._parse_content_stream(BytesIO(self._data))
1457
+ self._data = b""
1458
+ return self._operations
1459
+
1460
+ @operations.setter
1461
+ def operations(self, operations: list[tuple[Any, bytes]]) -> None:
1462
+ self._operations = operations
1463
+ self._data = b""
1464
+
1465
+ def isolate_graphics_state(self) -> None:
1466
+ if self._operations:
1467
+ self._operations.insert(0, ([], b"q"))
1468
+ self._operations.append(([], b"Q"))
1469
+ elif self._data:
1470
+ self._data = b"q\n" + self._data + b"\nQ\n"
1471
+
1472
+ # This overrides the parent method
1473
+ def write_to_stream(
1474
+ self, stream: StreamType, encryption_key: Union[None, str, bytes] = None
1475
+ ) -> None:
1476
+ if not self._data and self._operations:
1477
+ self.get_data() # this ensures ._data is rebuilt
1478
+ super().write_to_stream(stream, encryption_key)
1479
+
1480
+
1481
+ def read_object(
1482
+ stream: StreamType,
1483
+ pdf: Optional[PdfReaderProtocol],
1484
+ forced_encoding: Union[None, str, list[str], dict[int, str]] = None,
1485
+ ) -> Union[PdfObject, int, str, ContentStream]:
1486
+ tok = stream.read(1)
1487
+ stream.seek(-1, 1) # reset to start
1488
+ if tok == b"/":
1489
+ return NameObject.read_from_stream(stream, pdf)
1490
+ if tok == b"<":
1491
+ # hexadecimal string OR dictionary
1492
+ peek = stream.read(2)
1493
+ stream.seek(-2, 1) # reset to start
1494
+ if peek == b"<<":
1495
+ return DictionaryObject.read_from_stream(stream, pdf, forced_encoding)
1496
+ return read_hex_string_from_stream(stream, forced_encoding)
1497
+ if tok == b"[":
1498
+ return ArrayObject.read_from_stream(stream, pdf, forced_encoding)
1499
+ if tok in (b"t", b"f"):
1500
+ return BooleanObject.read_from_stream(stream)
1501
+ if tok == b"(":
1502
+ return read_string_from_stream(stream, forced_encoding)
1503
+ if tok == b"e" and stream.read(6) == b"endobj":
1504
+ return NullObject()
1505
+ if tok == b"n":
1506
+ return NullObject.read_from_stream(stream)
1507
+ if tok == b"%":
1508
+ # comment
1509
+ skip_over_comment(stream)
1510
+ tok = read_non_whitespace(stream)
1511
+ stream.seek(-1, 1)
1512
+ return read_object(stream, pdf, forced_encoding)
1513
+ if tok in b"0123456789+-.":
1514
+ # number object OR indirect reference
1515
+ peek = stream.read(20)
1516
+ stream.seek(-len(peek), 1) # reset to start
1517
+ if IndirectPattern.match(peek) is not None:
1518
+ assert pdf is not None, "mypy"
1519
+ return IndirectObject.read_from_stream(stream, pdf)
1520
+ return NumberObject.read_from_stream(stream)
1521
+ pos = stream.tell()
1522
+ stream.seek(-20, 1)
1523
+ stream_extract = stream.read(80)
1524
+ stream.seek(pos)
1525
+ read_until_whitespace(stream)
1526
+ raise PdfReadError(
1527
+ f"Invalid Elementary Object starting with {tok!r} @{pos}: {stream_extract!r}"
1528
+ )
1529
+
1530
+
1531
+ class Field(TreeObject):
1532
+ """
1533
+ A class representing a field dictionary.
1534
+
1535
+ This class is accessed through
1536
+ :meth:`get_fields()<pypdf.PdfReader.get_fields>`
1537
+ """
1538
+
1539
+ def __init__(self, data: DictionaryObject) -> None:
1540
+ DictionaryObject.__init__(self)
1541
+ field_attributes = (
1542
+ FieldDictionaryAttributes.attributes()
1543
+ + CheckboxRadioButtonAttributes.attributes()
1544
+ )
1545
+ self.indirect_reference = data.indirect_reference
1546
+ for attr in field_attributes:
1547
+ try:
1548
+ self[NameObject(attr)] = data[attr]
1549
+ except KeyError:
1550
+ pass
1551
+ if isinstance(self.get("/V"), EncodedStreamObject):
1552
+ d = cast(EncodedStreamObject, self[NameObject("/V")]).get_data()
1553
+ if isinstance(d, bytes):
1554
+ d_str = d.decode()
1555
+ elif d is None:
1556
+ d_str = ""
1557
+ else:
1558
+ raise Exception("Should never happen")
1559
+ self[NameObject("/V")] = TextStringObject(d_str)
1560
+
1561
+ # TABLE 8.69 Entries common to all field dictionaries
1562
+ @property
1563
+ def field_type(self) -> Optional[NameObject]:
1564
+ """Read-only property accessing the type of this field."""
1565
+ return self.get(FieldDictionaryAttributes.FT)
1566
+
1567
+ @property
1568
+ def parent(self) -> Optional[DictionaryObject]:
1569
+ """Read-only property accessing the parent of this field."""
1570
+ return self.get(FieldDictionaryAttributes.Parent)
1571
+
1572
+ @property
1573
+ def kids(self) -> Optional["ArrayObject"]:
1574
+ """Read-only property accessing the kids of this field."""
1575
+ return self.get(FieldDictionaryAttributes.Kids)
1576
+
1577
+ @property
1578
+ def name(self) -> Optional[str]:
1579
+ """Read-only property accessing the name of this field."""
1580
+ return self.get(FieldDictionaryAttributes.T)
1581
+
1582
+ @property
1583
+ def alternate_name(self) -> Optional[str]:
1584
+ """Read-only property accessing the alternate name of this field."""
1585
+ return self.get(FieldDictionaryAttributes.TU)
1586
+
1587
+ @property
1588
+ def mapping_name(self) -> Optional[str]:
1589
+ """
1590
+ Read-only property accessing the mapping name of this field.
1591
+
1592
+ This name is used by pypdf as a key in the dictionary returned by
1593
+ :meth:`get_fields()<pypdf.PdfReader.get_fields>`
1594
+ """
1595
+ return self.get(FieldDictionaryAttributes.TM)
1596
+
1597
+ @property
1598
+ def flags(self) -> Optional[int]:
1599
+ """
1600
+ Read-only property accessing the field flags, specifying various
1601
+ characteristics of the field (see Table 8.70 of the PDF 1.7 reference).
1602
+ """
1603
+ return self.get(FieldDictionaryAttributes.Ff)
1604
+
1605
+ @property
1606
+ def value(self) -> Optional[Any]:
1607
+ """
1608
+ Read-only property accessing the value of this field.
1609
+
1610
+ Format varies based on field type.
1611
+ """
1612
+ return self.get(FieldDictionaryAttributes.V)
1613
+
1614
+ @property
1615
+ def default_value(self) -> Optional[Any]:
1616
+ """Read-only property accessing the default value of this field."""
1617
+ return self.get(FieldDictionaryAttributes.DV)
1618
+
1619
+ @property
1620
+ def additional_actions(self) -> Optional[DictionaryObject]:
1621
+ """
1622
+ Read-only property accessing the additional actions dictionary.
1623
+
1624
+ This dictionary defines the field's behavior in response to trigger
1625
+ events. See Section 8.5.2 of the PDF 1.7 reference.
1626
+ """
1627
+ return self.get(FieldDictionaryAttributes.AA)
1628
+
1629
+
1630
+ class Destination(TreeObject):
1631
+ """
1632
+ A class representing a destination within a PDF file.
1633
+
1634
+ See section 12.3.2 of the PDF 2.0 reference.
1635
+
1636
+ Args:
1637
+ title: Title of this destination.
1638
+ page: Reference to the page of this destination. Should
1639
+ be an instance of :class:`IndirectObject<pypdf.generic.IndirectObject>`.
1640
+ fit: How the destination is displayed.
1641
+
1642
+ Raises:
1643
+ PdfReadError: If destination type is invalid.
1644
+
1645
+ """
1646
+
1647
+ node: Optional[
1648
+ DictionaryObject
1649
+ ] = None # node provide access to the original Object
1650
+
1651
+ def __init__(
1652
+ self,
1653
+ title: Union[str, bytes],
1654
+ page: Union[NumberObject, IndirectObject, NullObject, DictionaryObject],
1655
+ fit: Fit,
1656
+ ) -> None:
1657
+ self._filtered_children: list[Any] = [] # used in PdfWriter
1658
+
1659
+ typ = fit.fit_type
1660
+ args = fit.fit_args
1661
+
1662
+ DictionaryObject.__init__(self)
1663
+ self[NameObject("/Title")] = TextStringObject(title)
1664
+ self[NameObject("/Page")] = page
1665
+ self[NameObject("/Type")] = typ
1666
+
1667
+ # from table 8.2 of the PDF 1.7 reference.
1668
+ if typ == "/XYZ":
1669
+ if len(args) < 1: # left is missing : should never occur
1670
+ args.append(NumberObject(0.0))
1671
+ if len(args) < 2: # top is missing
1672
+ args.append(NumberObject(0.0))
1673
+ if len(args) < 3: # zoom is missing
1674
+ args.append(NumberObject(0.0))
1675
+ (
1676
+ self[NameObject(TA.LEFT)],
1677
+ self[NameObject(TA.TOP)],
1678
+ self[NameObject("/Zoom")],
1679
+ ) = args
1680
+ elif len(args) == 0:
1681
+ pass
1682
+ elif typ == TF.FIT_R:
1683
+ (
1684
+ self[NameObject(TA.LEFT)],
1685
+ self[NameObject(TA.BOTTOM)],
1686
+ self[NameObject(TA.RIGHT)],
1687
+ self[NameObject(TA.TOP)],
1688
+ ) = args
1689
+ elif typ in [TF.FIT_H, TF.FIT_BH]:
1690
+ try: # Prefer to be more robust not only to null parameters
1691
+ (self[NameObject(TA.TOP)],) = args
1692
+ except Exception:
1693
+ (self[NameObject(TA.TOP)],) = (NullObject(),)
1694
+ elif typ in [TF.FIT_V, TF.FIT_BV]:
1695
+ try: # Prefer to be more robust not only to null parameters
1696
+ (self[NameObject(TA.LEFT)],) = args
1697
+ except Exception:
1698
+ (self[NameObject(TA.LEFT)],) = (NullObject(),)
1699
+ elif typ in [TF.FIT, TF.FIT_B]:
1700
+ pass
1701
+ else:
1702
+ raise PdfReadError(f"Unknown Destination Type: {typ!r}")
1703
+
1704
+ @property
1705
+ def dest_array(self) -> "ArrayObject":
1706
+ return ArrayObject(
1707
+ [self.raw_get("/Page"), self["/Type"]]
1708
+ + [
1709
+ self[x]
1710
+ for x in ["/Left", "/Bottom", "/Right", "/Top", "/Zoom"]
1711
+ if x in self
1712
+ ]
1713
+ )
1714
+
1715
+ def write_to_stream(
1716
+ self, stream: StreamType, encryption_key: Union[None, str, bytes] = None
1717
+ ) -> None:
1718
+ if encryption_key is not None: # deprecated
1719
+ deprecation_no_replacement(
1720
+ "the encryption_key parameter of write_to_stream", "5.0.0"
1721
+ )
1722
+ stream.write(b"<<\n")
1723
+ key = NameObject("/D")
1724
+ key.write_to_stream(stream)
1725
+ stream.write(b" ")
1726
+ value = self.dest_array
1727
+ value.write_to_stream(stream)
1728
+
1729
+ key = NameObject("/S")
1730
+ key.write_to_stream(stream)
1731
+ stream.write(b" ")
1732
+ value_s = NameObject("/GoTo")
1733
+ value_s.write_to_stream(stream)
1734
+
1735
+ stream.write(b"\n")
1736
+ stream.write(b">>")
1737
+
1738
+ @property
1739
+ def title(self) -> Optional[str]:
1740
+ """Read-only property accessing the destination title."""
1741
+ return self.get("/Title")
1742
+
1743
+ @property
1744
+ def page(self) -> Optional[IndirectObject]:
1745
+ """Read-only property accessing the IndirectObject of the destination page."""
1746
+ return self.get("/Page")
1747
+
1748
+ @property
1749
+ def typ(self) -> Optional[str]:
1750
+ """Read-only property accessing the destination type."""
1751
+ return self.get("/Type")
1752
+
1753
+ @property
1754
+ def zoom(self) -> Optional[int]:
1755
+ """Read-only property accessing the zoom factor."""
1756
+ return self.get("/Zoom", None)
1757
+
1758
+ @property
1759
+ def left(self) -> Optional[FloatObject]:
1760
+ """Read-only property accessing the left horizontal coordinate."""
1761
+ return self.get("/Left", None)
1762
+
1763
+ @property
1764
+ def right(self) -> Optional[FloatObject]:
1765
+ """Read-only property accessing the right horizontal coordinate."""
1766
+ return self.get("/Right", None)
1767
+
1768
+ @property
1769
+ def top(self) -> Optional[FloatObject]:
1770
+ """Read-only property accessing the top vertical coordinate."""
1771
+ return self.get("/Top", None)
1772
+
1773
+ @property
1774
+ def bottom(self) -> Optional[FloatObject]:
1775
+ """Read-only property accessing the bottom vertical coordinate."""
1776
+ return self.get("/Bottom", None)
1777
+
1778
+ @property
1779
+ def color(self) -> Optional["ArrayObject"]:
1780
+ """Read-only property accessing the color in (R, G, B) with values 0.0-1.0."""
1781
+ return cast(
1782
+ "ArrayObject",
1783
+ self.get("/C", ArrayObject([FloatObject(0), FloatObject(0), FloatObject(0)])),
1784
+ )
1785
+
1786
+ @property
1787
+ def font_format(self) -> Optional[OutlineFontFlag]:
1788
+ """
1789
+ Read-only property accessing the font type.
1790
+
1791
+ 1=italic, 2=bold, 3=both
1792
+ """
1793
+ return OutlineFontFlag(self.get("/F", 0))
1794
+
1795
+ @property
1796
+ def outline_count(self) -> Optional[int]:
1797
+ """
1798
+ Read-only property accessing the outline count.
1799
+
1800
+ positive = expanded
1801
+ negative = collapsed
1802
+ absolute value = number of visible descendants at all levels
1803
+ """
1804
+ return self.get("/Count", None)
micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/generic/_files.py ADDED
@@ -0,0 +1,404 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import bisect
4
+ from functools import cached_property
5
+ from typing import TYPE_CHECKING, cast
6
+
7
+ from pypdf._utils import format_iso8824_date, parse_iso8824_date
8
+ from pypdf.constants import CatalogAttributes as CA
9
+ from pypdf.constants import FileSpecificationDictionaryEntries
10
+ from pypdf.constants import PageAttributes as PG
11
+ from pypdf.errors import PdfReadError, PyPdfError
12
+ from pypdf.generic import (
13
+ ArrayObject,
14
+ ByteStringObject,
15
+ DecodedStreamObject,
16
+ DictionaryObject,
17
+ NameObject,
18
+ NullObject,
19
+ NumberObject,
20
+ StreamObject,
21
+ TextStringObject,
22
+ is_null_or_none,
23
+ )
24
+
25
+ if TYPE_CHECKING:
26
+ import datetime
27
+ from collections.abc import Generator
28
+
29
+ from pypdf._writer import PdfWriter
30
+
31
+
32
+ class EmbeddedFile:
33
+ """
34
+ Container holding the information on an embedded file.
35
+
36
+ Attributes are evaluated lazily if possible.
37
+
38
+ Further information on embedded files can be found in section 7.11 of the PDF 2.0 specification.
39
+ """
40
+ def __init__(self, name: str, pdf_object: DictionaryObject, parent: ArrayObject | None = None) -> None:
41
+ """
42
+ Args:
43
+ name: The (primary) name as provided in the name tree.
44
+ pdf_object: The corresponding PDF object to allow retrieving further data.
45
+ parent: The parent list.
46
+ """
47
+ self._name = name
48
+ self.pdf_object = pdf_object
49
+ self._parent = parent
50
+
51
+ @property
52
+ def name(self) -> str:
53
+ """The (primary) name of the embedded file as provided in the name tree."""
54
+ return self._name
55
+
56
+ @classmethod
57
+ def _create_new(cls, writer: PdfWriter, name: str, content: str | bytes) -> EmbeddedFile:
58
+ """
59
+ Create a new embedded file and add it to the PdfWriter.
60
+
61
+ Args:
62
+ writer: The PdfWriter instance to add the embedded file to.
63
+ name: The filename to display.
64
+ content: The data in the file.
65
+
66
+ Returns:
67
+ EmbeddedFile instance for the newly created embedded file.
68
+ """
69
+ # Convert string content to bytes if needed
70
+ if isinstance(content, str):
71
+ content = content.encode("latin-1")
72
+
73
+ # Create the file entry (the actual embedded file stream)
74
+ file_entry = DecodedStreamObject()
75
+ file_entry.set_data(content)
76
+ file_entry.update({NameObject(PG.TYPE): NameObject("/EmbeddedFile")})
77
+
78
+ # Create the /EF entry
79
+ ef_entry = DictionaryObject()
80
+ ef_entry.update({NameObject("/F"): writer._add_object(file_entry)})
81
+
82
+ # Create the filespec dictionary
83
+ from pypdf.generic import create_string_object # noqa: PLC0415
84
+ filespec = DictionaryObject()
85
+ filespec_reference = writer._add_object(filespec)
86
+ name_object = cast(TextStringObject, create_string_object(name))
87
+ filespec.update(
88
+ {
89
+ NameObject(PG.TYPE): NameObject("/Filespec"),
90
+ NameObject(FileSpecificationDictionaryEntries.F): name_object,
91
+ NameObject(FileSpecificationDictionaryEntries.EF): ef_entry,
92
+ }
93
+ )
94
+
95
+ # Add the name and filespec to the names array.
96
+ # We use the inverse order for insertion, as this allows us to re-use the
97
+ # same index.
98
+ names_array = cls._get_names_array(writer)
99
+ insertion_index = cls._get_insertion_index(names_array, name_object)
100
+ names_array.insert(insertion_index, filespec_reference)
101
+ names_array.insert(insertion_index, name_object)
102
+
103
+ # Return an EmbeddedFile instance
104
+ return cls(name=name, pdf_object=filespec, parent=names_array)
105
+
106
+ @classmethod
107
+ def _get_names_array(cls, writer: PdfWriter) -> ArrayObject:
108
+ """Get the names array for embedded files, possibly creating and flattening it."""
109
+ if CA.NAMES not in writer.root_object:
110
+ # Add the /Names entry to the catalog.
111
+ writer.root_object[NameObject(CA.NAMES)] = writer._add_object(DictionaryObject())
112
+
113
+ names_dict = cast(DictionaryObject, writer.root_object[CA.NAMES])
114
+ if "/EmbeddedFiles" not in names_dict:
115
+ # We do not yet have an entry for embedded files. Create and return it.
116
+ names = ArrayObject()
117
+ embedded_files_names_dictionary = DictionaryObject(
118
+ {NameObject(CA.NAMES): names}
119
+ )
120
+ names_dict[NameObject("/EmbeddedFiles")] = writer._add_object(embedded_files_names_dictionary)
121
+ return names
122
+
123
+ # We have an existing embedded files entry.
124
+ embedded_files_names_tree = cast(DictionaryObject, names_dict["/EmbeddedFiles"])
125
+ if "/Names" in embedded_files_names_tree:
126
+ # Simple case: We already have a flat list.
127
+ return cast(ArrayObject, embedded_files_names_tree[NameObject(CA.NAMES)])
128
+ if "/Kids" not in embedded_files_names_tree:
129
+ # Invalid case: This is no name tree.
130
+ raise PdfReadError("Got neither Names nor Kids in embedded files tree.")
131
+
132
+ # Complex case: Convert a /Kids-based name tree to a /Names-based one.
133
+ # /Name-based ones are much easier to handle and allow us to simplify the
134
+ # actual insertion logic by only having to consider one case.
135
+ names = ArrayObject()
136
+ kids = cast(ArrayObject, embedded_files_names_tree["/Kids"].get_object())
137
+ embedded_files_names_dictionary = DictionaryObject(
138
+ {NameObject(CA.NAMES): names}
139
+ )
140
+ names_dict[NameObject("/EmbeddedFiles")] = writer._add_object(embedded_files_names_dictionary)
141
+ for kid in kids:
142
+ # Write the flattened file entries. As we do not change the actual files,
143
+ # this should not have any impact on references to them.
144
+ # There might be further (nested) kids here.
145
+ # Wait for an example before evaluating an implementation.
146
+ for name in kid.get_object().get("/Names", []):
147
+ names.append(name)
148
+ return names
149
+
150
+ @classmethod
151
+ def _get_insertion_index(cls, names_array: ArrayObject, name: str) -> int:
152
+ keys = [names_array[i].encode("utf-8") for i in range(0, len(names_array), 2)]
153
+ name_bytes = name.encode("utf-8")
154
+
155
+ start = bisect.bisect_left(keys, name_bytes)
156
+ end = bisect.bisect_right(keys, name_bytes)
157
+
158
+ if start != end:
159
+ return end * 2
160
+ if start == 0:
161
+ return 0
162
+ if start == (key_count := len(keys)):
163
+ return key_count * 2
164
+ return end * 2
165
+
166
+ @property
167
+ def alternative_name(self) -> str | None:
168
+ """Retrieve the alternative name (file specification)."""
169
+ for key in [FileSpecificationDictionaryEntries.UF, FileSpecificationDictionaryEntries.F]:
170
+ # PDF 2.0 reference, table 43:
171
+ # > A PDF reader shall use the value of the UF key, when present, instead of the F key.
172
+ if key in self.pdf_object:
173
+ value = self.pdf_object[key].get_object()
174
+ if not is_null_or_none(value):
175
+ return cast(str, value)
176
+ return None
177
+
178
+ @alternative_name.setter
179
+ def alternative_name(self, value: TextStringObject | None) -> None:
180
+ """Set the alternative name (file specification)."""
181
+ if value is None:
182
+ if FileSpecificationDictionaryEntries.UF in self.pdf_object:
183
+ self.pdf_object[NameObject(FileSpecificationDictionaryEntries.UF)] = NullObject()
184
+ if FileSpecificationDictionaryEntries.F in self.pdf_object:
185
+ self.pdf_object[NameObject(FileSpecificationDictionaryEntries.F)] = NullObject()
186
+ else:
187
+ self.pdf_object[NameObject(FileSpecificationDictionaryEntries.UF)] = value
188
+ self.pdf_object[NameObject(FileSpecificationDictionaryEntries.F)] = value
189
+
190
+ @property
191
+ def description(self) -> str | None:
192
+ """Retrieve the description."""
193
+ value = self.pdf_object.get(FileSpecificationDictionaryEntries.DESC)
194
+ if is_null_or_none(value):
195
+ return None
196
+ return value
197
+
198
+ @description.setter
199
+ def description(self, value: TextStringObject | None) -> None:
200
+ """Set the description."""
201
+ if value is None:
202
+ self.pdf_object[NameObject(FileSpecificationDictionaryEntries.DESC)] = NullObject()
203
+ else:
204
+ self.pdf_object[NameObject(FileSpecificationDictionaryEntries.DESC)] = value
205
+
206
+ @property
207
+ def associated_file_relationship(self) -> str:
208
+ """Retrieve the relationship of the referring document to this embedded file."""
209
+ return cast(
210
+ NameObject,
211
+ self.pdf_object.get("/AFRelationship", NameObject("/Unspecified")),
212
+ )
213
+
214
+ @associated_file_relationship.setter
215
+ def associated_file_relationship(self, value: NameObject) -> None:
216
+ """Set the relationship of the referring document to this embedded file."""
217
+ self.pdf_object[NameObject("/AFRelationship")] = value
218
+
219
+ @property
220
+ def _embedded_file(self) -> StreamObject:
221
+ """Retrieve the actual embedded file stream."""
222
+ if "/EF" not in self.pdf_object:
223
+ raise PdfReadError(f"/EF entry not found: {self.pdf_object}")
224
+ ef = cast(DictionaryObject, self.pdf_object["/EF"])
225
+ for key in [FileSpecificationDictionaryEntries.UF, FileSpecificationDictionaryEntries.F]:
226
+ if key in ef:
227
+ return cast(StreamObject, ef[key].get_object())
228
+ raise PdfReadError(f"No /(U)F key found in file dictionary: {ef}")
229
+
230
+ @property
231
+ def _params(self) -> DictionaryObject:
232
+ """Retrieve the file-specific parameters."""
233
+ return cast(DictionaryObject, self._embedded_file.get("/Params", DictionaryObject()).get_object())
234
+
235
+ @cached_property
236
+ def _ensure_params(self) -> DictionaryObject:
237
+ """Ensure the /Params dictionary exists and return it."""
238
+ embedded_file = self._embedded_file
239
+ if "/Params" not in embedded_file:
240
+ embedded_file[NameObject("/Params")] = DictionaryObject()
241
+ return cast(DictionaryObject, embedded_file["/Params"])
242
+
243
+ @property
244
+ def subtype(self) -> str | None:
245
+ """Retrieve the subtype. This is a MIME media type, prefixed by a slash."""
246
+ value = self._embedded_file.get("/Subtype")
247
+ if is_null_or_none(value):
248
+ return None
249
+ return value
250
+
251
+ @subtype.setter
252
+ def subtype(self, value: NameObject | None) -> None:
253
+ """Set the subtype. This should be a MIME media type, prefixed by a slash."""
254
+ embedded_file = self._embedded_file
255
+ if value is None:
256
+ embedded_file[NameObject("/Subtype")] = NullObject()
257
+ else:
258
+ embedded_file[NameObject("/Subtype")] = value
259
+
260
+ @property
261
+ def content(self) -> bytes:
262
+ """Retrieve the actual file content."""
263
+ return self._embedded_file.get_data()
264
+
265
+ @content.setter
266
+ def content(self, value: str | bytes) -> None:
267
+ """Set the file content."""
268
+ if isinstance(value, str):
269
+ value = value.encode("latin-1")
270
+ self._embedded_file.set_data(value)
271
+
272
+ @property
273
+ def size(self) -> int | None:
274
+ """Retrieve the size of the uncompressed file in bytes."""
275
+ value = self._params.get("/Size")
276
+ if is_null_or_none(value):
277
+ return None
278
+ return value
279
+
280
+ @size.setter
281
+ def size(self, value: NumberObject | None) -> None:
282
+ """Set the size of the uncompressed file in bytes."""
283
+ params = self._ensure_params
284
+ if value is None:
285
+ params[NameObject("/Size")] = NullObject()
286
+ else:
287
+ params[NameObject("/Size")] = value
288
+
289
+ @property
290
+ def creation_date(self) -> datetime.datetime | None:
291
+ """Retrieve the file creation datetime."""
292
+ return parse_iso8824_date(self._params.get("/CreationDate"))
293
+
294
+ @creation_date.setter
295
+ def creation_date(self, value: datetime.datetime | None) -> None:
296
+ """Set the file creation datetime."""
297
+ params = self._ensure_params
298
+ if value is None:
299
+ params[NameObject("/CreationDate")] = NullObject()
300
+ else:
301
+ date_str = format_iso8824_date(value)
302
+ params[NameObject("/CreationDate")] = TextStringObject(date_str)
303
+
304
+ @property
305
+ def modification_date(self) -> datetime.datetime | None:
306
+ """Retrieve the datetime of the last file modification."""
307
+ return parse_iso8824_date(self._params.get("/ModDate"))
308
+
309
+ @modification_date.setter
310
+ def modification_date(self, value: datetime.datetime | None) -> None:
311
+ """Set the datetime of the last file modification."""
312
+ params = self._ensure_params
313
+ if value is None:
314
+ params[NameObject("/ModDate")] = NullObject()
315
+ else:
316
+ date_str = format_iso8824_date(value)
317
+ params[NameObject("/ModDate")] = TextStringObject(date_str)
318
+
319
+ @property
320
+ def checksum(self) -> bytes | None:
321
+ """Retrieve the MD5 checksum of the (uncompressed) file."""
322
+ value = self._params.get("/CheckSum")
323
+ if is_null_or_none(value):
324
+ return None
325
+ return value
326
+
327
+ @checksum.setter
328
+ def checksum(self, value: ByteStringObject | None) -> None:
329
+ """Set the MD5 checksum of the (uncompressed) file."""
330
+ params = self._ensure_params
331
+ if value is None:
332
+ params[NameObject("/CheckSum")] = NullObject()
333
+ else:
334
+ params[NameObject("/CheckSum")] = value
335
+
336
+ def delete(self) -> None:
337
+ """Delete the file from the document."""
338
+ if not self._parent:
339
+ raise PyPdfError("Parent required to delete file from document.")
340
+ if self.pdf_object in self._parent:
341
+ index = self._parent.index(self.pdf_object)
342
+ elif (
343
+ (indirect_reference := getattr(self.pdf_object, "indirect_reference", None)) is not None
344
+ and indirect_reference in self._parent
345
+ ):
346
+ index = self._parent.index(indirect_reference)
347
+ else:
348
+ raise PyPdfError("File not found in parent object.")
349
+ self._parent.pop(index) # Reference.
350
+ self._parent.pop(index - 1) # Name.
351
+ self.pdf_object = DictionaryObject() # Invalidate.
352
+
353
+ def __repr__(self) -> str:
354
+ return f"<{self.__class__.__name__} name={self.name!r}>"
355
+
356
+ @classmethod
357
+ def _load_from_names(cls, names: ArrayObject) -> Generator[EmbeddedFile]:
358
+ """
359
+ Convert the given name tree into class instances.
360
+
361
+ Args:
362
+ names: The name tree to load the data from.
363
+
364
+ Returns:
365
+ Iterable of class instances for the files found.
366
+ """
367
+ # This is a name tree of the format [name_1, reference_1, name_2, reference_2, ...]
368
+ for i, name in enumerate(names):
369
+ if not isinstance(name, str):
370
+ # Skip plain strings and retrieve them as `direct_name` by index.
371
+ file_dictionary = name.get_object()
372
+ direct_name = names[i - 1].get_object()
373
+ yield EmbeddedFile(name=direct_name, pdf_object=file_dictionary, parent=names)
374
+
375
+ @classmethod
376
+ def _load(cls, catalog: DictionaryObject) -> Generator[EmbeddedFile]:
377
+ """
378
+ Load the embedded files for the given document catalog.
379
+
380
+ This method and its signature are considered internal API and thus not exposed publicly for now.
381
+
382
+ Args:
383
+ catalog: The document catalog to load from.
384
+
385
+ Returns:
386
+ Iterable of class instances for the files found.
387
+ """
388
+ try:
389
+ container = cast(
390
+ DictionaryObject,
391
+ cast(DictionaryObject, catalog["/Names"])["/EmbeddedFiles"],
392
+ )
393
+ except KeyError:
394
+ return
395
+
396
+ if "/Kids" in container:
397
+ for kid in cast(ArrayObject, container["/Kids"].get_object()):
398
+ # There might be further (nested) kids here.
399
+ # Wait for an example before evaluating an implementation.
400
+ kid = kid.get_object()
401
+ if "/Names" in kid:
402
+ yield from cls._load_from_names(cast(ArrayObject, kid["/Names"]))
403
+ if "/Names" in container:
404
+ yield from cls._load_from_names(cast(ArrayObject, container["/Names"]))
micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/generic/_fit.py ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Optional, Union
2
+
3
+ from ._base import is_null_or_none
4
+
5
+
6
+ class Fit:
7
+ def __init__(
8
+ self, fit_type: str, fit_args: tuple[Union[None, float, Any], ...] = ()
9
+ ) -> None:
10
+ from ._base import FloatObject, NameObject, NullObject, NumberObject # noqa: PLC0415
11
+
12
+ self.fit_type = NameObject(fit_type)
13
+ self.fit_args: list[Union[NullObject, FloatObject, NumberObject]] = [
14
+ NullObject() if is_null_or_none(a) else FloatObject(a) for a in fit_args
15
+ ]
16
+
17
+ @classmethod
18
+ def xyz(
19
+ cls,
20
+ left: Optional[float] = None,
21
+ top: Optional[float] = None,
22
+ zoom: Optional[float] = None,
23
+ ) -> "Fit":
24
+ """
25
+ Display the page designated by page, with the coordinates (left, top)
26
+ positioned at the upper-left corner of the window and the contents
27
+ of the page magnified by the factor zoom.
28
+
29
+ A null value for any of the parameters left, top, or zoom specifies
30
+ that the current value of that parameter is to be retained unchanged.
31
+
32
+ A zoom value of 0 has the same meaning as a null value.
33
+
34
+ Args:
35
+ left:
36
+ top:
37
+ zoom:
38
+
39
+ Returns:
40
+ The created fit object.
41
+
42
+ """
43
+ return Fit(fit_type="/XYZ", fit_args=(left, top, zoom))
44
+
45
+ @classmethod
46
+ def fit(cls) -> "Fit":
47
+ """
48
+ Display the page designated by page, with its contents magnified just
49
+ enough to fit the entire page within the window both horizontally and
50
+ vertically.
51
+
52
+ If the required horizontal and vertical magnification factors are
53
+ different, use the smaller of the two, centering the page within the
54
+ window in the other dimension.
55
+ """
56
+ return Fit(fit_type="/Fit")
57
+
58
+ @classmethod
59
+ def fit_horizontally(cls, top: Optional[float] = None) -> "Fit":
60
+ """
61
+ Display the page designated by page, with the vertical coordinate top
62
+ positioned at the top edge of the window and the contents of the page
63
+ magnified just enough to fit the entire width of the page within the
64
+ window.
65
+
66
+ A null value for ``top`` specifies that the current value of that
67
+ parameter is to be retained unchanged.
68
+
69
+ Args:
70
+ top:
71
+
72
+ Returns:
73
+ The created fit object.
74
+
75
+ """
76
+ return Fit(fit_type="/FitH", fit_args=(top,))
77
+
78
+ @classmethod
79
+ def fit_vertically(cls, left: Optional[float] = None) -> "Fit":
80
+ return Fit(fit_type="/FitV", fit_args=(left,))
81
+
82
+ @classmethod
83
+ def fit_rectangle(
84
+ cls,
85
+ left: Optional[float] = None,
86
+ bottom: Optional[float] = None,
87
+ right: Optional[float] = None,
88
+ top: Optional[float] = None,
89
+ ) -> "Fit":
90
+ """
91
+ Display the page designated by page, with its contents magnified
92
+ just enough to fit the rectangle specified by the coordinates
93
+ left, bottom, right, and top entirely within the window
94
+ both horizontally and vertically.
95
+
96
+ If the required horizontal and vertical magnification factors are
97
+ different, use the smaller of the two, centering the rectangle within
98
+ the window in the other dimension.
99
+
100
+ A null value for any of the parameters may result in unpredictable
101
+ behavior.
102
+
103
+ Args:
104
+ left:
105
+ bottom:
106
+ right:
107
+ top:
108
+
109
+ Returns:
110
+ The created fit object.
111
+
112
+ """
113
+ return Fit(fit_type="/FitR", fit_args=(left, bottom, right, top))
114
+
115
+ @classmethod
116
+ def fit_box(cls) -> "Fit":
117
+ """
118
+ Display the page designated by page, with its contents magnified just
119
+ enough to fit its bounding box entirely within the window both
120
+ horizontally and vertically.
121
+
122
+ If the required horizontal and vertical magnification factors are
123
+ different, use the smaller of the two, centering the bounding box
124
+ within the window in the other dimension.
125
+ """
126
+ return Fit(fit_type="/FitB")
127
+
128
+ @classmethod
129
+ def fit_box_horizontally(cls, top: Optional[float] = None) -> "Fit":
130
+ """
131
+ Display the page designated by page, with the vertical coordinate top
132
+ positioned at the top edge of the window and the contents of the page
133
+ magnified just enough to fit the entire width of its bounding box
134
+ within the window.
135
+
136
+ A null value for top specifies that the current value of that parameter
137
+ is to be retained unchanged.
138
+
139
+ Args:
140
+ top:
141
+
142
+ Returns:
143
+ The created fit object.
144
+
145
+ """
146
+ return Fit(fit_type="/FitBH", fit_args=(top,))
147
+
148
+ @classmethod
149
+ def fit_box_vertically(cls, left: Optional[float] = None) -> "Fit":
150
+ """
151
+ Display the page designated by page, with the horizontal coordinate
152
+ left positioned at the left edge of the window and the contents of the
153
+ page magnified just enough to fit the entire height of its bounding box
154
+ within the window.
155
+
156
+ A null value for left specifies that the current value of that
157
+ parameter is to be retained unchanged.
158
+
159
+ Args:
160
+ left:
161
+
162
+ Returns:
163
+ The created fit object.
164
+
165
+ """
166
+ return Fit(fit_type="/FitBV", fit_args=(left,))
167
+
168
+ def __str__(self) -> str:
169
+ if not self.fit_args:
170
+ return f"Fit({self.fit_type})"
171
+ return f"Fit({self.fit_type}, {self.fit_args})"
172
+
173
+
174
+ DEFAULT_FIT = Fit.fit()
micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/generic/_image_inline.py ADDED
@@ -0,0 +1,315 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2024, pypdf contributors
2
+ # All rights reserved.
3
+ #
4
+ # Redistribution and use in source and binary forms, with or without
5
+ # modification, are permitted provided that the following conditions are
6
+ # met:
7
+ #
8
+ # * Redistributions of source code must retain the above copyright notice,
9
+ # this list of conditions and the following disclaimer.
10
+ # * Redistributions in binary form must reproduce the above copyright notice,
11
+ # this list of conditions and the following disclaimer in the documentation
12
+ # and/or other materials provided with the distribution.
13
+ # * The name of the author may not be used to endorse or promote products
14
+ # derived from this software without specific prior written permission.
15
+ #
16
+ # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17
+ # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18
+ # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19
+ # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
20
+ # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21
+ # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22
+ # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23
+ # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24
+ # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25
+ # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26
+ # POSSIBILITY OF SUCH DAMAGE.
27
+
28
+ import logging
29
+ from io import BytesIO
30
+ from typing import IO
31
+
32
+ from .._utils import (
33
+ WHITESPACES,
34
+ WHITESPACES_AS_BYTES,
35
+ BinaryStreamType,
36
+ StreamType,
37
+ logger_warning,
38
+ read_non_whitespace,
39
+ )
40
+ from ..errors import PdfReadError
41
+
42
+ logger = logging.getLogger(__name__)
43
+
44
+ # An inline image should be used only for small images (4096 bytes or less),
45
+ # but allow twice this for cases where this has been exceeded.
46
+ BUFFER_SIZE = 8192
47
+
48
+
49
+ def _check_end_image_marker(stream: StreamType) -> bool:
50
+ ei_tok = read_non_whitespace(stream)
51
+ ei_tok += stream.read(2)
52
+ stream.seek(-3, 1)
53
+ return ei_tok[:2] == b"EI" and (ei_tok[2:3] == b"" or ei_tok[2:3] in WHITESPACES)
54
+
55
+
56
+ def extract_inline__ascii_hex_decode(stream: StreamType) -> bytes:
57
+ """
58
+ Extract HexEncoded stream from inline image.
59
+ The stream will be moved onto the EI.
60
+ """
61
+ data_out = bytearray()
62
+ # Read data until delimiter > and EI as backup.
63
+ while True:
64
+ data_buffered = read_non_whitespace(stream) + stream.read(BUFFER_SIZE)
65
+ if not data_buffered:
66
+ raise PdfReadError("Unexpected end of stream")
67
+ pos_tok = data_buffered.find(b">")
68
+ if pos_tok >= 0: # found >
69
+ data_out += data_buffered[: pos_tok + 1]
70
+ stream.seek(-len(data_buffered) + pos_tok + 1, 1)
71
+ break
72
+ pos_ei = data_buffered.find(b"EI")
73
+ if pos_ei >= 0: # found EI
74
+ stream.seek(-len(data_buffered) + pos_ei - 1, 1)
75
+ c = stream.read(1)
76
+ while c in WHITESPACES:
77
+ stream.seek(-2, 1)
78
+ c = stream.read(1)
79
+ pos_ei -= 1
80
+ data_out += data_buffered[:pos_ei]
81
+ break
82
+ if len(data_buffered) == 2:
83
+ data_out += data_buffered
84
+ raise PdfReadError("Unexpected end of stream")
85
+ # Neither > nor EI found
86
+ data_out += data_buffered[:-2]
87
+ stream.seek(-2, 1)
88
+
89
+ if not _check_end_image_marker(stream):
90
+ raise PdfReadError("EI stream not found")
91
+ return bytes(data_out)
92
+
93
+
94
+ def extract_inline__ascii85_decode(stream: StreamType) -> bytes:
95
+ """
96
+ Extract A85 stream from inline image.
97
+ The stream will be moved onto the EI.
98
+ """
99
+ data_out = bytearray()
100
+ # Read data until delimiter ~>
101
+ while True:
102
+ data_buffered = read_non_whitespace(stream) + stream.read(BUFFER_SIZE)
103
+ if not data_buffered:
104
+ raise PdfReadError("Unexpected end of stream")
105
+ pos_tok = data_buffered.find(b"~>")
106
+ if pos_tok >= 0: # found!
107
+ data_out += data_buffered[: pos_tok + 2]
108
+ stream.seek(-len(data_buffered) + pos_tok + 2, 1)
109
+ break
110
+ if len(data_buffered) == 2: # end of buffer
111
+ data_out += data_buffered
112
+ raise PdfReadError("Unexpected end of stream")
113
+ data_out += data_buffered[
114
+ :-2
115
+ ] # back by one char in case of in the middle of ~>
116
+ stream.seek(-2, 1)
117
+
118
+ if not _check_end_image_marker(stream):
119
+ raise PdfReadError("EI stream not found")
120
+ return bytes(data_out)
121
+
122
+
123
+ def extract_inline__run_length_decode(stream: StreamType) -> bytes:
124
+ """
125
+ Extract RL (RunLengthDecode) stream from inline image.
126
+ The stream will be moved onto the EI.
127
+ """
128
+ data_out = bytearray()
129
+ # Read data until delimiter 128
130
+ while True:
131
+ data_buffered = stream.read(BUFFER_SIZE)
132
+ if not data_buffered:
133
+ raise PdfReadError("Unexpected end of stream")
134
+ pos_tok = data_buffered.find(b"\x80")
135
+ if pos_tok >= 0: # found
136
+ # Ideally, we could just use plain run-length decoding here, where 80_16 = 128_10
137
+ # marks the EOD. But there apparently are cases like in issue #3517, where we have
138
+ # an inline image with up to 51 EOD markers. In these cases, be resilient here and
139
+ # use the default `EI` marker detection instead. Please note that this fallback
140
+ # still omits special `EI` handling within the stream, but for now assume that having
141
+ # both of these cases occur at the same time is very unlikely (and the image stream
142
+ # is broken anyway).
143
+ # For now, do not skip over more than one whitespace character.
144
+ after_token = data_buffered[pos_tok + 1 : pos_tok + 4]
145
+ if after_token.startswith(b"EI") or after_token.endswith(b"EI"):
146
+ data_out += data_buffered[: pos_tok + 1]
147
+ stream.seek(-len(data_buffered) + pos_tok + 1, 1)
148
+ else:
149
+ logger_warning("Early EOD in RunLengthDecode of inline image, using fallback.", __name__)
150
+ ei_marker = data_buffered.find(b"EI")
151
+ if ei_marker > 0:
152
+ data_out += data_buffered[: ei_marker]
153
+ stream.seek(-len(data_buffered) + ei_marker - 1, 1)
154
+ break
155
+ data_out += data_buffered
156
+
157
+ if not _check_end_image_marker(stream):
158
+ raise PdfReadError("EI stream not found")
159
+ return bytes(data_out)
160
+
161
+
162
+ def extract_inline__dct_decode(stream: BinaryStreamType) -> bytes:
163
+ """
164
+ Extract DCT (JPEG) stream from inline image.
165
+ The stream will be moved onto the EI.
166
+ """
167
+ def read(length: int) -> bytes:
168
+ # If 0 bytes are returned, and *size* was not 0, this indicates end of file.
169
+ # If the object is in non-blocking mode and no bytes are available, `None` is returned.
170
+ _result = stream.read(length)
171
+ if _result is None or len(_result) != length:
172
+ raise PdfReadError("Unexpected end of stream")
173
+ return _result
174
+
175
+ data_out = bytearray()
176
+ # Read Blocks of data (ID/Size/data) up to ID=FF/D9
177
+ # https://www.digicamsoft.com/itu/itu-t81-36.html
178
+ not_first = False
179
+ while True:
180
+ c = read(1)
181
+ if not_first or (c == b"\xff"):
182
+ data_out += c
183
+ if c != b"\xff":
184
+ continue
185
+ not_first = True
186
+ c = read(1)
187
+ data_out += c
188
+ if c == b"\xff":
189
+ stream.seek(-1, 1) # pragma: no cover
190
+ elif c == b"\x00": # stuffing
191
+ pass
192
+ elif c == b"\xd9": # end
193
+ break
194
+ elif c in (
195
+ b"\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc9\xca\xcb\xcc\xcd\xce\xcf"
196
+ b"\xda\xdb\xdc\xdd\xde\xdf"
197
+ b"\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xfe"
198
+ ):
199
+ c = read(2)
200
+ data_out += c
201
+ sz = c[0] * 256 + c[1]
202
+ data_out += read(sz - 2)
203
+
204
+ if not _check_end_image_marker(stream):
205
+ raise PdfReadError("EI stream not found")
206
+ return bytes(data_out)
207
+
208
+
209
+ def extract_inline_default(stream: StreamType) -> bytes:
210
+ """Legacy method, used by default"""
211
+ stream_out = BytesIO()
212
+ # Read the inline image, while checking for EI (End Image) operator.
213
+ while True:
214
+ data_buffered = stream.read(BUFFER_SIZE)
215
+ if not data_buffered:
216
+ raise PdfReadError("Unexpected end of stream")
217
+ pos_ei = data_buffered.find(
218
+ b"E"
219
+ ) # We can not look straight for "EI" because it may not have been loaded in the buffer
220
+
221
+ if pos_ei == -1:
222
+ stream_out.write(data_buffered)
223
+ else:
224
+ # Write out everything including E (the one from EI to be removed)
225
+ stream_out.write(data_buffered[0 : pos_ei + 1])
226
+ sav_pos_ei = stream_out.tell() - 1
227
+ # Seek back in the stream to read the E next
228
+ stream.seek(pos_ei + 1 - len(data_buffered), 1)
229
+ saved_pos = stream.tell()
230
+ # Check for End Image
231
+ tok2 = stream.read(1) # I of "EI"
232
+ if tok2 != b"I":
233
+ stream.seek(saved_pos, 0)
234
+ continue
235
+ tok3 = stream.read(1) # possible space after "EI"
236
+ if tok3 not in WHITESPACES:
237
+ stream.seek(saved_pos, 0)
238
+ continue
239
+ while tok3 in WHITESPACES:
240
+ tok3 = stream.read(1)
241
+ if data_buffered[pos_ei - 1 : pos_ei] not in WHITESPACES and tok3 not in {
242
+ b"Q",
243
+ b"E",
244
+ }: # for Q or EMC
245
+ stream.seek(saved_pos, 0)
246
+ continue
247
+ if is_followed_by_binary_data(stream):
248
+ # Inline image contains `EI ` sequence usually marking the end of it, but
249
+ # is followed by binary data which does not make sense for the actual end.
250
+ stream.seek(saved_pos, 0)
251
+ continue
252
+ # Data contains [\s]EI[\s](Q|EMC): 4 chars are sufficient
253
+ # remove E(I) wrongly inserted earlier
254
+ stream.seek(saved_pos - 1, 0)
255
+ stream_out.truncate(sav_pos_ei)
256
+ break
257
+
258
+ return stream_out.getvalue()
259
+
260
+
261
+ def is_followed_by_binary_data(stream: IO[bytes], length: int = 10) -> bool:
262
+ """
263
+ Check if the next bytes of the stream look like binary image data or regular page content.
264
+
265
+ This is just some heuristics due to the PDF specification being too imprecise about
266
+ inline images containing the `EI` marker which would end an image. Starting with PDF 2.0,
267
+ we finally get a mandatory length field, but with (proper) PDF 2.0 support being very limited
268
+ everywhere, we should not expect to be able to remove such hacks in the near future - especially
269
+ considering legacy documents as well.
270
+
271
+ The actual implementation draws some inspiration from
272
+ https://github.com/itext/itext-java/blob/9.1.0/kernel/src/main/java/com/itextpdf/kernel/pdf/canvas/parser/util/InlineImageParsingUtils.java
273
+ """
274
+ position = stream.tell()
275
+ data = stream.read(length)
276
+ stream.seek(position)
277
+ if not data:
278
+ return False
279
+ operator_start = None
280
+ operator_end = None
281
+
282
+ for index, byte in enumerate(data):
283
+ if byte < 32 and byte not in WHITESPACES_AS_BYTES:
284
+ # This covers all characters not being displayable directly, although omitting whitespace
285
+ # to allow for operator detection.
286
+ return True
287
+ is_whitespace = byte in WHITESPACES_AS_BYTES
288
+ if operator_start is None and not is_whitespace:
289
+ # Interpret all other non-whitespace characters as the start of an operation.
290
+ operator_start = index
291
+ if operator_start is not None and is_whitespace:
292
+ # A whitespace stops an operation.
293
+ # Assume that having an inline image with tons of whitespace is rather unlikely.
294
+ operator_end = index
295
+ break
296
+
297
+ if operator_start is None:
298
+ # Inline images should not have tons of whitespaces, which would lead to no operator start.
299
+ return False
300
+ if operator_end is None:
301
+ # We probably are inside an operation.
302
+ operator_end = length
303
+ operator_length = operator_end - operator_start
304
+ operator = data[operator_start:operator_end]
305
+ if operator.startswith(b"/") and operator_length > 1:
306
+ # Name object.
307
+ return False
308
+ if operator.replace(b".", b"").isdigit():
309
+ # Graphics operator, for example a move. A number (integer or float).
310
+ return False
311
+ if operator_length > 3: # noqa: SIM103
312
+ # Usually, the operators inside a content stream should not have more than three characters,
313
+ # especially after an inline image.
314
+ return True
315
+ return False
micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/generic/_image_xobject.py ADDED
@@ -0,0 +1,590 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Functions to convert an image XObject to an image"""
2
+
3
+ import sys
4
+ from io import BytesIO
5
+ from typing import Any, Literal, Optional, Union, cast
6
+
7
+ from .._utils import check_if_whitespace_only, logger_warning
8
+ from ..constants import ColorSpaces, StreamAttributes
9
+ from ..constants import FilterTypes as FT
10
+ from ..constants import ImageAttributes as IA
11
+ from ..errors import EmptyImageDataError, LimitReachedError, PdfReadError
12
+ from ..generic import (
13
+ ArrayObject,
14
+ DecodedStreamObject,
15
+ EncodedStreamObject,
16
+ NullObject,
17
+ TextStringObject,
18
+ is_null_or_none,
19
+ )
20
+
21
+ if sys.version_info[:2] >= (3, 10):
22
+ from typing import TypeAlias
23
+ else:
24
+ from typing_extensions import TypeAlias
25
+
26
+
27
+ try:
28
+ from PIL import Image, UnidentifiedImageError
29
+ except ImportError:
30
+ raise ImportError(
31
+ "pillow is required to do image extraction. "
32
+ "It can be installed via 'pip install pypdf[image]'"
33
+ )
34
+
35
+ mode_str_type: TypeAlias = Literal[
36
+ "", "1", "RGB", "2bits", "4bits", "P", "L", "RGBA", "CMYK"
37
+ ]
38
+
39
+ MAX_IMAGE_MODE_NESTING_DEPTH: int = 10
40
+
41
+
42
+ def _get_image_mode(
43
+ color_space: Union[str, list[Any], Any],
44
+ color_components: int,
45
+ prev_mode: mode_str_type,
46
+ depth: int = 0,
47
+ ) -> tuple[mode_str_type, bool]:
48
+ """
49
+ Returns:
50
+ Image mode, not taking into account mask (transparency).
51
+ ColorInversion is required (like for some DeviceCMYK).
52
+
53
+ """
54
+ if depth > MAX_IMAGE_MODE_NESTING_DEPTH:
55
+ raise PdfReadError(
56
+ "Color spaces nested too deeply. If required, consider increasing MAX_IMAGE_MODE_NESTING_DEPTH."
57
+ )
58
+ if is_null_or_none(color_space):
59
+ return "", False
60
+ color_space_str: str = ""
61
+ if isinstance(color_space, str):
62
+ color_space_str = color_space
63
+ elif not isinstance(color_space, list):
64
+ raise PdfReadError(
65
+ "Cannot interpret color space", color_space
66
+ ) # pragma: no cover
67
+ elif not color_space:
68
+ return "", False
69
+ elif color_space[0].startswith("/Cal"): # /CalRGB or /CalGray
70
+ color_space_str = "/Device" + color_space[0][4:]
71
+ elif color_space[0] == "/ICCBased":
72
+ icc_profile = color_space[1].get_object()
73
+ color_components = cast(int, icc_profile["/N"])
74
+ color_space_str = icc_profile.get("/Alternate", "")
75
+ elif color_space[0] == "/Indexed":
76
+ color_space_str = color_space[1].get_object()
77
+ mode, invert_color = _get_image_mode(
78
+ color_space_str, color_components, prev_mode, depth + 1
79
+ )
80
+ if mode in ("RGB", "CMYK"):
81
+ mode = "P"
82
+ return mode, invert_color
83
+ elif color_space[0] == "/Separation":
84
+ color_space_str = color_space[2].get_object()
85
+ mode, invert_color = _get_image_mode(
86
+ color_space_str, color_components, prev_mode, depth + 1
87
+ )
88
+ return mode, True
89
+ elif color_space[0] == "/DeviceN":
90
+ original_color_space = color_space
91
+ color_components = len(color_space[1])
92
+ color_space_str = color_space[2].get_object()
93
+ if color_space_str == "/DeviceCMYK" and color_components == 1:
94
+ if original_color_space[1][0] != "/Black":
95
+ logger_warning(
96
+ f"Color {original_color_space[1][0]} converted to Gray. Please share PDF with pypdf dev team",
97
+ __name__,
98
+ )
99
+ return "L", True
100
+ mode, invert_color = _get_image_mode(
101
+ color_space_str, color_components, prev_mode, depth + 1
102
+ )
103
+ return mode, invert_color
104
+
105
+ mode_map: dict[str, mode_str_type] = {
106
+ "1bit": "1", # must be zeroth position: color_components may index the values
107
+ "/DeviceGray": "L", # must be first position: color_components may index the values
108
+ "palette": "P", # must be second position: color_components may index the values
109
+ "/DeviceRGB": "RGB", # must be third position: color_components may index the values
110
+ "/DeviceCMYK": "CMYK", # must be fourth position: color_components may index the values
111
+ "2bit": "2bits",
112
+ "4bit": "4bits",
113
+ }
114
+
115
+ mode = (
116
+ mode_map.get(color_space_str)
117
+ or list(mode_map.values())[color_components]
118
+ or prev_mode
119
+ )
120
+
121
+ return mode, mode == "CMYK"
122
+
123
+
124
+ def bits2byte(data: bytes, size: tuple[int, int], bits: int) -> bytes:
125
+ from pypdf.filters import FLATE_MAX_BUFFER_SIZE # noqa: PLC0415
126
+
127
+ buffer_size = size[0] * size[1]
128
+ if buffer_size > FLATE_MAX_BUFFER_SIZE:
129
+ raise LimitReachedError(f"Requested buffer size {buffer_size} exceeds limit of {FLATE_MAX_BUFFER_SIZE}.")
130
+
131
+ byte_buffer = bytearray(buffer_size)
132
+ mask = (1 << bits) - 1
133
+ data_index = 0
134
+ bit = 8 - bits
135
+ for y in range(size[1]):
136
+ if bit != 8 - bits:
137
+ data_index += 1
138
+ bit = 8 - bits
139
+ for x in range(size[0]):
140
+ byte_buffer[x + y * size[0]] = (data[data_index] >> bit) & mask
141
+ bit -= bits
142
+ if bit < 0:
143
+ data_index += 1
144
+ bit = 8 - bits
145
+ return bytes(byte_buffer)
146
+
147
+
148
+ def _extended_image_from_bytes(
149
+ mode: str, size: tuple[int, int], data: bytes
150
+ ) -> Image.Image:
151
+ try:
152
+ img = Image.frombytes(mode, size, data)
153
+ except ValueError as exc:
154
+ nb_pix = size[0] * size[1]
155
+ data_length = len(data)
156
+ if data_length == 0:
157
+ raise EmptyImageDataError(
158
+ "Data is 0 bytes, cannot process an image from empty data."
159
+ ) from exc
160
+ if data_length % nb_pix != 0:
161
+ raise exc
162
+ k = nb_pix * len(mode) / data_length
163
+ data = b"".join(bytes((x,) * int(k)) for x in data)
164
+ img = Image.frombytes(mode, size, data)
165
+ return img
166
+
167
+
168
+ def __handle_flate__indexed(color_space: ArrayObject) -> tuple[Any, Any, Any, Any]:
169
+ count = len(color_space)
170
+ if count == 4:
171
+ color_space, base, hival, lookup = (value.get_object() for value in color_space)
172
+ return color_space, base, hival, lookup
173
+
174
+ # Deal with strange AutoDesk files where `base` and `hival` look like this:
175
+ # /DeviceRGB\x00255
176
+ element1 = color_space[1]
177
+ element1 = element1 if isinstance(element1, str) else element1.get_object()
178
+ if count == 3 and "\x00" in element1:
179
+ color_space, lookup = color_space[0].get_object(), color_space[2].get_object()
180
+ base, hival = element1.split("\x00")
181
+ hival = int(hival)
182
+ return color_space, base, hival, lookup
183
+ raise PdfReadError(f"Expected color space with 4 values, got {count}: {color_space}")
184
+
185
+
186
+ def _handle_flate(
187
+ size: tuple[int, int],
188
+ data: bytes,
189
+ mode: mode_str_type,
190
+ color_space: Union[str, ArrayObject],
191
+ colors: int,
192
+ obj_as_text: str,
193
+ ) -> tuple[Image.Image, str, str, bool]:
194
+ """
195
+ Process image encoded in flateEncode
196
+ Returns img, image_format, extension, color inversion
197
+ """
198
+ extension = ".png" # mime_type: "image/png"
199
+ image_format = "PNG"
200
+ lookup: Any
201
+ base: Any
202
+ hival: Any
203
+ if isinstance(color_space, ArrayObject) and color_space[0] == "/Indexed":
204
+ color_space, base, hival, lookup = __handle_flate__indexed(color_space)
205
+ if mode == "2bits":
206
+ mode = "P"
207
+ data = bits2byte(data, size, 2)
208
+ elif mode == "4bits":
209
+ mode = "P"
210
+ data = bits2byte(data, size, 4)
211
+ img = _extended_image_from_bytes(mode, size, data)
212
+ if color_space == "/Indexed":
213
+ if isinstance(lookup, (EncodedStreamObject, DecodedStreamObject)):
214
+ lookup = lookup.get_data()
215
+ if isinstance(lookup, TextStringObject):
216
+ lookup = lookup.original_bytes
217
+ if isinstance(lookup, str):
218
+ lookup = lookup.encode()
219
+ try:
220
+ nb, conv, mode = { # type: ignore
221
+ "1": (0, "", ""),
222
+ "L": (1, "P", "L"),
223
+ "P": (0, "", ""),
224
+ "RGB": (3, "P", "RGB"),
225
+ "CMYK": (4, "P", "CMYK"),
226
+ }[_get_image_mode(base, 0, "")[0]]
227
+ except KeyError: # pragma: no cover
228
+ logger_warning(
229
+ f"Base {base} not coded please share the pdf file with pypdf dev team",
230
+ __name__,
231
+ )
232
+ lookup = None
233
+ else:
234
+ if img.mode == "1":
235
+ # Two values ("high" and "low").
236
+ expected_count = 2 * nb
237
+ actual_count = len(lookup)
238
+ if actual_count != expected_count:
239
+ if actual_count < expected_count:
240
+ logger_warning(
241
+ f"Not enough lookup values: Expected {expected_count}, got {actual_count}.",
242
+ __name__
243
+ )
244
+ lookup += bytes([0] * (expected_count - actual_count))
245
+ elif not check_if_whitespace_only(lookup[expected_count:]):
246
+ logger_warning(
247
+ f"Too many lookup values: Expected {expected_count}, got {actual_count}.",
248
+ __name__
249
+ )
250
+ lookup = lookup[:expected_count]
251
+ colors_arr = [lookup[:nb], lookup[nb:]]
252
+ arr = b"".join(
253
+ b"".join(
254
+ colors_arr[1 if img.getpixel((x, y)) > 127 else 0] # type: ignore[operator,unused-ignore] # TODO: Remove unused-ignore on Python 3.10
255
+ for x in range(img.size[0])
256
+ )
257
+ for y in range(img.size[1])
258
+ )
259
+ img = Image.frombytes(mode, img.size, arr)
260
+ else:
261
+ img = img.convert(conv)
262
+ if len(lookup) != (hival + 1) * nb:
263
+ logger_warning(f"Invalid Lookup Table in {obj_as_text}", __name__)
264
+ lookup = None
265
+ elif mode == "L":
266
+ # gray lookup does not work: it is converted to a similar RGB lookup
267
+ lookup = b"".join([bytes([b, b, b]) for b in lookup])
268
+ mode = "RGB"
269
+ # TODO: https://github.com/py-pdf/pypdf/pull/2039
270
+ # this is a work around until PIL is able to process CMYK images
271
+ elif mode == "CMYK":
272
+ _rgb = []
273
+ for _c, _m, _y, _k in (
274
+ lookup[n : n + 4] for n in range(0, 4 * (len(lookup) // 4), 4)
275
+ ):
276
+ _r = int(255 * (1 - _c / 255) * (1 - _k / 255))
277
+ _g = int(255 * (1 - _m / 255) * (1 - _k / 255))
278
+ _b = int(255 * (1 - _y / 255) * (1 - _k / 255))
279
+ _rgb.append(bytes((_r, _g, _b)))
280
+ lookup = b"".join(_rgb)
281
+ mode = "RGB"
282
+ if lookup is not None:
283
+ img.putpalette(lookup, rawmode=mode)
284
+ img = img.convert("L" if base == ColorSpaces.DEVICE_GRAY else "RGB")
285
+ elif not is_null_or_none(color_space) and color_space[0] == "/ICCBased":
286
+ # Exclude pure black-and-white images.
287
+ # TODO: The remaining code still does not look correct. Shouldn't the proper way be
288
+ # to use the original image and apply the ICC transformation on it?
289
+ # For now, this just loads the original image with a different color space.
290
+ if mode != "1":
291
+ # Table 65 - Additional Entries Specific to an ICC Profile Stream Dictionary
292
+ mode2 = _get_image_mode(color_space, colors, mode)[0]
293
+ if mode != mode2:
294
+ img = Image.frombytes(mode, size, data) # reloaded as mode may have changed
295
+ if mode == "CMYK":
296
+ extension = ".tif"
297
+ image_format = "TIFF"
298
+ return img, image_format, extension, False
299
+
300
+
301
+ def _handle_jpx(
302
+ size: tuple[int, int],
303
+ data: bytes,
304
+ mode: mode_str_type,
305
+ color_space: str,
306
+ colors: int,
307
+ ) -> tuple[Image.Image, str, str, bool]:
308
+ """
309
+ Process image encoded as JPX/JPEG2000
310
+ Returns img, image_format, extension, inversion
311
+ """
312
+ extension = ".jp2" # mime_type: "image/x-jp2"
313
+ img1: Image.Image = Image.open(BytesIO(data), formats=("JPEG2000",))
314
+ mode, invert_color = _get_image_mode(color_space, colors, mode)
315
+ if mode == "":
316
+ mode = cast(mode_str_type, img1.mode)
317
+ invert_color = mode == "CMYK"
318
+ if img1.mode == "RGBA" and mode == "RGB":
319
+ mode = "RGBA"
320
+ # we need to convert to the good mode
321
+ if img1.mode == mode or {img1.mode, mode} == {"L", "P"}: # compare (unordered) sets
322
+ # L and P are indexed modes which should not be changed.
323
+ img = img1
324
+ elif {img1.mode, mode} == {"RGBA", "CMYK"}:
325
+ # RGBA / CMYK are 4bytes encoding where
326
+ # the encoding should be corrected
327
+ img = Image.frombytes(mode, img1.size, img1.tobytes())
328
+ else: # pragma: no cover
329
+ img = img1.convert(mode)
330
+ # CMYK conversion
331
+ # https://stackverflow.com/questions/38855022/
332
+ if img.mode == "CMYK" and color_space == "/ICCBased":
333
+ img = img.convert("RGB")
334
+ image_format = "JPEG2000"
335
+ return img, image_format, extension, invert_color
336
+
337
+
338
+ def _apply_decode(
339
+ img: Image.Image,
340
+ x_object_obj: dict[str, Any],
341
+ lfilters: FT,
342
+ color_space: Union[str, list[Any], Any],
343
+ invert_color: bool,
344
+ ) -> Image.Image:
345
+ # CMYK image and other color spaces without decode
346
+ # requires reverting scale (cf p243,2§ last sentence)
347
+ if IA.DECODE in x_object_obj:
348
+ decode = x_object_obj[IA.DECODE]
349
+ # if invert_color and lfilters == FT.DCT_DECODE:
350
+ # decode = list(reversed(decode))
351
+ elif img.mode == "CMYK" and lfilters == FT.JPX_DECODE:
352
+ decode = [1.0, 0.0] if not invert_color else [0.0, 1.0]
353
+ decode = decode * len(img.getbands())
354
+ elif (img.mode == "CMYK" and lfilters == FT.DCT_DECODE) or (invert_color and img.mode == "L"):
355
+ decode = [1.0, 0.0] * len(img.getbands())
356
+ else:
357
+ decode = None
358
+
359
+ if (
360
+ isinstance(color_space, ArrayObject)
361
+ and color_space[0].get_object() == "/Indexed"
362
+ ):
363
+ decode = None # decode is meaningless if Indexed
364
+ if (
365
+ isinstance(color_space, ArrayObject)
366
+ and color_space[0].get_object() == "/Separation"
367
+ ):
368
+ decode = [1.0, 0.0] * len(img.getbands())
369
+ if decode is not None and not all(decode[i] == i % 2 for i in range(len(decode))):
370
+ lut: list[int] = []
371
+ for i in range(0, len(decode), 2):
372
+ dmin = decode[i]
373
+ dmax = decode[i + 1]
374
+ lut.extend(
375
+ round(255.0 * (j / 255.0 * (dmax - dmin) + dmin)) for j in range(256)
376
+ )
377
+ img = img.point(lut)
378
+ return img
379
+
380
+
381
+ def _get_mode_and_invert_color(
382
+ x_object_obj: dict[str, Any], colors: int, color_space: Union[str, list[Any], Any]
383
+ ) -> tuple[mode_str_type, bool]:
384
+ if (
385
+ IA.COLOR_SPACE in x_object_obj
386
+ and x_object_obj[IA.COLOR_SPACE] == ColorSpaces.DEVICE_RGB
387
+ ):
388
+ # https://pillow.readthedocs.io/en/stable/handbook/concepts.html#modes
389
+ mode: mode_str_type = "RGB"
390
+ if x_object_obj.get("/BitsPerComponent", 8) < 8:
391
+ mode, invert_color = _get_image_mode(
392
+ f"{x_object_obj.get('/BitsPerComponent', 8)}bit", 0, ""
393
+ )
394
+ else:
395
+ mode, invert_color = _get_image_mode(
396
+ color_space,
397
+ 2
398
+ if (
399
+ colors == 1
400
+ and (
401
+ not is_null_or_none(color_space)
402
+ and "Gray" not in color_space
403
+ )
404
+ )
405
+ else colors,
406
+ "",
407
+ )
408
+ return mode, invert_color
409
+
410
+
411
+ def _xobj_to_image(
412
+ x_object: dict[str, Any],
413
+ pillow_parameters: Union[dict[str, Any], None] = None
414
+ ) -> tuple[Optional[str], bytes, Any]:
415
+ """
416
+ Users need to have the pillow package installed.
417
+
418
+ It's unclear if pypdf will keep this function here, hence it's private.
419
+ It might get removed at any point.
420
+
421
+ Args:
422
+ x_object:
423
+ pillow_parameters: parameters provided to Pillow Image.save() method,
424
+ cf. <https://pillow.readthedocs.io/en/stable/reference/Image.html#PIL.Image.Image.save>
425
+
426
+ Returns:
427
+ Tuple[file extension, bytes, PIL.Image.Image]
428
+
429
+ """
430
+ def _apply_alpha(
431
+ img: Image.Image,
432
+ x_object: dict[str, Any],
433
+ obj_as_text: str,
434
+ image_format: str,
435
+ extension: str,
436
+ ) -> tuple[Image.Image, str, str]:
437
+ alpha = None
438
+ if IA.S_MASK in x_object: # add alpha channel
439
+ alpha = _xobj_to_image(x_object[IA.S_MASK])[2]
440
+ if img.size != alpha.size:
441
+ logger_warning(
442
+ f"image and mask size not matching: {obj_as_text}", __name__
443
+ )
444
+ else:
445
+ # TODO: implement mask
446
+ if alpha.mode != "L":
447
+ alpha = alpha.convert("L")
448
+ if img.mode == "P":
449
+ img = img.convert("RGB")
450
+ elif img.mode == "1":
451
+ img = img.convert("L")
452
+ img.putalpha(alpha)
453
+ if "JPEG" in image_format:
454
+ image_format = "JPEG2000"
455
+ extension = ".jp2"
456
+ else:
457
+ image_format = "PNG"
458
+ extension = ".png"
459
+ return img, extension, image_format
460
+
461
+ # For error reporting
462
+ obj_as_text = (
463
+ x_object.indirect_reference.__repr__()
464
+ if x_object is None # pragma: no cover
465
+ else x_object.__repr__()
466
+ )
467
+
468
+ # Get size and data
469
+ size = (cast(int, x_object[IA.WIDTH]), cast(int, x_object[IA.HEIGHT]))
470
+ data = x_object.get_data() # type: ignore
471
+ if isinstance(data, str): # pragma: no cover
472
+ data = data.encode()
473
+ if len(data) % (size[0] * size[1]) == 1 and data[-1] == 0x0A: # ie. '\n'
474
+ data = data[:-1]
475
+
476
+ # Get color properties
477
+ colors = x_object.get("/Colors", 1)
478
+ color_space: Any = x_object.get("/ColorSpace", NullObject()).get_object()
479
+ if isinstance(color_space, list) and len(color_space) == 1:
480
+ color_space = color_space[0].get_object()
481
+
482
+ mode, invert_color = _get_mode_and_invert_color(x_object, colors, color_space)
483
+
484
+ # Get filters
485
+ filters = x_object.get(StreamAttributes.FILTER, NullObject()).get_object()
486
+ lfilters = filters[-1] if isinstance(filters, list) else filters
487
+ decode_parms = x_object.get(StreamAttributes.DECODE_PARMS)
488
+ if decode_parms and isinstance(decode_parms, (tuple, list)):
489
+ decode_parms = decode_parms[0]
490
+ else:
491
+ decode_parms = {}
492
+ if not isinstance(decode_parms, dict):
493
+ decode_parms = {}
494
+
495
+ extension = None
496
+ if lfilters in (FT.FLATE_DECODE, FT.RUN_LENGTH_DECODE):
497
+ img, image_format, extension, _ = _handle_flate(
498
+ size,
499
+ data,
500
+ mode,
501
+ color_space,
502
+ colors,
503
+ obj_as_text,
504
+ )
505
+ elif lfilters in (FT.LZW_DECODE, FT.ASCII_85_DECODE):
506
+ # I'm not sure if the following logic is correct.
507
+ # There might not be any relationship between the filters and the
508
+ # extension
509
+ if lfilters == FT.LZW_DECODE:
510
+ image_format = "TIFF"
511
+ extension = ".tiff" # mime_type = "image/tiff"
512
+ else:
513
+ image_format = "PNG"
514
+ extension = ".png" # mime_type = "image/png"
515
+ try:
516
+ img = Image.open(BytesIO(data), formats=("TIFF", "PNG"))
517
+ except UnidentifiedImageError:
518
+ img = _extended_image_from_bytes(mode, size, data)
519
+ elif lfilters == FT.DCT_DECODE:
520
+ img, image_format, extension = Image.open(BytesIO(data)), "JPEG", ".jpg"
521
+ # invert_color kept unchanged
522
+ elif lfilters == FT.JPX_DECODE:
523
+ img, image_format, extension, invert_color = _handle_jpx(
524
+ size, data, mode, color_space, colors
525
+ )
526
+ elif lfilters == FT.CCITT_FAX_DECODE:
527
+ img, image_format, extension, invert_color = (
528
+ Image.open(BytesIO(data), formats=("TIFF",)),
529
+ "TIFF",
530
+ ".tiff",
531
+ False,
532
+ )
533
+ elif lfilters == FT.JBIG2_DECODE:
534
+ img, image_format, extension, invert_color = (
535
+ Image.open(BytesIO(data), formats=("PNG", "PPM")),
536
+ "PNG",
537
+ ".png",
538
+ False,
539
+ )
540
+ elif mode == "CMYK":
541
+ img, image_format, extension, invert_color = (
542
+ _extended_image_from_bytes(mode, size, data),
543
+ "TIFF",
544
+ ".tif",
545
+ False,
546
+ )
547
+ elif mode == "":
548
+ raise PdfReadError(f"ColorSpace field not found in {x_object}")
549
+ else:
550
+ img, image_format, extension, invert_color = (
551
+ _extended_image_from_bytes(mode, size, data),
552
+ "PNG",
553
+ ".png",
554
+ False,
555
+ )
556
+
557
+ img = _apply_decode(img, x_object, lfilters, color_space, invert_color)
558
+ img, extension, image_format = _apply_alpha(
559
+ img, x_object, obj_as_text, image_format, extension
560
+ )
561
+
562
+ if pillow_parameters is None:
563
+ pillow_parameters = {}
564
+ # Preserve JPEG image quality - see issue #3515.
565
+ if image_format == "JPEG":
566
+ # This prevents: Cannot use 'keep' when original image is not a JPEG:
567
+ # "JPEG" is the value of PIL.JpegImagePlugin.JpegImageFile.format
568
+ img.format = "JPEG"
569
+ if "quality" not in pillow_parameters:
570
+ pillow_parameters["quality"] = "keep"
571
+
572
+ # Save image to bytes
573
+ img_byte_arr = BytesIO()
574
+ try:
575
+ img.save(img_byte_arr, format=image_format, **pillow_parameters)
576
+ except OSError: # pragma: no cover # covered with pillow 10.3
577
+ # in case of we convert to RGBA and then to PNG
578
+ img1 = img.convert("RGBA")
579
+ image_format = "PNG"
580
+ extension = ".png"
581
+ img_byte_arr = BytesIO()
582
+ img1.save(img_byte_arr, format=image_format)
583
+ data = img_byte_arr.getvalue()
584
+
585
+ try: # temporary try/except until other fixes of images
586
+ img = Image.open(BytesIO(data))
587
+ except Exception as exception:
588
+ logger_warning(f"Failed loading image: {exception}", __name__)
589
+ img = None # type: ignore[assignment,unused-ignore] # TODO: Remove unused-ignore on Python 3.10
590
+ return extension, data, img
micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/generic/_link.py ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # All rights reserved.
2
+ #
3
+ # Redistribution and use in source and binary forms, with or without
4
+ # modification, are permitted provided that the following conditions are
5
+ # met:
6
+ #
7
+ # * Redistributions of source code must retain the above copyright notice,
8
+ # this list of conditions and the following disclaimer.
9
+ # * Redistributions in binary form must reproduce the above copyright notice,
10
+ # this list of conditions and the following disclaimer in the documentation
11
+ # and/or other materials provided with the distribution.
12
+ # * The name of the author may not be used to endorse or promote products
13
+ # derived from this software without specific prior written permission.
14
+ #
15
+ # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
16
+ # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17
+ # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18
+ # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
19
+ # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
20
+ # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
21
+ # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
22
+ # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
23
+ # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
24
+ # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
25
+ # POSSIBILITY OF SUCH DAMAGE.
26
+
27
+
28
+ # This module contains code used by _writer.py to track links in pages
29
+ # being added to the writer until the links can be resolved.
30
+
31
+ from typing import TYPE_CHECKING, Optional, Union, cast
32
+
33
+ from .._utils import logger_warning
34
+ from . import ArrayObject, DictionaryObject, IndirectObject, PdfObject, TextStringObject, is_null_or_none
35
+
36
+ if TYPE_CHECKING:
37
+ from .._page import PageObject
38
+ from .._reader import PdfReader
39
+ from .._writer import PdfWriter
40
+
41
+
42
+ class NamedReferenceLink:
43
+ """Named reference link being preserved until we can resolve it correctly."""
44
+
45
+ def __init__(self, reference: TextStringObject, source_pdf: "PdfReader") -> None:
46
+ """reference: TextStringObject with named reference"""
47
+ self._reference = reference
48
+ self._source_pdf = source_pdf
49
+
50
+ def find_referenced_page(self) -> Union[IndirectObject, None]:
51
+ destination = self._source_pdf.named_destinations.get(str(self._reference))
52
+ return destination.page if destination else None
53
+
54
+ def patch_reference(self, target_pdf: "PdfWriter", new_page: IndirectObject) -> None:
55
+ """target_pdf: PdfWriter which the new link went into"""
56
+ # point named destination in new PDF to the new page
57
+ if str(self._reference) not in target_pdf.named_destinations:
58
+ target_pdf.add_named_destination(str(self._reference), new_page.page_number)
59
+
60
+
61
+ class DirectReferenceLink:
62
+ """Direct reference link being preserved until we can resolve it correctly."""
63
+
64
+ def __init__(self, reference: ArrayObject) -> None:
65
+ """reference: an ArrayObject whose first element is the Page indirect object"""
66
+ self._reference = reference
67
+
68
+ def find_referenced_page(self) -> IndirectObject:
69
+ return cast(IndirectObject, self._reference[0])
70
+
71
+ def patch_reference(self, target_pdf: "PdfWriter", new_page: IndirectObject) -> None:
72
+ """target_pdf: PdfWriter which the new link went into"""
73
+ self._reference[0] = new_page
74
+
75
+
76
+ ReferenceLink = Union[NamedReferenceLink, DirectReferenceLink]
77
+
78
+
79
+ def extract_links(new_page: "PageObject", old_page: "PageObject") -> list[tuple[ReferenceLink, ReferenceLink]]:
80
+ """Extracts links from two pages on the assumption that the two pages are
81
+ the same. Produces one list of (new link, old link) tuples.
82
+
83
+ Non-link annotations are ignored before pairing to avoid dropping valid
84
+ links when one page includes additional non-link annotation entries.
85
+ """
86
+ new_annotations = new_page.get("/Annots", ArrayObject()).get_object()
87
+ old_annotations = old_page.get("/Annots", ArrayObject()).get_object()
88
+ if is_null_or_none(new_annotations):
89
+ new_annotations = ArrayObject()
90
+ if is_null_or_none(old_annotations):
91
+ old_annotations = ArrayObject()
92
+ if not isinstance(new_annotations, ArrayObject) or not isinstance(old_annotations, ArrayObject):
93
+ logger_warning(
94
+ f"Expected annotation arrays: {old_annotations} {new_annotations}. Ignoring annotations.",
95
+ __name__
96
+ )
97
+ return []
98
+ new_links = [
99
+ link
100
+ for annotation in new_annotations
101
+ if (link := _build_link(annotation, new_page)) is not None
102
+ ]
103
+ old_links = [
104
+ link
105
+ for annotation in old_annotations
106
+ if (link := _build_link(annotation, old_page)) is not None
107
+ ]
108
+
109
+ if len(new_links) != len(old_links):
110
+ logger_warning(
111
+ f"Annotation sizes differ: {old_links} vs. {new_links}",
112
+ __name__,
113
+ )
114
+
115
+ return list(zip(new_links, old_links))
116
+
117
+
118
+ def _build_link(indirect_object: IndirectObject, page: "PageObject") -> Optional[ReferenceLink]:
119
+ src = cast("PdfReader", page.pdf)
120
+ link = cast(DictionaryObject, indirect_object.get_object())
121
+ if (not isinstance(link, DictionaryObject)) or link.get("/Subtype") != "/Link":
122
+ return None
123
+
124
+ if "/A" in link:
125
+ action = cast(DictionaryObject, link["/A"])
126
+ if action.get("/S") != "/GoTo":
127
+ return None
128
+
129
+ if "/D" not in action:
130
+ return None
131
+ return _create_link(action["/D"], src)
132
+
133
+ if "/Dest" in link:
134
+ return _create_link(link["/Dest"], src)
135
+
136
+ return None # Nothing to do here
137
+
138
+
139
+ def _create_link(reference: PdfObject, source_pdf: "PdfReader") -> Optional[ReferenceLink]:
140
+ if isinstance(reference, TextStringObject):
141
+ return NamedReferenceLink(reference, source_pdf)
142
+ if isinstance(reference, ArrayObject):
143
+ return DirectReferenceLink(reference)
144
+ return None
micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/generic/_outline.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Union
2
+
3
+ from .._utils import StreamType, deprecation_no_replacement
4
+ from ._base import NameObject
5
+ from ._data_structures import Destination
6
+
7
+
8
+ class OutlineItem(Destination):
9
+ def write_to_stream(
10
+ self, stream: StreamType, encryption_key: Union[None, str, bytes] = None
11
+ ) -> None:
12
+ if encryption_key is not None: # deprecated
13
+ deprecation_no_replacement(
14
+ "the encryption_key parameter of write_to_stream", "5.0.0"
15
+ )
16
+ stream.write(b"<<\n")
17
+ for key in [
18
+ NameObject(x)
19
+ for x in ["/Title", "/Parent", "/First", "/Last", "/Next", "/Prev"]
20
+ if x in self
21
+ ]:
22
+ key.write_to_stream(stream)
23
+ stream.write(b" ")
24
+ value = self.raw_get(key)
25
+ value.write_to_stream(stream)
26
+ stream.write(b"\n")
27
+ key = NameObject("/Dest")
28
+ key.write_to_stream(stream)
29
+ stream.write(b" ")
30
+ value = self.dest_array
31
+ value.write_to_stream(stream)
32
+ stream.write(b"\n")
33
+ stream.write(b">>")
micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/generic/_rectangle.py ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Union
2
+
3
+ from ._base import FloatObject, NumberObject
4
+ from ._data_structures import ArrayObject
5
+
6
+
7
+ class RectangleObject(ArrayObject):
8
+ """
9
+ This class is used to represent *page boxes* in pypdf.
10
+
11
+ These boxes include:
12
+
13
+ * :attr:`artbox <pypdf._page.PageObject.artbox>`
14
+ * :attr:`bleedbox <pypdf._page.PageObject.bleedbox>`
15
+ * :attr:`cropbox <pypdf._page.PageObject.cropbox>`
16
+ * :attr:`mediabox <pypdf._page.PageObject.mediabox>`
17
+ * :attr:`trimbox <pypdf._page.PageObject.trimbox>`
18
+ """
19
+
20
+ def __init__(
21
+ self, arr: Union["RectangleObject", tuple[float, float, float, float]]
22
+ ) -> None:
23
+ # must have four points
24
+ assert len(arr) == 4
25
+ # automatically convert arr[x] into NumberObject(arr[x]) if necessary
26
+ ArrayObject.__init__(self, [self._ensure_is_number(x) for x in arr])
27
+
28
+ def _ensure_is_number(self, value: Any) -> Union[FloatObject, NumberObject]:
29
+ if not isinstance(value, (FloatObject, NumberObject)):
30
+ return FloatObject(value)
31
+ return value
32
+
33
+ def scale(self, sx: float, sy: float) -> "RectangleObject":
34
+ return RectangleObject(
35
+ (
36
+ float(self.left) * sx,
37
+ float(self.bottom) * sy,
38
+ float(self.right) * sx,
39
+ float(self.top) * sy,
40
+ )
41
+ )
42
+
43
+ def __repr__(self) -> str:
44
+ return f"RectangleObject({list(self)!r})"
45
+
46
+ @property
47
+ def left(self) -> FloatObject:
48
+ value: FloatObject = self[0]
49
+ return value
50
+
51
+ @left.setter
52
+ def left(self, f: float) -> None:
53
+ self[0] = FloatObject(f)
54
+
55
+ @property
56
+ def bottom(self) -> FloatObject:
57
+ value: FloatObject = self[1]
58
+ return value
59
+
60
+ @bottom.setter
61
+ def bottom(self, f: float) -> None:
62
+ self[1] = FloatObject(f)
63
+
64
+ @property
65
+ def right(self) -> FloatObject:
66
+ value: FloatObject = self[2]
67
+ return value
68
+
69
+ @right.setter
70
+ def right(self, f: float) -> None:
71
+ self[2] = FloatObject(f)
72
+
73
+ @property
74
+ def top(self) -> FloatObject:
75
+ value: FloatObject = self[3]
76
+ return value
77
+
78
+ @top.setter
79
+ def top(self, f: float) -> None:
80
+ self[3] = FloatObject(f)
81
+
82
+ @property
83
+ def lower_left(self) -> tuple[float, float]:
84
+ """
85
+ Property to read and modify the lower left coordinate of this box
86
+ in (x,y) form.
87
+ """
88
+ return self.left, self.bottom
89
+
90
+ @lower_left.setter
91
+ def lower_left(self, value: tuple[float, float]) -> None:
92
+ self[0], self[1] = (self._ensure_is_number(x) for x in value)
93
+
94
+ @property
95
+ def lower_right(self) -> tuple[float, float]:
96
+ """
97
+ Property to read and modify the lower right coordinate of this box
98
+ in (x,y) form.
99
+ """
100
+ return self.right, self.bottom
101
+
102
+ @lower_right.setter
103
+ def lower_right(self, value: tuple[float, float]) -> None:
104
+ self[2], self[1] = (self._ensure_is_number(x) for x in value)
105
+
106
+ @property
107
+ def upper_left(self) -> tuple[float, float]:
108
+ """
109
+ Property to read and modify the upper left coordinate of this box
110
+ in (x,y) form.
111
+ """
112
+ return self.left, self.top
113
+
114
+ @upper_left.setter
115
+ def upper_left(self, value: tuple[float, float]) -> None:
116
+ self[0], self[3] = (self._ensure_is_number(x) for x in value)
117
+
118
+ @property
119
+ def upper_right(self) -> tuple[float, float]:
120
+ """
121
+ Property to read and modify the upper right coordinate of this box
122
+ in (x,y) form.
123
+ """
124
+ return self.right, self.top
125
+
126
+ @upper_right.setter
127
+ def upper_right(self, value: tuple[float, float]) -> None:
128
+ self[2], self[3] = (self._ensure_is_number(x) for x in value)
129
+
130
+ @property
131
+ def width(self) -> float:
132
+ return self.right - self.left
133
+
134
+ @property
135
+ def height(self) -> float:
136
+ return self.top - self.bottom
micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/generic/_utils.py ADDED
@@ -0,0 +1,208 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import codecs
2
+ from typing import Union
3
+
4
+ from .._codecs import _pdfdoc_encoding
5
+ from .._utils import StreamType, logger_warning, read_non_whitespace
6
+ from ..errors import STREAM_TRUNCATED_PREMATURELY, PdfStreamError
7
+ from ._base import ByteStringObject, TextStringObject
8
+
9
+
10
+ def hex_to_rgb(value: str) -> tuple[float, float, float]:
11
+ return tuple(int(value.lstrip("#")[i : i + 2], 16) / 255.0 for i in (0, 2, 4)) # type: ignore
12
+
13
+
14
+ def read_hex_string_from_stream(
15
+ stream: StreamType,
16
+ forced_encoding: Union[None, str, list[str], dict[int, str]] = None,
17
+ ) -> Union["TextStringObject", "ByteStringObject"]:
18
+ stream.read(1)
19
+ arr = []
20
+ x = b""
21
+ while True:
22
+ tok = read_non_whitespace(stream)
23
+ if not tok:
24
+ raise PdfStreamError(STREAM_TRUNCATED_PREMATURELY)
25
+ if tok == b">":
26
+ break
27
+ x += tok
28
+ if len(x) == 2:
29
+ arr.append(int(x, base=16))
30
+ x = b""
31
+ if len(x) == 1:
32
+ x += b"0"
33
+ if x != b"":
34
+ arr.append(int(x, base=16))
35
+ return create_string_object(bytes(arr), forced_encoding)
36
+
37
+
38
+ __ESCAPE_DICT__ = {
39
+ b"n": ord(b"\n"),
40
+ b"r": ord(b"\r"),
41
+ b"t": ord(b"\t"),
42
+ b"b": ord(b"\b"),
43
+ b"f": ord(b"\f"),
44
+ b"(": ord(b"("),
45
+ b")": ord(b")"),
46
+ b"/": ord(b"/"),
47
+ b"\\": ord(b"\\"),
48
+ b" ": ord(b" "),
49
+ b"%": ord(b"%"),
50
+ b"<": ord(b"<"),
51
+ b">": ord(b">"),
52
+ b"[": ord(b"["),
53
+ b"]": ord(b"]"),
54
+ b"#": ord(b"#"),
55
+ b"_": ord(b"_"),
56
+ b"&": ord(b"&"),
57
+ b"$": ord(b"$"),
58
+ }
59
+ __BACKSLASH_CODE__ = 92
60
+
61
+
62
+ def read_string_from_stream(
63
+ stream: StreamType,
64
+ forced_encoding: Union[None, str, list[str], dict[int, str]] = None,
65
+ ) -> Union["TextStringObject", "ByteStringObject"]:
66
+ tok = stream.read(1)
67
+ parens = 1
68
+ txt = []
69
+ while True:
70
+ tok = stream.read(1)
71
+ if not tok:
72
+ raise PdfStreamError(STREAM_TRUNCATED_PREMATURELY)
73
+ if tok == b"(":
74
+ parens += 1
75
+ elif tok == b")":
76
+ parens -= 1
77
+ if parens == 0:
78
+ break
79
+ elif tok == b"\\":
80
+ tok = stream.read(1)
81
+ try:
82
+ txt.append(__ESCAPE_DICT__[tok])
83
+ continue
84
+ except KeyError:
85
+ if b"0" <= tok <= b"7":
86
+ # "The number ddd may consist of one, two, or three
87
+ # octal digits; high-order overflow shall be ignored.
88
+ # Three octal digits shall be used, with leading zeros
89
+ # as needed, if the next character of the string is also
90
+ # a digit." (PDF reference 7.3.4.2, p 16)
91
+ sav = stream.tell() - 1
92
+ for _ in range(2):
93
+ ntok = stream.read(1)
94
+ if b"0" <= ntok <= b"7":
95
+ tok += ntok
96
+ else:
97
+ stream.seek(-1, 1) # ntok has to be analyzed
98
+ break
99
+ i = int(tok, base=8)
100
+ if i > 255:
101
+ txt.append(__BACKSLASH_CODE__)
102
+ stream.seek(sav)
103
+ else:
104
+ txt.append(i)
105
+ continue
106
+ if tok in b"\n\r":
107
+ # This case is hit when a backslash followed by a line
108
+ # break occurs. If it's a multi-char EOL, consume the
109
+ # second character:
110
+ tok = stream.read(1)
111
+ if tok not in b"\n\r":
112
+ stream.seek(-1, 1)
113
+ # Then don't add anything to the actual string, since this
114
+ # line break was escaped:
115
+ continue
116
+ msg = f"Unexpected escaped string: {tok.decode('utf-8', 'ignore')}"
117
+ logger_warning(msg, __name__)
118
+ txt.append(__BACKSLASH_CODE__)
119
+ txt.append(ord(tok))
120
+ return create_string_object(bytes(txt), forced_encoding)
121
+
122
+
123
+ def create_string_object(
124
+ string: Union[str, bytes],
125
+ forced_encoding: Union[None, str, list[str], dict[int, str]] = None,
126
+ ) -> Union[TextStringObject, ByteStringObject]:
127
+ """
128
+ Create a ByteStringObject or a TextStringObject from a string to represent the string.
129
+
130
+ Args:
131
+ string: The data being used
132
+ forced_encoding: Typically None, or an encoding string
133
+
134
+ Returns:
135
+ A ByteStringObject
136
+
137
+ Raises:
138
+ TypeError: If string is not of type str or bytes.
139
+
140
+ """
141
+ if isinstance(string, str):
142
+ return TextStringObject(string)
143
+ if isinstance(string, bytes):
144
+ if isinstance(forced_encoding, (list, dict)):
145
+ out = ""
146
+ for x in string:
147
+ try:
148
+ out += forced_encoding[x]
149
+ except Exception:
150
+ out += bytes((x,)).decode("charmap")
151
+ obj = TextStringObject(out)
152
+ obj._original_bytes = string
153
+ return obj
154
+ if isinstance(forced_encoding, str):
155
+ if forced_encoding == "bytes":
156
+ return ByteStringObject(string)
157
+ obj = TextStringObject(string.decode(forced_encoding))
158
+ obj._original_bytes = string
159
+ return obj
160
+ try:
161
+ if string.startswith((codecs.BOM_UTF16_BE, codecs.BOM_UTF16_LE)):
162
+ retval = TextStringObject(string.decode("utf-16"))
163
+ retval._original_bytes = string
164
+ retval.autodetect_utf16 = True
165
+ retval.utf16_bom = string[:2]
166
+ return retval
167
+ if string.startswith(b"\x00"):
168
+ retval = TextStringObject(string.decode("utf-16be"))
169
+ retval._original_bytes = string
170
+ retval.autodetect_utf16 = True
171
+ retval.utf16_bom = codecs.BOM_UTF16_BE
172
+ return retval
173
+ if string[1:2] == b"\x00":
174
+ retval = TextStringObject(string.decode("utf-16le"))
175
+ retval._original_bytes = string
176
+ retval.autodetect_utf16 = True
177
+ retval.utf16_bom = codecs.BOM_UTF16_LE
178
+ return retval
179
+
180
+ # This is probably a big performance hit here, but we need
181
+ # to convert string objects into the text/unicode-aware
182
+ # version if possible... and the only way to check if that's
183
+ # possible is to try.
184
+ # Some strings are strings, some are just byte arrays.
185
+ retval = TextStringObject(decode_pdfdocencoding(string))
186
+ retval._original_bytes = string
187
+ retval.autodetect_pdfdocencoding = True
188
+ return retval
189
+ except UnicodeDecodeError:
190
+ return ByteStringObject(string)
191
+ else:
192
+ raise TypeError("create_string_object should have str or unicode arg")
193
+
194
+
195
+ def decode_pdfdocencoding(byte_array: bytes) -> str:
196
+ retval = ""
197
+ for b in byte_array:
198
+ c = _pdfdoc_encoding[b]
199
+ if c == "\u0000":
200
+ raise UnicodeDecodeError(
201
+ "pdfdocencoding",
202
+ bytearray(b),
203
+ -1,
204
+ -1,
205
+ "does not exist in translation table",
206
+ )
207
+ retval += c
208
+ return retval
micromamba_root/envs/pytorch_env/Lib/site-packages/pypdf/generic/_viewerpref.py ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2023, Pubpub-ZZ
2
+ #
3
+ # All rights reserved.
4
+ #
5
+ # Redistribution and use in source and binary forms, with or without
6
+ # modification, are permitted provided that the following conditions are
7
+ # met:
8
+ #
9
+ # * Redistributions of source code must retain the above copyright notice,
10
+ # this list of conditions and the following disclaimer.
11
+ # * Redistributions in binary form must reproduce the above copyright notice,
12
+ # this list of conditions and the following disclaimer in the documentation
13
+ # and/or other materials provided with the distribution.
14
+ # * The name of the author may not be used to endorse or promote products
15
+ # derived from this software without specific prior written permission.
16
+ #
17
+ # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
18
+ # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19
+ # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20
+ # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
21
+ # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
22
+ # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
23
+ # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
24
+ # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
25
+ # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
26
+ # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27
+ # POSSIBILITY OF SUCH DAMAGE.
28
+
29
+ from typing import (
30
+ Any,
31
+ Optional,
32
+ cast,
33
+ )
34
+
35
+ from ._base import BooleanObject, NameObject, NumberObject, is_null_or_none
36
+ from ._data_structures import ArrayObject, DictionaryObject
37
+
38
+ f_obj = BooleanObject(False)
39
+
40
+
41
+ class ViewerPreferences(DictionaryObject):
42
+ def __init__(self, obj: Optional[DictionaryObject] = None) -> None:
43
+ super().__init__(self)
44
+ if not is_null_or_none(obj):
45
+ self.update(obj.items()) # type: ignore
46
+ try:
47
+ self.indirect_reference = obj.indirect_reference # type: ignore
48
+ except AttributeError:
49
+ pass
50
+
51
+ def _get_bool(self, key: str, default: Optional[BooleanObject]) -> Optional[BooleanObject]:
52
+ return self.get(key, default)
53
+
54
+ def _set_bool(self, key: str, v: bool) -> None:
55
+ self[NameObject(key)] = BooleanObject(v is True)
56
+
57
+ def _get_name(self, key: str, default: Optional[NameObject]) -> Optional[NameObject]:
58
+ return self.get(key, default)
59
+
60
+ def _set_name(self, key: str, lst: list[str], v: NameObject) -> None:
61
+ if v[0] != "/":
62
+ raise ValueError(f"{v} does not start with '/'")
63
+ if lst != [] and v not in lst:
64
+ raise ValueError(f"{v} is an unacceptable value")
65
+ self[NameObject(key)] = NameObject(v)
66
+
67
+ def _get_arr(self, key: str, default: Optional[list[Any]]) -> Optional[ArrayObject]:
68
+ return self.get(key, None if default is None else ArrayObject(default))
69
+
70
+ def _set_arr(self, key: str, v: Optional[ArrayObject]) -> None:
71
+ if v is None:
72
+ try:
73
+ del self[NameObject(key)]
74
+ except KeyError:
75
+ pass
76
+ return
77
+ if not isinstance(v, ArrayObject):
78
+ raise ValueError("ArrayObject is expected")
79
+ self[NameObject(key)] = v
80
+
81
+ def _get_int(self, key: str, default: Optional[NumberObject]) -> Optional[NumberObject]:
82
+ return self.get(key, default)
83
+
84
+ def _set_int(self, key: str, v: int) -> None:
85
+ self[NameObject(key)] = NumberObject(v)
86
+
87
+ @property
88
+ def PRINT_SCALING(self) -> NameObject:
89
+ return NameObject("/PrintScaling")
90
+
91
+ def __new__(cls: Any, value: Any = None) -> "ViewerPreferences": # noqa: PYI034
92
+ def _add_prop_bool(key: str, default: Optional[BooleanObject]) -> property:
93
+ return property(
94
+ lambda self: self._get_bool(key, default),
95
+ lambda self, v: self._set_bool(key, v),
96
+ None,
97
+ f"""
98
+ Returns/Modify the status of {key}, Returns {default} if not defined
99
+ """,
100
+ )
101
+
102
+ def _add_prop_name(
103
+ key: str, lst: list[str], default: Optional[NameObject]
104
+ ) -> property:
105
+ return property(
106
+ lambda self: self._get_name(key, default),
107
+ lambda self, v: self._set_name(key, lst, v),
108
+ None,
109
+ f"""
110
+ Returns/Modify the status of {key}, Returns {default} if not defined.
111
+ Acceptable values: {lst}
112
+ """,
113
+ )
114
+
115
+ def _add_prop_arr(key: str, default: Optional[ArrayObject]) -> property:
116
+ return property(
117
+ lambda self: self._get_arr(key, default),
118
+ lambda self, v: self._set_arr(key, v),
119
+ None,
120
+ f"""
121
+ Returns/Modify the status of {key}, Returns {default} if not defined
122
+ """,
123
+ )
124
+
125
+ def _add_prop_int(key: str, default: Optional[int]) -> property:
126
+ return property(
127
+ lambda self: self._get_int(key, default),
128
+ lambda self, v: self._set_int(key, v),
129
+ None,
130
+ f"""
131
+ Returns/Modify the status of {key}, Returns {default} if not defined
132
+ """,
133
+ )
134
+
135
+ cls.hide_toolbar = _add_prop_bool("/HideToolbar", f_obj)
136
+ cls.hide_menubar = _add_prop_bool("/HideMenubar", f_obj)
137
+ cls.hide_windowui = _add_prop_bool("/HideWindowUI", f_obj)
138
+ cls.fit_window = _add_prop_bool("/FitWindow", f_obj)
139
+ cls.center_window = _add_prop_bool("/CenterWindow", f_obj)
140
+ cls.display_doctitle = _add_prop_bool("/DisplayDocTitle", f_obj)
141
+
142
+ cls.non_fullscreen_pagemode = _add_prop_name(
143
+ "/NonFullScreenPageMode",
144
+ ["/UseNone", "/UseOutlines", "/UseThumbs", "/UseOC"],
145
+ NameObject("/UseNone"),
146
+ )
147
+ cls.direction = _add_prop_name(
148
+ "/Direction", ["/L2R", "/R2L"], NameObject("/L2R")
149
+ )
150
+ cls.view_area = _add_prop_name("/ViewArea", [], None)
151
+ cls.view_clip = _add_prop_name("/ViewClip", [], None)
152
+ cls.print_area = _add_prop_name("/PrintArea", [], None)
153
+ cls.print_clip = _add_prop_name("/PrintClip", [], None)
154
+ cls.print_scaling = _add_prop_name("/PrintScaling", [], None)
155
+ cls.duplex = _add_prop_name(
156
+ "/Duplex", ["/Simplex", "/DuplexFlipShortEdge", "/DuplexFlipLongEdge"], None
157
+ )
158
+ cls.pick_tray_by_pdfsize = _add_prop_bool("/PickTrayByPDFSize", None)
159
+ cls.print_pagerange = _add_prop_arr("/PrintPageRange", None)
160
+ cls.num_copies = _add_prop_int("/NumCopies", None)
161
+
162
+ cls.enforce = _add_prop_arr("/Enforce", ArrayObject())
163
+
164
+ return cast("ViewerPreferences", DictionaryObject.__new__(cls))
micromamba_root/envs/pytorch_env/Lib/site-packages/pypika-0.51.1.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ pip
micromamba_root/envs/pytorch_env/Lib/site-packages/pypika-0.51.1.dist-info/METADATA ADDED
@@ -0,0 +1,1879 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.4
2
+ Name: PyPika
3
+ Version: 0.51.1
4
+ Summary: A SQL query builder API for Python
5
+ Home-page: https://github.com/kayak/pypika
6
+ Author: Timothy Heys
7
+ Author-email: theys@kayak.com
8
+ License: Apache License Version 2.0
9
+ Keywords: pypika python query builder querybuilder sql mysql postgres psql oracle vertica aggregated relational database rdbms business analytics bi data science analysis pandas orm object mapper
10
+ Classifier: License :: OSI Approved :: Apache Software License
11
+ Classifier: Development Status :: 5 - Production/Stable
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: PL/SQL
15
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
16
+ Classifier: Topic :: Scientific/Engineering :: Information Analysis
17
+ Classifier: Topic :: Scientific/Engineering :: Mathematics
18
+ Classifier: Operating System :: POSIX
19
+ Classifier: Operating System :: MacOS :: MacOS X
20
+ Classifier: Operating System :: Microsoft :: Windows
21
+ License-File: LICENSE.txt
22
+ Requires-Dist: typing_extensions>=4.5.0; python_version < "3.11"
23
+ Dynamic: author
24
+ Dynamic: author-email
25
+ Dynamic: classifier
26
+ Dynamic: description
27
+ Dynamic: home-page
28
+ Dynamic: keywords
29
+ Dynamic: license
30
+ Dynamic: license-file
31
+ Dynamic: requires-dist
32
+ Dynamic: summary
33
+
34
+ PyPika - Python Query Builder
35
+ =============================
36
+
37
+ .. _intro_start:
38
+
39
+ |BuildStatus| |CoverageStatus| |Codacy| |Docs| |PyPi| |License|
40
+
41
+ Abstract
42
+ --------
43
+
44
+ What is |Brand|?
45
+
46
+ |Brand| is a Python API for building SQL queries. The motivation behind |Brand| is to provide a simple interface for
47
+ building SQL queries without limiting the flexibility of handwritten SQL. Designed with data analysis in mind, |Brand|
48
+ leverages the builder design pattern to construct queries to avoid messy string formatting and concatenation. It is also
49
+ easily extended to take full advantage of specific features of SQL database vendors.
50
+
51
+ What are the design goals for |Brand|?
52
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
53
+
54
+ |Brand| is a fast, expressive and flexible way to replace handwritten SQL (or even ORM for the courageous souls amongst you).
55
+ Validation of SQL correctness is not an explicit goal of |Brand|. With such a large number of
56
+ SQL database vendors providing a robust validation of input data is difficult. Instead you are encouraged to check inputs you provide to |Brand| or appropriately handle errors raised from
57
+ your SQL database - just as you would have if you were writing SQL yourself.
58
+
59
+ .. _intro_end:
60
+
61
+ Read the docs: http://pypika.readthedocs.io/en/latest/
62
+
63
+ Installation
64
+ ------------
65
+
66
+ .. _installation_start:
67
+
68
+ |Brand| supports is tested for supported Python, i.e. 3.9+. It is tested for PyPy3.9 and PyPy3.10. It may also work Cython, and Jython but is not being tested for in the CI script.
69
+
70
+ To install |Brand| run the following command:
71
+
72
+ .. code-block:: bash
73
+
74
+ pip install pypika
75
+
76
+
77
+ .. _installation_end:
78
+
79
+
80
+ Tutorial
81
+ --------
82
+
83
+ .. _tutorial_start:
84
+
85
+ The main classes in pypika are ``pypika.Query``, ``pypika.Table``, and ``pypika.Field``.
86
+
87
+ .. code-block:: python
88
+
89
+ from pypika import Query, Table, Field
90
+
91
+
92
+ Selecting Data
93
+ ^^^^^^^^^^^^^^
94
+
95
+ The entry point for building queries is ``pypika.Query``. In order to select columns from a table, the table must
96
+ first be added to the query. For simple queries with only one table, tables and columns can be references using
97
+ strings. For more sophisticated queries a ``pypika.Table`` must be used.
98
+
99
+ .. code-block:: python
100
+
101
+ q = Query.from_('customers').select('id', 'fname', 'lname', 'phone')
102
+
103
+ To convert the query into raw SQL, it can be cast to a string.
104
+
105
+ .. code-block:: python
106
+
107
+ str(q)
108
+
109
+ Alternatively, you can use the `Query.get_sql()` function:
110
+
111
+ .. code-block:: python
112
+
113
+ q.get_sql()
114
+
115
+
116
+ Tables, Columns, Schemas, and Databases
117
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
118
+
119
+ In simple queries like the above example, columns in the "from" table can be referenced by passing string names into
120
+ the ``select`` query builder function. In more complex examples, the ``pypika.Table`` class should be used. Columns can be
121
+ referenced as attributes on instances of ``pypika.Table``.
122
+
123
+ .. code-block:: python
124
+
125
+ from pypika import Table, Query
126
+
127
+ customers = Table('customers')
128
+ q = Query.from_(customers).select(customers.id, customers.fname, customers.lname, customers.phone)
129
+
130
+ Both of the above examples result in the following SQL:
131
+
132
+ .. code-block:: sql
133
+
134
+ SELECT id,fname,lname,phone FROM customers
135
+
136
+ An alias for the table can be given using the ``.as_`` function on ``pypika.Table``
137
+
138
+ .. code-block:: sql
139
+
140
+ customers = Table('x_view_customers').as_('customers')
141
+ q = Query.from_(customers).select(customers.id, customers.phone)
142
+
143
+ .. code-block:: sql
144
+
145
+ SELECT id,phone FROM x_view_customers customers
146
+
147
+ A schema can also be specified. Tables can be referenced as attributes on the schema.
148
+
149
+ .. code-block:: sql
150
+
151
+ from pypika import Table, Query, Schema
152
+
153
+ views = Schema('views')
154
+ q = Query.from_(views.customers).select(customers.id, customers.phone)
155
+
156
+ .. code-block:: sql
157
+
158
+ SELECT id,phone FROM views.customers
159
+
160
+ Also references to databases can be used. Schemas can be referenced as attributes on the database.
161
+
162
+ .. code-block:: sql
163
+
164
+ from pypika import Table, Query, Database
165
+
166
+ my_db = Database('my_db')
167
+ q = Query.from_(my_db.analytics.customers).select(customers.id, customers.phone)
168
+
169
+ .. code-block:: sql
170
+
171
+ SELECT id,phone FROM my_db.analytics.customers
172
+
173
+
174
+ Results can be ordered by using the following syntax:
175
+
176
+ .. code-block:: python
177
+
178
+ from pypika import Order
179
+ Query.from_('customers').select('id', 'fname', 'lname', 'phone').orderby('id', order=Order.desc)
180
+
181
+ This results in the following SQL:
182
+
183
+ .. code-block:: sql
184
+
185
+ SELECT "id","fname","lname","phone" FROM "customers" ORDER BY "id" DESC
186
+
187
+ Arithmetic
188
+ """"""""""
189
+
190
+ Arithmetic expressions can also be constructed using pypika. Operators such as `+`, `-`, `*`, and `/` are implemented
191
+ by ``pypika.Field`` which can be used simply with a ``pypika.Table`` or directly.
192
+
193
+ .. code-block:: python
194
+
195
+ from pypika import Field
196
+
197
+ q = Query.from_('account').select(
198
+ Field('revenue') - Field('cost')
199
+ )
200
+
201
+ .. code-block:: sql
202
+
203
+ SELECT revenue-cost FROM accounts
204
+
205
+ Using ``pypika.Table``
206
+
207
+ .. code-block:: python
208
+
209
+ accounts = Table('accounts')
210
+ q = Query.from_(accounts).select(
211
+ accounts.revenue - accounts.cost
212
+ )
213
+
214
+ .. code-block:: sql
215
+
216
+ SELECT revenue-cost FROM accounts
217
+
218
+ An alias can also be used for fields and expressions.
219
+
220
+ .. code-block:: sql
221
+
222
+ q = Query.from_(accounts).select(
223
+ (accounts.revenue - accounts.cost).as_('profit')
224
+ )
225
+
226
+ .. code-block:: sql
227
+
228
+ SELECT revenue-cost profit FROM accounts
229
+
230
+ More arithmetic examples
231
+
232
+ .. code-block:: python
233
+
234
+ table = Table('table')
235
+ q = Query.from_(table).select(
236
+ table.foo + table.bar,
237
+ table.foo - table.bar,
238
+ table.foo * table.bar,
239
+ table.foo / table.bar,
240
+ (table.foo+table.bar) / table.fiz,
241
+ )
242
+
243
+ .. code-block:: sql
244
+
245
+ SELECT foo+bar,foo-bar,foo*bar,foo/bar,(foo+bar)/fiz FROM table
246
+
247
+ Bitwise operations are also supported using the ``bitwiseand`` and ``bitwiseor`` methods.
248
+
249
+ .. code-block:: python
250
+
251
+ from pypika import Query, Field
252
+
253
+ q = Query.from_('flags').select('name').where(Field('permissions').bitwiseand(4) == 4)
254
+
255
+ .. code-block:: sql
256
+
257
+ SELECT "name" FROM "flags" WHERE ("permissions" & 4)=4
258
+
259
+ .. code-block:: python
260
+
261
+ q = Query.from_('flags').select('name').where(Field('permissions').bitwiseor(2) == 3)
262
+
263
+ .. code-block:: sql
264
+
265
+ SELECT "name" FROM "flags" WHERE ("permissions" | 2)=3
266
+
267
+
268
+ Filtering
269
+ """""""""
270
+
271
+ Queries can be filtered with ``pypika.Criterion`` by using equality or inequality operators
272
+
273
+ .. code-block:: python
274
+
275
+ customers = Table('customers')
276
+ q = Query.from_(customers).select(
277
+ customers.id, customers.fname, customers.lname, customers.phone
278
+ ).where(
279
+ customers.lname == 'Mustermann'
280
+ )
281
+
282
+ .. code-block:: sql
283
+
284
+ SELECT id,fname,lname,phone FROM customers WHERE lname='Mustermann'
285
+
286
+ Query methods such as select, where, groupby, and orderby can be called multiple times. Multiple calls to the where
287
+ method will add additional conditions as
288
+
289
+ .. code-block:: python
290
+
291
+ customers = Table('customers')
292
+ q = Query.from_(customers).select(
293
+ customers.id, customers.fname, customers.lname, customers.phone
294
+ ).where(
295
+ customers.fname == 'Max'
296
+ ).where(
297
+ customers.lname == 'Mustermann'
298
+ )
299
+
300
+ .. code-block:: sql
301
+
302
+ SELECT id,fname,lname,phone FROM customers WHERE fname='Max' AND lname='Mustermann'
303
+
304
+ Filters such as IN and BETWEEN are also supported
305
+
306
+ .. code-block:: python
307
+
308
+ customers = Table('customers')
309
+ q = Query.from_(customers).select(
310
+ customers.id,customers.fname
311
+ ).where(
312
+ customers.age[18:65] & customers.status.isin(['new', 'active'])
313
+ )
314
+
315
+ .. code-block:: sql
316
+
317
+ SELECT id,fname FROM customers WHERE age BETWEEN 18 AND 65 AND status IN ('new','active')
318
+
319
+ Filtering with complex criteria can be created using boolean symbols ``&``, ``|``, and ``^``.
320
+
321
+ AND
322
+
323
+ .. code-block:: python
324
+
325
+ customers = Table('customers')
326
+ q = Query.from_(customers).select(
327
+ customers.id, customers.fname, customers.lname, customers.phone
328
+ ).where(
329
+ (customers.age >= 18) & (customers.lname == 'Mustermann')
330
+ )
331
+
332
+ .. code-block:: sql
333
+
334
+ SELECT id,fname,lname,phone FROM customers WHERE age>=18 AND lname='Mustermann'
335
+
336
+ OR
337
+
338
+ .. code-block:: python
339
+
340
+ customers = Table('customers')
341
+ q = Query.from_(customers).select(
342
+ customers.id, customers.fname, customers.lname, customers.phone
343
+ ).where(
344
+ (customers.age >= 18) | (customers.lname == 'Mustermann')
345
+ )
346
+
347
+ .. code-block:: sql
348
+
349
+ SELECT id,fname,lname,phone FROM customers WHERE age>=18 OR lname='Mustermann'
350
+
351
+ XOR
352
+
353
+ .. code-block:: python
354
+
355
+ customers = Table('customers')
356
+ q = Query.from_(customers).select(
357
+ customers.id, customers.fname, customers.lname, customers.phone
358
+ ).where(
359
+ (customers.age >= 18) ^ customers.is_registered
360
+ )
361
+
362
+ .. code-block:: sql
363
+
364
+ SELECT id,fname,lname,phone FROM customers WHERE age>=18 XOR is_registered
365
+
366
+
367
+ Convenience Methods
368
+ """""""""""""""""""
369
+
370
+ In the `Criterion` class, there are the static methods `any` and `all` that allow building chains AND and OR expressions with a list of terms.
371
+
372
+ .. code-block:: python
373
+
374
+ from pypika import Criterion
375
+
376
+ customers = Table('customers')
377
+ q = Query.from_(customers).select(
378
+ customers.id,
379
+ customers.fname
380
+ ).where(
381
+ Criterion.all([
382
+ customers.is_registered,
383
+ customers.age >= 18,
384
+ customers.lname == "Jones",
385
+ ])
386
+ )
387
+
388
+ .. code-block:: sql
389
+
390
+ SELECT id,fname FROM customers WHERE is_registered AND age>=18 AND lname = "Jones"
391
+
392
+
393
+ Grouping and Aggregating
394
+ """"""""""""""""""""""""
395
+
396
+ Grouping allows for aggregated results and works similar to ``SELECT`` clauses.
397
+
398
+ .. code-block:: python
399
+
400
+ from pypika import functions as fn
401
+
402
+ customers = Table('customers')
403
+ q = Query \
404
+ .from_(customers) \
405
+ .where(customers.age >= 18) \
406
+ .groupby(customers.id) \
407
+ .select(customers.id, fn.Sum(customers.revenue))
408
+
409
+ .. code-block:: sql
410
+
411
+ SELECT id,SUM("revenue") FROM "customers" WHERE "age">=18 GROUP BY "id"
412
+
413
+ After adding a ``GROUP BY`` clause to a query, the ``HAVING`` clause becomes available. The method
414
+ ``Query.having()`` takes a ``Criterion`` parameter similar to the method ``Query.where()``.
415
+
416
+ .. code-block:: python
417
+
418
+ from pypika import functions as fn
419
+
420
+ payments = Table('payments')
421
+ q = Query \
422
+ .from_(payments) \
423
+ .where(payments.transacted[date(2015, 1, 1):date(2016, 1, 1)]) \
424
+ .groupby(payments.customer_id) \
425
+ .having(fn.Sum(payments.total) >= 1000) \
426
+ .select(payments.customer_id, fn.Sum(payments.total))
427
+
428
+ .. code-block:: sql
429
+
430
+ SELECT customer_id,SUM(total) FROM payments
431
+ WHERE transacted BETWEEN '2015-01-01' AND '2016-01-01'
432
+ GROUP BY customer_id HAVING SUM(total)>=1000
433
+
434
+ The ``QUALIFY`` clause can be used to filter rows based on window function results. This is particularly useful
435
+ when you want to filter after window functions have been evaluated.
436
+
437
+ .. code-block:: python
438
+
439
+ from pypika import Query, Table, analytics as an
440
+
441
+ table = Table('events')
442
+ rank_expr = an.Rank().over(table.user_id).orderby(table.created_at)
443
+
444
+ q = Query.from_(table).select('*').qualify(rank_expr == 1)
445
+
446
+ .. code-block:: sql
447
+
448
+ SELECT * FROM "events" QUALIFY RANK() OVER(PARTITION BY "user_id" ORDER BY "created_at")=1
449
+
450
+ GROUP BY Modifiers
451
+ """"""""""""""""""
452
+
453
+ The ``ROLLUP`` modifier allows for aggregating to higher levels than the given groups, called super-aggregates.
454
+
455
+ .. code-block:: python
456
+
457
+ from pypika import Query, Table, Rollup, functions as fn
458
+
459
+ products = Table('products')
460
+ q = Query.from_(products).select(
461
+ products.id, products.category, fn.Sum(products.price)
462
+ ).rollup(products.id, products.category)
463
+
464
+ .. code-block:: sql
465
+
466
+ SELECT "id","category",SUM("price") FROM "products" GROUP BY ROLLUP("id","category")
467
+
468
+
469
+ Joining Tables and Subqueries
470
+ """""""""""""""""""""""""""""
471
+
472
+ Tables and subqueries can be joined to any query using the ``Query.join()`` method. Joins can be performed with either
473
+ a ``USING`` or ``ON`` clauses. The ``USING`` clause can be used when both tables/subqueries contain the same field and
474
+ the ``ON`` clause can be used with a criterion. To perform a join, ``...join()`` can be chained but then must be
475
+ followed immediately by ``...on(<criterion>)`` or ``...using(*field)``.
476
+
477
+
478
+ Join Types
479
+ ~~~~~~~~~~
480
+
481
+ All join types are supported by |Brand|.
482
+
483
+ .. code-block:: python
484
+
485
+ Query \
486
+ .from_(base_table)
487
+ ...
488
+ .join(join_table, JoinType.left)
489
+ ...
490
+
491
+
492
+ .. code-block:: python
493
+
494
+ Query \
495
+ .from_(base_table)
496
+ ...
497
+ .left_join(join_table) \
498
+ .left_outer_join(join_table) \
499
+ .right_join(join_table) \
500
+ .right_outer_join(join_table) \
501
+ .inner_join(join_table) \
502
+ .outer_join(join_table) \
503
+ .full_outer_join(join_table) \
504
+ .cross_join(join_table) \
505
+ .hash_join(join_table) \
506
+ ...
507
+
508
+ See the list of join types here ``pypika.enums.JoinTypes``
509
+
510
+ Example of a join using `ON`
511
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
512
+
513
+ .. code-block:: python
514
+
515
+ history, customers = Tables('history', 'customers')
516
+ q = Query \
517
+ .from_(history) \
518
+ .join(customers) \
519
+ .on(history.customer_id == customers.id) \
520
+ .select(history.star) \
521
+ .where(customers.id == 5)
522
+
523
+
524
+ .. code-block:: sql
525
+
526
+ SELECT "history".* FROM "history" JOIN "customers" ON "history"."customer_id"="customers"."id" WHERE "customers"."id"=5
527
+
528
+ As a shortcut, the ``Query.join().on_field()`` function is provided for joining the (first) table in the ``FROM`` clause
529
+ with the joined table when the field name(s) are the same in both tables.
530
+
531
+ Example of a join using `ON`
532
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
533
+
534
+ .. code-block:: python
535
+
536
+ history, customers = Tables('history', 'customers')
537
+ q = Query \
538
+ .from_(history) \
539
+ .join(customers) \
540
+ .on_field('customer_id', 'group') \
541
+ .select(history.star) \
542
+ .where(customers.group == 'A')
543
+
544
+
545
+ .. code-block:: sql
546
+
547
+ SELECT "history".* FROM "history" JOIN "customers" ON "history"."customer_id"="customers"."customer_id" AND "history"."group"="customers"."group" WHERE "customers"."group"='A'
548
+
549
+
550
+ Example of a join using `USING`
551
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
552
+
553
+ .. code-block:: python
554
+
555
+ history, customers = Tables('history', 'customers')
556
+ q = Query \
557
+ .from_(history) \
558
+ .join(customers) \
559
+ .using('customer_id') \
560
+ .select(history.star) \
561
+ .where(customers.id == 5)
562
+
563
+
564
+ .. code-block:: sql
565
+
566
+ SELECT "history".* FROM "history" JOIN "customers" USING "customer_id" WHERE "customers"."id"=5
567
+
568
+
569
+ Example of a correlated subquery in the `SELECT`
570
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
571
+
572
+ .. code-block:: python
573
+
574
+ history, customers = Tables('history', 'customers')
575
+ last_purchase_at = Query.from_(history).select(
576
+ history.purchase_at
577
+ ).where(history.customer_id==customers.customer_id).orderby(
578
+ history.purchase_at, order=Order.desc
579
+ ).limit(1)
580
+ q = Query.from_(customers).select(
581
+ customers.id, last_purchase_at.as_('last_purchase_at')
582
+ )
583
+
584
+
585
+ .. code-block:: sql
586
+
587
+ SELECT
588
+ "id",
589
+ (SELECT "history"."purchase_at"
590
+ FROM "history"
591
+ WHERE "history"."customer_id" = "customers"."customer_id"
592
+ ORDER BY "history"."purchase_at" DESC
593
+ LIMIT 1) "last_purchase_at"
594
+ FROM "customers"
595
+
596
+
597
+ Unions
598
+ """"""
599
+
600
+ Both ``UNION`` and ``UNION ALL`` are supported. ``UNION DISTINCT`` is synonymous with ``UNION`` so |Brand| does not
601
+ provide a separate function for it. Unions require that queries have the same number of ``SELECT`` clauses so
602
+ trying to cast a unioned query to string will throw a ``SetOperationException`` if the column sizes are mismatched.
603
+
604
+ To create a union query, use either the ``Query.union()`` method or `+` operator with two query instances. For a
605
+ union all, use ``Query.union_all()`` or the `*` operator.
606
+
607
+ .. code-block:: python
608
+
609
+ provider_a, provider_b = Tables('provider_a', 'provider_b')
610
+ q = Query.from_(provider_a).select(
611
+ provider_a.created_time, provider_a.foo, provider_a.bar
612
+ ) + Query.from_(provider_b).select(
613
+ provider_b.created_time, provider_b.fiz, provider_b.buz
614
+ )
615
+
616
+ .. code-block:: sql
617
+
618
+ SELECT "created_time","foo","bar" FROM "provider_a" UNION SELECT "created_time","fiz","buz" FROM "provider_b"
619
+
620
+ Intersect
621
+ """""""""
622
+
623
+ ``INTERSECT`` is supported. Intersects require that queries have the same number of ``SELECT`` clauses so
624
+ trying to cast a intersected query to string will throw a ``SetOperationException`` if the column sizes are mismatched.
625
+
626
+ To create a intersect query, use the ``Query.intersect()`` method.
627
+
628
+ .. code-block:: python
629
+
630
+ provider_a, provider_b = Tables('provider_a', 'provider_b')
631
+ q = Query.from_(provider_a).select(
632
+ provider_a.created_time, provider_a.foo, provider_a.bar
633
+ )
634
+ r = Query.from_(provider_b).select(
635
+ provider_b.created_time, provider_b.fiz, provider_b.buz
636
+ )
637
+ intersected_query = q.intersect(r)
638
+
639
+ .. code-block:: sql
640
+
641
+ SELECT "created_time","foo","bar" FROM "provider_a" INTERSECT SELECT "created_time","fiz","buz" FROM "provider_b"
642
+
643
+ Minus
644
+ """""
645
+
646
+ ``MINUS`` is supported. Minus require that queries have the same number of ``SELECT`` clauses so
647
+ trying to cast a minus query to string will throw a ``SetOperationException`` if the column sizes are mismatched.
648
+
649
+ To create a minus query, use either the ``Query.minus()`` method or `-` operator with two query instances.
650
+
651
+ .. code-block:: python
652
+
653
+ provider_a, provider_b = Tables('provider_a', 'provider_b')
654
+ q = Query.from_(provider_a).select(
655
+ provider_a.created_time, provider_a.foo, provider_a.bar
656
+ )
657
+ r = Query.from_(provider_b).select(
658
+ provider_b.created_time, provider_b.fiz, provider_b.buz
659
+ )
660
+ minus_query = q.minus(r)
661
+
662
+ (or)
663
+
664
+ minus_query = Query.from_(provider_a).select(
665
+ provider_a.created_time, provider_a.foo, provider_a.bar
666
+ ) - Query.from_(provider_b).select(
667
+ provider_b.created_time, provider_b.fiz, provider_b.buz
668
+ )
669
+
670
+ .. code-block:: sql
671
+
672
+ SELECT "created_time","foo","bar" FROM "provider_a" MINUS SELECT "created_time","fiz","buz" FROM "provider_b"
673
+
674
+ EXCEPT
675
+ """"""
676
+
677
+ ``EXCEPT`` is supported. Minus require that queries have the same number of ``SELECT`` clauses so
678
+ trying to cast a except query to string will throw a ``SetOperationException`` if the column sizes are mismatched.
679
+
680
+ To create a except query, use the ``Query.except_of()`` method.
681
+
682
+ .. code-block:: python
683
+
684
+ provider_a, provider_b = Tables('provider_a', 'provider_b')
685
+ q = Query.from_(provider_a).select(
686
+ provider_a.created_time, provider_a.foo, provider_a.bar
687
+ )
688
+ r = Query.from_(provider_b).select(
689
+ provider_b.created_time, provider_b.fiz, provider_b.buz
690
+ )
691
+ minus_query = q.except_of(r)
692
+
693
+ .. code-block:: sql
694
+
695
+ SELECT "created_time","foo","bar" FROM "provider_a" EXCEPT SELECT "created_time","fiz","buz" FROM "provider_b"
696
+
697
+ Date, Time, and Intervals
698
+ """""""""""""""""""""""""
699
+
700
+ Using ``pypika.Interval``, queries can be constructed with date arithmetic. Any combination of intervals can be
701
+ used except for weeks and quarters, which must be used separately and will ignore any other values if selected.
702
+
703
+ .. code-block:: python
704
+
705
+ from pypika import functions as fn
706
+
707
+ fruits = Tables('fruits')
708
+ q = Query.from_(fruits) \
709
+ .select(fruits.id, fruits.name) \
710
+ .where(fruits.harvest_date + Interval(months=1) < fn.Now())
711
+
712
+ .. code-block:: sql
713
+
714
+ SELECT id,name FROM fruits WHERE harvest_date+INTERVAL 1 MONTH<NOW()
715
+
716
+
717
+ Tuples
718
+ """"""
719
+
720
+ Tuples are supported through the class ``pypika.Tuple`` but also through the native python tuple wherever possible.
721
+ Tuples can be used with ``pypika.Criterion`` in **WHERE** clauses for pairwise comparisons.
722
+
723
+ .. code-block:: python
724
+
725
+ from pypika import Query, Tuple
726
+
727
+ q = Query.from_(self.table_abc) \
728
+ .select(self.table_abc.foo, self.table_abc.bar) \
729
+ .where(Tuple(self.table_abc.foo, self.table_abc.bar) == Tuple(1, 2))
730
+
731
+ .. code-block:: sql
732
+
733
+ SELECT "foo","bar" FROM "abc" WHERE ("foo","bar")=(1,2)
734
+
735
+ Using ``pypika.Tuple`` on both sides of the comparison is redundant and |Brand| supports native python tuples.
736
+
737
+ .. code-block:: python
738
+
739
+ from pypika import Query, Tuple
740
+
741
+ q = Query.from_(self.table_abc) \
742
+ .select(self.table_abc.foo, self.table_abc.bar) \
743
+ .where(Tuple(self.table_abc.foo, self.table_abc.bar) == (1, 2))
744
+
745
+ .. code-block:: sql
746
+
747
+ SELECT "foo","bar" FROM "abc" WHERE ("foo","bar")=(1,2)
748
+
749
+ Tuples can be used in **IN** clauses.
750
+
751
+ .. code-block:: python
752
+
753
+ Query.from_(self.table_abc) \
754
+ .select(self.table_abc.foo, self.table_abc.bar) \
755
+ .where(Tuple(self.table_abc.foo, self.table_abc.bar).isin([(1, 1), (2, 2), (3, 3)]))
756
+
757
+ .. code-block:: sql
758
+
759
+ SELECT "foo","bar" FROM "abc" WHERE ("foo","bar") IN ((1,1),(2,2),(3,3))
760
+
761
+
762
+ Strings Functions
763
+ """""""""""""""""
764
+
765
+ There are several string operations and function wrappers included in |Brand|. Function wrappers can be found in the
766
+ ``pypika.functions`` package. In addition, `LIKE` and `REGEX` queries are supported as well.
767
+
768
+ .. code-block:: python
769
+
770
+ from pypika import functions as fn
771
+
772
+ customers = Tables('customers')
773
+ q = Query.from_(customers).select(
774
+ customers.id,
775
+ customers.fname,
776
+ customers.lname,
777
+ ).where(
778
+ customers.lname.like('Mc%')
779
+ )
780
+
781
+ .. code-block:: sql
782
+
783
+ SELECT id,fname,lname FROM customers WHERE lname LIKE 'Mc%'
784
+
785
+ .. code-block:: python
786
+
787
+ from pypika import functions as fn
788
+
789
+ customers = Tables('customers')
790
+ q = Query.from_(customers).select(
791
+ customers.id,
792
+ customers.fname,
793
+ customers.lname,
794
+ ).where(
795
+ customers.lname.regex(r'^[abc][a-zA-Z]+&')
796
+ )
797
+
798
+ .. code-block:: sql
799
+
800
+ SELECT id,fname,lname FROM customers WHERE lname REGEX '^[abc][a-zA-Z]+&';
801
+
802
+
803
+ .. code-block:: python
804
+
805
+ from pypika import functions as fn
806
+
807
+ customers = Tables('customers')
808
+ q = Query.from_(customers).select(
809
+ customers.id,
810
+ fn.Concat(customers.fname, ' ', customers.lname).as_('full_name'),
811
+ )
812
+
813
+ .. code-block:: sql
814
+
815
+ SELECT id,CONCAT(fname, ' ', lname) full_name FROM customers
816
+
817
+
818
+ Custom Functions
819
+ """"""""""""""""
820
+
821
+ Custom Functions allows us to use any function on queries, as some functions are not covered by PyPika as default, we can appeal
822
+ to Custom functions.
823
+
824
+ .. code-block:: python
825
+
826
+ from pypika import CustomFunction
827
+
828
+ customers = Tables('customers')
829
+ DateDiff = CustomFunction('DATE_DIFF', ['interval', 'start_date', 'end_date'])
830
+
831
+ q = Query.from_(customers).select(
832
+ customers.id,
833
+ customers.fname,
834
+ customers.lname,
835
+ DateDiff('day', customers.created_date, customers.updated_date)
836
+ )
837
+
838
+ .. code-block:: sql
839
+
840
+ SELECT id,fname,lname,DATE_DIFF('day',created_date,updated_date) FROM customers
841
+
842
+ Case Statements
843
+ """""""""""""""
844
+
845
+ Case statements allow fow a number of conditions to be checked sequentially and return a value for the first condition
846
+ met or otherwise a default value. The Case object can be used to chain conditions together along with their output
847
+ using the ``when`` method and to set the default value using ``else_``.
848
+
849
+
850
+ .. code-block:: python
851
+
852
+ from pypika import Case, functions as fn
853
+
854
+ customers = Tables('customers')
855
+ q = Query.from_(customers).select(
856
+ customers.id,
857
+ Case()
858
+ .when(customers.fname == "Tom", "It was Tom")
859
+ .when(customers.fname == "John", "It was John")
860
+ .else_("It was someone else.").as_('who_was_it')
861
+ )
862
+
863
+
864
+ .. code-block:: sql
865
+
866
+ SELECT "id",CASE WHEN "fname"='Tom' THEN 'It was Tom' WHEN "fname"='John' THEN 'It was John' ELSE 'It was someone else.' END "who_was_it" FROM "customers"
867
+
868
+
869
+ Pseudo Columns
870
+ """"""""""""""
871
+
872
+ A pseudo-column is an SQL assigned value (pseudo-field) used in the same context as a column, but not stored on disk.
873
+ The pseudo-column can change from database to database, so here it's possible to define them.
874
+
875
+ .. code-block:: python
876
+
877
+ from pypika import Query
878
+ from pypika.terms import PseudoColumn
879
+
880
+ CurrentDate = PseudoColumn('current_date')
881
+ q = Query.from_('products').select(CurrentDate)
882
+
883
+ .. code-block:: sql
884
+
885
+ SELECT current_date FROM "products"
886
+
887
+
888
+ With Clause
889
+ """""""""""""""
890
+
891
+ With clause allows give a sub-query block a name, which can be referenced in several places within the main SQL query.
892
+ The SQL WITH clause is basically a drop-in replacement to the normal sub-query.
893
+
894
+ .. code-block:: python
895
+
896
+ from pypika import Table, AliasedQuery, Query
897
+
898
+ customers = Table('customers')
899
+
900
+ sub_query = (Query
901
+ .from_(customers)
902
+ .select('*'))
903
+
904
+ test_query = (Query
905
+ .with_(sub_query, "an_alias")
906
+ .from_(AliasedQuery("an_alias"))
907
+ .select('*'))
908
+
909
+ You can use as much as `.with_()` as you want.
910
+
911
+ .. code-block:: sql
912
+
913
+ WITH an_alias AS (SELECT * FROM "customers") SELECT * FROM an_alias
914
+
915
+
916
+ Inserting Data
917
+ ^^^^^^^^^^^^^^
918
+
919
+ Data can be inserted into tables either by providing the values in the query or by selecting them through another query.
920
+
921
+ By default, data can be inserted by providing values for all columns in the order that they are defined in the table.
922
+
923
+ Insert with values
924
+ """"""""""""""""""
925
+
926
+ .. code-block:: python
927
+
928
+ customers = Table('customers')
929
+
930
+ q = Query.into(customers).insert(1, 'Jane', 'Doe', 'jane@example.com')
931
+
932
+ .. code-block:: sql
933
+
934
+ INSERT INTO customers VALUES (1,'Jane','Doe','jane@example.com')
935
+
936
+ .. code-block:: python
937
+
938
+ customers = Table('customers')
939
+
940
+ q = customers.insert(1, 'Jane', 'Doe', 'jane@example.com')
941
+
942
+ .. code-block:: sql
943
+
944
+ INSERT INTO customers VALUES (1,'Jane','Doe','jane@example.com')
945
+
946
+ Multiple rows of data can be inserted either by chaining the ``insert`` function or passing multiple tuples as args.
947
+
948
+ .. code-block:: python
949
+
950
+ customers = Table('customers')
951
+
952
+ q = Query.into(customers).insert(1, 'Jane', 'Doe', 'jane@example.com').insert(2, 'John', 'Doe', 'john@example.com')
953
+
954
+ .. code-block:: python
955
+
956
+ customers = Table('customers')
957
+
958
+ q = Query.into(customers).insert((1, 'Jane', 'Doe', 'jane@example.com'),
959
+ (2, 'John', 'Doe', 'john@example.com'))
960
+
961
+ Insert with constraint violation handling
962
+ """""""""""""""""""""""""""""""""""""""""
963
+
964
+ MySQL
965
+ ~~~~~
966
+
967
+ .. code-block:: python
968
+
969
+ customers = Table('customers')
970
+
971
+ q = MySQLQuery.into(customers) \
972
+ .insert(1, 'Jane', 'Doe', 'jane@example.com') \
973
+ .on_duplicate_key_ignore())
974
+
975
+ .. code-block:: sql
976
+
977
+ INSERT INTO `customers` VALUES (1,'Jane','Doe','jane@example.com') ON DUPLICATE KEY IGNORE
978
+
979
+ .. code-block:: python
980
+
981
+ customers = Table('customers')
982
+
983
+ q = MySQLQuery.into(customers) \
984
+ .insert(1, 'Jane', 'Doe', 'jane@example.com') \
985
+ .on_duplicate_key_update(customers.email, Values(customers.email))
986
+
987
+ .. code-block:: sql
988
+
989
+ INSERT INTO `customers` VALUES (1,'Jane','Doe','jane@example.com') ON DUPLICATE KEY UPDATE `email`=VALUES(`email`)
990
+
991
+ ``.on_duplicate_key_update`` works similar to ``.set`` for updating rows, additionally it provides the ``Values``
992
+ wrapper to update to the value specified in the ``INSERT`` clause.
993
+
994
+ PostgreSQL
995
+ ~~~~~~~~~~
996
+
997
+ .. code-block:: python
998
+
999
+ customers = Table('customers')
1000
+
1001
+ q = PostgreSQLQuery.into(customers) \
1002
+ .insert(1, 'Jane', 'Doe', 'jane@example.com') \
1003
+ .on_conflict(customers.email) \
1004
+ .do_nothing()
1005
+
1006
+ .. code-block:: sql
1007
+
1008
+ INSERT INTO "customers" VALUES (1,'Jane','Doe','jane@example.com') ON CONFLICT ("email") DO NOTHING
1009
+
1010
+ .. code-block:: python
1011
+
1012
+ customers = Table('customers')
1013
+
1014
+ q = PostgreSQLQuery.into(customers) \
1015
+ .insert(1, 'Jane', 'Doe', 'jane@example.com') \
1016
+ .on_conflict(customers.email) \
1017
+ .do_update(customers.email, 'bob@example.com')
1018
+
1019
+ .. code-block:: sql
1020
+
1021
+ INSERT INTO "customers" VALUES (1,'Jane','Doe','jane@example.com') ON CONFLICT ("email") DO UPDATE SET "email"='bob@example.com'
1022
+
1023
+
1024
+ Insert from a SELECT Sub-query
1025
+ """"""""""""""""""""""""""""""
1026
+
1027
+ .. code-block:: sql
1028
+
1029
+ INSERT INTO "customers" VALUES (1,'Jane','Doe','jane@example.com'),(2,'John','Doe','john@example.com')
1030
+
1031
+
1032
+ To specify the columns and the order, use the ``columns`` function.
1033
+
1034
+ .. code-block:: python
1035
+
1036
+ customers = Table('customers')
1037
+
1038
+ q = Query.into(customers).columns('id', 'fname', 'lname').insert(1, 'Jane', 'Doe')
1039
+
1040
+ .. code-block:: sql
1041
+
1042
+ INSERT INTO customers (id,fname,lname) VALUES (1,'Jane','Doe','jane@example.com')
1043
+
1044
+
1045
+ Inserting data with a query works the same as querying data with the additional call to the ``into`` method in the
1046
+ builder chain.
1047
+
1048
+ .. code-block:: python
1049
+
1050
+ customers, customers_backup = Tables('customers', 'customers_backup')
1051
+
1052
+ q = Query.into(customers_backup).from_(customers).select('*')
1053
+
1054
+ .. code-block:: sql
1055
+
1056
+ INSERT INTO customers_backup SELECT * FROM customers
1057
+
1058
+ .. code-block:: python
1059
+
1060
+ customers, customers_backup = Tables('customers', 'customers_backup')
1061
+
1062
+ q = Query.into(customers_backup).columns('id', 'fname', 'lname')
1063
+ .from_(customers).select(customers.id, customers.fname, customers.lname)
1064
+
1065
+ .. code-block:: sql
1066
+
1067
+ INSERT INTO customers_backup SELECT "id", "fname", "lname" FROM customers
1068
+
1069
+ The syntax for joining tables is the same as when selecting data
1070
+
1071
+ .. code-block:: python
1072
+
1073
+ customers, orders, orders_backup = Tables('customers', 'orders', 'orders_backup')
1074
+
1075
+ q = Query.into(orders_backup).columns('id', 'address', 'customer_fname', 'customer_lname')
1076
+ .from_(customers)
1077
+ .join(orders).on(orders.customer_id == customers.id)
1078
+ .select(orders.id, customers.fname, customers.lname)
1079
+
1080
+ .. code-block:: sql
1081
+
1082
+ INSERT INTO "orders_backup" ("id","address","customer_fname","customer_lname")
1083
+ SELECT "orders"."id","customers"."fname","customers"."lname" FROM "customers"
1084
+ JOIN "orders" ON "orders"."customer_id"="customers"."id"
1085
+
1086
+ Updating Data
1087
+ ^^^^^^^^^^^^^^
1088
+ PyPika allows update queries to be constructed with or without where clauses.
1089
+
1090
+ .. code-block:: python
1091
+
1092
+ customers = Table('customers')
1093
+
1094
+ Query.update(customers).set(customers.last_login, '2017-01-01 10:00:00')
1095
+
1096
+ Query.update(customers).set(customers.lname, 'smith').where(customers.id == 10)
1097
+
1098
+ .. code-block:: sql
1099
+
1100
+ UPDATE "customers" SET "last_login"='2017-01-01 10:00:00'
1101
+
1102
+ UPDATE "customers" SET "lname"='smith' WHERE "id"=10
1103
+
1104
+ The syntax for joining tables is the same as when selecting data
1105
+
1106
+ .. code-block:: python
1107
+
1108
+ customers, profiles = Tables('customers', 'profiles')
1109
+
1110
+ Query.update(customers)
1111
+ .join(profiles).on(profiles.customer_id == customers.id)
1112
+ .set(customers.lname, profiles.lname)
1113
+
1114
+ .. code-block:: sql
1115
+
1116
+ UPDATE "customers"
1117
+ JOIN "profiles" ON "profiles"."customer_id"="customers"."id"
1118
+ SET "customers"."lname"="profiles"."lname"
1119
+
1120
+ Using ``pypika.Table`` alias to perform the update
1121
+
1122
+ .. code-block:: python
1123
+
1124
+ customers = Table('customers')
1125
+
1126
+ customers.update()
1127
+ .set(customers.lname, 'smith')
1128
+ .where(customers.id == 10)
1129
+
1130
+ .. code-block:: sql
1131
+
1132
+ UPDATE "customers" SET "lname"='smith' WHERE "id"=10
1133
+
1134
+ Using ``limit`` for performing update
1135
+
1136
+ .. code-block:: python
1137
+
1138
+ customers = Table('customers')
1139
+
1140
+ customers.update()
1141
+ .set(customers.lname, 'smith')
1142
+ .limit(2)
1143
+
1144
+ .. code-block:: sql
1145
+
1146
+ UPDATE "customers" SET "lname"='smith' LIMIT 2
1147
+
1148
+ .. _advanced_start:
1149
+
1150
+ Analytic Queries
1151
+ ^^^^^^^^^^^^^^^^
1152
+
1153
+ The ``pypika.analytics`` module contains analytic/window function wrappers. These can be used in ``SELECT`` clauses
1154
+ when building queries for databases that support them.
1155
+
1156
+ NTILE and RANK
1157
+ """"""""""""""
1158
+
1159
+ The ``NTILE`` function requires a constant integer argument while the ``RANK`` function takes no arguments.
1160
+
1161
+ .. code-block:: python
1162
+
1163
+ from pypika import Query, Table, analytics as an, functions as fn
1164
+
1165
+ sales = Table('sales')
1166
+ q = Query.from_(sales).select(
1167
+ sales.region,
1168
+ fn.Sum(sales.amount).as_('total'),
1169
+ an.NTile(4).over(sales.region).orderby(fn.Sum(sales.amount)).as_('quartile')
1170
+ ).groupby(sales.region)
1171
+
1172
+ FIRST_VALUE and LAST_VALUE
1173
+ """"""""""""""""""""""""""
1174
+
1175
+ ``FIRST_VALUE`` and ``LAST_VALUE`` both expect a single argument. They also support an additional ``IGNORE NULLS`` clause.
1176
+
1177
+ .. code-block:: python
1178
+
1179
+ from pypika import Query, Table, analytics as an
1180
+
1181
+ t = Table('monthly_data')
1182
+ first_val = an.FirstValue(t.value).over(t.category).orderby(t.month)
1183
+ last_val = an.LastValue(t.value).over(t.category).orderby(t.month).ignore_nulls()
1184
+
1185
+ q = Query.from_(t).select(first_val, last_val)
1186
+
1187
+ .. code-block:: sql
1188
+
1189
+ SELECT FIRST_VALUE("value") OVER(PARTITION BY "category" ORDER BY "month"),LAST_VALUE("value" IGNORE NULLS) OVER(PARTITION BY "category" ORDER BY "month") FROM "monthly_data"
1190
+
1191
+ MEDIAN, AVG and STDDEV
1192
+ """"""""""""""""""""""
1193
+
1194
+ These analytic functions take one or more arguments with window partitioning.
1195
+
1196
+ .. code-block:: python
1197
+
1198
+ from pypika import Query, Table, analytics as an
1199
+
1200
+ customers = Table('customers')
1201
+ median_income = an.Median(customers.income).over(customers.state).as_('median')
1202
+ avg_income = an.Avg(customers.income).over(customers.state).as_('avg')
1203
+
1204
+ q = Query.from_(customers).select(median_income, avg_income)
1205
+
1206
+ Window Frames
1207
+ """""""""""""
1208
+
1209
+ Functions which use window aggregation expose the ``rows()`` and ``range()`` methods to define the window frame.
1210
+ Boundaries can be set using ``an.CURRENT_ROW``, ``an.Preceding(n)``, or ``an.Following(n)``.
1211
+ Unbounded ranges use ``an.Preceding()`` or ``an.Following()`` without arguments.
1212
+
1213
+ .. code-block:: python
1214
+
1215
+ from pypika import Query, Table, analytics as an
1216
+
1217
+ t = Table('transactions')
1218
+ rolling_sum = an.Sum(t.amount).over(t.account_id).orderby(t.date).rows(an.Preceding(7), an.CURRENT_ROW)
1219
+
1220
+ q = Query.from_(t).select(t.date, t.amount, rolling_sum.as_('rolling_7_day'))
1221
+
1222
+ .. code-block:: sql
1223
+
1224
+ SELECT "date","amount",SUM("amount") OVER(PARTITION BY "account_id" ORDER BY "date" ROWS BETWEEN 7 PRECEDING AND CURRENT ROW) "rolling_7_day" FROM "transactions"
1225
+
1226
+
1227
+ Parametrized Queries
1228
+ ^^^^^^^^^^^^^^^^^^^^
1229
+
1230
+ PyPika allows you to use ``Parameter(str)`` term as a placeholder for parametrized queries.
1231
+
1232
+ .. code-block:: python
1233
+
1234
+ customers = Table('customers')
1235
+
1236
+ q = Query.into(customers).columns('id', 'fname', 'lname')
1237
+ .insert(Parameter(':1'), Parameter(':2'), Parameter(':3'))
1238
+
1239
+ .. code-block:: sql
1240
+
1241
+ INSERT INTO customers (id,fname,lname) VALUES (:1,:2,:3)
1242
+
1243
+ This allows you to build prepared statements, and/or avoid SQL-injection related risks.
1244
+
1245
+ Due to the mix of syntax for parameters, depending on connector/driver, it is required that you specify the
1246
+ parameter token explicitly or use one of the specialized Parameter types per [PEP-0249](https://www.python.org/dev/peps/pep-0249/#paramstyle):
1247
+ ``QmarkParameter()``, ``NumericParameter(int)``, ``NamedParameter(str)``, ``FormatParameter()``, ``PyformatParameter(str)``
1248
+
1249
+ An example of some common SQL parameter styles used in Python drivers are:
1250
+
1251
+ PostgreSQL:
1252
+ ``$number`` OR ``%s`` + ``:name`` (depending on driver)
1253
+ MySQL:
1254
+ ``%s``
1255
+ SQLite:
1256
+ ``?``
1257
+ Vertica:
1258
+ ``:name``
1259
+ Oracle:
1260
+ ``:number`` + ``:name``
1261
+ MSSQL:
1262
+ ``%(name)s`` OR ``:name`` + ``:number`` (depending on driver)
1263
+
1264
+ You can find out what parameter style is needed for DBAPI compliant drivers here: https://www.python.org/dev/peps/pep-0249/#paramstyle or in the DB driver documentation.
1265
+
1266
+ Extracting Parameter Values
1267
+ """""""""""""""""""""""""""
1268
+
1269
+ When building parameterized queries, you can pass a parameter object to ``get_sql()`` to automatically collect
1270
+ parameter values. This is useful for executing queries with database drivers that require separate parameter lists.
1271
+
1272
+ .. code-block:: python
1273
+
1274
+ from pypika import Query, Table, QmarkParameter
1275
+
1276
+ customers = Table('customers')
1277
+ q = Query.from_(customers).select('*').where(
1278
+ (customers.status == 'active') & (customers.age >= 18)
1279
+ )
1280
+
1281
+ parameter = QmarkParameter()
1282
+ sql = q.get_sql(parameter=parameter)
1283
+ params = parameter.get_parameters()
1284
+
1285
+ # sql: SELECT * FROM "customers" WHERE "status"=? AND "age">=?
1286
+ # params: ['active', 18]
1287
+
1288
+ This works with all parameter types. For dict-based parameters like ``NamedParameter``:
1289
+
1290
+ .. code-block:: python
1291
+
1292
+ from pypika import Query, Table, NamedParameter
1293
+
1294
+ customers = Table('customers')
1295
+ q = Query.from_(customers).select('*').where(customers.status == 'active')
1296
+
1297
+ parameter = NamedParameter()
1298
+ sql = q.get_sql(parameter=parameter)
1299
+ params = parameter.get_parameters()
1300
+
1301
+ # sql: SELECT * FROM "customers" WHERE "status"=:param1
1302
+ # params: {'param1': 'active'}
1303
+
1304
+ Temporal support
1305
+ ^^^^^^^^^^^^^^^^
1306
+
1307
+ Temporal criteria can be added to the tables.
1308
+
1309
+ Select
1310
+ """"""
1311
+
1312
+ Here is a select using system time.
1313
+
1314
+ .. code-block:: python
1315
+
1316
+ t = Table("abc")
1317
+ q = Query.from_(t.for_(SYSTEM_TIME.as_of('2020-01-01'))).select("*")
1318
+
1319
+ This produces:
1320
+
1321
+ .. code-block:: sql
1322
+
1323
+ SELECT * FROM "abc" FOR SYSTEM_TIME AS OF '2020-01-01'
1324
+
1325
+ You can also use between.
1326
+
1327
+ .. code-block:: python
1328
+
1329
+ t = Table("abc")
1330
+ q = Query.from_(
1331
+ t.for_(SYSTEM_TIME.between('2020-01-01', '2020-02-01'))
1332
+ ).select("*")
1333
+
1334
+ This produces:
1335
+
1336
+ .. code-block:: sql
1337
+
1338
+ SELECT * FROM "abc" FOR SYSTEM_TIME BETWEEN '2020-01-01' AND '2020-02-01'
1339
+
1340
+ You can also use a period range.
1341
+
1342
+ .. code-block:: python
1343
+
1344
+ t = Table("abc")
1345
+ q = Query.from_(
1346
+ t.for_(SYSTEM_TIME.from_to('2020-01-01', '2020-02-01'))
1347
+ ).select("*")
1348
+
1349
+ This produces:
1350
+
1351
+ .. code-block:: sql
1352
+
1353
+ SELECT * FROM "abc" FOR SYSTEM_TIME FROM '2020-01-01' TO '2020-02-01'
1354
+
1355
+ Finally you can select for all times:
1356
+
1357
+ .. code-block:: python
1358
+
1359
+ t = Table("abc")
1360
+ q = Query.from_(t.for_(SYSTEM_TIME.all_())).select("*")
1361
+
1362
+ This produces:
1363
+
1364
+ .. code-block:: sql
1365
+
1366
+ SELECT * FROM "abc" FOR SYSTEM_TIME ALL
1367
+
1368
+ A user defined period can also be used in the following manner.
1369
+
1370
+ .. code-block:: python
1371
+
1372
+ t = Table("abc")
1373
+ q = Query.from_(
1374
+ t.for_(t.valid_period.between('2020-01-01', '2020-02-01'))
1375
+ ).select("*")
1376
+
1377
+ This produces:
1378
+
1379
+ .. code-block:: sql
1380
+
1381
+ SELECT * FROM "abc" FOR "valid_period" BETWEEN '2020-01-01' AND '2020-02-01'
1382
+
1383
+ Joins
1384
+ """""
1385
+
1386
+ With joins, when the table object is used when specifying columns, it is
1387
+ important to use the table from which the temporal constraint was generated.
1388
+ This is because `Table("abc")` is not the same table as `Table("abc").for_(...)`.
1389
+ The following example demonstrates this.
1390
+
1391
+ .. code-block:: python
1392
+
1393
+ t0 = Table("abc").for_(SYSTEM_TIME.as_of('2020-01-01'))
1394
+ t1 = Table("efg").for_(SYSTEM_TIME.as_of('2020-01-01'))
1395
+ query = (
1396
+ Query.from_(t0)
1397
+ .join(t1)
1398
+ .on(t0.foo == t1.bar)
1399
+ .select("*")
1400
+ )
1401
+
1402
+ This produces:
1403
+
1404
+ .. code-block:: sql
1405
+
1406
+ SELECT * FROM "abc" FOR SYSTEM_TIME AS OF '2020-01-01'
1407
+ JOIN "efg" FOR SYSTEM_TIME AS OF '2020-01-01'
1408
+ ON "abc"."foo"="efg"."bar"
1409
+
1410
+ Update & Deletes
1411
+ """"""""""""""""
1412
+
1413
+ An update can be written as follows:
1414
+
1415
+ .. code-block:: python
1416
+
1417
+ t = Table("abc")
1418
+ q = Query.update(
1419
+ t.for_portion(
1420
+ SYSTEM_TIME.from_to('2020-01-01', '2020-02-01')
1421
+ )
1422
+ ).set("foo", "bar")
1423
+
1424
+ This produces:
1425
+
1426
+ .. code-block:: sql
1427
+
1428
+ UPDATE "abc"
1429
+ FOR PORTION OF SYSTEM_TIME FROM '2020-01-01' TO '2020-02-01'
1430
+ SET "foo"='bar'
1431
+
1432
+ Here is a delete:
1433
+
1434
+ .. code-block:: python
1435
+
1436
+ t = Table("abc")
1437
+ q = Query.from_(
1438
+ t.for_portion(t.valid_period.from_to('2020-01-01', '2020-02-01'))
1439
+ ).delete()
1440
+
1441
+ This produces:
1442
+
1443
+ .. code-block:: sql
1444
+
1445
+ DELETE FROM "abc"
1446
+ FOR PORTION OF "valid_period" FROM '2020-01-01' TO '2020-02-01'
1447
+
1448
+ Creating Tables
1449
+ ^^^^^^^^^^^^^^^
1450
+
1451
+ The entry point for creating tables is ``pypika.Query.create_table``, which is used with the class ``pypika.Column``.
1452
+ As with selecting data, first the table should be specified. This can be either a
1453
+ string or a `pypika.Table`. Then the columns, and constraints. Here's an example
1454
+ that demonstrates much of the functionality.
1455
+
1456
+ .. code-block:: python
1457
+
1458
+ stmt = Query \
1459
+ .create_table("person") \
1460
+ .columns(
1461
+ Column("id", "INT", nullable=False),
1462
+ Column("first_name", "VARCHAR(100)", nullable=False),
1463
+ Column("last_name", "VARCHAR(100)", nullable=False),
1464
+ Column("phone_number", "VARCHAR(20)", nullable=True),
1465
+ Column("status", "VARCHAR(20)", nullable=False, default=ValueWrapper("NEW")),
1466
+ Column("date_of_birth", "DATETIME")) \
1467
+ .unique("last_name", "first_name") \
1468
+ .primary_key("id")
1469
+
1470
+ This produces:
1471
+
1472
+ .. code-block:: sql
1473
+
1474
+ CREATE TABLE "person" (
1475
+ "id" INT NOT NULL,
1476
+ "first_name" VARCHAR(100) NOT NULL,
1477
+ "last_name" VARCHAR(100) NOT NULL,
1478
+ "phone_number" VARCHAR(20) NULL,
1479
+ "status" VARCHAR(20) NOT NULL DEFAULT 'NEW',
1480
+ "date_of_birth" DATETIME,
1481
+ UNIQUE ("last_name","first_name"),
1482
+ PRIMARY KEY ("id")
1483
+ )
1484
+
1485
+ There is also support for creating a table from a query.
1486
+
1487
+ .. code-block:: python
1488
+
1489
+ stmt = Query.create_table("names").as_select(
1490
+ Query.from_("person").select("last_name", "first_name")
1491
+ )
1492
+
1493
+ This produces:
1494
+
1495
+ .. code-block:: sql
1496
+
1497
+ CREATE TABLE "names" AS (SELECT "last_name","first_name" FROM "person")
1498
+
1499
+ TEMPORARY and UNLOGGED tables can also be created:
1500
+
1501
+ .. code-block:: python
1502
+
1503
+ from pypika import Query, Table, Columns
1504
+
1505
+ columns = Columns(('id', 'INT'), ('name', 'VARCHAR(100)'))
1506
+
1507
+ Query.create_table('temp_items').columns(*columns).temporary()
1508
+ Query.create_table('fast_items').columns(*columns).unlogged()
1509
+
1510
+ .. code-block:: sql
1511
+
1512
+ CREATE TEMPORARY TABLE "temp_items" ("id" INT,"name" VARCHAR(100))
1513
+
1514
+ CREATE UNLOGGED TABLE "fast_items" ("id" INT,"name" VARCHAR(100))
1515
+
1516
+ Managing Table Indices
1517
+ ^^^^^^^^^^^^^^^^^^^^^^
1518
+
1519
+ Create Indices
1520
+ """"""""""""""""
1521
+
1522
+ The entry point for creating indices is ``pypika.Query.create_index``.
1523
+ An index name (as ``str``) or a ``pypika.terms.Index`` a table (as ``str`` or ``pypika.Table``) and
1524
+ columns (as ``pypika.Column``) must be specified.
1525
+
1526
+ .. code-block:: python
1527
+
1528
+ my_index = Index("my_index")
1529
+ person = Table("person")
1530
+ stmt = Query \
1531
+ .create_index(my_index) \
1532
+ .on(person) \
1533
+ .columns(person.first_name, person.last_name)
1534
+
1535
+ This produces:
1536
+
1537
+ .. code-block:: sql
1538
+
1539
+ CREATE INDEX my_index
1540
+ ON person (first_name, last_name)
1541
+
1542
+ It is also possible to create a unique index
1543
+
1544
+ .. code-block:: python
1545
+
1546
+ my_index = Index("my_index")
1547
+ person = Table("person")
1548
+ stmt = Query \
1549
+ .create_index(my_index) \
1550
+ .on(person) \
1551
+ .columns(person.first_name, person.last_name) \
1552
+ .unique()
1553
+
1554
+ This produces:
1555
+
1556
+ .. code-block:: sql
1557
+
1558
+ CREATE UNIQUE INDEX my_index
1559
+ ON person (first_name, last_name)
1560
+
1561
+ It is also possible to create an index if it does not exist
1562
+
1563
+ .. code-block:: python
1564
+
1565
+ my_index = Index("my_index")
1566
+ person = Table("person")
1567
+ stmt = Query \
1568
+ .create_index(my_index) \
1569
+ .on(person) \
1570
+ .columns(person.first_name, person.last_name) \
1571
+ .if_not_exists()
1572
+
1573
+ This produces:
1574
+
1575
+ .. code-block:: sql
1576
+
1577
+ CREATE INDEX IF NOT EXISTS my_index
1578
+ ON person (first_name, last_name)
1579
+
1580
+ Drop Indices
1581
+ """"""""""""""""
1582
+
1583
+ Then entry point for dropping indices is ``pypika.Query.drop_index``.
1584
+ It takes either ``str`` or ``pypika.terms.Index`` as an argument.
1585
+
1586
+ .. code-block:: python
1587
+
1588
+ my_index = Index("my_index")
1589
+ stmt = Query.drop_index(my_index)
1590
+
1591
+ This produces:
1592
+
1593
+ .. code-block:: sql
1594
+
1595
+ DROP INDEX my_index
1596
+
1597
+ It is also possible to drop an index if it exists
1598
+
1599
+ .. code-block:: python
1600
+
1601
+ my_index = Index("my_index")
1602
+ stmt = Query.drop_index(my_index).if_exists()
1603
+
1604
+ This produces:
1605
+
1606
+ .. code-block:: sql
1607
+
1608
+ DROP INDEX IF EXISTS my_index
1609
+
1610
+
1611
+ Handling Different Database Platforms
1612
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1613
+
1614
+ There can sometimes be differences between how database vendors implement SQL in their platform, for example
1615
+ which quote characters are used. To ensure that the correct SQL standard is used for your platform,
1616
+ the platform-specific Query classes can be used.
1617
+
1618
+ .. code-block:: python
1619
+
1620
+ from pypika import MySQLQuery, MSSQLQuery, PostgreSQLQuery, OracleQuery, VerticaQuery, ClickHouseQuery
1621
+
1622
+ You can use these query classes as a drop in replacement for the default ``Query`` class shown in the other examples.
1623
+
1624
+
1625
+ ClickHouse-Specific Features
1626
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1627
+
1628
+ |Brand| provides several ClickHouse-specific query features through the ``ClickHouseQuery`` class.
1629
+
1630
+ FINAL
1631
+ """""
1632
+
1633
+ The ``FINAL`` modifier forces ClickHouse to fully merge data before returning results, useful with
1634
+ ReplacingMergeTree and CollapsingMergeTree tables.
1635
+
1636
+ .. code-block:: python
1637
+
1638
+ from pypika import ClickHouseQuery, Table
1639
+
1640
+ t = Table('events')
1641
+ q = ClickHouseQuery.from_(t).select(t.user_id, t.event).final()
1642
+
1643
+ .. code-block:: sql
1644
+
1645
+ SELECT "user_id","event" FROM "events" FINAL
1646
+
1647
+ SAMPLE
1648
+ """"""
1649
+
1650
+ The ``SAMPLE`` clause enables approximate query processing on a fraction of data.
1651
+
1652
+ .. code-block:: python
1653
+
1654
+ from pypika import ClickHouseQuery, Table
1655
+
1656
+ t = Table('events')
1657
+ q = ClickHouseQuery.from_(t).select(t.user_id).sample(10)
1658
+
1659
+ .. code-block:: sql
1660
+
1661
+ SELECT "user_id" FROM "events" SAMPLE 10
1662
+
1663
+ You can also specify an offset:
1664
+
1665
+ .. code-block:: python
1666
+
1667
+ q = ClickHouseQuery.from_(t).select(t.user_id).sample(10, 5)
1668
+
1669
+ .. code-block:: sql
1670
+
1671
+ SELECT "user_id" FROM "events" SAMPLE 10 OFFSET 5
1672
+
1673
+ DISTINCT ON
1674
+ """""""""""
1675
+
1676
+ ClickHouse supports ``DISTINCT ON`` to return distinct rows based on specific columns.
1677
+
1678
+ .. code-block:: python
1679
+
1680
+ from pypika import ClickHouseQuery, Table
1681
+
1682
+ t = Table('users')
1683
+ q = ClickHouseQuery.from_(t).distinct_on('department', t.role).select('name', 'department', 'role')
1684
+
1685
+ .. code-block:: sql
1686
+
1687
+ SELECT DISTINCT ON("department","role") "name","department","role" FROM "users"
1688
+
1689
+ LIMIT BY
1690
+ """"""""
1691
+
1692
+ The ``LIMIT BY`` clause limits the number of rows per group of column values.
1693
+
1694
+ .. code-block:: python
1695
+
1696
+ from pypika import ClickHouseQuery, Table
1697
+
1698
+ t = Table('events')
1699
+ q = ClickHouseQuery.from_(t).select('user_id', 'event', 'timestamp').limit_by(3, 'user_id')
1700
+
1701
+ .. code-block:: sql
1702
+
1703
+ SELECT "user_id","event","timestamp" FROM "events" LIMIT 3 BY ("user_id")
1704
+
1705
+ You can also specify an offset with ``limit_offset_by``:
1706
+
1707
+ .. code-block:: python
1708
+
1709
+ q = ClickHouseQuery.from_(t).select('user_id', 'event').limit_offset_by(3, 1, 'user_id')
1710
+
1711
+ .. code-block:: sql
1712
+
1713
+ SELECT "user_id","event" FROM "events" LIMIT 3 OFFSET 1 BY ("user_id")
1714
+
1715
+
1716
+ Oracle-Specific Features
1717
+ ^^^^^^^^^^^^^^^^^^^^^^^^
1718
+
1719
+ LIMIT and OFFSET
1720
+ """"""""""""""""
1721
+
1722
+ Oracle queries support ``LIMIT`` and ``OFFSET`` using the ``FETCH NEXT ... ROWS ONLY`` and ``OFFSET ... ROWS`` syntax.
1723
+
1724
+ .. code-block:: python
1725
+
1726
+ from pypika import OracleQuery, Table
1727
+
1728
+ t = Table('employees')
1729
+ q = OracleQuery.from_(t).select(t.name).limit(10)
1730
+
1731
+ .. code-block:: sql
1732
+
1733
+ SELECT name FROM employees FETCH NEXT 10 ROWS ONLY
1734
+
1735
+ With offset:
1736
+
1737
+ .. code-block:: python
1738
+
1739
+ q = OracleQuery.from_(t).select(t.name).limit(10).offset(20)
1740
+
1741
+ .. code-block:: sql
1742
+
1743
+ SELECT name FROM employees OFFSET 20 ROWS FETCH NEXT 10 ROWS ONLY
1744
+
1745
+
1746
+ Jira Query Language (JQL)
1747
+ ^^^^^^^^^^^^^^^^^^^^^^^^^
1748
+
1749
+ |Brand| supports generating Jira Query Language expressions through the ``JiraQuery`` class.
1750
+
1751
+ .. code-block:: python
1752
+
1753
+ from pypika import JiraQuery
1754
+
1755
+ J = JiraQuery.Table()
1756
+ query = (
1757
+ JiraQuery.where(J.project.isin(["PROJ1", "PROJ2"]))
1758
+ .where(J.issuetype == "Bug")
1759
+ .where(J.labels.isempty() | J.labels.notin(["stale", "wontfix"]))
1760
+ )
1761
+
1762
+ .. code-block:: sql
1763
+
1764
+ project IN ("PROJ1","PROJ2") AND issuetype="Bug" AND (labels is EMPTY OR labels NOT IN ("stale","wontfix"))
1765
+
1766
+ JQL fields support ``isempty()`` and ``notempty()`` methods for checking empty/non-empty values.
1767
+
1768
+ .. _advanced_end:
1769
+
1770
+ Chaining Functions
1771
+ ^^^^^^^^^^^^^^^^^^
1772
+
1773
+ The ``QueryBuilder.pipe`` method gives a more readable alternative while chaining functions.
1774
+
1775
+ .. code-block:: python
1776
+
1777
+ # This
1778
+ (
1779
+ query
1780
+ .pipe(func1, *args)
1781
+ .pipe(func2, **kwargs)
1782
+ .pipe(func3)
1783
+ )
1784
+
1785
+ # Is equivalent to this
1786
+ func3(func2(func1(query, *args), **kwargs))
1787
+
1788
+ Or for a more concrete example:
1789
+
1790
+ .. code-block:: python
1791
+
1792
+ from pypika import Field, Query, functions as fn
1793
+ from pypika.queries import QueryBuilder
1794
+
1795
+ def filter_days(query: QueryBuilder, col, num_days: int) -> QueryBuilder:
1796
+ if isinstance(col, str):
1797
+ col = Field(col)
1798
+
1799
+ return query.where(col > fn.Now() - num_days)
1800
+
1801
+ def count_groups(query: QueryBuilder, *groups) -> QueryBuilder:
1802
+ return query.groupby(*groups).select(*groups, fn.Count("*").as_("n_rows"))
1803
+
1804
+ base_query = Query.from_("table")
1805
+
1806
+ query = (
1807
+ base_query
1808
+ .pipe(filter_days, "date", num_days=7)
1809
+ .pipe(count_groups, "col1", "col2")
1810
+ )
1811
+
1812
+ This produces:
1813
+
1814
+ .. code-block:: sql
1815
+
1816
+ SELECT "col1","col2",COUNT(*) n_rows
1817
+ FROM "table"
1818
+ WHERE "date">NOW()-7
1819
+ GROUP BY "col1","col2"
1820
+
1821
+ .. _tutorial_end:
1822
+
1823
+ .. _contributing_start:
1824
+
1825
+ Contributing
1826
+ ------------
1827
+
1828
+ We welcome community contributions to |Brand|. Please see the `contributing guide <6_contributing.html>`_ to more info.
1829
+
1830
+ .. _contributing_end:
1831
+
1832
+
1833
+ .. _license_start:
1834
+
1835
+ License
1836
+ -------
1837
+
1838
+ Copyright 2020 KAYAK Germany, GmbH
1839
+
1840
+ Licensed under the Apache License, Version 2.0 (the "License");
1841
+ you may not use this file except in compliance with the License.
1842
+ You may obtain a copy of the License at
1843
+
1844
+ http://www.apache.org/licenses/LICENSE-2.0
1845
+
1846
+ Unless required by applicable law or agreed to in writing, software
1847
+ distributed under the License is distributed on an "AS IS" BASIS,
1848
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1849
+ See the License for the specific language governing permissions and
1850
+ limitations under the License.
1851
+
1852
+
1853
+ Crafted with ♥ in Berlin.
1854
+
1855
+ .. _license_end:
1856
+
1857
+
1858
+ .. _appendix_start:
1859
+
1860
+ .. |Brand| replace:: *PyPika*
1861
+
1862
+ .. _appendix_end:
1863
+
1864
+ .. _available_badges_start:
1865
+
1866
+ .. |BuildStatus| image:: https://github.com/kayak/pypika/workflows/Unit%20Tests/badge.svg
1867
+ :target: https://github.com/kayak/pypika/actions
1868
+ .. |CoverageStatus| image:: https://coveralls.io/repos/kayak/pypika/badge.svg?branch=master
1869
+ :target: https://coveralls.io/github/kayak/pypika?branch=master
1870
+ .. |Codacy| image:: https://api.codacy.com/project/badge/Grade/6d7e44e5628b4839a23da0bd82eaafcf
1871
+ :target: https://www.codacy.com/app/twheys/pypika
1872
+ .. |Docs| image:: https://readthedocs.org/projects/pypika/badge/?version=latest
1873
+ :target: http://pypika.readthedocs.io/en/latest/
1874
+ .. |PyPi| image:: https://img.shields.io/pypi/v/pypika.svg?style=flat
1875
+ :target: https://pypi.python.org/pypi/pypika
1876
+ .. |License| image:: https://img.shields.io/hexpm/l/plug.svg?maxAge=2592000
1877
+ :target: http://www.apache.org/licenses/LICENSE-2.0
1878
+
1879
+ .. _available_badges_end:
micromamba_root/envs/pytorch_env/Lib/site-packages/pypika-0.51.1.dist-info/RECORD ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ pypika-0.51.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
2
+ pypika-0.51.1.dist-info/METADATA,sha256=NJx9lzkGLQXvk6kgXN7ZUSAvnv0FuM1oXNzm6uUvpRg,51987
3
+ pypika-0.51.1.dist-info/RECORD,,
4
+ pypika-0.51.1.dist-info/WHEEL,sha256=Mk1ST5gDzEO5il5kYREiBnzzM469m5sI8ESPl7TRhJY,110
5
+ pypika-0.51.1.dist-info/licenses/LICENSE.txt,sha256=xazLvYVG6Uw0rtJK_miaYXYn0Y7tWmxIJ35I21fCOFE,11356
6
+ pypika-0.51.1.dist-info/top_level.txt,sha256=jxoMoGSWV0-WzJzIUK5Zfdpd04A0PQGhMsPBnAVua0s,7
7
+ pypika/__init__.py,sha256=HqDn8MztsDtVJmuxCzQuYP0LL5zmIzBfOqxYKmNgpeg,3481
8
+ pypika/__pycache__/__init__.cpython-311.pyc,,
9
+ pypika/__pycache__/analytics.cpython-311.pyc,,
10
+ pypika/__pycache__/dialects.cpython-311.pyc,,
11
+ pypika/__pycache__/enums.cpython-311.pyc,,
12
+ pypika/__pycache__/functions.cpython-311.pyc,,
13
+ pypika/__pycache__/pseudocolumns.cpython-311.pyc,,
14
+ pypika/__pycache__/queries.cpython-311.pyc,,
15
+ pypika/__pycache__/terms.cpython-311.pyc,,
16
+ pypika/__pycache__/utils.cpython-311.pyc,,
17
+ pypika/analytics.py,sha256=443DbrmVM9soj9qngRzYndob_8vePVQZSbyqcFdwF0M,3144
18
+ pypika/clickhouse/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
19
+ pypika/clickhouse/__pycache__/__init__.cpython-311.pyc,,
20
+ pypika/clickhouse/__pycache__/array.cpython-311.pyc,,
21
+ pypika/clickhouse/__pycache__/condition.cpython-311.pyc,,
22
+ pypika/clickhouse/__pycache__/dates_and_times.cpython-311.pyc,,
23
+ pypika/clickhouse/__pycache__/nullable_arg.cpython-311.pyc,,
24
+ pypika/clickhouse/__pycache__/search_string.cpython-311.pyc,,
25
+ pypika/clickhouse/__pycache__/type_conversion.cpython-311.pyc,,
26
+ pypika/clickhouse/array.py,sha256=rM4qxwF1aBSS6GdctQg5M9XuAJ89M1Q-kwWY7G29RJo,2893
27
+ pypika/clickhouse/condition.py,sha256=lCAA2jPuBrQd2_xj9ppFgEJOQXMIqpm0NDgKkPdfRfg,290
28
+ pypika/clickhouse/dates_and_times.py,sha256=X-ufzVUU6idvRKQdXHY8JLCxzqFAqnZyS5jwKBNaW5c,1225
29
+ pypika/clickhouse/nullable_arg.py,sha256=2fI_9HFDaUzcQLID11Kxb8sNnRGLHpqZLkwfaQGMvD0,161
30
+ pypika/clickhouse/search_string.py,sha256=DwHyNn3xMZaMh6Ezey_ZkXXQj897CSlL7Mz6eQKHgWA,2597
31
+ pypika/clickhouse/type_conversion.py,sha256=EZ0nKjrwMKlooP_hO9galdQTOJuorJMCOpTVfLNWXvk,2627
32
+ pypika/dialects.py,sha256=Cvwp6ECeBH_e5YCbZaUj6LEVesDZElvMXSla7p3PGmo,35977
33
+ pypika/enums.py,sha256=HI-Uzm-6sIZ14MiBl6OxilCMoW2mzO0_BS40XyJdqv8,3162
34
+ pypika/functions.py,sha256=XYkwktn44V4JLfH9tylTTk5MZ3qkMi9yd1Mu1oFylFY,9634
35
+ pypika/pseudocolumns.py,sha256=kbOVVf6nPV7wng_ymayQJxuNkHF8MbYDkDS2hRHSol0,252
36
+ pypika/py.typed,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1
37
+ pypika/queries.py,sha256=gDjKg__fNe1AOuJX-Cl_zfro6HiIKflvDk08O61oN54,76398
38
+ pypika/terms.py,sha256=bKXySs2ehkjUpGnLiCPCmqbGTmzq2VY0Ck5P6iruF_8,61281
39
+ pypika/utils.py,sha256=FzUZVcXLYRtGha2xtlDv9FWrER_doU6h8ikUmphRzsg,4487
micromamba_root/envs/pytorch_env/Lib/site-packages/pypika-0.51.1.dist-info/WHEEL ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (80.10.2)
3
+ Root-Is-Purelib: true
4
+ Tag: py2-none-any
5
+ Tag: py3-none-any
6
+
micromamba_root/envs/pytorch_env/Lib/site-packages/pypika-0.51.1.dist-info/licenses/LICENSE.txt ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "{}"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright {yyyy} {name of copyright owner}
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
micromamba_root/envs/pytorch_env/Lib/site-packages/pypika-0.51.1.dist-info/top_level.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ pypika