Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/pypdf/pagerange.py: 31%
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
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
1"""
2Representation and utils for ranges of PDF file pages.
4Copyright (c) 2014, Steve Witham <switham_github@mac-guyver.com>.
5All rights reserved. This software is available under a BSD license;
6see https://github.com/py-pdf/pypdf/blob/main/LICENSE
7"""
9import re
10from typing import Any, Union
12from ._utils import deprecate_no_replacement
13from .errors import ParseError
15_INT_RE = r"(0|-?[1-9]\d*)" # A decimal int, don't allow "-0".
16PAGE_RANGE_RE = f"^({_INT_RE}|({_INT_RE}?(:{_INT_RE}?(:{_INT_RE}?)?)))$"
17# groups: 12 34 5 6 7 8
20class PageRange:
21 """
22 A slice-like representation of a range of page indices.
24 For example, page numbers, only starting at zero.
26 The syntax is like what you would put between brackets [ ].
27 The slice is one of the few Python types that can't be subclassed,
28 but this class converts to and from slices, and allows similar use.
30 - PageRange(str) parses a string representing a page range.
31 - PageRange(slice) directly "imports" a slice.
32 - to_slice() gives the equivalent slice.
33 - str() and repr() allow printing.
34 - indices(n) is like slice.indices(n).
35 """
37 def __init__(self, arg: Union[slice, "PageRange", str]) -> None:
38 """
39 Initialize with either a slice -- giving the equivalent page range,
40 or a PageRange object -- making a copy,
41 or a string like
42 "int", "[int]:[int]" or "[int]:[int]:[int]",
43 where the brackets indicate optional ints.
44 Remember, page indices start with zero.
45 Page range expression examples:
47 : all pages. -1 last page.
48 22 just the 23rd page. :-1 all but the last page.
49 0:3 the first three pages. -2 second-to-last page.
50 :3 the first three pages. -2: last two pages.
51 5: from the sixth page onward. -3:-1 third & second to last.
52 The third, "stride" or "step" number is also recognized.
53 ::2 0 2 4 ... to the end. 3:0:-1 3 2 1 but not 0.
54 1:10:2 1 3 5 7 9 2::-1 2 1 0.
55 ::-1 all pages in reverse order.
56 Note the difference between this notation and arguments to slice():
57 slice(3) means the first three pages;
58 PageRange("3") means the range of only the fourth page.
59 However PageRange(slice(3)) means the first three pages.
60 """
61 if isinstance(arg, slice):
62 if arg.step == 0:
63 raise ParseError(arg)
64 self._slice = arg
65 return
67 if isinstance(arg, PageRange):
68 self._slice = arg.to_slice()
69 return
71 m = isinstance(arg, str) and re.match(PAGE_RANGE_RE, arg)
72 if not m:
73 raise ParseError(arg)
74 if m.group(2):
75 # Special case: just an int means a range of one page.
76 start = int(m.group(2))
77 stop = start + 1 if start != -1 else None
78 self._slice = slice(start, stop)
79 else:
80 bounds = [int(g) if g else None for g in m.group(4, 6, 8)]
81 step = bounds[2]
82 if step == 0:
83 # A zero stride cannot select anything; slice() accepts it here
84 # but raises as soon as the range is applied.
85 raise ParseError(arg)
86 self._slice = slice(*bounds)
88 @staticmethod
89 def valid(input: Any) -> bool:
90 """
91 True if input is a valid initializer for a PageRange.
93 Args:
94 input: A possible PageRange string, slice, or PageRange object.
96 Returns:
97 True, if the ``input`` is a valid PageRange.
99 """
100 if isinstance(input, PageRange):
101 return True
102 if not isinstance(input, (str, slice)):
103 return False
104 try:
105 PageRange(input)
106 except ParseError:
107 return False
108 return True
110 def to_slice(self) -> slice:
111 """Return the slice equivalent of this page range."""
112 return self._slice
114 def __str__(self) -> str:
115 """A string like "1:2:3"."""
116 s = self._slice
117 indices: tuple[int, int] | tuple[int, int, int]
118 if s.step is None:
119 # A lone "-1" parses as the last page, which is slice(-1, None),
120 # so slice(-1, 0) cannot be written that way.
121 if s.start is not None and s.stop == s.start + 1 and s.start != -1:
122 return str(s.start)
124 indices = s.start, s.stop
125 else:
126 indices = s.start, s.stop, s.step
127 return ":".join("" if i is None else str(i) for i in indices)
129 def __repr__(self) -> str:
130 """A string like "PageRange('1:2:3')"."""
131 return "PageRange(" + repr(str(self)) + ")"
133 def indices(self, n: int) -> tuple[int, int, int]:
134 """
135 Assuming a sequence of length n, calculate the start and stop indices,
136 and the stride length of the PageRange.
138 See help(slice.indices).
140 Args:
141 n: the length of the list of pages to choose from.
143 Returns:
144 Arguments for range().
146 """
147 return self._slice.indices(n)
149 def __eq__(self, other: object) -> bool:
150 if not isinstance(other, PageRange):
151 return False
152 return self._slice == other._slice
154 def __hash__(self) -> int:
155 return hash((self.__class__, (self._slice.start, self._slice.stop, self._slice.step)))
157 def __add__(self, other: "PageRange") -> "PageRange":
158 if not isinstance(other, PageRange):
159 raise TypeError(f"Can't add PageRange and {type(other)}")
160 if self._slice.step is not None or other._slice.step is not None:
161 raise ValueError("Can't add PageRange with stride")
162 a = self._slice.start, self._slice.stop
163 b = other._slice.start, other._slice.stop
165 # None start means "beginning" (-inf for ordering); None stop means "end" (+inf).
166 def _start_key(v: int | None) -> float:
167 return float("-inf") if v is None else v
169 def _stop_key(v: int | None) -> float:
170 return float("inf") if v is None else v
172 # Order by start, and on equal starts put the larger stop first, so that
173 # an empty range such as 2:0 does not decide whether there is a gap.
174 if (_start_key(a[0]), -_stop_key(a[1])) > (_start_key(b[0]), -_stop_key(b[1])):
175 a, b = b, a
177 # Now `a` has the smaller start (and the larger stop on equal starts).
178 if _start_key(b[0]) > _stop_key(a[1]):
179 # There is a gap between a and b.
180 raise ValueError("Can't add PageRanges with gap")
181 stop = b[1] if _stop_key(b[1]) > _stop_key(a[1]) else a[1]
182 return PageRange(slice(a[0], stop))
185PAGE_RANGE_ALL = PageRange(":") # The range of all pages.
188def parse_filename_page_ranges(
189 args: list[str | PageRange | None]
190) -> list[tuple[str, PageRange]]:
191 """
192 Given a list of filenames and page ranges, return a list of (filename, page_range) pairs.
194 Args:
195 args: A list where the first element is a filename. The other elements are
196 filenames, page-range expressions, slice objects, or PageRange objects.
197 A filename not followed by a page range indicates all pages of the file.
199 Returns:
200 A list of (filename, page_range) pairs.
202 .. deprecated:: 7.2.0
203 ``parse_filename_page_ranges`` is deprecated and will be removed in
204 pypdf 8.0.0. pypdf does not use it since the ``pdfcat`` script was removed.
206 """
207 deprecate_no_replacement("parse_filename_page_ranges", "8.0.0")
208 pairs: list[tuple[str, PageRange]] = []
209 pdf_filename: str | None = None
210 did_page_range = False
211 for arg in [*args, None]:
212 if PageRange.valid(arg):
213 if not pdf_filename:
214 raise ValueError(
215 "The first argument must be a filename, not a page range."
216 )
218 assert arg is not None
219 pairs.append((pdf_filename, PageRange(arg)))
220 did_page_range = True
221 else:
222 # New filename or end of list - use the complete previous file?
223 if pdf_filename and not did_page_range:
224 pairs.append((pdf_filename, PAGE_RANGE_ALL))
226 assert not isinstance(arg, PageRange), arg
227 pdf_filename = arg
228 did_page_range = False
229 return pairs
232PageRangeSpec = str | PageRange | tuple[int, int] | tuple[int, int, int] | list[int]