Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/pypdf/_utils.py: 51%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

330 statements  

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"""Utility functions for PDF library.""" 

29__author__ = "Mathieu Fenniak" 

30__author_email__ = "biziqe@mathieu.fenniak.net" 

31 

32import functools 

33import inspect 

34import logging 

35import os 

36import re 

37import sys 

38import warnings 

39from collections.abc import Callable 

40from dataclasses import dataclass 

41from datetime import datetime, timezone 

42from io import DEFAULT_BUFFER_SIZE 

43from os import SEEK_CUR 

44from re import Pattern 

45from typing import ( 

46 IO, 

47 Any, 

48 NoReturn, 

49 ParamSpec, 

50 TypeAlias, 

51 TypeVar, 

52 cast, 

53) 

54 

55if sys.version_info >= (3, 11): 

56 from typing import Self 

57else: 

58 from typing_extensions import Self 

59 

60from .errors import ( 

61 STREAM_TRUNCATED_PREMATURELY, 

62 DeprecationError, 

63 LimitReachedError, 

64 PdfStreamError, 

65) 

66 

67TransformationMatrixType: TypeAlias = tuple[ 

68 tuple[float, float, float], tuple[float, float, float], tuple[float, float, float] 

69] 

70CompressedTransformationMatrix: TypeAlias = tuple[ 

71 float, float, float, float, float, float 

72] 

73 

74StreamType = IO[Any] 

75BinaryStreamType = IO[bytes] 

76StrByteType = str | StreamType 

77 

78 

79def parse_iso8824_date(text: str | None) -> datetime | None: 

80 orgtext = text 

81 if not text: 

82 return None 

83 if text[0].isdigit(): 

84 text = "D:" + text 

85 if text.endswith(("Z", "z")): 

86 text += "0000" 

87 text = text.replace("z", "+").replace("Z", "+").replace("'", "") 

88 i = max(text.find("+"), text.find("-")) 

89 if i > 0 and i != len(text) - 5: 

90 text += "00" 

91 for f in ( 

92 "D:%Y", 

93 "D:%Y%m", 

94 "D:%Y%m%d", 

95 "D:%Y%m%d%H", 

96 "D:%Y%m%d%H%M", 

97 "D:%Y%m%d%H%M%S", 

98 "D:%Y%m%d%H%M%S%z", 

99 ): 

100 try: 

101 d = datetime.strptime(text, f) # noqa: DTZ007 

102 except ValueError: 

103 continue 

104 else: 

105 if text.endswith("+0000"): 

106 d = d.replace(tzinfo=timezone.utc) 

107 return d 

108 raise ValueError(f"Can not convert date: {orgtext}") 

109 

110 

111def format_iso8824_date(dt: datetime) -> str: 

112 """ 

113 Convert a datetime object to PDF date string format. 

114 

115 Converts datetime to the PDF date format D:YYYYMMDDHHmmSSOHH'mm 

116 as specified in the PDF Reference. 

117 

118 Args: 

119 dt: A datetime object to convert. 

120 

121 Returns: 

122 A date string in PDF format. 

123 """ 

124 date_str = dt.strftime("D:%Y%m%d%H%M%S") 

125 if dt.tzinfo is not None: 

126 offset = dt.utcoffset() 

127 assert offset is not None 

128 total_seconds = int(offset.total_seconds()) 

129 hours, remainder = divmod(abs(total_seconds), 3600) 

130 minutes = remainder // 60 

131 sign = "+" if total_seconds >= 0 else "-" 

132 date_str += f"{sign}{hours:02d}'{minutes:02d}'" 

133 return date_str 

134 

135 

136def _get_max_pdf_version_header(header1: str, header2: str) -> str: 

137 versions = ( 

138 "%PDF-1.3", 

139 "%PDF-1.4", 

140 "%PDF-1.5", 

141 "%PDF-1.6", 

142 "%PDF-1.7", 

143 "%PDF-2.0", 

144 ) 

145 pdf_header_indices = [] 

146 if header1 in versions: 

147 pdf_header_indices.append(versions.index(header1)) 

148 if header2 in versions: 

149 pdf_header_indices.append(versions.index(header2)) 

150 if len(pdf_header_indices) == 0: 

151 raise ValueError(f"Neither {header1!r} nor {header2!r} are proper headers") 

152 return versions[max(pdf_header_indices)] 

153 

154 

155WHITESPACES = (b"\x00", b"\t", b"\n", b"\f", b"\r", b" ") 

156WHITESPACES_AS_BYTES = b"".join(WHITESPACES) 

157WHITESPACES_AS_REGEXP = b"[" + WHITESPACES_AS_BYTES + b"]" 

158 

159 

160def read_until_whitespace(stream: StreamType, max_bytes: int | None = None, strict: bool = False) -> bytes: 

161 """ 

162 Read non-whitespace characters and return them. 

163 

164 Stops upon encountering whitespace or when max_bytes is reached. 

165 

166 Args: 

167 stream: The data stream from which was read. 

168 max_bytes: The maximum number of bytes which are considered valid. One more byte 

169 will always be read from the stream. 

170 strict: Whether to raise an exception if the token exceeds max_bytes. 

171 If False, a warning is logged and only the first max_bytes are returned. 

172 

173 Returns: 

174 The data which was read. 

175 

176 """ 

177 txt = bytearray() 

178 while True: 

179 tok = stream.read(1) 

180 if tok.isspace() or tok in WHITESPACES or not tok: 

181 break 

182 if max_bytes is not None and len(txt) >= max_bytes: 

183 if strict: 

184 raise LimitReachedError(f"Token exceeds maximum length of {max_bytes} bytes.") 

185 logger_warning( 

186 "Token exceeds maximum length of %(max_bytes)d bytes.", source=__name__, max_bytes=max_bytes 

187 ) 

188 break 

189 txt += tok 

190 return bytes(txt) 

191 

192 

193def read_non_whitespace(stream: BinaryStreamType) -> bytes: 

194 """ 

195 Find and read the next non-whitespace character (ignores whitespace). 

196 

197 Args: 

198 stream: The data stream from which was read. 

199 

200 Returns: 

201 The data which was read. 

202 

203 """ 

204 tok = stream.read(1) 

205 while tok in WHITESPACES: 

206 tok = stream.read(1) 

207 return tok 

208 

209 

210def skip_over_whitespace(stream: StreamType) -> bool: 

211 """ 

212 Similar to read_non_whitespace, but return a boolean if at least one 

213 whitespace character was read. 

214 

215 Args: 

216 stream: The data stream from which was read. 

217 

218 Returns: 

219 True if one or more whitespace was skipped, otherwise return False. 

220 

221 """ 

222 tok = stream.read(1) 

223 cnt = 0 

224 while tok in WHITESPACES: 

225 cnt += 1 

226 tok = stream.read(1) 

227 return cnt > 0 

228 

229 

230def check_if_whitespace_only(value: bytes) -> bool: 

231 """ 

232 Check if the given value consists of whitespace characters only. 

233 

234 Args: 

235 value: The bytes to check. 

236 

237 Returns: 

238 True if the value only has whitespace characters, otherwise return False. 

239 

240 """ 

241 return all(b in WHITESPACES_AS_BYTES for b in value) 

242 

243 

244NEUTRAL_CHARACTER_RANGES = ( 

245 ("\x00", "\x2F"), # ASCII control codes, space, and early punctuation (!"#$%) 

246 ("\x3A", "\x40"), # ASCII operators and punctuation between digits & A (:;<=>?@) 

247 ("\u0660", "\u066D"), # Arabic-Indic digits and Arabic numeric separators 

248 ("\u06F0", "\u06F9"), # Extended Arabic-Indic (Persian) digits 

249 ("\u2000", "\u206F"), # General punctuation 

250 ("\u20A0", "\u21FF"), # Currency symbols, diacritical marks, letter-like symbols, number forms, arrows 

251) 

252 

253 

254def is_char_neutral(char: str, custom_special_characters: str = "") -> bool: 

255 """Check if a character is part of neutral character ranges""" 

256 if any(start <= char <= end for start, end in NEUTRAL_CHARACTER_RANGES): 

257 return True 

258 

259 return bool(custom_special_characters and char in custom_special_characters) 

260 

261 

262RTL_CHARACTER_RANGES: tuple[tuple[str, str], ...] = ( 

263 ("\u0590", "\u08FF"), # Hebrew, Arabic, Syriac, Thaana, N'Ko, etc. 

264 ("\uFB1D", "\uFDFF"), # Hebrew & Arabic Presentation Forms-A 

265 ("\uFE70", "\uFEFF"), # Arabic Presentation Forms-B 

266) 

267 

268 

269def is_char_rtl(char: str, custom_rtl_min: str = "", custom_rtl_max: str = "") -> bool: 

270 """Check if a character is part of RTL character ranges""" 

271 if any(start <= char <= end for start, end in RTL_CHARACTER_RANGES): 

272 return True 

273 

274 return bool(custom_rtl_min and custom_rtl_max and (custom_rtl_min <= char <= custom_rtl_max)) 

275 

276 

277def skip_over_comment(stream: StreamType) -> None: 

278 tok = stream.read(1) 

279 stream.seek(-1, 1) 

280 if tok == b"%": 

281 while tok not in (b"\n", b"\r"): 

282 tok = stream.read(1) 

283 if tok == b"": 

284 raise PdfStreamError("File ended unexpectedly.") 

285 

286 

287def skip_over_comments(stream: StreamType, *, limit: int | None = None) -> None: 

288 """ 

289 Skip consecutive leading comments and the whitespace following each one. 

290 

291 The stream must be positioned at the first comment, if any. If the next 

292 character is not ``%``, the stream position is unchanged. If only whitespace 

293 follows the last comment before EOF, leave the stream at the last whitespace 

294 byte, preserving the existing read_object behaviour for a missing object. 

295 

296 Args: 

297 stream: The stream to read from. 

298 limit: The maximum number of comments to skip, or ``None`` for no limit. 

299 

300 Raises: 

301 LimitReachedError: If another comment follows after ``limit`` comments; 

302 the stream remains at its ``%`` without reading its body. 

303 PdfStreamError: If a comment ends before a line ending. 

304 

305 """ 

306 tok = stream.read(1) 

307 stream.seek(-len(tok), 1) 

308 comment_count = 0 

309 while tok == b"%": 

310 if limit is not None and comment_count >= limit: 

311 raise LimitReachedError(f"Maximum number of leading comments reached: {limit}.") 

312 skip_over_comment(stream) 

313 tok = read_non_whitespace(stream) 

314 stream.seek(-1, 1) 

315 comment_count += 1 

316 

317 

318# read_until_regex() reads chunks of 16, 32, 64, ... bytes, up to 8192 bytes 

319# each. The maximum token lengths of _CONTENT_STREAM_SIMPLE_TOKEN in 

320# generic/_data_structures.py are derived from these chunk sizes; update them 

321# when changing these values. 

322_READ_UNTIL_REGEX_FIRST_CHUNK_SIZE = 16 

323_READ_UNTIL_REGEX_MAXIMUM_CHUNK_SIZE = 8192 

324 

325 

326def read_until_regex(*, stream: StreamType, regex: Pattern[bytes], length: int = sys.maxsize) -> bytes: 

327 """ 

328 Read until the regular expression pattern matched (ignore the match). 

329 Treats EOF on the underlying stream as the end of the token to be matched. 

330 

331 Args: 

332 stream: The stream to read from. 

333 regex: The pattern to search for. 

334 length: The (approximated) maximum number of bytes to read before raising an exception. 

335 

336 Returns: 

337 The read bytes. 

338 

339 """ 

340 parts: list[bytes] = [] 

341 total_length = 0 

342 tail = b"" 

343 chunk_size = _READ_UNTIL_REGEX_FIRST_CHUNK_SIZE 

344 while True: 

345 token = stream.read(chunk_size) 

346 if not token: 

347 return b"".join(parts) 

348 token_length = len(token) 

349 if (current_length := total_length + token_length) >= length: 

350 raise LimitReachedError( 

351 f"Read stream length of {current_length} exceeds maximum allowed length of {length}." 

352 ) 

353 

354 # Search overlap of previous tail + new chunk to catch 

355 # multi-byte regex matches spanning chunk boundaries. 

356 current_buffer = tail + token 

357 search_match = regex.search(current_buffer) 

358 parts.append(token) 

359 if search_match is not None: 

360 overlap = len(tail) 

361 actual_start = total_length - overlap + search_match.start() 

362 stream.seek(actual_start - total_length - token_length, 1) 

363 return b"".join(parts)[:actual_start] 

364 total_length += token_length 

365 

366 # Fixed overlap: 16 bytes is sufficient for the short 

367 # delimiter patterns used in PDF parsing. 

368 tail = token[-16:] 

369 if chunk_size < _READ_UNTIL_REGEX_MAXIMUM_CHUNK_SIZE: 

370 chunk_size <<= 1 

371 

372 

373def read_block_backwards(stream: BinaryStreamType, to_read: int) -> bytes: 

374 """ 

375 Given a stream at position X, read a block of size to_read ending at position X. 

376 

377 This changes the stream's position to the beginning of where the block was 

378 read. 

379 

380 Args: 

381 stream: 

382 to_read: 

383 

384 Returns: 

385 The data which was read. 

386 

387 """ 

388 if stream.tell() < to_read: 

389 raise PdfStreamError("Could not read malformed PDF file") 

390 # Seek to the start of the block we want to read. 

391 stream.seek(-to_read, SEEK_CUR) 

392 read = stream.read(to_read) 

393 # Seek to the start of the block we read after reading it. 

394 stream.seek(-to_read, SEEK_CUR) 

395 return read 

396 

397 

398def read_previous_line(stream: StreamType) -> bytes: 

399 """ 

400 Given a byte stream with current position X, return the previous line. 

401 

402 All characters between the first CR/LF byte found before X 

403 (or, the start of the file, if no such byte is found) and position X 

404 After this call, the stream will be positioned one byte after the 

405 first non-CRLF character found beyond the first CR/LF byte before X, 

406 or, if no such byte is found, at the beginning of the stream. 

407 

408 Args: 

409 stream: StreamType: 

410 

411 Returns: 

412 The data which was read. 

413 

414 """ 

415 line_content = [] 

416 found_crlf = False 

417 if stream.tell() == 0: 

418 raise PdfStreamError(STREAM_TRUNCATED_PREMATURELY) 

419 while True: 

420 to_read = min(DEFAULT_BUFFER_SIZE, stream.tell()) 

421 if to_read == 0: 

422 break 

423 # Read the block. After this, our stream will be one 

424 # beyond the initial position. 

425 block = read_block_backwards(stream, to_read) 

426 idx = len(block) - 1 

427 if not found_crlf: 

428 # We haven't found our first CR/LF yet. 

429 # Read off characters until we hit one. 

430 while idx >= 0 and block[idx] not in b"\r\n": 

431 idx -= 1 

432 if idx >= 0: 

433 found_crlf = True 

434 if found_crlf: 

435 # We found our first CR/LF already (on this block or 

436 # a previous one). 

437 # Our combined line is the remainder of the block 

438 # plus any previously read blocks. 

439 line_content.append(block[idx + 1 :]) 

440 # Continue to read off any more CRLF characters. 

441 while idx >= 0 and block[idx] in b"\r\n": 

442 idx -= 1 

443 else: 

444 # Didn't find CR/LF yet - add this block to our 

445 # previously read blocks and continue. 

446 line_content.append(block) 

447 if idx >= 0: 

448 # We found the next non-CRLF character. 

449 # Set the stream position correctly, then break 

450 stream.seek(idx + 1, SEEK_CUR) 

451 break 

452 # Join all the blocks in the line (which are in reverse order) 

453 return b"".join(line_content[::-1]) 

454 

455 

456def matrix_multiply( 

457 a: TransformationMatrixType, b: TransformationMatrixType 

458) -> TransformationMatrixType: 

459 return tuple( # type: ignore[return-value] 

460 tuple(sum(float(i) * float(j) for i, j in zip(row, col)) for col in zip(*b)) 

461 for row in a 

462 ) 

463 

464 

465def mark_location(stream: StreamType) -> None: 

466 """Create text file showing current location in context.""" 

467 # Mainly for debugging 

468 radius = 5000 

469 stream.seek(-radius, 1) 

470 with open("pypdf_pdfLocation.txt", "wb") as output_fh: 

471 output_fh.write(stream.read(radius)) 

472 output_fh.write(b"HERE") 

473 output_fh.write(stream.read(radius)) 

474 stream.seek(-radius, 1) 

475 

476 

477def deprecate(msg: str, stacklevel: int = 3) -> None: 

478 warnings.warn(msg, DeprecationWarning, stacklevel=stacklevel) 

479 

480 

481def deprecation(msg: str) -> NoReturn: 

482 raise DeprecationError(msg) 

483 

484 

485def deprecate_with_replacement(old_name: str, new_name: str, removed_in: str) -> None: 

486 """Issue a warning that a feature will be removed, but has a replacement.""" 

487 deprecate( 

488 f"{old_name} is deprecated and will be removed in pypdf {removed_in}. Use {new_name} instead.", 

489 4, 

490 ) 

491 

492 

493def deprecation_with_replacement(old_name: str, new_name: str, removed_in: str) -> NoReturn: 

494 """Raise an exception that a feature was already removed, but has a replacement.""" 

495 deprecation( 

496 f"{old_name} is deprecated and was removed in pypdf {removed_in}. Use {new_name} instead." 

497 ) 

498 

499 

500_P = ParamSpec("_P") 

501_R = TypeVar("_R") 

502 

503 

504def deprecate_positional_arguments(removed_in: str) -> Callable[[Callable[_P, _R]], Callable[_P, _R]]: 

505 """ 

506 Accept positional arguments for keyword-only parameters, but issue a warning. 

507 

508 Use it for a function whose parameters became keyword-only. The positional 

509 arguments that exceed the positional parameters are passed to the 

510 keyword-only parameters in the order of the signature. 

511 

512 Args: 

513 removed_in: The version in which positional arguments will raise an error. 

514 

515 Returns: 

516 The decorator. 

517 

518 """ 

519 def decorator(func: Callable[_P, _R]) -> Callable[_P, _R]: 

520 parameters = inspect.signature(func).parameters.values() 

521 positional_count = sum( 

522 parameter.kind in (parameter.POSITIONAL_ONLY, parameter.POSITIONAL_OR_KEYWORD) 

523 for parameter in parameters 

524 ) 

525 keyword_only_names = [parameter.name for parameter in parameters if parameter.kind == parameter.KEYWORD_ONLY] 

526 

527 @functools.wraps(func) 

528 def wrapper(*args: Any, **kwargs: Any) -> Any: 

529 extra_args = args[positional_count:] 

530 if extra_args: 

531 if len(extra_args) > len(keyword_only_names): 

532 raise TypeError( 

533 f"{func.__qualname__}() takes {positional_count + len(keyword_only_names)} " 

534 f"positional arguments but {len(args)} were given" 

535 ) 

536 for name, value in zip(keyword_only_names, extra_args): 

537 if name in kwargs: 

538 raise TypeError(f"{func.__qualname__}() got multiple values for argument '{name}'") 

539 kwargs[name] = value 

540 deprecate_with_replacement( 

541 f"Passing positional arguments to {func.__qualname__}()", "keyword arguments", removed_in 

542 ) 

543 return func(*args[:positional_count], **kwargs) 

544 

545 return cast(Callable[_P, _R], wrapper) 

546 

547 return decorator 

548 

549 

550def deprecate_no_replacement(name: str, removed_in: str) -> None: 

551 """Issue a warning that a feature will be removed without replacement.""" 

552 deprecate(f"{name} is deprecated and will be removed in pypdf {removed_in}.", 4) 

553 

554 

555def deprecation_no_replacement(name: str, removed_in: str) -> NoReturn: 

556 """Raise an exception that a feature was already removed without replacement.""" 

557 deprecation(f"{name} is deprecated and was removed in pypdf {removed_in}.") 

558 

559 

560def logger_error(message: str, *, source: str, **values: Any) -> None: 

561 """ 

562 Use this instead of logger.error directly. 

563 

564 That allows people to overwrite it more easily. 

565 

566 See the docs on when to use which: 

567 https://pypdf.readthedocs.io/en/latest/user/suppress-warnings.html 

568 """ 

569 if values: 

570 logging.getLogger(source).error(message, values) 

571 else: 

572 logging.getLogger(source).error(message) 

573 

574 

575def logger_warning(message: str, *, source: str, **values: Any) -> None: 

576 """ 

577 Use this instead of logger.warning directly. 

578 

579 That allows people to overwrite it more easily. 

580 

581 ## Exception, warnings.warn, logger_warning 

582 - Exceptions should be used if the user should write code that deals with 

583 an error case, e.g. the PDF being completely broken. 

584 - warnings.warn should be used if the user needs to fix their code, e.g. 

585 DeprecationWarnings 

586 - logger_warning should be used if the user needs to know that an issue was 

587 handled by pypdf, e.g. a non-compliant PDF being read in a way that 

588 pypdf could apply a robustness fix to still read it. This applies mainly 

589 to strict=False mode. 

590 """ 

591 if values: 

592 logging.getLogger(source).warning(message, values) 

593 else: 

594 # Keep parity with logger_error and support plain warning messages. 

595 # Passing an empty dict to logging is not equivalent to passing no args: 

596 # plain messages would fail while being formatted. 

597 logging.getLogger(source).warning(message) 

598 

599 

600def rename_kwargs( 

601 func_name: str, kwargs: dict[str, Any], aliases: dict[str, str], fail: bool = False 

602) -> None: 

603 """ 

604 Helper function to deprecate arguments. 

605 

606 Args: 

607 func_name: Name of the function to be deprecated 

608 kwargs: 

609 aliases: 

610 fail: 

611 

612 """ 

613 for old_term, new_term in aliases.items(): 

614 if old_term in kwargs: 

615 if fail: 

616 raise DeprecationError( 

617 f"{old_term} is deprecated as an argument. Use {new_term} instead" 

618 ) 

619 if new_term in kwargs: 

620 raise TypeError( 

621 f"{func_name} received both {old_term} and {new_term} as " 

622 f"an argument. {old_term} is deprecated. " 

623 f"Use {new_term} instead." 

624 ) 

625 kwargs[new_term] = kwargs.pop(old_term) 

626 warnings.warn( 

627 message=( 

628 f"{old_term} is deprecated as an argument. Use {new_term} instead" 

629 ), 

630 category=DeprecationWarning, 

631 stacklevel=3, 

632 ) 

633 

634 

635def _human_readable_bytes(bytes: int) -> str: 

636 if bytes < 10**3: 

637 return f"{bytes} Byte" 

638 if bytes < 10**6: 

639 return f"{bytes / 10**3:.1f} kB" 

640 if bytes < 10**9: 

641 return f"{bytes / 10**6:.1f} MB" 

642 return f"{bytes / 10**9:.1f} GB" 

643 

644 

645def get_stream_size(stream: StreamType) -> int: 

646 position = stream.tell() 

647 stream.seek(0, os.SEEK_END) 

648 size = stream.tell() 

649 stream.seek(position) 

650 return size 

651 

652 

653def get_stream_data(stream: StreamType) -> bytes: 

654 position = stream.tell() 

655 stream.seek(0, os.SEEK_SET) 

656 data = stream.read(-1) 

657 stream.seek(position) 

658 return cast(bytes, data) 

659 

660 

661# The following class has been copied from Django: 

662# https://github.com/django/django/blob/adae619426b6f50046b3daaa744db52989c9d6db/django/utils/functional.py#L51-L65 

663# It received some modifications to comply with our own coding standards. 

664# 

665# Original license: 

666# 

667# --------------------------------------------------------------------------------- 

668# Copyright (c) Django Software Foundation and individual contributors. 

669# All rights reserved. 

670# 

671# Redistribution and use in source and binary forms, with or without modification, 

672# are permitted provided that the following conditions are met: 

673# 

674# 1. Redistributions of source code must retain the above copyright notice, 

675# this list of conditions and the following disclaimer. 

676# 

677# 2. Redistributions in binary form must reproduce the above copyright 

678# notice, this list of conditions and the following disclaimer in the 

679# documentation and/or other materials provided with the distribution. 

680# 

681# 3. Neither the name of Django nor the names of its contributors may be used 

682# to endorse or promote products derived from this software without 

683# specific prior written permission. 

684# 

685# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 

686# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 

687# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 

688# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 

689# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 

690# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 

691# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 

692# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 

693# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 

694# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 

695# --------------------------------------------------------------------------------- 

696class classproperty: # noqa: N801 

697 """ 

698 Decorator that converts a method with a single cls argument into a property 

699 that can be accessed directly from the class. 

700 """ 

701 

702 def __init__(self, method=None) -> None: # type: ignore[no-untyped-def] # noqa: ANN001 

703 self.fget = method 

704 

705 def __get__(self, instance, cls=None) -> Any: # type: ignore[no-untyped-def] # noqa: ANN001 

706 return self.fget(cls) 

707 

708 def getter(self, method) -> Self: # type: ignore[no-untyped-def] # noqa: ANN001 

709 self.fget = method 

710 return self 

711 

712 

713@dataclass 

714class File: 

715 from .generic import IndirectObject # noqa: PLC0415 

716 

717 name: str = "" 

718 """ 

719 Filename as identified within the PDF file. 

720 """ 

721 data: bytes = b"" 

722 """ 

723 Data as bytes. 

724 """ 

725 indirect_reference: IndirectObject | None = None 

726 """ 

727 Reference to the object storing the stream. 

728 """ 

729 

730 def __str__(self) -> str: 

731 return f"{self.__class__.__name__}(name={self.name}, data: {_human_readable_bytes(len(self.data))})" 

732 

733 def __repr__(self) -> str: 

734 return self.__str__()[:-1] + f", hash: {hash(self.data)})" 

735 

736 

737@functools.total_ordering 

738class Version: 

739 COMPONENT_PATTERN = re.compile(r"^(\d+)(.*)$") 

740 

741 def __init__(self, version_str: str) -> None: 

742 self.version_str = version_str 

743 self.components = self._parse_version(version_str) 

744 

745 def _parse_version(self, version_str: str) -> list[tuple[int, str]]: 

746 components = version_str.split(".") 

747 parsed_components = [] 

748 for component in components: 

749 match = Version.COMPONENT_PATTERN.match(component) 

750 if not match: 

751 parsed_components.append((0, component)) 

752 continue 

753 integer_prefix = match.group(1) 

754 suffix = match.group(2) 

755 parsed_components.append((int(integer_prefix), suffix)) 

756 return parsed_components 

757 

758 def __eq__(self, other: object) -> bool: 

759 if not isinstance(other, Version): 

760 return False 

761 return self.components == other.components 

762 

763 def __hash__(self) -> int: 

764 # Convert to tuple as lists cannot be hashed. 

765 return hash((self.__class__, tuple(self.components))) 

766 

767 def __lt__(self, other: Any) -> bool: 

768 if not isinstance(other, Version): 

769 raise TypeError(f"Version cannot be compared against {type(other)}") 

770 

771 for self_component, other_component in zip(self.components, other.components): 

772 self_value, self_suffix = self_component 

773 other_value, other_suffix = other_component 

774 

775 if self_value < other_value: 

776 return True 

777 if self_value > other_value: 

778 return False 

779 

780 if self_suffix < other_suffix: 

781 return True 

782 if self_suffix > other_suffix: 

783 return False 

784 

785 return len(self.components) < len(other.components) 

786 

787 

788@dataclass 

789class _TraversalState: 

790 """Sometimes we need mutable objects which just count something.""" 

791 entry_count: int = 0 

792 has_logged: bool = False